Search in sources :

Example 6 with HeapMemoryMonitor

use of org.apache.geode.internal.cache.control.HeapMemoryMonitor in project geode by apache.

the class ExecuteFunction66 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection servConn, long start) throws IOException {
    Object function = null;
    Object args = null;
    MemberMappedArgument memberMappedArg = null;
    String[] groups = null;
    byte hasResult = 0;
    byte functionState = 0;
    boolean isReexecute = false;
    boolean allMembers = false;
    boolean ignoreFailedMembers = false;
    int functionTimeout = ConnectionImpl.DEFAULT_CLIENT_FUNCTION_TIMEOUT;
    try {
        byte[] bytes = clientMessage.getPart(0).getSerializedForm();
        functionState = bytes[0];
        if (bytes.length >= 5 && servConn.getClientVersion().ordinal() >= Version.GFE_8009.ordinal()) {
            functionTimeout = Part.decodeInt(bytes, 1);
        }
        if (functionState == AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE_REEXECUTE) {
            functionState = AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE;
            isReexecute = true;
        } else if (functionState == AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE_REEXECUTE) {
            functionState = AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE;
            isReexecute = true;
        }
        if (functionState != 1) {
            hasResult = (byte) ((functionState & 2) - 1);
        } else {
            hasResult = functionState;
        }
        if (hasResult == 1) {
            servConn.setAsTrue(REQUIRES_RESPONSE);
            servConn.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
        }
        function = clientMessage.getPart(1).getStringOrObject();
        args = clientMessage.getPart(2).getObject();
        Part part = clientMessage.getPart(3);
        if (part != null) {
            memberMappedArg = (MemberMappedArgument) part.getObject();
        }
        groups = getGroups(clientMessage);
        allMembers = getAllMembers(clientMessage);
        ignoreFailedMembers = getIgnoreFailedMembers(clientMessage);
    } catch (ClassNotFoundException exception) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception);
        if (hasResult == 1) {
            writeChunkedException(clientMessage, exception, servConn);
        } else {
            writeException(clientMessage, exception, false, servConn);
        }
        servConn.setAsTrue(RESPONDED);
        return;
    }
    if (function == null) {
        final String message = LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL.toLocalizedString();
        logger.warn(LocalizedMessage.create(LocalizedStrings.TWO_ARG_COLON, new Object[] { servConn.getName(), message }));
        sendError(hasResult, clientMessage, message, servConn);
        return;
    }
    // Execute function on the cache
    try {
        Function functionObject = null;
        if (function instanceof String) {
            functionObject = FunctionService.getFunction((String) function);
            if (functionObject == null) {
                final String message = LocalizedStrings.ExecuteFunction_FUNCTION_NAMED_0_IS_NOT_REGISTERED.toLocalizedString(function);
                logger.warn("{}: {}", servConn.getName(), message);
                sendError(hasResult, clientMessage, message, servConn);
                return;
            } else {
                byte functionStateOnServerSide = AbstractExecution.getFunctionState(functionObject.isHA(), functionObject.hasResult(), functionObject.optimizeForWrite());
                if (logger.isDebugEnabled()) {
                    logger.debug("Function State on server side: {} on client: {}", functionStateOnServerSide, functionState);
                }
                if (functionStateOnServerSide != functionState) {
                    String message = LocalizedStrings.FunctionService_FUNCTION_ATTRIBUTE_MISMATCH_CLIENT_SERVER.toLocalizedString(function);
                    logger.warn("{}: {}", servConn.getName(), message);
                    sendError(hasResult, clientMessage, message, servConn);
                    return;
                }
            }
        } else {
            functionObject = (Function) function;
        }
        FunctionStats stats = FunctionStats.getFunctionStats(functionObject.getId());
        this.securityService.authorizeDataWrite();
        // check if the caller is authorized to do this operation on server
        AuthorizeRequest authzRequest = servConn.getAuthzRequest();
        ExecuteFunctionOperationContext executeContext = null;
        if (authzRequest != null) {
            executeContext = authzRequest.executeFunctionAuthorize(functionObject.getId(), null, null, args, functionObject.optimizeForWrite());
        }
        ChunkedMessage m = servConn.getFunctionResponseMessage();
        m.setTransactionId(clientMessage.getTransactionId());
        ServerToClientFunctionResultSender resultSender = new ServerToClientFunctionResultSender65(m, MessageType.EXECUTE_FUNCTION_RESULT, servConn, functionObject, executeContext);
        InternalDistributedMember localVM = (InternalDistributedMember) servConn.getCache().getDistributedSystem().getDistributedMember();
        FunctionContext context = null;
        if (memberMappedArg != null) {
            context = new FunctionContextImpl(functionObject.getId(), memberMappedArg.getArgumentsForMember(localVM.getId()), resultSender, isReexecute);
        } else {
            context = new FunctionContextImpl(functionObject.getId(), args, resultSender, isReexecute);
        }
        HandShake handShake = (HandShake) servConn.getHandshake();
        int earlierClientReadTimeout = handShake.getClientReadTimeout();
        handShake.setClientReadTimeout(functionTimeout);
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Executing Function on Server: {} with context: {}", servConn, context);
            }
            InternalCache cache = servConn.getCache();
            HeapMemoryMonitor hmm = ((InternalResourceManager) cache.getResourceManager()).getHeapMonitor();
            if (functionObject.optimizeForWrite() && cache != null && hmm.getState().isCritical() && !MemoryThresholds.isLowMemoryExceptionDisabled()) {
                Set<DistributedMember> sm = Collections.singleton((DistributedMember) cache.getMyId());
                Exception e = new LowMemoryException(LocalizedStrings.ResourceManager_LOW_MEMORY_FOR_0_FUNCEXEC_MEMBERS_1.toLocalizedString(new Object[] { functionObject.getId(), sm }), sm);
                sendException(hasResult, clientMessage, e.getMessage(), servConn, e);
                return;
            }
            /**
         * if cache is null, then either cache has not yet been created on this node or it is a
         * shutdown scenario.
         */
            DM dm = null;
            if (cache != null) {
                dm = cache.getDistributionManager();
            }
            if (groups != null && groups.length > 0) {
                executeFunctionOnGroups(function, args, groups, allMembers, functionObject, resultSender, ignoreFailedMembers);
            } else {
                executeFunctionaLocally(functionObject, context, (ServerToClientFunctionResultSender65) resultSender, dm, stats);
            }
            if (!functionObject.hasResult()) {
                writeReply(clientMessage, servConn);
            }
        } catch (FunctionException functionException) {
            stats.endFunctionExecutionWithException(functionObject.hasResult());
            throw functionException;
        } catch (Exception exception) {
            stats.endFunctionExecutionWithException(functionObject.hasResult());
            throw new FunctionException(exception);
        } finally {
            handShake.setClientReadTimeout(earlierClientReadTimeout);
        }
    } catch (IOException ioException) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioException);
        String message = LocalizedStrings.ExecuteFunction_SERVER_COULD_NOT_SEND_THE_REPLY.toLocalizedString();
        sendException(hasResult, clientMessage, message, servConn, ioException);
    } catch (InternalFunctionInvocationTargetException internalfunctionException) {
        // 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 }), internalfunctionException);
        }
        final String message = internalfunctionException.getMessage();
        sendException(hasResult, clientMessage, message, servConn, internalfunctionException);
    } catch (Exception e) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e);
        final String message = e.getMessage();
        sendException(hasResult, clientMessage, message, servConn, e);
    }
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) InternalCache(org.apache.geode.internal.cache.InternalCache) DM(org.apache.geode.distributed.internal.DM) InternalResourceManager(org.apache.geode.internal.cache.control.InternalResourceManager) Function(org.apache.geode.cache.execute.Function) HandShake(org.apache.geode.internal.cache.tier.sockets.HandShake) MemberMappedArgument(org.apache.geode.internal.cache.execute.MemberMappedArgument) FunctionStats(org.apache.geode.internal.cache.execute.FunctionStats) LowMemoryException(org.apache.geode.cache.LowMemoryException) FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) ExecuteFunctionOperationContext(org.apache.geode.cache.operations.ExecuteFunctionOperationContext) ServerToClientFunctionResultSender65(org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender65) FunctionException(org.apache.geode.cache.execute.FunctionException) HeapMemoryMonitor(org.apache.geode.internal.cache.control.HeapMemoryMonitor) IOException(java.io.IOException) FunctionContext(org.apache.geode.cache.execute.FunctionContext) FunctionException(org.apache.geode.cache.execute.FunctionException) LowMemoryException(org.apache.geode.cache.LowMemoryException) IOException(java.io.IOException) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) Part(org.apache.geode.internal.cache.tier.sockets.Part) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) DistributedMember(org.apache.geode.distributed.DistributedMember) ServerToClientFunctionResultSender(org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender) ChunkedMessage(org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)

