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