public ChannelMethodHandler(IServiceLocator services, Type channel, MethodInfo method, AuthenticationSettings settings, string baseURL, string channelHandlerId)
        {
            _services  = services ?? throw new ArgumentNullException(nameof(services));
            _method    = method ?? throw new ArgumentNullException(nameof(method));
            _channel   = channel ?? throw new ArgumentNullException(nameof(channel));
            _settings  = settings;
            _baseURL   = baseURL;
            _isManaged = false;

            _channelMethodDescriptor = _services.Get <IChannelMethodDescriptor>();
            _requestActivator        = _services.Get <IChannelMethodRequestActivator>();
            _msgService            = _services.Get <IChannelMessageService>();
            _contextProvider       = _services.Get <IChannelMethodContextProvider>();
            _configuration         = _services.Get <IChannelConfiguration>();
            _authenticationService = _services.Get <IChannelAuthenticationService>();
            _heuristics            = _services.Get <IChannelHeuristics>();
            _session = _services.Get <ISessionService>();

            HandlerId        = $"{Guid.NewGuid()}";
            ChannelHandlerId = channelHandlerId;

            _isDisposed = false;
            _safeHandle = new SafeFileHandle(IntPtr.Zero, true);
        }
示例#2
0
            public override void FinishRead(SocketChannelAsyncOperation operation)
            {
                Contract.Assert(this.channel.EventLoop.InEventLoop);

                TcpServerSocketChannel ch = this.Channel;

                if ((ch.ResetState(StateFlags.ReadScheduled) & StateFlags.Active) == 0)
                {
                    return; // read was signaled as a result of channel closure
                }
                IChannelConfiguration       config      = ch.Configuration;
                IChannelPipeline            pipeline    = ch.Pipeline;
                IRecvByteBufAllocatorHandle allocHandle = this.Channel.Unsafe.RecvBufAllocHandle;

                allocHandle.Reset(config);

                bool      closed    = false;
                Exception exception = null;

                try
                {
                    Socket connectedSocket = null;
                    try
                    {
                        connectedSocket        = operation.AcceptSocket;
                        operation.AcceptSocket = null;
                        operation.Validate();

                        var message = this.PrepareChannel(connectedSocket);

                        connectedSocket = null;
                        ch.ReadPending  = false;
                        pipeline.FireChannelRead(message);
                        allocHandle.IncMessagesRead(1);

                        if (!config.AutoRead && !ch.ReadPending)
                        {
                            // ChannelConfig.setAutoRead(false) was called in the meantime.
                            // Completed Accept has to be processed though.
                            return;
                        }

                        while (allocHandle.ContinueReading())
                        {
                            connectedSocket = ch.Socket.Accept();
                            message         = this.PrepareChannel(connectedSocket);

                            connectedSocket = null;
                            ch.ReadPending  = false;
                            pipeline.FireChannelRead(message);
                            allocHandle.IncMessagesRead(1);
                        }
                    }
                    catch (SocketException ex) when(ex.SocketErrorCode == SocketError.OperationAborted || ex.SocketErrorCode == SocketError.InvalidArgument)
                    {
                        closed = true;
                    }
                    catch (SocketException ex) when(ex.SocketErrorCode == SocketError.WouldBlock)
                    {
                    }
                    catch (SocketException ex)
                    {
                        // socket exceptions here are internal to channel's operation and should not go through the pipeline
                        // especially as they have no effect on overall channel's operation
                        Logger.Info("Exception on accept.", ex);
                    }
                    catch (ObjectDisposedException)
                    {
                        closed = true;
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }

                    allocHandle.ReadComplete();
                    pipeline.FireChannelReadComplete();

                    if (exception != null)
                    {
                        // ServerChannel should not be closed even on SocketException because it can often continue
                        // accepting incoming connections. (e.g. too many open files)

                        pipeline.FireExceptionCaught(exception);
                    }

                    if (closed && ch.Open)
                    {
                        this.CloseSafe();
                    }
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    if (!closed && (ch.ReadPending || config.AutoRead))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
示例#3
0
            public override void FinishRead(SocketChannelAsyncOperation operation)
            {
                Contract.Requires(this._channel.EventLoop.InEventLoop);

                TcpServerSocketChannel ch = this.Channel;

                ch.ResetState(StateFlags.ReadScheduled);
                IChannelConfiguration config = ch.Configuration;

                int maxMessagesPerRead     = config.MaxMessagesPerRead;
                IChannelPipeline pipeline  = ch.Pipeline;
                bool             closed    = false;
                Exception        exception = null;

                int messageCount = 0;

                try
                {
                    Socket connectedSocket = null;
                    try
                    {
                        connectedSocket = operation.AcceptSocket;
                        operation.Validate();
                        operation.AcceptSocket = null;

                        var message = new TcpSocketChannel(ch, connectedSocket, true);
                        ch.ReadPending = false;
                        pipeline.FireChannelRead(message);
                        messageCount++;

                        if (!config.AutoRead && !ch.ReadPending)
                        {
                            // ChannelConfig.setAutoRead(false) was called in the meantime.
                            // Completed Accept has to be processed though.
                            return;
                        }

                        while (messageCount < maxMessagesPerRead)
                        {
                            connectedSocket = null;
                            connectedSocket = ch.Socket.Accept();
                            message         = new TcpSocketChannel(ch, connectedSocket, true);
                            pipeline.FireChannelRead(message);

                            // stop reading and remove op
                            if (!config.AutoRead)
                            {
                                break;
                            }
                            messageCount++;
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        closed = true;
                    }
                    catch (Exception ex)
                    {
                        var asSocketException = ex as SocketException;
                        if (asSocketException == null || asSocketException.SocketErrorCode != SocketError.WouldBlock)
                        {
                            Logger.Warning(ex, "Failed to create a new channel from an accepted socket.");
                            if (connectedSocket != null)
                            {
                                try
                                {
                                    connectedSocket.Close();
                                }
                                catch (Exception ex2)
                                {
                                    Logger.Warning(ex2, "Failed to close a socket.");
                                }
                            }
                            exception = ex;
                        }
                    }

                    pipeline.FireChannelReadComplete();

                    if (exception != null)
                    {
                        // ServerChannel should not be closed even on SocketException because it can often continue
                        // accepting incoming connections. (e.g. too many open files)

                        pipeline.FireExceptionCaught(exception);
                    }

                    if (closed)
                    {
                        if (ch.IsOpen)
                        {
                            this.CloseAsync();
                        }
                    }
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    if (!closed && (config.AutoRead || ch.ReadPending))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
 public PathLookupService(IEmailTemplateFormatter formatter, IChannelConfiguration channelConfiguration, WebConfiguration webConfig)
 {
     this.formatter            = formatter;
     this.channelConfiguration = channelConfiguration;
     this.webConfig            = webConfig;
 }
示例#5
0
        public Launch(
            ILogger logger,
            IIrcClient freenodeClient,
            IIrcClient wikimediaClient,
            IAppConfiguration appConfig,
            ITemplateConfiguration templateConfiguration,
            IBotUserConfiguration userConfiguration,
            IChannelConfiguration channelConfiguration,
            IStalkFactory stalkFactory,
            IFileService fileService)
        {
            this.logger               = logger;
            this.freenodeClient       = freenodeClient;
            this.wikimediaClient      = wikimediaClient;
            this.appConfig            = appConfig;
            this.channelConfiguration = channelConfiguration;

            if (!this.channelConfiguration.Items.Any())
            {
                this.logger.InfoFormat("Migrating to channel configuration file...");

                var defaultChannel = new IrcChannel(this.appConfig.FreenodeChannel);
                this.channelConfiguration.Add(defaultChannel);

                if (appConfig.StalkConfigFile != null)
                {
                    var stalkConfig = new StalkConfiguration(
                        appConfig,
                        logger.CreateChildLogger("LegacyStalkConfig"),
                        stalkFactory,
                        fileService
                        );
                    stalkConfig.Initialize();

                    foreach (var stalk in stalkConfig.Items)
                    {
                        stalk.Channel = this.appConfig.FreenodeChannel;
                        defaultChannel.Stalks.Add(stalk.Identifier, stalk);
                        stalkConfig.Remove(stalk.Identifier);
                    }

                    stalkConfig.Save();
                }

                this.channelConfiguration.Save();
            }

            this.logger.InfoFormat(
                "Tracking {0} stalks, {1} templates, {2} users, and {3} channels.",
                this.channelConfiguration.Items.Aggregate(0, (i, channel) => i + channel.Stalks.Count),
                templateConfiguration.Items.Count,
                userConfiguration.Items.Count,
                channelConfiguration.Items.Count
                );

            if (appConfig.MetricsPort != 0)
            {
                this.logger.DebugFormat("Setting up metrics server on port {0}", appConfig.MetricsPort);
                this.metricsServer = new MetricServer(appConfig.MetricsPort);
                this.metricsServer.Start();

                VersionInfo.WithLabels(
                    FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion,
                    FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(IrcClient)).Location)
                    .FileVersion,
                    FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(CommandBase)).Location)
                    .FileVersion,
                    FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(MediaWikiApi)).Location)
                    .FileVersion,
                    FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(ConduitClient)).Location)
                    .FileVersion,
                    Environment.Version.ToString(),
                    Environment.OSVersion.ToString(),
                    ((TargetFrameworkAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(TargetFrameworkAttribute), false).FirstOrDefault())?.FrameworkDisplayName ?? "Unknown"
                    )
                .Set(1);

                this.logger.DebugFormat("Metrics server configured.");
            }
            else
            {
                this.logger.Warn("Prometheus metrics server disabled.");
            }

            this.freenodeClient.DisconnectedEvent  += this.OnDisconnect;
            this.wikimediaClient.DisconnectedEvent += this.OnDisconnect;
        }
