Search in sources :

Example 6 with PutAllOperationContext

use of org.apache.geode.cache.operations.PutAllOperationContext in project geode by apache.

the class PutAll70 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, valuePart = 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();
    // requiresResponse = true;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadPutAllRequestTime(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 putAllMsg = LocalizedStrings.PutAll_THE_INPUT_REGION_NAME_FOR_THE_PUTALL_REQUEST_IS_NULL.toLocalizedString();
            logger.warn("{}: {}", serverConnection.getName(), putAllMsg);
            errMessage.append(putAllMsg);
            writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
        LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
        if (region == null) {
            String reason = " was not found during put 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);
        // part 2: invoke callbacks (used by import)
        Part callbacksPart = clientMessage.getPart(2);
        boolean skipCallbacks = callbacksPart.getInt() == 1 ? true : false;
        // part 3: number of keys
        numberOfKeysPart = clientMessage.getPart(3);
        numberOfKeys = numberOfKeysPart.getInt();
        // building the map
        Map map = new LinkedHashMap();
        Map<Object, VersionTag> retryVersions = new LinkedHashMap<Object, VersionTag>();
        // Map isObjectMap = new LinkedHashMap();
        for (int i = 0; i < numberOfKeys; i++) {
            keyPart = clientMessage.getPart(4 + i * 2);
            key = keyPart.getStringOrObject();
            if (key == null) {
                String putAllMsg = LocalizedStrings.PutAll_ONE_OF_THE_INPUT_KEYS_FOR_THE_PUTALL_REQUEST_IS_NULL.toLocalizedString();
                logger.warn("{}: {}", serverConnection.getName(), putAllMsg);
                errMessage.append(putAllMsg);
                writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
                serverConnection.setAsTrue(RESPONDED);
                return;
            }
            valuePart = clientMessage.getPart(4 + i * 2 + 1);
            if (valuePart.isNull()) {
                String putAllMsg = LocalizedStrings.PutAll_ONE_OF_THE_INPUT_VALUES_FOR_THE_PUTALL_REQUEST_IS_NULL.toLocalizedString();
                logger.warn("{}: {}", serverConnection.getName(), putAllMsg);
                errMessage.append(putAllMsg);
                writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
                serverConnection.setAsTrue(RESPONDED);
                return;
            }
            // byte[] value = valuePart.getSerializedForm();
            Object value;
            if (valuePart.isObject()) {
                // skipCallbacks configurable this code will need to be updated.
                if (skipCallbacks && Token.INVALID.isSerializedValue(valuePart.getSerializedForm())) {
                    value = Token.INVALID;
                } else {
                    value = CachedDeserializableFactory.create(valuePart.getSerializedForm());
                }
            } else {
                value = valuePart.getSerializedForm();
            }
            // put serializedform for auth. It will be modified with auth callback
            if (clientMessage.isRetry()) {
                // Constuct the thread id/sequence id information for this element in the
                // put all map
                // 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);
                if (tag != null) {
                    retryVersions.put(key, tag);
                }
            // FIND THE VERSION TAG FOR THIS KEY - but how? all we have is the
            // putAll eventId, not individual eventIds for entries, right?
            }
            map.put(key, value);
        // isObjectMap.put(key, new Boolean(isObject));
        }
        if (clientMessage.getNumberOfParts() == (4 + 2 * numberOfKeys + 1)) {
            // it means optional
            // timeout has
            // been added
            int timeout = clientMessage.getPart(4 + 2 * numberOfKeys).getInt();
            serverConnection.setRequestSpecificTimeout(timeout);
        }
        this.securityService.authorizeRegionWrite(regionName);
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
                authzRequest.createRegionAuthorize(regionName);
            } else {
                PutAllOperationContext putAllContext = authzRequest.putAllAuthorize(regionName, map, null);
                map = putAllContext.getMap();
                if (map instanceof UpdateOnlyMap) {
                    map = ((UpdateOnlyMap) map).getInternalMap();
                }
            }
        } else {
        // no auth, so update the map based on isObjectMap here
        /*
         * Collection entries = map.entrySet(); Iterator iterator = entries.iterator(); Map.Entry
         * mapEntry = null; while (iterator.hasNext()) { mapEntry = (Map.Entry)iterator.next();
         * Object currkey = mapEntry.getKey(); byte[] serializedValue = (byte[])mapEntry.getValue();
         * boolean isObject = ((Boolean)isObjectMap.get(currkey)).booleanValue(); if (isObject) {
         * map.put(currkey, CachedDeserializableFactory.create(serializedValue)); } }
         */
        }
        if (logger.isDebugEnabled()) {
            logger.debug("{}: Received putAll request ({} bytes) from {} for region {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName);
        }
        response = region.basicBridgePutAll(map, retryVersions, serverConnection.getProxyID(), eventId, skipCallbacks, null);
        if (!region.getConcurrencyChecksEnabled()) {
            // the client only needs this if versioning is being used
            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) {
        writeException(clientMessage, rde, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (ResourceException re) {
        writeException(clientMessage, re, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (PutAllPartialResultException pre) {
        writeException(clientMessage, pre, false, 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 put, preserve the connection
        writeException(clientMessage, ce, false, 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.incProcessPutAllTime(start - oldStart);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending putAll70 response back to {} for region {}: {}", serverConnection.getName(), serverConnection.getSocketString(), regionName, response);
    }
    // Starting in 7.0.1 we do not send the keys back
    if (response != null && Version.GFE_70.compareTo(serverConnection.getClientVersion()) < 0) {
        if (logger.isDebugEnabled()) {
            logger.debug("setting putAll keys to null");
        }
        response.setKeys(null);
    }
    // Increment statistics and write the reply
    if (!replyWithMetaData) {
        writeReply(clientMessage, response, serverConnection);
    }
    serverConnection.setAsTrue(RESPONDED);
    stats.incWritePutAllResponseTime(DistributionStats.getStatTime() - start);
}
Also used : UpdateOnlyMap(org.apache.geode.cache.operations.internal.UpdateOnlyMap) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) LocalRegion(org.apache.geode.internal.cache.LocalRegion) LinkedHashMap(java.util.LinkedHashMap) PutAllPartialResultException(org.apache.geode.internal.cache.PutAllPartialResultException) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) PutAllOperationContext(org.apache.geode.cache.operations.PutAllOperationContext) 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) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) UpdateOnlyMap(org.apache.geode.cache.operations.internal.UpdateOnlyMap)

Example 7 with PutAllOperationContext

use of org.apache.geode.cache.operations.PutAllOperationContext in project geode by apache.

the class FilterPreAuthorization method authorizeOperation.

public boolean authorizeOperation(String regionName, OperationContext context) {
    assert !context.isPostOperation();
    OperationCode opCode = context.getOperationCode();
    if (opCode.isPut()) {
        PutOperationContext createContext = (PutOperationContext) context;
        // byte[] serializedValue = createContext.getSerializedValue();
        byte[] serializedValue = null;
        Object value = createContext.getValue();
        int valLength;
        byte lastByte;
        if (value == null) {
            // This means serializedValue too is null.
            valLength = 0;
            lastByte = 0;
        } else {
            if (value instanceof byte[]) {
                serializedValue = (byte[]) value;
                valLength = serializedValue.length;
                lastByte = serializedValue[valLength - 1];
            } else {
                ObjectWithAuthz authzObj = new ObjectWithAuthz(value, Integer.valueOf(value.hashCode()));
                createContext.setValue(authzObj, true);
                return true;
            }
        }
        HeapDataOutputStream hos = new HeapDataOutputStream(valLength + 32, Version.CURRENT);
        try {
            InternalDataSerializer.writeUserDataSerializableHeader(ObjectWithAuthz.CLASSID, hos);
            if (serializedValue != null) {
                hos.write(serializedValue);
            }
            // Some value that determines the Principals that can get this object.
            Integer allowedIndex = Integer.valueOf(lastByte);
            DataSerializer.writeObject(allowedIndex, hos);
        } catch (Exception ex) {
            return false;
        }
        createContext.setSerializedValue(hos.toByteArray(), true);
        if (this.logger.fineEnabled())
            this.logger.fine("FilterPreAuthorization: added authorization " + "info for key: " + createContext.getKey());
    } else if (opCode.isPutAll()) {
        PutAllOperationContext createContext = (PutAllOperationContext) context;
        Map map = createContext.getMap();
        Collection entries = map.entrySet();
        Iterator iterator = entries.iterator();
        Map.Entry mapEntry = null;
        while (iterator.hasNext()) {
            mapEntry = (Map.Entry) iterator.next();
            String currkey = (String) mapEntry.getKey();
            Object value = mapEntry.getValue();
            Integer authCode;
            if (value != null) {
                String valStr = value.toString();
                authCode = (int) valStr.charAt(valStr.length() - 1);
            } else {
                authCode = 0;
            }
            ObjectWithAuthz authzObj = new ObjectWithAuthz(value, authCode);
            mapEntry.setValue(authzObj);
            if (this.logger.fineEnabled())
                this.logger.fine("FilterPreAuthorization: putAll: added authorization " + "info for key: " + currkey);
        }
    // Now each of the map's values have become ObjectWithAuthz
    }
    return true;
}
Also used : OperationCode(org.apache.geode.cache.operations.OperationContext.OperationCode) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) PutAllOperationContext(org.apache.geode.cache.operations.PutAllOperationContext) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) Iterator(java.util.Iterator) Collection(java.util.Collection) PutOperationContext(org.apache.geode.cache.operations.PutOperationContext) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with PutAllOperationContext

