Search in sources :

Example 11 with AuthorizeRequest

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

the class GetAll70 method fillAndSendGetAllResponseChunks.

private void fillAndSendGetAllResponseChunks(Region region, String regionName, Object[] keys, ServerConnection servConn, boolean requestSerializedValues) throws IOException {
    // Interpret null keys object as a request to get all key,value entry pairs
    // of the region; otherwise iterate each key and perform the get behavior.
    Iterator allKeysIter;
    int numKeys;
    if (keys != null) {
        allKeysIter = null;
        numKeys = keys.length;
    } else {
        Set allKeys = region.keySet();
        allKeysIter = allKeys.iterator();
        numKeys = allKeys.size();
    }
    // Shouldn't it be 'keys != null' below?
    // The answer is no.
    // Note that the current implementation of client/server getAll the "keys" will always be
    // non-null.
    // The server callects and returns the values in the same order as the keys it received.
    // So the server does not need to send the keys back to the client.
    // When the client receives the server's "values" it calls setKeys using the key list the client
    // already has.
    // So the only reason we would tell the VersionedObjectList that it needs to track keys is if we
    // are running
    // in the old mode (which may be impossible since we only used that mode pre 7.0) in which the
    // client told us
    // to get and return all the keys and values. I think this was used for register interest.
    VersionedObjectList values = new VersionedObjectList(MAXIMUM_CHUNK_SIZE, keys == null, region.getAttributes().getConcurrencyChecksEnabled(), requestSerializedValues);
    try {
        AuthorizeRequest authzRequest = servConn.getAuthzRequest();
        AuthorizeRequestPP postAuthzRequest = servConn.getPostAuthzRequest();
        Get70 request = (Get70) Get70.getCommand();
        final boolean isDebugEnabled = logger.isDebugEnabled();
        for (int i = 0; i < numKeys; i++) {
            // Send the intermediate chunk if necessary
            if (values.size() == MAXIMUM_CHUNK_SIZE) {
                // Send the chunk and clear the list
                values.setKeys(null);
                sendGetAllResponseChunk(region, values, false, servConn);
                values.clear();
            }
            Object key;
            boolean keyNotPresent = false;
            if (keys != null) {
                key = keys[i];
            } else {
                key = allKeysIter.next();
            }
            if (isDebugEnabled) {
                logger.debug("{}: Getting value for key={}", servConn.getName(), key);
            }
            // Determine if the user authorized to get this key
            GetOperationContext getContext = null;
            if (authzRequest != null) {
                try {
                    getContext = authzRequest.getAuthorize(regionName, key, null);
                    if (isDebugEnabled) {
                        logger.debug("{}: Passed GET pre-authorization for key={}", servConn.getName(), key);
                    }
                } catch (NotAuthorizedException ex) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                    values.addExceptionPart(key, ex);
                    continue;
                }
            }
            try {
                this.securityService.authorizeRegionRead(regionName, key.toString());
            } catch (NotAuthorizedException ex) {
                logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                values.addExceptionPart(key, ex);
                continue;
            }
            // Get the value and update the statistics. Do not deserialize
            // the value if it is a byte[].
            // Getting a value in serialized form is pretty nasty. I split this out
            // so the logic can be re-used by the CacheClientProxy.
            Get70.Entry entry = request.getEntry(region, key, null, servConn);
            @Retained final Object originalData = entry.value;
            Object data = originalData;
            if (logger.isDebugEnabled()) {
                logger.debug("retrieved key={} {}", key, entry);
            }
            boolean addedToValues = false;
            try {
                boolean isObject = entry.isObject;
                VersionTag versionTag = entry.versionTag;
                keyNotPresent = entry.keyNotPresent;
                if (postAuthzRequest != null) {
                    try {
                        getContext = postAuthzRequest.getAuthorize(regionName, key, data, isObject, getContext);
                        GetOperationContextImpl gci = (GetOperationContextImpl) getContext;
                        Object newData = gci.getRawValue();
                        if (newData != data) {
                            // user changed the value
                            isObject = getContext.isObject();
                            data = newData;
                        }
                    } catch (NotAuthorizedException ex) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                        values.addExceptionPart(key, ex);
                        continue;
                    } finally {
                        if (getContext != null) {
                            ((GetOperationContextImpl) getContext).release();
                        }
                    }
                }
                data = this.securityService.postProcess(regionName, key, data, entry.isObject);
                // Add the entry to the list that will be returned to the client
                if (keyNotPresent) {
                    values.addObjectPartForAbsentKey(key, data, versionTag);
                    addedToValues = true;
                } else {
                    values.addObjectPart(key, data, isObject, versionTag);
                    addedToValues = true;
                }
            } finally {
                if (!addedToValues || data != originalData) {
                    OffHeapHelper.release(originalData);
                }
            }
        }
        // Send the last chunk even if the list is of zero size.
        if (Version.GFE_701.compareTo(servConn.getClientVersion()) <= 0) {
            // 7.0.1 and later clients do not expect the keys in the response
            values.setKeys(null);
        }
        sendGetAllResponseChunk(region, values, true, servConn);
        servConn.setAsTrue(RESPONDED);
    } finally {
        values.release();
    }
}
Also used : Set(java.util.Set) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) AuthorizeRequestPP(org.apache.geode.internal.security.AuthorizeRequestPP) VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) GetOperationContextImpl(org.apache.geode.cache.operations.internal.GetOperationContextImpl) GetOperationContext(org.apache.geode.cache.operations.GetOperationContext) Retained(org.apache.geode.internal.offheap.annotations.Retained) Iterator(java.util.Iterator) VersionTag(org.apache.geode.internal.cache.versions.VersionTag)

