All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.cassandra.db.ReadCommandVerbHandler Maven / Gradle / Ivy

Go to download

The Apache Cassandra Project develops a highly scalable second-generation distributed database, bringing together Dynamo's fully distributed design and Bigtable's ColumnFamily-based data model.

There is a newer version: 5.0.2
Show newest version
/*
 * 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.db;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.partitions.UnfilteredPartitionIterator;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.locator.Replica;
import org.apache.cassandra.net.IVerbHandler;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.tracing.Tracing;
import org.apache.cassandra.utils.NoSpamLogger;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

public class ReadCommandVerbHandler implements IVerbHandler
{
    public static final ReadCommandVerbHandler instance = new ReadCommandVerbHandler();

    private static final Logger logger = LoggerFactory.getLogger(ReadCommandVerbHandler.class);
    private static final String logMessageTemplate = "Receiving read(s) for token(s) neither owned nor pending. Example: from {} for token {} in {}.{}";
    private static final String exceptionMessageTemplate = "Exception thrown checking if token {} outside valid range for keyspace {} - permitting";

    public void doVerb(Message message)
    {
        if (StorageService.instance.isBootstrapMode())
        {
            throw new RuntimeException("Cannot service reads while bootstrapping!");
        }

        ReadCommand command = message.payload;

        // no out of token range checking for partition range reads yet
        if (command.isSinglePartitionRead())
        {
            boolean outOfRangeTokenLogging = DatabaseDescriptor.getLogOutOfTokenRangeRequests();
            boolean outOfRangeTokenRejection = DatabaseDescriptor.getRejectOutOfTokenRangeRequests();

            DecoratedKey key = ((SinglePartitionReadCommand)command).partitionKey();
            if (!command.metadata().isVirtual() && isOutOfRangeRead(command.metadata().keyspace, key))
            {
                StorageService.instance.incOutOfRangeOperationCount();
                Keyspace.open(command.metadata().keyspace).metric.outOfRangeTokenReads.inc();

                // Log at most 1 message per second
                if (outOfRangeTokenLogging)
                    NoSpamLogger.log(logger, NoSpamLogger.Level.WARN, 1, TimeUnit.SECONDS, logMessageTemplate,
                                     message.from(), key.getToken(), command.metadata().keyspace,  command.metadata().name);

                if (outOfRangeTokenRejection)
                    // no need to respond, just drop the request
                    return;
            }
        }

        validateTransientStatus(message);

        long timeout = message.expiresAtNanos() - message.createdAtNanos();
        command.setMonitoringTime(message.createdAtNanos(), message.isCrossNode(), timeout, DatabaseDescriptor.getSlowQueryTimeout(NANOSECONDS));

        ReadResponse response;
        try (ReadExecutionController controller = command.executionController(message.trackRepairedData());
             UnfilteredPartitionIterator iterator = command.executeLocally(controller))
        {
            response = command.createResponse(iterator, controller.getRepairedDataInfo());
        }

        if (!command.complete())
        {
            Tracing.trace("Discarding partial response to {} (timed out)", message.from());
            MessagingService.instance().metrics.recordDroppedMessage(message, message.elapsedSinceCreated(NANOSECONDS), NANOSECONDS);
            return;
        }

        Tracing.trace("Enqueuing response to {}", message.from());
        Message reply = message.responseWith(response);
        MessagingService.instance().send(reply, message.from());
    }

    private void validateTransientStatus(Message message)
    {
        ReadCommand command = message.payload;
        Token token;

        if (command instanceof SinglePartitionReadCommand)
            token = ((SinglePartitionReadCommand) command).partitionKey().getToken();
        else
            token = ((PartitionRangeReadCommand) command).dataRange().keyRange().right.getToken();

        Replica replica = Keyspace.open(command.metadata().keyspace)
                                  .getReplicationStrategy()
                                  .getLocalReplicaFor(token);

        if (replica == null)
        {
            logger.warn("Received a read request from {} for a range that is not owned by the current replica {}.",
                        message.from(),
                        command);
            return;
        }

        if (!command.acceptsTransient() && replica.isTransient())
        {
            MessagingService.instance().metrics.recordDroppedMessage(message, message.elapsedSinceCreated(NANOSECONDS), NANOSECONDS);
            throw new InvalidRequestException(String.format("Attempted to serve %s data request from %s node in %s",
                                                            command.acceptsTransient() ? "transient" : "full",
                                                            replica.isTransient() ? "transient" : "full",
                                                            this));
        }
    }

    private boolean isOutOfRangeRead(String keyspace, DecoratedKey key)
    {
        try
        {
            return Keyspace.open(keyspace)
                           .getReplicationStrategy()
                           .getNaturalReplicas(key)
                           .selfIfPresent() == null;
        }
        catch (Throwable tr)
        {
            NoSpamLogger.log(logger, NoSpamLogger.Level.WARN, 1, TimeUnit.SECONDS, exceptionMessageTemplate, keyspace, key.getKey(), tr);
            return false;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy