Search in sources :

Example 36 with BucketRegion

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

the class AbstractGatewaySenderEventProcessor method processQueue.

protected void processQueue() {
    final boolean isDebugEnabled = logger.isDebugEnabled();
    final boolean isTraceEnabled = logger.isTraceEnabled();
    final int batchTimeInterval = sender.getBatchTimeInterval();
    final GatewaySenderStats statistics = this.sender.getStatistics();
    if (isDebugEnabled) {
        logger.debug("STARTED processQueue {}", this.getId());
    }
    // list of the events peeked from queue
    List<GatewaySenderEventImpl> events = null;
    // list of the above peeked events which are filtered through the filters attached
    List<GatewaySenderEventImpl> filteredList = new ArrayList<GatewaySenderEventImpl>();
    // list of the PDX events which are peeked from pDX region and needs to go acrossthe site
    List<GatewaySenderEventImpl> pdxEventsToBeDispatched = new ArrayList<GatewaySenderEventImpl>();
    // list of filteredList + pdxEventsToBeDispatched events
    List<GatewaySenderEventImpl> eventsToBeDispatched = new ArrayList<GatewaySenderEventImpl>();
    for (; ; ) {
        if (stopped()) {
            break;
        }
        try {
            // Check if paused. If so, wait for resumption
            if (this.isPaused) {
                waitForResumption();
            }
            // Peek a batch
            if (isDebugEnabled) {
                logger.debug("Attempting to peek a batch of {} events", this.batchSize);
            }
            for (; ; ) {
                // check before sleeping
                if (stopped()) {
                    if (isDebugEnabled) {
                        logger.debug("GatewaySenderEventProcessor is stopped. Returning without peeking events.");
                    }
                    break;
                }
                // Check if paused. If so, wait for resumption
                if (this.isPaused) {
                    waitForResumption();
                }
                // We need to initialize connection in dispatcher before sending first
                // batch here ONLY, because we need GatewayReceiver's version for
                // filtering VERSION_ACTION events from being sent.
                boolean sendUpdateVersionEvents = shouldSendVersionEvents(this.dispatcher);
                // sleep a little bit, look for events
                boolean interrupted = Thread.interrupted();
                try {
                    if (resetLastPeekedEvents) {
                        resetLastPeekedEvents();
                        resetLastPeekedEvents = false;
                    }
                    {
                    // Below code was added to consider the case of queue region is
                    // destroyed due to userPRs localdestroy or destroy operation.
                    // In this case we were waiting for queue region to get created
                    // and then only peek from the region queue.
                    // With latest change of multiple PR with single ParalleSender, we
                    // cant wait for particular regionqueue to get recreated as there
                    // will be other region queue from which events can be picked
                    /*
               * // Check if paused. If so, wait for resumption if (this.isPaused) {
               * waitForResumption(); }
               * 
               * synchronized (this.getQueue()) { // its quite possible that the queue region is //
               * destroyed(userRegion // localdestroy destroys shadow region locally). In this case
               * // better to // wait for shadows region to get recreated instead of keep loop //
               * for peeking events if (this.getQueue().getRegion() == null ||
               * this.getQueue().getRegion().isDestroyed()) { try { this.getQueue().wait();
               * continue; // this continue is important to recheck the // conditions of stop/ pause
               * after the wait of 1 sec } catch (InterruptedException e1) {
               * Thread.currentThread().interrupt(); } } }
               */
                    }
                    events = this.queue.peek(this.batchSize, batchTimeInterval);
                } catch (InterruptedException e) {
                    interrupted = true;
                    this.sender.getCancelCriterion().checkCancelInProgress(e);
                    // keep trying
                    continue;
                } finally {
                    if (interrupted) {
                        Thread.currentThread().interrupt();
                    }
                }
                if (events.isEmpty()) {
                    // nothing to do!
                    continue;
                }
                // this list is access by ack reader thread so create new every time. #50220
                filteredList = new ArrayList<GatewaySenderEventImpl>();
                filteredList.addAll(events);
                // remove all events whose serialized value is no longer available
                if (this.exception != null && this.exception.getCause() != null && this.exception.getCause() instanceof IllegalStateException) {
                    for (Iterator<GatewaySenderEventImpl> i = filteredList.iterator(); i.hasNext(); ) {
                        GatewaySenderEventImpl event = i.next();
                        if (event.isSerializedValueNotAvailable()) {
                            i.remove();
                        }
                    }
                    this.exception = null;
                }
                // Filter the events
                for (GatewayEventFilter filter : sender.getGatewayEventFilters()) {
                    Iterator<GatewaySenderEventImpl> itr = filteredList.iterator();
                    while (itr.hasNext()) {
                        GatewayQueueEvent event = itr.next();
                        // version is < 7.0.1, especially to prevent another loop over events.
                        if (!sendUpdateVersionEvents && event.getOperation() == Operation.UPDATE_VERSION_STAMP) {
                            if (isTraceEnabled) {
                                logger.trace("Update Event Version event: {} removed from Gateway Sender queue: {}", event, sender);
                            }
                            itr.remove();
                            statistics.incEventsNotQueued();
                            continue;
                        }
                        boolean transmit = filter.beforeTransmit(event);
                        if (!transmit) {
                            if (isDebugEnabled) {
                                logger.debug("{}: Did not transmit event due to filtering: {}", sender.getId(), event);
                            }
                            itr.remove();
                            statistics.incEventsFiltered();
                        }
                    }
                }
                // AsyncEventQueue since possibleDuplicate flag is not used in WAN.
                if (this.getSender().isParallel() && (this.getDispatcher() instanceof GatewaySenderEventCallbackDispatcher)) {
                    Iterator<GatewaySenderEventImpl> itr = filteredList.iterator();
                    while (itr.hasNext()) {
                        GatewaySenderEventImpl event = (GatewaySenderEventImpl) itr.next();
                        PartitionedRegion qpr = null;
                        if (this.getQueue() instanceof ConcurrentParallelGatewaySenderQueue) {
                            qpr = ((ConcurrentParallelGatewaySenderQueue) this.getQueue()).getRegion(event.getRegionPath());
                        } else {
                            qpr = ((ParallelGatewaySenderQueue) this.getQueue()).getRegion(event.getRegionPath());
                        }
                        int bucketId = event.getBucketId();
                        // primary, then set possibleDuplicate to true on the event
                        if (qpr != null) {
                            BucketRegion bucket = qpr.getDataStore().getLocalBucketById(bucketId);
                            if (bucket == null || !bucket.getBucketAdvisor().isPrimary()) {
                                event.setPossibleDuplicate(true);
                                if (isDebugEnabled) {
                                    logger.debug("Bucket id: {} is no longer primary on this node. The event: {} will be dispatched from this node with possibleDuplicate set to true.", bucketId, event);
                                }
                            }
                        }
                    }
                }
                eventsToBeDispatched.clear();
                if (!(this.dispatcher instanceof GatewaySenderEventCallbackDispatcher)) {
                    // store the batch before dispatching so it can be retrieved by the ack thread.
                    List<GatewaySenderEventImpl>[] eventsArr = (List<GatewaySenderEventImpl>[]) new List[2];
                    eventsArr[0] = events;
                    eventsArr[1] = filteredList;
                    this.batchIdToEventsMap.put(getBatchId(), eventsArr);
                    // find out PDX event and append it in front of the list
                    pdxEventsToBeDispatched = addPDXEvent();
                    eventsToBeDispatched.addAll(pdxEventsToBeDispatched);
                    if (!pdxEventsToBeDispatched.isEmpty()) {
                        this.batchIdToPDXEventsMap.put(getBatchId(), pdxEventsToBeDispatched);
                    }
                }
                eventsToBeDispatched.addAll(filteredList);
                // Conflate the batch. Event conflation only occurs on the queue.
                // Once an event has been peeked into a batch, it won't be
                // conflated. So if events go through the queue quickly (as in the
                // no-ack case), then multiple events for the same key may end up in
                // the batch.
                List conflatedEventsToBeDispatched = conflate(eventsToBeDispatched);
                if (isDebugEnabled) {
                    logBatchFine("During normal processing, dispatching the following ", conflatedEventsToBeDispatched);
                }
                boolean success = this.dispatcher.dispatchBatch(conflatedEventsToBeDispatched, sender.isRemoveFromQueueOnException(), false);
                if (success) {
                    if (isDebugEnabled) {
                        logger.debug("During normal processing, successfully dispatched {} events (batch #{})", conflatedEventsToBeDispatched.size(), getBatchId());
                    }
                    removeEventFromFailureMap(getBatchId());
                } else {
                    if (!skipFailureLogging(getBatchId())) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.GatewayImpl_EVENT_QUEUE_DISPATCH_FAILED, new Object[] { filteredList.size(), getBatchId() }));
                    }
                }
                // check again, don't do post-processing if we're stopped.
                if (stopped()) {
                    break;
                }
                // If the batch is successfully processed, remove it from the queue.
                if (success) {
                    if (this.dispatcher instanceof GatewaySenderEventCallbackDispatcher) {
                        handleSuccessfulBatchDispatch(conflatedEventsToBeDispatched, events);
                    } else {
                        incrementBatchId();
                    }
                    // isDispatched
                    for (GatewaySenderEventImpl pdxGatewaySenderEvent : pdxEventsToBeDispatched) {
                        pdxGatewaySenderEvent.isDispatched = true;
                    }
                    if (TEST_HOOK) {
                        this.numEventsDispatched += conflatedEventsToBeDispatched.size();
                    }
                } else // successful batch
                {
                    // The batch was unsuccessful.
                    if (this.dispatcher instanceof GatewaySenderEventCallbackDispatcher) {
                        handleUnSuccessfulBatchDispatch(events);
                        this.resetLastPeekedEvents = true;
                    } else {
                        handleUnSuccessfulBatchDispatch(events);
                        if (!resetLastPeekedEvents) {
                            while (!this.dispatcher.dispatchBatch(conflatedEventsToBeDispatched, sender.isRemoveFromQueueOnException(), true)) {
                                if (isDebugEnabled) {
                                    logger.debug("During normal processing, unsuccessfully dispatched {} events (batch #{})", conflatedEventsToBeDispatched.size(), getBatchId());
                                }
                                if (stopped() || resetLastPeekedEvents) {
                                    break;
                                }
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException ie) {
                                    Thread.currentThread().interrupt();
                                }
                            }
                            incrementBatchId();
                        }
                    }
                }
                // unsuccessful batch
                if (logger.isDebugEnabled()) {
                    logger.debug("Finished processing events (batch #{})", (getBatchId() - 1));
                }
            }
        // for
        } catch (RegionDestroyedException e) {
            // setting this flag will ensure that already peeked events will make
            // it to the next batch before new events are peeked (fix for #48784)
            this.resetLastPeekedEvents = true;
            // shadow PR is also locally destroyed
            if (logger.isDebugEnabled()) {
                logger.debug("Observed RegionDestroyedException on Queue's region.");
            }
        } catch (CancelException e) {
            logger.debug("Caught cancel exception", e);
            setIsStopped(true);
        } catch (VirtualMachineError err) {
            SystemFailure.initiateFailure(err);
            // now, so don't let this thread continue.
            throw err;
        } catch (Throwable e) {
            // 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();
            // Well, OK. Some strange nonfatal thing.
            if (stopped()) {
                // don't complain, just exit.
                return;
            }
            if (events != null) {
                handleUnSuccessfulBatchDispatch(events);
            }
            this.resetLastPeekedEvents = true;
            if (e instanceof GatewaySenderException) {
                Throwable cause = e.getCause();
                if (cause instanceof IOException || e instanceof GatewaySenderConfigurationException) {
                    continue;
                }
            }
            // We'll log it but continue on with the next batch.
            logger.warn(LocalizedMessage.create(LocalizedStrings.GatewayImpl_AN_EXCEPTION_OCCURRED_THE_DISPATCHER_WILL_CONTINUE), e);
        }
    }
