Esempio n. 1
0
    private void ListenerWork()
    {
        while (true)
        {
            _threadRunning     = true;
            _listenerCancelled = false;
            AsyncIO.ForceDotNet.Force();
            using (var server = new PairSocket())
            {
                server.Bind("tcp://*:" + port);

                while (!_listenerCancelled)
                {
                    Connected = _contactWatch.ElapsedMilliseconds < ContactThreshold;
                    byte[] frameBytes;
                    if (!server.TryReceiveFrameBytes(out frameBytes))
                    {
                        continue;
                    }
                    _contactWatch.Restart();
                    if (OnBytes != null && frameBytes != null)
                    {
                        OnBytes.Invoke(frameBytes);
                    }
                }

                server.Close();
            }
            NetMQConfig.Cleanup();
            _threadRunning = false;
        }
    }
Esempio n. 2
0
        private void OnMessage(Message msg, PairSocket socket)
        {
            Console.WriteLine("> Recebido via OnMessage");

            var op = msg.ReadNext <uint>();

            if (op == ADD)
            {
                storedvalues.Add(msg.ReadNext <string>());
            }
            else if (op == GET)
            {
                msg.Append(PRINT);
                foreach (var item in storedvalues)
                {
                    msg.Append(item);
                }

                socket.Send(msg);
            }
            else
            {
                Console.WriteLine(msg.ToString()); //Show all package frames as String
            }
        }
Esempio n. 3
0
        private void Run(PairSocket shim)
        {
            using (m_publisherSocket = new XPublisherSocket(m_address))
            {
                m_publisherSocket.SetWelcomeMessage(WelcomeMessage);

                m_publisherSocket.ReceiveReady += DropPublisherSubscriptions;

                m_heartbeatTimer          = new NetMQTimer(HeartbeatInterval);
                m_heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;

                shim.ReceiveReady += OnShimMessage;

                // signal the actor that the shim is ready to work
                shim.SignalOK();

                m_poller = new NetMQPoller {
                    m_publisherSocket, shim
                };
                m_poller.Add(m_heartbeatTimer);

                // Polling until poller is cancelled
                m_poller.Run();
            }
        }
Esempio n. 4
0
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer          = new NetMQTimer(interval: TimeSpan.Zero);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable   = false;

                using (m_poller = new NetMQPoller {
                    m_pipe, m_pingTimer
                })
                {
                    m_poller.Run();
                }

                // the beacon might never been configured
#if NET35
                m_udpSocket?.Close();
#else
                m_udpSocket?.Dispose();
#endif
            }
Esempio n. 5
0
        private void Run(PairSocket shim)
        {
            _shim = shim;
            using (_publisherSocket = new XPublisherSocket())
            {
                _publisherSocket.SetWelcomeMessage(WelcomeMessage);
                _publisherSocket.Bind(_address);

                _publisherSocket.ReceiveReady += DropPublisherSubscriptions;

                _heartbeatTimer          = new NetMQTimer(_heartbeatInterval);
                _heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;

                if (_receiveTimeout > 0)
                {
                    _receiveTimeoutTimer          = new NetMQTimer(1000);
                    _receiveTimeoutTimer.Enable   = false;
                    _receiveTimeoutTimer.Elapsed += OnReceiveTimeout;;
                }

                shim.ReceiveReady += OnShimMessage;

                // signal the actor that the shim is ready to work
                shim.SignalOK();

                _poller = new NetMQPoller {
                    _publisherSocket, shim, _heartbeatTimer, _receiveTimeoutTimer
                };
                // Polling until poller is cancelled
                _poller.Run();
            }
        }
Esempio n. 6
0
        public void RespondToPing()
        {
            // Setup
            var serverSocket = new PairSocket();

            serverSocket.Bind("inproc://stream-test");

            var pingMessage = new PingRequest().Wrap(MessageType.PingRequest);

            var stream = new Stream("inproc://stream-test");

            stream.Connect();

            // Run test case
            var task1 = Task.Run(() => serverSocket.SendFrame(pingMessage.ToByteString().ToByteArray()));
            var task2 = Task.Run(() =>
            {
                var message = new Message();
                message.MergeFrom(serverSocket.ReceiveFrameBytes());

                return(message);
            });

            Task.WhenAll(new[] { task1, task2 });

            var actualMessage = task2.Result;

            // Verify
            Assert.Equal(MessageType.PingResponse, actualMessage.MessageType);
            Assert.Equal(pingMessage.CorrelationId, actualMessage.CorrelationId);

            serverSocket.Unbind("inproc://stream-test");
            stream.Disconnect();
        }