Example 7 with HeapMemoryMonitor

use of org.apache.geode.internal.cache.control.HeapMemoryMonitor in project geode by apache.

the class ExecuteFunction method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection servConn, long start) throws IOException {
    Object function = null;
    Object args = null;
    MemberMappedArgument memberMappedArg = null;
    byte hasResult = 0;
    try {
        hasResult = clientMessage.getPart(0).getSerializedForm()[0];
        if (hasResult == 1) {
            servConn.setAsTrue(REQUIRES_RESPONSE);
            servConn.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
        }
        function = clientMessage.getPart(1).getStringOrObject();
        args = clientMessage.getPart(2).getObject();
        Part part = clientMessage.getPart(3);
        if (part != null) {
            memberMappedArg = (MemberMappedArgument) part.getObject();
        }
    } catch (ClassNotFoundException exception) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception);
        if (hasResult == 1) {
            writeChunkedException(clientMessage, exception, servConn);
            servConn.setAsTrue(RESPONDED);
            return;
        }
    }
    if (function == null) {
        final String message = LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL.toLocalizedString();
        logger.warn("{}: {}", servConn.getName(), message);
        sendError(hasResult, clientMessage, message, servConn);
        return;
    }
    // Execute function on the cache
    try {
        Function functionObject = null;
        if (function instanceof String) {
            functionObject = FunctionService.getFunction((String) function);
            if (functionObject == null) {
                final String message = LocalizedStrings.ExecuteFunction_FUNCTION_NAMED_0_IS_NOT_REGISTERED.toLocalizedString(function);
                logger.warn("{}: {}", servConn.getName(), message);
                sendError(hasResult, clientMessage, message, servConn);
                return;
            }
        } else {
            functionObject = (Function) function;
        }
        FunctionStats stats = FunctionStats.getFunctionStats(functionObject.getId());
        this.securityService.authorizeDataWrite();
        // check if the caller is authorized to do this operation on server
        AuthorizeRequest authzRequest = servConn.getAuthzRequest();
        ExecuteFunctionOperationContext executeContext = null;
        if (authzRequest != null) {
            executeContext = authzRequest.executeFunctionAuthorize(functionObject.getId(), null, null, args, functionObject.optimizeForWrite());
        }
        ChunkedMessage m = servConn.getFunctionResponseMessage();
        m.setTransactionId(clientMessage.getTransactionId());
        ResultSender resultSender = new ServerToClientFunctionResultSender(m, MessageType.EXECUTE_FUNCTION_RESULT, servConn, functionObject, executeContext);
        InternalDistributedMember localVM = (InternalDistributedMember) servConn.getCache().getDistributedSystem().getDistributedMember();
        FunctionContext context = null;
        if (memberMappedArg != null) {
            context = new FunctionContextImpl(functionObject.getId(), memberMappedArg.getArgumentsForMember(localVM.getId()), resultSender);
        } else {
            context = new FunctionContextImpl(functionObject.getId(), args, resultSender);
        }
        HandShake handShake = (HandShake) servConn.getHandshake();
        int earlierClientReadTimeout = handShake.getClientReadTimeout();
        handShake.setClientReadTimeout(0);
        try {
            long startExecution = stats.startTime();
            stats.startFunctionExecution(functionObject.hasResult());
            if (logger.isDebugEnabled()) {
                logger.debug("Executing Function on Server: " + servConn.toString() + "with context :" + context.toString());
            }
            InternalCache cache = servConn.getCache();
            HeapMemoryMonitor hmm = ((InternalResourceManager) cache.getResourceManager()).getHeapMonitor();
            if (functionObject.optimizeForWrite() && cache != null && hmm.getState().isCritical() && !MemoryThresholds.isLowMemoryExceptionDisabled()) {
                Set<DistributedMember> sm = Collections.<DistributedMember>singleton(cache.getMyId());
                throw new LowMemoryException(LocalizedStrings.ResourceManager_LOW_MEMORY_FOR_0_FUNCEXEC_MEMBERS_1.toLocalizedString(new Object[] { functionObject.getId(), sm }), sm);
            }
            functionObject.execute(context);
            stats.endFunctionExecution(startExecution, functionObject.hasResult());
        } catch (FunctionException functionException) {
            stats.endFunctionExecutionWithException(functionObject.hasResult());
            throw functionException;
        } catch (Exception exception) {
            stats.endFunctionExecutionWithException(functionObject.hasResult());
            throw new FunctionException(exception);
        } finally {
            handShake.setClientReadTimeout(earlierClientReadTimeout);
        }
    } catch (IOException ioException) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioException);
        String message = LocalizedStrings.ExecuteFunction_SERVER_COULD_NOT_SEND_THE_REPLY.toLocalizedString();
        sendException(hasResult, clientMessage, message, servConn, ioException);
    } catch (InternalFunctionInvocationTargetException internalfunctionException) {
        // 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 }), internalfunctionException);
        }
        final String message = internalfunctionException.getMessage();
        sendException(hasResult, clientMessage, message, servConn, internalfunctionException);
    } catch (Exception e) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e);
        final String message = e.getMessage();
        sendException(hasResult, clientMessage, message, servConn, e);
    }
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) InternalCache(org.apache.geode.internal.cache.InternalCache) ServerToClientFunctionResultSender(org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender) ResultSender(org.apache.geode.cache.execute.ResultSender) InternalResourceManager(org.apache.geode.internal.cache.control.InternalResourceManager) Function(org.apache.geode.cache.execute.Function) HandShake(org.apache.geode.internal.cache.tier.sockets.HandShake) MemberMappedArgument(org.apache.geode.internal.cache.execute.MemberMappedArgument) FunctionStats(org.apache.geode.internal.cache.execute.FunctionStats) LowMemoryException(org.apache.geode.cache.LowMemoryException) FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) ExecuteFunctionOperationContext(org.apache.geode.cache.operations.ExecuteFunctionOperationContext) FunctionException(org.apache.geode.cache.execute.FunctionException) HeapMemoryMonitor(org.apache.geode.internal.cache.control.HeapMemoryMonitor) IOException(java.io.IOException) FunctionContext(org.apache.geode.cache.execute.FunctionContext) FunctionException(org.apache.geode.cache.execute.FunctionException) LowMemoryException(org.apache.geode.cache.LowMemoryException) IOException(java.io.IOException) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) Part(org.apache.geode.internal.cache.tier.sockets.Part) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) DistributedMember(org.apache.geode.distributed.DistributedMember) ServerToClientFunctionResultSender(org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender) ChunkedMessage(org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)

