Search in sources :

Example 21 with AuthorizeRequest

use of org.apache.geode.internal.security.AuthorizeRequest in project geode by apache.

the class Put method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, InterruptedException {
    Part regionNamePart = null, keyPart = null, valuePart = null, callbackArgPart = null;
    String regionName = null;
    Object callbackArg = null, key = null;
    Part eventPart = null;
    String errMessage = "";
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    // requiresResponse = true;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadPutRequestTime(start - oldStart);
    }
    // Retrieve the data from the message parts
    regionNamePart = clientMessage.getPart(0);
    keyPart = clientMessage.getPart(1);
    valuePart = clientMessage.getPart(2);
    eventPart = clientMessage.getPart(3);
    // callbackArgPart = null; (redundant assignment)
    if (clientMessage.getNumberOfParts() > 4) {
        callbackArgPart = clientMessage.getPart(4);
        try {
            callbackArg = callbackArgPart.getObject();
        } catch (Exception e) {
            writeException(clientMessage, e, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    regionName = regionNamePart.getString();
    try {
        key = keyPart.getStringOrObject();
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (logger.isTraceEnabled()) {
        logger.trace("{}: Received put request ({} bytes) from {} for region {} key {} value {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName, key, valuePart);
    }
    // Process the put request
    if (key == null || regionName == null) {
        if (key == null) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.Put_0_THE_INPUT_KEY_FOR_THE_PUT_REQUEST_IS_NULL, serverConnection.getName()));
            errMessage = LocalizedStrings.Put_THE_INPUT_KEY_FOR_THE_PUT_REQUEST_IS_NULL.toLocalizedString();
        }
        if (regionName == null) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.Put_0_THE_INPUT_REGION_NAME_FOR_THE_PUT_REQUEST_IS_NULL, serverConnection.getName()));
            errMessage = LocalizedStrings.Put_THE_INPUT_REGION_NAME_FOR_THE_PUT_REQUEST_IS_NULL.toLocalizedString();
        }
        writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        String reason = LocalizedStrings.Put_REGION_WAS_NOT_FOUND_DURING_PUT_REQUEST.toLocalizedString();
        writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (valuePart.isNull() && region.containsKey(key)) {
        // Invalid to 'put' a null value in an existing key
        logger.info(LocalizedMessage.create(LocalizedStrings.Put_0_ATTEMPTED_TO_PUT_A_NULL_VALUE_FOR_EXISTING_KEY_1, new Object[] { serverConnection.getName(), key }));
        errMessage = LocalizedStrings.Put_ATTEMPTED_TO_PUT_A_NULL_VALUE_FOR_EXISTING_KEY_0.toLocalizedString();
        writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
    long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
    long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
    EventID eventId = new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId);
    try {
        byte[] value = valuePart.getSerializedForm();
        boolean isObject = valuePart.isObject();
        this.securityService.authorizeRegionWrite(regionName, key.toString());
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
                authzRequest.createRegionAuthorize((String) key);
            } else // Allow PUT operations on meta regions (bug #38961)
            if (!region.isUsedForMetaRegion()) {
                PutOperationContext putContext = authzRequest.putAuthorize(regionName, key, value, isObject, callbackArg);
                value = putContext.getSerializedValue();
                isObject = putContext.isObject();
                callbackArg = putContext.getCallbackArg();
            }
        }
        // If the value is 1 byte and the byte represents null,
        // attempt to create the entry. This test needs to be
        // moved to DataSerializer or DataSerializer.NULL needs
        // to be publicly accessible.
        boolean result = false;
        if (value == null) {
            // Create the null entry. Since the value is null, the value of the
            // isObject
            // the true after null doesn't matter and is not used.
            result = region.basicBridgeCreate(key, null, true, callbackArg, serverConnection.getProxyID(), true, new EventIDHolder(eventId), false);
        } else {
            // Put the entry
            result = region.basicBridgePut(key, value, null, isObject, callbackArg, serverConnection.getProxyID(), true, new EventIDHolder(eventId));
        }
        if (result) {
            serverConnection.setModificationInfo(true, regionName, key);
        } else {
            StringId message = LocalizedStrings.PUT_0_FAILED_TO_PUT_ENTRY_FOR_REGION_1_KEY_2_VALUE_3;
            Object[] messageArgs = new Object[] { serverConnection.getName(), regionName, key, valuePart };
            String s = message.toLocalizedString(messageArgs);
            logger.info(s);
            throw new Exception(s);
        }
    } catch (RegionDestroyedException rde) {
        writeException(clientMessage, rde, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (ResourceException re) {
        writeException(clientMessage, re, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (Exception ce) {
        // If an interrupted exception is thrown , rethrow it
        checkForInterrupt(serverConnection, ce);
        // If an exception occurs during the put, preserve the connection
        writeException(clientMessage, ce, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        if (ce instanceof GemFireSecurityException) {
            // logged by the security logger
            if (logger.isDebugEnabled()) {
                logger.debug("{}: Unexpected Security exception", serverConnection.getName(), ce);
            }
        } else {
            logger.warn(LocalizedMessage.create(LocalizedStrings.PUT_0_UNEXPECTED_EXCEPTION, serverConnection.getName()), ce);
        }
        return;
    } finally {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessPutTime(start - oldStart);
    }
    // Increment statistics and write the reply
    writeReply(clientMessage, serverConnection);
    serverConnection.setAsTrue(RESPONDED);
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Sent put response back to {} for region {} key {} value {}", serverConnection.getName(), serverConnection.getSocketString(), regionName, key, valuePart);
    }
    stats.incWritePutResponseTime(DistributionStats.getStatTime() - start);
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) EventIDHolder(org.apache.geode.internal.cache.EventIDHolder) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) LocalRegion(org.apache.geode.internal.cache.LocalRegion) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) ResourceException(org.apache.geode.cache.ResourceException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) StringId(org.apache.geode.i18n.StringId) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) Part(org.apache.geode.internal.cache.tier.sockets.Part) EventID(org.apache.geode.internal.cache.EventID) ResourceException(org.apache.geode.cache.ResourceException) PutOperationContext(org.apache.geode.cache.operations.PutOperationContext)

