You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by be...@apache.org on 2015/02/11 16:23:36 UTC
[1/7] cassandra git commit: Safer Resource Management++
Repository: cassandra
Updated Branches:
refs/heads/cassandra-2.1 708b0ce6d -> 61384c575
refs/heads/trunk 5a17ec875 -> 02c348939
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/BloomFilter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/BloomFilter.java b/src/java/org/apache/cassandra/utils/BloomFilter.java
index ceba89b..77b2d44 100644
--- a/src/java/org/apache/cassandra/utils/BloomFilter.java
+++ b/src/java/org/apache/cassandra/utils/BloomFilter.java
@@ -21,9 +21,10 @@ import java.nio.ByteBuffer;
import com.google.common.annotations.VisibleForTesting;
+import org.apache.cassandra.utils.concurrent.WrappedSharedCloseable;
import org.apache.cassandra.utils.obs.IBitSet;
-public abstract class BloomFilter implements IFilter
+public abstract class BloomFilter extends WrappedSharedCloseable implements IFilter
{
private static final ThreadLocal<long[]> reusableIndexes = new ThreadLocal<long[]>()
{
@@ -36,12 +37,20 @@ public abstract class BloomFilter implements IFilter
public final IBitSet bitset;
public final int hashCount;
- BloomFilter(int hashes, IBitSet bitset)
+ BloomFilter(int hashCount, IBitSet bitset)
{
- this.hashCount = hashes;
+ super(bitset);
+ this.hashCount = hashCount;
this.bitset = bitset;
}
+ BloomFilter(BloomFilter copy)
+ {
+ super(copy);
+ this.hashCount = copy.hashCount;
+ this.bitset = copy.bitset;
+ }
+
// Murmur is faster than an SHA-based approach and provides as-good collision
// resistance. The combinatorial generation approach described in
// http://www.eecs.harvard.edu/~kirsch/pubs/bbbf/esa06.pdf
@@ -110,9 +119,4 @@ public abstract class BloomFilter implements IFilter
{
bitset.clear();
}
-
- public void close()
- {
- bitset.close();
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/IFilter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/IFilter.java b/src/java/org/apache/cassandra/utils/IFilter.java
index 60c0590..bde6333 100644
--- a/src/java/org/apache/cassandra/utils/IFilter.java
+++ b/src/java/org/apache/cassandra/utils/IFilter.java
@@ -17,10 +17,11 @@
*/
package org.apache.cassandra.utils;
-import java.io.Closeable;
import java.nio.ByteBuffer;
-public interface IFilter extends Closeable
+import org.apache.cassandra.utils.concurrent.SharedCloseable;
+
+public interface IFilter extends SharedCloseable
{
void add(ByteBuffer key);
@@ -32,6 +33,8 @@ public interface IFilter extends Closeable
void close();
+ IFilter sharedCopy();
+
/**
* Returns the amount of memory in bytes used off heap.
* @return the amount of memory in bytes used off heap
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java b/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java
index f7c7632..431ca5b 100644
--- a/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java
+++ b/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java
@@ -26,9 +26,14 @@ public class Murmur3BloomFilter extends BloomFilter
{
public static final Murmur3BloomFilterSerializer serializer = new Murmur3BloomFilterSerializer();
- public Murmur3BloomFilter(int hashes, IBitSet bs)
+ public Murmur3BloomFilter(int hashCount, IBitSet bs)
{
- super(hashes, bs);
+ super(hashCount, bs);
+ }
+
+ protected Murmur3BloomFilter(Murmur3BloomFilter copy)
+ {
+ super(copy);
}
public long serializedSize()
@@ -36,6 +41,11 @@ public class Murmur3BloomFilter extends BloomFilter
return serializer.serializedSize(this, TypeSizes.NATIVE);
}
+ public IFilter sharedCopy()
+ {
+ return new Murmur3BloomFilter(this);
+ }
+
@Override
public long offHeapSize()
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/concurrent/Ref.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/concurrent/Ref.java b/src/java/org/apache/cassandra/utils/concurrent/Ref.java
index 4afceb0..ad1293b 100644
--- a/src/java/org/apache/cassandra/utils/concurrent/Ref.java
+++ b/src/java/org/apache/cassandra/utils/concurrent/Ref.java
@@ -2,24 +2,69 @@ package org.apache.cassandra.utils.concurrent;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
+import java.util.Collections;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.apache.cassandra.concurrent.NamedThreadFactory;
+
/**
- * A single managed reference to a RefCounted object
+ * An object that needs ref counting does the two following:
+ * - defines a Tidy object that will cleanup once it's gone,
+ * (this must retain no references to the object we're tracking (only its resources and how to clean up))
+ * Then, one of two options:
+ * 1) Construct a Ref directly pointing to it, and always use this Ref; or
+ * 2)
+ * - implements RefCounted
+ * - encapsulates a Ref, we'll call selfRef, to which it proxies all calls to RefCounted behaviours
+ * - users must ensure no references to the selfRef leak, or are retained outside of a method scope.
+ * (to ensure the selfRef is collected with the object, so that leaks may be detected and corrected)
+ *
+ * This class' functionality is achieved by what may look at first glance like a complex web of references,
+ * but boils down to:
+ *
+ * Target --> selfRef --> [Ref.State] <--> Ref.GlobalState --> Tidy
+ * ^
+ * |
+ * Ref ----------------------------------------
+ * |
+ * Global -------------------------------------
+ *
+ * So that, if Target is collected, Impl is collected and, hence, so is selfRef.
+ *
+ * Once ref or selfRef are collected, the paired Ref.State's release method is called, which if it had
+ * not already been called will update Ref.GlobalState and log an error.
+ *
+ * Once the Ref.GlobalState has been completely released, the Tidy method is called and it removes the global reference
+ * to itself so it may also be collected.
*/
-public final class Ref
+public final class Ref<T> implements RefCounted<T>, AutoCloseable
{
static final Logger logger = LoggerFactory.getLogger(Ref.class);
static final boolean DEBUG_ENABLED = System.getProperty("cassandra.debugrefcount", "false").equalsIgnoreCase("true");
final State state;
+ final T referent;
- Ref(RefCountedImpl.GlobalState state, boolean isSharedRef)
+ public Ref(T referent, Tidy tidy)
{
- this.state = new State(state, this, RefCountedImpl.referenceQueue, isSharedRef);
+ this.state = new State(new GlobalState(tidy), this, referenceQueue);
+ this.referent = referent;
+ }
+
+ Ref(T referent, GlobalState state)
+ {
+ this.state = new State(state, this, referenceQueue);
+ this.referent = referent;
}
/**
@@ -32,6 +77,36 @@ public final class Ref
state.release(false);
}
+ public void ensureReleased()
+ {
+ state.ensureReleased();
+ }
+
+ public void close()
+ {
+ state.ensureReleased();
+ }
+
+ public T get()
+ {
+ state.assertNotReleased();
+ return referent;
+ }
+
+ public Ref<T> tryRef()
+ {
+ return state.globalState.ref() ? new Ref<>(referent, state.globalState) : null;
+ }
+
+ public Ref<T> ref()
+ {
+ Ref<T> ref = tryRef();
+ // TODO: print the last release as well as the release here
+ if (ref == null)
+ state.assertNotReleased();
+ return ref;
+ }
+
/**
* A convenience method for reporting:
* @return the number of currently extant references globally, including the shared reference
@@ -41,25 +116,36 @@ public final class Ref
return state.globalState.count();
}
- // similar to RefCountedState, but tracks only the management of each unique ref created to the managed object
+ // similar to Ref.GlobalState, but tracks only the management of each unique ref created to the managed object
// ensures it is only released once, and that it is always released
static final class State extends PhantomReference<Ref>
{
final Debug debug = DEBUG_ENABLED ? new Debug() : null;
- final boolean isSharedRef;
- final RefCountedImpl.GlobalState globalState;
+ final GlobalState globalState;
private volatile int released;
private static final AtomicIntegerFieldUpdater<State> releasedUpdater = AtomicIntegerFieldUpdater.newUpdater(State.class, "released");
- public State(final RefCountedImpl.GlobalState globalState, Ref reference, ReferenceQueue<? super Ref> q, boolean isSharedRef)
+ public State(final GlobalState globalState, Ref reference, ReferenceQueue<? super Ref> q)
{
super(reference, q);
this.globalState = globalState;
- this.isSharedRef = isSharedRef;
globalState.register(this);
}
+ void assertNotReleased()
+ {
+ if (DEBUG_ENABLED && released == 1)
+ debug.log(toString());
+ assert released == 0;
+ }
+
+ void ensureReleased()
+ {
+ if (releasedUpdater.getAndSet(this, 1) == 0)
+ globalState.release(this);
+ }
+
void release(boolean leak)
{
if (!releasedUpdater.compareAndSet(this, 0, 1))
@@ -67,7 +153,7 @@ public final class Ref
if (!leak)
{
String id = this.toString();
- logger.error("BAD RELEASE: attempted to release a{} reference ({}) that has already been released", isSharedRef ? " shared" : "", id);
+ logger.error("BAD RELEASE: attempted to release a reference ({}) that has already been released", id);
if (DEBUG_ENABLED)
debug.log(id);
throw new IllegalStateException("Attempted to release a reference that has already been released");
@@ -78,10 +164,7 @@ public final class Ref
if (leak)
{
String id = this.toString();
- if (isSharedRef)
- logger.error("LEAK DETECTED: the shared reference ({}) to {} was not released before the object was garbage collected", id, globalState);
- else
- logger.error("LEAK DETECTED: a reference ({}) to {} was not released before the reference was garbage collected", id, globalState);
+ logger.error("LEAK DETECTED: a reference ({}) to {} was not released before the reference was garbage collected", id, globalState);
if (DEBUG_ENABLED)
debug.log(id);
}
@@ -129,6 +212,101 @@ public final class Ref
}
}
-}
+ // the object that manages the actual cleaning up; this does not reference the target object
+ // so that we can detect when references are lost to the resource itself, and still cleanup afterwards
+ // the Tidy object MUST not contain any references to the object we are managing
+ static final class GlobalState
+ {
+ // we need to retain a reference to each of the PhantomReference instances
+ // we are using to track individual refs
+ private final ConcurrentLinkedQueue<State> locallyExtant = new ConcurrentLinkedQueue<>();
+ // the number of live refs
+ private final AtomicInteger counts = new AtomicInteger();
+ // the object to call to cleanup when our refs are all finished with
+ private final Tidy tidy;
+
+ GlobalState(Tidy tidy)
+ {
+ this.tidy = tidy;
+ globallyExtant.add(this);
+ }
+ void register(Ref.State ref)
+ {
+ locallyExtant.add(ref);
+ }
+ // increment ref count if not already tidied, and return success/failure
+ boolean ref()
+ {
+ while (true)
+ {
+ int cur = counts.get();
+ if (cur < 0)
+ return false;
+ if (counts.compareAndSet(cur, cur + 1))
+ return true;
+ }
+ }
+
+ // release a single reference, and cleanup if no more are extant
+ void release(Ref.State ref)
+ {
+ locallyExtant.remove(ref);
+ if (-1 == counts.decrementAndGet())
+ {
+ globallyExtant.remove(this);
+ try
+ {
+ tidy.tidy();
+ }
+ catch (Throwable t)
+ {
+ logger.error("Error when closing {}", this, t);
+ Throwables.propagate(t);
+ }
+ }
+ }
+
+ int count()
+ {
+ return 1 + counts.get();
+ }
+
+ public String toString()
+ {
+ return tidy.getClass() + "@" + System.identityHashCode(tidy) + ":" + tidy.name();
+ }
+ }
+
+ private static final Set<GlobalState> globallyExtant = Collections.newSetFromMap(new ConcurrentHashMap<GlobalState, Boolean>());
+ static final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
+ private static final ExecutorService EXEC = Executors.newFixedThreadPool(1, new NamedThreadFactory("Reference-Reaper"));
+ static
+ {
+ EXEC.execute(new Runnable()
+ {
+ public void run()
+ {
+ try
+ {
+ while (true)
+ {
+ Object obj = referenceQueue.remove();
+ if (obj instanceof Ref.State)
+ {
+ ((Ref.State) obj).release(true);
+ }
+ }
+ }
+ catch (InterruptedException e)
+ {
+ }
+ finally
+ {
+ EXEC.execute(this);
+ }
+ }
+ });
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java b/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java
index 7ad51ad..e68c7bd 100644
--- a/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java
+++ b/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java
@@ -36,59 +36,29 @@ import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.NamedThreadFactory;
/**
- * An object that needs ref counting does the following:
+ * An object that needs ref counting does the two following:
* - defines a Tidy object that will cleanup once it's gone,
* (this must retain no references to the object we're tracking (only its resources and how to clean up))
+ * Then, one of two options:
+ * 1) Construct a Ref directly pointing to it, and always use this Ref; or
+ * 2)
* - implements RefCounted
- * - encapsulates a RefCounted.Impl, to which it proxies all calls to RefCounted behaviours
- * - ensures no external access to the encapsulated Impl, and permits no references to it to leak
- * - users must ensure no references to the sharedRef leak, or are retained outside of a method scope either.
- * (to ensure the sharedRef is collected with the object, so that leaks may be detected and corrected)
- *
- * This class' functionality is achieved by what may look at first glance like a complex web of references,
- * but boils down to:
- *
- * Target --> Impl --> sharedRef --> [RefState] <--> RefCountedState --> Tidy
- * ^ ^
- * | |
- * Ref ----------------------------------- |
- * |
- * Global -------------------------------------------------
- *
- * So that, if Target is collected, Impl is collected and, hence, so is sharedRef.
- *
- * Once ref or sharedRef are collected, the paired RefState's release method is called, which if it had
- * not already been called will update RefCountedState and log an error.
- *
- * Once the RefCountedState has been completely released, the Tidy method is called and it removes the global reference
- * to itself so it may also be collected.
+ * - encapsulates a Ref, we'll call selfRef, to which it proxies all calls to RefCounted behaviours
+ * - users must ensure no references to the selfRef leak, or are retained outside of a method scope.
+ * (to ensure the selfRef is collected with the object, so that leaks may be detected and corrected)
*/
-public interface RefCounted
+public interface RefCounted<T>
{
-
/**
* @return the a new Ref() to the managed object, incrementing its refcount, or null if it is already released
*/
- public Ref tryRef();
+ public Ref<T> tryRef();
- /**
- * @return the shared Ref that is created at instantiation of the RefCounted instance.
- * Once released, if no other refs are extant the object will be tidied; references to
- * this object should never be retained outside of a method's scope
- */
- public Ref sharedRef();
+ public Ref<T> ref();
public static interface Tidy
{
- void tidy();
+ void tidy() throws Exception;
String name();
}
-
- public static class Impl
- {
- public static RefCounted get(Tidy tidy)
- {
- return new RefCountedImpl(tidy);
- }
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/concurrent/RefCountedImpl.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/concurrent/RefCountedImpl.java b/src/java/org/apache/cassandra/utils/concurrent/RefCountedImpl.java
deleted file mode 100644
index 0de6f40..0000000
--- a/src/java/org/apache/cassandra/utils/concurrent/RefCountedImpl.java
+++ /dev/null
@@ -1,132 +0,0 @@
-package org.apache.cassandra.utils.concurrent;
-
-import java.lang.ref.ReferenceQueue;
-import java.util.Collections;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.cassandra.concurrent.NamedThreadFactory;
-
-// default implementation; can be hidden and proxied (like we do for SSTableReader)
-final class RefCountedImpl implements RefCounted
-{
- private final Ref sharedRef;
- private final GlobalState state;
-
- public RefCountedImpl(Tidy tidy)
- {
- this.state = new GlobalState(tidy);
- sharedRef = new Ref(this.state, true);
- globallyExtant.add(this.state);
- }
-
- /**
- * see {@link RefCounted#tryRef()}
- */
- public Ref tryRef()
- {
- return state.ref() ? new Ref(state, false) : null;
- }
-
- /**
- * see {@link RefCounted#sharedRef()}
- */
- public Ref sharedRef()
- {
- return sharedRef;
- }
-
- // the object that manages the actual cleaning up; this does not reference the RefCounted.Impl
- // so that we can detect when references are lost to the resource itself, and still cleanup afterwards
- // the Tidy object MUST not contain any references to the object we are managing
- static final class GlobalState
- {
- // we need to retain a reference to each of the PhantomReference instances
- // we are using to track individual refs
- private final ConcurrentLinkedQueue<Ref.State> locallyExtant = new ConcurrentLinkedQueue<>();
- // the number of live refs
- private final AtomicInteger counts = new AtomicInteger();
- // the object to call to cleanup when our refs are all finished with
- private final Tidy tidy;
-
- GlobalState(Tidy tidy)
- {
- this.tidy = tidy;
- }
-
- void register(Ref.State ref)
- {
- locallyExtant.add(ref);
- }
-
- // increment ref count if not already tidied, and return success/failure
- boolean ref()
- {
- while (true)
- {
- int cur = counts.get();
- if (cur < 0)
- return false;
- if (counts.compareAndSet(cur, cur + 1))
- return true;
- }
- }
-
- // release a single reference, and cleanup if no more are extant
- void release(Ref.State ref)
- {
- locallyExtant.remove(ref);
- if (-1 == counts.decrementAndGet())
- {
- globallyExtant.remove(this);
- tidy.tidy();
- }
- }
-
- int count()
- {
- return 1 + counts.get();
- }
-
- public String toString()
- {
- return tidy.name();
- }
- }
-
- private static final Set<GlobalState> globallyExtant = Collections.newSetFromMap(new ConcurrentHashMap<GlobalState, Boolean>());
- static final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
- private static final ExecutorService EXEC = Executors.newFixedThreadPool(1, new NamedThreadFactory("Reference-Reaper"));
- static
- {
- EXEC.execute(new Runnable()
- {
- public void run()
- {
- try
- {
- while (true)
- {
- Object obj = referenceQueue.remove();
- if (obj instanceof Ref.State)
- {
- ((Ref.State) obj).release(true);
- }
- }
- }
- catch (InterruptedException e)
- {
- }
- finally
- {
- EXEC.execute(this);
- }
- }
- });
- }
-}
-
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/concurrent/Refs.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/concurrent/Refs.java b/src/java/org/apache/cassandra/utils/concurrent/Refs.java
index ed5fcfa..3a930d2 100644
--- a/src/java/org/apache/cassandra/utils/concurrent/Refs.java
+++ b/src/java/org/apache/cassandra/utils/concurrent/Refs.java
@@ -12,16 +12,16 @@ import com.google.common.collect.Iterators;
*
* All of the java.util.Collection operations that modify the collection are unsupported.
*/
-public final class Refs<T extends RefCounted> extends AbstractCollection<T> implements AutoCloseable
+public final class Refs<T extends RefCounted<T>> extends AbstractCollection<T> implements AutoCloseable
{
- private final Map<T, Ref> references;
+ private final Map<T, Ref<T>> references;
public Refs()
{
this.references = new HashMap<>();
}
- public Refs(Map<T, Ref> references)
+ public Refs(Map<T, Ref<T>> references)
{
this.references = new HashMap<>(references);
}
@@ -88,11 +88,11 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
*/
public void release(Collection<T> release)
{
- List<Ref> refs = new ArrayList<>();
+ List<Ref<T>> refs = new ArrayList<>();
List<T> notPresent = null;
for (T obj : release)
{
- Ref ref = references.remove(obj);
+ Ref<T> ref = references.remove(obj);
if (ref == null)
{
if (notPresent == null)
@@ -132,7 +132,7 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
*/
public boolean tryRef(T t)
{
- Ref ref = t.tryRef();
+ Ref<T> ref = t.tryRef();
if (ref == null)
return false;
ref = references.put(t, ref);
@@ -156,8 +156,8 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
*/
public Refs<T> addAll(Refs<T> add)
{
- List<Ref> overlap = new ArrayList<>();
- for (Map.Entry<T, Ref> e : add.references.entrySet())
+ List<Ref<T>> overlap = new ArrayList<>();
+ for (Map.Entry<T, Ref<T>> e : add.references.entrySet())
{
if (this.references.containsKey(e.getKey()))
overlap.add(e.getValue());
@@ -172,12 +172,12 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
/**
* Acquire a reference to all of the provided objects, or none
*/
- public static <T extends RefCounted> Refs<T> tryRef(Iterable<T> reference)
+ public static <T extends RefCounted<T>> Refs<T> tryRef(Iterable<T> reference)
{
- HashMap<T, Ref> refs = new HashMap<>();
+ HashMap<T, Ref<T>> refs = new HashMap<>();
for (T rc : reference)
{
- Ref ref = rc.tryRef();
+ Ref<T> ref = rc.tryRef();
if (ref == null)
{
release(refs.values());
@@ -188,7 +188,7 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
return new Refs<T>(refs);
}
- public static <T extends RefCounted> Refs<T> ref(Iterable<T> reference)
+ public static <T extends RefCounted<T>> Refs<T> ref(Iterable<T> reference)
{
Refs<T> refs = tryRef(reference);
if (refs != null)
@@ -196,7 +196,7 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
throw new IllegalStateException();
}
- private static void release(Iterable<Ref> refs)
+ private static void release(Iterable<? extends Ref<?>> refs)
{
Throwable fail = null;
for (Ref ref : refs)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java b/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java
index b23f1c6..02efa65 100644
--- a/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java
+++ b/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java
@@ -172,4 +172,9 @@ public class OffHeapBitSet implements IBitSet
}
return (int) ((h >> 32) ^ h) + 0x98761234;
}
+
+ public String toString()
+ {
+ return "[OffHeapBitSet]";
+ }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java b/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
index 2732be5..ec8ad8a 100644
--- a/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
+++ b/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
@@ -1753,9 +1753,10 @@ public class ColumnFamilyStoreTest extends SchemaLoader
sstables = dir.sstableLister().list();
assertEquals(2, sstables.size());
+ SSTableReader sstable2 = SSTableReader.open(sstable1.descriptor);
UUID compactionTaskID = SystemKeyspace.startCompaction(
Keyspace.open(ks).getColumnFamilyStore(cf),
- Collections.singleton(SSTableReader.open(sstable1.descriptor)));
+ Collections.singleton(sstable2));
Map<Integer, UUID> unfinishedCompaction = new HashMap<>();
unfinishedCompaction.put(sstable1.descriptor.generation, compactionTaskID);
@@ -1768,6 +1769,8 @@ public class ColumnFamilyStoreTest extends SchemaLoader
Map<Pair<String, String>, Map<Integer, UUID>> unfinished = SystemKeyspace.getUnfinishedCompactions();
assertTrue(unfinished.isEmpty());
+ sstable1.selfRef().release();
+ sstable2.selfRef().release();
}
/**
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java b/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
index d9442c7..7756abe 100644
--- a/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
+++ b/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
@@ -96,7 +96,7 @@ public class AntiCompactionTest extends SchemaLoader
for (SSTableReader sstable : store.getSSTables())
{
assertFalse(sstable.isMarkedCompacted());
- assertEquals(1, sstable.sharedRef().globalCount());
+ assertEquals(1, sstable.selfRef().globalCount());
}
assertEquals(0, store.getDataTracker().getCompacting().size());
assertEquals(repairedKeys, 4);
@@ -157,7 +157,7 @@ public class AntiCompactionTest extends SchemaLoader
CompactionManager.instance.performAnticompaction(store, ranges, refs, 1);
assertThat(store.getSSTables().size(), is(1));
assertThat(Iterables.get(store.getSSTables(), 0).isRepaired(), is(false));
- assertThat(Iterables.get(store.getSSTables(), 0).sharedRef().globalCount(), is(1));
+ assertThat(Iterables.get(store.getSSTables(), 0).selfRef().globalCount(), is(1));
assertThat(store.getDataTracker().getCompacting().size(), is(0));
}
@@ -174,7 +174,7 @@ public class AntiCompactionTest extends SchemaLoader
assertThat(store.getSSTables().size(), is(1));
assertThat(Iterables.get(store.getSSTables(), 0).isRepaired(), is(true));
- assertThat(Iterables.get(store.getSSTables(), 0).sharedRef().globalCount(), is(1));
+ assertThat(Iterables.get(store.getSSTables(), 0).selfRef().globalCount(), is(1));
assertThat(store.getDataTracker().getCompacting().size(), is(0));
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java b/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
index d9bf017..87b284e 100644
--- a/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
+++ b/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
@@ -173,9 +173,9 @@ public class SizeTieredCompactionStrategyTest extends SchemaLoader
List<SSTableReader> interestingBucket = mostInterestingBucket(Collections.singletonList(sstrs.subList(0, 2)), 4, 32);
assertTrue("nothing should be returned when all buckets are below the min threshold", interestingBucket.isEmpty());
- sstrs.get(0).readMeter = new RestorableMeter(100.0, 100.0);
- sstrs.get(1).readMeter = new RestorableMeter(200.0, 200.0);
- sstrs.get(2).readMeter = new RestorableMeter(300.0, 300.0);
+ sstrs.get(0).overrideReadMeter(new RestorableMeter(100.0, 100.0));
+ sstrs.get(1).overrideReadMeter(new RestorableMeter(200.0, 200.0));
+ sstrs.get(2).overrideReadMeter(new RestorableMeter(300.0, 300.0));
long estimatedKeys = sstrs.get(0).estimatedKeys();
@@ -215,43 +215,43 @@ public class SizeTieredCompactionStrategyTest extends SchemaLoader
List<SSTableReader> sstrs = new ArrayList<>(cfs.getSSTables());
for (SSTableReader sstr : sstrs)
- sstr.readMeter = null;
+ sstr.overrideReadMeter(null);
filtered = filterColdSSTables(sstrs, 0.05, 0);
assertEquals("when there are no read meters, no sstables should be filtered", sstrs.size(), filtered.size());
for (SSTableReader sstr : sstrs)
- sstr.readMeter = new RestorableMeter(0.0, 0.0);
+ sstr.overrideReadMeter(new RestorableMeter(0.0, 0.0));
filtered = filterColdSSTables(sstrs, 0.05, 0);
assertEquals("when all read meters are zero, no sstables should be filtered", sstrs.size(), filtered.size());
// leave all read rates at 0 besides one
- sstrs.get(0).readMeter = new RestorableMeter(1000.0, 1000.0);
+ sstrs.get(0).overrideReadMeter(new RestorableMeter(1000.0, 1000.0));
filtered = filterColdSSTables(sstrs, 0.05, 0);
assertEquals("there should only be one hot sstable", 1, filtered.size());
- assertEquals(1000.0, filtered.get(0).readMeter.twoHourRate(), 0.5);
+ assertEquals(1000.0, filtered.get(0).getReadMeter().twoHourRate(), 0.5);
// the total read rate is 100, and we'll set a threshold of 2.5%, so two of the sstables with read
// rate 1.0 should be ignored, but not the third
for (SSTableReader sstr : sstrs)
- sstr.readMeter = new RestorableMeter(0.0, 0.0);
- sstrs.get(0).readMeter = new RestorableMeter(97.0, 97.0);
- sstrs.get(1).readMeter = new RestorableMeter(1.0, 1.0);
- sstrs.get(2).readMeter = new RestorableMeter(1.0, 1.0);
- sstrs.get(3).readMeter = new RestorableMeter(1.0, 1.0);
+ sstr.overrideReadMeter(new RestorableMeter(0.0, 0.0));
+ sstrs.get(0).overrideReadMeter(new RestorableMeter(97.0, 97.0));
+ sstrs.get(1).overrideReadMeter(new RestorableMeter(1.0, 1.0));
+ sstrs.get(2).overrideReadMeter(new RestorableMeter(1.0, 1.0));
+ sstrs.get(3).overrideReadMeter(new RestorableMeter(1.0, 1.0));
filtered = filterColdSSTables(sstrs, 0.025, 0);
assertEquals(2, filtered.size());
- assertEquals(98.0, filtered.get(0).readMeter.twoHourRate() + filtered.get(1).readMeter.twoHourRate(), 0.5);
+ assertEquals(98.0, filtered.get(0).getReadMeter().twoHourRate() + filtered.get(1).getReadMeter().twoHourRate(), 0.5);
// make sure a threshold of 0.0 doesn't result in any sstables being filtered
for (SSTableReader sstr : sstrs)
- sstr.readMeter = new RestorableMeter(1.0, 1.0);
+ sstr.overrideReadMeter(new RestorableMeter(1.0, 1.0));
filtered = filterColdSSTables(sstrs, 0.0, 0);
assertEquals(sstrs.size(), filtered.size());
// just for fun, set a threshold where all sstables are considered cold
for (SSTableReader sstr : sstrs)
- sstr.readMeter = new RestorableMeter(1.0, 1.0);
+ sstr.overrideReadMeter(new RestorableMeter(1.0, 1.0));
filtered = filterColdSSTables(sstrs, 1.0, 0);
assertTrue(filtered.isEmpty());
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java b/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
index 0a2b5a6..0bb9d5f 100644
--- a/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
@@ -90,7 +90,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
private static List<SSTableReader> resetSummaries(List<SSTableReader> sstables, long originalOffHeapSize) throws IOException
{
for (SSTableReader sstable : sstables)
- sstable.readMeter = new RestorableMeter(100.0, 100.0);
+ sstable.overrideReadMeter(new RestorableMeter(100.0, 100.0));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, originalOffHeapSize * sstables.size());
for (SSTableReader sstable : sstables)
@@ -117,7 +117,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
{
public int compare(SSTableReader o1, SSTableReader o2)
{
- return Double.compare(o1.readMeter.fifteenMinuteRate(), o2.readMeter.fifteenMinuteRate());
+ return Double.compare(o1.getReadMeter().fifteenMinuteRate(), o2.getReadMeter().fifteenMinuteRate());
}
};
@@ -172,7 +172,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
List<SSTableReader> sstables = new ArrayList<>(cfs.getSSTables());
for (SSTableReader sstable : sstables)
- sstable.readMeter = new RestorableMeter(100.0, 100.0);
+ sstable.overrideReadMeter(new RestorableMeter(100.0, 100.0));
for (SSTableReader sstable : sstables)
assertEquals(cfs.metadata.getMinIndexInterval(), sstable.getEffectiveIndexInterval(), 0.001);
@@ -244,7 +244,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
List<SSTableReader> sstables = new ArrayList<>(cfs.getSSTables());
for (SSTableReader sstable : sstables)
- sstable.readMeter = new RestorableMeter(100.0, 100.0);
+ sstable.overrideReadMeter(new RestorableMeter(100.0, 100.0));
IndexSummaryManager.redistributeSummaries(Collections.EMPTY_LIST, sstables, 1);
sstables = new ArrayList<>(cfs.getSSTables());
@@ -286,7 +286,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
List<SSTableReader> sstables = new ArrayList<>(cfs.getSSTables());
for (SSTableReader sstable : sstables)
- sstable.readMeter = new RestorableMeter(100.0, 100.0);
+ sstable.overrideReadMeter(new RestorableMeter(100.0, 100.0));
long singleSummaryOffHeapSpace = sstables.get(0).getIndexSummaryOffHeapSize();
@@ -325,8 +325,8 @@ public class IndexSummaryManagerTest extends SchemaLoader
// make two of the four sstables cold, only leave enough space for three full index summaries,
// so the two cold sstables should get downsampled to be half of their original size
- sstables.get(0).readMeter = new RestorableMeter(50.0, 50.0);
- sstables.get(1).readMeter = new RestorableMeter(50.0, 50.0);
+ sstables.get(0).overrideReadMeter(new RestorableMeter(50.0, 50.0));
+ sstables.get(1).overrideReadMeter(new RestorableMeter(50.0, 50.0));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, (singleSummaryOffHeapSpace * 3));
Collections.sort(sstables, hotnessComparator);
assertEquals(BASE_SAMPLING_LEVEL / 2, sstables.get(0).getIndexSummarySamplingLevel());
@@ -338,8 +338,8 @@ public class IndexSummaryManagerTest extends SchemaLoader
// small increases or decreases in the read rate don't result in downsampling or upsampling
double lowerRate = 50.0 * (DOWNSAMPLE_THESHOLD + (DOWNSAMPLE_THESHOLD * 0.10));
double higherRate = 50.0 * (UPSAMPLE_THRESHOLD - (UPSAMPLE_THRESHOLD * 0.10));
- sstables.get(0).readMeter = new RestorableMeter(lowerRate, lowerRate);
- sstables.get(1).readMeter = new RestorableMeter(higherRate, higherRate);
+ sstables.get(0).overrideReadMeter(new RestorableMeter(lowerRate, lowerRate));
+ sstables.get(1).overrideReadMeter(new RestorableMeter(higherRate, higherRate));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, (singleSummaryOffHeapSpace * 3));
Collections.sort(sstables, hotnessComparator);
assertEquals(BASE_SAMPLING_LEVEL / 2, sstables.get(0).getIndexSummarySamplingLevel());
@@ -350,10 +350,10 @@ public class IndexSummaryManagerTest extends SchemaLoader
// reset, and then this time, leave enough space for one of the cold sstables to not get downsampled
sstables = resetSummaries(sstables, singleSummaryOffHeapSpace);
- sstables.get(0).readMeter = new RestorableMeter(1.0, 1.0);
- sstables.get(1).readMeter = new RestorableMeter(2.0, 2.0);
- sstables.get(2).readMeter = new RestorableMeter(1000.0, 1000.0);
- sstables.get(3).readMeter = new RestorableMeter(1000.0, 1000.0);
+ sstables.get(0).overrideReadMeter(new RestorableMeter(1.0, 1.0));
+ sstables.get(1).overrideReadMeter(new RestorableMeter(2.0, 2.0));
+ sstables.get(2).overrideReadMeter(new RestorableMeter(1000.0, 1000.0));
+ sstables.get(3).overrideReadMeter(new RestorableMeter(1000.0, 1000.0));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, (singleSummaryOffHeapSpace * 3) + 50);
Collections.sort(sstables, hotnessComparator);
@@ -372,10 +372,10 @@ public class IndexSummaryManagerTest extends SchemaLoader
// coldest sstables will get downsampled to 4/128 of their size, leaving us with 1 and 92/128th index
// summaries worth of space. The hottest sstable should get a full index summary, and the one in the middle
// should get the remainder.
- sstables.get(0).readMeter = new RestorableMeter(0.0, 0.0);
- sstables.get(1).readMeter = new RestorableMeter(0.0, 0.0);
- sstables.get(2).readMeter = new RestorableMeter(92, 92);
- sstables.get(3).readMeter = new RestorableMeter(128.0, 128.0);
+ sstables.get(0).overrideReadMeter(new RestorableMeter(0.0, 0.0));
+ sstables.get(1).overrideReadMeter(new RestorableMeter(0.0, 0.0));
+ sstables.get(2).overrideReadMeter(new RestorableMeter(92, 92));
+ sstables.get(3).overrideReadMeter(new RestorableMeter(128.0, 128.0));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, (long) (singleSummaryOffHeapSpace + (singleSummaryOffHeapSpace * (92.0 / BASE_SAMPLING_LEVEL))));
Collections.sort(sstables, hotnessComparator);
assertEquals(1, sstables.get(0).getIndexSummarySize()); // at the min sampling level
@@ -421,10 +421,13 @@ public class IndexSummaryManagerTest extends SchemaLoader
SSTableReader sstable = original;
for (int samplingLevel = 1; samplingLevel < BASE_SAMPLING_LEVEL; samplingLevel++)
{
+ SSTableReader prev = sstable;
sstable = sstable.cloneWithNewSummarySamplingLevel(cfs, samplingLevel);
assertEquals(samplingLevel, sstable.getIndexSummarySamplingLevel());
int expectedSize = (numRows * samplingLevel) / (sstable.metadata.getMinIndexInterval() * BASE_SAMPLING_LEVEL);
assertEquals(expectedSize, sstable.getIndexSummarySize(), 1);
+ if (prev != original)
+ prev.selfRef().release();
}
// don't leave replaced SSTRs around to break other tests
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java b/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
index 8bef669..19ba274 100644
--- a/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
@@ -118,7 +118,7 @@ public class LegacySSTableTest extends SchemaLoader
ranges.add(new Range<>(p.getMinimumToken(), p.getToken(ByteBufferUtil.bytes("100"))));
ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("100")), p.getMinimumToken()));
ArrayList<StreamSession.SSTableStreamingSections> details = new ArrayList<>();
- details.add(new StreamSession.SSTableStreamingSections(sstable, sstable.tryRef(),
+ details.add(new StreamSession.SSTableStreamingSections(sstable, sstable.ref(),
sstable.getPositionsForRanges(ranges),
sstable.estimatedKeysForRanges(ranges), sstable.getSSTableMetadata().repairedAt));
new StreamPlan("LegacyStreamingTest").transferFiles(FBUtilities.getBroadcastAddress(), details)
@@ -138,6 +138,7 @@ public class LegacySSTableTest extends SchemaLoader
assert cf.deletionInfo().equals(DeletionInfo.live());
assert iter.next().name().toByteBuffer().equals(key);
}
+ sstable.selfRef().release();
}
@Test
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java b/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
index 51588f2..9607673 100644
--- a/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
@@ -203,15 +203,15 @@ public class SSTableReaderTest extends SchemaLoader
store.forceBlockingFlush();
SSTableReader sstable = store.getSSTables().iterator().next();
- assertEquals(0, sstable.readMeter.count());
+ assertEquals(0, sstable.getReadMeter().count());
DecoratedKey key = sstable.partitioner.decorateKey(ByteBufferUtil.bytes("4"));
store.getColumnFamily(key, Composites.EMPTY, Composites.EMPTY, false, 100, 100);
- assertEquals(1, sstable.readMeter.count());
+ assertEquals(1, sstable.getReadMeter().count());
store.getColumnFamily(key, cellname("0"), cellname("0"), false, 100, 100);
- assertEquals(2, sstable.readMeter.count());
+ assertEquals(2, sstable.getReadMeter().count());
store.getColumnFamily(Util.namesQueryFilter(store, key, cellname("0")));
- assertEquals(3, sstable.readMeter.count());
+ assertEquals(3, sstable.getReadMeter().count());
}
@Test
@@ -334,6 +334,7 @@ public class SSTableReaderTest extends SchemaLoader
Assert.assertArrayEquals(ByteBufferUtil.getArray(firstKey.getKey()), target.getIndexSummaryKey(0));
assert target.first.equals(firstKey);
assert target.last.equals(lastKey);
+ target.selfRef().release();
}
@Test
@@ -360,6 +361,7 @@ public class SSTableReaderTest extends SchemaLoader
SSTableReader reopened = SSTableReader.open(sstable.descriptor);
assert reopened.first.getToken() instanceof LocalToken;
+ reopened.selfRef().release();
}
/** see CASSANDRA-5407 */
@@ -417,6 +419,7 @@ public class SSTableReaderTest extends SchemaLoader
SSTableReader bulkLoaded = SSTableReader.openForBatch(sstable.descriptor, components, store.metadata, sstable.partitioner);
sections = bulkLoaded.getPositionsForRanges(ranges);
assert sections.size() == 1 : "Expected to find range in sstable opened for bulk loading";
+ bulkLoaded.selfRef().release();
}
@Test
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java b/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
index acf8c90..2e11624 100644
--- a/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
@@ -19,11 +19,7 @@ package org.apache.cassandra.io.sstable;
import java.io.File;
import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
import com.google.common.collect.Sets;
import org.junit.Test;
@@ -200,10 +196,11 @@ public class SSTableRewriterTest extends SchemaLoader
assertTrue(s != s2);
assertFileCounts(dir.list(), 2, 3);
s.markObsolete();
- s.sharedRef().release();
+ s.selfRef().release();
+ s2.selfRef().release();
Thread.sleep(1000);
assertFileCounts(dir.list(), 0, 3);
- writer.abort(false);
+ writer.abort();
Thread.sleep(1000);
int datafiles = assertFileCounts(dir.list(), 0, 0);
assertEquals(datafiles, 0);
@@ -705,7 +702,7 @@ public class SSTableRewriterTest extends SchemaLoader
for (SSTableReader sstable : cfs.getSSTables())
{
assertFalse(sstable.isMarkedCompacted());
- assertEquals(1, sstable.sharedRef().globalCount());
+ assertEquals(1, sstable.selfRef().globalCount());
liveDescriptors.add(sstable.descriptor.generation);
}
for (File dir : cfs.directories.getCFDirectories())
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java b/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
index f84ae11..1447b29 100644
--- a/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
+++ b/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
@@ -64,7 +64,7 @@ public class StreamTransferTaskTest extends SchemaLoader
{
List<Range<Token>> ranges = new ArrayList<>();
ranges.add(new Range<>(sstable.first.getToken(), sstable.last.getToken()));
- task.addTransferFile(sstable, sstable.sharedRef(), 1, sstable.getPositionsForRanges(ranges), 0);
+ task.addTransferFile(sstable, sstable.selfRef(), 1, sstable.getPositionsForRanges(ranges), 0);
}
assertEquals(2, task.getTotalNumberOfFiles());
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/tools/SSTableExportTest.java b/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
index c3f3419..c918d6a 100644
--- a/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
+++ b/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
@@ -189,6 +189,7 @@ public class SSTableExportTest extends SchemaLoader
qf = Util.namesQueryFilter(cfs, Util.dk("rowExclude"), "name");
cf = qf.getSSTableColumnIterator(reader).getColumnFamily();
assert cf == null;
+ reader.selfRef().release();
}
@Test
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/tools/SSTableImportTest.java b/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
index b0f4c0a..a5f05f8 100644
--- a/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
+++ b/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
@@ -71,6 +71,7 @@ public class SSTableImportTest extends SchemaLoader
assert expCol.value().equals(hexToBytes("76616c4143"));
assert expCol instanceof ExpiringCell;
assert ((ExpiringCell)expCol).getTimeToLive() == 42 && expCol.getLocalDeletionTime() == 2000000000;
+ reader.selfRef().release();
}
private ColumnFamily cloneForAdditions(OnDiskAtomIterator iter)
@@ -105,6 +106,7 @@ public class SSTableImportTest extends SchemaLoader
assert expCol.value().equals(hexToBytes("76616c4143"));
assert expCol instanceof ExpiringCell;
assert ((ExpiringCell) expCol).getTimeToLive() == 42 && expCol.getLocalDeletionTime() == 2000000000;
+ reader.selfRef().release();
}
@Test
@@ -129,6 +131,7 @@ public class SSTableImportTest extends SchemaLoader
assert expCol.value().equals(hexToBytes("76616c4143"));
assert expCol instanceof ExpiringCell;
assert ((ExpiringCell) expCol).getTimeToLive() == 42 && expCol.getLocalDeletionTime() == 2000000000;
+ reader.selfRef().release();
}
@Test
@@ -148,6 +151,7 @@ public class SSTableImportTest extends SchemaLoader
Cell c = cf.getColumn(Util.cellname("colAA"));
assert c instanceof CounterCell : c;
assert ((CounterCell) c).total() == 42;
+ reader.selfRef().release();
}
@Test
@@ -168,6 +172,7 @@ public class SSTableImportTest extends SchemaLoader
QueryFilter qf2 = QueryFilter.getIdentityFilter(Util.dk("726f7741", BytesType.instance), "AsciiKeys", System.currentTimeMillis());
OnDiskAtomIterator iter2 = qf2.getSSTableColumnIterator(reader);
assert !iter2.hasNext(); // "bytes" key does not exist
+ reader.selfRef().release();
}
@Test
@@ -186,6 +191,7 @@ public class SSTableImportTest extends SchemaLoader
QueryFilter qf = QueryFilter.getIdentityFilter(Util.dk("rowA"), "AsciiKeys", System.currentTimeMillis());
OnDiskAtomIterator iter = qf.getSSTableColumnIterator(reader);
assert iter.hasNext(); // "bytes" key exists
+ reader.selfRef().release();
}
@Test
@@ -207,6 +213,7 @@ public class SSTableImportTest extends SchemaLoader
assertThat(result.size(), is(2));
assertThat(result, hasItem(withElements(1, "NY", 1980)));
assertThat(result, hasItem(withElements(2, "CA", 2014)));
+ reader.selfRef().release();
}
@Test(expected=AssertionError.class)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/utils/BloomFilterTest.java b/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
index 4180a8c..aee0880 100644
--- a/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
+++ b/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
@@ -30,10 +30,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.*;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.io.util.DataOutputStreamAndChannel;
@@ -45,7 +42,7 @@ public class BloomFilterTest
public BloomFilterTest()
{
- bf = FilterFactory.getFilter(10000L, FilterTestHelper.MAX_FAILURE_RATE, true);
+
}
public static IFilter testSerialize(IFilter f) throws IOException
@@ -64,9 +61,15 @@ public class BloomFilterTest
@Before
- public void clear()
+ public void setup()
+ {
+ bf = FilterFactory.getFilter(10000L, FilterTestHelper.MAX_FAILURE_RATE, true);
+ }
+
+ @After
+ public void destroy()
{
- bf.clear();
+ bf.close();
}
@Test(expected = UnsupportedOperationException.class)
@@ -114,12 +117,13 @@ public class BloomFilterTest
FilterTestHelper.testFalsePositives(bf2,
new KeyGenerator.WordGenerator(skipEven, 2),
new KeyGenerator.WordGenerator(1, 2));
+ bf2.close();
}
@Test
public void testSerialize() throws IOException
{
- BloomFilterTest.testSerialize(bf);
+ BloomFilterTest.testSerialize(bf).close();
}
public void testManyHashes(Iterator<ByteBuffer> keys)
@@ -137,6 +141,7 @@ public class BloomFilterTest
hashes.add(hashIndex);
}
collisions += (MAX_HASH_COUNT - hashes.size());
+ bf.close();
}
assert collisions <= 100;
}
@@ -167,6 +172,7 @@ public class BloomFilterTest
FilterFactory.serialize(filter, out);
filter.bitset.serialize(out);
out.close();
+ filter.close();
DataInputStream in = new DataInputStream(new FileInputStream(file));
BloomFilter filter2 = (BloomFilter) FilterFactory.deserialize(in, true);
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/utils/SerializationsTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/utils/SerializationsTest.java b/test/unit/org/apache/cassandra/utils/SerializationsTest.java
index 976a3eb..b0a23fd 100644
--- a/test/unit/org/apache/cassandra/utils/SerializationsTest.java
+++ b/test/unit/org/apache/cassandra/utils/SerializationsTest.java
@@ -39,6 +39,7 @@ public class SerializationsTest extends AbstractSerializationsTester
DataOutputStreamAndChannel out = getOutput("utils.BloomFilter.bin");
FilterFactory.serialize(bf, out);
out.close();
+ bf.close();
}
@Test
@@ -48,7 +49,9 @@ public class SerializationsTest extends AbstractSerializationsTester
testBloomFilterWrite(true);
DataInputStream in = getInput("utils.BloomFilter.bin");
- assert FilterFactory.deserialize(in, true) != null;
+ IFilter bf = FilterFactory.deserialize(in, true);
+ assert bf != null;
+ bf.close();
in.close();
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java b/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java
index fe22d21..a9247cd 100644
--- a/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java
+++ b/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java
@@ -44,9 +44,9 @@ public class RefCountedTest
public void testLeak() throws InterruptedException
{
Tidier tidier = new Tidier();
- RefCounted obj = RefCounted.Impl.get(tidier);
+ Ref<?> obj = new Ref(null, tidier);
obj.tryRef();
- obj.sharedRef().release();
+ obj.release();
System.gc();
System.gc();
Thread.sleep(1000);
@@ -57,7 +57,7 @@ public class RefCountedTest
public void testSeriousLeak() throws InterruptedException
{
Tidier tidier = new Tidier();
- RefCounted.Impl.get(tidier);
+ new Ref(null, tidier);
System.gc();
System.gc();
System.gc();
@@ -73,9 +73,9 @@ public class RefCountedTest
try
{
tidier = new Tidier();
- RefCounted obj = RefCounted.Impl.get(tidier);
- obj.sharedRef().release();
- obj.sharedRef().release();
+ Ref<?> obj = new Ref(null, tidier);
+ obj.release();
+ obj.release();
Assert.assertTrue(false);
}
catch (Exception e)
[5/7] cassandra git commit: Merge branch 'cassandra-2.1' into trunk
Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/sstable/format/SSTableWriter.java
----------------------------------------------------------------------
diff --cc src/java/org/apache/cassandra/io/sstable/format/SSTableWriter.java
index 32b5520,0000000..33f6bd1
mode 100644,000000..100644
--- a/src/java/org/apache/cassandra/io/sstable/format/SSTableWriter.java
+++ b/src/java/org/apache/cassandra/io/sstable/format/SSTableWriter.java
@@@ -1,215 -1,0 +1,213 @@@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.io.sstable.format;
+
+import com.google.common.collect.Sets;
+import org.apache.cassandra.config.CFMetaData;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.config.Schema;
+import org.apache.cassandra.db.ColumnFamily;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.RowIndexEntry;
+import org.apache.cassandra.db.compaction.AbstractCompactedRow;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.io.sstable.Component;
+import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.SSTable;
+import org.apache.cassandra.io.sstable.metadata.MetadataCollector;
+import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
+import org.apache.cassandra.io.util.FileUtils;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.DataInput;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * This is the API all table writers must implement.
+ *
+ * TableWriter.create() is the primary way to create a writer for a particular format.
+ * The format information is part of the Descriptor.
+ */
+public abstract class SSTableWriter extends SSTable
+{
+ private static final Logger logger = LoggerFactory.getLogger(SSTableWriter.class);
+
+ public static enum FinishType
+ {
- NORMAL(SSTableReader.OpenReason.NORMAL),
- EARLY(SSTableReader.OpenReason.EARLY), // no renaming
- FINISH_EARLY(SSTableReader.OpenReason.NORMAL); // tidy up an EARLY finish
++ CLOSE(null, true),
++ NORMAL(SSTableReader.OpenReason.NORMAL, true),
++ EARLY(SSTableReader.OpenReason.EARLY, false), // no renaming
++ FINISH_EARLY(SSTableReader.OpenReason.NORMAL, true); // tidy up an EARLY finish
+ public final SSTableReader.OpenReason openReason;
+
- FinishType(SSTableReader.OpenReason openReason)
++ public final boolean isFinal;
++ FinishType(SSTableReader.OpenReason openReason, boolean isFinal)
+ {
+ this.openReason = openReason;
++ this.isFinal = isFinal;
+ }
+ }
+
+ protected final long repairedAt;
+ protected final long keyCount;
+ protected final MetadataCollector metadataCollector;
+ protected final RowIndexEntry.IndexSerializer rowIndexEntrySerializer;
+
+ protected SSTableWriter(Descriptor descriptor, long keyCount, long repairedAt, CFMetaData metadata, IPartitioner partitioner, MetadataCollector metadataCollector)
+ {
+ super(descriptor, components(metadata), metadata, partitioner);
+ this.keyCount = keyCount;
+ this.repairedAt = repairedAt;
+ this.metadataCollector = metadataCollector;
+ this.rowIndexEntrySerializer = descriptor.version.getSSTableFormat().getIndexSerializer(metadata);
+ }
+
+ public static SSTableWriter create(Descriptor descriptor, Long keyCount, Long repairedAt, CFMetaData metadata, IPartitioner partitioner, MetadataCollector metadataCollector)
+ {
+ Factory writerFactory = descriptor.getFormat().getWriterFactory();
+ return writerFactory.open(descriptor, keyCount, repairedAt, metadata, partitioner, metadataCollector);
+ }
+
+ public static SSTableWriter create(Descriptor descriptor, long keyCount, long repairedAt)
+ {
+ return create(descriptor, keyCount, repairedAt, 0);
+ }
+
+ public static SSTableWriter create(Descriptor descriptor, long keyCount, long repairedAt, int sstableLevel)
+ {
+ CFMetaData metadata = Schema.instance.getCFMetaData(descriptor);
+ MetadataCollector collector = new MetadataCollector(metadata.comparator).sstableLevel(sstableLevel);
+
+ return create(descriptor, keyCount, repairedAt, metadata, DatabaseDescriptor.getPartitioner(), collector);
+ }
+
+ public static SSTableWriter create(String filename, long keyCount, long repairedAt, int sstableLevel)
+ {
+ return create(Descriptor.fromFilename(filename), keyCount, repairedAt, sstableLevel);
+ }
+
+ public static SSTableWriter create(String filename, long keyCount, long repairedAt)
+ {
+ return create(Descriptor.fromFilename(filename), keyCount, repairedAt, 0);
+ }
+
+ private static Set<Component> components(CFMetaData metadata)
+ {
+ Set<Component> components = new HashSet<Component>(Arrays.asList(Component.DATA,
+ Component.PRIMARY_INDEX,
+ Component.STATS,
+ Component.SUMMARY,
+ Component.TOC,
+ Component.DIGEST));
+
+ if (metadata.getBloomFilterFpChance() < 1.0)
+ components.add(Component.FILTER);
+
+ if (metadata.compressionParameters().sstableCompressor != null)
+ {
+ components.add(Component.COMPRESSION_INFO);
+ }
+ else
+ {
+ // it would feel safer to actually add this component later in maybeWriteDigest(),
+ // but the components are unmodifiable after construction
+ components.add(Component.CRC);
+ }
+ return components;
+ }
+
+
+ public abstract void mark();
+
+
+ /**
+ * @param row
+ * @return null if the row was compacted away entirely; otherwise, the PK index entry for this row
+ */
+ public abstract RowIndexEntry append(AbstractCompactedRow row);
+
+ public abstract void append(DecoratedKey decoratedKey, ColumnFamily cf);
+
+ public abstract long appendFromStream(DecoratedKey key, CFMetaData metadata, DataInput in, Version version) throws IOException;
+
+ public abstract long getFilePointer();
+
+ public abstract long getOnDiskFilePointer();
+
+ public abstract void isolateReferences();
+
+ public abstract void resetAndTruncate();
+
+ public SSTableReader closeAndOpenReader()
+ {
+ return closeAndOpenReader(System.currentTimeMillis());
+ }
+
+ public SSTableReader closeAndOpenReader(long maxDataAge)
+ {
+ return finish(FinishType.NORMAL, maxDataAge, repairedAt);
+ }
+
+ public abstract SSTableReader finish(FinishType finishType, long maxDataAge, long repairedAt);
+
+ public abstract SSTableReader openEarly(long maxDataAge);
+
+ // Close the writer and return the descriptor to the new sstable and it's metadata
+ public abstract Pair<Descriptor, StatsMetadata> close();
+
+
+
+ public static Descriptor rename(Descriptor tmpdesc, Set<Component> components)
+ {
+ Descriptor newdesc = tmpdesc.asType(Descriptor.Type.FINAL);
+ rename(tmpdesc, newdesc, components);
+ return newdesc;
+ }
+
+ public static void rename(Descriptor tmpdesc, Descriptor newdesc, Set<Component> components)
+ {
+ for (Component component : Sets.difference(components, Sets.newHashSet(Component.DATA, Component.SUMMARY)))
+ {
+ FileUtils.renameWithConfirm(tmpdesc.filenameFor(component), newdesc.filenameFor(component));
+ }
+
+ // do -Data last because -Data present should mean the sstable was completely renamed before crash
+ FileUtils.renameWithConfirm(tmpdesc.filenameFor(Component.DATA), newdesc.filenameFor(Component.DATA));
+
+ // rename it without confirmation because summary can be available for loadNewSSTables but not for closeAndOpenReader
+ FileUtils.renameWithOutConfirm(tmpdesc.filenameFor(Component.SUMMARY), newdesc.filenameFor(Component.SUMMARY));
+ }
+
+
+ /**
+ * After failure, attempt to close the index writer and data file before deleting all temp components for the sstable
+ */
- public void abort()
- {
- abort(true);
- }
-
- public abstract void abort(boolean closeBf);
++ public abstract void abort();
+
+
+ public static abstract class Factory
+ {
+ public abstract SSTableWriter open(Descriptor descriptor, long keyCount, long repairedAt, CFMetaData metadata, IPartitioner partitioner, MetadataCollector metadataCollector);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/sstable/format/big/BigTableWriter.java
----------------------------------------------------------------------
diff --cc src/java/org/apache/cassandra/io/sstable/format/big/BigTableWriter.java
index 005e4c4,0000000..bba7550
mode 100644,000000..100644
--- a/src/java/org/apache/cassandra/io/sstable/format/big/BigTableWriter.java
+++ b/src/java/org/apache/cassandra/io/sstable/format/big/BigTableWriter.java
@@@ -1,587 -1,0 +1,588 @@@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.io.sstable.format.big;
+
+import java.io.DataInput;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.cassandra.db.*;
+import org.apache.cassandra.io.sstable.*;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.io.sstable.format.SSTableWriter;
+import org.apache.cassandra.io.sstable.format.Version;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.config.CFMetaData;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.db.compaction.AbstractCompactedRow;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.io.FSWriteError;
+import org.apache.cassandra.io.compress.CompressedSequentialWriter;
+import org.apache.cassandra.io.sstable.metadata.MetadataCollector;
+import org.apache.cassandra.io.sstable.metadata.MetadataComponent;
+import org.apache.cassandra.io.sstable.metadata.MetadataType;
+import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
+import org.apache.cassandra.io.util.DataOutputPlus;
+import org.apache.cassandra.io.util.DataOutputStreamAndChannel;
+import org.apache.cassandra.io.util.FileMark;
+import org.apache.cassandra.io.util.FileUtils;
+import org.apache.cassandra.io.util.SegmentedFile;
+import org.apache.cassandra.io.util.SequentialWriter;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.FilterFactory;
+import org.apache.cassandra.utils.IFilter;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.StreamingHistogram;
+
+public class BigTableWriter extends SSTableWriter
+{
+ private static final Logger logger = LoggerFactory.getLogger(BigTableWriter.class);
+
+ // not very random, but the only value that can't be mistaken for a legal column-name length
+ public static final int END_OF_ROW = 0x0000;
+
+ private IndexWriter iwriter;
+ private SegmentedFile.Builder dbuilder;
+ private final SequentialWriter dataFile;
+ private DecoratedKey lastWrittenKey;
+ private FileMark dataMark;
+
+ BigTableWriter(Descriptor descriptor, Long keyCount, Long repairedAt, CFMetaData metadata, IPartitioner partitioner, MetadataCollector metadataCollector)
+ {
+ super(descriptor, keyCount, repairedAt, metadata, partitioner, metadataCollector);
+
+ iwriter = new IndexWriter(keyCount);
+
+ if (compression)
+ {
+ dataFile = SequentialWriter.open(getFilename(),
+ descriptor.filenameFor(Component.COMPRESSION_INFO),
+ metadata.compressionParameters(),
+ metadataCollector);
+ dbuilder = SegmentedFile.getCompressedBuilder((CompressedSequentialWriter) dataFile);
+ }
+ else
+ {
+ dataFile = SequentialWriter.open(new File(getFilename()), new File(descriptor.filenameFor(Component.CRC)));
+ dbuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getDiskAccessMode());
+ }
+ }
+
+ public void mark()
+ {
+ dataMark = dataFile.mark();
+ iwriter.mark();
+ }
+
+ public void resetAndTruncate()
+ {
+ dataFile.resetAndTruncate(dataMark);
+ iwriter.resetAndTruncate();
+ }
+
+ /**
+ * Perform sanity checks on @param decoratedKey and @return the position in the data file before any data is written
+ */
+ private long beforeAppend(DecoratedKey decoratedKey)
+ {
+ assert decoratedKey != null : "Keys must not be null"; // empty keys ARE allowed b/c of indexed column values
+ if (lastWrittenKey != null && lastWrittenKey.compareTo(decoratedKey) >= 0)
+ throw new RuntimeException("Last written key " + lastWrittenKey + " >= current key " + decoratedKey + " writing into " + getFilename());
+ return (lastWrittenKey == null) ? 0 : dataFile.getFilePointer();
+ }
+
+ private void afterAppend(DecoratedKey decoratedKey, long dataPosition, RowIndexEntry index)
+ {
+ metadataCollector.addKey(decoratedKey.getKey());
+ lastWrittenKey = decoratedKey;
+ last = lastWrittenKey;
+ if (first == null)
+ first = lastWrittenKey;
+
+ if (logger.isTraceEnabled())
+ logger.trace("wrote {} at {}", decoratedKey, dataPosition);
+ iwriter.append(decoratedKey, index);
+ dbuilder.addPotentialBoundary(dataPosition);
+ }
+
+ /**
+ * @param row
+ * @return null if the row was compacted away entirely; otherwise, the PK index entry for this row
+ */
+ public RowIndexEntry append(AbstractCompactedRow row)
+ {
+ long currentPosition = beforeAppend(row.key);
+ RowIndexEntry entry;
+ try
+ {
+ entry = row.write(currentPosition, dataFile);
+ if (entry == null)
+ return null;
+ }
+ catch (IOException e)
+ {
+ throw new FSWriteError(e, dataFile.getPath());
+ }
+ metadataCollector.update(dataFile.getFilePointer() - currentPosition, row.columnStats());
+ afterAppend(row.key, currentPosition, entry);
+ return entry;
+ }
+
+ public void append(DecoratedKey decoratedKey, ColumnFamily cf)
+ {
+ if (decoratedKey.getKey().remaining() > FBUtilities.MAX_UNSIGNED_SHORT)
+ {
+ logger.error("Key size {} exceeds maximum of {}, skipping row",
+ decoratedKey.getKey().remaining(),
+ FBUtilities.MAX_UNSIGNED_SHORT);
+ return;
+ }
+
+ long startPosition = beforeAppend(decoratedKey);
+ try
+ {
+ RowIndexEntry entry = rawAppend(cf, startPosition, decoratedKey, dataFile.stream);
+ afterAppend(decoratedKey, startPosition, entry);
+ }
+ catch (IOException e)
+ {
+ throw new FSWriteError(e, dataFile.getPath());
+ }
+ metadataCollector.update(dataFile.getFilePointer() - startPosition, cf.getColumnStats());
+ }
+
+ private static RowIndexEntry rawAppend(ColumnFamily cf, long startPosition, DecoratedKey key, DataOutputPlus out) throws IOException
+ {
+ assert cf.hasColumns() || cf.isMarkedForDelete();
+
+ ColumnIndex.Builder builder = new ColumnIndex.Builder(cf, key.getKey(), out);
+ ColumnIndex index = builder.build(cf);
+
+ out.writeShort(END_OF_ROW);
+ return RowIndexEntry.create(startPosition, cf.deletionInfo().getTopLevelDeletion(), index);
+ }
+
+ /**
+ * @throws IOException if a read from the DataInput fails
+ * @throws FSWriteError if a write to the dataFile fails
+ */
+ public long appendFromStream(DecoratedKey key, CFMetaData metadata, DataInput in, Version version) throws IOException
+ {
+ long currentPosition = beforeAppend(key);
+
+ ColumnStats.MaxLongTracker maxTimestampTracker = new ColumnStats.MaxLongTracker(Long.MAX_VALUE);
+ ColumnStats.MinLongTracker minTimestampTracker = new ColumnStats.MinLongTracker(Long.MIN_VALUE);
+ ColumnStats.MaxIntTracker maxDeletionTimeTracker = new ColumnStats.MaxIntTracker(Integer.MAX_VALUE);
+ List<ByteBuffer> minColumnNames = Collections.emptyList();
+ List<ByteBuffer> maxColumnNames = Collections.emptyList();
+ StreamingHistogram tombstones = new StreamingHistogram(TOMBSTONE_HISTOGRAM_BIN_SIZE);
+ boolean hasLegacyCounterShards = false;
+
+ ColumnFamily cf = ArrayBackedSortedColumns.factory.create(metadata);
+ cf.delete(DeletionTime.serializer.deserialize(in));
+
+ ColumnIndex.Builder columnIndexer = new ColumnIndex.Builder(cf, key.getKey(), dataFile.stream);
+
+ if (cf.deletionInfo().getTopLevelDeletion().localDeletionTime < Integer.MAX_VALUE)
+ {
+ tombstones.update(cf.deletionInfo().getTopLevelDeletion().localDeletionTime);
+ maxDeletionTimeTracker.update(cf.deletionInfo().getTopLevelDeletion().localDeletionTime);
+ minTimestampTracker.update(cf.deletionInfo().getTopLevelDeletion().markedForDeleteAt);
+ maxTimestampTracker.update(cf.deletionInfo().getTopLevelDeletion().markedForDeleteAt);
+ }
+
+ Iterator<RangeTombstone> rangeTombstoneIterator = cf.deletionInfo().rangeIterator();
+ while (rangeTombstoneIterator.hasNext())
+ {
+ RangeTombstone rangeTombstone = rangeTombstoneIterator.next();
+ tombstones.update(rangeTombstone.getLocalDeletionTime());
+ minTimestampTracker.update(rangeTombstone.timestamp());
+ maxTimestampTracker.update(rangeTombstone.timestamp());
+ maxDeletionTimeTracker.update(rangeTombstone.getLocalDeletionTime());
+ minColumnNames = ColumnNameHelper.minComponents(minColumnNames, rangeTombstone.min, metadata.comparator);
+ maxColumnNames = ColumnNameHelper.maxComponents(maxColumnNames, rangeTombstone.max, metadata.comparator);
+ }
+
+ Iterator<OnDiskAtom> iter = AbstractCell.onDiskIterator(in, ColumnSerializer.Flag.PRESERVE_SIZE, Integer.MIN_VALUE, version, metadata.comparator);
+ try
+ {
+ while (iter.hasNext())
+ {
+ OnDiskAtom atom = iter.next();
+ if (atom == null)
+ break;
+
+ if (atom instanceof CounterCell)
+ {
+ atom = ((CounterCell) atom).markLocalToBeCleared();
+ hasLegacyCounterShards = hasLegacyCounterShards || ((CounterCell) atom).hasLegacyShards();
+ }
+
+ int deletionTime = atom.getLocalDeletionTime();
+ if (deletionTime < Integer.MAX_VALUE)
+ tombstones.update(deletionTime);
+ minTimestampTracker.update(atom.timestamp());
+ maxTimestampTracker.update(atom.timestamp());
+ minColumnNames = ColumnNameHelper.minComponents(minColumnNames, atom.name(), metadata.comparator);
+ maxColumnNames = ColumnNameHelper.maxComponents(maxColumnNames, atom.name(), metadata.comparator);
+ maxDeletionTimeTracker.update(atom.getLocalDeletionTime());
+
+ columnIndexer.add(atom); // This write the atom on disk too
+ }
+
+ columnIndexer.maybeWriteEmptyRowHeader();
+ dataFile.stream.writeShort(END_OF_ROW);
+ }
+ catch (IOException e)
+ {
+ throw new FSWriteError(e, dataFile.getPath());
+ }
+
+ metadataCollector.updateMinTimestamp(minTimestampTracker.get())
+ .updateMaxTimestamp(maxTimestampTracker.get())
+ .updateMaxLocalDeletionTime(maxDeletionTimeTracker.get())
+ .addRowSize(dataFile.getFilePointer() - currentPosition)
+ .addColumnCount(columnIndexer.writtenAtomCount())
+ .mergeTombstoneHistogram(tombstones)
+ .updateMinColumnNames(minColumnNames)
+ .updateMaxColumnNames(maxColumnNames)
+ .updateHasLegacyCounterShards(hasLegacyCounterShards);
+
+ afterAppend(key, currentPosition, RowIndexEntry.create(currentPosition, cf.deletionInfo().getTopLevelDeletion(), columnIndexer.build()));
+ return currentPosition;
+ }
+
+ /**
+ * After failure, attempt to close the index writer and data file before deleting all temp components for the sstable
+ */
- public void abort(boolean closeBf)
++ public void abort()
+ {
+ assert descriptor.type.isTemporary;
+ if (iwriter == null && dataFile == null)
+ return;
+
+ if (iwriter != null)
- iwriter.abort(closeBf);
++ iwriter.abort();
+
+ if (dataFile!= null)
+ dataFile.abort();
+
+ Set<Component> components = SSTable.componentsFor(descriptor);
+ try
+ {
+ if (!components.isEmpty())
+ SSTable.delete(descriptor, components);
+ }
+ catch (FSWriteError e)
+ {
+ logger.error(String.format("Failed deleting temp components for %s", descriptor), e);
+ throw e;
+ }
+ }
+
+ // we use this method to ensure any managed data we may have retained references to during the write are no
+ // longer referenced, so that we do not need to enclose the expensive call to closeAndOpenReader() in a transaction
+ public void isolateReferences()
+ {
+ // currently we only maintain references to first/last/lastWrittenKey from the data provided; all other
+ // data retention is done through copying
+ first = getMinimalKey(first);
+ last = lastWrittenKey = getMinimalKey(last);
+ }
+
+ private Descriptor makeTmpLinks()
+ {
+ // create temp links if they don't already exist
+ Descriptor link = descriptor.asType(Descriptor.Type.TEMPLINK);
+ if (!new File(link.filenameFor(Component.PRIMARY_INDEX)).exists())
+ {
+ FileUtils.createHardLink(new File(descriptor.filenameFor(Component.PRIMARY_INDEX)), new File(link.filenameFor(Component.PRIMARY_INDEX)));
+ FileUtils.createHardLink(new File(descriptor.filenameFor(Component.DATA)), new File(link.filenameFor(Component.DATA)));
+ }
+ return link;
+ }
+
+ public SSTableReader openEarly(long maxDataAge)
+ {
+ StatsMetadata sstableMetadata = (StatsMetadata) metadataCollector.finalizeMetadata(partitioner.getClass().getCanonicalName(),
+ metadata.getBloomFilterFpChance(),
+ repairedAt).get(MetadataType.STATS);
+
+ // find the max (exclusive) readable key
+ DecoratedKey exclusiveUpperBoundOfReadableIndex = iwriter.getMaxReadableKey(0);
+ if (exclusiveUpperBoundOfReadableIndex == null)
+ return null;
+
+ Descriptor link = makeTmpLinks();
+ // open the reader early, giving it a FINAL descriptor type so that it is indistinguishable for other consumers
+ SegmentedFile ifile = iwriter.builder.complete(link.filenameFor(Component.PRIMARY_INDEX), FinishType.EARLY);
+ SegmentedFile dfile = dbuilder.complete(link.filenameFor(Component.DATA), FinishType.EARLY);
+ SSTableReader sstable = SSTableReader.internalOpen(descriptor.asType(Descriptor.Type.FINAL),
+ components, metadata,
+ partitioner, ifile,
+ dfile, iwriter.summary.build(partitioner, exclusiveUpperBoundOfReadableIndex),
- iwriter.bf, maxDataAge, sstableMetadata, SSTableReader.OpenReason.EARLY);
++ iwriter.bf.sharedCopy(), maxDataAge, sstableMetadata, SSTableReader.OpenReason.EARLY);
+
+ // now it's open, find the ACTUAL last readable key (i.e. for which the data file has also been flushed)
+ sstable.first = getMinimalKey(first);
+ sstable.last = getMinimalKey(exclusiveUpperBoundOfReadableIndex);
+ DecoratedKey inclusiveUpperBoundOfReadableData = iwriter.getMaxReadableKey(1);
+ if (inclusiveUpperBoundOfReadableData == null)
+ {
+ // Prevent leaving tmplink files on disk
- sstable.sharedRef().release();
++ sstable.selfRef().release();
+ return null;
+ }
+ int offset = 2;
+ while (true)
+ {
+ RowIndexEntry indexEntry = sstable.getPosition(inclusiveUpperBoundOfReadableData, SSTableReader.Operator.GT);
+ if (indexEntry != null && indexEntry.position <= dataFile.getLastFlushOffset())
+ break;
+ inclusiveUpperBoundOfReadableData = iwriter.getMaxReadableKey(offset++);
+ if (inclusiveUpperBoundOfReadableData == null)
+ {
- sstable.sharedRef().release();
++ sstable.selfRef().release();
+ return null;
+ }
+ }
+ sstable.last = getMinimalKey(inclusiveUpperBoundOfReadableData);
+ return sstable;
+ }
+
+ public SSTableReader closeAndOpenReader()
+ {
+ return closeAndOpenReader(System.currentTimeMillis());
+ }
+
+ public SSTableReader closeAndOpenReader(long maxDataAge)
+ {
+ return finish(FinishType.NORMAL, maxDataAge, this.repairedAt);
+ }
+
+ public SSTableReader finish(FinishType finishType, long maxDataAge, long repairedAt)
+ {
++ assert finishType != FinishType.CLOSE;
+ Pair<Descriptor, StatsMetadata> p;
+
+ p = close(finishType, repairedAt < 0 ? this.repairedAt : repairedAt);
+ Descriptor desc = p.left;
+ StatsMetadata metadata = p.right;
+
+ if (finishType == FinishType.EARLY)
+ desc = makeTmpLinks();
+
+ // finalize in-memory state for the reader
+ SegmentedFile ifile = iwriter.builder.complete(desc.filenameFor(Component.PRIMARY_INDEX), finishType);
+ SegmentedFile dfile = dbuilder.complete(desc.filenameFor(Component.DATA), finishType);
+ SSTableReader sstable = SSTableReader.internalOpen(desc.asType(Descriptor.Type.FINAL),
+ components,
+ this.metadata,
+ partitioner,
+ ifile,
+ dfile,
+ iwriter.summary.build(partitioner),
- iwriter.bf,
++ iwriter.bf.sharedCopy(),
+ maxDataAge,
+ metadata,
+ finishType.openReason);
+ sstable.first = getMinimalKey(first);
+ sstable.last = getMinimalKey(last);
+
- switch (finishType)
++ if (finishType.isFinal)
+ {
- case NORMAL: case FINISH_EARLY:
++ iwriter.bf.close();
+ // try to save the summaries to disk
+ sstable.saveSummary(iwriter.builder, dbuilder);
+ iwriter = null;
+ dbuilder = null;
+ }
+ return sstable;
+ }
+
+ // Close the writer and return the descriptor to the new sstable and it's metadata
+ public Pair<Descriptor, StatsMetadata> close()
+ {
- return close(FinishType.NORMAL, this.repairedAt);
++ return close(FinishType.CLOSE, this.repairedAt);
+ }
+
+ private Pair<Descriptor, StatsMetadata> close(FinishType type, long repairedAt)
+ {
+ switch (type)
+ {
- case EARLY: case NORMAL:
++ case EARLY: case CLOSE: case NORMAL:
+ iwriter.close();
+ dataFile.close();
++ if (type == FinishType.CLOSE)
++ iwriter.bf.close();
+ }
+
+ // write sstable statistics
+ Map<MetadataType, MetadataComponent> metadataComponents;
+ metadataComponents = metadataCollector
+ .finalizeMetadata(partitioner.getClass().getCanonicalName(),
+ metadata.getBloomFilterFpChance(),repairedAt);
+
+ // remove the 'tmp' marker from all components
+ Descriptor descriptor = this.descriptor;
- switch (type)
++ if (type.isFinal)
+ {
- case NORMAL: case FINISH_EARLY:
+ dataFile.writeFullChecksum(descriptor);
+ writeMetadata(descriptor, metadataComponents);
+ // save the table of components
+ SSTable.appendTOC(descriptor, components);
+ descriptor = rename(descriptor, components);
+ }
+
+ return Pair.create(descriptor, (StatsMetadata) metadataComponents.get(MetadataType.STATS));
+ }
+
+ private static void writeMetadata(Descriptor desc, Map<MetadataType, MetadataComponent> components)
+ {
+ SequentialWriter out = SequentialWriter.open(new File(desc.filenameFor(Component.STATS)));
+ try
+ {
+ desc.getMetadataSerializer().serialize(components, out.stream);
+ }
+ catch (IOException e)
+ {
+ throw new FSWriteError(e, out.getPath());
+ }
+ finally
+ {
+ out.close();
+ }
+ }
+
+ public long getFilePointer()
+ {
+ return dataFile.getFilePointer();
+ }
+
+ public long getOnDiskFilePointer()
+ {
+ return dataFile.getOnDiskFilePointer();
+ }
+
+ /**
+ * Encapsulates writing the index and filter for an SSTable. The state of this object is not valid until it has been closed.
+ */
+ class IndexWriter
+ {
+ private final SequentialWriter indexFile;
+ public final SegmentedFile.Builder builder;
+ public final IndexSummaryBuilder summary;
+ public final IFilter bf;
+ private FileMark mark;
+
+ IndexWriter(long keyCount)
+ {
+ indexFile = SequentialWriter.open(new File(descriptor.filenameFor(Component.PRIMARY_INDEX)));
+ builder = SegmentedFile.getBuilder(DatabaseDescriptor.getIndexAccessMode());
+ summary = new IndexSummaryBuilder(keyCount, metadata.getMinIndexInterval(), Downsampling.BASE_SAMPLING_LEVEL);
+ bf = FilterFactory.getFilter(keyCount, metadata.getBloomFilterFpChance(), true);
+ }
+
+ // finds the last (-offset) decorated key that can be guaranteed to occur fully in the flushed portion of the index file
+ DecoratedKey getMaxReadableKey(int offset)
+ {
+ long maxIndexLength = indexFile.getLastFlushOffset();
+ return summary.getMaxReadableKey(maxIndexLength, offset);
+ }
+
+ public void append(DecoratedKey key, RowIndexEntry indexEntry)
+ {
+ bf.add(key.getKey());
+ long indexPosition = indexFile.getFilePointer();
+ try
+ {
+ ByteBufferUtil.writeWithShortLength(key.getKey(), indexFile.stream);
+ rowIndexEntrySerializer.serialize(indexEntry, indexFile.stream);
+ }
+ catch (IOException e)
+ {
+ throw new FSWriteError(e, indexFile.getPath());
+ }
+
+ if (logger.isTraceEnabled())
+ logger.trace("wrote index entry: {} at {}", indexEntry, indexPosition);
+
+ summary.maybeAddEntry(key, indexPosition);
+ builder.addPotentialBoundary(indexPosition);
+ }
+
- public void abort(boolean closeBf)
++ public void abort()
+ {
+ indexFile.abort();
- if (closeBf)
- bf.close();
++ bf.close();
+ }
+
+ /**
+ * Closes the index and bloomfilter, making the public state of this writer valid for consumption.
+ */
+ public void close()
+ {
+ if (components.contains(Component.FILTER))
+ {
+ String path = descriptor.filenameFor(Component.FILTER);
+ try
+ {
+ // bloom filter
+ FileOutputStream fos = new FileOutputStream(path);
+ DataOutputStreamAndChannel stream = new DataOutputStreamAndChannel(fos);
+ FilterFactory.serialize(bf, stream);
+ stream.flush();
+ fos.getFD().sync();
+ stream.close();
+ }
+ catch (IOException e)
+ {
+ throw new FSWriteError(e, path);
+ }
+ }
+
+ // index
+ long position = indexFile.getFilePointer();
+ indexFile.close(); // calls force
+ FileUtils.truncate(indexFile.getPath(), position);
+ }
+
+ public void mark()
+ {
+ mark = indexFile.mark();
+ }
+
+ public void resetAndTruncate()
+ {
+ // we can't un-set the bloom filter addition, but extra keys in there are harmless.
+ // we can't reset dbuilder either, but that is the last thing called in afterappend so
+ // we assume that if that worked then we won't be trying to reset.
+ indexFile.resetAndTruncate(mark);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/util/Memory.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/util/SegmentedFile.java
----------------------------------------------------------------------
diff --cc src/java/org/apache/cassandra/io/util/SegmentedFile.java
index d3b5bf2,d557b72..dbfbeac
--- a/src/java/org/apache/cassandra/io/util/SegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/SegmentedFile.java
@@@ -29,8 -29,10 +29,10 @@@ import org.apache.cassandra.config.Conf
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.FSReadError;
import org.apache.cassandra.io.compress.CompressedSequentialWriter;
-import org.apache.cassandra.io.sstable.SSTableWriter;
+import org.apache.cassandra.io.sstable.format.SSTableWriter;
import org.apache.cassandra.utils.Pair;
+ import org.apache.cassandra.utils.concurrent.RefCounted;
+ import org.apache.cassandra.utils.concurrent.SharedCloseableImpl;
/**
* Abstracts a read-only file that has been split into segments, each of which can be represented by an independent
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/service/ActiveRepairService.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/streaming/StreamSession.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
----------------------------------------------------------------------
diff --cc src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
index 43db5af,069e97f..7047c84
--- a/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
+++ b/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
@@@ -61,9 -62,9 +61,9 @@@ public class OutgoingFileMessage extend
public final FileMessageHeader header;
public final SSTableReader sstable;
- public final Ref ref;
+ public final Ref<SSTableReader> ref;
- public OutgoingFileMessage(SSTableReader sstable, Ref ref, int sequenceNumber, long estimatedKeys, List<Pair<Long, Long>> sections, long repairedAt)
+ public OutgoingFileMessage(SSTableReader sstable, Ref ref, int sequenceNumber, long estimatedKeys, List<Pair<Long, Long>> sections, long repairedAt, boolean keepSSTableLevel)
{
super(Type.FILE);
this.sstable = sstable;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
----------------------------------------------------------------------
diff --cc test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
index c823215,2e11624..3f4d9c1
--- a/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
@@@ -19,15 -19,9 +19,11 @@@ package org.apache.cassandra.io.sstable
import java.io.File;
import java.nio.ByteBuffer;
- import java.util.Arrays;
- import java.util.Collection;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
+ import java.util.*;
import com.google.common.collect.Sets;
+import org.junit.After;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.cassandra.SchemaLoader;
@@@ -224,17 -193,14 +220,16 @@@ public class SSTableRewriterTest extend
for (int i = 500; i < 1000; i++)
writer.append(StorageService.getPartitioner().decorateKey(ByteBufferUtil.bytes(i)), cf);
SSTableReader s2 = writer.openEarly(1000);
+
assertTrue(s != s2);
assertFileCounts(dir.list(), 2, 3);
+
- s.setReplacedBy(s2);
- s2.markObsolete();
- s.sharedRef().release();
- s2.sharedRef().release();
-
- writer.abort(false);
-
+ s.markObsolete();
+ s.selfRef().release();
+ s2.selfRef().release();
+ Thread.sleep(1000);
+ assertFileCounts(dir.list(), 0, 3);
+ writer.abort();
Thread.sleep(1000);
int datafiles = assertFileCounts(dir.list(), 0, 0);
assertEquals(datafiles, 0);
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
----------------------------------------------------------------------
[7/7] cassandra git commit: Merge branch 'cassandra-2.1' into trunk
Posted by be...@apache.org.
Merge branch 'cassandra-2.1' into trunk
Conflicts:
src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
src/java/org/apache/cassandra/io/sstable/format/big/BigTableWriter.java
src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
test/unit/org/apache/cassandra/utils/SerializationsTest.java
Project: http://git-wip-us.apache.org/repos/asf/cassandra/repo
Commit: http://git-wip-us.apache.org/repos/asf/cassandra/commit/02c34893
Tree: http://git-wip-us.apache.org/repos/asf/cassandra/tree/02c34893
Diff: http://git-wip-us.apache.org/repos/asf/cassandra/diff/02c34893
Branch: refs/heads/trunk
Commit: 02c348939a6c2ba391af5eb52d290b0838643cb4
Parents: 5a17ec8 61384c5
Author: Benedict Elliott Smith <be...@apache.org>
Authored: Wed Feb 11 15:23:17 2015 +0000
Committer: Benedict Elliott Smith <be...@apache.org>
Committed: Wed Feb 11 15:23:17 2015 +0000
----------------------------------------------------------------------
CHANGES.txt | 1 +
.../org/apache/cassandra/db/DataTracker.java | 6 +-
.../SizeTieredCompactionStrategy.java | 10 +-
.../io/compress/CompressionMetadata.java | 19 +-
.../cassandra/io/sstable/IndexSummary.java | 47 +-
.../io/sstable/IndexSummaryBuilder.java | 3 +-
.../io/sstable/IndexSummaryManager.java | 6 +-
.../io/sstable/SSTableDeletingTask.java | 36 +-
.../cassandra/io/sstable/SSTableLoader.java | 4 +-
.../cassandra/io/sstable/SSTableRewriter.java | 10 +-
.../io/sstable/format/SSTableReader.java | 576 ++++++++++++-------
.../io/sstable/format/SSTableWriter.java | 18 +-
.../io/sstable/format/big/BigTableWriter.java | 31 +-
.../io/util/BufferedPoolingSegmentedFile.java | 12 +-
.../io/util/BufferedSegmentedFile.java | 22 +-
.../io/util/CompressedPoolingSegmentedFile.java | 29 +-
.../io/util/CompressedSegmentedFile.java | 32 +-
.../org/apache/cassandra/io/util/Memory.java | 8 +-
.../cassandra/io/util/MmappedSegmentedFile.java | 55 +-
.../cassandra/io/util/PoolingSegmentedFile.java | 35 +-
.../apache/cassandra/io/util/SegmentedFile.java | 40 +-
.../cassandra/service/ActiveRepairService.java | 4 +-
.../cassandra/streaming/StreamSession.java | 2 +-
.../streaming/messages/OutgoingFileMessage.java | 2 +-
.../cassandra/tools/StandaloneScrubber.java | 2 +-
.../cassandra/utils/AlwaysPresentFilter.java | 5 +
.../org/apache/cassandra/utils/BloomFilter.java | 20 +-
.../org/apache/cassandra/utils/IFilter.java | 7 +-
.../cassandra/utils/Murmur3BloomFilter.java | 14 +-
.../apache/cassandra/utils/concurrent/Ref.java | 208 ++++++-
.../cassandra/utils/concurrent/RefCounted.java | 52 +-
.../utils/concurrent/RefCountedImpl.java | 132 -----
.../apache/cassandra/utils/concurrent/Refs.java | 26 +-
.../cassandra/utils/obs/OffHeapBitSet.java | 5 +
.../cassandra/db/ColumnFamilyStoreTest.java | 5 +-
.../db/compaction/AntiCompactionTest.java | 4 +-
.../SizeTieredCompactionStrategyTest.java | 30 +-
.../io/sstable/IndexSummaryManagerTest.java | 37 +-
.../cassandra/io/sstable/LegacySSTableTest.java | 3 +-
.../cassandra/io/sstable/SSTableReaderTest.java | 11 +-
.../io/sstable/SSTableRewriterTest.java | 21 +-
.../streaming/StreamTransferTaskTest.java | 2 +-
.../cassandra/tools/SSTableExportTest.java | 1 +
.../cassandra/tools/SSTableImportTest.java | 7 +
.../apache/cassandra/utils/BloomFilterTest.java | 22 +-
.../utils/concurrent/RefCountedTest.java | 12 +-
46 files changed, 986 insertions(+), 648 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/CHANGES.txt
----------------------------------------------------------------------
diff --cc CHANGES.txt
index f9faa6b,b323f18..c32a2c4
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@@ -1,63 -1,5 +1,64 @@@
+3.0
+ * Add role based access control (CASSANDRA-7653, 8650)
+ * Avoid accessing partitioner through StorageProxy (CASSANDRA-8244, 8268)
+ * Upgrade Metrics library and remove depricated metrics (CASSANDRA-5657)
+ * Serializing Row cache alternative, fully off heap (CASSANDRA-7438)
+ * Duplicate rows returned when in clause has repeated values (CASSANDRA-6707)
+ * Make CassandraException unchecked, extend RuntimeException (CASSANDRA-8560)
+ * Support direct buffer decompression for reads (CASSANDRA-8464)
+ * DirectByteBuffer compatible LZ4 methods (CASSANDRA-7039)
+ * Group sstables for anticompaction correctly (CASSANDRA-8578)
+ * Add ReadFailureException to native protocol, respond
+ immediately when replicas encounter errors while handling
+ a read request (CASSANDRA-7886)
+ * Switch CommitLogSegment from RandomAccessFile to nio (CASSANDRA-8308)
+ * Allow mixing token and partition key restrictions (CASSANDRA-7016)
+ * Support index key/value entries on map collections (CASSANDRA-8473)
+ * Modernize schema tables (CASSANDRA-8261)
+ * Support for user-defined aggregation functions (CASSANDRA-8053)
+ * Fix NPE in SelectStatement with empty IN values (CASSANDRA-8419)
+ * Refactor SelectStatement, return IN results in natural order instead
+ of IN value list order and ignore duplicate values in partition key IN restrictions (CASSANDRA-7981)
+ * Support UDTs, tuples, and collections in user-defined
+ functions (CASSANDRA-7563)
+ * Fix aggregate fn results on empty selection, result column name,
+ and cqlsh parsing (CASSANDRA-8229)
+ * Mark sstables as repaired after full repair (CASSANDRA-7586)
+ * Extend Descriptor to include a format value and refactor reader/writer
+ APIs (CASSANDRA-7443)
+ * Integrate JMH for microbenchmarks (CASSANDRA-8151)
+ * Keep sstable levels when bootstrapping (CASSANDRA-7460)
+ * Add Sigar library and perform basic OS settings check on startup (CASSANDRA-7838)
+ * Support for aggregation functions (CASSANDRA-4914)
+ * Remove cassandra-cli (CASSANDRA-7920)
+ * Accept dollar quoted strings in CQL (CASSANDRA-7769)
+ * Make assassinate a first class command (CASSANDRA-7935)
+ * Support IN clause on any partition key column (CASSANDRA-7855)
+ * Support IN clause on any clustering column (CASSANDRA-4762)
+ * Improve compaction logging (CASSANDRA-7818)
+ * Remove YamlFileNetworkTopologySnitch (CASSANDRA-7917)
+ * Do anticompaction in groups (CASSANDRA-6851)
+ * Support user-defined functions (CASSANDRA-7395, 7526, 7562, 7740, 7781, 7929,
+ 7924, 7812, 8063, 7813, 7708)
+ * Permit configurable timestamps with cassandra-stress (CASSANDRA-7416)
+ * Move sstable RandomAccessReader to nio2, which allows using the
+ FILE_SHARE_DELETE flag on Windows (CASSANDRA-4050)
+ * Remove CQL2 (CASSANDRA-5918)
+ * Add Thrift get_multi_slice call (CASSANDRA-6757)
+ * Optimize fetching multiple cells by name (CASSANDRA-6933)
+ * Allow compilation in java 8 (CASSANDRA-7028)
+ * Make incremental repair default (CASSANDRA-7250)
+ * Enable code coverage thru JaCoCo (CASSANDRA-7226)
+ * Switch external naming of 'column families' to 'tables' (CASSANDRA-4369)
+ * Shorten SSTable path (CASSANDRA-6962)
+ * Use unsafe mutations for most unit tests (CASSANDRA-6969)
+ * Fix race condition during calculation of pending ranges (CASSANDRA-7390)
+ * Fail on very large batch sizes (CASSANDRA-8011)
+ * Improve concurrency of repair (CASSANDRA-6455, 8208)
+
+
2.1.4
+ * Safer Resource Management++ (CASSANDRA-8707)
* Write partition size estimates into a system table (CASSANDRA-7688)
* cqlsh: Fix keys() and full() collection indexes in DESCRIBE output
(CASSANDRA-8154)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/db/DataTracker.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
----------------------------------------------------------------------
diff --cc src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
index 6139a5c,aaf1656..890aa0a
--- a/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
+++ b/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
@@@ -326,20 -325,17 +326,17 @@@ public class CompressionMetadat
public CompressionMetadata open(long dataLength, long compressedLength, SSTableWriter.FinishType finishType)
{
RefCountedMemory offsets;
- switch (finishType)
+ if (finishType.isFinal)
{
- case EARLY:
- offsets = this.offsets;
- break;
- case NORMAL:
- case FINISH_EARLY:
- offsets = this.offsets.copy(count * 8L);
- this.offsets.unreference();
- break;
- default:
- throw new AssertionError();
+ // we now know how many offsets we have and can resize the offsets properly
+ offsets = this.offsets.copy(count * 8L);
+ this.offsets.unreference();
+ }
+ else
+ {
+ offsets = this.offsets;
}
- return new CompressionMetadata(filePath, parameters, offsets, count * 8L, dataLength, compressedLength, Descriptor.Version.CURRENT.hasPostCompressionAdlerChecksums);
+ return new CompressionMetadata(filePath, parameters, offsets, count * 8L, dataLength, compressedLength);
}
/**
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
----------------------------------------------------------------------
[2/7] cassandra git commit: Safer Resource Management++
Posted by be...@apache.org.
Safer Resource Management++
patch by benedict; reviewed by marcus for CASSANDRA-8707
Project: http://git-wip-us.apache.org/repos/asf/cassandra/repo
Commit: http://git-wip-us.apache.org/repos/asf/cassandra/commit/61384c57
Tree: http://git-wip-us.apache.org/repos/asf/cassandra/tree/61384c57
Diff: http://git-wip-us.apache.org/repos/asf/cassandra/diff/61384c57
Branch: refs/heads/cassandra-2.1
Commit: 61384c57546da3d411630c64c4aa89d90cac98f7
Parents: 708b0ce
Author: Benedict Elliott Smith <be...@apache.org>
Authored: Wed Feb 11 14:56:23 2015 +0000
Committer: Benedict Elliott Smith <be...@apache.org>
Committed: Wed Feb 11 14:56:23 2015 +0000
----------------------------------------------------------------------
CHANGES.txt | 1 +
.../org/apache/cassandra/db/DataTracker.java | 6 +-
.../cassandra/db/compaction/CompactionTask.java | 4 -
.../SizeTieredCompactionStrategy.java | 10 +-
.../io/compress/CompressionMetadata.java | 19 +-
.../cassandra/io/sstable/IndexSummary.java | 47 +-
.../io/sstable/IndexSummaryBuilder.java | 3 +-
.../io/sstable/IndexSummaryManager.java | 6 +-
.../io/sstable/SSTableDeletingTask.java | 36 +-
.../cassandra/io/sstable/SSTableLoader.java | 4 +-
.../cassandra/io/sstable/SSTableReader.java | 590 ++++++++++++-------
.../cassandra/io/sstable/SSTableRewriter.java | 10 +-
.../cassandra/io/sstable/SSTableWriter.java | 45 +-
.../io/util/BufferedPoolingSegmentedFile.java | 12 +-
.../io/util/BufferedSegmentedFile.java | 23 +-
.../io/util/CompressedPoolingSegmentedFile.java | 29 +-
.../io/util/CompressedSegmentedFile.java | 32 +-
.../org/apache/cassandra/io/util/Memory.java | 8 +-
.../cassandra/io/util/MmappedSegmentedFile.java | 55 +-
.../cassandra/io/util/PoolingSegmentedFile.java | 35 +-
.../apache/cassandra/io/util/SegmentedFile.java | 40 +-
.../cassandra/service/ActiveRepairService.java | 4 +-
.../cassandra/streaming/StreamSession.java | 2 +-
.../streaming/messages/OutgoingFileMessage.java | 2 +-
.../cassandra/tools/StandaloneScrubber.java | 2 +-
.../cassandra/utils/AlwaysPresentFilter.java | 5 +
.../org/apache/cassandra/utils/BloomFilter.java | 20 +-
.../org/apache/cassandra/utils/IFilter.java | 7 +-
.../cassandra/utils/Murmur3BloomFilter.java | 14 +-
.../apache/cassandra/utils/concurrent/Ref.java | 208 ++++++-
.../cassandra/utils/concurrent/RefCounted.java | 52 +-
.../utils/concurrent/RefCountedImpl.java | 132 -----
.../apache/cassandra/utils/concurrent/Refs.java | 26 +-
.../cassandra/utils/obs/OffHeapBitSet.java | 5 +
.../cassandra/db/ColumnFamilyStoreTest.java | 5 +-
.../db/compaction/AntiCompactionTest.java | 6 +-
.../SizeTieredCompactionStrategyTest.java | 30 +-
.../io/sstable/IndexSummaryManagerTest.java | 37 +-
.../cassandra/io/sstable/LegacySSTableTest.java | 3 +-
.../cassandra/io/sstable/SSTableReaderTest.java | 11 +-
.../io/sstable/SSTableRewriterTest.java | 13 +-
.../streaming/StreamTransferTaskTest.java | 2 +-
.../cassandra/tools/SSTableExportTest.java | 1 +
.../cassandra/tools/SSTableImportTest.java | 7 +
.../apache/cassandra/utils/BloomFilterTest.java | 22 +-
.../cassandra/utils/SerializationsTest.java | 5 +-
.../utils/concurrent/RefCountedTest.java | 12 +-
47 files changed, 991 insertions(+), 657 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/CHANGES.txt
----------------------------------------------------------------------
diff --git a/CHANGES.txt b/CHANGES.txt
index 248139f..b323f18 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,4 +1,5 @@
2.1.4
+ * Safer Resource Management++ (CASSANDRA-8707)
* Write partition size estimates into a system table (CASSANDRA-7688)
* cqlsh: Fix keys() and full() collection indexes in DESCRIBE output
(CASSANDRA-8154)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/db/DataTracker.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/DataTracker.java b/src/java/org/apache/cassandra/db/DataTracker.java
index 5ec06bc..acf9f92 100644
--- a/src/java/org/apache/cassandra/db/DataTracker.java
+++ b/src/java/org/apache/cassandra/db/DataTracker.java
@@ -367,7 +367,7 @@ public class DataTracker
while (!view.compareAndSet(currentView, newView));
for (SSTableReader sstable : currentView.sstables)
if (!remaining.contains(sstable))
- sstable.sharedRef().release();
+ sstable.selfRef().release();
notifySSTablesChanged(remaining, Collections.<SSTableReader>emptySet(), OperationType.UNKNOWN);
}
@@ -406,7 +406,7 @@ public class DataTracker
sstable.setTrackedBy(this);
for (SSTableReader sstable : oldSSTables)
- sstable.sharedRef().release();
+ sstable.selfRef().release();
}
private void removeSSTablesFromTracker(Collection<SSTableReader> oldSSTables)
@@ -467,7 +467,7 @@ public class DataTracker
{
boolean firstToCompact = sstable.markObsolete();
assert tolerateCompacted || firstToCompact : sstable + " was already marked compacted";
- sstable.sharedRef().release();
+ sstable.selfRef().release();
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/compaction/CompactionTask.java b/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
index b6c215e..4d9b463 100644
--- a/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
+++ b/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
@@ -18,10 +18,8 @@
package org.apache.cassandra.db.compaction;
import java.io.File;
-import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -31,7 +29,6 @@ import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
@@ -40,7 +37,6 @@ import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
-import org.apache.cassandra.db.RowIndexEntry;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.db.compaction.CompactionManager.CompactionExecutorStatsCollector;
import org.apache.cassandra.io.sstable.SSTableReader;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java b/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
index fbd715c..8b1610e 100644
--- a/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
+++ b/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
@@ -144,8 +144,8 @@ public class SizeTieredCompactionStrategy extends AbstractCompactionStrategy
// calculate the total reads/sec across all sstables
double totalReads = 0.0;
for (SSTableReader sstr : sstables)
- if (sstr.readMeter != null)
- totalReads += sstr.readMeter.twoHourRate();
+ if (sstr.getReadMeter() != null)
+ totalReads += sstr.getReadMeter().twoHourRate();
// if this is a system table with no read meters or we don't have any read rates yet, just return them all
if (totalReads == 0.0)
@@ -159,11 +159,11 @@ public class SizeTieredCompactionStrategy extends AbstractCompactionStrategy
while (cutoffIndex < sstables.size())
{
SSTableReader sstable = sstables.get(cutoffIndex);
- if (sstable.readMeter == null)
+ if (sstable.getReadMeter() == null)
{
throw new AssertionError("If you're seeing this exception, please attach your logs to CASSANDRA-8238 to help us debug. "+sstable);
}
- double reads = sstable.readMeter.twoHourRate();
+ double reads = sstable.getReadMeter().twoHourRate();
if (totalColdReads + reads > maxColdReads)
break;
@@ -307,7 +307,7 @@ public class SizeTieredCompactionStrategy extends AbstractCompactionStrategy
private static double hotness(SSTableReader sstr)
{
// system tables don't have read meters, just use 0.0 for the hotness
- return sstr.readMeter == null ? 0.0 : sstr.readMeter.twoHourRate() / sstr.estimatedKeys();
+ return sstr.getReadMeter() == null ? 0.0 : sstr.getReadMeter().twoHourRate() / sstr.estimatedKeys();
}
public synchronized AbstractCompactionTask getNextBackgroundTask(int gcBefore)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java b/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
index a40048a..aaf1656 100644
--- a/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
+++ b/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
@@ -325,18 +325,15 @@ public class CompressionMetadata
public CompressionMetadata open(long dataLength, long compressedLength, SSTableWriter.FinishType finishType)
{
RefCountedMemory offsets;
- switch (finishType)
+ if (finishType.isFinal)
{
- case EARLY:
- offsets = this.offsets;
- break;
- case NORMAL:
- case FINISH_EARLY:
- offsets = this.offsets.copy(count * 8L);
- this.offsets.unreference();
- break;
- default:
- throw new AssertionError();
+ // we now know how many offsets we have and can resize the offsets properly
+ offsets = this.offsets.copy(count * 8L);
+ this.offsets.unreference();
+ }
+ else
+ {
+ offsets = this.offsets;
}
return new CompressionMetadata(filePath, parameters, offsets, count * 8L, dataLength, compressedLength, Descriptor.Version.CURRENT.hasPostCompressionAdlerChecksums);
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/IndexSummary.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/IndexSummary.java b/src/java/org/apache/cassandra/io/sstable/IndexSummary.java
index f53a7e4..0cde124 100644
--- a/src/java/org/apache/cassandra/io/sstable/IndexSummary.java
+++ b/src/java/org/apache/cassandra/io/sstable/IndexSummary.java
@@ -17,21 +17,19 @@
*/
package org.apache.cassandra.io.sstable;
-import java.io.Closeable;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import org.apache.cassandra.cache.RefCountedMemory;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.io.util.DataOutputPlus;
+import org.apache.cassandra.io.util.Memory;
import org.apache.cassandra.io.util.MemoryOutputStream;
import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.concurrent.WrappedSharedCloseable;
import static org.apache.cassandra.io.sstable.Downsampling.BASE_SAMPLING_LEVEL;
@@ -45,10 +43,8 @@ import static org.apache.cassandra.io.sstable.Downsampling.BASE_SAMPLING_LEVEL;
* (This is necessary because keys can have different lengths.)
* 2. A sequence of (DecoratedKey, position) pairs, where position is the offset into the actual index file.
*/
-public class IndexSummary implements Closeable
+public class IndexSummary extends WrappedSharedCloseable
{
- private static final Logger logger = LoggerFactory.getLogger(IndexSummary.class);
-
public static final IndexSummarySerializer serializer = new IndexSummarySerializer();
/**
@@ -60,7 +56,7 @@ public class IndexSummary implements Closeable
private final IPartitioner partitioner;
private final int summarySize;
private final int sizeAtFullSampling;
- private final RefCountedMemory bytes;
+ private final Memory bytes;
/**
* A value between 1 and BASE_SAMPLING_LEVEL that represents how many of the original
@@ -70,17 +66,29 @@ public class IndexSummary implements Closeable
*/
private final int samplingLevel;
- public IndexSummary(IPartitioner partitioner, RefCountedMemory memory, int summarySize, int sizeAtFullSampling,
+ public IndexSummary(IPartitioner partitioner, Memory bytes, int summarySize, int sizeAtFullSampling,
int minIndexInterval, int samplingLevel)
{
+ super(bytes);
this.partitioner = partitioner;
this.minIndexInterval = minIndexInterval;
this.summarySize = summarySize;
this.sizeAtFullSampling = sizeAtFullSampling;
- this.bytes = memory;
+ this.bytes = bytes;
this.samplingLevel = samplingLevel;
}
+ private IndexSummary(IndexSummary copy)
+ {
+ super(copy);
+ this.partitioner = copy.partitioner;
+ this.minIndexInterval = copy.minIndexInterval;
+ this.summarySize = copy.summarySize;
+ this.sizeAtFullSampling = copy.sizeAtFullSampling;
+ this.bytes = copy.bytes;
+ this.samplingLevel = copy.samplingLevel;
+ }
+
// binary search is notoriously more difficult to get right than it looks; this is lifted from
// Harmony's Collections implementation
public int binarySearch(RowPosition key)
@@ -137,7 +145,7 @@ public class IndexSummary implements Closeable
long start = getPositionInSummary(index);
long end = calculateEnd(index);
byte[] entry = new byte[(int)(end - start)];
- bytes.getBytes(start, entry, 0, (int)(end - start));
+ bytes.getBytes(start, entry, 0, (int) (end - start));
return entry;
}
@@ -206,6 +214,11 @@ public class IndexSummary implements Closeable
return Downsampling.getEffectiveIndexIntervalAfterIndex(index, samplingLevel, minIndexInterval);
}
+ public IndexSummary sharedCopy()
+ {
+ return new IndexSummary(this);
+ }
+
public static class IndexSummarySerializer
{
public void serialize(IndexSummary t, DataOutputPlus out, boolean withSamplingLevel) throws IOException
@@ -256,16 +269,4 @@ public class IndexSummary implements Closeable
return new IndexSummary(partitioner, memory, summarySize, fullSamplingSummarySize, minIndexInterval, samplingLevel);
}
}
-
- @Override
- public void close()
- {
- bytes.unreference();
- }
-
- public IndexSummary readOnlyClone()
- {
- bytes.reference();
- return this;
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java b/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
index 8e9cc30..df326d7 100644
--- a/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
+++ b/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
@@ -28,6 +28,7 @@ import org.apache.cassandra.cache.RefCountedMemory;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.io.util.Memory;
import static org.apache.cassandra.io.sstable.Downsampling.BASE_SAMPLING_LEVEL;
import static org.apache.cassandra.io.sstable.SSTable.getMinimalKey;
@@ -148,7 +149,7 @@ public class IndexSummaryBuilder
// first we write out the position in the *summary* for each key in the summary,
// then we write out (key, actual index position) pairs
- RefCountedMemory memory = new RefCountedMemory(offheapSize + (length * 4));
+ Memory memory = Memory.allocate(offheapSize + (length * 4));
int idxPosition = 0;
int keyPosition = length * 4;
for (int i = 0; i < length; i++)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java b/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
index 65b25a4..4144c32 100644
--- a/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
+++ b/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
@@ -266,9 +266,9 @@ public class IndexSummaryManager implements IndexSummaryManagerMBean
double totalReadsPerSec = 0.0;
for (SSTableReader sstable : nonCompacting)
{
- if (sstable.readMeter != null)
+ if (sstable.getReadMeter() != null)
{
- Double readRate = sstable.readMeter.fifteenMinuteRate();
+ Double readRate = sstable.getReadMeter().fifteenMinuteRate();
totalReadsPerSec += readRate;
readRates.put(sstable, readRate);
}
@@ -314,7 +314,7 @@ public class IndexSummaryManager implements IndexSummaryManagerMBean
int minIndexInterval = sstable.metadata.getMinIndexInterval();
int maxIndexInterval = sstable.metadata.getMaxIndexInterval();
- double readsPerSec = sstable.readMeter == null ? 0.0 : sstable.readMeter.fifteenMinuteRate();
+ double readsPerSec = sstable.getReadMeter() == null ? 0.0 : sstable.getReadMeter().fifteenMinuteRate();
long idealSpace = Math.round(remainingSpace * (readsPerSec / totalReadsPerSec));
// figure out how many entries our idealSpace would buy us, and pick a new sampling level based on that
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java b/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
index fb1cbb3..3da6906 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
@@ -40,31 +40,42 @@ public class SSTableDeletingTask implements Runnable
// and delete will fail (on Windows) until it is (we only force the unmapping on SUN VMs).
// Additionally, we need to make sure to delete the data file first, so on restart the others
// will be recognized as GCable.
- private static final Set<SSTableDeletingTask> failedTasks = new CopyOnWriteArraySet<SSTableDeletingTask>();
+ private static final Set<SSTableDeletingTask> failedTasks = new CopyOnWriteArraySet<>();
private final SSTableReader referent;
private final Descriptor desc;
private final Set<Component> components;
private DataTracker tracker;
- public SSTableDeletingTask(SSTableReader referent)
+ /**
+ * realDescriptor is the actual descriptor for the sstable, the descriptor inside
+ * referent can be 'faked' as FINAL for early opened files. We need the real one
+ * to be able to remove the files.
+ */
+ public SSTableDeletingTask(Descriptor realDescriptor, SSTableReader referent)
{
this.referent = referent;
- if (referent.openReason == SSTableReader.OpenReason.EARLY)
+ this.desc = realDescriptor;
+ switch (desc.type)
{
- this.desc = referent.descriptor.asType(Descriptor.Type.TEMPLINK);
- this.components = Sets.newHashSet(Component.DATA, Component.PRIMARY_INDEX);
- }
- else
- {
- this.desc = referent.descriptor;
- this.components = referent.components;
+ case FINAL:
+ this.components = referent.components;
+ break;
+ case TEMPLINK:
+ this.components = Sets.newHashSet(Component.DATA, Component.PRIMARY_INDEX);
+ break;
+ default:
+ throw new IllegalStateException();
}
}
public void setTracker(DataTracker tracker)
{
- this.tracker = tracker;
+ // the tracker is used only to notify listeners of deletion of the sstable;
+ // since deletion of a non-final file is not really deletion of the sstable,
+ // we don't want to notify the listeners in this event
+ if (desc.type == Descriptor.Type.FINAL)
+ this.tracker = tracker;
}
public void schedule()
@@ -79,9 +90,6 @@ public class SSTableDeletingTask implements Runnable
if (tracker != null)
tracker.notifyDeleting(referent);
- if (referent.readMeter != null)
- SystemKeyspace.clearSSTableReadMeter(referent.getKeyspaceName(), referent.getColumnFamilyName(), referent.descriptor.generation);
-
// If we can't successfully delete the DATA component, set the task to be retried later: see above
File datafile = new File(desc.filenameFor(Component.DATA));
if (!datafile.delete())
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java b/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
index 06f71d8..cd23ae2 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
@@ -209,8 +209,8 @@ public class SSTableLoader implements StreamEventHandler
{
for (SSTableReader sstable : sstables)
{
- sstable.sharedRef().release();
- assert sstable.sharedRef().globalCount() == 0;
+ sstable.selfRef().release();
+ assert sstable.selfRef().globalCount() == 0;
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableReader.java b/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
index f34939a..a28eb44 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
@@ -36,11 +36,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
+import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
@@ -118,10 +114,62 @@ import org.apache.cassandra.utils.concurrent.RefCounted;
import static org.apache.cassandra.db.Directories.SECONDARY_INDEX_NAME_SEPARATOR;
/**
- * SSTableReaders are open()ed by Keyspace.onStart; after that they are created by SSTableWriter.renameAndOpen.
- * Do not re-call open() on existing SSTable files; use the references kept by ColumnFamilyStore post-start instead.
+ * An SSTableReader can be constructed in a number of places, but typically is either
+ * read from disk at startup, or constructed from a flushed memtable, or after compaction
+ * to replace some existing sstables. However once created, an sstablereader may also be modified.
+ *
+ * A reader's OpenReason describes its current stage in its lifecycle, as follows:
+ *
+ * NORMAL
+ * From: None => Reader has been read from disk, either at startup or from a flushed memtable
+ * EARLY => Reader is the final result of a compaction
+ * MOVED_START => Reader WAS being compacted, but this failed and it has been restored to NORMAL status
+ *
+ * EARLY
+ * From: None => Reader is a compaction replacement that is either incomplete and has been opened
+ * to represent its partial result status, or has been finished but the compaction
+ * it is a part of has not yet completed fully
+ * EARLY => Same as from None, only it is not the first time it has been
+ *
+ * MOVED_START
+ * From: NORMAL => Reader is being compacted. This compaction has not finished, but the compaction result
+ * is either partially or fully opened, to either partially or fully replace this reader.
+ * This reader's start key has been updated to represent this, so that reads only hit
+ * one or the other reader.
+ *
+ * METADATA_CHANGE
+ * From: NORMAL => Reader has seen low traffic and the amount of memory available for index summaries is
+ * constrained, so its index summary has been downsampled.
+ * METADATA_CHANGE => Same
+ *
+ * Note that in parallel to this, there are two different Descriptor types; TMPLINK and FINAL; the latter corresponds
+ * to NORMAL state readers and all readers that replace a NORMAL one. TMPLINK is used for EARLY state readers and
+ * no others.
+ *
+ * When a reader is being compacted, if the result is large its replacement may be opened as EARLY before compaction
+ * completes in order to present the result to consumers earlier. In this case the reader will itself be changed to
+ * a MOVED_START state, where its start no longer represents its on-disk minimum key. This is to permit reads to be
+ * directed to only one reader when the two represent the same data. The EARLY file can represent a compaction result
+ * that is either partially complete and still in-progress, or a complete and immutable sstable that is part of a larger
+ * macro compaction action that has not yet fully completed.
+ *
+ * Currently ALL compaction results at least briefly go through an EARLY open state prior to completion, regardless
+ * of if early opening is enabled.
+ *
+ * Since a reader can be created multiple times over the same shared underlying resources, and the exact resources
+ * it shares between each instance differ subtly, we track the lifetime of any underlying resource with its own
+ * reference count, which each instance takes a Ref to. Each instance then tracks references to itself, and once these
+ * all expire it releases its Refs to these underlying resources.
+ *
+ * There is some shared cleanup behaviour needed only once all sstablereaders in a certain stage of their lifecycle
+ * (i.e. EARLY or NORMAL opening), and some that must only occur once all readers of any kind over a single logical
+ * sstable have expired. These are managed by the TypeTidy and GlobalTidy classes at the bottom, and are effectively
+ * managed as another resource each instance tracks its own Ref instance to, to ensure all of these resources are
+ * cleaned up safely and can be debugged otherwise.
+ *
+ * TODO: fill in details about DataTracker and lifecycle interactions for tools, and for compaction strategies
*/
-public class SSTableReader extends SSTable implements RefCounted
+public class SSTableReader extends SSTable implements RefCounted<SSTableReader>
{
private static final Logger logger = LoggerFactory.getLogger(SSTableReader.class);
@@ -166,7 +214,8 @@ public class SSTableReader extends SSTable implements RefCounted
{
NORMAL,
EARLY,
- METADATA_CHANGE
+ METADATA_CHANGE,
+ MOVED_START
}
public final OpenReason openReason;
@@ -174,7 +223,6 @@ public class SSTableReader extends SSTable implements RefCounted
// indexfile and datafile: might be null before a call to load()
private SegmentedFile ifile;
private SegmentedFile dfile;
-
private IndexSummary indexSummary;
private IFilter bf;
@@ -184,8 +232,7 @@ public class SSTableReader extends SSTable implements RefCounted
// technically isCompacted is not necessary since it should never be unreferenced unless it is also compacted,
// but it seems like a good extra layer of protection against reference counting bugs to not delete data based on that alone
- private final AtomicBoolean isCompacted = new AtomicBoolean(false);
- private final AtomicBoolean isSuspect = new AtomicBoolean(false);
+ private AtomicBoolean isSuspect = new AtomicBoolean(false);
// not final since we need to be able to change level on a file.
private volatile StatsMetadata sstableMetadata;
@@ -193,12 +240,10 @@ public class SSTableReader extends SSTable implements RefCounted
private final AtomicLong keyCacheHit = new AtomicLong(0);
private final AtomicLong keyCacheRequest = new AtomicLong(0);
- private final Tidier tidy = new Tidier();
- private final RefCounted refCounted = RefCounted.Impl.get(tidy);
+ private final InstanceTidier tidy = new InstanceTidier(descriptor, metadata);
+ private final Ref<SSTableReader> selfRef = new Ref<>(this, tidy);
- @VisibleForTesting
- public RestorableMeter readMeter;
- private ScheduledFuture readMeterSyncFuture;
+ private RestorableMeter readMeter;
/**
* Calculate approximate key count.
@@ -399,7 +444,7 @@ public class SSTableReader extends SSTable implements RefCounted
sstable.ifile = ibuilder.complete(sstable.descriptor.filenameFor(Component.PRIMARY_INDEX));
sstable.dfile = dbuilder.complete(sstable.descriptor.filenameFor(Component.DATA));
sstable.bf = FilterFactory.AlwaysPresent;
- sstable.tidy.setup(sstable);
+ sstable.setup();
return sstable;
}
@@ -443,13 +488,13 @@ public class SSTableReader extends SSTable implements RefCounted
sstable.load(validationMetadata);
logger.debug("INDEX LOAD TIME for {}: {} ms.", descriptor, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
+ sstable.setup();
if (validate)
sstable.validate();
if (sstable.getKeyCache() != null)
logger.debug("key cache contains {}/{} keys", sstable.getKeyCache().size(), sstable.getKeyCache().getCapacity());
- sstable.tidy.setup(sstable);
return sstable;
}
@@ -545,32 +590,6 @@ public class SSTableReader extends SSTable implements RefCounted
this.sstableMetadata = sstableMetadata;
this.maxDataAge = maxDataAge;
this.openReason = openReason;
-
- tidy.deletingTask = new SSTableDeletingTask(this);
-
- // Don't track read rates for tables in the system keyspace and don't bother trying to load or persist
- // the read meter when in client mode. Also don't track reads for special operations (like early open)
- // this is to avoid overflowing the executor queue (see CASSANDRA-8066)
- if (Keyspace.SYSTEM_KS.equals(desc.ksname) || Config.isClientMode() || openReason != OpenReason.NORMAL)
- {
- readMeter = null;
- readMeterSyncFuture = null;
- return;
- }
-
- readMeter = SystemKeyspace.getSSTableReadMeter(desc.ksname, desc.cfname, desc.generation);
- // sync the average read rate to system.sstable_activity every five minutes, starting one minute from now
- readMeterSyncFuture = syncExecutor.scheduleAtFixedRate(new Runnable()
- {
- public void run()
- {
- if (!isCompacted.get())
- {
- meterSyncThrottle.acquire();
- SystemKeyspace.persistSSTableReadMeter(desc.ksname, desc.cfname, desc.generation, readMeter);
- }
- }
- }, 1, 5, TimeUnit.MINUTES);
}
private SSTableReader(Descriptor desc,
@@ -586,12 +605,11 @@ public class SSTableReader extends SSTable implements RefCounted
OpenReason openReason)
{
this(desc, components, metadata, partitioner, maxDataAge, sstableMetadata, openReason);
-
this.ifile = ifile;
this.dfile = dfile;
this.indexSummary = indexSummary;
this.bf = bloomFilter;
- tidy.setup(this);
+ this.setup();
}
public static long getTotalBytes(Iterable<SSTableReader> sstables)
@@ -626,7 +644,7 @@ public class SSTableReader extends SSTable implements RefCounted
public void setTrackedBy(DataTracker tracker)
{
- tidy.deletingTask.setTracker(tracker);
+ tidy.type.deletingTask.setTracker(tracker);
// under normal operation we can do this at any time, but SSTR is also used outside C* proper,
// e.g. by BulkLoader, which does not initialize the cache. As a kludge, we set up the cache
// here when we know we're being wired into the rest of the server infrastructure.
@@ -698,7 +716,6 @@ public class SSTableReader extends SSTable implements RefCounted
dfile = dbuilder.complete(descriptor.filenameFor(Component.DATA));
if (saveSummaryIfCreated && (recreateBloomFilter || !summaryLoaded)) // save summary information to disk
saveSummary(ibuilder, dbuilder);
- tidy.setup(this);
}
/**
@@ -792,6 +809,8 @@ public class SSTableReader extends SSTable implements RefCounted
}
catch (IOException e)
{
+ if (indexSummary != null)
+ indexSummary.close();
logger.debug("Cannot deserialize SSTable Summary File {}: {}", summariesFile.getPath(), e.getMessage());
// corrupted; delete it and fall back to creating a new summary
FileUtils.closeQuietly(iStream);
@@ -850,20 +869,21 @@ public class SSTableReader extends SSTable implements RefCounted
public void setReplacedBy(SSTableReader replacement)
{
- synchronized (tidy.replaceLock)
+ synchronized (tidy.global)
{
- assert tidy.replacedBy == null;
- tidy.replacedBy = replacement;
- replacement.tidy.replaces = this;
- replacement.tidy.replaceLock = tidy.replaceLock;
+ assert replacement != null;
+ assert !tidy.isReplaced;
+ assert tidy.global.live == this;
+ tidy.isReplaced = true;
+ tidy.global.live = replacement;
}
}
public SSTableReader cloneWithNewStart(DecoratedKey newStart, final Runnable runOnClose)
{
- synchronized (tidy.replaceLock)
+ synchronized (tidy.global)
{
- assert tidy.replacedBy == null;
+ assert openReason != OpenReason.EARLY;
if (newStart.compareTo(this.first) > 0)
{
@@ -895,10 +915,9 @@ public class SSTableReader extends SSTable implements RefCounted
}
}
- SSTableReader replacement = new SSTableReader(descriptor, components, metadata, partitioner, ifile, dfile, indexSummary.readOnlyClone(), bf, maxDataAge, sstableMetadata,
- openReason == OpenReason.EARLY ? openReason : OpenReason.METADATA_CHANGE);
- replacement.readMeterSyncFuture = this.readMeterSyncFuture;
- replacement.readMeter = this.readMeter;
+ SSTableReader replacement = new SSTableReader(descriptor, components, metadata, partitioner, ifile.sharedCopy(),
+ dfile.sharedCopy(), indexSummary.sharedCopy(), bf.sharedCopy(),
+ maxDataAge, sstableMetadata, OpenReason.MOVED_START);
replacement.first = this.last.compareTo(newStart) > 0 ? newStart : this.last;
replacement.last = this.last;
setReplacedBy(replacement);
@@ -916,9 +935,9 @@ public class SSTableReader extends SSTable implements RefCounted
*/
public SSTableReader cloneWithNewSummarySamplingLevel(ColumnFamilyStore parent, int samplingLevel) throws IOException
{
- synchronized (tidy.replaceLock)
+ synchronized (tidy.global)
{
- assert tidy.replacedBy == null;
+ assert openReason != OpenReason.EARLY;
int minIndexInterval = metadata.getMinIndexInterval();
int maxIndexInterval = metadata.getMaxIndexInterval();
@@ -957,10 +976,9 @@ public class SSTableReader extends SSTable implements RefCounted
StorageMetrics.load.inc(newSize - oldSize);
parent.metric.liveDiskSpaceUsed.inc(newSize - oldSize);
- SSTableReader replacement = new SSTableReader(descriptor, components, metadata, partitioner, ifile, dfile, newSummary, bf, maxDataAge, sstableMetadata,
- openReason == OpenReason.EARLY ? openReason : OpenReason.METADATA_CHANGE);
- replacement.readMeterSyncFuture = this.readMeterSyncFuture;
- replacement.readMeter = this.readMeter;
+ SSTableReader replacement = new SSTableReader(descriptor, components, metadata, partitioner, ifile.sharedCopy(),
+ dfile.sharedCopy(), newSummary, bf.sharedCopy(), maxDataAge,
+ sstableMetadata, OpenReason.METADATA_CHANGE);
replacement.first = this.first;
replacement.last = this.last;
setReplacedBy(replacement);
@@ -992,6 +1010,11 @@ public class SSTableReader extends SSTable implements RefCounted
}
}
+ public RestorableMeter getReadMeter()
+ {
+ return readMeter;
+ }
+
public int getIndexSummarySamplingLevel()
{
return indexSummary.getSamplingLevel();
@@ -1014,14 +1037,17 @@ public class SSTableReader extends SSTable implements RefCounted
public void releaseSummary() throws IOException
{
- indexSummary.close();
+ tidy.releaseSummary();
indexSummary = null;
}
private void validate()
{
if (this.first.compareTo(this.last) > 0)
+ {
+ selfRef().release();
throw new IllegalStateException(String.format("SSTable first key %s > last key %s", this.first, this.last));
+ }
}
/**
@@ -1567,16 +1593,16 @@ public class SSTableReader extends SSTable implements RefCounted
if (logger.isDebugEnabled())
logger.debug("Marking {} compacted", getFilename());
- synchronized (tidy.replaceLock)
+ synchronized (tidy.global)
{
- assert tidy.replacedBy == null : getFilename();
+ assert !tidy.isReplaced;
}
- return !isCompacted.getAndSet(true);
+ return !tidy.global.isCompacted.getAndSet(true);
}
public boolean isMarkedCompacted()
{
- return isCompacted.get();
+ return tidy.global.isCompacted.get();
}
public void markSuspect()
@@ -1673,16 +1699,7 @@ public class SSTableReader extends SSTable implements RefCounted
public SSTableReader getCurrentReplacement()
{
- synchronized (tidy.replaceLock)
- {
- SSTableReader cur = this, next = tidy.replacedBy;
- while (next != null)
- {
- cur = next;
- next = next.tidy.replacedBy;
- }
- return cur;
- }
+ return tidy.global.live;
}
/**
@@ -1882,199 +1899,314 @@ public class SSTableReader extends SSTable implements RefCounted
}
}
- public Ref tryRef()
+ public Ref<SSTableReader> tryRef()
{
- return refCounted.tryRef();
+ return selfRef.tryRef();
}
- public Ref sharedRef()
+ public Ref<SSTableReader> selfRef()
{
- return refCounted.sharedRef();
+ return selfRef;
}
- private static final class Tidier implements Tidy
+ public Ref<SSTableReader> ref()
{
- private String name;
- private CFMetaData metadata;
- // indexfile and datafile: might be null before a call to load()
- private SegmentedFile ifile;
- private SegmentedFile dfile;
+ return selfRef.ref();
+ }
- private IndexSummary indexSummary;
- private IFilter bf;
+ void setup()
+ {
+ tidy.setup(this);
+ this.readMeter = tidy.global.readMeter;
+ }
+
+ @VisibleForTesting
+ public void overrideReadMeter(RestorableMeter readMeter)
+ {
+ this.readMeter = tidy.global.readMeter = readMeter;
+ }
- private AtomicBoolean isCompacted;
+ /**
+ * One instance per SSTableReader we create. This references the type-shared tidy, which in turn references
+ * the globally shared tidy, i.e.
+ *
+ * InstanceTidier => DescriptorTypeTitdy => GlobalTidy
+ *
+ * We can create many InstanceTidiers (one for every time we reopen an sstable with MOVED_START for example), but there can only be
+ * two DescriptorTypeTidy (FINAL and TEMPLINK) and only one GlobalTidy for one single logical sstable.
+ *
+ * When the InstanceTidier cleansup, it releases its reference to its DescriptorTypeTidy; when all InstanceTidiers
+ * for that type have run, the DescriptorTypeTidy cleansup. DescriptorTypeTidy behaves in the same way towards GlobalTidy.
+ *
+ * For ease, we stash a direct reference to both our type-shared and global tidier
+ */
+ private static final class InstanceTidier implements Tidy
+ {
+ private final Descriptor descriptor;
+ private final CFMetaData metadata;
+ private IFilter bf;
+ private IndexSummary summary;
- /**
- * To support replacing this sstablereader with another object that represents that same underlying sstable, but with different associated resources,
- * we build a linked-list chain of replacement, which we synchronise using a shared object to make maintenance of the list across multiple threads simple.
- * On close we check if any of the closeable resources differ between any chains either side of us; any that are in neither of the adjacent links (if any) are closed.
- * Once we've made this decision we remove ourselves from the linked list, so that anybody behind/ahead will compare against only other still opened resources.
- */
- private Object replaceLock = new Object();
- private SSTableReader replacedBy;
- private SSTableReader replaces;
- private SSTableDeletingTask deletingTask;
+ private SegmentedFile dfile;
+ private SegmentedFile ifile;
private Runnable runOnClose;
+ private boolean isReplaced = false;
+
+ // a reference to our shared per-Descriptor.Type tidy instance, that
+ // we will release when we are ourselves released
+ private Ref<DescriptorTypeTidy> typeRef;
+
+ // a convenience stashing of the shared per-descriptor-type tidy instance itself
+ // and the per-logical-sstable globally shared state that it is linked to
+ private DescriptorTypeTidy type;
+ private GlobalTidy global;
+
+ private boolean setup;
+
+ void setup(SSTableReader reader)
+ {
+ this.setup = true;
+ this.bf = reader.bf;
+ this.summary = reader.indexSummary;
+ this.dfile = reader.dfile;
+ this.ifile = reader.ifile;
+ // get a new reference to the shared descriptor-type tidy
+ this.typeRef = DescriptorTypeTidy.get(reader);
+ this.type = typeRef.get();
+ this.global = type.globalRef.get();
+ }
- @VisibleForTesting
- public RestorableMeter readMeter;
- private volatile ScheduledFuture readMeterSyncFuture;
+ InstanceTidier(Descriptor descriptor, CFMetaData metadata)
+ {
+ this.descriptor = descriptor;
+ this.metadata = metadata;
+ }
- private void setup(SSTableReader reader)
+ public void tidy()
{
- name = reader.toString();
- metadata = reader.metadata;
- ifile = reader.ifile;
- dfile = reader.dfile;
- indexSummary = reader.indexSummary;
- bf = reader.bf;
- isCompacted = reader.isCompacted;
- readMeterSyncFuture = reader.readMeterSyncFuture;
+ // don't try to cleanup if the sstablereader was never fully constructed
+ if (!setup)
+ return;
+
+ final ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(metadata.cfId);
+ final OpOrder.Barrier barrier;
+ if (cfs != null)
+ {
+ barrier = cfs.readOrdering.newBarrier();
+ barrier.issue();
+ }
+ else
+ barrier = null;
+
+ ScheduledExecutors.nonPeriodicTasks.execute(new Runnable()
+ {
+ public void run()
+ {
+ if (barrier != null)
+ barrier.await();
+ bf.close();
+ dfile.close();
+ ifile.close();
+ if (summary != null)
+ summary.close();
+ if (runOnClose != null)
+ runOnClose.run();
+ typeRef.release();
+ }
+ });
}
public String name()
{
- return name;
+ return descriptor.toString();
}
- private void dropPageCache()
+ void releaseSummary()
{
- dropPageCache(dfile.path);
- dropPageCache(ifile.path);
+ summary.close();
+ assert summary.isCleanedUp();
+ summary = null;
}
+ }
+
+ /**
+ * One shared between all instances of a given Descriptor.Type.
+ * Performs only two things: the deletion of the sstables for the type,
+ * if necessary; and the shared reference to the globally shared state.
+ *
+ * All InstanceTidiers, on setup(), ask the static get() method for their shared state,
+ * and stash a reference to it to be released when they are. Once all such references are
+ * released, the shared tidy will be performed.
+ */
+ static final class DescriptorTypeTidy implements Tidy
+ {
+ // keyed by REAL descriptor (TMPLINK/FINAL), mapping to the shared DescriptorTypeTidy for that descriptor
+ static final ConcurrentMap<Descriptor, Ref<DescriptorTypeTidy>> lookup = new ConcurrentHashMap<>();
- private void dropPageCache(String filePath)
+ private final Descriptor desc;
+ private final Ref<GlobalTidy> globalRef;
+ private final SSTableDeletingTask deletingTask;
+
+ DescriptorTypeTidy(Descriptor desc, SSTableReader sstable)
{
- RandomAccessFile file = null;
+ this.desc = desc;
+ this.deletingTask = new SSTableDeletingTask(desc, sstable);
+ // get a new reference to the shared global tidy
+ this.globalRef = GlobalTidy.get(sstable);
+ }
- try
+ public void tidy()
+ {
+ lookup.remove(desc);
+ boolean isCompacted = globalRef.get().isCompacted.get();
+ globalRef.release();
+ switch (desc.type)
{
- file = new RandomAccessFile(filePath, "r");
+ case FINAL:
+ if (isCompacted)
+ deletingTask.run();
+ break;
+ case TEMPLINK:
+ deletingTask.run();
+ break;
+ default:
+ throw new IllegalStateException();
+ }
+ }
- int fd = CLibrary.getfd(file.getFD());
+ public String name()
+ {
+ return desc.toString();
+ }
- if (fd > 0)
- {
- if (logger.isDebugEnabled())
- logger.debug(String.format("Dropping page cache of file %s.", filePath));
+ // get a new reference to the shared DescriptorTypeTidy for this sstable
+ public static Ref<DescriptorTypeTidy> get(SSTableReader sstable)
+ {
+ Descriptor desc = sstable.descriptor;
+ if (sstable.openReason == OpenReason.EARLY)
+ desc = desc.asType(Descriptor.Type.TEMPLINK);
+ Ref<DescriptorTypeTidy> refc = lookup.get(desc);
+ if (refc != null)
+ return refc.ref();
+ final DescriptorTypeTidy tidy = new DescriptorTypeTidy(desc, sstable);
+ refc = new Ref<>(tidy, tidy);
+ Ref<?> ex = lookup.putIfAbsent(desc, refc);
+ assert ex == null;
+ return refc;
+ }
+ }
- CLibrary.trySkipCache(fd, 0, 0);
- }
- }
- catch (IOException e)
+ /**
+ * One instance per logical sstable. This both tracks shared cleanup and some shared state related
+ * to the sstable's lifecycle. All DescriptorTypeTidy instances, on construction, obtain a reference to us
+ * via our static get(). There should only ever be at most two such references extant at any one time,
+ * since only TMPLINK and FINAL type descriptors should be open as readers. When all files of both
+ * kinds have been released, this shared tidy will be performed.
+ */
+ static final class GlobalTidy implements Tidy
+ {
+ // keyed by FINAL descriptor, mapping to the shared GlobalTidy for that descriptor
+ static final ConcurrentMap<Descriptor, Ref<GlobalTidy>> lookup = new ConcurrentHashMap<>();
+
+ private final Descriptor desc;
+ // a single convenience property for getting the most recent version of an sstable, not related to tidying
+ private SSTableReader live;
+ // the readMeter that is shared between all instances of the sstable, and can be overridden in all of them
+ // at once also, for testing purposes
+ private RestorableMeter readMeter;
+ // the scheduled persistence of the readMeter, that we will cancel once all instances of this logical
+ // sstable have been released
+ private final ScheduledFuture readMeterSyncFuture;
+ // shared state managing if the logical sstable has been compacted; this is used in cleanup both here
+ // and in the FINAL type tidier
+ private final AtomicBoolean isCompacted;
+
+ GlobalTidy(final SSTableReader reader)
+ {
+ this.desc = reader.descriptor;
+ this.isCompacted = new AtomicBoolean();
+ this.live = reader;
+ // Don't track read rates for tables in the system keyspace and don't bother trying to load or persist
+ // the read meter when in client mode.
+ if (Keyspace.SYSTEM_KS.equals(desc.ksname) || Config.isClientMode())
{
- // we don't care if cache cleanup fails
+ readMeter = null;
+ readMeterSyncFuture = null;
+ return;
}
- finally
+
+ readMeter = SystemKeyspace.getSSTableReadMeter(desc.ksname, desc.cfname, desc.generation);
+ // sync the average read rate to system.sstable_activity every five minutes, starting one minute from now
+ readMeterSyncFuture = syncExecutor.scheduleAtFixedRate(new Runnable()
{
- FileUtils.closeQuietly(file);
- }
+ public void run()
+ {
+ if (!isCompacted.get())
+ {
+ meterSyncThrottle.acquire();
+ SystemKeyspace.persistSSTableReadMeter(desc.ksname, desc.cfname, desc.generation, readMeter);
+ }
+ }
+ }, 1, 5, TimeUnit.MINUTES);
}
public void tidy()
{
+ lookup.remove(desc);
if (readMeterSyncFuture != null)
- readMeterSyncFuture.cancel(false);
+ readMeterSyncFuture.cancel(true);
+ if (isCompacted.get())
+ SystemKeyspace.clearSSTableReadMeter(desc.ksname, desc.cfname, desc.generation);
+ // don't ideally want to dropPageCache for the file until all instances have been released
+ dropPageCache(desc.filenameFor(Component.DATA));
+ dropPageCache(desc.filenameFor(Component.PRIMARY_INDEX));
+ }
- synchronized (replaceLock)
- {
- boolean closeBf = true, closeSummary = true, closeFiles = true, deleteFiles = isCompacted.get();
+ public String name()
+ {
+ return desc.toString();
+ }
- if (replacedBy != null)
- {
- closeBf = replacedBy.bf != bf;
- closeSummary = replacedBy.indexSummary != indexSummary;
- closeFiles = replacedBy.dfile != dfile;
- // if the replacement sstablereader uses a different path, clean up our paths
- deleteFiles = !dfile.path.equals(replacedBy.dfile.path);
- }
+ // get a new reference to the shared GlobalTidy for this sstable
+ public static Ref<GlobalTidy> get(SSTableReader sstable)
+ {
+ Descriptor descriptor = sstable.descriptor;
+ Ref<GlobalTidy> refc = lookup.get(descriptor);
+ if (refc != null)
+ return refc.ref();
+ final GlobalTidy tidy = new GlobalTidy(sstable);
+ refc = new Ref<>(tidy, tidy);
+ Ref<?> ex = lookup.putIfAbsent(descriptor, refc);
+ assert ex == null;
+ return refc;
+ }
+ }
- if (replaces != null)
- {
- closeBf &= replaces.bf != bf;
- closeSummary &= replaces.indexSummary != indexSummary;
- closeFiles &= replaces.dfile != dfile;
- deleteFiles &= !dfile.path.equals(replaces.dfile.path);
- }
+ private static void dropPageCache(String filePath)
+ {
+ RandomAccessFile file = null;
- boolean deleteAll = false;
- if (isCompacted.get())
- {
- assert replacedBy == null;
- if (replaces != null && !deleteFiles)
- {
- replaces.tidy.replacedBy = null;
- replaces.tidy.deletingTask = deletingTask;
- replaces.markObsolete();
- }
- else
- {
- deleteAll = true;
- }
- }
- else
- {
- closeSummary &= indexSummary != null;
- if (replaces != null)
- replaces.tidy.replacedBy = replacedBy;
- if (replacedBy != null)
- replacedBy.tidy.replaces = replaces;
- }
+ try
+ {
+ file = new RandomAccessFile(filePath, "r");
- scheduleTidy(closeBf, closeSummary, closeFiles, deleteFiles, deleteAll);
- }
- }
+ int fd = CLibrary.getfd(file.getFD());
- private void scheduleTidy(final boolean closeBf, final boolean closeSummary, final boolean closeFiles, final boolean deleteFiles, final boolean deleteAll)
- {
- final ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(metadata.cfId);
- final OpOrder.Barrier barrier;
- if (cfs != null)
+ if (fd > 0)
{
- barrier = cfs.readOrdering.newBarrier();
- barrier.issue();
- }
- else
- barrier = null;
+ if (logger.isDebugEnabled())
+ logger.debug(String.format("Dropping page cache of file %s.", filePath));
- ScheduledExecutors.nonPeriodicTasks.execute(new Runnable()
- {
- public void run()
- {
- if (barrier != null)
- barrier.await();
- if (closeBf)
- bf.close();
- if (closeSummary)
- indexSummary.close();
- if (closeFiles)
- {
- ifile.cleanup();
- dfile.cleanup();
- }
- if (runOnClose != null)
- runOnClose.run();
- if (deleteAll)
- {
- /**
- * Do the OS a favour and suggest (using fadvice call) that we
- * don't want to see pages of this SSTable in memory anymore.
- *
- * NOTE: We can't use madvice in java because it requires the address of
- * the mapping, so instead we always open a file and run fadvice(fd, 0, 0) on it
- */
- dropPageCache();
- deletingTask.run();
- }
- else if (deleteFiles)
- {
- FileUtils.deleteWithConfirm(new File(dfile.path));
- FileUtils.deleteWithConfirm(new File(ifile.path));
- }
- }
- });
+ CLibrary.trySkipCache(fd, 0, 0);
+ }
+ }
+ catch (IOException e)
+ {
+ // we don't care if cache cleanup fails
+ }
+ finally
+ {
+ FileUtils.closeQuietly(file);
}
}
-
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java b/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
index 7784b18..6356d4d 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
@@ -183,14 +183,14 @@ public class SSTableRewriter
for (SSTableReader sstable : finished)
{
sstable.markObsolete();
- sstable.sharedRef().release();
+ sstable.selfRef().release();
}
// abort the writers
for (Finished finished : finishedEarly)
{
boolean opened = finished.reader != null;
- finished.writer.abort(!opened);
+ finished.writer.abort();
if (opened)
{
// if we've already been opened, add ourselves to the discard pile
@@ -361,7 +361,7 @@ public class SSTableRewriter
}
else
{
- f.writer.abort(true);
+ f.writer.abort();
assert f.reader == null;
}
}
@@ -380,9 +380,9 @@ public class SSTableRewriter
{
for (SSTableReader reader : discard)
{
- if (reader.getCurrentReplacement() == null)
+ if (reader.getCurrentReplacement() == reader)
reader.markObsolete();
- reader.sharedRef().release();
+ reader.selfRef().release();
}
}
else
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java b/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
index cc60594..d430314 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
@@ -17,7 +17,6 @@
*/
package org.apache.cassandra.io.sstable;
-import java.io.Closeable;
import java.io.DataInput;
import java.io.File;
import java.io.FileOutputStream;
@@ -339,16 +338,12 @@ public class SSTableWriter extends SSTable
*/
public void abort()
{
- abort(true);
- }
- public void abort(boolean closeBf)
- {
assert descriptor.type.isTemporary;
if (iwriter == null && dataFile == null)
return;
if (iwriter != null)
- iwriter.abort(closeBf);
+ iwriter.abort();
if (dataFile!= null)
dataFile.abort();
@@ -407,7 +402,7 @@ public class SSTableWriter extends SSTable
components, metadata,
partitioner, ifile,
dfile, iwriter.summary.build(partitioner, exclusiveUpperBoundOfReadableIndex),
- iwriter.bf, maxDataAge, sstableMetadata, SSTableReader.OpenReason.EARLY);
+ iwriter.bf.sharedCopy(), maxDataAge, sstableMetadata, SSTableReader.OpenReason.EARLY);
// now it's open, find the ACTUAL last readable key (i.e. for which the data file has also been flushed)
sstable.first = getMinimalKey(first);
@@ -416,7 +411,7 @@ public class SSTableWriter extends SSTable
if (inclusiveUpperBoundOfReadableData == null)
{
// Prevent leaving tmplink files on disk
- sstable.sharedRef().release();
+ sstable.selfRef().release();
return null;
}
int offset = 2;
@@ -428,7 +423,7 @@ public class SSTableWriter extends SSTable
inclusiveUpperBoundOfReadableData = iwriter.getMaxReadableKey(offset++);
if (inclusiveUpperBoundOfReadableData == null)
{
- sstable.sharedRef().release();
+ sstable.selfRef().release();
return null;
}
}
@@ -438,14 +433,17 @@ public class SSTableWriter extends SSTable
public static enum FinishType
{
- NORMAL(SSTableReader.OpenReason.NORMAL),
- EARLY(SSTableReader.OpenReason.EARLY), // no renaming
- FINISH_EARLY(SSTableReader.OpenReason.NORMAL); // tidy up an EARLY finish
+ CLOSE(null, true),
+ NORMAL(SSTableReader.OpenReason.NORMAL, true),
+ EARLY(SSTableReader.OpenReason.EARLY, false), // no renaming
+ FINISH_EARLY(SSTableReader.OpenReason.NORMAL, true); // tidy up an EARLY finish
final SSTableReader.OpenReason openReason;
- FinishType(SSTableReader.OpenReason openReason)
+ public final boolean isFinal;
+ FinishType(SSTableReader.OpenReason openReason, boolean isFinal)
{
this.openReason = openReason;
+ this.isFinal = isFinal;
}
}
@@ -461,6 +459,7 @@ public class SSTableWriter extends SSTable
public SSTableReader finish(FinishType finishType, long maxDataAge, long repairedAt)
{
+ assert finishType != FinishType.CLOSE;
Pair<Descriptor, StatsMetadata> p;
p = close(finishType, repairedAt < 0 ? this.repairedAt : repairedAt);
@@ -480,16 +479,16 @@ public class SSTableWriter extends SSTable
ifile,
dfile,
iwriter.summary.build(partitioner),
- iwriter.bf,
+ iwriter.bf.sharedCopy(),
maxDataAge,
metadata,
finishType.openReason);
sstable.first = getMinimalKey(first);
sstable.last = getMinimalKey(last);
- switch (finishType)
+ if (finishType.isFinal)
{
- case NORMAL: case FINISH_EARLY:
+ iwriter.bf.close();
// try to save the summaries to disk
sstable.saveSummary(iwriter.builder, dbuilder);
iwriter = null;
@@ -501,16 +500,18 @@ public class SSTableWriter extends SSTable
// Close the writer and return the descriptor to the new sstable and it's metadata
public Pair<Descriptor, StatsMetadata> close()
{
- return close(FinishType.NORMAL, this.repairedAt);
+ return close(FinishType.CLOSE, this.repairedAt);
}
private Pair<Descriptor, StatsMetadata> close(FinishType type, long repairedAt)
{
switch (type)
{
- case EARLY: case NORMAL:
+ case EARLY: case CLOSE: case NORMAL:
iwriter.close();
dataFile.close();
+ if (type == FinishType.CLOSE)
+ iwriter.bf.close();
}
// write sstable statistics
@@ -521,9 +522,8 @@ public class SSTableWriter extends SSTable
// remove the 'tmp' marker from all components
Descriptor descriptor = this.descriptor;
- switch (type)
+ if (type.isFinal)
{
- case NORMAL: case FINISH_EARLY:
dataFile.writeFullChecksum(descriptor);
writeMetadata(descriptor, metadataComponents);
// save the table of components
@@ -629,11 +629,10 @@ public class SSTableWriter extends SSTable
builder.addPotentialBoundary(indexPosition);
}
- public void abort(boolean closeBf)
+ public void abort()
{
indexFile.abort();
- if (closeBf)
- bf.close();
+ bf.close();
}
/**
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java b/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
index 57f465f..8334965 100644
--- a/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
@@ -25,7 +25,17 @@ public class BufferedPoolingSegmentedFile extends PoolingSegmentedFile
{
public BufferedPoolingSegmentedFile(String path, long length)
{
- super(path, length);
+ super(new Cleanup(path), path, length);
+ }
+
+ private BufferedPoolingSegmentedFile(BufferedPoolingSegmentedFile copy)
+ {
+ super(copy);
+ }
+
+ public BufferedPoolingSegmentedFile sharedCopy()
+ {
+ return new BufferedPoolingSegmentedFile(this);
}
public static class Builder extends SegmentedFile.Builder
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java b/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
index 2f715da..c29bbf3 100644
--- a/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
@@ -20,12 +20,30 @@ package org.apache.cassandra.io.util;
import java.io.File;
import org.apache.cassandra.io.sstable.SSTableWriter;
+import org.apache.cassandra.utils.concurrent.SharedCloseable;
public class BufferedSegmentedFile extends SegmentedFile
{
public BufferedSegmentedFile(String path, long length)
{
- super(path, length);
+ super(new Cleanup(path), path, length);
+ }
+
+ private BufferedSegmentedFile(BufferedSegmentedFile copy)
+ {
+ super(copy);
+ }
+
+ private static class Cleanup extends SegmentedFile.Cleanup
+ {
+ protected Cleanup(String path)
+ {
+ super(path);
+ }
+ public void tidy() throws Exception
+ {
+
+ }
}
public static class Builder extends SegmentedFile.Builder
@@ -49,7 +67,8 @@ public class BufferedSegmentedFile extends SegmentedFile
return reader;
}
- public void cleanup()
+ public BufferedSegmentedFile sharedCopy()
{
+ return new BufferedSegmentedFile(this);
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java b/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
index 11d091a..94d23bf 100644
--- a/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
@@ -28,10 +28,31 @@ public class CompressedPoolingSegmentedFile extends PoolingSegmentedFile impleme
public CompressedPoolingSegmentedFile(String path, CompressionMetadata metadata)
{
- super(path, metadata.dataLength, metadata.compressedFileLength);
+ super(new Cleanup(path, metadata), path, metadata.dataLength, metadata.compressedFileLength);
this.metadata = metadata;
}
+ private CompressedPoolingSegmentedFile(CompressedPoolingSegmentedFile copy)
+ {
+ super(copy);
+ this.metadata = copy.metadata;
+ }
+
+ protected static final class Cleanup extends PoolingSegmentedFile.Cleanup
+ {
+ final CompressionMetadata metadata;
+ protected Cleanup(String path, CompressionMetadata metadata)
+ {
+ super(path);
+ this.metadata = metadata;
+ }
+ public void tidy() throws Exception
+ {
+ super.tidy();
+ metadata.close();
+ }
+ }
+
public static class Builder extends CompressedSegmentedFile.Builder
{
public Builder(CompressedSequentialWriter writer)
@@ -59,10 +80,8 @@ public class CompressedPoolingSegmentedFile extends PoolingSegmentedFile impleme
return metadata;
}
- @Override
- public void cleanup()
+ public CompressedPoolingSegmentedFile sharedCopy()
{
- super.cleanup();
- metadata.close();
+ return new CompressedPoolingSegmentedFile(this);
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java b/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
index b788715..0c20bb9 100644
--- a/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
@@ -28,10 +28,35 @@ public class CompressedSegmentedFile extends SegmentedFile implements ICompresse
public CompressedSegmentedFile(String path, CompressionMetadata metadata)
{
- super(path, metadata.dataLength, metadata.compressedFileLength);
+ super(new Cleanup(path, metadata), path, metadata.dataLength, metadata.compressedFileLength);
this.metadata = metadata;
}
+ private CompressedSegmentedFile(CompressedSegmentedFile copy)
+ {
+ super(copy);
+ this.metadata = copy.metadata;
+ }
+
+ private static final class Cleanup extends SegmentedFile.Cleanup
+ {
+ final CompressionMetadata metadata;
+ protected Cleanup(String path, CompressionMetadata metadata)
+ {
+ super(path);
+ this.metadata = metadata;
+ }
+ public void tidy() throws Exception
+ {
+ metadata.close();
+ }
+ }
+
+ public CompressedSegmentedFile sharedCopy()
+ {
+ return new CompressedSegmentedFile(this);
+ }
+
public static class Builder extends SegmentedFile.Builder
{
protected final CompressedSequentialWriter writer;
@@ -70,9 +95,4 @@ public class CompressedSegmentedFile extends SegmentedFile implements ICompresse
{
return metadata;
}
-
- public void cleanup()
- {
- metadata.close();
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/Memory.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/Memory.java b/src/java/org/apache/cassandra/io/util/Memory.java
index 5306433..3874669 100644
--- a/src/java/org/apache/cassandra/io/util/Memory.java
+++ b/src/java/org/apache/cassandra/io/util/Memory.java
@@ -17,6 +17,7 @@
*/
package org.apache.cassandra.io.util;
+import java.io.Closeable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -30,7 +31,7 @@ import sun.nio.ch.DirectBuffer;
/**
* An off-heap region of memory that must be manually free'd when no longer needed.
*/
-public class Memory
+public class Memory implements AutoCloseable
{
private static final Unsafe unsafe = NativeAllocator.unsafe;
private static final IAllocator allocator = DatabaseDescriptor.getoffHeapMemoryAllocator();
@@ -302,6 +303,11 @@ public class Memory
peer = 0;
}
+ public void close() throws Exception
+ {
+ free();
+ }
+
public long size()
{
assert peer != 0;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java b/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
index 3b2cc98..8b4ae9d 100644
--- a/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
@@ -47,10 +47,21 @@ public class MmappedSegmentedFile extends SegmentedFile
public MmappedSegmentedFile(String path, long length, Segment[] segments)
{
- super(path, length);
+ super(new Cleanup(path, segments), path, length);
this.segments = segments;
}
+ private MmappedSegmentedFile(MmappedSegmentedFile copy)
+ {
+ super(copy);
+ this.segments = copy.segments;
+ }
+
+ public MmappedSegmentedFile sharedCopy()
+ {
+ return new MmappedSegmentedFile(this);
+ }
+
/**
* @return The segment entry for the given position.
*/
@@ -85,31 +96,41 @@ public class MmappedSegmentedFile extends SegmentedFile
return file;
}
- public void cleanup()
+ private static final class Cleanup extends SegmentedFile.Cleanup
{
- if (!FileUtils.isCleanerAvailable())
- return;
+ final Segment[] segments;
+ protected Cleanup(String path, Segment[] segments)
+ {
+ super(path);
+ this.segments = segments;
+ }
+
+ public void tidy()
+ {
+ if (!FileUtils.isCleanerAvailable())
+ return;
/*
* Try forcing the unmapping of segments using undocumented unsafe sun APIs.
* If this fails (non Sun JVM), we'll have to wait for the GC to finalize the mapping.
* If this works and a thread tries to access any segment, hell will unleash on earth.
*/
- try
- {
- for (Segment segment : segments)
+ try
{
- if (segment.right == null)
- continue;
- FileUtils.clean(segment.right);
+ for (Segment segment : segments)
+ {
+ if (segment.right == null)
+ continue;
+ FileUtils.clean(segment.right);
+ }
+ logger.debug("All segments have been unmapped successfully");
+ }
+ catch (Exception e)
+ {
+ JVMStabilityInspector.inspectThrowable(e);
+ // This is not supposed to happen
+ logger.error("Error while unmapping segments", e);
}
- logger.debug("All segments have been unmapped successfully");
- }
- catch (Exception e)
- {
- JVMStabilityInspector.inspectThrowable(e);
- // This is not supposed to happen
- logger.error("Error while unmapping segments", e);
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java b/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java
index 01f4e31..daca22f 100644
--- a/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java
@@ -21,15 +21,35 @@ import org.apache.cassandra.service.FileCacheService;
public abstract class PoolingSegmentedFile extends SegmentedFile
{
- final FileCacheService.CacheKey cacheKey = new FileCacheService.CacheKey();
- protected PoolingSegmentedFile(String path, long length)
+ final FileCacheService.CacheKey cacheKey;
+ protected PoolingSegmentedFile(Cleanup cleanup, String path, long length)
{
- super(path, length);
+ this(cleanup, path, length, length);
}
- protected PoolingSegmentedFile(String path, long length, long onDiskLength)
+ protected PoolingSegmentedFile(Cleanup cleanup, String path, long length, long onDiskLength)
{
- super(path, length, onDiskLength);
+ super(cleanup, path, length, onDiskLength);
+ cacheKey = cleanup.cacheKey;
+ }
+
+ public PoolingSegmentedFile(PoolingSegmentedFile copy)
+ {
+ super(copy);
+ cacheKey = copy.cacheKey;
+ }
+
+ protected static class Cleanup extends SegmentedFile.Cleanup
+ {
+ final FileCacheService.CacheKey cacheKey = new FileCacheService.CacheKey();
+ protected Cleanup(String path)
+ {
+ super(path);
+ }
+ public void tidy() throws Exception
+ {
+ FileCacheService.instance.invalidate(cacheKey, path);
+ }
}
public FileDataInput getSegment(long position)
@@ -49,9 +69,4 @@ public abstract class PoolingSegmentedFile extends SegmentedFile
{
FileCacheService.instance.put(cacheKey, reader);
}
-
- public void cleanup()
- {
- FileCacheService.instance.invalidate(cacheKey, path);
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/SegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/SegmentedFile.java b/src/java/org/apache/cassandra/io/util/SegmentedFile.java
index badae56..d557b72 100644
--- a/src/java/org/apache/cassandra/io/util/SegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/SegmentedFile.java
@@ -31,6 +31,8 @@ import org.apache.cassandra.io.FSReadError;
import org.apache.cassandra.io.compress.CompressedSequentialWriter;
import org.apache.cassandra.io.sstable.SSTableWriter;
import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.concurrent.RefCounted;
+import org.apache.cassandra.utils.concurrent.SharedCloseableImpl;
/**
* Abstracts a read-only file that has been split into segments, each of which can be represented by an independent
@@ -41,7 +43,7 @@ import org.apache.cassandra.utils.Pair;
* would need to be longer than 2GB, that segment will not be mmap'd, and a new RandomAccessFile will be created for
* each access to that segment.
*/
-public abstract class SegmentedFile
+public abstract class SegmentedFile extends SharedCloseableImpl
{
public final String path;
public final long length;
@@ -53,18 +55,43 @@ public abstract class SegmentedFile
/**
* Use getBuilder to get a Builder to construct a SegmentedFile.
*/
- SegmentedFile(String path, long length)
+ SegmentedFile(Cleanup cleanup, String path, long length)
{
- this(path, length, length);
+ this(cleanup, path, length, length);
}
- protected SegmentedFile(String path, long length, long onDiskLength)
+ protected SegmentedFile(Cleanup cleanup, String path, long length, long onDiskLength)
{
+ super(cleanup);
this.path = new File(path).getAbsolutePath();
this.length = length;
this.onDiskLength = onDiskLength;
}
+ public SegmentedFile(SegmentedFile copy)
+ {
+ super(copy);
+ path = copy.path;
+ length = copy.length;
+ onDiskLength = copy.onDiskLength;
+ }
+
+ protected static abstract class Cleanup implements RefCounted.Tidy
+ {
+ final String path;
+ protected Cleanup(String path)
+ {
+ this.path = path;
+ }
+
+ public String name()
+ {
+ return path;
+ }
+ }
+
+ public abstract SegmentedFile sharedCopy();
+
/**
* @return A SegmentedFile.Builder.
*/
@@ -96,11 +123,6 @@ public abstract class SegmentedFile
}
/**
- * Do whatever action is needed to reclaim ressources used by this SegmentedFile.
- */
- public abstract void cleanup();
-
- /**
* Collects potential segmentation points in an underlying file, and builds a SegmentedFile to represent it.
*/
public static abstract class Builder
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/service/ActiveRepairService.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/service/ActiveRepairService.java b/src/java/org/apache/cassandra/service/ActiveRepairService.java
index 15e7641..bf1cdd6 100644
--- a/src/java/org/apache/cassandra/service/ActiveRepairService.java
+++ b/src/java/org/apache/cassandra/service/ActiveRepairService.java
@@ -432,7 +432,7 @@ public class ActiveRepairService
{
Set<SSTableReader> sstables = sstableMap.get(cfId);
Iterator<SSTableReader> sstableIterator = sstables.iterator();
- ImmutableMap.Builder<SSTableReader, Ref> references = ImmutableMap.builder();
+ ImmutableMap.Builder<SSTableReader, Ref<SSTableReader>> references = ImmutableMap.builder();
while (sstableIterator.hasNext())
{
SSTableReader sstable = sstableIterator.next();
@@ -442,7 +442,7 @@ public class ActiveRepairService
}
else
{
- Ref ref = sstable.tryRef();
+ Ref<SSTableReader> ref = sstable.tryRef();
if (ref == null)
sstableIterator.remove();
else
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/streaming/StreamSession.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamSession.java b/src/java/org/apache/cassandra/streaming/StreamSession.java
index 6108dea..a9f5075 100644
--- a/src/java/org/apache/cassandra/streaming/StreamSession.java
+++ b/src/java/org/apache/cassandra/streaming/StreamSession.java
@@ -353,7 +353,7 @@ public class StreamSession implements IEndpointStateChangeSubscriber
public static class SSTableStreamingSections
{
public final SSTableReader sstable;
- public final Ref ref;
+ public final Ref<SSTableReader> ref;
public final List<Pair<Long, Long>> sections;
public final long estimatedKeys;
public final long repairedAt;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java b/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
index 5ebf289..069e97f 100644
--- a/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
+++ b/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
@@ -62,7 +62,7 @@ public class OutgoingFileMessage extends StreamMessage
public final FileMessageHeader header;
public final SSTableReader sstable;
- public final Ref ref;
+ public final Ref<SSTableReader> ref;
public OutgoingFileMessage(SSTableReader sstable, Ref ref, int sequenceNumber, long estimatedKeys, List<Pair<Long, Long>> sections, long repairedAt)
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/tools/StandaloneScrubber.java b/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
index 1bc2674..d420218 100644
--- a/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
+++ b/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
@@ -121,7 +121,7 @@ public class StandaloneScrubber
// Remove the sstable (it's been copied by scrub and snapshotted)
sstable.markObsolete();
- sstable.sharedRef().release();
+ sstable.selfRef().release();
}
catch (Exception e)
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java b/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java
index cc162d4..1a029e5 100644
--- a/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java
+++ b/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java
@@ -32,6 +32,11 @@ public class AlwaysPresentFilter implements IFilter
public void close() { }
+ public IFilter sharedCopy()
+ {
+ return this;
+ }
+
public long serializedSize() { return 0; }
@Override
[4/7] cassandra git commit: Safer Resource Management++
Posted by be...@apache.org.
Safer Resource Management++
patch by benedict; reviewed by marcus for CASSANDRA-8707
Project: http://git-wip-us.apache.org/repos/asf/cassandra/repo
Commit: http://git-wip-us.apache.org/repos/asf/cassandra/commit/61384c57
Tree: http://git-wip-us.apache.org/repos/asf/cassandra/tree/61384c57
Diff: http://git-wip-us.apache.org/repos/asf/cassandra/diff/61384c57
Branch: refs/heads/trunk
Commit: 61384c57546da3d411630c64c4aa89d90cac98f7
Parents: 708b0ce
Author: Benedict Elliott Smith <be...@apache.org>
Authored: Wed Feb 11 14:56:23 2015 +0000
Committer: Benedict Elliott Smith <be...@apache.org>
Committed: Wed Feb 11 14:56:23 2015 +0000
----------------------------------------------------------------------
CHANGES.txt | 1 +
.../org/apache/cassandra/db/DataTracker.java | 6 +-
.../cassandra/db/compaction/CompactionTask.java | 4 -
.../SizeTieredCompactionStrategy.java | 10 +-
.../io/compress/CompressionMetadata.java | 19 +-
.../cassandra/io/sstable/IndexSummary.java | 47 +-
.../io/sstable/IndexSummaryBuilder.java | 3 +-
.../io/sstable/IndexSummaryManager.java | 6 +-
.../io/sstable/SSTableDeletingTask.java | 36 +-
.../cassandra/io/sstable/SSTableLoader.java | 4 +-
.../cassandra/io/sstable/SSTableReader.java | 590 ++++++++++++-------
.../cassandra/io/sstable/SSTableRewriter.java | 10 +-
.../cassandra/io/sstable/SSTableWriter.java | 45 +-
.../io/util/BufferedPoolingSegmentedFile.java | 12 +-
.../io/util/BufferedSegmentedFile.java | 23 +-
.../io/util/CompressedPoolingSegmentedFile.java | 29 +-
.../io/util/CompressedSegmentedFile.java | 32 +-
.../org/apache/cassandra/io/util/Memory.java | 8 +-
.../cassandra/io/util/MmappedSegmentedFile.java | 55 +-
.../cassandra/io/util/PoolingSegmentedFile.java | 35 +-
.../apache/cassandra/io/util/SegmentedFile.java | 40 +-
.../cassandra/service/ActiveRepairService.java | 4 +-
.../cassandra/streaming/StreamSession.java | 2 +-
.../streaming/messages/OutgoingFileMessage.java | 2 +-
.../cassandra/tools/StandaloneScrubber.java | 2 +-
.../cassandra/utils/AlwaysPresentFilter.java | 5 +
.../org/apache/cassandra/utils/BloomFilter.java | 20 +-
.../org/apache/cassandra/utils/IFilter.java | 7 +-
.../cassandra/utils/Murmur3BloomFilter.java | 14 +-
.../apache/cassandra/utils/concurrent/Ref.java | 208 ++++++-
.../cassandra/utils/concurrent/RefCounted.java | 52 +-
.../utils/concurrent/RefCountedImpl.java | 132 -----
.../apache/cassandra/utils/concurrent/Refs.java | 26 +-
.../cassandra/utils/obs/OffHeapBitSet.java | 5 +
.../cassandra/db/ColumnFamilyStoreTest.java | 5 +-
.../db/compaction/AntiCompactionTest.java | 6 +-
.../SizeTieredCompactionStrategyTest.java | 30 +-
.../io/sstable/IndexSummaryManagerTest.java | 37 +-
.../cassandra/io/sstable/LegacySSTableTest.java | 3 +-
.../cassandra/io/sstable/SSTableReaderTest.java | 11 +-
.../io/sstable/SSTableRewriterTest.java | 13 +-
.../streaming/StreamTransferTaskTest.java | 2 +-
.../cassandra/tools/SSTableExportTest.java | 1 +
.../cassandra/tools/SSTableImportTest.java | 7 +
.../apache/cassandra/utils/BloomFilterTest.java | 22 +-
.../cassandra/utils/SerializationsTest.java | 5 +-
.../utils/concurrent/RefCountedTest.java | 12 +-
47 files changed, 991 insertions(+), 657 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/CHANGES.txt
----------------------------------------------------------------------
diff --git a/CHANGES.txt b/CHANGES.txt
index 248139f..b323f18 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,4 +1,5 @@
2.1.4
+ * Safer Resource Management++ (CASSANDRA-8707)
* Write partition size estimates into a system table (CASSANDRA-7688)
* cqlsh: Fix keys() and full() collection indexes in DESCRIBE output
(CASSANDRA-8154)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/db/DataTracker.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/DataTracker.java b/src/java/org/apache/cassandra/db/DataTracker.java
index 5ec06bc..acf9f92 100644
--- a/src/java/org/apache/cassandra/db/DataTracker.java
+++ b/src/java/org/apache/cassandra/db/DataTracker.java
@@ -367,7 +367,7 @@ public class DataTracker
while (!view.compareAndSet(currentView, newView));
for (SSTableReader sstable : currentView.sstables)
if (!remaining.contains(sstable))
- sstable.sharedRef().release();
+ sstable.selfRef().release();
notifySSTablesChanged(remaining, Collections.<SSTableReader>emptySet(), OperationType.UNKNOWN);
}
@@ -406,7 +406,7 @@ public class DataTracker
sstable.setTrackedBy(this);
for (SSTableReader sstable : oldSSTables)
- sstable.sharedRef().release();
+ sstable.selfRef().release();
}
private void removeSSTablesFromTracker(Collection<SSTableReader> oldSSTables)
@@ -467,7 +467,7 @@ public class DataTracker
{
boolean firstToCompact = sstable.markObsolete();
assert tolerateCompacted || firstToCompact : sstable + " was already marked compacted";
- sstable.sharedRef().release();
+ sstable.selfRef().release();
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/compaction/CompactionTask.java b/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
index b6c215e..4d9b463 100644
--- a/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
+++ b/src/java/org/apache/cassandra/db/compaction/CompactionTask.java
@@ -18,10 +18,8 @@
package org.apache.cassandra.db.compaction;
import java.io.File;
-import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -31,7 +29,6 @@ import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
@@ -40,7 +37,6 @@ import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
-import org.apache.cassandra.db.RowIndexEntry;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.db.compaction.CompactionManager.CompactionExecutorStatsCollector;
import org.apache.cassandra.io.sstable.SSTableReader;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java b/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
index fbd715c..8b1610e 100644
--- a/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
+++ b/src/java/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategy.java
@@ -144,8 +144,8 @@ public class SizeTieredCompactionStrategy extends AbstractCompactionStrategy
// calculate the total reads/sec across all sstables
double totalReads = 0.0;
for (SSTableReader sstr : sstables)
- if (sstr.readMeter != null)
- totalReads += sstr.readMeter.twoHourRate();
+ if (sstr.getReadMeter() != null)
+ totalReads += sstr.getReadMeter().twoHourRate();
// if this is a system table with no read meters or we don't have any read rates yet, just return them all
if (totalReads == 0.0)
@@ -159,11 +159,11 @@ public class SizeTieredCompactionStrategy extends AbstractCompactionStrategy
while (cutoffIndex < sstables.size())
{
SSTableReader sstable = sstables.get(cutoffIndex);
- if (sstable.readMeter == null)
+ if (sstable.getReadMeter() == null)
{
throw new AssertionError("If you're seeing this exception, please attach your logs to CASSANDRA-8238 to help us debug. "+sstable);
}
- double reads = sstable.readMeter.twoHourRate();
+ double reads = sstable.getReadMeter().twoHourRate();
if (totalColdReads + reads > maxColdReads)
break;
@@ -307,7 +307,7 @@ public class SizeTieredCompactionStrategy extends AbstractCompactionStrategy
private static double hotness(SSTableReader sstr)
{
// system tables don't have read meters, just use 0.0 for the hotness
- return sstr.readMeter == null ? 0.0 : sstr.readMeter.twoHourRate() / sstr.estimatedKeys();
+ return sstr.getReadMeter() == null ? 0.0 : sstr.getReadMeter().twoHourRate() / sstr.estimatedKeys();
}
public synchronized AbstractCompactionTask getNextBackgroundTask(int gcBefore)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java b/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
index a40048a..aaf1656 100644
--- a/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
+++ b/src/java/org/apache/cassandra/io/compress/CompressionMetadata.java
@@ -325,18 +325,15 @@ public class CompressionMetadata
public CompressionMetadata open(long dataLength, long compressedLength, SSTableWriter.FinishType finishType)
{
RefCountedMemory offsets;
- switch (finishType)
+ if (finishType.isFinal)
{
- case EARLY:
- offsets = this.offsets;
- break;
- case NORMAL:
- case FINISH_EARLY:
- offsets = this.offsets.copy(count * 8L);
- this.offsets.unreference();
- break;
- default:
- throw new AssertionError();
+ // we now know how many offsets we have and can resize the offsets properly
+ offsets = this.offsets.copy(count * 8L);
+ this.offsets.unreference();
+ }
+ else
+ {
+ offsets = this.offsets;
}
return new CompressionMetadata(filePath, parameters, offsets, count * 8L, dataLength, compressedLength, Descriptor.Version.CURRENT.hasPostCompressionAdlerChecksums);
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/IndexSummary.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/IndexSummary.java b/src/java/org/apache/cassandra/io/sstable/IndexSummary.java
index f53a7e4..0cde124 100644
--- a/src/java/org/apache/cassandra/io/sstable/IndexSummary.java
+++ b/src/java/org/apache/cassandra/io/sstable/IndexSummary.java
@@ -17,21 +17,19 @@
*/
package org.apache.cassandra.io.sstable;
-import java.io.Closeable;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import org.apache.cassandra.cache.RefCountedMemory;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.io.util.DataOutputPlus;
+import org.apache.cassandra.io.util.Memory;
import org.apache.cassandra.io.util.MemoryOutputStream;
import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.concurrent.WrappedSharedCloseable;
import static org.apache.cassandra.io.sstable.Downsampling.BASE_SAMPLING_LEVEL;
@@ -45,10 +43,8 @@ import static org.apache.cassandra.io.sstable.Downsampling.BASE_SAMPLING_LEVEL;
* (This is necessary because keys can have different lengths.)
* 2. A sequence of (DecoratedKey, position) pairs, where position is the offset into the actual index file.
*/
-public class IndexSummary implements Closeable
+public class IndexSummary extends WrappedSharedCloseable
{
- private static final Logger logger = LoggerFactory.getLogger(IndexSummary.class);
-
public static final IndexSummarySerializer serializer = new IndexSummarySerializer();
/**
@@ -60,7 +56,7 @@ public class IndexSummary implements Closeable
private final IPartitioner partitioner;
private final int summarySize;
private final int sizeAtFullSampling;
- private final RefCountedMemory bytes;
+ private final Memory bytes;
/**
* A value between 1 and BASE_SAMPLING_LEVEL that represents how many of the original
@@ -70,17 +66,29 @@ public class IndexSummary implements Closeable
*/
private final int samplingLevel;
- public IndexSummary(IPartitioner partitioner, RefCountedMemory memory, int summarySize, int sizeAtFullSampling,
+ public IndexSummary(IPartitioner partitioner, Memory bytes, int summarySize, int sizeAtFullSampling,
int minIndexInterval, int samplingLevel)
{
+ super(bytes);
this.partitioner = partitioner;
this.minIndexInterval = minIndexInterval;
this.summarySize = summarySize;
this.sizeAtFullSampling = sizeAtFullSampling;
- this.bytes = memory;
+ this.bytes = bytes;
this.samplingLevel = samplingLevel;
}
+ private IndexSummary(IndexSummary copy)
+ {
+ super(copy);
+ this.partitioner = copy.partitioner;
+ this.minIndexInterval = copy.minIndexInterval;
+ this.summarySize = copy.summarySize;
+ this.sizeAtFullSampling = copy.sizeAtFullSampling;
+ this.bytes = copy.bytes;
+ this.samplingLevel = copy.samplingLevel;
+ }
+
// binary search is notoriously more difficult to get right than it looks; this is lifted from
// Harmony's Collections implementation
public int binarySearch(RowPosition key)
@@ -137,7 +145,7 @@ public class IndexSummary implements Closeable
long start = getPositionInSummary(index);
long end = calculateEnd(index);
byte[] entry = new byte[(int)(end - start)];
- bytes.getBytes(start, entry, 0, (int)(end - start));
+ bytes.getBytes(start, entry, 0, (int) (end - start));
return entry;
}
@@ -206,6 +214,11 @@ public class IndexSummary implements Closeable
return Downsampling.getEffectiveIndexIntervalAfterIndex(index, samplingLevel, minIndexInterval);
}
+ public IndexSummary sharedCopy()
+ {
+ return new IndexSummary(this);
+ }
+
public static class IndexSummarySerializer
{
public void serialize(IndexSummary t, DataOutputPlus out, boolean withSamplingLevel) throws IOException
@@ -256,16 +269,4 @@ public class IndexSummary implements Closeable
return new IndexSummary(partitioner, memory, summarySize, fullSamplingSummarySize, minIndexInterval, samplingLevel);
}
}
-
- @Override
- public void close()
- {
- bytes.unreference();
- }
-
- public IndexSummary readOnlyClone()
- {
- bytes.reference();
- return this;
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java b/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
index 8e9cc30..df326d7 100644
--- a/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
+++ b/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
@@ -28,6 +28,7 @@ import org.apache.cassandra.cache.RefCountedMemory;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.io.util.Memory;
import static org.apache.cassandra.io.sstable.Downsampling.BASE_SAMPLING_LEVEL;
import static org.apache.cassandra.io.sstable.SSTable.getMinimalKey;
@@ -148,7 +149,7 @@ public class IndexSummaryBuilder
// first we write out the position in the *summary* for each key in the summary,
// then we write out (key, actual index position) pairs
- RefCountedMemory memory = new RefCountedMemory(offheapSize + (length * 4));
+ Memory memory = Memory.allocate(offheapSize + (length * 4));
int idxPosition = 0;
int keyPosition = length * 4;
for (int i = 0; i < length; i++)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java b/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
index 65b25a4..4144c32 100644
--- a/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
+++ b/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java
@@ -266,9 +266,9 @@ public class IndexSummaryManager implements IndexSummaryManagerMBean
double totalReadsPerSec = 0.0;
for (SSTableReader sstable : nonCompacting)
{
- if (sstable.readMeter != null)
+ if (sstable.getReadMeter() != null)
{
- Double readRate = sstable.readMeter.fifteenMinuteRate();
+ Double readRate = sstable.getReadMeter().fifteenMinuteRate();
totalReadsPerSec += readRate;
readRates.put(sstable, readRate);
}
@@ -314,7 +314,7 @@ public class IndexSummaryManager implements IndexSummaryManagerMBean
int minIndexInterval = sstable.metadata.getMinIndexInterval();
int maxIndexInterval = sstable.metadata.getMaxIndexInterval();
- double readsPerSec = sstable.readMeter == null ? 0.0 : sstable.readMeter.fifteenMinuteRate();
+ double readsPerSec = sstable.getReadMeter() == null ? 0.0 : sstable.getReadMeter().fifteenMinuteRate();
long idealSpace = Math.round(remainingSpace * (readsPerSec / totalReadsPerSec));
// figure out how many entries our idealSpace would buy us, and pick a new sampling level based on that
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java b/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
index fb1cbb3..3da6906 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
@@ -40,31 +40,42 @@ public class SSTableDeletingTask implements Runnable
// and delete will fail (on Windows) until it is (we only force the unmapping on SUN VMs).
// Additionally, we need to make sure to delete the data file first, so on restart the others
// will be recognized as GCable.
- private static final Set<SSTableDeletingTask> failedTasks = new CopyOnWriteArraySet<SSTableDeletingTask>();
+ private static final Set<SSTableDeletingTask> failedTasks = new CopyOnWriteArraySet<>();
private final SSTableReader referent;
private final Descriptor desc;
private final Set<Component> components;
private DataTracker tracker;
- public SSTableDeletingTask(SSTableReader referent)
+ /**
+ * realDescriptor is the actual descriptor for the sstable, the descriptor inside
+ * referent can be 'faked' as FINAL for early opened files. We need the real one
+ * to be able to remove the files.
+ */
+ public SSTableDeletingTask(Descriptor realDescriptor, SSTableReader referent)
{
this.referent = referent;
- if (referent.openReason == SSTableReader.OpenReason.EARLY)
+ this.desc = realDescriptor;
+ switch (desc.type)
{
- this.desc = referent.descriptor.asType(Descriptor.Type.TEMPLINK);
- this.components = Sets.newHashSet(Component.DATA, Component.PRIMARY_INDEX);
- }
- else
- {
- this.desc = referent.descriptor;
- this.components = referent.components;
+ case FINAL:
+ this.components = referent.components;
+ break;
+ case TEMPLINK:
+ this.components = Sets.newHashSet(Component.DATA, Component.PRIMARY_INDEX);
+ break;
+ default:
+ throw new IllegalStateException();
}
}
public void setTracker(DataTracker tracker)
{
- this.tracker = tracker;
+ // the tracker is used only to notify listeners of deletion of the sstable;
+ // since deletion of a non-final file is not really deletion of the sstable,
+ // we don't want to notify the listeners in this event
+ if (desc.type == Descriptor.Type.FINAL)
+ this.tracker = tracker;
}
public void schedule()
@@ -79,9 +90,6 @@ public class SSTableDeletingTask implements Runnable
if (tracker != null)
tracker.notifyDeleting(referent);
- if (referent.readMeter != null)
- SystemKeyspace.clearSSTableReadMeter(referent.getKeyspaceName(), referent.getColumnFamilyName(), referent.descriptor.generation);
-
// If we can't successfully delete the DATA component, set the task to be retried later: see above
File datafile = new File(desc.filenameFor(Component.DATA));
if (!datafile.delete())
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java b/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
index 06f71d8..cd23ae2 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
@@ -209,8 +209,8 @@ public class SSTableLoader implements StreamEventHandler
{
for (SSTableReader sstable : sstables)
{
- sstable.sharedRef().release();
- assert sstable.sharedRef().globalCount() == 0;
+ sstable.selfRef().release();
+ assert sstable.selfRef().globalCount() == 0;
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableReader.java b/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
index f34939a..a28eb44 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
@@ -36,11 +36,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
+import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
@@ -118,10 +114,62 @@ import org.apache.cassandra.utils.concurrent.RefCounted;
import static org.apache.cassandra.db.Directories.SECONDARY_INDEX_NAME_SEPARATOR;
/**
- * SSTableReaders are open()ed by Keyspace.onStart; after that they are created by SSTableWriter.renameAndOpen.
- * Do not re-call open() on existing SSTable files; use the references kept by ColumnFamilyStore post-start instead.
+ * An SSTableReader can be constructed in a number of places, but typically is either
+ * read from disk at startup, or constructed from a flushed memtable, or after compaction
+ * to replace some existing sstables. However once created, an sstablereader may also be modified.
+ *
+ * A reader's OpenReason describes its current stage in its lifecycle, as follows:
+ *
+ * NORMAL
+ * From: None => Reader has been read from disk, either at startup or from a flushed memtable
+ * EARLY => Reader is the final result of a compaction
+ * MOVED_START => Reader WAS being compacted, but this failed and it has been restored to NORMAL status
+ *
+ * EARLY
+ * From: None => Reader is a compaction replacement that is either incomplete and has been opened
+ * to represent its partial result status, or has been finished but the compaction
+ * it is a part of has not yet completed fully
+ * EARLY => Same as from None, only it is not the first time it has been
+ *
+ * MOVED_START
+ * From: NORMAL => Reader is being compacted. This compaction has not finished, but the compaction result
+ * is either partially or fully opened, to either partially or fully replace this reader.
+ * This reader's start key has been updated to represent this, so that reads only hit
+ * one or the other reader.
+ *
+ * METADATA_CHANGE
+ * From: NORMAL => Reader has seen low traffic and the amount of memory available for index summaries is
+ * constrained, so its index summary has been downsampled.
+ * METADATA_CHANGE => Same
+ *
+ * Note that in parallel to this, there are two different Descriptor types; TMPLINK and FINAL; the latter corresponds
+ * to NORMAL state readers and all readers that replace a NORMAL one. TMPLINK is used for EARLY state readers and
+ * no others.
+ *
+ * When a reader is being compacted, if the result is large its replacement may be opened as EARLY before compaction
+ * completes in order to present the result to consumers earlier. In this case the reader will itself be changed to
+ * a MOVED_START state, where its start no longer represents its on-disk minimum key. This is to permit reads to be
+ * directed to only one reader when the two represent the same data. The EARLY file can represent a compaction result
+ * that is either partially complete and still in-progress, or a complete and immutable sstable that is part of a larger
+ * macro compaction action that has not yet fully completed.
+ *
+ * Currently ALL compaction results at least briefly go through an EARLY open state prior to completion, regardless
+ * of if early opening is enabled.
+ *
+ * Since a reader can be created multiple times over the same shared underlying resources, and the exact resources
+ * it shares between each instance differ subtly, we track the lifetime of any underlying resource with its own
+ * reference count, which each instance takes a Ref to. Each instance then tracks references to itself, and once these
+ * all expire it releases its Refs to these underlying resources.
+ *
+ * There is some shared cleanup behaviour needed only once all sstablereaders in a certain stage of their lifecycle
+ * (i.e. EARLY or NORMAL opening), and some that must only occur once all readers of any kind over a single logical
+ * sstable have expired. These are managed by the TypeTidy and GlobalTidy classes at the bottom, and are effectively
+ * managed as another resource each instance tracks its own Ref instance to, to ensure all of these resources are
+ * cleaned up safely and can be debugged otherwise.
+ *
+ * TODO: fill in details about DataTracker and lifecycle interactions for tools, and for compaction strategies
*/
-public class SSTableReader extends SSTable implements RefCounted
+public class SSTableReader extends SSTable implements RefCounted<SSTableReader>
{
private static final Logger logger = LoggerFactory.getLogger(SSTableReader.class);
@@ -166,7 +214,8 @@ public class SSTableReader extends SSTable implements RefCounted
{
NORMAL,
EARLY,
- METADATA_CHANGE
+ METADATA_CHANGE,
+ MOVED_START
}
public final OpenReason openReason;
@@ -174,7 +223,6 @@ public class SSTableReader extends SSTable implements RefCounted
// indexfile and datafile: might be null before a call to load()
private SegmentedFile ifile;
private SegmentedFile dfile;
-
private IndexSummary indexSummary;
private IFilter bf;
@@ -184,8 +232,7 @@ public class SSTableReader extends SSTable implements RefCounted
// technically isCompacted is not necessary since it should never be unreferenced unless it is also compacted,
// but it seems like a good extra layer of protection against reference counting bugs to not delete data based on that alone
- private final AtomicBoolean isCompacted = new AtomicBoolean(false);
- private final AtomicBoolean isSuspect = new AtomicBoolean(false);
+ private AtomicBoolean isSuspect = new AtomicBoolean(false);
// not final since we need to be able to change level on a file.
private volatile StatsMetadata sstableMetadata;
@@ -193,12 +240,10 @@ public class SSTableReader extends SSTable implements RefCounted
private final AtomicLong keyCacheHit = new AtomicLong(0);
private final AtomicLong keyCacheRequest = new AtomicLong(0);
- private final Tidier tidy = new Tidier();
- private final RefCounted refCounted = RefCounted.Impl.get(tidy);
+ private final InstanceTidier tidy = new InstanceTidier(descriptor, metadata);
+ private final Ref<SSTableReader> selfRef = new Ref<>(this, tidy);
- @VisibleForTesting
- public RestorableMeter readMeter;
- private ScheduledFuture readMeterSyncFuture;
+ private RestorableMeter readMeter;
/**
* Calculate approximate key count.
@@ -399,7 +444,7 @@ public class SSTableReader extends SSTable implements RefCounted
sstable.ifile = ibuilder.complete(sstable.descriptor.filenameFor(Component.PRIMARY_INDEX));
sstable.dfile = dbuilder.complete(sstable.descriptor.filenameFor(Component.DATA));
sstable.bf = FilterFactory.AlwaysPresent;
- sstable.tidy.setup(sstable);
+ sstable.setup();
return sstable;
}
@@ -443,13 +488,13 @@ public class SSTableReader extends SSTable implements RefCounted
sstable.load(validationMetadata);
logger.debug("INDEX LOAD TIME for {}: {} ms.", descriptor, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
+ sstable.setup();
if (validate)
sstable.validate();
if (sstable.getKeyCache() != null)
logger.debug("key cache contains {}/{} keys", sstable.getKeyCache().size(), sstable.getKeyCache().getCapacity());
- sstable.tidy.setup(sstable);
return sstable;
}
@@ -545,32 +590,6 @@ public class SSTableReader extends SSTable implements RefCounted
this.sstableMetadata = sstableMetadata;
this.maxDataAge = maxDataAge;
this.openReason = openReason;
-
- tidy.deletingTask = new SSTableDeletingTask(this);
-
- // Don't track read rates for tables in the system keyspace and don't bother trying to load or persist
- // the read meter when in client mode. Also don't track reads for special operations (like early open)
- // this is to avoid overflowing the executor queue (see CASSANDRA-8066)
- if (Keyspace.SYSTEM_KS.equals(desc.ksname) || Config.isClientMode() || openReason != OpenReason.NORMAL)
- {
- readMeter = null;
- readMeterSyncFuture = null;
- return;
- }
-
- readMeter = SystemKeyspace.getSSTableReadMeter(desc.ksname, desc.cfname, desc.generation);
- // sync the average read rate to system.sstable_activity every five minutes, starting one minute from now
- readMeterSyncFuture = syncExecutor.scheduleAtFixedRate(new Runnable()
- {
- public void run()
- {
- if (!isCompacted.get())
- {
- meterSyncThrottle.acquire();
- SystemKeyspace.persistSSTableReadMeter(desc.ksname, desc.cfname, desc.generation, readMeter);
- }
- }
- }, 1, 5, TimeUnit.MINUTES);
}
private SSTableReader(Descriptor desc,
@@ -586,12 +605,11 @@ public class SSTableReader extends SSTable implements RefCounted
OpenReason openReason)
{
this(desc, components, metadata, partitioner, maxDataAge, sstableMetadata, openReason);
-
this.ifile = ifile;
this.dfile = dfile;
this.indexSummary = indexSummary;
this.bf = bloomFilter;
- tidy.setup(this);
+ this.setup();
}
public static long getTotalBytes(Iterable<SSTableReader> sstables)
@@ -626,7 +644,7 @@ public class SSTableReader extends SSTable implements RefCounted
public void setTrackedBy(DataTracker tracker)
{
- tidy.deletingTask.setTracker(tracker);
+ tidy.type.deletingTask.setTracker(tracker);
// under normal operation we can do this at any time, but SSTR is also used outside C* proper,
// e.g. by BulkLoader, which does not initialize the cache. As a kludge, we set up the cache
// here when we know we're being wired into the rest of the server infrastructure.
@@ -698,7 +716,6 @@ public class SSTableReader extends SSTable implements RefCounted
dfile = dbuilder.complete(descriptor.filenameFor(Component.DATA));
if (saveSummaryIfCreated && (recreateBloomFilter || !summaryLoaded)) // save summary information to disk
saveSummary(ibuilder, dbuilder);
- tidy.setup(this);
}
/**
@@ -792,6 +809,8 @@ public class SSTableReader extends SSTable implements RefCounted
}
catch (IOException e)
{
+ if (indexSummary != null)
+ indexSummary.close();
logger.debug("Cannot deserialize SSTable Summary File {}: {}", summariesFile.getPath(), e.getMessage());
// corrupted; delete it and fall back to creating a new summary
FileUtils.closeQuietly(iStream);
@@ -850,20 +869,21 @@ public class SSTableReader extends SSTable implements RefCounted
public void setReplacedBy(SSTableReader replacement)
{
- synchronized (tidy.replaceLock)
+ synchronized (tidy.global)
{
- assert tidy.replacedBy == null;
- tidy.replacedBy = replacement;
- replacement.tidy.replaces = this;
- replacement.tidy.replaceLock = tidy.replaceLock;
+ assert replacement != null;
+ assert !tidy.isReplaced;
+ assert tidy.global.live == this;
+ tidy.isReplaced = true;
+ tidy.global.live = replacement;
}
}
public SSTableReader cloneWithNewStart(DecoratedKey newStart, final Runnable runOnClose)
{
- synchronized (tidy.replaceLock)
+ synchronized (tidy.global)
{
- assert tidy.replacedBy == null;
+ assert openReason != OpenReason.EARLY;
if (newStart.compareTo(this.first) > 0)
{
@@ -895,10 +915,9 @@ public class SSTableReader extends SSTable implements RefCounted
}
}
- SSTableReader replacement = new SSTableReader(descriptor, components, metadata, partitioner, ifile, dfile, indexSummary.readOnlyClone(), bf, maxDataAge, sstableMetadata,
- openReason == OpenReason.EARLY ? openReason : OpenReason.METADATA_CHANGE);
- replacement.readMeterSyncFuture = this.readMeterSyncFuture;
- replacement.readMeter = this.readMeter;
+ SSTableReader replacement = new SSTableReader(descriptor, components, metadata, partitioner, ifile.sharedCopy(),
+ dfile.sharedCopy(), indexSummary.sharedCopy(), bf.sharedCopy(),
+ maxDataAge, sstableMetadata, OpenReason.MOVED_START);
replacement.first = this.last.compareTo(newStart) > 0 ? newStart : this.last;
replacement.last = this.last;
setReplacedBy(replacement);
@@ -916,9 +935,9 @@ public class SSTableReader extends SSTable implements RefCounted
*/
public SSTableReader cloneWithNewSummarySamplingLevel(ColumnFamilyStore parent, int samplingLevel) throws IOException
{
- synchronized (tidy.replaceLock)
+ synchronized (tidy.global)
{
- assert tidy.replacedBy == null;
+ assert openReason != OpenReason.EARLY;
int minIndexInterval = metadata.getMinIndexInterval();
int maxIndexInterval = metadata.getMaxIndexInterval();
@@ -957,10 +976,9 @@ public class SSTableReader extends SSTable implements RefCounted
StorageMetrics.load.inc(newSize - oldSize);
parent.metric.liveDiskSpaceUsed.inc(newSize - oldSize);
- SSTableReader replacement = new SSTableReader(descriptor, components, metadata, partitioner, ifile, dfile, newSummary, bf, maxDataAge, sstableMetadata,
- openReason == OpenReason.EARLY ? openReason : OpenReason.METADATA_CHANGE);
- replacement.readMeterSyncFuture = this.readMeterSyncFuture;
- replacement.readMeter = this.readMeter;
+ SSTableReader replacement = new SSTableReader(descriptor, components, metadata, partitioner, ifile.sharedCopy(),
+ dfile.sharedCopy(), newSummary, bf.sharedCopy(), maxDataAge,
+ sstableMetadata, OpenReason.METADATA_CHANGE);
replacement.first = this.first;
replacement.last = this.last;
setReplacedBy(replacement);
@@ -992,6 +1010,11 @@ public class SSTableReader extends SSTable implements RefCounted
}
}
+ public RestorableMeter getReadMeter()
+ {
+ return readMeter;
+ }
+
public int getIndexSummarySamplingLevel()
{
return indexSummary.getSamplingLevel();
@@ -1014,14 +1037,17 @@ public class SSTableReader extends SSTable implements RefCounted
public void releaseSummary() throws IOException
{
- indexSummary.close();
+ tidy.releaseSummary();
indexSummary = null;
}
private void validate()
{
if (this.first.compareTo(this.last) > 0)
+ {
+ selfRef().release();
throw new IllegalStateException(String.format("SSTable first key %s > last key %s", this.first, this.last));
+ }
}
/**
@@ -1567,16 +1593,16 @@ public class SSTableReader extends SSTable implements RefCounted
if (logger.isDebugEnabled())
logger.debug("Marking {} compacted", getFilename());
- synchronized (tidy.replaceLock)
+ synchronized (tidy.global)
{
- assert tidy.replacedBy == null : getFilename();
+ assert !tidy.isReplaced;
}
- return !isCompacted.getAndSet(true);
+ return !tidy.global.isCompacted.getAndSet(true);
}
public boolean isMarkedCompacted()
{
- return isCompacted.get();
+ return tidy.global.isCompacted.get();
}
public void markSuspect()
@@ -1673,16 +1699,7 @@ public class SSTableReader extends SSTable implements RefCounted
public SSTableReader getCurrentReplacement()
{
- synchronized (tidy.replaceLock)
- {
- SSTableReader cur = this, next = tidy.replacedBy;
- while (next != null)
- {
- cur = next;
- next = next.tidy.replacedBy;
- }
- return cur;
- }
+ return tidy.global.live;
}
/**
@@ -1882,199 +1899,314 @@ public class SSTableReader extends SSTable implements RefCounted
}
}
- public Ref tryRef()
+ public Ref<SSTableReader> tryRef()
{
- return refCounted.tryRef();
+ return selfRef.tryRef();
}
- public Ref sharedRef()
+ public Ref<SSTableReader> selfRef()
{
- return refCounted.sharedRef();
+ return selfRef;
}
- private static final class Tidier implements Tidy
+ public Ref<SSTableReader> ref()
{
- private String name;
- private CFMetaData metadata;
- // indexfile and datafile: might be null before a call to load()
- private SegmentedFile ifile;
- private SegmentedFile dfile;
+ return selfRef.ref();
+ }
- private IndexSummary indexSummary;
- private IFilter bf;
+ void setup()
+ {
+ tidy.setup(this);
+ this.readMeter = tidy.global.readMeter;
+ }
+
+ @VisibleForTesting
+ public void overrideReadMeter(RestorableMeter readMeter)
+ {
+ this.readMeter = tidy.global.readMeter = readMeter;
+ }
- private AtomicBoolean isCompacted;
+ /**
+ * One instance per SSTableReader we create. This references the type-shared tidy, which in turn references
+ * the globally shared tidy, i.e.
+ *
+ * InstanceTidier => DescriptorTypeTitdy => GlobalTidy
+ *
+ * We can create many InstanceTidiers (one for every time we reopen an sstable with MOVED_START for example), but there can only be
+ * two DescriptorTypeTidy (FINAL and TEMPLINK) and only one GlobalTidy for one single logical sstable.
+ *
+ * When the InstanceTidier cleansup, it releases its reference to its DescriptorTypeTidy; when all InstanceTidiers
+ * for that type have run, the DescriptorTypeTidy cleansup. DescriptorTypeTidy behaves in the same way towards GlobalTidy.
+ *
+ * For ease, we stash a direct reference to both our type-shared and global tidier
+ */
+ private static final class InstanceTidier implements Tidy
+ {
+ private final Descriptor descriptor;
+ private final CFMetaData metadata;
+ private IFilter bf;
+ private IndexSummary summary;
- /**
- * To support replacing this sstablereader with another object that represents that same underlying sstable, but with different associated resources,
- * we build a linked-list chain of replacement, which we synchronise using a shared object to make maintenance of the list across multiple threads simple.
- * On close we check if any of the closeable resources differ between any chains either side of us; any that are in neither of the adjacent links (if any) are closed.
- * Once we've made this decision we remove ourselves from the linked list, so that anybody behind/ahead will compare against only other still opened resources.
- */
- private Object replaceLock = new Object();
- private SSTableReader replacedBy;
- private SSTableReader replaces;
- private SSTableDeletingTask deletingTask;
+ private SegmentedFile dfile;
+ private SegmentedFile ifile;
private Runnable runOnClose;
+ private boolean isReplaced = false;
+
+ // a reference to our shared per-Descriptor.Type tidy instance, that
+ // we will release when we are ourselves released
+ private Ref<DescriptorTypeTidy> typeRef;
+
+ // a convenience stashing of the shared per-descriptor-type tidy instance itself
+ // and the per-logical-sstable globally shared state that it is linked to
+ private DescriptorTypeTidy type;
+ private GlobalTidy global;
+
+ private boolean setup;
+
+ void setup(SSTableReader reader)
+ {
+ this.setup = true;
+ this.bf = reader.bf;
+ this.summary = reader.indexSummary;
+ this.dfile = reader.dfile;
+ this.ifile = reader.ifile;
+ // get a new reference to the shared descriptor-type tidy
+ this.typeRef = DescriptorTypeTidy.get(reader);
+ this.type = typeRef.get();
+ this.global = type.globalRef.get();
+ }
- @VisibleForTesting
- public RestorableMeter readMeter;
- private volatile ScheduledFuture readMeterSyncFuture;
+ InstanceTidier(Descriptor descriptor, CFMetaData metadata)
+ {
+ this.descriptor = descriptor;
+ this.metadata = metadata;
+ }
- private void setup(SSTableReader reader)
+ public void tidy()
{
- name = reader.toString();
- metadata = reader.metadata;
- ifile = reader.ifile;
- dfile = reader.dfile;
- indexSummary = reader.indexSummary;
- bf = reader.bf;
- isCompacted = reader.isCompacted;
- readMeterSyncFuture = reader.readMeterSyncFuture;
+ // don't try to cleanup if the sstablereader was never fully constructed
+ if (!setup)
+ return;
+
+ final ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(metadata.cfId);
+ final OpOrder.Barrier barrier;
+ if (cfs != null)
+ {
+ barrier = cfs.readOrdering.newBarrier();
+ barrier.issue();
+ }
+ else
+ barrier = null;
+
+ ScheduledExecutors.nonPeriodicTasks.execute(new Runnable()
+ {
+ public void run()
+ {
+ if (barrier != null)
+ barrier.await();
+ bf.close();
+ dfile.close();
+ ifile.close();
+ if (summary != null)
+ summary.close();
+ if (runOnClose != null)
+ runOnClose.run();
+ typeRef.release();
+ }
+ });
}
public String name()
{
- return name;
+ return descriptor.toString();
}
- private void dropPageCache()
+ void releaseSummary()
{
- dropPageCache(dfile.path);
- dropPageCache(ifile.path);
+ summary.close();
+ assert summary.isCleanedUp();
+ summary = null;
}
+ }
+
+ /**
+ * One shared between all instances of a given Descriptor.Type.
+ * Performs only two things: the deletion of the sstables for the type,
+ * if necessary; and the shared reference to the globally shared state.
+ *
+ * All InstanceTidiers, on setup(), ask the static get() method for their shared state,
+ * and stash a reference to it to be released when they are. Once all such references are
+ * released, the shared tidy will be performed.
+ */
+ static final class DescriptorTypeTidy implements Tidy
+ {
+ // keyed by REAL descriptor (TMPLINK/FINAL), mapping to the shared DescriptorTypeTidy for that descriptor
+ static final ConcurrentMap<Descriptor, Ref<DescriptorTypeTidy>> lookup = new ConcurrentHashMap<>();
- private void dropPageCache(String filePath)
+ private final Descriptor desc;
+ private final Ref<GlobalTidy> globalRef;
+ private final SSTableDeletingTask deletingTask;
+
+ DescriptorTypeTidy(Descriptor desc, SSTableReader sstable)
{
- RandomAccessFile file = null;
+ this.desc = desc;
+ this.deletingTask = new SSTableDeletingTask(desc, sstable);
+ // get a new reference to the shared global tidy
+ this.globalRef = GlobalTidy.get(sstable);
+ }
- try
+ public void tidy()
+ {
+ lookup.remove(desc);
+ boolean isCompacted = globalRef.get().isCompacted.get();
+ globalRef.release();
+ switch (desc.type)
{
- file = new RandomAccessFile(filePath, "r");
+ case FINAL:
+ if (isCompacted)
+ deletingTask.run();
+ break;
+ case TEMPLINK:
+ deletingTask.run();
+ break;
+ default:
+ throw new IllegalStateException();
+ }
+ }
- int fd = CLibrary.getfd(file.getFD());
+ public String name()
+ {
+ return desc.toString();
+ }
- if (fd > 0)
- {
- if (logger.isDebugEnabled())
- logger.debug(String.format("Dropping page cache of file %s.", filePath));
+ // get a new reference to the shared DescriptorTypeTidy for this sstable
+ public static Ref<DescriptorTypeTidy> get(SSTableReader sstable)
+ {
+ Descriptor desc = sstable.descriptor;
+ if (sstable.openReason == OpenReason.EARLY)
+ desc = desc.asType(Descriptor.Type.TEMPLINK);
+ Ref<DescriptorTypeTidy> refc = lookup.get(desc);
+ if (refc != null)
+ return refc.ref();
+ final DescriptorTypeTidy tidy = new DescriptorTypeTidy(desc, sstable);
+ refc = new Ref<>(tidy, tidy);
+ Ref<?> ex = lookup.putIfAbsent(desc, refc);
+ assert ex == null;
+ return refc;
+ }
+ }
- CLibrary.trySkipCache(fd, 0, 0);
- }
- }
- catch (IOException e)
+ /**
+ * One instance per logical sstable. This both tracks shared cleanup and some shared state related
+ * to the sstable's lifecycle. All DescriptorTypeTidy instances, on construction, obtain a reference to us
+ * via our static get(). There should only ever be at most two such references extant at any one time,
+ * since only TMPLINK and FINAL type descriptors should be open as readers. When all files of both
+ * kinds have been released, this shared tidy will be performed.
+ */
+ static final class GlobalTidy implements Tidy
+ {
+ // keyed by FINAL descriptor, mapping to the shared GlobalTidy for that descriptor
+ static final ConcurrentMap<Descriptor, Ref<GlobalTidy>> lookup = new ConcurrentHashMap<>();
+
+ private final Descriptor desc;
+ // a single convenience property for getting the most recent version of an sstable, not related to tidying
+ private SSTableReader live;
+ // the readMeter that is shared between all instances of the sstable, and can be overridden in all of them
+ // at once also, for testing purposes
+ private RestorableMeter readMeter;
+ // the scheduled persistence of the readMeter, that we will cancel once all instances of this logical
+ // sstable have been released
+ private final ScheduledFuture readMeterSyncFuture;
+ // shared state managing if the logical sstable has been compacted; this is used in cleanup both here
+ // and in the FINAL type tidier
+ private final AtomicBoolean isCompacted;
+
+ GlobalTidy(final SSTableReader reader)
+ {
+ this.desc = reader.descriptor;
+ this.isCompacted = new AtomicBoolean();
+ this.live = reader;
+ // Don't track read rates for tables in the system keyspace and don't bother trying to load or persist
+ // the read meter when in client mode.
+ if (Keyspace.SYSTEM_KS.equals(desc.ksname) || Config.isClientMode())
{
- // we don't care if cache cleanup fails
+ readMeter = null;
+ readMeterSyncFuture = null;
+ return;
}
- finally
+
+ readMeter = SystemKeyspace.getSSTableReadMeter(desc.ksname, desc.cfname, desc.generation);
+ // sync the average read rate to system.sstable_activity every five minutes, starting one minute from now
+ readMeterSyncFuture = syncExecutor.scheduleAtFixedRate(new Runnable()
{
- FileUtils.closeQuietly(file);
- }
+ public void run()
+ {
+ if (!isCompacted.get())
+ {
+ meterSyncThrottle.acquire();
+ SystemKeyspace.persistSSTableReadMeter(desc.ksname, desc.cfname, desc.generation, readMeter);
+ }
+ }
+ }, 1, 5, TimeUnit.MINUTES);
}
public void tidy()
{
+ lookup.remove(desc);
if (readMeterSyncFuture != null)
- readMeterSyncFuture.cancel(false);
+ readMeterSyncFuture.cancel(true);
+ if (isCompacted.get())
+ SystemKeyspace.clearSSTableReadMeter(desc.ksname, desc.cfname, desc.generation);
+ // don't ideally want to dropPageCache for the file until all instances have been released
+ dropPageCache(desc.filenameFor(Component.DATA));
+ dropPageCache(desc.filenameFor(Component.PRIMARY_INDEX));
+ }
- synchronized (replaceLock)
- {
- boolean closeBf = true, closeSummary = true, closeFiles = true, deleteFiles = isCompacted.get();
+ public String name()
+ {
+ return desc.toString();
+ }
- if (replacedBy != null)
- {
- closeBf = replacedBy.bf != bf;
- closeSummary = replacedBy.indexSummary != indexSummary;
- closeFiles = replacedBy.dfile != dfile;
- // if the replacement sstablereader uses a different path, clean up our paths
- deleteFiles = !dfile.path.equals(replacedBy.dfile.path);
- }
+ // get a new reference to the shared GlobalTidy for this sstable
+ public static Ref<GlobalTidy> get(SSTableReader sstable)
+ {
+ Descriptor descriptor = sstable.descriptor;
+ Ref<GlobalTidy> refc = lookup.get(descriptor);
+ if (refc != null)
+ return refc.ref();
+ final GlobalTidy tidy = new GlobalTidy(sstable);
+ refc = new Ref<>(tidy, tidy);
+ Ref<?> ex = lookup.putIfAbsent(descriptor, refc);
+ assert ex == null;
+ return refc;
+ }
+ }
- if (replaces != null)
- {
- closeBf &= replaces.bf != bf;
- closeSummary &= replaces.indexSummary != indexSummary;
- closeFiles &= replaces.dfile != dfile;
- deleteFiles &= !dfile.path.equals(replaces.dfile.path);
- }
+ private static void dropPageCache(String filePath)
+ {
+ RandomAccessFile file = null;
- boolean deleteAll = false;
- if (isCompacted.get())
- {
- assert replacedBy == null;
- if (replaces != null && !deleteFiles)
- {
- replaces.tidy.replacedBy = null;
- replaces.tidy.deletingTask = deletingTask;
- replaces.markObsolete();
- }
- else
- {
- deleteAll = true;
- }
- }
- else
- {
- closeSummary &= indexSummary != null;
- if (replaces != null)
- replaces.tidy.replacedBy = replacedBy;
- if (replacedBy != null)
- replacedBy.tidy.replaces = replaces;
- }
+ try
+ {
+ file = new RandomAccessFile(filePath, "r");
- scheduleTidy(closeBf, closeSummary, closeFiles, deleteFiles, deleteAll);
- }
- }
+ int fd = CLibrary.getfd(file.getFD());
- private void scheduleTidy(final boolean closeBf, final boolean closeSummary, final boolean closeFiles, final boolean deleteFiles, final boolean deleteAll)
- {
- final ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(metadata.cfId);
- final OpOrder.Barrier barrier;
- if (cfs != null)
+ if (fd > 0)
{
- barrier = cfs.readOrdering.newBarrier();
- barrier.issue();
- }
- else
- barrier = null;
+ if (logger.isDebugEnabled())
+ logger.debug(String.format("Dropping page cache of file %s.", filePath));
- ScheduledExecutors.nonPeriodicTasks.execute(new Runnable()
- {
- public void run()
- {
- if (barrier != null)
- barrier.await();
- if (closeBf)
- bf.close();
- if (closeSummary)
- indexSummary.close();
- if (closeFiles)
- {
- ifile.cleanup();
- dfile.cleanup();
- }
- if (runOnClose != null)
- runOnClose.run();
- if (deleteAll)
- {
- /**
- * Do the OS a favour and suggest (using fadvice call) that we
- * don't want to see pages of this SSTable in memory anymore.
- *
- * NOTE: We can't use madvice in java because it requires the address of
- * the mapping, so instead we always open a file and run fadvice(fd, 0, 0) on it
- */
- dropPageCache();
- deletingTask.run();
- }
- else if (deleteFiles)
- {
- FileUtils.deleteWithConfirm(new File(dfile.path));
- FileUtils.deleteWithConfirm(new File(ifile.path));
- }
- }
- });
+ CLibrary.trySkipCache(fd, 0, 0);
+ }
+ }
+ catch (IOException e)
+ {
+ // we don't care if cache cleanup fails
+ }
+ finally
+ {
+ FileUtils.closeQuietly(file);
}
}
-
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java b/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
index 7784b18..6356d4d 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableRewriter.java
@@ -183,14 +183,14 @@ public class SSTableRewriter
for (SSTableReader sstable : finished)
{
sstable.markObsolete();
- sstable.sharedRef().release();
+ sstable.selfRef().release();
}
// abort the writers
for (Finished finished : finishedEarly)
{
boolean opened = finished.reader != null;
- finished.writer.abort(!opened);
+ finished.writer.abort();
if (opened)
{
// if we've already been opened, add ourselves to the discard pile
@@ -361,7 +361,7 @@ public class SSTableRewriter
}
else
{
- f.writer.abort(true);
+ f.writer.abort();
assert f.reader == null;
}
}
@@ -380,9 +380,9 @@ public class SSTableRewriter
{
for (SSTableReader reader : discard)
{
- if (reader.getCurrentReplacement() == null)
+ if (reader.getCurrentReplacement() == reader)
reader.markObsolete();
- reader.sharedRef().release();
+ reader.selfRef().release();
}
}
else
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java b/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
index cc60594..d430314 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
@@ -17,7 +17,6 @@
*/
package org.apache.cassandra.io.sstable;
-import java.io.Closeable;
import java.io.DataInput;
import java.io.File;
import java.io.FileOutputStream;
@@ -339,16 +338,12 @@ public class SSTableWriter extends SSTable
*/
public void abort()
{
- abort(true);
- }
- public void abort(boolean closeBf)
- {
assert descriptor.type.isTemporary;
if (iwriter == null && dataFile == null)
return;
if (iwriter != null)
- iwriter.abort(closeBf);
+ iwriter.abort();
if (dataFile!= null)
dataFile.abort();
@@ -407,7 +402,7 @@ public class SSTableWriter extends SSTable
components, metadata,
partitioner, ifile,
dfile, iwriter.summary.build(partitioner, exclusiveUpperBoundOfReadableIndex),
- iwriter.bf, maxDataAge, sstableMetadata, SSTableReader.OpenReason.EARLY);
+ iwriter.bf.sharedCopy(), maxDataAge, sstableMetadata, SSTableReader.OpenReason.EARLY);
// now it's open, find the ACTUAL last readable key (i.e. for which the data file has also been flushed)
sstable.first = getMinimalKey(first);
@@ -416,7 +411,7 @@ public class SSTableWriter extends SSTable
if (inclusiveUpperBoundOfReadableData == null)
{
// Prevent leaving tmplink files on disk
- sstable.sharedRef().release();
+ sstable.selfRef().release();
return null;
}
int offset = 2;
@@ -428,7 +423,7 @@ public class SSTableWriter extends SSTable
inclusiveUpperBoundOfReadableData = iwriter.getMaxReadableKey(offset++);
if (inclusiveUpperBoundOfReadableData == null)
{
- sstable.sharedRef().release();
+ sstable.selfRef().release();
return null;
}
}
@@ -438,14 +433,17 @@ public class SSTableWriter extends SSTable
public static enum FinishType
{
- NORMAL(SSTableReader.OpenReason.NORMAL),
- EARLY(SSTableReader.OpenReason.EARLY), // no renaming
- FINISH_EARLY(SSTableReader.OpenReason.NORMAL); // tidy up an EARLY finish
+ CLOSE(null, true),
+ NORMAL(SSTableReader.OpenReason.NORMAL, true),
+ EARLY(SSTableReader.OpenReason.EARLY, false), // no renaming
+ FINISH_EARLY(SSTableReader.OpenReason.NORMAL, true); // tidy up an EARLY finish
final SSTableReader.OpenReason openReason;
- FinishType(SSTableReader.OpenReason openReason)
+ public final boolean isFinal;
+ FinishType(SSTableReader.OpenReason openReason, boolean isFinal)
{
this.openReason = openReason;
+ this.isFinal = isFinal;
}
}
@@ -461,6 +459,7 @@ public class SSTableWriter extends SSTable
public SSTableReader finish(FinishType finishType, long maxDataAge, long repairedAt)
{
+ assert finishType != FinishType.CLOSE;
Pair<Descriptor, StatsMetadata> p;
p = close(finishType, repairedAt < 0 ? this.repairedAt : repairedAt);
@@ -480,16 +479,16 @@ public class SSTableWriter extends SSTable
ifile,
dfile,
iwriter.summary.build(partitioner),
- iwriter.bf,
+ iwriter.bf.sharedCopy(),
maxDataAge,
metadata,
finishType.openReason);
sstable.first = getMinimalKey(first);
sstable.last = getMinimalKey(last);
- switch (finishType)
+ if (finishType.isFinal)
{
- case NORMAL: case FINISH_EARLY:
+ iwriter.bf.close();
// try to save the summaries to disk
sstable.saveSummary(iwriter.builder, dbuilder);
iwriter = null;
@@ -501,16 +500,18 @@ public class SSTableWriter extends SSTable
// Close the writer and return the descriptor to the new sstable and it's metadata
public Pair<Descriptor, StatsMetadata> close()
{
- return close(FinishType.NORMAL, this.repairedAt);
+ return close(FinishType.CLOSE, this.repairedAt);
}
private Pair<Descriptor, StatsMetadata> close(FinishType type, long repairedAt)
{
switch (type)
{
- case EARLY: case NORMAL:
+ case EARLY: case CLOSE: case NORMAL:
iwriter.close();
dataFile.close();
+ if (type == FinishType.CLOSE)
+ iwriter.bf.close();
}
// write sstable statistics
@@ -521,9 +522,8 @@ public class SSTableWriter extends SSTable
// remove the 'tmp' marker from all components
Descriptor descriptor = this.descriptor;
- switch (type)
+ if (type.isFinal)
{
- case NORMAL: case FINISH_EARLY:
dataFile.writeFullChecksum(descriptor);
writeMetadata(descriptor, metadataComponents);
// save the table of components
@@ -629,11 +629,10 @@ public class SSTableWriter extends SSTable
builder.addPotentialBoundary(indexPosition);
}
- public void abort(boolean closeBf)
+ public void abort()
{
indexFile.abort();
- if (closeBf)
- bf.close();
+ bf.close();
}
/**
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java b/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
index 57f465f..8334965 100644
--- a/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/BufferedPoolingSegmentedFile.java
@@ -25,7 +25,17 @@ public class BufferedPoolingSegmentedFile extends PoolingSegmentedFile
{
public BufferedPoolingSegmentedFile(String path, long length)
{
- super(path, length);
+ super(new Cleanup(path), path, length);
+ }
+
+ private BufferedPoolingSegmentedFile(BufferedPoolingSegmentedFile copy)
+ {
+ super(copy);
+ }
+
+ public BufferedPoolingSegmentedFile sharedCopy()
+ {
+ return new BufferedPoolingSegmentedFile(this);
}
public static class Builder extends SegmentedFile.Builder
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java b/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
index 2f715da..c29bbf3 100644
--- a/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/BufferedSegmentedFile.java
@@ -20,12 +20,30 @@ package org.apache.cassandra.io.util;
import java.io.File;
import org.apache.cassandra.io.sstable.SSTableWriter;
+import org.apache.cassandra.utils.concurrent.SharedCloseable;
public class BufferedSegmentedFile extends SegmentedFile
{
public BufferedSegmentedFile(String path, long length)
{
- super(path, length);
+ super(new Cleanup(path), path, length);
+ }
+
+ private BufferedSegmentedFile(BufferedSegmentedFile copy)
+ {
+ super(copy);
+ }
+
+ private static class Cleanup extends SegmentedFile.Cleanup
+ {
+ protected Cleanup(String path)
+ {
+ super(path);
+ }
+ public void tidy() throws Exception
+ {
+
+ }
}
public static class Builder extends SegmentedFile.Builder
@@ -49,7 +67,8 @@ public class BufferedSegmentedFile extends SegmentedFile
return reader;
}
- public void cleanup()
+ public BufferedSegmentedFile sharedCopy()
{
+ return new BufferedSegmentedFile(this);
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java b/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
index 11d091a..94d23bf 100644
--- a/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/CompressedPoolingSegmentedFile.java
@@ -28,10 +28,31 @@ public class CompressedPoolingSegmentedFile extends PoolingSegmentedFile impleme
public CompressedPoolingSegmentedFile(String path, CompressionMetadata metadata)
{
- super(path, metadata.dataLength, metadata.compressedFileLength);
+ super(new Cleanup(path, metadata), path, metadata.dataLength, metadata.compressedFileLength);
this.metadata = metadata;
}
+ private CompressedPoolingSegmentedFile(CompressedPoolingSegmentedFile copy)
+ {
+ super(copy);
+ this.metadata = copy.metadata;
+ }
+
+ protected static final class Cleanup extends PoolingSegmentedFile.Cleanup
+ {
+ final CompressionMetadata metadata;
+ protected Cleanup(String path, CompressionMetadata metadata)
+ {
+ super(path);
+ this.metadata = metadata;
+ }
+ public void tidy() throws Exception
+ {
+ super.tidy();
+ metadata.close();
+ }
+ }
+
public static class Builder extends CompressedSegmentedFile.Builder
{
public Builder(CompressedSequentialWriter writer)
@@ -59,10 +80,8 @@ public class CompressedPoolingSegmentedFile extends PoolingSegmentedFile impleme
return metadata;
}
- @Override
- public void cleanup()
+ public CompressedPoolingSegmentedFile sharedCopy()
{
- super.cleanup();
- metadata.close();
+ return new CompressedPoolingSegmentedFile(this);
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java b/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
index b788715..0c20bb9 100644
--- a/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/CompressedSegmentedFile.java
@@ -28,10 +28,35 @@ public class CompressedSegmentedFile extends SegmentedFile implements ICompresse
public CompressedSegmentedFile(String path, CompressionMetadata metadata)
{
- super(path, metadata.dataLength, metadata.compressedFileLength);
+ super(new Cleanup(path, metadata), path, metadata.dataLength, metadata.compressedFileLength);
this.metadata = metadata;
}
+ private CompressedSegmentedFile(CompressedSegmentedFile copy)
+ {
+ super(copy);
+ this.metadata = copy.metadata;
+ }
+
+ private static final class Cleanup extends SegmentedFile.Cleanup
+ {
+ final CompressionMetadata metadata;
+ protected Cleanup(String path, CompressionMetadata metadata)
+ {
+ super(path);
+ this.metadata = metadata;
+ }
+ public void tidy() throws Exception
+ {
+ metadata.close();
+ }
+ }
+
+ public CompressedSegmentedFile sharedCopy()
+ {
+ return new CompressedSegmentedFile(this);
+ }
+
public static class Builder extends SegmentedFile.Builder
{
protected final CompressedSequentialWriter writer;
@@ -70,9 +95,4 @@ public class CompressedSegmentedFile extends SegmentedFile implements ICompresse
{
return metadata;
}
-
- public void cleanup()
- {
- metadata.close();
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/Memory.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/Memory.java b/src/java/org/apache/cassandra/io/util/Memory.java
index 5306433..3874669 100644
--- a/src/java/org/apache/cassandra/io/util/Memory.java
+++ b/src/java/org/apache/cassandra/io/util/Memory.java
@@ -17,6 +17,7 @@
*/
package org.apache.cassandra.io.util;
+import java.io.Closeable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -30,7 +31,7 @@ import sun.nio.ch.DirectBuffer;
/**
* An off-heap region of memory that must be manually free'd when no longer needed.
*/
-public class Memory
+public class Memory implements AutoCloseable
{
private static final Unsafe unsafe = NativeAllocator.unsafe;
private static final IAllocator allocator = DatabaseDescriptor.getoffHeapMemoryAllocator();
@@ -302,6 +303,11 @@ public class Memory
peer = 0;
}
+ public void close() throws Exception
+ {
+ free();
+ }
+
public long size()
{
assert peer != 0;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java b/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
index 3b2cc98..8b4ae9d 100644
--- a/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/MmappedSegmentedFile.java
@@ -47,10 +47,21 @@ public class MmappedSegmentedFile extends SegmentedFile
public MmappedSegmentedFile(String path, long length, Segment[] segments)
{
- super(path, length);
+ super(new Cleanup(path, segments), path, length);
this.segments = segments;
}
+ private MmappedSegmentedFile(MmappedSegmentedFile copy)
+ {
+ super(copy);
+ this.segments = copy.segments;
+ }
+
+ public MmappedSegmentedFile sharedCopy()
+ {
+ return new MmappedSegmentedFile(this);
+ }
+
/**
* @return The segment entry for the given position.
*/
@@ -85,31 +96,41 @@ public class MmappedSegmentedFile extends SegmentedFile
return file;
}
- public void cleanup()
+ private static final class Cleanup extends SegmentedFile.Cleanup
{
- if (!FileUtils.isCleanerAvailable())
- return;
+ final Segment[] segments;
+ protected Cleanup(String path, Segment[] segments)
+ {
+ super(path);
+ this.segments = segments;
+ }
+
+ public void tidy()
+ {
+ if (!FileUtils.isCleanerAvailable())
+ return;
/*
* Try forcing the unmapping of segments using undocumented unsafe sun APIs.
* If this fails (non Sun JVM), we'll have to wait for the GC to finalize the mapping.
* If this works and a thread tries to access any segment, hell will unleash on earth.
*/
- try
- {
- for (Segment segment : segments)
+ try
{
- if (segment.right == null)
- continue;
- FileUtils.clean(segment.right);
+ for (Segment segment : segments)
+ {
+ if (segment.right == null)
+ continue;
+ FileUtils.clean(segment.right);
+ }
+ logger.debug("All segments have been unmapped successfully");
+ }
+ catch (Exception e)
+ {
+ JVMStabilityInspector.inspectThrowable(e);
+ // This is not supposed to happen
+ logger.error("Error while unmapping segments", e);
}
- logger.debug("All segments have been unmapped successfully");
- }
- catch (Exception e)
- {
- JVMStabilityInspector.inspectThrowable(e);
- // This is not supposed to happen
- logger.error("Error while unmapping segments", e);
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java b/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java
index 01f4e31..daca22f 100644
--- a/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/PoolingSegmentedFile.java
@@ -21,15 +21,35 @@ import org.apache.cassandra.service.FileCacheService;
public abstract class PoolingSegmentedFile extends SegmentedFile
{
- final FileCacheService.CacheKey cacheKey = new FileCacheService.CacheKey();
- protected PoolingSegmentedFile(String path, long length)
+ final FileCacheService.CacheKey cacheKey;
+ protected PoolingSegmentedFile(Cleanup cleanup, String path, long length)
{
- super(path, length);
+ this(cleanup, path, length, length);
}
- protected PoolingSegmentedFile(String path, long length, long onDiskLength)
+ protected PoolingSegmentedFile(Cleanup cleanup, String path, long length, long onDiskLength)
{
- super(path, length, onDiskLength);
+ super(cleanup, path, length, onDiskLength);
+ cacheKey = cleanup.cacheKey;
+ }
+
+ public PoolingSegmentedFile(PoolingSegmentedFile copy)
+ {
+ super(copy);
+ cacheKey = copy.cacheKey;
+ }
+
+ protected static class Cleanup extends SegmentedFile.Cleanup
+ {
+ final FileCacheService.CacheKey cacheKey = new FileCacheService.CacheKey();
+ protected Cleanup(String path)
+ {
+ super(path);
+ }
+ public void tidy() throws Exception
+ {
+ FileCacheService.instance.invalidate(cacheKey, path);
+ }
}
public FileDataInput getSegment(long position)
@@ -49,9 +69,4 @@ public abstract class PoolingSegmentedFile extends SegmentedFile
{
FileCacheService.instance.put(cacheKey, reader);
}
-
- public void cleanup()
- {
- FileCacheService.instance.invalidate(cacheKey, path);
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/io/util/SegmentedFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/util/SegmentedFile.java b/src/java/org/apache/cassandra/io/util/SegmentedFile.java
index badae56..d557b72 100644
--- a/src/java/org/apache/cassandra/io/util/SegmentedFile.java
+++ b/src/java/org/apache/cassandra/io/util/SegmentedFile.java
@@ -31,6 +31,8 @@ import org.apache.cassandra.io.FSReadError;
import org.apache.cassandra.io.compress.CompressedSequentialWriter;
import org.apache.cassandra.io.sstable.SSTableWriter;
import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.concurrent.RefCounted;
+import org.apache.cassandra.utils.concurrent.SharedCloseableImpl;
/**
* Abstracts a read-only file that has been split into segments, each of which can be represented by an independent
@@ -41,7 +43,7 @@ import org.apache.cassandra.utils.Pair;
* would need to be longer than 2GB, that segment will not be mmap'd, and a new RandomAccessFile will be created for
* each access to that segment.
*/
-public abstract class SegmentedFile
+public abstract class SegmentedFile extends SharedCloseableImpl
{
public final String path;
public final long length;
@@ -53,18 +55,43 @@ public abstract class SegmentedFile
/**
* Use getBuilder to get a Builder to construct a SegmentedFile.
*/
- SegmentedFile(String path, long length)
+ SegmentedFile(Cleanup cleanup, String path, long length)
{
- this(path, length, length);
+ this(cleanup, path, length, length);
}
- protected SegmentedFile(String path, long length, long onDiskLength)
+ protected SegmentedFile(Cleanup cleanup, String path, long length, long onDiskLength)
{
+ super(cleanup);
this.path = new File(path).getAbsolutePath();
this.length = length;
this.onDiskLength = onDiskLength;
}
+ public SegmentedFile(SegmentedFile copy)
+ {
+ super(copy);
+ path = copy.path;
+ length = copy.length;
+ onDiskLength = copy.onDiskLength;
+ }
+
+ protected static abstract class Cleanup implements RefCounted.Tidy
+ {
+ final String path;
+ protected Cleanup(String path)
+ {
+ this.path = path;
+ }
+
+ public String name()
+ {
+ return path;
+ }
+ }
+
+ public abstract SegmentedFile sharedCopy();
+
/**
* @return A SegmentedFile.Builder.
*/
@@ -96,11 +123,6 @@ public abstract class SegmentedFile
}
/**
- * Do whatever action is needed to reclaim ressources used by this SegmentedFile.
- */
- public abstract void cleanup();
-
- /**
* Collects potential segmentation points in an underlying file, and builds a SegmentedFile to represent it.
*/
public static abstract class Builder
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/service/ActiveRepairService.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/service/ActiveRepairService.java b/src/java/org/apache/cassandra/service/ActiveRepairService.java
index 15e7641..bf1cdd6 100644
--- a/src/java/org/apache/cassandra/service/ActiveRepairService.java
+++ b/src/java/org/apache/cassandra/service/ActiveRepairService.java
@@ -432,7 +432,7 @@ public class ActiveRepairService
{
Set<SSTableReader> sstables = sstableMap.get(cfId);
Iterator<SSTableReader> sstableIterator = sstables.iterator();
- ImmutableMap.Builder<SSTableReader, Ref> references = ImmutableMap.builder();
+ ImmutableMap.Builder<SSTableReader, Ref<SSTableReader>> references = ImmutableMap.builder();
while (sstableIterator.hasNext())
{
SSTableReader sstable = sstableIterator.next();
@@ -442,7 +442,7 @@ public class ActiveRepairService
}
else
{
- Ref ref = sstable.tryRef();
+ Ref<SSTableReader> ref = sstable.tryRef();
if (ref == null)
sstableIterator.remove();
else
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/streaming/StreamSession.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamSession.java b/src/java/org/apache/cassandra/streaming/StreamSession.java
index 6108dea..a9f5075 100644
--- a/src/java/org/apache/cassandra/streaming/StreamSession.java
+++ b/src/java/org/apache/cassandra/streaming/StreamSession.java
@@ -353,7 +353,7 @@ public class StreamSession implements IEndpointStateChangeSubscriber
public static class SSTableStreamingSections
{
public final SSTableReader sstable;
- public final Ref ref;
+ public final Ref<SSTableReader> ref;
public final List<Pair<Long, Long>> sections;
public final long estimatedKeys;
public final long repairedAt;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java b/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
index 5ebf289..069e97f 100644
--- a/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
+++ b/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
@@ -62,7 +62,7 @@ public class OutgoingFileMessage extends StreamMessage
public final FileMessageHeader header;
public final SSTableReader sstable;
- public final Ref ref;
+ public final Ref<SSTableReader> ref;
public OutgoingFileMessage(SSTableReader sstable, Ref ref, int sequenceNumber, long estimatedKeys, List<Pair<Long, Long>> sections, long repairedAt)
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/tools/StandaloneScrubber.java b/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
index 1bc2674..d420218 100644
--- a/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
+++ b/src/java/org/apache/cassandra/tools/StandaloneScrubber.java
@@ -121,7 +121,7 @@ public class StandaloneScrubber
// Remove the sstable (it's been copied by scrub and snapshotted)
sstable.markObsolete();
- sstable.sharedRef().release();
+ sstable.selfRef().release();
}
catch (Exception e)
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java b/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java
index cc162d4..1a029e5 100644
--- a/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java
+++ b/src/java/org/apache/cassandra/utils/AlwaysPresentFilter.java
@@ -32,6 +32,11 @@ public class AlwaysPresentFilter implements IFilter
public void close() { }
+ public IFilter sharedCopy()
+ {
+ return this;
+ }
+
public long serializedSize() { return 0; }
@Override
[6/7] cassandra git commit: Merge branch 'cassandra-2.1' into trunk
Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/cassandra/blob/02c34893/src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
----------------------------------------------------------------------
diff --cc src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
index de2bbc6,0000000..889ade3
mode 100644,000000..100644
--- a/src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
+++ b/src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
@@@ -1,1908 -1,0 +1,2046 @@@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.io.sstable.format;
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Iterators;
+import com.google.common.collect.Ordering;
+import com.google.common.primitives.Longs;
+import com.google.common.util.concurrent.RateLimiter;
+
+import com.clearspring.analytics.stream.cardinality.CardinalityMergeException;
+import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus;
+import com.clearspring.analytics.stream.cardinality.ICardinality;
+import org.apache.cassandra.cache.CachingOptions;
+import org.apache.cassandra.cache.InstrumentingCache;
+import org.apache.cassandra.cache.KeyCacheKey;
+import org.apache.cassandra.concurrent.DebuggableThreadPoolExecutor;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.*;
+import org.apache.cassandra.db.*;
+import org.apache.cassandra.db.columniterator.OnDiskAtomIterator;
+import org.apache.cassandra.db.commitlog.ReplayPosition;
+import org.apache.cassandra.db.composites.CellName;
+import org.apache.cassandra.db.filter.ColumnSlice;
+import org.apache.cassandra.db.index.SecondaryIndex;
+import org.apache.cassandra.dht.*;
+import org.apache.cassandra.io.compress.CompressedRandomAccessReader;
+import org.apache.cassandra.io.compress.CompressedThrottledReader;
+import org.apache.cassandra.io.compress.CompressionMetadata;
+import org.apache.cassandra.io.sstable.*;
+import org.apache.cassandra.io.sstable.metadata.*;
+import org.apache.cassandra.io.util.*;
+import org.apache.cassandra.metrics.RestorableMeter;
+import org.apache.cassandra.metrics.StorageMetrics;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.service.CacheService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.*;
+import org.apache.cassandra.utils.concurrent.OpOrder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.cassandra.utils.concurrent.Ref;
+import org.apache.cassandra.utils.concurrent.RefCounted;
+
+import static org.apache.cassandra.db.Directories.SECONDARY_INDEX_NAME_SEPARATOR;
+
+/**
- * SSTableReaders are open()ed by Keyspace.onStart; after that they are created by SSTableWriter.renameAndOpen.
- * Do not re-call open() on existing SSTable files; use the references kept by ColumnFamilyStore post-start instead.
++ * An SSTableReader can be constructed in a number of places, but typically is either
++ * read from disk at startup, or constructed from a flushed memtable, or after compaction
++ * to replace some existing sstables. However once created, an sstablereader may also be modified.
++ *
++ * A reader's OpenReason describes its current stage in its lifecycle, as follows:
++ *
++ * NORMAL
++ * From: None => Reader has been read from disk, either at startup or from a flushed memtable
++ * EARLY => Reader is the final result of a compaction
++ * MOVED_START => Reader WAS being compacted, but this failed and it has been restored to NORMAL status
++ *
++ * EARLY
++ * From: None => Reader is a compaction replacement that is either incomplete and has been opened
++ * to represent its partial result status, or has been finished but the compaction
++ * it is a part of has not yet completed fully
++ * EARLY => Same as from None, only it is not the first time it has been
++ *
++ * MOVED_START
++ * From: NORMAL => Reader is being compacted. This compaction has not finished, but the compaction result
++ * is either partially or fully opened, to either partially or fully replace this reader.
++ * This reader's start key has been updated to represent this, so that reads only hit
++ * one or the other reader.
++ *
++ * METADATA_CHANGE
++ * From: NORMAL => Reader has seen low traffic and the amount of memory available for index summaries is
++ * constrained, so its index summary has been downsampled.
++ * METADATA_CHANGE => Same
++ *
++ * Note that in parallel to this, there are two different Descriptor types; TMPLINK and FINAL; the latter corresponds
++ * to NORMAL state readers and all readers that replace a NORMAL one. TMPLINK is used for EARLY state readers and
++ * no others.
++ *
++ * When a reader is being compacted, if the result is large its replacement may be opened as EARLY before compaction
++ * completes in order to present the result to consumers earlier. In this case the reader will itself be changed to
++ * a MOVED_START state, where its start no longer represents its on-disk minimum key. This is to permit reads to be
++ * directed to only one reader when the two represent the same data. The EARLY file can represent a compaction result
++ * that is either partially complete and still in-progress, or a complete and immutable sstable that is part of a larger
++ * macro compaction action that has not yet fully completed.
++ *
++ * Currently ALL compaction results at least briefly go through an EARLY open state prior to completion, regardless
++ * of if early opening is enabled.
++ *
++ * Since a reader can be created multiple times over the same shared underlying resources, and the exact resources
++ * it shares between each instance differ subtly, we track the lifetime of any underlying resource with its own
++ * reference count, which each instance takes a Ref to. Each instance then tracks references to itself, and once these
++ * all expire it releases its Refs to these underlying resources.
++ *
++ * There is some shared cleanup behaviour needed only once all sstablereaders in a certain stage of their lifecycle
++ * (i.e. EARLY or NORMAL opening), and some that must only occur once all readers of any kind over a single logical
++ * sstable have expired. These are managed by the TypeTidy and GlobalTidy classes at the bottom, and are effectively
++ * managed as another resource each instance tracks its own Ref instance to, to ensure all of these resources are
++ * cleaned up safely and can be debugged otherwise.
++ *
++ * TODO: fill in details about DataTracker and lifecycle interactions for tools, and for compaction strategies
+ */
- public abstract class SSTableReader extends SSTable implements RefCounted
++public abstract class SSTableReader extends SSTable implements RefCounted<SSTableReader>
+{
+ private static final Logger logger = LoggerFactory.getLogger(SSTableReader.class);
+
+ private static final ScheduledThreadPoolExecutor syncExecutor = new ScheduledThreadPoolExecutor(1);
+ private static final RateLimiter meterSyncThrottle = RateLimiter.create(100.0);
+
+ public static final Comparator<SSTableReader> maxTimestampComparator = new Comparator<SSTableReader>()
+ {
+ public int compare(SSTableReader o1, SSTableReader o2)
+ {
+ long ts1 = o1.getMaxTimestamp();
+ long ts2 = o2.getMaxTimestamp();
+ return (ts1 > ts2 ? -1 : (ts1 == ts2 ? 0 : 1));
+ }
+ };
+
+ public static final Comparator<SSTableReader> sstableComparator = new Comparator<SSTableReader>()
+ {
+ public int compare(SSTableReader o1, SSTableReader o2)
+ {
+ return o1.first.compareTo(o2.first);
+ }
+ };
+
+ public static final Ordering<SSTableReader> sstableOrdering = Ordering.from(sstableComparator);
+
+ /**
+ * maxDataAge is a timestamp in local server time (e.g. System.currentTimeMilli) which represents an upper bound
+ * to the newest piece of data stored in the sstable. In other words, this sstable does not contain items created
+ * later than maxDataAge.
+ *
+ * The field is not serialized to disk, so relying on it for more than what truncate does is not advised.
+ *
+ * When a new sstable is flushed, maxDataAge is set to the time of creation.
+ * When a sstable is created from compaction, maxDataAge is set to max of all merged sstables.
+ *
+ * The age is in milliseconds since epoc and is local to this host.
+ */
+ public final long maxDataAge;
+
+ public enum OpenReason
+ {
+ NORMAL,
+ EARLY,
- METADATA_CHANGE
++ METADATA_CHANGE,
++ MOVED_START
+ }
+
+ public final OpenReason openReason;
+
+ // indexfile and datafile: might be null before a call to load()
+ protected SegmentedFile ifile;
+ protected SegmentedFile dfile;
-
+ protected IndexSummary indexSummary;
+ protected IFilter bf;
+
+ protected final RowIndexEntry.IndexSerializer rowIndexEntrySerializer;
+
+ protected InstrumentingCache<KeyCacheKey, RowIndexEntry> keyCache;
+
+ protected final BloomFilterTracker bloomFilterTracker = new BloomFilterTracker();
+
+ // technically isCompacted is not necessary since it should never be unreferenced unless it is also compacted,
+ // but it seems like a good extra layer of protection against reference counting bugs to not delete data based on that alone
- protected final AtomicBoolean isCompacted = new AtomicBoolean(false);
+ protected final AtomicBoolean isSuspect = new AtomicBoolean(false);
+
+ // not final since we need to be able to change level on a file.
+ protected volatile StatsMetadata sstableMetadata;
+
+ protected final AtomicLong keyCacheHit = new AtomicLong(0);
+ protected final AtomicLong keyCacheRequest = new AtomicLong(0);
+
- private final Tidier tidy = new Tidier();
- private final RefCounted refCounted = RefCounted.Impl.get(tidy);
++ private final InstanceTidier tidy = new InstanceTidier(descriptor, metadata);
++ private final Ref<SSTableReader> selfRef = new Ref<>(this, tidy);
+
- @VisibleForTesting
- public RestorableMeter readMeter;
- protected ScheduledFuture readMeterSyncFuture;
++ private RestorableMeter readMeter;
+
+ /**
+ * Calculate approximate key count.
+ * If cardinality estimator is available on all given sstables, then this method use them to estimate
+ * key count.
+ * If not, then this uses index summaries.
+ *
+ * @param sstables SSTables to calculate key count
+ * @return estimated key count
+ */
+ public static long getApproximateKeyCount(Collection<SSTableReader> sstables)
+ {
+ long count = -1;
+
+ // check if cardinality estimator is available for all SSTables
+ boolean cardinalityAvailable = !sstables.isEmpty() && Iterators.all(sstables.iterator(), new Predicate<SSTableReader>()
+ {
+ public boolean apply(SSTableReader sstable)
+ {
+ return sstable.descriptor.version.hasNewStatsFile();
+ }
+ });
+
+ // if it is, load them to estimate key count
+ if (cardinalityAvailable)
+ {
+ boolean failed = false;
+ ICardinality cardinality = null;
+ for (SSTableReader sstable : sstables)
+ {
+ try
+ {
+ CompactionMetadata metadata = (CompactionMetadata) sstable.descriptor.getMetadataSerializer().deserialize(sstable.descriptor, MetadataType.COMPACTION);
+ assert metadata != null : sstable.getFilename();
+ if (cardinality == null)
+ cardinality = metadata.cardinalityEstimator;
+ else
+ cardinality = cardinality.merge(metadata.cardinalityEstimator);
+ }
+ catch (IOException e)
+ {
+ logger.warn("Reading cardinality from Statistics.db failed.", e);
+ failed = true;
+ break;
+ }
+ catch (CardinalityMergeException e)
+ {
+ logger.warn("Cardinality merge failed.", e);
+ failed = true;
+ break;
+ }
+ }
+ if (cardinality != null && !failed)
+ count = cardinality.cardinality();
+ }
+
+ // if something went wrong above or cardinality is not available, calculate using index summary
+ if (count < 0)
+ {
+ for (SSTableReader sstable : sstables)
+ count += sstable.estimatedKeys();
+ }
+ return count;
+ }
+
+ /**
+ * Estimates how much of the keys we would keep if the sstables were compacted together
+ */
+ public static double estimateCompactionGain(Set<SSTableReader> overlapping)
+ {
+ Set<ICardinality> cardinalities = new HashSet<>(overlapping.size());
+ for (SSTableReader sstable : overlapping)
+ {
+ try
+ {
+ ICardinality cardinality = ((CompactionMetadata) sstable.descriptor.getMetadataSerializer().deserialize(sstable.descriptor, MetadataType.COMPACTION)).cardinalityEstimator;
+ if (cardinality != null)
+ cardinalities.add(cardinality);
+ else
+ logger.debug("Got a null cardinality estimator in: "+sstable.getFilename());
+ }
+ catch (IOException e)
+ {
+ logger.warn("Could not read up compaction metadata for " + sstable, e);
+ }
+ }
+ long totalKeyCountBefore = 0;
+ for (ICardinality cardinality : cardinalities)
+ {
+ totalKeyCountBefore += cardinality.cardinality();
+ }
+ if (totalKeyCountBefore == 0)
+ return 1;
+
+ long totalKeyCountAfter = mergeCardinalities(cardinalities).cardinality();
+ logger.debug("Estimated compaction gain: {}/{}={}", totalKeyCountAfter, totalKeyCountBefore, ((double)totalKeyCountAfter)/totalKeyCountBefore);
+ return ((double)totalKeyCountAfter)/totalKeyCountBefore;
+ }
+
+ private static ICardinality mergeCardinalities(Collection<ICardinality> cardinalities)
+ {
+ ICardinality base = new HyperLogLogPlus(13, 25); // see MetadataCollector.cardinality
+ try
+ {
+ base = base.merge(cardinalities.toArray(new ICardinality[cardinalities.size()]));
+ }
+ catch (CardinalityMergeException e)
+ {
+ logger.warn("Could not merge cardinalities", e);
+ }
+ return base;
+ }
+
+ public static SSTableReader open(Descriptor descriptor) throws IOException
+ {
+ CFMetaData metadata;
+ if (descriptor.cfname.contains(SECONDARY_INDEX_NAME_SEPARATOR))
+ {
+ int i = descriptor.cfname.indexOf(SECONDARY_INDEX_NAME_SEPARATOR);
+ String parentName = descriptor.cfname.substring(0, i);
+ CFMetaData parent = Schema.instance.getCFMetaData(descriptor.ksname, parentName);
+ ColumnDefinition def = parent.getColumnDefinitionForIndex(descriptor.cfname.substring(i + 1));
+ metadata = CFMetaData.newIndexMetadata(parent, def, SecondaryIndex.getIndexComparator(parent, def));
+ }
+ else
+ {
+ metadata = Schema.instance.getCFMetaData(descriptor.ksname, descriptor.cfname);
+ }
+ return open(descriptor, metadata);
+ }
+
+ public static SSTableReader open(Descriptor desc, CFMetaData metadata) throws IOException
+ {
+ IPartitioner p = desc.cfname.contains(SECONDARY_INDEX_NAME_SEPARATOR)
+ ? new LocalPartitioner(metadata.getKeyValidator())
+ : StorageService.getPartitioner();
+ return open(desc, componentsFor(desc), metadata, p);
+ }
+
+ public static SSTableReader open(Descriptor descriptor, Set<Component> components, CFMetaData metadata, IPartitioner partitioner) throws IOException
+ {
+ return open(descriptor, components, metadata, partitioner, true);
+ }
+
+ public static SSTableReader openNoValidation(Descriptor descriptor, Set<Component> components, CFMetaData metadata) throws IOException
+ {
+ return open(descriptor, components, metadata, StorageService.getPartitioner(), false);
+ }
+
+ /**
+ * Open SSTable reader to be used in batch mode(such as sstableloader).
+ *
+ * @param descriptor
+ * @param components
+ * @param metadata
+ * @param partitioner
+ * @return opened SSTableReader
+ * @throws IOException
+ */
+ public static SSTableReader openForBatch(Descriptor descriptor, Set<Component> components, CFMetaData metadata, IPartitioner partitioner) throws IOException
+ {
+ // Minimum components without which we can't do anything
+ assert components.contains(Component.DATA) : "Data component is missing for sstable" + descriptor;
+ assert components.contains(Component.PRIMARY_INDEX) : "Primary index component is missing for sstable " + descriptor;
+
+ Map<MetadataType, MetadataComponent> sstableMetadata = descriptor.getMetadataSerializer().deserialize(descriptor,
+ EnumSet.of(MetadataType.VALIDATION, MetadataType.STATS));
+ ValidationMetadata validationMetadata = (ValidationMetadata) sstableMetadata.get(MetadataType.VALIDATION);
+ StatsMetadata statsMetadata = (StatsMetadata) sstableMetadata.get(MetadataType.STATS);
+
+ // Check if sstable is created using same partitioner.
+ // Partitioner can be null, which indicates older version of sstable or no stats available.
+ // In that case, we skip the check.
+ String partitionerName = partitioner.getClass().getCanonicalName();
+ if (validationMetadata != null && !partitionerName.equals(validationMetadata.partitioner))
+ {
+ logger.error(String.format("Cannot open %s; partitioner %s does not match system partitioner %s. Note that the default partitioner starting with Cassandra 1.2 is Murmur3Partitioner, so you will need to edit that to match your old partitioner if upgrading.",
+ descriptor, validationMetadata.partitioner, partitionerName));
+ System.exit(1);
+ }
+
+ logger.info("Opening {} ({} bytes)", descriptor, new File(descriptor.filenameFor(Component.DATA)).length());
+ SSTableReader sstable = internalOpen(descriptor, components, metadata, partitioner, System.currentTimeMillis(),
+ statsMetadata, OpenReason.NORMAL);
+
+ // special implementation of load to use non-pooled SegmentedFile builders
+ SegmentedFile.Builder ibuilder = new BufferedSegmentedFile.Builder();
+ SegmentedFile.Builder dbuilder = sstable.compression
+ ? new CompressedSegmentedFile.Builder(null)
+ : new BufferedSegmentedFile.Builder();
+ if (!sstable.loadSummary(ibuilder, dbuilder))
+ sstable.buildSummary(false, ibuilder, dbuilder, false, Downsampling.BASE_SAMPLING_LEVEL);
+ sstable.ifile = ibuilder.complete(sstable.descriptor.filenameFor(Component.PRIMARY_INDEX));
+ sstable.dfile = dbuilder.complete(sstable.descriptor.filenameFor(Component.DATA));
+ sstable.bf = FilterFactory.AlwaysPresent;
- sstable.tidy.setup(sstable);
++ sstable.setup();
+ return sstable;
+ }
+
+ private static SSTableReader open(Descriptor descriptor,
+ Set<Component> components,
+ CFMetaData metadata,
+ IPartitioner partitioner,
+ boolean validate) throws IOException
+ {
+ // Minimum components without which we can't do anything
+ assert components.contains(Component.DATA) : "Data component is missing for sstable" + descriptor;
+ assert components.contains(Component.PRIMARY_INDEX) : "Primary index component is missing for sstable " + descriptor;
+
+ Map<MetadataType, MetadataComponent> sstableMetadata = descriptor.getMetadataSerializer().deserialize(descriptor,
+ EnumSet.of(MetadataType.VALIDATION, MetadataType.STATS));
+ ValidationMetadata validationMetadata = (ValidationMetadata) sstableMetadata.get(MetadataType.VALIDATION);
+ StatsMetadata statsMetadata = (StatsMetadata) sstableMetadata.get(MetadataType.STATS);
+
+ // Check if sstable is created using same partitioner.
+ // Partitioner can be null, which indicates older version of sstable or no stats available.
+ // In that case, we skip the check.
+ String partitionerName = partitioner.getClass().getCanonicalName();
+ if (validationMetadata != null && !partitionerName.equals(validationMetadata.partitioner))
+ {
+ logger.error(String.format("Cannot open %s; partitioner %s does not match system partitioner %s. Note that the default partitioner starting with Cassandra 1.2 is Murmur3Partitioner, so you will need to edit that to match your old partitioner if upgrading.",
+ descriptor, validationMetadata.partitioner, partitionerName));
+ System.exit(1);
+ }
+
+ logger.info("Opening {} ({} bytes)", descriptor, new File(descriptor.filenameFor(Component.DATA)).length());
+ SSTableReader sstable = internalOpen(descriptor, components, metadata, partitioner, System.currentTimeMillis(),
+ statsMetadata, OpenReason.NORMAL);
+
+ // load index and filter
+ long start = System.nanoTime();
+ sstable.load(validationMetadata);
+ logger.debug("INDEX LOAD TIME for {}: {} ms.", descriptor, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
+
++ sstable.setup();
+ if (validate)
+ sstable.validate();
+
+ if (sstable.getKeyCache() != null)
+ logger.debug("key cache contains {}/{} keys", sstable.getKeyCache().size(), sstable.getKeyCache().getCapacity());
+
- sstable.tidy.setup(sstable);
+ return sstable;
+ }
+
+ public static void logOpenException(Descriptor descriptor, IOException e)
+ {
+ if (e instanceof FileNotFoundException)
+ logger.error("Missing sstable component in {}; skipped because of {}", descriptor, e.getMessage());
+ else
+ logger.error("Corrupt sstable {}; skipped", descriptor, e);
+ }
+
+ public static Collection<SSTableReader> openAll(Set<Map.Entry<Descriptor, Set<Component>>> entries,
+ final CFMetaData metadata,
+ final IPartitioner partitioner)
+ {
+ final Collection<SSTableReader> sstables = new LinkedBlockingQueue<>();
+
+ ExecutorService executor = DebuggableThreadPoolExecutor.createWithFixedPoolSize("SSTableBatchOpen", FBUtilities.getAvailableProcessors());
+ for (final Map.Entry<Descriptor, Set<Component>> entry : entries)
+ {
+ Runnable runnable = new Runnable()
+ {
+ public void run()
+ {
+ SSTableReader sstable;
+ try
+ {
+ sstable = open(entry.getKey(), entry.getValue(), metadata, partitioner);
+ }
+ catch (IOException ex)
+ {
+ logger.error("Corrupt sstable {}; skipped", entry, ex);
+ return;
+ }
+ sstables.add(sstable);
+ }
+ };
+ executor.submit(runnable);
+ }
+
+ executor.shutdown();
+ try
+ {
+ executor.awaitTermination(7, TimeUnit.DAYS);
+ }
+ catch (InterruptedException e)
+ {
+ throw new AssertionError(e);
+ }
+
+ return sstables;
+
+ }
+
+ /**
+ * Open a RowIndexedReader which already has its state initialized (by SSTableWriter).
+ */
+ public static SSTableReader internalOpen(Descriptor desc,
+ Set<Component> components,
+ CFMetaData metadata,
+ IPartitioner partitioner,
+ SegmentedFile ifile,
+ SegmentedFile dfile,
+ IndexSummary isummary,
+ IFilter bf,
+ long maxDataAge,
+ StatsMetadata sstableMetadata,
+ OpenReason openReason)
+ {
+ assert desc != null && partitioner != null && ifile != null && dfile != null && isummary != null && bf != null && sstableMetadata != null;
+
+ SSTableReader reader = internalOpen(desc, components, metadata, partitioner, maxDataAge, sstableMetadata, openReason);
+
+ reader.bf = bf;
+ reader.ifile = ifile;
+ reader.dfile = dfile;
+ reader.indexSummary = isummary;
- reader.tidy.setup(reader);
++ reader.setup();
+
+ return reader;
+ }
+
+
+ private static SSTableReader internalOpen(final Descriptor descriptor,
+ Set<Component> components,
+ CFMetaData metadata,
+ IPartitioner partitioner,
+ Long maxDataAge,
+ StatsMetadata sstableMetadata,
+ OpenReason openReason)
+ {
+ Factory readerFactory = descriptor.getFormat().getReaderFactory();
+
+ return readerFactory.open(descriptor, components, metadata, partitioner, maxDataAge, sstableMetadata, openReason);
+ }
+
+ protected SSTableReader(final Descriptor desc,
+ Set<Component> components,
+ CFMetaData metadata,
+ IPartitioner partitioner,
+ long maxDataAge,
+ StatsMetadata sstableMetadata,
+ OpenReason openReason)
+ {
+ super(desc, components, metadata, partitioner);
+ this.sstableMetadata = sstableMetadata;
+ this.maxDataAge = maxDataAge;
+ this.openReason = openReason;
-
+ this.rowIndexEntrySerializer = descriptor.version.getSSTableFormat().getIndexSerializer(metadata);
-
- tidy.deletingTask = new SSTableDeletingTask(this);
-
- // Don't track read rates for tables in the system keyspace. Also don't track reads for special operations (like early open)
- // this is to avoid overflowing the executor queue (see CASSANDRA-8066)
- if (SystemKeyspace.NAME.equals(desc.ksname) || openReason != OpenReason.NORMAL)
- {
- readMeter = null;
- readMeterSyncFuture = null;
- return;
- }
-
- readMeter = SystemKeyspace.getSSTableReadMeter(desc.ksname, desc.cfname, desc.generation);
- // sync the average read rate to system.sstable_activity every five minutes, starting one minute from now
- readMeterSyncFuture = syncExecutor.scheduleAtFixedRate(new Runnable()
- {
- public void run()
- {
- if (!isCompacted.get())
- {
- meterSyncThrottle.acquire();
- SystemKeyspace.persistSSTableReadMeter(desc.ksname, desc.cfname, desc.generation, readMeter);
- }
- }
- }, 1, 5, TimeUnit.MINUTES);
+ }
+
+ public static long getTotalBytes(Iterable<SSTableReader> sstables)
+ {
+ long sum = 0;
+ for (SSTableReader sstable : sstables)
+ {
+ sum += sstable.onDiskLength();
+ }
+ return sum;
+ }
+
+ public boolean equals(Object that)
+ {
+ return that instanceof SSTableReader && ((SSTableReader) that).descriptor.equals(this.descriptor);
+ }
+
+ public int hashCode()
+ {
+ return this.descriptor.hashCode();
+ }
+
+ public String getFilename()
+ {
+ return dfile.path;
+ }
+
+ public String getIndexFilename()
+ {
+ return ifile.path;
+ }
+
+ public void setTrackedBy(DataTracker tracker)
+ {
- tidy.deletingTask.setTracker(tracker);
++ tidy.type.deletingTask.setTracker(tracker);
+ // under normal operation we can do this at any time, but SSTR is also used outside C* proper,
+ // e.g. by BulkLoader, which does not initialize the cache. As a kludge, we set up the cache
+ // here when we know we're being wired into the rest of the server infrastructure.
+ keyCache = CacheService.instance.keyCache;
+ }
+
+ private void load(ValidationMetadata validation) throws IOException
+ {
+ if (metadata.getBloomFilterFpChance() == 1.0)
+ {
+ // bf is disabled.
+ load(false, true);
+ bf = FilterFactory.AlwaysPresent;
+ }
+ else if (!components.contains(Component.FILTER) || validation == null)
+ {
+ // bf is enabled, but filter component is missing.
+ load(true, true);
+ }
+ else if (validation.bloomFilterFPChance != metadata.getBloomFilterFpChance())
+ {
+ // bf fp chance in sstable metadata and it has changed since compaction.
+ load(true, true);
+ }
+ else
+ {
+ // bf is enabled and fp chance matches the currently configured value.
+ load(false, true);
+ loadBloomFilter();
+ }
+ }
+
+ /**
+ * Load bloom filter from Filter.db file.
+ *
+ * @throws IOException
+ */
+ private void loadBloomFilter() throws IOException
+ {
+ DataInputStream stream = null;
+ try
+ {
+ stream = new DataInputStream(new BufferedInputStream(new FileInputStream(descriptor.filenameFor(Component.FILTER))));
+ bf = FilterFactory.deserialize(stream, true);
+ }
+ finally
+ {
+ FileUtils.closeQuietly(stream);
+ }
+ }
+
+ /**
+ * Loads ifile, dfile and indexSummary, and optionally recreates the bloom filter.
+ * @param saveSummaryIfCreated for bulk loading purposes, if the summary was absent and needed to be built, you can
+ * avoid persisting it to disk by setting this to false
+ */
+ private void load(boolean recreateBloomFilter, boolean saveSummaryIfCreated) throws IOException
+ {
+ SegmentedFile.Builder ibuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getIndexAccessMode());
+ SegmentedFile.Builder dbuilder = compression
+ ? SegmentedFile.getCompressedBuilder()
+ : SegmentedFile.getBuilder(DatabaseDescriptor.getDiskAccessMode());
+
+ boolean summaryLoaded = loadSummary(ibuilder, dbuilder);
+ if (recreateBloomFilter || !summaryLoaded)
+ buildSummary(recreateBloomFilter, ibuilder, dbuilder, summaryLoaded, Downsampling.BASE_SAMPLING_LEVEL);
+
+ ifile = ibuilder.complete(descriptor.filenameFor(Component.PRIMARY_INDEX));
+ dfile = dbuilder.complete(descriptor.filenameFor(Component.DATA));
+ if (saveSummaryIfCreated && (recreateBloomFilter || !summaryLoaded)) // save summary information to disk
+ saveSummary(ibuilder, dbuilder);
- tidy.setup(this);
+ }
+
+ /**
+ * Build index summary(and optionally bloom filter) by reading through Index.db file.
+ *
+ * @param recreateBloomFilter true if recreate bloom filter
+ * @param ibuilder
+ * @param dbuilder
+ * @param summaryLoaded true if index summary is already loaded and not need to build again
+ * @throws IOException
+ */
+ private void buildSummary(boolean recreateBloomFilter, SegmentedFile.Builder ibuilder, SegmentedFile.Builder dbuilder, boolean summaryLoaded, int samplingLevel) throws IOException
+ {
+ // we read the positions in a BRAF so we don't have to worry about an entry spanning a mmap boundary.
+ RandomAccessReader primaryIndex = RandomAccessReader.open(new File(descriptor.filenameFor(Component.PRIMARY_INDEX)));
+
+ try
+ {
+ long indexSize = primaryIndex.length();
+ long histogramCount = sstableMetadata.estimatedRowSize.count();
+ long estimatedKeys = histogramCount > 0 && !sstableMetadata.estimatedRowSize.isOverflowed()
+ ? histogramCount
+ : estimateRowsFromIndex(primaryIndex); // statistics is supposed to be optional
+
+ if (recreateBloomFilter)
+ bf = FilterFactory.getFilter(estimatedKeys, metadata.getBloomFilterFpChance(), true);
+
+ IndexSummaryBuilder summaryBuilder = null;
+ if (!summaryLoaded)
+ summaryBuilder = new IndexSummaryBuilder(estimatedKeys, metadata.getMinIndexInterval(), samplingLevel);
+
+ long indexPosition;
+ RowIndexEntry.IndexSerializer rowIndexSerializer = descriptor.getFormat().getIndexSerializer(metadata);
+
+ while ((indexPosition = primaryIndex.getFilePointer()) != indexSize)
+ {
+ ByteBuffer key = ByteBufferUtil.readWithShortLength(primaryIndex);
+ RowIndexEntry indexEntry = rowIndexSerializer.deserialize(primaryIndex, descriptor.version);
+ DecoratedKey decoratedKey = partitioner.decorateKey(key);
+ if (first == null)
+ first = decoratedKey;
+ last = decoratedKey;
+
+ if (recreateBloomFilter)
+ bf.add(decoratedKey.getKey());
+
+ // if summary was already read from disk we don't want to re-populate it using primary index
+ if (!summaryLoaded)
+ {
+ summaryBuilder.maybeAddEntry(decoratedKey, indexPosition);
+ ibuilder.addPotentialBoundary(indexPosition);
+ dbuilder.addPotentialBoundary(indexEntry.position);
+ }
+ }
+
+ if (!summaryLoaded)
+ indexSummary = summaryBuilder.build(partitioner);
+ }
+ finally
+ {
+ FileUtils.closeQuietly(primaryIndex);
+ }
+
+ first = getMinimalKey(first);
+ last = getMinimalKey(last);
+ }
+
+ /**
+ * Load index summary from Summary.db file if it exists.
+ *
+ * if loaded index summary has different index interval from current value stored in schema,
+ * then Summary.db file will be deleted and this returns false to rebuild summary.
+ *
+ * @param ibuilder
+ * @param dbuilder
+ * @return true if index summary is loaded successfully from Summary.db file.
+ */
+ public boolean loadSummary(SegmentedFile.Builder ibuilder, SegmentedFile.Builder dbuilder)
+ {
+ File summariesFile = new File(descriptor.filenameFor(Component.SUMMARY));
+ if (!summariesFile.exists())
+ return false;
+
+ DataInputStream iStream = null;
+ try
+ {
+ iStream = new DataInputStream(new FileInputStream(summariesFile));
+ indexSummary = IndexSummary.serializer.deserialize(iStream, partitioner, descriptor.version.hasSamplingLevel(), metadata.getMinIndexInterval(), metadata.getMaxIndexInterval());
+ first = partitioner.decorateKey(ByteBufferUtil.readWithLength(iStream));
+ last = partitioner.decorateKey(ByteBufferUtil.readWithLength(iStream));
+ ibuilder.deserializeBounds(iStream);
+ dbuilder.deserializeBounds(iStream);
+ }
+ catch (IOException e)
+ {
++ if (indexSummary != null)
++ indexSummary.close();
+ logger.debug("Cannot deserialize SSTable Summary File {}: {}", summariesFile.getPath(), e.getMessage());
+ // corrupted; delete it and fall back to creating a new summary
+ FileUtils.closeQuietly(iStream);
+ // delete it and fall back to creating a new summary
+ FileUtils.deleteWithConfirm(summariesFile);
+ return false;
+ }
+ finally
+ {
+ FileUtils.closeQuietly(iStream);
+ }
+
+ return true;
+ }
+
+ /**
+ * Save index summary to Summary.db file.
+ *
+ * @param ibuilder
+ * @param dbuilder
+ */
+ public void saveSummary(SegmentedFile.Builder ibuilder, SegmentedFile.Builder dbuilder)
+ {
+ saveSummary(ibuilder, dbuilder, indexSummary);
+ }
+
+ private void saveSummary(SegmentedFile.Builder ibuilder, SegmentedFile.Builder dbuilder, IndexSummary summary)
+ {
+ File summariesFile = new File(descriptor.filenameFor(Component.SUMMARY));
+ if (summariesFile.exists())
+ FileUtils.deleteWithConfirm(summariesFile);
+
+ DataOutputStreamAndChannel oStream = null;
+ try
+ {
+ oStream = new DataOutputStreamAndChannel(new FileOutputStream(summariesFile));
+ IndexSummary.serializer.serialize(summary, oStream, descriptor.version.hasSamplingLevel());
+ ByteBufferUtil.writeWithLength(first.getKey(), oStream);
+ ByteBufferUtil.writeWithLength(last.getKey(), oStream);
+ ibuilder.serializeBounds(oStream);
+ dbuilder.serializeBounds(oStream);
+ }
+ catch (IOException e)
+ {
+ logger.debug("Cannot save SSTable Summary: ", e);
+
+ // corrupted hence delete it and let it load it now.
+ if (summariesFile.exists())
+ FileUtils.deleteWithConfirm(summariesFile);
+ }
+ finally
+ {
+ FileUtils.closeQuietly(oStream);
+ }
+ }
+
+ public void setReplacedBy(SSTableReader replacement)
+ {
- synchronized (tidy.replaceLock)
++ synchronized (tidy.global)
+ {
- assert tidy.replacedBy == null;
- tidy.replacedBy = replacement;
- replacement.tidy.replaces = this;
- replacement.tidy.replaceLock = tidy.replaceLock;
++ assert replacement != null;
++ assert !tidy.isReplaced;
++ assert tidy.global.live == this;
++ tidy.isReplaced = true;
++ tidy.global.live = replacement;
+ }
+ }
+
+ public SSTableReader cloneWithNewStart(DecoratedKey newStart, final Runnable runOnClose)
+ {
- synchronized (tidy.replaceLock)
++ synchronized (tidy.global)
+ {
- assert tidy.replacedBy == null;
++ assert openReason != OpenReason.EARLY;
+
+ if (newStart.compareTo(this.first) > 0)
+ {
+ if (newStart.compareTo(this.last) > 0)
+ {
+ this.tidy.runOnClose = new Runnable()
+ {
+ public void run()
+ {
+ CLibrary.trySkipCache(dfile.path, 0, 0);
+ CLibrary.trySkipCache(ifile.path, 0, 0);
+ runOnClose.run();
+ }
+ };
+ }
+ else
+ {
+ final long dataStart = getPosition(newStart, Operator.GE).position;
+ final long indexStart = getIndexScanPosition(newStart);
+ this.tidy.runOnClose = new Runnable()
+ {
+ public void run()
+ {
+ CLibrary.trySkipCache(dfile.path, 0, dataStart);
+ CLibrary.trySkipCache(ifile.path, 0, indexStart);
+ runOnClose.run();
+ }
+ };
+ }
+ }
+
- SSTableReader replacement = internalOpen(descriptor, components, metadata, partitioner, ifile, dfile, indexSummary.readOnlyClone(), bf, maxDataAge, sstableMetadata,
- openReason == OpenReason.EARLY ? openReason : OpenReason.METADATA_CHANGE);
- replacement.readMeterSyncFuture = this.readMeterSyncFuture;
- replacement.readMeter = this.readMeter;
++ SSTableReader replacement = internalOpen(descriptor, components, metadata, partitioner, ifile.sharedCopy(),
++ dfile.sharedCopy(), indexSummary.sharedCopy(), bf.sharedCopy(),
++ maxDataAge, sstableMetadata, OpenReason.MOVED_START);
+ replacement.first = this.last.compareTo(newStart) > 0 ? newStart : this.last;
+ replacement.last = this.last;
+ setReplacedBy(replacement);
+ return replacement;
+ }
+ }
+
+ /**
+ * Returns a new SSTableReader with the same properties as this SSTableReader except that a new IndexSummary will
+ * be built at the target samplingLevel. This (original) SSTableReader instance will be marked as replaced, have
+ * its DeletingTask removed, and have its periodic read-meter sync task cancelled.
+ * @param samplingLevel the desired sampling level for the index summary on the new SSTableReader
+ * @return a new SSTableReader
+ * @throws IOException
+ */
+ public SSTableReader cloneWithNewSummarySamplingLevel(ColumnFamilyStore parent, int samplingLevel) throws IOException
+ {
- synchronized (tidy.replaceLock)
++ synchronized (tidy.global)
+ {
- assert tidy.replacedBy == null;
++ assert openReason != OpenReason.EARLY;
+
+ int minIndexInterval = metadata.getMinIndexInterval();
+ int maxIndexInterval = metadata.getMaxIndexInterval();
+ double effectiveInterval = indexSummary.getEffectiveIndexInterval();
+
+ IndexSummary newSummary;
+ long oldSize = bytesOnDisk();
+
+ // We have to rebuild the summary from the on-disk primary index in three cases:
+ // 1. The sampling level went up, so we need to read more entries off disk
+ // 2. The min_index_interval changed (in either direction); this changes what entries would be in the summary
+ // at full sampling (and consequently at any other sampling level)
+ // 3. The max_index_interval was lowered, forcing us to raise the sampling level
+ if (samplingLevel > indexSummary.getSamplingLevel() || indexSummary.getMinIndexInterval() != minIndexInterval || effectiveInterval > maxIndexInterval)
+ {
+ newSummary = buildSummaryAtLevel(samplingLevel);
+ }
+ else if (samplingLevel < indexSummary.getSamplingLevel())
+ {
+ // we can use the existing index summary to make a smaller one
+ newSummary = IndexSummaryBuilder.downsample(indexSummary, samplingLevel, minIndexInterval, partitioner);
+
+ SegmentedFile.Builder ibuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getIndexAccessMode());
+ SegmentedFile.Builder dbuilder = compression
+ ? SegmentedFile.getCompressedBuilder()
+ : SegmentedFile.getBuilder(DatabaseDescriptor.getDiskAccessMode());
+ saveSummary(ibuilder, dbuilder, newSummary);
+ }
+ else
+ {
+ throw new AssertionError("Attempted to clone SSTableReader with the same index summary sampling level and " +
+ "no adjustments to min/max_index_interval");
+ }
+
+ long newSize = bytesOnDisk();
+ StorageMetrics.load.inc(newSize - oldSize);
+ parent.metric.liveDiskSpaceUsed.inc(newSize - oldSize);
+
- SSTableReader replacement = internalOpen(descriptor, components, metadata, partitioner, ifile, dfile, newSummary, bf, maxDataAge, sstableMetadata,
- openReason == OpenReason.EARLY ? openReason : OpenReason.METADATA_CHANGE);
- replacement.readMeterSyncFuture = this.readMeterSyncFuture;
- replacement.readMeter = this.readMeter;
++ SSTableReader replacement = internalOpen(descriptor, components, metadata, partitioner, ifile.sharedCopy(),
++ dfile.sharedCopy(), newSummary, bf.sharedCopy(), maxDataAge,
++ sstableMetadata, OpenReason.METADATA_CHANGE);
+ replacement.first = this.first;
+ replacement.last = this.last;
+ setReplacedBy(replacement);
+ return replacement;
+ }
+ }
+
+ private IndexSummary buildSummaryAtLevel(int newSamplingLevel) throws IOException
+ {
+ // we read the positions in a BRAF so we don't have to worry about an entry spanning a mmap boundary.
+ RandomAccessReader primaryIndex = RandomAccessReader.open(new File(descriptor.filenameFor(Component.PRIMARY_INDEX)));
+ try
+ {
+ long indexSize = primaryIndex.length();
+ IndexSummaryBuilder summaryBuilder = new IndexSummaryBuilder(estimatedKeys(), metadata.getMinIndexInterval(), newSamplingLevel);
+
+ long indexPosition;
+ while ((indexPosition = primaryIndex.getFilePointer()) != indexSize)
+ {
+ summaryBuilder.maybeAddEntry(partitioner.decorateKey(ByteBufferUtil.readWithShortLength(primaryIndex)), indexPosition);
+ RowIndexEntry.Serializer.skip(primaryIndex);
+ }
+
+ return summaryBuilder.build(partitioner);
+ }
+ finally
+ {
+ FileUtils.closeQuietly(primaryIndex);
+ }
+ }
+
++ public RestorableMeter getReadMeter()
++ {
++ return readMeter;
++ }
++
+ public int getIndexSummarySamplingLevel()
+ {
+ return indexSummary.getSamplingLevel();
+ }
+
+ public long getIndexSummaryOffHeapSize()
+ {
+ return indexSummary.getOffHeapSize();
+ }
+
+ public int getMinIndexInterval()
+ {
+ return indexSummary.getMinIndexInterval();
+ }
+
+ public double getEffectiveIndexInterval()
+ {
+ return indexSummary.getEffectiveIndexInterval();
+ }
+
+ public void releaseSummary()
+ {
- indexSummary.close();
++ tidy.releaseSummary();
+ indexSummary = null;
+ }
+
+ private void validate()
+ {
+ if (this.first.compareTo(this.last) > 0)
++ {
++ selfRef().release();
+ throw new IllegalStateException(String.format("SSTable first key %s > last key %s", this.first, this.last));
++ }
+ }
+
+ /**
+ * Gets the position in the index file to start scanning to find the given key (at most indexInterval keys away,
+ * modulo downsampling of the index summary).
+ */
+ public long getIndexScanPosition(RowPosition key)
+ {
+ return getIndexScanPositionFromBinarySearchResult(indexSummary.binarySearch(key), indexSummary);
+ }
+
+ protected static long getIndexScanPositionFromBinarySearchResult(int binarySearchResult, IndexSummary referencedIndexSummary)
+ {
+ if (binarySearchResult == -1)
+ return -1;
+ else
+ return referencedIndexSummary.getPosition(getIndexSummaryIndexFromBinarySearchResult(binarySearchResult));
+ }
+
+ protected static int getIndexSummaryIndexFromBinarySearchResult(int binarySearchResult)
+ {
+ if (binarySearchResult < 0)
+ {
+ // binary search gives us the first index _greater_ than the key searched for,
+ // i.e., its insertion position
+ int greaterThan = (binarySearchResult + 1) * -1;
+ if (greaterThan == 0)
+ return -1;
+ return greaterThan - 1;
+ }
+ else
+ {
+ return binarySearchResult;
+ }
+ }
+
+ /**
+ * Returns the compression metadata for this sstable.
+ * @throws IllegalStateException if the sstable is not compressed
+ */
+ public CompressionMetadata getCompressionMetadata()
+ {
+ if (!compression)
+ throw new IllegalStateException(this + " is not compressed");
+
+ CompressionMetadata cmd = ((ICompressedFile) dfile).getMetadata();
+
+ //We need the parent cf metadata
+ String cfName = metadata.isSecondaryIndex() ? metadata.getParentColumnFamilyName() : metadata.cfName;
+ cmd.parameters.setLiveMetadata(Schema.instance.getCFMetaData(metadata.ksName, cfName));
+
+ return cmd;
+ }
+
+ /**
+ * Returns the amount of memory in bytes used off heap by the compression meta-data.
+ * @return the amount of memory in bytes used off heap by the compression meta-data
+ */
+ public long getCompressionMetadataOffHeapSize()
+ {
+ if (!compression)
+ return 0;
+
+ return getCompressionMetadata().offHeapSize();
+ }
+
+ /**
+ * For testing purposes only.
+ */
+ public void forceFilterFailures()
+ {
+ bf = FilterFactory.AlwaysPresent;
+ }
+
+ public IFilter getBloomFilter()
+ {
+ return bf;
+ }
+
+ public long getBloomFilterSerializedSize()
+ {
+ return bf.serializedSize();
+ }
+
+ /**
+ * Returns the amount of memory in bytes used off heap by the bloom filter.
+ * @return the amount of memory in bytes used off heap by the bloom filter
+ */
+ public long getBloomFilterOffHeapSize()
+ {
+ return bf.offHeapSize();
+ }
+
+ /**
+ * @return An estimate of the number of keys in this SSTable based on the index summary.
+ */
+ public long estimatedKeys()
+ {
+ return indexSummary.getEstimatedKeyCount();
+ }
+
+ /**
+ * @param ranges
+ * @return An estimate of the number of keys for given ranges in this SSTable.
+ */
+ public long estimatedKeysForRanges(Collection<Range<Token>> ranges)
+ {
+ long sampleKeyCount = 0;
+ List<Pair<Integer, Integer>> sampleIndexes = getSampleIndexesForRanges(indexSummary, ranges);
+ for (Pair<Integer, Integer> sampleIndexRange : sampleIndexes)
+ sampleKeyCount += (sampleIndexRange.right - sampleIndexRange.left + 1);
+
+ // adjust for the current sampling level: (BSL / SL) * index_interval_at_full_sampling
+ long estimatedKeys = sampleKeyCount * (Downsampling.BASE_SAMPLING_LEVEL * indexSummary.getMinIndexInterval()) / indexSummary.getSamplingLevel();
+ return Math.max(1, estimatedKeys);
+ }
+
+ /**
+ * Returns the number of entries in the IndexSummary. At full sampling, this is approximately 1/INDEX_INTERVALth of
+ * the keys in this SSTable.
+ */
+ public int getIndexSummarySize()
+ {
+ return indexSummary.size();
+ }
+
+ /**
+ * Returns the approximate number of entries the IndexSummary would contain if it were at full sampling.
+ */
+ public int getMaxIndexSummarySize()
+ {
+ return indexSummary.getMaxNumberOfEntries();
+ }
+
+ /**
+ * Returns the key for the index summary entry at `index`.
+ */
+ public byte[] getIndexSummaryKey(int index)
+ {
+ return indexSummary.getKey(index);
+ }
+
+ private static List<Pair<Integer,Integer>> getSampleIndexesForRanges(IndexSummary summary, Collection<Range<Token>> ranges)
+ {
+ // use the index to determine a minimal section for each range
+ List<Pair<Integer,Integer>> positions = new ArrayList<>();
+
+ for (Range<Token> range : Range.normalize(ranges))
+ {
+ RowPosition leftPosition = range.left.maxKeyBound();
+ RowPosition rightPosition = range.right.maxKeyBound();
+
+ int left = summary.binarySearch(leftPosition);
+ if (left < 0)
+ left = (left + 1) * -1;
+ else
+ // left range are start exclusive
+ left = left + 1;
+ if (left == summary.size())
+ // left is past the end of the sampling
+ continue;
+
+ int right = Range.isWrapAround(range.left, range.right)
+ ? summary.size() - 1
+ : summary.binarySearch(rightPosition);
+ if (right < 0)
+ {
+ // range are end inclusive so we use the previous index from what binarySearch give us
+ // since that will be the last index we will return
+ right = (right + 1) * -1;
+ if (right == 0)
+ // Means the first key is already stricly greater that the right bound
+ continue;
+ right--;
+ }
+
+ if (left > right)
+ // empty range
+ continue;
+ positions.add(Pair.create(left, right));
+ }
+ return positions;
+ }
+
+ public Iterable<DecoratedKey> getKeySamples(final Range<Token> range)
+ {
+ final List<Pair<Integer, Integer>> indexRanges = getSampleIndexesForRanges(indexSummary, Collections.singletonList(range));
+
+ if (indexRanges.isEmpty())
+ return Collections.emptyList();
+
+ return new Iterable<DecoratedKey>()
+ {
+ public Iterator<DecoratedKey> iterator()
+ {
+ return new Iterator<DecoratedKey>()
+ {
+ private Iterator<Pair<Integer, Integer>> rangeIter = indexRanges.iterator();
+ private Pair<Integer, Integer> current;
+ private int idx;
+
+ public boolean hasNext()
+ {
+ if (current == null || idx > current.right)
+ {
+ if (rangeIter.hasNext())
+ {
+ current = rangeIter.next();
+ idx = current.left;
+ return true;
+ }
+ return false;
+ }
+
+ return true;
+ }
+
+ public DecoratedKey next()
+ {
+ byte[] bytes = indexSummary.getKey(idx++);
+ return partitioner.decorateKey(ByteBuffer.wrap(bytes));
+ }
+
+ public void remove()
+ {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+ };
+ }
+
+ /**
+ * Determine the minimal set of sections that can be extracted from this SSTable to cover the given ranges.
+ * @return A sorted list of (offset,end) pairs that cover the given ranges in the datafile for this SSTable.
+ */
+ public List<Pair<Long,Long>> getPositionsForRanges(Collection<Range<Token>> ranges)
+ {
+ // use the index to determine a minimal section for each range
+ List<Pair<Long,Long>> positions = new ArrayList<>();
+ for (Range<Token> range : Range.normalize(ranges))
+ {
+ assert !range.isWrapAround() || range.right.isMinimum();
+ // truncate the range so it at most covers the sstable
+ AbstractBounds<RowPosition> bounds = range.toRowBounds();
+ RowPosition leftBound = bounds.left.compareTo(first) > 0 ? bounds.left : first.getToken().minKeyBound();
+ RowPosition rightBound = bounds.right.isMinimum() ? last.getToken().maxKeyBound() : bounds.right;
+
+ if (leftBound.compareTo(last) > 0 || rightBound.compareTo(first) < 0)
+ continue;
+
+ long left = getPosition(leftBound, Operator.GT).position;
+ long right = (rightBound.compareTo(last) > 0)
+ ? (openReason == OpenReason.EARLY
+ // if opened early, we overlap with the old sstables by one key, so we know that the last
+ // (and further) key(s) will be streamed from these if necessary
+ ? getPosition(last.getToken().maxKeyBound(), Operator.GT).position
+ : uncompressedLength())
+ : getPosition(rightBound, Operator.GT).position;
+
+ if (left == right)
+ // empty range
+ continue;
+
+ assert left < right : String.format("Range=%s openReason=%s first=%s last=%s left=%d right=%d", range, openReason, first, last, left, right);
+ positions.add(Pair.create(left, right));
+ }
+ return positions;
+ }
+
+ public void invalidateCacheKey(DecoratedKey key)
+ {
+ KeyCacheKey cacheKey = new KeyCacheKey(metadata.cfId, descriptor, key.getKey());
+ keyCache.remove(cacheKey);
+ }
+
+ public void cacheKey(DecoratedKey key, RowIndexEntry info)
+ {
+ CachingOptions caching = metadata.getCaching();
+
+ if (!caching.keyCache.isEnabled()
+ || keyCache == null
+ || keyCache.getCapacity() == 0)
+ {
+ return;
+ }
+
+ KeyCacheKey cacheKey = new KeyCacheKey(metadata.cfId, descriptor, key.getKey());
+ logger.trace("Adding cache entry for {} -> {}", cacheKey, info);
+ keyCache.put(cacheKey, info);
+ }
+
+ public RowIndexEntry getCachedPosition(DecoratedKey key, boolean updateStats)
+ {
+ return getCachedPosition(new KeyCacheKey(metadata.cfId, descriptor, key.getKey()), updateStats);
+ }
+
+ protected RowIndexEntry getCachedPosition(KeyCacheKey unifiedKey, boolean updateStats)
+ {
+ if (keyCache != null && keyCache.getCapacity() > 0) {
+ if (updateStats)
+ {
+ RowIndexEntry cachedEntry = keyCache.get(unifiedKey);
+ keyCacheRequest.incrementAndGet();
+ if (cachedEntry != null)
+ {
+ keyCacheHit.incrementAndGet();
+ bloomFilterTracker.addTruePositive();
+ }
+ return cachedEntry;
+ }
+ else
+ {
+ return keyCache.getInternal(unifiedKey);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Get position updating key cache and stats.
+ * @see #getPosition(org.apache.cassandra.db.RowPosition, SSTableReader.Operator, boolean)
+ */
+ public RowIndexEntry getPosition(RowPosition key, Operator op)
+ {
+ return getPosition(key, op, true);
+ }
+
+ /**
+ * @param key The key to apply as the rhs to the given Operator. A 'fake' key is allowed to
+ * allow key selection by token bounds but only if op != * EQ
+ * @param op The Operator defining matching keys: the nearest key to the target matching the operator wins.
+ * @param updateCacheAndStats true if updating stats and cache
+ * @return The index entry corresponding to the key, or null if the key is not present
+ */
+ public abstract RowIndexEntry getPosition(RowPosition key, Operator op, boolean updateCacheAndStats);
+
+ //Corresponds to a name column
+ public abstract OnDiskAtomIterator iterator(DecoratedKey key, SortedSet<CellName> columns);
+ public abstract OnDiskAtomIterator iterator(FileDataInput file, DecoratedKey key, SortedSet<CellName> columns, RowIndexEntry indexEntry);
+
+ //Corresponds to a slice query
+ public abstract OnDiskAtomIterator iterator(DecoratedKey key, ColumnSlice[] slices, boolean reverse);
+ public abstract OnDiskAtomIterator iterator(FileDataInput file, DecoratedKey key, ColumnSlice[] slices, boolean reversed, RowIndexEntry indexEntry);
+
+ /**
+ * Finds and returns the first key beyond a given token in this SSTable or null if no such key exists.
+ */
+ public DecoratedKey firstKeyBeyond(RowPosition token)
+ {
+ long sampledPosition = getIndexScanPosition(token);
+ if (sampledPosition == -1)
+ sampledPosition = 0;
+
+ Iterator<FileDataInput> segments = ifile.iterator(sampledPosition);
+ while (segments.hasNext())
+ {
+ FileDataInput in = segments.next();
+ try
+ {
+ while (!in.isEOF())
+ {
+ ByteBuffer indexKey = ByteBufferUtil.readWithShortLength(in);
+ DecoratedKey indexDecoratedKey = partitioner.decorateKey(indexKey);
+ if (indexDecoratedKey.compareTo(token) > 0)
+ return indexDecoratedKey;
+
+ RowIndexEntry.Serializer.skip(in);
+ }
+ }
+ catch (IOException e)
+ {
+ markSuspect();
+ throw new CorruptSSTableException(e, in.getPath());
+ }
+ finally
+ {
+ FileUtils.closeQuietly(in);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * @return The length in bytes of the data for this SSTable. For
+ * compressed files, this is not the same thing as the on disk size (see
+ * onDiskLength())
+ */
+ public long uncompressedLength()
+ {
+ return dfile.length;
+ }
+
+ /**
+ * @return The length in bytes of the on disk size for this SSTable. For
+ * compressed files, this is not the same thing as the data length (see
+ * length())
+ */
+ public long onDiskLength()
+ {
+ return dfile.onDiskLength;
+ }
+
+ /**
+ * Mark the sstable as obsolete, i.e., compacted into newer sstables.
+ *
+ * When calling this function, the caller must ensure that the SSTableReader is not referenced anywhere
+ * except for threads holding a reference.
+ *
+ * @return true if the this is the first time the file was marked obsolete. Calling this
+ * multiple times is usually buggy (see exceptions in DataTracker.unmarkCompacting and removeOldSSTablesSize).
+ */
+ public boolean markObsolete()
+ {
+ if (logger.isDebugEnabled())
+ logger.debug("Marking {} compacted", getFilename());
+
- synchronized (tidy.replaceLock)
++ synchronized (tidy.global)
+ {
- assert tidy.replacedBy == null : getFilename();
++ assert !tidy.isReplaced;
+ }
- return !isCompacted.getAndSet(true);
++ return !tidy.global.isCompacted.getAndSet(true);
+ }
+
+ public boolean isMarkedCompacted()
+ {
- return isCompacted.get();
++ return tidy.global.isCompacted.get();
+ }
+
+ public void markSuspect()
+ {
+ if (logger.isDebugEnabled())
+ logger.debug("Marking {} as a suspect for blacklisting.", getFilename());
+
+ isSuspect.getAndSet(true);
+ }
+
+ public boolean isMarkedSuspect()
+ {
+ return isSuspect.get();
+ }
+
+
+ /**
+ * I/O SSTableScanner
+ * @return A Scanner for seeking over the rows of the SSTable.
+ */
+ public ISSTableScanner getScanner()
+ {
+ return getScanner((RateLimiter) null);
+ }
+
+ public ISSTableScanner getScanner(RateLimiter limiter)
+ {
+ return getScanner(DataRange.allData(partitioner), limiter);
+ }
+
+ /**
+ *
+ * @param dataRange filter to use when reading the columns
+ * @return A Scanner for seeking over the rows of the SSTable.
+ */
+ public ISSTableScanner getScanner(DataRange dataRange)
+ {
+ return getScanner(dataRange, null);
+ }
+
+ /**
+ * Direct I/O SSTableScanner over a defined range of tokens.
+ *
+ * @param range the range of keys to cover
+ * @return A Scanner for seeking over the rows of the SSTable.
+ */
+ public ISSTableScanner getScanner(Range<Token> range, RateLimiter limiter)
+ {
+ if (range == null)
+ return getScanner(limiter);
+ return getScanner(Collections.singletonList(range), limiter);
+ }
+
+ /**
+ * Direct I/O SSTableScanner over a defined collection of ranges of tokens.
+ *
+ * @param ranges the range of keys to cover
+ * @return A Scanner for seeking over the rows of the SSTable.
+ */
+ public abstract ISSTableScanner getScanner(Collection<Range<Token>> ranges, RateLimiter limiter);
+
+ /**
+ *
+ * @param dataRange filter to use when reading the columns
+ * @return A Scanner for seeking over the rows of the SSTable.
+ */
+ public abstract ISSTableScanner getScanner(DataRange dataRange, RateLimiter limiter);
+
+
+
+ public FileDataInput getFileDataInput(long position)
+ {
+ return dfile.getSegment(position);
+ }
+
+ /**
+ * Tests if the sstable contains data newer than the given age param (in localhost currentMilli time).
+ * This works in conjunction with maxDataAge which is an upper bound on the create of data in this sstable.
+ * @param age The age to compare the maxDataAre of this sstable. Measured in millisec since epoc on this host
+ * @return True iff this sstable contains data that's newer than the given age parameter.
+ */
+ public boolean newSince(long age)
+ {
+ return maxDataAge > age;
+ }
+
+ public void createLinks(String snapshotDirectoryPath)
+ {
+ for (Component component : components)
+ {
+ File sourceFile = new File(descriptor.filenameFor(component));
+ File targetLink = new File(snapshotDirectoryPath, sourceFile.getName());
+ FileUtils.createHardLink(sourceFile, targetLink);
+ }
+ }
+
+ public boolean isRepaired()
+ {
+ return sstableMetadata.repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE;
+ }
+
+ public SSTableReader getCurrentReplacement()
+ {
- synchronized (tidy.replaceLock)
- {
- SSTableReader cur = this, next = tidy.replacedBy;
- while (next != null)
- {
- cur = next;
- next = next.tidy.replacedBy;
- }
- return cur;
- }
++ return tidy.global.live;
+ }
+
+ /**
+ * TODO: Move someplace reusable
+ */
+ public abstract static class Operator
+ {
+ public static final Operator EQ = new Equals();
+ public static final Operator GE = new GreaterThanOrEqualTo();
+ public static final Operator GT = new GreaterThan();
+
+ /**
+ * @param comparison The result of a call to compare/compareTo, with the desired field on the rhs.
+ * @return less than 0 if the operator cannot match forward, 0 if it matches, greater than 0 if it might match forward.
+ */
+ public abstract int apply(int comparison);
+
+ final static class Equals extends Operator
+ {
+ public int apply(int comparison) { return -comparison; }
+ }
+
+ final static class GreaterThanOrEqualTo extends Operator
+ {
+ public int apply(int comparison) { return comparison >= 0 ? 0 : 1; }
+ }
+
+ final static class GreaterThan extends Operator
+ {
+ public int apply(int comparison) { return comparison > 0 ? 0 : 1; }
+ }
+ }
+
+ public long getBloomFilterFalsePositiveCount()
+ {
+ return bloomFilterTracker.getFalsePositiveCount();
+ }
+
+ public long getRecentBloomFilterFalsePositiveCount()
+ {
+ return bloomFilterTracker.getRecentFalsePositiveCount();
+ }
+
+ public long getBloomFilterTruePositiveCount()
+ {
+ return bloomFilterTracker.getTruePositiveCount();
+ }
+
+ public long getRecentBloomFilterTruePositiveCount()
+ {
+ return bloomFilterTracker.getRecentTruePositiveCount();
+ }
+
+ public InstrumentingCache<KeyCacheKey, RowIndexEntry> getKeyCache()
+ {
+ return keyCache;
+ }
+
+ public EstimatedHistogram getEstimatedRowSize()
+ {
+ return sstableMetadata.estimatedRowSize;
+ }
+
+ public EstimatedHistogram getEstimatedColumnCount()
+ {
+ return sstableMetadata.estimatedColumnCount;
+ }
+
+ public double getEstimatedDroppableTombstoneRatio(int gcBefore)
+ {
+ return sstableMetadata.getEstimatedDroppableTombstoneRatio(gcBefore);
+ }
+
+ public double getDroppableTombstonesBefore(int gcBefore)
+ {
+ return sstableMetadata.getDroppableTombstonesBefore(gcBefore);
+ }
+
+ public double getCompressionRatio()
+ {
+ return sstableMetadata.compressionRatio;
+ }
+
+ public ReplayPosition getReplayPosition()
+ {
+ return sstableMetadata.replayPosition;
+ }
+
+ public long getMinTimestamp()
+ {
+ return sstableMetadata.minTimestamp;
+ }
+
+ public long getMaxTimestamp()
+ {
+ return sstableMetadata.maxTimestamp;
+ }
+
+ public Set<Integer> getAncestors()
+ {
+ try
+ {
+ CompactionMetadata compactionMetadata = (CompactionMetadata) descriptor.getMetadataSerializer().deserialize(descriptor, MetadataType.COMPACTION);
+ return compactionMetadata.ancestors;
+ }
+ catch (IOException e)
+ {
+ SSTableReader.logOpenException(descriptor, e);
+ return Collections.emptySet();
+ }
+ }
+
+ public int getSSTableLevel()
+ {
+ return sstableMetadata.sstableLevel;
+ }
+
+ /**
+ * Reloads the sstable metadata from disk.
+ *
+ * Called after level is changed on sstable, for example if the sstable is dropped to L0
+ *
+ * Might be possible to remove in future versions
+ *
+ * @throws IOException
+ */
+ public void reloadSSTableMetadata() throws IOException
+ {
+ this.sstableMetadata = (StatsMetadata) descriptor.getMetadataSerializer().deserialize(descriptor, MetadataType.STATS);
+ }
+
+ public StatsMetadata getSSTableMetadata()
+ {
+ return sstableMetadata;
+ }
+
+ public RandomAccessReader openDataReader(RateLimiter limiter)
+ {
+ assert limiter != null;
+ return compression
+ ? CompressedThrottledReader.open(getFilename(), getCompressionMetadata(), limiter)
+ : ThrottledReader.open(new File(getFilename()), limiter);
+ }
+
+ public RandomAccessReader openDataReader()
+ {
+ return compression
+ ? CompressedRandomAccessReader.open(getFilename(), getCompressionMetadata())
+ : RandomAccessReader.open(new File(getFilename()));
+ }
+
+ public RandomAccessReader openIndexReader()
+ {
+ return RandomAccessReader.open(new File(getIndexFilename()));
+ }
+
+ /**
+ * @param component component to get timestamp.
+ * @return last modified time for given component. 0 if given component does not exist or IO error occurs.
+ */
+ public long getCreationTimeFor(Component component)
+ {
+ return new File(descriptor.filenameFor(component)).lastModified();
+ }
+
+ /**
+ * @return Number of key cache hit
+ */
+ public long getKeyCacheHit()
+ {
+ return keyCacheHit.get();
+ }
+
+ /**
+ * @return Number of key cache request
+ */
+ public long getKeyCacheRequest()
+ {
+ return keyCacheRequest.get();
+ }
+
+ /**
+ * Increment the total row read count and read rate for this SSTable. This should not be incremented for range
+ * slice queries, row cache hits, or non-query reads, like compaction.
+ */
+ public void incrementReadCount()
+ {
+ if (readMeter != null)
+ readMeter.mark();
+ }
+
+ public static class SizeComparator implements Comparator<SSTableReader>
+ {
+ public int compare(SSTableReader o1, SSTableReader o2)
+ {
+ return Longs.compare(o1.onDiskLength(), o2.onDiskLength());
+ }
+ }
+
- public Ref tryRef()
++ public Ref<SSTableReader> tryRef()
+ {
- return refCounted.tryRef();
++ return selfRef.tryRef();
+ }
+
- public Ref sharedRef()
++ public Ref<SSTableReader> selfRef()
+ {
- return refCounted.sharedRef();
++ return selfRef;
+ }
+
- private static final class Tidier implements Tidy
++ public Ref<SSTableReader> ref()
+ {
- private String name;
- private CFMetaData metadata;
- // indexfile and datafile: might be null before a call to load()
- private SegmentedFile ifile;
- private SegmentedFile dfile;
++ return selfRef.ref();
++ }
+
- private IndexSummary indexSummary;
- private IFilter bf;
++ void setup()
++ {
++ tidy.setup(this);
++ this.readMeter = tidy.global.readMeter;
++ }
+
- private AtomicBoolean isCompacted;
++ @VisibleForTesting
++ public void overrideReadMeter(RestorableMeter readMeter)
++ {
++ this.readMeter = tidy.global.readMeter = readMeter;
++ }
+
- /**
- * To support replacing this sstablereader with another object that represents that same underlying sstable, but with different associated resources,
- * we build a linked-list chain of replacement, which we synchronise using a shared object to make maintenance of the list across multiple threads simple.
- * On close we check if any of the closeable resources differ between any chains either side of us; any that are in neither of the adjacent links (if any) are closed.
- * Once we've made this decision we remove ourselves from the linked list, so that anybody behind/ahead will compare against only other still opened resources.
- */
- private Object replaceLock = new Object();
- private SSTableReader replacedBy;
- private SSTableReader replaces;
- private SSTableDeletingTask deletingTask;
++ /**
++ * One instance per SSTableReader we create. This references the type-shared tidy, which in turn references
++ * the globally shared tidy, i.e.
++ *
++ * InstanceTidier => DescriptorTypeTitdy => GlobalTidy
++ *
++ * We can create many InstanceTidiers (one for every time we reopen an sstable with MOVED_START for example), but there can only be
++ * two DescriptorTypeTidy (FINAL and TEMPLINK) and only one GlobalTidy for one single logical sstable.
++ *
++ * When the InstanceTidier cleansup, it releases its reference to its DescriptorTypeTidy; when all InstanceTidiers
++ * for that type have run, the DescriptorTypeTidy cleansup. DescriptorTypeTidy behaves in the same way towards GlobalTidy.
++ *
++ * For ease, we stash a direct reference to both our type-shared and global tidier
++ */
++ private static final class InstanceTidier implements Tidy
++ {
++ private final Descriptor descriptor;
++ private final CFMetaData metadata;
++ private IFilter bf;
++ private IndexSummary summary;
++
++ private SegmentedFile dfile;
++ private SegmentedFile ifile;
+ private Runnable runOnClose;
++ private boolean isReplaced = false;
+
- @VisibleForTesting
- public RestorableMeter readMeter;
- private volatile ScheduledFuture readMeterSyncFuture;
++ // a reference to our shared per-Descriptor.Type tidy instance, that
++ // we will release when we are ourselves released
++ private Ref<DescriptorTypeTidy> typeRef;
+
- private void setup(SSTableReader reader)
- {
- name = reader.toString();
- metadata = reader.metadata;
- ifile = reader.ifile;
- dfile = reader.dfile;
- indexSummary = reader.indexSummary;
- bf = reader.bf;
- isCompacted = reader.isCompacted;
- readMeterSyncFuture = reader.readMeterSyncFuture;
- }
++ // a convenience stashing of the shared per-descriptor-type tidy instance itself
++ // and the per-logical-sstable globally shared state that it is linked to
++ private DescriptorTypeTidy type;
++ private GlobalTidy global;
+
- public String name()
++ private boolean setup;
++
++ void setup(SSTableReader reader)
+ {
- return name;
++ this.setup = true;
++ this.bf = reader.bf;
++ this.summary = reader.indexSummary;
++ this.dfile = reader.dfile;
++ this.ifile = reader.ifile;
++ // get a new reference to the shared descriptor-type tidy
++ this.typeRef = DescriptorTypeTidy.get(reader);
++ this.type = typeRef.get();
++ this.global = type.globalRef.get();
+ }
+
- private void dropPageCache()
++ InstanceTidier(Descriptor descriptor, CFMetaData metadata)
+ {
- dropPageCache(dfile.path);
- dropPageCache(ifile.path);
++ this.descriptor = descriptor;
++ this.metadata = metadata;
+ }
+
- private void dropPageCache(String filePath)
++ public void tidy()
+ {
- RandomAccessFile file = null;
++ // don't try to cleanup if the sstablereader was never fully constructed
++ if (!setup)
++ return;
+
- try
++ final ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(metadata.cfId);
++ final OpOrder.Barrier barrier;
++ if (cfs != null)
+ {
- file = new RandomAccessFile(filePath, "r");
-
- int fd = CLibrary.getfd(file.getFD());
++ barrier = cfs.readOrdering.newBarrier();
++ barrier.issue();
++ }
++ else
++ barrier = null;
+
- if (fd > 0)
++ ScheduledExecutors.nonPeriodicTasks.execute(new Runnable()
++ {
++ public void run()
+ {
- if (logger.isDebugEnabled())
- logger.debug(String.format("Dropping page cache of file %s.", filePath));
-
- CLibrary.trySkipCache(fd, 0, 0);
++ if (barrier != null)
++ barrier.await();
++ bf.close();
++ dfile.close();
++ ifile.close();
++ if (summary != null)
++ summary.close();
++ if (runOnClose != null)
++ runOnClose.run();
++ typeRef.release();
+ }
- }
- catch (IOException e)
- {
- // we don't care if cache cleanup fails
- }
- finally
- {
- FileUtils.closeQuietly(file);
- }
++ });
+ }
+
- public void tidy()
++ public String name()
+ {
- if (readMeterSyncFuture != null)
- readMeterSyncFuture.cancel(false);
++ return descriptor.toString();
++ }
+
- synchronized (replaceLock)
- {
- boolean closeBf = true, closeSummary = true, closeFiles = true, deleteFiles = isCompacted.get();
++ void releaseSummary()
++ {
++ summary.close();
++ assert summary.isCleanedUp();
++ summary = null;
++ }
++ }
+
- if (replacedBy != null)
- {
- closeBf = replacedBy.bf != bf;
- closeSummary = replacedBy.indexSummary != indexSummary;
- closeFiles = replacedBy.dfile != dfile;
- // if the replacement sstablereader uses a different path, clean up our paths
- deleteFiles = !dfile.path.equals(replacedBy.dfile.path);
- }
++ /**
++ * One shared between all instances of a given Descriptor.Type.
++ * Performs only two things: the deletion of the sstables for the type,
++ * if necessary; and the shared reference to the globally shared state.
++ *
++ * All InstanceTidiers, on setup(), ask the static get() method for their shared state,
++ * and stash a reference to it to be released when they are. Once all such references are
++ * released, the shared tidy will be performed.
++ */
++ static final class DescriptorTypeTidy implements Tidy
++ {
++ // keyed by REAL descriptor (TMPLINK/FINAL), mapping to the shared DescriptorTypeTidy for that descriptor
++ static final ConcurrentMap<Descriptor, Ref<DescriptorTypeTidy>> lookup = new ConcurrentHashMap<>();
+
- if (replaces != null)
- {
- closeBf &= replaces.bf != bf;
- closeSummary &= replaces.indexSummary != indexSummary;
- closeFiles &= replaces.dfile != dfile;
- deleteFiles &= !dfile.path.equals(replaces.dfile.path);
- }
++ private final Descriptor desc;
++ private final Ref<GlobalTidy> globalRef;
++ private final SSTableDeletingTask deletingTask;
+
- boolean deleteAll = false;
- if (isCompacted.get())
- {
- assert replacedBy == null;
- if (replaces != null && !deleteFiles)
- {
- replaces.tidy.replacedBy = null;
- replaces.tidy.deletingTask = deletingTask;
- replaces.markObsolete();
- }
- else
- {
- deleteAll = true;
- }
- }
- else
- {
- closeSummary &= indexSummary != null;
- if (replaces != null)
- replaces.tidy.replacedBy = replacedBy;
- if (replacedBy != null)
- replacedBy.tidy.replaces = replaces;
- }
++ DescriptorTypeTidy(Descriptor desc, SSTableReader sstable)
++ {
++ this.desc = desc;
++ this.deletingTask = new SSTableDeletingTask(desc, sstable);
++ // get a new reference to the shared global tidy
++ this.globalRef = GlobalTidy.get(sstable);
++ }
+
- scheduleTidy(closeBf, closeSummary, closeFiles, deleteFiles, deleteAll);
++ public void tidy()
++ {
++ lookup.remove(desc);
++ boolean isCompacted = globalRef.get().isCompacted.get();
++ globalRef.release();
++ switch (desc.type)
++ {
++ case FINAL:
++ if (isCompacted)
++ deletingTask.run();
++ break;
++ case TEMPLINK:
++ deletingTask.run();
++ break;
++ default:
++ throw new IllegalStateException();
+ }
+ }
+
- private void scheduleTidy(final boolean closeBf, final boolean closeSummary, final boolean closeFiles, final boolean deleteFiles, final boolean deleteAll)
++ public String name()
+ {
- final ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(metadata.cfId);
- final OpOrder.Barrier barrier;
- if (cfs != null)
++ return desc.toString();
++ }
++
++ // get a new reference to the shared DescriptorTypeTidy for this sstable
++ public static Ref<DescriptorTypeTidy> get(SSTableReader sstable)
++ {
++ Descriptor desc = sstable.descriptor;
++ if (sstable.openReason == OpenReason.EARLY)
++ desc = desc.asType(Descriptor.Type.TEMPLINK);
++ Ref<DescriptorTypeTidy> refc = lookup.get(desc);
++ if (refc != null)
++ return refc.ref();
++ final DescriptorTypeTidy tidy = new DescriptorTypeTidy(desc, sstable);
++ refc = new Ref<>(tidy, tidy);
++ Ref<?> ex = lookup.putIfAbsent(desc, refc);
++ assert ex == null;
++ return refc;
++ }
++ }
++
++ /**
++ * One instance per logical sstable. This both tracks shared cleanup and some shared state related
++ * to the sstable's lifecycle. All DescriptorTypeTidy instances, on construction, obtain a reference to us
++ * via our static get(). There should only ever be at most two such references extant at any one time,
++ * since only TMPLINK and FINAL type descriptors should be open as readers. When all files of both
++ * kinds have been released, this shared tidy will be performed.
++ */
++ static final class GlobalTidy implements Tidy
++ {
++ // keyed by FINAL descriptor, mapping to the shared GlobalTidy for that descriptor
++ static final ConcurrentMap<Descriptor, Ref<GlobalTidy>> lookup = new ConcurrentHashMap<>();
++
++ private final Descriptor desc;
++ // a single convenience property for getting the most recent version of an sstable, not related to tidying
++ private SSTableReader live;
++ // the readMeter that is shared between all instances of the sstable, and can be overridden in all of them
++ // at once also, for testing purposes
++ private RestorableMeter readMeter;
++ // the scheduled persistence of the readMeter, that we will cancel once all instances of this logical
++ // sstable have been released
++ private final ScheduledFuture readMeterSyncFuture;
++ // shared state managing if the logical sstable has been c
<TRUNCATED>
[3/7] cassandra git commit: Safer Resource Management++
Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/BloomFilter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/BloomFilter.java b/src/java/org/apache/cassandra/utils/BloomFilter.java
index ceba89b..77b2d44 100644
--- a/src/java/org/apache/cassandra/utils/BloomFilter.java
+++ b/src/java/org/apache/cassandra/utils/BloomFilter.java
@@ -21,9 +21,10 @@ import java.nio.ByteBuffer;
import com.google.common.annotations.VisibleForTesting;
+import org.apache.cassandra.utils.concurrent.WrappedSharedCloseable;
import org.apache.cassandra.utils.obs.IBitSet;
-public abstract class BloomFilter implements IFilter
+public abstract class BloomFilter extends WrappedSharedCloseable implements IFilter
{
private static final ThreadLocal<long[]> reusableIndexes = new ThreadLocal<long[]>()
{
@@ -36,12 +37,20 @@ public abstract class BloomFilter implements IFilter
public final IBitSet bitset;
public final int hashCount;
- BloomFilter(int hashes, IBitSet bitset)
+ BloomFilter(int hashCount, IBitSet bitset)
{
- this.hashCount = hashes;
+ super(bitset);
+ this.hashCount = hashCount;
this.bitset = bitset;
}
+ BloomFilter(BloomFilter copy)
+ {
+ super(copy);
+ this.hashCount = copy.hashCount;
+ this.bitset = copy.bitset;
+ }
+
// Murmur is faster than an SHA-based approach and provides as-good collision
// resistance. The combinatorial generation approach described in
// http://www.eecs.harvard.edu/~kirsch/pubs/bbbf/esa06.pdf
@@ -110,9 +119,4 @@ public abstract class BloomFilter implements IFilter
{
bitset.clear();
}
-
- public void close()
- {
- bitset.close();
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/IFilter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/IFilter.java b/src/java/org/apache/cassandra/utils/IFilter.java
index 60c0590..bde6333 100644
--- a/src/java/org/apache/cassandra/utils/IFilter.java
+++ b/src/java/org/apache/cassandra/utils/IFilter.java
@@ -17,10 +17,11 @@
*/
package org.apache.cassandra.utils;
-import java.io.Closeable;
import java.nio.ByteBuffer;
-public interface IFilter extends Closeable
+import org.apache.cassandra.utils.concurrent.SharedCloseable;
+
+public interface IFilter extends SharedCloseable
{
void add(ByteBuffer key);
@@ -32,6 +33,8 @@ public interface IFilter extends Closeable
void close();
+ IFilter sharedCopy();
+
/**
* Returns the amount of memory in bytes used off heap.
* @return the amount of memory in bytes used off heap
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java b/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java
index f7c7632..431ca5b 100644
--- a/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java
+++ b/src/java/org/apache/cassandra/utils/Murmur3BloomFilter.java
@@ -26,9 +26,14 @@ public class Murmur3BloomFilter extends BloomFilter
{
public static final Murmur3BloomFilterSerializer serializer = new Murmur3BloomFilterSerializer();
- public Murmur3BloomFilter(int hashes, IBitSet bs)
+ public Murmur3BloomFilter(int hashCount, IBitSet bs)
{
- super(hashes, bs);
+ super(hashCount, bs);
+ }
+
+ protected Murmur3BloomFilter(Murmur3BloomFilter copy)
+ {
+ super(copy);
}
public long serializedSize()
@@ -36,6 +41,11 @@ public class Murmur3BloomFilter extends BloomFilter
return serializer.serializedSize(this, TypeSizes.NATIVE);
}
+ public IFilter sharedCopy()
+ {
+ return new Murmur3BloomFilter(this);
+ }
+
@Override
public long offHeapSize()
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/concurrent/Ref.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/concurrent/Ref.java b/src/java/org/apache/cassandra/utils/concurrent/Ref.java
index 4afceb0..ad1293b 100644
--- a/src/java/org/apache/cassandra/utils/concurrent/Ref.java
+++ b/src/java/org/apache/cassandra/utils/concurrent/Ref.java
@@ -2,24 +2,69 @@ package org.apache.cassandra.utils.concurrent;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
+import java.util.Collections;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.apache.cassandra.concurrent.NamedThreadFactory;
+
/**
- * A single managed reference to a RefCounted object
+ * An object that needs ref counting does the two following:
+ * - defines a Tidy object that will cleanup once it's gone,
+ * (this must retain no references to the object we're tracking (only its resources and how to clean up))
+ * Then, one of two options:
+ * 1) Construct a Ref directly pointing to it, and always use this Ref; or
+ * 2)
+ * - implements RefCounted
+ * - encapsulates a Ref, we'll call selfRef, to which it proxies all calls to RefCounted behaviours
+ * - users must ensure no references to the selfRef leak, or are retained outside of a method scope.
+ * (to ensure the selfRef is collected with the object, so that leaks may be detected and corrected)
+ *
+ * This class' functionality is achieved by what may look at first glance like a complex web of references,
+ * but boils down to:
+ *
+ * Target --> selfRef --> [Ref.State] <--> Ref.GlobalState --> Tidy
+ * ^
+ * |
+ * Ref ----------------------------------------
+ * |
+ * Global -------------------------------------
+ *
+ * So that, if Target is collected, Impl is collected and, hence, so is selfRef.
+ *
+ * Once ref or selfRef are collected, the paired Ref.State's release method is called, which if it had
+ * not already been called will update Ref.GlobalState and log an error.
+ *
+ * Once the Ref.GlobalState has been completely released, the Tidy method is called and it removes the global reference
+ * to itself so it may also be collected.
*/
-public final class Ref
+public final class Ref<T> implements RefCounted<T>, AutoCloseable
{
static final Logger logger = LoggerFactory.getLogger(Ref.class);
static final boolean DEBUG_ENABLED = System.getProperty("cassandra.debugrefcount", "false").equalsIgnoreCase("true");
final State state;
+ final T referent;
- Ref(RefCountedImpl.GlobalState state, boolean isSharedRef)
+ public Ref(T referent, Tidy tidy)
{
- this.state = new State(state, this, RefCountedImpl.referenceQueue, isSharedRef);
+ this.state = new State(new GlobalState(tidy), this, referenceQueue);
+ this.referent = referent;
+ }
+
+ Ref(T referent, GlobalState state)
+ {
+ this.state = new State(state, this, referenceQueue);
+ this.referent = referent;
}
/**
@@ -32,6 +77,36 @@ public final class Ref
state.release(false);
}
+ public void ensureReleased()
+ {
+ state.ensureReleased();
+ }
+
+ public void close()
+ {
+ state.ensureReleased();
+ }
+
+ public T get()
+ {
+ state.assertNotReleased();
+ return referent;
+ }
+
+ public Ref<T> tryRef()
+ {
+ return state.globalState.ref() ? new Ref<>(referent, state.globalState) : null;
+ }
+
+ public Ref<T> ref()
+ {
+ Ref<T> ref = tryRef();
+ // TODO: print the last release as well as the release here
+ if (ref == null)
+ state.assertNotReleased();
+ return ref;
+ }
+
/**
* A convenience method for reporting:
* @return the number of currently extant references globally, including the shared reference
@@ -41,25 +116,36 @@ public final class Ref
return state.globalState.count();
}
- // similar to RefCountedState, but tracks only the management of each unique ref created to the managed object
+ // similar to Ref.GlobalState, but tracks only the management of each unique ref created to the managed object
// ensures it is only released once, and that it is always released
static final class State extends PhantomReference<Ref>
{
final Debug debug = DEBUG_ENABLED ? new Debug() : null;
- final boolean isSharedRef;
- final RefCountedImpl.GlobalState globalState;
+ final GlobalState globalState;
private volatile int released;
private static final AtomicIntegerFieldUpdater<State> releasedUpdater = AtomicIntegerFieldUpdater.newUpdater(State.class, "released");
- public State(final RefCountedImpl.GlobalState globalState, Ref reference, ReferenceQueue<? super Ref> q, boolean isSharedRef)
+ public State(final GlobalState globalState, Ref reference, ReferenceQueue<? super Ref> q)
{
super(reference, q);
this.globalState = globalState;
- this.isSharedRef = isSharedRef;
globalState.register(this);
}
+ void assertNotReleased()
+ {
+ if (DEBUG_ENABLED && released == 1)
+ debug.log(toString());
+ assert released == 0;
+ }
+
+ void ensureReleased()
+ {
+ if (releasedUpdater.getAndSet(this, 1) == 0)
+ globalState.release(this);
+ }
+
void release(boolean leak)
{
if (!releasedUpdater.compareAndSet(this, 0, 1))
@@ -67,7 +153,7 @@ public final class Ref
if (!leak)
{
String id = this.toString();
- logger.error("BAD RELEASE: attempted to release a{} reference ({}) that has already been released", isSharedRef ? " shared" : "", id);
+ logger.error("BAD RELEASE: attempted to release a reference ({}) that has already been released", id);
if (DEBUG_ENABLED)
debug.log(id);
throw new IllegalStateException("Attempted to release a reference that has already been released");
@@ -78,10 +164,7 @@ public final class Ref
if (leak)
{
String id = this.toString();
- if (isSharedRef)
- logger.error("LEAK DETECTED: the shared reference ({}) to {} was not released before the object was garbage collected", id, globalState);
- else
- logger.error("LEAK DETECTED: a reference ({}) to {} was not released before the reference was garbage collected", id, globalState);
+ logger.error("LEAK DETECTED: a reference ({}) to {} was not released before the reference was garbage collected", id, globalState);
if (DEBUG_ENABLED)
debug.log(id);
}
@@ -129,6 +212,101 @@ public final class Ref
}
}
-}
+ // the object that manages the actual cleaning up; this does not reference the target object
+ // so that we can detect when references are lost to the resource itself, and still cleanup afterwards
+ // the Tidy object MUST not contain any references to the object we are managing
+ static final class GlobalState
+ {
+ // we need to retain a reference to each of the PhantomReference instances
+ // we are using to track individual refs
+ private final ConcurrentLinkedQueue<State> locallyExtant = new ConcurrentLinkedQueue<>();
+ // the number of live refs
+ private final AtomicInteger counts = new AtomicInteger();
+ // the object to call to cleanup when our refs are all finished with
+ private final Tidy tidy;
+
+ GlobalState(Tidy tidy)
+ {
+ this.tidy = tidy;
+ globallyExtant.add(this);
+ }
+ void register(Ref.State ref)
+ {
+ locallyExtant.add(ref);
+ }
+ // increment ref count if not already tidied, and return success/failure
+ boolean ref()
+ {
+ while (true)
+ {
+ int cur = counts.get();
+ if (cur < 0)
+ return false;
+ if (counts.compareAndSet(cur, cur + 1))
+ return true;
+ }
+ }
+
+ // release a single reference, and cleanup if no more are extant
+ void release(Ref.State ref)
+ {
+ locallyExtant.remove(ref);
+ if (-1 == counts.decrementAndGet())
+ {
+ globallyExtant.remove(this);
+ try
+ {
+ tidy.tidy();
+ }
+ catch (Throwable t)
+ {
+ logger.error("Error when closing {}", this, t);
+ Throwables.propagate(t);
+ }
+ }
+ }
+
+ int count()
+ {
+ return 1 + counts.get();
+ }
+
+ public String toString()
+ {
+ return tidy.getClass() + "@" + System.identityHashCode(tidy) + ":" + tidy.name();
+ }
+ }
+
+ private static final Set<GlobalState> globallyExtant = Collections.newSetFromMap(new ConcurrentHashMap<GlobalState, Boolean>());
+ static final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
+ private static final ExecutorService EXEC = Executors.newFixedThreadPool(1, new NamedThreadFactory("Reference-Reaper"));
+ static
+ {
+ EXEC.execute(new Runnable()
+ {
+ public void run()
+ {
+ try
+ {
+ while (true)
+ {
+ Object obj = referenceQueue.remove();
+ if (obj instanceof Ref.State)
+ {
+ ((Ref.State) obj).release(true);
+ }
+ }
+ }
+ catch (InterruptedException e)
+ {
+ }
+ finally
+ {
+ EXEC.execute(this);
+ }
+ }
+ });
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java b/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java
index 7ad51ad..e68c7bd 100644
--- a/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java
+++ b/src/java/org/apache/cassandra/utils/concurrent/RefCounted.java
@@ -36,59 +36,29 @@ import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.NamedThreadFactory;
/**
- * An object that needs ref counting does the following:
+ * An object that needs ref counting does the two following:
* - defines a Tidy object that will cleanup once it's gone,
* (this must retain no references to the object we're tracking (only its resources and how to clean up))
+ * Then, one of two options:
+ * 1) Construct a Ref directly pointing to it, and always use this Ref; or
+ * 2)
* - implements RefCounted
- * - encapsulates a RefCounted.Impl, to which it proxies all calls to RefCounted behaviours
- * - ensures no external access to the encapsulated Impl, and permits no references to it to leak
- * - users must ensure no references to the sharedRef leak, or are retained outside of a method scope either.
- * (to ensure the sharedRef is collected with the object, so that leaks may be detected and corrected)
- *
- * This class' functionality is achieved by what may look at first glance like a complex web of references,
- * but boils down to:
- *
- * Target --> Impl --> sharedRef --> [RefState] <--> RefCountedState --> Tidy
- * ^ ^
- * | |
- * Ref ----------------------------------- |
- * |
- * Global -------------------------------------------------
- *
- * So that, if Target is collected, Impl is collected and, hence, so is sharedRef.
- *
- * Once ref or sharedRef are collected, the paired RefState's release method is called, which if it had
- * not already been called will update RefCountedState and log an error.
- *
- * Once the RefCountedState has been completely released, the Tidy method is called and it removes the global reference
- * to itself so it may also be collected.
+ * - encapsulates a Ref, we'll call selfRef, to which it proxies all calls to RefCounted behaviours
+ * - users must ensure no references to the selfRef leak, or are retained outside of a method scope.
+ * (to ensure the selfRef is collected with the object, so that leaks may be detected and corrected)
*/
-public interface RefCounted
+public interface RefCounted<T>
{
-
/**
* @return the a new Ref() to the managed object, incrementing its refcount, or null if it is already released
*/
- public Ref tryRef();
+ public Ref<T> tryRef();
- /**
- * @return the shared Ref that is created at instantiation of the RefCounted instance.
- * Once released, if no other refs are extant the object will be tidied; references to
- * this object should never be retained outside of a method's scope
- */
- public Ref sharedRef();
+ public Ref<T> ref();
public static interface Tidy
{
- void tidy();
+ void tidy() throws Exception;
String name();
}
-
- public static class Impl
- {
- public static RefCounted get(Tidy tidy)
- {
- return new RefCountedImpl(tidy);
- }
- }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/concurrent/RefCountedImpl.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/concurrent/RefCountedImpl.java b/src/java/org/apache/cassandra/utils/concurrent/RefCountedImpl.java
deleted file mode 100644
index 0de6f40..0000000
--- a/src/java/org/apache/cassandra/utils/concurrent/RefCountedImpl.java
+++ /dev/null
@@ -1,132 +0,0 @@
-package org.apache.cassandra.utils.concurrent;
-
-import java.lang.ref.ReferenceQueue;
-import java.util.Collections;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.cassandra.concurrent.NamedThreadFactory;
-
-// default implementation; can be hidden and proxied (like we do for SSTableReader)
-final class RefCountedImpl implements RefCounted
-{
- private final Ref sharedRef;
- private final GlobalState state;
-
- public RefCountedImpl(Tidy tidy)
- {
- this.state = new GlobalState(tidy);
- sharedRef = new Ref(this.state, true);
- globallyExtant.add(this.state);
- }
-
- /**
- * see {@link RefCounted#tryRef()}
- */
- public Ref tryRef()
- {
- return state.ref() ? new Ref(state, false) : null;
- }
-
- /**
- * see {@link RefCounted#sharedRef()}
- */
- public Ref sharedRef()
- {
- return sharedRef;
- }
-
- // the object that manages the actual cleaning up; this does not reference the RefCounted.Impl
- // so that we can detect when references are lost to the resource itself, and still cleanup afterwards
- // the Tidy object MUST not contain any references to the object we are managing
- static final class GlobalState
- {
- // we need to retain a reference to each of the PhantomReference instances
- // we are using to track individual refs
- private final ConcurrentLinkedQueue<Ref.State> locallyExtant = new ConcurrentLinkedQueue<>();
- // the number of live refs
- private final AtomicInteger counts = new AtomicInteger();
- // the object to call to cleanup when our refs are all finished with
- private final Tidy tidy;
-
- GlobalState(Tidy tidy)
- {
- this.tidy = tidy;
- }
-
- void register(Ref.State ref)
- {
- locallyExtant.add(ref);
- }
-
- // increment ref count if not already tidied, and return success/failure
- boolean ref()
- {
- while (true)
- {
- int cur = counts.get();
- if (cur < 0)
- return false;
- if (counts.compareAndSet(cur, cur + 1))
- return true;
- }
- }
-
- // release a single reference, and cleanup if no more are extant
- void release(Ref.State ref)
- {
- locallyExtant.remove(ref);
- if (-1 == counts.decrementAndGet())
- {
- globallyExtant.remove(this);
- tidy.tidy();
- }
- }
-
- int count()
- {
- return 1 + counts.get();
- }
-
- public String toString()
- {
- return tidy.name();
- }
- }
-
- private static final Set<GlobalState> globallyExtant = Collections.newSetFromMap(new ConcurrentHashMap<GlobalState, Boolean>());
- static final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
- private static final ExecutorService EXEC = Executors.newFixedThreadPool(1, new NamedThreadFactory("Reference-Reaper"));
- static
- {
- EXEC.execute(new Runnable()
- {
- public void run()
- {
- try
- {
- while (true)
- {
- Object obj = referenceQueue.remove();
- if (obj instanceof Ref.State)
- {
- ((Ref.State) obj).release(true);
- }
- }
- }
- catch (InterruptedException e)
- {
- }
- finally
- {
- EXEC.execute(this);
- }
- }
- });
- }
-}
-
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/concurrent/Refs.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/concurrent/Refs.java b/src/java/org/apache/cassandra/utils/concurrent/Refs.java
index ed5fcfa..3a930d2 100644
--- a/src/java/org/apache/cassandra/utils/concurrent/Refs.java
+++ b/src/java/org/apache/cassandra/utils/concurrent/Refs.java
@@ -12,16 +12,16 @@ import com.google.common.collect.Iterators;
*
* All of the java.util.Collection operations that modify the collection are unsupported.
*/
-public final class Refs<T extends RefCounted> extends AbstractCollection<T> implements AutoCloseable
+public final class Refs<T extends RefCounted<T>> extends AbstractCollection<T> implements AutoCloseable
{
- private final Map<T, Ref> references;
+ private final Map<T, Ref<T>> references;
public Refs()
{
this.references = new HashMap<>();
}
- public Refs(Map<T, Ref> references)
+ public Refs(Map<T, Ref<T>> references)
{
this.references = new HashMap<>(references);
}
@@ -88,11 +88,11 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
*/
public void release(Collection<T> release)
{
- List<Ref> refs = new ArrayList<>();
+ List<Ref<T>> refs = new ArrayList<>();
List<T> notPresent = null;
for (T obj : release)
{
- Ref ref = references.remove(obj);
+ Ref<T> ref = references.remove(obj);
if (ref == null)
{
if (notPresent == null)
@@ -132,7 +132,7 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
*/
public boolean tryRef(T t)
{
- Ref ref = t.tryRef();
+ Ref<T> ref = t.tryRef();
if (ref == null)
return false;
ref = references.put(t, ref);
@@ -156,8 +156,8 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
*/
public Refs<T> addAll(Refs<T> add)
{
- List<Ref> overlap = new ArrayList<>();
- for (Map.Entry<T, Ref> e : add.references.entrySet())
+ List<Ref<T>> overlap = new ArrayList<>();
+ for (Map.Entry<T, Ref<T>> e : add.references.entrySet())
{
if (this.references.containsKey(e.getKey()))
overlap.add(e.getValue());
@@ -172,12 +172,12 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
/**
* Acquire a reference to all of the provided objects, or none
*/
- public static <T extends RefCounted> Refs<T> tryRef(Iterable<T> reference)
+ public static <T extends RefCounted<T>> Refs<T> tryRef(Iterable<T> reference)
{
- HashMap<T, Ref> refs = new HashMap<>();
+ HashMap<T, Ref<T>> refs = new HashMap<>();
for (T rc : reference)
{
- Ref ref = rc.tryRef();
+ Ref<T> ref = rc.tryRef();
if (ref == null)
{
release(refs.values());
@@ -188,7 +188,7 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
return new Refs<T>(refs);
}
- public static <T extends RefCounted> Refs<T> ref(Iterable<T> reference)
+ public static <T extends RefCounted<T>> Refs<T> ref(Iterable<T> reference)
{
Refs<T> refs = tryRef(reference);
if (refs != null)
@@ -196,7 +196,7 @@ public final class Refs<T extends RefCounted> extends AbstractCollection<T> impl
throw new IllegalStateException();
}
- private static void release(Iterable<Ref> refs)
+ private static void release(Iterable<? extends Ref<?>> refs)
{
Throwable fail = null;
for (Ref ref : refs)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java b/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java
index b23f1c6..02efa65 100644
--- a/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java
+++ b/src/java/org/apache/cassandra/utils/obs/OffHeapBitSet.java
@@ -172,4 +172,9 @@ public class OffHeapBitSet implements IBitSet
}
return (int) ((h >> 32) ^ h) + 0x98761234;
}
+
+ public String toString()
+ {
+ return "[OffHeapBitSet]";
+ }
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java b/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
index 2732be5..ec8ad8a 100644
--- a/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
+++ b/test/unit/org/apache/cassandra/db/ColumnFamilyStoreTest.java
@@ -1753,9 +1753,10 @@ public class ColumnFamilyStoreTest extends SchemaLoader
sstables = dir.sstableLister().list();
assertEquals(2, sstables.size());
+ SSTableReader sstable2 = SSTableReader.open(sstable1.descriptor);
UUID compactionTaskID = SystemKeyspace.startCompaction(
Keyspace.open(ks).getColumnFamilyStore(cf),
- Collections.singleton(SSTableReader.open(sstable1.descriptor)));
+ Collections.singleton(sstable2));
Map<Integer, UUID> unfinishedCompaction = new HashMap<>();
unfinishedCompaction.put(sstable1.descriptor.generation, compactionTaskID);
@@ -1768,6 +1769,8 @@ public class ColumnFamilyStoreTest extends SchemaLoader
Map<Pair<String, String>, Map<Integer, UUID>> unfinished = SystemKeyspace.getUnfinishedCompactions();
assertTrue(unfinished.isEmpty());
+ sstable1.selfRef().release();
+ sstable2.selfRef().release();
}
/**
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java b/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
index d9442c7..7756abe 100644
--- a/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
+++ b/test/unit/org/apache/cassandra/db/compaction/AntiCompactionTest.java
@@ -96,7 +96,7 @@ public class AntiCompactionTest extends SchemaLoader
for (SSTableReader sstable : store.getSSTables())
{
assertFalse(sstable.isMarkedCompacted());
- assertEquals(1, sstable.sharedRef().globalCount());
+ assertEquals(1, sstable.selfRef().globalCount());
}
assertEquals(0, store.getDataTracker().getCompacting().size());
assertEquals(repairedKeys, 4);
@@ -157,7 +157,7 @@ public class AntiCompactionTest extends SchemaLoader
CompactionManager.instance.performAnticompaction(store, ranges, refs, 1);
assertThat(store.getSSTables().size(), is(1));
assertThat(Iterables.get(store.getSSTables(), 0).isRepaired(), is(false));
- assertThat(Iterables.get(store.getSSTables(), 0).sharedRef().globalCount(), is(1));
+ assertThat(Iterables.get(store.getSSTables(), 0).selfRef().globalCount(), is(1));
assertThat(store.getDataTracker().getCompacting().size(), is(0));
}
@@ -174,7 +174,7 @@ public class AntiCompactionTest extends SchemaLoader
assertThat(store.getSSTables().size(), is(1));
assertThat(Iterables.get(store.getSSTables(), 0).isRepaired(), is(true));
- assertThat(Iterables.get(store.getSSTables(), 0).sharedRef().globalCount(), is(1));
+ assertThat(Iterables.get(store.getSSTables(), 0).selfRef().globalCount(), is(1));
assertThat(store.getDataTracker().getCompacting().size(), is(0));
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java b/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
index d9bf017..87b284e 100644
--- a/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
+++ b/test/unit/org/apache/cassandra/db/compaction/SizeTieredCompactionStrategyTest.java
@@ -173,9 +173,9 @@ public class SizeTieredCompactionStrategyTest extends SchemaLoader
List<SSTableReader> interestingBucket = mostInterestingBucket(Collections.singletonList(sstrs.subList(0, 2)), 4, 32);
assertTrue("nothing should be returned when all buckets are below the min threshold", interestingBucket.isEmpty());
- sstrs.get(0).readMeter = new RestorableMeter(100.0, 100.0);
- sstrs.get(1).readMeter = new RestorableMeter(200.0, 200.0);
- sstrs.get(2).readMeter = new RestorableMeter(300.0, 300.0);
+ sstrs.get(0).overrideReadMeter(new RestorableMeter(100.0, 100.0));
+ sstrs.get(1).overrideReadMeter(new RestorableMeter(200.0, 200.0));
+ sstrs.get(2).overrideReadMeter(new RestorableMeter(300.0, 300.0));
long estimatedKeys = sstrs.get(0).estimatedKeys();
@@ -215,43 +215,43 @@ public class SizeTieredCompactionStrategyTest extends SchemaLoader
List<SSTableReader> sstrs = new ArrayList<>(cfs.getSSTables());
for (SSTableReader sstr : sstrs)
- sstr.readMeter = null;
+ sstr.overrideReadMeter(null);
filtered = filterColdSSTables(sstrs, 0.05, 0);
assertEquals("when there are no read meters, no sstables should be filtered", sstrs.size(), filtered.size());
for (SSTableReader sstr : sstrs)
- sstr.readMeter = new RestorableMeter(0.0, 0.0);
+ sstr.overrideReadMeter(new RestorableMeter(0.0, 0.0));
filtered = filterColdSSTables(sstrs, 0.05, 0);
assertEquals("when all read meters are zero, no sstables should be filtered", sstrs.size(), filtered.size());
// leave all read rates at 0 besides one
- sstrs.get(0).readMeter = new RestorableMeter(1000.0, 1000.0);
+ sstrs.get(0).overrideReadMeter(new RestorableMeter(1000.0, 1000.0));
filtered = filterColdSSTables(sstrs, 0.05, 0);
assertEquals("there should only be one hot sstable", 1, filtered.size());
- assertEquals(1000.0, filtered.get(0).readMeter.twoHourRate(), 0.5);
+ assertEquals(1000.0, filtered.get(0).getReadMeter().twoHourRate(), 0.5);
// the total read rate is 100, and we'll set a threshold of 2.5%, so two of the sstables with read
// rate 1.0 should be ignored, but not the third
for (SSTableReader sstr : sstrs)
- sstr.readMeter = new RestorableMeter(0.0, 0.0);
- sstrs.get(0).readMeter = new RestorableMeter(97.0, 97.0);
- sstrs.get(1).readMeter = new RestorableMeter(1.0, 1.0);
- sstrs.get(2).readMeter = new RestorableMeter(1.0, 1.0);
- sstrs.get(3).readMeter = new RestorableMeter(1.0, 1.0);
+ sstr.overrideReadMeter(new RestorableMeter(0.0, 0.0));
+ sstrs.get(0).overrideReadMeter(new RestorableMeter(97.0, 97.0));
+ sstrs.get(1).overrideReadMeter(new RestorableMeter(1.0, 1.0));
+ sstrs.get(2).overrideReadMeter(new RestorableMeter(1.0, 1.0));
+ sstrs.get(3).overrideReadMeter(new RestorableMeter(1.0, 1.0));
filtered = filterColdSSTables(sstrs, 0.025, 0);
assertEquals(2, filtered.size());
- assertEquals(98.0, filtered.get(0).readMeter.twoHourRate() + filtered.get(1).readMeter.twoHourRate(), 0.5);
+ assertEquals(98.0, filtered.get(0).getReadMeter().twoHourRate() + filtered.get(1).getReadMeter().twoHourRate(), 0.5);
// make sure a threshold of 0.0 doesn't result in any sstables being filtered
for (SSTableReader sstr : sstrs)
- sstr.readMeter = new RestorableMeter(1.0, 1.0);
+ sstr.overrideReadMeter(new RestorableMeter(1.0, 1.0));
filtered = filterColdSSTables(sstrs, 0.0, 0);
assertEquals(sstrs.size(), filtered.size());
// just for fun, set a threshold where all sstables are considered cold
for (SSTableReader sstr : sstrs)
- sstr.readMeter = new RestorableMeter(1.0, 1.0);
+ sstr.overrideReadMeter(new RestorableMeter(1.0, 1.0));
filtered = filterColdSSTables(sstrs, 1.0, 0);
assertTrue(filtered.isEmpty());
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java b/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
index 0a2b5a6..0bb9d5f 100644
--- a/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/IndexSummaryManagerTest.java
@@ -90,7 +90,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
private static List<SSTableReader> resetSummaries(List<SSTableReader> sstables, long originalOffHeapSize) throws IOException
{
for (SSTableReader sstable : sstables)
- sstable.readMeter = new RestorableMeter(100.0, 100.0);
+ sstable.overrideReadMeter(new RestorableMeter(100.0, 100.0));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, originalOffHeapSize * sstables.size());
for (SSTableReader sstable : sstables)
@@ -117,7 +117,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
{
public int compare(SSTableReader o1, SSTableReader o2)
{
- return Double.compare(o1.readMeter.fifteenMinuteRate(), o2.readMeter.fifteenMinuteRate());
+ return Double.compare(o1.getReadMeter().fifteenMinuteRate(), o2.getReadMeter().fifteenMinuteRate());
}
};
@@ -172,7 +172,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
List<SSTableReader> sstables = new ArrayList<>(cfs.getSSTables());
for (SSTableReader sstable : sstables)
- sstable.readMeter = new RestorableMeter(100.0, 100.0);
+ sstable.overrideReadMeter(new RestorableMeter(100.0, 100.0));
for (SSTableReader sstable : sstables)
assertEquals(cfs.metadata.getMinIndexInterval(), sstable.getEffectiveIndexInterval(), 0.001);
@@ -244,7 +244,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
List<SSTableReader> sstables = new ArrayList<>(cfs.getSSTables());
for (SSTableReader sstable : sstables)
- sstable.readMeter = new RestorableMeter(100.0, 100.0);
+ sstable.overrideReadMeter(new RestorableMeter(100.0, 100.0));
IndexSummaryManager.redistributeSummaries(Collections.EMPTY_LIST, sstables, 1);
sstables = new ArrayList<>(cfs.getSSTables());
@@ -286,7 +286,7 @@ public class IndexSummaryManagerTest extends SchemaLoader
List<SSTableReader> sstables = new ArrayList<>(cfs.getSSTables());
for (SSTableReader sstable : sstables)
- sstable.readMeter = new RestorableMeter(100.0, 100.0);
+ sstable.overrideReadMeter(new RestorableMeter(100.0, 100.0));
long singleSummaryOffHeapSpace = sstables.get(0).getIndexSummaryOffHeapSize();
@@ -325,8 +325,8 @@ public class IndexSummaryManagerTest extends SchemaLoader
// make two of the four sstables cold, only leave enough space for three full index summaries,
// so the two cold sstables should get downsampled to be half of their original size
- sstables.get(0).readMeter = new RestorableMeter(50.0, 50.0);
- sstables.get(1).readMeter = new RestorableMeter(50.0, 50.0);
+ sstables.get(0).overrideReadMeter(new RestorableMeter(50.0, 50.0));
+ sstables.get(1).overrideReadMeter(new RestorableMeter(50.0, 50.0));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, (singleSummaryOffHeapSpace * 3));
Collections.sort(sstables, hotnessComparator);
assertEquals(BASE_SAMPLING_LEVEL / 2, sstables.get(0).getIndexSummarySamplingLevel());
@@ -338,8 +338,8 @@ public class IndexSummaryManagerTest extends SchemaLoader
// small increases or decreases in the read rate don't result in downsampling or upsampling
double lowerRate = 50.0 * (DOWNSAMPLE_THESHOLD + (DOWNSAMPLE_THESHOLD * 0.10));
double higherRate = 50.0 * (UPSAMPLE_THRESHOLD - (UPSAMPLE_THRESHOLD * 0.10));
- sstables.get(0).readMeter = new RestorableMeter(lowerRate, lowerRate);
- sstables.get(1).readMeter = new RestorableMeter(higherRate, higherRate);
+ sstables.get(0).overrideReadMeter(new RestorableMeter(lowerRate, lowerRate));
+ sstables.get(1).overrideReadMeter(new RestorableMeter(higherRate, higherRate));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, (singleSummaryOffHeapSpace * 3));
Collections.sort(sstables, hotnessComparator);
assertEquals(BASE_SAMPLING_LEVEL / 2, sstables.get(0).getIndexSummarySamplingLevel());
@@ -350,10 +350,10 @@ public class IndexSummaryManagerTest extends SchemaLoader
// reset, and then this time, leave enough space for one of the cold sstables to not get downsampled
sstables = resetSummaries(sstables, singleSummaryOffHeapSpace);
- sstables.get(0).readMeter = new RestorableMeter(1.0, 1.0);
- sstables.get(1).readMeter = new RestorableMeter(2.0, 2.0);
- sstables.get(2).readMeter = new RestorableMeter(1000.0, 1000.0);
- sstables.get(3).readMeter = new RestorableMeter(1000.0, 1000.0);
+ sstables.get(0).overrideReadMeter(new RestorableMeter(1.0, 1.0));
+ sstables.get(1).overrideReadMeter(new RestorableMeter(2.0, 2.0));
+ sstables.get(2).overrideReadMeter(new RestorableMeter(1000.0, 1000.0));
+ sstables.get(3).overrideReadMeter(new RestorableMeter(1000.0, 1000.0));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, (singleSummaryOffHeapSpace * 3) + 50);
Collections.sort(sstables, hotnessComparator);
@@ -372,10 +372,10 @@ public class IndexSummaryManagerTest extends SchemaLoader
// coldest sstables will get downsampled to 4/128 of their size, leaving us with 1 and 92/128th index
// summaries worth of space. The hottest sstable should get a full index summary, and the one in the middle
// should get the remainder.
- sstables.get(0).readMeter = new RestorableMeter(0.0, 0.0);
- sstables.get(1).readMeter = new RestorableMeter(0.0, 0.0);
- sstables.get(2).readMeter = new RestorableMeter(92, 92);
- sstables.get(3).readMeter = new RestorableMeter(128.0, 128.0);
+ sstables.get(0).overrideReadMeter(new RestorableMeter(0.0, 0.0));
+ sstables.get(1).overrideReadMeter(new RestorableMeter(0.0, 0.0));
+ sstables.get(2).overrideReadMeter(new RestorableMeter(92, 92));
+ sstables.get(3).overrideReadMeter(new RestorableMeter(128.0, 128.0));
sstables = redistributeSummaries(Collections.EMPTY_LIST, sstables, (long) (singleSummaryOffHeapSpace + (singleSummaryOffHeapSpace * (92.0 / BASE_SAMPLING_LEVEL))));
Collections.sort(sstables, hotnessComparator);
assertEquals(1, sstables.get(0).getIndexSummarySize()); // at the min sampling level
@@ -421,10 +421,13 @@ public class IndexSummaryManagerTest extends SchemaLoader
SSTableReader sstable = original;
for (int samplingLevel = 1; samplingLevel < BASE_SAMPLING_LEVEL; samplingLevel++)
{
+ SSTableReader prev = sstable;
sstable = sstable.cloneWithNewSummarySamplingLevel(cfs, samplingLevel);
assertEquals(samplingLevel, sstable.getIndexSummarySamplingLevel());
int expectedSize = (numRows * samplingLevel) / (sstable.metadata.getMinIndexInterval() * BASE_SAMPLING_LEVEL);
assertEquals(expectedSize, sstable.getIndexSummarySize(), 1);
+ if (prev != original)
+ prev.selfRef().release();
}
// don't leave replaced SSTRs around to break other tests
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java b/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
index 8bef669..19ba274 100644
--- a/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
@@ -118,7 +118,7 @@ public class LegacySSTableTest extends SchemaLoader
ranges.add(new Range<>(p.getMinimumToken(), p.getToken(ByteBufferUtil.bytes("100"))));
ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("100")), p.getMinimumToken()));
ArrayList<StreamSession.SSTableStreamingSections> details = new ArrayList<>();
- details.add(new StreamSession.SSTableStreamingSections(sstable, sstable.tryRef(),
+ details.add(new StreamSession.SSTableStreamingSections(sstable, sstable.ref(),
sstable.getPositionsForRanges(ranges),
sstable.estimatedKeysForRanges(ranges), sstable.getSSTableMetadata().repairedAt));
new StreamPlan("LegacyStreamingTest").transferFiles(FBUtilities.getBroadcastAddress(), details)
@@ -138,6 +138,7 @@ public class LegacySSTableTest extends SchemaLoader
assert cf.deletionInfo().equals(DeletionInfo.live());
assert iter.next().name().toByteBuffer().equals(key);
}
+ sstable.selfRef().release();
}
@Test
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java b/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
index 51588f2..9607673 100644
--- a/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
@@ -203,15 +203,15 @@ public class SSTableReaderTest extends SchemaLoader
store.forceBlockingFlush();
SSTableReader sstable = store.getSSTables().iterator().next();
- assertEquals(0, sstable.readMeter.count());
+ assertEquals(0, sstable.getReadMeter().count());
DecoratedKey key = sstable.partitioner.decorateKey(ByteBufferUtil.bytes("4"));
store.getColumnFamily(key, Composites.EMPTY, Composites.EMPTY, false, 100, 100);
- assertEquals(1, sstable.readMeter.count());
+ assertEquals(1, sstable.getReadMeter().count());
store.getColumnFamily(key, cellname("0"), cellname("0"), false, 100, 100);
- assertEquals(2, sstable.readMeter.count());
+ assertEquals(2, sstable.getReadMeter().count());
store.getColumnFamily(Util.namesQueryFilter(store, key, cellname("0")));
- assertEquals(3, sstable.readMeter.count());
+ assertEquals(3, sstable.getReadMeter().count());
}
@Test
@@ -334,6 +334,7 @@ public class SSTableReaderTest extends SchemaLoader
Assert.assertArrayEquals(ByteBufferUtil.getArray(firstKey.getKey()), target.getIndexSummaryKey(0));
assert target.first.equals(firstKey);
assert target.last.equals(lastKey);
+ target.selfRef().release();
}
@Test
@@ -360,6 +361,7 @@ public class SSTableReaderTest extends SchemaLoader
SSTableReader reopened = SSTableReader.open(sstable.descriptor);
assert reopened.first.getToken() instanceof LocalToken;
+ reopened.selfRef().release();
}
/** see CASSANDRA-5407 */
@@ -417,6 +419,7 @@ public class SSTableReaderTest extends SchemaLoader
SSTableReader bulkLoaded = SSTableReader.openForBatch(sstable.descriptor, components, store.metadata, sstable.partitioner);
sections = bulkLoaded.getPositionsForRanges(ranges);
assert sections.size() == 1 : "Expected to find range in sstable opened for bulk loading";
+ bulkLoaded.selfRef().release();
}
@Test
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java b/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
index acf8c90..2e11624 100644
--- a/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
@@ -19,11 +19,7 @@ package org.apache.cassandra.io.sstable;
import java.io.File;
import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
import com.google.common.collect.Sets;
import org.junit.Test;
@@ -200,10 +196,11 @@ public class SSTableRewriterTest extends SchemaLoader
assertTrue(s != s2);
assertFileCounts(dir.list(), 2, 3);
s.markObsolete();
- s.sharedRef().release();
+ s.selfRef().release();
+ s2.selfRef().release();
Thread.sleep(1000);
assertFileCounts(dir.list(), 0, 3);
- writer.abort(false);
+ writer.abort();
Thread.sleep(1000);
int datafiles = assertFileCounts(dir.list(), 0, 0);
assertEquals(datafiles, 0);
@@ -705,7 +702,7 @@ public class SSTableRewriterTest extends SchemaLoader
for (SSTableReader sstable : cfs.getSSTables())
{
assertFalse(sstable.isMarkedCompacted());
- assertEquals(1, sstable.sharedRef().globalCount());
+ assertEquals(1, sstable.selfRef().globalCount());
liveDescriptors.add(sstable.descriptor.generation);
}
for (File dir : cfs.directories.getCFDirectories())
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java b/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
index f84ae11..1447b29 100644
--- a/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
+++ b/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
@@ -64,7 +64,7 @@ public class StreamTransferTaskTest extends SchemaLoader
{
List<Range<Token>> ranges = new ArrayList<>();
ranges.add(new Range<>(sstable.first.getToken(), sstable.last.getToken()));
- task.addTransferFile(sstable, sstable.sharedRef(), 1, sstable.getPositionsForRanges(ranges), 0);
+ task.addTransferFile(sstable, sstable.selfRef(), 1, sstable.getPositionsForRanges(ranges), 0);
}
assertEquals(2, task.getTotalNumberOfFiles());
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/tools/SSTableExportTest.java b/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
index c3f3419..c918d6a 100644
--- a/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
+++ b/test/unit/org/apache/cassandra/tools/SSTableExportTest.java
@@ -189,6 +189,7 @@ public class SSTableExportTest extends SchemaLoader
qf = Util.namesQueryFilter(cfs, Util.dk("rowExclude"), "name");
cf = qf.getSSTableColumnIterator(reader).getColumnFamily();
assert cf == null;
+ reader.selfRef().release();
}
@Test
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/tools/SSTableImportTest.java b/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
index b0f4c0a..a5f05f8 100644
--- a/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
+++ b/test/unit/org/apache/cassandra/tools/SSTableImportTest.java
@@ -71,6 +71,7 @@ public class SSTableImportTest extends SchemaLoader
assert expCol.value().equals(hexToBytes("76616c4143"));
assert expCol instanceof ExpiringCell;
assert ((ExpiringCell)expCol).getTimeToLive() == 42 && expCol.getLocalDeletionTime() == 2000000000;
+ reader.selfRef().release();
}
private ColumnFamily cloneForAdditions(OnDiskAtomIterator iter)
@@ -105,6 +106,7 @@ public class SSTableImportTest extends SchemaLoader
assert expCol.value().equals(hexToBytes("76616c4143"));
assert expCol instanceof ExpiringCell;
assert ((ExpiringCell) expCol).getTimeToLive() == 42 && expCol.getLocalDeletionTime() == 2000000000;
+ reader.selfRef().release();
}
@Test
@@ -129,6 +131,7 @@ public class SSTableImportTest extends SchemaLoader
assert expCol.value().equals(hexToBytes("76616c4143"));
assert expCol instanceof ExpiringCell;
assert ((ExpiringCell) expCol).getTimeToLive() == 42 && expCol.getLocalDeletionTime() == 2000000000;
+ reader.selfRef().release();
}
@Test
@@ -148,6 +151,7 @@ public class SSTableImportTest extends SchemaLoader
Cell c = cf.getColumn(Util.cellname("colAA"));
assert c instanceof CounterCell : c;
assert ((CounterCell) c).total() == 42;
+ reader.selfRef().release();
}
@Test
@@ -168,6 +172,7 @@ public class SSTableImportTest extends SchemaLoader
QueryFilter qf2 = QueryFilter.getIdentityFilter(Util.dk("726f7741", BytesType.instance), "AsciiKeys", System.currentTimeMillis());
OnDiskAtomIterator iter2 = qf2.getSSTableColumnIterator(reader);
assert !iter2.hasNext(); // "bytes" key does not exist
+ reader.selfRef().release();
}
@Test
@@ -186,6 +191,7 @@ public class SSTableImportTest extends SchemaLoader
QueryFilter qf = QueryFilter.getIdentityFilter(Util.dk("rowA"), "AsciiKeys", System.currentTimeMillis());
OnDiskAtomIterator iter = qf.getSSTableColumnIterator(reader);
assert iter.hasNext(); // "bytes" key exists
+ reader.selfRef().release();
}
@Test
@@ -207,6 +213,7 @@ public class SSTableImportTest extends SchemaLoader
assertThat(result.size(), is(2));
assertThat(result, hasItem(withElements(1, "NY", 1980)));
assertThat(result, hasItem(withElements(2, "CA", 2014)));
+ reader.selfRef().release();
}
@Test(expected=AssertionError.class)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/utils/BloomFilterTest.java b/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
index 4180a8c..aee0880 100644
--- a/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
+++ b/test/unit/org/apache/cassandra/utils/BloomFilterTest.java
@@ -30,10 +30,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.*;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.io.util.DataOutputStreamAndChannel;
@@ -45,7 +42,7 @@ public class BloomFilterTest
public BloomFilterTest()
{
- bf = FilterFactory.getFilter(10000L, FilterTestHelper.MAX_FAILURE_RATE, true);
+
}
public static IFilter testSerialize(IFilter f) throws IOException
@@ -64,9 +61,15 @@ public class BloomFilterTest
@Before
- public void clear()
+ public void setup()
+ {
+ bf = FilterFactory.getFilter(10000L, FilterTestHelper.MAX_FAILURE_RATE, true);
+ }
+
+ @After
+ public void destroy()
{
- bf.clear();
+ bf.close();
}
@Test(expected = UnsupportedOperationException.class)
@@ -114,12 +117,13 @@ public class BloomFilterTest
FilterTestHelper.testFalsePositives(bf2,
new KeyGenerator.WordGenerator(skipEven, 2),
new KeyGenerator.WordGenerator(1, 2));
+ bf2.close();
}
@Test
public void testSerialize() throws IOException
{
- BloomFilterTest.testSerialize(bf);
+ BloomFilterTest.testSerialize(bf).close();
}
public void testManyHashes(Iterator<ByteBuffer> keys)
@@ -137,6 +141,7 @@ public class BloomFilterTest
hashes.add(hashIndex);
}
collisions += (MAX_HASH_COUNT - hashes.size());
+ bf.close();
}
assert collisions <= 100;
}
@@ -167,6 +172,7 @@ public class BloomFilterTest
FilterFactory.serialize(filter, out);
filter.bitset.serialize(out);
out.close();
+ filter.close();
DataInputStream in = new DataInputStream(new FileInputStream(file));
BloomFilter filter2 = (BloomFilter) FilterFactory.deserialize(in, true);
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/utils/SerializationsTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/utils/SerializationsTest.java b/test/unit/org/apache/cassandra/utils/SerializationsTest.java
index 976a3eb..b0a23fd 100644
--- a/test/unit/org/apache/cassandra/utils/SerializationsTest.java
+++ b/test/unit/org/apache/cassandra/utils/SerializationsTest.java
@@ -39,6 +39,7 @@ public class SerializationsTest extends AbstractSerializationsTester
DataOutputStreamAndChannel out = getOutput("utils.BloomFilter.bin");
FilterFactory.serialize(bf, out);
out.close();
+ bf.close();
}
@Test
@@ -48,7 +49,9 @@ public class SerializationsTest extends AbstractSerializationsTester
testBloomFilterWrite(true);
DataInputStream in = getInput("utils.BloomFilter.bin");
- assert FilterFactory.deserialize(in, true) != null;
+ IFilter bf = FilterFactory.deserialize(in, true);
+ assert bf != null;
+ bf.close();
in.close();
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/61384c57/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java b/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java
index fe22d21..a9247cd 100644
--- a/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java
+++ b/test/unit/org/apache/cassandra/utils/concurrent/RefCountedTest.java
@@ -44,9 +44,9 @@ public class RefCountedTest
public void testLeak() throws InterruptedException
{
Tidier tidier = new Tidier();
- RefCounted obj = RefCounted.Impl.get(tidier);
+ Ref<?> obj = new Ref(null, tidier);
obj.tryRef();
- obj.sharedRef().release();
+ obj.release();
System.gc();
System.gc();
Thread.sleep(1000);
@@ -57,7 +57,7 @@ public class RefCountedTest
public void testSeriousLeak() throws InterruptedException
{
Tidier tidier = new Tidier();
- RefCounted.Impl.get(tidier);
+ new Ref(null, tidier);
System.gc();
System.gc();
System.gc();
@@ -73,9 +73,9 @@ public class RefCountedTest
try
{
tidier = new Tidier();
- RefCounted obj = RefCounted.Impl.get(tidier);
- obj.sharedRef().release();
- obj.sharedRef().release();
+ Ref<?> obj = new Ref(null, tidier);
+ obj.release();
+ obj.release();
Assert.assertTrue(false);
}
catch (Exception e)