// for
}
Also used : GatewayQueueEvent(org.apache.geode.cache.wan.GatewayQueueEvent) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) GatewayEventFilter(org.apache.geode.cache.wan.GatewayEventFilter) IOException(java.io.IOException) BucketRegion(org.apache.geode.internal.cache.BucketRegion) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) ConcurrentParallelGatewaySenderQueue(org.apache.geode.internal.cache.wan.parallel.ConcurrentParallelGatewaySenderQueue) CancelException(org.apache.geode.CancelException)

Example 37 with BucketRegion

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

the class ResourceManagerDUnitTest method testRemoveColocatedBuckets.

/**
   * Creates a chain of three colocated PRs and then calls removeBucket to make sure that all
   * colocated buckets are removed together.
   */
// GEODE-928: RemoveBucketMessage failure?
@Category(FlakyTest.class)
@Test
public void testRemoveColocatedBuckets() {
    final String[] regionPath = new String[] { getUniqueName() + "-PR-0", getUniqueName() + "-PR-1", getUniqueName() + "-PR-2" };
    final int numBuckets = 1;
    final int redundantCopies = 1;
    final int localMaxMemory = 100;
    createRegion(Host.getHost(0).getVM(0), regionPath[0], localMaxMemory, numBuckets, redundantCopies);
    createRegion(Host.getHost(0).getVM(1), regionPath[0], localMaxMemory, numBuckets, redundantCopies);
    createRegion(Host.getHost(0).getVM(0), regionPath[1], localMaxMemory, numBuckets, redundantCopies, regionPath[0]);
    createRegion(Host.getHost(0).getVM(1), regionPath[1], localMaxMemory, numBuckets, redundantCopies, regionPath[0]);
    createRegion(Host.getHost(0).getVM(0), regionPath[2], localMaxMemory, numBuckets, redundantCopies, regionPath[1]);
    createRegion(Host.getHost(0).getVM(1), regionPath[2], localMaxMemory, numBuckets, redundantCopies, regionPath[1]);
    final Integer bucketKey = Integer.valueOf(0);
    final byte[] value = new byte[1];
    createBucket(0, regionPath[0], bucketKey, value);
    createBucket(0, regionPath[1], bucketKey, value);
    createBucket(0, regionPath[2], bucketKey, value);
    // identify the members and their config values
    final InternalDistributedMember[] members = new InternalDistributedMember[2];
    final long[] memberSizes = new long[members.length];
    final int[] memberBucketCounts = new int[members.length];
    final int[] memberPrimaryCounts = new int[members.length];
    fillValidationArrays(members, memberSizes, memberBucketCounts, memberPrimaryCounts, regionPath[0]);
    int primaryVM = -1;
    int otherVM = -1;
    for (int i = 0; i < memberPrimaryCounts.length; i++) {
        if (memberPrimaryCounts[i] == 0) {
            otherVM = i;
        } else if (memberPrimaryCounts[i] == 1) {
            // found the primary
            primaryVM = i;
        }
    }
    assertTrue(primaryVM > -1);
    assertTrue(otherVM > -1);
    assertTrue(primaryVM != otherVM);
    final int finalOtherVM = otherVM;
    Host.getHost(0).getVM(otherVM).invoke(new SerializableRunnable() {

        public void run() {
            for (int i = 0; i < regionPath.length; i++) {
                PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[i]);
                Bucket bucket = pr.getRegionAdvisor().getBucket(0);
                assertTrue("Target member is not hosting bucket to remove for " + regionPath[i], bucket.isHosting());
                assertNotNull("Bucket is null on target member for " + regionPath[i], bucket);
                assertNotNull("BucketRegion is null on target member for " + regionPath[i], bucket.getBucketAdvisor().getProxyBucketRegion().getHostedBucketRegion());
            }
        }
    });
    boolean sentRemoveBucket = ((Boolean) Host.getHost(0).getVM(primaryVM).invoke(new SerializableCallable() {

        public Object call() {
            InternalDistributedMember recipient = members[finalOtherVM];
            PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[0]);
            RemoveBucketResponse response = RemoveBucketMessage.send(recipient, pr, 0, false);
            if (response != null) {
                response.waitForRepliesUninterruptibly();
                return true;
            } else {
                return Boolean.FALSE;
            }
        }
    })).booleanValue();
    assertTrue("Failed to get reply to RemoveBucketMessage", sentRemoveBucket);
    Host.getHost(0).getVM(otherVM).invoke(new SerializableRunnable() {

        public void run() {
            for (int i = 0; i < regionPath.length; i++) {
                PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[i]);
                Bucket bucket = pr.getRegionAdvisor().getBucket(0);
                BucketRegion bucketRegion = bucket.getBucketAdvisor().getProxyBucketRegion().getHostedBucketRegion();
                assertFalse("Target member is still hosting removed bucket for " + regionPath[i], bucket.isHosting());
                assertNull("BucketRegion is not null on target member for " + regionPath[i], bucketRegion);
            }
        }
    });
}
Also used : SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) RemoveBucketResponse(org.apache.geode.internal.cache.partitioned.RemoveBucketMessage.RemoveBucketResponse) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) BucketRegion(org.apache.geode.internal.cache.BucketRegion) Bucket(org.apache.geode.internal.cache.partitioned.Bucket) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) Category(org.junit.experimental.categories.Category) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) FlakyTest(org.apache.geode.test.junit.categories.FlakyTest) Test(org.junit.Test)

