1 /*******************************************************************************
2 * Copyright (c) 2007, 2018 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics;
14 import static org.simantics.db.common.utils.Transaction.commit;
15 import static org.simantics.db.common.utils.Transaction.endTransaction;
16 import static org.simantics.db.common.utils.Transaction.readGraph;
17 import static org.simantics.db.common.utils.Transaction.startTransaction;
18 import static org.simantics.db.common.utils.Transaction.writeGraph;
21 import java.io.IOException;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.nio.file.Paths;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Properties;
33 import java.util.TreeMap;
34 import java.util.UUID;
36 import org.eclipse.core.runtime.ILog;
37 import org.eclipse.core.runtime.IProduct;
38 import org.eclipse.core.runtime.IProgressMonitor;
39 import org.eclipse.core.runtime.IStatus;
40 import org.eclipse.core.runtime.NullProgressMonitor;
41 import org.eclipse.core.runtime.Platform;
42 import org.eclipse.core.runtime.Status;
43 import org.eclipse.core.runtime.SubMonitor;
44 import org.eclipse.osgi.service.datalocation.Location;
45 import org.eclipse.osgi.service.resolver.BundleDescription;
47 import org.ini4j.InvalidFileFormatException;
48 import org.simantics.databoard.Bindings;
49 import org.simantics.databoard.Databoard;
50 import org.simantics.datatypes.literal.Font;
51 import org.simantics.datatypes.literal.RGB;
52 import org.simantics.db.Driver;
53 import org.simantics.db.Driver.Management;
54 import org.simantics.db.Manager;
55 import org.simantics.db.ReadGraph;
56 import org.simantics.db.Resource;
57 import org.simantics.db.Session;
58 import org.simantics.db.SessionModel;
59 import org.simantics.db.UndoContext;
60 import org.simantics.db.VirtualGraph;
61 import org.simantics.db.WriteGraph;
62 import org.simantics.db.common.request.ObjectsWithType;
63 import org.simantics.db.common.request.WriteResultRequest;
64 import org.simantics.db.common.utils.Transaction;
65 import org.simantics.db.exception.ClusterSetExistException;
66 import org.simantics.db.exception.DatabaseException;
67 import org.simantics.db.indexing.DatabaseIndexing;
68 import org.simantics.db.layer0.genericrelation.DependenciesRelation;
69 import org.simantics.db.layer0.genericrelation.IndexException;
70 import org.simantics.db.layer0.genericrelation.IndexedRelations;
71 import org.simantics.db.layer0.request.PossibleResource;
72 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
73 import org.simantics.db.layer0.util.SimanticsKeys;
74 import org.simantics.db.layer0.util.TGTransferableGraphSource;
75 import org.simantics.db.layer0.variable.VariableRepository;
76 import org.simantics.db.management.SessionContext;
77 import org.simantics.db.request.Read;
78 import org.simantics.db.request.Write;
79 import org.simantics.db.service.LifecycleSupport.LifecycleListener;
80 import org.simantics.db.service.LifecycleSupport.LifecycleState;
81 import org.simantics.db.service.QueryControl;
82 import org.simantics.db.service.UndoRedoSupport;
83 import org.simantics.db.service.VirtualGraphSupport;
84 import org.simantics.db.service.XSupport;
85 import org.simantics.graph.db.GraphDependencyAnalyzer;
86 import org.simantics.graph.db.GraphDependencyAnalyzer.IU;
87 import org.simantics.graph.db.GraphDependencyAnalyzer.IdentityNode;
88 import org.simantics.graph.db.IImportAdvisor;
89 import org.simantics.graph.db.ImportResult;
90 import org.simantics.graph.db.TransferableGraphs;
91 import org.simantics.graph.diff.Diff;
92 import org.simantics.graph.diff.TransferableGraphDelta1;
93 import org.simantics.internal.Activator;
94 import org.simantics.internal.TimedSessionCache;
95 import org.simantics.internal.startup.StartupExtensions;
96 import org.simantics.layer0.Layer0;
97 import org.simantics.operation.Layer0X;
98 import org.simantics.project.IProject;
99 import org.simantics.project.ProjectFeatures;
100 import org.simantics.project.ProjectKeys;
101 import org.simantics.project.Projects;
102 import org.simantics.project.SessionDescriptor;
103 import org.simantics.project.exception.ProjectException;
104 import org.simantics.project.features.registry.GroupReference;
105 import org.simantics.project.management.DatabaseManagement;
106 import org.simantics.project.management.GraphBundle;
107 import org.simantics.project.management.GraphBundleEx;
108 import org.simantics.project.management.GraphBundleRef;
109 import org.simantics.project.management.PlatformUtil;
110 import org.simantics.project.management.ServerManager;
111 import org.simantics.project.management.ServerManagerFactory;
112 import org.simantics.project.management.WorkspaceUtil;
113 import org.simantics.scl.compiler.module.repository.ModuleRepository;
114 import org.simantics.scl.osgi.SCLOsgi;
115 import org.simantics.utils.FileUtils;
116 import org.simantics.utils.datastructures.Pair;
117 import org.simantics.utils.strings.EString;
118 import org.simantics.utils.threads.ExecutorWorker;
119 import org.simantics.utils.threads.ThreadUtils;
120 import org.slf4j.Logger;
121 import org.slf4j.LoggerFactory;
124 * SimanticsPlatform performs procedures required in order to get simantics
125 * workbench into operational state. This consists of the following steps:
127 * <li> Asserting there is Database
129 * <li> Starting Database process
131 * <li> Opening a session to Database process
133 * <li> Asserting required ontologies or other transferable graphs are installed in the database
135 * <li> Asserting required project is installed in the database
137 * <li> Asserting Simantics Features are installed in the database
139 * <li> Asserting Simantics Features are installed to the project
141 * <li> Shutdown: Save Session, Close session, Kill Database process
145 * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
147 public class SimanticsPlatform implements LifecycleListener {
149 private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsPlatform.class);
152 * The policy is relevant when developing Simantics from Eclipse IDE.
153 * It is applied when the ontology in the database of a workspace doesn't match
154 * a newer ontology in the Eclipse workspace.
156 public static enum OntologyRecoveryPolicy { ThrowError, Merge, ReinstallDatabase }
159 * This policy dictates how the Simantics platform startup should react if
160 * the started workspace is not set up properly. The alternatives are to
161 * just throw an error and fail or to attempt all possible measures to fix
162 * the encountered problems.
164 public static enum RecoveryPolicy { ThrowError, FixError }
166 /** Singleton instance, started in SimanticsWorkbenchAdvisor */
167 public static final SimanticsPlatform INSTANCE = new SimanticsPlatform();
169 /** Set to true when the Simantics Platform is in good-and-go condition */
170 public boolean running;
172 /** ID of the database driver that the platform is currently using */
173 private String currentDatabaseDriver;
175 /** Database Session */
176 public Session session;
177 private Management databasebManagement;
179 /** Database session context */
180 public SessionContext sessionContext;
182 /** Project identifier in Database */
183 public String projectURI;
186 public String projectName;
188 /** Project resource */
189 public Resource projectResource;
191 /** Session specific bindings */
192 public SimanticsBindings simanticsBindings;
194 public Thread mainThread;
196 private Thread shutdownHook = new Thread() {
200 LOGGER.warn("Simantics platform was not properly shut down. Executing safety shutdown hook.");
201 shutdown(null, false);
202 } catch (PlatformException e) {
203 LOGGER.error("Simantics Platform shutdown hook execution failed.", e);
204 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Simantics Platform shutdown hook execution failed.", e));
210 * The {@link IProject} activated by
211 * {@link #startUp(IProgressMonitor, RecoveryPolicy, OntologyRecoveryPolicy, ServerAddress, PlatformUserAgent)}
213 private IProject project;
218 * Create a new simantics plaform manager in uninitialized state and
219 * with default policies. <p>
221 public SimanticsPlatform() {
222 log = Platform.getLog(Activator.getBundleContext().getBundle());
223 mainThread = Thread.currentThread();
226 public String getApplicationClientId() {
227 IProduct product = Platform.getProduct();
228 if(product == null) return "noProduct";//UUID.randomUUID().toString();
229 String application = product.getApplication();
230 return application != null ? application : UUID.randomUUID().toString();
233 private SessionDescriptor setupDatabase(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, PlatformUserAgent userAgent) throws PlatformException {
234 if (progressMonitor == null)
235 progressMonitor = new NullProgressMonitor();
236 Path workspaceLocation = Platform.getLocation().toFile().toPath();
237 Path dbLocation = workspaceLocation.resolve("db");
238 Path dbIniPath = workspaceLocation.resolve("db.ini");
239 // The driver file overrides any command line arguments to prevent
240 // using the wrong driver for an existing database directory.
241 ServerManager serverManager;
243 Ini dbIni = loadOrCreateDatabaseIni(dbIniPath, databaseDriverId);
244 databaseDriverId = dbIni.get("driver", "id");
245 serverManager = ServerManagerFactory.create(databaseDriverId, dbLocation.toAbsolutePath().toString());
246 } catch (DatabaseException | IOException e) {
247 throw new PlatformException("Failed to initialize database ServerManager with driver " + databaseDriverId, e);
249 progressMonitor.beginTask("Setting up Simantics Database", 100);
250 progressMonitor.setTaskName("Asserting Database is installed.");
251 String msg = "Failed to initialize Simantics database.";
254 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Initializing database at " + dbLocation + " with driver " + databaseDriverId));
255 progressMonitor.setTaskName("Creating database at " + dbLocation);
256 databasebManagement = serverManager.getManagement(dbLocation.toFile());
257 databasebManagement.create();
258 currentDatabaseDriver = databaseDriverId;
260 return serverManager.createDatabase(dbLocation.toFile());
261 } catch (DatabaseException e) {
262 throw new PlatformException(msg, e);
263 } catch (Throwable e) {
264 throw new PlatformException(msg, e);
266 progressMonitor.worked(20);
270 public void synchronizeOntologies(IProgressMonitor progressMonitor, OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize) throws PlatformException {
272 SubMonitor monitor = SubMonitor.convert(progressMonitor, 100);
274 monitor.setTaskName("Compile dynamic ontologies");
275 PlatformUtil.compileAllDynamicOntologies();
277 String message = "Asserting all ontologies are installed";
278 LOGGER.info(message);
279 monitor.setTaskName(message);
281 DatabaseManagement mgmt = new DatabaseManagement();
282 Map<GraphBundleRef, GraphBundleEx> platformTGs = new HashMap<>();
285 // Get a list of bundles installed into the database
286 message = "find installed bundles from database";
287 monitor.subTask(message);
288 LOGGER.info(message);
289 Map<GraphBundleRef, GraphBundleEx> installedTGs = new HashMap<>();
290 for (GraphBundle b : session.syncRequest( mgmt.GraphBundleQuery )) {
291 installedTGs.put(GraphBundleRef.of(b), GraphBundleEx.extend(b));
294 if(!requireSynchronize && installedTGs.size() > 1 && !Platform.inDevelopmentMode()) return;
295 // if(installedTGs.size() > 1) return;
297 // Get a list of all bundles in the platform (Bundle Context)
298 message = "load all transferable graphs from platform";
299 monitor.subTask(message);
300 LOGGER.info(message);
301 Collection<GraphBundle> tgs = PlatformUtil.getAllGraphs();
302 message = "extend bundles to compile versions";
303 monitor.subTask(message);
304 LOGGER.info(message);
305 for (GraphBundle b : tgs) {
306 GraphBundleEx gbe = GraphBundleEx.extend(b);
308 platformTGs.put(GraphBundleRef.of(b), gbe);
311 // Compile a list of TGs that need to be installed or reinstalled in the database
312 message = "check bundle reinstallation demand";
313 monitor.subTask(message);
314 LOGGER.info(message);
315 List<GraphBundleEx> installTGs = new ArrayList<>();
316 // Create list of TGs to update, <newTg, oldTg>
317 Map<GraphBundleEx,GraphBundleEx> reinstallTGs = new TreeMap<>();
318 for (Entry<GraphBundleRef, GraphBundleEx> e : platformTGs.entrySet()) {
319 GraphBundleRef key = e.getKey();
320 GraphBundleEx platformBundle = e.getValue();
321 GraphBundleEx existingBundle = installedTGs.get(key);
323 // System.out.println("GraphBundleRef key=" + key.toString());
325 if (existingBundle == null) {
326 // Bundle did not exist in the database, put it into list of bundles to install
327 installTGs.add(platformBundle);
330 // Bundle exists in the database
331 boolean platformBundleIsNewer = existingBundle.getVersion().compareTo(platformBundle.getVersion())<0;
332 if (!platformBundleIsNewer)
334 // Check hash of transferable graph to know whether to update or not.
335 if (platformBundle.getHashcode() == existingBundle.getHashcode())
337 //System.out.println("Ontology hashcodes do not match: platform bundle="
338 // + platformBundle.getVersionedId() + ", hash=" + platformBundle.getHashcode()
339 // + "; existing bundle=" + existingBundle.getVersionedId() + ", hash=" + existingBundle.getHashcode());
340 reinstallTGs.put(platformBundle, existingBundle);
344 // Database is missing graphs
345 if (!installTGs.isEmpty() || !reinstallTGs.isEmpty()) {
346 session.getService(XSupport.class).setServiceMode(true, true);
349 if (ontologyPolicy == OntologyRecoveryPolicy.ThrowError) {
350 StringBuilder sb = new StringBuilder("The following graphs are not installed in the database: ");
351 if (!installTGs.isEmpty()) {
353 for (GraphBundleEx e : installTGs) {
354 if (i>0) sb.append(", ");
356 sb.append(e.toString());
358 sb.append(" is missing from the database.\n");
360 if (!reinstallTGs.isEmpty()) {
362 for (Entry<GraphBundleEx, GraphBundleEx> e : reinstallTGs.entrySet()) {
363 if (i>0) sb.append(", ");
365 sb.append(e.getKey().toString());
367 sb.append(" Database/Platform Bundle version mismatch.\n");
369 sb.append("Hint: Use -fixErrors to install the graphs.");
370 throw new PlatformException(sb.toString());
372 // Reinstall database
373 if (ontologyPolicy == OntologyRecoveryPolicy.ReinstallDatabase) {
374 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Reinstalling the database."));
383 throw new PlatformException("Reinstalling Database, NOT IMPLEMENTED");
386 if (ontologyPolicy == OntologyRecoveryPolicy.Merge) {
387 message = "Merging ontology changes";
388 monitor.subTask(message);
389 LOGGER.info(message);
390 // Sort missing TGs into install order
391 GraphDependencyAnalyzer<GraphBundle> analyzer = new GraphDependencyAnalyzer<GraphBundle>();
392 for(GraphBundle tg : installTGs) analyzer.addGraph(tg, tg.getGraph());
393 for(GraphBundle tg : reinstallTGs.keySet()) analyzer.addGraph(tg, tg.getGraph());
394 if(!analyzer.analyzeDependency()) {
395 Collection<Pair<GraphBundle, GraphBundle>> problems = analyzer.getConflicts();
396 StringBuilder sb = new StringBuilder();
397 for (Pair<GraphBundle, GraphBundle> problem : problems) {
398 sb.append("Conflict with "+problem.first+" and "+problem.second+".\n");
400 throw new PlatformException(sb.toString());
401 } else if(!session.syncRequest( analyzer.queryExternalDependenciesSatisfied )) {
402 Collection<IdentityNode> unsatisfiedDependencies = analyzer.getUnsatisfiedDependencies();
403 StringBuilder sb = new StringBuilder();
404 for (IdentityNode dep: unsatisfiedDependencies) {
405 sb.append("Unsatisfied Dependency "+dep+". Required by\n");
406 for(IU iu : GraphDependencyAnalyzer.toCollection(dep.getRequires())) {
407 sb.append(" " + ((GraphBundle)iu.getId()).getId() + "\n");
410 throw new PlatformException(sb.toString());
413 message = "Analyzed graph bundles";
414 monitor.subTask(message);
415 LOGGER.info(message);
417 List<GraphBundle> sortedBundles = analyzer.getSortedGraphs();
418 if(!sortedBundles.isEmpty()) {
420 session.syncRequest((Write) graph -> {
422 graph.newClusterSet(graph.getRootLibrary());
423 } catch (ClusterSetExistException e) {
424 // Cluster set exist already, no problem.
426 graph.setClusterSet4NewResource(graph.getRootLibrary());
427 graph.flushCluster();
430 boolean mergedOntologies = false;
433 for(final GraphBundle tg : sortedBundles) {
435 final IImportAdvisor advisor = new OntologyImportAdvisor(tg, mgmt);
436 final GraphBundle oldTG = reinstallTGs.get(tg);
438 boolean createImmutable = tg.getImmutable();
442 session.getService(XSupport.class).setServiceMode(true, createImmutable);
445 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Installing "+tg.toString()+" - "+tg.getName()));
446 ImportResult result = TransferableGraphs.importGraph1(session, new TGTransferableGraphSource(tg.getGraph()), advisor, null);
447 if (!result.missingExternals.isEmpty()) {
448 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import of " + tg.toString() + " was missing the following external entities:\n" + EString.implode(result.missingExternals)));
455 startTransaction(session, false);
456 TransferableGraphDelta1 delta = new Diff(oldTG.getGraph(), tg.getGraph()).diff();
457 final long[] oldResources = oldTG.getResourceArray();
458 boolean changes = TransferableGraphs.hasChanges(readGraph(), oldResources, delta);
461 //log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Nothing to merge for "+tg.toString()));
465 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Merging new version of "+tg.toString()));
467 startTransaction(session, true);
471 long[] resourceArray = TransferableGraphs.applyDelta(writeGraph(), oldResources, delta);
472 tg.setResourceArray(resourceArray);
473 mgmt.setGraphBundleEntry(tg);
475 mergedOntologies = true;
476 } catch (Throwable t) {
477 throw new PlatformException(t);
484 session.syncRequest((Write) graph -> {
485 graph.setClusterSet4NewResource(graph.getRootLibrary());
486 graph.flushCluster();
489 if (mergedOntologies)
490 DatabaseIndexing.deleteAllIndexes();
493 session.getService(XSupport.class).setServiceMode(false, false);
495 message = "Ontologies synchronized";
496 monitor.subTask(message);
497 LOGGER.info(message);
499 } catch (IOException e) {
500 throw new PlatformException(e);
501 } catch (DatabaseException e) {
502 throw new PlatformException(e);
507 public boolean assertConfiguration(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy) throws PlatformException {
509 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
511 File workspaceLocation = Platform.getLocation().toFile();
513 boolean installProject = false;
514 progressMonitor.setTaskName("Asserting simantics.cfg is installed");
516 File propertyFile = new File(workspaceLocation, "simantics.cfg");
517 Properties properties;
519 properties = WorkspaceUtil.readProperties(propertyFile);
520 } catch (IOException e) {
521 if (workspacePolicy == RecoveryPolicy.ThrowError) throw new PlatformException("Could not load "+propertyFile);
523 // Create a project and write Property file
524 properties = new Properties();
525 properties.setProperty("project_uri", "http://Projects/Development%20Project");
526 properties.setProperty("project_name", "Development Project");
527 WorkspaceUtil.writeProperties(propertyFile, properties);
528 installProject |= true;
530 projectURI = properties.getProperty("project_uri");
531 projectName = properties.getProperty("project_name");
532 progressMonitor.worked(10);
533 } catch (IOException e) {
534 throw new PlatformException(e);
537 return installProject;
541 public boolean assertProject(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, boolean installProject) throws PlatformException {
543 SubMonitor monitor = SubMonitor.convert(progressMonitor, 10);
545 final DatabaseManagement mgmt = new DatabaseManagement();
547 monitor.setTaskName("Asserting project resource exists in the database");
549 projectResource = session.syncRequest(new PossibleResource(projectURI));
550 if (projectResource == null) {
551 // Project was not found
552 if (workspacePolicy == RecoveryPolicy.ThrowError)
553 throw new PlatformException("Project Resource "+projectURI+" is not found in the database.");
554 // Create empty project with no features
556 Transaction.startTransaction(session, true);
558 // The project needs to be created mutable.
559 session.getService(XSupport.class).setServiceMode(true, false);
561 ArrayList<String> empty = new ArrayList<String>();
562 projectResource = mgmt.createProject(projectName, empty);
563 installProject |= true;
565 session.getService(XSupport.class).setServiceMode(false, false);
566 Transaction.commit();
568 Transaction.endTransaction();
570 //session.getService( LifecycleSupport.class ).save();
571 } catch (DatabaseException e) {
572 throw new PlatformException("Failed to create "+projectURI, e);
575 } catch (DatabaseException e) {
576 throw new PlatformException("Failed to create "+projectURI, e);
580 return installProject;
584 public void updateInstalledGroups(IProgressMonitor progressMonitor, boolean installProject) throws PlatformException {
588 // Attach all feature groups available in platform to created project
589 progressMonitor.setTaskName("Install all features");
590 Set<GroupReference> publishedFeatureGroups = ProjectFeatures.getInstallGroupsOfPublishedFeatures();
591 Collection<GroupReference> groupsWithoutVersion = GroupReference.stripVersions(publishedFeatureGroups);
596 Projects.setProjectInstalledGroups(graph, projectResource, groupsWithoutVersion));
597 } catch (DatabaseException ae) {
598 throw new PlatformException("Failed to install features", ae);
600 progressMonitor.worked(10);
605 public void assertSessionModel(IProgressMonitor progressMonitor) throws PlatformException {
607 Properties properties = session.getService(Properties.class);
608 final String clientId = properties.getProperty("clientId");
612 // Currently this needs to be done before data becomes available
613 VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
614 VirtualGraph activations = support.getWorkspacePersistent("activations");
616 Resource sessionModel = session.syncRequest(new Read<Resource>() {
619 public Resource perform(ReadGraph graph) throws DatabaseException {
621 Layer0X L0X = Layer0X.getInstance(graph);
622 for(Resource sessionModel : graph.syncRequest(new ObjectsWithType(graph.getRootLibrary(), L0X.HasSession, L0X.Session))) {
623 String id = graph.getPossibleRelatedValue(sessionModel, L0X.Session_HasClientId);
624 if(id != null && id.equals(clientId)) return sessionModel;
632 if(sessionModel == null) {
634 sessionModel = session.syncRequest(new WriteResultRequest<Resource>(activations) {
637 public Resource perform(WriteGraph graph) throws DatabaseException {
638 Layer0 L0 = Layer0.getInstance(graph);
639 Layer0X L0X = Layer0X.getInstance(graph);
640 Resource session = graph.newResource();
641 graph.claim(session, L0.InstanceOf, null, L0X.Session);
642 graph.claim(session, L0X.Session_HasUser, null, graph.getResource("http://Users/AdminUser"));
643 graph.addLiteral(session, L0X.Session_HasClientId, L0X.Session_HasClientId_Inverse, clientId, Bindings.STRING);
644 graph.claim(graph.getRootLibrary(), L0X.HasSession, session);
651 session.registerService(SessionModel.class, new PlatformSessionModel(sessionModel));
652 } catch (DatabaseException e) {
653 throw new PlatformException(e);
658 static class PlatformSessionModel implements SessionModel {
659 private final Resource sessionModel;
661 public PlatformSessionModel(Resource model) {
662 this.sessionModel = model;
666 public Resource getResource() {
671 public void resetDatabase(IProgressMonitor monitor) throws PlatformException {
672 File dbLocation = Platform.getLocation().append("db").toFile();
673 if(!dbLocation.exists()) return;
675 Driver driver = Manager.getDriver("procore");
676 Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
678 } catch (DatabaseException e) {
679 throw new PlatformException("Failed to remove database at " + dbLocation.getAbsolutePath(), e);
681 // We have created extra files to database folder which have to be deleted also.
682 // This is an awful idea! Do not create extra files to database folder!
684 for (int i=0; i<10; ++i) {
686 FileUtils.deleteAll(dbLocation);
689 } catch (IOException e) {
690 // Assuming this has been thrown because delete file/folder failed.
695 } catch (InterruptedException e) {
696 // Ignoring interrupted exception.
700 throw new PlatformException("Failed to remove database folder at " + dbLocation.getAbsolutePath(), t);
702 public void resetWorkspace(IProgressMonitor monitor, ArrayList<String> fileFilter) throws PlatformException, IllegalStateException, IOException {
703 File file = Platform.getLocation().toFile();
704 if (null != fileFilter)
705 FileUtils.deleteAllWithFilter(file , fileFilter);
706 resetDatabase(monitor);
709 private static Path tryGetInstallLocation() {
710 Location l = Platform.getInstallLocation();
711 return l == null ? null : new File(l.getURL().getPath()).toPath();
714 private Path resolveBaselineFile() throws PlatformException {
715 String dbBaselineArchive = System.getProperty("org.simantics.db.baseline", null);
716 if (dbBaselineArchive == null)
719 Path baseline = Paths.get(dbBaselineArchive);
720 if (baseline.isAbsolute()) {
721 if (!Files.isRegularFile(baseline))
722 throw new PlatformException("Specified database baseline archive " + baseline
723 + " does not exist. Cannot initialize workspace database from baseline.");
727 // Relative path resolution order:
728 // 1. from the platform "install location"
729 // 2. from working directory
730 Path installLocation = tryGetInstallLocation();
731 if (installLocation != null) {
732 Path installedBaseline = installLocation.resolve(dbBaselineArchive);
733 if (Files.isRegularFile(installedBaseline))
734 return installedBaseline;
736 if (!Files.isRegularFile(baseline))
737 throw new PlatformException("Specified database baseline archive " + baseline
738 + " does not exist in either the install location (" + installLocation
739 + ") or the working directory (" + Paths.get(".").toAbsolutePath()
740 + "). Cannot initialize workspace database.");
744 private boolean handleBaselineDatabase() throws PlatformException {
745 Path workspaceLocation = Platform.getLocation().toFile().toPath();
746 Path baselineIndicatorFile = workspaceLocation.resolve(".baselined");
747 if (Files.isRegularFile(baselineIndicatorFile)) {
748 // This means that the workspace has already been initialized from
749 // a database baseline and further initialization is not necessary.
753 Path baseline = resolveBaselineFile();
754 if (baseline == null)
757 DatabaseBaselines.validateBaselineFile(baseline);
758 DatabaseBaselines.validateWorkspaceForBaselineInitialization(workspaceLocation);
759 DatabaseBaselines.initializeWorkspaceWithBaseline(baseline, workspaceLocation, baselineIndicatorFile);
764 * Start-up the platform. The procedure consists of 8 steps. Once everything
765 * is up and running, all fields are set property.
768 * If workspacePolicy is FixErrors, there is an attempt to fix unexpected
769 * errors. It includes installing database files, installing ontologies, and
770 * installing project features.
773 * In Simantics Workbench this is handled in
774 * <code>SimanticsWorkbenchAdvisor#openWindows()</code>.
777 * If remote server is given, simantics plaform takes connection there
778 * instead of local server at "db/".
780 * @param workspacePolicy action to take on workspace/database related
782 * @param ontologyPolicy action to take on ontology mismatch
783 * @param progressMonitor optional progress monitor
784 * @param userAgent interface for resorting to user feedback during platform
785 * startup or <code>null</code> to resort to default measures
786 * @throws PlatformException
788 public synchronized SessionContext startUp(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy,
789 OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize, PlatformUserAgent userAgent)
790 throws PlatformException
794 LOGGER.info("Beginning of SimanticsPlatform.startUp");
796 SubMonitor monitor = SubMonitor.convert(progressMonitor, 1000);
798 // For debugging on what kind of platform automatic tests are running in
799 // case there are problems.
800 if ("true".equals(System.getProperty("org.simantics.dumpBundleState")))
801 dumpPlatformBundleState();
803 // 0. Consult all startup extensions before doing anything with the workspace.
804 StartupExtensions.consultStartupExtensions();
805 LOGGER.info("Consulted platform pre-startup extensions");
807 // 0.1. Clear all temporary files
808 Simantics.clearTemporaryDirectory();
809 LOGGER.info("Cleared temporary directory");
811 // 0.2 Clear VariableRepository.repository static map which holds references to SessionImplDb
812 VariableRepository.clear();
814 // 0.2.1 Activate org.simantics.scl.osgi to prime the SCL compiler early.
815 @SuppressWarnings("unused")
816 ModuleRepository modRepo = SCLOsgi.MODULE_REPOSITORY;
818 // 0.3 Handle baseline database before opening db
819 @SuppressWarnings("unused")
820 boolean usingBaseline = handleBaselineDatabase();
822 // 1. Assert there is a database at <workspace>/db
823 SessionDescriptor sessionDescriptor = setupDatabase(databaseDriverId, monitor.newChild(200, SubMonitor.SUPPRESS_NONE), workspacePolicy, userAgent);
824 session = sessionDescriptor.getSession();
825 LOGGER.info("Database setup complete");
827 // 2. Delete all indexes if we cannot be certain they are up-to-date
828 // A full index rebuild will be done later, before project activation.
829 XSupport support = session.getService(XSupport.class);
830 if (support.rolledback()) {
832 DatabaseIndexing.deleteAllIndexes();
833 } catch (IOException e) {
834 throw new PlatformException(e);
838 // 3. Assert all graphs, and correct versions, are installed to the database
839 synchronizeOntologies(monitor.newChild(400, SubMonitor.SUPPRESS_NONE), ontologyPolicy, requireSynchronize);
841 // 4. Assert simantics.cfg exists
842 boolean installProject = assertConfiguration(monitor.newChild(25, SubMonitor.SUPPRESS_NONE),workspacePolicy);
844 // 5. Assert Project Resource is installed in the database
845 installProject = assertProject(monitor.newChild(25, SubMonitor.SUPPRESS_NONE), workspacePolicy, installProject);
847 // 6. Install all features into project, if in debug mode
848 updateInstalledGroups(monitor.newChild(25), true); //installProject);
849 LOGGER.info("Installed all features into project");
851 // 7. Assert L0.Session in database for this session
852 assertSessionModel(monitor.newChild(25, SubMonitor.SUPPRESS_NONE));
854 session.getService(XSupport.class).setServiceMode(false, false);
857 String message = "Flush query cache";
858 monitor.setTaskName(message);
859 LOGGER.info(message);
860 session.syncRequest((Write) graph -> {
861 QueryControl qc = graph.getService(QueryControl.class);
864 } catch (DatabaseException e) {
865 LOGGER.error("Flushing queries failed.", e);
867 boolean loadProject = true;
869 String message = "Open database session";
870 monitor.setTaskName(message);
871 LOGGER.info(message);
872 sessionContext = SimanticsPlatform.INSTANCE.createSessionContext(true);
873 // This must be before setSessionContext since some listeners might query this
874 sessionContext.setHint(SimanticsKeys.KEY_PROJECT, SimanticsPlatform.INSTANCE.projectResource);
876 Simantics.setSessionContext(sessionContext);
878 // 1. Put ResourceBinding that throws an exception to General Bindings
879 message = "Put ResourceBinding that throws an exception to General Bindings";
880 LOGGER.info(message);
881 simanticsBindings = new SimanticsBindings();
882 Bindings.classBindingFactory.addFactory( simanticsBindings );
884 Session session = sessionContext.getSession();
885 session.registerService(Databoard.class, Bindings.databoard);
887 // Register datatype bindings
888 message = "Register datatype bindings";
889 LOGGER.info(message);
890 Bindings.defaultBindingFactory.getRepository().put(RGB.Integer.BINDING.type(), RGB.Integer.BINDING);
891 Bindings.defaultBindingFactory.getRepository().put(Font.BINDING.type(), Font.BINDING);
893 if (support.rolledback() || sessionDescriptor.isFreshDatabase()) {
894 message = "Rebuilding all indexes";
895 LOGGER.info(message);
896 monitor.setTaskName(message);
898 session.getService(IndexedRelations.class).fullRebuild(monitor.newChild(100), session);
899 } catch (IndexException e) {
900 LOGGER.error("Failed to re-build all indexes", e);
907 message = "Load project";
908 monitor.setTaskName(message);
909 LOGGER.info(message);
910 project = Projects.loadProject(sessionContext.getSession(), SimanticsPlatform.INSTANCE.projectResource);
911 sessionContext.setHint(ProjectKeys.KEY_PROJECT, project);
913 message = "Loading projects complete";
914 LOGGER.info(message);
916 message = "Activate project";
917 monitor.setTaskName(message);
918 LOGGER.info(message);
921 LOGGER.info("Project activated");
924 } catch (DatabaseException e) {
925 LOGGER.error("Platform startup failed.", e);
926 throw new PlatformException(e);
927 } catch (ProjectException e) {
928 boolean hasStackTrace = e.getStackTrace().length > 0;
930 throw new PlatformException(e.getMessage(), hasStackTrace);
931 throw new PlatformException(e, hasStackTrace);
936 // #7650: improve shutdown robustness in all applications that use the platform
937 Runtime.getRuntime().addShutdownHook(shutdownHook);
939 // Discard database session undo history at this point to prevent
940 // the user from undoing any initialization operations performed
941 // by the platform startup.
942 SimanticsPlatform.INSTANCE.discardSessionUndoHistory();
943 LOGGER.info("Discarded session undo history");
945 return sessionContext;
949 public SessionContext createSessionContext(boolean init) throws PlatformException {
951 // Construct and initialize SessionContext from Session.
952 SessionContext sessionContext = SessionContext.create(session, init);
953 String message = "Session context created";
954 LOGGER.info(message);
956 sessionContext.registerServices();
957 message = "Session services registered";
958 LOGGER.info(message);
960 return sessionContext;
961 } catch (DatabaseException e) {
962 throw new PlatformException(e);
967 * Perform normal shutdown for the Simantics Platform.
969 * @param progressMonitor optional progress monitor
970 * @throws PlatformException
971 * @see {@link #shutdown(IProgressMonitor, boolean)}
973 public synchronized void shutdown(IProgressMonitor progressMonitor) throws PlatformException {
974 shutdown(progressMonitor, true);
978 * Shutdown Simantics Platform.
980 * In Simantics Workbench this is handled in
981 * <code>SimanticsWorkbenchAdvisor#disconnectFromWorkspace</code>.
983 * @param progressMonitor
984 * optional progress monitor
985 * @param clearTemporaryFiles
986 * allow or prevent deletion of temporary files at the end of the
988 * @throws PlatformException
990 public synchronized void shutdown(IProgressMonitor progressMonitor, boolean clearTemporaryFiles) throws PlatformException
992 SubMonitor progress = SubMonitor.convert(progressMonitor, 100);
993 PlatformException platformException = null;
995 progress.subTask("Close Project");
996 if (project != null) {
997 project.safeDispose();
1001 // NOP at the moment
1002 TimedSessionCache.close();
1004 progress.subTask("Thread pools");
1005 ThreadUtils.shutdown();
1006 ExecutorWorker.shutdown();
1010 progress.subTask("Close Database Session");
1011 if (sessionContext != null) {
1012 Session s = sessionContext.peekSession();
1014 progress.subTask("Flushing Index Caches");
1016 Simantics.flushIndexCaches(progress.newChild(20), s);
1017 } catch (Throwable t) {
1018 LOGGER.error("Failed to flush index caches.", t);
1022 progress.subTask("Close Database Session");
1023 sessionContext.safeDispose();
1024 sessionContext = null;
1025 Simantics.setSessionContext(null);
1027 if (simanticsBindings != null) {
1028 Bindings.classBindingFactory.removeFactory( simanticsBindings );
1029 simanticsBindings = null;
1032 // Make sure Simantics clipboard doesn't store unwanted session data references.
1033 Simantics.setClipboard(new SimanticsClipboardImpl());
1035 progress.worked(50);
1038 projectResource = null;
1039 currentDatabaseDriver = null;
1041 DependenciesRelation.assertFinishedTracking();
1043 } catch (Exception e) {
1044 platformException = new PlatformException("Failed to shutdown Simantics Platform", e);
1047 progress.worked(10);
1048 progress.subTask("Shutting down database");
1050 if (null != databasebManagement)
1051 databasebManagement.shutdown();
1052 } catch (Throwable t) {
1053 LOGGER.error("Database shutdown failed.", t);
1055 progress.worked(10);
1057 progress.subTask("Clear index status");
1059 // Everything ok, clear index dirty state.
1060 DatabaseIndexing.clearAllDirty();
1061 } catch (IOException e) {
1062 LOGGER.error("Problems encountered while refreshing database index states, see exception for details.", e);
1066 if (clearTemporaryFiles) {
1067 progress.subTask("Clearing Workspace Temporary Directory");
1069 Simantics.clearTemporaryDirectory();
1070 } catch (Throwable t) {
1071 LOGGER.error("Failed to clear the temporary directory.", t);
1074 progress.worked(10);
1075 if (null != platformException)
1076 throw platformException;
1078 // #7650: improve shutdown robustness in all applications that use the platform
1079 Runtime.getRuntime().removeShutdownHook(shutdownHook);
1082 // TODO: consider removing this in the future ??
1084 public void stateChanged(LifecycleState newState) {
1085 if(newState == LifecycleState.CLOSED) {
1087 if(Platform.isRunning()) {
1088 mainThread.interrupt();
1095 * @return <code>true</code> if discard was successful, <code>false</code>
1096 * if there was no session, {@link UndoRedoSupport} or
1097 * {@link UndoContext} to discard through
1099 public boolean discardSessionUndoHistory() {
1100 Session s = session;
1102 UndoRedoSupport urs = s.peekService(UndoRedoSupport.class);
1104 UndoContext uc = urs.getUndoContext(s);
1114 public void reconnect(String databaseDriverId) throws Exception {
1115 // Starts database server.
1116 if (currentDatabaseDriver != null)
1117 databaseDriverId = currentDatabaseDriver;
1118 SimanticsPlatform.INSTANCE.startUp(databaseDriverId, null, RecoveryPolicy.ThrowError, OntologyRecoveryPolicy.ThrowError, true, null);
1121 private void dumpPlatformBundleState() {
1122 BundleDescription[] bs = Platform.getPlatformAdmin().getState().getBundles();
1123 System.out.println("Total bundles: " + bs.length);
1124 for (BundleDescription b : bs) {
1125 System.out.format("%-80s @ %s\n", b.toString(), b.getLocation());
1129 private Ini loadOrCreateDatabaseIni(Path path, String databaseDriverId)
1130 throws InvalidFileFormatException, IOException
1132 File f = path.toFile();
1133 Ini dbIni = Files.isRegularFile(path) ? new Ini(f) : new Ini();
1134 String iniId = dbIni != null ? dbIni.get("driver", "id") : null;
1135 if (iniId == null) {
1136 dbIni.put("driver", "id", databaseDriverId);