Search in sources :

Example 6 with RegionExistsException

use of org.apache.geode.cache.RegionExistsException in project geode by apache.

the class GemFireCacheImpl method createVMRegion.

// TODO: createVMRegion method is too complex for IDE to analyze
@Override
public <K, V> Region<K, V> createVMRegion(String name, RegionAttributes<K, V> p_attrs, InternalRegionArguments internalRegionArgs) throws RegionExistsException, TimeoutException, IOException, ClassNotFoundException {
    if (getMyId().getVmKind() == DistributionManager.LOCATOR_DM_TYPE) {
        if (!internalRegionArgs.isUsedForMetaRegion() && internalRegionArgs.getInternalMetaRegion() == null) {
            throw new IllegalStateException("Regions can not be created in a locator.");
        }
    }
    this.stopper.checkCancelInProgress(null);
    LocalRegion.validateRegionName(name, internalRegionArgs);
    RegionAttributes<K, V> attrs = p_attrs;
    attrs = invokeRegionBefore(null, name, attrs, internalRegionArgs);
    if (attrs == null) {
        throw new IllegalArgumentException(LocalizedStrings.GemFireCache_ATTRIBUTES_MUST_NOT_BE_NULL.toLocalizedString());
    }
    LocalRegion region;
    final InputStream snapshotInputStream = internalRegionArgs.getSnapshotInputStream();
    InternalDistributedMember imageTarget = internalRegionArgs.getImageTarget();
    final boolean recreate = internalRegionArgs.getRecreateFlag();
    final boolean isPartitionedRegion = attrs.getPartitionAttributes() != null;
    final boolean isReInitCreate = snapshotInputStream != null || imageTarget != null || recreate;
    try {
        for (; ; ) {
            getCancelCriterion().checkCancelInProgress(null);
            Future future = null;
            synchronized (this.rootRegions) {
                region = this.rootRegions.get(name);
                if (region != null) {
                    throw new RegionExistsException(region);
                }
                if (!isReInitCreate) {
                    // fix bug 33523
                    String fullPath = Region.SEPARATOR + name;
                    future = (Future) this.reinitializingRegions.get(fullPath);
                }
                if (future == null) {
                    if (internalRegionArgs.getInternalMetaRegion() != null) {
                        region = internalRegionArgs.getInternalMetaRegion();
                    } else if (isPartitionedRegion) {
                        region = new PartitionedRegion(name, attrs, null, this, internalRegionArgs);
                    } else {
                        if (attrs.getScope().isLocal()) {
                            region = new LocalRegion(name, attrs, null, this, internalRegionArgs);
                        } else {
                            region = new DistributedRegion(name, attrs, null, this, internalRegionArgs);
                        }
                    }
                    this.rootRegions.put(name, region);
                    if (isReInitCreate) {
                        regionReinitialized(region);
                    }
                    break;
                }
            }
            // synchronized
            boolean interrupted = Thread.interrupted();
            try {
                // future != null
                // wait on Future
                LocalRegion localRegion = (LocalRegion) future.get();
                throw new RegionExistsException(localRegion);
            } catch (InterruptedException ignore) {
                interrupted = true;
            } catch (ExecutionException e) {
                throw new Error(LocalizedStrings.GemFireCache_UNEXPECTED_EXCEPTION.toLocalizedString(), e);
            } catch (CancellationException e) {
                // future was cancelled
                if (logger.isTraceEnabled()) {
                    logger.trace("future cancelled", e);
                }
            } finally {
                if (interrupted) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        // for
        boolean success = false;
        try {
            setRegionByPath(region.getFullPath(), region);
            region.initialize(snapshotInputStream, imageTarget, internalRegionArgs);
            success = true;
        } catch (CancelException | RedundancyAlreadyMetException e) {
            // don't print a call stack
            throw e;
        } catch (RuntimeException validationException) {
            logger.warn(LocalizedMessage.create(LocalizedStrings.GemFireCache_INITIALIZATION_FAILED_FOR_REGION_0, region.getFullPath()), validationException);
            throw validationException;
        } finally {
            if (!success) {
                try {
                    // do this before removing the region from
                    // the root set to fix bug 41982.
                    region.cleanupFailedInitialization();
                } catch (VirtualMachineError e) {
                    SystemFailure.initiateFailure(e);
                    throw e;
                } catch (Throwable t) {
                    SystemFailure.checkFailure();
                    this.stopper.checkCancelInProgress(t);
                    // bug #44672 - log the failure but don't override the original exception
                    logger.warn(LocalizedMessage.create(LocalizedStrings.GemFireCache_INIT_CLEANUP_FAILED_FOR_REGION_0, region.getFullPath()), t);
                } finally {
                    // clean up if initialize fails for any reason
                    setRegionByPath(region.getFullPath(), null);
                    synchronized (this.rootRegions) {
                        Region rootRegion = this.rootRegions.get(name);
                        if (rootRegion == region) {
                            this.rootRegions.remove(name);
                        }
                    }
                // synchronized
                }
            }
        // success
        }
        region.postCreateRegion();
    } catch (RegionExistsException ex) {
        // outside of sync make sure region is initialized to fix bug 37563
        LocalRegion localRegion = (LocalRegion) ex.getRegion();
        // don't give out ref until initialized
        localRegion.waitOnInitialization();
        throw ex;
    }
    invokeRegionAfter(region);
    // Added for M&M . Putting the callback here to avoid creating RegionMBean in case of Exception
    if (!region.isInternalRegion()) {
        this.system.handleResourceEvent(ResourceEvent.REGION_CREATE, region);
    }
    return region;
}
Also used : RegionExistsException(org.apache.geode.cache.RegionExistsException) ExecutionException(java.util.concurrent.ExecutionException) ByteArrayInputStream(java.io.ByteArrayInputStream) StringBufferInputStream(java.io.StringBufferInputStream) InputStream(java.io.InputStream) InternalGemFireError(org.apache.geode.InternalGemFireError) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) CancellationException(java.util.concurrent.CancellationException) RedundancyAlreadyMetException(org.apache.geode.internal.cache.partitioned.RedundancyAlreadyMetException) Future(java.util.concurrent.Future) Region(org.apache.geode.cache.Region) CancelException(org.apache.geode.CancelException)

Example 7 with RegionExistsException

use of org.apache.geode.cache.RegionExistsException in project geode by apache.

the class PartitionedRegionHelper method getPRRoot.

/**
   * Return a region that is the root for all PartitionedRegion meta data on this Node. The main
   * administrative Regions contained within are <code>allPartitionedRegion</code> (Scope
   * DISTRIBUTED_ACK) and <code>bucket2Node</code> (Scope DISTRIBUTED_ACK) and dataStore regions.
   * 
   * @return a GLOBLAL scoped root region used for PartitionedRegion administration
   */
public static LocalRegion getPRRoot(final InternalCache cache, boolean createIfAbsent) {
    DistributedRegion root = (DistributedRegion) cache.getRegion(PR_ROOT_REGION_NAME, true);
    if (root == null) {
        if (!createIfAbsent) {
            return null;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Creating root Partitioned Admin Region {}", PartitionedRegionHelper.PR_ROOT_REGION_NAME);
        }
        AttributesFactory factory = new AttributesFactory();
        factory.setScope(Scope.DISTRIBUTED_ACK);
        factory.setDataPolicy(DataPolicy.REPLICATE);
        factory.addCacheListener(new FixedPartitionAttributesListener());
        if (Boolean.getBoolean(DistributionConfig.GEMFIRE_PREFIX + "PRDebug")) {
            factory.addCacheListener(new CacheListenerAdapter() {

                @Override
                public void afterCreate(EntryEvent event) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Create Event for allPR: key = {} oldVal = {} newVal = {} Op = {} origin = {} isNetSearch = {}", event.getKey(), event.getOldValue(), event.getNewValue(), event.getOperation(), event.getDistributedMember(), event.getOperation().isNetSearch());
                    }
                }

                @Override
                public void afterUpdate(EntryEvent event) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Update Event for allPR: key = {} oldVal = {} newVal = {} Op = {} origin = {} isNetSearch = {}", event.getKey(), event.getOldValue(), event.getNewValue(), event.getOperation(), event.getDistributedMember(), event.getOperation().isNetSearch());
                    }
                }

                @Override
                public void afterDestroy(EntryEvent event) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Destroy Event for allPR: key = {} oldVal = {} newVal = {} Op = {} origin = {} isNetSearch = {}", event.getKey(), event.getOldValue(), event.getNewValue(), event.getOperation(), event.getDistributedMember(), event.getOperation().isNetSearch());
                    }
                }
            });
            factory.setCacheWriter(new CacheWriterAdapter() {

                @Override
                public void beforeUpdate(EntryEvent event) throws CacheWriterException {
                    // the prConfig node list must advance (otherwise meta data becomes out of sync)
                    final PartitionRegionConfig newConf = (PartitionRegionConfig) event.getNewValue();
                    final PartitionRegionConfig oldConf = (PartitionRegionConfig) event.getOldValue();
                    if (newConf != oldConf && !newConf.isGreaterNodeListVersion(oldConf)) {
                        throw new CacheWriterException(LocalizedStrings.PartitionedRegionHelper_NEW_PARTITIONEDREGIONCONFIG_0_DOES_NOT_HAVE_NEWER_VERSION_THAN_PREVIOUS_1.toLocalizedString(new Object[] { newConf, oldConf }));
                    }
                }
            });
        }
        RegionAttributes ra = factory.create();
        // Create anonymous stats holder for Partitioned Region meta data
        final HasCachePerfStats prMetaStatsHolder = new HasCachePerfStats() {

            public CachePerfStats getCachePerfStats() {
                return new CachePerfStats(cache.getDistributedSystem(), "partitionMetaData");
            }
        };
        try {
            root = (DistributedRegion) cache.createVMRegion(PR_ROOT_REGION_NAME, ra, new InternalRegionArguments().setIsUsedForPartitionedRegionAdmin(true).setInternalRegion(true).setCachePerfStatsHolder(prMetaStatsHolder));
            root.getDistributionAdvisor().addMembershipListener(new MemberFailureListener());
        } catch (RegionExistsException ignore) {
            // we avoid this before hand, but yet we have to catch it
            root = (DistributedRegion) cache.getRegion(PR_ROOT_REGION_NAME, true);
        } catch (IOException ieo) {
            Assert.assertTrue(false, "IOException creating Partitioned Region root: " + ieo);
        } catch (ClassNotFoundException cne) {
            Assert.assertTrue(false, "ClassNotFoundExcpetion creating Partitioned Region root: " + cne);
        }
    }
    Assert.assertTrue(root != null, "Can not obtain internal Partitioned Region configuration root");
    return root;
}
Also used : CacheWriterAdapter(org.apache.geode.cache.util.CacheWriterAdapter) RegionAttributes(org.apache.geode.cache.RegionAttributes) RegionExistsException(org.apache.geode.cache.RegionExistsException) IOException(java.io.IOException) AttributesFactory(org.apache.geode.cache.AttributesFactory) CacheListenerAdapter(org.apache.geode.cache.util.CacheListenerAdapter) EntryEvent(org.apache.geode.cache.EntryEvent) CacheWriterException(org.apache.geode.cache.CacheWriterException)

