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 ClusterImpl cluster = (ClusterImpl) cluster_;
295 int clusterKey = cluster.getClusterKey();
296 ClusterImpl existing = (ClusterImpl) clusterArray[clusterKey];
297 if (existing.hasVirtual())
298 cluster.markVirtual();
300 if (existing.cc != null) {
301 if (existing.isLoaded()) {
302 // This shall be promoted to actual exception in the future -
303 // for now, minimal changes
304 new Exception("Trying to replace cluster with pending changes " + existing.getClusterUID())
307 // Adopt changes to loaded cluster
308 cluster.cc = existing.cc;
309 cluster.cc.adopt(cluster);
310 cluster.foreignLookup = existing.foreignLookup;
311 cluster.change = existing.change;
315 importanceMap.remove(existing.getImportance());
316 if (collectorPolicy != null)
317 collectorPolicy.removed((ClusterImpl)existing);
319 //System.out.println("ClusterTable.replace(" + existing + " (I=" + existing.getImportance() + ") => " + cluster + " (I=" + cluster.getImportance() + ")");
321 clusters.replace((ClusterImpl)cluster);
322 if (!cluster.isLoaded())
323 Logger.defaultLogError(new Exception("Bug in ClusterTable.replaceCluster(ClusterI), cluster not loaded"));
325 importanceMap.put(cluster.getImportance(), new ImportanceEntry((ClusterImpl)cluster));
326 if(collectorPolicy != null) collectorPolicy.added((ClusterImpl)cluster);
328 if (!dirtySizeInBytes) {
329 if (existing != cluster) {
330 adjustCachedSize(-existing.getCachedSize(), existing);
332 // This will update sizeInBytes through adjustCachedSize
333 cluster.getCachedSize();
336 validateSize("replaceCluster");
339 synchronized void release(CollectorCluster cluster) {
340 importanceMap.remove(cluster.getImportance());
341 release(cluster.getClusterId());
344 synchronized void release(long clusterId) {
345 //System.out.println("ClusterTable.release(" + clusterId + "): " + sizeInBytes);
347 ClusterImpl clusterImpl = clusters.getClusterByClusterId(clusterId);
348 if (null == clusterImpl)
350 if(!clusterImpl.isLoaded() || clusterImpl.isEmpty())
352 //printMaps("release");
353 clusters.freeProxy(clusterImpl);
354 importanceMap.remove(clusterImpl.getImportance());
355 if (collectorPolicy != null)
356 collectorPolicy.removed(clusterImpl);
357 if (sessionImpl.writeState != null)
358 sessionImpl.clusterStream.flush(clusterImpl.clusterUID);
359 if (!dirtySizeInBytes) {
360 adjustCachedSize(-clusterImpl.getCachedSize(), clusterImpl);
363 validateSize("release");
366 synchronized void compact(long id) {
367 ClusterI impl = clusters.getClusterByClusterId(id);
373 // cachedSize = getSizeInBytes();
376 double getLoadProbability() {
377 // This can currently cause stack overflow
379 // if(cachedSize < SLOW_LIMIT) return 1.0;
380 // if(cachedSize > HIGH_LIMIT) return 1e-2;
382 // double pos = (double)(cachedSize - SLOW_LIMIT) / (double)(HIGH_LIMIT -
384 // double val = 0.1 * ((pos-1) * (pos-1)) + 1e-2;
388 class SizeProcedure implements TObjectProcedure<ClusterImpl> {
389 public long result = 0;
392 public boolean execute(ClusterImpl cluster) {
393 if (cluster != null) {
395 if (cluster.isLoaded() && !cluster.isEmpty()) {
396 result += cluster.getCachedSize();
398 } catch (Throwable t) {
399 Logger.defaultLogError(t);
405 public void clear() {
411 private SizeProcedure sizeProcedure = new SizeProcedure();
412 long getSizeInBytes() {
413 if (dirtySizeInBytes) {
414 sizeProcedure.clear();
415 clusters.forEachValue(sizeProcedure);
416 sizeInBytes = sizeProcedure.result;
417 // System.err.println("recomputed size of clusterTable => " + sizeInBytes);
418 setDirtySizeInBytes(false);
423 public void setDirtySizeInBytes(boolean value) {
424 dirtySizeInBytes = value;
427 ClusterStateImpl getState() {
428 final ClusterStateImpl result = new ClusterStateImpl();
429 clusters.forEachEntry(new TLongObjectProcedure<ClusterImpl>() {
431 public boolean execute(long arg0, ClusterImpl arg1) {
434 if (arg1.isLoaded() && !arg1.isEmpty()) {
435 result.ids.add(new ImportanceEntry(arg1));
443 void restoreState(ClusterStateImpl state) {
444 ClusterStateImpl current = getState();
445 for (CollectorCluster id : current.ids)
446 if (!state.ids.contains(id))
447 collectorSupport.release(id);
450 class ClusterCollectorImpl implements ClusterCollector {
452 final private ClusterCollectorSupport support;
453 private ClusterCollectorPolicy policy;
454 ClusterCollectorImpl(ClusterCollectorSupport support) {
455 this.support = support;
458 ClusterCollectorPolicy setPolicy(ClusterCollectorPolicy newPolicy) {
460 ClusterCollectorPolicy oldPolicy = policy;
464 for (CollectorCluster id : support.getResidentClusters()) {
465 policy.added(getClusterByClusterId(id.getClusterId()));
469 support.setPolicy(policy);
476 public void collect() {
480 release(policy.select());
484 int size = support.getCurrentSize();
485 boolean dynamicAllocation = useDynamicAllocation();
486 if (dynamicAllocation)
487 setAllocateSize(estimateProperAllocation(support));
488 if (DebugPolicy.CLUSTER_COLLECTION) {
489 System.out.println("Cluster collector activated, current size = " + size + " limit = " + maximumBytes);
491 if (dynamicAllocation) {
492 int collectSize = maximumBytes / 2;
493 collectSize = Math.min(collectSize, 32 * 1024 * 1024);
494 // try to keep allocated clusters below the maximum
495 if (maximumBytes - size > collectSize)
497 collectSize += size - maximumBytes;
498 collect(collectSize);
500 // try to keep allocated clusters below the maximum
501 if (size < maximumBytes)
511 private boolean useDynamicAllocation() {
512 return "true".equalsIgnoreCase(System.getProperty("org.simantics.db.cluster.dynamicAlloc"));
516 public void collect(int target) {
520 release(policy.select(target));
524 ArrayList<CollectorCluster> toRelease = new ArrayList<CollectorCluster>();
526 for (CollectorCluster cluster : support.getResidentClusters()) {
527 target -= support.getClusterSize(cluster);
529 toRelease.add(cluster);
537 if (DebugPolicy.CLUSTER_COLLECTION) {
538 System.out.println("Cluster collector finished, current size = " + support.getCurrentSize());
545 void release(Collection<CollectorCluster> toRelease) {
546 for (CollectorCluster id : toRelease) {
553 private ClusterCollectorSupport collectorSupport = new ClusterCollectorSupportImpl(this);
554 ClusterCollectorImpl collector = new ClusterCollectorImpl(collectorSupport);
560 private long newResourceClusterId = Constants.NewClusterId;
561 public static final int CLUSTER_FILL_SIZE = ClusterTraitsBase.getMaxNumberOfResources();
564 * Uusi id varataan vasta, kun lis�t��n resurssi => reservedIds sis�lt��
565 * vain jo k�yt�ss� olevia klustereita
568 ClusterImpl getNewResourceCluster(ClusterSupport cs, GraphSession graphSession, boolean writeOnly)
569 throws DatabaseException {
570 ClusterImpl result = null;
571 if (Constants.NewClusterId == newResourceClusterId) {
572 newResourceClusterId = graphSession.newClusterId();
573 result = getClusterByClusterIdOrMake(newResourceClusterId, writeOnly);
575 ClusterImpl cluster = getClusterByClusterIdOrThrow(newResourceClusterId);
576 if (cluster.getNumberOfResources(cs) >= CLUSTER_FILL_SIZE) {
577 newResourceClusterId = graphSession.newClusterId();
578 cluster = getClusterByClusterIdOrMake(newResourceClusterId, writeOnly);
582 return ensureLoaded(result);
585 void flushCluster(GraphSession graphSession) {
586 // We seem to disagree about this.
587 // graphSession.newClusterId();
588 newResourceClusterId = Constants.NewClusterId;
591 void writeOnlyInvalidate(ClusterI impl) {
592 writeOnlyInvalidates.add(impl.getClusterKey());
595 void removeWriteOnlyClusters() {
596 for (ClusterI proxy : writeOnlyClusters) {
597 if (!(proxy instanceof ClusterImpl))
598 throw new RuntimeDatabaseException("ClusterTable corrupted. Contact application support.");
599 clusters.freeProxy((ClusterImpl)proxy);
601 writeOnlyClusters.clear();
602 writeOnlyInvalidates.forEach(new TIntProcedure() {
604 public boolean execute(int clusterKey) {
605 ClusterImpl proxy = clusterArray[clusterKey];
606 ClusterUID clusterUID = proxy.getClusterUID();
607 clusters.freeProxy(proxy);
611 writeOnlyInvalidates.clear();
614 public ClusterImpl getClusterByClusterUID(ClusterUID clusterUID) {
615 synchronized (this) {
616 return clusters.getClusterByClusterUID(clusterUID);
619 public int getClusterKeyByClusterUIDOrMakeProxy(ClusterUID clusterUID) {
620 return getClusterKeyByClusterUIDOrMakeProxy(0/*clusterUID.first*/, clusterUID.second);
622 public int getClusterKeyByClusterUIDOrMakeProxy(long id1, long id2) {
623 return getClusterByClusterUIDOrMakeProxy(id1, id2).clusterKey;
625 public ClusterImpl getClusterByClusterUIDOrMakeProxy(ClusterUID clusterUID) {
626 synchronized (this) {
627 ClusterImpl clusterImpl = clusters.getClusterByClusterUID(clusterUID);
628 if (null == clusterImpl)
629 clusterImpl = clusters.makeProxy(clusterUID);
633 public ClusterImpl getClusterByClusterUIDOrMakeProxy(long id1, long id2) {
634 synchronized (this) {
635 ClusterImpl clusterImpl = clusters.getClusterByClusterUID(id1, id2);
636 if (null == clusterImpl)
637 clusterImpl = clusters.makeProxy(id2);
641 ClusterImpl getLoadOrThrow(long clusterId) throws DatabaseException {
642 synchronized (this) {
643 ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
646 if (proxy.isLoaded())
649 clusterKey = proxy.getClusterKey();
651 if (clusterKey == 0) {
652 proxy = clusters.makeProxy(clusterId);
653 clusterKey = proxy.getClusterKey();
655 ClusterImpl ci = tryLoad(clusterId, clusterKey);
657 throw new ResourceNotFoundException(clusterId);
659 } catch (ClusterDoesNotExistException t) {
660 clusters.removeProxy(proxy);
666 ClusterImpl getClusterByClusterIdOrMake(long clusterId, boolean writeOnly) {
667 synchronized (this) {
668 ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
672 return makeCluster(clusterId, writeOnly);
675 ClusterImpl getClusterByClusterIdOrThrow(long clusterId) {
676 synchronized (this) {
677 ClusterImpl proxy = clusters.getClusterByClusterId(clusterId);
679 throw new IllegalArgumentException("Cluster id=" + clusterId + " is not created.");
683 long getClusterIdOrCreate(ClusterUID clusterUID) {
684 return clusterUID.second;
686 final long getClusterIdByResourceKey(final int resourceKey)
687 throws DatabaseException {
688 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKey(resourceKey);
689 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
690 throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
691 ClusterI c = clusterArray[clusterKey];
693 throw new RuntimeException("No cluster for key " + resourceKey);
694 return c.getClusterId();
696 final long getClusterIdByResourceKeyNoThrow(final int resourceKey) {
697 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
698 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey)) {
699 Logger.defaultLogError("Tried to get a persistent cluster for a virtual resource. key=" + resourceKey);
702 ClusterI c = clusterArray[clusterKey];
704 Logger.defaultLogError("No cluster for key " + resourceKey);
707 return c.getClusterId();
712 void refresh(long csid, SessionImplSocket session, ClusterUID[] clusterUID) {
713 synchronized (this) {
714 session.flushCounter = 0;
715 session.clusterStream.reallyFlush();
716 ClientChangesImpl cs = new ClientChangesImpl(session);
717 if (session.clientChanges == null)
718 session.clientChanges = cs;
719 //printMaps("refresh");
720 for (int i=0; i<clusterUID.length; ++i) {
722 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
723 System.err.println("cluster=" + clusterUID[i] + " has changed. length=" + clusterUID.length);
724 ClusterImpl oldCluster = clusters.getClusterByClusterUID(clusterUID[i]);
725 if (null == oldCluster)
727 if (!oldCluster.isLoaded())
729 int clusterKey = oldCluster.getClusterKey();
730 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
732 boolean big = oldCluster instanceof ClusterBig;
733 boolean small = oldCluster instanceof ClusterSmall;
736 // ClusterImpl newCluster = (ClusterImpl) sessionImpl.graphSession.getClusterImpl(clusterUID[i], clusterKey);
737 Database.Session dbSession = sessionImpl.graphSession.dbSession;
739 ClusterImpl newCluster = dbSession.clone(clusterUID[i], new ClusterCreator() {
742 public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
743 ClusterSupport support = sessionImpl.clusterTranslator;
745 return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
746 } catch (DatabaseException e) {
753 if (null == newCluster)
755 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
756 System.err.println("cluster=" + newCluster + " updated.");
757 importanceMap.remove(oldCluster.getImportance());
758 if (collectorPolicy != null)
759 collectorPolicy.removed(oldCluster);
760 clusters.replace(newCluster);
761 if (!newCluster.isLoaded())
762 Logger.defaultLogError(new Exception("Bug in ClusterTable.refresh, cluster not loaded"));
763 importanceMap.put(newCluster.getImportance(), new ImportanceEntry(newCluster));
764 if (collectorPolicy != null)
765 collectorPolicy.added(newCluster);
766 // Now we have fetched the new cluster but to emulate effects of the changes in it we fetch the cluster changes from server.
767 refreshCluster(csid, session, oldCluster, clusterUID[i], newCluster.clusterId, clusterKey);
768 } catch (Throwable t) {
769 Logger.defaultLogError("Failed to load cluster in refresh.", t);
773 validateSize("refresh");
774 // Fake update of cluster changes.
775 QueryProcessor queryProcessor = session.getQueryProvider2();
776 WriteGraphImpl writer = WriteGraphImpl.create(queryProcessor, session.writeSupport, null);
777 TaskHelper th = null;
778 if (null == session.writeState) {
779 th = new TaskHelper("Refresh");
780 session.writeState = new WriteState<Object>(writer, th.writeTraits, th.sema, th.proc);
782 session.getQueryProvider2().performDirtyUpdates(writer);
783 session.fireMetadataListeners(writer, cs);
784 session.getQueryProvider2().performScheduledUpdates(writer);
785 session.fireReactionsToSynchronize(cs);
786 session.fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
787 session.printDiagnostics();
790 session.writeState = null;
796 final void refreshCluster(long csid, SessionImplSocket session, ClusterImpl cluster, ClusterUID clusterUID, long clusterId, int clusterKey)
797 throws DatabaseException {
798 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
799 System.err.println("cluster=" + clusterUID + " id=" + clusterId + " key=" + clusterKey + " resources will be updated.");
800 // get cluster change sets
801 QueryProcessor queryProcessor = session.getQueryProvider2();
804 cc = session.graphSession.getClusterChanges(clusterUID, csid);
805 } catch (Exception e) {
806 Logger.defaultLogError("Could not get cluster changes. cluster=" + clusterUID, e);
810 for (int i=0; i<cc.getResourceIndex().length; ++i) {
811 int resource = ClusterTraits.createResourceKey(clusterKey, cc.getResourceIndex()[i]);
812 ClusterUID pClusterUID = new ClusterUID(cc.getPredicateFirst()[i], cc.getPredicateSecond()[i]);
813 ClusterImpl pCluster = clusters.getClusterByClusterUID(pClusterUID);
814 if (null == pCluster)
816 int pClusterKey = pCluster.getClusterKey();
817 int predicate = ClusterTraits.createResourceKey(pClusterKey, cc.getPredicateIndex()[i]);
818 queryProcessor.updateStatements(resource, predicate);
819 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
820 System.err.println("resource " + cc.getResourceIndex()[i] + " relation " + cc.getPredicateIndex()[i] + " changed.");
822 for (int i=0; i<cc.getValueIndex().length; ++i) {
823 int resource = ClusterTraits.createResourceKey(clusterKey, cc.getValueIndex()[i]);
824 queryProcessor.updateValue(resource);
825 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
826 System.err.println("value " + cc.getValueIndex()[i] + " changed.");
829 final void refreshImportance(ClusterImpl c) {
834 //printMaps("refreshImportance");
836 importanceMap.remove(c.getImportance());
837 if(collectorPolicy != null) collectorPolicy.removed(c);
839 long newImportance = timeCounter();
840 // System.err.println("refreshImportance " + c.getClusterId() + " => " + newImportance);
841 c.setImportance(newImportance);
843 Logger.defaultLogError(new Exception("Bug in ClusterTable.refreshImportance(ClusterImpl), cluster not loaded"));
845 importanceMap.put(c.getImportance(), new ImportanceEntry(c));
846 if(collectorPolicy != null) collectorPolicy.added(c);
848 validateSize("refreshImportance");
852 static long loadTime = 0;
854 @SuppressWarnings("unchecked")
855 public final <T extends ClusterI> T getClusterProxyByResourceKey(final int resourceKey) {
856 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
857 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
858 throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
859 ClusterI cluster = clusterArray[clusterKey];
861 throw new RuntimeException("No proxy for existing cluster. Resource key = " + resourceKey);
865 TLongIntHashMap clusterLoadHistogram = new TLongIntHashMap();
866 int clusterLoadCounter = 0;
868 private <T extends ClusterI> T ensureLoaded(T c) {
870 ClusterImpl cs = (ClusterImpl) c;
872 if(DebugPolicy.REPORT_CLUSTER_LOADING) {
873 long start = System.nanoTime();
874 cluster = load2(cs.getClusterId(), cs.getClusterKey());
875 long load = System.nanoTime()-start;
877 if(DebugPolicy.REPORT_CLUSTER_LOADING) {
878 int was = clusterLoadHistogram.get(cluster.getClusterId());
879 clusterLoadHistogram.put(cluster.getClusterId(), was+1);
880 clusterLoadCounter++;
881 String text = "Load2 " + cluster + " " + 1e-9*loadTime + "s. " + 1e-6*load + "ms. " + clusterLoadCounter + " " + was + " " + cluster.getUsedSpace() + " " + cluster.getImportance();
882 if(DebugPolicy.REPORT_CLUSTER_LOADING_STACKS) {
883 new Exception(text).printStackTrace();
885 System.err.println(text);
889 cluster = load2(cs.getClusterId(), cs.getClusterKey());
891 } catch (DatabaseException e) {
892 Logger.defaultLogError(e);
893 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
895 String msg = "Failed to load cluster " + cs.getClusterUID();// + " resourceId=" + (((cs.getClusterId() << 16 + (resourceKey & 65535))));
896 // TODO: this jams the system => needs refactoring.
897 throw new RuntimeDatabaseException(msg, e);
902 @SuppressWarnings("unchecked")
903 public synchronized final <T extends ClusterI> T getClusterByResourceKey(final int resourceKey) {
904 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
905 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
906 throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
907 ClusterI c = clusterArray[clusterKey];
911 if ((counter++ & 4095) == 0)
912 refreshImportance((ClusterImpl) c);
915 if (!(c instanceof ClusterSmall)) {
916 Logger.defaultLogError("Proxy must be instance of ClusterSmall");
919 return ensureLoaded((T)c);
922 @SuppressWarnings("unchecked")
923 final <T extends ClusterI> T checkedGetClusterByResourceKey(final int resourceKey) {
924 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
925 if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
926 throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
927 ClusterI c = clusterArray[clusterKey];
929 throw new RuntimeException("No cluster for resource key " + resourceKey);
931 if ((counter++ & 4095) == 0)
932 refreshImportance((ClusterImpl) c);
935 if (!(c instanceof ClusterSmall)) {
936 Logger.defaultLogError("Proxy must be instance of ClusterSmall");
940 ClusterSmall cs = (ClusterSmall) c;
942 // System.err.println("Load2 " + resourceKey);
943 cluster = load2(cs.getClusterId(), cs.getClusterKey());
944 } catch (DatabaseException e) {
945 if (DebugPolicy.REPORT_CLUSTER_EVENTS)
947 int resourceIndex = resourceKey & ClusterTraitsBase.getResourceIndexFromResourceKeyNoThrow(resourceKey);
948 long resourceId = ClusterTraitsBase.createResourceIdNoThrow(cs.getClusterId(), resourceIndex);
949 String msg = "Failed to load cluster " + cs.getClusterUID() + " for resource key " + resourceKey + " resourceIndex=" + resourceIndex + " resourceId=" + resourceId;
950 Logger.defaultLogError(msg, e);
951 c.setDeleted(true, null);
957 void printDebugInfo(ClusterSupport support)
958 throws DatabaseException {
959 final int SIZE = clusters.size();
961 for (int i = 1; i < SIZE; ++i) {
962 ClusterI c = clusterArray[i];
963 c.getNumberOfResources(support);
964 long size = c.getUsedSpace();
965 System.out.println("cluster=" + c.getClusterId() + " size=" + size);
966 c.printDebugInfo("koss: ", support);
969 System.out.println("Total number of clusters " + SIZE);
970 System.out.println("Total cluster size " + sum);
973 Map<Long,ClusterImpl> prefetch = new HashMap<Long,ClusterImpl>();
975 public synchronized ClusterImpl load2(long clusterId, int clusterKey) throws DatabaseException {
976 ClusterImpl curr = (ClusterImpl) clusterArray[clusterKey];
982 // curr = (ClusterImpl) clusterArray[clusterKey];
983 // if (curr.isLoaded())
986 final Semaphore s = new Semaphore(0);
987 final DatabaseException[] ex = new DatabaseException[1];
989 load2(clusterId, clusterKey, e -> {
995 } catch (InterruptedException e) {
996 Logger.defaultLogError(e);
1000 if (Development.DEVELOPMENT) {
1001 if (Development.<Boolean>getProperty(DevelopmentKeys.CLUSTERTABLE_VALIDATE_ON_LOAD, Bindings.BOOLEAN)) {
1003 ClusterImpl loaded = (ClusterImpl) clusterArray[clusterKey];
1004 if (loaded instanceof ClusterSmall)
1005 ((ClusterSmall) loaded).check();
1006 else if (loaded instanceof ClusterBig)
1007 ((ClusterBig) loaded).check();
1008 } catch (Throwable t) {
1009 t.printStackTrace();
1014 validate(clusterKey);
1016 return (ClusterImpl) clusterArray[clusterKey];
1019 void validate(int clusterKey) {
1021 // if(sessionImpl.graphSession.graphClient instanceof GraphClientImpl2) {
1023 // ClusterImpl server = (ClusterImpl)clusterArray[clusterKey];
1024 // String sd = server.dump(sessionImpl.clusterTranslator);
1025 // GraphClientImpl2 gci = ((GraphClientImpl2)sessionImpl.graphSession.graphClient);
1026 // ClusterImpl memory = gci.clusters.get(server.clusterUID);
1027 // if(memory == null)
1028 // System.err.println("ad");
1029 // String md = memory.dump(gci.support);
1031 // if(!sd.equals(md)) {
1034 // int minLength = Math.min(sd.length(), md.length());
1035 // for (int i = 0; i < minLength; i++) {
1036 // if (sd.charAt(i) != md.charAt(i)) {
1042 // int start = Math.max(diffPos-200, 0);
1043 // int end = Math.min(minLength-1, diffPos+200);
1045 // System.err.println("== CLUSTER DIFFERENCE " + clusterArray[clusterKey].getClusterUID() + " == ");
1046 // System.err.println("== SESSION == ");
1047 // System.err.println(sd.substring(start, end));
1048 // System.err.println("== MEM == ");
1049 // System.err.println(md.substring(start, end));
1050 // System.err.println("== CLUSTER DIFFERENCE ENDS == ");
1052 // throw new IllegalStateException();
1058 public synchronized ClusterImpl getPrefetched() {
1059 synchronized(prefetch) {
1064 public synchronized void load2(long clusterId, int clusterKey, final Consumer<DatabaseException> runnable) {
1066 assert (Constants.ReservedClusterId != clusterId);
1068 ClusterImpl cluster = null;
1069 DatabaseException e = null;
1073 ClusterUID clusterUID = clusters.makeClusterUID(clusterId);
1074 // cluster = (ClusterImpl) sessionImpl.getGraphSession().getClusterImpl(clusterUID, clusterKey);
1075 Database.Session session = sessionImpl.graphSession.dbSession;
1076 // cluster = (ClusterImpl)gci.getClusterByClusterKey(clusterKey).clone(sessionImpl.clusterTranslator);
1077 // cluster = (ClusterImpl)((ClusterImpl)gci.getClusterByClusterUIDOrMakeProxy(clusterUID)).clone(sessionImpl.clusterTranslator);
1079 // cluster = gci.clone(clusterUID, sessionImpl.clusterTranslator);
1081 cluster = session.clone(clusterUID, new ClusterCreator() {
1084 public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
1085 ClusterSupport support = sessionImpl.clusterTranslator;
1087 return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
1088 } catch (DatabaseException e) {
1089 e.printStackTrace();
1096 } catch (Throwable t) {
1097 // It's totally legal to call for non-existing cluster.
1098 // Sometimes this indicates an error, though.
1099 Logger.getDefault().logInfo("Load cluster failed.", t);
1100 if (t instanceof DatabaseException)
1101 e = (DatabaseException) t;
1103 e = new DatabaseException("Load cluster failed.", t);
1105 if (null == cluster) {
1110 // new Exception("Load cluster " + cluster.getClusterId() + " " + cluster.getCachedSize() + " " + cluster.getImmutable()).printStackTrace();
1112 // Can not be called with null argument.
1113 replaceCluster(cluster);
1114 sessionImpl.onClusterLoaded(clusterId);
1115 runnable.accept(null);
1119 public synchronized ClusterImpl tryLoad(long clusterId, int clusterKey) throws DatabaseException {
1121 assert (Constants.ReservedClusterId != clusterId);
1123 ClusterUID clusterUID = clusters.makeClusterUID(clusterId);
1125 Database.Session session = sessionImpl.graphSession.dbSession;
1127 ClusterImpl cluster = session.clone(clusterUID, new ClusterCreator() {
1130 public <T> T create(ClusterUID uid, byte[] bytes, int[] ints, long[] longs) {
1131 ClusterSupport support = sessionImpl.clusterTranslator;
1133 return (T)ClusterImpl.make(longs, ints, bytes, support, support.getClusterKeyByClusterUIDOrMake(uid));
1134 } catch (DatabaseException e) {
1135 e.printStackTrace();
1141 if (null == clusterArray[clusterKey])
1142 clusterArray[clusterKey] = cluster;
1144 replaceCluster(cluster);
1145 sessionImpl.onClusterLoaded(clusterId);
1147 validate(clusterKey);
1152 public Collection<ClusterI> getClusters() {
1153 ArrayList<ClusterI> result = new ArrayList<ClusterI>();
1154 for (int i = 0; i < clusterArray.length; i++) {
1155 ClusterI cluster = clusterArray[i];
1156 if (cluster != null)
1157 result.add(cluster);
1163 return clusters.size();
1166 public long timeCounter() {
1167 return timeCounter.getAndIncrement();
1170 public boolean hasVirtual(int index) {
1171 return virtuals[index];
1174 public void markVirtual(int index) {
1175 virtuals[index] = true;
1178 public ClusterImpl[] getClusterArray() {
1179 return clusterArray;
1182 public boolean isImmutable(int id) {
1184 int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(id);
1185 Boolean exist = immutables[clusterKey];
1186 if(exist != null) return exist;
1188 ClusterI cluster = getClusterByResourceKey(id);
1189 if(cluster == null) {
1192 boolean result = cluster.getImmutable();
1193 markImmutable(cluster, result);
1199 public void markImmutable(ClusterI cluster, boolean value) {
1200 immutables[cluster.getClusterKey()] = value;
1203 public int getClusterKeyByUID(long first, long second) throws DatabaseException {
1204 return getClusterKeyByClusterUIDOrMakeProxy(ClusterUID.make(first, second));
1207 public void adjustCachedSize(long l, ClusterI cluster) {
1209 //System.out.println("ClusterTable: adjusting cluster table cached size by " + l + ": " + sizeInBytes + " -> "
1210 // + (sizeInBytes + l) + ", for cluster " + cluster.getClusterId() + " (" + cluster + ")");
1215 private void validateSize(String place) {
1219 int ims = importanceMap.size();
1220 int ihms = countImportantClusters();
1222 // System.out.format("[ClusterTable.%s] Validating: byteSize=%d (%d MB), hashMap=%d/%d, importanceMap=%d%n",
1223 // place, sizeInBytes, sizeInBytes / (1024*1024), ihms, clusters.hashMap.size(), ims);
1225 int i = clusterArray.length;
1227 for (int j = 0; j < i; ++j) {
1228 ClusterI c = clusterArray[j];
1231 size += c.getCachedSize();
1233 if (sizeInBytes != size) {
1234 if (!dirtySizeInBytes)
1235 System.out.println("BUG: CACHED CLUSTER SIZE DIFFERS FROM CALCULATED: " + sizeInBytes + " != " + size + ", delta = " + (sizeInBytes - size));
1236 //else System.out.println("\"BUG?\": SIZES DIFFER: " + sizeInBytes + " != " + size + ", delta = " + (sizeInBytes - size));
1239 System.out.println("BUG2: hashmap and importanceMap sizes differ: " + ihms + " != " + ims + ", delta=" + (ihms - ims));
1240 printMaps("validateSize");
1242 //System.out.println("[" + place + "] VALIDATED");
1245 private void printMaps(String place) {
1246 int ihms = countImportantClusters();
1247 System.out.println("## printMaps(" + place + ") - " + importanceMap.size() + " - (" + ihms + "/" + clusters.hashMap.size() + ")");
1248 System.out.println("importanceMap (" + importanceMap.size() + "):");
1249 importanceMap.forEach((importance, ie) -> {
1250 System.out.format("\t%d: %s%n", importance, ie.toString());
1252 System.out.println("clusters.hashMap (" + ihms + "/" + clusters.hashMap.size() + "):");
1253 clusters.hashMap.forEachEntry((cid, c) -> {
1254 boolean important = importantCluster(c);
1255 boolean wo = c != null && c.isWriteOnly();
1256 boolean empty = c != null && c.isEmpty();
1257 boolean loaded = c != null && c.isLoaded();
1258 System.out.format("\t%s: %d - %s (writeOnly=%b, empty=%b, loaded=%b)%n", important ? " I" : "NI", cid, c, wo, empty, loaded);
1263 private int countImportantClusters() {
1264 int[] result = { 0 };
1265 clusters.hashMap.forEachEntry((cid, c) -> {
1266 if (importantCluster(c))
1273 private static boolean importantCluster(ClusterImpl c) {
1274 return c != null && !c.isWriteOnly() && c.isLoaded();// && !c.isEmpty();