Search in sources :

Example 16 with CacheWriterException

use of org.apache.geode.cache.CacheWriterException 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 17 with CacheWriterException

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

the class ExportLogsCacheWriter method beforeCreate.

@Override
public void beforeCreate(EntryEvent event) throws CacheWriterException {
    if (currentOutputStream == null) {
        throw new IllegalStateException("No outputStream is open.  You must call startFile before sending data.");
    }
    try {
        Object newValue = event.getNewValue();
        if (!(newValue instanceof byte[])) {
            throw new IllegalArgumentException("Value must be a byte[].  Recieved " + newValue.getClass().getCanonicalName());
        }
        currentOutputStream.write((byte[]) newValue);
        isEmpty = false;
    } catch (IOException e) {
        throw new CacheWriterException(e);
    }
}
Also used : IOException(java.io.IOException) CacheWriterException(org.apache.geode.cache.CacheWriterException)

Example 18 with CacheWriterException

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

the class ClientStatsManager method publishClientStats.

/**
   * This method publishes the client stats using the admin region.
   * 
   * @param pool Connection pool which may be used for admin region.
   */
public static synchronized void publishClientStats(PoolImpl pool) {
    InternalCache currentCache = GemFireCacheImpl.getInstance();
    if (!initializeStatistics(currentCache)) {
        // handles null case too
        return;
    }
    LogWriterI18n logger = currentCache.getLoggerI18n();
    if (logger.fineEnabled())
        logger.fine("Entering ClientStatsManager#publishClientStats...");
    ClientHealthStats stats = getClientHealthStats(currentCache, pool);
    try {
        InternalDistributedSystem ds = (InternalDistributedSystem) currentCache.getDistributedSystem();
        ServerRegionProxy regionProxy = new ServerRegionProxy(ClientHealthMonitoringRegion.ADMIN_REGION_NAME, pool);
        EventID eventId = new EventID(ds);
        @Released EntryEventImpl event = new EntryEventImpl((Object) null);
        try {
            event.setEventId(eventId);
            regionProxy.putForMetaRegion(ds.getMemberId(), stats, null, event, null, true);
        } finally {
            event.release();
        }
    } catch (DistributedSystemDisconnectedException e) {
        throw e;
    } catch (CacheWriterException cwx) {
        pool.getCancelCriterion().checkCancelInProgress(cwx);
        currentCache.getCancelCriterion().checkCancelInProgress(cwx);
        // TODO: Need to analyze these exception scenarios.
        logger.warning(LocalizedStrings.ClientStatsManager_FAILED_TO_SEND_CLIENT_HEALTH_STATS_TO_CACHESERVER, cwx);
    } catch (Exception e) {
        pool.getCancelCriterion().checkCancelInProgress(e);
        currentCache.getCancelCriterion().checkCancelInProgress(e);
        logger.info(LocalizedStrings.ClientStatsManager_FAILED_TO_PUBLISH_CLIENT_STATISTICS, e);
    }
    if (logger.fineEnabled()) {
        logger.fine("Exiting ClientStatsManager#publishClientStats.");
    }
}
Also used : DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) Released(org.apache.geode.internal.offheap.annotations.Released) EntryEventImpl(org.apache.geode.internal.cache.EntryEventImpl) ServerRegionProxy(org.apache.geode.cache.client.internal.ServerRegionProxy) InternalCache(org.apache.geode.internal.cache.InternalCache) EventID(org.apache.geode.internal.cache.EventID) LogWriterI18n(org.apache.geode.i18n.LogWriterI18n) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) ClientHealthStats(org.apache.geode.internal.admin.remote.ClientHealthStats) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CacheWriterException(org.apache.geode.cache.CacheWriterException) CacheWriterException(org.apache.geode.cache.CacheWriterException)

Example 19 with CacheWriterException

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

the class DistTXState method applyOpsOnRedundantCopy.

protected boolean applyOpsOnRedundantCopy(DistributedMember sender, ArrayList<DistTxEntryEvent> secondaryTransactionalOperations) {
    boolean returnValue = true;
    try {
        boolean result = true;
        // Start TxState Update During PreCommit phase
        setUpdatingTxStateDuringPreCommit(true);
        if (logger.isDebugEnabled()) {
            logger.debug("DistTXState.applyOpOnRedundantCopy: size of " + "secondaryTransactionalOperations = {}", secondaryTransactionalOperations.size());
        }
        /*
       * Handle Put Operations meant for secondary.
       * 
       * @see org.apache.geode.internal.cache.partitioned.PutMessage.
       * operateOnPartitionedRegion(DistributionManager, PartitionedRegion, long)
       * 
       * [DISTTX] TODO need to handle other operations
       */
        for (DistTxEntryEvent dtop : secondaryTransactionalOperations) {
            if (logger.isDebugEnabled()) {
                logger.debug("DistTXState.applyOpOnRedundantCopy: processing dist " + "tx operation {}", dtop);
            }
            dtop.setDistributedMember(sender);
            dtop.setOriginRemote(false);
            /*
         * [DISTTX} TODO handle call back argument version tag and other settings in PutMessage
         */
            String failureReason = null;
            try {
                if (dtop.getKeyInfo().isDistKeyInfo()) {
                    dtop.getKeyInfo().setCheckPrimary(false);
                } else {
                    dtop.setKeyInfo(new DistTxKeyInfo(dtop.getKeyInfo()));
                    dtop.getKeyInfo().setCheckPrimary(false);
                }
                // apply the op
                result = applyIndividualOp(dtop);
                if (!result) {
                    // make sure the region hasn't gone away
                    dtop.getRegion().checkReadiness();
                }
            } catch (CacheWriterException cwe) {
                result = false;
                failureReason = "CacheWriterException";
            } catch (PrimaryBucketException pbe) {
                result = false;
                failureReason = "PrimaryBucketException";
            } catch (InvalidDeltaException ide) {
                result = false;
                failureReason = "InvalidDeltaException";
            } catch (DataLocationException e) {
                result = false;
                failureReason = "DataLocationException";
            }
            if (logger.isDebugEnabled()) {
                logger.debug("DistTXState.applyOpOnRedundantCopy {} ##op {},  " + "##region {}, ##key {}", (result ? " sucessfully applied op " : " failed to apply op due to " + failureReason), dtop.getOperation(), dtop.getRegion().getName(), dtop.getKey());
            }
            if (!result) {
                returnValue = false;
                break;
            }
        }
    } finally {
        // End TxState Update During PreCommit phase
        setUpdatingTxStateDuringPreCommit(false);
    }
    return returnValue;
}
Also used : InvalidDeltaException(org.apache.geode.InvalidDeltaException) DistTxEntryEvent(org.apache.geode.internal.cache.tx.DistTxEntryEvent) DistTxKeyInfo(org.apache.geode.internal.cache.tx.DistTxKeyInfo) CacheWriterException(org.apache.geode.cache.CacheWriterException)

Example 20 with CacheWriterException

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

the class PutMessage method operateOnPartitionedRegion.

/**
   * This method is called upon receipt and make the desired changes to the PartitionedRegion Note:
   * It is very important that this message does NOT cause any deadlocks as the sender will wait
   * indefinitely for the acknowledgement
   */
