1 package org.simantics.acorn;
3 import java.io.IOException;
4 import java.math.BigInteger;
5 import java.nio.file.DirectoryStream;
6 import java.nio.file.Files;
7 import java.nio.file.Path;
8 import java.util.ArrayList;
9 import java.util.Collection;
10 import java.util.HashMap;
12 import java.util.concurrent.atomic.AtomicBoolean;
14 import org.simantics.acorn.cluster.ClusterImpl;
15 import org.simantics.acorn.exception.AcornAccessVerificationException;
16 import org.simantics.acorn.exception.IllegalAcornStateException;
17 import org.simantics.acorn.exception.InvalidHeadStateException;
18 import org.simantics.acorn.internal.ClusterSupport2;
19 import org.simantics.acorn.lru.ChangeSetInfo;
20 import org.simantics.acorn.lru.ClusterInfo;
21 import org.simantics.acorn.lru.ClusterLRU;
22 import org.simantics.acorn.lru.ClusterStreamChunk;
23 import org.simantics.acorn.lru.FileInfo;
24 import org.simantics.acorn.lru.LRU;
25 import org.simantics.db.ClusterCreator;
26 import org.simantics.db.Database.Session.ClusterIds;
27 import org.simantics.db.Database.Session.ResourceSegment;
28 import org.simantics.db.ServiceLocator;
29 import org.simantics.db.exception.DatabaseException;
30 import org.simantics.db.impl.ClusterBase;
31 import org.simantics.db.impl.ClusterI;
32 import org.simantics.db.impl.ClusterSupport;
33 import org.simantics.db.procore.cluster.ClusterTraits;
34 import org.simantics.db.service.ClusterSetsSupport;
35 import org.simantics.db.service.ClusterUID;
36 import org.simantics.utils.threads.logger.ITask;
37 import org.simantics.utils.threads.logger.ThreadLogger;
39 public class ClusterManager {
41 private ArrayList<String> currentChanges = new ArrayList<String>();
43 public final Path dbFolder;
44 public Path lastSessionDirectory;
45 public Path workingDirectory;
47 public LRU<String, ClusterStreamChunk> streamLRU;
48 public LRU<Long, ChangeSetInfo> csLRU;
49 public ClusterLRU clusterLRU;
50 public LRU<String, FileInfo> fileLRU;
52 public MainState mainState;
53 public HeadState state;
55 private long lastSnapshot = System.nanoTime();
57 final public ClusterSupport2 support = new ClusterSupport2(this);
64 public ClusterManager(Path dbFolder) {
65 this.dbFolder = dbFolder;
68 public ArrayList<String> getChanges(long changeSetId) throws AcornAccessVerificationException, IllegalAcornStateException {
69 ChangeSetInfo info = csLRU.getWithoutMutex(changeSetId);
73 return info.getCSSIds();
79 public ClusterBase getClusterByClusterKey(int clusterKey) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
80 return clusterLRU.getClusterByClusterKey(clusterKey);
83 public ClusterBase getClusterByClusterUIDOrMake(ClusterUID clusterUID) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
84 return clusterLRU.getClusterByClusterUIDOrMake(clusterUID);
87 public ClusterImpl getClusterByClusterUIDOrMakeProxy(ClusterUID clusterUID) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
88 return clusterLRU.getClusterByClusterUIDOrMakeProxy(clusterUID);
91 public int getClusterKeyByClusterUIDOrMake(ClusterUID clusterUID) throws AcornAccessVerificationException {
92 return clusterLRU.getClusterKeyByClusterUIDOrMake(clusterUID);
95 public int getClusterKeyByClusterUIDOrMakeWithoutMutex(ClusterUID clusterUID) throws IllegalAcornStateException, AcornAccessVerificationException {
96 return clusterLRU.getClusterKeyByClusterUIDOrMakeWithoutMutex(clusterUID);
99 public int getClusterKeyByUID(long id1, long id2) throws DatabaseException, IllegalAcornStateException {
100 return clusterLRU.getClusterKeyByUIDWithoutMutex(id1, id2);
103 public <T extends ClusterI> T getClusterProxyByResourceKey(int resourceKey) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
104 return clusterLRU.getClusterProxyByResourceKey(resourceKey);
107 public ClusterUID getClusterUIDByResourceKey(int resourceKey) throws DatabaseException, AcornAccessVerificationException {
108 return clusterLRU.getClusterUIDByResourceKey(resourceKey);
111 public ClusterUID getClusterUIDByResourceKeyWithoutMutex(int resourceKey) throws DatabaseException, IllegalAcornStateException, AcornAccessVerificationException {
112 return clusterLRU.getClusterUIDByResourceKeyWithoutMutex(resourceKey);
116 * Private implementation
120 private static long countFiles(Path directory) throws IOException {
121 try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
123 for (@SuppressWarnings("unused") Path p : ds)
129 // Add check to make sure if it safe to make snapshot (used with cancel which is not yet supported and may cause corrupted head.state writing)
130 private AtomicBoolean safeToMakeSnapshot = new AtomicBoolean(true);
131 private IllegalAcornStateException cause;
133 public synchronized boolean makeSnapshot(ServiceLocator locator, boolean fullSave) throws IllegalAcornStateException {
135 if (!safeToMakeSnapshot.get())
137 // Maximum autosave frequency is per 60s
138 if(!fullSave && System.nanoTime() - lastSnapshot < 10*1000000000L) {
139 // System.err.println("lastSnapshot too early");
143 // Cluster files are always there
144 // Nothing has been written => no need to do anything
145 long amountOfFiles = countFiles(workingDirectory);
146 if(!fullSave && amountOfFiles < 3) {
147 // System.err.println("amountOfFiles < 3");
151 System.err.println("makeSnapshot");
153 // Schedule writing of all data to disk
156 // Wait for all files to be written
157 clusterLRU.shutdown();
159 streamLRU.shutdown();
162 // Lets check if it is still safe to make a snapshot
163 if (!safeToMakeSnapshot.get())
169 mainState.save(dbFolder);
171 ClusterSetsSupport cssi = locator.getService(ClusterSetsSupport.class);
174 amountOfFiles = countFiles(workingDirectory);
176 System.err.println(" -finished: amount of files is " + amountOfFiles);
178 workingDirectory = dbFolder.resolve(Integer.toString(mainState.headDir));
179 if (!Files.exists(workingDirectory)) {
180 Files.createDirectories(workingDirectory);
183 cssi.updateWriteDirectory(workingDirectory);
185 clusterLRU.setWriteDir(workingDirectory);
186 fileLRU.setWriteDir(workingDirectory);
187 streamLRU.setWriteDir(workingDirectory);
188 csLRU.setWriteDir(workingDirectory);
195 lastSnapshot = System.nanoTime();
198 } catch (IllegalAcornStateException e) {
199 notSafeToMakeSnapshot(e);
201 } catch (IOException e) {
202 IllegalAcornStateException e1 = new IllegalAcornStateException(e);
203 notSafeToMakeSnapshot(e1);
208 private void refreshHeadState() throws IOException, IllegalAcornStateException {
209 state.clusters.clear();
211 state.stream.clear();
214 clusterLRU.persist(state.clusters);
215 fileLRU.persist(state.files);
216 streamLRU.persist(state.stream);
217 csLRU.persist(state.cs);
220 private void persistHeadState() throws IOException {
221 // Sync current working directory
222 Files.walk(workingDirectory, 1).filter(Files::isRegularFile).forEach(FileIO::uncheckedSyncPath);
223 state.save(workingDirectory);
228 // public void save() throws IOException {
230 // refreshHeadState();
232 // clusterLRU.shutdown();
233 // fileLRU.shutdown();
234 // streamLRU.shutdown();
237 // persistHeadState();
239 // mainState.save(getBaseDirectory());
242 // ThreadLogVisualizer visualizer = new ThreadLogVisualizer();
243 // visualizer.read(new DataInputStream(new FileInputStream(
244 // ThreadLogger.LOG_FILE)));
245 // visualizer.visualize3(new PrintStream(ThreadLogger.LOG_FILE
247 // } catch (FileNotFoundException e) {
248 // // TODO Auto-generated catch block
249 // e.printStackTrace();
252 // System.err.println("-- load statistics --");
253 // for(Pair<ClusterUID, Integer> entry :
254 // CollectionUtils.valueSortedEntries(histogram)) {
255 // System.err.println(" " + entry.second + " " + entry.first);
260 private void acquireAll() throws IllegalAcornStateException {
261 clusterLRU.acquireMutex();
262 fileLRU.acquireMutex();
263 streamLRU.acquireMutex();
264 csLRU.acquireMutex();
267 private void releaseAll() {
268 csLRU.releaseMutex();
269 streamLRU.releaseMutex();
270 fileLRU.releaseMutex();
271 clusterLRU.releaseMutex();
274 private AtomicBoolean rollback = new AtomicBoolean(false);
276 boolean rolledback() {
277 return rollback.get();
280 public void load() throws IOException {
283 mainState = MainState.load(dbFolder, t -> rollback.set(true));
285 lastSessionDirectory = dbFolder.resolve(Integer.toString(mainState.headDir - 1));
289 state = HeadState.load(lastSessionDirectory);
290 } catch (InvalidHeadStateException e) {
291 // For backwards compatibility only!
292 Throwable cause = e.getCause();
293 if (cause instanceof Throwable) {
295 org.simantics.db.javacore.HeadState oldState = org.simantics.db.javacore.HeadState.load(lastSessionDirectory);
297 HeadState newState = new HeadState();
298 newState.clusters = oldState.clusters;
299 newState.cs = oldState.cs;
300 newState.files = oldState.files;
301 newState.stream = oldState.stream;
302 newState.headChangeSetId = oldState.headChangeSetId;
303 newState.reservedIds = oldState.reservedIds;
304 newState.transactionId = oldState.transactionId;
306 } catch (InvalidHeadStateException e1) {
307 throw new IOException("Could not load HeadState due to corruption", e1);
310 // This should never happen as MainState.load() checks the integrity
311 // of head.state files and rolls back in cases of corruption until a
312 // consistent state is found (could be case 0 - initial db state)
313 // IF this does happen something is completely wrong
314 throw new IOException("Could not load HeadState due to corruption", e);
318 workingDirectory = dbFolder.resolve(Integer.toString(mainState.headDir));
319 Files.createDirectories(workingDirectory);
321 csLRU = new LRU<Long, ChangeSetInfo>(this, "Change Set", workingDirectory);
322 streamLRU = new LRU<String, ClusterStreamChunk>(this, "Cluster Stream", workingDirectory);
323 clusterLRU = new ClusterLRU(this, "Cluster", workingDirectory);
324 fileLRU = new LRU<String, FileInfo>(this, "External Value", workingDirectory);
329 for (String clusterKey : state.clusters) {
330 String[] parts1 = clusterKey.split("#");
331 String[] parts = parts1[0].split("\\.");
332 long first = new BigInteger(parts[0], 16).longValue();
333 long second = new BigInteger(parts[1], 16).longValue();
334 ClusterUID uuid = ClusterUID.make(first, second);
335 Path readDir = dbFolder.resolve(parts1[1]);
336 int offset = Integer.parseInt(parts1[2]);
337 int length = Integer.parseInt(parts1[3]);
338 clusterLRU.map(new ClusterInfo(this, clusterLRU, readDir, uuid, offset, length));
341 for (String fileKey : state.files) {
342 // System.err.println("loadFile: " + fileKey);
343 String[] parts = fileKey.split("#");
344 Path readDir = dbFolder.resolve(parts[1]);
345 int offset = Integer.parseInt(parts[2]);
346 int length = Integer.parseInt(parts[3]);
347 FileInfo info = new FileInfo(fileLRU, readDir, parts[0], offset, length);
351 for (String fileKey : state.stream) {
352 // System.err.println("loadStream: " + fileKey);
353 String[] parts = fileKey.split("#");
354 Path readDir = dbFolder.resolve(parts[1]);
355 int offset = Integer.parseInt(parts[2]);
356 int length = Integer.parseInt(parts[3]);
357 ClusterStreamChunk info = new ClusterStreamChunk(this,
358 streamLRU, readDir, parts[0], offset, length);
362 for (String fileKey : state.cs) {
363 String[] parts = fileKey.split("#");
364 Path readDir = dbFolder.resolve(parts[1]);
365 Long revisionId = Long.parseLong(parts[0]);
366 int offset = Integer.parseInt(parts[2]);
367 int length = Integer.parseInt(parts[3]);
368 ChangeSetInfo info = new ChangeSetInfo(csLRU, readDir, revisionId, offset, length);
373 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
374 // ROLLBACK ONE DIR UNTIL WE ARE FINE!
375 throw new IOException(e);
379 public <T> T clone(ClusterUID uid, ClusterCreator creator) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException, IOException {
381 clusterLRU.ensureUpdates(uid);
383 ClusterInfo info = clusterLRU.getWithoutMutex(uid);
384 return info.clone(uid, creator);
387 //private int loadCounter = 0;
389 public static void startLog(String msg) {
390 tasks.put(msg, ThreadLogger.getInstance().begin(msg));
393 public static void endLog(String msg) {
394 ITask task = tasks.get(msg);
399 static Map<String, ITask> tasks = new HashMap<String, ITask>();
401 public void update(ClusterUID uid, ClusterImpl clu) throws AcornAccessVerificationException, IllegalAcornStateException {
402 ClusterInfo info = clusterLRU.getWithoutMutex(uid);
411 public long getClusterIdOrCreate(ClusterUID clusterUID) {
415 public int getResourceKey(ClusterUID uid, int index) throws AcornAccessVerificationException {
416 return clusterLRU.getResourceKey(uid, index);
419 public int getResourceKeyWitoutMutex(ClusterUID uid, int index) throws IllegalAcornStateException {
420 return clusterLRU.getResourceKeyWithoutMutex(uid, index);
423 public ClusterIds getClusterIds() throws IllegalAcornStateException {
424 clusterLRU.acquireMutex();
427 Collection<ClusterInfo> infos = clusterLRU.values();
428 final int status = infos.size();
429 final long[] firsts = new long[status];
430 final long[] seconds = new long[status];
433 for (ClusterInfo info : infos) {
435 seconds[index] = info.getKey().second;
439 return new ClusterIds() {
442 public int getStatus() {
447 public long[] getFirst() {
452 public long[] getSecond() {
458 } catch (Throwable t) {
459 throw new IllegalAcornStateException(t);
461 clusterLRU.releaseMutex();
465 public void addIntoCurrentChangeSet(String ccs) throws IllegalAcornStateException {
466 csLRU.acquireMutex();
469 currentChanges.add(ccs);
470 } catch (Throwable t) {
471 throw new IllegalAcornStateException(t);
473 csLRU.releaseMutex();
477 public void commitChangeSet(long changeSetId, byte[] data) throws IllegalAcornStateException {
478 csLRU.acquireMutex();
480 ArrayList<String> csids = new ArrayList<String>(currentChanges);
481 currentChanges = new ArrayList<String>();
482 new ChangeSetInfo(csLRU, changeSetId, data, csids);
483 } catch (Throwable t) {
484 throw new IllegalAcornStateException(t);
486 csLRU.releaseMutex();
490 public byte[] getMetadata(long changeSetId) throws AcornAccessVerificationException, IllegalAcornStateException {
492 ChangeSetInfo info = csLRU.getWithoutMutex(changeSetId);
493 if (info == null) return null;
496 return info.getMetadataBytes();
497 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
499 } catch (Throwable t) {
500 throw new IllegalAcornStateException(t);
506 public byte[] getResourceFile(final byte[] clusterUID, final int resourceIndex) throws AcornAccessVerificationException, IllegalAcornStateException {
508 ClusterUID uid = ClusterUID.make(clusterUID, 0);
509 String key = uid.toString() + "_" + resourceIndex;
510 FileInfo info = fileLRU.getWithoutMutex(key);
511 if(info == null) return null;
514 return info.getResourceFile();
515 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
517 } catch (Throwable t) {
518 throw new IllegalAcornStateException(t);
524 public ResourceSegment getResourceSegment(final byte[] clusterUID, final int resourceIndex, final long segmentOffset, short segmentSize) throws AcornAccessVerificationException, IllegalAcornStateException {
525 ClusterUID uid = ClusterUID.make(clusterUID, 0);
527 String key = uid.toString() + "_" + resourceIndex;
528 FileInfo info = fileLRU.getWithoutMutex(key);
529 if(info == null) return null;
532 return info.getResourceSegment(clusterUID, resourceIndex, segmentOffset, segmentSize);
533 } catch (Throwable t) {
534 throw new IllegalAcornStateException(t);
540 public void modiFileEx(ClusterUID uid, int resourceKey, long offset, long size, byte[] bytes, long pos, ClusterSupport support) throws IllegalAcornStateException {
542 String key = uid.toString() + "_" + ClusterTraits.getResourceIndexFromResourceKey(resourceKey);
544 FileInfo info = null;
545 fileLRU.acquireMutex();
547 info = fileLRU.get(key);
549 info = new FileInfo(fileLRU, key, (int) (offset + size));
551 } catch (Throwable t) {
552 throw new IllegalAcornStateException(t);
554 fileLRU.releaseMutex();
559 info.updateData(bytes, offset, pos, size);
560 } catch (Throwable t) {
561 throw new IllegalAcornStateException(t);
565 } catch (DatabaseException e) {
570 public void shutdown() {
571 clusterLRU.shutdown();
573 streamLRU.shutdown();
577 public void notSafeToMakeSnapshot(IllegalAcornStateException t) {
578 this.safeToMakeSnapshot.compareAndSet(true, false);