1 /*******************************************************************************
2 * Copyright (c) 2012 Association for Decentralized Information Management in
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.db.layer0.migration;
14 import java.io.Closeable;
16 import java.io.IOException;
17 import java.text.DateFormat;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Date;
21 import java.util.HashMap;
24 import org.eclipse.core.runtime.IProgressMonitor;
25 import org.simantics.databoard.Bindings;
26 import org.simantics.databoard.binding.mutable.Variant;
27 import org.simantics.databoard.container.DataContainer;
28 import org.simantics.databoard.container.DataContainers;
29 import org.simantics.db.ReadGraph;
30 import org.simantics.db.Resource;
31 import org.simantics.db.Session;
32 import org.simantics.db.WriteGraph;
33 import org.simantics.db.WriteOnlyGraph;
34 import org.simantics.db.common.request.WriteResultRequest;
35 import org.simantics.db.common.utils.Logger;
36 import org.simantics.db.exception.AssumptionException;
37 import org.simantics.db.exception.DatabaseException;
38 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
39 import org.simantics.db.layer0.internal.SimanticsInternal;
40 import org.simantics.db.layer0.util.Layer0Utils;
41 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
42 import org.simantics.db.layer0.util.TGProgressMonitor;
43 import org.simantics.db.layer0.util.TGTransferableGraphSource;
44 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
45 import org.simantics.db.request.Read;
46 import org.simantics.db.service.ManagementSupport;
47 import org.simantics.db.service.SerialisationSupport;
48 import org.simantics.graph.db.IImportAdvisor;
49 import org.simantics.graph.db.IImportAdvisor2;
50 import org.simantics.graph.db.StreamingTransferableGraphFileReader;
51 import org.simantics.graph.db.TGStatusMonitor;
52 import org.simantics.graph.db.TransferableGraphImporter;
53 import org.simantics.graph.db.TransferableGraphSource;
54 import org.simantics.graph.db.TransferableGraphs;
55 import org.simantics.graph.db.WrapperAdvisor;
56 import org.simantics.graph.representation.TransferableGraph1;
57 import org.simantics.graph.representation.TransferableGraphFileReader;
58 import org.simantics.layer0.Layer0;
59 import org.simantics.utils.logging.TimeLogger;
61 public class MigrationStateImpl implements MigrationState {
63 final private HashMap<String, Object> properties = new HashMap<String, Object>();
65 @SuppressWarnings("unchecked")
67 public <T> T probeProperty(String key) throws DatabaseException {
68 return (T)properties.get(key);
71 @SuppressWarnings("unchecked")
73 public <T> T getProperty(String key) throws DatabaseException {
75 T property = (T)properties.get(key);
76 if(property != null) return property;
78 if(MigrationStateKeys.BASE_URI.equals(key)) {
79 throw new IllegalStateException("Base URI needs to be supplied for migration.");
80 } else if (MigrationStateKeys.SESSION.equals(key)) {
81 throw new IllegalStateException("Session needs to be supplied for migration.");
82 } else if (MigrationStateKeys.MODEL_FILE.equals(key)) {
83 throw new IllegalStateException("Model file needs to be supplied for migration.");
84 } else if (MigrationStateKeys.CURRENT_TG.equals(key)) {
86 final Resource resource = probeProperty(MigrationStateKeys.CURRENT_RESOURCE);
87 final Collection<Resource> roots = probeProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES);
89 Session session = getProperty(MigrationStateKeys.SESSION);
90 TransferableGraph1 tg = session.syncRequest(new Read<TransferableGraph1>() {
92 public TransferableGraph1 perform(ReadGraph graph) throws DatabaseException {
93 TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, roots, true, false);
94 TransferableGraphSource source = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
95 return TransferableGraphs.create(graph, source);
99 MigrationUtils.clearTempResource(session, resource);
100 setProperty(MigrationStateKeys.CURRENT_RESOURCE, null);
101 setProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES, null);
102 setProperty(MigrationStateKeys.DATABASE_REVISION_AFTER_TG_IMPORT, null);
103 setProperty(MigrationStateKeys.CURRENT_TG, tg);
107 TransferableGraphFileReader reader = null;
109 File modelFile = getProperty(MigrationStateKeys.MODEL_FILE);
110 reader = new TransferableGraphFileReader(modelFile);
111 TimeLogger.log(MigrationStateImpl.class, "reading TG into memory from " + modelFile);
112 TransferableGraph1 tg = reader.readTG();
113 TimeLogger.log(MigrationStateImpl.class, "read TG into memory from " + modelFile);
114 setProperty(MigrationStateKeys.CURRENT_TG, tg);
116 } catch (DatabaseException e) {
118 } catch (Throwable t) {
119 throw new DatabaseException(t);
121 uncheckedClose(reader);
124 } else if (MigrationStateKeys.CURRENT_TGS.equals(key)) {
126 File modelFile = getProperty(MigrationStateKeys.MODEL_FILE);
127 return (T) initializeTransferableGraphSource(modelFile);
129 } else if (MigrationStateKeys.CURRENT_DATA_CONTAINER.equals(key)) {
133 TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
134 DataContainer dc = tgs.getHeader();
135 setProperty(MigrationStateKeys.CURRENT_DATA_CONTAINER, dc);
138 } catch (DatabaseException e) {
140 } catch (Throwable t) {
141 throw new DatabaseException(t);
144 } else if (MigrationStateKeys.TG_EXTENSIONS.equals(key)) {
148 TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
149 Map<String,Variant> extensions = tgs.getExtensions();
150 setProperty(MigrationStateKeys.TG_EXTENSIONS, extensions);
151 return (T)extensions;
153 } catch (DatabaseException e) {
155 } catch (Throwable t) {
156 throw new DatabaseException(t);
159 } else if (MigrationStateKeys.CURRENT_RESOURCE.equals(key) || MigrationStateKeys.CURRENT_ROOT_RESOURCES.equals(key)) {
161 final Session session = getProperty(MigrationStateKeys.SESSION);
162 final IProgressMonitor monitor = probeProperty(MigrationStateKeys.PROGRESS_MONITOR);
163 final boolean updateDependencies = MigrationUtils.getProperty(this, MigrationStateKeys.UPDATE_DEPENDENCIES, Boolean.TRUE);
165 File temporaryTg = exportCurrentTgAsTemporaryFile(session, monitor);
166 if (temporaryTg != null)
167 setProperty(MigrationStateKeys.CURRENT_TGS, initializeTransferableGraphSource(temporaryTg));
169 TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
171 importTransferableGraphSource(monitor, session, updateDependencies, tgs);
172 // Delete temporary file if necessary
173 if (temporaryTg != null)
174 temporaryTg.delete();
175 return getProperty(key);
178 } else if (MigrationStateKeys.UPDATE_DEPENDENCIES.equals(key)) {
189 public <T> void setProperty(String key, T value) {
190 properties.put(key, value);
194 public void dispose() {
195 // Close all possible open file handles
197 StreamingTransferableGraphFileReader tgs = probeProperty(MigrationStateKeys.CURRENT_TGS_READER);
199 } catch (DatabaseException e) {
200 Logger.defaultLogError(e);
204 private static void uncheckedClose(Closeable closeable) {
206 if (closeable != null)
208 } catch (IOException e) {
213 private Resource createTemporaryRoot(WriteGraph graph) throws DatabaseException {
214 Layer0 L0 = Layer0.getInstance(graph);
215 Resource project = SimanticsInternal.getProject();
216 Resource root = graph.getPossibleObject(project, L0.PartOf);
217 Resource temp = Layer0Utils.getPossibleChild(graph, root, "Temp");
219 throw new AssumptionException("Temporary folder 'Temp' not found under " + graph.getPossibleURI(root));
221 Resource indexRoot = graph.newResource();
222 String indexRootName = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date());
223 graph.claim(indexRoot, L0.InstanceOf, L0.IndexRoot);
224 graph.addLiteral(indexRoot, L0.HasName, L0.String, indexRootName, Bindings.STRING);
225 graph.claim(temp, L0.ConsistsOf, indexRoot);
229 private File exportCurrentTgAsTemporaryFile(Session session, IProgressMonitor monitor) throws DatabaseException {
230 TransferableGraph1 tg = probeProperty(MigrationStateKeys.CURRENT_TG);
235 // Write TG back to disk and initialize CURRENT_TGS for the migrated TG.
236 File modelFile = getProperty(MigrationStateKeys.MODEL_FILE);
237 File tempFile = File.createTempFile("temporary-tgs", ".tg", SimanticsInternal.getTemporaryDirectory());
238 TimeLogger.log(MigrationStateImpl.class, "export temporary TG " + tempFile);
240 DataContainer dc = DataContainers.readHeader(modelFile);
241 TransferableGraphs.writeTransferableGraph(session, dc.format, dc.version, dc.metadata,
242 new TGTransferableGraphSource(tg),
244 new TGExportMonitor(monitor, "Exporting temporary transferable graph"));
246 // Allow potentially large TG structure to be GC'ed.
247 setProperty(MigrationStateKeys.CURRENT_TG, null);
249 TimeLogger.log(MigrationStateImpl.class, "export temporary TG done " + tempFile);
251 } catch (Exception e) {
252 throw new DatabaseException(e);
256 private TransferableGraphSource initializeTransferableGraphSource(File dataContainer) throws DatabaseException {
258 StreamingTransferableGraphFileReader reader = new StreamingTransferableGraphFileReader(dataContainer);
259 TransferableGraphSource tgs = reader.readTG();
260 setProperty(MigrationStateKeys.CURRENT_TGS_READER, reader);
261 setProperty(MigrationStateKeys.CURRENT_TGS, tgs);
263 } catch (DatabaseException e) {
265 } catch (IOException e) {
266 throw new DatabaseException("An I/O exception occurred during reading '" + dataContainer.getAbsolutePath() + "'", e);
267 } catch (Throwable t) {
268 throw new DatabaseException(t);
272 private void importTransferableGraphSource(IProgressMonitor monitor, Session session, boolean updateDependencies, TransferableGraphSource tgs) throws DatabaseException {
273 TimeLogger.log(MigrationStateImpl.class, "import TGS " + tgs);
274 final Resource indexRoot = session.syncRequest(new WriteResultRequest<Resource>() {
276 public Resource perform(WriteGraph graph) throws DatabaseException {
277 if(!updateDependencies)
278 Layer0Utils.setDependenciesIndexingDisabled(graph, true);
279 return createTemporaryRoot(graph);
283 IImportAdvisor baseAdvisor = MigrationUtils.getProperty(this, MigrationStateKeys.IMPORT_ADVISOR, new DefaultPasteImportAdvisor(indexRoot));
284 IImportAdvisor2 advisor = new WrapperAdvisor(baseAdvisor) {
286 public Resource getTarget() {
290 public void beforeWrite(WriteOnlyGraph graph, TransferableGraphImporter process) throws DatabaseException {
291 super.beforeWrite(graph, process);
292 if(!updateDependencies)
293 Layer0Utils.setDependenciesIndexingDisabled(graph, true);
296 public void afterWrite(WriteOnlyGraph graph, TransferableGraphImporter process) throws DatabaseException {
297 super.afterWrite(graph, process);
298 Boolean storeResources = probeProperty(MigrationStateKeys.GET_RESOURCE_IDS);
299 if(storeResources != null && storeResources) {
300 long[] ids = process.getResourceIds(session.getService(SerialisationSupport.class));
301 setProperty(MigrationStateKeys.RESOURCE_IDS, ids);
306 // Make sure that the supplied advisor is redirected to temp
307 advisor.redirect(indexRoot);
309 String task = "Importing model into database";
310 monitor.subTask(task);
311 TransferableGraphs.importGraph1(session, tgs, advisor, new TGImportMonitor(monitor, task));
313 setProperty(MigrationStateKeys.CURRENT_RESOURCE, indexRoot);
314 setProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES, new ArrayList<>(advisor.getRoots()));
315 setProperty(MigrationStateKeys.DATABASE_REVISION_AFTER_TG_IMPORT, session.getService(ManagementSupport.class).getHeadRevisionId());
316 TimeLogger.log(MigrationStateImpl.class, "imported TGS " + tgs);
320 static class TGImportMonitor implements TGStatusMonitor {
321 private final IProgressMonitor monitor;
322 private final String message;
323 public TGImportMonitor(IProgressMonitor monitor, String message) {
324 this.monitor = monitor;
325 this.message = message;
328 public void status(int percentage) {
329 monitor.subTask(message + " (" + percentage + "%)");
332 public boolean isCanceled() {
333 return monitor.isCanceled();
337 static class TGExportMonitor extends TGProgressMonitor {
338 private final String message;
339 public TGExportMonitor(IProgressMonitor monitor, String message) {
341 this.message = message;
344 protected void workDone(int percentage) {
345 monitor.subTask(message + " (" + percentage + "%)");