Ejemplo n.º 1
0
 public void Idle()
 {
     if (!CheckForClockTick())
     {
         CheckInterruptedStatus();
         idleStrategy.Idle();
     }
 }
Ejemplo n.º 2
0
 private void AwaitActiveLog()
 {
     while (null == newActiveLogEvent)
     {
         CheckInterruptedStatus();
         idleStrategy.Idle(serviceControlAdapter.Poll());
     }
 }
Ejemplo n.º 3
0
        public void Start(DataHandler dataHandler)
        {
            if (Interlocked.CompareExchange(ref _isRunning, 1, 0) == 0)
            {
                _log.InfoFormat("Starting transport for channel [{0}] and stream [{1}]", _channel, _stream);
                var fragmentAssembler = new FragmentAssembler(
                    (buffer, offset, length, _) =>
                {
                    var data = new byte[length];
                    buffer.GetBytes(offset, data);
                    dataHandler(data, length);
                }
                    );

                //will block until stopped
                while (_isRunning == 1)
                {
                    var fragmentsRead = _subscription.Poll(fragmentAssembler.OnFragment, _fragmentLimit);
                    _idleStrategy.Idle(fragmentsRead);
                }

                _log.InfoFormat("Stopped transport for channel [{0}] and stream [{1}]", _channel, _stream);
            }
            else
            {
                var message = string.Format(
                    "Cannot start transport for channel [{0}] and stream [{1}]; transport is already active",
                    _channel,
                    _stream
                    );
                _log.Warn(message);
                throw new InvalidOperationException(message);
            }
        }
