]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.acorn/src/org/simantics/acorn/ClusterManager.java
Fixed bad bug related to AcornBackupProvider
[simantics/platform.git] / bundles / org.simantics.acorn / src / org / simantics / acorn / ClusterManager.java
1 package org.simantics.acorn;
2
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.nio.file.StandardCopyOption;
9 import java.util.ArrayList;
10 import java.util.Collection;
11 import java.util.HashMap;
12 import java.util.Map;
13 import java.util.concurrent.atomic.AtomicBoolean;
14
15 import org.simantics.acorn.cluster.ClusterImpl;
16 import org.simantics.acorn.exception.AcornAccessVerificationException;
17 import org.simantics.acorn.exception.IllegalAcornStateException;
18 import org.simantics.acorn.exception.InvalidHeadStateException;
19 import org.simantics.acorn.internal.ClusterSupport2;
20 import org.simantics.acorn.lru.ChangeSetInfo;
21 import org.simantics.acorn.lru.ClusterInfo;
22 import org.simantics.acorn.lru.ClusterLRU;
23 import org.simantics.acorn.lru.ClusterStreamChunk;
24 import org.simantics.acorn.lru.FileInfo;
25 import org.simantics.acorn.lru.LRU;
26 import org.simantics.db.ClusterCreator;
27 import org.simantics.db.Database.Session.ClusterIds;
28 import org.simantics.db.Database.Session.ResourceSegment;
29 import org.simantics.db.ServiceLocator;
30 import org.simantics.db.exception.DatabaseException;
31 import org.simantics.db.impl.ClusterBase;
32 import org.simantics.db.impl.ClusterI;
33 import org.simantics.db.impl.ClusterSupport;
34 import org.simantics.db.procore.cluster.ClusterTraits;
35 import org.simantics.db.service.ClusterSetsSupport;
36 import org.simantics.db.service.ClusterUID;
37 import org.simantics.utils.FileUtils;
38 import org.simantics.utils.threads.logger.ITask;
39 import org.simantics.utils.threads.logger.ThreadLogger;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class ClusterManager {
44     
45     final static Logger LOGGER = LoggerFactory.getLogger(ClusterManager.class); 
46
47         private ArrayList<String> currentChanges = new ArrayList<String>();
48
49         public final Path dbFolder;
50         public Path lastSessionDirectory;
51         public Path workingDirectory;
52
53         public LRU<String, ClusterStreamChunk> streamLRU;
54         public LRU<Long, ChangeSetInfo> csLRU;
55         public ClusterLRU clusterLRU;
56         public LRU<String, FileInfo> fileLRU;
57
58         public MainState mainState;
59         public HeadState state;
60
61         private long lastSnapshot = System.nanoTime();
62
63         final public ClusterSupport2 support = new ClusterSupport2(this);
64
65         /*
66          * Public interface
67          * 
68          */
69
70         public ClusterManager(Path dbFolder) {
71                 this.dbFolder = dbFolder;
72         }
73
74         public ArrayList<String> getChanges(long changeSetId) throws AcornAccessVerificationException, IllegalAcornStateException {
75                 ChangeSetInfo info = csLRU.getWithoutMutex(changeSetId);
76                 info.acquireMutex();
77                 try {
78                         info.makeResident();
79                         return info.getCCSIds();
80                 } finally {
81                         info.releaseMutex();
82                 }
83         }
84
85         public ClusterBase getClusterByClusterKey(int clusterKey) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
86                 return clusterLRU.getClusterByClusterKey(clusterKey);
87         }
88         
89         public ClusterBase getClusterByClusterUIDOrMake(ClusterUID clusterUID) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
90                 return clusterLRU.getClusterByClusterUIDOrMake(clusterUID);
91         }
92
93         public ClusterImpl getClusterByClusterUIDOrMakeProxy(ClusterUID clusterUID) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
94                 return clusterLRU.getClusterByClusterUIDOrMakeProxy(clusterUID);
95         }
96
97         public int getClusterKeyByClusterUIDOrMake(ClusterUID clusterUID) throws AcornAccessVerificationException {
98                 return clusterLRU.getClusterKeyByClusterUIDOrMake(clusterUID);
99         }
100
101         public int getClusterKeyByClusterUIDOrMakeWithoutMutex(ClusterUID clusterUID) throws IllegalAcornStateException, AcornAccessVerificationException {
102                 return clusterLRU.getClusterKeyByClusterUIDOrMakeWithoutMutex(clusterUID);
103         }
104
105         public int getClusterKeyByUID(long id1, long id2) throws DatabaseException, IllegalAcornStateException {
106                 return clusterLRU.getClusterKeyByUIDWithoutMutex(id1, id2);
107         }
108         
109         public <T extends ClusterI> T getClusterProxyByResourceKey(int resourceKey) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
110                 return clusterLRU.getClusterProxyByResourceKey(resourceKey);
111         }
112
113         public ClusterUID getClusterUIDByResourceKey(int resourceKey) throws DatabaseException, AcornAccessVerificationException {
114                 return clusterLRU.getClusterUIDByResourceKey(resourceKey);
115         }
116
117         public ClusterUID getClusterUIDByResourceKeyWithoutMutex(int resourceKey) throws DatabaseException, IllegalAcornStateException, AcornAccessVerificationException {
118                 return clusterLRU.getClusterUIDByResourceKeyWithoutMutex(resourceKey);
119         }
120
121         /*
122          * Private implementation
123          * 
124          */
125
126         private static long countFiles(Path directory) throws IOException {
127                 try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
128                         int count = 0;
129                         for (@SuppressWarnings("unused") Path p : ds)
130                                 ++count;
131                         return count;
132                 }
133         }
134
135         // 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)
136         private AtomicBoolean safeToMakeSnapshot = new AtomicBoolean(true);
137         private IllegalAcornStateException cause;
138         
139         public synchronized void purge(ServiceLocator locator) throws IllegalAcornStateException {
140                 
141             try {
142
143                 // Schedule writing of all data to disk
144                 refreshHeadState();
145                 // Wait for files to be written
146                 synchronizeWorkingDirectory();
147                 
148                 String currentDir = workingDirectory.getFileName().toString();
149                 Path baseline = workingDirectory.resolveSibling(currentDir + "_baseline");
150                 
151                 Files.createDirectories(baseline);
152                 
153                 for(String clusterKey : state.clusters) {
154                         String[] parts1 = clusterKey.split("#");
155                         String[] parts = parts1[0].split("\\.");
156                         String readDirName = parts1[1];
157                         if(!readDirName.equals(currentDir)) {
158                                 String fileName = parts[0] + "." + parts[1] + ".cluster";
159                                 Path from = dbFolder.resolve(readDirName).resolve(fileName);
160                                 Path to = baseline.resolve(fileName);
161                                 System.err.println("purge copies " + from + "  => " + to);
162                                 Files.copy(from, to, StandardCopyOption.COPY_ATTRIBUTES);
163                                 long first = new BigInteger(parts[0], 16).longValue();
164                                 long second = new BigInteger(parts[1], 16).longValue();
165                                 ClusterUID uuid = ClusterUID.make(first, second);
166                                 ClusterInfo info = clusterLRU.getWithoutMutex(uuid);
167                                 info.moveTo(baseline);
168                         }
169                 }
170                 
171                 for (String fileKey : state.files) {
172                         String[] parts = fileKey.split("#");
173                         String readDirName = parts[1];
174                         if(!readDirName.equals(currentDir)) {
175                                 String fileName = parts[0] + ".extFile";
176                                 Path from = dbFolder.resolve(readDirName).resolve(fileName);
177                                 Path to = baseline.resolve(fileName);
178                                 System.err.println("purge copies " + from + "  => " + to);
179                                 Files.copy(from, to, StandardCopyOption.COPY_ATTRIBUTES);
180                                 FileInfo info = fileLRU.getWithoutMutex(parts[0]);
181                                 info.moveTo(baseline);
182                         }
183                 }
184                 
185                 for (String fileKey : state.stream) {
186                         String[] parts = fileKey.split("#");
187                         String readDirName = parts[1];
188                         if(!readDirName.equals(currentDir)) {
189                                 ClusterStreamChunk chunk = streamLRU.purge(parts[0]);
190                                 System.err.println("purge removes " + chunk);
191                         }
192                 }
193                 
194                 // Change sets
195                 for (String fileKey : state.cs) {
196                         String[] parts = fileKey.split("#");
197                         String readDirName = parts[1];
198                         if(!readDirName.equals(currentDir)) {
199                                 Long revisionId = Long.parseLong(parts[0]);
200                                 ChangeSetInfo info = csLRU.purge(revisionId);
201                                 System.err.println("purge removes " + info);
202                         }
203 //                      Path readDir = dbFolder.resolve(parts[1]);
204 //                      Long revisionId = Long.parseLong(parts[0]);
205 //                      int offset = Integer.parseInt(parts[2]);
206 //                      int length = Integer.parseInt(parts[3]);
207 //                      ChangeSetInfo info = new ChangeSetInfo(csLRU, readDir, revisionId, offset, length);
208 //                      csLRU.map(info);
209                 }               
210                 
211                 state.tailChangeSetId = state.headChangeSetId;
212                 
213                 makeSnapshot(locator, true);
214                 
215                 Files.walk(dbFolder, 1).filter(Files::isDirectory).forEach(f -> tryPurgeDirectory(f));
216
217             } catch (IllegalAcornStateException e) {
218                 notSafeToMakeSnapshot(e);
219                 throw e;
220             } catch (IOException e) {
221                 IllegalAcornStateException e1 = new IllegalAcornStateException(e);
222                 notSafeToMakeSnapshot(e1);
223                 throw e1;
224             } catch (AcornAccessVerificationException e) {
225                 IllegalAcornStateException e1 = new IllegalAcornStateException(e);
226                 notSafeToMakeSnapshot(e1);
227                 throw e1;
228                 }
229         
230         }
231         
232         void tryPurgeDirectory(Path f) {
233                 
234                 
235                 System.err.println("purge deletes " + f);
236
237                 String currentDir = f.getFileName().toString();
238                 if(currentDir.endsWith("db"))
239                         return;
240
241                 if(currentDir.endsWith("_baseline"))
242                         currentDir = currentDir.replace("_baseline", "");
243
244                 int ordinal = Integer.parseInt(currentDir);
245                 if(ordinal < mainState.headDir - 1) {
246                         System.err.println("purge deletes " + f);
247                         FileUtils.deleteDir(f.toFile());
248                 }
249                 
250         }
251
252         public synchronized boolean makeSnapshot(ServiceLocator locator, boolean fullSave) throws IllegalAcornStateException {
253             try {
254             if (!safeToMakeSnapshot.get())
255                 throw cause;
256                 // Maximum autosave frequency is per 60s
257                 if(!fullSave && System.nanoTime() - lastSnapshot < 10*1000000000L) {
258     //              System.err.println("lastSnapshot too early");
259                     return false;
260                 }
261     
262                 // Cluster files are always there 
263                 // Nothing has been written => no need to do anything
264                 long amountOfFiles = countFiles(workingDirectory);
265                 if(!fullSave && amountOfFiles == 0) {
266                         //LOGGER.info("makeSnapshot: " + amountOfFiles + " files, skipping snapshot");
267                     return false;
268                 }
269     
270                 LOGGER.info("makeSnapshot: start with " + amountOfFiles + " files");
271     
272                 // Schedule writing of all data to disk
273             refreshHeadState();
274     
275                 // Wait for all files to be written
276                 clusterLRU.shutdown();
277                 fileLRU.shutdown();
278                 streamLRU.shutdown();
279                 csLRU.shutdown();
280                 
281                 // Lets check if it is still safe to make a snapshot
282                 if (!safeToMakeSnapshot.get())
283                     throw cause;
284                 
285                 ClusterSetsSupport cssi = locator.getService(ClusterSetsSupport.class); 
286                 cssi.save();
287
288                 persistHeadState();
289
290                 if (LOGGER.isInfoEnabled()) {
291                         amountOfFiles = countFiles(workingDirectory);
292                         LOGGER.info(" -finished: amount of files is {}", amountOfFiles);
293                 }
294
295                 workingDirectory = dbFolder.resolve(Integer.toString(mainState.headDir));
296                 if (!Files.exists(workingDirectory)) {
297                     Files.createDirectories(workingDirectory);
298                 }
299     
300                 cssi.updateWriteDirectory(workingDirectory);
301     
302                 clusterLRU.setWriteDir(workingDirectory);
303                 fileLRU.setWriteDir(workingDirectory);
304                 streamLRU.setWriteDir(workingDirectory);
305                 csLRU.setWriteDir(workingDirectory);
306     
307                 clusterLRU.resume();
308                 fileLRU.resume();
309                 streamLRU.resume();
310                 csLRU.resume();
311     
312                 lastSnapshot = System.nanoTime();
313                 
314                 return true;
315             } catch (IllegalAcornStateException e) {
316                 notSafeToMakeSnapshot(e);
317                 throw e;
318             } catch (IOException e) {
319                 IllegalAcornStateException e1 = new IllegalAcornStateException(e);
320                 notSafeToMakeSnapshot(e1);
321                 throw e1;
322             }
323         }
324         
325         private void refreshHeadState() throws IOException, IllegalAcornStateException {
326                 state.clusters.clear();
327                 state.files.clear();
328                 state.stream.clear();
329                 state.cs.clear();
330
331                 clusterLRU.persist(state.clusters);
332                 fileLRU.persist(state.files);
333                 streamLRU.persist(state.stream);
334                 csLRU.persist(state.cs);
335         }
336         
337         private void synchronizeWorkingDirectory() throws IOException {
338                 // Sync current working directory
339                 Files.walk(workingDirectory, 1).filter(Files::isRegularFile).forEach(FileIO::uncheckedSyncPath);
340         }
341         
342         private void persistHeadState() throws IOException {
343                 synchronizeWorkingDirectory();
344                 state.save(workingDirectory);
345                 mainState.headDir++;
346         }
347
348         
349 //      public void save() throws IOException {
350 //
351 //              refreshHeadState();
352 //              
353 //              clusterLRU.shutdown();
354 //              fileLRU.shutdown();
355 //              streamLRU.shutdown();
356 //              csLRU.shutdown();
357 //
358 //              persistHeadState();
359 //
360 //              mainState.save(getBaseDirectory());
361
362 //              try {
363 //                      ThreadLogVisualizer visualizer = new ThreadLogVisualizer();
364 //                      visualizer.read(new DataInputStream(new FileInputStream(
365 //                                      ThreadLogger.LOG_FILE)));
366 //                      visualizer.visualize3(new PrintStream(ThreadLogger.LOG_FILE
367 //                                      + ".svg"));
368 //              } catch (FileNotFoundException e) {
369 //                      // TODO Auto-generated catch block
370 //                      e.printStackTrace();
371 //              }
372
373                 // System.err.println("-- load statistics --");
374                 // for(Pair<ClusterUID, Integer> entry :
375                 // CollectionUtils.valueSortedEntries(histogram)) {
376                 // System.err.println(" " + entry.second + " " + entry.first);
377                 // }
378
379 //      }
380         
381         private void acquireAll() throws IllegalAcornStateException {
382                 clusterLRU.acquireMutex();
383                 fileLRU.acquireMutex();
384                 streamLRU.acquireMutex();
385                 csLRU.acquireMutex();
386         }
387         
388         private void releaseAll() {
389                 csLRU.releaseMutex();
390                 streamLRU.releaseMutex();
391                 fileLRU.releaseMutex();
392                 clusterLRU.releaseMutex();
393         }
394
395         private AtomicBoolean rollback = new AtomicBoolean(false);
396         
397         boolean rolledback() {
398             return rollback.get();
399         }
400         
401         public void load() throws IOException {
402
403                 // Main state
404                 mainState = MainState.load(dbFolder, () -> rollback.set(true));
405
406                 lastSessionDirectory = dbFolder.resolve(Integer.toString(mainState.headDir - 1));
407                 
408                 // Head State
409                 try {
410             state = HeadState.load(lastSessionDirectory);
411         } catch (InvalidHeadStateException e) {
412             // For backwards compatibility only!
413             Throwable cause = e.getCause();
414             if (cause instanceof Throwable) {
415                 try {
416                     org.simantics.db.javacore.HeadState oldState = org.simantics.db.javacore.HeadState.load(lastSessionDirectory);
417                     
418                     HeadState newState = new HeadState();
419                     newState.clusters = oldState.clusters;
420                     newState.cs = oldState.cs;
421                     newState.files = oldState.files;
422                     newState.stream = oldState.stream;
423                     newState.headChangeSetId = oldState.headChangeSetId;
424                     newState.reservedIds = oldState.reservedIds;
425                     newState.transactionId = oldState.transactionId;
426                     state = newState;
427                 } catch (InvalidHeadStateException e1) {
428                     throw new IOException("Could not load HeadState due to corruption", e1);
429                 }
430             } else {
431                 // This should never happen as MainState.load() checks the integrity
432                 // of head.state files and rolls back in cases of corruption until a
433                 // consistent state is found (could be case 0 - initial db state)
434                 // IF this does happen something is completely wrong
435                 throw new IOException("Could not load HeadState due to corruption", e);
436             }
437         }
438                 try {
439                 workingDirectory = dbFolder.resolve(Integer.toString(mainState.headDir));
440                 Files.createDirectories(workingDirectory);
441     
442                 csLRU = new LRU<Long, ChangeSetInfo>(this, "Change Set", workingDirectory);
443                 streamLRU = new LRU<String, ClusterStreamChunk>(this, "Cluster Stream", workingDirectory);
444                 clusterLRU = new ClusterLRU(this, "Cluster", workingDirectory);
445                 fileLRU = new LRU<String, FileInfo>(this, "External Value", workingDirectory);
446     
447                 acquireAll();
448                 
449                 // Clusters
450                 for (String clusterKey : state.clusters) {
451                         String[] parts1 = clusterKey.split("#");
452                         String[] parts = parts1[0].split("\\.");
453                         long first = new BigInteger(parts[0], 16).longValue();
454                         long second = new BigInteger(parts[1], 16).longValue();
455                         ClusterUID uuid = ClusterUID.make(first, second);
456                         Path readDir = dbFolder.resolve(parts1[1]);
457                         int offset = Integer.parseInt(parts1[2]);
458                         int length = Integer.parseInt(parts1[3]);
459                         clusterLRU.map(new ClusterInfo(this, clusterLRU, readDir, uuid, offset, length));
460                 }
461                 // Files
462                 for (String fileKey : state.files) {
463     //                  System.err.println("loadFile: " + fileKey);
464                         String[] parts = fileKey.split("#");
465                         Path readDir = dbFolder.resolve(parts[1]);
466                         int offset = Integer.parseInt(parts[2]);
467                         int length = Integer.parseInt(parts[3]);
468                         FileInfo info = new FileInfo(fileLRU, readDir, parts[0], offset, length);
469                         fileLRU.map(info);
470                 }
471                 // Update chunks
472                 for (String fileKey : state.stream) {
473     //                  System.err.println("loadStream: " + fileKey);
474                         String[] parts = fileKey.split("#");
475                         Path readDir = dbFolder.resolve(parts[1]);
476                         int offset = Integer.parseInt(parts[2]);
477                         int length = Integer.parseInt(parts[3]);
478                         ClusterStreamChunk info = new ClusterStreamChunk(this,
479                                         streamLRU, readDir, parts[0], offset, length);
480                         streamLRU.map(info);
481                 }
482                 // Change sets
483                 for (String fileKey : state.cs) {
484                         String[] parts = fileKey.split("#");
485                         Path readDir = dbFolder.resolve(parts[1]);
486                         Long revisionId = Long.parseLong(parts[0]);
487                         int offset = Integer.parseInt(parts[2]);
488                         int length = Integer.parseInt(parts[3]);
489                         ChangeSetInfo info = new ChangeSetInfo(csLRU, readDir, revisionId, offset, length);
490                         csLRU.map(info);
491                 }
492                 
493                 releaseAll();
494                 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
495                     // ROLLBACK ONE DIR UNTIL WE ARE FINE!
496                     throw new IOException(e);
497                 }
498         }
499
500         public <T> T clone(ClusterUID uid, ClusterCreator creator) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException, IOException {
501                 
502                 clusterLRU.ensureUpdates(uid);
503                 
504                 ClusterInfo info = clusterLRU.getWithoutMutex(uid);
505                 return info.clone(uid, creator);
506         }
507
508         //private int loadCounter = 0;
509
510         public static void startLog(String msg) {
511                 tasks.put(msg, ThreadLogger.getInstance().begin(msg));
512         }
513
514         public static void endLog(String msg) {
515                 ITask task = tasks.get(msg);
516                 if (task != null)
517                         task.finish();
518         }
519
520         static Map<String, ITask> tasks = new HashMap<String, ITask>();
521
522         public void update(ClusterUID uid, ClusterImpl clu) throws AcornAccessVerificationException, IllegalAcornStateException {
523                 ClusterInfo info = clusterLRU.getWithoutMutex(uid);
524                 info.acquireMutex();
525                 try {
526                         info.update(clu);
527                 } finally {
528                         info.releaseMutex();
529                 }
530         }
531
532         public long getClusterIdOrCreate(ClusterUID clusterUID) {
533                 return 1;
534         }
535
536         public int getResourceKey(ClusterUID uid, int index) throws AcornAccessVerificationException {
537                 return clusterLRU.getResourceKey(uid, index);
538         }
539
540         public int getResourceKeyWitoutMutex(ClusterUID uid, int index) throws IllegalAcornStateException {
541                 return clusterLRU.getResourceKeyWithoutMutex(uid, index);
542         }
543
544         public ClusterIds getClusterIds() throws IllegalAcornStateException {
545                 clusterLRU.acquireMutex();
546
547                 try {
548                         Collection<ClusterInfo> infos = clusterLRU.values();
549                         final int status = infos.size();
550                         final long[] firsts = new long[status];
551                         final long[] seconds = new long[status];
552
553                         int index = 0;
554                         for (ClusterInfo info : infos) {
555                                 firsts[index] = 0;
556                                 seconds[index] = info.getKey().second;
557                                 index++;
558                         }
559
560                         return new ClusterIds() {
561
562                                 @Override
563                                 public int getStatus() {
564                                         return status;
565                                 }
566
567                                 @Override
568                                 public long[] getFirst() {
569                                         return firsts;
570                                 }
571
572                                 @Override
573                                 public long[] getSecond() {
574                                         return seconds;
575                                 }
576
577                         };
578
579                 } catch (Throwable t) {
580                         throw new IllegalAcornStateException(t);
581                 } finally {
582                         clusterLRU.releaseMutex();
583                 }
584         }
585
586         public void addIntoCurrentChangeSet(String ccs) throws IllegalAcornStateException {
587                 csLRU.acquireMutex();
588
589                 try {
590                         currentChanges.add(ccs);
591                 } catch (Throwable t) {
592                         throw new IllegalAcornStateException(t);
593                 } finally {
594                         csLRU.releaseMutex();
595                 }
596         }
597
598         public void commitChangeSet(long changeSetId, byte[] data) throws IllegalAcornStateException {
599                 csLRU.acquireMutex();
600                 try {
601                         ArrayList<String> csids = new ArrayList<String>(currentChanges);
602                         currentChanges = new ArrayList<String>();
603                         new ChangeSetInfo(csLRU, changeSetId, data, csids);
604                 } catch (Throwable t) {
605                         throw new IllegalAcornStateException(t);
606                 } finally {
607                         csLRU.releaseMutex();
608                 }
609         }
610
611         public byte[] getMetadata(long changeSetId) throws AcornAccessVerificationException, IllegalAcornStateException {
612                 
613                 ChangeSetInfo info = csLRU.getWithoutMutex(changeSetId);
614                 if (info == null) return null;
615         info.acquireMutex();
616         try {
617             return info.getMetadataBytes();
618         } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
619             throw e;
620         } catch (Throwable t) {
621                         throw new IllegalAcornStateException(t);
622                 } finally {
623                         info.releaseMutex();
624                 }
625         }
626
627         public byte[] getResourceFile(final byte[] clusterUID, final int resourceIndex) throws AcornAccessVerificationException, IllegalAcornStateException {
628
629                 ClusterUID uid = ClusterUID.make(clusterUID, 0);
630                 String key = uid.toString() + "_" + resourceIndex;
631                 FileInfo info = fileLRU.getWithoutMutex(key);
632                 if(info == null) return null;
633                 info.acquireMutex();
634                 try {
635                         return info.getResourceFile();
636                 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
637                     throw e;
638                 } catch (Throwable t) {
639                         throw new IllegalAcornStateException(t);
640                 } finally {
641                         info.releaseMutex();
642                 }
643         }
644
645         public ResourceSegment getResourceSegment(final byte[] clusterUID, final int resourceIndex, final long segmentOffset, short segmentSize) throws AcornAccessVerificationException, IllegalAcornStateException {
646                 ClusterUID uid = ClusterUID.make(clusterUID, 0);
647
648                 String key = uid.toString() + "_" + resourceIndex;
649                 FileInfo info = fileLRU.getWithoutMutex(key);
650                 if(info == null) return null;
651                 info.acquireMutex();
652                 try {
653                         return info.getResourceSegment(clusterUID, resourceIndex, segmentOffset, segmentSize);
654                 } catch (Throwable t) {
655                         throw new IllegalAcornStateException(t);
656                 } finally {
657                         info.releaseMutex();
658                 }
659         }
660
661         public void modiFileEx(ClusterUID uid, int resourceKey, long offset, long size, byte[] bytes, long pos, ClusterSupport support) throws IllegalAcornStateException {
662                 try {
663                         String key = uid.toString() + "_" + ClusterTraits.getResourceIndexFromResourceKey(resourceKey);
664
665                         FileInfo info = null;
666                         fileLRU.acquireMutex();
667                         try {
668                                 info = fileLRU.get(key);
669                                 if (info == null) {
670                                         info = new FileInfo(fileLRU, key, (int) (offset + size));
671                                 }
672                         } catch (Throwable t) {
673                                 throw new IllegalAcornStateException(t);
674                         } finally {
675                                 fileLRU.releaseMutex();
676                         }
677                         
678                         info.acquireMutex();
679                         try {
680                                 info.updateData(bytes, offset, pos, size);
681                         } catch (Throwable t) {
682                                 throw new IllegalAcornStateException(t);
683                         } finally {
684                                 info.releaseMutex();
685                         }
686                 } catch (DatabaseException e) {
687                         e.printStackTrace();
688                 }
689         }
690
691     public void shutdown() {
692         clusterLRU.shutdown();
693         fileLRU.shutdown();
694         streamLRU.shutdown();
695         csLRU.shutdown();
696     }
697
698     public void notSafeToMakeSnapshot(IllegalAcornStateException t) {
699         this.safeToMakeSnapshot.compareAndSet(true, false);
700         this.cause = t;
701     }
702
703     public long getTailChangeSetId() {
704         return state.tailChangeSetId;
705     }
706     
707 }