use of org.apache.geode.cache.operations.PutAllOperationContext in project geode by apache.

the class PutAllOperationContextJUnitTest method testLegalMapMods.

@Test
public void testLegalMapMods() {
    LinkedHashMap<String, String> m = new LinkedHashMap<>();
    m.put("1", "1");
    m.put("2", "2");
    m.put("3", "3");
    PutAllOperationContext paoc = new PutAllOperationContext(m);
    Map<String, String> opMap = paoc.getMap();
    assertEquals(m, opMap);
    {
        // change order and make sure paoc map order is unchanged
        LinkedHashMap<String, String> m2 = new LinkedHashMap<>();
        m2.put("3", "3");
        m2.put("1", "1");
        m2.put("2", "2");
        paoc.setMap(m2);
        assertEquals(Arrays.asList("1", "2", "3"), new ArrayList<>(opMap.keySet()));
        assertEquals(m, opMap);
    }
    assertEquals(false, opMap.isEmpty());
    assertEquals(3, opMap.size());
    assertEquals(true, opMap.containsKey("1"));
    assertEquals(false, opMap.containsKey("4"));
    assertEquals("1", opMap.get("1"));
    assertEquals(Arrays.asList("1", "2", "3"), new ArrayList<String>(opMap.values()));
    opMap.put("1", "1b");
    opMap.put("2", "2b");
    opMap.put("3", "3b");
    m = new LinkedHashMap<>();
    m.put("1", "1b");
    m.put("2", "2b");
    m.put("3", "3b");
    assertEquals(m, opMap);
    m.put("2", "2c");
    paoc.setMap(m);
    assertEquals(m, opMap);
    for (Map.Entry<String, String> me : opMap.entrySet()) {
        if (me.getKey().equals("1")) {
            me.setValue("1d");
        }
    }
    m.put("1", "1d");
    assertEquals(m, opMap);
    paoc.setMap(opMap);
    // check that none of updates changed to key order
    assertEquals(Arrays.asList("1", "2", "3"), new ArrayList<>(opMap.keySet()));
    opMap.toString();
}
Also used : PutAllOperationContext(org.apache.geode.cache.operations.PutAllOperationContext) ArrayList(java.util.ArrayList) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test) UnitTest(org.apache.geode.test.junit.categories.UnitTest)

