Search in sources :

Example 11 with PartitionAttributes

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

the class CacheXml66DUnitTest method validateAttributes.

private void validateAttributes(Region region, List<FixedPartitionAttributes> fpattrsList, QuarterPartitionResolver resolver, boolean isColocated) {
    RegionAttributes regionAttrs = region.getAttributes();
    PartitionAttributes pa = regionAttrs.getPartitionAttributes();
    assertEquals(pa.getRedundantCopies(), 1);
    assertNotNull(pa.getPartitionResolver().getClass());
    assertEquals(pa.getPartitionResolver(), resolver);
    List<FixedPartitionAttributesImpl> fixedPartitionsList = pa.getFixedPartitionAttributes();
    if (isColocated) {
        assertNull(fixedPartitionsList);
        assertNotNull(pa.getColocatedWith());
    } else {
        assertNull(pa.getColocatedWith());
        assertEquals(fixedPartitionsList.size(), 4);
        assertEquals(fixedPartitionsList.containsAll(fpattrsList), true);
        for (FixedPartitionAttributes fpa : fixedPartitionsList) {
            if (fpa.getPartitionName().equals("Q1")) {
                assertEquals(fpa.getNumBuckets(), 1);
                assertEquals(fpa.isPrimary(), false);
            }
            if (fpa.getPartitionName().equals("Q2")) {
                assertEquals(fpa.getNumBuckets(), 1);
                assertEquals(fpa.isPrimary(), true);
            }
            if (fpa.getPartitionName().equals("Q3")) {
                assertEquals(fpa.getNumBuckets(), 3);
                assertEquals(fpa.isPrimary(), false);
            }
            if (fpa.getPartitionName().equals("Q4")) {
                assertEquals(fpa.getNumBuckets(), 3);
                assertEquals(fpa.isPrimary(), false);
            }
        }
    }
}
Also used : FixedPartitionAttributes(org.apache.geode.cache.FixedPartitionAttributes) RegionAttributes(org.apache.geode.cache.RegionAttributes) PartitionAttributes(org.apache.geode.cache.PartitionAttributes) FixedPartitionAttributes(org.apache.geode.cache.FixedPartitionAttributes) FixedPartitionAttributesImpl(org.apache.geode.internal.cache.FixedPartitionAttributesImpl)

Example 12 with PartitionAttributes

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

the class CacheXmlGenerator method generate.

/**
   * Generates XML for region attributes.
   *
   * @param id The id of the named region attributes (may be <code>null</code>)
   */