Esempio n. 7
0
        /// <summary>
        /// Create new NetMQQueue.
        /// </summary>
        /// <param name="context">NetMQContext must be provided to the queue</param>
        /// <param name="capacity">The capacity of the queue, use zero for unlimited</param>
        public NetMQQueue(NetMQContext context, int capacity = 0)
        {
            m_context = context;
            m_queue   = new ConcurrentQueue <T>();
            m_writer  = m_context.CreatePairSocket();
            m_reader  = m_context.CreatePairSocket();

            if (capacity != 0)
            {
                m_writer.Options.SendHighWatermark = m_reader.Options.ReceiveHighWatermark = capacity / 2;
            }
            else
            {
                m_writer.Options.SendHighWatermark = m_reader.Options.ReceiveHighWatermark = 0;
            }

            m_eventDelegator = new EventDelegator <NetMQQueueEventArgs <T> >(() =>
            {
                m_reader.ReceiveReady += OnReceiveReady;
            }, () =>
            {
                m_reader.ReceiveReady -= OnReceiveReady;
            });

            string address = string.Format("inproc://NetMQQueue#{0}", Interlocked.Increment(ref s_sequence));

            m_reader.Bind(address);
            m_writer.Connect(address);

            m_dequeueMsg = new Msg();
            m_dequeueMsg.InitEmpty();
        }
Esempio n. 8
0
        private void RunActor(PairSocket shim)
        {
            _shim = shim;

            using (_subscriber = new SubscriberSocket())
                using (_publisher = new PublisherSocket())
                {
                    using (_beacon = new NetMQBeacon())
                    {
                        _shim.ReceiveReady += OnShimReady;

                        _subscriber.Subscribe(string.Empty);
                        _port = _subscriber.BindRandomPort("tcp://*");
                        _logger?.LogInformation($"{_id}: Peer bus is bound to {{BusPort}}", _port);
                        _subscriber.ReceiveReady += OnSubscriberReady;

                        _logger?.LogInformation($"{_id}: Peer is broadcasting UDP on port {{BeaconPort}}", _beaconPort);
                        _beacon.Configure(_beaconPort);
                        _beacon.Publish(_port.ToString(), _beaconInterval);
                        _beacon.Subscribe(string.Empty);
                        _beacon.ReceiveReady += OnBeaconReady;

                        var cleanupTimer = new NetMQTimer(_cleanupInterval);
                        cleanupTimer.Elapsed += Cleanup;

                        _poll = new NetMQPoller {
                            _shim, _subscriber, _beacon, cleanupTimer
                        };
                        _shim.SignalOK();
                        _poll.Run();
                    }
                }
        }
Esempio n. 9
0
        private void Run(PairSocket shim)
        {
            m_shim             = shim;
            shim.ReceiveReady += OnShimMessage;

            m_timeoutTimer          = new NetMQTimer(TimeOut);
            m_timeoutTimer.Elapsed += OnTimeoutTimer;

            m_reconnectTimer          = new NetMQTimer(ReconnectTimer);
            m_reconnectTimer.Elapsed += OnReconnectTimer;

            m_poller = new Poller(shim);
            m_poller.AddTimer(m_timeoutTimer);
            m_poller.AddTimer(m_reconnectTimer);

            shim.SignalOK();

            Connect();

            m_poller.PollTillCancelled();

            if (m_subscriber != null)
            {
                m_subscriber.Dispose();
            }
        }
Esempio n. 10
0
        public void Run(PairSocket shim)
        {
            shim.SignalOK();

            while (true)
            {
                try
                {
                    NetMQMessage msg = shim.ReceiveMultipartMessage();

                    string command = msg[0].ConvertToString();

                    if (command == NetMQActor.EndShimMessage)
                    {
                        break;
                    }

                    //Simulate a failure that should be sent back to Actor
                    throw new InvalidOperationException("Actors Shim threw an Exception");
                }
                //You WILL need to decide what Exceptions should be caught here, this is for
                //demonstration purposes only, any unhandled fault will bubble up to caller's code
                catch (InvalidOperationException e)
                {
                    shim.Send(string.Format("Error: Exception occurred {0}", e.Message));
                }
            }
        }
            public void RunPipeline(PairSocket shim)
            {
                publisherSocket = context.CreatePublisherSocket();
                publisherSocket.Bind("tcp://*:" + StreamingProtocol.Port);

                snapshotSocket = context.CreateResponseSocket();
                snapshotSocket.Bind("tcp://*:" + SnapshotProtocol.Port);
                snapshotSocket.ReceiveReady += OnSnapshotReady;

                shim.ReceiveReady += OnShimReady;

                heartbeatTimer          = new NetMQTimer(StreamingProtocol.HeartbeatInterval);
                heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;

                shim.SignalOK();

                poller = new Poller();
                poller.AddSocket(shim);
                poller.AddSocket(snapshotSocket);
                poller.AddTimer(heartbeatTimer);
                poller.Start();

                publisherSocket.Dispose();
                snapshotSocket.Dispose();
            }