Example 38 with BucketRegion

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

the class ResourceManagerDUnitTest method testCreateRedundantColocatedBuckets.

/**
   * Creates colocated buckets on two members. Then brings up a third member and creates an extra
   * redundant copy of the buckets on it.
   */
@Test
public void testCreateRedundantColocatedBuckets() {
    final String[] regionPath = new String[] { getUniqueName() + "-PR-0", getUniqueName() + "-PR-1", getUniqueName() + "-PR-2" };
    final int numBuckets = 1;
    final int redundantCopies = 1;
    final int localMaxMemory = 100;
    // create the PartitionedRegion on the first two members
    createRegion(Host.getHost(0).getVM(0), regionPath[0], localMaxMemory, numBuckets, redundantCopies);
    createRegion(Host.getHost(0).getVM(1), regionPath[0], localMaxMemory, numBuckets, redundantCopies);
    createRegion(Host.getHost(0).getVM(0), regionPath[1], localMaxMemory, numBuckets, redundantCopies, regionPath[0]);
    createRegion(Host.getHost(0).getVM(1), regionPath[1], localMaxMemory, numBuckets, redundantCopies, regionPath[0]);
    createRegion(Host.getHost(0).getVM(0), regionPath[2], localMaxMemory, numBuckets, redundantCopies, regionPath[1]);
    createRegion(Host.getHost(0).getVM(1), regionPath[2], localMaxMemory, numBuckets, redundantCopies, regionPath[1]);
    // create the bucket on the first two members
    final Integer bucketKey = Integer.valueOf(0);
    final byte[] value = new byte[1];
    createBucket(0, regionPath[0], bucketKey, value);
    createBucket(0, regionPath[1], bucketKey, value);
    createBucket(0, regionPath[2], bucketKey, value);
    // identify the primaryVM and otherVM
    final InternalDistributedMember[] members = new InternalDistributedMember[2];
    final long[] memberSizes = new long[members.length];
    final int[] memberBucketCounts = new int[members.length];
    final int[] memberPrimaryCounts = new int[members.length];
    fillValidationArrays(members, memberSizes, memberBucketCounts, memberPrimaryCounts, regionPath[0]);
    int primaryVM = -1;
    int otherVM = -1;
    for (int i = 0; i < memberPrimaryCounts.length; i++) {
        if (memberPrimaryCounts[i] == 0) {
            otherVM = i;
        } else if (memberPrimaryCounts[i] == 1) {
            // found the primary
            primaryVM = i;
        }
    }
    assertTrue(primaryVM > -1);
    assertTrue(otherVM > -1);
    assertTrue(primaryVM != otherVM);
    final int finalOtherVM = otherVM;
    // make sure colocated buckets exists on otherVM
    Host.getHost(0).getVM(otherVM).invoke(new SerializableRunnable() {

        public void run() {
            for (int i = 0; i < regionPath.length; i++) {
                PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[i]);
                Bucket bucket = pr.getRegionAdvisor().getBucket(0);
                assertNotNull("Bucket is null on SRC member for " + regionPath[i], bucket);
                BucketRegion bucketRegion = bucket.getBucketAdvisor().getProxyBucketRegion().getHostedBucketRegion();
                assertTrue("SRC member is not hosting bucket for " + regionPath[i], bucket.isHosting());
                assertNotNull("BucketRegion is null on SRC member for " + regionPath[i], bucketRegion);
                int redundancy = bucket.getBucketAdvisor().getBucketRedundancy();
                assertEquals("SRC member reports redundancy " + redundancy + " for " + regionPath[i], redundantCopies, redundancy);
            }
        }
    });
    // create newVM to create extra redundant buckets on
    final int finalNewVM = 2;
    createRegion(Host.getHost(0).getVM(finalNewVM), regionPath[0], localMaxMemory, numBuckets, redundantCopies);
    createRegion(Host.getHost(0).getVM(finalNewVM), regionPath[1], localMaxMemory, numBuckets, redundantCopies, regionPath[0]);
    createRegion(Host.getHost(0).getVM(finalNewVM), regionPath[2], localMaxMemory, numBuckets, redundantCopies, regionPath[1]);
    // create extra redundant buckets on finalNewVM
    Host.getHost(0).getVM(finalNewVM).invoke(new SerializableRunnable() {

        public void run() {
            for (int i = 0; i < regionPath.length; i++) {
                PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[i]);
                if (i == 0) {
                    // only call createRedundantBucket on leader PR
                    pr.getDataStore().createRedundantBucket(0, false, new InternalDistributedMember());
                }
                Bucket bucket = pr.getRegionAdvisor().getBucket(0);
                assertNotNull("Bucket is null on DST member", bucket);
                BucketRegion bucketRegion = bucket.getBucketAdvisor().getProxyBucketRegion().getHostedBucketRegion();
                assertTrue("DST member is not hosting bucket", bucket.isHosting());
                assertNotNull("BucketRegion is null on DST member", bucketRegion);
                assertEquals(redundantCopies + 1, bucket.getBucketAdvisor().getBucketRedundancy());
            }
        }
    });
}
Also used : SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) BucketRegion(org.apache.geode.internal.cache.BucketRegion) Bucket(org.apache.geode.internal.cache.partitioned.Bucket) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) FlakyTest(org.apache.geode.test.junit.categories.FlakyTest) Test(org.junit.Test)

