Ejemplo n.º 1
0
 static LocalChannel()
 {
     METADATA = new ChannelMetadata(false);
     DoWriteClosedChannelException = new ClosedChannelException();
     DoCloseClosedChannelException = new ClosedChannelException();
     InternalReadAction            = o => InternalRead(o);
 }
Ejemplo n.º 2
0
        void Discard(Exception cause = null)
        {
            for (;;)
            {
                PendingWrite current = this.currentWrite;
                if (this.currentWrite == null)
                {
                    current = this.queue.Count > 0 ? this.queue.Dequeue() : null;
                }
                else
                {
                    this.currentWrite = null;
                }

                if (current == null)
                {
                    break;
                }

                object message = current.Message;
                var    chunks  = message as IChunkedInput <T>;
                if (chunks != null)
                {
                    try
                    {
                        if (!chunks.IsEndOfInput)
                        {
                            if (cause == null)
                            {
                                cause = new ClosedChannelException();
                            }

                            current.Fail(cause);
                        }
                        else
                        {
                            current.Success();
                        }
                    }
                    catch (Exception exception)
                    {
                        current.Fail(exception);
                        Logger.Warn($"{StringUtil.SimpleClassName(typeof(ChunkedWriteHandler<T>))}.IsEndOfInput failed", exception);
                    }
                    finally
                    {
                        CloseInput(chunks);
                    }
                }
                else
                {
                    if (cause == null)
                    {
                        cause = new ClosedChannelException();
                    }

                    current.Fail(cause);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Reopens the channel if it has been closed and the close() method on
        /// this swapper has not been called. In other words, if the channel has
        /// been "accidentally" closed by an interrupt or the like.
        ///
        /// If the channel has been explicitly closed with the PageSwapper#close()
        /// method, then this method will re-throw the passed-in exception.
        ///
        /// If the reopening of the file fails with an exception for some reason,
        /// then that exception is added as a suppressed exception to the passed in
        /// ClosedChannelException, and the CCE is then rethrown.
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private synchronized void tryReopen(long filePageId, java.nio.channels.ClosedChannelException closedException) throws java.nio.channels.ClosedChannelException
        private void TryReopen(long filePageId, ClosedChannelException closedException)
        {
            lock (this)
            {
                int          stripe  = stripe(filePageId);
                StoreChannel channel = _channels[stripe];
                if (channel.Open)
                {
                    // Someone got ahead of us, presumably. Nothing to do.
                    return;
                }

                if (_closed)
                {
                    // We've been explicitly closed, so we shouldn't reopen the
                    // channel.
                    throw closedException;
                }

                try
                {
                    _channels[stripe] = _fs.open(_file, OpenMode.READ_WRITE);
                    if (stripe == TOKEN_CHANNEL_STRIPE)
                    {
                        // The closing of a FileChannel also releases all associated file locks.
                        AcquireLock();
                    }
                }
                catch (IOException e)
                {
                    closedException.addSuppressed(e);
                    throw closedException;
                }
            }
        }
Ejemplo n.º 4
0
        void Discard(Exception cause = null)
        {
            while (true)
            {
                if (!_queue.TryRemoveFromFront(out PendingWrite currentWrite))
                {
                    break;
                }

                object message = currentWrite.Message;
                if (message is IChunkedInput <T> chunks)
                {
                    bool endOfInput;
                    long inputLength;
                    try
                    {
                        endOfInput  = chunks.IsEndOfInput;
                        inputLength = chunks.Length;
                        CloseInput(chunks);
                    }
                    catch (Exception exc)
                    {
                        CloseInput(chunks);
                        currentWrite.Fail(exc);
                        if (Logger.WarnEnabled)
                        {
                            Logger.IsEndOfInputFailed <T>(exc);
                        }
                        continue;
                    }

                    if (!endOfInput)
                    {
                        if (cause is null)
                        {
                            cause = ThrowHelper.GetClosedChannelException();
                        }
                        currentWrite.Fail(cause);
                    }
                    else
                    {
                        currentWrite.Success(inputLength);
                    }
                }
                else
                {
                    if (cause is null)
                    {
                        cause = new ClosedChannelException();
                    }

                    currentWrite.Fail(cause);
                }
            }
        }
Ejemplo n.º 5
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void handleClosedChannelException(java.nio.channels.ClosedChannelException e) throws java.nio.channels.ClosedChannelException
        private void HandleClosedChannelException(ClosedChannelException e)
        {
            // We don't want to check the closed flag every time we empty, instead we can avoid unnecessary the
            // volatile read and catch ClosedChannelException where we see if the channel being closed was
            // deliberate or not. If it was deliberately closed then throw IllegalStateException instead so
            // that callers won't treat this as a kernel panic.
            if (_closed)
            {
                throw new System.InvalidOperationException("This log channel has been closed", e);
            }

            // OK, this channel was closed without us really knowing about it, throw exception as is.
            throw e;
        }
        public void Ctors()
        {
            var e = new ClosedChannelException();

            Assert.NotEmpty(e.Message);
            Assert.Null(e.InnerException);

            e = new ClosedChannelException("hello");
            Assert.Equal("hello", e.Message);
            Assert.Null(e.InnerException);

            var inner = new FormatException();

            e = new ClosedChannelException("hello", inner);
            Assert.Equal("hello", e.Message);
            Assert.Same(inner, e.InnerException);
        }
Ejemplo n.º 7
0
        TaskCompletionSource <ConnectResult> connectFuture; //create a Task start with Connect, end by ConnAct.
        public async Task <ConnectResult> ConnectAsync(string host, int port)
        {
            if (isConnected())
            {
                return(new ConnectResult(true, ConnectReturnCode.Accepted, channel.CloseCompletion));
            }

            if (eventLoopGroup == null)
            {
                eventLoopGroup = new MultithreadEventLoopGroup();
            }

            connectFuture = new TaskCompletionSource <ConnectResult>();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ClientSettings.ProcessDirectory, ClientSettings.KeyFile), ClientSettings.Password);
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            var bootstrap = new Bootstrap();

            bootstrap
            .Group(eventLoopGroup)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                if (cert != null)
                {
                    pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                }
                if (ClientSettings.EnableLoggingHandler)
                {
                    pipeline.AddLast(new LoggingHandler());
                }
                pipeline.AddLast(MqttEncoder.Instance);
                pipeline.AddLast(new MqttDecoder(false, ClientSettings.MaxMessageSize));
                AddHandlers(pipeline);
                pipeline.AddLast(new MqttHandler(this));
            }));
            try
            {
                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(host), port));

                if (clientChannel.Open)
                {
                    channel = clientChannel;
                    _       = clientChannel.CloseCompletion.ContinueWith((t, s) =>
                    {
                        var self = (MqttClient)s;
                        if (self.isConnected())
                        {
                            return;
                        }
                        if (self.OnConnectionChange != null)
                        {
                            if (connectFuture.Task.IsCompleted)
                            {
                                var result = connectFuture.Task.Result;
                                if (result.ReturnCode != ConnectReturnCode.Accepted)
                                {
                                    ChannelClosedException e = new ChannelClosedException(result.ReturnCode.ToString());
                                    self.OnConnectionChange.OnConnectionLost(e);
                                    connectFuture.TrySetException(e);
                                }//ConnAct with refused code.
                            }
                            else
                            {
                                ChannelClosedException e = new ChannelClosedException("Channel is closed!", connectFuture.Task.Exception);
                                self.OnConnectionChange.OnConnectionLost(e);
                                connectFuture.TrySetException(e);
                            }//Channel closed before ConnAct.
                        }
                        pendingPublishes.Clear();
                        pendingIncomingQoS2Publishes.Clear();
                        pendingSubscribes.Clear();
                        pendingSubscribeTopics.Clear();
                        pendingUnsubscribes.Clear();
                        topicSubscriptions.Clear();
                        subscribedTopics.Clear();
                        callbackSubscriptions.Clear();
                        reconnecting = true;
                        scheduleReconnect(host, port);//auto reconnect when channel closed.
                    }, this, TaskContinuationOptions.ExecuteSynchronously);
                }
                else
                {
                    var e = new ClosedChannelException();
                    if (OnConnectionChange != null)
                    {
                        OnConnectionChange.OnConnectionLost(e);
                    }
                    connectFuture.SetException(e);
                    scheduleReconnect(host, port);//auto reconnect when connect failed.
                }
            }
            catch (Exception e)
            {
                connectFuture.SetException(e);
                scheduleReconnect(host, port); //auto reconnect when connect error.
            }
            return(await connectFuture.Task);
        }
