Search in sources :

Example 6 with Bounds

use of org.apache.cassandra.dht.Bounds in project cassandra by apache.

the class CassandraValidationIterator method getSSTablesToValidate.

@VisibleForTesting
public static synchronized Refs<SSTableReader> getSSTablesToValidate(ColumnFamilyStore cfs, Collection<Range<Token>> ranges, UUID parentId, boolean isIncremental) throws NoSuchRepairSessionException {
    Refs<SSTableReader> sstables;
    ActiveRepairService.ParentRepairSession prs = ActiveRepairService.instance.getParentRepairSession(parentId);
    Set<SSTableReader> sstablesToValidate = new HashSet<>();
    com.google.common.base.Predicate<SSTableReader> predicate;
    if (prs.isPreview()) {
        predicate = prs.previewKind.predicate();
    } else if (isIncremental) {
        predicate = s -> parentId.equals(s.getSSTableMetadata().pendingRepair);
    } else {
        // note that we always grab all existing sstables for this - if we were to just grab the ones that
        // were marked as repairing, we would miss any ranges that were compacted away and this would cause us to overstream
        predicate = (s) -> !prs.isIncremental || !s.isRepaired();
    }
    try (ColumnFamilyStore.RefViewFragment sstableCandidates = cfs.selectAndReference(View.selectFunction(SSTableSet.CANONICAL))) {
        for (SSTableReader sstable : sstableCandidates.sstables) {
            if (new Bounds<>(sstable.first.getToken(), sstable.last.getToken()).intersects(ranges) && predicate.apply(sstable)) {
                sstablesToValidate.add(sstable);
            }
        }
        sstables = Refs.tryRef(sstablesToValidate);
        if (sstables == null) {
            logger.error("Could not reference sstables for {}", parentId);
            throw new RuntimeException("Could not reference sstables");
        }
    }
    return sstables;
}
Also used : NoSuchRepairSessionException(org.apache.cassandra.repair.NoSuchRepairSessionException) CompactionManager(org.apache.cassandra.db.compaction.CompactionManager) SSTableSet(org.apache.cassandra.db.lifecycle.SSTableSet) LoggerFactory(org.slf4j.LoggerFactory) Range(org.apache.cassandra.dht.Range) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) HashSet(java.util.HashSet) DecoratedKey(org.apache.cassandra.db.DecoratedKey) Token(org.apache.cassandra.dht.Token) ActiveRepairService(org.apache.cassandra.service.ActiveRepairService) CompactionController(org.apache.cassandra.db.compaction.CompactionController) OperationType(org.apache.cassandra.db.compaction.OperationType) UnfilteredRowIterator(org.apache.cassandra.db.rows.UnfilteredRowIterator) Map(java.util.Map) LongPredicate(java.util.function.LongPredicate) Refs(org.apache.cassandra.utils.concurrent.Refs) ValidationPartitionIterator(org.apache.cassandra.repair.ValidationPartitionIterator) Logger(org.slf4j.Logger) ActiveCompactionsTracker(org.apache.cassandra.db.compaction.ActiveCompactionsTracker) Collection(java.util.Collection) Set(java.util.Set) ISSTableScanner(org.apache.cassandra.io.sstable.ISSTableScanner) StorageService(org.apache.cassandra.service.StorageService) IOException(java.io.IOException) UUID(java.util.UUID) Bounds(org.apache.cassandra.dht.Bounds) Maps(com.google.common.collect.Maps) CompactionInfo(org.apache.cassandra.db.compaction.CompactionInfo) UUIDGen(org.apache.cassandra.utils.UUIDGen) List(java.util.List) ColumnFamilyStore(org.apache.cassandra.db.ColumnFamilyStore) CompactionIterator(org.apache.cassandra.db.compaction.CompactionIterator) TableMetadata(org.apache.cassandra.schema.TableMetadata) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) AbstractCompactionStrategy(org.apache.cassandra.db.compaction.AbstractCompactionStrategy) View(org.apache.cassandra.db.lifecycle.View) ActiveRepairService(org.apache.cassandra.service.ActiveRepairService) Bounds(org.apache.cassandra.dht.Bounds) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) ColumnFamilyStore(org.apache.cassandra.db.ColumnFamilyStore) HashSet(java.util.HashSet) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 7 with Bounds

use of org.apache.cassandra.dht.Bounds in project cassandra by apache.

the class RowCacheTest method getBounds.