@Override
protected boolean operateOnPartitionedRegion(DistributionManager dm, PartitionedRegion r, long startTime) throws EntryExistsException, DataLocationException, IOException {
    // set the internal DS. Required to
    this.setInternalDs(r.getSystem());
    // checked DS level delta-enabled property
    // while sending delta
    PartitionedRegionDataStore ds = r.getDataStore();
    boolean sendReply = true;
    InternalDistributedMember eventSender = originalSender;
    if (eventSender == null) {
        eventSender = getSender();
    }
    @Released final EntryEventImpl ev = EntryEventImpl.create(r, getOperation(), getKey(), null, /* newValue */
    getCallbackArg(), false, /* originRemote - false to force distribution in buckets */
    eventSender, true, /* generateCallbacks */
    false);
    try {
        if (this.versionTag != null) {
            this.versionTag.replaceNullIDs(getSender());
            ev.setVersionTag(this.versionTag);
        }
        if (this.bridgeContext != null) {
            ev.setContext(this.bridgeContext);
        }
        Assert.assertTrue(eventId != null);
        ev.setEventId(eventId);
        ev.setCausedByMessage(this);
        ev.setInvokePRCallbacks(!notificationOnly);
        ev.setPossibleDuplicate(this.posDup);
        /*
       * if (this.hasOldValue) { if (this.oldValueIsSerialized) {
       * ev.setSerializedOldValue(getOldValueBytes()); } else { ev.setOldValue(getOldValueBytes());
       * } }
       */
        ev.setDeltaBytes(this.deltaBytes);
        if (this.hasDelta) {
            this.valObj = null;
            // New value will be set once it is generated with fromDelta() inside
            // EntryEventImpl.processDeltaBytes()
            ev.setNewValue(this.valObj);
        } else {
            switch(this.deserializationPolicy) {
                case DistributedCacheOperation.DESERIALIZATION_POLICY_LAZY:
                    ev.setSerializedNewValue(getValBytes());
                    break;
                case DistributedCacheOperation.DESERIALIZATION_POLICY_NONE:
                    ev.setNewValue(getValBytes());
                    break;
                default:
                    throw new AssertionError("unknown deserialization policy: " + deserializationPolicy);
            }
        }
        if (!notificationOnly) {
            if (ds == null) {
                throw new AssertionError("This process should have storage" + " for this operation: " + this.toString());
            }
            try {
                // the event must show it's true origin for cachewriter invocation
                // event.setOriginRemote(true);
                // this.op = r.doCacheWriteBeforePut(event, ifNew); // TODO fix this for bug 37072
                ev.setOriginRemote(false);
                result = r.getDataView().putEntryOnRemote(ev, this.ifNew, this.ifOld, this.expectedOldValue, this.requireOldValue, this.lastModified, true);
                if (!this.result) {
                    // make sure the region hasn't gone away
                    r.checkReadiness();
                // sbawaska: I cannot see how ifOld and ifNew can both be false, hence removing
                // if (!this.ifNew && !this.ifOld) {
                // // no reason to be throwing an exception, so let's retry
                // ForceReattemptException fre = new ForceReattemptException(
                // LocalizedStrings.PutMessage_UNABLE_TO_PERFORM_PUT_BUT_OPERATION_SHOULD_NOT_FAIL_0.toLocalizedString());
                // fre.setHash(key.hashCode());
                // sendReply(getSender(), getProcessorId(), dm,
                // new ReplyException(fre), r, startTime);
                // sendReply = false;
                // }
                }
            } catch (CacheWriterException cwe) {
                sendReply(getSender(), getProcessorId(), dm, new ReplyException(cwe), r, startTime);
                return false;
            } catch (PrimaryBucketException pbe) {
                sendReply(getSender(), getProcessorId(), dm, new ReplyException(pbe), r, startTime);
                return false;
            } catch (InvalidDeltaException ide) {
                sendReply(getSender(), getProcessorId(), dm, new ReplyException(ide), r, startTime);
                r.getCachePerfStats().incDeltaFullValuesRequested();
                return false;
            }
            if (logger.isTraceEnabled(LogMarker.DM)) {
                logger.trace(LogMarker.DM, "PutMessage {} with key: {} val: {}", (result ? "updated bucket" : "did not update bucket"), getKey(), (getValBytes() == null ? "null" : "(" + getValBytes().length + " bytes)"));
            }
        } else {
            // notificationOnly
            @Released EntryEventImpl e2 = createListenerEvent(ev, r, dm.getDistributionManagerId());
            final EnumListenerEvent le;
            try {
                if (e2.getOperation().isCreate()) {
                    le = EnumListenerEvent.AFTER_CREATE;
                } else {
                    le = EnumListenerEvent.AFTER_UPDATE;
                }
                r.invokePutCallbacks(le, e2, r.isInitialized(), true);
            } finally {
                // if e2 == ev then no need to free it here. The outer finally block will get it.
                if (e2 != ev) {
                    e2.release();
                }
            }
            result = true;
        }
        // set operation for reply message
        setOperation(ev.getOperation());
        if (sendReply) {
            sendReply(getSender(), getProcessorId(), dm, null, r, startTime, ev);
        }
        return false;
    } finally {
        ev.release();
    }
}
Also used : InvalidDeltaException(org.apache.geode.InvalidDeltaException) EnumListenerEvent(org.apache.geode.internal.cache.EnumListenerEvent) Released(org.apache.geode.internal.offheap.annotations.Released) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) EntryEventImpl(org.apache.geode.internal.cache.EntryEventImpl) PartitionedRegionDataStore(org.apache.geode.internal.cache.PartitionedRegionDataStore) PrimaryBucketException(org.apache.geode.internal.cache.PrimaryBucketException) ReplyException(org.apache.geode.distributed.internal.ReplyException) CacheWriterException(org.apache.geode.cache.CacheWriterException)

Aggregations

CacheWriterException (org.apache.geode.cache.CacheWriterException)50 Region (org.apache.geode.cache.Region)22 Test (org.junit.Test)14 EntryEvent (org.apache.geode.cache.EntryEvent)13 Released (org.apache.geode.internal.offheap.annotations.Released)12 AttributesFactory (org.apache.geode.cache.AttributesFactory)11 CacheException (org.apache.geode.cache.CacheException)11 TimeoutException (org.apache.geode.cache.TimeoutException)11 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)10 CacheWriterAdapter (org.apache.geode.cache.util.CacheWriterAdapter)9 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)9 EntryNotFoundException (org.apache.geode.cache.EntryNotFoundException)8 VM (org.apache.geode.test.dunit.VM)8 Cache (org.apache.geode.cache.Cache)7 RegionEvent (org.apache.geode.cache.RegionEvent)7 Host (org.apache.geode.test.dunit.Host)7 IOException (java.io.IOException)6 CacheWriter (org.apache.geode.cache.CacheWriter)6 EntryEventImpl (org.apache.geode.internal.cache.EntryEventImpl)6 InternalGemFireError (org.apache.geode.InternalGemFireError)5