Esempio n. 12
0
        public override bool HandleMessage(PairSocket me, PairSocket remote, Envelope envelop)
        {
            var msg = envelop.GetMessage();

            if (me.IdentityConnectionSocketsMap.ContainsKey(remote))
            {
                //Evita de várias conexões fake no servidor
                remote.Close();
            }

            byte[] identifier;
            if (msg.Length >= 16)
            {
                identifier          = msg.ReadNext(16);
                remote.ConnectionId = new Guid(identifier);
            }
            else
            {
                remote.ConnectionId = Guid.NewGuid();
                identifier          = remote.ConnectionId.ToByteArray();
            }

            me.IdentitySocketsMap[identifier] = remote;
            SendResultCode(remote, identifier);

            return(true);
        }
        public async Task CanGetState()
        {
            var serverAddress = "inproc://get-state-test";

            var serverSocket = new PairSocket();

            serverSocket.Bind(serverAddress);

            var processor = new TransactionProcessor(serverAddress);

            processor.Start();

            var context   = new TransactionContext(processor, "context");
            var addresses = new[] { "address1", "address2" };

            var task = Task.Run(() =>
            {
                var message = new Message();
                message.MergeFrom(serverSocket.ReceiveFrameBytes());

                Assert.Equal(MessageType.TpStateGetRequest, message.MessageType);

                var response = new TpStateGetResponse();
                response.Entries.AddRange(addresses.Select(x => new TpStateEntry {
                    Address = x, Data = ByteString.Empty
                }));

                serverSocket.SendFrame(response.Wrap(message, MessageType.TpStateGetResponse).ToByteArray());
            });

            var stateResponse = await context.GetStateAsync(addresses);

            Assert.Equal(addresses.Length, stateResponse.Count());
        }
Esempio n. 14
0
        /// <summary>
        /// Create a Zyre API that communicates with a node on the ZRE bus.
        /// </summary>
        /// <param name="name">The name of the node</param>
        /// <param name="useEvents">Set this to true to disable Receive() and instead subscribe to events for getting messages from peers. Default is true.</param>
        /// <param name="loggerDelegate">An action to take for logging when _verbose is true. Default is null.</param>
        public Zyre(string name, bool useEvents = true, Action <string> loggerDelegate = null)
        {
            _useEvents = useEvents;
            // Create front-to-back pipe pair for data traffic
            // outbox is passed to ZyreNode for sending Zyre message traffic back to _inbox
            PairSocket outbox;

            PairSocket.CreateSocketPair(out outbox, out _inbox);

            // Start node engine and wait for it to be ready
            // All node control is done through _actor

            _actor = ZyreNode.Create(outbox, loggerDelegate);

            if (useEvents)
            {
                _inboxPoller         = new NetMQPoller();
                _inbox.ReceiveReady += InboxReceiveReady;
                _inboxPoller.RunAsync();
            }

            // Send name, if any, to node ending
            if (!string.IsNullOrEmpty(name))
            {
                _actor.SendMoreFrame("SET NAME").SendFrame(name);
            }
        }
Esempio n. 15
0
 private void ConnectionWork()
 {
     AsyncIO.ForceDotNet.Force();
     using (var pairSocket = new PairSocket()) {
         pairSocket.Options.ReceiveHighWatermark = 1000;
         if (_createConnection)
         {
             pairSocket.Bind("tcp://*:12345");
         }
         else
         {
             pairSocket.Connect("tcp://localhost:12345");
         }
         //Do one more loop in-case we send out a closing msg and then cancel the connection
         bool flushedBuffer = true;
         while (!_connectionCancelled || !flushedBuffer)
         {
             string frameString;
             while (pairSocket.TryReceiveFrameString(out frameString))
             {
                 _incomingMessageQueue.Enqueue(frameString);
             }
             while (_outgoingMessageQueue.TryDequeue(out frameString))
             {
                 pairSocket.SendFrame(frameString);
             }
             flushedBuffer = _connectionCancelled;
         }
         pairSocket.Close();
     }
     NetMQConfig.Cleanup();
 }
Esempio n. 16
0
        public override bool HandleMessage(PairSocket me, PairSocket remote, Envelope envelop)
        {
            me.ConnectionId = envelop.ReadNext <Guid>();
            me.idAwaiter.Set();

            return(true);
        }
Esempio n. 17
0
    void SocketThreadLoop()
    {
        while (true)
        {
            threadRunning   = true;
            senderCancelled = false;
            AsyncIO.ForceDotNet.Force();
            using (var sock = new PairSocket())
            {
                sock.Connect("tcp://" + ip + ":" + port);

                while (!senderCancelled)
                {
                    if (!framePending)
                    {
                        continue;
                    }
                    sock.SendFrame(msgBuffer);
                    framesSent++;
                    framePending = false;
                }

                sock.Close();
            }
            NetMQConfig.Cleanup();
            threadRunning = false;
        }
    }