Example 8 with RegionExistsException

use of org.apache.geode.cache.RegionExistsException in project geode by apache.

the class CacheXml66DUnitTest method testCreateSameRegionTwice.

/**
   * Tests to make sure that we cannot create the same region multiple times in a {@code cache.xml}
   * file.
   */
@Test
public void testCreateSameRegionTwice() throws Exception {
    CacheCreation cache = new CacheCreation();
    RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
    String name = "root";
    cache.createRegion(name, attrs);
    try {
        cache.createRegion(name, attrs);
        fail("Should have thrown a RegionExistsException");
    } catch (RegionExistsException ex) {
    // pass...
    }
    setXmlFile(findFile("sameRootRegion.xml"));
    IgnoredException expectedException = IgnoredException.addIgnoredException("While reading Cache XML file");
    try {
        getCache();
        fail("Should have thrown a CacheXmlException");
    } catch (CacheXmlException ex) {
        Throwable cause = ex.getCause();
        assertTrue(cause instanceof SAXException);
        cause = ((SAXException) cause).getException();
        if (!(cause instanceof RegionExistsException)) {
            Assert.fail("Expected a RegionExistsException, not a " + cause.getClass().getName(), cause);
        }
    } finally {
        expectedException.remove();
    }
}
Also used : CacheXmlException(org.apache.geode.cache.CacheXmlException) RegionAttributesCreation(org.apache.geode.internal.cache.xmlcache.RegionAttributesCreation) IgnoredException(org.apache.geode.test.dunit.IgnoredException) RegionExistsException(org.apache.geode.cache.RegionExistsException) CacheCreation(org.apache.geode.internal.cache.xmlcache.CacheCreation) ClientCacheCreation(org.apache.geode.internal.cache.xmlcache.ClientCacheCreation) SAXException(org.xml.sax.SAXException) Test(org.junit.Test)

