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 = dbLocation();
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 = dbLocation().toFile();
683 if(!dbLocation.exists())
686 Driver driver = Manager.getDriver("acorn");
687 Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
689 } catch (DatabaseException e) {
690 throw new PlatformException("Failed to remove database at " + dbLocation.getAbsolutePath(), e);
692 // We have created extra files to database folder which have to be deleted also.
693 // This is an awful idea! Do not create extra files to database folder!
695 for (int i=0; i<10; ++i) {
697 FileUtils.deleteAll(dbLocation);
700 } catch (IOException e) {
701 // Assuming this has been thrown because delete file/folder failed.
706 } catch (InterruptedException e) {
707 // Ignoring interrupted exception.
711 throw new PlatformException("Failed to remove database folder at " + dbLocation.getAbsolutePath(), t);
713 public void resetWorkspace(IProgressMonitor monitor, ArrayList<String> fileFilter) throws PlatformException, IllegalStateException, IOException {
714 File file = Platform.getLocation().toFile();
715 if (null != fileFilter)
716 FileUtils.deleteAllWithFilter(file , fileFilter);
717 resetDatabase(monitor);
720 private static Path tryGetInstallLocation() {
721 Location l = Platform.getInstallLocation();
722 return l == null ? null : new File(l.getURL().getPath()).toPath();
725 public Path databaseExists() {
726 Path dbLocation = dbLocation();
727 if(Files.exists(dbLocation))
732 public Path dbLocation() {
733 Path workspaceLocation = Platform.getLocation().toFile().toPath();
734 return workspaceLocation.resolve("db");
738 * Start-up the platform. The procedure consists of 8 steps. Once everything
739 * is up and running, all fields are set property.
742 * If workspacePolicy is FixErrors, there is an attempt to fix unexpected
743 * errors. It includes installing database files, installing ontologies, and
744 * installing project features.
747 * In Simantics Workbench this is handled in
748 * <code>SimanticsWorkbenchAdvisor#openWindows()</code>.
751 * If remote server is given, simantics plaform takes connection there
752 * instead of local server at "db/".
754 * @param workspacePolicy action to take on workspace/database related
756 * @param ontologyPolicy action to take on ontology mismatch
757 * @param progressMonitor optional progress monitor
758 * @param userAgent interface for resorting to user feedback during platform
759 * startup or <code>null</code> to resort to default measures
760 * @throws PlatformException
762 public synchronized SessionContext startUp(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy,
763 OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize, PlatformUserAgent userAgent)
764 throws PlatformException
768 LOGGER.info("Beginning of SimanticsPlatform.startUp");
770 SubMonitor monitor = SubMonitor.convert(progressMonitor, 1000);
772 // For debugging on what kind of platform automatic tests are running in
773 // case there are problems.
774 if ("true".equals(System.getProperty("org.simantics.dumpBundleState")))
775 dumpPlatformBundleState();
777 // 0. Consult all startup extensions before doing anything with the workspace.
778 StartupExtensions.consultStartupExtensions();
779 LOGGER.info("Consulted platform pre-startup extensions");
781 // 0.1. Clear all temporary files
782 Simantics.clearTemporaryDirectory();
783 LOGGER.info("Cleared temporary directory");
785 // 0.2 Clear VariableRepository.repository static map which holds references to SessionImplDb
786 VariableRepository.clear();
788 // 0.2.1 Activate org.simantics.scl.osgi to prime the SCL compiler early.
789 @SuppressWarnings("unused")
790 ModuleRepository modRepo = SCLOsgi.MODULE_REPOSITORY;
792 // 0.3 Handle baseline database before opening db
793 @SuppressWarnings("unused")
794 boolean usingBaseline = DatabaseBaselines.handleBaselineDatabase(tryGetInstallLocation(), databaseExists() != null);
796 // 1. Assert there is a database at <workspace>/db
797 SessionDescriptor sessionDescriptor = setupDatabase(databaseDriverId, monitor.newChild(200, SubMonitor.SUPPRESS_NONE), workspacePolicy, userAgent);
798 session = sessionDescriptor.getSession();
799 LOGGER.info("Database setup complete");
801 // 2. Delete all indexes if we cannot be certain they are up-to-date
802 // A full index rebuild will be done later, before project activation.
803 XSupport support = session.getService(XSupport.class);
804 if (support.rolledback()) {
806 DatabaseIndexing.deleteAllIndexes();
807 } catch (IOException e) {
808 throw new PlatformException(e);
812 // 3. Assert all graphs, and correct versions, are installed to the database
813 synchronizeOntologies(monitor.newChild(400, SubMonitor.SUPPRESS_NONE), ontologyPolicy, requireSynchronize);
815 // 4. Assert simantics.cfg exists
816 boolean installProject = assertConfiguration(monitor.newChild(25, SubMonitor.SUPPRESS_NONE),workspacePolicy);
818 // 5. Assert Project Resource is installed in the database
819 installProject = assertProject(monitor.newChild(25, SubMonitor.SUPPRESS_NONE), workspacePolicy, installProject);
821 // 6. Install all features into project, if in debug mode
822 updateInstalledGroups(monitor.newChild(25), true); //installProject);
823 LOGGER.info("Installed all features into project");
825 // 7. Assert L0.Session in database for this session
826 assertSessionModel(monitor.newChild(25, SubMonitor.SUPPRESS_NONE));
828 session.getService(XSupport.class).setServiceMode(false, false);
831 String message = "Flush query cache";
832 monitor.setTaskName(message);
833 LOGGER.info(message);
834 session.syncRequest((Write) graph -> {
835 QueryControl qc = graph.getService(QueryControl.class);
838 } catch (DatabaseException e) {
839 LOGGER.error("Flushing queries failed.", e);
841 boolean loadProject = true;
843 String message = "Open database session";
844 monitor.setTaskName(message);
845 LOGGER.info(message);
846 sessionContext = SimanticsPlatform.INSTANCE.createSessionContext(true);
847 // This must be before setSessionContext since some listeners might query this
848 sessionContext.setHint(SimanticsKeys.KEY_PROJECT, SimanticsPlatform.INSTANCE.projectResource);
850 Simantics.setSessionContext(sessionContext);
852 // 1. Put ResourceBinding that throws an exception to General Bindings
853 message = "Put ResourceBinding that throws an exception to General Bindings";
854 LOGGER.info(message);
855 simanticsBindings = new SimanticsBindings();
856 Bindings.classBindingFactory.addFactory( simanticsBindings );
858 Session session = sessionContext.getSession();
859 session.registerService(Databoard.class, Bindings.databoard);
861 // Register datatype bindings
862 message = "Register datatype bindings";
863 LOGGER.info(message);
864 Bindings.defaultBindingFactory.getRepository().put(RGB.Integer.BINDING.type(), RGB.Integer.BINDING);
865 Bindings.defaultBindingFactory.getRepository().put(Font.BINDING.type(), Font.BINDING);
867 if (support.rolledback() || sessionDescriptor.isFreshDatabase()) {
868 message = "Rebuilding all indexes";
869 LOGGER.info(message);
870 monitor.setTaskName(message);
872 session.getService(IndexedRelations.class).fullRebuild(monitor.newChild(100), session);
873 } catch (IndexException e) {
874 LOGGER.error("Failed to re-build all indexes", e);
881 message = "Load project";
882 monitor.setTaskName(message);
883 LOGGER.info(message);
884 project = Projects.loadProject(sessionContext.getSession(), SimanticsPlatform.INSTANCE.projectResource);
885 sessionContext.setHint(ProjectKeys.KEY_PROJECT, project);
887 message = "Loading projects complete";
888 LOGGER.info(message);
890 message = "Activate project";
891 monitor.setTaskName(message);
892 LOGGER.info(message);
895 LOGGER.info("Project activated");
898 } catch (DatabaseException e) {
899 LOGGER.error("Platform startup failed.", e);
900 throw new PlatformException(e);
901 } catch (ProjectException e) {
902 boolean hasStackTrace = e.getStackTrace().length > 0;
904 throw new PlatformException(e.getMessage(), hasStackTrace);
905 throw new PlatformException(e, hasStackTrace);
910 // #7650: improve shutdown robustness in all applications that use the platform
911 Runtime.getRuntime().addShutdownHook(shutdownHook);
913 // Discard database session undo history at this point to prevent
914 // the user from undoing any initialization operations performed
915 // by the platform startup.
916 SimanticsPlatform.INSTANCE.discardSessionUndoHistory();
917 LOGGER.info("Discarded session undo history");
919 return sessionContext;
923 public void registerServices(SessionContext context) {
924 new GlobalServiceInitializer().initialize(session);
925 session.registerService(MergingGraphRequestProcessor.class, new MergingGraphRequestProcessor("SessionService", session, 20));
926 session.registerService(MergingDelayedWriteProcessor.class, new MergingDelayedWriteProcessor(session, 20));
930 public SessionContext createSessionContext(boolean init) throws PlatformException {
932 // Construct and initialize SessionContext from Session.
933 SessionContext sessionContext = SessionContext.create(session, init);
934 String message = "Session context created";
935 LOGGER.info(message);
937 registerServices(sessionContext);
938 message = "Session services registered";
939 LOGGER.info(message);
941 return sessionContext;
942 } catch (DatabaseException e) {
943 throw new PlatformException(e);
948 * Perform normal shutdown for the Simantics Platform.
950 * @param progressMonitor optional progress monitor
951 * @throws PlatformException
952 * @see {@link #shutdown(IProgressMonitor, boolean)}
954 public synchronized void shutdown(IProgressMonitor progressMonitor) throws PlatformException {
955 shutdown(progressMonitor, true);
959 * Shutdown Simantics Platform.
961 * In Simantics Workbench this is handled in
962 * <code>SimanticsWorkbenchAdvisor#disconnectFromWorkspace</code>.
964 * @param progressMonitor
965 * optional progress monitor
966 * @param clearTemporaryFiles
967 * allow or prevent deletion of temporary files at the end of the
969 * @throws PlatformException
971 public synchronized void shutdown(IProgressMonitor progressMonitor, boolean clearTemporaryFiles) throws PlatformException
973 SubMonitor progress = SubMonitor.convert(progressMonitor, 100);
974 PlatformException platformException = null;
976 progress.subTask("Close Project");
977 if (project != null) {
978 project.safeDispose();
983 TimedSessionCache.close();
985 progress.subTask("Thread pools");
986 ThreadUtils.shutdown();
987 ExecutorWorker.shutdown();
991 progress.subTask("Close Database Session");
992 if (sessionContext != null) {
993 Session s = sessionContext.peekSession();
995 progress.subTask("Flushing Index Caches");
997 Simantics.flushIndexCaches(progress.newChild(20), s);
998 } catch (Throwable t) {
999 LOGGER.error("Failed to flush index caches.", t);
1003 progress.subTask("Close Database Session");
1004 sessionContext.safeDispose();
1005 sessionContext = null;
1006 Simantics.setSessionContext(null);
1008 if (simanticsBindings != null) {
1009 Bindings.classBindingFactory.removeFactory( simanticsBindings );
1010 simanticsBindings = null;
1013 // Make sure Simantics clipboard doesn't store unwanted session data references.
1014 Simantics.setClipboard(new SimanticsClipboardImpl());
1016 progress.worked(50);
1019 projectResource = null;
1020 currentDatabaseDriver = null;
1022 DependenciesRelation.assertFinishedTracking();
1024 } catch (Exception e) {
1025 platformException = new PlatformException("Failed to shutdown Simantics Platform", e);
1028 progress.worked(10);
1029 progress.subTask("Shutting down database");
1031 if (null != databasebManagement)
1032 databasebManagement.shutdown();
1033 } catch (Throwable t) {
1034 LOGGER.error("Database shutdown failed.", t);
1036 progress.worked(10);
1038 progress.subTask("Clear index status");
1040 // Everything ok, clear index dirty state.
1041 DatabaseIndexing.clearAllDirty();
1042 } catch (IOException e) {
1043 LOGGER.error("Problems encountered while refreshing database index states, see exception for details.", e);
1047 if (clearTemporaryFiles) {
1048 progress.subTask("Clearing Workspace Temporary Directory");
1050 Simantics.clearTemporaryDirectory();
1051 } catch (Throwable t) {
1052 LOGGER.error("Failed to clear the temporary directory.", t);
1055 progress.worked(10);
1056 if (null != platformException)
1057 throw platformException;
1059 // #7650: improve shutdown robustness in all applications that use the platform
1060 Runtime.getRuntime().removeShutdownHook(shutdownHook);
1063 // TODO: consider removing this in the future ??
1065 public void stateChanged(LifecycleState newState) {
1066 if(newState == LifecycleState.CLOSED) {
1068 if(Platform.isRunning()) {
1069 mainThread.interrupt();
1076 * @return <code>true</code> if discard was successful, <code>false</code>
1077 * if there was no session, {@link UndoRedoSupport} or
1078 * {@link UndoContext} to discard through
1080 public boolean discardSessionUndoHistory() {
1081 Session s = session;
1083 UndoRedoSupport urs = s.peekService(UndoRedoSupport.class);
1085 UndoContext uc = urs.getUndoContext(s);
1095 public void reconnect(String databaseDriverId) throws Exception {
1096 // Starts database server.
1097 if (currentDatabaseDriver != null)
1098 databaseDriverId = currentDatabaseDriver;
1099 SimanticsPlatform.INSTANCE.startUp(databaseDriverId, null, RecoveryPolicy.ThrowError, OntologyRecoveryPolicy.ThrowError, true, null);
1102 private void dumpPlatformBundleState() {
1103 BundleDescription[] bs = Platform.getPlatformAdmin().getState().getBundles();
1104 System.out.println("Total bundles: " + bs.length);
1105 for (BundleDescription b : bs) {
1106 System.out.format("%-80s @ %s\n", b.toString(), b.getLocation());
1110 private Ini loadOrCreateDatabaseIni(Path path, String databaseDriverId)
1111 throws InvalidFileFormatException, IOException
1113 File f = path.toFile();
1114 Ini dbIni = Files.isRegularFile(path) ? new Ini(f) : new Ini();
1115 String iniId = dbIni != null ? dbIni.get("driver", "id") : null;
1116 if (iniId == null) {
1117 dbIni.put("driver", "id", databaseDriverId);