private ArrayList<Bounds<Token>> getBounds(int nElements) {
    ColumnFamilyStore store = Keyspace.open(KEYSPACE_CACHED).getColumnFamilyStore(CF_CACHED);
    TreeSet<DecoratedKey> orderedKeys = new TreeSet<>();
    for (Iterator<RowCacheKey> it = CacheService.instance.rowCache.keyIterator(); it.hasNext(); ) orderedKeys.add(store.decorateKey(ByteBuffer.wrap(it.next().key)));
    ArrayList<Bounds<Token>> boundsToInvalidate = new ArrayList<>();
    Iterator<DecoratedKey> iterator = orderedKeys.iterator();
    while (iterator.hasNext()) {
        Token startRange = iterator.next().getToken();
        for (int i = 0; i < nElements - 2; i++) iterator.next();
        Token endRange = iterator.next().getToken();
        boundsToInvalidate.add(new Bounds<>(startRange, endRange));
    }
    return boundsToInvalidate;
}
Also used : Bounds(org.apache.cassandra.dht.Bounds) ArrayList(java.util.ArrayList) BytesToken(org.apache.cassandra.dht.ByteOrderedPartitioner.BytesToken) Token(org.apache.cassandra.dht.Token) TreeSet(java.util.TreeSet) RowCacheKey(org.apache.cassandra.cache.RowCacheKey)

Example 8 with Bounds

use of org.apache.cassandra.dht.Bounds in project cassandra by apache.

the class SSTableExport method main.

/**
 * Given arguments specifying an SSTable, and optionally an output file, export the contents of the SSTable to JSON.
 *
 * @param args
 *            command lines arguments
 * @throws ConfigurationException
 *             on configuration failure (wrong params given)
 */