Example 9 with RegionExistsException

use of org.apache.geode.cache.RegionExistsException in project geode by apache.

the class PartitionedRegionStatsJUnitTest method createPRWithEviction.

private PartitionedRegion createPRWithEviction(String name, int lmax, int redundancy, int evictionCount, boolean diskSync, boolean persistent) {
    PartitionAttributesFactory paf = new PartitionAttributesFactory();
    // set low to
    paf.setLocalMaxMemory(lmax).setRedundantCopies(redundancy).setTotalNumBuckets(13);
    // reduce
    // logging
    AttributesFactory af = new AttributesFactory();
    af.setPartitionAttributes(paf.create());
    if (persistent) {
        af.setDataPolicy(DataPolicy.PERSISTENT_PARTITION);
    }
    af.setEvictionAttributes(EvictionAttributes.createLRUEntryAttributes(1, EvictionAction.OVERFLOW_TO_DISK));
    af.setDiskStoreName("diskstore");
    af.setDiskSynchronous(diskSync);
    Cache cache = PartitionedRegionTestHelper.createCache();
    DISK_DIR.mkdir();
    cache.createDiskStoreFactory().setDiskDirs(new File[] { DISK_DIR }).create("diskstore");
    PartitionedRegion pr = null;
    try {
        pr = (PartitionedRegion) cache.createRegion(name, af.create());
    } catch (RegionExistsException rex) {
        pr = (PartitionedRegion) cache.getRegion(name);
    }
    return pr;
}
Also used : PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) AttributesFactory(org.apache.geode.cache.AttributesFactory) PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) RegionExistsException(org.apache.geode.cache.RegionExistsException) File(java.io.File) Cache(org.apache.geode.cache.Cache)

