1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics;
14 import static org.simantics.db.common.utils.Transaction.commit;
15 import static org.simantics.db.common.utils.Transaction.endTransaction;
16 import static org.simantics.db.common.utils.Transaction.readGraph;
17 import static org.simantics.db.common.utils.Transaction.startTransaction;
18 import static org.simantics.db.common.utils.Transaction.writeGraph;
21 import java.io.IOException;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Properties;
32 import java.util.TreeMap;
33 import java.util.UUID;
35 import org.eclipse.core.runtime.ILog;
36 import org.eclipse.core.runtime.IProduct;
37 import org.eclipse.core.runtime.IProgressMonitor;
38 import org.eclipse.core.runtime.IStatus;
39 import org.eclipse.core.runtime.NullProgressMonitor;
40 import org.eclipse.core.runtime.Platform;
41 import org.eclipse.core.runtime.Status;
42 import org.eclipse.core.runtime.SubMonitor;
43 import org.eclipse.osgi.service.resolver.BundleDescription;
45 import org.ini4j.InvalidFileFormatException;
46 import org.simantics.databoard.Bindings;
47 import org.simantics.databoard.Databoard;
48 import org.simantics.datatypes.literal.Font;
49 import org.simantics.datatypes.literal.RGB;
50 import org.simantics.db.Driver;
51 import org.simantics.db.Driver.Management;
52 import org.simantics.db.Manager;
53 import org.simantics.db.ReadGraph;
54 import org.simantics.db.Resource;
55 import org.simantics.db.Session;
56 import org.simantics.db.SessionModel;
57 import org.simantics.db.UndoContext;
58 import org.simantics.db.VirtualGraph;
59 import org.simantics.db.WriteGraph;
60 import org.simantics.db.common.request.ObjectsWithType;
61 import org.simantics.db.common.request.Queries;
62 import org.simantics.db.common.request.WriteRequest;
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.util.SimanticsClipboardImpl;
71 import org.simantics.db.layer0.util.SimanticsKeys;
72 import org.simantics.db.layer0.util.TGTransferableGraphSource;
73 import org.simantics.db.layer0.variable.VariableRepository;
74 import org.simantics.db.management.SessionContext;
75 import org.simantics.db.request.Read;
76 import org.simantics.db.service.LifecycleSupport.LifecycleListener;
77 import org.simantics.db.service.LifecycleSupport.LifecycleState;
78 import org.simantics.db.service.QueryControl;
79 import org.simantics.db.service.UndoRedoSupport;
80 import org.simantics.db.service.VirtualGraphSupport;
81 import org.simantics.db.service.XSupport;
82 import org.simantics.graph.db.GraphDependencyAnalyzer;
83 import org.simantics.graph.db.GraphDependencyAnalyzer.IU;
84 import org.simantics.graph.db.GraphDependencyAnalyzer.IdentityNode;
85 import org.simantics.graph.db.IImportAdvisor;
86 import org.simantics.graph.db.ImportResult;
87 import org.simantics.graph.db.TransferableGraphs;
88 import org.simantics.graph.diff.Diff;
89 import org.simantics.graph.diff.TransferableGraphDelta1;
90 import org.simantics.internal.Activator;
91 import org.simantics.internal.startup.StartupExtensions;
92 import org.simantics.layer0.Layer0;
93 import org.simantics.operation.Layer0X;
94 import org.simantics.project.IProject;
95 import org.simantics.project.ProjectFeatures;
96 import org.simantics.project.ProjectKeys;
97 import org.simantics.project.Projects;
98 import org.simantics.project.exception.ProjectException;
99 import org.simantics.project.features.registry.GroupReference;
100 import org.simantics.project.management.DatabaseManagement;
101 import org.simantics.project.management.GraphBundle;
102 import org.simantics.project.management.GraphBundleEx;
103 import org.simantics.project.management.GraphBundleRef;
104 import org.simantics.project.management.PlatformUtil;
105 import org.simantics.project.management.ServerManager;
106 import org.simantics.project.management.ServerManagerFactory;
107 import org.simantics.project.management.WorkspaceUtil;
108 import org.simantics.utils.FileUtils;
109 import org.simantics.utils.datastructures.Pair;
110 import org.simantics.utils.logging.TimeLogger;
111 import org.simantics.utils.strings.EString;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
116 * SimanticsPlatform performs procedures required in order to get simantics
117 * workbench into operational state. This consists of the following steps:
119 * <li> Asserting there is Database
121 * <li> Starting Database process
123 * <li> Opening a session to Database process
125 * <li> Asserting required ontologies or other transferable graphs are installed in the database
127 * <li> Asserting required project is installed in the database
129 * <li> Asserting Simantics Features are installed in the database
131 * <li> Asserting Simantics Features are installed to the project
133 * <li> Shutdown: Save Session, Close session, Kill Database process
137 * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
139 public class SimanticsPlatform implements LifecycleListener {
141 private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsPlatform.class);
144 * The policy is relevant when developing Simantics from Eclipse IDE.
145 * It is applied when the ontology in the database of a workspace doesn't match
146 * a newer ontology in the Eclipse workspace.
148 public static enum OntologyRecoveryPolicy { ThrowError, Merge, ReinstallDatabase }
151 * This policy dictates how the Simantics platform startup should react if
152 * the started workspace is not set up properly. The alternatives are to
153 * just throw an error and fail or to attempt all possible measures to fix
154 * the encountered problems.
156 public static enum RecoveryPolicy { ThrowError, FixError }
158 /** Singleton instance, started in SimanticsWorkbenchAdvisor */
159 public static final SimanticsPlatform INSTANCE = new SimanticsPlatform();
161 /** Set to true when the Simantics Platform is in good-and-go condition */
162 public boolean running;
164 /** ID of the database driver that the platform is currently using */
165 private String currentDatabaseDriver;
167 /** Database Session */
168 public Session session;
169 private Management databasebManagement;
171 /** Database session context */
172 public SessionContext sessionContext;
174 /** Project identifier in Database */
175 public String projectURI;
178 public String projectName;
180 /** Project resource */
181 public Resource projectResource;
183 /** Session specific bindings */
184 public SimanticsBindings simanticsBindings;
185 public SimanticsBindings simanticsBindings2;
187 public Thread mainThread;
190 * The {@link IProject} activated by
191 * {@link #startUp(IProgressMonitor, RecoveryPolicy, OntologyRecoveryPolicy, ServerAddress, PlatformUserAgent)}
193 private IProject project;
198 * Create a new simantics plaform manager in uninitialized state and
199 * with default policies. <p>
201 public SimanticsPlatform() {
202 log = Platform.getLog(Activator.getBundleContext().getBundle());
203 mainThread = Thread.currentThread();
206 public String getApplicationClientId() {
207 IProduct product = Platform.getProduct();
208 if(product == null) return "noProduct";//UUID.randomUUID().toString();
209 String application = product.getApplication();
210 return application != null ? application : UUID.randomUUID().toString();
213 private Session setupDatabase(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, PlatformUserAgent userAgent) throws PlatformException {
214 if (progressMonitor == null)
215 progressMonitor = new NullProgressMonitor();
216 Path workspaceLocation = Platform.getLocation().toFile().toPath();
217 Path dbLocation = workspaceLocation.resolve("db");
218 Path dbIniPath = workspaceLocation.resolve("db.ini");
219 // The driver file overrides any command line arguments to prevent
220 // using the wrong driver for an existing database directory.
221 ServerManager serverManager;
223 Ini dbIni = loadOrCreateDatabaseIni(dbIniPath, databaseDriverId);
224 databaseDriverId = dbIni.get("driver", "id");
225 serverManager = ServerManagerFactory.create(databaseDriverId, dbLocation.toAbsolutePath().toString());
226 } catch (DatabaseException | IOException e) {
227 throw new PlatformException("Failed to initialize database ServerManager with driver " + databaseDriverId, e);
229 progressMonitor.beginTask("Setting up Simantics Database", 100);
230 progressMonitor.setTaskName("Asserting Database is installed.");
231 String msg = "Failed to initialize Simantics database.";
234 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Initializing database at " + dbLocation + " with driver " + databaseDriverId));
235 progressMonitor.setTaskName("Creating database at " + dbLocation);
236 databasebManagement = serverManager.getManagement(dbLocation.toFile());
237 databasebManagement.create();
238 currentDatabaseDriver = databaseDriverId;
240 return serverManager.createDatabase(dbLocation.toFile());
241 } catch (DatabaseException e) {
242 throw new PlatformException(msg, e);
243 } catch (Throwable e) {
244 throw new PlatformException(msg, e);
246 progressMonitor.worked(20);
250 public void synchronizeOntologies(IProgressMonitor progressMonitor, OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize) throws PlatformException {
252 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
254 final DatabaseManagement mgmt = new DatabaseManagement();
256 PlatformUtil.compileAllDynamicOntologies();
258 progressMonitor.setTaskName("Asserting all ontologies are installed");
259 final Map<GraphBundleRef, GraphBundleEx> platformTGs = new HashMap<GraphBundleRef, GraphBundleEx>();
262 // Get a list of bundles installed into the database
263 progressMonitor.subTask("find installed bundles from database");
264 Map<GraphBundleRef, GraphBundleEx> installedTGs = new HashMap<GraphBundleRef, GraphBundleEx>();
265 for (GraphBundle b : session.syncRequest( mgmt.GraphBundleQuery )) {
266 installedTGs.put(GraphBundleRef.of(b), GraphBundleEx.extend(b));
269 if(!requireSynchronize && installedTGs.size() > 1 && !Platform.inDevelopmentMode()) return;
270 // if(installedTGs.size() > 1) return;
272 // Get a list of all bundles in the platform (Bundle Context)
273 List<GraphBundle> tgs = new ArrayList<GraphBundle>();
274 progressMonitor.subTask("load all transferable graphs from platform");
275 PlatformUtil.getAllGraphs(tgs);
276 progressMonitor.subTask("extend bundles to compile versions");
277 for (GraphBundle b : tgs) {
278 GraphBundleEx gbe = GraphBundleEx.extend(b);
280 platformTGs.put(GraphBundleRef.of(b), gbe);
283 // Compile a list of TGs that need to be installed or reinstalled in the database
284 progressMonitor.subTask("check bundle reinstallation demand");
285 List<GraphBundleEx> installTGs = new ArrayList<GraphBundleEx>();
286 // Create list of TGs to update, <newTg, oldTg>
287 Map<GraphBundleEx,GraphBundleEx> reinstallTGs = new TreeMap<GraphBundleEx,GraphBundleEx>();
288 for (Entry<GraphBundleRef, GraphBundleEx> e : platformTGs.entrySet()) {
289 GraphBundleRef key = e.getKey();
290 GraphBundleEx platformBundle = e.getValue();
291 GraphBundleEx existingBundle = installedTGs.get(key);
293 // System.out.println("GraphBundleRef key=" + key.toString());
295 if (existingBundle == null) {
296 // Bundle did not exist in the database, put it into list of bundles to install
297 installTGs.add(platformBundle);
300 // Bundle exists in the database
301 boolean platformBundleIsNewer = existingBundle.getVersion().compareTo(platformBundle.getVersion())<0;
302 if (!platformBundleIsNewer)
304 // Check hash of transferable graph to know whether to update or not.
305 if (platformBundle.getHashcode() == existingBundle.getHashcode())
307 //System.out.println("Ontology hashcodes do not match: platform bundle="
308 // + platformBundle.getVersionedId() + ", hash=" + platformBundle.getHashcode()
309 // + "; existing bundle=" + existingBundle.getVersionedId() + ", hash=" + existingBundle.getHashcode());
310 reinstallTGs.put(platformBundle, existingBundle);
314 // Database is missing graphs
315 if (!installTGs.isEmpty() || !reinstallTGs.isEmpty()) {
316 session.getService(XSupport.class).setServiceMode(true, true);
319 if (ontologyPolicy == OntologyRecoveryPolicy.ThrowError) {
320 StringBuilder sb = new StringBuilder("The following graphs are not installed in the database: ");
321 if (!installTGs.isEmpty()) {
323 for (GraphBundleEx e : installTGs) {
324 if (i>0) sb.append(", ");
326 sb.append(e.toString());
328 sb.append(" is missing from the database.\n");
330 if (!reinstallTGs.isEmpty()) {
332 for (Entry<GraphBundleEx, GraphBundleEx> e : reinstallTGs.entrySet()) {
333 if (i>0) sb.append(", ");
335 sb.append(e.getKey().toString());
337 sb.append(" Database/Platform Bundle version mismatch.\n");
339 sb.append("Hint: Use -fixErrors to install the graphs.");
340 throw new PlatformException(sb.toString());
342 // Reinstall database
343 if (ontologyPolicy == OntologyRecoveryPolicy.ReinstallDatabase) {
344 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Reinstalling the database."));
353 throw new PlatformException("Reinstalling Database, NOT IMPLEMENTED");
356 if (ontologyPolicy == OntologyRecoveryPolicy.Merge) {
357 progressMonitor.subTask("Merging ontology changes");
358 // Sort missing TGs into install order
359 GraphDependencyAnalyzer<GraphBundle> analyzer = new GraphDependencyAnalyzer<GraphBundle>();
360 for(GraphBundle tg : installTGs) analyzer.addGraph(tg, tg.getGraph());
361 for(GraphBundle tg : reinstallTGs.keySet()) analyzer.addGraph(tg, tg.getGraph());
362 if(!analyzer.analyzeDependency()) {
363 Collection<Pair<GraphBundle, GraphBundle>> problems = analyzer.getConflicts();
364 StringBuilder sb = new StringBuilder();
365 for (Pair<GraphBundle, GraphBundle> problem : problems) {
366 sb.append("Conflict with "+problem.first+" and "+problem.second+".\n");
368 throw new PlatformException(sb.toString());
370 else if(!session.syncRequest( analyzer.queryExternalDependenciesSatisfied )) {
371 Collection<IdentityNode> unsatisfiedDependencies = analyzer.getUnsatisfiedDependencies();
372 StringBuilder sb = new StringBuilder();
373 for (IdentityNode dep: unsatisfiedDependencies) {
374 sb.append("Unsatisfied Dependency "+dep+". Required by\n");
375 for(IU iu : GraphDependencyAnalyzer.toCollection(dep.getRequires())) {
376 sb.append(" " + ((GraphBundle)iu.getId()).getId() + "\n");
379 throw new PlatformException(sb.toString());
382 List<GraphBundle> sortedBundles = analyzer.getSortedGraphs();
383 if(!sortedBundles.isEmpty()) {
385 session.syncRequest(new WriteRequest() {
387 public void perform(WriteGraph graph) throws DatabaseException {
389 graph.newClusterSet(graph.getRootLibrary());
390 } catch (ClusterSetExistException e) {
391 // Cluster set exist already, no problem.
393 graph.setClusterSet4NewResource(graph.getRootLibrary());
394 graph.flushCluster();
398 boolean mergedOntologies = false;
401 for(final GraphBundle tg : sortedBundles) {
403 final IImportAdvisor advisor = new OntologyImportAdvisor(tg, mgmt);
404 final GraphBundle oldTG = reinstallTGs.get(tg);
408 boolean createImmutable = tg.getImmutable();
409 session.getService(XSupport.class).setServiceMode(true, createImmutable);
412 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Installing "+tg.toString()+" - "+tg.getName()));
413 ImportResult result = TransferableGraphs.importGraph1(session, new TGTransferableGraphSource(tg.getGraph()), advisor, null);
414 if (!result.missingExternals.isEmpty()) {
415 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import of " + tg.toString() + " was missing the following external entities:\n" + EString.implode(result.missingExternals)));
419 startTransaction(session, false);
420 TransferableGraphDelta1 delta = new Diff(oldTG.getGraph(), tg.getGraph()).diff();
421 final long[] oldResources = oldTG.getResourceArray();
422 boolean changes = TransferableGraphs.hasChanges(readGraph(), oldResources, delta);
425 //log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Nothing to merge for "+tg.toString()));
429 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Merging new version of "+tg.toString()));
431 startTransaction(session, true);
437 long[] resourceArray = TransferableGraphs.applyDelta(writeGraph(), oldResources, delta);
438 tg.setResourceArray(resourceArray);
439 mgmt.setGraphBundleEntry(tg);
441 mergedOntologies = true;
442 } catch (Throwable t) {
443 throw new PlatformException(t);
450 session.syncRequest(new WriteRequest() {
452 public void perform(WriteGraph graph) throws DatabaseException {
453 graph.setClusterSet4NewResource(graph.getRootLibrary());
454 graph.flushCluster();
458 if (mergedOntologies)
459 DatabaseIndexing.deleteAllIndexes();
462 TimeLogger.log("Ontologies synchronized.");
465 session.getService(XSupport.class).setServiceMode(false, false);
467 progressMonitor.worked(20);
468 } catch (IOException e) {
469 throw new PlatformException(e);
470 } catch (DatabaseException e) {
471 throw new PlatformException(e);
476 public boolean assertConfiguration(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy) throws PlatformException {
478 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
480 File workspaceLocation = Platform.getLocation().toFile();
482 boolean installProject = false;
483 progressMonitor.setTaskName("Asserting simantics.cfg is installed");
485 File propertyFile = new File(workspaceLocation, "simantics.cfg");
486 Properties properties;
488 properties = WorkspaceUtil.readProperties(propertyFile);
489 } catch (IOException e) {
490 if (workspacePolicy == RecoveryPolicy.ThrowError) throw new PlatformException("Could not load "+propertyFile);
492 // Create a project and write Property file
493 properties = new Properties();
494 properties.setProperty("project_uri", "http://Projects/Development%20Project");
495 properties.setProperty("project_name", "Development Project");
496 WorkspaceUtil.writeProperties(propertyFile, properties);
497 installProject |= true;
499 projectURI = properties.getProperty("project_uri");
500 projectName = properties.getProperty("project_name");
501 progressMonitor.worked(10);
502 } catch (IOException e) {
503 throw new PlatformException(e);
506 return installProject;
510 public boolean assertProject(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, boolean installProject) throws PlatformException {
512 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
514 final DatabaseManagement mgmt = new DatabaseManagement();
516 progressMonitor.setTaskName("Asserting project resource exists in the database");
518 projectResource = session.syncRequest( Queries.resource( projectURI ) );
519 } catch (ResourceNotFoundException nfe) {
520 // Project was not found
521 if (workspacePolicy == RecoveryPolicy.ThrowError)
522 throw new PlatformException("Project Resource "+projectURI+" is not found in the database.");
523 // Create empty project with no features
525 Transaction.startTransaction(session, true);
527 // The project needs to be created mutable.
528 session.getService(XSupport.class).setServiceMode(true, false);
530 ArrayList<String> empty = new ArrayList<String>();
531 projectResource = mgmt.createProject(projectName, empty);
532 installProject |= true;
534 session.getService(XSupport.class).setServiceMode(false, false);
535 Transaction.commit();
537 Transaction.endTransaction();
539 //session.getService( LifecycleSupport.class ).save();
540 } catch (DatabaseException e) {
541 throw new PlatformException("Failed to create "+projectURI, e);
543 } catch (DatabaseException e) {
544 throw new PlatformException("Failed to create "+projectURI, e);
546 progressMonitor.worked(10);
548 return installProject;
552 public void updateInstalledGroups(IProgressMonitor progressMonitor, boolean installProject) throws PlatformException {
556 // Attach all feature groups available in platform to created project
557 progressMonitor.setTaskName("Install all features");
558 Set<GroupReference> publishedFeatureGroups = ProjectFeatures.getInstallGroupsOfPublishedFeatures();
559 Collection<GroupReference> groupsWithoutVersion = GroupReference.stripVersions(publishedFeatureGroups);
561 // final List<String> Platform_Features = new ArrayList<String>();
563 // // Convert graph instances
564 // Collection<TransferableGraph1> platformGraphs = new ArrayList<TransferableGraph1>();
565 // for (GraphBundleEx e : platformTGs.values()) platformGraphs.add( e.getGraph() );
566 // IGraph graph = Graphs.createGraph(platformGraphs);
568 // Res PublishedProjectFeatures = UriUtils.uriToPath( ProjectResource.URIs.PublishedProjectFeatures );
569 // Path HasFeature = UriUtils.uriToPath( ProjectResource.URIs.HasFeature );
570 // for(Res feature : graph.getObjects(PublishedProjectFeatures, HasFeature)) {
571 // System.out.println("Installing Project Feature: "+feature.toString());
572 // Platform_Features.add( feature.toString() );
576 Transaction.startTransaction(session, true);
578 // for (String feature : Platform_Features) {
580 // getResource(feature);
581 // } catch(ResourceNotFoundException e) {
582 // System.out.println(feature+" not found");
584 // mgmt.installFeature(projectResource, feature);
586 Projects.setProjectInstalledGroups(writeGraph(), projectResource, groupsWithoutVersion);
587 Transaction.commit();
589 Transaction.endTransaction();
591 //session.getService( LifecycleSupport.class ).save();
592 } catch(DatabaseException ae) {
593 throw new PlatformException("Failed to install features", ae);
595 progressMonitor.worked(10);
600 public void assertSessionModel(IProgressMonitor progressMonitor) throws PlatformException {
602 Properties properties = session.getService(Properties.class);
603 final String clientId = properties.getProperty("clientId");
607 // Currently this needs to be done before data becomes available
608 VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
609 VirtualGraph activations = support.getWorkspacePersistent("activations");
611 Resource sessionModel = session.syncRequest(new Read<Resource>() {
614 public Resource perform(ReadGraph graph) throws DatabaseException {
616 Layer0X L0X = Layer0X.getInstance(graph);
617 for(Resource sessionModel : graph.syncRequest(new ObjectsWithType(graph.getRootLibrary(), L0X.HasSession, L0X.Session))) {
618 String id = graph.getPossibleRelatedValue(sessionModel, L0X.Session_HasClientId);
619 if(id != null && id.equals(clientId)) return sessionModel;
627 if(sessionModel == null) {
629 sessionModel = session.syncRequest(new WriteResultRequest<Resource>(activations) {
632 public Resource perform(WriteGraph graph) throws DatabaseException {
633 Layer0 L0 = Layer0.getInstance(graph);
634 Layer0X L0X = Layer0X.getInstance(graph);
635 Resource session = graph.newResource();
636 graph.claim(session, L0.InstanceOf, null, L0X.Session);
637 graph.claim(session, L0X.Session_HasUser, null, graph.getResource("http://Users/AdminUser"));
638 graph.addLiteral(session, L0X.Session_HasClientId, L0X.Session_HasClientId_Inverse, clientId, Bindings.STRING);
639 graph.claim(graph.getRootLibrary(), L0X.HasSession, session);
646 session.registerService(SessionModel.class, new PlatformSessionModel(sessionModel));
647 } catch (DatabaseException e) {
648 throw new PlatformException(e);
653 static class PlatformSessionModel implements SessionModel {
654 private final Resource sessionModel;
656 public PlatformSessionModel(Resource model) {
657 this.sessionModel = model;
661 public Resource getResource() {
666 public void resetDatabase(IProgressMonitor monitor) throws PlatformException {
667 File dbLocation = Platform.getLocation().append("db").toFile();
668 if(!dbLocation.exists()) return;
670 Driver driver = Manager.getDriver("procore");
671 Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
673 } catch (DatabaseException e) {
674 throw new PlatformException("Failed to remove database at " + dbLocation.getAbsolutePath(), e);
676 // We have created extra files to database folder which have to be deleted also.
677 // This is an awful idea! Do not create extra files to database folder!
679 for (int i=0; i<10; ++i) {
681 FileUtils.deleteAll(dbLocation);
684 } catch (IOException e) {
685 // Assuming this has been thrown because delete file/folder failed.
690 } catch (InterruptedException e) {
691 // Ignoring interrupted exception.
695 throw new PlatformException("Failed to remove database folder at " + dbLocation.getAbsolutePath(), t);
697 public void resetWorkspace(IProgressMonitor monitor, ArrayList<String> fileFilter) throws PlatformException, IllegalStateException, IOException {
698 File file = Platform.getLocation().toFile();
699 if (null != fileFilter)
700 FileUtils.deleteAllWithFilter(file , fileFilter);
701 resetDatabase(monitor);
705 * Start-up the platform. The procedure consists of 8 steps. Once everything
706 * is up and running, all fields are set property.
709 * If workspacePolicy is FixErrors, there is an attempt to fix unexpected
710 * errors. It includes installing database files, installing ontologies, and
711 * installing project features.
714 * In SWB this is handled in SimanticsWorkbenchAdvisor#openWindows().
717 * If remote server is given, simantics plaform takes connection there
718 * instead of local server at "db/".
720 * @param workspacePolicy action to take on workspace/database related
722 * @param ontologyPolicy action to take on ontology mismatch
723 * @param progressMonitor optional progress monitor
724 * @param userAgent interface for resorting to user feedback during platform
725 * startup or <code>null</code> to resort to default measures
726 * @throws PlatformException
728 public SessionContext startUp(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy,
729 OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize, PlatformUserAgent userAgent)
730 throws PlatformException
734 TimeLogger.log("Beginning of SimanticsPlatform.startUp");
736 LOGGER.info("Beginning of SimanticsPlatform.startUp");
738 if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
740 // For debugging on what kind of platform automatic tests are running in
741 // case there are problems.
742 if ("true".equals(System.getProperty("org.simantics.dumpBundleState")))
743 dumpPlatformBundleState();
745 // 0. Consult all startup extensions before doing anything with the workspace.
746 StartupExtensions.consultStartupExtensions();
747 TimeLogger.log("Consulted platform pre-startup extensions");
749 // 0.1. Clear all temporary files
750 Simantics.clearTemporaryDirectory();
751 TimeLogger.log("Cleared temporary directory");
753 // 0.2 Clear VariableRepository.repository static map which holds references to SessionImplDb
754 VariableRepository.clear();
756 // 1. Assert there is a database at <workspace>/db
757 session = setupDatabase(databaseDriverId, progressMonitor, workspacePolicy, userAgent);
758 TimeLogger.log("Database setup complete");
761 XSupport support = session.getService(XSupport.class);
762 if (support.rolledback()) {
764 DatabaseIndexing.deleteAllIndexes();
765 } catch (IOException e) {
766 throw new PlatformException(e);
770 // 2. Assert all graphs, and correct versions, are installed to the database
771 synchronizeOntologies(progressMonitor, ontologyPolicy, requireSynchronize);
772 TimeLogger.log("Synchronized ontologies");
774 // 4. Assert simantics.cfg exists
775 boolean installProject = assertConfiguration(progressMonitor,workspacePolicy);
777 // 5. Assert Project Resource is installed in the database
778 installProject = assertProject(progressMonitor, workspacePolicy, installProject);
780 // 6. Install all features into project, if in debug mode
781 updateInstalledGroups(progressMonitor, installProject);
782 TimeLogger.log("Installed all features into project");
784 // 7. Assert L0.Session in database for this session
785 assertSessionModel(progressMonitor);
787 session.getService(XSupport.class).setServiceMode(false, false);
790 session.sync(new WriteRequest() {
793 public void perform(WriteGraph graph) throws DatabaseException {
794 QueryControl qc = graph.getService(QueryControl.class);
799 TimeLogger.log("Flushed queries");
800 } catch (DatabaseException e) {
801 LOGGER.error("Flushing queries failed.", e);
803 boolean loadProject = true;
806 sessionContext = SimanticsPlatform.INSTANCE.createSessionContext(true);
807 // This must be before setSessionContext since some listeners might query this
808 sessionContext.setHint(SimanticsKeys.KEY_PROJECT, SimanticsPlatform.INSTANCE.projectResource);
810 Simantics.setSessionContext(sessionContext);
812 // 1. Put ResourceBinding that throws an exception to General Bindings
813 simanticsBindings = new SimanticsBindings( null );
814 Bindings.classBindingFactory.addFactory( simanticsBindings );
817 // 2. Create session-specific second Binding context (Databoard) and
818 // put that to Session as a service
819 Session session = sessionContext.getSession();
820 Databoard sessionDataboard = new Databoard();
821 session.registerService(Databoard.class, sessionDataboard);
822 simanticsBindings2 = new SimanticsBindings( session );
823 sessionDataboard.classBindingFactory.addFactory( simanticsBindings2 );
825 // Register datatype bindings
826 Bindings.defaultBindingFactory.getRepository().put(RGB.Integer.BINDING.type(), RGB.Integer.BINDING);
827 Bindings.defaultBindingFactory.getRepository().put(Font.BINDING.type(), Font.BINDING);
831 TimeLogger.log("Load projects");
832 project = Projects.loadProject(sessionContext.getSession(), SimanticsPlatform.INSTANCE.projectResource);
834 sessionContext.setHint(ProjectKeys.KEY_PROJECT, project);
835 TimeLogger.log("Loading projects complete");
838 TimeLogger.log("Project activated");
841 } catch (DatabaseException e) {
842 LOGGER.error("Platform startup failed.", e);
843 throw new PlatformException(e);
844 } catch (ProjectException e) {
845 boolean hasStackTrace = e.getStackTrace().length > 0;
847 throw new PlatformException(e.getMessage(), hasStackTrace);
848 throw new PlatformException(e, hasStackTrace);
853 return sessionContext;
857 public SessionContext createSessionContext(boolean init) throws PlatformException {
859 // Construct and initialize SessionContext from Session.
860 SessionContext sessionContext = SessionContext.create(session, init);
862 sessionContext.registerServices();
863 return sessionContext;
864 } catch (DatabaseException e) {
865 throw new PlatformException(e);
869 // private static File getIgnorePrerequisitesFile(URL workspaceUrl) {
870 // if (workspaceUrl == null)
872 // return new File(workspaceUrl.getPath(), ".ignorePrerequisites");
875 // private void ensurePrerequisites(IProgressMonitor progressMonitor, PlatformUserAgent userAgent) throws PlatformException {
876 // Location loc = Platform.getInstanceLocation();
877 // File ignorePrerequisites = getIgnorePrerequisitesFile(loc.getURL());
878 // if (loc.isSet() && ignorePrerequisites != null) {
879 // if (ignorePrerequisites.exists() || ignorePrerequisites.isFile())
884 // ServerEnvironment.ensureServerDependenciesMet();
885 // } catch (ExecutionEnvironmentException e) {
886 // // Not installed properly, ask user whether to try installation.
888 // StringBuilder msg = new StringBuilder();
889 // msg.append("Your system seems to be missing the following prerequisites for running this application:\n\n");
890 // for (Product product : e.requiredProducts)
891 // msg.append("\t" + product.getDescription() + "\n");
892 // msg.append("\nYou can either install the missing components now or ignore and attempt to start the application without them. Ignore Always will ignore this question for this workspace.");
893 // msg.append("\n\nSelecting Cancel will close the application.");
895 // int selection = 0;
896 // if (userAgent != null) {
897 // selection = userAgent.showPrompt("Missing Prerequisites", msg.toString(), new String[] {
898 // "Install Pre-requisites",
904 // boolean tryInstall = false;
905 // switch (selection) {
907 // tryInstall = true;
910 // ignorePrerequisites.createNewFile();
915 // throw new CancelStartupException();
919 // // Try to install it and check for success afterwards.
920 // ServerEnvironment.tryInstallDependencies(progressMonitor);
921 // ServerEnvironment.ensureServerDependenciesMet();
923 // } catch (InstallException ie) {
924 // throw new PlatformException(ie);
925 // } catch (ExecutionEnvironmentException eee) {
926 // throw new PlatformException(eee);
927 // } catch (IOException ie) {
928 // throw new PlatformException(ie);
934 * Shutdown Simantics Platform.
936 * In SWB this is handled in SimanticsWorkbenchAdvisor#disconnectFromWorkspace.
938 * @param progressMonitor optional progress monitor
939 * @throws PlatformException
941 public void shutdown(IProgressMonitor progressMonitor) throws PlatformException
943 SubMonitor progress = SubMonitor.convert(progressMonitor, 100);
944 PlatformException platformException = null;
946 progress.subTask("Close Project");
947 if (project != null) {
948 project.safeDispose();
953 progress.subTask("Close Database Session");
954 Databoard databoard = null;
955 if (sessionContext != null) {
956 Session s = sessionContext.peekSession();
958 databoard = s.peekService(Databoard.class);
960 progress.subTask("Flushing Index Caches");
962 Simantics.flushIndexCaches(progress.newChild(20), s);
963 } catch (Throwable t) {
964 LOGGER.error("Failed to flush index caches.", t);
968 progress.subTask("Close Database Session");
969 sessionContext.safeDispose();
970 sessionContext = null;
971 Simantics.setSessionContext(null);
973 if (simanticsBindings != null) {
974 Bindings.classBindingFactory.removeFactory( simanticsBindings );
975 simanticsBindings = null;
977 if (databoard != null) {
978 if (simanticsBindings2 != null) {
979 databoard.classBindingFactory.removeFactory( simanticsBindings2 );
980 simanticsBindings2 = null;
985 // Make sure Simantics clipboard doesn't store unwanted session data references.
986 Simantics.setClipboard(new SimanticsClipboardImpl());
991 projectResource = null;
992 currentDatabaseDriver = null;
994 DependenciesRelation.assertFinishedTracking();
996 } catch (Exception e) {
997 platformException = new PlatformException("Failed to shutdown Simantics Platform", e);
1000 progress.worked(10);
1001 progress.subTask("Shutting down database");
1003 if (null != databasebManagement)
1004 databasebManagement.shutdown();
1005 } catch (Throwable t) {
1006 LOGGER.error("Database shutdown failed.", t);
1008 progress.worked(10);
1010 progress.subTask("Clearing Workspace Temporary Directory");
1012 Simantics.clearTemporaryDirectory();
1013 } catch (Throwable t) {
1014 LOGGER.error("Failed to clear the temporary directory.", t);
1016 progress.worked(10);
1017 if (null != platformException)
1018 throw platformException;
1021 // TODO: consider removing this in the future ??
1023 public void stateChanged(LifecycleState newState) {
1024 if(newState == LifecycleState.CLOSED) {
1026 if(Platform.isRunning()) {
1027 mainThread.interrupt();
1034 * @return <code>true</code> if discard was successful, <code>false</code>
1035 * if there was no session, {@link UndoRedoSupport} or
1036 * {@link UndoContext} to discard through
1038 public boolean discardSessionUndoHistory() {
1039 Session s = session;
1041 UndoRedoSupport urs = s.peekService(UndoRedoSupport.class);
1043 UndoContext uc = urs.getUndoContext(s);
1053 public void reconnect(String databaseDriverId) throws Exception {
1054 // Starts database server.
1055 if (currentDatabaseDriver != null)
1056 databaseDriverId = currentDatabaseDriver;
1057 SimanticsPlatform.INSTANCE.startUp(databaseDriverId, null, RecoveryPolicy.ThrowError, OntologyRecoveryPolicy.ThrowError, true, null);
1060 private void dumpPlatformBundleState() {
1061 BundleDescription[] bs = Platform.getPlatformAdmin().getState().getBundles();
1062 System.out.println("Total bundles: " + bs.length);
1063 for (BundleDescription b : bs) {
1064 System.out.format("%-80s @ %s\n", b.toString(), b.getLocation());
1068 private Ini loadOrCreateDatabaseIni(Path path, String databaseDriverId)
1069 throws InvalidFileFormatException, IOException
1071 File f = path.toFile();
1072 Ini dbIni = Files.isRegularFile(path) ? new Ini(f) : new Ini();
1073 String iniId = dbIni != null ? dbIni.get("driver", "id") : null;
1074 if (iniId == null) {
1075 dbIni.put("driver", "id", databaseDriverId);