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.exception.AcornAccessVerificationException;
25 import org.simantics.acorn.exception.IllegalAcornStateException;
26 import org.simantics.acorn.internal.ClusterChange;
27 import org.simantics.acorn.internal.ClusterUpdateProcessorBase;
28 import org.simantics.acorn.internal.UndoClusterUpdateProcessor;
29 import org.simantics.acorn.lru.ClusterInfo;
30 import org.simantics.acorn.lru.ClusterStreamChunk;
31 import org.simantics.acorn.lru.ClusterUpdateOperation;
32 import org.simantics.acorn.lru.ClusterChangeSet.Entry;
33 import org.simantics.db.ClusterCreator;
34 import org.simantics.db.Database;
35 import org.simantics.db.ServiceLocator;
36 import org.simantics.db.common.utils.Logger;
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;
46 import gnu.trove.map.hash.TLongObjectHashMap;
48 public class GraphClientImpl2 implements Database.Session {
50 public static final boolean DEBUG = false;
52 public final ClusterManager clusters;
54 private TransactionManager transactionManager = new TransactionManager();
55 private ExecutorService executor = Executors.newSingleThreadExecutor(new ClientThreadFactory("Core Main Program", false));
56 private ExecutorService saver = Executors.newSingleThreadExecutor(new ClientThreadFactory("Core Snapshot Saver", true));
58 private Path dbFolder;
59 private final Database database;
60 private ServiceLocator locator;
61 private MainProgram mainProgram;
63 static class ClientThreadFactory implements ThreadFactory {
68 public ClientThreadFactory(String name, boolean daemon) {
74 public Thread newThread(Runnable r) {
75 Thread thread = new Thread(r, name);
76 thread.setDaemon(daemon);
81 public GraphClientImpl2(Database database, Path dbFolder, ServiceLocator locator) throws IOException {
82 this.database = database;
83 this.dbFolder = dbFolder;
84 this.locator = locator;
85 this.clusters = new ClusterManager(dbFolder);
87 ClusterSetsSupport cssi = locator.getService(ClusterSetsSupport.class);
88 cssi.setReadDirectory(clusters.lastSessionDirectory);
89 mainProgram = new MainProgram(this, clusters);
90 executor.execute(mainProgram);
93 public Path getDbFolder() {
97 public void tryMakeSnapshot() throws IOException {
99 if (isClosing || unexpectedClose)
102 saver.execute(new Runnable() {
106 Transaction tr = null;
108 // First take a write transaction
109 tr = askWriteTransaction(-1);
110 // Then make sure that MainProgram is idling
111 mainProgram.mutex.acquire();
113 synchronized(mainProgram) {
114 if(mainProgram.operations.isEmpty()) {
117 // MainProgram is becoming busy again - delay snapshotting
122 mainProgram.mutex.release();
124 } catch (IllegalAcornStateException | ProCoreException e) {
125 Logger.defaultLogError("Snapshotting failed", e);
126 unexpectedClose = true;
127 } catch (InterruptedException e) {
128 Logger.defaultLogError("Snapshotting interrupted", e);
132 endTransaction(tr.getTransactionId());
133 if (unexpectedClose) {
134 LifecycleSupport support = getServiceLocator().getService(LifecycleSupport.class);
137 } catch (DatabaseException e1) {
138 Logger.defaultLogError("Failed to close database as a safety measure due to failed snapshotting", e1);
141 } catch (ProCoreException e) {
142 Logger.defaultLogError("Failed to end snapshotting write transaction", e);
149 public void makeSnapshot(boolean fullSave) throws IllegalAcornStateException {
150 clusters.makeSnapshot(locator, fullSave);
153 public <T> T clone(ClusterUID uid, ClusterCreator creator) throws DatabaseException {
155 return clusters.clone(uid, creator);
156 } catch (AcornAccessVerificationException | IllegalAcornStateException | IOException e) {
157 unexpectedClose = true;
158 throw new DatabaseException(e);
162 // private void save() throws IOException {
166 public void load() throws IOException {
170 // public void modiFileEx(ClusterUID uid, int resourceKey, long offset, long size, byte[] bytes, long pos, ClusterSupport support) {
171 // clusters.modiFileEx(uid, resourceKey, offset, size, bytes, pos, support);
175 public Database getDatabase() {
179 private boolean closed = false;
180 private boolean isClosing = false;
181 private boolean unexpectedClose = false;
184 public void close() throws ProCoreException {
185 System.err.println("Closing " + this + " and mainProgram " + mainProgram);
186 if(!closed && !isClosing) {
189 if (!unexpectedClose)
196 boolean executorTerminated = executor.awaitTermination(500, TimeUnit.MILLISECONDS);
197 boolean saverTerminated = saver.awaitTermination(500, TimeUnit.MILLISECONDS);
199 System.err.println("executorTerminated=" + executorTerminated + ", saverTerminated=" + saverTerminated);
205 } catch (IllegalAcornStateException | InterruptedException e) {
206 throw new ProCoreException(e);
214 public void open() throws ProCoreException {
215 throw new UnsupportedOperationException();
219 public boolean isClosed() throws ProCoreException {
224 public void acceptCommit(long transactionId, long changeSetId, byte[] metadata) throws ProCoreException {
225 clusters.state.headChangeSetId++;
226 long committedChangeSetId = changeSetId + 1;
228 clusters.commitChangeSet(committedChangeSetId, metadata);
230 clusters.state.transactionId = transactionId;
232 mainProgram.committed();
234 TimeLogger.log("Accepted commit");
235 } catch (IllegalAcornStateException e) {
236 throw new ProCoreException(e);
241 public long cancelCommit(long transactionId, long changeSetId, byte[] metadata, OnChangeSetUpdate onChangeSetUpdate) throws ProCoreException {
242 // Accept and finalize current transaction and then undo it
243 acceptCommit(transactionId, changeSetId, metadata);
246 undo(new long[] {changeSetId+1}, onChangeSetUpdate);
247 clusters.state.headChangeSetId++;
248 return clusters.state.headChangeSetId;
249 } catch (SDBException e) {
250 Logger.defaultLogError("Failed to undo cancelled transaction", e);
251 throw new ProCoreException(e);
256 public Transaction askReadTransaction() throws ProCoreException {
257 return transactionManager.askReadTransaction();
260 enum TransactionState {
264 class TransactionRequest {
265 public TransactionState state;
266 public Semaphore semaphore;
267 public TransactionRequest(TransactionState state, Semaphore semaphore) {
269 this.semaphore = semaphore;
273 class TransactionManager {
275 private TransactionState currentTransactionState = TransactionState.IDLE;
277 private int reads = 0;
279 LinkedList<TransactionRequest> requests = new LinkedList<TransactionRequest>();
281 TLongObjectHashMap<TransactionRequest> requestMap = new TLongObjectHashMap<TransactionRequest>();
283 private synchronized Transaction makeTransaction(TransactionRequest req) {
285 final int csId = clusters.state.headChangeSetId;
286 final long trId = clusters.state.transactionId+1;
287 requestMap.put(trId, req);
288 return new Transaction() {
291 public long getTransactionId() {
296 public long getHeadChangeSetId() {
303 * This method cannot be synchronized since it waits and must support multiple entries
304 * by query thread(s) and internal transactions such as snapshot saver
306 public Transaction askReadTransaction() throws ProCoreException {
308 Semaphore semaphore = new Semaphore(0);
310 TransactionRequest req = queue(TransactionState.READ, semaphore);
314 } catch (InterruptedException e) {
315 throw new ProCoreException(e);
318 return makeTransaction(req);
322 private synchronized void dispatch() {
323 TransactionRequest r = requests.removeFirst();
324 if(r.state == TransactionState.READ) reads++;
325 r.semaphore.release();
328 private synchronized void processRequests() {
332 if(requests.isEmpty()) return;
333 TransactionRequest req = requests.peek();
335 if(currentTransactionState == TransactionState.IDLE) {
337 // Accept anything while IDLE
338 currentTransactionState = req.state;
341 } else if (currentTransactionState == TransactionState.READ) {
343 if(req.state == currentTransactionState) {
355 } else if (currentTransactionState == TransactionState.WRITE) {
366 private synchronized TransactionRequest queue(TransactionState state, Semaphore semaphore) {
367 TransactionRequest req = new TransactionRequest(state, semaphore);
368 requests.addLast(req);
374 * This method cannot be synchronized since it waits and must support multiple entries
375 * by query thread(s) and internal transactions such as snapshot saver
377 public Transaction askWriteTransaction() throws IllegalAcornStateException {
379 Semaphore semaphore = new Semaphore(0);
380 TransactionRequest req = queue(TransactionState.WRITE, semaphore);
384 } catch (InterruptedException e) {
385 throw new IllegalAcornStateException(e);
387 mainProgram.startTransaction(clusters.state.headChangeSetId+1);
388 return makeTransaction(req);
391 public synchronized long endTransaction(long transactionId) throws ProCoreException {
393 TransactionRequest req = requestMap.remove(transactionId);
394 if(req.state == TransactionState.WRITE) {
395 currentTransactionState = TransactionState.IDLE;
400 currentTransactionState = TransactionState.IDLE;
404 return clusters.state.transactionId;
410 public Transaction askWriteTransaction(final long transactionId) throws ProCoreException {
412 if (isClosing || unexpectedClose || closed) {
413 throw new ProCoreException("GraphClientImpl2 is already closing so no more write transactions allowed!");
415 return transactionManager.askWriteTransaction();
416 } catch (IllegalAcornStateException e) {
417 throw new ProCoreException(e);
422 public long endTransaction(long transactionId) throws ProCoreException {
423 return transactionManager.endTransaction(transactionId);
427 public String execute(String command) throws ProCoreException {
428 // This is called only by WriteGraphImpl.commitAccessorChanges
429 // We can ignore this in Acorn
434 public byte[] getChangeSetMetadata(long changeSetId) throws ProCoreException {
436 return clusters.getMetadata(changeSetId);
437 } catch (AcornAccessVerificationException | IllegalAcornStateException e) {
438 throw new ProCoreException(e);
443 public ChangeSetData getChangeSetData(long minChangeSetId,
444 long maxChangeSetId, OnChangeSetUpdate onChangeSetupate)
445 throws ProCoreException {
447 new Exception("GetChangeSetDataFunction " + minChangeSetId + " " + maxChangeSetId).printStackTrace();;
453 public ChangeSetIds getChangeSetIds() throws ProCoreException {
454 throw new UnsupportedOperationException();
458 public Cluster getCluster(byte[] clusterId) throws ProCoreException {
459 throw new UnsupportedOperationException();
463 public ClusterChanges getClusterChanges(long changeSetId, byte[] clusterId)
464 throws ProCoreException {
465 throw new UnsupportedOperationException();
469 public ClusterIds getClusterIds() throws ProCoreException {
471 return clusters.getClusterIds();
472 } catch (IllegalAcornStateException e) {
473 throw new ProCoreException(e);
478 public Information getInformation() throws ProCoreException {
479 return new Information() {
482 public String getServerId() {
487 public String getProtocolId() {
492 public String getDatabaseId() {
497 public long getFirstChangeSetId() {
505 public Refresh getRefresh(long changeSetId) throws ProCoreException {
507 final ClusterIds ids = getClusterIds();
509 return new Refresh() {
512 public long getHeadChangeSetId() {
513 return clusters.state.headChangeSetId;
517 public long[] getFirst() {
518 return ids.getFirst();
522 public long[] getSecond() {
523 return ids.getSecond();
530 public byte[] getResourceFile(final byte[] clusterUID, final int resourceIndex) throws ProCoreException, AcornAccessVerificationException, IllegalAcornStateException {
531 return clusters.getResourceFile(clusterUID, resourceIndex);
535 public ResourceSegment getResourceSegment(final byte[] clusterUID, final int resourceIndex, final long segmentOffset, short segmentSize) throws ProCoreException {
537 return clusters.getResourceSegment(clusterUID, resourceIndex, segmentOffset, segmentSize);
538 } catch (AcornAccessVerificationException | IllegalAcornStateException e) {
539 throw new ProCoreException(e);
544 public long reserveIds(int count) throws ProCoreException {
545 return clusters.state.reservedIds++;
549 public void updateCluster(byte[] operations) throws ProCoreException {
550 ClusterInfo info = null;
552 ClusterUpdateOperation operation = new ClusterUpdateOperation(clusters, operations);
553 info = clusters.clusterLRU.getOrCreate(operation.uid, true);
555 throw new IllegalAcornStateException("info == null for operation " + operation);
557 info.scheduleUpdate();
558 mainProgram.schedule(operation);
559 } catch (IllegalAcornStateException | AcornAccessVerificationException e) {
560 throw new ProCoreException(e);
567 private UndoClusterUpdateProcessor getUndoCSS(String ccsId) throws DatabaseException, AcornAccessVerificationException, IllegalAcornStateException {
569 String[] ss = ccsId.split("\\.");
570 String chunkKey = ss[0];
571 int chunkOffset = Integer.parseInt(ss[1]);
572 ClusterStreamChunk chunk = clusters.streamLRU.getWithoutMutex(chunkKey);
573 if(chunk == null) throw new IllegalAcornStateException("Cluster Stream Chunk " + chunkKey + " was not found.");
574 chunk.acquireMutex();
576 return chunk.getUndoProcessor(clusters, chunkOffset, ccsId);
577 } catch (DatabaseException e) {
579 } catch (Throwable t) {
580 throw new IllegalStateException(t);
582 chunk.releaseMutex();
586 private void performUndo(String ccsId, ArrayList<Pair<ClusterUID, byte[]>> clusterChanges, UndoClusterSupport support) throws ProCoreException, DatabaseException, IllegalAcornStateException, AcornAccessVerificationException {
587 UndoClusterUpdateProcessor proc = getUndoCSS(ccsId);
589 int clusterKey = clusters.getClusterKeyByClusterUIDOrMakeWithoutMutex(proc.getClusterUID());
591 clusters.clusterLRU.acquireMutex();
594 ClusterChange cs = new ClusterChange(clusterChanges, proc.getClusterUID());
595 for(int i=0;i<proc.entries.size();i++) {
597 Entry e = proc.entries.get(proc.entries.size() - 1 - i);
598 e.process(clusters, cs, clusterKey);
603 clusters.clusterLRU.releaseMutex();
608 public boolean undo(long[] changeSetIds, OnChangeSetUpdate onChangeSetUpdate) throws SDBException {
610 final ArrayList<Pair<ClusterUID, byte[]>> clusterChanges = new ArrayList<Pair<ClusterUID, byte[]>>();
612 UndoClusterSupport support = new UndoClusterSupport(clusters);
614 final int changeSetId = clusters.state.headChangeSetId;
616 if(ClusterUpdateProcessorBase.DEBUG)
617 System.err.println(" === BEGIN UNDO ===");
619 for(int i=0;i<changeSetIds.length;i++) {
620 final long id = changeSetIds[changeSetIds.length-1-i];
621 ArrayList<String> ccss = clusters.getChanges(id);
623 for(int j=0;j<ccss.size();j++) {
624 String ccsid = ccss.get(ccss.size()-j-1);
626 if(ClusterUpdateProcessorBase.DEBUG)
627 System.err.println("performUndo " + ccsid);
628 performUndo(ccsid, clusterChanges, support);
629 } catch (DatabaseException e) {
635 if(ClusterUpdateProcessorBase.DEBUG)
636 System.err.println(" === END UNDO ===");
638 for(int i=0;i<clusterChanges.size();i++) {
640 final int changeSetIndex = i;
642 final Pair<ClusterUID, byte[]> pair = clusterChanges.get(i);
644 final ClusterUID cuid = pair.first;
645 final byte[] data = pair.second;
647 onChangeSetUpdate.onChangeSetUpdate(new ChangeSetUpdate() {
650 public long getChangeSetId() {
655 public int getChangeSetIndex() {
660 public int getNumberOfClusterChangeSets() {
661 return clusterChanges.size();
665 public int getIndexOfClusterChangeSet() {
666 return changeSetIndex;
670 public byte[] getClusterId() {
671 return cuid.asBytes();
675 public boolean getNewCluster() {
680 public byte[] getData() {
686 } catch (AcornAccessVerificationException | IllegalAcornStateException e1) {
687 throw new ProCoreException(e1);
692 public ServiceLocator getServiceLocator() {
697 public boolean refreshEnabled() {
702 public boolean rolledback() {
703 return clusters.rolledback();
716 ////////////////////////