Example 10 with RegionExistsException

use of org.apache.geode.cache.RegionExistsException in project geode by apache.

the class PartitionedRegionWithSameNameDUnitTest method createMultiplePartitionRegion.

/**
   * This function creates multiple partition regions in a VM. The name of the Partition Region will
   * be PRPrefix+index (index starts from startIndexForRegion and ends to endIndexForRegion)
   * 
   * @param PRPrefix : Used in the name of the Partition Region
   * 
   *        These indices Represents range of the Partition Region
   * @param startIndexForRegion :
   * @param endIndexForRegion
   * @param redundancy
   * @param localmaxMemory
   * @return
   */
public CacheSerializableRunnable createMultiplePartitionRegion(final String PRPrefix, final int startIndexForRegion, final int endIndexForRegion, final int redundancy, final int localmaxMemory, final boolean firstCreationFlag, final boolean multipleVMFlag) {
    SerializableRunnable createPRs = new CacheSerializableRunnable("createPrRegions") {

        String innerPRPrefix = PRPrefix;

        int innerStartIndexForRegion = startIndexForRegion;

        int innerEndIndexForRegion = endIndexForRegion;

        int innerRedundancy = redundancy;

        int innerlocalmaxMemory = localmaxMemory;

        public void run2() throws CacheException {
            Cache cache = getCache();
            if (firstCreationFlag) {
                for (int i = startIndexForRegion; i < endIndexForRegion; i++) {
                    cache.createRegion(innerPRPrefix + i, createRegionAttrsForPR(innerRedundancy, innerlocalmaxMemory));
                }
            } else {
                for (int i = startIndexForRegion; i < endIndexForRegion; i++) {
                    if (!multipleVMFlag) {
                        try {
                            cache.createRegion(innerPRPrefix + i, createRegionAttrsForPR(innerRedundancy, innerlocalmaxMemory));
                            fail("test failed : partition region with same name as local region is created");
                        } catch (RegionExistsException expected) {
                        // getLogWriter()
                        // .info(
                        // "Expected exception RegionExistsException for creating
                        // partition region with same name as of the distributed region
                        // ", ex);
                        }
                    } else {
                        final String expectedExceptions = IllegalStateException.class.getName();
                        getCache().getLogger().info("<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>");
                        try {
                            cache.createRegion(innerPRPrefix + i, createRegionAttrsForPR(innerRedundancy, innerlocalmaxMemory));
                            fail("test failed : partition region with same name as distributed region is created");
                        } catch (IllegalStateException expected) {
                        // getLogWriter()
                        // .info(
                        // "Expected exception IllegalStateException for creating
                        // partition region with same name as of the distributed region"
                        // + ex);
                        }
                        getCache().getLogger().info("<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>");
                    }
                }
            }
            LogWriterUtils.getLogWriter().info("createMultiplePartitionRegion() - Partition Regions Successfully Completed ");
        }
    };
    return (CacheSerializableRunnable) createPRs;
}
Also used : CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) RegionExistsException(org.apache.geode.cache.RegionExistsException) Cache(org.apache.geode.cache.Cache)

Aggregations

RegionExistsException (org.apache.geode.cache.RegionExistsException)18 AttributesFactory (org.apache.geode.cache.AttributesFactory)9 Region (org.apache.geode.cache.Region)7 RegionAttributes (org.apache.geode.cache.RegionAttributes)6 Cache (org.apache.geode.cache.Cache)5 IOException (java.io.IOException)4 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)4 CancelException (org.apache.geode.CancelException)3 PartitionAttributesFactory (org.apache.geode.cache.PartitionAttributesFactory)3 InternalRegionArguments (org.apache.geode.internal.cache.InternalRegionArguments)3 LocalRegion (org.apache.geode.internal.cache.LocalRegion)3 Test (org.junit.Test)3 InputStream (java.io.InputStream)2 InternalGemFireError (org.apache.geode.InternalGemFireError)2 CacheWriterException (org.apache.geode.cache.CacheWriterException)2 CacheXmlException (org.apache.geode.cache.CacheXmlException)2 TimeoutException (org.apache.geode.cache.TimeoutException)2 CacheSerializableRunnable (org.apache.geode.cache30.CacheSerializableRunnable)2 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)2 CachePerfStats (org.apache.geode.internal.cache.CachePerfStats)2