Esempio n. 1
0
 public override bool SetAttribute(string name, object value)
 {
     _ownerMessage.AddEvent(SharedObjectEventType.CLIENT_UPDATE_ATTRIBUTE, name, null);
     if (value == null && base.RemoveAttribute(name))
     {
         // Setting a null value removes the attribute
         _modified = true;
         _syncEvents.Enqueue(new SharedObjectEvent(SharedObjectEventType.CLIENT_DELETE_DATA, name, null));
         _deleteStats.Increment();
         NotifyModified();
         return(true);
     }
     else if (value != null && base.SetAttribute(name, value))
     {
         // only sync if the attribute changed
         _modified = true;
         _syncEvents.Enqueue(new SharedObjectEvent(SharedObjectEventType.CLIENT_UPDATE_DATA, name, value));
         _changeStats.Increment();
         NotifyModified();
         return(true);
     }
     else
     {
         NotifyModified();
         return(false);
     }
 }
        public bool TrySampling()
        {
            if (!_sample_on)
            {
                return(true);
            }

            return(_atomicInteger.Increment() < _sample_N_Per_3_Secs);
        }
        public bool Sampled()
        {
            if (!_sample_on)
            {
                return(true);
            }

            return(_idx.Increment() < _samplePer3Secs);
        }
Esempio n. 4
0
        /// <summary>
        /// Call blocks until the result is received. Use Send for a nonblocking call.
        /// </summary>
        /// <param name="notify">Call</param>
        /// <returns>Result or null if failed</returns>
        protected Notify Call(Notify notify)
        {
            var callresult = new CallResultWait(notify, true);

            lock (WaitLock)
            {
                WaitInvokeList.Add(callresult);
            }
            notify.InvokeId = CurrentInvoke.Increment();

            SendPacket(notify);

            callresult.Wait.WaitOne(-1);
            return(callresult.Result);
        }
 protected override void WritingMessage(RtmpPacket packet)
 {
     base.WritingMessage(packet);
     if (packet.Message is VideoData)
     {
         int           streamId = packet.Header.StreamId;
         AtomicInteger integer  = new AtomicInteger();
         AtomicInteger integer2 = null;
         lock (((ICollection)this._pendingVideos).SyncRoot)
         {
             if (!this._pendingVideos.ContainsKey(streamId))
             {
                 this._pendingVideos.Add(streamId, integer);
                 integer2 = integer;
             }
             else
             {
                 integer2 = this._pendingVideos[streamId];
             }
         }
         if (integer2 == null)
         {
             integer2 = integer;
         }
         integer2.Increment();
     }
 }
        public void Increment_Test()
        {
            var atomicInteger = new AtomicInteger(5);
            var result        = atomicInteger.Increment();

            Assert.Equal(6, result);
        }
Esempio n. 7
0
        public async Task TestChannelInitializerReentrance()
        {
            AtomicInteger         registeredCalled  = new AtomicInteger(0);
            ChannelHandlerAdapter handler1          = new ChannelInboundHandlerAdapter0(registeredCalled);
            AtomicInteger         initChannelCalled = new AtomicInteger(0);

            _client.Handler(new ActionChannelInitializer <IChannel>(ch =>
            {
                initChannelCalled.Increment();
                ch.Pipeline.AddLast(handler1);
                ch.Pipeline.FireChannelRegistered();
            })).LocalAddress(LocalAddress.Any);

            var channel = await _client.BindAsync();

            try
            {
                // Execute some task on the EventLoop and wait until its done to be sure all handlers are added to the
                // pipeline.
                await channel.EventLoop.SubmitAsync(() =>
                {
                    // NOOP
                    return(0);
                });

                Assert.Equal(1, initChannelCalled.Value);
                Assert.Equal(2, registeredCalled.Value);
            }
            finally
            {
                await channel.CloseAsync();
            }
        }