private void generate(String id, RegionAttributes attrs) throws SAXException {
    AttributesImpl atts = new AttributesImpl();
    if (id != null) {
        atts.addAttribute("", "", ID, "", id);
    }
    // point, the refid information is lost.
    if (attrs instanceof RegionAttributesCreation) {
        String refId = ((RegionAttributesCreation) attrs).getRefid();
        if (refId != null) {
            atts.addAttribute("", "", REFID, "", refId);
        }
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasScope())) {
        String scopeString;
        Scope scope = attrs.getScope();
        if (scope.equals(Scope.LOCAL)) {
            scopeString = LOCAL;
        } else if (scope.equals(Scope.DISTRIBUTED_NO_ACK)) {
            scopeString = DISTRIBUTED_NO_ACK;
        } else if (scope.equals(Scope.DISTRIBUTED_ACK)) {
            scopeString = DISTRIBUTED_ACK;
        } else if (scope.equals(Scope.GLOBAL)) {
            scopeString = GLOBAL;
        } else {
            throw new InternalGemFireException(LocalizedStrings.CacheXmlGenerator_UNKNOWN_SCOPE_0.toLocalizedString(scope));
        }
        final boolean isPartitionedRegion;
        if (attrs instanceof RegionAttributesCreation) {
            RegionAttributesCreation rac = (RegionAttributesCreation) attrs;
            isPartitionedRegion = rac.getPartitionAttributes() != null || (rac.hasDataPolicy() && rac.getDataPolicy().withPartitioning());
        } else {
            isPartitionedRegion = attrs.getPartitionAttributes() != null || attrs.getDataPolicy().withPartitioning();
        }
        if (!isPartitionedRegion) {
            // Partitioned Region don't support setting scope
            if (generateDefaults() || !scope.equals(AbstractRegion.DEFAULT_SCOPE))
                atts.addAttribute("", "", SCOPE, "", scopeString);
        }
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasEarlyAck())) {
        if (generateDefaults() || attrs.getEarlyAck())
            atts.addAttribute("", "", EARLY_ACK, "", String.valueOf(attrs.getEarlyAck()));
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasMulticastEnabled())) {
        if (generateDefaults() || attrs.getMulticastEnabled())
            atts.addAttribute("", "", MULTICAST_ENABLED, "", String.valueOf(attrs.getMulticastEnabled()));
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasPublisher())) {
        if (generateDefaults() || attrs.getPublisher())
            atts.addAttribute("", "", PUBLISHER, "", String.valueOf(attrs.getPublisher()));
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasEnableAsyncConflation())) {
        if (generateDefaults() || attrs.getEnableAsyncConflation())
            atts.addAttribute("", "", ENABLE_ASYNC_CONFLATION, "", String.valueOf(attrs.getEnableAsyncConflation()));
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_5_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasEnableSubscriptionConflation())) {
            if (this.version.compareTo(CacheXmlVersion.GEMFIRE_5_7) >= 0) {
                // starting with 5.7 it is enable-subscription-conflation
                if (generateDefaults() || attrs.getEnableSubscriptionConflation())
                    atts.addAttribute("", "", ENABLE_SUBSCRIPTION_CONFLATION, "", String.valueOf(attrs.getEnableSubscriptionConflation()));
            } else {
                // before 5.7 it was enable-bridge-conflation
                if (generateDefaults() || attrs.getEnableSubscriptionConflation())
                    atts.addAttribute("", "", ENABLE_BRIDGE_CONFLATION, "", String.valueOf(attrs.getEnableSubscriptionConflation()));
            }
        }
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasDataPolicy())) {
            String dpString;
            DataPolicy dp = attrs.getDataPolicy();
            if (dp.isEmpty()) {
                dpString = EMPTY_DP;
            } else if (dp.isNormal()) {
                dpString = NORMAL_DP;
            } else if (dp.isPreloaded()) {
                dpString = PRELOADED_DP;
            } else if (dp.isReplicate()) {
                dpString = REPLICATE_DP;
            } else if (dp == DataPolicy.PERSISTENT_REPLICATE) {
                dpString = PERSISTENT_REPLICATE_DP;
            } else if (dp == DataPolicy.PERSISTENT_PARTITION) {
                dpString = PERSISTENT_PARTITION_DP;
            } else if (dp.isPartition()) {
                if (this.version.compareTo(CacheXmlVersion.GEMFIRE_5_1) >= 0) {
                    dpString = PARTITION_DP;
                } else {
                    // prior to 5.1 the data policy for partitioned regions was EMPTY
                    dpString = EMPTY_DP;
                }
            } else {
                throw new InternalGemFireException(LocalizedStrings.CacheXmlGenerator_UNKNOWN_DATA_POLICY_0.toLocalizedString(dp));
            }
            if (generateDefaults() || !dp.equals(DataPolicy.DEFAULT))
                atts.addAttribute("", "", DATA_POLICY, "", dpString);
        }
    // hasDataPolicy
    } else // GEMFIRE_5_0 >= 0
    {
        // GEMFIRE_5_0 < 0
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasEnableSubscriptionConflation())) {
            if (generateDefaults() || attrs.getEnableSubscriptionConflation())
                atts.addAttribute("", "", "enable-conflation", "", String.valueOf(attrs.getEnableSubscriptionConflation()));
        }
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasMirrorType())) {
            String mirrorString;
            MirrorType mirror = attrs.getMirrorType();
            if (mirror.equals(MirrorType.NONE))
                mirrorString = NONE;
            else if (mirror.equals(MirrorType.KEYS))
                mirrorString = KEYS;
            else if (mirror.equals(MirrorType.KEYS_VALUES))
                mirrorString = KEYS_VALUES;
            else
                throw new InternalGemFireException(LocalizedStrings.CacheXmlGenerator_UNKNOWN_MIRROR_TYPE_0.toLocalizedString(mirror));
            atts.addAttribute("", "", MIRROR_TYPE, "", mirrorString);
        }
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasPersistBackup())) {
            atts.addAttribute("", "", PERSIST_BACKUP, "", String.valueOf(attrs.getDataPolicy() == DataPolicy.PERSISTENT_REPLICATE));
        }
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasInitialCapacity())) {
        if (generateDefaults() || attrs.getInitialCapacity() != 16)
            atts.addAttribute("", "", INITIAL_CAPACITY, "", String.valueOf(attrs.getInitialCapacity()));
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasLoadFactor())) {
        if (generateDefaults() || attrs.getLoadFactor() != 0.75f)
            atts.addAttribute("", "", LOAD_FACTOR, "", String.valueOf(attrs.getLoadFactor()));
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasConcurrencyLevel())) {
        if (generateDefaults() || attrs.getConcurrencyLevel() != 16)
            atts.addAttribute("", "", CONCURRENCY_LEVEL, "", String.valueOf(attrs.getConcurrencyLevel()));
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_7_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasConcurrencyChecksEnabled())) {
            if (generateDefaults() || attrs.getConcurrencyChecksEnabled() != true)
                /* fixes bug 46654 */
                atts.addAttribute("", "", CONCURRENCY_CHECKS_ENABLED, "", String.valueOf(attrs.getConcurrencyChecksEnabled()));
        }
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasStatisticsEnabled())) {
        if (generateDefaults() || attrs.getStatisticsEnabled())
            atts.addAttribute("", "", STATISTICS_ENABLED, "", String.valueOf(attrs.getStatisticsEnabled()));
    }
    if (!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasIgnoreJTA()) {
        if (generateDefaults() || attrs.getIgnoreJTA())
            atts.addAttribute("", "", IGNORE_JTA, "", String.valueOf(attrs.getIgnoreJTA()));
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_4_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasIsLockGrantor())) {
            if (generateDefaults() || attrs.isLockGrantor())
                atts.addAttribute("", "", IS_LOCK_GRANTOR, "", String.valueOf(attrs.isLockGrantor()));
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_5_7) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasPoolName())) {
            String cpVal = attrs.getPoolName();
            if (cpVal == null) {
                cpVal = "";
            }
            if (generateDefaults() || !cpVal.equals(""))
                atts.addAttribute("", "", POOL_NAME, "", cpVal);
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_6_5) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasDiskStoreName())) {
            String dsVal = attrs.getDiskStoreName();
            if (dsVal != null) {
                atts.addAttribute("", "", DISK_STORE_NAME, "", dsVal);
            }
        }
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasDiskSynchronous())) {
            if (generateDefaults() || attrs.isDiskSynchronous() != AttributesFactory.DEFAULT_DISK_SYNCHRONOUS)
                atts.addAttribute("", "", DISK_SYNCHRONOUS, "", String.valueOf(attrs.isDiskSynchronous()));
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_6_1) >= 0)
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasCloningEnabled())) {
            if (generateDefaults() || attrs.getCloningEnabled())
                atts.addAttribute("", "", CLONING_ENABLED, "", String.valueOf(attrs.getCloningEnabled()));
        }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_7_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasGatewaySenderId())) {
            Set<String> senderIds = new HashSet<String>(attrs.getGatewaySenderIds());
            StringBuilder senderStringBuff = new StringBuilder();
            if (senderIds != null && senderIds.size() != 0) {
                for (String senderId : senderIds) {
                    if (!(senderStringBuff.length() == 0)) {
                        senderStringBuff.append(",");
                    }
                    senderStringBuff.append(senderId);
                }
            }
            if (generateDefaults() || senderStringBuff.length() > 0)
                atts.addAttribute("", "", GATEWAY_SENDER_IDS, "", senderStringBuff.toString());
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_7_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasAsyncEventListeners())) {
            Set<String> asyncEventQueueIds = new HashSet<String>(attrs.getAsyncEventQueueIds());
            StringBuilder asyncEventQueueStringBuff = new StringBuilder();
            if (asyncEventQueueIds != null && asyncEventQueueIds.size() != 0) {
                for (String asyncEventQueueId : asyncEventQueueIds) {
                    if (!(asyncEventQueueStringBuff.length() == 0)) {
                        asyncEventQueueStringBuff.append(",");
                    }
                    asyncEventQueueStringBuff.append(asyncEventQueueId);
                }
            }
            if (generateDefaults() || asyncEventQueueStringBuff.length() > 0)
                atts.addAttribute("", "", ASYNC_EVENT_QUEUE_IDS, "", asyncEventQueueStringBuff.toString());
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEODE_1_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasOffHeap())) {
            if (generateDefaults() || attrs.getOffHeap()) {
                atts.addAttribute("", "", OFF_HEAP, "", String.valueOf(attrs.getOffHeap()));
            }
        }
    }
    handler.startElement("", REGION_ATTRIBUTES, REGION_ATTRIBUTES, atts);
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasKeyConstraint())) {
        generate(attrs.getKeyConstraint(), KEY_CONSTRAINT);
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasValueConstraint())) {
        generate(attrs.getValueConstraint(), VALUE_CONSTRAINT);
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasRegionTimeToLive())) {
        if (generateDefaults() || !attrs.getRegionTimeToLive().equals(ExpirationAttributes.DEFAULT))
            generate(REGION_TIME_TO_LIVE, attrs.getRegionTimeToLive(), null);
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasRegionIdleTimeout())) {
        if (generateDefaults() || !attrs.getRegionIdleTimeout().equals(ExpirationAttributes.DEFAULT))
            generate(REGION_IDLE_TIME, attrs.getRegionIdleTimeout(), null);
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasEntryTimeToLive() || ((RegionAttributesCreation) attrs).hasCustomEntryTimeToLive())) {
        if (generateDefaults() || !attrs.getEntryTimeToLive().equals(ExpirationAttributes.DEFAULT) || attrs.getCustomEntryTimeToLive() != null)
            generate(ENTRY_TIME_TO_LIVE, attrs.getEntryTimeToLive(), attrs.getCustomEntryTimeToLive());
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasEntryIdleTimeout() || ((RegionAttributesCreation) attrs).hasCustomEntryIdleTimeout())) {
        if (generateDefaults() || !attrs.getEntryIdleTimeout().equals(ExpirationAttributes.DEFAULT) || attrs.getCustomEntryIdleTimeout() != null)
            generate(ENTRY_IDLE_TIME, attrs.getEntryIdleTimeout(), attrs.getCustomEntryIdleTimeout());
    }
    if (attrs.getDiskStoreName() == null && (generateDefaults() || this.version.compareTo(CacheXmlVersion.GEMFIRE_6_5) < 0)) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasDiskWriteAttributes())) {
            generate(attrs.getDiskWriteAttributes());
        }
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasDiskDirs())) {
            File[] diskDirs = attrs.getDiskDirs();
            int[] diskSizes = attrs.getDiskDirSizes();
            if (diskDirs != null && diskDirs.length > 0) {
                handler.startElement("", DISK_DIRS, DISK_DIRS, EMPTY);
                for (int i = 0; i < diskDirs.length; i++) {
                    AttributesImpl diskAtts = new AttributesImpl();
                    if (diskSizes[i] != DiskStoreFactory.DEFAULT_DISK_DIR_SIZE) {
                        diskAtts.addAttribute("", "", DIR_SIZE, "", String.valueOf(diskSizes[i]));
                    }
                    handler.startElement("", DISK_DIR, DISK_DIR, diskAtts);
                    File dir = diskDirs[i];
                    String name = generateDefaults() ? dir.getAbsolutePath() : dir.getPath();
                    handler.characters(name.toCharArray(), 0, name.length());
                    handler.endElement("", DISK_DIR, DISK_DIR);
                }
                handler.endElement("", DISK_DIRS, DISK_DIRS);
            }
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_5_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasPartitionAttributes())) {
            PartitionAttributes p = attrs.getPartitionAttributes();
            if (p != null) {
                generate(p);
            }
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_5_0) >= 0) {
        MembershipAttributes p = attrs.getMembershipAttributes();
        if (p != null && p.hasRequiredRoles()) {
            generate(p);
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_5_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasSubscriptionAttributes())) {
            SubscriptionAttributes sa = attrs.getSubscriptionAttributes();
            if (sa != null) {
                if (generateDefaults() || !sa.equals(new SubscriptionAttributes()))
                    generate(sa);
            }
        }
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasCacheLoader())) {
        generate(CACHE_LOADER, attrs.getCacheLoader());
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasCacheWriter())) {
        generate(CACHE_WRITER, attrs.getCacheWriter());
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasCacheListeners())) {
        CacheListener[] listeners = attrs.getCacheListeners();
        for (int i = 0; i < listeners.length; i++) {
            generate(CACHE_LISTENER, listeners[i]);
        }
    }
    if (this.version.compareTo(CacheXmlVersion.GEMFIRE_8_0) >= 0) {
        if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasCompressor())) {
            generate(COMPRESSOR, attrs.getCompressor());
        }
    }
    if ((!(attrs instanceof RegionAttributesCreation) || ((RegionAttributesCreation) attrs).hasEvictionAttributes())) {
        generate(attrs.getEvictionAttributes());
    }
    handler.endElement("", REGION_ATTRIBUTES, REGION_ATTRIBUTES);
}
Also used : InternalGemFireException(org.apache.geode.InternalGemFireException) PartitionAttributes(org.apache.geode.cache.PartitionAttributes) FixedPartitionAttributes(org.apache.geode.cache.FixedPartitionAttributes) CacheListener(org.apache.geode.cache.CacheListener) DiskWriteAttributesImpl(org.apache.geode.internal.cache.DiskWriteAttributesImpl) PartitionAttributesImpl(org.apache.geode.internal.cache.PartitionAttributesImpl) AttributesImpl(org.xml.sax.helpers.AttributesImpl) Scope(org.apache.geode.cache.Scope) MirrorType(org.apache.geode.cache.MirrorType) DataPolicy(org.apache.geode.cache.DataPolicy) File(java.io.File) HashSet(java.util.HashSet) MembershipAttributes(org.apache.geode.cache.MembershipAttributes) SubscriptionAttributes(org.apache.geode.cache.SubscriptionAttributes)