Example 12 with AuthorizeRequest

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

the class GetAllWithCallback method fillAndSendGetAllResponseChunks.

private void fillAndSendGetAllResponseChunks(Region region, String regionName, Object[] keys, ServerConnection servConn, Object callback) throws IOException {
    assert keys != null;
    int numKeys = keys.length;
    VersionedObjectList values = new VersionedObjectList(MAXIMUM_CHUNK_SIZE, false, region.getAttributes().getConcurrencyChecksEnabled(), false);
    try {
        AuthorizeRequest authzRequest = servConn.getAuthzRequest();
        AuthorizeRequestPP postAuthzRequest = servConn.getPostAuthzRequest();
        Get70 request = (Get70) Get70.getCommand();
        for (int i = 0; i < numKeys; i++) {
            // Send the intermediate chunk if necessary
            if (values.size() == MAXIMUM_CHUNK_SIZE) {
                // Send the chunk and clear the list
                sendGetAllResponseChunk(region, values, false, servConn);
                values.clear();
            }
            Object key;
            boolean keyNotPresent = false;
            key = keys[i];
            if (logger.isDebugEnabled()) {
                logger.debug("{}: Getting value for key={}", servConn.getName(), key);
            }
            // Determine if the user authorized to get this key
            GetOperationContext getContext = null;
            if (authzRequest != null) {
                try {
                    getContext = authzRequest.getAuthorize(regionName, key, callback);
                    if (logger.isDebugEnabled()) {
                        logger.debug("{}: Passed GET pre-authorization for key={}", servConn.getName(), key);
                    }
                } catch (NotAuthorizedException ex) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                    values.addExceptionPart(key, ex);
                    continue;
                }
            }
            try {
                this.securityService.authorizeRegionRead(regionName, key.toString());
            } catch (NotAuthorizedException ex) {
                logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                values.addExceptionPart(key, ex);
                continue;
            }
            // Get the value and update the statistics. Do not deserialize
            // the value if it is a byte[].
            // Getting a value in serialized form is pretty nasty. I split this out
            // so the logic can be re-used by the CacheClientProxy.
            Get70.Entry entry = request.getEntry(region, key, callback, servConn);
            @Retained final Object originalData = entry.value;
            Object data = originalData;
            if (logger.isDebugEnabled()) {
                logger.debug("retrieved key={} {}", key, entry);
            }
            boolean addedToValues = false;
            try {
                boolean isObject = entry.isObject;
                VersionTag versionTag = entry.versionTag;
                keyNotPresent = entry.keyNotPresent;
                if (postAuthzRequest != null) {
                    try {
                        getContext = postAuthzRequest.getAuthorize(regionName, key, data, isObject, getContext);
                        GetOperationContextImpl gci = (GetOperationContextImpl) getContext;
                        Object newData = gci.getRawValue();
                        if (newData != data) {
                            // user changed the value
                            isObject = getContext.isObject();
                            data = newData;
                        }
                    } catch (NotAuthorizedException ex) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                        values.addExceptionPart(key, ex);
                        continue;
                    } finally {
                        if (getContext != null) {
                            ((GetOperationContextImpl) getContext).release();
                        }
                    }
                }
                // Add the entry to the list that will be returned to the client
                if (keyNotPresent) {
                    values.addObjectPartForAbsentKey(key, data, versionTag);
                    addedToValues = true;
                } else {
                    values.addObjectPart(key, data, isObject, versionTag);
                    addedToValues = true;
                }
            } finally {
                if (!addedToValues || data != originalData) {
                    OffHeapHelper.release(originalData);
                }
            }
        }
        // Send the last chunk even if the list is of zero size.
        sendGetAllResponseChunk(region, values, true, servConn);
        servConn.setAsTrue(RESPONDED);
    } finally {
        values.release();
    }
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) AuthorizeRequestPP(org.apache.geode.internal.security.AuthorizeRequestPP) VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) GetOperationContextImpl(org.apache.geode.cache.operations.internal.GetOperationContextImpl) GetOperationContext(org.apache.geode.cache.operations.GetOperationContext) Retained(org.apache.geode.internal.offheap.annotations.Retained) VersionTag(org.apache.geode.internal.cache.versions.VersionTag)

