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