@SuppressWarnings("resource")
public static void main(String[] args) throws ConfigurationException {
    CommandLineParser parser = new PosixParser();
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        System.err.println(e1.getMessage());
        printUsage();
        System.exit(1);
    }
    String[] keys = cmd.getOptionValues(KEY_OPTION);
    HashSet<String> excludes = new HashSet<>(Arrays.asList(cmd.getOptionValues(EXCLUDE_KEY_OPTION) == null ? new String[0] : cmd.getOptionValues(EXCLUDE_KEY_OPTION)));
    if (cmd.getArgs().length != 1) {
        String msg = "You must supply exactly one sstable";
        if (cmd.getArgs().length == 0 && (keys != null && keys.length > 0 || !excludes.isEmpty()))
            msg += ", which should be before the -k/-x options so it's not interpreted as a partition key.";
        System.err.println(msg);
        printUsage();
        System.exit(1);
    }
    String ssTableFileName = new File(cmd.getArgs()[0]).absolutePath();
    if (!new File(ssTableFileName).exists()) {
        System.err.println("Cannot find file " + ssTableFileName);
        System.exit(1);
    }
    Descriptor desc = Descriptor.fromFilename(ssTableFileName);
    try {
        TableMetadata metadata = Util.metadataFromSSTable(desc);
        if (cmd.hasOption(ENUMERATE_KEYS_OPTION)) {
            try (KeyIterator iter = new KeyIterator(desc, metadata)) {
                JsonTransformer.keysToJson(null, Util.iterToStream(iter), cmd.hasOption(RAW_TIMESTAMPS), metadata, System.out);
            }
        } else {
            SSTableReader sstable = SSTableReader.openNoValidation(desc, TableMetadataRef.forOfflineTools(metadata));
            IPartitioner partitioner = sstable.getPartitioner();
            final ISSTableScanner currentScanner;
            if ((keys != null) && (keys.length > 0)) {
                List<AbstractBounds<PartitionPosition>> bounds = Arrays.stream(keys).filter(key -> !excludes.contains(key)).map(metadata.partitionKeyType::fromString).map(partitioner::decorateKey).sorted().map(DecoratedKey::getToken).map(token -> new Bounds<>(token.minKeyBound(), token.maxKeyBound())).collect(Collectors.toList());
                currentScanner = sstable.getScanner(bounds.iterator());
            } else {
                currentScanner = sstable.getScanner();
            }
            Stream<UnfilteredRowIterator> partitions = Util.iterToStream(currentScanner).filter(i -> excludes.isEmpty() || !excludes.contains(metadata.partitionKeyType.getString(i.partitionKey().getKey())));
            if (cmd.hasOption(DEBUG_OUTPUT_OPTION)) {
                AtomicLong position = new AtomicLong();
                partitions.forEach(partition -> {
                    position.set(currentScanner.getCurrentPosition());
                    if (!partition.partitionLevelDeletion().isLive()) {
                        System.out.println("[" + metadata.partitionKeyType.getString(partition.partitionKey().getKey()) + "]@" + position.get() + " " + partition.partitionLevelDeletion());
                    }
                    if (!partition.staticRow().isEmpty()) {
                        System.out.println("[" + metadata.partitionKeyType.getString(partition.partitionKey().getKey()) + "]@" + position.get() + " " + partition.staticRow().toString(metadata, true));
                    }
                    partition.forEachRemaining(row -> {
                        System.out.println("[" + metadata.partitionKeyType.getString(partition.partitionKey().getKey()) + "]@" + position.get() + " " + row.toString(metadata, false, true));
                        position.set(currentScanner.getCurrentPosition());
                    });
                });
            } else if (cmd.hasOption(PARTITION_JSON_LINES)) {
                JsonTransformer.toJsonLines(currentScanner, partitions, cmd.hasOption(RAW_TIMESTAMPS), metadata, System.out);
            } else {
                JsonTransformer.toJson(currentScanner, partitions, cmd.hasOption(RAW_TIMESTAMPS), metadata, System.out);
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    System.exit(0);
}
Also used : ISSTableScanner(org.apache.cassandra.io.sstable.ISSTableScanner) Arrays(java.util.Arrays) File(org.apache.cassandra.io.util.File) Options(org.apache.commons.cli.Options) HelpFormatter(org.apache.commons.cli.HelpFormatter) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) HashSet(java.util.HashSet) KeyIterator(org.apache.cassandra.io.sstable.KeyIterator) DecoratedKey(org.apache.cassandra.db.DecoratedKey) ConfigurationException(org.apache.cassandra.exceptions.ConfigurationException) UnfilteredRowIterator(org.apache.cassandra.db.rows.UnfilteredRowIterator) AbstractBounds(org.apache.cassandra.dht.AbstractBounds) Descriptor(org.apache.cassandra.io.sstable.Descriptor) CommandLine(org.apache.commons.cli.CommandLine) PosixParser(org.apache.commons.cli.PosixParser) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) Option(org.apache.commons.cli.Option) FBUtilities(org.apache.cassandra.utils.FBUtilities) CommandLineParser(org.apache.commons.cli.CommandLineParser) ISSTableScanner(org.apache.cassandra.io.sstable.ISSTableScanner) IOException(java.io.IOException) Bounds(org.apache.cassandra.dht.Bounds) Collectors(java.util.stream.Collectors) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Stream(java.util.stream.Stream) PartitionPosition(org.apache.cassandra.db.PartitionPosition) IPartitioner(org.apache.cassandra.dht.IPartitioner) ParseException(org.apache.commons.cli.ParseException) TableMetadataRef(org.apache.cassandra.schema.TableMetadataRef) TableMetadata(org.apache.cassandra.schema.TableMetadata) UnfilteredRowIterator(org.apache.cassandra.db.rows.UnfilteredRowIterator) PosixParser(org.apache.commons.cli.PosixParser) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) CommandLineParser(org.apache.commons.cli.CommandLineParser) HashSet(java.util.HashSet) IPartitioner(org.apache.cassandra.dht.IPartitioner) TableMetadata(org.apache.cassandra.schema.TableMetadata) KeyIterator(org.apache.cassandra.io.sstable.KeyIterator) DecoratedKey(org.apache.cassandra.db.DecoratedKey) AbstractBounds(org.apache.cassandra.dht.AbstractBounds) Bounds(org.apache.cassandra.dht.Bounds) IOException(java.io.IOException) AtomicLong(java.util.concurrent.atomic.AtomicLong) AbstractBounds(org.apache.cassandra.dht.AbstractBounds) Descriptor(org.apache.cassandra.io.sstable.Descriptor) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) ParseException(org.apache.commons.cli.ParseException) File(org.apache.cassandra.io.util.File)

Example 9 with Bounds

use of org.apache.cassandra.dht.Bounds in project eiger by wlloyd.

the class QueryProcessor method multiRangeSlice.

