Search in sources :

Example 1 with FunctionContextImpl

use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.

the class MemberFunctionStreamingMessage method process.

@Override
protected void process(final DistributionManager dm) {
    Throwable thr = null;
    ReplyException rex = null;
    if (this.functionObject == null) {
        rex = new ReplyException(new FunctionException(LocalizedStrings.ExecuteFunction_FUNCTION_NAMED_0_IS_NOT_REGISTERED.toLocalizedString(this.functionName)));
        replyWithException(dm, rex);
        return;
    }
    FunctionStats stats = FunctionStats.getFunctionStats(this.functionObject.getId(), dm.getSystem());
    TXStateProxy tx = null;
    try {
        tx = prepForTransaction();
        ResultSender resultSender = new MemberFunctionResultSender(dm, this, this.functionObject);
        Set<Region> regions = new HashSet<Region>();
        if (this.regionPathSet != null) {
            InternalCache cache = GemFireCacheImpl.getInstance();
            for (String regionPath : this.regionPathSet) {
                if (checkCacheClosing(dm) || checkDSClosing(dm)) {
                    thr = new CacheClosedException(LocalizedStrings.PartitionMessage_REMOTE_CACHE_IS_CLOSED_0.toLocalizedString(dm.getId()));
                    return;
                }
                regions.add(cache.getRegion(regionPath));
            }
        }
        FunctionContextImpl context = new MultiRegionFunctionContextImpl(this.functionObject.getId(), this.args, resultSender, regions, isReExecute);
        long start = stats.startTime();
        stats.startFunctionExecution(this.functionObject.hasResult());
        if (logger.isDebugEnabled()) {
            logger.debug("Executing Function: {} on remote member with context: {}", this.functionObject.getId(), context.toString());
        }
        this.functionObject.execute(context);
        if (!this.replyLastMsg && this.functionObject.hasResult()) {
            throw new FunctionException(LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT.toString(functionObject.getId()));
        }
        stats.endFunctionExecution(start, this.functionObject.hasResult());
    } catch (FunctionException functionException) {
        if (logger.isDebugEnabled()) {
            logger.debug("FunctionException occurred on remote member while executing Function: {}", this.functionObject.getId(), functionException);
        }
        stats.endFunctionExecutionWithException(this.functionObject.hasResult());
        rex = new ReplyException(functionException);
        replyWithException(dm, rex);
    // thr = functionException.getCause();
    } catch (CancelException exception) {
        // bug 37026: this is too noisy...
        // throw new CacheClosedException("remote system shutting down");
        // thr = se; cache is closed, no point trying to send a reply
        thr = new FunctionInvocationTargetException(exception);
        stats.endFunctionExecutionWithException(this.functionObject.hasResult());
        rex = new ReplyException(thr);
        replyWithException(dm, rex);
    } catch (Exception exception) {
        if (logger.isDebugEnabled()) {
            logger.debug("Exception occurred on remote member while executing Function: {}", this.functionObject.getId(), exception);
        }
        stats.endFunctionExecutionWithException(this.functionObject.hasResult());
        rex = new ReplyException(exception);
        replyWithException(dm, rex);
    // thr = e.getCause();
    } catch (VirtualMachineError err) {
        SystemFailure.initiateFailure(err);
        // now, so don't let this thread continue.
        throw err;
    } catch (Throwable t) {
        // Whenever you catch Error or Throwable, you must also
        // catch VirtualMachineError (see above). However, there is
        // _still_ a possibility that you are dealing with a cascading
        // error condition, so you also need to check to see if the JVM
        // is still usable:
        SystemFailure.checkFailure();
        thr = t;
    } finally {
        cleanupTransaction(tx);
        if (thr != null) {
            rex = new ReplyException(thr);
            replyWithException(dm, rex);
        }
    }
}
Also used : FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) MultiRegionFunctionContextImpl(org.apache.geode.internal.cache.execute.MultiRegionFunctionContextImpl) FunctionException(org.apache.geode.cache.execute.FunctionException) CacheClosedException(org.apache.geode.cache.CacheClosedException) ReplyException(org.apache.geode.distributed.internal.ReplyException) MemberFunctionResultSender(org.apache.geode.internal.cache.execute.MemberFunctionResultSender) ResultSender(org.apache.geode.cache.execute.ResultSender) FunctionInvocationTargetException(org.apache.geode.cache.execute.FunctionInvocationTargetException) FunctionException(org.apache.geode.cache.execute.FunctionException) CacheClosedException(org.apache.geode.cache.CacheClosedException) CancelException(org.apache.geode.CancelException) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) ReplyException(org.apache.geode.distributed.internal.ReplyException) QueryException(org.apache.geode.cache.query.QueryException) FunctionInvocationTargetException(org.apache.geode.cache.execute.FunctionInvocationTargetException) FunctionStats(org.apache.geode.internal.cache.execute.FunctionStats) MemberFunctionResultSender(org.apache.geode.internal.cache.execute.MemberFunctionResultSender) Region(org.apache.geode.cache.Region) CancelException(org.apache.geode.CancelException) MultiRegionFunctionContextImpl(org.apache.geode.internal.cache.execute.MultiRegionFunctionContextImpl) HashSet(java.util.HashSet)