Example 22 with AuthorizeRequest

use of org.apache.geode.internal.security.AuthorizeRequest in project geode by apache.

the class Put61 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long p_start) throws IOException, InterruptedException {
    long start = p_start;
    Part regionNamePart = null, keyPart = null, valuePart = null, callbackArgPart = null;
    String regionName = null;
    Object callbackArg = null, key = null;
    Part eventPart = null;
    StringBuffer errMessage = new StringBuffer();
    boolean isDelta = false;
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    // requiresResponse = true;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadPutRequestTime(start - oldStart);
    }
    // Retrieve the data from the message parts
    regionNamePart = clientMessage.getPart(0);
    keyPart = clientMessage.getPart(1);
    try {
        isDelta = (Boolean) clientMessage.getPart(2).getObject();
    } catch (Exception e) {
        writeException(clientMessage, MessageType.PUT_DELTA_ERROR, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        // CachePerfStats not available here.
        return;
    }
    valuePart = clientMessage.getPart(3);
    eventPart = clientMessage.getPart(4);
    if (clientMessage.getNumberOfParts() > 5) {
        callbackArgPart = clientMessage.getPart(5);
        try {
            callbackArg = callbackArgPart.getObject();
        } catch (Exception e) {
            writeException(clientMessage, e, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    regionName = regionNamePart.getString();
    try {
        key = keyPart.getStringOrObject();
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    final boolean isDebugEnabled = logger.isDebugEnabled();
    if (isDebugEnabled) {
        logger.debug("{}: Received 6.1{}put request ({} bytes) from {} for region {} key {}", serverConnection.getName(), (isDelta ? " delta " : " "), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName, key);
    }
    // Process the put request
    if (key == null || regionName == null) {
        if (key == null) {
            String putMsg = " The input key for the 6.1 put request is null";
            if (isDebugEnabled) {
                logger.debug("{}:{}", serverConnection.getName(), putMsg);
            }
            errMessage.append(putMsg);
        }
        if (regionName == null) {
            String putMsg = " The input region name for the 6.1 put request is null";
            if (isDebugEnabled) {
                logger.debug("{}:{}", serverConnection.getName(), putMsg);
            }
            errMessage.append(putMsg);
        }
        writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        String reason = " was not found during 6.1 put request";
        writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (valuePart.isNull() && region.containsKey(key)) {
        // Invalid to 'put' a null value in an existing key
        String putMsg = " Attempted to 6.1 put a null value for existing key " + key;
        if (isDebugEnabled) {
            logger.debug("{}:{}", serverConnection.getName(), putMsg);
        }
        errMessage.append(putMsg);
        writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    // try {
    // this.eventId = (EventID)eventPart.getObject();
    ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
    long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
    long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
    EventID eventId = new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId);
    try {
        Object value = null;
        if (!isDelta) {
            value = valuePart.getSerializedForm();
        }
        boolean isObject = valuePart.isObject();
        boolean isMetaRegion = region.isUsedForMetaRegion();
        clientMessage.setMetaRegion(isMetaRegion);
        this.securityService.authorizeRegionWrite(regionName, key.toString());
        AuthorizeRequest authzRequest = null;
        if (!isMetaRegion) {
            authzRequest = serverConnection.getAuthzRequest();
        }
        if (authzRequest != null) {
            if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
                authzRequest.createRegionAuthorize((String) key);
            } else // Allow PUT operations on meta regions (bug #38961)
            {
                PutOperationContext putContext = authzRequest.putAuthorize(regionName, key, value, isObject, callbackArg);
                value = putContext.getValue();
                isObject = putContext.isObject();
                callbackArg = putContext.getCallbackArg();
            }
        }
        // If the value is 1 byte and the byte represents null,
        // attempt to create the entry. This test needs to be
        // moved to DataSerializer or DataSerializer.NULL needs
        // to be publicly accessible.
        boolean result = false;
        if (value == null && !isDelta) {
            // Create the null entry. Since the value is null, the value of the
            // isObject
            // the true after null doesn't matter and is not used.
            result = region.basicBridgeCreate(key, null, true, callbackArg, serverConnection.getProxyID(), true, new EventIDHolder(eventId), false);
        } else {
            // Put the entry
            byte[] delta = null;
            if (isDelta) {
                delta = valuePart.getSerializedForm();
            }
            result = region.basicBridgePut(key, value, delta, isObject, callbackArg, serverConnection.getProxyID(), true, new EventIDHolder(eventId));
        }
        if (result) {
            serverConnection.setModificationInfo(true, regionName, key);
        } else {
            String message = serverConnection.getName() + ": Failed to 6.1 put entry for region " + regionName + " key " + key + " value " + valuePart;
            if (isDebugEnabled) {
                logger.debug(message);
            }
            throw new Exception(message);
        }
    } catch (RegionDestroyedException rde) {
        writeException(clientMessage, rde, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (ResourceException re) {
        writeException(clientMessage, re, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (InvalidDeltaException ide) {
        logger.info(LocalizedMessage.create(LocalizedStrings.UpdateOperation_ERROR_APPLYING_DELTA_FOR_KEY_0_OF_REGION_1, new Object[] { key, regionName }));
        writeException(clientMessage, MessageType.PUT_DELTA_ERROR, ide, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        region.getCachePerfStats().incDeltaFullValuesRequested();
        return;
    } catch (Exception ce) {
        // If an interrupted exception is thrown , rethrow it
        checkForInterrupt(serverConnection, ce);
        // If an exception occurs during the put, preserve the connection
        writeException(clientMessage, ce, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        if (ce instanceof GemFireSecurityException) {
            // logged by the security logger
            if (isDebugEnabled) {
                logger.debug("{}: Unexpected Security exception", serverConnection.getName(), ce);
            }
        } else if (isDebugEnabled) {
            logger.debug("{}: Unexpected Exception", serverConnection.getName(), ce);
        }
        return;
    } finally {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessPutTime(start - oldStart);
    }
    // Increment statistics and write the reply
    if (region instanceof PartitionedRegion) {
        PartitionedRegion pr = (PartitionedRegion) region;
        if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
            writeReplyWithRefreshMetadata(clientMessage, serverConnection, pr, pr.getNetworkHopType());
            pr.clearNetworkHopData();
        } else {
            writeReply(clientMessage, serverConnection);
        }
    } else {
        writeReply(clientMessage, serverConnection);
    }
    serverConnection.setAsTrue(RESPONDED);
    if (isDebugEnabled) {
        logger.debug("{}: Sent 6.1 put response back to {} for region {} key {} value {}", serverConnection.getName(), serverConnection.getSocketString(), regionName, key, valuePart);
    }
    stats.incWritePutResponseTime(DistributionStats.getStatTime() - start);
}
Also used : InvalidDeltaException(org.apache.geode.InvalidDeltaException) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) EventIDHolder(org.apache.geode.internal.cache.EventIDHolder) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) LocalRegion(org.apache.geode.internal.cache.LocalRegion) ByteBuffer(java.nio.ByteBuffer) InvalidDeltaException(org.apache.geode.InvalidDeltaException) IOException(java.io.IOException) ResourceException(org.apache.geode.cache.ResourceException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) Part(org.apache.geode.internal.cache.tier.sockets.Part) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) EventID(org.apache.geode.internal.cache.EventID) ResourceException(org.apache.geode.cache.ResourceException) PutOperationContext(org.apache.geode.cache.operations.PutOperationContext)

Example 23 with AuthorizeRequest

use of org.apache.geode.internal.security.AuthorizeRequest in project geode by apache.

the class Invalidate method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, InterruptedException {
    Part regionNamePart = null, keyPart = null, callbackArgPart = null;
    String regionName = null;
    Object callbackArg = null, key = null;
    Part eventPart = null;
    StringBuffer errMessage = new StringBuffer();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadInvalidateRequestTime(start - oldStart);
    }
    // Retrieve the data from the message parts
    regionNamePart = clientMessage.getPart(0);
    keyPart = clientMessage.getPart(1);
    eventPart = clientMessage.getPart(2);
    // callbackArgPart = null; (redundant assignment)
    if (clientMessage.getNumberOfParts() > 3) {
        callbackArgPart = clientMessage.getPart(3);
        try {
            callbackArg = callbackArgPart.getObject();
        } catch (Exception e) {
            writeException(clientMessage, e, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    regionName = regionNamePart.getString();
    try {
        key = keyPart.getStringOrObject();
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug(serverConnection.getName() + ": Received invalidate request (" + clientMessage.getPayloadLength() + " bytes) from " + serverConnection.getSocketString() + " for region " + regionName + " key " + key);
    }
    // Process the invalidate request
    if (key == null || regionName == null) {
        if (key == null) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.BaseCommand__THE_INPUT_KEY_FOR_THE_0_REQUEST_IS_NULL, "invalidate"));
            errMessage.append(LocalizedStrings.BaseCommand__THE_INPUT_KEY_FOR_THE_0_REQUEST_IS_NULL.toLocalizedString("invalidate"));
        }
        if (regionName == null) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.BaseCommand__THE_INPUT_REGION_NAME_FOR_THE_0_REQUEST_IS_NULL, "invalidate"));
            errMessage.append(LocalizedStrings.BaseCommand__THE_INPUT_REGION_NAME_FOR_THE_0_REQUEST_IS_NULL.toLocalizedString("invalidate"));
        }
        writeErrorResponse(clientMessage, MessageType.DESTROY_DATA_ERROR, errMessage.toString(), serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        String reason = LocalizedStrings.BaseCommand__0_WAS_NOT_FOUND_DURING_1_REQUEST.toLocalizedString(regionName, "invalidate");
        writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    // Invalidate the entry
    ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
    long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
    long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
    EventID eventId = new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId);
    Breadcrumbs.setEventId(eventId);
    VersionTag tag = null;
    try {
        // for integrated security
        this.securityService.authorizeRegionWrite(regionName, key.toString());
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            InvalidateOperationContext invalidateContext = authzRequest.invalidateAuthorize(regionName, key, callbackArg);
            callbackArg = invalidateContext.getCallbackArg();
        }
        EventIDHolder clientEvent = new EventIDHolder(eventId);
        // msg.isRetry might be set by v7.0 and later clients
        if (clientMessage.isRetry()) {
            // if (logger.isDebugEnabled()) {
            // logger.debug("DEBUG: encountered isRetry in Invalidate");
            // }
            clientEvent.setPossibleDuplicate(true);
            if (region.getAttributes().getConcurrencyChecksEnabled()) {
                // recover the version tag from other servers
                clientEvent.setRegion(region);
                if (!recoverVersionTagForRetriedOperation(clientEvent)) {
                    // no-one has seen this event
                    clientEvent.setPossibleDuplicate(false);
                }
            }
        }
        region.basicBridgeInvalidate(key, callbackArg, serverConnection.getProxyID(), true, clientEvent);
        tag = clientEvent.getVersionTag();
        serverConnection.setModificationInfo(true, regionName, key);
    } catch (EntryNotFoundException e) {
        // Don't send an exception back to the client if this
        // exception happens. Just log it and continue.
        logger.info(LocalizedMessage.create(LocalizedStrings.BaseCommand_DURING_0_NO_ENTRY_WAS_FOUND_FOR_KEY_1, new Object[] { "invalidate", key }));
    } catch (RegionDestroyedException rde) {
        writeException(clientMessage, rde, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (Exception e) {
        // If an interrupted exception is thrown , rethrow it
        checkForInterrupt(serverConnection, e);
        // If an exception occurs during the destroy, preserve the connection
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        if (e instanceof GemFireSecurityException) {
            // logged by the security logger
            if (logger.isDebugEnabled()) {
                logger.debug("{}: Unexpected Security exception", serverConnection.getName(), e);
            }
        } else {
            logger.warn(LocalizedMessage.create(LocalizedStrings.BaseCommand_0_UNEXPECTED_EXCEPTION, serverConnection.getName()), e);
        }
        return;
    }
    // Update the statistics and write the reply
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessInvalidateTime(start - oldStart);
    }
    if (region instanceof PartitionedRegion) {
        PartitionedRegion pr = (PartitionedRegion) region;
        if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
            writeReplyWithRefreshMetadata(clientMessage, serverConnection, pr, pr.getNetworkHopType(), tag);
            pr.clearNetworkHopData();
        } else {
            writeReply(clientMessage, serverConnection, tag);
        }
    } else {
        writeReply(clientMessage, serverConnection, tag);
    }
    serverConnection.setAsTrue(RESPONDED);
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Sent invalidate response for region {} key {}", serverConnection.getName(), regionName, key);
    }
    stats.incWriteInvalidateResponseTime(DistributionStats.getStatTime() - start);
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) EventIDHolder(org.apache.geode.internal.cache.EventIDHolder) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) LocalRegion(org.apache.geode.internal.cache.LocalRegion) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) InvalidateOperationContext(org.apache.geode.cache.operations.InvalidateOperationContext) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) Part(org.apache.geode.internal.cache.tier.sockets.Part) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) VersionTag(org.apache.geode.internal.cache.versions.VersionTag) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) EventID(org.apache.geode.internal.cache.EventID)