private static List<org.apache.cassandra.db.Row> multiRangeSlice(CFMetaData metadata, SelectStatement select, List<String> variables) throws TimedOutException, UnavailableException, InvalidRequestException {
    List<org.apache.cassandra.db.Row> rows;
    IPartitioner<?> p = StorageService.getPartitioner();
    AbstractType<?> keyType = Schema.instance.getCFMetaData(metadata.ksName, select.getColumnFamily()).getKeyValidator();
    ByteBuffer startKeyBytes = (select.getKeyStart() != null) ? select.getKeyStart().getByteBuffer(keyType, variables) : null;
    ByteBuffer finishKeyBytes = (select.getKeyFinish() != null) ? select.getKeyFinish().getByteBuffer(keyType, variables) : null;
    RowPosition startKey = RowPosition.forKey(startKeyBytes, p), finishKey = RowPosition.forKey(finishKeyBytes, p);
    if (startKey.compareTo(finishKey) > 0 && !finishKey.isMinimum(p)) {
        if (p instanceof RandomPartitioner)
            throw new InvalidRequestException("Start key sorts after end key. This is not allowed; you probably should not specify end key at all, under RandomPartitioner");
        else
            throw new InvalidRequestException("Start key must sort before (or equal to) finish key in your partitioner!");
    }
    AbstractBounds<RowPosition> bounds = new Bounds<RowPosition>(startKey, finishKey);
    // XXX: Our use of Thrift structs internally makes me Sad. :(
    SlicePredicate thriftSlicePredicate = slicePredicateFromSelect(select, metadata, variables);
    validateSlicePredicate(metadata, thriftSlicePredicate);
    List<IndexExpression> expressions = new ArrayList<IndexExpression>();
    for (Relation columnRelation : select.getColumnRelations()) {
        // Left and right side of relational expression encoded according to comparator/validator.
        ByteBuffer entity = columnRelation.getEntity().getByteBuffer(metadata.comparator, variables);
        ByteBuffer value = columnRelation.getValue().getByteBuffer(select.getValueValidator(metadata.ksName, entity), variables);
        expressions.add(new IndexExpression(entity, IndexOperator.valueOf(columnRelation.operator().toString()), value));
    }
    int limit = select.isKeyRange() && select.getKeyStart() != null ? select.getNumRecords() + 1 : select.getNumRecords();
    try {
        rows = StorageProxy.getRangeSlice(new RangeSliceCommand(metadata.ksName, select.getColumnFamily(), null, thriftSlicePredicate, bounds, expressions, limit), select.getConsistencyLevel());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (org.apache.cassandra.thrift.UnavailableException e) {
        throw new UnavailableException();
    } catch (TimeoutException e) {
        throw new TimedOutException();
    }
    // if start key was set and relation was "greater than"
    if (select.getKeyStart() != null && !select.includeStartKey() && !rows.isEmpty()) {
        if (rows.get(0).key.key.equals(startKeyBytes))
            rows.remove(0);
    }
    // if finish key was set and relation was "less than"
    if (select.getKeyFinish() != null && !select.includeFinishKey() && !rows.isEmpty()) {
        int lastIndex = rows.size() - 1;
        if (rows.get(lastIndex).key.key.equals(finishKeyBytes))
            rows.remove(lastIndex);
    }
    return rows.subList(0, select.getNumRecords() < rows.size() ? select.getNumRecords() : rows.size());
}
Also used : RandomPartitioner(org.apache.cassandra.dht.RandomPartitioner) org.apache.cassandra.thrift(org.apache.cassandra.thrift) TimeoutException(java.util.concurrent.TimeoutException) AbstractBounds(org.apache.cassandra.dht.AbstractBounds) Bounds(org.apache.cassandra.dht.Bounds) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Aggregations

Bounds (org.apache.cassandra.dht.Bounds)9 AbstractBounds (org.apache.cassandra.dht.AbstractBounds)5 Token (org.apache.cassandra.dht.Token)5 SSTableReader (org.apache.cassandra.io.sstable.format.SSTableReader)5 IOException (java.io.IOException)4 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 PartitionPosition (org.apache.cassandra.db.PartitionPosition)3 UnfilteredRowIterator (org.apache.cassandra.db.rows.UnfilteredRowIterator)3 ISSTableScanner (org.apache.cassandra.io.sstable.ISSTableScanner)3 TableMetadata (org.apache.cassandra.schema.TableMetadata)3 Preconditions (com.google.common.base.Preconditions)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 DatabaseDescriptor (org.apache.cassandra.config.DatabaseDescriptor)2 DecoratedKey (org.apache.cassandra.db.DecoratedKey)2 SSTableSet (org.apache.cassandra.db.lifecycle.SSTableSet)2 View (org.apache.cassandra.db.lifecycle.View)2 Range (org.apache.cassandra.dht.Range)2