Search in sources :

Example 6 with VersionedObjectList

use of org.apache.geode.internal.cache.tier.sockets.VersionedObjectList in project geode by apache.

the class RemoveAll method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long startp) throws IOException, InterruptedException {
    // copy this since we need to modify it
    long start = startp;
    Part regionNamePart = null, numberOfKeysPart = null, keyPart = null;
    String regionName = null;
    int numberOfKeys = 0;
    Object key = null;
    Part eventPart = null;
    boolean replyWithMetaData = false;
    VersionedObjectList response = null;
    StringBuffer errMessage = new StringBuffer();
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    serverConnection.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadRemoveAllRequestTime(start - oldStart);
    }
    try {
        // Retrieve the data from the message parts
        // part 0: region name
        regionNamePart = clientMessage.getPart(0);
        regionName = regionNamePart.getString();
        if (regionName == null) {
            String txt = LocalizedStrings.RemoveAll_THE_INPUT_REGION_NAME_FOR_THE_REMOVEALL_REQUEST_IS_NULL.toLocalizedString();
            logger.warn(LocalizedMessage.create(LocalizedStrings.TWO_ARG_COLON, new Object[] { serverConnection.getName(), txt }));
            errMessage.append(txt);
            writeChunkedErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
        LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
        if (region == null) {
            String reason = " was not found during removeAll request";
            writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
        // part 1: eventID
        eventPart = clientMessage.getPart(1);
        ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
        long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
        long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
        EventID eventId = new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId);
        Breadcrumbs.setEventId(eventId);
        // part 2: flags
        int flags = clientMessage.getPart(2).getInt();
        boolean clientIsEmpty = (flags & PutAllOp.FLAG_EMPTY) != 0;
        boolean clientHasCCEnabled = (flags & PutAllOp.FLAG_CONCURRENCY_CHECKS) != 0;
        // part 3: callbackArg
        Object callbackArg = clientMessage.getPart(3).getObject();
        // part 4: number of keys
        numberOfKeysPart = clientMessage.getPart(4);
        numberOfKeys = numberOfKeysPart.getInt();
        if (logger.isDebugEnabled()) {
            StringBuilder buffer = new StringBuilder();
            buffer.append(serverConnection.getName()).append(": Received removeAll request from ").append(serverConnection.getSocketString()).append(" for region ").append(regionName).append(callbackArg != null ? (" callbackArg " + callbackArg) : "").append(" with ").append(numberOfKeys).append(" keys.");
            logger.debug(buffer);
        }
        ArrayList<Object> keys = new ArrayList<Object>(numberOfKeys);
        ArrayList<VersionTag> retryVersions = new ArrayList<VersionTag>(numberOfKeys);
        for (int i = 0; i < numberOfKeys; i++) {
            keyPart = clientMessage.getPart(5 + i);
            key = keyPart.getStringOrObject();
            if (key == null) {
                String txt = LocalizedStrings.RemoveAll_ONE_OF_THE_INPUT_KEYS_FOR_THE_REMOVEALL_REQUEST_IS_NULL.toLocalizedString();
                logger.warn(LocalizedMessage.create(LocalizedStrings.TWO_ARG_COLON, new Object[] { serverConnection.getName(), txt }));
                errMessage.append(txt);
                writeChunkedErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
                serverConnection.setAsTrue(RESPONDED);
                return;
            }
            if (clientMessage.isRetry()) {
                // Constuct the thread id/sequence id information for this element of the bulk op
                // The sequence id is constructed from the base sequence id and the offset
                EventID entryEventId = new EventID(eventId, i);
                // For PRs, the thread id assigned as a fake thread id.
                if (region instanceof PartitionedRegion) {
                    PartitionedRegion pr = (PartitionedRegion) region;
                    int bucketId = pr.getKeyInfo(key).getBucketId();
                    long entryThreadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId, entryEventId.getThreadID());
                    entryEventId = new EventID(entryEventId.getMembershipID(), entryThreadId, entryEventId.getSequenceID());
                }
                VersionTag tag = findVersionTagsForRetriedBulkOp(region, entryEventId);
                retryVersions.add(tag);
            // FIND THE VERSION TAG FOR THIS KEY - but how? all we have is the
            // removeAll eventId, not individual eventIds for entries, right?
            } else {
                retryVersions.add(null);
            }
            keys.add(key);
        }
        if (clientMessage.getNumberOfParts() == (5 + numberOfKeys + 1)) {
            // it means optional timeout
            // has been
            // added
            int timeout = clientMessage.getPart(5 + numberOfKeys).getInt();
            serverConnection.setRequestSpecificTimeout(timeout);
        }
        this.securityService.authorizeRegionWrite(regionName);
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
                authzRequest.createRegionAuthorize(regionName);
            } else {
                RemoveAllOperationContext removeAllContext = authzRequest.removeAllAuthorize(regionName, keys, callbackArg);
                callbackArg = removeAllContext.getCallbackArg();
            }
        }
        response = region.basicBridgeRemoveAll(keys, retryVersions, serverConnection.getProxyID(), eventId, callbackArg);
        if (!region.getConcurrencyChecksEnabled() || clientIsEmpty || !clientHasCCEnabled) {
            // has storage
            if (logger.isTraceEnabled()) {
                logger.trace("setting removeAll response to null. region-cc-enabled={}; clientIsEmpty={}; client-cc-enabled={}", region.getConcurrencyChecksEnabled(), clientIsEmpty, clientHasCCEnabled);
            }
            response = null;
        }
        if (region instanceof PartitionedRegion) {
            PartitionedRegion pr = (PartitionedRegion) region;
            if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
                writeReplyWithRefreshMetadata(clientMessage, response, serverConnection, pr, pr.getNetworkHopType());
                pr.clearNetworkHopData();
                replyWithMetaData = true;
            }
        }
    } catch (RegionDestroyedException rde) {
        writeChunkedException(clientMessage, rde, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (ResourceException re) {
        writeChunkedException(clientMessage, re, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (PutAllPartialResultException pre) {
        writeChunkedException(clientMessage, pre, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (Exception ce) {
        // If an interrupted exception is thrown , rethrow it
        checkForInterrupt(serverConnection, ce);
        // If an exception occurs during the op, preserve the connection
        writeChunkedException(clientMessage, ce, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        // if (logger.fineEnabled()) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.Generic_0_UNEXPECTED_EXCEPTION, serverConnection.getName()), ce);
        // }
        return;
    } finally {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessRemoveAllTime(start - oldStart);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending removeAll response back to {} for region {}{}", serverConnection.getName(), serverConnection.getSocketString(), regionName, (logger.isTraceEnabled() ? ": " + response : ""));
    }
    // Increment statistics and write the reply
    if (!replyWithMetaData) {
        writeReply(clientMessage, response, serverConnection);
    }
    serverConnection.setAsTrue(RESPONDED);
    stats.incWriteRemoveAllResponseTime(DistributionStats.getStatTime() - start);
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) ArrayList(java.util.ArrayList) VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) LocalRegion(org.apache.geode.internal.cache.LocalRegion) RemoveAllOperationContext(org.apache.geode.cache.operations.RemoveAllOperationContext) PutAllPartialResultException(org.apache.geode.internal.cache.PutAllPartialResultException) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) VersionTag(org.apache.geode.internal.cache.versions.VersionTag) ResourceException(org.apache.geode.cache.ResourceException) ByteBuffer(java.nio.ByteBuffer) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) PutAllPartialResultException(org.apache.geode.internal.cache.PutAllPartialResultException) IOException(java.io.IOException) ResourceException(org.apache.geode.cache.ResourceException) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) Part(org.apache.geode.internal.cache.tier.sockets.Part) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) EventID(org.apache.geode.internal.cache.EventID)

Example 7 with VersionedObjectList

use of org.apache.geode.internal.cache.tier.sockets.VersionedObjectList in project geode by apache.

the class RemoveAll method writeReplyWithRefreshMetadata.

private void writeReplyWithRefreshMetadata(Message origMsg, VersionedObjectList response, ServerConnection servConn, PartitionedRegion pr, byte nwHop) throws IOException {
    servConn.getCache().getCancelCriterion().checkCancelInProgress(null);
    ChunkedMessage replyMsg = servConn.getChunkedResponseMessage();
    replyMsg.setMessageType(MessageType.RESPONSE);
    replyMsg.setTransactionId(origMsg.getTransactionId());
    replyMsg.sendHeader();
    int listSize = (response == null) ? 0 : response.size();
    if (logger.isDebugEnabled()) {
        logger.debug("sending chunked response header with metadata refresh status. Version list size = {}{}", listSize, (logger.isTraceEnabled() ? "; list=" + response : ""));
    }
    if (response != null) {
        response.setKeys(null);
    }
    replyMsg.setNumberOfParts(1);
    replyMsg.setTransactionId(origMsg.getTransactionId());
    replyMsg.addBytesPart(new byte[] { pr.getMetadataVersion(), nwHop });
    if (listSize > 0) {
        replyMsg.setLastChunk(false);
        replyMsg.sendChunk(servConn);
        // MAXIMUM_CHUNK_SIZE
        int chunkSize = 2 * MAXIMUM_CHUNK_SIZE;
        // Chunker will stream over the list in its toData method
        VersionedObjectList.Chunker chunk = new VersionedObjectList.Chunker(response, chunkSize, false, false);
        for (int i = 0; i < listSize; i += chunkSize) {
            boolean lastChunk = (i + chunkSize >= listSize);
            // resets the message
            replyMsg.setNumberOfParts(1);
            replyMsg.setMessageType(MessageType.RESPONSE);
            replyMsg.setLastChunk(lastChunk);
            replyMsg.setTransactionId(origMsg.getTransactionId());
            replyMsg.addObjPart(chunk);
            if (logger.isDebugEnabled()) {
                logger.debug("sending chunk at index {} last chunk={} numParts={}", i, lastChunk, replyMsg.getNumberOfParts());
            }
            replyMsg.sendChunk(servConn);
        }
    } else {
        replyMsg.setLastChunk(true);
        if (logger.isDebugEnabled()) {
            logger.debug("sending first and only part of chunked message");
        }
        replyMsg.sendChunk(servConn);
    }
    pr.getPrStats().incPRMetaDataSentCount();
    if (logger.isTraceEnabled()) {
        logger.trace("{}: rpl with REFRESH_METADATA tx: {}", servConn.getName(), origMsg.getTransactionId());
    }
}
Also used : VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) ChunkedMessage(org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)

Example 8 with VersionedObjectList

use of org.apache.geode.internal.cache.tier.sockets.VersionedObjectList in project geode by apache.

the class PutAll80 method writeReply.

protected void writeReply(Message origMsg, VersionedObjectList response, ServerConnection servConn) throws IOException {
    servConn.getCache().getCancelCriterion().checkCancelInProgress(null);
    ChunkedMessage replyMsg = servConn.getChunkedResponseMessage();
    replyMsg.setMessageType(MessageType.RESPONSE);
    replyMsg.setTransactionId(origMsg.getTransactionId());
    int listSize = (response == null) ? 0 : response.size();
    if (response != null) {
        response.setKeys(null);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("sending chunked response header.  version list size={}{}", listSize, (logger.isTraceEnabled() ? " list=" + response : ""));
    }
    replyMsg.sendHeader();
    if (listSize > 0) {
        int chunkSize = 2 * MAXIMUM_CHUNK_SIZE;
        // Chunker will stream over the list in its toData method
        VersionedObjectList.Chunker chunk = new VersionedObjectList.Chunker(response, chunkSize, false, false);
        for (int i = 0; i < listSize; i += chunkSize) {
            boolean lastChunk = (i + chunkSize >= listSize);
            replyMsg.setNumberOfParts(1);
            replyMsg.setMessageType(MessageType.RESPONSE);
            replyMsg.setLastChunk(lastChunk);
            replyMsg.setTransactionId(origMsg.getTransactionId());
            replyMsg.addObjPart(chunk);
            if (logger.isDebugEnabled()) {
                logger.debug("sending chunk at index {} last chunk={} numParts={}", i, lastChunk, replyMsg.getNumberOfParts());
            }
            replyMsg.sendChunk(servConn);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("sending only header");
        }
        replyMsg.addObjPart(null);
        replyMsg.setLastChunk(true);
        replyMsg.sendChunk(servConn);
    }
    servConn.setAsTrue(RESPONDED);
    if (logger.isTraceEnabled()) {
        logger.trace("{}: rpl tx: {}", servConn.getName(), origMsg.getTransactionId());
    }
}
Also used : VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) ChunkedMessage(org.apache.geode.internal.cache.tier.sockets.ChunkedMessage)

Example 9 with VersionedObjectList

use of org.apache.geode.internal.cache.tier.sockets.VersionedObjectList in project geode by apache.

the class LocalRegion method basicPutAll.

// TODO: refactor basicPutAll
public VersionedObjectList basicPutAll(final Map<?, ?> map, final DistributedPutAllOperation putAllOp, final Map<Object, VersionTag> retryVersions) {
    final boolean isDebugEnabled = logger.isDebugEnabled();
    final EntryEventImpl event = putAllOp.getBaseEvent();
    EventID eventId = event.getEventId();
    if (eventId == null && generateEventID()) {
        // We need to "reserve" the eventIds for the entries in map here
        event.reserveNewEventId(this.cache.getDistributedSystem(), map.size());
        eventId = event.getEventId();
    }
    verifyPutAllMap(map);
    VersionedObjectList proxyResult = null;
    boolean partialResult = false;
    RuntimeException runtimeException = null;
    if (hasServerProxy()) {
        // send message to bridge server
        if (isTX()) {
            TXStateProxyImpl txState = (TXStateProxyImpl) this.cache.getTxManager().getTXState();
            txState.getRealDeal(null, this);
        }
        try {
            proxyResult = getServerProxy().putAll(map, eventId, !event.isGenerateCallbacks(), event.getCallbackArgument());
            if (isDebugEnabled) {
                logger.debug("PutAll received response from server: {}", proxyResult);
            }
        } catch (PutAllPartialResultException e) {
            // adjust the map to only add succeeded entries, then apply the adjustedMap
            proxyResult = e.getSucceededKeysAndVersions();
            partialResult = true;
            if (isDebugEnabled) {
                logger.debug("putAll in client encountered a PutAllPartialResultException:{}{}. Adjusted keys are: {}", e.getMessage(), getLineSeparator(), proxyResult.getKeys());
            }
            Throwable txException = e.getFailure();
            while (txException != null) {
                if (txException instanceof TransactionException) {
                    runtimeException = (RuntimeException) txException;
                    break;
                }
                txException = txException.getCause();
            }
            if (runtimeException == null) {
                // for cache close
                runtimeException = getCancelCriterion().generateCancelledException(e.getFailure());
                if (runtimeException == null) {
                    runtimeException = new ServerOperationException(LocalizedStrings.Region_PutAll_Applied_PartialKeys_At_Server_0.toLocalizedString(getFullPath()), e.getFailure());
                }
            }
        }
    }
    final VersionedObjectList succeeded = new VersionedObjectList(map.size(), true, this.concurrencyChecksEnabled);
    // if this is a transactional putAll, we will not have version information as it is only
    // generated at commit
    // so treat transactional putAll as if the server is not versioned
    final boolean serverIsVersioned = proxyResult != null && proxyResult.regionIsVersioned() && !isTX() && this.dataPolicy != DataPolicy.EMPTY;
    if (!serverIsVersioned && !partialResult) {
        // we don't need server information if it isn't versioned or if the region is empty
        proxyResult = null;
    }
    lockRVVForBulkOp();
    try {
        try {
            int size = proxyResult == null ? map.size() : proxyResult.size();
            if (isDebugEnabled) {
                logger.debug("size of put result is {} maps is {} proxyResult is {}", size, map, proxyResult);
            }
            final PutAllPartialResult partialKeys = new PutAllPartialResult(size);
            final Iterator iterator;
            final boolean isVersionedResults;
            if (proxyResult != null) {
                iterator = proxyResult.iterator();
                isVersionedResults = true;
            } else {
                iterator = map.entrySet().iterator();
                isVersionedResults = false;
            }
            // TODO: refactor this mess
            Runnable task = new Runnable() {

                @Override
                public void run() {
                    int offset = 0;
                    VersionTagHolder tagHolder = new VersionTagHolder();
                    while (iterator.hasNext()) {
                        stopper.checkCancelInProgress(null);
                        Map.Entry mapEntry = (Map.Entry) iterator.next();
                        Object key = mapEntry.getKey();
                        VersionTag versionTag = null;
                        tagHolder.setVersionTag(null);
                        final Object value;
                        boolean overwritten = false;
                        if (isVersionedResults) {
                            versionTag = ((VersionedObjectList.Entry) mapEntry).getVersionTag();
                            value = map.get(key);
                            if (isDebugEnabled) {
                                logger.debug("putAll key {} -> {} version={}", key, value, versionTag);
                            }
                            if (versionTag == null && serverIsVersioned && concurrencyChecksEnabled && dataPolicy.withStorage()) {
                                // entry since we don't know what its state should be (but the server should)
                                if (isDebugEnabled) {
                                    logger.debug("server returned no version information for {}", key);
                                }
                                localDestroyNoCallbacks(key);
                                // to be consistent we need to fetch the current entry
                                get(key, event.getCallbackArgument(), false, null);
                                overwritten = true;
                            }
                        } else {
                            value = mapEntry.getValue();
                            if (isDebugEnabled) {
                                logger.debug("putAll {} -> {}", key, value);
                            }
                        }
                        try {
                            if (serverIsVersioned) {
                                if (isDebugEnabled) {
                                    logger.debug("associating version tag with {} version={}", key, versionTag);
                                }
                                // If we have received a version tag from a server, add it to the event
                                tagHolder.setVersionTag(versionTag);
                                tagHolder.setFromServer(true);
                            } else if (retryVersions != null && retryVersions.containsKey(key)) {
                                // If this is a retried event, and we have a version tag for the retry,
                                // add it to the event.
                                tagHolder.setVersionTag(retryVersions.get(key));
                            }
                            if (!overwritten) {
                                basicEntryPutAll(key, value, putAllOp, offset, tagHolder);
                            }
                            // now we must check again since the cache may have closed during
                            // distribution (causing this process to not receive and queue the
                            // event for clients
                            stopper.checkCancelInProgress(null);
                            succeeded.addKeyAndVersion(key, tagHolder.getVersionTag());
                        } catch (Exception ex) {
                            if (isDebugEnabled) {
                                logger.debug("PutAll operation encountered exception for key {}", key, ex);
                            }
                            partialKeys.saveFailedKey(key, ex);
                        }
                        offset++;
                    }
                }
            };
            syncBulkOp(task, eventId);
            if (partialKeys.hasFailure()) {
                // Bug 51725: Now succeeded contains an order key list, may be missing the version tags.
                // Save reference of succeeded into partialKeys. The succeeded may be modified by
                // postPutAll() to fill in the version tags.
                partialKeys.setSucceededKeysAndVersions(succeeded);
                logger.info(LocalizedMessage.create(LocalizedStrings.Region_PutAll_Applied_PartialKeys_0_1, new Object[] { getFullPath(), partialKeys }));
                if (isDebugEnabled) {
                    logger.debug(partialKeys.detailString());
                }
                if (runtimeException == null) {
                    // if received exception from server first, ignore local exception
                    if (putAllOp.isBridgeOperation()) {
                        if (partialKeys.getFailure() instanceof CancelException) {
                            runtimeException = (RuntimeException) partialKeys.getFailure();
                        } else if (partialKeys.getFailure() instanceof LowMemoryException) {
                            // fix for #43589
                            throw partialKeys.getFailure();
                        } else {
                            runtimeException = new PutAllPartialResultException(partialKeys);
                            if (isDebugEnabled) {
                                logger.debug("basicPutAll:" + partialKeys.detailString());
                            }
                        }
                    } else {
                        throw partialKeys.getFailure();
                    }
                }
            }
        } catch (LowMemoryException lme) {
            throw lme;
        } catch (RuntimeException ex) {
            runtimeException = ex;
        } catch (Exception ex) {
            runtimeException = new RuntimeException(ex);
        } finally {
            putAllOp.getBaseEvent().release();
            putAllOp.freeOffHeapResources();
        }
        getDataView().postPutAll(putAllOp, succeeded, this);
    } finally {
        unlockRVVForBulkOp();
    }
    if (runtimeException != null) {
        throw runtimeException;
    }
    return succeeded;
}
Also used : VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) PutAllPartialResult(org.apache.geode.internal.cache.PutAllPartialResultException.PutAllPartialResult) Endpoint(org.apache.geode.cache.client.internal.Endpoint) TimeoutException(org.apache.geode.cache.TimeoutException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) InternalGemFireException(org.apache.geode.InternalGemFireException) ConflictingPersistentDataException(org.apache.geode.cache.persistence.ConflictingPersistentDataException) CacheRuntimeException(org.apache.geode.cache.CacheRuntimeException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) EntryDestroyedException(org.apache.geode.cache.EntryDestroyedException) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) ExecutionException(java.util.concurrent.ExecutionException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) EntryExistsException(org.apache.geode.cache.EntryExistsException) PartitionedRegionStorageException(org.apache.geode.cache.PartitionedRegionStorageException) StatisticsDisabledException(org.apache.geode.cache.StatisticsDisabledException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) FailedSynchronizationException(org.apache.geode.cache.FailedSynchronizationException) NoSuchElementException(java.util.NoSuchElementException) QueryException(org.apache.geode.cache.query.QueryException) RedundancyAlreadyMetException(org.apache.geode.internal.cache.partitioned.RedundancyAlreadyMetException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) LowMemoryException(org.apache.geode.cache.LowMemoryException) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) SystemException(javax.transaction.SystemException) SubscriptionNotEnabledException(org.apache.geode.cache.client.SubscriptionNotEnabledException) RegionExistsException(org.apache.geode.cache.RegionExistsException) RegionReinitializedException(org.apache.geode.cache.RegionReinitializedException) CancelException(org.apache.geode.CancelException) DiskAccessException(org.apache.geode.cache.DiskAccessException) CacheWriterException(org.apache.geode.cache.CacheWriterException) IndexMaintenanceException(org.apache.geode.cache.query.IndexMaintenanceException) TransactionException(org.apache.geode.cache.TransactionException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CacheClosedException(org.apache.geode.cache.CacheClosedException) RollbackException(javax.transaction.RollbackException) ConcurrentCacheModificationException(org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException) MultiIndexCreationException(org.apache.geode.cache.query.MultiIndexCreationException) DeltaSerializationException(org.apache.geode.DeltaSerializationException) LRUEntry(org.apache.geode.internal.cache.lru.LRUEntry) CacheRuntimeException(org.apache.geode.cache.CacheRuntimeException) TransactionException(org.apache.geode.cache.TransactionException) Iterator(java.util.Iterator) VersionTag(org.apache.geode.internal.cache.versions.VersionTag) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) StoredObject(org.apache.geode.internal.offheap.StoredObject) CancelException(org.apache.geode.CancelException) Map(java.util.Map) IndexMap(org.apache.geode.internal.cache.persistence.query.IndexMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashMap(java.util.HashMap) LowMemoryException(org.apache.geode.cache.LowMemoryException)

Example 10 with VersionedObjectList

use of org.apache.geode.internal.cache.tier.sockets.VersionedObjectList in project geode by apache.

the class LocalRegion method basicRemoveAll.

VersionedObjectList basicRemoveAll(final Collection<Object> keys, final DistributedRemoveAllOperation removeAllOp, final List<VersionTag> retryVersions) {
    final boolean isDebugEnabled = logger.isDebugEnabled();
    final boolean isTraceEnabled = logger.isTraceEnabled();
    final EntryEventImpl event = removeAllOp.getBaseEvent();
    EventID eventId = event.getEventId();
    if (eventId == null && generateEventID()) {
        // We need to "reserve" the eventIds for the entries in map here
        event.reserveNewEventId(this.cache.getDistributedSystem(), keys.size());
        eventId = event.getEventId();
    }
    verifyRemoveAllKeys(keys);
    VersionedObjectList proxyResult = null;
    boolean partialResult = false;
    RuntimeException runtimeException = null;
    if (hasServerProxy()) {
        // send message to bridge server
        if (isTX()) {
            TXStateProxyImpl txState = (TXStateProxyImpl) this.cache.getTxManager().getTXState();
            txState.getRealDeal(null, this);
        }
        try {
            proxyResult = getServerProxy().removeAll(keys, eventId, event.getCallbackArgument());
            if (isDebugEnabled) {
                logger.debug("removeAll received response from server: {}", proxyResult);
            }
        } catch (PutAllPartialResultException e) {
            // adjust the map to only add succeeded entries, then apply the adjustedMap
            proxyResult = e.getSucceededKeysAndVersions();
            partialResult = true;
            if (isDebugEnabled) {
                logger.debug("removeAll in client encountered a BulkOpPartialResultException: {}{}. Adjusted keys are: {}", e.getMessage(), getLineSeparator(), proxyResult.getKeys());
            }
            Throwable txException = e.getFailure();
            while (txException != null) {
                if (txException instanceof TransactionException) {
                    runtimeException = (RuntimeException) txException;
                    break;
                }
                txException = txException.getCause();
            }
            if (runtimeException == null) {
                runtimeException = new ServerOperationException(LocalizedStrings.Region_RemoveAll_Applied_PartialKeys_At_Server_0.toLocalizedString(getFullPath()), e.getFailure());
            }
        }
    }
    final VersionedObjectList succeeded = new VersionedObjectList(keys.size(), true, this.concurrencyChecksEnabled);
    // If this is a transactional removeAll, we will not have version information as it is only
    // generated at commit
    // so treat transactional removeAll as if the server is not versioned.
    // If we have no storage then act as if the server is not versioned.
    final boolean serverIsVersioned = proxyResult != null && proxyResult.regionIsVersioned() && !isTX() && getDataPolicy().withStorage();
    if (!serverIsVersioned && !partialResult) {
        // since the server is not versioned and we do not have a partial result
        // get rid of the proxyResult info returned by the server.
        proxyResult = null;
    }
    lockRVVForBulkOp();
    try {
        try {
            int size = proxyResult == null ? keys.size() : proxyResult.size();
            if (isInternalRegion()) {
                if (isTraceEnabled) {
                    logger.trace("size of removeAll result is {} keys are {} proxyResult is {}", size, keys, proxyResult);
                } else {
                    if (isTraceEnabled) {
                        logger.trace("size of removeAll result is {} keys are {} proxyResult is {}", size, keys, proxyResult);
                    }
                }
            } else {
                if (isTraceEnabled) {
                    logger.trace("size of removeAll result is {} keys are {} proxyResult is {}", size, keys, proxyResult);
                }
            }
            final PutAllPartialResult partialKeys = new PutAllPartialResult(size);
            final Iterator iterator;
            final boolean isVersionedResults;
            if (proxyResult != null) {
                iterator = proxyResult.iterator();
                isVersionedResults = true;
            } else {
                iterator = keys.iterator();
                isVersionedResults = false;
            }
            // TODO: refactor this mess
            Runnable task = new Runnable() {

                @Override
                public void run() {
                    int offset = 0;
                    VersionTagHolder tagHolder = new VersionTagHolder();
                    while (iterator.hasNext()) {
                        stopper.checkCancelInProgress(null);
                        tagHolder.setVersionTag(null);
                        Object key;
                        VersionTag versionTag = null;
                        if (isVersionedResults) {
                            Map.Entry mapEntry = (Map.Entry) iterator.next();
                            key = mapEntry.getKey();
                            versionTag = ((VersionedObjectList.Entry) mapEntry).getVersionTag();
                            if (isDebugEnabled) {
                                logger.debug("removeAll key {} version={}", key, versionTag);
                            }
                            if (versionTag == null) {
                                if (isDebugEnabled) {
                                    logger.debug("removeAll found invalid version tag, which means the entry is not found at server for key={}.", key);
                                }
                                succeeded.addKeyAndVersion(key, null);
                                continue;
                            }
                        // No need for special handling here in removeAll.
                        // We can just remove this key from the client with versionTag set to null.
                        } else {
                            key = iterator.next();
                            if (isTraceEnabled) {
                                logger.trace("removeAll {}", key);
                            }
                        }
                        try {
                            if (serverIsVersioned) {
                                if (isDebugEnabled) {
                                    logger.debug("associating version tag with {} version={}", key, versionTag);
                                }
                                // If we have received a version tag from a server, add it to the event
                                tagHolder.setVersionTag(versionTag);
                                tagHolder.setFromServer(true);
                            } else if (retryVersions != null) {
                                VersionTag versionTag1 = retryVersions.get(offset);
                                if (versionTag1 != null) {
                                    // If this is a retried event, and we have a version tag for the retry,
                                    // add it to the event.
                                    tagHolder.setVersionTag(versionTag1);
                                }
                            }
                            basicEntryRemoveAll(key, removeAllOp, offset, tagHolder);
                            // now we must check again since the cache may have closed during
                            // distribution causing this process to not receive and queue the
                            // event for clients
                            stopper.checkCancelInProgress(null);
                            succeeded.addKeyAndVersion(key, tagHolder.getVersionTag());
                        } catch (Exception ex) {
                            partialKeys.saveFailedKey(key, ex);
                        }
                        offset++;
                    }
                }
            };
            syncBulkOp(task, eventId);
            if (partialKeys.hasFailure()) {
                // Bug 51725: Now succeeded contains an order key list, may be missing the version tags.
                // Save reference of succeeded into partialKeys. The succeeded may be modified by
                // postRemoveAll() to fill in the version tags.
                partialKeys.setSucceededKeysAndVersions(succeeded);
                logger.info(LocalizedMessage.create(LocalizedStrings.Region_RemoveAll_Applied_PartialKeys_0_1, new Object[] { getFullPath(), partialKeys }));
                if (isDebugEnabled) {
                    logger.debug(partialKeys.detailString());
                }
                if (runtimeException == null) {
                    // if received exception from server first, ignore local exception
                    if (removeAllOp.isBridgeOperation()) {
                        if (partialKeys.getFailure() instanceof CancelException) {
                            runtimeException = (RuntimeException) partialKeys.getFailure();
                        } else if (partialKeys.getFailure() instanceof LowMemoryException) {
                            // fix for #43589
                            throw partialKeys.getFailure();
                        } else {
                            runtimeException = new PutAllPartialResultException(partialKeys);
                            if (isDebugEnabled) {
                                logger.debug("basicRemoveAll: {}", partialKeys.detailString());
                            }
                        }
                    } else {
                        throw partialKeys.getFailure();
                    }
                }
            }
        } catch (LowMemoryException lme) {
            throw lme;
        } catch (RuntimeException ex) {
            runtimeException = ex;
        } catch (Exception ex) {
            runtimeException = new RuntimeException(ex);
        } finally {
            removeAllOp.getBaseEvent().release();
            removeAllOp.freeOffHeapResources();
        }
        getDataView().postRemoveAll(removeAllOp, succeeded, this);
    } finally {
        unlockRVVForBulkOp();
    }
    if (runtimeException != null) {
        throw runtimeException;
    }
    return succeeded;
}
Also used : VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) PutAllPartialResult(org.apache.geode.internal.cache.PutAllPartialResultException.PutAllPartialResult) Endpoint(org.apache.geode.cache.client.internal.Endpoint) TimeoutException(org.apache.geode.cache.TimeoutException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) InternalGemFireException(org.apache.geode.InternalGemFireException) ConflictingPersistentDataException(org.apache.geode.cache.persistence.ConflictingPersistentDataException) CacheRuntimeException(org.apache.geode.cache.CacheRuntimeException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) EntryDestroyedException(org.apache.geode.cache.EntryDestroyedException) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) ExecutionException(java.util.concurrent.ExecutionException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) EntryExistsException(org.apache.geode.cache.EntryExistsException) PartitionedRegionStorageException(org.apache.geode.cache.PartitionedRegionStorageException) StatisticsDisabledException(org.apache.geode.cache.StatisticsDisabledException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) FailedSynchronizationException(org.apache.geode.cache.FailedSynchronizationException) NoSuchElementException(java.util.NoSuchElementException) QueryException(org.apache.geode.cache.query.QueryException) RedundancyAlreadyMetException(org.apache.geode.internal.cache.partitioned.RedundancyAlreadyMetException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) LowMemoryException(org.apache.geode.cache.LowMemoryException) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) SystemException(javax.transaction.SystemException) SubscriptionNotEnabledException(org.apache.geode.cache.client.SubscriptionNotEnabledException) RegionExistsException(org.apache.geode.cache.RegionExistsException) RegionReinitializedException(org.apache.geode.cache.RegionReinitializedException) CancelException(org.apache.geode.CancelException) DiskAccessException(org.apache.geode.cache.DiskAccessException) CacheWriterException(org.apache.geode.cache.CacheWriterException) IndexMaintenanceException(org.apache.geode.cache.query.IndexMaintenanceException) TransactionException(org.apache.geode.cache.TransactionException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CacheClosedException(org.apache.geode.cache.CacheClosedException) RollbackException(javax.transaction.RollbackException) ConcurrentCacheModificationException(org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException) MultiIndexCreationException(org.apache.geode.cache.query.MultiIndexCreationException) DeltaSerializationException(org.apache.geode.DeltaSerializationException) LRUEntry(org.apache.geode.internal.cache.lru.LRUEntry) CacheRuntimeException(org.apache.geode.cache.CacheRuntimeException) TransactionException(org.apache.geode.cache.TransactionException) Iterator(java.util.Iterator) VersionTag(org.apache.geode.internal.cache.versions.VersionTag) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) StoredObject(org.apache.geode.internal.offheap.StoredObject) CancelException(org.apache.geode.CancelException) Map(java.util.Map) IndexMap(org.apache.geode.internal.cache.persistence.query.IndexMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashMap(java.util.HashMap) LowMemoryException(org.apache.geode.cache.LowMemoryException)

Aggregations

VersionedObjectList (org.apache.geode.internal.cache.tier.sockets.VersionedObjectList)37 HashMap (java.util.HashMap)13 Map (java.util.Map)12 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)12 VersionTag (org.apache.geode.internal.cache.versions.VersionTag)12 CacheClosedException (org.apache.geode.cache.CacheClosedException)10 PutAllPartialResult (org.apache.geode.internal.cache.PutAllPartialResultException.PutAllPartialResult)10 ArrayList (java.util.ArrayList)9 Iterator (java.util.Iterator)9 List (java.util.List)9 CancelException (org.apache.geode.CancelException)9 CacheException (org.apache.geode.cache.CacheException)9 EntryNotFoundException (org.apache.geode.cache.EntryNotFoundException)9 IOException (java.io.IOException)8 PutAllPartialResultException (org.apache.geode.internal.cache.PutAllPartialResultException)8 ConcurrentCacheModificationException (org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException)8 Released (org.apache.geode.internal.offheap.annotations.Released)8 ExecutionException (java.util.concurrent.ExecutionException)7 InternalGemFireException (org.apache.geode.InternalGemFireException)7 CacheWriterException (org.apache.geode.cache.CacheWriterException)7