Esempio n. 8
0
 public override void UserEventTriggered(IChannelHandlerContext ctx, object evt)
 {
     if (evt is ChannelInputShutdownEvent)
     {
         _halfClosureCount.Increment();
         _halfClosure.Signal();
     }
 }
Esempio n. 9
0
 public bool Invoke(SamplingContext samplingContext, Sampler next)
 {
     if (!_sample_on)
     {
         return(next(samplingContext));
     }
     return(_idx.Increment() <= _samplePer3Secs && next(samplingContext));
 }
Esempio n. 10
0
 public void SendMessage(string handler, IList arguments)
 {
     _ownerMessage.AddEvent(SharedObjectEventType.CLIENT_SEND_MESSAGE, handler, arguments);
     _syncEvents.Enqueue(new SharedObjectEvent(SharedObjectEventType.CLIENT_SEND_MESSAGE, handler, arguments));
     _sendStats.Increment();
     _modified = true;
     NotifyModified();
 }
Esempio n. 11
0
 public override void ChannelRead(IChannelHandlerContext ctx, object msg)
 {
     ReferenceCountUtil.Release(msg);
     if (_count.Increment() == 1)
     {
         // Call read the first time, to ensure it is not reset the second time.
         ctx.Read(); // Socket BeginRead 没有做重复调用检测
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Call blocks until the result is received. Use Send for a nonblocking call.
        /// </summary>
        /// <param name="notify">Call</param>
        /// <returns>Result or null if failed</returns>
        public Notify Call(Notify notify)
        {
            var callresult = new CallResultWait(notify, true);

            lock (WaitLock)
            {
                if (WaitInvokeList == null)
                {
                    return(null);
                }
                WaitInvokeList.Add(callresult);
            }
            notify.InvokeId = CurrentInvoke.Increment();

            InternalSend(notify, false);

            callresult.Wait.WaitOne(-1);
            return(callresult.Result);
        }
Esempio n. 13
0
            protected override void InitChannel(IChannel channel)
            {
                _invokeCount.Increment();
                IChannelHandlerContext ctx = channel.Pipeline.Context(this);

                Assert.NotNull(ctx);
                channel.Pipeline.AddAfter(ctx.Executor,
                                          ctx.Name, null, new ChannelInboundHandlerAdapter1(_latch));
                _completeCount.Increment();
            }
Esempio n. 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerSession"/> class.
        /// </summary>
        public ServerSession(IPacketCodeTable packetCodeTable)
        {
            NetworkSessionId = RollingNetworkSessionId.Increment();

            _isPushing = false;
            _packets   = new ConcurrentQueue <byte[]>();

            _packetCodeTable = packetCodeTable;

            PacketReceived += HandlePacketReceived;
        }
Esempio n. 15
0
        public int GetNextFixedRecordLength()
        {
            int i = _currentFixedRecordLength.Increment() - 1;

            if (i < _fixedRecordLength.Count)
            {
                return(_fixedRecordLength[i]);
            }
            _currentFixedRecordLength.Value = 0;
            return(_fixedRecordLength[0]);
        }
Esempio n. 16
0
        public Action <IByteBuffer> GetNextHandler()
        {
            int i = _currentPipe.Increment() - 1;

            if (i < _pipe.Count)
            {
                return(_pipe[i]);
            }
            _currentPipe.Value = 0;
            return(_pipe[0]);
        }
Esempio n. 17
0
 public override void UserEventTriggered(IChannelHandlerContext ctx, object evt)
 {
     if (evt == ChannelInputShutdownEvent.Instance)
     {
         _shutdownEventReceivedCounter.Increment();
     }
     else if (evt == ChannelInputShutdownReadComplete.Instance)
     {
         _shutdownReadCompleteEventReceivedCounter.Increment();
         ctx.Executor.Schedule(() => ctx.CloseAsync(), TimeSpan.FromMilliseconds(100));
     }
 }
Esempio n. 18
0
 public override void ChannelReadComplete(IChannelHandlerContext ctx)
 {
     _clientReadCompletes.Increment();
     if (_bytesRead == _totalServerBytesWritten)
     {
         _clientReadAllDataLatch.SafeSignal();
     }
     if (!_autoRead)
     {
         ctx.Read();
     }
 }
Esempio n. 19
0
        public override object GetAttribute(string name, object value)
        {
            if (name == null)
            {
                return(null);
            }

            object result = base.GetAttribute(name, value);

            if (result == null)
            {
                // No previous value
                _modified = true;
                _ownerMessage.AddEvent(SharedObjectEventType.CLIENT_UPDATE_DATA, name, value);
                _syncEvents.Enqueue(new SharedObjectEvent(SharedObjectEventType.CLIENT_UPDATE_DATA, name, value));
                NotifyModified();
                _changeStats.Increment();
                result = value;
            }
            return(result);
        }
Esempio n. 20
0
 public override void ChannelRead(IChannelHandlerContext ctx, object msg)
 {
     ReferenceCountUtil.Release(msg);
     if (_count.Increment() == 1)
     {
         ctx.Channel.Configuration.IsAutoRead = false;
     }
     if (_callRead)
     {
         // Test calling read in the EventLoop thread to ensure a read is eventually done.
         ctx.Read();
     }
 }
Esempio n. 21
0
        private void SendPing(object sender, ElapsedEventArgs e)
        {
            if (_sentPings.Increment() > MissedPingsAllowed)
            {
                Disconnect("No ping response.");
                return;
            }

            using (var ping = PacketFactory.CreatePacket("Ping"))
            {
                ServerSession.WritePacket(ping.ToByteArray());
            }
        }
Esempio n. 22
0
        public void ShutdownWithPendingTasks()
        {
            int            NUM_TASKS = 3;
            AtomicInteger  ranTasks  = new AtomicInteger();
            CountdownEvent latch     = new CountdownEvent(1);
            Action         task      = () =>
            {
                ranTasks.Increment();
                while (latch.CurrentCount > 0)
                {
                    try
                    {
                        Assert.True(latch.Wait(TimeSpan.FromMinutes(1)));
                    }
                    catch (Exception) { }
                }
            };

            for (int i = 0; i < NUM_TASKS; i++)
            {
                this.eventLoop.Execute(task);
            }

            // At this point, the first task should be running and stuck at latch.await().
            while (ranTasks.Value == 0)
            {
                Thread.Yield();
            }
            Assert.Equal(1, ranTasks.Value);

            // Shut down the event loop to test if the other tasks are run before termination.
            this.eventLoop.ShutdownGracefullyAsync(TimeSpan.Zero, TimeSpan.Zero);

            // Let the other tasks run.
            latch.Signal();

            // Wait until the event loop is terminated.
            while (!this.eventLoop.IsTerminated)
            {
                this.eventLoop.WaitTermination(TimeSpan.FromDays(1));
            }

            // Make sure loop.shutdown() above triggered wakeup().
            Assert.Equal(NUM_TASKS, ranTasks.Value);
        }
Esempio n. 23
0
        /// <inheritdoc />
        public bool TryRegisterSession(int accountId, out int sessionId)
        {
            if (_activeAccounts.ContainsKey(accountId))
            {
                sessionId = 0;
                return(false);
            }
            else
            {
                sessionId = _currentSessionId.Increment();

                var account = new ActiveAccount(accountId, sessionId);
                account.KeepAlive(_clock.Now);

                _activeAccounts.Add(accountId, account);
                return(true);
            }
        }
Esempio n. 24
0
            protected override bool ConfirmShutdown()
            {
                var result = base.ConfirmShutdown();

                // After shutdown is confirmed, scheduled one more task and record it
                if (result)
                {
                    _attempts.Increment();
                    try
                    {
                        _submittedTasks.Add(SubmitAsync(() => 0));
                    }
                    catch (RejectedExecutionException)
                    {
                        // ignore, tasks are either accepted or rejected
                        _rejects.Increment();
                    }
                }
                return(result);
            }
Esempio n. 25
0
        public void Start()
        {
            if (_shutdown.CompareAndSet(true, false))
            {
                _eventId    = new AtomicInteger(0);
                _eventQueue = new BlockingCollection <ZooKeeperEvent>();

                Task.Factory.StartNew(() =>
                {
                    var events = _eventQueue.GetConsumingEnumerable();
                    foreach (var @event in events)
                    {
                        var eventId        = _eventId.Increment();
                        @event.Description = string.Format("Delivering event #{0} {1}", eventId, @event.Description);
                        @event.Run();
                    }

                    _shutdownCompleted.Set();
                });
            }
        }
 public void Increment()
 {
     _num.Increment();
 }
        private void HandleFlexClientStreamingOpenRequest(HttpRequest request, HttpResponse response, IClient flexClient)
        {
            Session session = FluorineContext.Current.Session as Session;

            if (session == null)
            {
                string msg = string.Format("Cannot grant streaming connection when ASP.NET session state is disabled", this.Id);
                if (log.IsWarnEnabled)
                {
                    log.Warn(msg);
                }
                try {
                    HandleBadRequest(msg, HttpContext.Current.Response);
                } catch (HttpException) { }
                return;
            }
            if (!_canStream || !session.CanStream)
            {
                string msg = string.Format("Cannot grant streaming connection, limit has been reached", this.Id);
                try {
                    HandleBadRequest(msg, HttpContext.Current.Response);
                } catch (HttpException) { }
                return;
            }

            bool canStream = false;

            lock (this.SyncRoot) {
                _streamingClientsCount.Increment();
                if (_streamingClientsCount.Value == this.MaxStreamingClients)
                {
                    canStream  = true;                    // This thread got the last spot.
                    _canStream = false;
                }
                else if (_streamingClientsCount.Value > this.MaxStreamingClients)
                {
                    canStream = false;                     // This thread lost the last spot.
                    _streamingClientsCount.Decrement();    // We're not going to grant the streaming right to the client.
                }
                else
                {
                    // Allow this thread to stream.
                    canStream = true;
                }
            }
            if (!canStream)
            {
                string msg = string.Format("Cannot service streaming request, max-streaming-clients reached in endpoint {0}", this.Id);
                try {
                    HandleBadRequest(msg, HttpContext.Current.Response);
                } catch (HttpException) { }
                return;
            }

            UserAgent userAgent = this.ChannelDefinition.Properties.UserAgentSettings[request.Browser.Browser];

            if (userAgent != null)
            {
                lock (session.SyncRoot) {
                    session.MaxConnectionsPerSession = userAgent.MaxStreamingConnectionsPerSession;
                }
            }

            lock (session.SyncRoot) {
                session.StreamingConnectionsCount++;
                if (session.StreamingConnectionsCount == session.MaxConnectionsPerSession)
                {
                    canStream         = true;             // This thread got the last spot in the session.
                    session.CanStream = false;
                }
                else if (session.StreamingConnectionsCount > session.MaxConnectionsPerSession)
                {
                    canStream = false;
                    session.StreamingConnectionsCount--;
                    _streamingClientsCount.Decrement();
                }
                else
                {
                    canStream = true;
                }
            }
            if (!canStream)
            {
                string msg = string.Format("Cannot grant streaming connection, limit has been reached", this.Id);
                try {
                    HandleBadRequest(msg, HttpContext.Current.Response);
                } catch (HttpException) { }
                return;
            }

            EndpointPushNotifier notifier = null;

            try {
                response.ContentType = ContentType.AMF;
                response.AppendHeader("Cache-Control", "no-cache");
                response.AppendHeader("Pragma", "no-cache");
                response.AppendHeader("Connection", "close");
                //response.AppendHeader("Transfer-Encoding", "chunked");
                response.Flush();

                // Setup for specific user agents.
                byte[] kickStartBytesToStream = null;
                int    kickStartBytes         = userAgent != null ? userAgent.KickstartBytes : 0;
                if (kickStartBytes > 0)
                {
                    // The minimum number of actual bytes that need to be sent to kickstart, taking into account transfer-encoding overhead.
                    try {
                        int chunkLengthHeaderSize = System.Text.Encoding.ASCII.GetBytes(System.Convert.ToString(kickStartBytes, 0x10)).Length; //System.Text.ASCIIEncoding.ASCII.GetBytes(kickStartBytes.ToString("X")).Length;
                        int chunkOverhead         = chunkLengthHeaderSize + 4;                                                                 // 4 for the 2 wrapping CRLF tokens.
                        int minimumKickstartBytes = kickStartBytes - chunkOverhead;
                        kickStartBytesToStream = new byte[(minimumKickstartBytes > 0) ? minimumKickstartBytes : kickStartBytes];
                    } catch {
                        kickStartBytesToStream = new byte[kickStartBytes];
                    }
                }
                if (kickStartBytesToStream != null)
                {
                    StreamChunk(kickStartBytesToStream, response);
                }
                try {
                    notifier = new EndpointPushNotifier(this, flexClient);
                    lock (_currentStreamingRequests.SyncRoot) {
                        _currentStreamingRequests.Add(notifier.Id, notifier);
                    }
                    // Push down an acknowledgement for the 'connect' request containing the unique id for this specific stream.
                    AcknowledgeMessage connectAck = new AcknowledgeMessage();
                    connectAck.body          = notifier.Id;
                    connectAck.correlationId = OpenCommand;
                    StreamMessage(connectAck, response);
                } catch (MessageException) {
                }

                if (log.IsDebugEnabled)
                {
                    string msg = string.Format("Start streaming for endpoint with id {0} and client with id {1}", this.Id, flexClient.Id);
                    log.Debug(msg);
                }

                int serverToClientHeartbeatMillis = this.ChannelDefinition.Properties.ServerToClientHeartbeatMillis >= 0 ? this.ChannelDefinition.Properties.ServerToClientHeartbeatMillis : 0;
                serverToClientHeartbeatMillis = 100;
                while (!notifier.IsClosed)
                {
                    IList messages = notifier.GetPendingMessages();
                    StreamMessages(messages, response);
                    lock (notifier.SyncRoot) {
                        Monitor.Wait(notifier.SyncRoot, serverToClientHeartbeatMillis);

                        messages = notifier.GetPendingMessages();
                        // If there are no messages to send to the client, send a 0
                        // byte as a heartbeat to make sure the client is still valid.
                        if ((messages == null || messages.Count == 0) && serverToClientHeartbeatMillis > 0)
                        {
                            try {
                                StreamChunk(Heartbeat, response);
                                response.Flush();
                            } catch (HttpException) {
                                break;
                            } catch (IOException) {
                                break;
                            }
                        }
                        else
                        {
                            StreamMessages(messages, response);
                        }
                    }
                }
                // Terminate the response.
                StreamChunk(null, response);
                if (log.IsDebugEnabled)
                {
                    string msg = string.Format("Releasing streaming connection for endpoint with id {0} and and client with id {1}", this.Id, flexClient.Id);
                    log.Debug(msg);
                }
            } catch (IOException ex)            //HttpException?
            {
                if (log.IsWarnEnabled)
                {
                    log.Warn("Streaming thread for endpoint with id " + this.Id + " is closing connection due to an IO error.", ex);
                }
            } catch (Exception ex) {
                if (log.IsErrorEnabled)
                {
                    log.Error("Streaming thread for endpoint with id " + this.Id + " is closing connection due to an error.", ex);
                }
            } finally {
                if (notifier != null && _currentStreamingRequests != null)
                {
                    if (_currentStreamingRequests != null)
                    {
                        lock (_currentStreamingRequests.SyncRoot) {
                            _currentStreamingRequests.Remove(notifier.Id);
                        }
                    }
                    notifier.Close();
                }
                _streamingClientsCount.Decrement();
                lock (session.SyncRoot) {
                    session.StreamingConnectionsCount--;
                    session.CanStream = session.StreamingConnectionsCount < session.MaxConnectionsPerSession;
                }
            }
        }
            public Cap ConnectCap(string uri)
            {
                if (_isDisposed)
                {
                    return(null);
                }
                if (this.State == ManagerState.Stop)
                {
                    return(null);
                }

                var garbages = new List <IDisposable>();

                try
                {
                    var config = this.Config;

                    var result = UriUtils.Parse(uri);
                    if (result == null)
                    {
                        throw new Exception();
                    }

                    string scheme  = result.GetValue <string>("Scheme");
                    string address = result.GetValue <string>("Address");
                    int    port    = result.GetValueOrDefault <int>("Port", () => 4050);

                    var connectionFilter = config.ConnectionFilters.FirstOrDefault(n => n.Scheme == scheme);
                    if (connectionFilter == null || connectionFilter.Type == ConnectionType.None)
                    {
                        return(null);
                    }

                    if (connectionFilter.Type == ConnectionType.Tcp)
                    {
                        // Check
                        {
                            IPAddress ipAddress;

                            if (!IPAddress.TryParse(address, out ipAddress))
                            {
                                return(null);
                            }

#if !DEBUG
                            if (!CheckGlobalIpAddress(ipAddress))
                            {
                                return(null);
                            }
#endif

                            if (!_catharsisManager.Check(ipAddress))
                            {
                                _blockCount.Increment();

                                return(null);
                            }
                        }

                        var socket = Connect(new IPEndPoint(IPAddress.Parse(address), port));
                        garbages.Add(socket);

                        var cap = new SocketCap(socket);
                        garbages.Add(cap);

                        return(cap);
                    }
                    else if (connectionFilter.Type == ConnectionType.Socks5Proxy ||
                             connectionFilter.Type == ConnectionType.HttpProxy)
                    {
                        var result2 = UriUtils.Parse(connectionFilter.ProxyUri);
                        if (result2 == null)
                        {
                            throw new Exception();
                        }

                        string proxyScheme = result2.GetValue <string>("Scheme");
                        if (proxyScheme != "tcp")
                        {
                            throw new Exception();
                        }

                        if (connectionFilter.Type == ConnectionType.HttpProxy)
                        {
                            string proxyAddress = result2.GetValue <string>("Address");
                            int    proxyPort    = result2.GetValueOrDefault <int>("Port", () => 1080);

                            var socket = Connect(new IPEndPoint(GetIpAddress(proxyAddress), proxyPort));
                            garbages.Add(socket);

                            var proxy = new HttpProxyClient(address, port);
                            proxy.Create(socket, new TimeSpan(0, 0, 30));

                            var cap = new SocketCap(socket);
                            garbages.Add(cap);

                            return(cap);
                        }
                        else if (connectionFilter.Type == ConnectionType.Socks5Proxy)
                        {
                            string proxyAddress = result2.GetValue <string>("Address");
                            int    proxyPort    = result2.GetValueOrDefault <int>("Port", () => 80);

                            var socket = Connect(new IPEndPoint(GetIpAddress(proxyAddress), proxyPort));
                            garbages.Add(socket);

                            var proxy = new Socks5ProxyClient(address, port);
                            proxy.Create(socket, new TimeSpan(0, 0, 30));

                            var cap = new SocketCap(socket);
                            garbages.Add(cap);

                            return(cap);
                        }
                    }
                }
                catch (Exception)
                {
                    foreach (var item in garbages)
                    {
                        item.Dispose();
                    }
                }

                return(null);
            }
Esempio n. 29
0
 public void BeginUpdate(IEventListener listener)
 {
     _source = listener;
     // Increase number of pending updates
     _updateCounter.Increment();
 }
Esempio n. 30
0
 private void UpdateVersion()
 {
     _version.Increment();
 }