Example 13 with AuthorizeRequest

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

the class ExecuteRegionFunction61 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection servConn, long start) throws IOException {
    String regionName = null;
    Object function = null;
    Object args = null;
    MemberMappedArgument memberMappedArg = null;
    byte isReExecute = 0;
    Set filter = null;
    byte hasResult = 0;
    int removedNodesSize = 0;
    Set removedNodesSet = null;
    int filterSize = 0, partNumber = 0;
    CachedRegionHelper crHelper = servConn.getCachedRegionHelper();
    try {
        hasResult = clientMessage.getPart(0).getSerializedForm()[0];
        if (hasResult == 1) {
            servConn.setAsTrue(REQUIRES_RESPONSE);
            servConn.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
        }
        regionName = clientMessage.getPart(1).getString();
        function = clientMessage.getPart(2).getStringOrObject();
        args = clientMessage.getPart(3).getObject();
        Part part = clientMessage.getPart(4);
        if (part != null) {
            Object obj = part.getObject();
            if (obj instanceof MemberMappedArgument) {
                memberMappedArg = (MemberMappedArgument) obj;
            }
        }
        isReExecute = clientMessage.getPart(5).getSerializedForm()[0];
        filterSize = clientMessage.getPart(6).getInt();
        if (filterSize != 0) {
            filter = new HashSet();
            partNumber = 7;
            for (int i = 0; i < filterSize; i++) {
                filter.add(clientMessage.getPart(partNumber + i).getStringOrObject());
            }
        }
        partNumber = 7 + filterSize;
        removedNodesSize = clientMessage.getPart(partNumber).getInt();
        if (removedNodesSize != 0) {
            removedNodesSet = new HashSet();
            partNumber = partNumber + 1;
            for (int i = 0; i < removedNodesSize; i++) {
                removedNodesSet.add(clientMessage.getPart(partNumber + i).getStringOrObject());
            }
        }
    } catch (ClassNotFoundException exception) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception);
        if (hasResult == 1) {
            writeChunkedException(clientMessage, exception, servConn);
            servConn.setAsTrue(RESPONDED);
            return;
        }
    }
    if (function == null || regionName == null) {
        String message = null;
        if (function == null) {
            message = LocalizedStrings.ExecuteRegionFunction_THE_INPUT_0_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL.toLocalizedString("function");
        }
        if (regionName == null) {
            message = LocalizedStrings.ExecuteRegionFunction_THE_INPUT_0_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL.toLocalizedString("region");
        }
        logger.warn("{}: {}", servConn.getName(), message);
        sendError(hasResult, clientMessage, message, servConn);
        return;
    } else {
        Region region = crHelper.getRegion(regionName);
        if (region == null) {
            String message = LocalizedStrings.ExecuteRegionFunction_THE_REGION_NAMED_0_WAS_NOT_FOUND_DURING_EXECUTE_FUNCTION_REQUEST.toLocalizedString(regionName);
            logger.warn("{}: {}", servConn.getName(), message);
            sendError(hasResult, clientMessage, message, servConn);
            return;
        }
        HandShake handShake = (HandShake) servConn.getHandshake();
        int earlierClientReadTimeout = handShake.getClientReadTimeout();
        handShake.setClientReadTimeout(0);
        ServerToClientFunctionResultSender resultSender = null;
        Function functionObject = null;
        try {
            if (function instanceof String) {
                functionObject = FunctionService.getFunction((String) function);
                if (functionObject == null) {
                    String message = LocalizedStrings.ExecuteRegionFunction_THE_FUNCTION_0_HAS_NOT_BEEN_REGISTERED.toLocalizedString(function);
                    logger.warn("{}: {}", servConn.getName(), message);
                    sendError(hasResult, clientMessage, message, servConn);
                    return;
                }
            } else {
                functionObject = (Function) function;
            }
            // check if the caller is authorized to do this operation on server
            AuthorizeRequest authzRequest = servConn.getAuthzRequest();
            final String functionName = functionObject.getId();
            final String regionPath = region.getFullPath();
            ExecuteFunctionOperationContext executeContext = null;
            if (authzRequest != null) {
                executeContext = authzRequest.executeFunctionAuthorize(functionName, regionPath, filter, args, functionObject.optimizeForWrite());
            }
            // Construct execution
            AbstractExecution execution = (AbstractExecution) FunctionService.onRegion(region);
            ChunkedMessage m = servConn.getFunctionResponseMessage();
            m.setTransactionId(clientMessage.getTransactionId());
            resultSender = new ServerToClientFunctionResultSender(m, MessageType.EXECUTE_REGION_FUNCTION_RESULT, servConn, functionObject, executeContext);
            if (execution instanceof PartitionedRegionFunctionExecutor) {
                execution = new PartitionedRegionFunctionExecutor((PartitionedRegion) region, filter, args, memberMappedArg, resultSender, removedNodesSet, false);
            } else {
                execution = new DistributedRegionFunctionExecutor((DistributedRegion) region, filter, args, memberMappedArg, resultSender);
            }
            if (isReExecute == 1) {
                execution.setIsReExecute();
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Executing Function: {} on Server: {} with Execution: {}", functionObject.getId(), servConn, execution);
            }
            if (hasResult == 1) {
                if (function instanceof String) {
                    execution.execute((String) function).getResult();
                } else {
                    execution.execute(functionObject).getResult();
                }
            } else {
                if (function instanceof String) {
                    execution.execute((String) function);
                } else {
                    execution.execute(functionObject);
                }
            }
        } catch (IOException ioe) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioe);
            final String message = LocalizedStrings.ExecuteRegionFunction_SERVER_COULD_NOT_SEND_THE_REPLY.toLocalizedString();
            sendException(hasResult, clientMessage, message, servConn, ioe);
        } catch (FunctionException fe) {
            String message = fe.getMessage();
            if (fe.getCause() instanceof FunctionInvocationTargetException) {
                if (fe.getCause() instanceof InternalFunctionInvocationTargetException) {
                    // 4> in case of HA member departed
                    if (logger.isDebugEnabled()) {
                        logger.debug(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, new Object[] { function }), fe);
                    }
                } else if (functionObject.isHA()) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function + " :" + message));
                } else {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), fe);
                }
                resultSender.setException(fe);
            } else {
                logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), fe);
                sendException(hasResult, clientMessage, message, servConn, fe);
            }
        } catch (Exception e) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e);
            String message = e.getMessage();
            sendException(hasResult, clientMessage, message, servConn, e);
        } finally {
            handShake.setClientReadTimeout(earlierClientReadTimeout);
        }
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) Function(org.apache.geode.cache.execute.Function) HandShake(org.apache.geode.internal.cache.tier.sockets.HandShake) MemberMappedArgument(org.apache.geode.internal.cache.execute.MemberMappedArgument) DistributedRegion(org.apache.geode.internal.cache.DistributedRegion) HashSet(java.util.HashSet) AbstractExecution(org.apache.geode.internal.cache.execute.AbstractExecution) PartitionedRegionFunctionExecutor(org.apache.geode.internal.cache.execute.PartitionedRegionFunctionExecutor) ExecuteFunctionOperationContext(org.apache.geode.cache.operations.ExecuteFunctionOperationContext) FunctionException(org.apache.geode.cache.execute.FunctionException) IOException(java.io.IOException) DistributedRegionFunctionExecutor(org.apache.geode.internal.cache.execute.DistributedRegionFunctionExecutor) FunctionInvocationTargetException(org.apache.geode.cache.execute.FunctionInvocationTargetException) FunctionException(org.apache.geode.cache.execute.FunctionException) IOException(java.io.IOException) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) Part(org.apache.geode.internal.cache.tier.sockets.Part) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) FunctionInvocationTargetException(org.apache.geode.cache.execute.FunctionInvocationTargetException) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) DistributedRegion(org.apache.geode.internal.cache.DistributedRegion) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) ServerToClientFunctionResultSender(org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender) ChunkedMessage(org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)

