Ejemplo n.º 1
0
        public void CleanUp()
        {
            var connectionClosedException =
                new ConnectionClosedException("Connection was closed.");

            foreach (var channel in _channels.Values)
            {
                channel.Fail(connectionClosedException);
            }

            _channels.Clear();
        }
        public void CleanUp()
        {
            var connectionClosedException = new ConnectionClosedException(string.Format("Connection '{0}' was closed.", _connectionName));

            foreach (var subscription in _activeSubscriptions.Values
                     .Concat(_waitingSubscriptions)
                     .Concat(_retryPendingSubscriptions))
            {
                subscription.Operation.DropSubscription(SubscriptionDropReason.ConnectionClosed, connectionClosedException);
            }
            _activeSubscriptions.Clear();
            _waitingSubscriptions.Clear();
            _retryPendingSubscriptions.Clear();
        }
Ejemplo n.º 3
0
        public void CleanUp()
        {
            var connectionClosedException = new ConnectionClosedException(string.Format("Connection '{0}' was closed.", _connectionName));

            foreach (var operation in _activeOperations.Values
                     .Concat(_waitingOperations)
                     .Concat(_retryPendingOperations))
            {
                operation.Operation.Fail(connectionClosedException);
            }
            _activeOperations.Clear();
            _waitingOperations.Clear();
            _retryPendingOperations.Clear();
            _totalOperationCount = 0;
        }
Ejemplo n.º 4
0
        public void CleanUp()
        {
            var connectionClosedException =
                new ConnectionClosedException("Connection was closed.");

            foreach (var operation in _activeOperations.Values
                     .Concat(_waitingOperations)
                     .Concat(_retryPendingOperations))
            {
                operation.Operation.Fail(connectionClosedException);
            }

            _activeOperations.Clear();
            OperationItem dummy;

            while (_waitingOperations.TryDequeue(out dummy))
            {
                ;
            }
            _retryPendingOperations.Clear();
            _totalOperationCount = 0;
        }
Ejemplo n.º 5
0
            /// <seealso cref= Runnable#run() </seealso>
            public void run()
            {
                InvokeCallback callback = future.InvokeCallback;
                // a lot of try-catches to protect thread pool
                ResponseCommand response = null;

                try
                {
                    response = (ResponseCommand)future.waitResponse(0);
                }
                catch (ThreadInterruptedException e)
                {
                    string msg = "Exception caught when getting response from InvokeFuture. The address is " + remoteAddress;
                    logger.LogError(msg, e);
                }
                if (response == null || response.ResponseStatus != ResponseStatus.SUCCESS)
                {
                    try
                    {
                        System.Exception e;
                        if (response == null)
                        {
                            e = new InvokeException("Exception caught in invocation. The address is " + remoteAddress + " responseStatus:" + ResponseStatus.UNKNOWN, future.Cause);
                        }
                        else
                        {
                            response.InvokeContext = future.InvokeContext;
                            switch (response.ResponseStatus)
                            {
                            case ResponseStatus.TIMEOUT:
                                e = new InvokeTimeoutException("Invoke timeout when invoke with callback.The address is " + remoteAddress);
                                break;

                            case ResponseStatus.CONNECTION_CLOSED:
                                e = new ConnectionClosedException("Connection closed when invoke with callback.The address is " + remoteAddress);
                                break;

                            case ResponseStatus.SERVER_THREADPOOL_BUSY:
                                e = new InvokeServerBusyException("Server thread pool busy when invoke with callback.The address is " + remoteAddress);
                                break;

                            case ResponseStatus.SERVER_EXCEPTION:
                                string             msg  = "Server exception when invoke with callback.Please check the server log! The address is " + remoteAddress;
                                RpcResponseCommand resp = (RpcResponseCommand)response;
                                resp.deserialize();
                                object ex = resp.ResponseObject;
                                if (ex != null && ex is System.Exception)
                                {
                                    e = new InvokeServerException(msg, (System.Exception)ex);
                                }
                                else
                                {
                                    e = new InvokeServerException(msg);
                                }
                                break;

                            default:
                                e = new InvokeException("Exception caught in invocation. The address is " + remoteAddress + " responseStatus:" + response.ResponseStatus, future.Cause);

                                break;
                            }
                        }
                        callback.onException(e);
                    }
                    catch (System.Exception e)
                    {
                        logger.LogError("Exception occurred in user defined InvokeCallback#onException() logic, The address is {}", remoteAddress, e);
                    }
                }
                else
                {
                    try
                    {
                        response.InvokeContext = future.InvokeContext;
                        RpcResponseCommand rpcResponse = (RpcResponseCommand)response;
                        response.deserialize();
                        try
                        {
                            callback.onResponse(rpcResponse.ResponseObject);
                        }
                        catch (System.Exception e)
                        {
                            logger.LogError("Exception occurred in user defined InvokeCallback#onResponse() logic.", e);
                        }
                    }
                    catch (CodecException e)
                    {
                        logger.LogError("CodecException caught on when deserialize response in RpcInvokeCallbackListener. The address is {}.", remoteAddress, e);
                    }
                    catch (System.Exception e)
                    {
                        logger.LogError("Exception caught in RpcInvokeCallbackListener. The address is {}", remoteAddress, e);
                    }
                    finally
                    {
                    }
                }         // enf of else
            }             // end of run
