1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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.acorn;
14 import java.io.IOException;
15 import java.nio.file.Path;
16 import java.util.ArrayList;
17 import java.util.LinkedList;
18 import java.util.concurrent.ExecutorService;
19 import java.util.concurrent.Executors;
20 import java.util.concurrent.Semaphore;
21 import java.util.concurrent.ThreadFactory;
22 import java.util.concurrent.TimeUnit;
24 import org.simantics.acorn.MainProgram.MainProgramRunnable;
25 import org.simantics.acorn.exception.AcornAccessVerificationException;
26 import org.simantics.acorn.exception.IllegalAcornStateException;
27 import org.simantics.acorn.internal.ClusterChange;
28 import org.simantics.acorn.internal.ClusterUpdateProcessorBase;
29 import org.simantics.acorn.internal.UndoClusterUpdateProcessor;
30 import org.simantics.acorn.lru.ClusterChangeSet.Entry;
31 import org.simantics.acorn.lru.ClusterInfo;
32 import org.simantics.acorn.lru.ClusterStreamChunk;
33 import org.simantics.acorn.lru.ClusterUpdateOperation;
34 import org.simantics.db.ClusterCreator;
35 import org.simantics.db.Database;
36 import org.simantics.db.ServiceLocator;
37 import org.simantics.db.exception.DatabaseException;
38 import org.simantics.db.exception.SDBException;
39 import org.simantics.db.server.ProCoreException;
40 import org.simantics.db.service.ClusterSetsSupport;
41 import org.simantics.db.service.ClusterUID;
42 import org.simantics.db.service.LifecycleSupport;
43 import org.simantics.utils.datastructures.Pair;
44 import org.simantics.utils.logging.TimeLogger;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 import gnu.trove.map.hash.TLongObjectHashMap;
50 public class GraphClientImpl2 implements Database.Session {
52 private static final Logger LOGGER = LoggerFactory.getLogger(GraphClientImpl2.class);
53 public static final boolean DEBUG = false;
55 public final ClusterManager clusters;
57 private TransactionManager transactionManager = new TransactionManager();
58 private ExecutorService executor = Executors.newSingleThreadExecutor(new ClientThreadFactory("Core Main Program", false));
59 private ExecutorService saver = Executors.newSingleThreadExecutor(new ClientThreadFactory("Core Snapshot Saver", true));
61 private Path dbFolder;
62 private final Database database;
63 private ServiceLocator locator;
64 private MainProgram mainProgram;
66 static class ClientThreadFactory implements ThreadFactory {
71 public ClientThreadFactory(String name, boolean daemon) {
77 public Thread newThread(Runnable r) {
78 Thread thread = new Thread(r, name);
79 thread.setDaemon(daemon);
84 public GraphClientImpl2(Database database, Path dbFolder, ServiceLocator locator) throws IOException {
85 this.database = database;
86 this.dbFolder = dbFolder;
87 this.locator = locator;
88 this.clusters = new ClusterManager(dbFolder);
90 ClusterSetsSupport cssi = locator.getService(ClusterSetsSupport.class);
91 cssi.setReadDirectory(clusters.lastSessionDirectory);
92 cssi.updateWriteDirectory(clusters.workingDirectory);
93 mainProgram = new MainProgram(this, clusters);
94 executor.execute(mainProgram);
97 public Path getDbFolder() {
101 public void tryMakeSnapshot() throws IOException {
103 if (isClosing || unexpectedClose)
106 saver.execute(new Runnable() {
110 Transaction tr = null;
112 // First take a write transaction
113 tr = askWriteTransaction(-1);
114 // Then make sure that MainProgram is idling
115 mainProgram.mutex.acquire();
117 synchronized(mainProgram) {
118 if(mainProgram.operations.isEmpty()) {
121 // MainProgram is becoming busy again - delay snapshotting
126 mainProgram.mutex.release();
128 } catch (IllegalAcornStateException | ProCoreException e) {
129 LOGGER.error("Snapshotting failed", e);
130 unexpectedClose = true;
131 } catch (InterruptedException e) {
132 LOGGER.error("Snapshotting interrupted", e);
136 endTransaction(tr.getTransactionId());
137 if (unexpectedClose) {
138 LifecycleSupport support = getServiceLocator().getService(LifecycleSupport.class);
141 } catch (DatabaseException e1) {
142 LOGGER.error("Failed to close database as a safety measure due to failed snapshotting", e1);
145 } catch (ProCoreException e) {
146 LOGGER.error("Failed to end snapshotting write transaction", e);
153 public void makeSnapshot(boolean fullSave) throws IllegalAcornStateException {
154 clusters.makeSnapshot(locator, fullSave);
157 public <T> T clone(ClusterUID uid, ClusterCreator creator) throws DatabaseException {
159 return clusters.clone(uid, creator);
160 } catch (AcornAccessVerificationException | IllegalAcornStateException | IOException e) {
161 unexpectedClose = true;
162 throw new DatabaseException(e);
166 // private void save() throws IOException {
170 public void load() throws IOException {
174 // public void modiFileEx(ClusterUID uid, int resourceKey, long offset, long size, byte[] bytes, long pos, ClusterSupport support) {
175 // clusters.modiFileEx(uid, resourceKey, offset, size, bytes, pos, support);
179 public Database getDatabase() {
183 private boolean closed = false;
184 private boolean isClosing = false;
185 private boolean unexpectedClose = false;
188 public void close() throws ProCoreException {
189 LOGGER.info("Closing " + this + " and mainProgram " + mainProgram);
190 if(!closed && !isClosing) {
193 if (!unexpectedClose)
200 boolean executorTerminated = executor.awaitTermination(500, TimeUnit.MILLISECONDS);
201 boolean saverTerminated = saver.awaitTermination(500, TimeUnit.MILLISECONDS);
203 System.err.println("executorTerminated=" + executorTerminated + ", saverTerminated=" + saverTerminated);
206 clusters.mainState.save(dbFolder);
207 } catch (IOException e) {
208 LOGGER.error("Failed to save " + MainState.MAIN_STATE + " file in database folder " + dbFolder);
215 } catch (IllegalAcornStateException | InterruptedException e) {
216 throw new ProCoreException(e);
224 public void open() throws ProCoreException {
225 throw new UnsupportedOperationException();
229 public boolean isClosed() throws ProCoreException {
234 public void acceptCommit(long transactionId, long changeSetId, byte[] metadata) throws ProCoreException {
235 clusters.state.headChangeSetId++;
236 long committedChangeSetId = changeSetId + 1;
238 clusters.commitChangeSet(committedChangeSetId, metadata);
240 clusters.state.transactionId = transactionId;
242 mainProgram.committed();
244 TimeLogger.log("Accepted commit");
245 } catch (IllegalAcornStateException e) {
246 throw new ProCoreException(e);
251 public long cancelCommit(long transactionId, long changeSetId, byte[] metadata, OnChangeSetUpdate onChangeSetUpdate) throws ProCoreException {
252 // Accept and finalize current transaction and then undo it
253 acceptCommit(transactionId, changeSetId, metadata);
256 undo(new long[] {changeSetId+1}, onChangeSetUpdate);
257 clusters.state.headChangeSetId++;
258 return clusters.state.headChangeSetId;
259 } catch (SDBException e) {
260 LOGGER.error("Failed to undo cancelled transaction", e);
261 throw new ProCoreException(e);
266 public Transaction askReadTransaction() throws ProCoreException {
267 return transactionManager.askReadTransaction();
270 enum TransactionState {
274 class TransactionRequest {
275 public TransactionState state;
276 public Semaphore semaphore;
277 public TransactionRequest(TransactionState state, Semaphore semaphore) {
279 this.semaphore = semaphore;
283 class TransactionManager {
285 private TransactionState currentTransactionState = TransactionState.IDLE;
287 private int reads = 0;
289 LinkedList<TransactionRequest> requests = new LinkedList<TransactionRequest>();
291 TLongObjectHashMap<TransactionRequest> requestMap = new TLongObjectHashMap<TransactionRequest>();
293 private synchronized Transaction makeTransaction(TransactionRequest req) {
295 final int csId = clusters.state.headChangeSetId;
296 final long trId = clusters.state.transactionId+1;
297 requestMap.put(trId, req);
298 return new Transaction() {
301 public long getTransactionId() {
306 public long getHeadChangeSetId() {
313 * This method cannot be synchronized since it waits and must support multiple entries
314 * by query thread(s) and internal transactions such as snapshot saver
316 public Transaction askReadTransaction() throws ProCoreException {
318 Semaphore semaphore = new Semaphore(0);
320 TransactionRequest req = queue(TransactionState.READ, semaphore);
324 } catch (InterruptedException e) {
325 throw new ProCoreException(e);
328 return makeTransaction(req);
332 private synchronized void dispatch() {
333 TransactionRequest r = requests.removeFirst();
334 if(r.state == TransactionState.READ) reads++;
335 r.semaphore.release();
338 private synchronized void processRequests() {
342 if(requests.isEmpty()) return;
343 TransactionRequest req = requests.peek();
345 if(currentTransactionState == TransactionState.IDLE) {
347 // Accept anything while IDLE
348 currentTransactionState = req.state;
351 } else if (currentTransactionState == TransactionState.READ) {
353 if(req.state == currentTransactionState) {
365 } else if (currentTransactionState == TransactionState.WRITE) {
376 private synchronized TransactionRequest queue(TransactionState state, Semaphore semaphore) {
377 TransactionRequest req = new TransactionRequest(state, semaphore);
378 requests.addLast(req);
384 * This method cannot be synchronized since it waits and must support multiple entries
385 * by query thread(s) and internal transactions such as snapshot saver
387 public Transaction askWriteTransaction() throws IllegalAcornStateException {
389 Semaphore semaphore = new Semaphore(0);
390 TransactionRequest req = queue(TransactionState.WRITE, semaphore);
394 } catch (InterruptedException e) {
395 throw new IllegalAcornStateException(e);
397 mainProgram.startTransaction(clusters.state.headChangeSetId+1);
398 return makeTransaction(req);
401 public synchronized long endTransaction(long transactionId) throws ProCoreException {
403 TransactionRequest req = requestMap.remove(transactionId);
404 if(req.state == TransactionState.WRITE) {
405 currentTransactionState = TransactionState.IDLE;
410 currentTransactionState = TransactionState.IDLE;
414 return clusters.state.transactionId;
420 public Transaction askWriteTransaction(final long transactionId) throws ProCoreException {
422 if (isClosing || unexpectedClose || closed) {
423 throw new ProCoreException("GraphClientImpl2 is already closing so no more write transactions allowed!");
425 return transactionManager.askWriteTransaction();
426 } catch (IllegalAcornStateException e) {
427 throw new ProCoreException(e);
432 public long endTransaction(long transactionId) throws ProCoreException {
433 return transactionManager.endTransaction(transactionId);
437 public String execute(String command) throws ProCoreException {
438 // This is called only by WriteGraphImpl.commitAccessorChanges
439 // We can ignore this in Acorn
444 public byte[] getChangeSetMetadata(long changeSetId) throws ProCoreException {
446 return clusters.getMetadata(changeSetId);
447 } catch (AcornAccessVerificationException | IllegalAcornStateException e) {
448 throw new ProCoreException(e);
453 public ChangeSetData getChangeSetData(long minChangeSetId,
454 long maxChangeSetId, OnChangeSetUpdate onChangeSetupate)
455 throws ProCoreException {
457 new Exception("GetChangeSetDataFunction " + minChangeSetId + " " + maxChangeSetId).printStackTrace();;
463 public ChangeSetIds getChangeSetIds() throws ProCoreException {
464 throw new UnsupportedOperationException();
468 public Cluster getCluster(byte[] clusterId) throws ProCoreException {
469 throw new UnsupportedOperationException();
473 public ClusterChanges getClusterChanges(long changeSetId, byte[] clusterId)
474 throws ProCoreException {
475 throw new UnsupportedOperationException();
479 public ClusterIds getClusterIds() throws ProCoreException {
481 return clusters.getClusterIds();
482 } catch (IllegalAcornStateException e) {
483 throw new ProCoreException(e);
488 public Information getInformation() throws ProCoreException {
489 return new Information() {
492 public String getServerId() {
497 public String getProtocolId() {
502 public String getDatabaseId() {
507 public long getFirstChangeSetId() {
515 public Refresh getRefresh(long changeSetId) throws ProCoreException {
517 final ClusterIds ids = getClusterIds();
519 return new Refresh() {
522 public long getHeadChangeSetId() {
523 return clusters.state.headChangeSetId;
527 public long[] getFirst() {
528 return ids.getFirst();
532 public long[] getSecond() {
533 return ids.getSecond();
540 public byte[] getResourceFile(final byte[] clusterUID, final int resourceIndex) throws ProCoreException, AcornAccessVerificationException, IllegalAcornStateException {
541 return clusters.getResourceFile(clusterUID, resourceIndex);
545 public ResourceSegment getResourceSegment(final byte[] clusterUID, final int resourceIndex, final long segmentOffset, short segmentSize) throws ProCoreException {
547 return clusters.getResourceSegment(clusterUID, resourceIndex, segmentOffset, segmentSize);
548 } catch (AcornAccessVerificationException | IllegalAcornStateException e) {
549 throw new ProCoreException(e);
554 public long reserveIds(int count) throws ProCoreException {
555 return clusters.state.reservedIds++;
559 public void updateCluster(byte[] operations) throws ProCoreException {
560 ClusterInfo info = null;
562 ClusterUpdateOperation operation = new ClusterUpdateOperation(clusters, operations);
563 info = clusters.clusterLRU.getOrCreate(operation.uid, true);
565 throw new IllegalAcornStateException("info == null for operation " + operation);
567 info.scheduleUpdate();
568 mainProgram.schedule(operation);
569 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
570 throw new ProCoreException(e);
577 private UndoClusterUpdateProcessor getUndoCSS(String ccsId) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
579 String[] ss = ccsId.split("\\.");
580 String chunkKey = ss[0];
581 int chunkOffset = Integer.parseInt(ss[1]);
582 ClusterStreamChunk chunk = clusters.streamLRU.getWithoutMutex(chunkKey);
583 if(chunk == null) throw new IllegalAcornStateException("Cluster Stream Chunk " + chunkKey + " was not found.");
584 chunk.acquireMutex();
586 return chunk.getUndoProcessor(clusters, chunkOffset, ccsId);
587 } catch (DatabaseException e) {
589 } catch (Throwable t) {
590 throw new IllegalStateException(t);
592 chunk.releaseMutex();
596 private void performUndo(String ccsId, ArrayList<Pair<ClusterUID, byte[]>> clusterChanges, UndoClusterSupport support) throws ProCoreException, DatabaseException, IllegalAcornStateException, AcornAccessVerificationException {
597 UndoClusterUpdateProcessor proc = getUndoCSS(ccsId);
599 int clusterKey = clusters.getClusterKeyByClusterUIDOrMakeWithoutMutex(proc.getClusterUID());
601 clusters.clusterLRU.acquireMutex();
604 ClusterChange cs = new ClusterChange(clusterChanges, proc.getClusterUID());
605 for(int i=0;i<proc.entries.size();i++) {
607 Entry e = proc.entries.get(proc.entries.size() - 1 - i);
608 e.process(clusters, cs, clusterKey);
613 clusters.clusterLRU.releaseMutex();
618 public boolean undo(long[] changeSetIds, OnChangeSetUpdate onChangeSetUpdate) throws SDBException {
620 Exception exception = mainProgram.runIdle(new MainProgramRunnable() {
623 public void run() throws Exception {
627 final ArrayList<Pair<ClusterUID, byte[]>> clusterChanges = new ArrayList<Pair<ClusterUID, byte[]>>();
629 UndoClusterSupport support = new UndoClusterSupport(clusters);
631 final int changeSetId = clusters.state.headChangeSetId;
633 if(ClusterUpdateProcessorBase.DEBUG)
634 System.err.println(" === BEGIN UNDO ===");
636 for(int i=0;i<changeSetIds.length;i++) {
637 final long id = changeSetIds[changeSetIds.length-1-i];
638 ArrayList<String> ccss = clusters.getChanges(id);
640 for(int j=0;j<ccss.size();j++) {
641 String ccsid = ccss.get(ccss.size()-j-1);
643 if(ClusterUpdateProcessorBase.DEBUG)
644 System.err.println("performUndo " + ccsid);
645 performUndo(ccsid, clusterChanges, support);
646 } catch (DatabaseException e) {
652 if(ClusterUpdateProcessorBase.DEBUG)
653 System.err.println(" === END UNDO ===");
655 for(int i=0;i<clusterChanges.size();i++) {
657 final int changeSetIndex = i;
659 final Pair<ClusterUID, byte[]> pair = clusterChanges.get(i);
661 final ClusterUID cuid = pair.first;
662 final byte[] data = pair.second;
664 onChangeSetUpdate.onChangeSetUpdate(new ChangeSetUpdate() {
667 public long getChangeSetId() {
672 public int getChangeSetIndex() {
677 public int getNumberOfClusterChangeSets() {
678 return clusterChanges.size();
682 public int getIndexOfClusterChangeSet() {
683 return changeSetIndex;
687 public byte[] getClusterId() {
688 return cuid.asBytes();
692 public boolean getNewCluster() {
697 public byte[] getData() {
703 } catch (AcornAccessVerificationException | IllegalAcornStateException e1) {
704 throw new ProCoreException(e1);
716 if(exception instanceof SDBException) throw (SDBException)exception;
717 else if(exception != null) throw new IllegalAcornStateException(exception);
723 public ServiceLocator getServiceLocator() {
728 public boolean refreshEnabled() {
733 public boolean rolledback() {
734 return clusters.rolledback();
737 public void purge() throws IllegalAcornStateException {
738 clusters.purge(locator);
741 public void purgeDatabase() {
743 if (isClosing || unexpectedClose)
746 saver.execute(new Runnable() {
750 Transaction tr = null;
752 // First take a write transaction
753 tr = askWriteTransaction(-1);
754 // Then make sure that MainProgram is idling
755 mainProgram.mutex.acquire();
757 synchronized(mainProgram) {
758 if(mainProgram.operations.isEmpty()) {
761 // MainProgram is becoming busy again - delay snapshotting
766 mainProgram.mutex.release();
768 } catch (IllegalAcornStateException | ProCoreException e) {
769 LOGGER.error("Purge failed", e);
770 unexpectedClose = true;
771 } catch (InterruptedException e) {
772 LOGGER.error("Purge interrupted", e);
776 endTransaction(tr.getTransactionId());
777 if (unexpectedClose) {
778 LifecycleSupport support = getServiceLocator().getService(LifecycleSupport.class);
781 } catch (DatabaseException e1) {
782 LOGGER.error("Failed to close database as a safety measure due to failed purge", e1);
785 } catch (ProCoreException e) {
786 LOGGER.error("Failed to end purge write transaction", e);
794 public long getTailChangeSetId() {
795 return clusters.getTailChangeSetId();