Example 8 with HeapMemoryMonitor

use of org.apache.geode.internal.cache.control.HeapMemoryMonitor in project geode by apache.

the class PartitionedRegion method executeOnSingleNode.

/**
   * Single key execution on single node
   * 
   * @since GemFire 6.0
   */
private ResultCollector executeOnSingleNode(final Function function, final PartitionedRegionFunctionExecutor execution, ResultCollector rc, boolean isPRSingleHop, boolean isBucketSetAsFilter) {
    final Set routingKeys = execution.getFilter();
    final Object key = routingKeys.iterator().next();
    final Integer bucketId;
    if (isBucketSetAsFilter) {
        bucketId = (Integer) key;
    } else {
        bucketId = PartitionedRegionHelper.getHashKey(this, Operation.FUNCTION_EXECUTION, key, null, null);
    }
    InternalDistributedMember targetNode = null;
    if (function.optimizeForWrite()) {
        targetNode = createBucket(bucketId, 0, null);
        HeapMemoryMonitor hmm = ((InternalResourceManager) cache.getResourceManager()).getHeapMonitor();
        if (hmm.isMemberHeapCritical(targetNode) && !MemoryThresholds.isLowMemoryExceptionDisabled()) {
            Set<DistributedMember> sm = Collections.singleton((DistributedMember) targetNode);
            throw new LowMemoryException(LocalizedStrings.ResourceManager_LOW_MEMORY_FOR_0_FUNCEXEC_MEMBERS_1.toLocalizedString(function.getId(), sm), sm);
        }
    } else {
        targetNode = getOrCreateNodeForBucketRead(bucketId);
    }
    final DistributedMember localVm = getMyId();
    if (targetNode != null && isPRSingleHop && !localVm.equals(targetNode)) {
        Set<ServerBucketProfile> profiles = this.getRegionAdvisor().getClientBucketProfiles(bucketId);
        if (profiles != null) {
            for (ServerBucketProfile profile : profiles) {
                if (profile.getDistributedMember().equals(targetNode)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("FunctionServiceSingleHop: Found remote node.{}", localVm);
                    }
                    throw new InternalFunctionInvocationTargetException(LocalizedStrings.PartitionedRegion_MULTIPLE_TARGET_NODE_FOUND_FOR.toLocalizedString());
                }
            }
        }
    }
    if (targetNode == null) {
        throw new FunctionException(LocalizedStrings.PartitionedRegion_NO_TARGET_NODE_FOUND_FOR_KEY_0.toLocalizedString(key));
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Executing Function: {} setArguments={} on {}", function.getId(), execution.getArguments(), targetNode);
    }
    while (!execution.getFailedNodes().isEmpty()) {
        RetryTimeKeeper retryTime = new RetryTimeKeeper(this.retryTimeout);
        if (execution.getFailedNodes().contains(targetNode.getId())) {
            /*
         * if (retryTime.overMaximum()) { PRHARedundancyProvider.timedOut(this, null, null,
         * "doing function execution", this.retryTimeout); // NOTREACHED }
         */
            // Fix for Bug # 40083
            targetNode = null;
            while (targetNode == null) {
                if (retryTime.overMaximum()) {
                    PRHARedundancyProvider.timedOut(this, null, null, "doing function execution", this.retryTimeout);
                // NOTREACHED
                }
                retryTime.waitToRetryNode();
                if (function.optimizeForWrite()) {
                    targetNode = getOrCreateNodeForBucketWrite(bucketId, retryTime);
                } else {
                    targetNode = getOrCreateNodeForBucketRead(bucketId);
                }
            }
            if (targetNode == null) {
                throw new FunctionException(LocalizedStrings.PartitionedRegion_NO_TARGET_NODE_FOUND_FOR_KEY_0.toLocalizedString(key));
            }
        } else {
            execution.clearFailedNodes();
        }
    }
    final HashSet<Integer> buckets = new HashSet<Integer>();
    buckets.add(bucketId);
    final Set<InternalDistributedMember> singleMember = Collections.singleton(targetNode);
    execution.validateExecution(function, singleMember);
    execution.setExecutionNodes(singleMember);
    LocalResultCollector<?, ?> localRC = execution.getLocalResultCollector(function, rc);
    if (targetNode.equals(localVm)) {
        final DM dm = getDistributionManager();
        PartitionedRegionFunctionResultSender resultSender = new PartitionedRegionFunctionResultSender(dm, PartitionedRegion.this, 0, localRC, execution.getServerResultSender(), true, false, execution.isForwardExceptions(), function, buckets);
        final FunctionContext context = new RegionFunctionContextImpl(function.getId(), PartitionedRegion.this, execution.getArgumentsForMember(localVm.getId()), routingKeys, ColocationHelper.constructAndGetAllColocatedLocalDataSet(PartitionedRegion.this, buckets), buckets, resultSender, execution.isReExecute());
        execution.executeFunctionOnLocalPRNode(function, context, resultSender, dm, isTX());
        return localRC;
    } else {
        return executeFunctionOnRemoteNode(targetNode, function, execution.getArgumentsForMember(targetNode.getId()), routingKeys, function.isHA() ? rc : localRC, buckets, execution.getServerResultSender(), execution);
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ResultsSet(org.apache.geode.cache.query.internal.ResultsSet) FunctionException(org.apache.geode.cache.execute.FunctionException) EmptyRegionFunctionException(org.apache.geode.cache.execute.EmptyRegionFunctionException) DM(org.apache.geode.distributed.internal.DM) HeapMemoryMonitor(org.apache.geode.internal.cache.control.HeapMemoryMonitor) FunctionContext(org.apache.geode.cache.execute.FunctionContext) InternalResourceManager(org.apache.geode.internal.cache.control.InternalResourceManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerBucketProfile(org.apache.geode.internal.cache.BucketAdvisor.ServerBucketProfile) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) RegionFunctionContextImpl(org.apache.geode.internal.cache.execute.RegionFunctionContextImpl) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) DistributedMember(org.apache.geode.distributed.DistributedMember) PartitionedRegionFunctionResultSender(org.apache.geode.internal.cache.execute.PartitionedRegionFunctionResultSender) LowMemoryException(org.apache.geode.cache.LowMemoryException) HashSet(java.util.HashSet)