Example 39 with BucketRegion

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

the class PartitionRegionHelperDUnitTest method testMembersForKey.

@Test
public void testMembersForKey() throws Exception {
    Host host = Host.getHost(0);
    VM accessor = host.getVM(0);
    VM ds1 = host.getVM(1);
    VM ds2 = host.getVM(2);
    VM ds3 = host.getVM(3);
    final String prName = getUniqueName();
    final int tb = 11;
    final int rc = 1;
    accessor.invoke(new SerializableRunnable("createAccessor") {

        public void run() {
            Cache cache = getCache();
            AttributesFactory attr = new AttributesFactory();
            attr.setPartitionAttributes(new PartitionAttributesFactory().setLocalMaxMemory(0).setRedundantCopies(rc).setTotalNumBuckets(tb).create());
            cache.createRegion(prName, attr.create());
        }
    });
    HashMap<DistributedMember, VM> d2v = new HashMap<DistributedMember, VM>();
    SerializableCallable createPrRegion = new SerializableCallable("createDataStore") {

        public Object call() throws Exception {
            Cache cache = getCache();
            AttributesFactory attr = new AttributesFactory();
            attr.setPartitionAttributes(new PartitionAttributesFactory().setRedundantCopies(rc).setTotalNumBuckets(tb).create());
            cache.createRegion(prName, attr.create());
            return cache.getDistributedSystem().getDistributedMember();
        }
    };
    DistributedMember dm = (DistributedMember) ds1.invoke(createPrRegion);
    d2v.put(dm, ds1);
    dm = (DistributedMember) ds2.invoke(createPrRegion);
    d2v.put(dm, ds2);
    dm = (DistributedMember) ds3.invoke(createPrRegion);
    d2v.put(dm, ds3);
    final Integer buk0Key1 = new Integer(0);
    final Integer buk0Key2 = new Integer(buk0Key1.intValue() + tb);
    final Integer buk1Key1 = new Integer(1);
    accessor.invoke(new CacheSerializableRunnable("nonPRcheck") {

        @SuppressWarnings("unchecked")
        @Override
        public void run2() throws CacheException {
            AttributesFactory attr = new AttributesFactory();
            {
                attr.setScope(Scope.LOCAL);
                Region lr = getCache().createRegion(prName + "lr", attr.create());
                try {
                    // no-pr check
                    nonPRMemberForKey(lr, buk0Key1);
                } finally {
                    lr.destroyRegion();
                }
            }
            {
                attr = new AttributesFactory();
                attr.setScope(Scope.DISTRIBUTED_ACK);
                Region dr = getCache().createRegion(prName + "dr", attr.create());
                try {
                    // no-pr check
                    nonPRMemberForKey(dr, buk0Key1);
                } finally {
                    dr.destroyRegion();
                }
            }
        }

        private void nonPRMemberForKey(Region lr, final Object key) {
            try {
                PartitionRegionHelper.getPrimaryMemberForKey(lr, key);
                fail();
            } catch (IllegalArgumentException expected) {
            }
            try {
                PartitionRegionHelper.getAllMembersForKey(lr, key);
                fail();
            } catch (IllegalArgumentException expected) {
            }
            try {
                PartitionRegionHelper.getRedundantMembersForKey(lr, key);
                fail();
            } catch (IllegalArgumentException expected) {
            }
        }
    });
    Object[] noKeyThenKeyStuff = (Object[]) accessor.invoke(new SerializableCallable("noKeyThenKey") {

        public Object call() throws Exception {
            Region<Integer, String> r = getCache().getRegion(prName);
            // NPE check
            try {
                PartitionRegionHelper.getPrimaryMemberForKey(r, null);
                fail();
            } catch (IllegalStateException expected) {
            }
            try {
                PartitionRegionHelper.getAllMembersForKey(r, null);
                fail();
            } catch (IllegalStateException expected) {
            }
            try {
                PartitionRegionHelper.getRedundantMembersForKey(r, null);
                fail();
            } catch (IllegalStateException expected) {
            }
            // buk0
            assertNull(PartitionRegionHelper.getPrimaryMemberForKey(r, buk0Key1));
            assertTrue(PartitionRegionHelper.getAllMembersForKey(r, buk0Key1).isEmpty());
            assertTrue(PartitionRegionHelper.getRedundantMembersForKey(r, buk0Key1).isEmpty());
            // buk1
            assertNull(PartitionRegionHelper.getPrimaryMemberForKey(r, buk1Key1));
            assertTrue(PartitionRegionHelper.getAllMembersForKey(r, buk1Key1).isEmpty());
            assertTrue(PartitionRegionHelper.getRedundantMembersForKey(r, buk1Key1).isEmpty());
            r.put(buk0Key1, "zero");
            // buk0, key1
            DistributedMember key1Pri = PartitionRegionHelper.getPrimaryMemberForKey(r, buk0Key1);
            assertNotNull(key1Pri);
            Set<DistributedMember> buk0AllMems = PartitionRegionHelper.getAllMembersForKey(r, buk0Key1);
            assertEquals(rc + 1, buk0AllMems.size());
            Set<DistributedMember> buk0RedundantMems = PartitionRegionHelper.getRedundantMembersForKey(r, buk0Key1);
            assertEquals(rc, buk0RedundantMems.size());
            DistributedMember me = r.getCache().getDistributedSystem().getDistributedMember();
            try {
                buk0AllMems.add(me);
                fail();
            } catch (UnsupportedOperationException expected) {
            }
            try {
                buk0AllMems.remove(me);
                fail();
            } catch (UnsupportedOperationException expected) {
            }
            try {
                buk0RedundantMems.add(me);
                fail();
            } catch (UnsupportedOperationException expected) {
            }
            try {
                buk0RedundantMems.remove(me);
                fail();
            } catch (UnsupportedOperationException expected) {
            }
            assertTrue(buk0AllMems.containsAll(buk0RedundantMems));
            assertTrue(buk0AllMems.contains(key1Pri));
            assertTrue(!buk0RedundantMems.contains(key1Pri));
            // buk0, key2
            DistributedMember key2Pri = PartitionRegionHelper.getPrimaryMemberForKey(r, buk0Key2);
            assertNotNull(key2Pri);
            buk0AllMems = PartitionRegionHelper.getAllMembersForKey(r, buk0Key2);
            assertEquals(rc + 1, buk0AllMems.size());
            buk0RedundantMems = PartitionRegionHelper.getRedundantMembersForKey(r, buk0Key2);
            assertEquals(rc, buk0RedundantMems.size());
            assertTrue(buk0AllMems.containsAll(buk0RedundantMems));
            assertTrue(buk0AllMems.contains(key2Pri));
            assertTrue(!buk0RedundantMems.contains(key2Pri));
            // buk1
            assertNull(PartitionRegionHelper.getPrimaryMemberForKey(r, buk1Key1));
            assertTrue(PartitionRegionHelper.getAllMembersForKey(r, buk1Key1).isEmpty());
            assertTrue(PartitionRegionHelper.getRedundantMembersForKey(r, buk1Key1).isEmpty());
            return new Object[] { key1Pri, buk0AllMems, buk0RedundantMems };
        }
    });
    final DistributedMember buk0Key1Pri = (DistributedMember) noKeyThenKeyStuff[0];
    final Set<DistributedMember> buk0AllMems = (Set<DistributedMember>) noKeyThenKeyStuff[1];
    final Set<DistributedMember> buk0Redundants = (Set<DistributedMember>) noKeyThenKeyStuff[2];
    VM buk0Key1PriVM = d2v.get(buk0Key1Pri);
    buk0Key1PriVM.invoke(new CacheSerializableRunnable("assertPrimaryness") {

        @Override
        public void run2() throws CacheException {
            PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(prName);
            Integer bucketId = new Integer(PartitionedRegionHelper.getHashKey(pr, null, buk0Key1, null, null));
            try {
                BucketRegion buk0 = pr.getDataStore().getInitializedBucketForId(buk0Key1, bucketId);
                assertNotNull(buk0);
                assertTrue(buk0.getBucketAdvisor().isPrimary());
            } catch (ForceReattemptException e) {
                LogWriterUtils.getLogWriter().severe(e);
                fail();
            }
        }
    });
    CacheSerializableRunnable assertHasBucket = new CacheSerializableRunnable("assertHasBucketAndKey") {

        @Override
        public void run2() throws CacheException {
            PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(prName);
            Integer bucketId = new Integer(PartitionedRegionHelper.getHashKey(pr, null, buk0Key1, null, null));
            try {
                BucketRegion buk0 = pr.getDataStore().getInitializedBucketForId(buk0Key1, bucketId);
                assertNotNull(buk0);
                Entry k1e = buk0.getEntry(buk0Key1);
                assertNotNull(k1e);
            } catch (ForceReattemptException e) {
                LogWriterUtils.getLogWriter().severe(e);
                fail();
            }
        }
    };
    for (DistributedMember bom : buk0AllMems) {
        VM v = d2v.get(bom);
        LogWriterUtils.getLogWriter().info("Visiting bucket owner member " + bom + " for key " + buk0Key1);
        v.invoke(assertHasBucket);
    }
    CacheSerializableRunnable assertRed = new CacheSerializableRunnable("assertRedundant") {

        @Override
        public void run2() throws CacheException {
            PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(prName);
            Integer bucketId = new Integer(PartitionedRegionHelper.getHashKey(pr, null, buk0Key1, null, null));
            try {
                BucketRegion buk0 = pr.getDataStore().getInitializedBucketForId(buk0Key1, bucketId);
                assertNotNull(buk0);
                assertFalse(buk0.getBucketAdvisor().isPrimary());
            } catch (ForceReattemptException e) {
                LogWriterUtils.getLogWriter().severe(e);
                fail();
            }
        }
    };
    for (DistributedMember redm : buk0Redundants) {
        VM v = d2v.get(redm);
        LogWriterUtils.getLogWriter().info("Visiting redundant member " + redm + " for key " + buk0Key1);
        v.invoke(assertRed);
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) CacheException(org.apache.geode.cache.CacheException) Entry(org.apache.geode.cache.Region.Entry) AttributesFactory(org.apache.geode.cache.AttributesFactory) PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) Host(org.apache.geode.test.dunit.Host) PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) ForceReattemptException(org.apache.geode.internal.cache.ForceReattemptException) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) BucketRegion(org.apache.geode.internal.cache.BucketRegion) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) DistributedMember(org.apache.geode.distributed.DistributedMember) BucketRegion(org.apache.geode.internal.cache.BucketRegion) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) Cache(org.apache.geode.cache.Cache) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Example 40 with BucketRegion

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