Ejemplo n.º 6
0
        private async Task RunReaderAsync()
        {
            try
            {
                if (IsServer)
                {
                    EnsureBuffer(ClientPreface.Length);
                    await ClientPreface.ReadAsync(inputStream, config.ClientPrefaceTimeout);
                }

                var continueRead = true;

                if (serverUpgradeRequest != null)
                {
                    var upgrade = serverUpgradeRequest;
                    serverUpgradeRequest = null;

                    var headers = new CompleteHeadersFrameData
                    {
                        StreamId    = 1u,
                        Priority    = null,
                        Headers     = upgrade.Headers,
                        EndOfStream = upgrade.Payload == null,
                    };

                    var err = await HandleHeaders(headers);

                    if (err != null)
                    {
                        if (err.Value.StreamId == 0)
                        {
                            continueRead = false;
                        }
                        await HandleFrameProcessingError(err.Value);
                    }
                    else if (upgrade.Payload != null)
                    {
                        var buf = config.BufferPool.Rent(upgrade.Payload.Length);
                        Array.Copy(
                            upgrade.Payload, 0, buf, 0, upgrade.Payload.Length);

                        StreamImpl stream = null;
                        lock (shared.Mutex)
                        {
                            shared.streamMap.TryGetValue(1u, out stream);
                        }

                        bool tookBufferOwnership;
                        err = stream.PushBuffer(
                            new ArraySegment <byte>(buf, 0, upgrade.Payload.Length),
                            true,
                            out tookBufferOwnership);
                        if (!tookBufferOwnership)
                        {
                            config.BufferPool.Return(buf);
                        }
                        if (err != null)
                        {
                            if (err.Value.StreamId == 0)
                            {
                                continueRead = false;
                            }
                            await HandleFrameProcessingError(err.Value);
                        }
                    }
                }

                while (continueRead)
                {
                    EnsureBuffer(PersistentBufferSize);
                    var err = await ReadOneFrame();

                    ReleaseBuffer(PersistentBufferSize);
                    if (err != null)
                    {
                        if (err.Value.StreamId == 0)
                        {
                            continueRead = false;
                        }
                        await HandleFrameProcessingError(err.Value);
                    }
                }
            }
            catch (Exception e)
            {
            }

            await writer.CloseNow();

            await writer.Done;

            Dictionary <uint, StreamImpl> activeStreams = null;

            lock (shared.Mutex)
            {
                activeStreams    = shared.streamMap;
                shared.streamMap = null;


                shared.Closed = true;
            }
            foreach (var kvp in activeStreams)
            {
                await kvp.Value.Reset(ErrorCode.ConnectError, fromRemote : true);
            }

            PingState pingState = null;

            lock (shared.Mutex)
            {
                if (shared.PingState != null)
                {
                    pingState        = shared.PingState;
                    shared.PingState = null;
                }
            }
            if (pingState != null)
            {
                var ex = new ConnectionClosedException();
                foreach (var kvp in pingState.PingMap)
                {
                    kvp.Value.SetException(ex);
                }
            }
            if (!remoteGoAwayTcs.Task.IsCompleted)
            {
                remoteGoAwayTcs.TrySetException(new EndOfStreamException());
            }

            if (receiveBuffer != null)
            {
                config.BufferPool.Return(receiveBuffer);
                receiveBuffer = null;
            }

            headerReader.Dispose();
        }