Example 13 with PartitionAttributes

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

the class PDXQueryTestBase method configAndStartBridgeServer.

protected void configAndStartBridgeServer(boolean isPr, boolean isAccessor, boolean asyncIndex, Compressor compressor) {
    AttributesFactory factory = new AttributesFactory();
    if (isPr) {
        PartitionAttributesFactory paf = new PartitionAttributesFactory();
        if (isAccessor) {
            paf.setLocalMaxMemory(0);
        }
        PartitionAttributes prAttr = paf.setTotalNumBuckets(20).setRedundantCopies(0).create();
        factory.setPartitionAttributes(prAttr);
    } else {
        factory.setScope(Scope.DISTRIBUTED_ACK);
        factory.setDataPolicy(DataPolicy.REPLICATE);
    }
    if (asyncIndex) {
        factory.setIndexMaintenanceSynchronous(!asyncIndex);
    }
    if (compressor != null) {
        factory.setCompressor(compressor);
    }
    createRegion(this.regionName, this.rootRegionName, factory.create());
    createRegion(this.regionName2, this.rootRegionName, factory.create());
    try {
        startBridgeServer(0, false);
    } catch (Exception ex) {
        Assert.fail("While starting CacheServer", ex);
    }
}
Also used : PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) AttributesFactory(org.apache.geode.cache.AttributesFactory) PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) PartitionAttributes(org.apache.geode.cache.PartitionAttributes) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException)

