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);
209 } catch (IllegalAcornStateException | InterruptedException e) {
210 throw new ProCoreException(e);
218 public void open() throws ProCoreException {
219 throw new UnsupportedOperationException();
223 public boolean isClosed() throws ProCoreException {
228 public void acceptCommit(long transactionId, long changeSetId, byte[] metadata) throws ProCoreException {
229 clusters.state.headChangeSetId++;
230 long committedChangeSetId = changeSetId + 1;
232 clusters.commitChangeSet(committedChangeSetId, metadata);
234 clusters.state.transactionId = transactionId;
236 mainProgram.committed();
238 TimeLogger.log("Accepted commit");
239 } catch (IllegalAcornStateException e) {
240 throw new ProCoreException(e);
245 public long cancelCommit(long transactionId, long changeSetId, byte[] metadata, OnChangeSetUpdate onChangeSetUpdate) throws ProCoreException {
246 // Accept and finalize current transaction and then undo it
247 acceptCommit(transactionId, changeSetId, metadata);
250 undo(new long[] {changeSetId+1}, onChangeSetUpdate);
251 clusters.state.headChangeSetId++;
252 return clusters.state.headChangeSetId;
253 } catch (SDBException e) {
254 LOGGER.error("Failed to undo cancelled transaction", e);
255 throw new ProCoreException(e);
260 public Transaction askReadTransaction() throws ProCoreException {
261 return transactionManager.askReadTransaction();
264 enum TransactionState {
268 class TransactionRequest {
269 public TransactionState state;
270 public Semaphore semaphore;
271 public TransactionRequest(TransactionState state, Semaphore semaphore) {
273 this.semaphore = semaphore;
277 class TransactionManager {
279 private TransactionState currentTransactionState = TransactionState.IDLE;
281 private int reads = 0;
283 LinkedList<TransactionRequest> requests = new LinkedList<TransactionRequest>();
285 TLongObjectHashMap<TransactionRequest> requestMap = new TLongObjectHashMap<TransactionRequest>();
287 private synchronized Transaction makeTransaction(TransactionRequest req) {
289 final int csId = clusters.state.headChangeSetId;
290 final long trId = clusters.state.transactionId+1;
291 requestMap.put(trId, req);
292 return new Transaction() {
295 public long getTransactionId() {
300 public long getHeadChangeSetId() {
307 * This method cannot be synchronized since it waits and must support multiple entries
308 * by query thread(s) and internal transactions such as snapshot saver
310 public Transaction askReadTransaction() throws ProCoreException {
312 Semaphore semaphore = new Semaphore(0);
314 TransactionRequest req = queue(TransactionState.READ, semaphore);
318 } catch (InterruptedException e) {
319 throw new ProCoreException(e);
322 return makeTransaction(req);
326 private synchronized void dispatch() {
327 TransactionRequest r = requests.removeFirst();
328 if(r.state == TransactionState.READ) reads++;
329 r.semaphore.release();
332 private synchronized void processRequests() {
336 if(requests.isEmpty()) return;
337 TransactionRequest req = requests.peek();
339 if(currentTransactionState == TransactionState.IDLE) {
341 // Accept anything while IDLE
342 currentTransactionState = req.state;
345 } else if (currentTransactionState == TransactionState.READ) {
347 if(req.state == currentTransactionState) {
359 } else if (currentTransactionState == TransactionState.WRITE) {
370 private synchronized TransactionRequest queue(TransactionState state, Semaphore semaphore) {
371 TransactionRequest req = new TransactionRequest(state, semaphore);
372 requests.addLast(req);
378 * This method cannot be synchronized since it waits and must support multiple entries
379 * by query thread(s) and internal transactions such as snapshot saver
381 public Transaction askWriteTransaction() throws IllegalAcornStateException {
383 Semaphore semaphore = new Semaphore(0);
384 TransactionRequest req = queue(TransactionState.WRITE, semaphore);
388 } catch (InterruptedException e) {
389 throw new IllegalAcornStateException(e);
391 mainProgram.startTransaction(clusters.state.headChangeSetId+1);
392 return makeTransaction(req);
395 public synchronized long endTransaction(long transactionId) throws ProCoreException {
397 TransactionRequest req = requestMap.remove(transactionId);
398 if(req.state == TransactionState.WRITE) {
399 currentTransactionState = TransactionState.IDLE;
404 currentTransactionState = TransactionState.IDLE;
408 return clusters.state.transactionId;
414 public Transaction askWriteTransaction(final long transactionId) throws ProCoreException {
416 if (isClosing || unexpectedClose || closed) {
417 throw new ProCoreException("GraphClientImpl2 is already closing so no more write transactions allowed!");
419 return transactionManager.askWriteTransaction();
420 } catch (IllegalAcornStateException e) {
421 throw new ProCoreException(e);
426 public long endTransaction(long transactionId) throws ProCoreException {
427 return transactionManager.endTransaction(transactionId);
431 public String execute(String command) throws ProCoreException {
432 // This is called only by WriteGraphImpl.commitAccessorChanges
433 // We can ignore this in Acorn
438 public byte[] getChangeSetMetadata(long changeSetId) throws ProCoreException {
440 return clusters.getMetadata(changeSetId);
441 } catch (AcornAccessVerificationException | IllegalAcornStateException e) {
442 throw new ProCoreException(e);
447 public ChangeSetData getChangeSetData(long minChangeSetId,
448 long maxChangeSetId, OnChangeSetUpdate onChangeSetupate)
449 throws ProCoreException {
451 new Exception("GetChangeSetDataFunction " + minChangeSetId + " " + maxChangeSetId).printStackTrace();;
457 public ChangeSetIds getChangeSetIds() throws ProCoreException {
458 throw new UnsupportedOperationException();
462 public Cluster getCluster(byte[] clusterId) throws ProCoreException {
463 throw new UnsupportedOperationException();
467 public ClusterChanges getClusterChanges(long changeSetId, byte[] clusterId)
468 throws ProCoreException {
469 throw new UnsupportedOperationException();
473 public ClusterIds getClusterIds() throws ProCoreException {
475 return clusters.getClusterIds();
476 } catch (IllegalAcornStateException e) {
477 throw new ProCoreException(e);
482 public Information getInformation() throws ProCoreException {
483 return new Information() {
486 public String getServerId() {
491 public String getProtocolId() {
496 public String getDatabaseId() {
501 public long getFirstChangeSetId() {
509 public Refresh getRefresh(long changeSetId) throws ProCoreException {
511 final ClusterIds ids = getClusterIds();
513 return new Refresh() {
516 public long getHeadChangeSetId() {
517 return clusters.state.headChangeSetId;
521 public long[] getFirst() {
522 return ids.getFirst();
526 public long[] getSecond() {
527 return ids.getSecond();
534 public byte[] getResourceFile(final byte[] clusterUID, final int resourceIndex) throws ProCoreException, AcornAccessVerificationException, IllegalAcornStateException {
535 return clusters.getResourceFile(clusterUID, resourceIndex);
539 public ResourceSegment getResourceSegment(final byte[] clusterUID, final int resourceIndex, final long segmentOffset, short segmentSize) throws ProCoreException {
541 return clusters.getResourceSegment(clusterUID, resourceIndex, segmentOffset, segmentSize);
542 } catch (AcornAccessVerificationException | IllegalAcornStateException e) {
543 throw new ProCoreException(e);
548 public long reserveIds(int count) throws ProCoreException {
549 return clusters.state.reservedIds++;
553 public void updateCluster(byte[] operations) throws ProCoreException {
554 ClusterInfo info = null;
556 ClusterUpdateOperation operation = new ClusterUpdateOperation(clusters, operations);
557 info = clusters.clusterLRU.getOrCreate(operation.uid, true);
559 throw new IllegalAcornStateException("info == null for operation " + operation);
561 info.scheduleUpdate();
562 mainProgram.schedule(operation);
563 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
564 throw new ProCoreException(e);
571 private UndoClusterUpdateProcessor getUndoCSS(String ccsId) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
573 String[] ss = ccsId.split("\\.");
574 String chunkKey = ss[0];
575 int chunkOffset = Integer.parseInt(ss[1]);
576 ClusterStreamChunk chunk = clusters.streamLRU.getWithoutMutex(chunkKey);
577 if(chunk == null) throw new IllegalAcornStateException("Cluster Stream Chunk " + chunkKey + " was not found.");
578 chunk.acquireMutex();
580 return chunk.getUndoProcessor(clusters, chunkOffset, ccsId);
581 } catch (DatabaseException e) {
583 } catch (Throwable t) {
584 throw new IllegalStateException(t);
586 chunk.releaseMutex();
590 private void performUndo(String ccsId, ArrayList<Pair<ClusterUID, byte[]>> clusterChanges, UndoClusterSupport support) throws ProCoreException, DatabaseException, IllegalAcornStateException, AcornAccessVerificationException {
591 UndoClusterUpdateProcessor proc = getUndoCSS(ccsId);
593 int clusterKey = clusters.getClusterKeyByClusterUIDOrMakeWithoutMutex(proc.getClusterUID());
595 clusters.clusterLRU.acquireMutex();
598 ClusterChange cs = new ClusterChange(clusterChanges, proc.getClusterUID());
599 for(int i=0;i<proc.entries.size();i++) {
601 Entry e = proc.entries.get(proc.entries.size() - 1 - i);
602 e.process(clusters, cs, clusterKey);
607 clusters.clusterLRU.releaseMutex();
612 public boolean undo(long[] changeSetIds, OnChangeSetUpdate onChangeSetUpdate) throws SDBException {
614 Exception exception = mainProgram.runIdle(new MainProgramRunnable() {
617 public void run() throws Exception {
621 final ArrayList<Pair<ClusterUID, byte[]>> clusterChanges = new ArrayList<Pair<ClusterUID, byte[]>>();
623 UndoClusterSupport support = new UndoClusterSupport(clusters);
625 final int changeSetId = clusters.state.headChangeSetId;
627 if(ClusterUpdateProcessorBase.DEBUG)
628 System.err.println(" === BEGIN UNDO ===");
630 for(int i=0;i<changeSetIds.length;i++) {
631 final long id = changeSetIds[changeSetIds.length-1-i];
632 ArrayList<String> ccss = clusters.getChanges(id);
634 for(int j=0;j<ccss.size();j++) {
635 String ccsid = ccss.get(ccss.size()-j-1);
637 if(ClusterUpdateProcessorBase.DEBUG)
638 System.err.println("performUndo " + ccsid);
639 performUndo(ccsid, clusterChanges, support);
640 } catch (DatabaseException e) {
646 if(ClusterUpdateProcessorBase.DEBUG)
647 System.err.println(" === END UNDO ===");
649 for(int i=0;i<clusterChanges.size();i++) {
651 final int changeSetIndex = i;
653 final Pair<ClusterUID, byte[]> pair = clusterChanges.get(i);
655 final ClusterUID cuid = pair.first;
656 final byte[] data = pair.second;
658 onChangeSetUpdate.onChangeSetUpdate(new ChangeSetUpdate() {
661 public long getChangeSetId() {
666 public int getChangeSetIndex() {
671 public int getNumberOfClusterChangeSets() {
672 return clusterChanges.size();
676 public int getIndexOfClusterChangeSet() {
677 return changeSetIndex;
681 public byte[] getClusterId() {
682 return cuid.asBytes();
686 public boolean getNewCluster() {
691 public byte[] getData() {
697 } catch (AcornAccessVerificationException | IllegalAcornStateException e1) {
698 throw new ProCoreException(e1);
710 if(exception instanceof SDBException) throw (SDBException)exception;
711 else if(exception != null) throw new IllegalAcornStateException(exception);
717 public ServiceLocator getServiceLocator() {
722 public boolean refreshEnabled() {
727 public boolean rolledback() {
728 return clusters.rolledback();
731 public void purge() throws IllegalAcornStateException {
732 clusters.purge(locator);
735 public void purgeDatabase() {
737 if (isClosing || unexpectedClose)
740 saver.execute(new Runnable() {
744 Transaction tr = null;
746 // First take a write transaction
747 tr = askWriteTransaction(-1);
748 // Then make sure that MainProgram is idling
749 mainProgram.mutex.acquire();
751 synchronized(mainProgram) {
752 if(mainProgram.operations.isEmpty()) {
755 // MainProgram is becoming busy again - delay snapshotting
760 mainProgram.mutex.release();
762 } catch (IllegalAcornStateException | ProCoreException e) {
763 LOGGER.error("Purge failed", e);
764 unexpectedClose = true;
765 } catch (InterruptedException e) {
766 LOGGER.error("Purge interrupted", e);
770 endTransaction(tr.getTransactionId());
771 if (unexpectedClose) {
772 LifecycleSupport support = getServiceLocator().getService(LifecycleSupport.class);
775 } catch (DatabaseException e1) {
776 LOGGER.error("Failed to close database as a safety measure due to failed purge", e1);
779 } catch (ProCoreException e) {
780 LOGGER.error("Failed to end purge write transaction", e);
788 public long getTailChangeSetId() {
789 return clusters.getTailChangeSetId();