the class ResourceManagerDUnitTest method testMoveColocatedBuckets.

/**
   * Creates colocated buckets on two members. Then brings up a third member and moves the
   * non-primary colocated buckets to it.
   */
@Test
public void testMoveColocatedBuckets() {
    final String[] regionPath = new String[] { getUniqueName() + "-PR-0", getUniqueName() + "-PR-1", getUniqueName() + "-PR-2" };
    final int numBuckets = 1;
    final int redundantCopies = 1;
    final int localMaxMemory = 100;
    // create the PartitionedRegion on the first two members
    createRegion(Host.getHost(0).getVM(0), regionPath[0], localMaxMemory, numBuckets, redundantCopies);
    createRegion(Host.getHost(0).getVM(1), regionPath[0], localMaxMemory, numBuckets, redundantCopies);
    createRegion(Host.getHost(0).getVM(0), regionPath[1], localMaxMemory, numBuckets, redundantCopies, regionPath[0]);
    createRegion(Host.getHost(0).getVM(1), regionPath[1], localMaxMemory, numBuckets, redundantCopies, regionPath[0]);
    createRegion(Host.getHost(0).getVM(0), regionPath[2], localMaxMemory, numBuckets, redundantCopies, regionPath[1]);
    createRegion(Host.getHost(0).getVM(1), regionPath[2], localMaxMemory, numBuckets, redundantCopies, regionPath[1]);
    // create the bucket on the first two members
    final Integer bucketKey = Integer.valueOf(0);
    final byte[] value = new byte[1];
    createBucket(0, regionPath[0], bucketKey, value);
    createBucket(0, regionPath[1], bucketKey, value);
    createBucket(0, regionPath[2], bucketKey, value);
    // identify the primaryVM and otherVM
    final InternalDistributedMember[] members = new InternalDistributedMember[2];
    final long[] memberSizes = new long[members.length];
    final int[] memberBucketCounts = new int[members.length];
    final int[] memberPrimaryCounts = new int[members.length];
    fillValidationArrays(members, memberSizes, memberBucketCounts, memberPrimaryCounts, regionPath[0]);
    int primaryVM = -1;
    int otherVM = -1;
    for (int i = 0; i < memberPrimaryCounts.length; i++) {
        if (memberPrimaryCounts[i] == 0) {
            otherVM = i;
        } else if (memberPrimaryCounts[i] == 1) {
            // found the primary
            primaryVM = i;
        }
    }
    assertTrue(primaryVM > -1);
    assertTrue(otherVM > -1);
    assertTrue(primaryVM != otherVM);
    final int finalOtherVM = otherVM;
    // make sure colocated buckets exists on otherVM
    Host.getHost(0).getVM(otherVM).invoke(new SerializableRunnable() {

        public void run() {
            for (int i = 0; i < regionPath.length; i++) {
                PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[i]);
                Bucket bucket = pr.getRegionAdvisor().getBucket(0);
                assertNotNull("Bucket is null on SRC member", bucket);
                BucketRegion bucketRegion = bucket.getBucketAdvisor().getProxyBucketRegion().getHostedBucketRegion();
                assertTrue("SRC member is not hosting bucket", bucket.isHosting());
                assertNotNull("BucketRegion is null on SRC member", bucketRegion);
                int redundancy = bucket.getBucketAdvisor().getBucketRedundancy();
                assertEquals("SRC member reports redundancy " + redundancy, redundantCopies, redundancy);
            }
        }
    });
    // create newVM to create extra redundant buckets on
    final int finalNewVM = 2;
    createRegion(Host.getHost(0).getVM(finalNewVM), regionPath[0], localMaxMemory, numBuckets, redundantCopies);
    createRegion(Host.getHost(0).getVM(finalNewVM), regionPath[1], localMaxMemory, numBuckets, redundantCopies, regionPath[0]);
    createRegion(Host.getHost(0).getVM(finalNewVM), regionPath[2], localMaxMemory, numBuckets, redundantCopies, regionPath[1]);
    // create extra redundant buckets on finalNewVM
    Host.getHost(0).getVM(finalNewVM).invoke(new SerializableRunnable() {

        public void run() {
            for (int i = 0; i < regionPath.length; i++) {
                PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[i]);
                if (i == 0) {
                    // only call createRedundantBucket on leader PR
                    assertEquals(CreateBucketResult.CREATED, pr.getDataStore().createRedundantBucket(0, false, new InternalDistributedMember()));
                }
                Bucket bucket = pr.getRegionAdvisor().getBucket(0);
                assertNotNull("Bucket is null on DST member", bucket);
                BucketRegion bucketRegion = bucket.getBucketAdvisor().getProxyBucketRegion().getHostedBucketRegion();
                assertTrue("DST member is not hosting bucket", bucket.isHosting());
                assertNotNull("BucketRegion is null on DST member", bucketRegion);
                assertEquals(redundantCopies + 1, bucket.getBucketAdvisor().getBucketRedundancy());
            }
        }
    });
    if (true)
        return;
    // initiate moveBucket to move from otherVM to newVM
    boolean movedBucket = ((Boolean) Host.getHost(0).getVM(finalNewVM).invoke(new SerializableCallable() {

        public Object call() {
            InternalDistributedMember recipient = members[finalOtherVM];
            PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[0]);
            return pr.getDataStore().moveBucket(0, recipient, true);
        }
    })).booleanValue();
    assertTrue("Failed in call to moveBucket", movedBucket);
    // validate that otherVM no longer hosts colocated buckets
    Host.getHost(0).getVM(otherVM).invoke(new SerializableRunnable() {

        public void run() {
            for (int i = 0; i < regionPath.length; i++) {
                PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[i]);
                Bucket bucket = pr.getRegionAdvisor().getBucket(0);
                assertFalse("SRC member is still hosting moved bucket", bucket.isHosting());
                BucketRegion bucketRegion = bucket.getBucketAdvisor().getProxyBucketRegion().getHostedBucketRegion();
                assertNull("BucketRegion is not null on SRC member", bucketRegion);
            }
        }
    });
    // validate that newVM now hosts colocated bucket
    Host.getHost(0).getVM(finalNewVM).invoke(new SerializableRunnable() {

        public void run() {
            for (int i = 0; i < regionPath.length; i++) {
                PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionPath[i]);
                Bucket bucket = pr.getRegionAdvisor().getBucket(0);
                assertNotNull("Bucket is null on DST member", bucket);
                BucketRegion bucketRegion = bucket.getBucketAdvisor().getProxyBucketRegion().getHostedBucketRegion();
                assertTrue("DST member is not hosting bucket", bucket.isHosting());
                assertNotNull("BucketRegion is null on DST member", bucketRegion);
                assertEquals(redundantCopies, bucket.getBucketAdvisor().getBucketRedundancy());
            }
        }
    });
}
Also used : SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) BucketRegion(org.apache.geode.internal.cache.BucketRegion) Bucket(org.apache.geode.internal.cache.partitioned.Bucket) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) FlakyTest(org.apache.geode.test.junit.categories.FlakyTest) Test(org.junit.Test)

Aggregations

BucketRegion (org.apache.geode.internal.cache.BucketRegion)55 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)35 Region (org.apache.geode.cache.Region)13 Test (org.junit.Test)13 Bucket (org.apache.geode.internal.cache.partitioned.Bucket)11 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)11 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)11 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)10 ArrayList (java.util.ArrayList)9 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)9 HashMap (java.util.HashMap)7 LocalRegion (org.apache.geode.internal.cache.LocalRegion)7 PartitionedRegionDataStore (org.apache.geode.internal.cache.PartitionedRegionDataStore)7 FlakyTest (org.apache.geode.test.junit.categories.FlakyTest)6 HashSet (java.util.HashSet)5 GatewaySender (org.apache.geode.cache.wan.GatewaySender)5 Map (java.util.Map)4 AttributesFactory (org.apache.geode.cache.AttributesFactory)4 PartitionAttributesFactory (org.apache.geode.cache.PartitionAttributesFactory)4 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)4