Search in sources :

Example 21 with DistributedRegion

use of org.apache.geode.internal.cache.DistributedRegion in project geode by apache.

the class QueueMsgDUnitTest method testQueueWhenRoleMissing.

/**
   * Make sure that cache operations are queued when a required role is missing
   */
@Ignore("TODO: test is disabled")
@Test
public void testQueueWhenRoleMissing() throws Exception {
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(Scope.DISTRIBUTED_ACK);
    DistributedRegion r = (DistributedRegion) createRootRegion(factory.create());
    final CachePerfStats stats = r.getCachePerfStats();
    int queuedOps = stats.getReliableQueuedOps();
    r.create("createKey", "createValue", "createCBArg");
    r.invalidate("createKey", "invalidateCBArg");
    r.put("createKey", "putValue", "putCBArg");
    r.destroy("createKey", "destroyCBArg");
    assertEquals(queuedOps + 4, stats.getReliableQueuedOps());
    queuedOps = stats.getReliableQueuedOps();
    {
        Map m = new TreeMap();
        m.put("aKey", "aValue");
        m.put("bKey", "bValue");
        r.putAll(m);
    }
    assertEquals(queuedOps + 2, stats.getReliableQueuedOps());
    queuedOps = stats.getReliableQueuedOps();
    r.invalidateRegion("invalidateRegionCBArg");
    assertEquals(queuedOps + 1, stats.getReliableQueuedOps());
    queuedOps = stats.getReliableQueuedOps();
    r.clear();
    assertEquals(queuedOps + 1, stats.getReliableQueuedOps());
    queuedOps = stats.getReliableQueuedOps();
    // @todo darrel: try some other ops
    VM vm = Host.getHost(0).getVM(0);
    // now create a system that fills this role since it does not create the
    // region our queue should not be flushed
    vm.invoke(new SerializableRunnable() {

        public void run() {
            Properties config = new Properties();
            config.setProperty(ROLES, "missing");
            getSystem(config);
        }
    });
    // we still should have everything queued since the region is not created
    assertEquals(queuedOps, stats.getReliableQueuedOps());
    // now create the region
    vm.invoke(new CacheSerializableRunnable("create root") {

        public void run2() throws CacheException {
            AttributesFactory factory = new AttributesFactory();
            factory.setScope(Scope.DISTRIBUTED_ACK);
            factory.setDataPolicy(DataPolicy.NORMAL);
            factory.setSubscriptionAttributes(new SubscriptionAttributes(InterestPolicy.ALL));
            TestCacheListener cl = new TestCacheListener() {

                public void afterCreate2(EntryEvent event) {
                }

                public void afterUpdate2(EntryEvent event) {
                }

                public void afterInvalidate2(EntryEvent event) {
                }

                public void afterDestroy2(EntryEvent event) {
                }
            };
            cl.enableEventHistory();
            factory.addCacheListener(cl);
            createRootRegion(factory.create());
        }
    });
    // after some amount of time we should see the queuedOps flushed
    WaitCriterion ev = new WaitCriterion() {

        public boolean done() {
            return stats.getReliableQueuedOps() == 0;
        }

        public String description() {
            return "waiting for reliableQueuedOps to become 0";
        }
    };
    Wait.waitForCriterion(ev, 5 * 1000, 200, true);
    // now check that the queued op was delivered
    vm.invoke(new CacheSerializableRunnable("check") {

        public void run2() throws CacheException {
            Region r = getRootRegion();
            assertEquals(null, r.getEntry("createKey"));
            // assertIndexDetailsEquals("putValue", r.getEntry("createKey").getValue());
            {
                int evIdx = 0;
                TestCacheListener cl = (TestCacheListener) r.getAttributes().getCacheListener();
                List events = cl.getEventHistory();
                {
                    CacheEvent ce = (CacheEvent) events.get(evIdx++);
                    assertEquals(Operation.REGION_CREATE, ce.getOperation());
                }
                {
                    EntryEvent ee = (EntryEvent) events.get(evIdx++);
                    assertEquals(Operation.CREATE, ee.getOperation());
                    assertEquals("createKey", ee.getKey());
                    assertEquals("createValue", ee.getNewValue());
                    assertEquals(null, ee.getOldValue());
                    assertEquals("createCBArg", ee.getCallbackArgument());
                    assertEquals(true, ee.isOriginRemote());
                }
                {
                    EntryEvent ee = (EntryEvent) events.get(evIdx++);
                    assertEquals(Operation.INVALIDATE, ee.getOperation());
                    assertEquals("createKey", ee.getKey());
                    assertEquals(null, ee.getNewValue());
                    assertEquals("createValue", ee.getOldValue());
                    assertEquals("invalidateCBArg", ee.getCallbackArgument());
                    assertEquals(true, ee.isOriginRemote());
                }
                {
                    EntryEvent ee = (EntryEvent) events.get(evIdx++);
                    assertEquals(Operation.UPDATE, ee.getOperation());
                    assertEquals("createKey", ee.getKey());
                    assertEquals("putValue", ee.getNewValue());
                    assertEquals(null, ee.getOldValue());
                    assertEquals("putCBArg", ee.getCallbackArgument());
                    assertEquals(true, ee.isOriginRemote());
                }
                {
                    EntryEvent ee = (EntryEvent) events.get(evIdx++);
                    assertEquals(Operation.DESTROY, ee.getOperation());
                    assertEquals("createKey", ee.getKey());
                    assertEquals(null, ee.getNewValue());
                    assertEquals("putValue", ee.getOldValue());
                    assertEquals("destroyCBArg", ee.getCallbackArgument());
                    assertEquals(true, ee.isOriginRemote());
                }
                {
                    EntryEvent ee = (EntryEvent) events.get(evIdx++);
                    assertEquals(Operation.PUTALL_CREATE, ee.getOperation());
                    assertEquals("aKey", ee.getKey());
                    assertEquals("aValue", ee.getNewValue());
                    assertEquals(null, ee.getOldValue());
                    assertEquals(null, ee.getCallbackArgument());
                    assertEquals(true, ee.isOriginRemote());
                }
                {
                    EntryEvent ee = (EntryEvent) events.get(evIdx++);
                    assertEquals(Operation.PUTALL_CREATE, ee.getOperation());
                    assertEquals("bKey", ee.getKey());
                    assertEquals("bValue", ee.getNewValue());
                    assertEquals(null, ee.getOldValue());
                    assertEquals(null, ee.getCallbackArgument());
                    assertEquals(true, ee.isOriginRemote());
                }
                {
                    RegionEvent re = (RegionEvent) events.get(evIdx++);
                    assertEquals(Operation.REGION_INVALIDATE, re.getOperation());
                    assertEquals("invalidateRegionCBArg", re.getCallbackArgument());
                    assertEquals(true, re.isOriginRemote());
                }
                {
                    RegionEvent re = (RegionEvent) events.get(evIdx++);
                    assertEquals(Operation.REGION_CLEAR, re.getOperation());
                    assertEquals(null, re.getCallbackArgument());
                    assertEquals(true, re.isOriginRemote());
                }
                assertEquals(evIdx, events.size());
            }
        }
    });
}
Also used : CacheException(org.apache.geode.cache.CacheException) CachePerfStats(org.apache.geode.internal.cache.CachePerfStats) SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) TreeMap(java.util.TreeMap) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) RegionEvent(org.apache.geode.cache.RegionEvent) AttributesFactory(org.apache.geode.cache.AttributesFactory) WaitCriterion(org.apache.geode.test.dunit.WaitCriterion) VM(org.apache.geode.test.dunit.VM) EntryEvent(org.apache.geode.cache.EntryEvent) CacheEvent(org.apache.geode.cache.CacheEvent) DistributedRegion(org.apache.geode.internal.cache.DistributedRegion) Region(org.apache.geode.cache.Region) List(java.util.List) DistributedRegion(org.apache.geode.internal.cache.DistributedRegion) Map(java.util.Map) TreeMap(java.util.TreeMap) SubscriptionAttributes(org.apache.geode.cache.SubscriptionAttributes) Ignore(org.junit.Ignore) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Example 22 with DistributedRegion

