Search in sources :

Example 16 with QueryState

use of org.apache.cassandra.service.QueryState in project cassandra by apache.

the class AlterSchemaStatement method execute.

public ResultMessage execute(QueryState state, boolean locally) {
    if (SchemaConstants.isLocalSystemKeyspace(keyspaceName))
        throw ire("System keyspace '%s' is not user-modifiable", keyspaceName);
    KeyspaceMetadata keyspace = Schema.instance.getKeyspaceMetadata(keyspaceName);
    if (null != keyspace && keyspace.isVirtual())
        throw ire("Virtual keyspace '%s' is not user-modifiable", keyspaceName);
    validateKeyspaceName();
    KeyspacesDiff diff = MigrationManager.announce(this, locally);
    clientWarnings(diff).forEach(ClientWarn.instance::warn);
    if (diff.isEmpty())
        return new ResultMessage.Void();
    /*
         * When a schema alteration results in a new db object being created, we grant permissions on the new
         * object to the user performing the request if:
         * - the user is not anonymous
         * - the configured IAuthorizer supports granting of permissions (not all do, AllowAllAuthorizer doesn't and
         *   custom external implementations may not)
         */
    AuthenticatedUser user = state.getClientState().getUser();
    if (null != user && !user.isAnonymous())
        createdResources(diff).forEach(r -> grantPermissionsOnResource(r, user));
    return new ResultMessage.SchemaChange(schemaChangeEvent(diff));
}
Also used : ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) ImmutableSet(com.google.common.collect.ImmutableSet) QueryState(org.apache.cassandra.service.QueryState) ClientWarn(org.apache.cassandra.service.ClientWarn) SchemaChange(org.apache.cassandra.transport.Event.SchemaChange) ClientState(org.apache.cassandra.service.ClientState) Set(java.util.Set) AuthenticatedUser(org.apache.cassandra.auth.AuthenticatedUser) CQLStatement(org.apache.cassandra.cql3.CQLStatement) IResource(org.apache.cassandra.auth.IResource) KeyspacesDiff(org.apache.cassandra.schema.Keyspaces.KeyspacesDiff) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) QueryOptions(org.apache.cassandra.cql3.QueryOptions) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) org.apache.cassandra.schema(org.apache.cassandra.schema) KeyspacesDiff(org.apache.cassandra.schema.Keyspaces.KeyspacesDiff) SchemaChange(org.apache.cassandra.transport.Event.SchemaChange) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) AuthenticatedUser(org.apache.cassandra.auth.AuthenticatedUser)

Example 17 with QueryState

use of org.apache.cassandra.service.QueryState in project cassandra by apache.

the class DescribeStatement method executeLocally.

