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.SimanticsPlatform.OntologyRecoveryPolicy;
49 import org.simantics.SimanticsPlatform.RecoveryPolicy;
50 import org.simantics.databoard.Bindings;
51 import org.simantics.databoard.Databoard;
52 import org.simantics.datatypes.literal.Font;
53 import org.simantics.datatypes.literal.RGB;
54 import org.simantics.db.Driver;
55 import org.simantics.db.Driver.Management;
56 import org.simantics.db.Manager;
57 import org.simantics.db.ReadGraph;
58 import org.simantics.db.Resource;
59 import org.simantics.db.Session;
60 import org.simantics.db.SessionModel;
61 import org.simantics.db.UndoContext;
62 import org.simantics.db.VirtualGraph;
63 import org.simantics.db.WriteGraph;
64 import org.simantics.db.common.processor.MergingDelayedWriteProcessor;
65 import org.simantics.db.common.processor.MergingGraphRequestProcessor;
66 import org.simantics.db.common.request.ObjectsWithType;
67 import org.simantics.db.common.request.WriteResultRequest;
68 import org.simantics.db.common.utils.Transaction;
69 import org.simantics.db.exception.ClusterSetExistException;
70 import org.simantics.db.exception.DatabaseException;
71 import org.simantics.db.indexing.DatabaseIndexing;
72 import org.simantics.db.layer0.genericrelation.DependenciesRelation;
73 import org.simantics.db.layer0.genericrelation.IndexException;
74 import org.simantics.db.layer0.genericrelation.IndexedRelations;
75 import org.simantics.db.layer0.request.PossibleResource;
76 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
77 import org.simantics.db.layer0.util.SimanticsKeys;
78 import org.simantics.db.layer0.util.TGTransferableGraphSource;
79 import org.simantics.db.layer0.variable.VariableRepository;
80 import org.simantics.db.management.SessionContext;
81 import org.simantics.db.request.Read;
82 import org.simantics.db.request.Write;
83 import org.simantics.db.service.LifecycleSupport.LifecycleListener;
84 import org.simantics.db.service.LifecycleSupport.LifecycleState;
85 import org.simantics.db.service.QueryControl;
86 import org.simantics.db.service.UndoRedoSupport;
87 import org.simantics.db.service.VirtualGraphSupport;
88 import org.simantics.db.service.XSupport;
89 import org.simantics.db.services.GlobalServiceInitializer;
90 import org.simantics.graph.db.GraphDependencyAnalyzer;
91 import org.simantics.graph.db.GraphDependencyAnalyzer.IU;
92 import org.simantics.graph.db.GraphDependencyAnalyzer.IdentityNode;
93 import org.simantics.graph.db.IImportAdvisor;
94 import org.simantics.graph.db.ImportResult;
95 import org.simantics.graph.db.TransferableGraphs;
96 import org.simantics.graph.diff.Diff;
97 import org.simantics.graph.diff.TransferableGraphDelta1;
98 import org.simantics.internal.Activator;
99 import org.simantics.internal.TimedSessionCache;
100 import org.simantics.internal.startup.StartupExtensions;
101 import org.simantics.layer0.Layer0;
102 import org.simantics.operation.Layer0X;
103 import org.simantics.project.IProject;
104 import org.simantics.project.ProjectFeatures;
105 import org.simantics.project.ProjectKeys;
106 import org.simantics.project.Projects;
107 import org.simantics.project.SessionDescriptor;
108 import org.simantics.project.exception.ProjectException;
109 import org.simantics.project.features.registry.GroupReference;
110 import org.simantics.project.management.DatabaseManagement;
111 import org.simantics.project.management.GraphBundle;
112 import org.simantics.project.management.GraphBundleEx;
113 import org.simantics.project.management.GraphBundleRef;
114 import org.simantics.project.management.PlatformUtil;
115 import org.simantics.project.management.ServerManager;
116 import org.simantics.project.management.ServerManagerFactory;
117 import org.simantics.project.management.WorkspaceUtil;
118 import org.simantics.scl.compiler.module.repository.ModuleRepository;
119 import org.simantics.scl.osgi.SCLOsgi;
120 import org.simantics.utils.FileUtils;
121 import org.simantics.utils.datastructures.Pair;
122 import org.simantics.utils.strings.EString;
123 import org.simantics.utils.threads.ExecutorWorker;
124 import org.simantics.utils.threads.ThreadUtils;
125 import org.slf4j.Logger;
126 import org.slf4j.LoggerFactory;
129 * SimanticsPlatform performs procedures required in order to get simantics
130 * workbench into operational state. This consists of the following steps:
132 * <li> Asserting there is Database
134 * <li> Starting Database process
136 * <li> Opening a session to Database process
138 * <li> Asserting required ontologies or other transferable graphs are installed in the database
140 * <li> Asserting required project is installed in the database
142 * <li> Asserting Simantics Features are installed in the database
144 * <li> Asserting Simantics Features are installed to the project
146 * <li> Shutdown: Save Session, Close session, Kill Database process
150 * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
152 public class SimanticsPlatform implements LifecycleListener {
154 private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsPlatform.class);
157 * The policy is relevant when developing Simantics from Eclipse IDE.
158 * It is applied when the ontology in the database of a workspace doesn't match
159 * a newer ontology in the Eclipse workspace.
161 public static enum OntologyRecoveryPolicy { ThrowError, Merge, ReinstallDatabase, Bypass}
164 * This policy dictates how the Simantics platform startup should react if
165 * the started workspace is not set up properly. The alternatives are to
166 * just throw an error and fail or to attempt all possible measures to fix
167 * the encountered problems.
169 public static enum RecoveryPolicy { ThrowError, FixError }
171 /** Singleton instance, started in SimanticsWorkbenchAdvisor */
172 public static final SimanticsPlatform INSTANCE = new SimanticsPlatform();
174 /** Set to true when the Simantics Platform is in good-and-go condition */
175 public boolean running;
177 /** ID of the database driver that the platform is currently using */
178 private String currentDatabaseDriver;
180 /** Database Session */
181 public Session session;
182 private Management databasebManagement;
184 /** Database session context */
185 public SessionContext sessionContext;
187 /** Project identifier in Database */
188 public String projectURI;
191 public String projectName;
193 /** Project resource */
194 public Resource projectResource;
196 /** Session specific bindings */
197 public SimanticsBindings simanticsBindings;
199 public Thread mainThread;
201 private Thread shutdownHook = new Thread() {
205 LOGGER.warn("Simantics platform was not properly shut down. Executing safety shutdown hook.");
206 shutdown(null, false);
207 } catch (PlatformException e) {
208 LOGGER.error("Simantics Platform shutdown hook execution failed.", e);
209 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Simantics Platform shutdown hook execution failed.", e));
215 * The {@link IProject} activated by
216 * {@link #startUp(IProgressMonitor, RecoveryPolicy, OntologyRecoveryPolicy, ServerAddress, PlatformUserAgent)}
218 private IProject project;
223 * Create a new simantics plaform manager in uninitialized state and
224 * with default policies. <p>
226 public SimanticsPlatform() {
227 log = Platform.getLog(Activator.getBundleContext().getBundle());
228 mainThread = Thread.currentThread();
231 public String getApplicationClientId() {
232 IProduct product = Platform.getProduct();
233 if(product == null) return "noProduct";//UUID.randomUUID().toString();
234 String application = product.getApplication();
235 return application != null ? application : UUID.randomUUID().toString();
238 private SessionDescriptor setupDatabase(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, PlatformUserAgent userAgent) throws PlatformException {
239 if (progressMonitor == null)
240 progressMonitor = new NullProgressMonitor();
241 Path workspaceLocation = Platform.getLocation().toFile().toPath();
242 Path dbLocation = workspaceLocation.resolve("db");
243 Path dbIniPath = workspaceLocation.resolve("db.ini");
244 // The driver file overrides any command line arguments to prevent
245 // using the wrong driver for an existing database directory.
246 ServerManager serverManager;
248 Ini dbIni = loadOrCreateDatabaseIni(dbIniPath, databaseDriverId);
249 databaseDriverId = dbIni.get("driver", "id");
250 serverManager = ServerManagerFactory.create(databaseDriverId, dbLocation.toAbsolutePath().toString());
251 } catch (DatabaseException | IOException e) {
252 throw new PlatformException("Failed to initialize database ServerManager with driver " + databaseDriverId, e);
254 progressMonitor.beginTask("Setting up Simantics Database", 100);
255 progressMonitor.setTaskName("Asserting Database is installed.");
256 String msg = "Failed to initialize Simantics database.";
259 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Initializing database at " + dbLocation + " with driver " + databaseDriverId));
260 progressMonitor.setTaskName("Creating database at " + dbLocation);
261 databasebManagement = serverManager.getManagement(dbLocation.toFile());
262 databasebManagement.create();
263 currentDatabaseDriver = databaseDriverId;
265 return serverManager.createDatabase(dbLocation.toFile());
266 } catch (DatabaseException e) {
267 throw new PlatformException(msg, e);
268 } catch (Throwable e) {
269 throw new PlatformException(msg, e);
271 progressMonitor.worked(20);
275 public void synchronizeOntologies(IProgressMonitor progressMonitor, OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize) throws PlatformException {
277 SubMonitor monitor = SubMonitor.convert(progressMonitor, 100);
279 monitor.setTaskName("Compile dynamic ontologies");
280 PlatformUtil.compileAllDynamicOntologies();
282 String message = "Asserting all ontologies are installed";
283 LOGGER.info(message);
284 monitor.setTaskName(message);
286 DatabaseManagement mgmt = new DatabaseManagement();
287 Map<GraphBundleRef, GraphBundleEx> platformTGs = new HashMap<>();
290 // Get a list of bundles installed into the database
291 message = "find installed bundles from database";
292 monitor.subTask(message);
293 LOGGER.info(message);
294 Map<GraphBundleRef, GraphBundleEx> installedTGs = new HashMap<>();
295 for (GraphBundle b : session.syncRequest( mgmt.GraphBundleQuery )) {
296 installedTGs.put(GraphBundleRef.of(b), GraphBundleEx.extend(b));
299 if(!requireSynchronize && installedTGs.size() > 1 && !Platform.inDevelopmentMode()) return;
300 // if(installedTGs.size() > 1) return;
302 // Get a list of all bundles in the platform (Bundle Context)
303 message = "load all transferable graphs from platform";
304 monitor.subTask(message);
305 LOGGER.info(message);
306 Collection<GraphBundle> tgs = PlatformUtil.getAllGraphs();
307 message = "extend bundles to compile versions";
308 monitor.subTask(message);
309 LOGGER.info(message);
310 for (GraphBundle b : tgs) {
311 GraphBundleEx gbe = GraphBundleEx.extend(b);
313 platformTGs.put(GraphBundleRef.of(b), gbe);
316 // Compile a list of TGs that need to be installed or reinstalled in the database
317 message = "check bundle reinstallation demand";
318 monitor.subTask(message);
319 LOGGER.info(message);
320 List<GraphBundleEx> installTGs = new ArrayList<>();
321 // Create list of TGs to update, <newTg, oldTg>
322 Map<GraphBundleEx,GraphBundleEx> reinstallTGs = new TreeMap<>();
323 for (Entry<GraphBundleRef, GraphBundleEx> e : platformTGs.entrySet()) {
324 GraphBundleRef key = e.getKey();
325 GraphBundleEx platformBundle = e.getValue();
326 GraphBundleEx existingBundle = installedTGs.get(key);
328 // System.out.println("GraphBundleRef key=" + key.toString());
330 if (existingBundle == null) {
331 // Bundle did not exist in the database, put it into list of bundles to install
332 installTGs.add(platformBundle);
335 // Bundle exists in the database
336 boolean platformBundleIsNewer = existingBundle.getVersion().compareTo(platformBundle.getVersion())<0;
337 if (!platformBundleIsNewer)
339 // Check hash of transferable graph to know whether to update or not.
340 if (platformBundle.getHashcode() == existingBundle.getHashcode())
342 //System.out.println("Ontology hashcodes do not match: platform bundle="
343 // + platformBundle.getVersionedId() + ", hash=" + platformBundle.getHashcode()
344 // + "; existing bundle=" + existingBundle.getVersionedId() + ", hash=" + existingBundle.getHashcode());
345 reinstallTGs.put(platformBundle, existingBundle);
349 // Database is missing graphs
350 if (!installTGs.isEmpty() || !reinstallTGs.isEmpty()) {
351 session.getService(XSupport.class).setServiceMode(true, true);
354 if (ontologyPolicy == OntologyRecoveryPolicy.ThrowError || ontologyPolicy == OntologyRecoveryPolicy.Bypass) {
355 StringBuilder sb = new StringBuilder("The following graphs are not installed in the database: ");
356 if (!installTGs.isEmpty()) {
358 for (GraphBundleEx e : installTGs) {
359 if (i>0) sb.append(", ");
361 sb.append(e.toString());
363 sb.append(" is missing from the database.\n");
365 if (!reinstallTGs.isEmpty()) {
367 for (Entry<GraphBundleEx, GraphBundleEx> e : reinstallTGs.entrySet()) {
368 if (i>0) sb.append(", ");
370 sb.append(e.getKey().toString());
372 sb.append(" Database/Platform Bundle version mismatch.\n");
374 sb.append("Hint: Use -fixErrors to install the graphs.");
375 if (ontologyPolicy == OntologyRecoveryPolicy.ThrowError)
376 throw new PlatformException(sb.toString());
378 log.log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, sb.toString()));
381 // Reinstall database
382 if (ontologyPolicy == OntologyRecoveryPolicy.ReinstallDatabase) {
383 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Reinstalling the database."));
392 throw new PlatformException("Reinstalling Database, NOT IMPLEMENTED");
395 if (ontologyPolicy == OntologyRecoveryPolicy.Merge) {
396 message = "Merging ontology changes";
397 monitor.subTask(message);
398 LOGGER.info(message);
399 // Sort missing TGs into install order
400 GraphDependencyAnalyzer<GraphBundle> analyzer = new GraphDependencyAnalyzer<GraphBundle>();
401 for(GraphBundle tg : installTGs) analyzer.addGraph(tg, tg.getGraph());
402 for(GraphBundle tg : reinstallTGs.keySet()) analyzer.addGraph(tg, tg.getGraph());
403 if(!analyzer.analyzeDependency()) {
404 Collection<Pair<GraphBundle, GraphBundle>> problems = analyzer.getConflicts();
405 StringBuilder sb = new StringBuilder();
406 for (Pair<GraphBundle, GraphBundle> problem : problems) {
407 sb.append("Conflict with "+problem.first+" and "+problem.second+".\n");
409 throw new PlatformException(sb.toString());
410 } else if(!session.syncRequest( analyzer.queryExternalDependenciesSatisfied )) {
411 Collection<IdentityNode> unsatisfiedDependencies = analyzer.getUnsatisfiedDependencies();
412 StringBuilder sb = new StringBuilder();
413 for (IdentityNode dep: unsatisfiedDependencies) {
414 sb.append("Unsatisfied Dependency "+dep+". Required by\n");
415 for(IU iu : GraphDependencyAnalyzer.toCollection(dep.getRequires())) {
416 sb.append(" " + ((GraphBundle)iu.getId()).getId() + "\n");
419 throw new PlatformException(sb.toString());
422 message = "Analyzed graph bundles";
423 monitor.subTask(message);
424 LOGGER.info(message);
426 List<GraphBundle> sortedBundles = analyzer.getSortedGraphs();
427 if(!sortedBundles.isEmpty()) {
429 session.syncRequest((Write) graph -> {
431 graph.newClusterSet(graph.getRootLibrary());
432 } catch (ClusterSetExistException e) {
433 // Cluster set exist already, no problem.
435 graph.setClusterSet4NewResource(graph.getRootLibrary());
436 graph.flushCluster();
439 boolean mergedOntologies = false;
442 for(final GraphBundle tg : sortedBundles) {
444 final IImportAdvisor advisor = new OntologyImportAdvisor(tg, mgmt);
445 final GraphBundle oldTG = reinstallTGs.get(tg);
447 boolean createImmutable = tg.getImmutable();
451 session.getService(XSupport.class).setServiceMode(true, createImmutable);
454 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Installing "+tg.toString()+" - "+tg.getName()));
455 ImportResult result = TransferableGraphs.importGraph1(session, new TGTransferableGraphSource(tg.getGraph()), advisor, null);
456 if (!result.missingExternals.isEmpty()) {
457 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import of " + tg.toString() + " was missing the following external entities:\n" + EString.implode(result.missingExternals)));
464 startTransaction(session, false);
465 TransferableGraphDelta1 delta = new Diff(oldTG.getGraph(), tg.getGraph()).diff();
466 final long[] oldResources = oldTG.getResourceArray();
467 boolean changes = TransferableGraphs.hasChanges(readGraph(), oldResources, delta);
470 //log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Nothing to merge for "+tg.toString()));
474 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Merging new version of "+tg.toString()));
476 startTransaction(session, true);
480 long[] resourceArray = TransferableGraphs.applyDelta(writeGraph(), oldResources, delta);
481 tg.setResourceArray(resourceArray);
482 mgmt.setGraphBundleEntry(tg);
484 mergedOntologies = true;
485 } catch (Throwable t) {
486 throw new PlatformException(t);
493 session.syncRequest((Write) graph -> {
494 graph.setClusterSet4NewResource(graph.getRootLibrary());
495 graph.flushCluster();
498 if (mergedOntologies)
499 DatabaseIndexing.deleteAllIndexes();
502 session.getService(XSupport.class).setServiceMode(false, false);
504 message = "Ontologies synchronized";
505 monitor.subTask(message);
506 LOGGER.info(message);
508 } catch (IOException e) {
509 throw new PlatformException(e);
510 } catch (DatabaseException e) {
511 throw new PlatformException(e);
516 public boolean assertConfiguration(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy) throws PlatformException {
518 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
520 File workspaceLocation = Platform.getLocation().toFile();
522 boolean installProject = false;
523 progressMonitor.setTaskName("Asserting simantics.cfg is installed");
525 File propertyFile = new File(workspaceLocation, "simantics.cfg");
526 Properties properties;
528 properties = WorkspaceUtil.readProperties(propertyFile);
529 } catch (IOException e) {
530 if (workspacePolicy == RecoveryPolicy.ThrowError) throw new PlatformException("Could not load "+propertyFile);
532 // Create a project and write Property file
533 properties = new Properties();
534 properties.setProperty("project_uri", "http://Projects/Development%20Project");
535 properties.setProperty("project_name", "Development Project");
536 WorkspaceUtil.writeProperties(propertyFile, properties);
537 installProject |= true;
539 projectURI = properties.getProperty("project_uri");
540 projectName = properties.getProperty("project_name");
541 progressMonitor.worked(10);
542 } catch (IOException e) {
543 throw new PlatformException(e);
546 return installProject;
550 public boolean assertProject(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, boolean installProject) throws PlatformException {
552 SubMonitor monitor = SubMonitor.convert(progressMonitor, 10);
554 final DatabaseManagement mgmt = new DatabaseManagement();
556 monitor.setTaskName("Asserting project resource exists in the database");
558 projectResource = session.syncRequest(new PossibleResource(projectURI));
559 if (projectResource == null) {
560 // Project was not found
561 if (workspacePolicy == RecoveryPolicy.ThrowError)
562 throw new PlatformException("Project Resource "+projectURI+" is not found in the database.");
563 // Create empty project with no features
565 Transaction.startTransaction(session, true);
567 // The project needs to be created mutable.
568 session.getService(XSupport.class).setServiceMode(true, false);
570 ArrayList<String> empty = new ArrayList<String>();
571 projectResource = mgmt.createProject(projectName, empty);
572 installProject |= true;
574 session.getService(XSupport.class).setServiceMode(false, false);
575 Transaction.commit();
577 Transaction.endTransaction();
579 //session.getService( LifecycleSupport.class ).save();
580 } catch (DatabaseException e) {
581 throw new PlatformException("Failed to create "+projectURI, e);
584 } catch (DatabaseException e) {
585 throw new PlatformException("Failed to create "+projectURI, e);
589 return installProject;
593 public void updateInstalledGroups(IProgressMonitor progressMonitor, boolean installProject) throws PlatformException {
597 // Attach all feature groups available in platform to created project
598 progressMonitor.setTaskName("Install all features");
599 Set<GroupReference> publishedFeatureGroups = ProjectFeatures.getInstallGroupsOfPublishedFeatures();
600 Collection<GroupReference> groupsWithoutVersion = GroupReference.stripVersions(publishedFeatureGroups);
605 Projects.setProjectInstalledGroups(graph, projectResource, groupsWithoutVersion));
606 } catch (DatabaseException ae) {
607 throw new PlatformException("Failed to install features", ae);
609 progressMonitor.worked(10);
614 public void assertSessionModel(IProgressMonitor progressMonitor) throws PlatformException {
616 Properties properties = session.getService(Properties.class);
617 final String clientId = properties.getProperty("clientId");
621 // Currently this needs to be done before data becomes available
622 VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
623 VirtualGraph activations = support.getWorkspacePersistent("activations");
625 Resource sessionModel = session.syncRequest(new Read<Resource>() {
628 public Resource perform(ReadGraph graph) throws DatabaseException {
630 Layer0X L0X = Layer0X.getInstance(graph);
631 for(Resource sessionModel : graph.syncRequest(new ObjectsWithType(graph.getRootLibrary(), L0X.HasSession, L0X.Session))) {
632 String id = graph.getPossibleRelatedValue(sessionModel, L0X.Session_HasClientId);
633 if(id != null && id.equals(clientId)) return sessionModel;
641 if(sessionModel == null) {
643 sessionModel = session.syncRequest(new WriteResultRequest<Resource>(activations) {
646 public Resource perform(WriteGraph graph) throws DatabaseException {
647 Layer0 L0 = Layer0.getInstance(graph);
648 Layer0X L0X = Layer0X.getInstance(graph);
649 Resource session = graph.newResource();
650 graph.claim(session, L0.InstanceOf, null, L0X.Session);
651 graph.claim(session, L0X.Session_HasUser, null, graph.getResource("http://Users/AdminUser"));
652 graph.addLiteral(session, L0X.Session_HasClientId, L0X.Session_HasClientId_Inverse, clientId, Bindings.STRING);
653 graph.claim(graph.getRootLibrary(), L0X.HasSession, session);
660 session.registerService(SessionModel.class, new PlatformSessionModel(sessionModel));
661 } catch (DatabaseException e) {
662 throw new PlatformException(e);
667 static class PlatformSessionModel implements SessionModel {
668 private final Resource sessionModel;
670 public PlatformSessionModel(Resource model) {
671 this.sessionModel = model;
675 public Resource getResource() {
680 public void resetDatabase(IProgressMonitor monitor) throws PlatformException {
681 // TODO: fix this to use Path APIs
682 File dbLocation = Platform.getLocation().append("db").toFile();
683 if(!dbLocation.exists()) return;
685 Driver driver = Manager.getDriver("acorn");
686 Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
688 } catch (DatabaseException e) {
689 throw new PlatformException("Failed to remove database at " + dbLocation.getAbsolutePath(), e);
691 // We have created extra files to database folder which have to be deleted also.
692 // This is an awful idea! Do not create extra files to database folder!
694 for (int i=0; i<10; ++i) {
696 FileUtils.deleteAll(dbLocation);
699 } catch (IOException e) {
700 // Assuming this has been thrown because delete file/folder failed.
705 } catch (InterruptedException e) {
706 // Ignoring interrupted exception.
710 throw new PlatformException("Failed to remove database folder at " + dbLocation.getAbsolutePath(), t);
712 public void resetWorkspace(IProgressMonitor monitor, ArrayList<String> fileFilter) throws PlatformException, IllegalStateException, IOException {
713 File file = Platform.getLocation().toFile();
714 if (null != fileFilter)
715 FileUtils.deleteAllWithFilter(file , fileFilter);
716 resetDatabase(monitor);
719 private static Path tryGetInstallLocation() {
720 Location l = Platform.getInstallLocation();
721 return l == null ? null : new File(l.getURL().getPath()).toPath();
724 private Path resolveBaselineFile() throws PlatformException {
725 String dbBaselineArchive = System.getProperty("org.simantics.db.baseline", null);
726 if (dbBaselineArchive == null)
729 Path baseline = Paths.get(dbBaselineArchive);
730 if (baseline.isAbsolute()) {
731 if (!Files.isRegularFile(baseline))
732 throw new PlatformException("Specified database baseline archive " + baseline
733 + " does not exist. Cannot initialize workspace database from baseline.");
737 // Relative path resolution order:
738 // 1. from the platform "install location"
739 // 2. from working directory
740 Path installLocation = tryGetInstallLocation();
741 if (installLocation != null) {
742 Path installedBaseline = installLocation.resolve(dbBaselineArchive);
743 if (Files.isRegularFile(installedBaseline))
744 return installedBaseline;
746 if (!Files.isRegularFile(baseline))
747 throw new PlatformException("Specified database baseline archive " + baseline
748 + " does not exist in either the install location (" + installLocation
749 + ") or the working directory (" + Paths.get(".").toAbsolutePath()
750 + "). Cannot initialize workspace database.");
754 private boolean handleBaselineDatabase() throws PlatformException {
755 Path workspaceLocation = Platform.getLocation().toFile().toPath();
756 Path baselineIndicatorFile = workspaceLocation.resolve(".baselined");
757 if (Files.isRegularFile(baselineIndicatorFile)) {
758 // This means that the workspace has already been initialized from
759 // a database baseline and further initialization is not necessary.
763 Path baseline = resolveBaselineFile();
764 if (baseline == null)
767 DatabaseBaselines.validateBaselineFile(baseline);
768 DatabaseBaselines.validateWorkspaceForBaselineInitialization(workspaceLocation);
769 DatabaseBaselines.initializeWorkspaceWithBaseline(baseline, workspaceLocation, baselineIndicatorFile);
774 * Start-up the platform. The procedure consists of 8 steps. Once everything
775 * is up and running, all fields are set property.
778 * If workspacePolicy is FixErrors, there is an attempt to fix unexpected
779 * errors. It includes installing database files, installing ontologies, and
780 * installing project features.
783 * In Simantics Workbench this is handled in
784 * <code>SimanticsWorkbenchAdvisor#openWindows()</code>.
787 * If remote server is given, simantics plaform takes connection there
788 * instead of local server at "db/".
790 * @param workspacePolicy action to take on workspace/database related
792 * @param ontologyPolicy action to take on ontology mismatch
793 * @param progressMonitor optional progress monitor
794 * @param userAgent interface for resorting to user feedback during platform
795 * startup or <code>null</code> to resort to default measures
796 * @throws PlatformException
798 public synchronized SessionContext startUp(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy,
799 OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize, PlatformUserAgent userAgent)
800 throws PlatformException
804 LOGGER.info("Beginning of SimanticsPlatform.startUp");
806 SubMonitor monitor = SubMonitor.convert(progressMonitor, 1000);
808 // For debugging on what kind of platform automatic tests are running in
809 // case there are problems.
810 if ("true".equals(System.getProperty("org.simantics.dumpBundleState")))
811 dumpPlatformBundleState();
813 // 0. Consult all startup extensions before doing anything with the workspace.
814 StartupExtensions.consultStartupExtensions();
815 LOGGER.info("Consulted platform pre-startup extensions");
817 // 0.1. Clear all temporary files
818 Simantics.clearTemporaryDirectory();
819 LOGGER.info("Cleared temporary directory");
821 // 0.2 Clear VariableRepository.repository static map which holds references to SessionImplDb
822 VariableRepository.clear();
824 // 0.2.1 Activate org.simantics.scl.osgi to prime the SCL compiler early.
825 @SuppressWarnings("unused")
826 ModuleRepository modRepo = SCLOsgi.MODULE_REPOSITORY;
828 // 0.3 Handle baseline database before opening db
829 @SuppressWarnings("unused")
830 boolean usingBaseline = handleBaselineDatabase();
832 // 1. Assert there is a database at <workspace>/db
833 SessionDescriptor sessionDescriptor = setupDatabase(databaseDriverId, monitor.newChild(200, SubMonitor.SUPPRESS_NONE), workspacePolicy, userAgent);
834 session = sessionDescriptor.getSession();
835 LOGGER.info("Database setup complete");
837 // 2. Delete all indexes if we cannot be certain they are up-to-date
838 // A full index rebuild will be done later, before project activation.
839 XSupport support = session.getService(XSupport.class);
840 if (support.rolledback()) {
842 DatabaseIndexing.deleteAllIndexes();
843 } catch (IOException e) {
844 throw new PlatformException(e);
848 // 3. Assert all graphs, and correct versions, are installed to the database
849 synchronizeOntologies(monitor.newChild(400, SubMonitor.SUPPRESS_NONE), ontologyPolicy, requireSynchronize);
851 // 4. Assert simantics.cfg exists
852 boolean installProject = assertConfiguration(monitor.newChild(25, SubMonitor.SUPPRESS_NONE),workspacePolicy);
854 // 5. Assert Project Resource is installed in the database
855 installProject = assertProject(monitor.newChild(25, SubMonitor.SUPPRESS_NONE), workspacePolicy, installProject);
857 // 6. Install all features into project, if in debug mode
858 updateInstalledGroups(monitor.newChild(25), true); //installProject);
859 LOGGER.info("Installed all features into project");
861 // 7. Assert L0.Session in database for this session
862 assertSessionModel(monitor.newChild(25, SubMonitor.SUPPRESS_NONE));
864 session.getService(XSupport.class).setServiceMode(false, false);
867 String message = "Flush query cache";
868 monitor.setTaskName(message);
869 LOGGER.info(message);
870 session.syncRequest((Write) graph -> {
871 QueryControl qc = graph.getService(QueryControl.class);
874 } catch (DatabaseException e) {
875 LOGGER.error("Flushing queries failed.", e);
877 boolean loadProject = true;
879 String message = "Open database session";
880 monitor.setTaskName(message);
881 LOGGER.info(message);
882 sessionContext = SimanticsPlatform.INSTANCE.createSessionContext(true);
883 // This must be before setSessionContext since some listeners might query this
884 sessionContext.setHint(SimanticsKeys.KEY_PROJECT, SimanticsPlatform.INSTANCE.projectResource);
886 Simantics.setSessionContext(sessionContext);
888 // 1. Put ResourceBinding that throws an exception to General Bindings
889 message = "Put ResourceBinding that throws an exception to General Bindings";
890 LOGGER.info(message);
891 simanticsBindings = new SimanticsBindings();
892 Bindings.classBindingFactory.addFactory( simanticsBindings );
894 Session session = sessionContext.getSession();
895 session.registerService(Databoard.class, Bindings.databoard);
897 // Register datatype bindings
898 message = "Register datatype bindings";
899 LOGGER.info(message);
900 Bindings.defaultBindingFactory.getRepository().put(RGB.Integer.BINDING.type(), RGB.Integer.BINDING);
901 Bindings.defaultBindingFactory.getRepository().put(Font.BINDING.type(), Font.BINDING);
903 if (support.rolledback() || sessionDescriptor.isFreshDatabase()) {
904 message = "Rebuilding all indexes";
905 LOGGER.info(message);
906 monitor.setTaskName(message);
908 session.getService(IndexedRelations.class).fullRebuild(monitor.newChild(100), session);
909 } catch (IndexException e) {
910 LOGGER.error("Failed to re-build all indexes", e);
917 message = "Load project";
918 monitor.setTaskName(message);
919 LOGGER.info(message);
920 project = Projects.loadProject(sessionContext.getSession(), SimanticsPlatform.INSTANCE.projectResource);
921 sessionContext.setHint(ProjectKeys.KEY_PROJECT, project);
923 message = "Loading projects complete";
924 LOGGER.info(message);
926 message = "Activate project";
927 monitor.setTaskName(message);
928 LOGGER.info(message);
931 LOGGER.info("Project activated");
934 } catch (DatabaseException e) {
935 LOGGER.error("Platform startup failed.", e);
936 throw new PlatformException(e);
937 } catch (ProjectException e) {
938 boolean hasStackTrace = e.getStackTrace().length > 0;
940 throw new PlatformException(e.getMessage(), hasStackTrace);
941 throw new PlatformException(e, hasStackTrace);
946 // #7650: improve shutdown robustness in all applications that use the platform
947 Runtime.getRuntime().addShutdownHook(shutdownHook);
949 // Discard database session undo history at this point to prevent
950 // the user from undoing any initialization operations performed
951 // by the platform startup.
952 SimanticsPlatform.INSTANCE.discardSessionUndoHistory();
953 LOGGER.info("Discarded session undo history");
955 return sessionContext;
959 public void registerServices(SessionContext context) {
960 new GlobalServiceInitializer().initialize(session);
961 session.registerService(MergingGraphRequestProcessor.class, new MergingGraphRequestProcessor("SessionService", session, 20));
962 session.registerService(MergingDelayedWriteProcessor.class, new MergingDelayedWriteProcessor(session, 20));
966 public SessionContext createSessionContext(boolean init) throws PlatformException {
968 // Construct and initialize SessionContext from Session.
969 SessionContext sessionContext = SessionContext.create(session, init);
970 String message = "Session context created";
971 LOGGER.info(message);
973 registerServices(sessionContext);
974 message = "Session services registered";
975 LOGGER.info(message);
977 return sessionContext;
978 } catch (DatabaseException e) {
979 throw new PlatformException(e);
984 * Perform normal shutdown for the Simantics Platform.
986 * @param progressMonitor optional progress monitor
987 * @throws PlatformException
988 * @see {@link #shutdown(IProgressMonitor, boolean)}
990 public synchronized void shutdown(IProgressMonitor progressMonitor) throws PlatformException {
991 shutdown(progressMonitor, true);
995 * Shutdown Simantics Platform.
997 * In Simantics Workbench this is handled in
998 * <code>SimanticsWorkbenchAdvisor#disconnectFromWorkspace</code>.
1000 * @param progressMonitor
1001 * optional progress monitor
1002 * @param clearTemporaryFiles
1003 * allow or prevent deletion of temporary files at the end of the
1004 * shutdown procedure
1005 * @throws PlatformException
1007 public synchronized void shutdown(IProgressMonitor progressMonitor, boolean clearTemporaryFiles) throws PlatformException
1009 SubMonitor progress = SubMonitor.convert(progressMonitor, 100);
1010 PlatformException platformException = null;
1012 progress.subTask("Close Project");
1013 if (project != null) {
1014 project.safeDispose();
1016 progress.worked(10);
1018 // NOP at the moment
1019 TimedSessionCache.close();
1021 progress.subTask("Thread pools");
1022 ThreadUtils.shutdown();
1023 ExecutorWorker.shutdown();
1027 progress.subTask("Close Database Session");
1028 if (sessionContext != null) {
1029 Session s = sessionContext.peekSession();
1031 progress.subTask("Flushing Index Caches");
1033 Simantics.flushIndexCaches(progress.newChild(20), s);
1034 } catch (Throwable t) {
1035 LOGGER.error("Failed to flush index caches.", t);
1039 progress.subTask("Close Database Session");
1040 sessionContext.safeDispose();
1041 sessionContext = null;
1042 Simantics.setSessionContext(null);
1044 if (simanticsBindings != null) {
1045 Bindings.classBindingFactory.removeFactory( simanticsBindings );
1046 simanticsBindings = null;
1049 // Make sure Simantics clipboard doesn't store unwanted session data references.
1050 Simantics.setClipboard(new SimanticsClipboardImpl());
1052 progress.worked(50);
1055 projectResource = null;
1056 currentDatabaseDriver = null;
1058 DependenciesRelation.assertFinishedTracking();
1060 } catch (Exception e) {
1061 platformException = new PlatformException("Failed to shutdown Simantics Platform", e);
1064 progress.worked(10);
1065 progress.subTask("Shutting down database");
1067 if (null != databasebManagement)
1068 databasebManagement.shutdown();
1069 } catch (Throwable t) {
1070 LOGGER.error("Database shutdown failed.", t);
1072 progress.worked(10);
1074 progress.subTask("Clear index status");
1076 // Everything ok, clear index dirty state.
1077 DatabaseIndexing.clearAllDirty();
1078 } catch (IOException e) {
1079 LOGGER.error("Problems encountered while refreshing database index states, see exception for details.", e);
1083 if (clearTemporaryFiles) {
1084 progress.subTask("Clearing Workspace Temporary Directory");
1086 Simantics.clearTemporaryDirectory();
1087 } catch (Throwable t) {
1088 LOGGER.error("Failed to clear the temporary directory.", t);
1091 progress.worked(10);
1092 if (null != platformException)
1093 throw platformException;
1095 // #7650: improve shutdown robustness in all applications that use the platform
1096 Runtime.getRuntime().removeShutdownHook(shutdownHook);
1099 // TODO: consider removing this in the future ??
1101 public void stateChanged(LifecycleState newState) {
1102 if(newState == LifecycleState.CLOSED) {
1104 if(Platform.isRunning()) {
1105 mainThread.interrupt();
1112 * @return <code>true</code> if discard was successful, <code>false</code>
1113 * if there was no session, {@link UndoRedoSupport} or
1114 * {@link UndoContext} to discard through
1116 public boolean discardSessionUndoHistory() {
1117 Session s = session;
1119 UndoRedoSupport urs = s.peekService(UndoRedoSupport.class);
1121 UndoContext uc = urs.getUndoContext(s);
1131 public void reconnect(String databaseDriverId) throws Exception {
1132 // Starts database server.
1133 if (currentDatabaseDriver != null)
1134 databaseDriverId = currentDatabaseDriver;
1135 SimanticsPlatform.INSTANCE.startUp(databaseDriverId, null, RecoveryPolicy.ThrowError, OntologyRecoveryPolicy.ThrowError, true, null);
1138 private void dumpPlatformBundleState() {
1139 BundleDescription[] bs = Platform.getPlatformAdmin().getState().getBundles();
1140 System.out.println("Total bundles: " + bs.length);
1141 for (BundleDescription b : bs) {
1142 System.out.format("%-80s @ %s\n", b.toString(), b.getLocation());
1146 private Ini loadOrCreateDatabaseIni(Path path, String databaseDriverId)
1147 throws InvalidFileFormatException, IOException
1149 File f = path.toFile();
1150 Ini dbIni = Files.isRegularFile(path) ? new Ini(f) : new Ini();
1151 String iniId = dbIni != null ? dbIni.get("driver", "id") : null;
1152 if (iniId == null) {
1153 dbIni.put("driver", "id", databaseDriverId);