Search in sources :

Example 31 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class RegisterInterestList66 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, InterruptedException {
    // numberOfKeysPart = null;
    Part regionNamePart = null, keyPart = null;
    String regionName = null;
    Object key = null;
    InterestResultPolicy policy;
    List keys = null;
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    int numberOfKeys = 0, partNumber = 0;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    serverConnection.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
    ChunkedMessage chunkedResponseMsg = serverConnection.getRegisterInterestResponseMessage();
    // bserverStats.incLong(readDestroyRequestTimeId,
    // DistributionStats.getStatTime() - start);
    // bserverStats.incInt(destroyRequestsId, 1);
    // start = DistributionStats.getStatTime();
    // Retrieve the data from the message parts
    regionNamePart = clientMessage.getPart(0);
    regionName = regionNamePart.getString();
    // Retrieve the InterestResultPolicy
    try {
        policy = (InterestResultPolicy) clientMessage.getPart(1).getObject();
    } catch (Exception e) {
        writeChunkedException(clientMessage, e, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    boolean isDurable = false;
    try {
        Part durablePart = clientMessage.getPart(2);
        byte[] durablePartBytes = (byte[]) durablePart.getObject();
        isDurable = durablePartBytes[0] == 0x01;
    } catch (Exception e) {
        writeChunkedException(clientMessage, e, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    // region data policy
    byte[] regionDataPolicyPartBytes;
    boolean serializeValues = false;
    try {
        Part regionDataPolicyPart = clientMessage.getPart(clientMessage.getNumberOfParts() - 1);
        regionDataPolicyPartBytes = (byte[]) regionDataPolicyPart.getObject();
        if (serverConnection.getClientVersion().compareTo(Version.GFE_80) >= 0) {
            // The second byte here is serializeValues
            serializeValues = regionDataPolicyPartBytes[1] == (byte) 0x01;
        }
    } catch (Exception e) {
        writeChunkedException(clientMessage, e, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    partNumber = 3;
    Part list = clientMessage.getPart(partNumber);
    try {
        keys = (List) list.getObject();
        numberOfKeys = keys.size();
    } catch (Exception e) {
        writeChunkedException(clientMessage, e, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    boolean sendUpdatesAsInvalidates = false;
    try {
        Part notifyPart = clientMessage.getPart(partNumber + 1);
        byte[] notifyPartBytes = (byte[]) notifyPart.getObject();
        sendUpdatesAsInvalidates = notifyPartBytes[0] == 0x01;
    } catch (Exception e) {
        writeChunkedException(clientMessage, e, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Received register interest 66 request ({} bytes) from {} for the following {} keys in region {}: {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), numberOfKeys, regionName, keys);
    }
    // Process the register interest request
    if (keys.isEmpty() || regionName == null) {
        StringId errMessage = null;
        if (keys.isEmpty() && regionName == null) {
            errMessage = LocalizedStrings.RegisterInterestList_THE_INPUT_LIST_OF_KEYS_IS_EMPTY_AND_THE_INPUT_REGION_NAME_IS_NULL_FOR_THE_REGISTER_INTEREST_REQUEST;
        } else if (keys.isEmpty()) {
            errMessage = LocalizedStrings.RegisterInterestList_THE_INPUT_LIST_OF_KEYS_FOR_THE_REGISTER_INTEREST_REQUEST_IS_EMPTY;
        } else if (regionName == null) {
            errMessage = LocalizedStrings.RegisterInterest_THE_INPUT_REGION_NAME_FOR_THE_REGISTER_INTEREST_REQUEST_IS_NULL;
        }
        String s = errMessage.toLocalizedString();
        logger.warn("{}: {}", serverConnection.getName(), s);
        writeChunkedErrorResponse(clientMessage, MessageType.REGISTER_INTEREST_DATA_ERROR, s, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
    }
    // key not null
    LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        logger.info(LocalizedMessage.create(LocalizedStrings.RegisterInterestList_0_REGION_NAMED_1_WAS_NOT_FOUND_DURING_REGISTER_INTEREST_LIST_REQUEST, new Object[] { serverConnection.getName(), regionName }));
    // writeChunkedErrorResponse(msg,
    // MessageType.REGISTER_INTEREST_DATA_ERROR, message);
    // responded = true;
    }
    // else { // region not null
    try {
        this.securityService.authorizeRegionRead(regionName);
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            if (!DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
                RegisterInterestOperationContext registerContext = authzRequest.registerInterestListAuthorize(regionName, keys, policy);
                keys = (List) registerContext.getKey();
            }
        }
        // Register interest
        serverConnection.getAcceptor().getCacheClientNotifier().registerClientInterest(regionName, keys, serverConnection.getProxyID(), isDurable, sendUpdatesAsInvalidates, true, regionDataPolicyPartBytes[0], true);
    } catch (Exception ex) {
        // If an interrupted exception is thrown , rethrow it
        checkForInterrupt(serverConnection, ex);
        // Otherwise, write an exception message and continue
        writeChunkedException(clientMessage, ex, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    // Update the statistics and write the reply
    // bserverStats.incLong(processDestroyTimeId,
    // DistributionStats.getStatTime() - start);
    // start = DistributionStats.getStatTime();
    boolean isPrimary = serverConnection.getAcceptor().getCacheClientNotifier().getClientProxy(serverConnection.getProxyID()).isPrimary();
    if (!isPrimary) {
        chunkedResponseMsg.setMessageType(MessageType.RESPONSE_FROM_SECONDARY);
        chunkedResponseMsg.setTransactionId(clientMessage.getTransactionId());
        chunkedResponseMsg.sendHeader();
        chunkedResponseMsg.setLastChunk(true);
        if (logger.isDebugEnabled()) {
            logger.debug("{}: Sending register interest response chunk from secondary for region: {} for key: {} chunk=<{}>", serverConnection.getName(), regionName, key, chunkedResponseMsg);
        }
        chunkedResponseMsg.sendChunk(serverConnection);
    } else {
        // isPrimary
        // Send header which describes how many chunks will follow
        chunkedResponseMsg.setMessageType(MessageType.RESPONSE_FROM_PRIMARY);
        chunkedResponseMsg.setTransactionId(clientMessage.getTransactionId());
        chunkedResponseMsg.sendHeader();
        // Send chunk response
        try {
            fillAndSendRegisterInterestResponseChunks(region, keys, InterestType.KEY, serializeValues, policy, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
        } catch (Exception e) {
            // If an interrupted exception is thrown , rethrow it
            checkForInterrupt(serverConnection, e);
            // otherwise send the exception back to client
            writeChunkedException(clientMessage, e, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
        if (logger.isDebugEnabled()) {
            // logger.debug(getName() + ": Sent chunk (1 of 1) of register interest
            // response (" + chunkedResponseMsg.getBufferLength() + " bytes) for
            // region " + regionName + " key " + key);
            logger.debug("{}: Sent register interest response for the following {} keys in region {}: {}", serverConnection.getName(), numberOfKeys, regionName, keys);
        }
    // bserverStats.incLong(writeDestroyResponseTimeId,
    // DistributionStats.getStatTime() - start);
    // bserverStats.incInt(destroyResponsesId, 1);
    }
// isPrimary
// } // region not null
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) RegisterInterestOperationContext(org.apache.geode.cache.operations.RegisterInterestOperationContext) LocalRegion(org.apache.geode.internal.cache.LocalRegion) IOException(java.io.IOException) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) InterestResultPolicy(org.apache.geode.cache.InterestResultPolicy) StringId(org.apache.geode.i18n.StringId) List(java.util.List)

Example 32 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class GemFireBasicDataSource method getConnection.

/**
   * Implementation of datasource interface function. This method is used to get the connection from
   * the database. Default user name and password will be used.
   * 
   * @throws SQLException
   * @return ???
   */
@Override
public Connection getConnection() throws SQLException {
    // Asif : In case the user is requesting the
    // connection without username & password
    // we should just return the desired connection
    Connection connection = null;
    if (driverObject == null) {
        synchronized (this) {
            if (driverObject == null)
                loadDriver();
        }
    }
    if (url != null) {
        Properties props = new Properties();
        props.put("user", user);
        props.put("password", password);
        connection = driverObject.connect(url, props);
    } else {
        StringId exception = LocalizedStrings.GemFireBasicDataSource_GEMFIREBASICDATASOURCE_GETCONNECTION_URL_FOR_THE_DATASOURCE_NOT_AVAILABLE;
        logger.info(LocalizedMessage.create(exception));
        throw new SQLException(exception.toLocalizedString());
    }
    return connection;
}
Also used : StringId(org.apache.geode.i18n.StringId) SQLException(java.sql.SQLException) Connection(java.sql.Connection) Properties(java.util.Properties)

Example 33 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class Connection method processNIOBuffer.

/**
   * processes the current NIO buffer. If there are complete messages in the buffer, they are
   * deserialized and passed to TCPConduit for further processing
   */
private void processNIOBuffer() throws ConnectionException, IOException {
    if (nioInputBuffer != null) {
        nioInputBuffer.flip();
    }
    boolean done = false;
    while (!done && connected) {
        this.owner.getConduit().getCancelCriterion().checkCancelInProgress(null);
        // long startTime = DistributionStats.getStatTime();
        int remaining = nioInputBuffer.remaining();
        if (nioLengthSet || remaining >= MSG_HEADER_BYTES) {
            if (!nioLengthSet) {
                int headerStartPos = nioInputBuffer.position();
                nioMessageLength = nioInputBuffer.getInt();
                /* nioMessageVersion = */
                calcHdrVersion(nioMessageLength);
                nioMessageLength = calcMsgByteSize(nioMessageLength);
                nioMessageType = nioInputBuffer.get();
                nioMsgId = nioInputBuffer.getShort();
                directAck = (nioMessageType & DIRECT_ACK_BIT) != 0;
                if (directAck) {
                    // clear the ack bit
                    nioMessageType &= ~DIRECT_ACK_BIT;
                }
                // Following validation fixes bug 31145
                if (!validMsgType(nioMessageType)) {
                    Integer nioMessageTypeInteger = Integer.valueOf(nioMessageType);
                    logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_UNKNOWN_P2P_MESSAGE_TYPE_0, nioMessageTypeInteger));
                    this.readerShuttingDown = true;
                    requestClose(LocalizedStrings.Connection_UNKNOWN_P2P_MESSAGE_TYPE_0.toLocalizedString(nioMessageTypeInteger));
                    break;
                }
                nioLengthSet = true;
                // keep the header "in" the buffer until we have read the entire msg.
                // Trust me: this will reduce copying on large messages.
                nioInputBuffer.position(headerStartPos);
            }
            if (remaining >= nioMessageLength + MSG_HEADER_BYTES) {
                nioLengthSet = false;
                nioInputBuffer.position(nioInputBuffer.position() + MSG_HEADER_BYTES);
                // don't trust the message deserialization to leave the position in
                // the correct spot. Some of the serialization uses buffered
                // streams that can leave the position at the wrong spot
                int startPos = nioInputBuffer.position();
                int oldLimit = nioInputBuffer.limit();
                nioInputBuffer.limit(startPos + nioMessageLength);
                if (this.handshakeRead) {
                    if (nioMessageType == NORMAL_MSG_TYPE) {
                        this.owner.getConduit().stats.incMessagesBeingReceived(true, nioMessageLength);
                        ByteBufferInputStream bbis = remoteVersion == null ? new ByteBufferInputStream(nioInputBuffer) : new VersionedByteBufferInputStream(nioInputBuffer, remoteVersion);
                        DistributionMessage msg = null;
                        try {
                            ReplyProcessor21.initMessageRPId();
                            // add serialization stats
                            long startSer = this.owner.getConduit().stats.startMsgDeserialization();
                            msg = (DistributionMessage) InternalDataSerializer.readDSFID(bbis);
                            this.owner.getConduit().stats.endMsgDeserialization(startSer);
                            if (bbis.available() != 0) {
                                logger.warn(LocalizedMessage.create(LocalizedStrings.Connection_MESSAGE_DESERIALIZATION_OF_0_DID_NOT_READ_1_BYTES, new Object[] { msg, Integer.valueOf(bbis.available()) }));
                            }
                            try {
                                if (!dispatchMessage(msg, nioMessageLength, directAck)) {
                                    directAck = false;
                                }
                            } catch (MemberShunnedException e) {
                                // don't respond (bug39117)
                                directAck = false;
                            } catch (Exception de) {
                                this.owner.getConduit().getCancelCriterion().checkCancelInProgress(de);
                                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_ERROR_DISPATCHING_MESSAGE), de);
                            } catch (ThreadDeath td) {
                                throw td;
                            } 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();
                                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_THROWABLE_DISPATCHING_MESSAGE), t);
                            }
                        } 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();
                            sendFailureReply(ReplyProcessor21.getMessageRPId(), LocalizedStrings.Connection_ERROR_DESERIALIZING_MESSAGE.toLocalizedString(), t, directAck);
                            if (t instanceof ThreadDeath) {
                                throw (ThreadDeath) t;
                            }
                            if (t instanceof CancelException) {
                                if (!(t instanceof CacheClosedException)) {
                                    // CacheClosedException; see bug 43543
                                    throw (CancelException) t;
                                }
                            }
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_ERROR_DESERIALIZING_MESSAGE), t);
                        } finally {
                            ReplyProcessor21.clearMessageRPId();
                        }
                    } else if (nioMessageType == CHUNKED_MSG_TYPE) {
                        MsgDestreamer md = obtainMsgDestreamer(nioMsgId, remoteVersion);
                        this.owner.getConduit().stats.incMessagesBeingReceived(md.size() == 0, nioMessageLength);
                        try {
                            md.addChunk(nioInputBuffer, nioMessageLength);
                        } catch (IOException ex) {
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_FAILED_HANDLING_CHUNK_MESSAGE), ex);
                        }
                    } else /* (nioMessageType == END_CHUNKED_MSG_TYPE) */
                    {
                        // logger.info("END_CHUNK msgId="+nioMsgId);
                        MsgDestreamer md = obtainMsgDestreamer(nioMsgId, remoteVersion);
                        this.owner.getConduit().stats.incMessagesBeingReceived(md.size() == 0, nioMessageLength);
                        try {
                            md.addChunk(nioInputBuffer, nioMessageLength);
                        } catch (IOException ex) {
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_FAILED_HANDLING_END_CHUNK_MESSAGE), ex);
                        }
                        DistributionMessage msg = null;
                        int msgLength = 0;
                        String failureMsg = null;
                        Throwable failureEx = null;
                        int rpId = 0;
                        boolean interrupted = false;
                        try {
                            msg = md.getMessage();
                        } catch (ClassNotFoundException ex) {
                            this.owner.getConduit().stats.decMessagesBeingReceived(md.size());
                            failureMsg = LocalizedStrings.Connection_CLASSNOTFOUND_DESERIALIZING_MESSAGE.toLocalizedString();
                            failureEx = ex;
                            rpId = md.getRPid();
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_CLASSNOTFOUND_DESERIALIZING_MESSAGE_0, ex));
                        } catch (IOException ex) {
                            this.owner.getConduit().stats.decMessagesBeingReceived(md.size());
                            failureMsg = LocalizedStrings.Connection_IOEXCEPTION_DESERIALIZING_MESSAGE.toLocalizedString();
                            failureEx = ex;
                            rpId = md.getRPid();
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_IOEXCEPTION_DESERIALIZING_MESSAGE), failureEx);
                        } catch (InterruptedException ex) {
                            interrupted = true;
                            this.owner.getConduit().getCancelCriterion().checkCancelInProgress(ex);
                        } catch (VirtualMachineError err) {
                            SystemFailure.initiateFailure(err);
                            // now, so don't let this thread continue.
                            throw err;
                        } catch (Throwable ex) {
                            // 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();
                            this.owner.getConduit().getCancelCriterion().checkCancelInProgress(ex);
                            this.owner.getConduit().stats.decMessagesBeingReceived(md.size());
                            failureMsg = LocalizedStrings.Connection_UNEXPECTED_FAILURE_DESERIALIZING_MESSAGE.toLocalizedString();
                            failureEx = ex;
                            rpId = md.getRPid();
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_UNEXPECTED_FAILURE_DESERIALIZING_MESSAGE), failureEx);
                        } finally {
                            msgLength = md.size();
                            releaseMsgDestreamer(nioMsgId, md);
                            if (interrupted) {
                                Thread.currentThread().interrupt();
                            }
                        }
                        if (msg != null) {
                            try {
                                if (!dispatchMessage(msg, msgLength, directAck)) {
                                    directAck = false;
                                }
                            } catch (MemberShunnedException e) {
                                // not a member anymore - don't reply
                                directAck = false;
                            } catch (Exception de) {
                                this.owner.getConduit().getCancelCriterion().checkCancelInProgress(de);
                                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_ERROR_DISPATCHING_MESSAGE), de);
                            } catch (ThreadDeath td) {
                                throw td;
                            } 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();
                                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_THROWABLE_DISPATCHING_MESSAGE), t);
                            }
                        } else if (failureEx != null) {
                            sendFailureReply(rpId, failureMsg, failureEx, directAck);
                        }
                    }
                } else {
                    // read HANDSHAKE
                    ByteBufferInputStream bbis = new ByteBufferInputStream(nioInputBuffer);
                    DataInputStream dis = new DataInputStream(bbis);
                    if (!this.isReceiver) {
                        try {
                            this.replyCode = dis.readUnsignedByte();
                            if (this.replyCode == REPLY_CODE_OK_WITH_ASYNC_INFO) {
                                this.asyncDistributionTimeout = dis.readInt();
                                this.asyncQueueTimeout = dis.readInt();
                                this.asyncMaxQueueSize = (long) dis.readInt() * (1024 * 1024);
                                if (this.asyncDistributionTimeout != 0) {
                                    logger.info(LocalizedMessage.create(LocalizedStrings.Connection_0_ASYNC_CONFIGURATION_RECEIVED_1, new Object[] { p2pReaderName(), " asyncDistributionTimeout=" + this.asyncDistributionTimeout + " asyncQueueTimeout=" + this.asyncQueueTimeout + " asyncMaxQueueSize=" + (this.asyncMaxQueueSize / (1024 * 1024)) }));
                                }
                                // read the product version ordinal for on-the-fly serialization
                                // transformations (for rolling upgrades)
                                this.remoteVersion = Version.readVersion(dis, true);
                            }
                        } catch (Exception e) {
                            this.owner.getConduit().getCancelCriterion().checkCancelInProgress(e);
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_ERROR_DESERIALIZING_P2P_HANDSHAKE_REPLY), e);
                            this.readerShuttingDown = true;
                            requestClose(LocalizedStrings.Connection_ERROR_DESERIALIZING_P2P_HANDSHAKE_REPLY.toLocalizedString());
                            return;
                        } catch (ThreadDeath td) {
                            throw td;
                        } 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();
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_THROWABLE_DESERIALIZING_P2P_HANDSHAKE_REPLY), t);
                            this.readerShuttingDown = true;
                            requestClose(LocalizedStrings.Connection_THROWABLE_DESERIALIZING_P2P_HANDSHAKE_REPLY.toLocalizedString());
                            return;
                        }
                        if (this.replyCode != REPLY_CODE_OK && this.replyCode != REPLY_CODE_OK_WITH_ASYNC_INFO) {
                            StringId err = LocalizedStrings.Connection_UNKNOWN_HANDSHAKE_REPLY_CODE_0_NIOMESSAGELENGTH_1_PROCESSORTYPE_2;
                            Object[] errArgs = new Object[] { Integer.valueOf(this.replyCode), Integer.valueOf(nioMessageLength) };
                            if (replyCode == 0 && logger.isDebugEnabled()) {
                                // bug 37113
                                logger.debug(err.toLocalizedString(errArgs) + " (peer probably departed ungracefully)");
                            } else {
                                logger.fatal(LocalizedMessage.create(err, errArgs));
                            }
                            this.readerShuttingDown = true;
                            requestClose(err.toLocalizedString(errArgs));
                            return;
                        }
                        notifyHandshakeWaiter(true);
                    } else {
                        try {
                            byte b = dis.readByte();
                            if (b != 0) {
                                throw new IllegalStateException(LocalizedStrings.Connection_DETECTED_OLD_VERSION_PRE_501_OF_GEMFIRE_OR_NONGEMFIRE_DURING_HANDSHAKE_DUE_TO_INITIAL_BYTE_BEING_0.toLocalizedString(new Byte(b)));
                            }
                            byte handShakeByte = dis.readByte();
                            if (handShakeByte != HANDSHAKE_VERSION) {
                                throw new IllegalStateException(LocalizedStrings.Connection_DETECTED_WRONG_VERSION_OF_GEMFIRE_PRODUCT_DURING_HANDSHAKE_EXPECTED_0_BUT_FOUND_1.toLocalizedString(new Object[] { new Byte(HANDSHAKE_VERSION), new Byte(handShakeByte) }));
                            }
                            InternalDistributedMember remote = DSFIDFactory.readInternalDistributedMember(dis);
                            setRemoteAddr(remote);
                            this.sharedResource = dis.readBoolean();
                            this.preserveOrder = dis.readBoolean();
                            this.uniqueId = dis.readLong();
                            // read the product version ordinal for on-the-fly serialization
                            // transformations (for rolling upgrades)
                            this.remoteVersion = Version.readVersion(dis, true);
                            int dominoNumber = 0;
                            if (this.remoteVersion == null || (this.remoteVersion.compareTo(Version.GFE_80) >= 0)) {
                                dominoNumber = dis.readInt();
                                if (this.sharedResource) {
                                    dominoNumber = 0;
                                }
                                dominoCount.set(dominoNumber);
                            // this.senderName = dis.readUTF();
                            }
                            if (!this.sharedResource) {
                                if (tipDomino()) {
                                    logger.info(LocalizedMessage.create(LocalizedStrings.Connection_THREAD_OWNED_RECEIVER_FORCING_ITSELF_TO_SEND_ON_THREAD_OWNED_SOCKETS));
                                // bug #49565 - if domino count is >= 2 use shared resources.
                                // Also see DistributedCacheOperation#supportsDirectAck
                                } else {
                                    // if (dominoNumber < 2) {
                                    ConnectionTable.threadWantsOwnResources();
                                    if (logger.isDebugEnabled()) {
                                        logger.debug("thread-owned receiver with domino count of {} will prefer sending on thread-owned sockets", dominoNumber);
                                    }
                                // } else {
                                // ConnectionTable.threadWantsSharedResources();
                                }
                                this.conduit.stats.incThreadOwnedReceivers(1L, dominoNumber);
                                // Because this thread is not shared resource, it will be used for direct
                                // ack. Direct ack messages can be large. This call will resize the send
                                // buffer.
                                setSendBufferSize(this.socket);
                            }
                            // String name = owner.getDM().getConfig().getName();
                            // if (name == null) {
                            // name = "pid="+OSProcess.getId();
                            // }
                            setThreadName(dominoNumber);
                        } catch (Exception e) {
                            // bug 37101
                            this.owner.getConduit().getCancelCriterion().checkCancelInProgress(e);
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_ERROR_DESERIALIZING_P2P_HANDSHAKE_MESSAGE), e);
                            this.readerShuttingDown = true;
                            requestClose(LocalizedStrings.Connection_ERROR_DESERIALIZING_P2P_HANDSHAKE_MESSAGE.toLocalizedString());
                            return;
                        }
                        if (logger.isDebugEnabled()) {
                            logger.debug("P2P handshake remoteAddr is {}{}", this.remoteAddr, (this.remoteVersion != null ? " (" + this.remoteVersion + ')' : ""));
                        }
                        try {
                            String authInit = System.getProperty(DistributionConfigImpl.SECURITY_SYSTEM_PREFIX + SECURITY_PEER_AUTH_INIT);
                            boolean isSecure = authInit != null && authInit.length() != 0;
                            if (isSecure) {
                                if (owner.getConduit().waitForMembershipCheck(this.remoteAddr)) {
                                    // fix for bug 33224
                                    sendOKHandshakeReply();
                                    notifyHandshakeWaiter(true);
                                } else {
                                    // ARB: check if we need notifyHandshakeWaiter() call.
                                    notifyHandshakeWaiter(false);
                                    logger.warn(LocalizedMessage.create(LocalizedStrings.Connection_0_TIMED_OUT_DURING_A_MEMBERSHIP_CHECK, p2pReaderName()));
                                    return;
                                }
                            } else {
                                // fix for bug 33224
                                sendOKHandshakeReply();
                                try {
                                    notifyHandshakeWaiter(true);
                                } catch (Exception e) {
                                    logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_UNCAUGHT_EXCEPTION_FROM_LISTENER), e);
                                }
                            }
                        } catch (IOException ex) {
                            final String err = LocalizedStrings.Connection_FAILED_SENDING_HANDSHAKE_REPLY.toLocalizedString();
                            if (logger.isDebugEnabled()) {
                                logger.debug(err, ex);
                            }
                            this.readerShuttingDown = true;
                            requestClose(err + ": " + ex);
                            return;
                        }
                    }
                }
                if (!connected) {
                    continue;
                }
                accessed();
                nioInputBuffer.limit(oldLimit);
                nioInputBuffer.position(startPos + nioMessageLength);
            } else {
                done = true;
                compactOrResizeBuffer(nioMessageLength);
            }
        } else {
            done = true;
            if (nioInputBuffer.position() != 0) {
                nioInputBuffer.compact();
            } else {
                nioInputBuffer.position(nioInputBuffer.limit());
                nioInputBuffer.limit(nioInputBuffer.capacity());
            }
        }
    }
}
Also used : DistributionMessage(org.apache.geode.distributed.internal.DistributionMessage) CacheClosedException(org.apache.geode.cache.CacheClosedException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CancelException(org.apache.geode.CancelException) CancelledKeyException(java.nio.channels.CancelledKeyException) InterruptedIOException(java.io.InterruptedIOException) SocketException(java.net.SocketException) CacheClosedException(org.apache.geode.cache.CacheClosedException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ReplyException(org.apache.geode.distributed.internal.ReplyException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) StringId(org.apache.geode.i18n.StringId) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) CancelException(org.apache.geode.CancelException)

Example 34 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class LoggingThreadGroup method uncaughtException.

/**
   * Logs an uncaught exception to a log writer
   */
@Override
public void uncaughtException(final Thread t, final Throwable ex) {
    synchronized (this.dispatchLock) {
        if (ex instanceof VirtualMachineError) {
            // don't throw
            SystemFailure.setFailure((VirtualMachineError) ex);
        }
        // Solution to treat the shutdown hook error as a special case.
        // Do not change the hook's thread name without also changing it here.
        String threadName = t.getName();
        if ((ex instanceof NoClassDefFoundError) && (threadName.equals(InternalDistributedSystem.SHUTDOWN_HOOK_NAME))) {
            final StringId msg = LocalizedStrings.UNCAUGHT_EXCEPTION_IN_THREAD_0_THIS_MESSAGE_CAN_BE_DISREGARDED_IF_IT_OCCURRED_DURING_AN_APPLICATION_SERVER_SHUTDOWN_THE_EXCEPTION_MESSAGE_WAS_1;
            final Object[] msgArgs = new Object[] { t, ex.getLocalizedMessage() };
            stderr.info(msg, msgArgs);
            if (this.logger != null) {
                this.logger.info(LocalizedMessage.create(msg, msgArgs));
            }
            if (this.logWriter != null) {
                this.logWriter.info(msg, msgArgs);
            }
        } else {
            stderr.severe(LocalizedStrings.UNCAUGHT_EXCEPTION_IN_THREAD_0, t, ex);
            if (this.logger != null) {
                this.logger.fatal(LocalizedMessage.create(LocalizedStrings.UNCAUGHT_EXCEPTION_IN_THREAD_0, t), ex);
            }
            if (this.logWriter != null) {
                this.logWriter.severe(LocalizedStrings.UNCAUGHT_EXCEPTION_IN_THREAD_0, t, ex);
            }
        }
        // if (!(ex instanceof RuntimeException) && (ex instanceof Exception)) {
        // something's fishy - checked exceptions shouldn't get here
        // this.logger.severe("stack trace showing origin of uncaught checked exception", new
        // Exception("stack trace"));
        // }
        this.uncaughtExceptionsCount++;
    }
}
Also used : StringId(org.apache.geode.i18n.StringId)

Example 35 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class DirectChannel method handleAckTimeout.

/**
   * 
   * @param ackTimeout ack wait threshold
   * @param ackSATimeout severe alert threshold
   * @param c
   * @param processor
   * @throws ConnectionException
   */
private void handleAckTimeout(long ackTimeout, long ackSATimeout, Connection c, DirectReplyProcessor processor) throws ConnectionException {
    DM dm = getDM();
    Set activeMembers = dm.getDistributionManagerIds();
    // Increment the stat
    dm.getStats().incReplyTimeouts();
    // an alert that will show up in the console
    {
        final StringId msg = LocalizedStrings.DirectChannel_0_SECONDS_HAVE_ELAPSED_WHILE_WAITING_FOR_REPLY_FROM_1_ON_2_WHOSE_CURRENT_MEMBERSHIP_LIST_IS_3;
        final Object[] msgArgs = new Object[] { Long.valueOf(ackTimeout / 1000), c.getRemoteAddress(), dm.getId(), activeMembers };
        logger.warn(LocalizedMessage.create(msg, msgArgs));
        msgArgs[3] = "(omitted)";
        Breadcrumbs.setProblem(msg, msgArgs);
        if (ReplyProcessor21.THROW_EXCEPTION_ON_TIMEOUT) {
            // init the cause to be a TimeoutException so catchers can determine cause
            TimeoutException cause = new TimeoutException(LocalizedStrings.TIMED_OUT_WAITING_FOR_ACKS.toLocalizedString());
            throw new InternalGemFireException(msg.toLocalizedString(msgArgs), cause);
        }
    }
    if (activeMembers.contains(c.getRemoteAddress())) {
        // wait for ack-severe-alert-threshold period first, then wait forever
        if (ackSATimeout > 0) {
            try {
                c.readAck((int) ackSATimeout, ackSATimeout, processor);
                return;
            } catch (SocketTimeoutException e) {
                Object[] args = new Object[] { Long.valueOf((ackSATimeout + ackTimeout) / 1000), c.getRemoteAddress(), dm.getId(), activeMembers };
                logger.fatal(LocalizedMessage.create(LocalizedStrings.DirectChannel_0_SECONDS_HAVE_ELAPSED_WHILE_WAITING_FOR_REPLY_FROM_1_ON_2_WHOSE_CURRENT_MEMBERSHIP_LIST_IS_3, args));
            }
        }
        try {
            c.readAck(0, 0, processor);
        } catch (SocketTimeoutException ex) {
            // this can never happen when called with timeout of 0
            logger.error(LocalizedMessage.create(LocalizedStrings.DirectChannel_UNEXPECTED_TIMEOUT_WHILE_WAITING_FOR_ACK_FROM__0, c.getRemoteAddress()), ex);
        }
    } else {
        logger.warn(LocalizedMessage.create(LocalizedStrings.DirectChannel_VIEW_NO_LONGER_HAS_0_AS_AN_ACTIVE_MEMBER_SO_WE_WILL_NO_LONGER_WAIT_FOR_IT, c.getRemoteAddress()));
        processor.memberDeparted(c.getRemoteAddress(), true);
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) StringId(org.apache.geode.i18n.StringId) TimeoutException(org.apache.geode.cache.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException)

Aggregations

StringId (org.apache.geode.i18n.StringId)43 IOException (java.io.IOException)14 AuthorizeRequest (org.apache.geode.internal.security.AuthorizeRequest)11 LocalRegion (org.apache.geode.internal.cache.LocalRegion)10 CachedRegionHelper (org.apache.geode.internal.cache.tier.CachedRegionHelper)8 Part (org.apache.geode.internal.cache.tier.sockets.Part)8 TimeoutException (org.apache.geode.cache.TimeoutException)6 HashSet (java.util.HashSet)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 CancelException (org.apache.geode.CancelException)4 InterestResultPolicy (org.apache.geode.cache.InterestResultPolicy)4 RegisterInterestOperationContext (org.apache.geode.cache.operations.RegisterInterestOperationContext)4 CqClosedException (org.apache.geode.cache.query.CqClosedException)4 CqException (org.apache.geode.cache.query.CqException)4 CqExistsException (org.apache.geode.cache.query.CqExistsException)4 QueryException (org.apache.geode.cache.query.QueryException)4 RegionNotFoundException (org.apache.geode.cache.query.RegionNotFoundException)4 LinkedHashSet (java.util.LinkedHashSet)3