Example 24 with AuthorizeRequest

use of org.apache.geode.internal.security.AuthorizeRequest in project geode by apache.

the class KeySet method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, InterruptedException {
    Part regionNamePart = null;
    String regionName = null;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    serverConnection.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
    // Retrieve the region name from the message parts
    regionNamePart = clientMessage.getPart(0);
    regionName = regionNamePart.getString();
    ChunkedMessage chunkedResponseMsg = serverConnection.getChunkedResponseMessage();
    final boolean isDebugEnabled = logger.isDebugEnabled();
    if (isDebugEnabled) {
        logger.debug("{}: Received key set request ({} bytes) from {} for region {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName);
    }
    // Process the key set request
    if (regionName == null) {
        String message = null;
        // if (regionName == null) (can only be null)
        {
            message = LocalizedStrings.KeySet_0_THE_INPUT_REGION_NAME_FOR_THE_KEY_SET_REQUEST_IS_NULL.toLocalizedString(serverConnection.getName());
            logger.warn(LocalizedMessage.create(LocalizedStrings.KeySet_0_THE_INPUT_REGION_NAME_FOR_THE_KEY_SET_REQUEST_IS_NULL, serverConnection.getName()));
        }
        writeKeySetErrorResponse(clientMessage, MessageType.KEY_SET_DATA_ERROR, message, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        String reason = LocalizedStrings.KeySet__0_WAS_NOT_FOUND_DURING_KEY_SET_REQUEST.toLocalizedString(regionName);
        writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    try {
        this.securityService.authorizeRegionRead(regionName);
    } catch (NotAuthorizedException ex) {
        writeChunkedException(clientMessage, ex, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    KeySetOperationContext keySetContext = null;
    AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
    if (authzRequest != null) {
        try {
            keySetContext = authzRequest.keySetAuthorize(regionName);
        } catch (NotAuthorizedException ex) {
            writeChunkedException(clientMessage, ex, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    // Update the statistics and write the reply
    // bserverStats.incLong(processDestroyTimeId,
    // DistributionStats.getStatTime() - start);
    // start = DistributionStats.getStatTime();
    // Send header
    chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
    chunkedResponseMsg.setTransactionId(clientMessage.getTransactionId());
    chunkedResponseMsg.sendHeader();
    // Send chunk response
    try {
        fillAndSendKeySetResponseChunks(region, regionName, keySetContext, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
    } catch (Exception e) {
        // If an interrupted exception is thrown , rethrow it
        checkForInterrupt(serverConnection, e);
        // Otherwise, write an exception message and continue
        writeChunkedException(clientMessage, e, serverConnection, serverConnection.getChunkedResponseMessage());
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (isDebugEnabled) {
        // logger.fine(getName() + ": Sent chunk (1 of 1) of register interest
        // response (" + chunkedResponseMsg.getBufferLength() + " bytes) for
        // region " + regionName + " key " + key);
        logger.debug("{}: Sent key set response for the region {}", serverConnection.getName(), regionName);
    }
// bserverStats.incLong(writeDestroyResponseTimeId,
// DistributionStats.getStatTime() - start);
// bserverStats.incInt(destroyResponsesId, 1);
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) Part(org.apache.geode.internal.cache.tier.sockets.Part) KeySetOperationContext(org.apache.geode.cache.operations.KeySetOperationContext) LocalRegion(org.apache.geode.internal.cache.LocalRegion) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) ChunkedMessage(org.apache.geode.internal.cache.tier.sockets.ChunkedMessage) IOException(java.io.IOException) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException)

Example 25 with AuthorizeRequest

use of org.apache.geode.internal.security.AuthorizeRequest in project geode by apache.

the class UnregisterInterestList method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, ClassNotFoundException {
    Part regionNamePart = null, keyPart = null, numberOfKeysPart = null;
    String regionName = null;
    Object key = null;
    List keys = null;
    int numberOfKeys = 0, partNumber = 0;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    // bserverStats.incLong(readDestroyRequestTimeId,
    // DistributionStats.getStatTime() - start);
    // bserverStats.incInt(destroyRequestsId, 1);
    // start = DistributionStats.getStatTime();
    // Retrieve the data from the message parts
    regionNamePart = clientMessage.getPart(0);
    regionName = regionNamePart.getString();
    Part isClosingListPart = clientMessage.getPart(1);
    byte[] isClosingListPartBytes = (byte[]) isClosingListPart.getObject();
    boolean isClosingList = isClosingListPartBytes[0] == 0x01;
    boolean keepalive = false;
    try {
        Part keepalivePart = clientMessage.getPart(2);
        byte[] keepalivePartBytes = (byte[]) keepalivePart.getObject();
        keepalive = keepalivePartBytes[0] == 0x01;
    } catch (Exception e) {
        writeChunkedException(clientMessage, e, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    numberOfKeysPart = clientMessage.getPart(3);
    numberOfKeys = numberOfKeysPart.getInt();
    partNumber = 4;
    keys = new ArrayList();
    for (int i = 0; i < numberOfKeys; i++) {
        keyPart = clientMessage.getPart(partNumber + i);
        try {
            key = keyPart.getStringOrObject();
        } catch (Exception e) {
            writeException(clientMessage, e, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
        keys.add(key);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Received unregister interest request ({} bytes) from {} for the following {} keys in region {}: {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), numberOfKeys, regionName, keys);
    }
    // Process the unregister interest request
    if (keys.isEmpty() || regionName == null) {
        StringId errMessage = null;
        if (keys.isEmpty() && regionName == null) {
            errMessage = LocalizedStrings.UnRegisterInterestList_THE_INPUT_LIST_OF_KEYS_IS_EMPTY_AND_THE_INPUT_REGION_NAME_IS_NULL_FOR_THE_UNREGISTER_INTEREST_REQUEST;
        } else if (keys.isEmpty()) {
            errMessage = LocalizedStrings.UnRegisterInterestList_THE_INPUT_LIST_OF_KEYS_FOR_THE_UNREGISTER_INTEREST_REQUEST_IS_EMPTY;
        } else if (regionName == null) {
            errMessage = LocalizedStrings.UnRegisterInterest_THE_INPUT_REGION_NAME_FOR_THE_UNREGISTER_INTEREST_REQUEST_IS_NULL;
        }
        String s = errMessage.toLocalizedString();
        logger.warn("{}: {}", serverConnection.getName(), s);
        writeErrorResponse(clientMessage, MessageType.UNREGISTER_INTEREST_DATA_ERROR, s, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    try {
        this.securityService.authorizeRegionRead(regionName);
    } catch (NotAuthorizedException ex) {
        writeException(clientMessage, ex, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
    if (authzRequest != null) {
        if (!DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
            try {
                UnregisterInterestOperationContext unregisterContext = authzRequest.unregisterInterestListAuthorize(regionName, keys);
                keys = (List) unregisterContext.getKey();
            } catch (NotAuthorizedException ex) {
                writeException(clientMessage, ex, false, serverConnection);
                serverConnection.setAsTrue(RESPONDED);
                return;
            }
        }
    }
    // Yogesh : bug fix for 36457 :
    /*
     * Region destroy message from server to client results in client calling unregister to server
     * (an unnecessary callback). The unregister encounters an error because the region has been
     * destroyed on the server and hence falsely marks the server dead.
     */
    /*
     * Region region = crHelper.getRegion(regionName); if (region == null) {
     * logger.warning(this.name + ": Region named " + regionName + " was not found during register
     * interest list request"); writeErrorResponse(msg, MessageType.UNREGISTER_INTEREST_DATA_ERROR);
     * responded = true; } else {
     */
    // Register interest
    serverConnection.getAcceptor().getCacheClientNotifier().unregisterClientInterest(regionName, keys, isClosingList, serverConnection.getProxyID(), keepalive);
    // Update the statistics and write the reply
    // bserverStats.incLong(processDestroyTimeId,
    // DistributionStats.getStatTime() - start);
    // start = DistributionStats.getStatTime(); WHY ARE GETTING START AND NOT
    // USING IT?
    writeReply(clientMessage, serverConnection);
    serverConnection.setAsTrue(RESPONDED);
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Sent unregister interest response for the following {} keys in region {}: {}", serverConnection.getName(), numberOfKeys, regionName, keys);
    }
// bserverStats.incLong(writeDestroyResponseTimeId,
// DistributionStats.getStatTime() - start);
// bserverStats.incInt(destroyResponsesId, 1);
// }
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) ArrayList(java.util.ArrayList) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) IOException(java.io.IOException) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) StringId(org.apache.geode.i18n.StringId) Part(org.apache.geode.internal.cache.tier.sockets.Part) UnregisterInterestOperationContext(org.apache.geode.cache.operations.UnregisterInterestOperationContext) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

AuthorizeRequest (org.apache.geode.internal.security.AuthorizeRequest)48 IOException (java.io.IOException)40 Part (org.apache.geode.internal.cache.tier.sockets.Part)33 CachedRegionHelper (org.apache.geode.internal.cache.tier.CachedRegionHelper)26 LocalRegion (org.apache.geode.internal.cache.LocalRegion)23 CacheServerStats (org.apache.geode.internal.cache.tier.sockets.CacheServerStats)21 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)16 EventID (org.apache.geode.internal.cache.EventID)13 ByteBuffer (java.nio.ByteBuffer)12 ChunkedMessage (org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)12 NotAuthorizedException (org.apache.geode.security.NotAuthorizedException)12 Set (java.util.Set)11 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)11 StringId (org.apache.geode.i18n.StringId)11 Region (org.apache.geode.cache.Region)8 Function (org.apache.geode.cache.execute.Function)8 FunctionException (org.apache.geode.cache.execute.FunctionException)8 ExecuteFunctionOperationContext (org.apache.geode.cache.operations.ExecuteFunctionOperationContext)8 InternalFunctionInvocationTargetException (org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException)8 MemberMappedArgument (org.apache.geode.internal.cache.execute.MemberMappedArgument)8