Example 14 with AuthorizeRequest

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

the class ClearRegion method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, InterruptedException {
    Part regionNamePart = null, callbackArgPart = null;
    String regionName = null;
    Object callbackArg = null;
    Part eventPart = null;
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadClearRegionRequestTime(start - oldStart);
    }
    // Retrieve the data from the message parts
    regionNamePart = clientMessage.getPart(0);
    eventPart = clientMessage.getPart(1);
    // callbackArgPart = null; (redundant assignment)
    if (clientMessage.getNumberOfParts() > 2) {
        callbackArgPart = clientMessage.getPart(2);
        try {
            callbackArg = callbackArgPart.getObject();
        } catch (Exception e) {
            writeException(clientMessage, e, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    regionName = regionNamePart.getString();
    if (logger.isDebugEnabled()) {
        logger.debug(serverConnection.getName() + ": Received clear region request (" + clientMessage.getPayloadLength() + " bytes) from " + serverConnection.getSocketString() + " for region " + regionName);
    }
    // Process the clear region request
    if (regionName == null) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ClearRegion_0_THE_INPUT_REGION_NAME_FOR_THE_CLEAR_REGION_REQUEST_IS_NULL, serverConnection.getName()));
        String errMessage = LocalizedStrings.ClearRegion_THE_INPUT_REGION_NAME_FOR_THE_CLEAR_REGION_REQUEST_IS_NULL.toLocalizedString();
        writeErrorResponse(clientMessage, MessageType.CLEAR_REGION_DATA_ERROR, errMessage, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
    if (region == null) {
        String reason = LocalizedStrings.ClearRegion_WAS_NOT_FOUND_DURING_CLEAR_REGION_REGUEST.toLocalizedString();
        writeRegionDestroyedEx(clientMessage, regionName, reason, 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 {
        // Clear the region
        this.securityService.authorizeRegionWrite(regionName);
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            RegionClearOperationContext clearContext = authzRequest.clearAuthorize(regionName, callbackArg);
            callbackArg = clearContext.getCallbackArg();
        }
        region.basicBridgeClear(callbackArg, serverConnection.getProxyID(), true, /* boolean from cache Client */
        eventId);
    } catch (Exception e) {
        // If an interrupted exception is thrown , rethrow it
        checkForInterrupt(serverConnection, e);
        // If an exception occurs during the clear, preserve the connection
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    // Update the statistics and write the reply
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessClearRegionTime(start - oldStart);
    }
    writeReply(clientMessage, serverConnection);
    serverConnection.setAsTrue(RESPONDED);
    if (logger.isDebugEnabled()) {
        logger.debug(serverConnection.getName() + ": Sent clear region response for region " + regionName);
    }
    stats.incWriteClearRegionResponseTime(DistributionStats.getStatTime() - start);
}
Also used : CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) Part(org.apache.geode.internal.cache.tier.sockets.Part) EventID(org.apache.geode.internal.cache.EventID) LocalRegion(org.apache.geode.internal.cache.LocalRegion) RegionClearOperationContext(org.apache.geode.cache.operations.RegionClearOperationContext) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException)