Esempio n. 18
0
        internal void RemoveSubscriber(PairSocket subscriber, bool forced)
        {
            lock (this)
            {
                if (subscriber.ConnectionId != null)
                {
                    if (!IdentifierSubscriber.ContainsKey(subscriber.ConnectionId))
                    {
                        return;
                    }

                    var subConfig = IdentifierSubscriber[subscriber.ConnectionId];
                    subConfig.PairSocket = null;

                    if (subConfig.LostType == PubSubQueueLostType.Persistent)
                    {
                        if (forced)
                        {
                            IdentifierSubscriber.Remove(subscriber.ConnectionId);
                            persistentCount--;
                        }
                    }
                    else
                    {
                        IdentifierSubscriber.Remove(subscriber.ConnectionId);
                    }
                }
            }
        }
        public void Run(PairSocket shim)
        {
            shim.SignalOK();

            shim.ReceiveReady += OnShimReady;

            m_messagesPipe = new PairSocket();
            m_messagesPipe.Connect(string.Format("inproc://wsrouter-{0}", m_id));
            m_messagesPipe.ReceiveReady += OnMessagePipeReady;

            m_stream = new StreamSocket();
            m_stream.ReceiveReady += OnStreamReady;

            m_poller = new NetMQPoller();
            m_poller.Add(m_messagesPipe);
            m_poller.Add(shim);
            m_poller.Add(m_stream);

            m_messagesPipe.SignalOK();

            m_poller.Run();

            m_messagesPipe.Dispose();
            m_stream.Dispose();
        }
Esempio n. 20
0
        public void RunPipeline(PairSocket shim)
        {
            while (true)
            {
                try
                {
                    NetMQMessage msg = shim.ReceiveMessage();

                    string command = msg[0].ConvertToString();

                    if (command == ActorKnownMessages.END_PIPE)
                    {
                        break;
                    }

                    //Simulate a failure that should be sent back to Actor
                    //Simulate a failure that should be sent back to Actor
                    //Simulate a failure that should be sent back to Actor
                    //Simulate a failure that should be sent back to Actor
                    throw new InvalidOperationException("Actors Shim threw an Exception");
                }
                //You WILL need to decide what Exceptions should be caught here, this is for
                //demonstration purposes only, any unhandled falut will bubble up to callers code
                catch (InvalidOperationException e)
                {
                    shim.Send(string.Format("Error: Exception occurred {0}", e.Message));
                }
            }

            //broken out of work loop, so should dispose shim socket now
            shim.Dispose();
        }
Esempio n. 21
0
        public override bool HandleMessage(PairSocket me, PairSocket remote, Envelope envelop)
        {
            var queueName = envelop.ReadNext <string>();

            PubSubQueue queue;

            lock (me.Queue)
            {
                if (!me.Queue.ContainsKey(queueName))
                {
                    queue      = new PubSubQueue();
                    queue.Name = queueName;

                    me.Queue[queueName] = queue;
                }
                else
                {
                    queue = me.Queue[queueName];
                }
            }

            var lastWillEnvelop = new Envelope(envelop.GetMessage());

            lastWillEnvelop.Append(PublishDeliveredProtocol.Command);
            lastWillEnvelop.Append(queue);
            lastWillEnvelop.Append((byte)PubSubQueueLostType.None);

            remote.LastWill = lastWillEnvelop;

            return(true);
        }
Esempio n. 22
0
        public void BindAndConnect()
        {
            using (PairSocket bind = new PairSocket())
            {
                bind.Bind("inproc://test");
                Assert.That(!bind.HasOut);

                using (PairSocket connect = new PairSocket())
                {
                    connect.Connect("inproc://test");

                    Assert.That(connect.HasOut);
                    Assert.That(bind.HasOut);
                    Assert.That(!bind.HasIn);

                    Assert.That(connect.TrySendFrame("Hello"));
                    Assert.That(bind.HasIn);

                    string message;

                    Assert.That(bind.TryReceiveFrameString(out message));
                    Assert.That(message == "Hello");
                }
            }
        }
Esempio n. 23
0
 private static void Node0(string url)
 {
     using (var s = new PairSocket())
     {
         s.Bind(url);
         SendReceive(s);
     }
 }
Esempio n. 24
0
 public void Bind()
 {
     using (PairSocket bind = new PairSocket())
     {
         bind.TcpBind("localhost", 45000);
         Thread.Sleep(5000);
     }
 }
Esempio n. 25
0
        public override bool HandleMessage(PairSocket me, PairSocket remote, Envelope envelop)
        {
            var msgId = envelop.ReadNext <uint>();

            me.OnMessage?.Invoke(envelop.GetMessage(), remote, null);

            return(true);
        }
Esempio n. 26
0
 private static void Node1(string url)
 {
     using (var s = new PairSocket())
     {
         s.Connect(url);
         SendReceive(s);
     }
 }
Esempio n. 27
0
        private void OnDisconnected(PairSocket socket)
        {
            bool connected = false;

            while (!connected)
            {
                connected = socket.TryReconnect();
            }
        }