Ejemplo n.º 7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void preProcess(ResponseCommand responseCommand, String addr) throws exception.RemotingException
        private static void preProcess(ResponseCommand responseCommand, string addr)
        {
            RemotingException e   = null;
            string            msg = null;

            if (responseCommand == null)
            {
                msg = string.Format("Rpc invocation timeout[responseCommand null]! the address is {0}", addr);
                e   = new InvokeTimeoutException(msg);
            }
            else
            {
                switch (responseCommand.ResponseStatus)
                {
                case ResponseStatus.TIMEOUT:
                    msg = string.Format("Rpc invocation timeout[responseCommand TIMEOUT]! the address is {0}", addr);
                    e   = new InvokeTimeoutException(msg);
                    break;

                case ResponseStatus.CLIENT_SEND_ERROR:
                    msg = string.Format("Rpc invocation send failed! the address is {0}", addr);
                    e   = new InvokeSendFailedException(msg, responseCommand.Cause);
                    break;

                case ResponseStatus.CONNECTION_CLOSED:
                    msg = string.Format("Connection closed! the address is {0}", addr);
                    e   = new ConnectionClosedException(msg);
                    break;

                case ResponseStatus.SERVER_THREADPOOL_BUSY:
                    msg = string.Format("Server thread pool busy! the address is {0}, id={1}", addr, responseCommand.Id);
                    e   = new InvokeServerBusyException(msg);
                    break;

                case ResponseStatus.CODEC_EXCEPTION:
                    msg = string.Format("Codec exception! the address is {0}, id={1}", addr, responseCommand.Id);
                    e   = new CodecException(msg);
                    break;

                case ResponseStatus.SERVER_SERIAL_EXCEPTION:
                    msg = string.Format("Server serialize response exception! the address is {0}, id={1}, serverSide=true", addr, responseCommand.Id);
                    e   = new SerializationException(detailErrMsg(msg, responseCommand), toThrowable(responseCommand), true);
                    break;

                case ResponseStatus.SERVER_DESERIAL_EXCEPTION:
                    msg = string.Format("Server deserialize request exception! the address is {0}, id={1}, serverSide=true", addr, responseCommand.Id);
                    e   = new DeserializationException(detailErrMsg(msg, responseCommand), toThrowable(responseCommand), true);
                    break;

                case ResponseStatus.SERVER_EXCEPTION:
                    msg = string.Format("Server exception! Please check the server log, the address is {0}, id={1}", addr, responseCommand.Id);
                    e   = new InvokeServerException(detailErrMsg(msg, responseCommand), toThrowable(responseCommand));
                    break;

                default:
                    break;
                }
            }
            if (!string.IsNullOrWhiteSpace(msg))
            {
                logger.LogWarning(msg);
            }
            if (null != e)
            {
                throw e;
            }
        }
Ejemplo n.º 8
0
        private void ChannelRegistration <T>(IBasicProperties basicProperties, string queue, string errorQueue, string exchange, string routingKey, ConsumerResolver <T> resolver)
        {
            var rabbitConsumer = new EventingBasicConsumer(channel);

            rabbitConsumer.Received += (model, ea) =>
            {
                var serializer = RabbitMQWrapperConnection.DefaultAdapter;
                try
                {
                    var message = serializer.DeserializeBytes <RabbitMQWrapperMessage <T> >(ea.Body);

                    AbstractConsumer <T> consumer = null;
                    try
                    {
                        consumer = resolver(message.EventID, message.Event, message.ContractVersion);

                        if (message.Event == "")
                        {
                            consumer.Consume(message.EventID, message.Content, message.ContractVersion);
                        }
                        consumer.Consume(message.Event, message.Content, message.ContractVersion);
                    }
                    catch (Exception e)
                    {
                        Logger.Error("Consumer: " + consumer + " has unexpected error", e);
                        channel.BasicNack(deliveryTag: ea.DeliveryTag, multiple: false, requeue: true);
                        return;
                    }

                    try
                    {
                        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                    }
                    catch (Exception e)
                    {
                        Logger.Error("Connection lost", e);
                        throw e;
                    }
                }
                catch (JsonException e)
                {
                    var customError = new UnexpectedException(e);
                    Logger.Error("Could not deserialize the object: " + ea.Body, customError);
                    try
                    {
                        Logger.Warn("Creating error queue...");
                        this.EnsureRoute(errorQueue, exchange, routingKey);
                        this.channel.BasicPublish(exchange: exchange, routingKey: routingKey, basicProperties: basicProperties, body: ea.Body);
                        channel.BasicNack(deliveryTag: ea.DeliveryTag, multiple: false, requeue: false);
                    }
                    catch (Exception ex)
                    {
                        var custom = new UnexpectedException(ex);
                        Logger.Fatal("Unexpected error occured while publishing items to error queue", custom);
                        throw custom;
                    }
                }
                catch (Exception e)
                {
                    var custom = new UnexpectedException(e);
                    Logger.Fatal("Unexpected error occured while consumer received a message", custom);
                    throw custom;
                }
            };

            try
            {
                channel.BasicConsume(queue: queue, noAck: false, consumer: rabbitConsumer, consumerTag: appKey);
            }
            catch (IOException e)
            {
                if (channel.IsOpen == false)
                {
                    var custom = new ConnectionClosedException(e);
                    Logger.Info("Trying to reconnect again... Queue:" + queue, custom);
                    Thread.Sleep(200);
                    channel.BasicConsume(queue: queue, noAck: false, consumer: rabbitConsumer, consumerTag: appKey);
                }
                else
                {
                    var custom = new AccessDeniedException(e);
                    Logger.Fatal("Access denied. Queue: " + queue, custom);
                    throw custom;
                }
            }
        }