Example 15 with AuthorizeRequest

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

the class ContainsKey66 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException {
    Part regionNamePart = null, keyPart = null;
    String regionName = null;
    Object key = null;
    ContainsKeyOp.MODE mode;
    CacheServerStats stats = serverConnection.getCacheServerStats();
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadContainsKeyRequestTime(start - oldStart);
    }
    // Retrieve the data from the message parts
    regionNamePart = clientMessage.getPart(0);
    keyPart = clientMessage.getPart(1);
    mode = ContainsKeyOp.MODE.values()[(clientMessage.getPart(2).getInt())];
    regionName = regionNamePart.getString();
    try {
        key = keyPart.getStringOrObject();
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Received containsKey request ({} bytes) from {} for region {} key {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName, key);
    }
    // Process the containsKey request
    if (key == null || regionName == null) {
        String errMessage = "";
        if (key == null) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.ContainsKey_0_THE_INPUT_KEY_FOR_THE_CONTAINSKEY_REQUEST_IS_NULL, serverConnection.getName()));
            errMessage = LocalizedStrings.ContainsKey_THE_INPUT_KEY_FOR_THE_CONTAINSKEY_REQUEST_IS_NULL.toLocalizedString();
        }
        if (regionName == null) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.ContainsKey_0_THE_INPUT_REGION_NAME_FOR_THE_CONTAINSKEY_REQUEST_IS_NULL, serverConnection.getName()));
            errMessage = LocalizedStrings.ContainsKey_THE_INPUT_REGION_NAME_FOR_THE_CONTAINSKEY_REQUEST_IS_NULL.toLocalizedString();
        }
        writeErrorResponse(clientMessage, MessageType.CONTAINS_KEY_DATA_ERROR, errMessage, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        String reason = LocalizedStrings.ContainsKey_WAS_NOT_FOUND_DURING_CONTAINSKEY_REQUEST.toLocalizedString();
        writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    try {
        this.securityService.authorizeRegionRead(regionName, key.toString());
    } catch (NotAuthorizedException ex) {
        writeException(clientMessage, ex, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
    if (authzRequest != null) {
        try {
            authzRequest.containsKeyAuthorize(regionName, key);
        } catch (NotAuthorizedException ex) {
            writeException(clientMessage, ex, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    // Execute the containsKey
    boolean containsKey;
    switch(mode) {
        case KEY:
            containsKey = region.containsKey(key);
            break;
        case VALUE:
            containsKey = region.containsValue(key);
            break;
        case VALUE_FOR_KEY:
            containsKey = region.containsValueForKey(key);
            break;
        default:
            containsKey = false;
            break;
    }
    // Update the statistics and write the reply
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessContainsKeyTime(start - oldStart);
    }
    writeContainsKeyResponse(containsKey, clientMessage, serverConnection);
    serverConnection.setAsTrue(RESPONDED);
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Sent containsKey response for region {} key {}", serverConnection.getName(), regionName, key);
    }
    stats.incWriteContainsKeyResponseTime(DistributionStats.getStatTime() - start);
}
Also used : ContainsKeyOp(org.apache.geode.cache.client.internal.ContainsKeyOp) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) Part(org.apache.geode.internal.cache.tier.sockets.Part) LocalRegion(org.apache.geode.internal.cache.LocalRegion) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) IOException(java.io.IOException) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException)

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