use of org.apache.geode.internal.cache.DistributedRegion in project geode by apache.

the class BaseCommand method recoverVersionTagForRetriedOperation.

/**
   * If an operation is retried then some server may have seen it already. We cannot apply this
   * operation to the cache without knowing whether a version tag has already been created for it.
   * Otherwise caches that have seen the event already will reject it but others will not, but will
   * have no version tag with which to perform concurrency checks.
   * <p>
   * The client event should have the event identifier from the client and the region affected by
   * the operation.
   */
public boolean recoverVersionTagForRetriedOperation(EntryEventImpl clientEvent) {
    LocalRegion r = clientEvent.getRegion();
    VersionTag tag;
    if (clientEvent.getVersionTag() != null && clientEvent.getVersionTag().isGatewayTag()) {
        tag = r.findVersionTagForGatewayEvent(clientEvent.getEventId());
    } else {
        tag = r.findVersionTagForClientEvent(clientEvent.getEventId());
    }
    if (tag == null) {
        if (r instanceof DistributedRegion || r instanceof PartitionedRegion) {
            // TODO this could be optimized for partitioned regions by sending the key
            // so that the PR could look at an individual bucket for the event
            tag = FindVersionTagOperation.findVersionTag(r, clientEvent.getEventId(), false);
        }
    }
    if (tag != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("recovered version tag {} for replayed operation {}", tag, clientEvent.getEventId());
        }
        clientEvent.setVersionTag(tag);
    }
    return tag != null;
}
Also used : PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) VersionTag(org.apache.geode.internal.cache.versions.VersionTag) LocalRegion(org.apache.geode.internal.cache.LocalRegion) DistributedRegion(org.apache.geode.internal.cache.DistributedRegion)

