Search in sources :

Example 11 with Token

use of com.datastax.oss.driver.api.core.metadata.token.Token in project java-driver by datastax.

the class BasicLoadBalancingPolicy method getReplicas.

@NonNull
protected Set<Node> getReplicas(@Nullable Request request, @Nullable Session session) {
    if (request == null || session == null) {
        return Collections.emptySet();
    }
    Optional<TokenMap> maybeTokenMap = context.getMetadataManager().getMetadata().getTokenMap();
    if (!maybeTokenMap.isPresent()) {
        return Collections.emptySet();
    }
    // Note: we're on the hot path and the getXxx methods are potentially more than simple getters,
    // so we only call each method when strictly necessary (which is why the code below looks a bit
    // weird).
    CqlIdentifier keyspace;
    Token token;
    ByteBuffer key;
    try {
        keyspace = request.getKeyspace();
        if (keyspace == null) {
            keyspace = request.getRoutingKeyspace();
        }
        if (keyspace == null && session.getKeyspace().isPresent()) {
            keyspace = session.getKeyspace().get();
        }
        if (keyspace == null) {
            return Collections.emptySet();
        }
        token = request.getRoutingToken();
        key = (token == null) ? request.getRoutingKey() : null;
        if (token == null && key == null) {
            return Collections.emptySet();
        }
    } catch (Exception e) {
        // Protect against poorly-implemented Request instances
        LOG.error("Unexpected error while trying to compute query plan", e);
        return Collections.emptySet();
    }
    TokenMap tokenMap = maybeTokenMap.get();
    return token != null ? tokenMap.getReplicas(keyspace, token) : tokenMap.getReplicas(keyspace, key);
}
Also used : Token(com.datastax.oss.driver.api.core.metadata.token.Token) TokenMap(com.datastax.oss.driver.api.core.metadata.TokenMap) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) ByteBuffer(java.nio.ByteBuffer) NonNull(edu.umd.cs.findbugs.annotations.NonNull)

Example 12 with Token

use of com.datastax.oss.driver.api.core.metadata.token.Token in project java-driver by datastax.

the class ValuesHelper method encodeValues.

public static ByteBuffer[] encodeValues(Object[] values, List<DataType> fieldTypes, CodecRegistry codecRegistry, ProtocolVersion protocolVersion) {
    Preconditions.checkArgument(values.length <= fieldTypes.size(), "Too many values (expected %s, got %s)", fieldTypes.size(), values.length);
    ByteBuffer[] encodedValues = new ByteBuffer[fieldTypes.size()];
    for (int i = 0; i < values.length; i++) {
        Object value = values[i];
        ByteBuffer encodedValue;
        if (value instanceof Token) {
            if (value instanceof Murmur3Token) {
                encodedValue = TypeCodecs.BIGINT.encode(((Murmur3Token) value).getValue(), protocolVersion);
            } else if (value instanceof ByteOrderedToken) {
                encodedValue = TypeCodecs.BLOB.encode(((ByteOrderedToken) value).getValue(), protocolVersion);
            } else if (value instanceof RandomToken) {
                encodedValue = TypeCodecs.VARINT.encode(((RandomToken) value).getValue(), protocolVersion);
            } else {
                throw new IllegalArgumentException("Unsupported token type " + value.getClass());
            }
        } else {
            TypeCodec<Object> codec = (value == null) ? codecRegistry.codecFor(fieldTypes.get(i)) : codecRegistry.codecFor(fieldTypes.get(i), value);
            encodedValue = codec.encode(value, protocolVersion);
        }
        encodedValues[i] = encodedValue;
    }
    return encodedValues;
}
Also used : Murmur3Token(com.datastax.oss.driver.internal.core.metadata.token.Murmur3Token) Token(com.datastax.oss.driver.api.core.metadata.token.Token) ByteOrderedToken(com.datastax.oss.driver.internal.core.metadata.token.ByteOrderedToken) Murmur3Token(com.datastax.oss.driver.internal.core.metadata.token.Murmur3Token) RandomToken(com.datastax.oss.driver.internal.core.metadata.token.RandomToken) ByteOrderedToken(com.datastax.oss.driver.internal.core.metadata.token.ByteOrderedToken) RandomToken(com.datastax.oss.driver.internal.core.metadata.token.RandomToken) ByteBuffer(java.nio.ByteBuffer)

Example 13 with Token

use of com.datastax.oss.driver.api.core.metadata.token.Token in project java-driver by datastax.

the class ValuesHelper method encodePreparedValues.