@Override
public ResultMessage executeLocally(QueryState state, QueryOptions options) {
    Keyspaces keyspaces = Schema.instance.snapshot();
    UUID schemaVersion = Schema.instance.getVersion();
    keyspaces = Keyspaces.builder().add(keyspaces).add(VirtualKeyspaceRegistry.instance.virtualKeyspacesMetadata()).build();
    PagingState pagingState = options.getPagingState();
    // The paging implemented here uses some arbitray row number as the partition-key for paging,
    // which is used to skip/limit the result from the Java Stream. This works good enough for
    // reasonably sized schemas. Even a 'DESCRIBE SCHEMA' for an abnormally schema with 10000 tables
    // completes within a few seconds. This seems good enough for now. Once Cassandra actually supports
    // more than a few hundred tables, the implementation here should be reconsidered.
    // 
    // Paging is only supported on row-level.
    // 
    // The "partition key" in the paging-state contains a serialized object:
    // (short) version, currently 0x0001
    // (long) row offset
    // (vint bytes) serialized schema hash (currently the result of Keyspaces.hashCode())
    // 
    long offset = getOffset(pagingState, schemaVersion);
    int pageSize = options.getPageSize();
    Stream<? extends T> stream = describe(state.getClientState(), keyspaces);
    if (offset > 0L)
        stream = stream.skip(offset);
    if (pageSize > 0)
        stream = stream.limit(pageSize);
    List<List<ByteBuffer>> rows = stream.map(e -> toRow(e, includeInternalDetails)).collect(Collectors.toList());
    ResultSet.ResultMetadata resultMetadata = new ResultSet.ResultMetadata(metadata(state.getClientState()));
    ResultSet result = new ResultSet(resultMetadata, rows);
    if (pageSize > 0 && rows.size() == pageSize) {
        result.metadata.setHasMorePages(getPagingState(offset + pageSize, schemaVersion));
    }
    return new ResultMessage.Rows(result);
}
Also used : AuditLogContext(org.apache.cassandra.audit.AuditLogContext) java.util(java.util) RequestValidations.invalidRequest(org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest) DataOutputBuffer(org.apache.cassandra.io.util.DataOutputBuffer) RequestValidations.checkNotEmpty(org.apache.cassandra.cql3.statements.RequestValidations.checkNotEmpty) BiFunction(java.util.function.BiFunction) ByteBufferUtil.bytes(org.apache.cassandra.utils.ByteBufferUtil.bytes) ByteBuffer(java.nio.ByteBuffer) org.apache.cassandra.cql3(org.apache.cassandra.cql3) RequestExecutionException(org.apache.cassandra.exceptions.RequestExecutionException) ListType(org.apache.cassandra.db.marshal.ListType) UTF8Type(org.apache.cassandra.db.marshal.UTF8Type) ImmutableList(com.google.common.collect.ImmutableList) KeyspaceNotDefinedException(org.apache.cassandra.db.KeyspaceNotDefinedException) FunctionName(org.apache.cassandra.cql3.functions.FunctionName) RequestValidations.checkNotNull(org.apache.cassandra.cql3.statements.RequestValidations.checkNotNull) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) RequestValidationException(org.apache.cassandra.exceptions.RequestValidationException) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) FBUtilities(org.apache.cassandra.utils.FBUtilities) QueryState(org.apache.cassandra.service.QueryState) ByteBufferUtil(org.apache.cassandra.utils.ByteBufferUtil) RequestValidations.checkTrue(org.apache.cassandra.cql3.statements.RequestValidations.checkTrue) ClientState(org.apache.cassandra.service.ClientState) StorageService(org.apache.cassandra.service.StorageService) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) UUIDGen(org.apache.cassandra.utils.UUIDGen) String.format(java.lang.String.format) AuditLogEntryType(org.apache.cassandra.audit.AuditLogEntryType) MapType(org.apache.cassandra.db.marshal.MapType) Stream(java.util.stream.Stream) PagingState(org.apache.cassandra.service.pager.PagingState) VirtualKeyspaceRegistry(org.apache.cassandra.db.virtual.VirtualKeyspaceRegistry) org.apache.cassandra.schema(org.apache.cassandra.schema) DataInputBuffer(org.apache.cassandra.io.util.DataInputBuffer) PagingState(org.apache.cassandra.service.pager.PagingState) ImmutableList(com.google.common.collect.ImmutableList)

Example 18 with QueryState

use of org.apache.cassandra.service.QueryState in project cassandra by apache.

the class Dispatcher method processRequest.

/**
 * Note: this method may be executed on the netty event loop, during initial protocol negotiation; the caller is
 * responsible for cleaning up any global or thread-local state. (ex. tracing, client warnings, etc.).
 */