Ejemplo n.º 8
0
        internal void Close(ClosedChannelException cause)
        {
            if (this.inFail)
            {
                this.channel.EventLoop.Execute((buf, ex) => ((ChannelOutboundBuffer)buf).Close((ClosedChannelException)ex),
                    this, cause);
                return;
            }

            this.inFail = true;

            if (this.channel.Open)
            {
                throw new InvalidOperationException("close() must be invoked after the channel is closed.");
            }

            if (!this.IsEmpty)
            {
                throw new InvalidOperationException("close() must be invoked after all flushed writes are handled.");
            }

            // Release all unflushed messages.
            try
            {
                Entry e = this.unflushedEntry;
                while (e != null)
                {
                    // Just decrease; do not trigger any events via DecrementPendingOutboundBytes()
                    int size = e.PendingSize;
                    Interlocked.Add(ref this.totalPendingSize, -size);

                    if (!e.Cancelled)
                    {
                        ReferenceCountUtil.SafeRelease(e.Message);
                        Util.SafeSetFailure(e.Promise, cause);
                        if (e.Promise != TaskCompletionSource.Void && !e.Promise.TrySetException(cause))
                        {
                            ChannelEventSource.Log.Warning(string.Format("Failed to mark a promise as failure because it's done already: {0}", e.Promise), cause);
                        }
                    }
                    e = e.RecycleAndGetNext();
                }
            }
            finally
            {
                this.inFail = false;
            }
        }
Ejemplo n.º 9
0
 internal void Close(ClosedChannelException cause)
 {
     this.Close(cause, false);
 }