Example 9 with HeapMemoryMonitor

use of org.apache.geode.internal.cache.control.HeapMemoryMonitor in project geode by apache.

the class MemoryThresholdsDUnitTest method testDRLoadRejection.

/**
   * Test that DistributedRegion cacheLoade and netLoad are passed through to the calling thread if
   * the local VM is in a critical state. Once the VM has moved to a safe state then test that they
   * are allowed.
   * 
   * @throws Exception
   */
@Test
public void testDRLoadRejection() throws Exception {
    final Host host = Host.getHost(0);
    final VM replicate1 = host.getVM(2);
    final VM replicate2 = host.getVM(3);
    final String rName = getUniqueName();
    final float criticalHeapThresh = 0.90f;
    final int fakeHeapMaxSize = 1000;
    // Make sure the desired VMs will have a fresh DS.
    AsyncInvocation d1 = replicate1.invokeAsync(() -> disconnectFromDS());
    AsyncInvocation d2 = replicate2.invokeAsync(() -> disconnectFromDS());
    d1.join();
    assertFalse(d1.exceptionOccurred());
    d2.join();
    assertFalse(d2.exceptionOccurred());
    CacheSerializableRunnable establishConnectivity = new CacheSerializableRunnable("establishcConnectivity") {

        @Override
        public void run2() throws CacheException {
            getSystem();
        }
    };
    replicate1.invoke(establishConnectivity);
    replicate2.invoke(establishConnectivity);
    CacheSerializableRunnable createRegion = new CacheSerializableRunnable("create DistributedRegion") {

        @Override
        public void run2() throws CacheException {
            // Assert some level of connectivity
            InternalDistributedSystem ds = getSystem();
            assertTrue(ds.getDistributionManager().getNormalDistributionManagerIds().size() >= 1);
            // below
            final long fakeHeapUsage = Math.round(fakeHeapMaxSize * (criticalHeapThresh - 0.5f));
            // critical
            // by
            // 50%
            InternalResourceManager irm = (InternalResourceManager) getCache().getResourceManager();
            HeapMemoryMonitor hmm = irm.getHeapMonitor();
            assertTrue(fakeHeapMaxSize > 0);
            hmm.setTestMaxMemoryBytes(fakeHeapMaxSize);
            HeapMemoryMonitor.setTestBytesUsedForThresholdSet(fakeHeapUsage);
            irm.setCriticalHeapPercentage((criticalHeapThresh * 100.0f));
            AttributesFactory<Integer, String> af = new AttributesFactory<Integer, String>();
            af.setScope(Scope.DISTRIBUTED_ACK);
            af.setDataPolicy(DataPolicy.REPLICATE);
            getCache().createRegion(rName, af.create());
        }
    };
    replicate1.invoke(createRegion);
    replicate2.invoke(createRegion);
    replicate1.invoke(addExpectedException);
    replicate2.invoke(addExpectedException);
    final Integer expected = (Integer) replicate1.invoke(new SerializableCallable("test Local DistributedRegion Load") {

        public Object call() throws Exception {
            Region<Integer, String> r = getCache().getRegion(rName);
            AttributesMutator<Integer, String> am = r.getAttributesMutator();
            am.setCacheLoader(new CacheLoader<Integer, String>() {

                final AtomicInteger numLoaderInvocations = new AtomicInteger();

                public String load(LoaderHelper<Integer, String> helper) throws CacheLoaderException {
                    Integer expectedInvocations = (Integer) helper.getArgument();
                    final int actualInvocations = this.numLoaderInvocations.getAndIncrement();
                    if (expectedInvocations.intValue() != actualInvocations) {
                        throw new CacheLoaderException("Expected " + expectedInvocations + " invocations, actual is " + actualInvocations);
                    }
                    return helper.getKey().toString();
                }

                public void close() {
                }
            });
            int expectedInvocations = 0;
            HeapMemoryMonitor hmm = ((InternalResourceManager) getCache().getResourceManager()).getHeapMonitor();
            assertFalse(hmm.getState().isCritical());
            {
                Integer k = new Integer(1);
                assertEquals(k.toString(), r.get(k, new Integer(expectedInvocations++)));
            }
            // usage
            long newfakeHeapUsage = Math.round(fakeHeapMaxSize * (criticalHeapThresh + 0.1f));
            // above
            // critical
            // by
            // 10%
            assertTrue(newfakeHeapUsage > 0);
            assertTrue(newfakeHeapUsage <= fakeHeapMaxSize);
            hmm.updateStateAndSendEvent(newfakeHeapUsage);
            assertTrue(hmm.getState().isCritical());
            {
                Integer k = new Integer(2);
                assertEquals(k.toString(), r.get(k, new Integer(expectedInvocations++)));
            }
            // below
            newfakeHeapUsage = Math.round(fakeHeapMaxSize * (criticalHeapThresh - 0.3f));
            // critical
            // by 30%
            assertTrue(fakeHeapMaxSize > 0);
            getCache().getLoggerI18n().fine(addExpectedBelow);
            hmm.updateStateAndSendEvent(newfakeHeapUsage);
            getCache().getLoggerI18n().fine(removeExpectedBelow);
            assertFalse(hmm.getState().isCritical());
            {
                Integer k = new Integer(3);
                assertEquals(k.toString(), r.get(k, new Integer(expectedInvocations++)));
            }
            return new Integer(expectedInvocations);
        }
    });
    final CacheSerializableRunnable validateData1 = new CacheSerializableRunnable("Validate data 1") {

        @Override
        public void run2() throws CacheException {
            Region<Integer, String> r = getCache().getRegion(rName);
            Integer i1 = new Integer(1);
            assertTrue(r.containsKey(i1));
            assertNotNull(r.getEntry(i1));
            Integer i2 = new Integer(2);
            assertFalse(r.containsKey(i2));
            assertNull(r.getEntry(i2));
            Integer i3 = new Integer(3);
            assertTrue(r.containsKey(i3));
            assertNotNull(r.getEntry(i3));
        }
    };
    replicate1.invoke(validateData1);
    replicate2.invoke(validateData1);
    replicate2.invoke(new SerializableCallable("test DistributedRegion netLoad") {

        public Object call() throws Exception {
            Region<Integer, String> r = getCache().getRegion(rName);
            HeapMemoryMonitor hmm = ((InternalResourceManager) getCache().getResourceManager()).getHeapMonitor();
            assertFalse(hmm.getState().isCritical());
            int expectedInvocations = expected.intValue();
            {
                Integer k = new Integer(4);
                assertEquals(k.toString(), r.get(k, new Integer(expectedInvocations++)));
                assertFalse(hmm.getState().isCritical());
                assertTrue(r.containsKey(k));
            }
            // Place in a critical state for the next test
            // usage
            long newfakeHeapUsage = Math.round(fakeHeapMaxSize * (criticalHeapThresh + 0.1f));
            // above
            // critical
            // by 10%
            assertTrue(newfakeHeapUsage > 0);
            assertTrue(newfakeHeapUsage <= fakeHeapMaxSize);
            hmm.updateStateAndSendEvent(newfakeHeapUsage);
            assertTrue(hmm.getState().isCritical());
            {
                Integer k = new Integer(5);
                assertEquals(k.toString(), r.get(k, new Integer(expectedInvocations++)));
                assertTrue(hmm.getState().isCritical());
                assertFalse(r.containsKey(k));
            }
            // below
            newfakeHeapUsage = Math.round(fakeHeapMaxSize * (criticalHeapThresh - 0.3f));
            // critical by
            // 30%
            assertTrue(fakeHeapMaxSize > 0);
            getCache().getLoggerI18n().fine(addExpectedBelow);
            hmm.updateStateAndSendEvent(newfakeHeapUsage);
            getCache().getLoggerI18n().fine(removeExpectedBelow);
            assertFalse(hmm.getState().isCritical());
            {
                Integer k = new Integer(6);
                assertEquals(k.toString(), r.get(k, new Integer(expectedInvocations++)));
                assertFalse(hmm.getState().isCritical());
                assertTrue(r.containsKey(k));
            }
            return new Integer(expectedInvocations);
        }
    });
    replicate1.invoke(removeExpectedException);
    replicate2.invoke(removeExpectedException);
    final CacheSerializableRunnable validateData2 = new CacheSerializableRunnable("Validate data 2") {

        @Override
        public void run2() throws CacheException {
            Region<Integer, String> r = getCache().getRegion(rName);
            Integer i4 = new Integer(4);
            assertTrue(r.containsKey(i4));
            assertNotNull(r.getEntry(i4));
            Integer i5 = new Integer(5);
            assertFalse(r.containsKey(i5));
            assertNull(r.getEntry(i5));
            Integer i6 = new Integer(6);
            assertTrue(r.containsKey(i6));
            assertNotNull(r.getEntry(i6));
        }
    };
    replicate1.invoke(validateData2);
    replicate2.invoke(validateData2);
}
Also used : Host(org.apache.geode.test.dunit.Host) HeapMemoryMonitor(org.apache.geode.internal.cache.control.HeapMemoryMonitor) AsyncInvocation(org.apache.geode.test.dunit.AsyncInvocation) IgnoredException(org.apache.geode.test.dunit.IgnoredException) FunctionException(org.apache.geode.cache.execute.FunctionException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) LowMemoryException(org.apache.geode.cache.LowMemoryException) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) CacheException(org.apache.geode.cache.CacheException) InternalResourceManager(org.apache.geode.internal.cache.control.InternalResourceManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AttributesFactory(org.apache.geode.cache.AttributesFactory) PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) DistributedRegion(org.apache.geode.internal.cache.DistributedRegion) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) Region(org.apache.geode.cache.Region) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) FlakyTest(org.apache.geode.test.junit.categories.FlakyTest) Test(org.junit.Test)