Example 23 with DistributedRegion

use of org.apache.geode.internal.cache.DistributedRegion in project geode by apache.

the class MultiRegionFunctionExecutor method calculateMemberToRegionMap.

private Map<InternalDistributedMember, Set<String>> calculateMemberToRegionMap() {
    Map<InternalDistributedMember, Set<String>> memberToRegions = new HashMap<InternalDistributedMember, Set<String>>();
    // nodes is maintained for node pruning logic
    Set<InternalDistributedMember> nodes = new HashSet<InternalDistributedMember>();
    for (Region region : regions) {
        DataPolicy dp = region.getAttributes().getDataPolicy();
        if (region instanceof PartitionedRegion) {
            PartitionedRegion pr = (PartitionedRegion) region;
            Set<InternalDistributedMember> prMembers = pr.getRegionAdvisor().advisePrimaryOwners();
            if (pr.isDataStore()) {
                InternalCache cache = (InternalCache) region.getCache();
                // Add local node
                InternalDistributedMember localVm = cache.getMyId();
                Set<String> regions = memberToRegions.get(localVm);
                if (regions == null) {
                    regions = new HashSet<String>();
                }
                regions.add(pr.getFullPath());
                memberToRegions.put(localVm, regions);
            }
            if (prMembers != null) {
                for (InternalDistributedMember member : prMembers) {
                    Set<String> regions = memberToRegions.get(member);
                    if (regions == null) {
                        regions = new HashSet<String>();
                    }
                    regions.add(pr.getFullPath());
                    memberToRegions.put(member, regions);
                }
                nodes.addAll(prMembers);
            }
        } else if (region instanceof DistributedRegion) {
            if (dp.isEmpty() || dp.isNormal()) {
                // Add local members
                DistributedRegion dr = (DistributedRegion) region;
                Set<InternalDistributedMember> replicates = dr.getCacheDistributionAdvisor().adviseInitializedReplicates();
                // if existing nodes contain one of the nodes from replicates
                boolean added = false;
                for (InternalDistributedMember member : replicates) {
                    if (nodes.contains(member)) {
                        added = true;
                        Set<String> regions = memberToRegions.get(member);
                        if (regions == null) {
                            regions = new HashSet<String>();
                        }
                        regions.add(dr.getFullPath());
                        memberToRegions.put(member, regions);
                        break;
                    }
                }
                // if existing nodes set is mutually exclusive to replicates
                if (replicates.size() != 0 && !added) {
                    // select a random replicate
                    InternalDistributedMember member = (InternalDistributedMember) (replicates.toArray()[new Random().nextInt(replicates.size())]);
                    Set<String> regions = memberToRegions.get(member);
                    if (regions == null) {
                        regions = new HashSet<String>();
                    }
                    regions.add(dr.getFullPath());
                    memberToRegions.put(member, regions);
                }
            } else if (dp.withReplication()) {
                InternalCache cache = (InternalCache) region.getCache();
                // Add local node
                InternalDistributedMember local = cache.getMyId();
                Set<String> regions = memberToRegions.get(local);
                if (regions == null) {
                    regions = new HashSet<String>();
                }
                regions.add(region.getFullPath());
                memberToRegions.put(local, regions);
            }
        } else if (region instanceof LocalRegion) {
            InternalCache cache = (InternalCache) region.getCache();
            // Add local node
            InternalDistributedMember local = cache.getMyId();
            Set<String> regions = memberToRegions.get(local);
            if (regions == null) {
                regions = new HashSet<String>();
            }
            regions.add(region.getFullPath());
            memberToRegions.put(local, regions);
        }
    }
    return memberToRegions;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) InternalCache(org.apache.geode.internal.cache.InternalCache) LocalRegion(org.apache.geode.internal.cache.LocalRegion) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) Random(java.util.Random) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) LocalRegion(org.apache.geode.internal.cache.LocalRegion) DistributedRegion(org.apache.geode.internal.cache.DistributedRegion) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) DataPolicy(org.apache.geode.cache.DataPolicy) DistributedRegion(org.apache.geode.internal.cache.DistributedRegion) HashSet(java.util.HashSet)