private static Message.Response processRequest(ServerConnection connection, Message.Request request, Overload backpressure) {
    long queryStartNanoTime = nanoTime();
    if (connection.getVersion().isGreaterOrEqualTo(ProtocolVersion.V4))
        ClientWarn.instance.captureWarnings();
    // emit logs on the server; the warnings will just be ignored and not sent to the client
    if (request.isTrackable())
        CoordinatorWarnings.init();
    if (backpressure == Overload.REQUESTS) {
        String message = String.format("Request breached global limit of %d requests/second and triggered backpressure.", ClientResourceLimits.getNativeTransportMaxRequestsPerSecond());
        NoSpamLogger.log(logger, NoSpamLogger.Level.INFO, 1, TimeUnit.MINUTES, message);
        ClientWarn.instance.warn(message);
    } else if (backpressure == Overload.BYTES_IN_FLIGHT) {
        String message = String.format("Request breached limit(s) on bytes in flight (Endpoint: %d, Global: %d) and triggered backpressure.", ClientResourceLimits.getEndpointLimit(), ClientResourceLimits.getGlobalLimit());
        NoSpamLogger.log(logger, NoSpamLogger.Level.INFO, 1, TimeUnit.MINUTES, message);
        ClientWarn.instance.warn(message);
    }
    QueryState qstate = connection.validateNewMessage(request.type, connection.getVersion());
    Message.logger.trace("Received: {}, v={}", request, connection.getVersion());
    connection.requests.inc();
    Message.Response response = request.execute(qstate, queryStartNanoTime);
    if (request.isTrackable())
        CoordinatorWarnings.done();
    response.setStreamId(request.getStreamId());
    response.setWarnings(ClientWarn.instance.getWarnings());
    response.attach(connection);
    connection.applyStateTransition(request.type, response.type);
    return response;
}
Also used : EventMessage(org.apache.cassandra.transport.messages.EventMessage) ErrorMessage(org.apache.cassandra.transport.messages.ErrorMessage) QueryState(org.apache.cassandra.service.QueryState)

Example 19 with QueryState

use of org.apache.cassandra.service.QueryState in project cassandra by apache.

the class SerDeserTest method queryOptionsSerDeserTest.

private void queryOptionsSerDeserTest(ProtocolVersion version, QueryOptions options) {
    ByteBuf buf = Unpooled.buffer(QueryOptions.codec.encodedSize(options, version));
    QueryOptions.codec.encode(options, buf, version);
    QueryOptions decodedOptions = QueryOptions.codec.decode(buf, version);
    QueryState state = new QueryState(ClientState.forInternalCalls());
    assertNotNull(decodedOptions);
    assertEquals(options.getConsistency(), decodedOptions.getConsistency());
    assertEquals(options.getSerialConsistency(), decodedOptions.getSerialConsistency());
    assertEquals(options.getPageSize(), decodedOptions.getPageSize());
    assertEquals(options.getProtocolVersion(), decodedOptions.getProtocolVersion());
    assertEquals(options.getValues(), decodedOptions.getValues());
    assertEquals(options.getPagingState(), decodedOptions.getPagingState());
    assertEquals(options.skipMetadata(), decodedOptions.skipMetadata());
    assertEquals(options.getKeyspace(), decodedOptions.getKeyspace());
    assertEquals(options.getTimestamp(state), decodedOptions.getTimestamp(state));
    assertEquals(options.getNowInSeconds(state), decodedOptions.getNowInSeconds(state));
}
Also used : QueryState(org.apache.cassandra.service.QueryState) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

QueryState (org.apache.cassandra.service.QueryState)19 QueryOptions (org.apache.cassandra.cql3.QueryOptions)6 ClientState (org.apache.cassandra.service.ClientState)6 ResultMessage (org.apache.cassandra.transport.messages.ResultMessage)6 ByteBuf (io.netty.buffer.ByteBuf)5 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 List (java.util.List)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 ColumnFamilyStore (org.apache.cassandra.db.ColumnFamilyStore)4 ByteBuffer (java.nio.ByteBuffer)3 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 DatabaseDescriptor (org.apache.cassandra.config.DatabaseDescriptor)3 CQLStatement (org.apache.cassandra.cql3.CQLStatement)3 SelectStatement (org.apache.cassandra.cql3.statements.SelectStatement)3 InvalidRequestException (org.apache.cassandra.exceptions.InvalidRequestException)3 BurnTestUtil.generateQueryMessage (org.apache.cassandra.transport.BurnTestUtil.generateQueryMessage)3 QueryMessage (org.apache.cassandra.transport.messages.QueryMessage)3 IOException (java.io.IOException)2