Ejemplo n.º 4
0
 protected void CheckResultAndIdle(long result)
 {
     CheckResult(result);
     CheckInterruptedStatus();
     InvokeAeronClient();
     idleStrategy.Idle();
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Return a reusable, parameterized event loop that calls and idler when no messages are received
 /// </summary>
 /// <param name="fragmentHandler"> to be called back for each message. </param>
 /// <param name="limit">           passed to <seealso cref="Subscription#poll(FragmentHandler, int)"/> </param>
 /// <param name="running">         indication for loop </param>
 /// <param name="idleStrategy">    to use for loop </param>
 /// <returns> loop function </returns>
 public static Action <Subscription> SubscriberLoop(IFragmentHandler fragmentHandler, int limit, AtomicBoolean running, IIdleStrategy idleStrategy)
 {
     return(subscription =>
     {
         while (running)
         {
             idleStrategy.Idle(subscription.Poll(fragmentHandler, limit));
         }
     });
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Return a reusable, parameterized event loop that calls and idler when no messages are received
 /// </summary>
 /// <param name="fragmentHandler"> to be called back for each message. </param>
 /// <param name="limit">           passed to <seealso cref="Subscription#poll(FragmentHandler, int)"/> </param>
 /// <param name="running">         indication for loop </param>
 /// <param name="idleStrategy">    to use for loop </param>
 /// <returns> loop function </returns>
 public static Action<Subscription> SubscriberLoop(FragmentHandler fragmentHandler, int limit, AtomicBoolean running, IIdleStrategy idleStrategy)
 {
     return subscription =>
     {
         while (running.Get())
         {
             idleStrategy.Idle(subscription.Poll(fragmentHandler, limit));
         }
     };
 }
Ejemplo n.º 7
0
        public static void PingHandler(Publication pongPublication, UnsafeBuffer buffer, int offset, int length)
        {
            if (pongPublication.Offer(buffer, offset, length) > 0L)
            {
                return;
            }

            PingHandlerIdleStrategy.Reset();

            while (pongPublication.Offer(buffer, offset, length) < 0L)
            {
                PingHandlerIdleStrategy.Idle();
            }
        }
Ejemplo n.º 8
0
        private bool Offer(int length)
        {
            retryIdleStrategy.Reset();

            int attempts = retryAttempts;

            while (true)
            {
                long result;
                if ((result = publication.Offer(buffer, 0, MessageHeaderEncoder.ENCODED_LENGTH + length)) > 0)
                {
                    return(true);
                }

                if (result == Publication.CLOSED)
                {
                    throw new System.InvalidOperationException("connection to the archive has been closed");
                }

                if (result == Publication.NOT_CONNECTED)
                {
                    throw new System.InvalidOperationException("connection to the archive is no longer available");
                }

                if (result == Publication.MAX_POSITION_EXCEEDED)
                {
                    throw new System.InvalidOperationException("publication failed due to max position being reached");
                }

                if (--attempts <= 0)
                {
                    return(false);
                }

                retryIdleStrategy.Idle();
            }
        }
Ejemplo n.º 9
0
        private void AwaitResponse(long correlationId)
        {
            _driverException = null;
            var nowNs      = _nanoClock.NanoTime();
            var deadlineNs = nowNs + _driverTimeoutNs;

            CheckTimeouts(nowNs);

            _awaitingIdleStrategy.Reset();
            do
            {
                if (null == _driverAgentInvoker)
                {
                    _awaitingIdleStrategy.Idle();
                }
                else
                {
                    _driverAgentInvoker.Invoke();
                }

                Service(correlationId);

                if (_driverEventsAdapter.ReceivedCorrelationId == correlationId)
                {
                    _stashedChannel = null;

                    RegistrationException ex = _driverException;
                    if (null != _driverException)
                    {
                        _driverException = null;
                        throw ex;
                    }

                    return;
                }

                try
                {
                    Thread.Sleep(1);
                }
                catch (ThreadInterruptedException)
                {
                    _isTerminating = true;
                    throw new AgentTerminationException("thread interrupted");
                }
            } while (deadlineNs - _nanoClock.NanoTime() > 0);

            throw new DriverTimeoutException("no response from MediaDriver within (ms):" + _driverTimeoutMs);
        }
Ejemplo n.º 10
0
        private static void RoundTripMessages(UnsafeBuffer buffer,
                                              IFragmentHandler fragmentHandler, Publication publication, Subscription subscription, int count)
        {
            for (var i = 0; i < count; i++)
            {
                do
                {
                    buffer.PutLong(0, Stopwatch.GetTimestamp());
                } while (publication.Offer(buffer, 0, MessageLength) < 0L);

                PollingIdleStrategy.Reset();
                while (subscription.Poll(fragmentHandler, FragmentCountLimit) <= 0)
                {
                    PollingIdleStrategy.Idle();
                }
            }
        }
Ejemplo n.º 11
0
        private static void Publish <T>(T message,
                                        Publication publication,
                                        IIdleStrategy offerIdleStrategy,
                                        IMutableDirectBuffer buffer)
        {
            var serTm  = Util.Serialize(message);
            var length = serTm.Length;

            buffer.PutBytes(0, serTm);

            offerIdleStrategy.Reset();
            while (!Offer(publication, buffer, length))
            {
                // The offer failed, which is usually due to the publication
                // being temporarily blocked.  Retry the offer after a short
                // spin/yield/sleep, depending on the chosen IdleStrategy.
                //backPressureCount++;
                offerIdleStrategy.Idle();
            }

            //reporter.OnMessage(1, length);
        }
Ejemplo n.º 12
0
        private bool DoDutyCycle(IIdleStrategy idleStrategy, IAgent agent)
        {
            try
            {
                idleStrategy.Idle(agent.DoWork());
            }
            catch (ThreadInterruptedException)
            {
                return(true);
            }
            catch (AgentTerminationException ex)
            {
                HandleError(ex);
                return(true);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

            return(false);
        }
Ejemplo n.º 13
0
        public static void Main()
        {
            if (MessageLength < BitUtil.SIZE_OF_LONG)
            {
                throw new ArgumentException($"Message length must be at least {BitUtil.SIZE_OF_LONG:D} bytes");
            }

            ComputerSpecifications.Dump();

            var context  = new Aeron.Context();
            var reporter = new RateReporter(1000, PrintRate);

            _reporterThread = new Thread(_ => reporter.Run());
            _reporterThread.Start();

            // Connect to media driver and add publication to send messages on the configured channel and stream ID.
            // The Aeron and Publication classes implement AutoCloseable, and will automatically
            // clean up resources when this try block is finished.
            using (var aeron = Aeron.Connect(context))
                using (var publication = aeron.AddPublication(Channel, StreamID))
                    using (var byteBuffer = BufferUtil.AllocateDirectAligned(MessageLength, BitUtil.CACHE_LINE_LENGTH))
                        using (var buffer = new UnsafeBuffer(byteBuffer))
                        {
                            do
                            {
                                _printingActive = true;

                                Console.WriteLine($"Streaming {NumberOfMessages} messages of {(RandomMessageLength ? " random" : "")} size {MessageLength} bytes to {Channel} on stream Id {StreamID}");

                                long backPressureCount = 0;

                                for (long i = 0; i < NumberOfMessages; i++)
                                {
                                    var length = LengthGenerator.AsInt;

                                    buffer.PutLong(0, i);
                                    OfferIdleStrategy.Reset();
                                    while (publication.Offer(buffer, 0, length) < 0L)
                                    {
                                        // The offer failed, which is usually due to the publication
                                        // being temporarily blocked.  Retry the offer after a short
                                        // spin/yield/sleep, depending on the chosen IdleStrategy.
                                        backPressureCount++;
                                        OfferIdleStrategy.Idle();
                                    }

                                    reporter.OnMessage(1, length);
                                }

                                Console.WriteLine("Done streaming. Back pressure ratio " + (double)backPressureCount / NumberOfMessages);

                                if (0 < LingerTimeoutMs)
                                {
                                    Console.WriteLine("Lingering for " + LingerTimeoutMs + " milliseconds...");
                                    Thread.Sleep((int)LingerTimeoutMs);
                                }

                                _printingActive = false;

                                Console.WriteLine("Execute again?");
                            } while (Console.ReadLine() == "y");
                        }

            reporter.Halt();
            _reporterThread.Join();
        }