Esempio n. 28
0
        private void RunActor(PairSocket shim)
        {
            // save the shim to the class to use later
            m_shim = shim;

            // create all subscriber, publisher and beacon
            using (m_subscriber = new SubscriberSocket())
                using (m_publisher = new PublisherSocket())
                    using (m_beacon = new NetMQBeacon())
                    {
                        // listen to actor commands
                        m_shim.ReceiveReady += OnShimReady;

                        // subscribe to all messages
                        m_subscriber.Subscribe("");

                        // we bind to a random port, we will later publish this port
                        // using the beacon
                        m_randomPort = m_subscriber.BindRandomPort("tcp://*");
                        Console.WriteLine("Bus subscriber is bound to {0}", m_subscriber.Options.LastEndpoint);

                        // listen to incoming messages from other publishers, forward them to the shim
                        m_subscriber.ReceiveReady += OnSubscriberReady;

                        // configure the beacon to listen on the broadcast port
                        Console.WriteLine("Beacon is being configured to UDP port {0}", m_broadcastPort);
                        m_beacon.Configure(m_broadcastPort);

                        // publishing the random port to all other nodes
                        Console.WriteLine("Beacon is publishing the Bus subscriber port {0}", m_randomPort);
                        m_beacon.Publish(m_randomPort.ToString(), TimeSpan.FromSeconds(1));

                        // Subscribe to all beacon on the port
                        Console.WriteLine("Beacon is subscribing to all beacons on UDP port {0}", m_broadcastPort);
                        m_beacon.Subscribe("");

                        // listen to incoming beacons
                        m_beacon.ReceiveReady += OnBeaconReady;

                        // Create a timer to clear dead nodes
                        NetMQTimer timer = new NetMQTimer(TimeSpan.FromSeconds(1));
                        timer.Elapsed += ClearDeadNodes;

                        // Create and configure the poller with all sockets and the timer
                        m_poller = new NetMQPoller {
                            m_shim, m_subscriber, m_beacon, timer
                        };

                        // signal the actor that we finished with configuration and
                        // ready to work
                        m_shim.SignalOK();

                        // polling until cancelled
                        m_poller.Run();
                    }
        }
Esempio n. 29
0
 public void Run(PairSocket shim)
 {
     this.shim          = shim;
     shim.ReceiveReady += OnShimReady;
     shim.SignalOK();
     poller = new NetMQPoller {
         shim
     };
     poller.Run();
 }
Esempio n. 30
0
        private NetMQActor(PairSocket self, PairSocket shim, IShimHandler shimHandler)
        {
            m_shimHandler = shimHandler;

            m_self = self;
            m_shim = shim;

            EventHandler <NetMQSocketEventArgs> onReceive = (sender, e) =>
                                                            m_receiveEvent.Fire(this, new NetMQActorEventArgs(this));

            EventHandler <NetMQSocketEventArgs> onSend = (sender, e) =>
                                                         m_sendEvent.Fire(this, new NetMQActorEventArgs(this));

            m_receiveEvent = new EventDelegator <NetMQActorEventArgs>(
                () => m_self.ReceiveReady += onReceive,
                () => m_self.ReceiveReady -= onReceive);

            m_sendEvent = new EventDelegator <NetMQActorEventArgs>(
                () => m_self.SendReady += onSend,
                () => m_self.SendReady -= onSend);

            var random = new Random();

            // Bind and connect pipe ends
            string actorName;
            string endPoint;

            while (true)
            {
                try
                {
                    actorName = string.Format("NetMQActor-{0}-{1}", random.Next(0, 10000), random.Next(0, 10000));
                    endPoint  = string.Format("inproc://{0}", actorName);
                    m_self.Bind(endPoint);
                    break;
                }
                catch (AddressAlreadyInUseException)
                {
                    // Loop around and try another random address
                }
            }

            m_shim.Connect(endPoint);

            m_shimThread = new Thread(RunShim)
            {
                Name = actorName
            };
            m_shimThread.Start();

            // Mandatory handshake for new actor so that constructor returns only
            // when actor has also initialised. This eliminates timing issues at
            // application start up.
            m_self.ReceiveSignal();
        }
Esempio n. 31
0
        internal void HandleMessage(PairSocket me, PairSocket remote, Envelope envelope)
        {
            envelope.Move(0);

            var code = envelope.ReadNext <int>();

            if (SupportedProtocol.ContainsKey(code))
            {
                SupportedProtocol[code].HandleMessage(me, remote, envelope);
            }
        }
Esempio n. 32
0
        public StopSignaler()
        {
            PairSocket.CreateSocketPair(out m_writer, out m_reader);
            m_reader.ReceiveReady += delegate
            {
                m_reader.SkipFrame();
                IsStopRequested = true;
            };

            IsStopRequested = false;
        }
Esempio n. 33
0
        private void Run(PairSocket shim)
        {
            shim.ReceiveReady += OnShimReady;
            m_receiveSocket.ReceiveReady += OnSocketReady;
            m_poller = new NetMQPoller { m_receiveSocket, shim };

            shim.SignalOK();
            m_poller.Run();

            m_receiveSocket.ReceiveReady -= OnSocketReady;
        }