Example 2 with FunctionContextImpl

use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.

the class ExecuteFunction65 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;
    byte functionState = 0;
    boolean isReexecute = false;
    try {
        functionState = clientMessage.getPart(0).getSerializedForm()[0];
        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();
        }
    } 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 {
                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());
        ResultSender 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(0);
        try {
            long startExecution = stats.startTime();
            stats.startFunctionExecution(functionObject.hasResult());
            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;
            }
            functionObject.execute(context);
            if (!((ServerToClientFunctionResultSender65) resultSender).isLastResultReceived() && functionObject.hasResult()) {
                throw new FunctionException(LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT.toString(functionObject.getId()));
            }
            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) {
        // 2> 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) 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) 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) ChunkedMessage(org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)

Example 3 with FunctionContextImpl

use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.

the class ExportLogsFunctionIntegrationTest method verifyExportLogsFunctionDoesNotBlowUp.

public static void verifyExportLogsFunctionDoesNotBlowUp() throws Throwable {
    ExportLogsFunction.Args args = new ExportLogsFunction.Args(null, null, "info", false, false, false);
    CapturingResultSender resultSender = new CapturingResultSender();
    FunctionContext context = new FunctionContextImpl("functionId", args, resultSender);
    new ExportLogsFunction().execute(context);
    if (resultSender.getThrowable() != null) {
        throw resultSender.getThrowable();
    }
}
Also used : FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) FunctionContext(org.apache.geode.cache.execute.FunctionContext)

Example 4 with FunctionContextImpl

use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.

the class SizeExportLogsFunctionTest method sizeGreaterThanDiskAvailable_sendsErrorResult.

@Test
public void sizeGreaterThanDiskAvailable_sendsErrorResult() throws Throwable {
    server.withProperties(config).startServer();
    FunctionContext context = new FunctionContextImpl("functionId", nonFilteringArgs, resultSender);
    SizeExportLogsFunction testFunction = new SizeExportLogsFunction();
    SizeExportLogsFunction spyFunction = spy(testFunction);
    long fakeDiskAvailable = 1024;
    doReturn(fakeDiskAvailable).when(spyFunction).getDiskAvailable(Matchers.any(DistributionConfig.class));
    spyFunction.execute(context);
    assertThatThrownBy(resultSender::getResults).isInstanceOf(ManagementException.class);
}
Also used : FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) FunctionContext(org.apache.geode.cache.execute.FunctionContext) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 5 with FunctionContextImpl

use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.

the class SizeExportLogsFunctionTest method withFunctionError_shouldThrow.

@Test
public void withFunctionError_shouldThrow() throws Throwable {
    server.withProperties(config).startServer();
    FunctionContext context = new FunctionContextImpl("functionId", null, resultSender);
    new SizeExportLogsFunction().execute(context);
    assertThatThrownBy(resultSender::getResults).isInstanceOf(NullPointerException.class);
}
Also used : FunctionContextImpl(org.apache.geode.internal.cache.execute.FunctionContextImpl) FunctionContext(org.apache.geode.cache.execute.FunctionContext) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Aggregations

FunctionContextImpl (org.apache.geode.internal.cache.execute.FunctionContextImpl)13 FunctionContext (org.apache.geode.cache.execute.FunctionContext)10 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)7 Test (org.junit.Test)7 Function (org.apache.geode.cache.execute.Function)6 IOException (java.io.IOException)4 FunctionException (org.apache.geode.cache.execute.FunctionException)4 FunctionStats (org.apache.geode.internal.cache.execute.FunctionStats)4 LowMemoryException (org.apache.geode.cache.LowMemoryException)3 ResultSender (org.apache.geode.cache.execute.ResultSender)3 ExecuteFunctionOperationContext (org.apache.geode.cache.operations.ExecuteFunctionOperationContext)3 DistributedMember (org.apache.geode.distributed.DistributedMember)3 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)3 InternalCache (org.apache.geode.internal.cache.InternalCache)3 HeapMemoryMonitor (org.apache.geode.internal.cache.control.HeapMemoryMonitor)3 InternalResourceManager (org.apache.geode.internal.cache.control.InternalResourceManager)3 InternalFunctionInvocationTargetException (org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException)3 MemberMappedArgument (org.apache.geode.internal.cache.execute.MemberMappedArgument)3 ChunkedMessage (org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)3 HandShake (org.apache.geode.internal.cache.tier.sockets.HandShake)3