You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by GitBox <gi...@apache.org> on 2021/09/24 13:06:46 UTC
[GitHub] [cassandra] azotcsit commented on a change in pull request #1213: Add a Denylist to block reads and writes on specific partition keys
azotcsit commented on a change in pull request #1213:
URL: https://github.com/apache/cassandra/pull/1213#discussion_r715089691
##########
File path: src/java/org/apache/cassandra/config/DatabaseDescriptor.java
##########
@@ -3447,6 +3447,86 @@ public static void setConsecutiveMessageErrorsThreshold(int value)
conf.consecutive_message_errors_threshold = value;
}
+ public static boolean enablePartitionDenylist()
+ {
+ return conf.enable_partition_denylist;
+ }
+
+ public static void setEnablePartitionDenylist(boolean enabled)
+ {
+ conf.enable_partition_denylist = enabled;
+ }
+
+ public static boolean enableDenylistWrites()
+ {
+ return conf.enable_denylist_writes;
+ }
+
+ public static void setEnableDenylistWrites(boolean enabled)
+ {
+ conf.enable_denylist_writes = enabled;
+ }
+
+ public static boolean enableDenylistReads()
+ {
+ return conf.enable_denylist_reads;
+ }
+
+ public static void setEnableDenylistReads(boolean enabled)
+ {
+ conf.enable_denylist_reads = enabled;
+ }
+
+ public static boolean enableDenylistRangeReads()
+ {
+ return conf.enable_denylist_range_reads;
+ }
+
+ public static void setEnableDenylistRangeReads(boolean enabled)
+ {
+ conf.enable_denylist_range_reads = enabled;
+ }
+
+ public static int getDenylistRefreshPeriodSeconds()
+ {
+ return conf.denylist_refresh_period_seconds;
+ }
+
+ public static void setdenyDenylistRefreshPeriodSeconds(int period)
+ {
+ conf.denylist_refresh_period_seconds = period;
+ }
+
+ public static int getDenylistInitialLoadRetrySeconds()
+ {
+ return conf.denylist_initial_load_retry_seconds;
+ }
+
+ public static void setdenyDenylistInitialLoadRetrySeconds(int seconds)
Review comment:
nit: in many other setter there are validation checks for input parameters (to ensure they are positive, non-zero, etc), we can introduce it for `setDenylistInitialLoadRetrySeconds` and `setDenylistRefreshPeriodSeconds` methods too.
##########
File path: src/java/org/apache/cassandra/config/DatabaseDescriptor.java
##########
@@ -3447,6 +3447,86 @@ public static void setConsecutiveMessageErrorsThreshold(int value)
conf.consecutive_message_errors_threshold = value;
}
+ public static boolean enablePartitionDenylist()
+ {
+ return conf.enable_partition_denylist;
+ }
+
+ public static void setEnablePartitionDenylist(boolean enabled)
+ {
+ conf.enable_partition_denylist = enabled;
+ }
+
+ public static boolean enableDenylistWrites()
+ {
+ return conf.enable_denylist_writes;
+ }
+
+ public static void setEnableDenylistWrites(boolean enabled)
+ {
+ conf.enable_denylist_writes = enabled;
+ }
+
+ public static boolean enableDenylistReads()
+ {
+ return conf.enable_denylist_reads;
+ }
+
+ public static void setEnableDenylistReads(boolean enabled)
+ {
+ conf.enable_denylist_reads = enabled;
+ }
+
+ public static boolean enableDenylistRangeReads()
+ {
+ return conf.enable_denylist_range_reads;
+ }
+
+ public static void setEnableDenylistRangeReads(boolean enabled)
+ {
+ conf.enable_denylist_range_reads = enabled;
+ }
+
+ public static int getDenylistRefreshPeriodSeconds()
+ {
+ return conf.denylist_refresh_period_seconds;
+ }
+
+ public static void setdenyDenylistRefreshPeriodSeconds(int period)
Review comment:
nit: `period` -> `seconds` (to be coherent with `setDenylistInitialLoadRetrySeconds`)
##########
File path: src/java/org/apache/cassandra/config/DatabaseDescriptor.java
##########
@@ -3447,6 +3447,86 @@ public static void setConsecutiveMessageErrorsThreshold(int value)
conf.consecutive_message_errors_threshold = value;
}
+ public static boolean enablePartitionDenylist()
+ {
+ return conf.enable_partition_denylist;
+ }
+
+ public static void setEnablePartitionDenylist(boolean enabled)
+ {
+ conf.enable_partition_denylist = enabled;
+ }
+
+ public static boolean enableDenylistWrites()
+ {
+ return conf.enable_denylist_writes;
+ }
+
+ public static void setEnableDenylistWrites(boolean enabled)
+ {
+ conf.enable_denylist_writes = enabled;
+ }
+
+ public static boolean enableDenylistReads()
+ {
+ return conf.enable_denylist_reads;
+ }
+
+ public static void setEnableDenylistReads(boolean enabled)
+ {
+ conf.enable_denylist_reads = enabled;
+ }
+
+ public static boolean enableDenylistRangeReads()
+ {
+ return conf.enable_denylist_range_reads;
+ }
+
+ public static void setEnableDenylistRangeReads(boolean enabled)
+ {
+ conf.enable_denylist_range_reads = enabled;
+ }
+
+ public static int getDenylistRefreshPeriodSeconds()
+ {
+ return conf.denylist_refresh_period_seconds;
+ }
+
+ public static void setdenyDenylistRefreshPeriodSeconds(int period)
+ {
+ conf.denylist_refresh_period_seconds = period;
+ }
+
+ public static int getDenylistInitialLoadRetrySeconds()
+ {
+ return conf.denylist_initial_load_retry_seconds;
+ }
+
+ public static void setdenyDenylistInitialLoadRetrySeconds(int seconds)
+ {
+ conf.denylist_initial_load_retry_seconds = seconds;
+ }
+
+ public static int maxdenyDenylistKeysPerTable()
+ {
+ return conf.max_denylist_keys_per_table;
+ }
+
+ public static int maxdenyDenylistKeysTotal()
+ {
+ return conf.max_denylist_keys_total;
+ }
+
+ public static ConsistencyLevel denylistConsistencyLevel()
Review comment:
nit: the naming of the new "get" methods is not coherent with the old ones (which have "get" prefix).
##########
File path: src/java/org/apache/cassandra/config/DatabaseDescriptor.java
##########
@@ -3447,6 +3447,86 @@ public static void setConsecutiveMessageErrorsThreshold(int value)
conf.consecutive_message_errors_threshold = value;
}
+ public static boolean enablePartitionDenylist()
+ {
+ return conf.enable_partition_denylist;
+ }
+
+ public static void setEnablePartitionDenylist(boolean enabled)
+ {
+ conf.enable_partition_denylist = enabled;
+ }
+
+ public static boolean enableDenylistWrites()
+ {
+ return conf.enable_denylist_writes;
+ }
+
+ public static void setEnableDenylistWrites(boolean enabled)
+ {
+ conf.enable_denylist_writes = enabled;
+ }
+
+ public static boolean enableDenylistReads()
+ {
+ return conf.enable_denylist_reads;
+ }
+
+ public static void setEnableDenylistReads(boolean enabled)
+ {
+ conf.enable_denylist_reads = enabled;
+ }
+
+ public static boolean enableDenylistRangeReads()
+ {
+ return conf.enable_denylist_range_reads;
+ }
+
+ public static void setEnableDenylistRangeReads(boolean enabled)
+ {
+ conf.enable_denylist_range_reads = enabled;
+ }
+
+ public static int getDenylistRefreshPeriodSeconds()
+ {
+ return conf.denylist_refresh_period_seconds;
+ }
+
+ public static void setdenyDenylistRefreshPeriodSeconds(int period)
+ {
+ conf.denylist_refresh_period_seconds = period;
+ }
+
+ public static int getDenylistInitialLoadRetrySeconds()
+ {
+ return conf.denylist_initial_load_retry_seconds;
+ }
+
+ public static void setdenyDenylistInitialLoadRetrySeconds(int seconds)
+ {
+ conf.denylist_initial_load_retry_seconds = seconds;
+ }
+
+ public static int maxdenyDenylistKeysPerTable()
Review comment:
Many method names have a typo: "denyDeny", please, fix them all.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
+ {
+ return validateRange(getTableId(keyspace, cf), range);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final TableId tid, final AbstractBounds<PartitionPosition> range)
Review comment:
Maybe that's just me, but naming most of the methods is confusing for me (they are verbs and I have certain expectations when I see them). For example, method `validate` should throw an exception if something is invalid. `getInvalidKeysCount` seems to be more clear for me in this case.
The same:
`validateKey` -> `isKeyValid`
`denylist` -> `addToDenylist`
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
Review comment:
Am I right that we try to merge newly read records (allDenylists) with what we already had in the cache (denylist)? What is the point? Why can't we simply overwrite the data in cache?
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
Review comment:
Maybe I missed it, but I found no method to remove a key from the denylist. Is there any? I think it is important to have it.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
Review comment:
Just to highlight: when we mark a key as denied and then unmark, it may take sometime while it expires from denylist caches. I'm not sure it is a problem, but we definitely need to mention that in documentation.
##########
File path: src/java/org/apache/cassandra/metrics/DenylistMetrics.java
##########
@@ -0,0 +1,58 @@
+/*
+ * 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.metrics;
+
+import com.codahale.metrics.Meter;
+
+import static org.apache.cassandra.metrics.CassandraMetricsRegistry.Metrics;
+
+public class DenylistMetrics
+{
+ private final Meter writesRejected;;
Review comment:
nit: duplicated semicolon
##########
File path: src/java/org/apache/cassandra/service/StorageProxy.java
##########
@@ -2728,4 +2805,65 @@ public void disableCheckForDuplicateRowsDuringCompaction()
{
DatabaseDescriptor.setCheckForDuplicateRowsDuringCompaction(false);
}
+
+ public void initialLoadPartitionDenylist()
+ {
+ partitionDenylist.initialLoad();
+ }
+
+ @Override
+ public void loadPartitionDenylist()
+ {
+ partitionDenylist.load();
+ }
+
+ @Override
+ public int getPartitionDenylistLoadAttempts()
+ {
+ return partitionDenylist.getLoadAttempts();
+ }
+
+ @Override
+ public int getPartitionDenylistLoadSuccesses()
+ {
+ return partitionDenylist.getLoadSuccesses();
+ }
+
+ @Override
+ public void setEnablePartitionDenylist(boolean enabled)
+ {
+ DatabaseDescriptor.setEnablePartitionDenylist(enabled);
+ }
+
+ @Override
+ public void setEnableDenylistWrites(boolean enabled)
+ {
+ DatabaseDescriptor.setEnableDenylistWrites(enabled);
+ }
+
+ @Override
+ public void setEnableDenylistReads(boolean enabled)
+ {
+ DatabaseDescriptor.setEnableDenylistReads(enabled);
+ }
+
+ @Override
+ public void setEnableDenylistRangeReads(boolean enabled)
+ {
+ DatabaseDescriptor.setEnableDenylistRangeReads(enabled);
+ }
+
+ @Override
+ public boolean denylistKey(String keyspace, String table, String keyAsString)
+ {
+ if (!Schema.instance.getKeyspaces().contains(keyspace))
+ return false;
+
+ final ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(keyspace, table);
+ if (cfs == null)
+ return false;
+
+ final ByteBuffer bytes = cfs.metadata.get().partitionKeyType.fromString(keyAsString);
Review comment:
will it work for composite keys? what format of `keyAsString` should be used?
##########
File path: src/java/org/apache/cassandra/service/StorageProxy.java
##########
@@ -293,6 +305,15 @@ public static RowIterator cas(String keyspaceName,
{
TableMetadata metadata = Schema.instance.validateTable(keyspaceName, cfName);
+ if (DatabaseDescriptor.enablePartitionDenylist() && DatabaseDescriptor.enableDenylistWrites() && !partitionDenylist.validateKey(keyspaceName, cfName, key.getKey()))
+ {
+ denylistMetrics.incrementWritesRejected();
+ final byte[] keyBytes = new byte[key.getKey().remaining()];
+ key.getKey().slice().get(keyBytes);
+ throw new InvalidRequestException(String.format("Unable to CAS write to denylisted partition [0x%s] in %s/%s",
+ Hex.bytesToHex(keyBytes), keyspaceName, cfName));
Review comment:
Would `DecoratedKey#toString()` do the thing?
##########
File path: src/java/org/apache/cassandra/service/StorageProxy.java
##########
@@ -170,17 +177,22 @@ public AtomicInteger load(InetAddressAndPort inetAddress)
}
};
private static final ClientRequestMetrics readMetrics = new ClientRequestMetrics("Read");
+ @VisibleForTesting
+ public static final ClientRequestMetrics rangeMetrics = new ClientRequestMetrics("RangeSlice");
private static final ClientWriteRequestMetrics writeMetrics = new ClientWriteRequestMetrics("Write");
private static final CASClientWriteRequestMetrics casWriteMetrics = new CASClientWriteRequestMetrics("CASWrite");
private static final CASClientRequestMetrics casReadMetrics = new CASClientRequestMetrics("CASRead");
private static final ViewWriteMetrics viewWriteMetrics = new ViewWriteMetrics("ViewWrite");
private static final Map<ConsistencyLevel, ClientRequestMetrics> readMetricsMap = new EnumMap<>(ConsistencyLevel.class);
private static final Map<ConsistencyLevel, ClientWriteRequestMetrics> writeMetricsMap = new EnumMap<>(ConsistencyLevel.class);
+ private static final DenylistMetrics denylistMetrics = new DenylistMetrics();
private static final String DISABLE_SERIAL_READ_LINEARIZABILITY_KEY = "cassandra.unsafe.disable-serial-reads-linearizability";
private static final boolean disableSerialReadLinearizability =
Boolean.parseBoolean(System.getProperty(DISABLE_SERIAL_READ_LINEARIZABILITY_KEY, "false"));
+ public static final PartitionDenylist partitionDenylist = new PartitionDenylist();
Review comment:
Why is this public? If it is used in test, let's add `@VisibleForTesting`.
##########
File path: src/java/org/apache/cassandra/service/StorageProxy.java
##########
@@ -1052,6 +1073,33 @@ public static void mutateWithTriggers(List<? extends IMutation> mutations,
long queryStartNanoTime)
throws WriteTimeoutException, WriteFailureException, UnavailableException, OverloadedException, InvalidRequestException
{
+ if (DatabaseDescriptor.enablePartitionDenylist() && DatabaseDescriptor.enableDenylistWrites())
+ {
+ for (IMutation mutation : mutations)
+ {
+ for (final TableId tid : mutation.getTableIds())
Review comment:
Some variable are marked as final, some (e.g. `mutation`) are not. Let's either mark all or none.
##########
File path: src/java/org/apache/cassandra/service/StorageProxyMBean.java
##########
@@ -63,6 +63,15 @@
@Deprecated
public int getOtcBacklogExpirationInterval();
+ public void loadPartitionDenylist();
Review comment:
Just a question for better understanding: why don't we expose "set*Seconds" methods?
##########
File path: src/java/org/apache/cassandra/service/StorageService.java
##########
@@ -1101,6 +1102,8 @@ public void joinTokenRing(boolean finishJoiningRing,
{
logger.warn("Some data streaming failed. Use nodetool to check bootstrap state and resume. For more, see `nodetool help bootstrap`. {}", SystemKeyspace.getBootstrapState());
}
+
+ StorageProxy.instance.initialLoadPartitionDenylist();
Review comment:
It would be great if someone who understands startup sequence very well could confirm it is the right place to init the denylist.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
Review comment:
nit: fields are usually defined before constructors.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
Review comment:
The code is full of repeating check for table validity like
```
final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
if (tmd == null)
```
```
final TableId tid = getTableId(row.getString("ks_name"), row.getString("cf_name"));
if (tid == null)
```
They make it hard to read and understand what and where is validated. Can we start accepting `TableId` instead of "String cf"? And validate it somewhere in the beginning? Most of the internal check will go away which will simplify the code.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
+ {
+ return validateRange(getTableId(keyspace, cf), range);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final TableId tid, final AbstractBounds<PartitionPosition> range)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return 0;
+
+ try
+ {
+ final DenylistEntry denylistEntry = denylist.get(tid);
+ if (denylistEntry.tokens.size() == 0)
+ return 0;
+ final Token startToken = range.left.getToken();
+ final Token endToken = range.right.getToken();
+
+ // Normal case
+ if (startToken.compareTo(endToken) <= 0 || endToken.isMinimum())
+ {
+ NavigableSet<Token> subSet = denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind()));
+ if (!endToken.isMinimum())
+ subSet = subSet.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind()));
+ return subSet.size();
+ }
+
+ // Wrap around case
+ return denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind())).size()
+ + denylistEntry.tokens.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind())).size();
+ }
+ catch (final ExecutionException e)
+ {
+ logAccessFailure(tid, e);
+ return 0;
+ }
+ }
+
+ private DenylistEntry readDenylist(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return new DenylistEntry();
+
+ final String readDenylist = String.format("SELECT * FROM %s.%s WHERE ks_name='%s' AND cf_name='%s' LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE,
+ tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable() + 1);
+
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new DenylistEntry();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysPerTable())
+ logger.error("Partition denylist for {}/{} has exceeded the maximum allowable size ({}). Remaining keys were ignored.", tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable());
+
+ final Set<ByteBuffer> keys = new HashSet<>();
+ final NavigableSet<Token> tokens = new TreeSet<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final ByteBuffer key = row.getBlob("key");
+ keys.add(key);
+ tokens.add(StorageService.instance.getTokenMetadata().partitioner.getToken(key));
+ }
+ return new DenylistEntry(ImmutableSet.copyOf(keys), ImmutableSortedSet.copyOf(tokens));
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Error reading partition_denylist table for {}/{}", tmd.keyspace, tmd.name, e);
+ return null;
+ }
+ }
+
+ private Map<TableId, DenylistEntry> readAll()
+ {
+ final String readDenylist = String.format("SELECT * FROM %s.%s LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE, DatabaseDescriptor.maxdenyDenylistKeysTotal() + 1);
Review comment:
Why +1?
```
DatabaseDescriptor.maxdenyDenylistKeysTotal() + 1
```
I thought `LIMIT` is inclusive.
##########
File path: src/java/org/apache/cassandra/config/DatabaseDescriptor.java
##########
@@ -3447,6 +3447,86 @@ public static void setConsecutiveMessageErrorsThreshold(int value)
conf.consecutive_message_errors_threshold = value;
}
+ public static boolean enablePartitionDenylist()
+ {
+ return conf.enable_partition_denylist;
Review comment:
We need to update `cassandra.yaml` with mentioning all the properties and their description.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
+ {
+ return validateRange(getTableId(keyspace, cf), range);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final TableId tid, final AbstractBounds<PartitionPosition> range)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return 0;
+
+ try
+ {
+ final DenylistEntry denylistEntry = denylist.get(tid);
+ if (denylistEntry.tokens.size() == 0)
+ return 0;
+ final Token startToken = range.left.getToken();
+ final Token endToken = range.right.getToken();
+
+ // Normal case
+ if (startToken.compareTo(endToken) <= 0 || endToken.isMinimum())
+ {
+ NavigableSet<Token> subSet = denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind()));
+ if (!endToken.isMinimum())
+ subSet = subSet.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind()));
+ return subSet.size();
+ }
+
+ // Wrap around case
+ return denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind())).size()
+ + denylistEntry.tokens.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind())).size();
+ }
+ catch (final ExecutionException e)
+ {
+ logAccessFailure(tid, e);
+ return 0;
+ }
+ }
+
+ private DenylistEntry readDenylist(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return new DenylistEntry();
+
+ final String readDenylist = String.format("SELECT * FROM %s.%s WHERE ks_name='%s' AND cf_name='%s' LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE,
+ tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable() + 1);
+
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new DenylistEntry();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysPerTable())
+ logger.error("Partition denylist for {}/{} has exceeded the maximum allowable size ({}). Remaining keys were ignored.", tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable());
+
+ final Set<ByteBuffer> keys = new HashSet<>();
+ final NavigableSet<Token> tokens = new TreeSet<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final ByteBuffer key = row.getBlob("key");
+ keys.add(key);
+ tokens.add(StorageService.instance.getTokenMetadata().partitioner.getToken(key));
+ }
+ return new DenylistEntry(ImmutableSet.copyOf(keys), ImmutableSortedSet.copyOf(tokens));
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Error reading partition_denylist table for {}/{}", tmd.keyspace, tmd.name, e);
+ return null;
+ }
+ }
+
+ private Map<TableId, DenylistEntry> readAll()
+ {
+ final String readDenylist = String.format("SELECT * FROM %s.%s LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE, DatabaseDescriptor.maxdenyDenylistKeysTotal() + 1);
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new HashMap<>();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysTotal())
+ logger.error("Partition denylist has exceeded the maximum allowable total size ({}). Remaining keys were ignored.", DatabaseDescriptor.maxdenyDenylistKeysTotal());
+
+ final Map<TableId, Pair<Set<ByteBuffer>, NavigableSet<Token>>> allDenylists = new HashMap<>();
+ for (final UntypedResultSet.Row row : results)
Review comment:
Two lines above we state `Remaining keys were ignored` but in fact we read N+1 records. It is not critical but not precise.
And a general question - have you considered the option to limit number of keys stored on write? I'm just curious if it could simplify the logic.
I'm concerned that now (if the limit is exceeded) different nodes can have different denylist keys cache. So it would be pretty hard to troubleshoot.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
+ {
+ return validateRange(getTableId(keyspace, cf), range);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final TableId tid, final AbstractBounds<PartitionPosition> range)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return 0;
+
+ try
+ {
+ final DenylistEntry denylistEntry = denylist.get(tid);
+ if (denylistEntry.tokens.size() == 0)
+ return 0;
+ final Token startToken = range.left.getToken();
+ final Token endToken = range.right.getToken();
+
+ // Normal case
+ if (startToken.compareTo(endToken) <= 0 || endToken.isMinimum())
+ {
+ NavigableSet<Token> subSet = denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind()));
+ if (!endToken.isMinimum())
+ subSet = subSet.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind()));
+ return subSet.size();
+ }
+
+ // Wrap around case
+ return denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind())).size()
+ + denylistEntry.tokens.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind())).size();
+ }
+ catch (final ExecutionException e)
+ {
+ logAccessFailure(tid, e);
+ return 0;
+ }
+ }
+
+ private DenylistEntry readDenylist(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return new DenylistEntry();
+
+ final String readDenylist = String.format("SELECT * FROM %s.%s WHERE ks_name='%s' AND cf_name='%s' LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE,
+ tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable() + 1);
+
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new DenylistEntry();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysPerTable())
+ logger.error("Partition denylist for {}/{} has exceeded the maximum allowable size ({}). Remaining keys were ignored.", tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable());
+
+ final Set<ByteBuffer> keys = new HashSet<>();
+ final NavigableSet<Token> tokens = new TreeSet<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final ByteBuffer key = row.getBlob("key");
+ keys.add(key);
+ tokens.add(StorageService.instance.getTokenMetadata().partitioner.getToken(key));
+ }
+ return new DenylistEntry(ImmutableSet.copyOf(keys), ImmutableSortedSet.copyOf(tokens));
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Error reading partition_denylist table for {}/{}", tmd.keyspace, tmd.name, e);
+ return null;
+ }
+ }
+
+ private Map<TableId, DenylistEntry> readAll()
+ {
+ final String readDenylist = String.format("SELECT * FROM %s.%s LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE, DatabaseDescriptor.maxdenyDenylistKeysTotal() + 1);
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new HashMap<>();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysTotal())
+ logger.error("Partition denylist has exceeded the maximum allowable total size ({}). Remaining keys were ignored.", DatabaseDescriptor.maxdenyDenylistKeysTotal());
+
+ final Map<TableId, Pair<Set<ByteBuffer>, NavigableSet<Token>>> allDenylists = new HashMap<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final TableId tid = getTableId(row.getString("ks_name"), row.getString("cf_name"));
+ if (tid == null)
+ continue;
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, Pair.create(new HashSet<>(), new TreeSet<>()));
+ final ByteBuffer key = row.getBlob("key");
+ allDenylists.get(tid).left.add(key);
Review comment:
nit:
maybe that's optimized by the compiler but I'd write it like this
```
Pair<Set<ByteBuffer>, NavigableSet<Token>> pair = allDenylists.get(tid);
pair.left.add(key);
pair.right.add(StorageService.instance.getTokenMetadata().partitioner.getToken(key));
```
to ensure we do not do unnecessary lookups.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
+ {
+ return validateRange(getTableId(keyspace, cf), range);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final TableId tid, final AbstractBounds<PartitionPosition> range)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return 0;
+
+ try
+ {
+ final DenylistEntry denylistEntry = denylist.get(tid);
+ if (denylistEntry.tokens.size() == 0)
+ return 0;
+ final Token startToken = range.left.getToken();
+ final Token endToken = range.right.getToken();
+
+ // Normal case
+ if (startToken.compareTo(endToken) <= 0 || endToken.isMinimum())
+ {
+ NavigableSet<Token> subSet = denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind()));
+ if (!endToken.isMinimum())
+ subSet = subSet.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind()));
+ return subSet.size();
+ }
+
+ // Wrap around case
+ return denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind())).size()
+ + denylistEntry.tokens.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind())).size();
+ }
+ catch (final ExecutionException e)
+ {
+ logAccessFailure(tid, e);
+ return 0;
+ }
+ }
+
+ private DenylistEntry readDenylist(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return new DenylistEntry();
+
+ final String readDenylist = String.format("SELECT * FROM %s.%s WHERE ks_name='%s' AND cf_name='%s' LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE,
+ tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable() + 1);
+
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new DenylistEntry();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysPerTable())
+ logger.error("Partition denylist for {}/{} has exceeded the maximum allowable size ({}). Remaining keys were ignored.", tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable());
+
+ final Set<ByteBuffer> keys = new HashSet<>();
+ final NavigableSet<Token> tokens = new TreeSet<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final ByteBuffer key = row.getBlob("key");
+ keys.add(key);
+ tokens.add(StorageService.instance.getTokenMetadata().partitioner.getToken(key));
+ }
+ return new DenylistEntry(ImmutableSet.copyOf(keys), ImmutableSortedSet.copyOf(tokens));
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Error reading partition_denylist table for {}/{}", tmd.keyspace, tmd.name, e);
+ return null;
+ }
+ }
+
+ private Map<TableId, DenylistEntry> readAll()
+ {
+ final String readDenylist = String.format("SELECT * FROM %s.%s LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE, DatabaseDescriptor.maxdenyDenylistKeysTotal() + 1);
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new HashMap<>();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysTotal())
+ logger.error("Partition denylist has exceeded the maximum allowable total size ({}). Remaining keys were ignored.", DatabaseDescriptor.maxdenyDenylistKeysTotal());
+
+ final Map<TableId, Pair<Set<ByteBuffer>, NavigableSet<Token>>> allDenylists = new HashMap<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final TableId tid = getTableId(row.getString("ks_name"), row.getString("cf_name"));
+ if (tid == null)
+ continue;
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, Pair.create(new HashSet<>(), new TreeSet<>()));
+ final ByteBuffer key = row.getBlob("key");
+ allDenylists.get(tid).left.add(key);
+ allDenylists.get(tid).right.add(StorageService.instance.getTokenMetadata().partitioner.getToken(key));
+ }
+
+ final Map<TableId, DenylistEntry> ret = new HashMap<>();
+ for (final TableId tid : allDenylists.keySet())
+ {
+ final Pair<Set<ByteBuffer>, NavigableSet<Token>> entries = allDenylists.get(tid);
+ ret.put(tid, new DenylistEntry(ImmutableSet.copyOf(entries.left), ImmutableSortedSet.copyOf(entries.right)));
+ }
+ return ret;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Error reading partition_denylist table on startup", e);
+ return null;
Review comment:
Let's return an empty map to prevent possible NPE and to reduce number of null checks.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
+ {
+ return validateRange(getTableId(keyspace, cf), range);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final TableId tid, final AbstractBounds<PartitionPosition> range)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return 0;
+
+ try
+ {
+ final DenylistEntry denylistEntry = denylist.get(tid);
+ if (denylistEntry.tokens.size() == 0)
+ return 0;
+ final Token startToken = range.left.getToken();
+ final Token endToken = range.right.getToken();
+
+ // Normal case
+ if (startToken.compareTo(endToken) <= 0 || endToken.isMinimum())
+ {
+ NavigableSet<Token> subSet = denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind()));
+ if (!endToken.isMinimum())
+ subSet = subSet.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind()));
+ return subSet.size();
+ }
+
+ // Wrap around case
+ return denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind())).size()
+ + denylistEntry.tokens.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind())).size();
+ }
+ catch (final ExecutionException e)
+ {
+ logAccessFailure(tid, e);
+ return 0;
+ }
+ }
+
+ private DenylistEntry readDenylist(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return new DenylistEntry();
+
+ final String readDenylist = String.format("SELECT * FROM %s.%s WHERE ks_name='%s' AND cf_name='%s' LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE,
+ tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable() + 1);
+
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new DenylistEntry();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysPerTable())
+ logger.error("Partition denylist for {}/{} has exceeded the maximum allowable size ({}). Remaining keys were ignored.", tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable());
+
+ final Set<ByteBuffer> keys = new HashSet<>();
+ final NavigableSet<Token> tokens = new TreeSet<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final ByteBuffer key = row.getBlob("key");
+ keys.add(key);
+ tokens.add(StorageService.instance.getTokenMetadata().partitioner.getToken(key));
+ }
+ return new DenylistEntry(ImmutableSet.copyOf(keys), ImmutableSortedSet.copyOf(tokens));
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Error reading partition_denylist table for {}/{}", tmd.keyspace, tmd.name, e);
+ return null;
+ }
+ }
+
+ private Map<TableId, DenylistEntry> readAll()
+ {
+ final String readDenylist = String.format("SELECT * FROM %s.%s LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE, DatabaseDescriptor.maxdenyDenylistKeysTotal() + 1);
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new HashMap<>();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysTotal())
+ logger.error("Partition denylist has exceeded the maximum allowable total size ({}). Remaining keys were ignored.", DatabaseDescriptor.maxdenyDenylistKeysTotal());
+
+ final Map<TableId, Pair<Set<ByteBuffer>, NavigableSet<Token>>> allDenylists = new HashMap<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final TableId tid = getTableId(row.getString("ks_name"), row.getString("cf_name"));
+ if (tid == null)
+ continue;
+ if (!allDenylists.containsKey(tid))
Review comment:
please use `computeIfAbsent`.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
+ {
+ return validateRange(getTableId(keyspace, cf), range);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final TableId tid, final AbstractBounds<PartitionPosition> range)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return 0;
+
+ try
+ {
+ final DenylistEntry denylistEntry = denylist.get(tid);
+ if (denylistEntry.tokens.size() == 0)
+ return 0;
+ final Token startToken = range.left.getToken();
+ final Token endToken = range.right.getToken();
+
+ // Normal case
+ if (startToken.compareTo(endToken) <= 0 || endToken.isMinimum())
+ {
+ NavigableSet<Token> subSet = denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind()));
+ if (!endToken.isMinimum())
+ subSet = subSet.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind()));
+ return subSet.size();
+ }
+
+ // Wrap around case
+ return denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind())).size()
+ + denylistEntry.tokens.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind())).size();
+ }
+ catch (final ExecutionException e)
+ {
+ logAccessFailure(tid, e);
+ return 0;
+ }
+ }
+
+ private DenylistEntry readDenylist(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return new DenylistEntry();
+
+ final String readDenylist = String.format("SELECT * FROM %s.%s WHERE ks_name='%s' AND cf_name='%s' LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE,
+ tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable() + 1);
+
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new DenylistEntry();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysPerTable())
+ logger.error("Partition denylist for {}/{} has exceeded the maximum allowable size ({}). Remaining keys were ignored.", tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable());
+
+ final Set<ByteBuffer> keys = new HashSet<>();
+ final NavigableSet<Token> tokens = new TreeSet<>();
+ for (final UntypedResultSet.Row row : results)
Review comment:
Here we again read N+1 records. See another comment for details.
##########
File path: src/java/org/apache/cassandra/schema/PartitionDenylist.java
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.schema;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.apache.cassandra.concurrent.ScheduledExecutors;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.UntypedResultSet;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.exceptions.RequestExecutionException;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.service.reads.range.RangeCommands;
+import org.apache.cassandra.utils.Hex;
+import org.apache.cassandra.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.cassandra.cql3.QueryProcessor.process;
+
+/**
+ * PartitionDenylist uses the system_distributed.partition_denylist table to maintain a list of denylisted partition keys
+ * for each keyspace/table.
+ *
+ * Keys can be entered manually into the partition_denylist table or via the JMX operation StorageProxyMBean.denylistKey
+ *
+ * The denylist is stored as one CQL partition per table, and the denylisted keys are column names in that partition. The denylisted
+ * keys for each table are cached in memory, and reloaded from the partition_denylist table every 24 hours (default) or when the
+ * StorageProxyMBean.loadPartitionDenylist is called via JMX.
+ *
+ * Concurrency of the cache is provided by the concurrency semantics of the guava LoadingCache. All values (DenylistEntry) are
+ * immutable collections of keys/tokens which are replaced in whole when the cache refreshes from disk.
+ */
+public class PartitionDenylist
+{
+ private static final Logger logger = LoggerFactory.getLogger(PartitionDenylist.class);
+ public static final String PARTITION_DENYLIST_TABLE = "partition_denylist";
+
+ private final ExecutorService executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+ private final LoadingCache<TableId, DenylistEntry> denylist = CacheBuilder.newBuilder()
+ .refreshAfterWrite(DatabaseDescriptor.getDenylistRefreshPeriodSeconds(), TimeUnit.SECONDS)
+ .build(new CacheLoader<TableId, DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry load(final TableId tid) throws Exception
+ {
+ return readDenylist(tid);
+ }
+
+ @Override
+ public ListenableFuture<DenylistEntry> reload(final TableId tid, final DenylistEntry oldValue)
+ {
+ ListenableFutureTask<DenylistEntry> task = ListenableFutureTask.create(new Callable<DenylistEntry>()
+ {
+ @Override
+ public DenylistEntry call()
+ {
+ final DenylistEntry newEntry = readDenylist(tid);
+ if (newEntry != null)
+ return newEntry;
+ if (oldValue != null)
+ return oldValue;
+ return new DenylistEntry();
+ }
+ });
+ executor.execute(task);
+ return task;
+ }
+ });
+
+ /**
+ * Denylist entry is never mutated once constructed, only replaced with a new entry when the cache is refreshed
+ */
+ private static class DenylistEntry
+ {
+ public DenylistEntry()
+ {
+ keys = ImmutableSet.of();
+ tokens = ImmutableSortedSet.of();
+ }
+
+ public DenylistEntry(final ImmutableSet<ByteBuffer> keys, final ImmutableSortedSet<Token> tokens)
+ {
+ this.keys = keys;
+ this.tokens = tokens;
+ }
+
+ public final ImmutableSet<ByteBuffer> keys;
+ public final ImmutableSortedSet<Token> tokens;
+ }
+
+ // synchronized on this
+ private int loadAttempts = 0;
+ private int loadSuccesses = 0;
+
+ public synchronized int getLoadAttempts()
+ {
+ return loadAttempts;
+ }
+ public synchronized int getLoadSuccesses()
+ {
+ return loadSuccesses;
+ }
+
+ /**
+ * Performs initial load of the partition denylist. Should be called at startup and only loads if the operation
+ * is expected to succeed. If it is not possible to load at call time, a timer is set to retry.
+ */
+ public void initialLoad()
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist())
+ return;
+
+ synchronized (this)
+ {
+ loadAttempts++;
+ }
+
+ // Check if there are sufficient nodes to attempt reading all the denylist partitions before issuing the query.
+ // The pre-check prevents definite range-slice unavailables being marked and triggering an alert. Nodes may still change
+ // state between the check and the query, but it should significantly reduce the alert volume.
+ String retryReason = "Insufficient nodes";
+ try
+ {
+ if (readAllHasSufficientNodes() && load())
+ {
+ return;
+ }
+ }
+ catch (Throwable tr)
+ {
+ logger.error("Failed to load partition denylist", tr);
+ retryReason = "Exception";
+ }
+
+ // This path will also be taken on other failures other than UnavailableException,
+ // but seems like a good idea to retry anyway.
+ int retryInSeconds = DatabaseDescriptor.getDenylistInitialLoadRetrySeconds();
+ logger.info(retryReason + " while loading partition denylist cache. Scheduled retry in {} seconds.",
+ retryInSeconds);
+ ScheduledExecutors.optionalTasks.schedule(this::initialLoad, retryInSeconds, TimeUnit.SECONDS);
+ }
+
+ private boolean readAllHasSufficientNodes()
+ {
+ return RangeCommands.sufficientLiveNodesForSelectStar(SystemDistributedKeyspace.PartitionDenylistTable,
+ DatabaseDescriptor.denylistConsistencyLevel());
+ }
+
+ public boolean load()
+ {
+ final long start = System.currentTimeMillis();
+ final Map<TableId, DenylistEntry> allDenylists = readAll();
+ if (allDenylists == null)
+ return false;
+
+ // Cache iterators are weakly-consistent
+ for (final Iterator<TableId> it = denylist.asMap().keySet().iterator(); it.hasNext(); )
+ {
+ final TableId tid = it.next();
+ if (!allDenylists.containsKey(tid))
+ allDenylists.put(tid, new DenylistEntry());
+ }
+ denylist.putAll(allDenylists);
+ logger.info("Loaded partition denylist cache in {}ms", System.currentTimeMillis() - start);
+
+ synchronized (this)
+ {
+ loadSuccesses++;
+ }
+ return true;
+ }
+
+ public boolean denylist(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ if (!isPermitted(keyspace))
+ return false;
+
+ final byte[] keyBytes = new byte[key.remaining()];
+ key.slice().get(keyBytes);
+
+ final String insert = String.format("INSERT INTO system_distributed.partition_denylist (ks_name, cf_name, key) VALUES ('%s', '%s', 0x%s)",
+ keyspace, cf, Hex.bytesToHex(keyBytes));
+
+ try
+ {
+ process(insert, DatabaseDescriptor.denylistConsistencyLevel());
+ return true;
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Failed to denylist key [{}] in {}/{}", Hex.bytesToHex(keyBytes), keyspace, cf, e);
+ }
+ return false;
+ }
+
+ private boolean isPermitted(final String keyspace)
+ {
+ return !SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.TRACE_KEYSPACE_NAME.equals(keyspace) &&
+ !SchemaConstants.AUTH_KEYSPACE_NAME.equals(keyspace);
+ }
+
+ private boolean isPermitted(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return false;
+ return isPermitted(tmd.keyspace);
+ }
+
+ public boolean validateKey(final String keyspace, final String cf, final ByteBuffer key)
+ {
+ return validateKey(getTableId(keyspace, cf), key);
+ }
+
+ public boolean validateKey(final TableId tid, final ByteBuffer key)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return true;
+
+ try
+ {
+ return !denylist.get(tid).keys.contains(key);
+ }
+ catch (final ExecutionException e)
+ {
+ // In the event of an error accessing or populating the cache, assume it's not denylisted
+ logAccessFailure(tid, e);
+ return true;
+ }
+ }
+
+ private void logAccessFailure(final TableId tid, Throwable e)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ logger.debug("Failed to access partition denylist cache for unknown table id {}", tid.toString(), e);
+ else
+ logger.debug("Failed to access partition denylist cache for {}/{}", tmd.keyspace, tmd.name, e);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final String keyspace, final String cf, final AbstractBounds<PartitionPosition> range)
+ {
+ return validateRange(getTableId(keyspace, cf), range);
+ }
+
+ /**
+ * @return number of denylisted keys in range
+ */
+ public int validateRange(final TableId tid, final AbstractBounds<PartitionPosition> range)
+ {
+ if (!DatabaseDescriptor.enablePartitionDenylist() || tid == null || !isPermitted(tid))
+ return 0;
+
+ try
+ {
+ final DenylistEntry denylistEntry = denylist.get(tid);
+ if (denylistEntry.tokens.size() == 0)
+ return 0;
+ final Token startToken = range.left.getToken();
+ final Token endToken = range.right.getToken();
+
+ // Normal case
+ if (startToken.compareTo(endToken) <= 0 || endToken.isMinimum())
+ {
+ NavigableSet<Token> subSet = denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind()));
+ if (!endToken.isMinimum())
+ subSet = subSet.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind()));
+ return subSet.size();
+ }
+
+ // Wrap around case
+ return denylistEntry.tokens.tailSet(startToken, PartitionPosition.Kind.MIN_BOUND.equals(range.left.kind())).size()
+ + denylistEntry.tokens.headSet(endToken, PartitionPosition.Kind.MAX_BOUND.equals(range.right.kind())).size();
+ }
+ catch (final ExecutionException e)
+ {
+ logAccessFailure(tid, e);
+ return 0;
+ }
+ }
+
+ private DenylistEntry readDenylist(final TableId tid)
+ {
+ final TableMetadata tmd = Schema.instance.getTableMetadata(tid);
+ if (tmd == null)
+ return new DenylistEntry();
+
+ final String readDenylist = String.format("SELECT * FROM %s.%s WHERE ks_name='%s' AND cf_name='%s' LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE,
+ tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable() + 1);
+
+ try
+ {
+ final UntypedResultSet results = process(readDenylist, DatabaseDescriptor.denylistConsistencyLevel());
+ if (results == null || results.isEmpty())
+ return new DenylistEntry();
+
+ if (results.size() > DatabaseDescriptor.maxdenyDenylistKeysPerTable())
+ logger.error("Partition denylist for {}/{} has exceeded the maximum allowable size ({}). Remaining keys were ignored.", tmd.keyspace, tmd.name, DatabaseDescriptor.maxdenyDenylistKeysPerTable());
+
+ final Set<ByteBuffer> keys = new HashSet<>();
+ final NavigableSet<Token> tokens = new TreeSet<>();
+ for (final UntypedResultSet.Row row : results)
+ {
+ final ByteBuffer key = row.getBlob("key");
+ keys.add(key);
+ tokens.add(StorageService.instance.getTokenMetadata().partitioner.getToken(key));
+ }
+ return new DenylistEntry(ImmutableSet.copyOf(keys), ImmutableSortedSet.copyOf(tokens));
+ }
+ catch (final RequestExecutionException e)
+ {
+ logger.error("Error reading partition_denylist table for {}/{}", tmd.keyspace, tmd.name, e);
+ return null;
+ }
+ }
+
+ private Map<TableId, DenylistEntry> readAll()
+ {
+ final String readDenylist = String.format("SELECT * FROM %s.%s LIMIT %d", SystemDistributedKeyspace.NAME, PARTITION_DENYLIST_TABLE, DatabaseDescriptor.maxdenyDenylistKeysTotal() + 1);
Review comment:
Ok, you have a check to see whether the limit is exceeded. I'd add a comment on that here to prevent such confusion.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org