Esempio n. 34
0
        void IShimHandler.Run(PairSocket pipe)
        {
            _pipe = pipe;
            _pipe.SignalOK();
            _pipe.ReceiveReady += OnPipeReady;

            _zre = Zre.Create(_ctx, _name);
            _zre.ReceiveReady += OnZreReady;

            _poller = new Poller();
            _poller.AddSocket(_zre);
            _poller.AddSocket(_pipe);
            _poller.PollTillCancelled();
        }
Esempio n. 35
0
        void IShimHandler.Run(PairSocket shim)
        {
            _pipe = shim;
            _pipe.SignalOK();
            _pipe.ReceiveReady += OnPipeReady;

            _timer = new NetMQTimer(TimeSpan.FromSeconds(1));
            _timer.Elapsed += OnPingPeer;

            _inbox = _context.CreateRouterSocket();
            _inbox.ReceiveReady += OnInboxReady;

            _poller = new Poller(_pipe);
            _poller.AddTimer(_timer);
            _poller.PollTillCancelled();
        }
        public void Run(PairSocket shim, object[] args, CancellationToken token)
        {
            if (args == null || args.Count() != 1)
                throw new InvalidOperationException(
                    "Args were not correct, expected one argument");

            AccountAction accountAction = JsonConvert.DeserializeObject<AccountAction>(args[0].ToString());

            while (!token.IsCancellationRequested)
            {
                //Message for this actor/shim handler is expected to be
                //Frame[0] : Command
                //Frame[1] : Payload
                //
                //Result back to actor is a simple echoing of the Payload, where
                //the payload is prefixed with "AMEND ACCOUNT"
                NetMQMessage msg = null;

                //this may throw NetMQException if we have disposed of the actor
                //end of the pipe, and the CancellationToken.IsCancellationRequested
                //did not get picked up this loop cycle
                msg = shim.ReceiveMessage();

                if (msg == null)
                    break;

                if (msg[0].ConvertToString() == "AMEND ACCOUNT")
                {
                    string json = msg[1].ConvertToString();
                    Account account = JsonConvert.DeserializeObject<Account>(json);
                    AmmendAccount(accountAction, account);
                    shim.Send(JsonConvert.SerializeObject(account));
                }
                else
                {
                    throw NetMQException.Create("Unexpected command",
                        ErrorCode.EFAULT);
                }
            }
        }
Esempio n. 37
0
        public Actor(NetMQContext context, IShimHandler shimHandler, object[] args)
        {
            this.self = context.CreatePairSocket();
            this.shim = new Shim(shimHandler, context.CreatePairSocket());
            this.self.Options.SendHighWatermark = 1000;
            this.self.Options.SendHighWatermark = 1000;

            //now binding and connect pipe ends
            string endPoint = string.Empty;
            while (true)
            {
                Action bindAction = () =>
                {
                    endPoint = GetEndPointName();
                    self.Bind(endPoint);
                };

                try
                {
                    bindAction();
                    break;
                }
                catch (NetMQException nex)
                {
                    if (nex.ErrorCode == ErrorCode.EFAULT)
                    {
                        bindAction();
                    }
                }

            }

            shim.Pipe.Connect(endPoint);

            //Create Shim thread handler
            CreateShimThread(args);
        }
Esempio n. 38
0
        public void Run(PairSocket shim, object[] args, CancellationToken token)
        {
            if (args == null || args.Count() != 1 || (string)args[0] != "Hello World")
                throw new InvalidOperationException(
                    "Args were not correct, expected 'Hello World'");

            while (!token.IsCancellationRequested)
            {
                //Message for this actor/shim handler is expected to be
                //Frame[0] : Command
                //Frame[1] : Payload
                //
                //Result back to actor is a simple echoing of the Payload, where
                //the payload is prefixed with "ECHO BACK "
                NetMQMessage msg = null;

                //this may throw NetMQException if we have disposed of the actor
                //end of the pipe, and the CancellationToken.IsCancellationRequested
                //did not get picked up this loop cycle
                msg = shim.ReceiveMessage();

                if (msg == null)
                    break;

                if (msg[0].ConvertToString() == "ECHO")
                {
                    shim.Send(string.Format("ECHO BACK : {0}",
                        msg[1].ConvertToString()));
                }
                else
                {
                    throw NetMQException.Create("Unexpected command",
                        ErrorCode.EFAULT);
                }
            }
        }
        private void Run(PairSocket shim)
        {
            using (m_publisherSocket = m_context.CreateXPublisherSocket())
            {
                m_publisherSocket.SetWelcomeMessage(WelcomeMessage);
                m_publisherSocket.Bind(m_address);

                m_publisherSocket.ReceiveReady += DropPublisherSubscriptions;

                m_heartbeatTimer = new NetMQTimer(HeartbeatInterval);
                m_heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;

                shim.ReceiveReady += OnShimMessage;

                // signal the actor that the shim is ready to work
                shim.SignalOK();

                m_poller = new Poller(m_publisherSocket, shim);
                m_poller.AddTimer(m_heartbeatTimer);

                // Polling until poller is cancelled
                m_poller.PollTillCancelled();
            }
        }