Example 10 with HeapMemoryMonitor

use of org.apache.geode.internal.cache.control.HeapMemoryMonitor in project geode by apache.

the class MemoryThresholdsDUnitTest method testCriticalMemoryEventTolerance.

@Test
public void testCriticalMemoryEventTolerance() {
    final Host host = Host.getHost(0);
    final VM vm = host.getVM(0);
    vm.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            int defaultTolerance = 1;
            HeapMemoryMonitor.setTestDisableMemoryUpdates(false);
            GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
            InternalResourceManager irm = cache.getInternalResourceManager();
            HeapMemoryMonitor hmm = irm.getHeapMonitor();
            hmm.setTestMaxMemoryBytes(100);
            HeapMemoryMonitor.setTestBytesUsedForThresholdSet(1);
            irm.setCriticalHeapPercentage(95);
            for (int i = 0; i < defaultTolerance; i++) {
                hmm.updateStateAndSendEvent(96);
                assertFalse(hmm.getState().isCritical());
            }
            getCache().getLoggerI18n().fine(addExpectedExString);
            hmm.updateStateAndSendEvent(96);
            assertTrue(hmm.getState().isCritical());
            getCache().getLoggerI18n().fine(removeExpectedExString);
            getCache().getLoggerI18n().fine(addExpectedBelow);
            hmm.updateStateAndSendEvent(92);
            getCache().getLoggerI18n().fine(removeExpectedBelow);
            assertFalse(hmm.getState().isCritical());
            HeapMemoryMonitor.setTestDisableMemoryUpdates(true);
            return null;
        }
    });
}
Also used : VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) Host(org.apache.geode.test.dunit.Host) HeapMemoryMonitor(org.apache.geode.internal.cache.control.HeapMemoryMonitor) IgnoredException(org.apache.geode.test.dunit.IgnoredException) FunctionException(org.apache.geode.cache.execute.FunctionException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) LowMemoryException(org.apache.geode.cache.LowMemoryException) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) CacheException(org.apache.geode.cache.CacheException) InternalResourceManager(org.apache.geode.internal.cache.control.InternalResourceManager) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) FlakyTest(org.apache.geode.test.junit.categories.FlakyTest) Test(org.junit.Test)

Aggregations

HeapMemoryMonitor (org.apache.geode.internal.cache.control.HeapMemoryMonitor)15 InternalResourceManager (org.apache.geode.internal.cache.control.InternalResourceManager)11 LowMemoryException (org.apache.geode.cache.LowMemoryException)8 FunctionException (org.apache.geode.cache.execute.FunctionException)8 CacheException (org.apache.geode.cache.CacheException)6 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 CacheLoaderException (org.apache.geode.cache.CacheLoaderException)5 CacheSerializableRunnable (org.apache.geode.cache30.CacheSerializableRunnable)5 Host (org.apache.geode.test.dunit.Host)5 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)5 VM (org.apache.geode.test.dunit.VM)5 FlakyTest (org.apache.geode.test.junit.categories.FlakyTest)5 Test (org.junit.Test)5 Region (org.apache.geode.cache.Region)4 ServerOperationException (org.apache.geode.cache.client.ServerOperationException)4 FunctionContext (org.apache.geode.cache.execute.FunctionContext)4 DistributedMember (org.apache.geode.distributed.DistributedMember)4 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)4 DistributedRegion (org.apache.geode.internal.cache.DistributedRegion)4