Aggregations

PutAllOperationContext (org.apache.geode.cache.operations.PutAllOperationContext)8 LinkedHashMap (java.util.LinkedHashMap)7 Map (java.util.Map)7 HashMap (java.util.HashMap)4 UnitTest (org.apache.geode.test.junit.categories.UnitTest)4 Test (org.junit.Test)4 IOException (java.io.IOException)3 ByteBuffer (java.nio.ByteBuffer)3 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)3 ResourceException (org.apache.geode.cache.ResourceException)3 UpdateOnlyMap (org.apache.geode.cache.operations.internal.UpdateOnlyMap)3 EventID (org.apache.geode.internal.cache.EventID)3 LocalRegion (org.apache.geode.internal.cache.LocalRegion)3 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)3 PutAllPartialResultException (org.apache.geode.internal.cache.PutAllPartialResultException)3 CachedRegionHelper (org.apache.geode.internal.cache.tier.CachedRegionHelper)3 CacheServerStats (org.apache.geode.internal.cache.tier.sockets.CacheServerStats)3 Part (org.apache.geode.internal.cache.tier.sockets.Part)3 AuthorizeRequest (org.apache.geode.internal.security.AuthorizeRequest)3 VersionedObjectList (org.apache.geode.internal.cache.tier.sockets.VersionedObjectList)2