Example 14 with PartitionAttributes

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

the class PartitionedRegion method registerPartitionedRegion.

/**
   * Register this PartitionedRegion by: 1) Create a PartitionRegionConfig and 2) Bind it into the
   * allPartitionedRegion system wide Region.
   * 
   * @param storesData which indicates whether the instance in this cache stores data, effecting the
   *        Nodes PRType
   * 
   * @see Node#setPRType(int)
   */
private void registerPartitionedRegion(boolean storesData) {
    // Register this ParitionedRegion. First check if the ParitionedRegion
    // entry already exists globally.
    PartitionRegionConfig prConfig = null;
    PartitionAttributes prAttribs = getAttributes().getPartitionAttributes();
    if (storesData) {
        if (this.fixedPAttrs != null) {
            this.node.setPRType(Node.FIXED_PR_DATASTORE);
        } else {
            this.node.setPRType(Node.ACCESSOR_DATASTORE);
        }
        this.node.setPersistence(getAttributes().getDataPolicy() == DataPolicy.PERSISTENT_PARTITION);
        byte loaderByte = (byte) (getAttributes().getCacheLoader() != null ? 0x01 : 0x00);
        byte writerByte = (byte) (getAttributes().getCacheWriter() != null ? 0x02 : 0x00);
        this.node.setLoaderWriterByte((byte) (loaderByte + writerByte));
    } else {
        if (this.fixedPAttrs != null) {
            this.node.setPRType(Node.FIXED_PR_ACCESSOR);
        } else {
            this.node.setPRType(Node.ACCESSOR);
        }
    }
    final RegionLock rl = getRegionLock();
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("registerPartitionedRegion: obtaining lock");
        }
        rl.lock();
        checkReadiness();
        prConfig = this.prRoot.get(getRegionIdentifier());
        if (prConfig == null) {
            validateParalleGatewaySenderIds();
            this.partitionedRegionId = generatePRId(getSystem());
            prConfig = new PartitionRegionConfig(this.partitionedRegionId, this.getFullPath(), prAttribs, this.getScope(), getAttributes().getEvictionAttributes(), getAttributes().getRegionIdleTimeout(), getAttributes().getRegionTimeToLive(), getAttributes().getEntryIdleTimeout(), getAttributes().getEntryTimeToLive(), this.getAllGatewaySenderIds());
            logger.info(LocalizedMessage.create(LocalizedStrings.PartitionedRegion_PARTITIONED_REGION_0_IS_BORN_WITH_PRID_1_IDENT_2, new Object[] { getFullPath(), this.partitionedRegionId, getRegionIdentifier() }));
            PRSanityCheckMessage.schedule(this);
        } else {
            validator.validatePartitionAttrsFromPRConfig(prConfig);
            if (storesData) {
                validator.validatePersistentMatchBetweenDataStores(prConfig);
                validator.validateCacheLoaderWriterBetweenDataStores(prConfig);
                validator.validateFixedPABetweenDataStores(prConfig);
            }
            this.partitionedRegionId = prConfig.getPRId();
            logger.info(LocalizedMessage.create(LocalizedStrings.PartitionedRegion_PARTITIONED_REGION_0_IS_CREATED_WITH_PRID_1, new Object[] { getFullPath(), this.partitionedRegionId }));
        }
        synchronized (prIdToPR) {
            // last
            prIdToPR.put(this.partitionedRegionId, this);
        }
        prConfig.addNode(this.node);
        if (this.getFixedPartitionAttributesImpl() != null) {
            calculateStartingBucketIDs(prConfig);
        }
        updatePRConfig(prConfig, false);
        /*
       * try { if (this.redundantCopies > 0) { if (storesData) {
       * this.dataStore.grabBackupBuckets(false); } } } catch (RegionDestroyedException rde) { if
       * (!this.isClosed) throw rde; }
       */
        this.cleanPRRegistration = true;
    } catch (LockServiceDestroyedException lsde) {
        if (logger.isDebugEnabled()) {
            logger.debug("registerPartitionedRegion: unable to obtain lock for {}", this);
        }
        cleanupFailedInitialization();
        throw new PartitionedRegionException(LocalizedStrings.PartitionedRegion_CAN_NOT_CREATE_PARTITIONEDREGION_FAILED_TO_ACQUIRE_REGIONLOCK.toLocalizedString(), lsde);
    } catch (IllegalStateException ill) {
        cleanupFailedInitialization();
        throw ill;
    } catch (VirtualMachineError err) {
        SystemFailure.initiateFailure(err);
        // now, so don't let this thread continue.
        throw err;
    } catch (Throwable t) {
        // Whenever you catch Error or Throwable, you must also
        // catch VirtualMachineError (see above). However, there is
        // _still_ a possibility that you are dealing with a cascading
        // error condition, so you also need to check to see if the JVM
        // is still usable:
        SystemFailure.checkFailure();
        String registerErrMsg = LocalizedStrings.PartitionedRegion_AN_EXCEPTION_WAS_CAUGHT_WHILE_REGISTERING_PARTITIONEDREGION_0_DUMPPRID_1.toLocalizedString(getFullPath(), prIdToPR.dump());
        try {
            synchronized (prIdToPR) {
                if (prIdToPR.containsKey(this.partitionedRegionId)) {
                    prIdToPR.put(this.partitionedRegionId, PRIdMap.FAILED_REGISTRATION, false);
                    logger.info(LocalizedMessage.create(LocalizedStrings.PartitionedRegion_FAILED_REGISTRATION_PRID_0_NAMED_1, new Object[] { this.partitionedRegionId, this.getName() }));
                }
            }
        } 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();
            if (logger.isDebugEnabled()) {
                logger.debug("Partitioned Region creation, could not clean up after caught exception", e);
            }
        }
        throw new PartitionedRegionException(registerErrMsg, t);
    } finally {
        try {
            rl.unlock();
            if (logger.isDebugEnabled()) {
                logger.debug("registerPartitionedRegion: released lock");
            }
        } catch (Exception es) {
            if (logger.isDebugEnabled()) {
                logger.debug(es.getMessage(), es);
            }
        }
    }
}
Also used : LockServiceDestroyedException(org.apache.geode.distributed.LockServiceDestroyedException) PartitionAttributes(org.apache.geode.cache.PartitionAttributes) TimeoutException(org.apache.geode.cache.TimeoutException) IndexCreationException(org.apache.geode.cache.query.IndexCreationException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) InternalGemFireException(org.apache.geode.InternalGemFireException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) TransactionDataRebalancedException(org.apache.geode.cache.TransactionDataRebalancedException) LockServiceDestroyedException(org.apache.geode.distributed.LockServiceDestroyedException) GatewaySenderException(org.apache.geode.internal.cache.wan.GatewaySenderException) PartitionOfflineException(org.apache.geode.cache.persistence.PartitionOfflineException) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) GatewaySenderConfigurationException(org.apache.geode.internal.cache.wan.GatewaySenderConfigurationException) ExecutionException(java.util.concurrent.ExecutionException) ReplyException(org.apache.geode.distributed.internal.ReplyException) IndexNameConflictException(org.apache.geode.cache.query.IndexNameConflictException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) IndexExistsException(org.apache.geode.cache.query.IndexExistsException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) EntryExistsException(org.apache.geode.cache.EntryExistsException) PartitionedRegionDistributionException(org.apache.geode.cache.PartitionedRegionDistributionException) PartitionedRegionStorageException(org.apache.geode.cache.PartitionedRegionStorageException) FunctionException(org.apache.geode.cache.execute.FunctionException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) NoSuchElementException(java.util.NoSuchElementException) QueryException(org.apache.geode.cache.query.QueryException) PartitionNotAvailableException(org.apache.geode.cache.partition.PartitionNotAvailableException) LowMemoryException(org.apache.geode.cache.LowMemoryException) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) PRLocallyDestroyedException(org.apache.geode.internal.cache.partitioned.PRLocallyDestroyedException) RegionExistsException(org.apache.geode.cache.RegionExistsException) CancelException(org.apache.geode.CancelException) DiskAccessException(org.apache.geode.cache.DiskAccessException) CacheWriterException(org.apache.geode.cache.CacheWriterException) TransactionException(org.apache.geode.cache.TransactionException) CacheClosedException(org.apache.geode.cache.CacheClosedException) ConcurrentCacheModificationException(org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException) MultiIndexCreationException(org.apache.geode.cache.query.MultiIndexCreationException) TransactionDataNotColocatedException(org.apache.geode.cache.TransactionDataNotColocatedException) EmptyRegionFunctionException(org.apache.geode.cache.execute.EmptyRegionFunctionException)