public static ByteBuffer[] encodePreparedValues(Object[] values, ColumnDefinitions variableDefinitions, CodecRegistry codecRegistry, ProtocolVersion protocolVersion) {
    // Almost same as encodeValues, but we can't reuse because of variableDefinitions. Rebuilding a
    // list of datatypes is not worth it, so duplicate the code.
    Preconditions.checkArgument(values.length <= variableDefinitions.size(), "Too many variables (expected %s, got %s)", variableDefinitions.size(), values.length);
    ByteBuffer[] encodedValues = new ByteBuffer[variableDefinitions.size()];
    int i;
    for (i = 0; i < values.length; i++) {
        Object value = values[i];
        ByteBuffer encodedValue;
        if (value instanceof Token) {
            if (value instanceof Murmur3Token) {
                encodedValue = TypeCodecs.BIGINT.encode(((Murmur3Token) value).getValue(), protocolVersion);
            } else if (value instanceof ByteOrderedToken) {
                encodedValue = TypeCodecs.BLOB.encode(((ByteOrderedToken) value).getValue(), protocolVersion);
            } else if (value instanceof RandomToken) {
                encodedValue = TypeCodecs.VARINT.encode(((RandomToken) value).getValue(), protocolVersion);
            } else {
                throw new IllegalArgumentException("Unsupported token type " + value.getClass());
            }
        } else {
            TypeCodec<Object> codec = (value == null) ? codecRegistry.codecFor(variableDefinitions.get(i).getType()) : codecRegistry.codecFor(variableDefinitions.get(i).getType(), value);
            encodedValue = codec.encode(value, protocolVersion);
        }
        encodedValues[i] = encodedValue;
    }
    for (; i < encodedValues.length; i++) {
        encodedValues[i] = ProtocolConstants.UNSET_VALUE;
    }
    return encodedValues;
}
Also used : Murmur3Token(com.datastax.oss.driver.internal.core.metadata.token.Murmur3Token) Token(com.datastax.oss.driver.api.core.metadata.token.Token) ByteOrderedToken(com.datastax.oss.driver.internal.core.metadata.token.ByteOrderedToken) Murmur3Token(com.datastax.oss.driver.internal.core.metadata.token.Murmur3Token) RandomToken(com.datastax.oss.driver.internal.core.metadata.token.RandomToken) ByteOrderedToken(com.datastax.oss.driver.internal.core.metadata.token.ByteOrderedToken) RandomToken(com.datastax.oss.driver.internal.core.metadata.token.RandomToken) ByteBuffer(java.nio.ByteBuffer)

Example 14 with Token

use of com.datastax.oss.driver.api.core.metadata.token.Token in project java-driver by datastax.

the class BoundStatementCcmIT method should_propagate_attributes_when_preparing_a_simple_statement.

@Test
public void should_propagate_attributes_when_preparing_a_simple_statement() {
    CqlSession session = sessionRule.session();
    DriverExecutionProfile mockProfile = session.getContext().getConfig().getDefaultProfile().withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofSeconds(10));
    ByteBuffer mockPagingState = Bytes.fromHexString("0xaaaa");
    CqlIdentifier mockKeyspace = supportsPerRequestKeyspace(session) ? CqlIdentifier.fromCql("system") : null;
    CqlIdentifier mockRoutingKeyspace = CqlIdentifier.fromCql("mockRoutingKeyspace");
    ByteBuffer mockRoutingKey = Bytes.fromHexString("0xbbbb");
    Token mockRoutingToken = session.getMetadata().getTokenMap().get().newToken(mockRoutingKey);
    Map<String, ByteBuffer> mockCustomPayload = NullAllowingImmutableMap.of("key1", Bytes.fromHexString("0xcccc"));
    Duration mockTimeout = Duration.ofSeconds(1);
    ConsistencyLevel mockCl = DefaultConsistencyLevel.LOCAL_QUORUM;
    ConsistencyLevel mockSerialCl = DefaultConsistencyLevel.LOCAL_SERIAL;
    int mockPageSize = 2000;
    SimpleStatementBuilder simpleStatementBuilder = SimpleStatement.builder("SELECT release_version FROM system.local").setExecutionProfile(mockProfile).setPagingState(mockPagingState).setKeyspace(mockKeyspace).setRoutingKeyspace(mockRoutingKeyspace).setRoutingKey(mockRoutingKey).setRoutingToken(mockRoutingToken).setQueryTimestamp(42).setIdempotence(true).setTracing().setTimeout(mockTimeout).setConsistencyLevel(mockCl).setSerialConsistencyLevel(mockSerialCl).setPageSize(mockPageSize);
    if (atLeastV4) {
        simpleStatementBuilder = simpleStatementBuilder.addCustomPayload("key1", mockCustomPayload.get("key1"));
    }
    PreparedStatement preparedStatement = session.prepare(simpleStatementBuilder.build());
    // Cover all the ways to create bound statements:
    ImmutableList<Function<PreparedStatement, BoundStatement>> createMethods = ImmutableList.of(PreparedStatement::bind, p -> p.boundStatementBuilder().build());
    for (Function<PreparedStatement, BoundStatement> createMethod : createMethods) {
        BoundStatement boundStatement = createMethod.apply(preparedStatement);
        assertThat(boundStatement.getExecutionProfile()).isEqualTo(mockProfile);
        assertThat(boundStatement.getPagingState()).isEqualTo(mockPagingState);
        assertThat(boundStatement.getRoutingKeyspace()).isEqualTo(mockKeyspace != null ? mockKeyspace : mockRoutingKeyspace);
        assertThat(boundStatement.getRoutingKey()).isEqualTo(mockRoutingKey);
        assertThat(boundStatement.getRoutingToken()).isEqualTo(mockRoutingToken);
        if (atLeastV4) {
            assertThat(boundStatement.getCustomPayload()).isEqualTo(mockCustomPayload);
        }
        assertThat(boundStatement.isIdempotent()).isTrue();
        assertThat(boundStatement.isTracing()).isTrue();
        assertThat(boundStatement.getTimeout()).isEqualTo(mockTimeout);
        assertThat(boundStatement.getConsistencyLevel()).isEqualTo(mockCl);
        assertThat(boundStatement.getSerialConsistencyLevel()).isEqualTo(mockSerialCl);
        assertThat(boundStatement.getPageSize()).isEqualTo(mockPageSize);
        // Bound statements do not support per-query keyspaces, so this is not set
        assertThat(boundStatement.getKeyspace()).isNull();
        // Should not be propagated
        assertThat(boundStatement.getQueryTimestamp()).isEqualTo(Statement.NO_DEFAULT_TIMESTAMP);
    }
}
Also used : DriverExecutionProfile(com.datastax.oss.driver.api.core.config.DriverExecutionProfile) SimpleStatementBuilder(com.datastax.oss.driver.api.core.cql.SimpleStatementBuilder) Token(com.datastax.oss.driver.api.core.metadata.token.Token) Duration(java.time.Duration) PreparedStatement(com.datastax.oss.driver.api.core.cql.PreparedStatement) CqlSession(com.datastax.oss.driver.api.core.CqlSession) ByteBuffer(java.nio.ByteBuffer) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) DefaultConsistencyLevel(com.datastax.oss.driver.api.core.DefaultConsistencyLevel) ConsistencyLevel(com.datastax.oss.driver.api.core.ConsistencyLevel) Function(java.util.function.Function) BoundStatement(com.datastax.oss.driver.api.core.cql.BoundStatement) Test(org.junit.Test)

