1 package org.simantics.acorn;
3 import java.io.IOException;
4 import java.math.BigInteger;
5 import java.nio.file.CopyOption;
6 import java.nio.file.DirectoryStream;
7 import java.nio.file.Files;
8 import java.nio.file.Path;
9 import java.nio.file.StandardCopyOption;
10 import java.util.ArrayList;
11 import java.util.Collection;
12 import java.util.HashMap;
14 import java.util.concurrent.atomic.AtomicBoolean;
16 import org.simantics.acorn.cluster.ClusterImpl;
17 import org.simantics.acorn.exception.AcornAccessVerificationException;
18 import org.simantics.acorn.exception.IllegalAcornStateException;
19 import org.simantics.acorn.exception.InvalidHeadStateException;
20 import org.simantics.acorn.internal.ClusterSupport2;
21 import org.simantics.acorn.lru.ChangeSetInfo;
22 import org.simantics.acorn.lru.ClusterInfo;
23 import org.simantics.acorn.lru.ClusterLRU;
24 import org.simantics.acorn.lru.ClusterStreamChunk;
25 import org.simantics.acorn.lru.FileInfo;
26 import org.simantics.acorn.lru.LRU;
27 import org.simantics.databoard.file.RuntimeIOException;
28 import org.simantics.db.ClusterCreator;
29 import org.simantics.db.Database.Session.ClusterIds;
30 import org.simantics.db.Database.Session.ResourceSegment;
31 import org.simantics.db.ServiceLocator;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.impl.ClusterBase;
34 import org.simantics.db.impl.ClusterI;
35 import org.simantics.db.impl.ClusterSupport;
36 import org.simantics.db.procore.cluster.ClusterTraits;
37 import org.simantics.db.service.ClusterSetsSupport;
38 import org.simantics.db.service.ClusterUID;
39 import org.simantics.utils.FileUtils;
40 import org.simantics.utils.threads.logger.ITask;
41 import org.simantics.utils.threads.logger.ThreadLogger;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 public class ClusterManager {
47 final static Logger LOGGER = LoggerFactory.getLogger(ClusterManager.class);
49 private ArrayList<String> currentChanges = new ArrayList<String>();
51 public final Path dbFolder;
52 public Path lastSessionDirectory;
53 public Path workingDirectory;
55 public LRU<String, ClusterStreamChunk> streamLRU;
56 public LRU<Long, ChangeSetInfo> csLRU;
57 public ClusterLRU clusterLRU;
58 public LRU<String, FileInfo> fileLRU;
60 public MainState mainState;
61 public HeadState state;
63 private long lastSnapshot = System.nanoTime();
65 final public ClusterSupport2 support = new ClusterSupport2(this);
72 public ClusterManager(Path dbFolder) {
73 this.dbFolder = dbFolder;
76 public ArrayList<String> getChanges(long changeSetId) throws AcornAccessVerificationException, IllegalAcornStateException {
77 ChangeSetInfo info = csLRU.getWithoutMutex(changeSetId);
81 return info.getCCSIds();
87 public ClusterBase getClusterByClusterKey(int clusterKey) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
88 return clusterLRU.getClusterByClusterKey(clusterKey);
91 public ClusterBase getClusterByClusterUIDOrMake(ClusterUID clusterUID) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
92 return clusterLRU.getClusterByClusterUIDOrMake(clusterUID);
95 public ClusterImpl getClusterByClusterUIDOrMakeProxy(ClusterUID clusterUID) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
96 return clusterLRU.getClusterByClusterUIDOrMakeProxy(clusterUID);
99 public int getClusterKeyByClusterUIDOrMake(ClusterUID clusterUID) throws AcornAccessVerificationException {
100 return clusterLRU.getClusterKeyByClusterUIDOrMake(clusterUID);
103 public int getClusterKeyByClusterUIDOrMakeWithoutMutex(ClusterUID clusterUID) throws IllegalAcornStateException, AcornAccessVerificationException {
104 return clusterLRU.getClusterKeyByClusterUIDOrMakeWithoutMutex(clusterUID);
107 public int getClusterKeyByUID(long id1, long id2) throws DatabaseException, IllegalAcornStateException {
108 return clusterLRU.getClusterKeyByUIDWithoutMutex(id1, id2);
111 public <T extends ClusterI> T getClusterProxyByResourceKey(int resourceKey) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
112 return clusterLRU.getClusterProxyByResourceKey(resourceKey);
115 public ClusterUID getClusterUIDByResourceKey(int resourceKey) throws DatabaseException, AcornAccessVerificationException {
116 return clusterLRU.getClusterUIDByResourceKey(resourceKey);
119 public ClusterUID getClusterUIDByResourceKeyWithoutMutex(int resourceKey) throws DatabaseException, IllegalAcornStateException, AcornAccessVerificationException {
120 return clusterLRU.getClusterUIDByResourceKeyWithoutMutex(resourceKey);
124 * Private implementation
128 private static long countFiles(Path directory) throws IOException {
129 try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
131 for (@SuppressWarnings("unused") Path p : ds)
137 // 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)
138 private AtomicBoolean safeToMakeSnapshot = new AtomicBoolean(true);
139 private IllegalAcornStateException cause;
141 public synchronized void purge(ServiceLocator locator) throws IllegalAcornStateException {
145 // Schedule writing of all data to disk
147 // Wait for files to be written
148 synchronizeWorkingDirectory();
150 String currentDir = workingDirectory.getFileName().toString();
151 Path baseline = workingDirectory.resolveSibling(currentDir + "_baseline");
153 Files.createDirectories(baseline);
155 for(String clusterKey : state.clusters) {
156 String[] parts1 = clusterKey.split("#");
157 String[] parts = parts1[0].split("\\.");
158 String readDirName = parts1[1];
159 if(!readDirName.equals(currentDir)) {
160 String fileName = parts[0] + "." + parts[1] + ".cluster";
161 Path from = dbFolder.resolve(readDirName).resolve(fileName);
162 Path to = baseline.resolve(fileName);
163 System.err.println("purge copies " + from + " => " + to);
164 Files.copy(from, to, StandardCopyOption.COPY_ATTRIBUTES);
165 long first = new BigInteger(parts[0], 16).longValue();
166 long second = new BigInteger(parts[1], 16).longValue();
167 ClusterUID uuid = ClusterUID.make(first, second);
168 ClusterInfo info = clusterLRU.getWithoutMutex(uuid);
169 info.moveTo(baseline);
173 for (String fileKey : state.files) {
174 String[] parts = fileKey.split("#");
175 String readDirName = parts[1];
176 if(!readDirName.equals(currentDir)) {
177 String fileName = parts[0] + ".extFile";
178 Path from = dbFolder.resolve(readDirName).resolve(fileName);
179 Path to = baseline.resolve(fileName);
180 System.err.println("purge copies " + from + " => " + to);
181 Files.copy(from, to, StandardCopyOption.COPY_ATTRIBUTES);
182 FileInfo info = fileLRU.getWithoutMutex(parts[0]);
183 info.moveTo(baseline);
187 for (String fileKey : state.stream) {
188 String[] parts = fileKey.split("#");
189 String readDirName = parts[1];
190 if(!readDirName.equals(currentDir)) {
191 ClusterStreamChunk chunk = streamLRU.purge(parts[0]);
192 System.err.println("purge removes " + chunk);
197 for (String fileKey : state.cs) {
198 String[] parts = fileKey.split("#");
199 String readDirName = parts[1];
200 if(!readDirName.equals(currentDir)) {
201 Long revisionId = Long.parseLong(parts[0]);
202 ChangeSetInfo info = csLRU.purge(revisionId);
203 System.err.println("purge removes " + info);
205 // Path readDir = dbFolder.resolve(parts[1]);
206 // Long revisionId = Long.parseLong(parts[0]);
207 // int offset = Integer.parseInt(parts[2]);
208 // int length = Integer.parseInt(parts[3]);
209 // ChangeSetInfo info = new ChangeSetInfo(csLRU, readDir, revisionId, offset, length);
213 state.tailChangeSetId = state.headChangeSetId;
215 makeSnapshot(locator, true);
217 Files.walk(dbFolder, 1).filter(Files::isDirectory).forEach(f -> tryPurgeDirectory(f));
219 } catch (IllegalAcornStateException e) {
220 notSafeToMakeSnapshot(e);
222 } catch (IOException e) {
223 IllegalAcornStateException e1 = new IllegalAcornStateException(e);
224 notSafeToMakeSnapshot(e1);
226 } catch (AcornAccessVerificationException e) {
227 IllegalAcornStateException e1 = new IllegalAcornStateException(e);
228 notSafeToMakeSnapshot(e1);
234 void tryPurgeDirectory(Path f) {
237 System.err.println("purge deletes " + f);
239 String currentDir = f.getFileName().toString();
240 if(currentDir.endsWith("db"))
243 if(currentDir.endsWith("_baseline"))
244 currentDir = currentDir.replace("_baseline", "");
246 int ordinal = Integer.parseInt(currentDir);
247 if(ordinal < mainState.headDir - 1) {
248 System.err.println("purge deletes " + f);
249 FileUtils.deleteDir(f.toFile());
254 public synchronized boolean makeSnapshot(ServiceLocator locator, boolean fullSave) throws IllegalAcornStateException {
256 if (!safeToMakeSnapshot.get())
258 // Maximum autosave frequency is per 60s
259 if(!fullSave && System.nanoTime() - lastSnapshot < 10*1000000000L) {
260 // System.err.println("lastSnapshot too early");
264 // Cluster files are always there
265 // Nothing has been written => no need to do anything
266 long amountOfFiles = countFiles(workingDirectory);
267 if(!fullSave && amountOfFiles == 0) {
268 // System.err.println("amountOfFiles < 3");
272 LOGGER.info("makeSnapshot");
274 // Schedule writing of all data to disk
277 // Wait for all files to be written
278 clusterLRU.shutdown();
280 streamLRU.shutdown();
283 // Lets check if it is still safe to make a snapshot
284 if (!safeToMakeSnapshot.get())
287 ClusterSetsSupport cssi = locator.getService(ClusterSetsSupport.class);
293 mainState.save(dbFolder);
295 amountOfFiles = countFiles(workingDirectory);
297 LOGGER.info(" -finished: amount of files is {}", amountOfFiles);
299 workingDirectory = dbFolder.resolve(Integer.toString(mainState.headDir));
300 if (!Files.exists(workingDirectory)) {
301 Files.createDirectories(workingDirectory);
304 cssi.updateWriteDirectory(workingDirectory);
306 clusterLRU.setWriteDir(workingDirectory);
307 fileLRU.setWriteDir(workingDirectory);
308 streamLRU.setWriteDir(workingDirectory);
309 csLRU.setWriteDir(workingDirectory);
316 lastSnapshot = System.nanoTime();
319 } catch (IllegalAcornStateException e) {
320 notSafeToMakeSnapshot(e);
322 } catch (IOException e) {
323 IllegalAcornStateException e1 = new IllegalAcornStateException(e);
324 notSafeToMakeSnapshot(e1);
329 private void refreshHeadState() throws IOException, IllegalAcornStateException {
330 state.clusters.clear();
332 state.stream.clear();
335 clusterLRU.persist(state.clusters);
336 fileLRU.persist(state.files);
337 streamLRU.persist(state.stream);
338 csLRU.persist(state.cs);
341 private void synchronizeWorkingDirectory() throws IOException {
342 // Sync current working directory
343 Files.walk(workingDirectory, 1).filter(Files::isRegularFile).forEach(FileIO::uncheckedSyncPath);
346 private void persistHeadState() throws IOException {
347 synchronizeWorkingDirectory();
348 state.save(workingDirectory);
353 // public void save() throws IOException {
355 // refreshHeadState();
357 // clusterLRU.shutdown();
358 // fileLRU.shutdown();
359 // streamLRU.shutdown();
362 // persistHeadState();
364 // mainState.save(getBaseDirectory());
367 // ThreadLogVisualizer visualizer = new ThreadLogVisualizer();
368 // visualizer.read(new DataInputStream(new FileInputStream(
369 // ThreadLogger.LOG_FILE)));
370 // visualizer.visualize3(new PrintStream(ThreadLogger.LOG_FILE
372 // } catch (FileNotFoundException e) {
373 // // TODO Auto-generated catch block
374 // e.printStackTrace();
377 // System.err.println("-- load statistics --");
378 // for(Pair<ClusterUID, Integer> entry :
379 // CollectionUtils.valueSortedEntries(histogram)) {
380 // System.err.println(" " + entry.second + " " + entry.first);
385 private void acquireAll() throws IllegalAcornStateException {
386 clusterLRU.acquireMutex();
387 fileLRU.acquireMutex();
388 streamLRU.acquireMutex();
389 csLRU.acquireMutex();
392 private void releaseAll() {
393 csLRU.releaseMutex();
394 streamLRU.releaseMutex();
395 fileLRU.releaseMutex();
396 clusterLRU.releaseMutex();
399 private AtomicBoolean rollback = new AtomicBoolean(false);
401 boolean rolledback() {
402 return rollback.get();
405 public void load() throws IOException {
408 mainState = MainState.load(dbFolder, t -> rollback.set(true));
410 lastSessionDirectory = dbFolder.resolve(Integer.toString(mainState.headDir - 1));
414 state = HeadState.load(lastSessionDirectory);
415 } catch (InvalidHeadStateException e) {
416 // For backwards compatibility only!
417 Throwable cause = e.getCause();
418 if (cause instanceof Throwable) {
420 org.simantics.db.javacore.HeadState oldState = org.simantics.db.javacore.HeadState.load(lastSessionDirectory);
422 HeadState newState = new HeadState();
423 newState.clusters = oldState.clusters;
424 newState.cs = oldState.cs;
425 newState.files = oldState.files;
426 newState.stream = oldState.stream;
427 newState.headChangeSetId = oldState.headChangeSetId;
428 newState.reservedIds = oldState.reservedIds;
429 newState.transactionId = oldState.transactionId;
431 } catch (InvalidHeadStateException e1) {
432 throw new IOException("Could not load HeadState due to corruption", e1);
435 // This should never happen as MainState.load() checks the integrity
436 // of head.state files and rolls back in cases of corruption until a
437 // consistent state is found (could be case 0 - initial db state)
438 // IF this does happen something is completely wrong
439 throw new IOException("Could not load HeadState due to corruption", e);
443 workingDirectory = dbFolder.resolve(Integer.toString(mainState.headDir));
444 Files.createDirectories(workingDirectory);
446 csLRU = new LRU<Long, ChangeSetInfo>(this, "Change Set", workingDirectory);
447 streamLRU = new LRU<String, ClusterStreamChunk>(this, "Cluster Stream", workingDirectory);
448 clusterLRU = new ClusterLRU(this, "Cluster", workingDirectory);
449 fileLRU = new LRU<String, FileInfo>(this, "External Value", workingDirectory);
454 for (String clusterKey : state.clusters) {
455 String[] parts1 = clusterKey.split("#");
456 String[] parts = parts1[0].split("\\.");
457 long first = new BigInteger(parts[0], 16).longValue();
458 long second = new BigInteger(parts[1], 16).longValue();
459 ClusterUID uuid = ClusterUID.make(first, second);
460 Path readDir = dbFolder.resolve(parts1[1]);
461 int offset = Integer.parseInt(parts1[2]);
462 int length = Integer.parseInt(parts1[3]);
463 clusterLRU.map(new ClusterInfo(this, clusterLRU, readDir, uuid, offset, length));
466 for (String fileKey : state.files) {
467 // System.err.println("loadFile: " + fileKey);
468 String[] parts = fileKey.split("#");
469 Path readDir = dbFolder.resolve(parts[1]);
470 int offset = Integer.parseInt(parts[2]);
471 int length = Integer.parseInt(parts[3]);
472 FileInfo info = new FileInfo(fileLRU, readDir, parts[0], offset, length);
476 for (String fileKey : state.stream) {
477 // System.err.println("loadStream: " + fileKey);
478 String[] parts = fileKey.split("#");
479 Path readDir = dbFolder.resolve(parts[1]);
480 int offset = Integer.parseInt(parts[2]);
481 int length = Integer.parseInt(parts[3]);
482 ClusterStreamChunk info = new ClusterStreamChunk(this,
483 streamLRU, readDir, parts[0], offset, length);
487 for (String fileKey : state.cs) {
488 String[] parts = fileKey.split("#");
489 Path readDir = dbFolder.resolve(parts[1]);
490 Long revisionId = Long.parseLong(parts[0]);
491 int offset = Integer.parseInt(parts[2]);
492 int length = Integer.parseInt(parts[3]);
493 ChangeSetInfo info = new ChangeSetInfo(csLRU, readDir, revisionId, offset, length);
498 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
499 // ROLLBACK ONE DIR UNTIL WE ARE FINE!
500 throw new IOException(e);
504 public <T> T clone(ClusterUID uid, ClusterCreator creator) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException, IOException {
506 clusterLRU.ensureUpdates(uid);
508 ClusterInfo info = clusterLRU.getWithoutMutex(uid);
509 return info.clone(uid, creator);
512 //private int loadCounter = 0;
514 public static void startLog(String msg) {
515 tasks.put(msg, ThreadLogger.getInstance().begin(msg));
518 public static void endLog(String msg) {
519 ITask task = tasks.get(msg);
524 static Map<String, ITask> tasks = new HashMap<String, ITask>();
526 public void update(ClusterUID uid, ClusterImpl clu) throws AcornAccessVerificationException, IllegalAcornStateException {
527 ClusterInfo info = clusterLRU.getWithoutMutex(uid);
536 public long getClusterIdOrCreate(ClusterUID clusterUID) {
540 public int getResourceKey(ClusterUID uid, int index) throws AcornAccessVerificationException {
541 return clusterLRU.getResourceKey(uid, index);
544 public int getResourceKeyWitoutMutex(ClusterUID uid, int index) throws IllegalAcornStateException {
545 return clusterLRU.getResourceKeyWithoutMutex(uid, index);
548 public ClusterIds getClusterIds() throws IllegalAcornStateException {
549 clusterLRU.acquireMutex();
552 Collection<ClusterInfo> infos = clusterLRU.values();
553 final int status = infos.size();
554 final long[] firsts = new long[status];
555 final long[] seconds = new long[status];
558 for (ClusterInfo info : infos) {
560 seconds[index] = info.getKey().second;
564 return new ClusterIds() {
567 public int getStatus() {
572 public long[] getFirst() {
577 public long[] getSecond() {
583 } catch (Throwable t) {
584 throw new IllegalAcornStateException(t);
586 clusterLRU.releaseMutex();
590 public void addIntoCurrentChangeSet(String ccs) throws IllegalAcornStateException {
591 csLRU.acquireMutex();
594 currentChanges.add(ccs);
595 } catch (Throwable t) {
596 throw new IllegalAcornStateException(t);
598 csLRU.releaseMutex();
602 public void commitChangeSet(long changeSetId, byte[] data) throws IllegalAcornStateException {
603 csLRU.acquireMutex();
605 ArrayList<String> csids = new ArrayList<String>(currentChanges);
606 currentChanges = new ArrayList<String>();
607 new ChangeSetInfo(csLRU, changeSetId, data, csids);
608 } catch (Throwable t) {
609 throw new IllegalAcornStateException(t);
611 csLRU.releaseMutex();
615 public byte[] getMetadata(long changeSetId) throws AcornAccessVerificationException, IllegalAcornStateException {
617 ChangeSetInfo info = csLRU.getWithoutMutex(changeSetId);
618 if (info == null) return null;
621 return info.getMetadataBytes();
622 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
624 } catch (Throwable t) {
625 throw new IllegalAcornStateException(t);
631 public byte[] getResourceFile(final byte[] clusterUID, final int resourceIndex) throws AcornAccessVerificationException, IllegalAcornStateException {
633 ClusterUID uid = ClusterUID.make(clusterUID, 0);
634 String key = uid.toString() + "_" + resourceIndex;
635 FileInfo info = fileLRU.getWithoutMutex(key);
636 if(info == null) return null;
639 return info.getResourceFile();
640 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
642 } catch (Throwable t) {
643 throw new IllegalAcornStateException(t);
649 public ResourceSegment getResourceSegment(final byte[] clusterUID, final int resourceIndex, final long segmentOffset, short segmentSize) throws AcornAccessVerificationException, IllegalAcornStateException {
650 ClusterUID uid = ClusterUID.make(clusterUID, 0);
652 String key = uid.toString() + "_" + resourceIndex;
653 FileInfo info = fileLRU.getWithoutMutex(key);
654 if(info == null) return null;
657 return info.getResourceSegment(clusterUID, resourceIndex, segmentOffset, segmentSize);
658 } catch (Throwable t) {
659 throw new IllegalAcornStateException(t);
665 public void modiFileEx(ClusterUID uid, int resourceKey, long offset, long size, byte[] bytes, long pos, ClusterSupport support) throws IllegalAcornStateException {
667 String key = uid.toString() + "_" + ClusterTraits.getResourceIndexFromResourceKey(resourceKey);
669 FileInfo info = null;
670 fileLRU.acquireMutex();
672 info = fileLRU.get(key);
674 info = new FileInfo(fileLRU, key, (int) (offset + size));
676 } catch (Throwable t) {
677 throw new IllegalAcornStateException(t);
679 fileLRU.releaseMutex();
684 info.updateData(bytes, offset, pos, size);
685 } catch (Throwable t) {
686 throw new IllegalAcornStateException(t);
690 } catch (DatabaseException e) {
695 public void shutdown() {
696 clusterLRU.shutdown();
698 streamLRU.shutdown();
702 public void notSafeToMakeSnapshot(IllegalAcornStateException t) {
703 this.safeToMakeSnapshot.compareAndSet(true, false);
707 public long getTailChangeSetId() {
708 return state.tailChangeSetId;