]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics/src/org/simantics/SimanticsPlatform.java
Speeding up platform startup time
[simantics/platform.git] / bundles / org.simantics / src / org / simantics / SimanticsPlatform.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2018 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics;
13
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;
19
20 import java.io.File;
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;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Properties;
32 import java.util.Set;
33 import java.util.TreeMap;
34 import java.util.UUID;
35
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;
46 import org.ini4j.Ini;
47 import org.ini4j.InvalidFileFormatException;
48 import org.simantics.databoard.Bindings;
49 import org.simantics.databoard.Databoard;
50 import org.simantics.datatypes.literal.Font;
51 import org.simantics.datatypes.literal.RGB;
52 import org.simantics.db.Driver;
53 import org.simantics.db.Driver.Management;
54 import org.simantics.db.Manager;
55 import org.simantics.db.ReadGraph;
56 import org.simantics.db.Resource;
57 import org.simantics.db.Session;
58 import org.simantics.db.SessionModel;
59 import org.simantics.db.UndoContext;
60 import org.simantics.db.VirtualGraph;
61 import org.simantics.db.WriteGraph;
62 import org.simantics.db.common.request.ObjectsWithType;
63 import org.simantics.db.common.request.WriteResultRequest;
64 import org.simantics.db.common.utils.Transaction;
65 import org.simantics.db.exception.ClusterSetExistException;
66 import org.simantics.db.exception.DatabaseException;
67 import org.simantics.db.indexing.DatabaseIndexing;
68 import org.simantics.db.layer0.genericrelation.DependenciesRelation;
69 import org.simantics.db.layer0.genericrelation.IndexException;
70 import org.simantics.db.layer0.genericrelation.IndexedRelations;
71 import org.simantics.db.layer0.request.PossibleResource;
72 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
73 import org.simantics.db.layer0.util.SimanticsKeys;
74 import org.simantics.db.layer0.util.TGTransferableGraphSource;
75 import org.simantics.db.layer0.variable.VariableRepository;
76 import org.simantics.db.management.SessionContext;
77 import org.simantics.db.request.Read;
78 import org.simantics.db.request.Write;
79 import org.simantics.db.service.LifecycleSupport.LifecycleListener;
80 import org.simantics.db.service.LifecycleSupport.LifecycleState;
81 import org.simantics.db.service.QueryControl;
82 import org.simantics.db.service.UndoRedoSupport;
83 import org.simantics.db.service.VirtualGraphSupport;
84 import org.simantics.db.service.XSupport;
85 import org.simantics.graph.db.GraphDependencyAnalyzer;
86 import org.simantics.graph.db.GraphDependencyAnalyzer.IU;
87 import org.simantics.graph.db.GraphDependencyAnalyzer.IdentityNode;
88 import org.simantics.graph.db.IImportAdvisor;
89 import org.simantics.graph.db.ImportResult;
90 import org.simantics.graph.db.TransferableGraphs;
91 import org.simantics.graph.diff.Diff;
92 import org.simantics.graph.diff.TransferableGraphDelta1;
93 import org.simantics.internal.Activator;
94 import org.simantics.internal.TimedSessionCache;
95 import org.simantics.internal.startup.StartupExtensions;
96 import org.simantics.layer0.Layer0;
97 import org.simantics.operation.Layer0X;
98 import org.simantics.project.IProject;
99 import org.simantics.project.ProjectFeatures;
100 import org.simantics.project.ProjectKeys;
101 import org.simantics.project.Projects;
102 import org.simantics.project.SessionDescriptor;
103 import org.simantics.project.exception.ProjectException;
104 import org.simantics.project.features.registry.GroupReference;
105 import org.simantics.project.management.DatabaseManagement;
106 import org.simantics.project.management.GraphBundle;
107 import org.simantics.project.management.GraphBundleEx;
108 import org.simantics.project.management.GraphBundleRef;
109 import org.simantics.project.management.PlatformUtil;
110 import org.simantics.project.management.ServerManager;
111 import org.simantics.project.management.ServerManagerFactory;
112 import org.simantics.project.management.WorkspaceUtil;
113 import org.simantics.scl.compiler.module.repository.ModuleRepository;
114 import org.simantics.scl.osgi.SCLOsgi;
115 import org.simantics.utils.FileUtils;
116 import org.simantics.utils.datastructures.Pair;
117 import org.simantics.utils.strings.EString;
118 import org.simantics.utils.threads.ExecutorWorker;
119 import org.simantics.utils.threads.ThreadUtils;
120 import org.slf4j.Logger;
121 import org.slf4j.LoggerFactory;
122
123 /**
124  * SimanticsPlatform performs procedures required in order to get simantics
125  * workbench into operational state. This consists of the following steps:
126  * <ul>
127  *     <li> Asserting there is Database
128  *     </li>
129  *     <li> Starting Database process
130  *     </li>
131  *     <li> Opening a session to Database process
132  *     </li>
133  *     <li> Asserting required ontologies or other transferable graphs are installed in the database
134  *     </li>
135  *     <li> Asserting required project is installed in the database
136  *     </li>
137  *     <li> Asserting Simantics Features are installed in the database
138  *     </li>
139  *     <li> Asserting Simantics Features are installed to the project
140  *     </li>
141  *     <li> Shutdown: Save Session, Close session, Kill Database process
142  *     </li>
143  * </ul>
144  *
145  * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
146  */
147 public class SimanticsPlatform implements LifecycleListener {
148
149     private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsPlatform.class);
150     
151     /**
152      * The policy is relevant when developing Simantics from Eclipse IDE.
153      * It is applied when the ontology in the database of a workspace doesn't match
154      * a newer ontology in the Eclipse workspace.
155      */
156     public static enum OntologyRecoveryPolicy { ThrowError, Merge, ReinstallDatabase }
157
158     /**
159      * This policy dictates how the Simantics platform startup should react if
160      * the started workspace is not set up properly. The alternatives are to
161      * just throw an error and fail or to attempt all possible measures to fix
162      * the encountered problems.
163      */
164     public static enum RecoveryPolicy { ThrowError, FixError }
165
166     /** Singleton instance, started in SimanticsWorkbenchAdvisor */
167     public static final SimanticsPlatform INSTANCE = new SimanticsPlatform();
168
169     /** Set to true when the Simantics Platform is in good-and-go condition */
170     public boolean running;
171
172     /** ID of the database driver that the platform is currently using */
173     private String currentDatabaseDriver;
174
175     /** Database Session */
176     public Session session;
177     private Management databasebManagement;
178
179     /** Database session context */
180     public SessionContext sessionContext;
181
182     /** Project identifier in Database */
183     public String projectURI;
184
185     /** Project name */
186     public String projectName;
187
188     /** Project resource */
189     public Resource projectResource;
190
191     /** Session specific bindings */
192     public SimanticsBindings simanticsBindings;
193
194     public Thread mainThread;
195
196     private Thread shutdownHook = new Thread() {
197         @Override
198         public void run() {
199             try {
200                 LOGGER.warn("Simantics platform was not properly shut down. Executing safety shutdown hook.");
201                 shutdown(null, false);
202             } catch (PlatformException e) {
203                 LOGGER.error("Simantics Platform shutdown hook execution failed.", e);
204                 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Simantics Platform shutdown hook execution failed.", e));
205             }
206         }
207     };
208
209     /**
210      * The {@link IProject} activated by
211      * {@link #startUp(IProgressMonitor, RecoveryPolicy, OntologyRecoveryPolicy, ServerAddress, PlatformUserAgent)}
212      */
213     private IProject project;
214
215     protected ILog log;
216
217     /**
218      * Create a new simantics plaform manager in uninitialized state and
219      * with default policies. <p>
220      */
221     public SimanticsPlatform() {
222         log = Platform.getLog(Activator.getBundleContext().getBundle());
223         mainThread = Thread.currentThread();
224     }
225
226     public String getApplicationClientId() {
227         IProduct product = Platform.getProduct();
228         if(product == null) return "noProduct";//UUID.randomUUID().toString();
229         String application = product.getApplication();
230         return application != null ? application : UUID.randomUUID().toString();
231     }
232
233     private SessionDescriptor setupDatabase(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, PlatformUserAgent userAgent) throws PlatformException {
234         if (progressMonitor == null)
235             progressMonitor = new NullProgressMonitor();
236         Path workspaceLocation = Platform.getLocation().toFile().toPath();
237         Path dbLocation = workspaceLocation.resolve("db");
238         Path dbIniPath = workspaceLocation.resolve("db.ini");
239         // The driver file overrides any command line arguments to prevent
240         // using the wrong driver for an existing database directory.
241         ServerManager serverManager;
242         try {
243             Ini dbIni = loadOrCreateDatabaseIni(dbIniPath, databaseDriverId);
244             databaseDriverId = dbIni.get("driver", "id");
245             serverManager = ServerManagerFactory.create(databaseDriverId, dbLocation.toAbsolutePath().toString());
246         } catch (DatabaseException | IOException e) {
247             throw new PlatformException("Failed to initialize database ServerManager with driver " + databaseDriverId, e);
248         }
249         progressMonitor.beginTask("Setting up Simantics Database", 100);
250         progressMonitor.setTaskName("Asserting Database is installed.");
251         String msg = "Failed to initialize Simantics database.";
252         try {
253             // Create database
254             log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Initializing database at " + dbLocation + " with driver " + databaseDriverId));
255             progressMonitor.setTaskName("Creating database at " + dbLocation);
256             databasebManagement = serverManager.getManagement(dbLocation.toFile());
257             databasebManagement.create();
258             currentDatabaseDriver = databaseDriverId;
259             // Create layer0.
260             return serverManager.createDatabase(dbLocation.toFile());
261         } catch (DatabaseException e) {
262             throw new PlatformException(msg, e);
263         } catch (Throwable e) {
264             throw new PlatformException(msg, e);
265         } finally {
266             progressMonitor.worked(20);
267         }
268     }
269
270     public void synchronizeOntologies(IProgressMonitor progressMonitor, OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize) throws PlatformException {
271
272         SubMonitor monitor = SubMonitor.convert(progressMonitor, 100);
273
274         monitor.setTaskName("Compile dynamic ontologies");
275         PlatformUtil.compileAllDynamicOntologies();
276
277         String message = "Asserting all ontologies are installed";
278         LOGGER.info(message);
279         monitor.setTaskName(message);
280
281         DatabaseManagement mgmt = new DatabaseManagement();
282         Map<GraphBundleRef, GraphBundleEx> platformTGs = new HashMap<>();
283         try {
284
285             // Get a list of bundles installed into the database
286             message = "find installed bundles from database";
287             monitor.subTask(message);
288             LOGGER.info(message);
289             Map<GraphBundleRef, GraphBundleEx> installedTGs = new HashMap<>();
290             for (GraphBundle b : session.syncRequest( mgmt.GraphBundleQuery )) {
291                 installedTGs.put(GraphBundleRef.of(b), GraphBundleEx.extend(b));
292             }
293
294             if(!requireSynchronize && installedTGs.size() > 1 && !Platform.inDevelopmentMode()) return;
295 //            if(installedTGs.size() > 1) return;
296
297             // Get a list of all bundles in the platform (Bundle Context)
298             message = "load all transferable graphs from platform";
299             monitor.subTask(message);
300             LOGGER.info(message);
301             Collection<GraphBundle> tgs = PlatformUtil.getAllGraphs();
302             message = "extend bundles to compile versions";
303             monitor.subTask(message);
304             LOGGER.info(message);
305             for (GraphBundle b : tgs) {
306                 GraphBundleEx gbe = GraphBundleEx.extend(b);
307                 gbe.build();
308                 platformTGs.put(GraphBundleRef.of(b), gbe);
309             }
310
311             // Compile a list of TGs that need to be installed or reinstalled in the database
312             message = "check bundle reinstallation demand";
313             monitor.subTask(message);
314             LOGGER.info(message);
315             List<GraphBundleEx> installTGs = new ArrayList<>();
316             // Create list of TGs to update, <newTg, oldTg>
317             Map<GraphBundleEx,GraphBundleEx> reinstallTGs = new TreeMap<>();
318             for (Entry<GraphBundleRef, GraphBundleEx> e : platformTGs.entrySet()) {
319                 GraphBundleRef key = e.getKey();
320                 GraphBundleEx platformBundle = e.getValue();
321                 GraphBundleEx existingBundle = installedTGs.get(key);
322                 
323 //                System.out.println("GraphBundleRef key=" + key.toString());
324                 
325                 if (existingBundle == null) {
326                     // Bundle did not exist in the database, put it into list of bundles to install
327                     installTGs.add(platformBundle);
328                 }
329                 else {
330                     // Bundle exists in the database
331                     boolean platformBundleIsNewer = existingBundle.getVersion().compareTo(platformBundle.getVersion())<0;
332                     if (!platformBundleIsNewer)
333                         continue;
334                     // Check hash of transferable graph to know whether to update or not.
335                     if (platformBundle.getHashcode() == existingBundle.getHashcode())
336                         continue;
337                     //System.out.println("Ontology hashcodes do not match: platform bundle="
338                     //        + platformBundle.getVersionedId() + ", hash=" + platformBundle.getHashcode()
339                     //        + "; existing bundle=" + existingBundle.getVersionedId() + ", hash=" + existingBundle.getHashcode());
340                     reinstallTGs.put(platformBundle, existingBundle);
341                 }
342             }
343             // INSTALL
344             // Database is missing graphs
345             if (!installTGs.isEmpty() || !reinstallTGs.isEmpty()) {
346                 session.getService(XSupport.class).setServiceMode(true, true);
347
348                 // Throw error
349                 if (ontologyPolicy == OntologyRecoveryPolicy.ThrowError) {
350                     StringBuilder sb = new StringBuilder("The following graphs are not installed in the database: ");
351                     if (!installTGs.isEmpty()) {
352                         int i = 0;
353                         for (GraphBundleEx e : installTGs) {
354                             if (i>0) sb.append(", ");
355                             i++;
356                             sb.append(e.toString());
357                         }
358                         sb.append(" is missing from the database.\n");
359                     }
360                     if (!reinstallTGs.isEmpty()) {
361                         int i = 0;
362                         for (Entry<GraphBundleEx, GraphBundleEx> e : reinstallTGs.entrySet()) {
363                             if (i>0) sb.append(", ");
364                             i++;
365                             sb.append(e.getKey().toString());
366                         }
367                         sb.append(" Database/Platform Bundle version mismatch.\n");
368                     }
369                     sb.append("Hint: Use -fixErrors to install the graphs.");
370                     throw new PlatformException(sb.toString());
371                 }
372                 // Reinstall database
373                 if (ontologyPolicy == OntologyRecoveryPolicy.ReinstallDatabase) {
374                     log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Reinstalling the database."));
375                     // TODO Install DB
376                     // Stop Session
377                     // Kill Process
378                     // Delete Database
379                     // Create Database
380                     // Start Database
381                     // Open Session
382                     // Install TGs
383                     throw new PlatformException("Reinstalling Database, NOT IMPLEMENTED");
384                 }
385
386                 if (ontologyPolicy == OntologyRecoveryPolicy.Merge) {
387                     message = "Merging ontology changes";
388                     monitor.subTask(message);
389                     LOGGER.info(message);
390                     // Sort missing TGs into install order
391                     GraphDependencyAnalyzer<GraphBundle> analyzer = new GraphDependencyAnalyzer<GraphBundle>();
392                     for(GraphBundle tg : installTGs) analyzer.addGraph(tg, tg.getGraph());
393                     for(GraphBundle tg : reinstallTGs.keySet()) analyzer.addGraph(tg, tg.getGraph());
394                     if(!analyzer.analyzeDependency()) {
395                         Collection<Pair<GraphBundle, GraphBundle>> problems = analyzer.getConflicts();
396                         StringBuilder sb = new StringBuilder();
397                         for (Pair<GraphBundle, GraphBundle> problem : problems) {
398                             sb.append("Conflict with "+problem.first+" and "+problem.second+".\n");
399                         }
400                         throw new PlatformException(sb.toString());
401                     } else if(!session.syncRequest( analyzer.queryExternalDependenciesSatisfied )) {
402                         Collection<IdentityNode> unsatisfiedDependencies = analyzer.getUnsatisfiedDependencies();
403                         StringBuilder sb = new StringBuilder();
404                         for (IdentityNode dep: unsatisfiedDependencies) {
405                             sb.append("Unsatisfied Dependency "+dep+". Required by\n");
406                             for(IU iu : GraphDependencyAnalyzer.toCollection(dep.getRequires())) {
407                                 sb.append("    " + ((GraphBundle)iu.getId()).getId() + "\n");
408                             }
409                         }
410                         throw new PlatformException(sb.toString());
411                     }
412
413                     message = "Analyzed graph bundles";
414                     monitor.subTask(message);
415                     LOGGER.info(message);
416
417                     List<GraphBundle> sortedBundles = analyzer.getSortedGraphs();
418                     if(!sortedBundles.isEmpty()) {
419
420                         session.syncRequest((Write) graph -> {
421                             try {
422                                 graph.newClusterSet(graph.getRootLibrary());
423                             } catch (ClusterSetExistException e) {
424                                 // Cluster set exist already, no problem.
425                             }
426                             graph.setClusterSet4NewResource(graph.getRootLibrary());
427                             graph.flushCluster();
428                         });
429
430                         boolean mergedOntologies = false;
431
432                         // Install TGs
433                         for(final GraphBundle tg : sortedBundles) {
434
435                                 final IImportAdvisor advisor = new OntologyImportAdvisor(tg, mgmt);
436                                 final GraphBundle oldTG = reinstallTGs.get(tg);
437
438                                 boolean createImmutable = tg.getImmutable();
439
440                                 if (oldTG==null) {
441
442                                 session.getService(XSupport.class).setServiceMode(true, createImmutable);
443
444                                         // Install TG
445                                         log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Installing "+tg.toString()+" - "+tg.getName()));
446                                         ImportResult result = TransferableGraphs.importGraph1(session, new TGTransferableGraphSource(tg.getGraph()), advisor, null);
447                                         if (!result.missingExternals.isEmpty()) {
448                                                 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import of " + tg.toString() + " was missing the following external entities:\n" + EString.implode(result.missingExternals)));
449                                         }
450                                 } else {
451                                         if(!createImmutable)
452                                                 continue;
453
454                                         // Merge TG
455                                         startTransaction(session, false);
456                                         TransferableGraphDelta1 delta = new Diff(oldTG.getGraph(), tg.getGraph()).diff();
457                                         final long[] oldResources = oldTG.getResourceArray();
458                                         boolean changes = TransferableGraphs.hasChanges(readGraph(), oldResources, delta);
459                                         endTransaction();
460                                         if (!changes) {
461                                             //log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Nothing to merge for "+tg.toString()));
462                                             continue;
463                                         }
464
465                                 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Merging new version of "+tg.toString()));
466
467                                         startTransaction(session, true);
468
469                                         //delta.print();
470                                         try {
471                                                 long[] resourceArray = TransferableGraphs.applyDelta(writeGraph(), oldResources, delta);
472                                                 tg.setResourceArray(resourceArray);
473                                                 mgmt.setGraphBundleEntry(tg);
474                                                 commit();
475                                                 mergedOntologies = true;
476                                         } catch (Throwable t) {
477                                                 throw new PlatformException(t);
478                                         } finally {
479                                                 endTransaction();
480                                         }
481                                 }
482                         }
483
484                         session.syncRequest((Write) graph -> {
485                             graph.setClusterSet4NewResource(graph.getRootLibrary());
486                             graph.flushCluster();
487                         });
488
489                         if (mergedOntologies)
490                             DatabaseIndexing.deleteAllIndexes();
491                     }
492                 }
493                 session.getService(XSupport.class).setServiceMode(false, false);
494             }
495             message = "Ontologies synchronized";
496             monitor.subTask(message);
497             LOGGER.info(message);
498             monitor.worked(100);
499         } catch (IOException e) {
500             throw new PlatformException(e);
501         } catch (DatabaseException e) {
502             throw new PlatformException(e);
503         }
504
505     }
506
507     public boolean assertConfiguration(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy) throws PlatformException {
508
509         if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
510
511         File workspaceLocation = Platform.getLocation().toFile();
512
513         boolean installProject = false;
514         progressMonitor.setTaskName("Asserting simantics.cfg is installed");
515         try {
516             File propertyFile = new File(workspaceLocation, "simantics.cfg");
517             Properties properties;
518             try {
519                 properties = WorkspaceUtil.readProperties(propertyFile);
520             } catch (IOException e) {
521                 if (workspacePolicy == RecoveryPolicy.ThrowError) throw new PlatformException("Could not load "+propertyFile);
522
523                 // Create a project and write Property file
524                 properties = new Properties();
525                 properties.setProperty("project_uri", "http://Projects/Development%20Project");
526                 properties.setProperty("project_name", "Development Project");
527                 WorkspaceUtil.writeProperties(propertyFile, properties);
528                 installProject |= true;
529             }
530             projectURI = properties.getProperty("project_uri");
531             projectName = properties.getProperty("project_name");
532             progressMonitor.worked(10);
533         } catch (IOException e) {
534             throw new PlatformException(e);
535         }
536
537         return installProject;
538
539     }
540
541     public boolean assertProject(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, boolean installProject) throws PlatformException {
542
543         SubMonitor monitor = SubMonitor.convert(progressMonitor, 10);
544
545         final DatabaseManagement mgmt = new DatabaseManagement();
546
547         monitor.setTaskName("Asserting project resource exists in the database");
548         try {
549             projectResource = session.syncRequest(new PossibleResource(projectURI));
550             if (projectResource == null) {
551                 // Project was not found
552                 if (workspacePolicy == RecoveryPolicy.ThrowError)
553                     throw new PlatformException("Project Resource "+projectURI+" is not found in the database.");
554                 // Create empty project with no features
555                 try {
556                     Transaction.startTransaction(session, true);
557                     try {
558                         // The project needs to be created mutable.
559                         session.getService(XSupport.class).setServiceMode(true, false);
560
561                         ArrayList<String> empty = new ArrayList<String>();
562                         projectResource = mgmt.createProject(projectName, empty);
563                         installProject |= true;
564
565                         session.getService(XSupport.class).setServiceMode(false, false);
566                         Transaction.commit();
567                     } finally {
568                         Transaction.endTransaction();
569                     }
570                     //session.getService( LifecycleSupport.class ).save();
571                 } catch (DatabaseException e) {
572                     throw new PlatformException("Failed to create "+projectURI, e);
573                 }
574             }
575         } catch (DatabaseException e) {
576             throw new PlatformException("Failed to create "+projectURI, e);
577         }
578         monitor.worked(10);
579
580         return installProject;
581
582     }
583
584     public void updateInstalledGroups(IProgressMonitor progressMonitor, boolean installProject) throws PlatformException {
585
586         if (installProject)
587         {
588             // Attach all feature groups available in platform to created project
589             progressMonitor.setTaskName("Install all features");
590             Set<GroupReference> publishedFeatureGroups = ProjectFeatures.getInstallGroupsOfPublishedFeatures();
591             Collection<GroupReference> groupsWithoutVersion = GroupReference.stripVersions(publishedFeatureGroups);
592
593             try {
594                 session.syncRequest(
595                         (Write) graph ->
596                         Projects.setProjectInstalledGroups(graph, projectResource, groupsWithoutVersion));
597             } catch (DatabaseException ae) {
598                 throw new PlatformException("Failed to install features", ae);
599             }
600             progressMonitor.worked(10);
601         }
602
603     }
604
605     public void assertSessionModel(IProgressMonitor progressMonitor) throws PlatformException {
606
607         Properties properties = session.getService(Properties.class);
608         final String clientId = properties.getProperty("clientId");
609
610         try {
611
612             // Currently this needs to be done before data becomes available
613             VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
614             VirtualGraph activations = support.getWorkspacePersistent("activations");
615
616             Resource sessionModel = session.syncRequest(new Read<Resource>() {
617
618                 @Override
619                 public Resource perform(ReadGraph graph) throws DatabaseException {
620
621                     Layer0X L0X = Layer0X.getInstance(graph);
622                     for(Resource sessionModel : graph.syncRequest(new ObjectsWithType(graph.getRootLibrary(), L0X.HasSession, L0X.Session))) {
623                         String id = graph.getPossibleRelatedValue(sessionModel, L0X.Session_HasClientId);
624                         if(id != null && id.equals(clientId)) return sessionModel;
625                     }
626                     return null;
627
628                 }
629
630             });
631
632             if(sessionModel == null) {
633
634                 sessionModel = session.syncRequest(new WriteResultRequest<Resource>(activations) {
635
636                     @Override
637                     public Resource perform(WriteGraph graph) throws DatabaseException {
638                         Layer0 L0 = Layer0.getInstance(graph);
639                         Layer0X L0X = Layer0X.getInstance(graph);
640                         Resource session = graph.newResource();
641                         graph.claim(session, L0.InstanceOf, null, L0X.Session);
642                         graph.claim(session, L0X.Session_HasUser, null, graph.getResource("http://Users/AdminUser"));
643                         graph.addLiteral(session, L0X.Session_HasClientId, L0X.Session_HasClientId_Inverse, clientId, Bindings.STRING);
644                         graph.claim(graph.getRootLibrary(), L0X.HasSession, session);
645                         return session;
646                     }
647                 });
648
649             }
650
651             session.registerService(SessionModel.class, new PlatformSessionModel(sessionModel));
652         } catch (DatabaseException e) {
653             throw new PlatformException(e);
654         }
655
656     }
657
658     static class PlatformSessionModel implements SessionModel {
659         private final Resource sessionModel;
660
661         public PlatformSessionModel(Resource model) {
662             this.sessionModel = model;
663         }
664
665         @Override
666         public Resource getResource() {
667             return sessionModel;
668         }
669     }
670
671     public void resetDatabase(IProgressMonitor monitor) throws PlatformException {
672         File dbLocation = Platform.getLocation().append("db").toFile();
673         if(!dbLocation.exists()) return;
674         try { // Load driver
675             Driver driver = Manager.getDriver("procore");
676             Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
677             management.delete();
678         } catch (DatabaseException e) {
679             throw new PlatformException("Failed to remove database at " + dbLocation.getAbsolutePath(), e);
680         }
681         // We have created extra files to database folder which have to be deleted also.
682         // This is an awful idea! Do not create extra files to database folder!
683         Throwable t = null;
684         for (int i=0; i<10; ++i) {
685             try {
686                 FileUtils.deleteAll(dbLocation);
687                 t = null;
688                 break;
689             } catch (IOException e) {
690                 // Assuming this has been thrown because delete file/folder failed.
691                 t = e;
692             }
693             try {
694                 Thread.sleep(200);
695             } catch (InterruptedException e) {
696                 // Ignoring interrupted exception.
697             }
698         }
699         if (null != t)
700             throw new PlatformException("Failed to remove database folder at " + dbLocation.getAbsolutePath(), t);
701     }
702     public void resetWorkspace(IProgressMonitor monitor, ArrayList<String> fileFilter) throws PlatformException, IllegalStateException, IOException {
703         File file = Platform.getLocation().toFile();
704         if (null != fileFilter)
705             FileUtils.deleteAllWithFilter(file , fileFilter);
706         resetDatabase(monitor);
707     }
708
709     private static Path tryGetInstallLocation() {
710         Location l = Platform.getInstallLocation();
711         return l == null ? null : new File(l.getURL().getPath()).toPath();
712     }
713
714     private Path resolveBaselineFile() throws PlatformException {
715         String dbBaselineArchive = System.getProperty("org.simantics.db.baseline", null);
716         if (dbBaselineArchive == null)
717             return null;
718
719         Path baseline = Paths.get(dbBaselineArchive);
720         if (baseline.isAbsolute()) {
721             if (!Files.isRegularFile(baseline))
722                 throw new PlatformException("Specified database baseline archive " + baseline
723                         + " does not exist. Cannot initialize workspace database from baseline.");
724             return baseline;
725         }
726
727         // Relative path resolution order:
728         // 1. from the platform "install location"
729         // 2. from working directory
730         Path installLocation = tryGetInstallLocation();
731         if (installLocation != null) {
732             Path installedBaseline = installLocation.resolve(dbBaselineArchive);
733             if (Files.isRegularFile(installedBaseline))
734                 return installedBaseline;
735         }
736         if (!Files.isRegularFile(baseline))
737             throw new PlatformException("Specified database baseline archive " + baseline
738                     + " does not exist in either the install location (" + installLocation
739                     + ") or the working directory (" + Paths.get(".").toAbsolutePath()
740                     + "). Cannot initialize workspace database.");
741         return null;
742     }
743
744     private boolean handleBaselineDatabase() throws PlatformException {
745         Path workspaceLocation = Platform.getLocation().toFile().toPath();
746         Path baselineIndicatorFile = workspaceLocation.resolve(".baselined");
747         if (Files.isRegularFile(baselineIndicatorFile)) {
748             // This means that the workspace has already been initialized from
749             // a database baseline and further initialization is not necessary.
750             return true;
751         }
752
753         Path baseline = resolveBaselineFile();
754         if (baseline == null)
755             return false;
756
757         DatabaseBaselines.validateBaselineFile(baseline);
758         DatabaseBaselines.validateWorkspaceForBaselineInitialization(workspaceLocation);
759         DatabaseBaselines.initializeWorkspaceWithBaseline(baseline, workspaceLocation, baselineIndicatorFile);
760         return true;
761     }
762
763     /**
764      * Start-up the platform. The procedure consists of 8 steps. Once everything
765      * is up and running, all fields are set property.
766      * <p>
767      *
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.
771      * <p>
772      *
773      * In Simantics Workbench this is handled in
774      * <code>SimanticsWorkbenchAdvisor#openWindows()</code>.
775      * <p>
776      *
777      * If remote server is given, simantics plaform takes connection there
778      * instead of local server at "db/".
779      *
780      * @param workspacePolicy action to take on workspace/database related
781      *        errors
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
787      */
788     public synchronized SessionContext startUp(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy,
789             OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize, PlatformUserAgent userAgent)
790     throws PlatformException
791     {
792
793         assert(!running);
794         LOGGER.info("Beginning of SimanticsPlatform.startUp");
795
796         SubMonitor monitor = SubMonitor.convert(progressMonitor, 1000);
797
798         // For debugging on what kind of platform automatic tests are running in
799         // case there are problems.
800         if ("true".equals(System.getProperty("org.simantics.dumpBundleState")))
801             dumpPlatformBundleState();
802
803         // 0. Consult all startup extensions before doing anything with the workspace.
804         StartupExtensions.consultStartupExtensions();
805         LOGGER.info("Consulted platform pre-startup extensions");
806
807         // 0.1. Clear all temporary files
808         Simantics.clearTemporaryDirectory();
809         LOGGER.info("Cleared temporary directory");
810
811         // 0.2 Clear VariableRepository.repository static map which holds references to SessionImplDb
812         VariableRepository.clear();
813
814         // 0.2.1 Activate org.simantics.scl.osgi to prime the SCL compiler early.
815         @SuppressWarnings("unused")
816         ModuleRepository modRepo = SCLOsgi.MODULE_REPOSITORY;
817
818         // 0.3 Handle baseline database before opening db
819         @SuppressWarnings("unused")
820         boolean usingBaseline = handleBaselineDatabase();
821
822         // 1. Assert there is a database at <workspace>/db
823         SessionDescriptor sessionDescriptor = setupDatabase(databaseDriverId, monitor.newChild(200, SubMonitor.SUPPRESS_NONE), workspacePolicy, userAgent);
824         session = sessionDescriptor.getSession();
825         LOGGER.info("Database setup complete");
826
827         // 2. Delete all indexes if we cannot be certain they are up-to-date
828         //    A full index rebuild will be done later, before project activation.
829         XSupport support = session.getService(XSupport.class);
830         if (support.rolledback()) {
831             try {
832                 DatabaseIndexing.deleteAllIndexes();
833             } catch (IOException e) {
834                 throw new PlatformException(e);
835             }
836         }
837
838         // 3. Assert all graphs, and correct versions, are installed to the database
839         synchronizeOntologies(monitor.newChild(400, SubMonitor.SUPPRESS_NONE), ontologyPolicy, requireSynchronize);
840
841         // 4. Assert simantics.cfg exists
842         boolean installProject = assertConfiguration(monitor.newChild(25, SubMonitor.SUPPRESS_NONE),workspacePolicy);
843
844         // 5. Assert Project Resource is installed in the database
845         installProject = assertProject(monitor.newChild(25, SubMonitor.SUPPRESS_NONE), workspacePolicy, installProject);
846
847         // 6. Install all features into project, if in debug mode
848         updateInstalledGroups(monitor.newChild(25), true); //installProject);
849         LOGGER.info("Installed all features into project");
850
851         // 7. Assert L0.Session in database for this session
852         assertSessionModel(monitor.newChild(25, SubMonitor.SUPPRESS_NONE));
853
854         session.getService(XSupport.class).setServiceMode(false, false);
855
856         try {
857             String message = "Flush query cache";
858             monitor.setTaskName(message);
859             LOGGER.info(message);
860             session.syncRequest((Write) graph -> {
861                 QueryControl qc = graph.getService(QueryControl.class);
862                 qc.flush(graph);
863             });
864         } catch (DatabaseException e) {
865             LOGGER.error("Flushing queries failed.", e);
866         }
867         boolean loadProject = true;
868         try {
869             String message = "Open database session";
870             monitor.setTaskName(message);
871             LOGGER.info(message);
872                 sessionContext = SimanticsPlatform.INSTANCE.createSessionContext(true);
873                 // This must be before setSessionContext since some listeners might query this
874             sessionContext.setHint(SimanticsKeys.KEY_PROJECT, SimanticsPlatform.INSTANCE.projectResource);
875
876             Simantics.setSessionContext(sessionContext);
877
878             // 1. Put ResourceBinding that throws an exception to General Bindings
879             message = "Put ResourceBinding that throws an exception to General Bindings";
880             LOGGER.info(message);
881             simanticsBindings = new SimanticsBindings();
882             Bindings.classBindingFactory.addFactory( simanticsBindings );
883
884             Session session = sessionContext.getSession();
885             session.registerService(Databoard.class, Bindings.databoard);
886
887             // Register datatype bindings
888             message = "Register datatype bindings";
889             LOGGER.info(message);
890             Bindings.defaultBindingFactory.getRepository().put(RGB.Integer.BINDING.type(), RGB.Integer.BINDING);
891             Bindings.defaultBindingFactory.getRepository().put(Font.BINDING.type(), Font.BINDING);
892
893             if (support.rolledback() || sessionDescriptor.isFreshDatabase()) {
894                 message = "Rebuilding all indexes";
895                 LOGGER.info(message);
896                 monitor.setTaskName(message);
897                 try {
898                     session.getService(IndexedRelations.class).fullRebuild(monitor.newChild(100), session);
899                 } catch (IndexException e) {
900                     LOGGER.error("Failed to re-build all indexes", e);
901                 }
902             } else {
903                 monitor.worked(100);
904             }
905
906             if(loadProject) {
907                 message = "Load project";
908                 monitor.setTaskName(message);
909                 LOGGER.info(message);
910                 project = Projects.loadProject(sessionContext.getSession(), SimanticsPlatform.INSTANCE.projectResource);
911                 sessionContext.setHint(ProjectKeys.KEY_PROJECT, project);
912                 monitor.worked(100);
913                 message = "Loading projects complete";
914                 LOGGER.info(message);
915
916                 message = "Activate project";
917                 monitor.setTaskName(message);
918                 LOGGER.info(message);
919                 project.activate();
920                 monitor.worked(100);
921                 LOGGER.info("Project activated");
922             }
923
924         } catch (DatabaseException e) {
925             LOGGER.error("Platform startup failed.", e);
926             throw new PlatformException(e);
927         } catch (ProjectException e) {
928             boolean hasStackTrace = e.getStackTrace().length > 0;
929             if (!hasStackTrace)
930                 throw new PlatformException(e.getMessage(), hasStackTrace);
931             throw new PlatformException(e, hasStackTrace);
932         }
933
934         running = true;
935
936         // #7650: improve shutdown robustness in all applications that use the platform
937         Runtime.getRuntime().addShutdownHook(shutdownHook);
938
939         // Discard database session undo history at this point to prevent
940         // the user from undoing any initialization operations performed
941         // by the platform startup.
942         SimanticsPlatform.INSTANCE.discardSessionUndoHistory();
943         LOGGER.info("Discarded session undo history");
944
945         return sessionContext;
946
947     }
948
949     public SessionContext createSessionContext(boolean init) throws PlatformException {
950         try {
951             // Construct and initialize SessionContext from Session.
952             SessionContext sessionContext = SessionContext.create(session, init);
953             String message = "Session context created";
954             LOGGER.info(message);
955             if (init) {
956                 sessionContext.registerServices();
957                 message = "Session services registered";
958                 LOGGER.info(message);
959             }
960             return sessionContext;
961         } catch (DatabaseException e) {
962             throw new PlatformException(e);
963         }
964     }
965
966     /**
967      * Perform normal shutdown for the Simantics Platform.
968      *
969      * @param progressMonitor optional progress monitor
970      * @throws PlatformException
971      * @see {@link #shutdown(IProgressMonitor, boolean)}
972      */
973     public synchronized void shutdown(IProgressMonitor progressMonitor) throws PlatformException {
974         shutdown(progressMonitor, true);
975     }
976
977     /**
978      * Shutdown Simantics Platform.
979      *
980      * In Simantics Workbench this is handled in
981      * <code>SimanticsWorkbenchAdvisor#disconnectFromWorkspace</code>.
982      *
983      * @param progressMonitor
984      *            optional progress monitor
985      * @param clearTemporaryFiles
986      *            allow or prevent deletion of temporary files at the end of the
987      *            shutdown procedure
988      * @throws PlatformException
989      */
990     public synchronized void shutdown(IProgressMonitor progressMonitor, boolean clearTemporaryFiles) throws PlatformException
991     {
992         SubMonitor progress = SubMonitor.convert(progressMonitor, 100);
993         PlatformException platformException = null;
994         try {
995             progress.subTask("Close Project");
996             if (project != null) {
997                 project.safeDispose();
998             }
999             progress.worked(10);
1000
1001             // NOP at the moment
1002             TimedSessionCache.close();
1003
1004             progress.subTask("Thread pools");
1005             ThreadUtils.shutdown();
1006             ExecutorWorker.shutdown();
1007             progress.worked(5);
1008
1009             running = false;
1010             progress.subTask("Close Database Session");
1011             if (sessionContext != null) {
1012                 Session s = sessionContext.peekSession();
1013                 if (s != null) {
1014                     progress.subTask("Flushing Index Caches");
1015                     try {
1016                         Simantics.flushIndexCaches(progress.newChild(20), s);
1017                     } catch (Throwable t) {
1018                         LOGGER.error("Failed to flush index caches.", t);
1019                     }
1020                 }
1021
1022                 progress.subTask("Close Database Session");
1023                 sessionContext.safeDispose();
1024                 sessionContext = null;
1025                 Simantics.setSessionContext(null);
1026             }
1027             if (simanticsBindings != null) {
1028                 Bindings.classBindingFactory.removeFactory( simanticsBindings );
1029                 simanticsBindings = null;
1030             }
1031
1032             // Make sure Simantics clipboard doesn't store unwanted session data references.
1033             Simantics.setClipboard(new SimanticsClipboardImpl());
1034
1035             progress.worked(50);
1036
1037             session = null;
1038             projectResource = null;
1039             currentDatabaseDriver = null;
1040
1041             DependenciesRelation.assertFinishedTracking();
1042
1043         } catch (Exception e) {
1044             platformException = new PlatformException("Failed to shutdown Simantics Platform", e);
1045         }
1046
1047         progress.worked(10);
1048         progress.subTask("Shutting down database");
1049         try {
1050             if (null != databasebManagement)
1051                 databasebManagement.shutdown();
1052         } catch (Throwable t) {
1053             LOGGER.error("Database shutdown failed.", t);
1054         }
1055         progress.worked(10);
1056
1057         progress.subTask("Clear index status");
1058         try {
1059             // Everything ok, clear index dirty state.
1060             DatabaseIndexing.clearAllDirty();
1061         } catch (IOException e) {
1062             LOGGER.error("Problems encountered while refreshing database index states, see exception for details.", e);
1063         }
1064         progress.worked(5);
1065
1066         if (clearTemporaryFiles) {
1067             progress.subTask("Clearing Workspace Temporary Directory");
1068             try {
1069                 Simantics.clearTemporaryDirectory();
1070             } catch (Throwable t) {
1071                 LOGGER.error("Failed to clear the temporary directory.", t);
1072             }
1073         }
1074         progress.worked(10);
1075         if (null != platformException)
1076             throw platformException;
1077
1078         // #7650: improve shutdown robustness in all applications that use the platform
1079         Runtime.getRuntime().removeShutdownHook(shutdownHook);
1080     }
1081
1082     // TODO: consider removing this in the future ??
1083     @Override
1084     public void stateChanged(LifecycleState newState) {
1085         if(newState == LifecycleState.CLOSED) {
1086             if(running) {
1087                 if(Platform.isRunning()) {
1088                     mainThread.interrupt();
1089                 }
1090             }
1091         }
1092     }
1093
1094     /**
1095      * @return <code>true</code> if discard was successful, <code>false</code>
1096      *         if there was no session, {@link UndoRedoSupport} or
1097      *         {@link UndoContext} to discard through
1098      */
1099     public boolean discardSessionUndoHistory() {
1100         Session s = session;
1101         if (s != null) {
1102             UndoRedoSupport urs = s.peekService(UndoRedoSupport.class);
1103             if (urs != null) {
1104                 UndoContext uc = urs.getUndoContext(s);
1105                 if (uc != null) {
1106                     uc.clear();
1107                     return true;
1108                 }
1109             }
1110         }
1111         return false;
1112     }
1113
1114     public void reconnect(String databaseDriverId) throws Exception {
1115         // Starts database server.
1116         if (currentDatabaseDriver != null)
1117             databaseDriverId = currentDatabaseDriver;
1118         SimanticsPlatform.INSTANCE.startUp(databaseDriverId, null, RecoveryPolicy.ThrowError, OntologyRecoveryPolicy.ThrowError, true, null);
1119     }
1120
1121     private void dumpPlatformBundleState() {
1122         BundleDescription[] bs = Platform.getPlatformAdmin().getState().getBundles();
1123         System.out.println("Total bundles: " + bs.length);
1124         for (BundleDescription b : bs) {
1125             System.out.format("%-80s @ %s\n", b.toString(), b.getLocation());
1126         }
1127     }
1128
1129     private Ini loadOrCreateDatabaseIni(Path path, String databaseDriverId)
1130             throws InvalidFileFormatException, IOException
1131     {
1132         File f = path.toFile();
1133         Ini dbIni = Files.isRegularFile(path) ? new Ini(f) : new Ini();
1134         String iniId = dbIni != null ? dbIni.get("driver", "id") : null;
1135         if (iniId == null) {
1136             dbIni.put("driver", "id", databaseDriverId);
1137             dbIni.store(f);
1138         }
1139         return dbIni;
1140     }
1141
1142 }