Example 15 with Token

use of com.datastax.oss.driver.api.core.metadata.token.Token in project java-driver by datastax.

the class TokenRangeBase method splitEvenly.

@NonNull
@Override
public List<TokenRange> splitEvenly(int numberOfSplits) {
    if (numberOfSplits < 1)
        throw new IllegalArgumentException(String.format("numberOfSplits (%d) must be greater than 0.", numberOfSplits));
    if (isEmpty()) {
        throw new IllegalArgumentException("Can't split empty range " + this);
    }
    List<TokenRange> tokenRanges = new ArrayList<>();
    List<Token> splitPoints = split(start, end, numberOfSplits);
    Token splitStart = start;
    for (Token splitEnd : splitPoints) {
        tokenRanges.add(newTokenRange(splitStart, splitEnd));
        splitStart = splitEnd;
    }
    tokenRanges.add(newTokenRange(splitStart, end));
    return tokenRanges;
}
Also used : ArrayList(java.util.ArrayList) TokenRange(com.datastax.oss.driver.api.core.metadata.token.TokenRange) Token(com.datastax.oss.driver.api.core.metadata.token.Token) NonNull(edu.umd.cs.findbugs.annotations.NonNull)

Aggregations

Token (com.datastax.oss.driver.api.core.metadata.token.Token)22 Node (com.datastax.oss.driver.api.core.metadata.Node)6 Test (org.junit.Test)6 TokenRange (com.datastax.oss.driver.api.core.metadata.token.TokenRange)5 TokenMap (com.datastax.oss.driver.api.core.metadata.TokenMap)4 ImmutableMap (com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap)4 ByteBuffer (java.nio.ByteBuffer)4 CqlIdentifier (com.datastax.oss.driver.api.core.CqlIdentifier)3 PreparedStatement (com.datastax.oss.driver.api.core.cql.PreparedStatement)3 Row (com.datastax.oss.driver.api.core.cql.Row)3 NonNull (edu.umd.cs.findbugs.annotations.NonNull)3 BigInteger (java.math.BigInteger)3 Set (java.util.Set)3 CqlSession (com.datastax.oss.driver.api.core.CqlSession)2 BoundStatement (com.datastax.oss.driver.api.core.cql.BoundStatement)2 DefaultNode (com.datastax.oss.driver.internal.core.metadata.DefaultNode)2 ByteOrderedToken (com.datastax.oss.driver.internal.core.metadata.token.ByteOrderedToken)2 Murmur3Token (com.datastax.oss.driver.internal.core.metadata.token.Murmur3Token)2 RandomToken (com.datastax.oss.driver.internal.core.metadata.token.RandomToken)2 ImmutableSet (com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet)2