Example 15 with PartitionAttributes

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

the class PartitionRegionHelperDUnitTest method testMoveSingleBucket.

@Test
public void testMoveSingleBucket() {
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    VM vm2 = host.getVM(2);
    SerializableCallable createPrRegion = new SerializableCallable("createRegion") {

        public Object call() {
            Cache cache = getCache();
            AttributesFactory attr = new AttributesFactory();
            PartitionAttributesFactory paf = new PartitionAttributesFactory();
            paf.setRedundantCopies(1);
            paf.setTotalNumBuckets(12);
            PartitionAttributes prAttr = paf.create();
            attr.setPartitionAttributes(prAttr);
            cache.createRegion("region1", attr.create());
            return cache.getDistributedSystem().getDistributedMember();
        }
    };
    final DistributedMember member0 = (DistributedMember) vm0.invoke(createPrRegion);
    final DistributedMember member1 = (DistributedMember) vm1.invoke(createPrRegion);
    // populate the region with data so we have some buckets
    vm0.invoke(new SerializableRunnable("create data") {

        public void run() {
            for (int i = 0; i < 8; i++) {
                Region<Object, Object> region = getCache().getRegion("region1");
                region.put(i, "one");
            }
        }
    });
    // Create VM 2 later so that it doesn't have any buckets
    final DistributedMember member2 = (DistributedMember) vm2.invoke(createPrRegion);
    // Try some explicit moves
    vm0.invoke(new SerializableRunnable("create data") {

        public void run() {
            Region<Object, Object> region = getCache().getRegion("region1");
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 1), member0, member1);
            // Try to move a bucket to a member that already has the bucket
            try {
                PartitionRegionHelper.moveBucketByKey(region, member0, member1, 1);
                fail("Should have received an exception");
            } catch (IllegalStateException expected) {
                System.err.println(expected);
            }
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 1), member0, member1);
            // Try to move the bucket from a member that doesn't have the bucket
            try {
                PartitionRegionHelper.moveBucketByKey(region, member2, member2, 1);
                fail("Should have received an exception");
            } catch (IllegalStateException expected) {
                System.err.println(expected);
            }
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 1), member0, member1);
            // Try to move the bucket from an invalid member
            try {
                PartitionRegionHelper.moveBucketByKey(region, member2, new InternalDistributedMember("localhost", 5), 1);
                fail("Should have received an exception");
            } catch (IllegalStateException expected) {
                System.err.println(expected);
            }
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 1), member0, member1);
            // Try to move the bucket that doesn't exist
            try {
                PartitionRegionHelper.moveBucketByKey(region, member0, member2, 10);
                fail("Should have received an exception");
            } catch (IllegalStateException expected) {
                System.err.println(expected);
            }
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 10));
            // Do some successful moves.
            PartitionRegionHelper.moveBucketByKey(region, member0, member2, 1);
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 1), member1, member2);
            PartitionRegionHelper.moveBucketByKey(region, member2, member0, 1);
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 1), member0, member1);
            PartitionRegionHelper.moveBucketByKey(region, member0, member2, 2);
            PartitionRegionHelper.moveBucketByKey(region, member1, member2, 3);
            PartitionRegionHelper.moveBucketByKey(region, member1, member2, 4);
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 2), member1, member2);
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 3), member0, member2);
            assertHasMembers(PartitionRegionHelper.getAllMembersForKey(region, 4), member0, member2);
        }
    });
}
Also used : PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) AttributesFactory(org.apache.geode.cache.AttributesFactory) PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) PartitionAttributes(org.apache.geode.cache.PartitionAttributes) FixedPartitionAttributes(org.apache.geode.cache.FixedPartitionAttributes) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) DistributedMember(org.apache.geode.distributed.DistributedMember) SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) BucketRegion(org.apache.geode.internal.cache.BucketRegion) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) Host(org.apache.geode.test.dunit.Host) Cache(org.apache.geode.cache.Cache) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Aggregations

PartitionAttributes (org.apache.geode.cache.PartitionAttributes)129 PartitionAttributesFactory (org.apache.geode.cache.PartitionAttributesFactory)117 AttributesFactory (org.apache.geode.cache.AttributesFactory)107 Region (org.apache.geode.cache.Region)82 Test (org.junit.Test)67 Cache (org.apache.geode.cache.Cache)66 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)61 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)49 Host (org.apache.geode.test.dunit.Host)48 VM (org.apache.geode.test.dunit.VM)48 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)47 CacheSerializableRunnable (org.apache.geode.cache30.CacheSerializableRunnable)38 RegionAttributes (org.apache.geode.cache.RegionAttributes)28 CacheException (org.apache.geode.cache.CacheException)26 LocalRegion (org.apache.geode.internal.cache.LocalRegion)26 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)21 BucketRegion (org.apache.geode.internal.cache.BucketRegion)19 FixedPartitionAttributes (org.apache.geode.cache.FixedPartitionAttributes)18 RebalanceResults (org.apache.geode.cache.control.RebalanceResults)16 HashSet (java.util.HashSet)15