1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 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.Queries;
64 import org.simantics.db.common.request.WriteResultRequest;
65 import org.simantics.db.common.utils.Transaction;
66 import org.simantics.db.exception.ClusterSetExistException;
67 import org.simantics.db.exception.DatabaseException;
68 import org.simantics.db.exception.ResourceNotFoundException;
69 import org.simantics.db.indexing.DatabaseIndexing;
70 import org.simantics.db.layer0.genericrelation.DependenciesRelation;
71 import org.simantics.db.layer0.genericrelation.IndexException;
72 import org.simantics.db.layer0.genericrelation.IndexedRelations;
73 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
74 import org.simantics.db.layer0.util.SimanticsKeys;
75 import org.simantics.db.layer0.util.TGTransferableGraphSource;
76 import org.simantics.db.layer0.variable.VariableRepository;
77 import org.simantics.db.management.SessionContext;
78 import org.simantics.db.request.Read;
79 import org.simantics.db.request.Write;
80 import org.simantics.db.service.LifecycleSupport.LifecycleListener;
81 import org.simantics.db.service.LifecycleSupport.LifecycleState;
82 import org.simantics.db.service.QueryControl;
83 import org.simantics.db.service.UndoRedoSupport;
84 import org.simantics.db.service.VirtualGraphSupport;
85 import org.simantics.db.service.XSupport;
86 import org.simantics.graph.db.GraphDependencyAnalyzer;
87 import org.simantics.graph.db.GraphDependencyAnalyzer.IU;
88 import org.simantics.graph.db.GraphDependencyAnalyzer.IdentityNode;
89 import org.simantics.graph.db.IImportAdvisor;
90 import org.simantics.graph.db.ImportResult;
91 import org.simantics.graph.db.TransferableGraphs;
92 import org.simantics.graph.diff.Diff;
93 import org.simantics.graph.diff.TransferableGraphDelta1;
94 import org.simantics.internal.Activator;
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.utils.FileUtils;
114 import org.simantics.utils.datastructures.Pair;
115 import org.simantics.utils.logging.TimeLogger;
116 import org.simantics.utils.strings.EString;
117 import org.slf4j.Logger;
118 import org.slf4j.LoggerFactory;
121 * SimanticsPlatform performs procedures required in order to get simantics
122 * workbench into operational state. This consists of the following steps:
124 * <li> Asserting there is Database
126 * <li> Starting Database process
128 * <li> Opening a session to Database process
130 * <li> Asserting required ontologies or other transferable graphs are installed in the database
132 * <li> Asserting required project is installed in the database
134 * <li> Asserting Simantics Features are installed in the database
136 * <li> Asserting Simantics Features are installed to the project
138 * <li> Shutdown: Save Session, Close session, Kill Database process
142 * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
144 public class SimanticsPlatform implements LifecycleListener {
146 private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsPlatform.class);
149 * The policy is relevant when developing Simantics from Eclipse IDE.
150 * It is applied when the ontology in the database of a workspace doesn't match
151 * a newer ontology in the Eclipse workspace.
153 public static enum OntologyRecoveryPolicy { ThrowError, Merge, ReinstallDatabase }
156 * This policy dictates how the Simantics platform startup should react if
157 * the started workspace is not set up properly. The alternatives are to
158 * just throw an error and fail or to attempt all possible measures to fix
159 * the encountered problems.
161 public static enum RecoveryPolicy { ThrowError, FixError }
163 /** Singleton instance, started in SimanticsWorkbenchAdvisor */
164 public static final SimanticsPlatform INSTANCE = new SimanticsPlatform();
166 /** Set to true when the Simantics Platform is in good-and-go condition */
167 public boolean running;
169 /** ID of the database driver that the platform is currently using */
170 private String currentDatabaseDriver;
172 /** Database Session */
173 public Session session;
174 private Management databasebManagement;
176 /** Database session context */
177 public SessionContext sessionContext;
179 /** Project identifier in Database */
180 public String projectURI;
183 public String projectName;
185 /** Project resource */
186 public Resource projectResource;
188 /** Session specific bindings */
189 public SimanticsBindings simanticsBindings;
190 public SimanticsBindings simanticsBindings2;
192 public Thread mainThread;
194 private Thread shutdownHook = new Thread() {
198 LOGGER.warn("Simantics platform was not properly shut down. Executing safety shutdown hook.");
199 shutdown(null, false);
200 } catch (PlatformException e) {
201 LOGGER.error("Simantics Platform shutdown hook execution failed.", e);
202 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Simantics Platform shutdown hook execution failed.", e));
208 * The {@link IProject} activated by
209 * {@link #startUp(IProgressMonitor, RecoveryPolicy, OntologyRecoveryPolicy, ServerAddress, PlatformUserAgent)}
211 private IProject project;
216 * Create a new simantics plaform manager in uninitialized state and
217 * with default policies. <p>
219 public SimanticsPlatform() {
220 log = Platform.getLog(Activator.getBundleContext().getBundle());
221 mainThread = Thread.currentThread();
224 public String getApplicationClientId() {
225 IProduct product = Platform.getProduct();
226 if(product == null) return "noProduct";//UUID.randomUUID().toString();
227 String application = product.getApplication();
228 return application != null ? application : UUID.randomUUID().toString();
231 private SessionDescriptor setupDatabase(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, PlatformUserAgent userAgent) throws PlatformException {
232 if (progressMonitor == null)
233 progressMonitor = new NullProgressMonitor();
234 Path workspaceLocation = Platform.getLocation().toFile().toPath();
235 Path dbLocation = workspaceLocation.resolve("db");
236 Path dbIniPath = workspaceLocation.resolve("db.ini");
237 // The driver file overrides any command line arguments to prevent
238 // using the wrong driver for an existing database directory.
239 ServerManager serverManager;
241 Ini dbIni = loadOrCreateDatabaseIni(dbIniPath, databaseDriverId);
242 databaseDriverId = dbIni.get("driver", "id");
243 serverManager = ServerManagerFactory.create(databaseDriverId, dbLocation.toAbsolutePath().toString());
244 } catch (DatabaseException | IOException e) {
245 throw new PlatformException("Failed to initialize database ServerManager with driver " + databaseDriverId, e);
247 progressMonitor.beginTask("Setting up Simantics Database", 100);
248 progressMonitor.setTaskName("Asserting Database is installed.");
249 String msg = "Failed to initialize Simantics database.";
252 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Initializing database at " + dbLocation + " with driver " + databaseDriverId));
253 progressMonitor.setTaskName("Creating database at " + dbLocation);
254 databasebManagement = serverManager.getManagement(dbLocation.toFile());
255 databasebManagement.create();
256 currentDatabaseDriver = databaseDriverId;
258 return serverManager.createDatabase(dbLocation.toFile());
259 } catch (DatabaseException e) {
260 throw new PlatformException(msg, e);
261 } catch (Throwable e) {
262 throw new PlatformException(msg, e);
264 progressMonitor.worked(20);
268 public void synchronizeOntologies(IProgressMonitor progressMonitor, OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize) throws PlatformException {
270 SubMonitor monitor = SubMonitor.convert(progressMonitor, 100);
272 monitor.setTaskName("Compile dynamic ontologies");
273 PlatformUtil.compileAllDynamicOntologies();
275 String message = "Asserting all ontologies are installed";
276 LOGGER.info(message);
277 monitor.setTaskName(message);
279 DatabaseManagement mgmt = new DatabaseManagement();
280 Map<GraphBundleRef, GraphBundleEx> platformTGs = new HashMap<>();
283 // Get a list of bundles installed into the database
284 message = "find installed bundles from database";
285 monitor.subTask(message);
286 LOGGER.info(message);
287 Map<GraphBundleRef, GraphBundleEx> installedTGs = new HashMap<>();
288 for (GraphBundle b : session.syncRequest( mgmt.GraphBundleQuery )) {
289 installedTGs.put(GraphBundleRef.of(b), GraphBundleEx.extend(b));
292 if(!requireSynchronize && installedTGs.size() > 1 && !Platform.inDevelopmentMode()) return;
293 // if(installedTGs.size() > 1) return;
295 // Get a list of all bundles in the platform (Bundle Context)
296 message = "load all transferable graphs from platform";
297 monitor.subTask(message);
298 LOGGER.info(message);
299 Collection<GraphBundle> tgs = PlatformUtil.getAllGraphs();
300 System.err.println("getAllGraphs " + tgs.size());
301 message = "extend bundles to compile versions";
302 monitor.subTask(message);
303 LOGGER.info(message);
304 for (GraphBundle b : tgs) {
305 GraphBundleEx gbe = GraphBundleEx.extend(b);
307 platformTGs.put(GraphBundleRef.of(b), gbe);
310 // Compile a list of TGs that need to be installed or reinstalled in the database
311 message = "check bundle reinstallation demand";
312 monitor.subTask(message);
313 LOGGER.info(message);
314 List<GraphBundleEx> installTGs = new ArrayList<>();
315 // Create list of TGs to update, <newTg, oldTg>
316 Map<GraphBundleEx,GraphBundleEx> reinstallTGs = new TreeMap<>();
317 for (Entry<GraphBundleRef, GraphBundleEx> e : platformTGs.entrySet()) {
318 GraphBundleRef key = e.getKey();
319 GraphBundleEx platformBundle = e.getValue();
320 GraphBundleEx existingBundle = installedTGs.get(key);
322 // System.out.println("GraphBundleRef key=" + key.toString());
324 if (existingBundle == null) {
325 // Bundle did not exist in the database, put it into list of bundles to install
326 installTGs.add(platformBundle);
329 // Bundle exists in the database
330 boolean platformBundleIsNewer = existingBundle.getVersion().compareTo(platformBundle.getVersion())<0;
331 if (!platformBundleIsNewer)
333 // Check hash of transferable graph to know whether to update or not.
334 if (platformBundle.getHashcode() == existingBundle.getHashcode())
336 //System.out.println("Ontology hashcodes do not match: platform bundle="
337 // + platformBundle.getVersionedId() + ", hash=" + platformBundle.getHashcode()
338 // + "; existing bundle=" + existingBundle.getVersionedId() + ", hash=" + existingBundle.getHashcode());
339 reinstallTGs.put(platformBundle, existingBundle);
343 // Database is missing graphs
344 if (!installTGs.isEmpty() || !reinstallTGs.isEmpty()) {
345 session.getService(XSupport.class).setServiceMode(true, true);
348 if (ontologyPolicy == OntologyRecoveryPolicy.ThrowError) {
349 StringBuilder sb = new StringBuilder("The following graphs are not installed in the database: ");
350 if (!installTGs.isEmpty()) {
352 for (GraphBundleEx e : installTGs) {
353 if (i>0) sb.append(", ");
355 sb.append(e.toString());
357 sb.append(" is missing from the database.\n");
359 if (!reinstallTGs.isEmpty()) {
361 for (Entry<GraphBundleEx, GraphBundleEx> e : reinstallTGs.entrySet()) {
362 if (i>0) sb.append(", ");
364 sb.append(e.getKey().toString());
366 sb.append(" Database/Platform Bundle version mismatch.\n");
368 sb.append("Hint: Use -fixErrors to install the graphs.");
369 throw new PlatformException(sb.toString());
371 // Reinstall database
372 if (ontologyPolicy == OntologyRecoveryPolicy.ReinstallDatabase) {
373 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Reinstalling the database."));
382 throw new PlatformException("Reinstalling Database, NOT IMPLEMENTED");
385 if (ontologyPolicy == OntologyRecoveryPolicy.Merge) {
386 message = "Merging ontology changes";
387 monitor.subTask(message);
388 LOGGER.info(message);
389 // Sort missing TGs into install order
390 GraphDependencyAnalyzer<GraphBundle> analyzer = new GraphDependencyAnalyzer<GraphBundle>();
391 for(GraphBundle tg : installTGs) analyzer.addGraph(tg, tg.getGraph());
392 for(GraphBundle tg : reinstallTGs.keySet()) analyzer.addGraph(tg, tg.getGraph());
393 if(!analyzer.analyzeDependency()) {
394 Collection<Pair<GraphBundle, GraphBundle>> problems = analyzer.getConflicts();
395 StringBuilder sb = new StringBuilder();
396 for (Pair<GraphBundle, GraphBundle> problem : problems) {
397 sb.append("Conflict with "+problem.first+" and "+problem.second+".\n");
399 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 List<GraphBundle> sortedBundles = analyzer.getSortedGraphs();
414 if(!sortedBundles.isEmpty()) {
416 session.syncRequest((Write) graph -> {
418 graph.newClusterSet(graph.getRootLibrary());
419 } catch (ClusterSetExistException e) {
420 // Cluster set exist already, no problem.
422 graph.setClusterSet4NewResource(graph.getRootLibrary());
423 graph.flushCluster();
426 boolean mergedOntologies = false;
429 for(final GraphBundle tg : sortedBundles) {
431 final IImportAdvisor advisor = new OntologyImportAdvisor(tg, mgmt);
432 final GraphBundle oldTG = reinstallTGs.get(tg);
434 boolean createImmutable = tg.getImmutable();
438 session.getService(XSupport.class).setServiceMode(true, createImmutable);
441 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Installing "+tg.toString()+" - "+tg.getName()));
442 ImportResult result = TransferableGraphs.importGraph1(session, new TGTransferableGraphSource(tg.getGraph()), advisor, null);
443 if (!result.missingExternals.isEmpty()) {
444 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import of " + tg.toString() + " was missing the following external entities:\n" + EString.implode(result.missingExternals)));
451 startTransaction(session, false);
452 TransferableGraphDelta1 delta = new Diff(oldTG.getGraph(), tg.getGraph()).diff();
453 final long[] oldResources = oldTG.getResourceArray();
454 boolean changes = TransferableGraphs.hasChanges(readGraph(), oldResources, delta);
457 //log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Nothing to merge for "+tg.toString()));
461 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Merging new version of "+tg.toString()));
463 startTransaction(session, true);
467 long[] resourceArray = TransferableGraphs.applyDelta(writeGraph(), oldResources, delta);
468 tg.setResourceArray(resourceArray);
469 mgmt.setGraphBundleEntry(tg);
471 mergedOntologies = true;
472 } catch (Throwable t) {
473 throw new PlatformException(t);
480 session.syncRequest((Write) graph -> {
481 graph.setClusterSet4NewResource(graph.getRootLibrary());
482 graph.flushCluster();
485 if (mergedOntologies)
486 DatabaseIndexing.deleteAllIndexes();
489 session.getService(XSupport.class).setServiceMode(false, false);
492 } catch (IOException e) {
493 throw new PlatformException(e);
494 } catch (DatabaseException e) {
495 throw new PlatformException(e);
500 public boolean assertConfiguration(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy) throws PlatformException {
502 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
504 File workspaceLocation = Platform.getLocation().toFile();
506 boolean installProject = false;
507 progressMonitor.setTaskName("Asserting simantics.cfg is installed");
509 File propertyFile = new File(workspaceLocation, "simantics.cfg");
510 Properties properties;
512 properties = WorkspaceUtil.readProperties(propertyFile);
513 } catch (IOException e) {
514 if (workspacePolicy == RecoveryPolicy.ThrowError) throw new PlatformException("Could not load "+propertyFile);
516 // Create a project and write Property file
517 properties = new Properties();
518 properties.setProperty("project_uri", "http://Projects/Development%20Project");
519 properties.setProperty("project_name", "Development Project");
520 WorkspaceUtil.writeProperties(propertyFile, properties);
521 installProject |= true;
523 projectURI = properties.getProperty("project_uri");
524 projectName = properties.getProperty("project_name");
525 progressMonitor.worked(10);
526 } catch (IOException e) {
527 throw new PlatformException(e);
530 return installProject;
534 public boolean assertProject(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, boolean installProject) throws PlatformException {
536 SubMonitor monitor = SubMonitor.convert(progressMonitor, 10);
538 final DatabaseManagement mgmt = new DatabaseManagement();
540 monitor.setTaskName("Asserting project resource exists in the database");
542 projectResource = session.syncRequest( Queries.resource( projectURI ) );
543 } catch (ResourceNotFoundException nfe) {
544 // Project was not found
545 if (workspacePolicy == RecoveryPolicy.ThrowError)
546 throw new PlatformException("Project Resource "+projectURI+" is not found in the database.");
547 // Create empty project with no features
549 Transaction.startTransaction(session, true);
551 // The project needs to be created mutable.
552 session.getService(XSupport.class).setServiceMode(true, false);
554 ArrayList<String> empty = new ArrayList<String>();
555 projectResource = mgmt.createProject(projectName, empty);
556 installProject |= true;
558 session.getService(XSupport.class).setServiceMode(false, false);
559 Transaction.commit();
561 Transaction.endTransaction();
563 //session.getService( LifecycleSupport.class ).save();
564 } catch (DatabaseException e) {
565 throw new PlatformException("Failed to create "+projectURI, e);
567 } catch (DatabaseException e) {
568 throw new PlatformException("Failed to create "+projectURI, e);
572 return installProject;
576 public void updateInstalledGroups(IProgressMonitor progressMonitor, boolean installProject) throws PlatformException {
580 // Attach all feature groups available in platform to created project
581 progressMonitor.setTaskName("Install all features");
582 Set<GroupReference> publishedFeatureGroups = ProjectFeatures.getInstallGroupsOfPublishedFeatures();
583 Collection<GroupReference> groupsWithoutVersion = GroupReference.stripVersions(publishedFeatureGroups);
588 Projects.setProjectInstalledGroups(graph, projectResource, groupsWithoutVersion));
589 } catch (DatabaseException ae) {
590 throw new PlatformException("Failed to install features", ae);
592 progressMonitor.worked(10);
597 public void assertSessionModel(IProgressMonitor progressMonitor) throws PlatformException {
599 Properties properties = session.getService(Properties.class);
600 final String clientId = properties.getProperty("clientId");
604 // Currently this needs to be done before data becomes available
605 VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
606 VirtualGraph activations = support.getWorkspacePersistent("activations");
608 Resource sessionModel = session.syncRequest(new Read<Resource>() {
611 public Resource perform(ReadGraph graph) throws DatabaseException {
613 Layer0X L0X = Layer0X.getInstance(graph);
614 for(Resource sessionModel : graph.syncRequest(new ObjectsWithType(graph.getRootLibrary(), L0X.HasSession, L0X.Session))) {
615 String id = graph.getPossibleRelatedValue(sessionModel, L0X.Session_HasClientId);
616 if(id != null && id.equals(clientId)) return sessionModel;
624 if(sessionModel == null) {
626 sessionModel = session.syncRequest(new WriteResultRequest<Resource>(activations) {
629 public Resource perform(WriteGraph graph) throws DatabaseException {
630 Layer0 L0 = Layer0.getInstance(graph);
631 Layer0X L0X = Layer0X.getInstance(graph);
632 Resource session = graph.newResource();
633 graph.claim(session, L0.InstanceOf, null, L0X.Session);
634 graph.claim(session, L0X.Session_HasUser, null, graph.getResource("http://Users/AdminUser"));
635 graph.addLiteral(session, L0X.Session_HasClientId, L0X.Session_HasClientId_Inverse, clientId, Bindings.STRING);
636 graph.claim(graph.getRootLibrary(), L0X.HasSession, session);
643 session.registerService(SessionModel.class, new PlatformSessionModel(sessionModel));
644 } catch (DatabaseException e) {
645 throw new PlatformException(e);
650 static class PlatformSessionModel implements SessionModel {
651 private final Resource sessionModel;
653 public PlatformSessionModel(Resource model) {
654 this.sessionModel = model;
658 public Resource getResource() {
663 public void resetDatabase(IProgressMonitor monitor) throws PlatformException {
664 File dbLocation = Platform.getLocation().append("db").toFile();
665 if(!dbLocation.exists()) return;
667 Driver driver = Manager.getDriver("procore");
668 Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
670 } catch (DatabaseException e) {
671 throw new PlatformException("Failed to remove database at " + dbLocation.getAbsolutePath(), e);
673 // We have created extra files to database folder which have to be deleted also.
674 // This is an awful idea! Do not create extra files to database folder!
676 for (int i=0; i<10; ++i) {
678 FileUtils.deleteAll(dbLocation);
681 } catch (IOException e) {
682 // Assuming this has been thrown because delete file/folder failed.
687 } catch (InterruptedException e) {
688 // Ignoring interrupted exception.
692 throw new PlatformException("Failed to remove database folder at " + dbLocation.getAbsolutePath(), t);
694 public void resetWorkspace(IProgressMonitor monitor, ArrayList<String> fileFilter) throws PlatformException, IllegalStateException, IOException {
695 File file = Platform.getLocation().toFile();
696 if (null != fileFilter)
697 FileUtils.deleteAllWithFilter(file , fileFilter);
698 resetDatabase(monitor);
701 private static Path tryGetInstallLocation() {
702 Location l = Platform.getInstallLocation();
703 return l == null ? null : new File(l.getURL().getPath()).toPath();
706 private Path resolveBaselineFile() throws PlatformException {
707 String dbBaselineArchive = System.getProperty("org.simantics.db.baseline", null);
708 if (dbBaselineArchive == null)
711 Path baseline = Paths.get(dbBaselineArchive);
712 if (baseline.isAbsolute()) {
713 if (!Files.isRegularFile(baseline))
714 throw new PlatformException("Specified database baseline archive " + baseline
715 + " does not exist. Cannot initialize workspace database from baseline.");
719 // Relative path resolution order:
720 // 1. from the platform "install location"
721 // 2. from working directory
722 Path installLocation = tryGetInstallLocation();
723 if (installLocation != null) {
724 Path installedBaseline = installLocation.resolve(dbBaselineArchive);
725 if (Files.isRegularFile(installedBaseline))
726 return installedBaseline;
728 if (!Files.isRegularFile(baseline))
729 throw new PlatformException("Specified database baseline archive " + baseline
730 + " does not exist in either the install location (" + installLocation
731 + ") or the working directory (" + Paths.get(".").toAbsolutePath()
732 + "). Cannot initialize workspace database.");
736 private boolean handleBaselineDatabase() throws PlatformException {
737 Path workspaceLocation = Platform.getLocation().toFile().toPath();
738 Path baselineIndicatorFile = workspaceLocation.resolve(".baselined");
739 if (Files.isRegularFile(baselineIndicatorFile)) {
740 // This means that the workspace has already been initialized from
741 // a database baseline and further initialization is not necessary.
745 Path baseline = resolveBaselineFile();
746 if (baseline == null)
749 DatabaseBaselines.validateBaselineFile(baseline);
750 DatabaseBaselines.validateWorkspaceForBaselineInitialization(workspaceLocation);
751 DatabaseBaselines.initializeWorkspaceWithBaseline(baseline, workspaceLocation, baselineIndicatorFile);
756 * Start-up the platform. The procedure consists of 8 steps. Once everything
757 * is up and running, all fields are set property.
760 * If workspacePolicy is FixErrors, there is an attempt to fix unexpected
761 * errors. It includes installing database files, installing ontologies, and
762 * installing project features.
765 * In Simantics Workbench this is handled in
766 * <code>SimanticsWorkbenchAdvisor#openWindows()</code>.
769 * If remote server is given, simantics plaform takes connection there
770 * instead of local server at "db/".
772 * @param workspacePolicy action to take on workspace/database related
774 * @param ontologyPolicy action to take on ontology mismatch
775 * @param progressMonitor optional progress monitor
776 * @param userAgent interface for resorting to user feedback during platform
777 * startup or <code>null</code> to resort to default measures
778 * @throws PlatformException
780 public synchronized SessionContext startUp(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy,
781 OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize, PlatformUserAgent userAgent)
782 throws PlatformException
786 TimeLogger.log("Beginning of SimanticsPlatform.startUp");
788 LOGGER.info("Beginning of SimanticsPlatform.startUp");
790 SubMonitor monitor = SubMonitor.convert(progressMonitor, 1000);
792 // For debugging on what kind of platform automatic tests are running in
793 // case there are problems.
794 if ("true".equals(System.getProperty("org.simantics.dumpBundleState")))
795 dumpPlatformBundleState();
797 // 0. Consult all startup extensions before doing anything with the workspace.
798 StartupExtensions.consultStartupExtensions();
799 TimeLogger.log("Consulted platform pre-startup extensions");
801 // 0.1. Clear all temporary files
802 Simantics.clearTemporaryDirectory();
803 TimeLogger.log("Cleared temporary directory");
805 // 0.2 Clear VariableRepository.repository static map which holds references to SessionImplDb
806 VariableRepository.clear();
808 // 0.3 Handle baseline database before opening db
809 @SuppressWarnings("unused")
810 boolean usingBaseline = handleBaselineDatabase();
812 // 1. Assert there is a database at <workspace>/db
813 SessionDescriptor sessionDescriptor = setupDatabase(databaseDriverId, monitor.newChild(200, SubMonitor.SUPPRESS_NONE), workspacePolicy, userAgent);
814 session = sessionDescriptor.getSession();
815 TimeLogger.log("Database setup complete");
817 // 2. Delete all indexes if we cannot be certain they are up-to-date
818 // A full index rebuild will be done later, before project activation.
819 XSupport support = session.getService(XSupport.class);
820 if (support.rolledback()) {
822 DatabaseIndexing.deleteAllIndexes();
823 } catch (IOException e) {
824 throw new PlatformException(e);
828 // 3. Assert all graphs, and correct versions, are installed to the database
829 synchronizeOntologies(monitor.newChild(400, SubMonitor.SUPPRESS_NONE), ontologyPolicy, requireSynchronize);
830 TimeLogger.log("Synchronized ontologies");
832 // 4. Assert simantics.cfg exists
833 boolean installProject = assertConfiguration(monitor.newChild(25, SubMonitor.SUPPRESS_NONE),workspacePolicy);
835 // 5. Assert Project Resource is installed in the database
836 installProject = assertProject(monitor.newChild(25, SubMonitor.SUPPRESS_NONE), workspacePolicy, installProject);
838 // 6. Install all features into project, if in debug mode
839 updateInstalledGroups(monitor.newChild(25), true); //installProject);
840 TimeLogger.log("Installed all features into project");
842 // 7. Assert L0.Session in database for this session
843 assertSessionModel(monitor.newChild(25, SubMonitor.SUPPRESS_NONE));
845 session.getService(XSupport.class).setServiceMode(false, false);
848 monitor.setTaskName("Flush query cache");
849 session.syncRequest((Write) graph -> {
850 QueryControl qc = graph.getService(QueryControl.class);
853 TimeLogger.log("Flushed queries");
854 } catch (DatabaseException e) {
855 LOGGER.error("Flushing queries failed.", e);
857 boolean loadProject = true;
860 monitor.setTaskName("Open database session");
861 sessionContext = SimanticsPlatform.INSTANCE.createSessionContext(true);
862 // This must be before setSessionContext since some listeners might query this
863 sessionContext.setHint(SimanticsKeys.KEY_PROJECT, SimanticsPlatform.INSTANCE.projectResource);
865 Simantics.setSessionContext(sessionContext);
867 // 1. Put ResourceBinding that throws an exception to General Bindings
868 simanticsBindings = new SimanticsBindings( null );
869 Bindings.classBindingFactory.addFactory( simanticsBindings );
872 // 2. Create session-specific second Binding context (Databoard) and
873 // put that to Session as a service
874 Session session = sessionContext.getSession();
875 Databoard sessionDataboard = new Databoard();
876 session.registerService(Databoard.class, sessionDataboard);
877 simanticsBindings2 = new SimanticsBindings( session );
878 sessionDataboard.classBindingFactory.addFactory( simanticsBindings2 );
880 // Register datatype bindings
881 Bindings.defaultBindingFactory.getRepository().put(RGB.Integer.BINDING.type(), RGB.Integer.BINDING);
882 Bindings.defaultBindingFactory.getRepository().put(Font.BINDING.type(), Font.BINDING);
884 if (support.rolledback() || sessionDescriptor.isFreshDatabase()) {
885 monitor.setTaskName("Rebuilding all indexes");
887 session.getService(IndexedRelations.class).fullRebuild(monitor.newChild(100), session);
888 } catch (IndexException e) {
889 LOGGER.error("Failed to re-build all indexes", e);
896 TimeLogger.log("Load project");
897 monitor.setTaskName("Load project");
898 project = Projects.loadProject(sessionContext.getSession(), SimanticsPlatform.INSTANCE.projectResource);
899 sessionContext.setHint(ProjectKeys.KEY_PROJECT, project);
901 TimeLogger.log("Loading projects complete");
903 monitor.setTaskName("Activate project");
906 TimeLogger.log("Project activated");
909 } catch (DatabaseException e) {
910 LOGGER.error("Platform startup failed.", e);
911 throw new PlatformException(e);
912 } catch (ProjectException e) {
913 boolean hasStackTrace = e.getStackTrace().length > 0;
915 throw new PlatformException(e.getMessage(), hasStackTrace);
916 throw new PlatformException(e, hasStackTrace);
921 // #7650: improve shutdown robustness in all applications that use the platform
922 Runtime.getRuntime().addShutdownHook(shutdownHook);
924 // Discard database session undo history at this point to prevent
925 // the user from undoing any initialization operations performed
926 // by the platform startup.
927 SimanticsPlatform.INSTANCE.discardSessionUndoHistory();
928 TimeLogger.log("Discarded session undo history");
930 return sessionContext;
934 public SessionContext createSessionContext(boolean init) throws PlatformException {
936 // Construct and initialize SessionContext from Session.
937 SessionContext sessionContext = SessionContext.create(session, init);
938 TimeLogger.log("Session context created");
940 sessionContext.registerServices();
941 TimeLogger.log("Session services registered");
943 return sessionContext;
944 } catch (DatabaseException e) {
945 throw new PlatformException(e);
950 * Perform normal shutdown for the Simantics Platform.
952 * @param progressMonitor optional progress monitor
953 * @throws PlatformException
954 * @see {@link #shutdown(IProgressMonitor, boolean)}
956 public synchronized void shutdown(IProgressMonitor progressMonitor) throws PlatformException {
957 shutdown(progressMonitor, true);
961 * Shutdown Simantics Platform.
963 * In Simantics Workbench this is handled in
964 * <code>SimanticsWorkbenchAdvisor#disconnectFromWorkspace</code>.
966 * @param progressMonitor
967 * optional progress monitor
968 * @param clearTemporaryFiles
969 * allow or prevent deletion of temporary files at the end of the
971 * @throws PlatformException
973 public synchronized void shutdown(IProgressMonitor progressMonitor, boolean clearTemporaryFiles) throws PlatformException
975 SubMonitor progress = SubMonitor.convert(progressMonitor, 100);
976 PlatformException platformException = null;
978 progress.subTask("Close Project");
979 if (project != null) {
980 project.safeDispose();
985 progress.subTask("Close Database Session");
986 Databoard databoard = null;
987 if (sessionContext != null) {
988 Session s = sessionContext.peekSession();
990 databoard = s.peekService(Databoard.class);
992 progress.subTask("Flushing Index Caches");
994 Simantics.flushIndexCaches(progress.newChild(20), s);
995 } catch (Throwable t) {
996 LOGGER.error("Failed to flush index caches.", t);
1000 progress.subTask("Close Database Session");
1001 sessionContext.safeDispose();
1002 sessionContext = null;
1003 Simantics.setSessionContext(null);
1005 if (simanticsBindings != null) {
1006 Bindings.classBindingFactory.removeFactory( simanticsBindings );
1007 simanticsBindings = null;
1009 if (databoard != null) {
1010 if (simanticsBindings2 != null) {
1011 databoard.classBindingFactory.removeFactory( simanticsBindings2 );
1012 simanticsBindings2 = null;
1017 // Make sure Simantics clipboard doesn't store unwanted session data references.
1018 Simantics.setClipboard(new SimanticsClipboardImpl());
1020 progress.worked(30);
1023 projectResource = null;
1024 currentDatabaseDriver = null;
1026 DependenciesRelation.assertFinishedTracking();
1028 } catch (Exception e) {
1029 platformException = new PlatformException("Failed to shutdown Simantics Platform", e);
1032 progress.worked(10);
1033 progress.subTask("Shutting down database");
1035 if (null != databasebManagement)
1036 databasebManagement.shutdown();
1037 } catch (Throwable t) {
1038 LOGGER.error("Database shutdown failed.", t);
1040 progress.worked(10);
1042 if (clearTemporaryFiles) {
1043 progress.subTask("Clearing Workspace Temporary Directory");
1045 Simantics.clearTemporaryDirectory();
1046 } catch (Throwable t) {
1047 LOGGER.error("Failed to clear the temporary directory.", t);
1050 progress.worked(10);
1051 if (null != platformException)
1052 throw platformException;
1054 // #7650: improve shutdown robustness in all applications that use the platform
1055 Runtime.getRuntime().removeShutdownHook(shutdownHook);
1058 // TODO: consider removing this in the future ??
1060 public void stateChanged(LifecycleState newState) {
1061 if(newState == LifecycleState.CLOSED) {
1063 if(Platform.isRunning()) {
1064 mainThread.interrupt();
1071 * @return <code>true</code> if discard was successful, <code>false</code>
1072 * if there was no session, {@link UndoRedoSupport} or
1073 * {@link UndoContext} to discard through
1075 public boolean discardSessionUndoHistory() {
1076 Session s = session;
1078 UndoRedoSupport urs = s.peekService(UndoRedoSupport.class);
1080 UndoContext uc = urs.getUndoContext(s);
1090 public void reconnect(String databaseDriverId) throws Exception {
1091 // Starts database server.
1092 if (currentDatabaseDriver != null)
1093 databaseDriverId = currentDatabaseDriver;
1094 SimanticsPlatform.INSTANCE.startUp(databaseDriverId, null, RecoveryPolicy.ThrowError, OntologyRecoveryPolicy.ThrowError, true, null);
1097 private void dumpPlatformBundleState() {
1098 BundleDescription[] bs = Platform.getPlatformAdmin().getState().getBundles();
1099 System.out.println("Total bundles: " + bs.length);
1100 for (BundleDescription b : bs) {
1101 System.out.format("%-80s @ %s\n", b.toString(), b.getLocation());
1105 private Ini loadOrCreateDatabaseIni(Path path, String databaseDriverId)
1106 throws InvalidFileFormatException, IOException
1108 File f = path.toFile();
1109 Ini dbIni = Files.isRegularFile(path) ? new Ini(f) : new Ini();
1110 String iniId = dbIni != null ? dbIni.get("driver", "id") : null;
1111 if (iniId == null) {
1112 dbIni.put("driver", "id", databaseDriverId);