]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/migration/MigrationStateImpl.java
Less memory use for TG import when NamespaceMigrationStep is involved
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / migration / MigrationStateImpl.java
1 /*******************************************************************************
2  * Copyright (c) 2012 Association for Decentralized Information Management in
3  * 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.db.layer0.migration;
13
14 import java.io.Closeable;
15 import java.io.File;
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;
22 import java.util.Map;
23
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;
60
61 public class MigrationStateImpl implements MigrationState {
62
63         final private HashMap<String, Object> properties = new HashMap<String, Object>();
64         
65     @SuppressWarnings("unchecked")
66     @Override
67     public <T> T probeProperty(String key) throws DatabaseException {
68         return (T)properties.get(key);
69     }
70
71         @SuppressWarnings("unchecked")
72     @Override
73         public <T> T getProperty(String key) throws DatabaseException {
74             
75             T property = (T)properties.get(key);
76             if(property != null) return property;
77             
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)) {
85                 
86                 final Resource resource = probeProperty(MigrationStateKeys.CURRENT_RESOURCE);
87                 final Collection<Resource> roots = probeProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES);
88                 if(roots != null) {
89                     Session session = getProperty(MigrationStateKeys.SESSION);
90                     TransferableGraph1 tg = session.syncRequest(new Read<TransferableGraph1>() {
91                         @Override
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);
96                         }
97                     });
98                     if (resource != null)
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);
104                     return (T)tg;
105                 }
106                 
107             TransferableGraphFileReader reader = null;
108             try {
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);
115                 return (T)tg;
116             } catch (DatabaseException e) {
117                 throw e;
118             } catch (Throwable t) {
119                 throw new DatabaseException(t);
120             } finally {
121                 uncheckedClose(reader);
122             }
123                 
124         } else if (MigrationStateKeys.CURRENT_TGS.equals(key)) {
125
126             File modelFile = getProperty(MigrationStateKeys.MODEL_FILE);
127             return (T) initializeTransferableGraphSource(modelFile);
128
129         } else if (MigrationStateKeys.CURRENT_DATA_CONTAINER.equals(key)) {
130             
131             try {
132                 
133                 TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
134                 DataContainer dc = tgs.getHeader();
135                 setProperty(MigrationStateKeys.CURRENT_DATA_CONTAINER, dc);
136                 return (T)dc;
137                 
138             } catch (DatabaseException e) {
139                 throw e;
140             } catch (Throwable t) {
141                 throw new DatabaseException(t);
142             }
143             
144         } else if (MigrationStateKeys.TG_EXTENSIONS.equals(key)) {
145             
146             try {
147                 
148                 TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
149                 Map<String,Variant> extensions = tgs.getExtensions();
150                 setProperty(MigrationStateKeys.TG_EXTENSIONS, extensions);
151                 return (T)extensions;
152                 
153             } catch (DatabaseException e) {
154                 throw e;
155             } catch (Throwable t) {
156                 throw new DatabaseException(t);
157             }
158
159         } else if (MigrationStateKeys.CURRENT_RESOURCE.equals(key) || MigrationStateKeys.CURRENT_ROOT_RESOURCES.equals(key)) {
160
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);
164
165             File temporaryTg = exportCurrentTgAsTemporaryFile(session, monitor);
166             if (temporaryTg != null)
167                 setProperty(MigrationStateKeys.CURRENT_TGS, initializeTransferableGraphSource(temporaryTg));
168
169             TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
170             if (tgs != null) {
171                 importTransferableGraphSource(monitor, session, updateDependencies, tgs);
172                 // Delete temporary file if necessary
173                 if (temporaryTg != null)
174                     temporaryTg.delete();
175                 return getProperty(key);
176             }
177
178         } else if (MigrationStateKeys.UPDATE_DEPENDENCIES.equals(key)) {
179
180             return null;
181
182         }
183
184         return null;
185
186         }
187
188         @Override
189         public <T> void setProperty(String key, T value) {
190                 properties.put(key, value);
191         }
192
193         @Override
194         public void dispose() {
195                 // Close all possible open file handles
196                 try {
197                         StreamingTransferableGraphFileReader tgs = probeProperty(MigrationStateKeys.CURRENT_TGS_READER);
198                         uncheckedClose(tgs);
199                 } catch (DatabaseException e) {
200                         Logger.defaultLogError(e);
201                 }
202         }
203
204         private static void uncheckedClose(Closeable closeable) {
205                 try {
206                         if (closeable != null)
207                                 closeable.close();
208                 } catch (IOException e) {
209                         //ignore
210                 }
211         }
212
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");
218         if (temp == null) 
219             throw new AssumptionException("Temporary folder 'Temp' not found under " + graph.getPossibleURI(root));
220
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);
226         return indexRoot;
227     }
228
229         private File exportCurrentTgAsTemporaryFile(Session session, IProgressMonitor monitor) throws DatabaseException {
230                 TransferableGraph1 tg = probeProperty(MigrationStateKeys.CURRENT_TG);
231                 if (tg == null)
232                         return null;
233
234                 try {
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);
239
240                         DataContainer dc = DataContainers.readHeader(modelFile);
241                         TransferableGraphs.writeTransferableGraph(session, dc.format, dc.version, dc.metadata,
242                                         new TGTransferableGraphSource(tg),
243                                         tempFile,
244                                         new TGExportMonitor(monitor, "Exporting temporary transferable graph"));
245
246                         // Allow potentially large TG structure to be GC'ed.
247                         setProperty(MigrationStateKeys.CURRENT_TG, null);
248
249                         TimeLogger.log(MigrationStateImpl.class, "export temporary TG done " + tempFile);
250                         return tempFile;
251                 } catch (Exception e) {
252                         throw new DatabaseException(e);
253                 }
254         }
255
256         private TransferableGraphSource initializeTransferableGraphSource(File dataContainer) throws DatabaseException {
257                 try {
258                         StreamingTransferableGraphFileReader reader = new StreamingTransferableGraphFileReader(dataContainer);
259                         TransferableGraphSource tgs = reader.readTG();
260                         setProperty(MigrationStateKeys.CURRENT_TGS_READER, reader);
261                         setProperty(MigrationStateKeys.CURRENT_TGS, tgs);
262                         return tgs;
263                 } catch (DatabaseException e) {
264                         throw 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);
269                 }
270         }
271
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>() {
275                         @Override
276                         public Resource perform(WriteGraph graph) throws DatabaseException {
277                                 if(!updateDependencies)
278                                         Layer0Utils.setDependenciesIndexingDisabled(graph, true);
279                                 return createTemporaryRoot(graph);
280                         }
281                 });
282
283                 IImportAdvisor baseAdvisor = MigrationUtils.getProperty(this, MigrationStateKeys.IMPORT_ADVISOR, new DefaultPasteImportAdvisor(indexRoot));
284                 IImportAdvisor2 advisor = new WrapperAdvisor(baseAdvisor) {
285                         @Override
286                         public Resource getTarget() {
287                                 return indexRoot;
288                         }
289                         @Override
290                         public void beforeWrite(WriteOnlyGraph graph, TransferableGraphImporter process) throws DatabaseException {
291                                 super.beforeWrite(graph, process);
292                                 if(!updateDependencies)
293                                         Layer0Utils.setDependenciesIndexingDisabled(graph, true);
294                         }
295                         @Override
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);
302                                 }
303                         }
304                 };
305
306                 // Make sure that the supplied advisor is redirected to temp
307                 advisor.redirect(indexRoot);
308
309                 String task = "Importing model into database";
310                 monitor.subTask(task);
311                 TransferableGraphs.importGraph1(session, tgs, advisor, new TGImportMonitor(monitor, task));
312
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);
317         }
318
319         
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;
326                 }
327                 @Override
328                 public void status(int percentage) {
329                         monitor.subTask(message + " (" + percentage + "%)");
330                 }
331                 @Override
332                 public boolean isCanceled() {
333                         return monitor.isCanceled();
334                 }
335         }
336
337         static class TGExportMonitor extends TGProgressMonitor {
338                 private final String message;
339                 public TGExportMonitor(IProgressMonitor monitor, String message) {
340                         super(monitor);
341                         this.message = message;
342                 }
343                 @Override
344                 protected void workDone(int percentage) {
345                         monitor.subTask(message + " (" + percentage + "%)");
346                 }
347         }
348
349 }