Esempio n. 40
0
        /// <summary>
        ///     <para>is the main thread of the broker</para>
        ///     <para>it spawns threads handling titanic operations</para>
        ///     <para>it receives GUID from Titanic Request Service and dispatches the requests
        ///     to available workers via MDPBroker</para>
        ///     <para>it also manages the appropriate changes in the file system as well as in queue</para>
        /// </summary>
        /// <param name="requestWorker">mdp worker processing the incoming requests for services</param>
        /// <param name="replyWorker">mdp worker processing incoming reply requests</param>
        /// <param name="closeWorker">mdp worker processing incoming close requests</param>
        /// <param name="serviceCallClient">mdp client forwarding requests to service providing mdp worker
        ///                                 via mdp broker and collecting replies</param>
        /// <exception cref="TerminatingException">The socket has been stopped.</exception>
        /// <exception cref="AddressAlreadyInUseException">The specified address is already in use.</exception>
        /// <exception cref="NetMQException">No IO thread was found, or the protocol's listener encountered an
        ///                                  error during initialization.</exception>
        /// <exception cref="ObjectDisposedException">thrown if the socket was already disposed</exception>
        public void Run( IMDPWorker requestWorker = null,
                          IMDPWorker replyWorker = null,
                          IMDPWorker closeWorker = null,
                          IMDPClient serviceCallClient = null)
        {
            using (var pipeStart = new PairSocket ())
            using (var pipeEnd = new PairSocket ())
            using (var cts = new CancellationTokenSource ())
            {
                // set up the inter thread communication pipe
                pipeStart.Bind (_titanic_internal_communication);
                pipeEnd.Connect (_titanic_internal_communication);

                // start the three child tasks
                var requestTask = Task.Run (() => ProcessTitanicRequest (pipeEnd, requestWorker), cts.Token);
                var replyTask = Task.Run (() => ProcessTitanicReply (replyWorker), cts.Token);
                var closeTask = Task.Run (() => ProcessTitanicClose (closeWorker), cts.Token);

                var tasks = new[] { requestTask, replyTask, closeTask };

                while (true)
                {
                    // wait for 1s for a new request from 'Request' to process
                    var input = pipeStart.Poll (PollEvents.PollIn, TimeSpan.FromMilliseconds (1000));

                    // any message available? -> process it
                    if ((input & PollEvents.PollIn) == PollEvents.PollIn)
                    {
                        // only one frame will be send [Guid]
                        var msg = pipeStart.ReceiveFrameString ();

                        Guid guid;
                        if (!Guid.TryParse (msg, out guid))
                            Log ("[TITANIC BROKER] Received a malformed GUID via pipe - throw it away");
                        else
                        {
                            Log (string.Format ("[TITANIC BROKER] Received request GUID {0} via pipe", msg));
                            // now we have a valid GUID - save it to disk for further use
                            m_io.SaveNewRequestEntry (guid);
                        }
                    }
                    //! now dispatch (brute force) the requests -> SHOULD BE MORE INTELLIGENT (!)
                    // dispatching will also worry about the handling of a potential reply
                    // dispatch only requests which have not been closed
                    foreach (var entry in m_io.GetNotClosedRequestEntries ().Where (entry => entry != default (RequestEntry)))
                    {
                        if (DispatchRequests (entry.RequestId, serviceCallClient))
                            m_io.SaveProcessedRequestEntry (entry);
                    }

                    //! should implement some sort of restart
                    // beware of the silently dieing threads - must be detected!
                    if (DidAnyTaskStopp (tasks))
                    {
                        // stopp all threads
                        cts.Cancel ();
                        // stop processing!
                        break;
                    }
                }
            }
        }
Esempio n. 41
0
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer = new NetMQTimer(interval: TimeSpan.Zero);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable = false;

                using (m_poller = new NetMQPoller { m_pipe, m_pingTimer })
                {
                    m_poller.Run();
                }

                // the beacon might never been configured
                #if NET35
                m_udpSocket?.Close();
                #else
                m_udpSocket?.Dispose();
                #endif
            }
