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.time.Instant;
26 import java.time.ZoneId;
27 import java.time.format.DateTimeFormatter;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Properties;
36 import java.util.TreeMap;
37 import java.util.UUID;
38 import java.util.zip.ZipEntry;
39 import java.util.zip.ZipFile;
41 import org.eclipse.core.runtime.ILog;
42 import org.eclipse.core.runtime.IProduct;
43 import org.eclipse.core.runtime.IProgressMonitor;
44 import org.eclipse.core.runtime.IStatus;
45 import org.eclipse.core.runtime.NullProgressMonitor;
46 import org.eclipse.core.runtime.Platform;
47 import org.eclipse.core.runtime.Status;
48 import org.eclipse.core.runtime.SubMonitor;
49 import org.eclipse.osgi.service.resolver.BundleDescription;
51 import org.ini4j.InvalidFileFormatException;
52 import org.simantics.databoard.Bindings;
53 import org.simantics.databoard.Databoard;
54 import org.simantics.datatypes.literal.Font;
55 import org.simantics.datatypes.literal.RGB;
56 import org.simantics.db.Driver;
57 import org.simantics.db.Driver.Management;
58 import org.simantics.db.Manager;
59 import org.simantics.db.ReadGraph;
60 import org.simantics.db.Resource;
61 import org.simantics.db.Session;
62 import org.simantics.db.SessionModel;
63 import org.simantics.db.UndoContext;
64 import org.simantics.db.VirtualGraph;
65 import org.simantics.db.WriteGraph;
66 import org.simantics.db.common.request.ObjectsWithType;
67 import org.simantics.db.common.request.Queries;
68 import org.simantics.db.common.request.WriteResultRequest;
69 import org.simantics.db.common.utils.Transaction;
70 import org.simantics.db.exception.ClusterSetExistException;
71 import org.simantics.db.exception.DatabaseException;
72 import org.simantics.db.exception.ResourceNotFoundException;
73 import org.simantics.db.indexing.DatabaseIndexing;
74 import org.simantics.db.layer0.genericrelation.DependenciesRelation;
75 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
76 import org.simantics.db.layer0.util.SimanticsKeys;
77 import org.simantics.db.layer0.util.TGTransferableGraphSource;
78 import org.simantics.db.layer0.variable.VariableRepository;
79 import org.simantics.db.management.SessionContext;
80 import org.simantics.db.request.Read;
81 import org.simantics.db.request.Write;
82 import org.simantics.db.service.LifecycleSupport.LifecycleListener;
83 import org.simantics.db.service.LifecycleSupport.LifecycleState;
84 import org.simantics.db.service.QueryControl;
85 import org.simantics.db.service.UndoRedoSupport;
86 import org.simantics.db.service.VirtualGraphSupport;
87 import org.simantics.db.service.XSupport;
88 import org.simantics.graph.db.GraphDependencyAnalyzer;
89 import org.simantics.graph.db.GraphDependencyAnalyzer.IU;
90 import org.simantics.graph.db.GraphDependencyAnalyzer.IdentityNode;
91 import org.simantics.graph.db.IImportAdvisor;
92 import org.simantics.graph.db.ImportResult;
93 import org.simantics.graph.db.TransferableGraphs;
94 import org.simantics.graph.diff.Diff;
95 import org.simantics.graph.diff.TransferableGraphDelta1;
96 import org.simantics.internal.Activator;
97 import org.simantics.internal.startup.StartupExtensions;
98 import org.simantics.layer0.Layer0;
99 import org.simantics.operation.Layer0X;
100 import org.simantics.project.IProject;
101 import org.simantics.project.ProjectFeatures;
102 import org.simantics.project.ProjectKeys;
103 import org.simantics.project.Projects;
104 import org.simantics.project.exception.ProjectException;
105 import org.simantics.project.features.registry.GroupReference;
106 import org.simantics.project.management.DatabaseManagement;
107 import org.simantics.project.management.GraphBundle;
108 import org.simantics.project.management.GraphBundleEx;
109 import org.simantics.project.management.GraphBundleRef;
110 import org.simantics.project.management.PlatformUtil;
111 import org.simantics.project.management.ServerManager;
112 import org.simantics.project.management.ServerManagerFactory;
113 import org.simantics.project.management.WorkspaceUtil;
114 import org.simantics.utils.FileUtils;
115 import org.simantics.utils.datastructures.Pair;
116 import org.simantics.utils.logging.TimeLogger;
117 import org.simantics.utils.strings.EString;
118 import org.slf4j.Logger;
119 import org.slf4j.LoggerFactory;
122 * SimanticsPlatform performs procedures required in order to get simantics
123 * workbench into operational state. This consists of the following steps:
125 * <li> Asserting there is Database
127 * <li> Starting Database process
129 * <li> Opening a session to Database process
131 * <li> Asserting required ontologies or other transferable graphs are installed in the database
133 * <li> Asserting required project is installed in the database
135 * <li> Asserting Simantics Features are installed in the database
137 * <li> Asserting Simantics Features are installed to the project
139 * <li> Shutdown: Save Session, Close session, Kill Database process
143 * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
145 public class SimanticsPlatform implements LifecycleListener {
147 private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsPlatform.class);
150 * The policy is relevant when developing Simantics from Eclipse IDE.
151 * It is applied when the ontology in the database of a workspace doesn't match
152 * a newer ontology in the Eclipse workspace.
154 public static enum OntologyRecoveryPolicy { ThrowError, Merge, ReinstallDatabase }
157 * This policy dictates how the Simantics platform startup should react if
158 * the started workspace is not set up properly. The alternatives are to
159 * just throw an error and fail or to attempt all possible measures to fix
160 * the encountered problems.
162 public static enum RecoveryPolicy { ThrowError, FixError }
164 /** Singleton instance, started in SimanticsWorkbenchAdvisor */
165 public static final SimanticsPlatform INSTANCE = new SimanticsPlatform();
167 /** Set to true when the Simantics Platform is in good-and-go condition */
168 public boolean running;
170 /** ID of the database driver that the platform is currently using */
171 private String currentDatabaseDriver;
173 /** Database Session */
174 public Session session;
175 private Management databasebManagement;
177 /** Database session context */
178 public SessionContext sessionContext;
180 /** Project identifier in Database */
181 public String projectURI;
184 public String projectName;
186 /** Project resource */
187 public Resource projectResource;
189 /** Session specific bindings */
190 public SimanticsBindings simanticsBindings;
191 public SimanticsBindings simanticsBindings2;
193 public Thread mainThread;
195 private Thread shutdownHook = new Thread() {
199 LOGGER.warn("Simantics platform was not properly shut down. Executing safety shutdown hook.");
200 shutdown(null, false);
201 } catch (PlatformException e) {
202 LOGGER.error("Simantics Platform shutdown hook execution failed.", e);
203 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Simantics Platform shutdown hook execution failed.", e));
209 * The {@link IProject} activated by
210 * {@link #startUp(IProgressMonitor, RecoveryPolicy, OntologyRecoveryPolicy, ServerAddress, PlatformUserAgent)}
212 private IProject project;
217 * Create a new simantics plaform manager in uninitialized state and
218 * with default policies. <p>
220 public SimanticsPlatform() {
221 log = Platform.getLog(Activator.getBundleContext().getBundle());
222 mainThread = Thread.currentThread();
225 public String getApplicationClientId() {
226 IProduct product = Platform.getProduct();
227 if(product == null) return "noProduct";//UUID.randomUUID().toString();
228 String application = product.getApplication();
229 return application != null ? application : UUID.randomUUID().toString();
232 private Session setupDatabase(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, PlatformUserAgent userAgent) throws PlatformException {
233 if (progressMonitor == null)
234 progressMonitor = new NullProgressMonitor();
235 Path workspaceLocation = Platform.getLocation().toFile().toPath();
236 Path dbLocation = workspaceLocation.resolve("db");
237 Path dbIniPath = workspaceLocation.resolve("db.ini");
238 // The driver file overrides any command line arguments to prevent
239 // using the wrong driver for an existing database directory.
240 ServerManager serverManager;
242 Ini dbIni = loadOrCreateDatabaseIni(dbIniPath, databaseDriverId);
243 databaseDriverId = dbIni.get("driver", "id");
244 serverManager = ServerManagerFactory.create(databaseDriverId, dbLocation.toAbsolutePath().toString());
245 } catch (DatabaseException | IOException e) {
246 throw new PlatformException("Failed to initialize database ServerManager with driver " + databaseDriverId, e);
248 progressMonitor.beginTask("Setting up Simantics Database", 100);
249 progressMonitor.setTaskName("Asserting Database is installed.");
250 String msg = "Failed to initialize Simantics database.";
253 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Initializing database at " + dbLocation + " with driver " + databaseDriverId));
254 progressMonitor.setTaskName("Creating database at " + dbLocation);
255 databasebManagement = serverManager.getManagement(dbLocation.toFile());
256 databasebManagement.create();
257 currentDatabaseDriver = databaseDriverId;
259 return serverManager.createDatabase(dbLocation.toFile());
260 } catch (DatabaseException e) {
261 throw new PlatformException(msg, e);
262 } catch (Throwable e) {
263 throw new PlatformException(msg, e);
265 progressMonitor.worked(20);
269 public void synchronizeOntologies(IProgressMonitor progressMonitor, OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize) throws PlatformException {
271 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
273 final DatabaseManagement mgmt = new DatabaseManagement();
275 PlatformUtil.compileAllDynamicOntologies();
277 progressMonitor.setTaskName("Asserting all ontologies are installed");
278 final Map<GraphBundleRef, GraphBundleEx> platformTGs = new HashMap<GraphBundleRef, GraphBundleEx>();
281 // Get a list of bundles installed into the database
282 progressMonitor.subTask("find installed bundles from database");
283 Map<GraphBundleRef, GraphBundleEx> installedTGs = new HashMap<GraphBundleRef, GraphBundleEx>();
284 for (GraphBundle b : session.syncRequest( mgmt.GraphBundleQuery )) {
285 installedTGs.put(GraphBundleRef.of(b), GraphBundleEx.extend(b));
288 if(!requireSynchronize && installedTGs.size() > 1 && !Platform.inDevelopmentMode()) return;
289 // if(installedTGs.size() > 1) return;
291 // Get a list of all bundles in the platform (Bundle Context)
292 List<GraphBundle> tgs = new ArrayList<GraphBundle>();
293 progressMonitor.subTask("load all transferable graphs from platform");
294 PlatformUtil.getAllGraphs(tgs);
295 progressMonitor.subTask("extend bundles to compile versions");
296 for (GraphBundle b : tgs) {
297 GraphBundleEx gbe = GraphBundleEx.extend(b);
299 platformTGs.put(GraphBundleRef.of(b), gbe);
302 // Compile a list of TGs that need to be installed or reinstalled in the database
303 progressMonitor.subTask("check bundle reinstallation demand");
304 List<GraphBundleEx> installTGs = new ArrayList<GraphBundleEx>();
305 // Create list of TGs to update, <newTg, oldTg>
306 Map<GraphBundleEx,GraphBundleEx> reinstallTGs = new TreeMap<GraphBundleEx,GraphBundleEx>();
307 for (Entry<GraphBundleRef, GraphBundleEx> e : platformTGs.entrySet()) {
308 GraphBundleRef key = e.getKey();
309 GraphBundleEx platformBundle = e.getValue();
310 GraphBundleEx existingBundle = installedTGs.get(key);
312 // System.out.println("GraphBundleRef key=" + key.toString());
314 if (existingBundle == null) {
315 // Bundle did not exist in the database, put it into list of bundles to install
316 installTGs.add(platformBundle);
319 // Bundle exists in the database
320 boolean platformBundleIsNewer = existingBundle.getVersion().compareTo(platformBundle.getVersion())<0;
321 if (!platformBundleIsNewer)
323 // Check hash of transferable graph to know whether to update or not.
324 if (platformBundle.getHashcode() == existingBundle.getHashcode())
326 //System.out.println("Ontology hashcodes do not match: platform bundle="
327 // + platformBundle.getVersionedId() + ", hash=" + platformBundle.getHashcode()
328 // + "; existing bundle=" + existingBundle.getVersionedId() + ", hash=" + existingBundle.getHashcode());
329 reinstallTGs.put(platformBundle, existingBundle);
333 // Database is missing graphs
334 if (!installTGs.isEmpty() || !reinstallTGs.isEmpty()) {
335 session.getService(XSupport.class).setServiceMode(true, true);
338 if (ontologyPolicy == OntologyRecoveryPolicy.ThrowError) {
339 StringBuilder sb = new StringBuilder("The following graphs are not installed in the database: ");
340 if (!installTGs.isEmpty()) {
342 for (GraphBundleEx e : installTGs) {
343 if (i>0) sb.append(", ");
345 sb.append(e.toString());
347 sb.append(" is missing from the database.\n");
349 if (!reinstallTGs.isEmpty()) {
351 for (Entry<GraphBundleEx, GraphBundleEx> e : reinstallTGs.entrySet()) {
352 if (i>0) sb.append(", ");
354 sb.append(e.getKey().toString());
356 sb.append(" Database/Platform Bundle version mismatch.\n");
358 sb.append("Hint: Use -fixErrors to install the graphs.");
359 throw new PlatformException(sb.toString());
361 // Reinstall database
362 if (ontologyPolicy == OntologyRecoveryPolicy.ReinstallDatabase) {
363 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Reinstalling the database."));
372 throw new PlatformException("Reinstalling Database, NOT IMPLEMENTED");
375 if (ontologyPolicy == OntologyRecoveryPolicy.Merge) {
376 progressMonitor.subTask("Merging ontology changes");
377 // Sort missing TGs into install order
378 GraphDependencyAnalyzer<GraphBundle> analyzer = new GraphDependencyAnalyzer<GraphBundle>();
379 for(GraphBundle tg : installTGs) analyzer.addGraph(tg, tg.getGraph());
380 for(GraphBundle tg : reinstallTGs.keySet()) analyzer.addGraph(tg, tg.getGraph());
381 if(!analyzer.analyzeDependency()) {
382 Collection<Pair<GraphBundle, GraphBundle>> problems = analyzer.getConflicts();
383 StringBuilder sb = new StringBuilder();
384 for (Pair<GraphBundle, GraphBundle> problem : problems) {
385 sb.append("Conflict with "+problem.first+" and "+problem.second+".\n");
387 throw new PlatformException(sb.toString());
389 else if(!session.syncRequest( analyzer.queryExternalDependenciesSatisfied )) {
390 Collection<IdentityNode> unsatisfiedDependencies = analyzer.getUnsatisfiedDependencies();
391 StringBuilder sb = new StringBuilder();
392 for (IdentityNode dep: unsatisfiedDependencies) {
393 sb.append("Unsatisfied Dependency "+dep+". Required by\n");
394 for(IU iu : GraphDependencyAnalyzer.toCollection(dep.getRequires())) {
395 sb.append(" " + ((GraphBundle)iu.getId()).getId() + "\n");
398 throw new PlatformException(sb.toString());
401 List<GraphBundle> sortedBundles = analyzer.getSortedGraphs();
402 if(!sortedBundles.isEmpty()) {
404 session.syncRequest((Write) graph -> {
406 graph.newClusterSet(graph.getRootLibrary());
407 } catch (ClusterSetExistException e) {
408 // Cluster set exist already, no problem.
410 graph.setClusterSet4NewResource(graph.getRootLibrary());
411 graph.flushCluster();
414 boolean mergedOntologies = false;
417 for(final GraphBundle tg : sortedBundles) {
419 final IImportAdvisor advisor = new OntologyImportAdvisor(tg, mgmt);
420 final GraphBundle oldTG = reinstallTGs.get(tg);
422 boolean createImmutable = tg.getImmutable();
426 session.getService(XSupport.class).setServiceMode(true, createImmutable);
429 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Installing "+tg.toString()+" - "+tg.getName()));
430 ImportResult result = TransferableGraphs.importGraph1(session, new TGTransferableGraphSource(tg.getGraph()), advisor, null);
431 if (!result.missingExternals.isEmpty()) {
432 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import of " + tg.toString() + " was missing the following external entities:\n" + EString.implode(result.missingExternals)));
439 startTransaction(session, false);
440 TransferableGraphDelta1 delta = new Diff(oldTG.getGraph(), tg.getGraph()).diff();
441 final long[] oldResources = oldTG.getResourceArray();
442 boolean changes = TransferableGraphs.hasChanges(readGraph(), oldResources, delta);
445 //log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Nothing to merge for "+tg.toString()));
449 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Merging new version of "+tg.toString()));
451 startTransaction(session, true);
457 long[] resourceArray = TransferableGraphs.applyDelta(writeGraph(), oldResources, delta);
458 tg.setResourceArray(resourceArray);
459 mgmt.setGraphBundleEntry(tg);
461 mergedOntologies = true;
462 } catch (Throwable t) {
463 throw new PlatformException(t);
470 session.syncRequest((Write) graph -> {
471 graph.setClusterSet4NewResource(graph.getRootLibrary());
472 graph.flushCluster();
475 if (mergedOntologies)
476 DatabaseIndexing.deleteAllIndexes();
479 TimeLogger.log("Ontologies synchronized.");
482 session.getService(XSupport.class).setServiceMode(false, false);
484 progressMonitor.worked(20);
485 } catch (IOException e) {
486 throw new PlatformException(e);
487 } catch (DatabaseException e) {
488 throw new PlatformException(e);
493 public boolean assertConfiguration(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy) throws PlatformException {
495 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
497 File workspaceLocation = Platform.getLocation().toFile();
499 boolean installProject = false;
500 progressMonitor.setTaskName("Asserting simantics.cfg is installed");
502 File propertyFile = new File(workspaceLocation, "simantics.cfg");
503 Properties properties;
505 properties = WorkspaceUtil.readProperties(propertyFile);
506 } catch (IOException e) {
507 if (workspacePolicy == RecoveryPolicy.ThrowError) throw new PlatformException("Could not load "+propertyFile);
509 // Create a project and write Property file
510 properties = new Properties();
511 properties.setProperty("project_uri", "http://Projects/Development%20Project");
512 properties.setProperty("project_name", "Development Project");
513 WorkspaceUtil.writeProperties(propertyFile, properties);
514 installProject |= true;
516 projectURI = properties.getProperty("project_uri");
517 projectName = properties.getProperty("project_name");
518 progressMonitor.worked(10);
519 } catch (IOException e) {
520 throw new PlatformException(e);
523 return installProject;
527 public boolean assertProject(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, boolean installProject) throws PlatformException {
529 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
531 final DatabaseManagement mgmt = new DatabaseManagement();
533 progressMonitor.setTaskName("Asserting project resource exists in the database");
535 projectResource = session.syncRequest( Queries.resource( projectURI ) );
536 } catch (ResourceNotFoundException nfe) {
537 // Project was not found
538 if (workspacePolicy == RecoveryPolicy.ThrowError)
539 throw new PlatformException("Project Resource "+projectURI+" is not found in the database.");
540 // Create empty project with no features
542 Transaction.startTransaction(session, true);
544 // The project needs to be created mutable.
545 session.getService(XSupport.class).setServiceMode(true, false);
547 ArrayList<String> empty = new ArrayList<String>();
548 projectResource = mgmt.createProject(projectName, empty);
549 installProject |= true;
551 session.getService(XSupport.class).setServiceMode(false, false);
552 Transaction.commit();
554 Transaction.endTransaction();
556 //session.getService( LifecycleSupport.class ).save();
557 } catch (DatabaseException e) {
558 throw new PlatformException("Failed to create "+projectURI, e);
560 } catch (DatabaseException e) {
561 throw new PlatformException("Failed to create "+projectURI, e);
563 progressMonitor.worked(10);
565 return installProject;
569 public void updateInstalledGroups(IProgressMonitor progressMonitor, boolean installProject) throws PlatformException {
573 // Attach all feature groups available in platform to created project
574 progressMonitor.setTaskName("Install all features");
575 Set<GroupReference> publishedFeatureGroups = ProjectFeatures.getInstallGroupsOfPublishedFeatures();
576 Collection<GroupReference> groupsWithoutVersion = GroupReference.stripVersions(publishedFeatureGroups);
581 Projects.setProjectInstalledGroups(graph, projectResource, groupsWithoutVersion));
582 } catch (DatabaseException ae) {
583 throw new PlatformException("Failed to install features", ae);
585 progressMonitor.worked(10);
590 public void assertSessionModel(IProgressMonitor progressMonitor) throws PlatformException {
592 Properties properties = session.getService(Properties.class);
593 final String clientId = properties.getProperty("clientId");
597 // Currently this needs to be done before data becomes available
598 VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
599 VirtualGraph activations = support.getWorkspacePersistent("activations");
601 Resource sessionModel = session.syncRequest(new Read<Resource>() {
604 public Resource perform(ReadGraph graph) throws DatabaseException {
606 Layer0X L0X = Layer0X.getInstance(graph);
607 for(Resource sessionModel : graph.syncRequest(new ObjectsWithType(graph.getRootLibrary(), L0X.HasSession, L0X.Session))) {
608 String id = graph.getPossibleRelatedValue(sessionModel, L0X.Session_HasClientId);
609 if(id != null && id.equals(clientId)) return sessionModel;
617 if(sessionModel == null) {
619 sessionModel = session.syncRequest(new WriteResultRequest<Resource>(activations) {
622 public Resource perform(WriteGraph graph) throws DatabaseException {
623 Layer0 L0 = Layer0.getInstance(graph);
624 Layer0X L0X = Layer0X.getInstance(graph);
625 Resource session = graph.newResource();
626 graph.claim(session, L0.InstanceOf, null, L0X.Session);
627 graph.claim(session, L0X.Session_HasUser, null, graph.getResource("http://Users/AdminUser"));
628 graph.addLiteral(session, L0X.Session_HasClientId, L0X.Session_HasClientId_Inverse, clientId, Bindings.STRING);
629 graph.claim(graph.getRootLibrary(), L0X.HasSession, session);
636 session.registerService(SessionModel.class, new PlatformSessionModel(sessionModel));
637 } catch (DatabaseException e) {
638 throw new PlatformException(e);
643 static class PlatformSessionModel implements SessionModel {
644 private final Resource sessionModel;
646 public PlatformSessionModel(Resource model) {
647 this.sessionModel = model;
651 public Resource getResource() {
656 public void resetDatabase(IProgressMonitor monitor) throws PlatformException {
657 File dbLocation = Platform.getLocation().append("db").toFile();
658 if(!dbLocation.exists()) return;
660 Driver driver = Manager.getDriver("procore");
661 Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
663 } catch (DatabaseException e) {
664 throw new PlatformException("Failed to remove database at " + dbLocation.getAbsolutePath(), e);
666 // We have created extra files to database folder which have to be deleted also.
667 // This is an awful idea! Do not create extra files to database folder!
669 for (int i=0; i<10; ++i) {
671 FileUtils.deleteAll(dbLocation);
674 } catch (IOException e) {
675 // Assuming this has been thrown because delete file/folder failed.
680 } catch (InterruptedException e) {
681 // Ignoring interrupted exception.
685 throw new PlatformException("Failed to remove database folder at " + dbLocation.getAbsolutePath(), t);
687 public void resetWorkspace(IProgressMonitor monitor, ArrayList<String> fileFilter) throws PlatformException, IllegalStateException, IOException {
688 File file = Platform.getLocation().toFile();
689 if (null != fileFilter)
690 FileUtils.deleteAllWithFilter(file , fileFilter);
691 resetDatabase(monitor);
694 public boolean handleBaselineDatabase() throws PlatformException {
695 Path workspaceLocation = Platform.getLocation().toFile().toPath();
696 Path baselineIndicatorFile = workspaceLocation.resolve(".baselined");
697 if (Files.isRegularFile(baselineIndicatorFile)) {
698 // This means that the workspace has already been initialized from
699 // a database baseline and further initialization is not necessary.
703 String dbBaselineArchive = System.getProperty("org.simantics.db.baseline", null);
704 if (dbBaselineArchive == null)
707 Path baseline = Paths.get(dbBaselineArchive);
708 if (!Files.isRegularFile(baseline))
709 throw new PlatformException("Specified database baseline archive " + baseline + " does not exist. Cannot initialize workspace database.");
711 validateBaselineFile(baseline);
712 validateWorkspaceForBaselineInitialization(workspaceLocation);
715 Files.createDirectories(workspaceLocation);
716 FileUtils.extractZip(baseline.toFile(), workspaceLocation.toFile());
717 Files.write(baselineIndicatorFile, baselineIndicatorContents(baselineIndicatorFile));
719 } catch (IOException e) {
720 throw new PlatformException(e);
724 private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("d. MMM yyyy HH:mm:ss");
726 private static byte[] baselineIndicatorContents(Path path) throws IOException {
727 return String.format("%s%n%s%n",
729 Instant.now().atZone(ZoneId.systemDefault()).format(TIMESTAMP_FORMAT))
733 private void validateWorkspaceForBaselineInitialization(Path workspaceLocation) throws PlatformException {
735 Path db = workspaceLocation.resolve("db");
736 if (Files.exists(db))
737 throw new PlatformException("Database location " + db + " already exists. Cannot re-initialize workspace from baseline.");
738 Path index = workspaceLocation.resolve(".metadata/.plugins/org.simantics.db.indexing");
739 if (!Files.exists(index) || !isEmptyDirectory(index))
740 throw new PlatformException("Index location " + index + " already exists. Cannot re-initialize workspace from baseline.");
741 } catch (IOException e) {
742 throw new PlatformException("Failed to validate workspace for baseline initialization", e);
746 private static boolean isEmptyDirectory(Path dir) throws IOException {
747 return Files.walk(dir).count() == 1;
750 private void validateBaselineFile(Path baseline) throws PlatformException {
751 try (ZipFile zip = new ZipFile(baseline.toFile())) {
752 ZipEntry db = zip.getEntry("db");
754 throw new PlatformException("Baseline archive does not contain database directory 'db'");
755 ZipEntry index = zip.getEntry(".metadata/.plugins/org.simantics.db.indexing");
757 throw new PlatformException("Baseline archive does not contain database index directory '.metadata/.plugins/org.simantics.db.indexing'");
758 } catch (IOException e) {
759 throw new PlatformException("Failed to validate baseline archive " + baseline, e);
764 * Start-up the platform. The procedure consists of 8 steps. Once everything
765 * is up and running, all fields are set property.
768 * If workspacePolicy is FixErrors, there is an attempt to fix unexpected
769 * errors. It includes installing database files, installing ontologies, and
770 * installing project features.
773 * In Simantics Workbench this is handled in
774 * <code>SimanticsWorkbenchAdvisor#openWindows()</code>.
777 * If remote server is given, simantics plaform takes connection there
778 * instead of local server at "db/".
780 * @param workspacePolicy action to take on workspace/database related
782 * @param ontologyPolicy action to take on ontology mismatch
783 * @param progressMonitor optional progress monitor
784 * @param userAgent interface for resorting to user feedback during platform
785 * startup or <code>null</code> to resort to default measures
786 * @throws PlatformException
788 public synchronized SessionContext startUp(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy,
789 OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize, PlatformUserAgent userAgent)
790 throws PlatformException
794 TimeLogger.log("Beginning of SimanticsPlatform.startUp");
796 LOGGER.info("Beginning of SimanticsPlatform.startUp");
798 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
800 // For debugging on what kind of platform automatic tests are running in
801 // case there are problems.
802 if ("true".equals(System.getProperty("org.simantics.dumpBundleState")))
803 dumpPlatformBundleState();
805 // 0. Consult all startup extensions before doing anything with the workspace.
806 StartupExtensions.consultStartupExtensions();
807 TimeLogger.log("Consulted platform pre-startup extensions");
809 // 0.1. Clear all temporary files
810 Simantics.clearTemporaryDirectory();
811 TimeLogger.log("Cleared temporary directory");
813 // 0.2 Clear VariableRepository.repository static map which holds references to SessionImplDb
814 VariableRepository.clear();
816 // 0.3 Handle baseline database before opening db
817 boolean usingBaseline = handleBaselineDatabase();
819 // 1. Assert there is a database at <workspace>/db
820 session = setupDatabase(databaseDriverId, progressMonitor, workspacePolicy, userAgent);
821 TimeLogger.log("Database setup complete");
824 XSupport support = session.getService(XSupport.class);
825 if (support.rolledback()) {
827 DatabaseIndexing.deleteAllIndexes();
828 } catch (IOException e) {
829 throw new PlatformException(e);
833 // 2. Assert all graphs, and correct versions, are installed to the database
835 synchronizeOntologies(progressMonitor, ontologyPolicy, requireSynchronize);
836 TimeLogger.log("Synchronized ontologies");
839 // 4. Assert simantics.cfg exists
840 boolean installProject = assertConfiguration(progressMonitor,workspacePolicy);
842 // 5. Assert Project Resource is installed in the database
843 installProject = assertProject(progressMonitor, workspacePolicy, installProject);
845 // 6. Install all features into project, if in debug mode
846 updateInstalledGroups(progressMonitor, true); //installProject);
847 TimeLogger.log("Installed all features into project");
849 // 7. Assert L0.Session in database for this session
850 assertSessionModel(progressMonitor);
852 session.getService(XSupport.class).setServiceMode(false, false);
855 session.syncRequest((Write) graph -> {
856 QueryControl qc = graph.getService(QueryControl.class);
859 TimeLogger.log("Flushed queries");
860 } catch (DatabaseException e) {
861 LOGGER.error("Flushing queries failed.", e);
863 boolean loadProject = true;
866 sessionContext = SimanticsPlatform.INSTANCE.createSessionContext(true);
867 // This must be before setSessionContext since some listeners might query this
868 sessionContext.setHint(SimanticsKeys.KEY_PROJECT, SimanticsPlatform.INSTANCE.projectResource);
870 Simantics.setSessionContext(sessionContext);
872 // 1. Put ResourceBinding that throws an exception to General Bindings
873 simanticsBindings = new SimanticsBindings( null );
874 Bindings.classBindingFactory.addFactory( simanticsBindings );
877 // 2. Create session-specific second Binding context (Databoard) and
878 // put that to Session as a service
879 Session session = sessionContext.getSession();
880 Databoard sessionDataboard = new Databoard();
881 session.registerService(Databoard.class, sessionDataboard);
882 simanticsBindings2 = new SimanticsBindings( session );
883 sessionDataboard.classBindingFactory.addFactory( simanticsBindings2 );
885 // Register datatype bindings
886 Bindings.defaultBindingFactory.getRepository().put(RGB.Integer.BINDING.type(), RGB.Integer.BINDING);
887 Bindings.defaultBindingFactory.getRepository().put(Font.BINDING.type(), Font.BINDING);
891 TimeLogger.log("Load projects");
892 project = Projects.loadProject(sessionContext.getSession(), SimanticsPlatform.INSTANCE.projectResource);
894 sessionContext.setHint(ProjectKeys.KEY_PROJECT, project);
895 TimeLogger.log("Loading projects complete");
898 TimeLogger.log("Project activated");
901 } catch (DatabaseException e) {
902 LOGGER.error("Platform startup failed.", e);
903 throw new PlatformException(e);
904 } catch (ProjectException e) {
905 boolean hasStackTrace = e.getStackTrace().length > 0;
907 throw new PlatformException(e.getMessage(), hasStackTrace);
908 throw new PlatformException(e, hasStackTrace);
913 // #7650: improve shutdown robustness in all applications that use the platform
914 Runtime.getRuntime().addShutdownHook(shutdownHook);
916 // Discard database session undo history at this point to prevent
917 // the user from undoing any initialization operations performed
918 // by the platform startup.
919 SimanticsPlatform.INSTANCE.discardSessionUndoHistory();
920 TimeLogger.log("Discarded session undo history");
922 return sessionContext;
926 public SessionContext createSessionContext(boolean init) throws PlatformException {
928 // Construct and initialize SessionContext from Session.
929 SessionContext sessionContext = SessionContext.create(session, init);
930 TimeLogger.log("Session context created");
932 sessionContext.registerServices();
933 TimeLogger.log("Session services registered");
935 return sessionContext;
936 } catch (DatabaseException e) {
937 throw new PlatformException(e);
942 * Perform normal shutdown for the Simantics Platform.
944 * @param progressMonitor optional progress monitor
945 * @throws PlatformException
946 * @see {@link #shutdown(IProgressMonitor, boolean)}
948 public synchronized void shutdown(IProgressMonitor progressMonitor) throws PlatformException {
949 shutdown(progressMonitor, true);
953 * Shutdown Simantics Platform.
955 * In Simantics Workbench this is handled in
956 * <code>SimanticsWorkbenchAdvisor#disconnectFromWorkspace</code>.
958 * @param progressMonitor
959 * optional progress monitor
960 * @param clearTemporaryFiles
961 * allow or prevent deletion of temporary files at the end of the
963 * @throws PlatformException
965 public synchronized void shutdown(IProgressMonitor progressMonitor, boolean clearTemporaryFiles) throws PlatformException
967 SubMonitor progress = SubMonitor.convert(progressMonitor, 100);
968 PlatformException platformException = null;
970 progress.subTask("Close Project");
971 if (project != null) {
972 project.safeDispose();
977 progress.subTask("Close Database Session");
978 Databoard databoard = null;
979 if (sessionContext != null) {
980 Session s = sessionContext.peekSession();
982 databoard = s.peekService(Databoard.class);
984 progress.subTask("Flushing Index Caches");
986 Simantics.flushIndexCaches(progress.newChild(20), s);
987 } catch (Throwable t) {
988 LOGGER.error("Failed to flush index caches.", t);
992 progress.subTask("Close Database Session");
993 sessionContext.safeDispose();
994 sessionContext = null;
995 Simantics.setSessionContext(null);
997 if (simanticsBindings != null) {
998 Bindings.classBindingFactory.removeFactory( simanticsBindings );
999 simanticsBindings = null;
1001 if (databoard != null) {
1002 if (simanticsBindings2 != null) {
1003 databoard.classBindingFactory.removeFactory( simanticsBindings2 );
1004 simanticsBindings2 = null;
1009 // Make sure Simantics clipboard doesn't store unwanted session data references.
1010 Simantics.setClipboard(new SimanticsClipboardImpl());
1012 progress.worked(30);
1015 projectResource = null;
1016 currentDatabaseDriver = null;
1018 DependenciesRelation.assertFinishedTracking();
1020 } catch (Exception e) {
1021 platformException = new PlatformException("Failed to shutdown Simantics Platform", e);
1024 progress.worked(10);
1025 progress.subTask("Shutting down database");
1027 if (null != databasebManagement)
1028 databasebManagement.shutdown();
1029 } catch (Throwable t) {
1030 LOGGER.error("Database shutdown failed.", t);
1032 progress.worked(10);
1034 if (clearTemporaryFiles) {
1035 progress.subTask("Clearing Workspace Temporary Directory");
1037 Simantics.clearTemporaryDirectory();
1038 } catch (Throwable t) {
1039 LOGGER.error("Failed to clear the temporary directory.", t);
1042 progress.worked(10);
1043 if (null != platformException)
1044 throw platformException;
1046 // #7650: improve shutdown robustness in all applications that use the platform
1047 Runtime.getRuntime().removeShutdownHook(shutdownHook);
1050 // TODO: consider removing this in the future ??
1052 public void stateChanged(LifecycleState newState) {
1053 if(newState == LifecycleState.CLOSED) {
1055 if(Platform.isRunning()) {
1056 mainThread.interrupt();
1063 * @return <code>true</code> if discard was successful, <code>false</code>
1064 * if there was no session, {@link UndoRedoSupport} or
1065 * {@link UndoContext} to discard through
1067 public boolean discardSessionUndoHistory() {
1068 Session s = session;
1070 UndoRedoSupport urs = s.peekService(UndoRedoSupport.class);
1072 UndoContext uc = urs.getUndoContext(s);
1082 public void reconnect(String databaseDriverId) throws Exception {
1083 // Starts database server.
1084 if (currentDatabaseDriver != null)
1085 databaseDriverId = currentDatabaseDriver;
1086 SimanticsPlatform.INSTANCE.startUp(databaseDriverId, null, RecoveryPolicy.ThrowError, OntologyRecoveryPolicy.ThrowError, true, null);
1089 private void dumpPlatformBundleState() {
1090 BundleDescription[] bs = Platform.getPlatformAdmin().getState().getBundles();
1091 System.out.println("Total bundles: " + bs.length);
1092 for (BundleDescription b : bs) {
1093 System.out.format("%-80s @ %s\n", b.toString(), b.getLocation());
1097 private Ini loadOrCreateDatabaseIni(Path path, String databaseDriverId)
1098 throws InvalidFileFormatException, IOException
1100 File f = path.toFile();
1101 Ini dbIni = Files.isRegularFile(path) ? new Ini(f) : new Ini();
1102 String iniId = dbIni != null ? dbIni.get("driver", "id") : null;
1103 if (iniId == null) {
1104 dbIni.put("driver", "id", databaseDriverId);