Example 24 with DistributedRegion

use of org.apache.geode.internal.cache.DistributedRegion in project geode by apache.

the class ExecuteRegionFunction 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;
    Set filter = null;
    byte hasResult = 0;
    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;
            }
        }
        filterSize = clientMessage.getPart(5).getInt();
        if (filterSize != 0) {
            filter = new HashSet();
            partNumber = 6;
            for (int i = 0; i < filterSize; i++) {
                filter.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;
    }
    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;
        }
        this.securityService.authorizeDataWrite();
        // 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, null, false);
        } else {
            execution = new DistributedRegionFunctionExecutor((DistributedRegion) region, filter, args, memberMappedArg, resultSender);
        }
        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 (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 (FunctionException fe) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), fe);
        String message = fe.getMessage();
        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) 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) 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 25 with DistributedRegion

use of org.apache.geode.internal.cache.DistributedRegion in project geode by apache.

the class ExecuteRegionFunction65 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<Object> filter = null;
    byte hasResult = 0;
    int removedNodesSize = 0;
    Set<Object> removedNodesSet = null;
    int filterSize = 0, partNumber = 0;
    CachedRegionHelper crHelper = servConn.getCachedRegionHelper();
    byte functionState = 0;
    try {
        functionState = clientMessage.getPart(0).getSerializedForm()[0];
        if (functionState != 1) {
            hasResult = (byte) ((functionState & 2) - 1);
        } else {
            hasResult = functionState;
        }
        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<Object>();
            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<Object>();
            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;
    }
    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 {
                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;
        }
        this.securityService.authorizeDataWrite();
        // 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 ServerToClientFunctionResultSender65(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 = execution.setIsReExecute();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Executing Function: {} on Server: {} with Execution: {} functionState={} reexecute={} hasResult={}", functionObject.getId(), servConn, execution, functionState, isReExecute, hasResult);
        }
        if (hasResult == 1) {
            if (function instanceof String) {
                switch(functionState) {
                    case AbstractExecution.NO_HA_HASRESULT_NO_OPTIMIZEFORWRITE:
                        execution.execute((String) function, true, false, false).getResult();
                        break;
                    case AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE:
                        execution.execute((String) function, true, true, false).getResult();
                        break;
                    case AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE:
                        execution.execute((String) function, true, true, true).getResult();
                        break;
                    case AbstractExecution.NO_HA_HASRESULT_OPTIMIZEFORWRITE:
                        execution.execute((String) function, true, false, true).getResult();
                        break;
                }
            } else {
                execution.execute(functionObject).getResult();
            }
        } else {
            if (function instanceof String) {
                switch(functionState) {
                    case AbstractExecution.NO_HA_NO_HASRESULT_NO_OPTIMIZEFORWRITE:
                        execution.execute((String) function, false, false, false);
                        break;
                    case AbstractExecution.NO_HA_NO_HASRESULT_OPTIMIZEFORWRITE:
                        execution.execute((String) function, false, false, true);
                        break;
                }
            } 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 : 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) AbstractExecution(org.apache.geode.internal.cache.execute.AbstractExecution) PartitionedRegionFunctionExecutor(org.apache.geode.internal.cache.execute.PartitionedRegionFunctionExecutor) ExecuteFunctionOperationContext(org.apache.geode.cache.operations.ExecuteFunctionOperationContext) ServerToClientFunctionResultSender65(org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender65) 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)

Aggregations

DistributedRegion (org.apache.geode.internal.cache.DistributedRegion)36 Region (org.apache.geode.cache.Region)25 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)16 LocalRegion (org.apache.geode.internal.cache.LocalRegion)14 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)9 VM (org.apache.geode.test.dunit.VM)9 Test (org.junit.Test)9 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)8 Cache (org.apache.geode.cache.Cache)7 Host (org.apache.geode.test.dunit.Host)7 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)7 FunctionException (org.apache.geode.cache.execute.FunctionException)6 IOException (java.io.IOException)5 AttributesFactory (org.apache.geode.cache.AttributesFactory)5 CacheException (org.apache.geode.cache.CacheException)5 IgnoredException (org.apache.geode.test.dunit.IgnoredException)5 WaitCriterion (org.apache.geode.test.dunit.WaitCriterion)5 Set (java.util.Set)4 CancelException (org.apache.geode.CancelException)4 CacheLoaderException (org.apache.geode.cache.CacheLoaderException)4