Esempio n. 42
0
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer = new NetMQTimer(0);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable = false;

                m_poller = new Poller();
                m_poller.AddSocket(m_pipe);
                m_poller.AddTimer(m_pingTimer);

                m_poller.PollTillCancelled();

                // the beacon might never been configured
                if (m_udpSocket != null)
                {
                    m_udpSocket.Close();
                }
            }
        private void Run(PairSocket shim)
        {
            m_shim = shim;
            shim.ReceiveReady += OnShimMessage;

            m_timeoutTimer = new NetMQTimer(TimeOut);
            m_timeoutTimer.Elapsed += OnTimeoutTimer;

            m_reconnectTimer = new NetMQTimer(ReconnectTimer);
            m_reconnectTimer.Elapsed += OnReconnectTimer;

            m_poller = new Poller(shim);
            m_poller.AddTimer(m_timeoutTimer);
            m_poller.AddTimer(m_reconnectTimer);

            shim.SignalOK();

            Connect();

            m_poller.PollTillCancelled();

            if (m_subscriber != null)
                m_subscriber.Dispose();
        }
Esempio n. 44
0
        /// <summary>
        ///     process a titanic request according to TITANIC Protocol
        ///
        ///     <para>it connects via provided PAIR socket to main thread</para>
        ///     <para>write request to disk and return the GUID to client</para>
        ///     sends the GUID of the request back via the pipe for further processing
        /// </summary>
        internal void ProcessTitanicRequest( PairSocket pipe, IMDPWorker mdpWorker = null)
        {
            // get a MDP worker with an automatic id and register with the service "titanic.request"
            // the worker will automatically start and connect to a MDP Broker at the indicated address
            using (var worker = mdpWorker ?? new MDPWorker (m_titanicAddress, TitanicOperation.Request.ToString ()))
            {
                NetMQMessage reply = null;

                while (true)
                {
                    // initiate the communication with sending a 'null', since there is no initial reply
                    // a request should be [service name][request data]
                    var request = worker.Receive (reply);

                    Log (string.Format ("[TITANIC REQUEST] Received request: {0}", request));

                    //! has there been a breaking cause? -> exit
                    if (ReferenceEquals (request, null))
                        break;

                    //! check if service exists! and return 'Unknown' if not

                    // generate Guid for the request
                    var requestId = Guid.NewGuid ();
                    // save request to file -> [service name][request data]
                    m_io.SaveMessage (TitanicOperation.Request, requestId, request);

                    Log (string.Format ("[TITANIC REQUEST] sending through pipe: {0}", requestId));

                    // send GUID through message queue to main thread
                    pipe.SendFrame (requestId.ToString ());
                    // return GUID via reply message via worker.Receive call
                    reply = new NetMQMessage ();
                    // [Guid]
                    reply.Push (requestId.ToString ());
                    // [Ok][Guid]
                    reply.Push (TitanicReturnCode.Ok.ToString ());

                    Log (string.Format ("[TITANIC REQUEST] sending reply: {0}", reply));
                }
            }
        }
Esempio n. 45
0
File: Bus.cs Progetto: vadian/netmq
        private void RunActor(PairSocket shim)
        {
            // save the shim to the class to use later
            m_shim = shim;

            // create all subscriber, publisher and beacon
            using (m_subscriber = new SubscriberSocket())
            using (m_publisher = new PublisherSocket())
            using (m_beacon = new NetMQBeacon())
            {
                // listen to actor commands
                m_shim.ReceiveReady += OnShimReady;

                // subscribe to all messages
                m_subscriber.Subscribe("");

                // we bind to a random port, we will later publish this port
                // using the beacon
                m_randomPort = m_subscriber.BindRandomPort("tcp://*");
                Console.WriteLine("Bus subscriber is bound to {0}", m_subscriber.Options.LastEndpoint);

                // listen to incoming messages from other publishers, forward them to the shim
                m_subscriber.ReceiveReady += OnSubscriberReady;

                // configure the beacon to listen on the broadcast port
                Console.WriteLine("Beacon is being configured to UDP port {0}", m_broadcastPort);
                m_beacon.Configure(m_broadcastPort);

                // publishing the random port to all other nodes
                Console.WriteLine("Beacon is publishing the Bus subscriber port {0}", m_randomPort);
                m_beacon.Publish(m_randomPort.ToString(), TimeSpan.FromSeconds(1));

                // Subscribe to all beacon on the port
                Console.WriteLine("Beacon is subscribing to all beacons on UDP port {0}", m_broadcastPort);
                m_beacon.Subscribe("");

                // listen to incoming beacons
                m_beacon.ReceiveReady += OnBeaconReady;

                // Create a timer to clear dead nodes
                NetMQTimer timer = new NetMQTimer(TimeSpan.FromSeconds(1));
                timer.Elapsed += ClearDeadNodes;

                // Create and configure the poller with all sockets and the timer
                m_poller = new NetMQPoller { m_shim, m_subscriber, m_beacon, timer };

                // signal the actor that we finished with configuration and
                // ready to work
                m_shim.SignalOK();

                // polling until cancelled
                m_poller.Run();
            }
        }
Esempio n. 46
0
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer = new NetMQTimer(interval: TimeSpan.Zero);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable = false;

                m_poller = new NetMQPoller { m_pipe, m_pingTimer };

                m_poller.Run();

                // the beacon might never been configured
                if (m_udpSocket != null)
                    m_udpSocket.Close();
            }