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