示例#6
0
            //new AbstractSocketMessageChannel Channel => (AbstractSocketMessageChannel)this.channel;

            public override void FinishRead(SocketChannelAsyncOperation <TChannel, TUnsafe> operation)
            {
                Debug.Assert(_channel.EventLoop.InEventLoop);

                var ch = _channel;

                if (0u >= (uint)(ch.ResetState(StateFlags.ReadScheduled) & StateFlags.Active))
                {
                    return; // read was signaled as a result of channel closure
                }
                IChannelConfiguration config = ch.Configuration;

                IChannelPipeline            pipeline    = ch.Pipeline;
                IRecvByteBufAllocatorHandle allocHandle = ch.Unsafe.RecvBufAllocHandle;

                allocHandle.Reset(config);

                bool      closed    = false;
                Exception exception = null;

                try
                {
                    try
                    {
                        do
                        {
                            int  localRead  = ch.DoReadMessages(_readBuf);
                            uint uLocalRead = (uint)localRead;
                            if (0u >= uLocalRead)
                            {
                                break;
                            }
                            if (uLocalRead > SharedConstants.TooBigOrNegative) // localRead < 0
                            {
                                closed = true;
                                break;
                            }

                            allocHandle.IncMessagesRead(localRead);
                        }while (allocHandle.ContinueReading());
                    }
                    catch (Exception t)
                    {
                        exception = t;
                    }
                    int size = _readBuf.Count;
                    for (int i = 0; i < size; i++)
                    {
                        ch.ReadPending = false;
                        _ = pipeline.FireChannelRead(_readBuf[i]);
                    }

                    _readBuf.Clear();
                    allocHandle.ReadComplete();
                    _ = pipeline.FireChannelReadComplete();

                    if (exception is object)
                    {
                        if (exception is SocketException asSocketException && asSocketException.SocketErrorCode != SocketError.TryAgain) // todo: other conditions for not closing message-based socket?
                        {
                            // ServerChannel should not be closed even on SocketException because it can often continue
                            // accepting incoming connections. (e.g. too many open files)
                            closed = !(ch is IServerChannel);
                        }

                        _ = pipeline.FireExceptionCaught(exception);
                    }

                    if (closed)
                    {
                        if (ch.Open)
                        {
                            Close(VoidPromise());
                        }
                    }
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    // This could be for two reasons:
                    // /// The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
                    // /// The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method
                    //
                    // See https://github.com/netty/netty/issues/2254
                    if (!closed && (ch.ReadPending || config.AutoRead))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
示例#7
0
 public abstract bool Set(IChannelConfiguration configuration, object value);
 public void Reset(IChannelConfiguration channelConfig)
 {
     this.config = channelConfig;
 }
 protected static void CompositeBufferPartialWriteDoesNotCorruptDataInitServerConfig(IChannelConfiguration config, int soSndBuf)
 {
 }
示例#10
0
            public override void FinishRead(SocketChannelAsyncOperation operation)
            {
                AbstractSocketByteChannel ch = this.Channel;

                ch.ResetState(StateFlags.ReadScheduled);
                IChannelConfiguration config            = ch.Configuration;
                IChannelPipeline      pipeline          = ch.Pipeline;
                IByteBufferAllocator  allocator         = config.Allocator;
                int maxMessagesPerRead                  = config.MaxMessagesPerRead;
                IRecvByteBufAllocatorHandle allocHandle = this.RecvBufAllocHandle;

                IByteBuffer byteBuf  = null;
                int         messages = 0;
                bool        close    = false;

                try
                {
                    operation.Validate();

                    int  totalReadAmount  = 0;
                    bool readPendingReset = false;
                    do
                    {
                        byteBuf = allocHandle.Allocate(allocator);
                        int writable        = byteBuf.WritableBytes;
                        int localReadAmount = ch.DoReadBytes(byteBuf);
                        if (localReadAmount <= 0)
                        {
                            // not was read release the buffer
                            byteBuf.Release();
                            byteBuf = null;
                            close   = localReadAmount < 0;
                            break;
                        }
                        if (!readPendingReset)
                        {
                            readPendingReset = true;
                            ch.ReadPending   = false;
                        }
                        pipeline.FireChannelRead(byteBuf);
                        byteBuf = null;

                        if (totalReadAmount >= int.MaxValue - localReadAmount)
                        {
                            // Avoid overflow.
                            totalReadAmount = int.MaxValue;
                            break;
                        }

                        totalReadAmount += localReadAmount;

                        // stop reading
                        if (!config.AutoRead)
                        {
                            break;
                        }

                        if (localReadAmount < writable)
                        {
                            // Read less than what the buffer can hold,
                            // which might mean we drained the recv buffer completely.
                            break;
                        }
                    }while (++messages < maxMessagesPerRead);

                    pipeline.FireChannelReadComplete();
                    allocHandle.Record(totalReadAmount);

                    if (close)
                    {
                        this.CloseOnRead();
                        close = false;
                    }
                }
                catch (Exception t)
                {
                    this.HandleReadException(pipeline, byteBuf, t, close);
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    // This could be for two reasons:
                    // /// The user called Channel.read() or ChannelHandlerContext.read() input channelRead(...) method
                    // /// The user called Channel.read() or ChannelHandlerContext.read() input channelReadComplete(...) method
                    //
                    // See https://github.com/netty/netty/issues/2254
                    if (!close && (ch.ReadPending || config.AutoRead))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
示例#11
0
            public override void FinishRead(SocketChannelAsyncOperation operation)
            {
                Contract.Assert(this.channel.EventLoop.InEventLoop);

                AbstractSocketMessageChannel ch = this.Channel;

                ch.ResetState(StateFlags.ReadScheduled);
                IChannelConfiguration config = ch.Configuration;

                IChannelPipeline            pipeline    = ch.Pipeline;
                IRecvByteBufAllocatorHandle allocHandle = this.Channel.Unsafe.RecvBufAllocHandle;

                allocHandle.Reset(config);

                bool      closed    = false;
                Exception exception = null;

                try
                {
                    try
                    {
                        do
                        {
                            int localRead = ch.DoReadMessages(this.readBuf);
                            if (localRead == 0)
                            {
                                break;
                            }
                            if (localRead < 0)
                            {
                                closed = true;
                                break;
                            }

                            allocHandle.IncMessagesRead(localRead);
                        }while (allocHandle.ContinueReading());
                    }
                    catch (Exception t)
                    {
                        exception = t;
                    }
                    int size = this.readBuf.Count;
                    for (int i = 0; i < size; i++)
                    {
                        ch.ReadPending = false;
                        pipeline.FireChannelRead(this.readBuf[i]);
                    }

                    this.readBuf.Clear();
                    allocHandle.ReadComplete();
                    pipeline.FireChannelReadComplete();

                    if (exception != null)
                    {
                        var asSocketException = exception as SocketException;
                        if (asSocketException != null && asSocketException.SocketErrorCode != SocketError.TryAgain) // todo: other conditions for not closing message-based socket?
                        {
                            // ServerChannel should not be closed even on SocketException because it can often continue
                            // accepting incoming connections. (e.g. too many open files)
                            closed = !(ch is IServerChannel);
                        }

                        pipeline.FireExceptionCaught(exception);
                    }

                    if (closed)
                    {
                        if (ch.Open)
                        {
                            this.CloseAsync();
                        }
                    }
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    // This could be for two reasons:
                    // /// The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
                    // /// The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method
                    //
                    // See https://github.com/netty/netty/issues/2254
                    if (!closed && (ch.ReadPending || config.AutoRead))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
示例#12
0
 public TestChannel()
     : base(null)
 {
     _config = new DefaultChannelConfiguration(this);
 }
示例#13
0
 public void SetUpTest()
 {
     _channelConfig        = Setup.TestChannelConfig();
     _itemMatcherUnderTest = new IndividualItemMatcher <LocalTestResource, RemoteTestResource, int, ItemMatch <LocalTestResource, RemoteTestResource> >(
         _channelConfig, TargetType.T1);
 }
 public void SetUpTest()
 {
     _channelConfig = Setup.TestChannelConfig();
     _itemMatcherUnderTest = new IndividualItemMatcher<LocalTestResource, RemoteTestResource, int, ItemMatch<LocalTestResource, RemoteTestResource>>(
             _channelConfig, TargetType.T1);
 }
            public override void FinishRead(SocketChannelAsyncOperation operation)
            {
                Contract.Requires(this.channel.EventLoop.InEventLoop);
                AbstractSocketMessageChannel ch = this.Channel;

                ch.ResetState(StateFlags.ReadScheduled);
                IChannelConfiguration config = ch.Configuration;

                if (!config.AutoRead && !ch.ReadPending)
                {
                    // ChannelConfig.setAutoRead(false) was called in the meantime
                    //removeReadOp(); -- noop with IOCP, just don't schedule receive again
                    return;
                }

                int maxMessagesPerRead     = config.MaxMessagesPerRead;
                IChannelPipeline pipeline  = ch.Pipeline;
                bool             closed    = false;
                Exception        exception = null;

                try
                {
                    try
                    {
                        while (true)
                        {
                            int localRead = ch.DoReadMessages(this.readBuf);
                            if (localRead == 0)
                            {
                                break;
                            }
                            if (localRead < 0)
                            {
                                closed = true;
                                break;
                            }

                            // stop reading and remove op
                            if (!config.AutoRead)
                            {
                                break;
                            }

                            if (this.readBuf.Count >= maxMessagesPerRead)
                            {
                                break;
                            }
                        }
                    }
                    catch (Exception t)
                    {
                        exception = t;
                    }
                    ch.ReadPending = false;
                    int size = this.readBuf.Count;
                    for (int i = 0; i < size; i++)
                    {
                        pipeline.FireChannelRead(this.readBuf[i]);
                    }

                    this.readBuf.Clear();
                    pipeline.FireChannelReadComplete();

                    if (exception != null)
                    {
                        var asSocketException = exception as SocketException;
                        if (asSocketException != null && asSocketException.SocketErrorCode != SocketError.TryAgain) // todo: other conditions for not closing message-based socket?
                        {
                            // ServerChannel should not be closed even on SocketException because it can often continue
                            // accepting incoming connections. (e.g. too many open files)
                            closed = !(ch is IServerChannel);
                        }

                        pipeline.FireExceptionCaught(exception);
                    }

                    if (closed)
                    {
                        if (ch.Open)
                        {
                            this.CloseAsync();
                        }
                    }
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    // This could be for two reasons:
                    // /// The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
                    // /// The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method
                    //
                    // See https://github.com/netty/netty/issues/2254
                    if (!closed && (config.AutoRead || ch.ReadPending))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
示例#16
0
 public void Reset(IChannelConfiguration config)
 {
     this.numMessagesRead = 0;
 }
            public override void FinishRead(SocketChannelAsyncOperation <TServerChannel, TcpServerSocketChannelUnsafe> operation)
            {
                Debug.Assert(_channel.EventLoop.InEventLoop);

                var ch = _channel;

                if (0u >= (uint)(ch.ResetState(StateFlags.ReadScheduled) & StateFlags.Active))
                {
                    return; // read was signaled as a result of channel closure
                }
                IChannelConfiguration       config      = ch.Configuration;
                IChannelPipeline            pipeline    = ch.Pipeline;
                IRecvByteBufAllocatorHandle allocHandle = ch.Unsafe.RecvBufAllocHandle;

                allocHandle.Reset(config);

                var       closed    = false;
                var       aborted   = false;
                Exception exception = null;

                try
                {
                    Socket connectedSocket = null;
                    try
                    {
                        connectedSocket        = operation.AcceptSocket;
                        operation.AcceptSocket = null;
                        operation.Validate();

                        var message = PrepareChannel(connectedSocket);

                        connectedSocket = null;
                        ch.ReadPending  = false;
                        _ = pipeline.FireChannelRead(message);
                        allocHandle.IncMessagesRead(1);

                        if (!config.IsAutoRead && !ch.ReadPending)
                        {
                            // ChannelConfig.setAutoRead(false) was called in the meantime.
                            // Completed Accept has to be processed though.
                            return;
                        }

                        while (allocHandle.ContinueReading())
                        {
                            connectedSocket = ch.Socket.Accept();
                            message         = PrepareChannel(connectedSocket);

                            connectedSocket = null;
                            ch.ReadPending  = false;
                            _ = pipeline.FireChannelRead(message);
                            allocHandle.IncMessagesRead(1);
                        }
                    }
                    catch (SocketException ex) when(ex.SocketErrorCode.IsSocketAbortError())
                    {
                        ch.Socket.SafeClose(); // Unbind......
                        exception = ex;
                        aborted   = true;
                    }
                    catch (SocketException ex) when(ex.SocketErrorCode == SocketError.WouldBlock)
                    {
                    }
                    catch (SocketException ex)
                    {
                        // socket exceptions here are internal to channel's operation and should not go through the pipeline
                        // especially as they have no effect on overall channel's operation
                        if (Logger.InfoEnabled)
                        {
                            Logger.ExceptionOnAccept(ex);
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        closed = true;
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }

                    allocHandle.ReadComplete();
                    _ = pipeline.FireChannelReadComplete();

                    if (exception is object)
                    {
                        // ServerChannel should not be closed even on SocketException because it can often continue
                        // accepting incoming connections. (e.g. too many open files)

                        _ = pipeline.FireExceptionCaught(exception);
                    }

                    if (ch.IsOpen)
                    {
                        if (closed)
                        {
                            Close(VoidPromise());
                        }
                        else if (aborted)
                        {
                            ch.CloseSafe();
                        }
                    }
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    if (!closed && (ch.ReadPending || config.IsAutoRead))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
示例#18
0
            public override void FinishRead(SocketChannelAsyncOperation operation)
            {
                AbstractSocketByteChannel ch = this.Channel;

                if ((ch.ResetState(StateFlags.ReadScheduled) & StateFlags.Active) == 0)
                {
                    return; // read was signaled as a result of channel closure
                }
                IChannelConfiguration       config      = ch.Configuration;
                IChannelPipeline            pipeline    = ch.Pipeline;
                IByteBufferAllocator        allocator   = config.Allocator;
                IRecvByteBufAllocatorHandle allocHandle = this.RecvBufAllocHandle;

                allocHandle.Reset(config);

                IByteBuffer byteBuf = null;
                bool        close   = false;

                try
                {
                    operation.Validate();

                    do
                    {
                        byteBuf = allocHandle.Allocate(allocator);
                        //int writable = byteBuf.WritableBytes;
                        allocHandle.LastBytesRead = ch.DoReadBytes(byteBuf);
                        if (allocHandle.LastBytesRead <= 0)
                        {
                            // nothing was read -> release the buffer.
                            byteBuf.Release();
                            byteBuf = null;
                            close   = allocHandle.LastBytesRead < 0;
                            break;
                        }

                        allocHandle.IncMessagesRead(1);
                        this.Channel.ReadPending = false;

                        pipeline.FireChannelRead(byteBuf);
                        byteBuf = null;
                    }while (allocHandle.ContinueReading());

                    allocHandle.ReadComplete();
                    pipeline.FireChannelReadComplete();

                    if (close)
                    {
                        this.CloseOnRead();
                    }
                }
                catch (Exception t)
                {
                    this.HandleReadException(pipeline, byteBuf, t, close, allocHandle);
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    // This could be for two reasons:
                    // /// The user called Channel.read() or ChannelHandlerContext.read() input channelRead(...) method
                    // /// The user called Channel.read() or ChannelHandlerContext.read() input channelReadComplete(...) method
                    //
                    // See https://github.com/netty/netty/issues/2254
                    if (!close && (ch.ReadPending || config.AutoRead))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
 /// <summary>Only <see cref="IChannelConfiguration.MaxMessagesPerRead" /> is used.</summary>
 public void Reset(IChannelConfiguration config)
 {
     this.config            = config;
     this.maxMessagePerRead = this.Owner.MaxMessagesPerRead;
     this.totalMessages     = this.totalBytesRead = 0;
 }
示例#20
0
 public abstract bool Set(IChannelConfiguration config);
示例#21
0
 public abstract bool Set(IChannelConfiguration configuration, object value);
示例#22
0
            public override void FinishRead(SocketChannelAsyncOperation operation)
            {
                Contract.Assert(this.channel.EventLoop.InEventLoop);

                TcpServerSocketChannel ch = this.Channel;

                if ((ch.ResetState(StateFlags.ReadScheduled) & StateFlags.Active) == 0)
                {
                    return; // read was signaled as a result of channel closure
                }
                IChannelConfiguration       config      = ch.Configuration;
                IChannelPipeline            pipeline    = ch.Pipeline;
                IRecvByteBufAllocatorHandle allocHandle = this.Channel.Unsafe.RecvBufAllocHandle;

                allocHandle.Reset(config);

                bool      closed    = false;
                Exception exception = null;

                try
                {
                    Socket connectedSocket = null;
                    try
                    {
                        connectedSocket = operation.AcceptSocket;
                        operation.Validate();
                        operation.AcceptSocket = null;

                        var message = new TcpSocketChannel(ch, connectedSocket, true);
                        ch.ReadPending = false;
                        pipeline.FireChannelRead(message);
                        allocHandle.IncMessagesRead(1);

                        if (!config.AutoRead && !ch.ReadPending)
                        {
                            // ChannelConfig.setAutoRead(false) was called in the meantime.
                            // Completed Accept has to be processed though.
                            return;
                        }

                        while (allocHandle.ContinueReading())
                        {
                            connectedSocket = null;
                            connectedSocket = ch.Socket.Accept();
                            message         = new TcpSocketChannel(ch, connectedSocket, true);
                            ch.ReadPending  = false;
                            pipeline.FireChannelRead(message);

                            allocHandle.IncMessagesRead(1);
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        closed = true;
                    }
                    catch (Exception ex)
                    {
                        var asSocketException = ex as SocketException;
                        if (asSocketException == null || asSocketException.SocketErrorCode != SocketError.WouldBlock)
                        {
                            Logger.Warn("Failed to create a new channel from an accepted socket.", ex);
                            if (connectedSocket != null)
                            {
                                try
                                {
                                    connectedSocket.Dispose();
                                }
                                catch (Exception ex2)
                                {
                                    Logger.Warn("Failed to close a socket.", ex2);
                                }
                            }
                            exception = ex;
                        }
                    }

                    allocHandle.ReadComplete();
                    pipeline.FireChannelReadComplete();

                    if (exception != null)
                    {
                        // ServerChannel should not be closed even on SocketException because it can often continue
                        // accepting incoming connections. (e.g. too many open files)

                        pipeline.FireExceptionCaught(exception);
                    }

                    if (closed)
                    {
                        if (ch.Open)
                        {
                            this.CloseAsync();
                        }
                    }
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    if (!closed && (ch.ReadPending || config.AutoRead))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
示例#23
0
 /// <summary>
 /// Communication channel configuration
 /// </summary>
 public FluentApplicationBootstrapConfiguration AddChannelConfiguration(IChannelConfiguration channelConfiguration)
 {
     ChannelConfiguration = channelConfiguration;
     return(this);
 }
示例#24
0
 public void SetUpTest()
 {
     _channelConfig = Setup.TestChannelConfig();
     _localEndpoint = _channelConfig.Type1EndpointConfiguration.Endpoint as InMemoryCrudDataEndpoint<LocalTestResource, int>;
     _remoteEndpoint = _channelConfig.Type2EndpointConfiguration.Endpoint as InMemoryCrudDataEndpoint<RemoteTestResource, int>;
 }
示例#25
0
 internal bool ShouldBreakReadReady(IChannelConfiguration config)
 {
     return(IsInputShutdown && (_inputClosedSeenErrorOnRead || !IsAllowHalfClosure(config)));
 }
示例#26
0
            // Read callback from libuv thread
            void INativeUnsafe.FinishRead(ReadOperation operation)
            {
                var ch = _channel;
                IChannelConfiguration config   = ch.Configuration;
                IChannelPipeline      pipeline = ch.Pipeline;
                OperationException    error    = operation.Error;

                bool close = error is object || operation.EndOfStream;
                IRecvByteBufAllocatorHandle allocHandle = RecvBufAllocHandle;

                allocHandle.Reset(config);

                IByteBuffer buffer = operation.Buffer;

                Debug.Assert(buffer is object);

                allocHandle.LastBytesRead = operation.Status;
                if (allocHandle.LastBytesRead <= 0)
                {
                    // nothing was read -> release the buffer.
                    _     = buffer.Release();
                    close = allocHandle.LastBytesRead < 0;
                    if (close)
                    {
                        // There is nothing left to read as we received an EOF.
                        ch.ReadPending = false;
                    }
                }
                else
                {
                    _ = buffer.SetWriterIndex(buffer.WriterIndex + operation.Status);
                    allocHandle.IncMessagesRead(1);

                    ch.ReadPending = false;
                    _ = pipeline.FireChannelRead(buffer);
                }

                allocHandle.ReadComplete();
                _ = pipeline.FireChannelReadComplete();

                if (close)
                {
                    if (error is object)
                    {
                        _ = pipeline.FireExceptionCaught(ThrowHelper.GetChannelException(error));
                    }
                    if (ch.Open)
                    {
                        Close(VoidPromise());
                    }                                      // ## 苦竹 修改 this.CloseSafe(); ##
                }
                else
                {
                    // If read is called from channel read or read complete
                    // do not stop reading
                    if (!ch.ReadPending && !config.AutoRead)
                    {
                        ch.DoStopRead();
                    }
                }
            }
示例#27
0
 private static bool IsAllowHalfClosure(IChannelConfiguration config)
 {
     return(config is ISocketChannelConfiguration socketChannelConfiguration &&
            socketChannelConfiguration.AllowHalfClosure);
 }
示例#28
0
 public GrpcChannelFactory(IChannelConfiguration channelConfiguration)
 {
     _channelConfiguration = channelConfiguration;
 }
示例#29
0
            public override void FinishRead(SocketChannelAsyncOperation <TChannel, TUnsafe> operation)
            {
                var ch = _channel;

                if (0u >= (uint)(ch.ResetState(StateFlags.ReadScheduled) & StateFlags.Active))
                {
                    return; // read was signaled as a result of channel closure
                }

                IChannelConfiguration config = ch.Configuration;

                if (ch.ShouldBreakReadReady(config))
                {
                    ch.ClearReadPending();
                    return;
                }

                IChannelPipeline            pipeline    = ch.Pipeline;
                IByteBufferAllocator        allocator   = config.Allocator;
                IRecvByteBufAllocatorHandle allocHandle = RecvBufAllocHandle;

                allocHandle.Reset(config);

                IByteBuffer byteBuf = null;
                bool        close   = false;

                try
                {
                    operation.Validate();

                    do
                    {
                        byteBuf = allocHandle.Allocate(allocator);
                        allocHandle.LastBytesRead = ch.DoReadBytes(byteBuf);
                        if ((uint)(allocHandle.LastBytesRead - 1) > SharedConstants.TooBigOrNegative) // <= 0
                        {
                            // nothing was read -> release the buffer.
                            _       = byteBuf.Release();
                            byteBuf = null;
                            close   = (uint)allocHandle.LastBytesRead > SharedConstants.TooBigOrNegative; // < 0
                            if (close)
                            {
                                // There is nothing left to read as we received an EOF.
                                ch.ReadPending = false;
                            }
                            break;
                        }

                        allocHandle.IncMessagesRead(1);
                        ch.ReadPending = false;

                        _       = pipeline.FireChannelRead(byteBuf);
                        byteBuf = null;
                    }while (allocHandle.ContinueReading());

                    allocHandle.ReadComplete();
                    _ = pipeline.FireChannelReadComplete();

                    if (close)
                    {
                        CloseOnRead();
                    }
                }
                catch (Exception t)
                {
                    HandleReadException(pipeline, byteBuf, t, close, allocHandle);
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    // This could be for two reasons:
                    // /// The user called Channel.read() or ChannelHandlerContext.read() input channelRead(...) method
                    // /// The user called Channel.read() or ChannelHandlerContext.read() input channelReadComplete(...) method
                    //
                    // See https://github.com/netty/netty/issues/2254
                    if (!close && (ch.ReadPending || config.IsAutoRead))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
示例#30
0
 public override void HandlerAdded(IChannelHandlerContext ctx)
 {
     _config = ctx.Channel.Configuration;
 }
示例#31
0
 public void SetUpTest()
 {
     _channelConfig  = Setup.TestChannelConfig();
     _localEndpoint  = _channelConfig.Type1EndpointConfiguration.Endpoint as InMemoryCrudDataEndpoint <LocalTestResource, int>;
     _remoteEndpoint = _channelConfig.Type2EndpointConfiguration.Endpoint as InMemoryCrudDataEndpoint <RemoteTestResource, int>;
 }