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 fi.vtt.simantics.procore.internal;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashMap;
19 import java.util.TreeMap;
20 import java.util.concurrent.Semaphore;
21 import java.util.concurrent.atomic.AtomicLong;
22 import java.util.function.Consumer;
24 import org.simantics.databoard.Bindings;
25 import org.simantics.db.ClusterCreator;
26 import org.simantics.db.Database;
27 import org.simantics.db.Database.Session.ClusterChanges;
28 import org.simantics.db.DevelopmentKeys;
29 import org.simantics.db.SessionVariables;
30 import org.simantics.db.common.utils.Logger;
31 import org.simantics.db.exception.ClusterDoesNotExistException;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.exception.ResourceNotFoundException;
34 import org.simantics.db.exception.RuntimeDatabaseException;
35 import org.simantics.db.impl.ClusterBase;
36 import org.simantics.db.impl.ClusterI;
37 import org.simantics.db.impl.ClusterSupport;
38 import org.simantics.db.impl.ClusterTraitsBase;
39 import org.simantics.db.impl.IClusterTable;
40 import org.simantics.db.impl.graph.WriteGraphImpl;
41 import org.simantics.db.impl.query.QueryProcessor;
42 import org.simantics.db.procore.cluster.ClusterBig;
43 import org.simantics.db.procore.cluster.ClusterImpl;
44 import org.simantics.db.procore.cluster.ClusterSmall;
45 import org.simantics.db.procore.cluster.ClusterTraits;
46 import org.simantics.db.procore.protocol.Constants;
47 import org.simantics.db.service.ClusterCollectorPolicy;
48 import org.simantics.db.service.ClusterCollectorPolicy.CollectorCluster;
49 import org.simantics.db.service.ClusterUID;
50 import org.simantics.utils.Development;
52 import fi.vtt.simantics.procore.DebugPolicy;
53 import fi.vtt.simantics.procore.internal.ClusterControlImpl.ClusterStateImpl;
54 import fi.vtt.simantics.procore.internal.SessionImplSocket.TaskHelper;
55 import gnu.trove.map.hash.TLongIntHashMap;
56 import gnu.trove.map.hash.TLongObjectHashMap;
57 import gnu.trove.procedure.TIntProcedure;
58 import gnu.trove.procedure.TLongObjectProcedure;
59 import gnu.trove.procedure.TObjectProcedure;
60 import gnu.trove.set.hash.TIntHashSet;
62 public final class ClusterTable implements IClusterTable {
64 private static final boolean VALIDATE_SIZE = false;
66 int maximumBytes = 128 * 1024 * 1024;
67 int limit = (int)(0.8*(double)maximumBytes);
69 private final AtomicLong timeCounter = new AtomicLong(1);
71 final private SessionImplSocket sessionImpl;
72 final private ArrayList<ClusterI> writeOnlyClusters = new ArrayList<ClusterI>();
73 final private TIntHashSet writeOnlyInvalidates = new TIntHashSet();
74 final private static int ARRAY_SIZE = ClusterTraits.getClusterArraySize();
75 final private ClusterImpl[] clusterArray = new ClusterImpl[ARRAY_SIZE];
76 final private Boolean[] immutables = new Boolean[ARRAY_SIZE];
77 final private boolean[] virtuals = new boolean[ARRAY_SIZE];
78 static class ImportanceEntry implements CollectorCluster {
79 final public long importance;
80 final public long clusterId;
81 public ImportanceEntry(ClusterImpl impl) {
82 this(impl.getImportance(), impl.getClusterId());
85 public ImportanceEntry(long importance, long clusterId) {
86 this.importance = importance;
87 this.clusterId = clusterId;
90 public long getImportance() {
94 public long getClusterId() {
98 public String toString() {
99 return "CID " + clusterId;
102 private class Clusters {
103 // This makes sure that non-null values from hashMap.get can be trusted (no unsynchronized rehashes occur)
104 final public TLongObjectHashMap<ClusterImpl> hashMap = new TLongObjectHashMap<ClusterImpl>(2 * ARRAY_SIZE);
105 //private final HashMap<ClusterUID, ClusterImpl> clusterU2I = new HashMap<ClusterUID, ClusterImpl>(); // Maps cluster UID to cluster.
109 private void clear() {
111 // clusterU2I.clear();
112 hashMap.put(0, null); // reserved for null value
113 // clusterU2I.put(ClusterUID.make(0, 0), null);
116 return hashMap.size();
118 private ClusterImpl getClusterByClusterId(long clusterId) {
119 return hashMap.get(clusterId);
121 private ClusterImpl getClusterByClusterUID(ClusterUID clusterUID) {
122 return getClusterByClusterId(clusterUID.second);
123 //return clusterU2I.get(clusterUID);
125 private ClusterImpl getClusterByClusterUID(long id1, long id2) {
126 return getClusterByClusterId(id2);
128 private ClusterImpl makeProxy(long clusterId) {
129 return makeProxy(ClusterUID.make(0, clusterId));
131 private ClusterImpl makeProxy(ClusterUID clusterUID) {
132 ClusterImpl proxy = hashMap.get(clusterUID.second);
135 int clusterKey = hashMap.size();
136 ClusterSmall sentinel = new ClusterSmall(clusterUID, clusterKey, ClusterTable.this, sessionImpl.clusterTranslator);
137 if (sentinel.clusterId != sentinel.clusterUID.second)
138 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
142 private void replace(ClusterImpl proxy) {
143 ClusterImpl old = clusterArray[proxy.clusterKey];
146 if (old.clusterKey != proxy.clusterKey)
147 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
148 if (old.clusterId != proxy.clusterId)
149 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
150 if (!old.clusterUID.equals(proxy.clusterUID))
151 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
154 private ClusterSmall freeProxy(ClusterImpl proxy) {
155 ClusterImpl clusterImpl = hashMap.get(proxy.clusterId);
156 if (null == clusterImpl)
157 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
158 // ClusterUID clusterUID = ClusterUID.make(0, proxy.clusterId);
159 // ClusterImpl clusterImpl2 = clusterU2I.get(clusterUID );
160 // if (clusterImpl != clusterImpl2)
161 // throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
162 if (proxy.clusterId != clusterImpl.clusterId)
163 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
164 if (proxy.clusterKey != clusterImpl.clusterKey)
165 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
166 ClusterSmall sentinel = new ClusterSmall(makeClusterUID(proxy.clusterId) , proxy.clusterKey, ClusterTable.this, sessionImpl.clusterTranslator);
167 return (ClusterSmall)create(sentinel);
169 private ClusterImpl create(ClusterImpl clusterImpl) {
170 hashMap.put(clusterImpl.clusterId, clusterImpl);
171 // clusterU2I.put(clusterImpl.clusterUID, clusterImpl);
172 clusterArray[clusterImpl.clusterKey] = clusterImpl;
175 private void forEachValue(TObjectProcedure<ClusterImpl> procedure) {
176 hashMap.forEachValue(procedure);
178 private void forEachEntry(TLongObjectProcedure<ClusterImpl> procedure) {
179 hashMap.forEachEntry(procedure);
181 private ClusterUID makeClusterUID(long clusterId) {
182 return ClusterUID.make(0, clusterId);
184 private void removeProxy(ClusterImpl proxy) {
185 hashMap.remove(proxy.clusterId);
186 clusterArray[proxy.clusterKey] = null;
189 final public TreeMap<Long, CollectorCluster> importanceMap = new TreeMap<Long, CollectorCluster>();
191 private ClusterCollectorPolicy collectorPolicy;
192 private boolean dirtySizeInBytes = true;
193 private long sizeInBytes = 0;
194 private final Clusters clusters;
195 ClusterUID makeClusterUID(long clusterId) {
196 return clusters.makeClusterUID(clusterId);
198 public ClusterUID getClusterUIDByResourceKey(int resourceKey) throws DatabaseException {
199 int clusterKey = ClusterTraits.getClusterKeyFromResourceKey(resourceKey);
200 return clusterArray[clusterKey].clusterUID;
202 ClusterTable(SessionImplSocket sessionImpl, File folderPath) {
203 this.sessionImpl = sessionImpl;
204 clusters = new Clusters();
209 importanceMap.clear();
212 public void setCollectorPolicy(ClusterCollectorPolicy policy) {
213 this.collectorPolicy = policy;
217 * Sets Cluster Table allocation size by percentage of maximum usable
218 * memory. Allocation is limited between 5% and 50% of maximum memory.
222 private void setAllocateSize(double percentage) {
224 percentage = Math.max(percentage, 0.05);
225 percentage = Math.min(percentage, 0.5);
227 maximumBytes = (int) Math.floor(percentage * Runtime.getRuntime().maxMemory());
230 private double estimateProperAllocation(ClusterCollectorSupport support) {
231 long max = Runtime.getRuntime().maxMemory();
232 long free = Runtime.getRuntime().freeMemory();
233 long total = Runtime.getRuntime().totalMemory();
234 long realFree = max - total + free; // amount of free memory
235 long current = support.getCurrentSize(); // currently allocated cache
236 long inUseTotal = max - realFree; // currently used memory
237 long inUseOther = inUseTotal - current; // memory that the application uses (without the cache)
238 double otherUsePercentage = (double) inUseOther / (double) max; // percentage of memory that the application uses
239 double aimFree = 0.2; // percentage of maximum heap that we try to keep free
240 double estimate = 1.0 - otherUsePercentage - aimFree;
241 estimate = Math.min(estimate, 0.5);
242 estimate = Math.max(estimate, 0.05);
243 // System.out.println("Estimated allocation percentage " + estimate +
244 // " memory stats: max: " + max + ", free: " + realFree + ", inUse: " +
245 // inUseTotal + ", cached: " + current + ", cacheSize: " + maximumBytes);
249 void checkCollect() {
253 synchronized ClusterImpl getClusterByClusterId(long clusterId) {
254 return clusters.getClusterByClusterId(clusterId);
257 ClusterBase getClusterByClusterKey(int clusterKey) {
258 return clusterArray[clusterKey];
261 synchronized ClusterImpl makeProxy(ClusterUID clusterUID, long clusterId) {
262 if (clusterUID.second != clusterId)
263 throw new RuntimeDatabaseException("Illegal id for cluster=" + clusterUID + " id=" + clusterId);
264 return clusters.makeProxy(clusterUID);
267 synchronized ClusterImpl makeCluster(long clusterId, boolean writeOnly) {
269 ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
272 ClusterUID clusterUID = ClusterUID.make(0, clusterId);
273 int clusterKey = clusters.size(); // new key
275 proxy = new ClusterWriteOnly(clusterUID, clusterKey, sessionImpl);
276 writeOnlyClusters.add(proxy);
277 return clusters.create(proxy);
279 //printMaps("makeCluster");
280 ClusterImpl cluster = ClusterImpl.make(clusterUID, clusterKey, sessionImpl.clusterTranslator);
281 clusters.create(cluster);
282 if (!cluster.isLoaded())
283 Logger.defaultLogError(new Exception("Bug in ClusterTable.makeCluster(long, boolean), cluster not loaded"));
284 importanceMap.put(cluster.getImportance(), new ImportanceEntry(cluster));
286 validateSize("makeCluster");
287 if(collectorPolicy != null) collectorPolicy.added(cluster);
292 synchronized void replaceCluster(ClusterI cluster) {
293 //printMaps("replaceCluster");
295 int clusterKey = cluster.getClusterKey();
296 ClusterI existing = clusterArray[clusterKey];
297 if (existing.hasVirtual())
298 cluster.markVirtual();
300 importanceMap.remove(existing.getImportance());
301 if (collectorPolicy != null)
302 collectorPolicy.removed((ClusterImpl)existing);
304 //System.out.println("ClusterTable.replace(" + existing + " (I=" + existing.getImportance() + ") => " + cluster + " (I=" + cluster.getImportance() + ")");
306 clusters.replace((ClusterImpl)cluster);
307 if (!cluster.isLoaded())
308 Logger.defaultLogError(new Exception("Bug in ClusterTable.replaceCluster(ClusterI), cluster not loaded"));
310 importanceMap.put(cluster.getImportance(), new ImportanceEntry((ClusterImpl)cluster));
311 if(collectorPolicy != null) collectorPolicy.added((ClusterImpl)cluster);
313 if (!dirtySizeInBytes) {
314 if (existing != cluster) {
315 adjustCachedSize(-existing.getCachedSize(), existing);
317 // This will update sizeInBytes through adjustCachedSize
318 cluster.getCachedSize();
321 validateSize("replaceCluster");
324 synchronized void release(CollectorCluster cluster) {
325 importanceMap.remove(cluster.getImportance());
326 release(cluster.getClusterId());
329 synchronized void release(long clusterId) {
330 //System.out.println("ClusterTable.release(" + clusterId + "): " + sizeInBytes);
332 ClusterImpl clusterImpl = clusters.getClusterByClusterId(clusterId);
333 if (null == clusterImpl)
335 if(!clusterImpl.isLoaded() || clusterImpl.isEmpty())
337 //printMaps("release");
338 clusters.freeProxy(clusterImpl);
339 importanceMap.remove(clusterImpl.getImportance());
340 if (collectorPolicy != null)
341 collectorPolicy.removed(clusterImpl);
342 if (sessionImpl.writeState != null)
343 sessionImpl.clusterStream.flush(clusterImpl.clusterUID);
344 if (!dirtySizeInBytes) {
345 adjustCachedSize(-clusterImpl.getCachedSize(), clusterImpl);
348 validateSize("release");
351 synchronized void compact(long id) {
352 ClusterI impl = clusters.getClusterByClusterId(id);
358 // cachedSize = getSizeInBytes();
361 double getLoadProbability() {
362 // This can currently cause stack overflow
364 // if(cachedSize < SLOW_LIMIT) return 1.0;
365 // if(cachedSize > HIGH_LIMIT) return 1e-2;
367 // double pos = (double)(cachedSize - SLOW_LIMIT) / (double)(HIGH_LIMIT -
369 // double val = 0.1 * ((pos-1) * (pos-1)) + 1e-2;
373 class SizeProcedure implements TObjectProcedure<ClusterImpl> {
374 public long result = 0;
377 public boolean execute(ClusterImpl cluster) {
378 if (cluster != null) {
380 if (cluster.isLoaded() && !cluster.isEmpty()) {
381 result += cluster.getCachedSize();
383 } catch (Throwable t) {
384 Logger.defaultLogError(t);
390 public void clear() {
396 private SizeProcedure sizeProcedure = new SizeProcedure();
397 long getSizeInBytes() {
398 if (dirtySizeInBytes) {
399 sizeProcedure.clear();
400 clusters.forEachValue(sizeProcedure);
401 sizeInBytes = sizeProcedure.result;
402 // System.err.println("recomputed size of clusterTable => " + sizeInBytes);
403 setDirtySizeInBytes(false);
408 public void setDirtySizeInBytes(boolean value) {
409 dirtySizeInBytes = value;
412 ClusterStateImpl getState() {
413 final ClusterStateImpl result = new ClusterStateImpl();
414 clusters.forEachEntry(new TLongObjectProcedure<ClusterImpl>() {
416 public boolean execute(long arg0, ClusterImpl arg1) {
419 if (arg1.isLoaded() && !arg1.isEmpty()) {
420 result.ids.add(new ImportanceEntry(arg1));
428 void restoreState(ClusterStateImpl state) {
429 ClusterStateImpl current = getState();
430 for (CollectorCluster id : current.ids)
431 if (!state.ids.contains(id))
432 collectorSupport.release(id);
435 class ClusterCollectorImpl implements ClusterCollector {
437 final private ClusterCollectorSupport support;
438 private ClusterCollectorPolicy policy;
439 ClusterCollectorImpl(ClusterCollectorSupport support) {
440 this.support = support;
443 ClusterCollectorPolicy setPolicy(ClusterCollectorPolicy newPolicy) {
445 ClusterCollectorPolicy oldPolicy = policy;
449 for (CollectorCluster id : support.getResidentClusters()) {
450 policy.added(getClusterByClusterId(id.getClusterId()));
454 support.setPolicy(policy);
461 public void collect() {
465 release(policy.select());
469 int size = support.getCurrentSize();
470 boolean dynamicAllocation = useDynamicAllocation();
471 if (dynamicAllocation)
472 setAllocateSize(estimateProperAllocation(support));
473 if (DebugPolicy.CLUSTER_COLLECTION) {
474 System.out.println("Cluster collector activated, current size = " + size + " limit = " + maximumBytes);
476 if (dynamicAllocation) {
477 int collectSize = maximumBytes / 2;
478 collectSize = Math.min(collectSize, 32 * 1024 * 1024);
479 // try to keep allocated clusters below the maximum
480 if (maximumBytes - size > collectSize)
482 collectSize += size - maximumBytes;
483 collect(collectSize);
485 // try to keep allocated clusters below the maximum
486 if (size < maximumBytes)
496 private boolean useDynamicAllocation() {
497 return "true".equalsIgnoreCase(System.getProperty("org.simantics.db.cluster.dynamicAlloc"));
501 public void collect(int target) {
505 release(policy.select(target));
509 ArrayList<CollectorCluster> toRelease = new ArrayList<CollectorCluster>();
511 for (CollectorCluster cluster : support.getResidentClusters()) {
512 target -= support.getClusterSize(cluster);
514 toRelease.add(cluster);
522 if (DebugPolicy.CLUSTER_COLLECTION) {
523 System.out.println("Cluster collector finished, current size = " + support.getCurrentSize());
530 void release(Collection<CollectorCluster> toRelease) {
531 for (CollectorCluster id : toRelease) {
538 private ClusterCollectorSupport collectorSupport = new ClusterCollectorSupportImpl(this);
539 ClusterCollectorImpl collector = new ClusterCollectorImpl(collectorSupport);
545 private long newResourceClusterId = Constants.NewClusterId;
546 public static final int CLUSTER_FILL_SIZE = ClusterTraitsBase.getMaxNumberOfResources();
549 * Uusi id varataan vasta, kun lis�t��n resurssi => reservedIds sis�lt��
550 * vain jo k�yt�ss� olevia klustereita
553 ClusterImpl getNewResourceCluster(ClusterSupport cs, GraphSession graphSession, boolean writeOnly)
554 throws DatabaseException {
555 ClusterImpl result = null;
556 if (Constants.NewClusterId == newResourceClusterId) {
557 newResourceClusterId = graphSession.newClusterId();
558 result = getClusterByClusterIdOrMake(newResourceClusterId, writeOnly);
560 ClusterImpl cluster = getClusterByClusterIdOrThrow(newResourceClusterId);
561 if (cluster.getNumberOfResources(cs) >= CLUSTER_FILL_SIZE) {
562 newResourceClusterId = graphSession.newClusterId();
563 cluster = getClusterByClusterIdOrMake(newResourceClusterId, writeOnly);
567 return ensureLoaded(result);
570 void flushCluster(GraphSession graphSession) {
571 // We seem to disagree about this.
572 // graphSession.newClusterId();
573 newResourceClusterId = Constants.NewClusterId;
576 void writeOnlyInvalidate(ClusterI impl) {
577 writeOnlyInvalidates.add(impl.getClusterKey());
580 void removeWriteOnlyClusters() {
581 for (ClusterI proxy : writeOnlyClusters) {
582 if (!(proxy instanceof ClusterImpl))
583 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
584 clusters.freeProxy((ClusterImpl)proxy);
586 writeOnlyClusters.clear();
587 writeOnlyInvalidates.forEach(new TIntProcedure() {
589 public boolean execute(int clusterKey) {
590 ClusterImpl proxy = clusterArray[clusterKey];
591 ClusterUID clusterUID = proxy.getClusterUID();
592 System.err.println("writeOnlyInvalidate " + clusterUID);
593 clusters.freeProxy(proxy);
597 writeOnlyInvalidates.clear();
600 public ClusterImpl getClusterByClusterUID(ClusterUID clusterUID) {
601 synchronized (this) {
602 return clusters.getClusterByClusterUID(clusterUID);
605 public int getClusterKeyByClusterUIDOrMakeProxy(ClusterUID clusterUID) {
606 return getClusterKeyByClusterUIDOrMakeProxy(0/*clusterUID.first*/, clusterUID.second);
608 public int getClusterKeyByClusterUIDOrMakeProxy(long id1, long id2) {
609 return getClusterByClusterUIDOrMakeProxy(id1, id2).clusterKey;
611 public ClusterImpl getClusterByClusterUIDOrMakeProxy(ClusterUID clusterUID) {
612 synchronized (this) {
613 ClusterImpl clusterImpl = clusters.getClusterByClusterUID(clusterUID);
614 if (null == clusterImpl)
615 clusterImpl = clusters.makeProxy(clusterUID);
619 public ClusterImpl getClusterByClusterUIDOrMakeProxy(long id1, long id2) {
620 synchronized (this) {
621 ClusterImpl clusterImpl = clusters.getClusterByClusterUID(id1, id2);
622 if (null == clusterImpl)
623 clusterImpl = clusters.makeProxy(id2);
627 ClusterImpl getLoadOrThrow(long clusterId) throws DatabaseException {
628 synchronized (this) {
629 ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
632 if (proxy.isLoaded())
635 clusterKey = proxy.getClusterKey();
637 if (clusterKey == 0) {
638 proxy = clusters.makeProxy(clusterId);
639 clusterKey = proxy.getClusterKey();
641 ClusterImpl ci = tryLoad(clusterId, clusterKey);
643 throw new ResourceNotFoundException(clusterId);
645 } catch (ClusterDoesNotExistException t) {
646 clusters.removeProxy(proxy);
652 ClusterImpl getClusterByClusterIdOrMake(long clusterId, boolean writeOnly) {
653 synchronized (this) {
654 ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
658 return makeCluster(clusterId, writeOnly);
661 ClusterImpl getClusterByClusterIdOrThrow(long clusterId) {
662 synchronized (this) {
663 ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
665 throw new IllegalArgumentException("Cluster id=" + clusterId + " is not created.");
669 long getClusterIdOrCreate(ClusterUID clusterUID) {
670 return clusterUID.second;
672 final long getClusterIdByResourceKey(final int resourceKey)
673 throws DatabaseException {
674 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKey(resourceKey);
675 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
676 throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
677 ClusterI c = clusterArray[clusterKey];
679 throw new RuntimeException("No cluster for key " + resourceKey);
680 return c.getClusterId();
682 final long getClusterIdByResourceKeyNoThrow(final int resourceKey) {
683 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
684 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey)) {
685 Logger.defaultLogError("Tried to get a persistent cluster for a virtual resource. key=" + resourceKey);
688 ClusterI c = clusterArray[clusterKey];
690 Logger.defaultLogError("No cluster for key " + resourceKey);
693 return c.getClusterId();
698 void refresh(long csid, SessionImplSocket session, ClusterUID[] clusterUID) {
699 synchronized (this) {
700 session.flushCounter = 0;
701 session.clusterStream.reallyFlush();
702 ClientChangesImpl cs = new ClientChangesImpl(session);
703 if (session.clientChanges == null)
704 session.clientChanges = cs;
705 //printMaps("refresh");
706 for (int i=0; i<clusterUID.length; ++i) {
708 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
709 System.err.println("cluster=" + clusterUID[i] + " has changed. length=" + clusterUID.length);
710 ClusterImpl oldCluster = clusters.getClusterByClusterUID(clusterUID[i]);
711 if (null == oldCluster)
713 if (!oldCluster.isLoaded())
715 int clusterKey = oldCluster.getClusterKey();
716 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
718 boolean big = oldCluster instanceof ClusterBig;
719 boolean small = oldCluster instanceof ClusterSmall;
722 // ClusterImpl newCluster = (ClusterImpl) sessionImpl.graphSession.getClusterImpl(clusterUID[i], clusterKey);
723 Database.Session dbSession = sessionImpl.graphSession.dbSession;
725 ClusterImpl newCluster = dbSession.clone(clusterUID[i], new ClusterCreator() {
728 public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
729 ClusterSupport support = sessionImpl.clusterTranslator;
731 return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
732 } catch (DatabaseException e) {
739 if (null == newCluster)
741 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
742 System.err.println("cluster=" + newCluster + " updated.");
743 importanceMap.remove(oldCluster.getImportance());
744 if (collectorPolicy != null)
745 collectorPolicy.removed(oldCluster);
746 clusters.replace(newCluster);
747 if (!newCluster.isLoaded())
748 Logger.defaultLogError(new Exception("Bug in ClusterTable.refresh, cluster not loaded"));
749 importanceMap.put(newCluster.getImportance(), new ImportanceEntry(newCluster));
750 if (collectorPolicy != null)
751 collectorPolicy.added(newCluster);
752 // Now we have fetched the new cluster but to emulate effects of the changes in it we fetch the cluster changes from server.
753 refreshCluster(csid, session, oldCluster, clusterUID[i], newCluster.clusterId, clusterKey);
754 } catch (Throwable t) {
755 Logger.defaultLogError("Failed to load cluster in refresh.", t);
759 validateSize("refresh");
760 // Fake update of cluster changes.
761 QueryProcessor queryProcessor = session.getQueryProvider2();
762 WriteGraphImpl writer = WriteGraphImpl.create(queryProcessor, session.writeSupport, null);
763 TaskHelper th = null;
764 if (null == session.writeState) {
765 th = new TaskHelper("Refresh");
766 session.writeState = new WriteState<Object>(writer, th.writeTraits, th.sema, th.proc);
768 session.getQueryProvider2().performDirtyUpdates(writer);
769 session.fireMetadataListeners(writer, cs);
770 session.getQueryProvider2().performScheduledUpdates(writer);
771 session.fireReactionsToSynchronize(cs);
772 session.fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
773 session.printDiagnostics();
776 session.writeState = null;
782 final void refreshCluster(long csid, SessionImplSocket session, ClusterImpl cluster, ClusterUID clusterUID, long clusterId, int clusterKey)
783 throws DatabaseException {
784 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
785 System.err.println("cluster=" + clusterUID + " id=" + clusterId + " key=" + clusterKey + " resources will be updated.");
786 // get cluster change sets
787 QueryProcessor queryProcessor = session.getQueryProvider2();
790 cc = session.graphSession.getClusterChanges(clusterUID, csid);
791 } catch (Exception e) {
792 Logger.defaultLogError("Could not get cluster changes. cluster=" + clusterUID, e);
796 for (int i=0; i<cc.getResourceIndex().length; ++i) {
797 int resource = ClusterTraits.createResourceKey(clusterKey, cc.getResourceIndex()[i]);
798 ClusterUID pClusterUID = new ClusterUID(cc.getPredicateFirst()[i], cc.getPredicateSecond()[i]);
799 ClusterImpl pCluster = clusters.getClusterByClusterUID(pClusterUID);
800 if (null == pCluster)
802 int pClusterKey = pCluster.getClusterKey();
803 int predicate = ClusterTraits.createResourceKey(pClusterKey, cc.getPredicateIndex()[i]);
804 queryProcessor.updateStatements(resource, predicate);
805 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
806 System.err.println("resource " + cc.getResourceIndex()[i] + " relation " + cc.getPredicateIndex()[i] + " changed.");
808 for (int i=0; i<cc.getValueIndex().length; ++i) {
809 int resource = ClusterTraits.createResourceKey(clusterKey, cc.getValueIndex()[i]);
810 queryProcessor.updateValue(resource);
811 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
812 System.err.println("value " + cc.getValueIndex()[i] + " changed.");
815 final void refreshImportance(ClusterImpl c) {
820 //printMaps("refreshImportance");
822 importanceMap.remove(c.getImportance());
823 if(collectorPolicy != null) collectorPolicy.removed(c);
825 long newImportance = timeCounter();
826 // System.err.println("refreshImportance " + c.getClusterId() + " => " + newImportance);
827 c.setImportance(newImportance);
829 Logger.defaultLogError(new Exception("Bug in ClusterTable.refreshImportance(ClusterImpl), cluster not loaded"));
831 importanceMap.put(c.getImportance(), new ImportanceEntry(c));
832 if(collectorPolicy != null) collectorPolicy.added(c);
834 validateSize("refreshImportance");
838 static long loadTime = 0;
840 @SuppressWarnings("unchecked")
841 public final <T extends ClusterI> T getClusterProxyByResourceKey(final int resourceKey) {
842 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
843 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
844 throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
845 ClusterI cluster = clusterArray[clusterKey];
847 throw new RuntimeException("No proxy for existing cluster. Resource key = " + resourceKey);
851 TLongIntHashMap clusterLoadHistogram = new TLongIntHashMap();
852 int clusterLoadCounter = 0;
854 private <T extends ClusterI> T ensureLoaded(T c) {
856 ClusterImpl cs = (ClusterImpl) c;
858 if(DebugPolicy.REPORT_CLUSTER_LOADING) {
859 long start = System.nanoTime();
860 cluster = load2(cs.getClusterId(), cs.getClusterKey());
861 long load = System.nanoTime()-start;
863 if(DebugPolicy.REPORT_CLUSTER_LOADING) {
864 int was = clusterLoadHistogram.get(cluster.getClusterId());
865 clusterLoadHistogram.put(cluster.getClusterId(), was+1);
866 clusterLoadCounter++;
867 String text = "Load2 " + cluster + " " + 1e-9*loadTime + "s. " + 1e-6*load + "ms. " + clusterLoadCounter + " " + was + " " + cluster.getUsedSpace() + " " + cluster.getImportance();
868 if(DebugPolicy.REPORT_CLUSTER_LOADING_STACKS) {
869 new Exception(text).printStackTrace();
871 System.err.println(text);
875 cluster = load2(cs.getClusterId(), cs.getClusterKey());
877 } catch (DatabaseException e) {
878 Logger.defaultLogError(e);
879 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
881 String msg = "Failed to load cluster " + cs.getClusterUID();// + " resourceId=" + (((cs.getClusterId() << 16 + (resourceKey & 65535))));
882 // TODO: this jams the system => needs refactoring.
883 throw new RuntimeDatabaseException(msg, e);
888 @SuppressWarnings("unchecked")
889 public synchronized final <T extends ClusterI> T getClusterByResourceKey(final int resourceKey) {
890 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
891 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
892 throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
893 ClusterI c = clusterArray[clusterKey];
897 if ((counter++ & 4095) == 0)
898 refreshImportance((ClusterImpl) c);
901 if (!(c instanceof ClusterSmall)) {
902 Logger.defaultLogError("Proxy must be instance of ClusterSmall");
905 return ensureLoaded((T)c);
908 @SuppressWarnings("unchecked")
909 final <T extends ClusterI> T checkedGetClusterByResourceKey(final int resourceKey) {
910 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
911 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
912 throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
913 ClusterI c = clusterArray[clusterKey];
915 throw new RuntimeException("No cluster for resource key " + resourceKey);
917 if ((counter++ & 4095) == 0)
918 refreshImportance((ClusterImpl) c);
921 if (!(c instanceof ClusterSmall)) {
922 Logger.defaultLogError("Proxy must be instance of ClusterSmall");
926 ClusterSmall cs = (ClusterSmall) c;
928 // System.err.println("Load2 " + resourceKey);
929 cluster = load2(cs.getClusterId(), cs.getClusterKey());
930 } catch (DatabaseException e) {
931 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
933 int resourceIndex = resourceKey & ClusterTraitsBase.getResourceIndexFromResourceKeyNoThrow(resourceKey);
934 long resourceId = ClusterTraitsBase.createResourceIdNoThrow(cs.getClusterId(), resourceIndex);
935 String msg = "Failed to load cluster " + cs.getClusterUID() + " for resource key " + resourceKey + " resourceIndex=" + resourceIndex + " resourceId=" + resourceId;
936 Logger.defaultLogError(msg, e);
937 c.setDeleted(true, null);
943 void printDebugInfo(ClusterSupport support)
944 throws DatabaseException {
945 final int SIZE = clusters.size();
947 for (int i = 1; i < SIZE; ++i) {
948 ClusterI c = clusterArray[i];
949 c.getNumberOfResources(support);
950 long size = c.getUsedSpace();
951 System.out.println("cluster=" + c.getClusterId() + " size=" + size);
952 c.printDebugInfo("koss: ", support);
955 System.out.println("Total number of clusters " + SIZE);
956 System.out.println("Total cluster size " + sum);
959 Map<Long,ClusterImpl> prefetch = new HashMap<Long,ClusterImpl>();
961 public synchronized ClusterImpl load2(long clusterId, int clusterKey) throws DatabaseException {
962 ClusterImpl curr = (ClusterImpl) clusterArray[clusterKey];
968 // curr = (ClusterImpl) clusterArray[clusterKey];
969 // if (curr.isLoaded())
972 final Semaphore s = new Semaphore(0);
973 final DatabaseException[] ex = new DatabaseException[1];
975 load2(clusterId, clusterKey, e -> {
981 } catch (InterruptedException e) {
982 Logger.defaultLogError(e);
986 if (Development.DEVELOPMENT) {
987 if (Development.<Boolean>getProperty(DevelopmentKeys.CLUSTERTABLE_VALIDATE_ON_LOAD, Bindings.BOOLEAN)) {
989 ClusterImpl loaded = (ClusterImpl) clusterArray[clusterKey];
990 if (loaded instanceof ClusterSmall)
991 ((ClusterSmall) loaded).check();
992 else if (loaded instanceof ClusterBig)
993 ((ClusterBig) loaded).check();
994 } catch (Throwable t) {
1000 validate(clusterKey);
1002 return (ClusterImpl) clusterArray[clusterKey];
1005 void validate(int clusterKey) {
1007 // if(sessionImpl.graphSession.graphClient instanceof GraphClientImpl2) {
1009 // ClusterImpl server = (ClusterImpl)clusterArray[clusterKey];
1010 // String sd = server.dump(sessionImpl.clusterTranslator);
1011 // GraphClientImpl2 gci = ((GraphClientImpl2)sessionImpl.graphSession.graphClient);
1012 // ClusterImpl memory = gci.clusters.get(server.clusterUID);
1013 // if(memory == null)
1014 // System.err.println("ad");
1015 // String md = memory.dump(gci.support);
1017 // if(!sd.equals(md)) {
1020 // int minLength = Math.min(sd.length(), md.length());
1021 // for (int i = 0; i < minLength; i++) {
1022 // if (sd.charAt(i) != md.charAt(i)) {
1028 // int start = Math.max(diffPos-200, 0);
1029 // int end = Math.min(minLength-1, diffPos+200);
1031 // System.err.println("== CLUSTER DIFFERENCE " + clusterArray[clusterKey].getClusterUID() + " == ");
1032 // System.err.println("== SESSION == ");
1033 // System.err.println(sd.substring(start, end));
1034 // System.err.println("== MEM == ");
1035 // System.err.println(md.substring(start, end));
1036 // System.err.println("== CLUSTER DIFFERENCE ENDS == ");
1038 // throw new IllegalStateException();
1044 public synchronized ClusterImpl getPrefetched() {
1045 synchronized(prefetch) {
1050 public synchronized void load2(long clusterId, int clusterKey, final Consumer<DatabaseException> runnable) {
1052 assert (Constants.ReservedClusterId != clusterId);
1054 ClusterImpl cluster = null;
1055 DatabaseException e = null;
1059 ClusterUID clusterUID = clusters.makeClusterUID(clusterId);
1060 // cluster = (ClusterImpl) sessionImpl.getGraphSession().getClusterImpl(clusterUID, clusterKey);
1061 Database.Session session = sessionImpl.graphSession.dbSession;
1062 // cluster = (ClusterImpl)gci.getClusterByClusterKey(clusterKey).clone(sessionImpl.clusterTranslator);
1063 // cluster = (ClusterImpl)((ClusterImpl)gci.getClusterByClusterUIDOrMakeProxy(clusterUID)).clone(sessionImpl.clusterTranslator);
1065 // cluster = gci.clone(clusterUID, sessionImpl.clusterTranslator);
1067 cluster = session.clone(clusterUID, new ClusterCreator() {
1070 public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
1071 ClusterSupport support = sessionImpl.clusterTranslator;
1073 return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
1074 } catch (DatabaseException e) {
1075 e.printStackTrace();
1082 } catch (Throwable t) {
1083 // It's totally legal to call for non-existing cluster.
1084 // Sometimes this indicates an error, though.
1085 Logger.getDefault().logInfo("Load cluster failed.", t);
1086 if (t instanceof DatabaseException)
1087 e = (DatabaseException) t;
1089 e = new DatabaseException("Load cluster failed.", t);
1091 if (null == cluster) {
1096 // new Exception("Load cluster " + cluster.getClusterId() + " " + cluster.getCachedSize() + " " + cluster.getImmutable()).printStackTrace();
1098 // Can not be called with null argument.
1099 replaceCluster(cluster);
1100 sessionImpl.onClusterLoaded(clusterId);
1101 runnable.accept(null);
1105 public synchronized ClusterImpl tryLoad(long clusterId, int clusterKey) throws DatabaseException {
1107 assert (Constants.ReservedClusterId != clusterId);
1109 ClusterUID clusterUID = clusters.makeClusterUID(clusterId);
1111 Database.Session session = sessionImpl.graphSession.dbSession;
1113 ClusterImpl cluster = session.clone(clusterUID, new ClusterCreator() {
1116 public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
1117 ClusterSupport support = sessionImpl.clusterTranslator;
1119 return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
1120 } catch (DatabaseException e) {
1121 e.printStackTrace();
1127 if (null == clusterArray[clusterKey])
1128 clusterArray[clusterKey] = cluster;
1130 replaceCluster(cluster);
1131 sessionImpl.onClusterLoaded(clusterId);
1133 validate(clusterKey);
1138 public Collection<ClusterI> getClusters() {
1139 ArrayList<ClusterI> result = new ArrayList<ClusterI>();
1140 for (int i = 0; i < clusterArray.length; i++) {
1141 ClusterI cluster = clusterArray[i];
1142 if (cluster != null)
1143 result.add(cluster);
1149 return clusters.size();
1152 public long timeCounter() {
1153 return timeCounter.getAndIncrement();
1156 public boolean hasVirtual(int index) {
1157 return virtuals[index];
1160 public void markVirtual(int index) {
1161 virtuals[index] = true;
1164 public ClusterImpl[] getClusterArray() {
1165 return clusterArray;
1168 public boolean isImmutable(int id) {
1170 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(id);
1171 Boolean exist = immutables[clusterKey];
1172 if(exist != null) return exist;
1174 ClusterI cluster = getClusterByResourceKey(id);
1175 if(cluster == null) {
1178 boolean result = cluster.getImmutable();
1179 markImmutable(cluster, result);
1185 public void markImmutable(ClusterI cluster, boolean value) {
1186 immutables[cluster.getClusterKey()] = value;
1189 public int getClusterKeyByUID(long first, long second) throws DatabaseException {
1190 return getClusterKeyByClusterUIDOrMakeProxy(ClusterUID.make(first, second));
1193 public void adjustCachedSize(long l, ClusterI cluster) {
1195 //System.out.println("ClusterTable: adjusting cluster table cached size by " + l + ": " + sizeInBytes + " -> "
1196 // + (sizeInBytes + l) + ", for cluster " + cluster.getClusterId() + " (" + cluster + ")");
1201 private void validateSize(String place) {
1205 int ims = importanceMap.size();
1206 int ihms = countImportantClusters();
1208 // System.out.format("[ClusterTable.%s] Validating: byteSize=%d (%d MB), hashMap=%d/%d, importanceMap=%d%n",
1209 // place, sizeInBytes, sizeInBytes / (1024*1024), ihms, clusters.hashMap.size(), ims);
1211 int i = clusterArray.length;
1213 for (int j = 0; j < i; ++j) {
1214 ClusterI c = clusterArray[j];
1217 size += c.getCachedSize();
1219 if (sizeInBytes != size) {
1220 if (!dirtySizeInBytes)
1221 System.out.println("BUG: CACHED CLUSTER SIZE DIFFERS FROM CALCULATED: " + sizeInBytes + " != " + size + ", delta = " + (sizeInBytes - size));
1222 //else System.out.println("\"BUG?\": SIZES DIFFER: " + sizeInBytes + " != " + size + ", delta = " + (sizeInBytes - size));
1225 System.out.println("BUG2: hashmap and importanceMap sizes differ: " + ihms + " != " + ims + ", delta=" + (ihms - ims));
1226 printMaps("validateSize");
1228 //System.out.println("[" + place + "] VALIDATED");
1231 private void printMaps(String place) {
1232 int ihms = countImportantClusters();
1233 System.out.println("## printMaps(" + place + ") - " + importanceMap.size() + " - (" + ihms + "/" + clusters.hashMap.size() + ")");
1234 System.out.println("importanceMap (" + importanceMap.size() + "):");
1235 importanceMap.forEach((importance, ie) -> {
1236 System.out.format("\t%d: %s%n", importance, ie.toString());
1238 System.out.println("clusters.hashMap (" + ihms + "/" + clusters.hashMap.size() + "):");
1239 clusters.hashMap.forEachEntry((cid, c) -> {
1240 boolean important = importantCluster(c);
1241 boolean wo = c != null && c.isWriteOnly();
1242 boolean empty = c != null && c.isEmpty();
1243 boolean loaded = c != null && c.isLoaded();
1244 System.out.format("\t%s: %d - %s (writeOnly=%b, empty=%b, loaded=%b)%n", important ? " I" : "NI", cid, c, wo, empty, loaded);
1249 private int countImportantClusters() {
1250 int[] result = { 0 };
1251 clusters.hashMap.forEachEntry((cid, c) -> {
1252 if (importantCluster(c))
1259 private static boolean importantCluster(ClusterImpl c) {
1260 return c != null && !c.isWriteOnly() && c.isLoaded();// && !c.isEmpty();