Пример #1
0
        public void Run(PairSocket shim)
        {
            shim.SignalOK();

            while (true)
            {
                try
                {
                    //Message for this actor/shim handler is expected to be
                    //Frame[0] : Command
                    //Frame[2] : AccountAction as JSON
                    //Frame[1] : Account as JSON
                    //
                    //Result back to actor is a JSON message of the amended Account
                    NetMQMessage msg = shim.ReceiveMultipartMessage();

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

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

                    if (msg[0].ConvertToString() == "AMEND ACCOUNT")
                    {
                        string accountActionJson = msg[1].ConvertToString();
                        var    accountAction     = JsonConvert.DeserializeObject <AccountAction>(accountActionJson);

                        string accountJson = msg[2].ConvertToString();
                        var    account     = JsonConvert.DeserializeObject <Account>(accountJson);
                        if (account != null && accountAction != null)
                        {
                            AmendAccount(accountAction, account);
                            shim.SendFrame(JsonConvert.SerializeObject(account));
                        }
                        else
                        {
                            shim.SendFrame("Error: incorrectly formatted message to actor");
                        }
                    }
                    else
                    {
                        shim.SendFrame("Error: invalid message to actor");
                    }
                }
                // 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 (Exception e)
                {
                    shim.SendFrame($"Error: Exception occurred {e.Message}");
                }
            }
        }
        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());
        }
Пример #3
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();
        }
Пример #4
0
            private void OnShimReady(object sender, NetMQSocketEventArgs e)
            {
                string command = e.Socket.ReceiveFrameString();

                switch (command)
                {
                case NetMQActor.EndShimMessage:
                    Log.Information("Actor received EndShimMessage");
                    poller.Stop();
                    break;

                case "AmendAccount":
                    Log.Information("Actor received AmendAccount message");
                    string  accountJson = e.Socket.ReceiveFrameString();
                    Account account
                        = JsonConvert.DeserializeObject <Account>(accountJson);
                    string        accountActionJson = e.Socket.ReceiveFrameString();
                    AccountAction accountAction
                        = JsonConvert.DeserializeObject <AccountAction>(
                              accountActionJson);
                    Log.Information("Incoming Account details: {Account}", account);
                    AmendAccount(account, accountAction);
                    shim.SendFrame(JsonConvert.SerializeObject(account));
                    break;
                }
            }
Пример #5
0
        private void OnShimReady(object sender, NetMQSocketEventArgs e)
        {
            var command = _shim.ReceiveFrameString();

            switch (command)
            {
            case NetMQActor.EndShimMessage:
            {
                _poll.Stop();
                break;
            }

            case PublishCommand:
            {
                _publisher.SendMultipartMessage(_shim.ReceiveMultipartMessage());
                break;
            }

            case GetHostAddressCommand:
            {
                _shim.SendFrame($"{_beacon.BoundTo}:{_port}");
                break;
            }
            }
        }
Пример #6
0
        /// <summary>
        /// We do this once a second:
        /// - if peer has gone quiet, send TCP ping and emit EVASIVE event
        /// - if peer has disappeared, expire it
        /// </summary>
        /// <param name="peer">the peer to ping</param>
        /// <returns>true if this peer should be removed</returns>
        private bool PingPeer(ZyrePeer peer)
        {
            if (!_isRunning)
            {
                // We have been stopped. We know longer can communicate to peers.
                return(true);
            }
            if (DateTime.Now >= peer.ExpiredAt)
            {
                return(true);
            }
            if (DateTime.Now >= peer.EvasiveAt)
            {
                // If peer is being evasive, force a TCP ping.
                // ZeroMQTODO: do this only once for a peer in this state;
                // it would be nicer to use a proper state machine
                // for peer management.
                _loggerDelegate?.Invoke($"Peer seems dead/slow: name={peer.Name} endpoint={peer.Endpoint}");
                ZreMsg.SendPing(_outbox, 0);

                // Inform the calling application this peer is being evasive
                _outbox.SendMoreFrame("EVASIVE");
                _outbox.SendMoreFrame(peer.Uuid.ToByteArray());
                _outbox.SendFrame(peer.Name);
            }
            return(false);
        }
Пример #7
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;
        }
    }
        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.SendFrame(string.Format("Error: Exception occurred {0}", e.Message));
                }
            }
        }
Пример #9
0
        private void OnShimReady(object sender, NetMQSocketEventArgs e)
        {
            // new actor command
            string command = m_shim.ReceiveFrameString();

            // check if we received end shim command
            if (command == NetMQActor.EndShimMessage)
            {
                // we cancel the socket which dispose and exist the shim
                m_poller.Stop();
            }
            else if (command == PublishCommand)
            {
                // it is a publish command
                // we just forward everything to the publisher until end of message
                NetMQMessage message = m_shim.ReceiveMultipartMessage();
                m_publisher.SendMultipartMessage(message);
            }
            else if (command == GetHostAddressCommand)
            {
                var interfaceCollection = new InterfaceCollection();
                var bindTo  = interfaceCollection.Select(x => x.Address).First();
                var address = bindTo + ":" + m_randomPort;
                m_shim.SendFrame(address);
            }
        }
Пример #10
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();
 }
Пример #11
0
        public void Run(PairSocket shim)
        {
            shim.SignalOK();

            while (true)
            {
                try
                {
                    //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 = shim.ReceiveMultipartMessage();

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

                    switch (command)
                    {
                    case NetMQActor.EndShimMessage:
                        return;

                    case "ECHO":
                        shim.SendFrame($"ECHO BACK : {msg[1].ConvertToString()}");
                        break;

                    default:
                        shim.SendFrame("Error: invalid message to actor");
                        break;
                    }
                }
                // 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 (Exception e)
                {
                    shim.SendFrame($"Error: Exception occurred {e.Message}");
                }
            }
        }
Пример #12
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([NotNull] PairSocket pipe, [CanBeNull] 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($"[TITANIC REQUEST] Received request: {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($"[TITANIC REQUEST] sending through pipe: {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($"[TITANIC REQUEST] sending reply: {reply}");
                }
            }
        }
Пример #13
0
        private void OnShimReady(object sender, NetMQSocketEventArgs e)
        {
            // new actor command
            var command = shim.ReceiveFrameString();

            // check if we received end shim command
            if (command == NetMQActor.EndShimMessage)
            {
                // we cancel the socket which dispose and exist the shim
                poller.Stop();
            }
            else if (command == PublishCommand)
            {
                // it is a publish command
                // we just forward everything to the publisher until end of message
                var message = shim.ReceiveMultipartMessage();
                publisher.SendMultipartMessage(message);
            }
            else if (command == GetHostAddressCommand)
            {
                var address = beacon.BoundTo + ":" + randomPort;
                shim.SendFrame(address);
            }
        }
Пример #14
0
        private void OnShimReady(object sender, NetMQSocketEventArgs e)
        {
            // new actor command
            var command = _shim.ReceiveFrameString();

            // check if we received end shim command
            if (command == NetMQActor.EndShimMessage)
            {
                // we cancel the socket which dispose and exist the shim
                _poller.Stop();
            }
            else if (command == TaskSchedulerBusCommands.Publish.ToString())
            {
                // it is a publish command
                // we just forward everything to the publisher until end of message
                var message = _shim.ReceiveMultipartMessage();
                _publisher.SendMultipartMessage(message);
            }
            else if (command == TaskSchedulerBusCommands.GetHostAddress.ToString())
            {
                var address = _beacon.HostName + ":" + _randomPort;
                _shim.SendFrame(address);
            }
        }
Пример #15
0
 private void sendScreenshot(object sender, CameraScreenshotModifierEventArgs e)
 {
     camera.TakeScreenshot -= sendScreenshot;
     ScreenshotServer.SendFrame(e.jpg);
     ScreenshotResponseTask = new TaskCompletionSource <string>();
 }
Пример #16
0
        /// <summary>
        /// Here we handle the different control messages from the front-end
        /// </summary>
        private void ReceiveApi()
        {
            // Get the whole message off the pipe in one go
            var request = _pipe.ReceiveMultipartMessage();
            var command = request.Pop().ConvertToString();

            switch (command)
            {
            case "UUID":
                _pipe.SendFrame(_uuid.ToByteArray());
                break;

            case "NAME":
                _pipe.SendFrame(_name);
                break;

            case "ENDPOINT":
                _pipe.SendFrame(_endpoint ?? "");
                break;

            case "SET NAME":
                _name = request.Pop().ConvertToString();
                Debug.Assert(!String.IsNullOrEmpty(_name));
                break;

            case "SET HEADER":
                var key   = request.Pop().ConvertToString();
                var value = request.Pop().ConvertToString();
                _headers[key] = value;
                break;

            case "SET PORT":
                var str = request.Pop().ConvertToString();
                Int32.TryParse(str, out _beaconPort);
                break;

            case "SET INTERVAL":
                var intervalStr = request.Pop().ConvertToString();
                TimeSpan.TryParse(intervalStr, out _interval);
                break;

            case "START":
                var interfaceName = request.Pop().ConvertToString();
                Start(interfaceName);
                break;

            case "STOP":
                Stop();
                break;

            case "WHISPER":
                // Get peer to send message to
                var      uuid = PopGuid(request);
                ZyrePeer peer;
                if (_peers.TryGetValue(uuid, out peer))
                {
                    //  Send frame on out to peer's mailbox, drop message
                    //  if peer doesn't exist (may have been destroyed)
                    var msg = new ZreMsg
                    {
                        Id      = ZreMsg.MessageId.Whisper,
                        Whisper = { Content = request }
                    };
                    peer.Send(msg);
                }
                break;

            case "SHOUT":
                // Get group to send message to
                var       groupNameShout = request.Pop().ConvertToString();
                ZyreGroup group;
                if (_peerGroups.TryGetValue(groupNameShout, out group))
                {
                    var msg = new ZreMsg
                    {
                        Id    = ZreMsg.MessageId.Shout,
                        Shout = { Group = groupNameShout, Content = request }
                    };
                    group.Send(msg);
                }
                break;

            case "JOIN":
                var       groupNameJoin = request.Pop().ConvertToString();
                ZyreGroup groupJoin;
                if (!_ownGroups.TryGetValue(groupNameJoin, out groupJoin))
                {
                    // Only send if we're not already in group
                    ZyreGroup.NewGroup(groupNameJoin, _ownGroups);

                    // Update status before sending command
                    _status = _status == UbyteMax ? (byte)0 : ++_status;
                    var msg = new ZreMsg
                    {
                        Id   = ZreMsg.MessageId.Join,
                        Join =
                        {
                            Group  = groupNameJoin,
                            Status = _status
                        }
                    };
                    foreach (var peerJoin in _peers.Values)
                    {
                        peerJoin.Send(msg);
                    }
                }
                break;

            case "LEAVE":
                var       groupNameLeave = request.Pop().ConvertToString();
                ZyreGroup groupLeave;
                if (_ownGroups.TryGetValue(groupNameLeave, out groupLeave))
                {
                    // Only send if we are actually in group
                    // Update status before sending command
                    _status = _status == UbyteMax ? (byte)0 : ++_status;
                    var msg = new ZreMsg
                    {
                        Id    = ZreMsg.MessageId.Leave,
                        Leave =
                        {
                            Group  = groupNameLeave,
                            Status = _status
                        }
                    };
                    foreach (var peerLeave in _peers.Values)
                    {
                        peerLeave.Send(msg);
                    }
                    _ownGroups.Remove(groupNameLeave);
                }
                break;

            case "PEERS":
                // Send the list of the _peers keys
                var peersKeyBuffer = Serialization.BinarySerialize(_peers.Keys.ToList());
                _pipe.SendFrame(peersKeyBuffer);
                break;

            case "PEER ENDPOINT":
                var uuidForEndpoint = PopGuid(request);
                var peerForEndpoint = _peers[uuidForEndpoint];     // throw exception if not found
                _pipe.SendFrame(peerForEndpoint.Endpoint);
                break;

            case "PEER NAME":
                var uuidForName = PopGuid(request);
                var peerForName = _peers[uuidForName];     // throw exception if not found
                _pipe.SendFrame(peerForName.Name);
                break;

            case "PEER HEADER":
                var      uuidForHeader = PopGuid(request);
                var      keyForHeader  = request.Pop().ConvertToString();
                ZyrePeer peerForHeader;
                if (_peers.TryGetValue(uuidForHeader, out peerForHeader))
                {
                    string header;
                    if (peerForHeader.Headers.TryGetValue(keyForHeader, out header))
                    {
                        _pipe.SendFrame(header);
                    }
                    else
                    {
                        _loggerDelegate?.Invoke($"No header with key {keyForHeader} in peer uuidShort={uuidForHeader.ToShortString6()}");
                        _pipe.SendFrame("");
                    }
                }
                else
                {
                    _loggerDelegate?.Invoke($"PEER HEADER requested for peer uuidShort={uuidForHeader.ToShortString6()} that is not a peer");
                    _pipe.SendFrame("");
                }
                break;

            case "PEER GROUPS":
                // Send a list of the _peerGroups keys, comma-delimited
                var peerGroupsKeyBuffer = Serialization.BinarySerialize(_peerGroups.Keys.ToList());
                _pipe.SendFrame(peerGroupsKeyBuffer);
                break;

            case "OWN GROUPS":
                // Send a list of the _ownGroups keys, comma-delimited
                var ownGroupsKeyBuffer = Serialization.BinarySerialize(_ownGroups.Keys.ToList());
                _pipe.SendFrame(ownGroupsKeyBuffer);
                break;

            case "DUMP":
                Dump();
                break;

            case NetMQActor.EndShimMessage:
                // API shut us down
                _poller?.Stop();
                break;

            default:
                throw new ArgumentException(command);
            }
        }
Пример #17
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));
                }
            }
        }
Пример #18
0
 public void SendFrame(byte[] frame, bool more)
 {
     m_messagesPipe.SendFrame(frame, more);
 }
Пример #19
0
        static void Main()
        {
            using (var client = new PairSocket())
            {
                client.Connect("tcp://127.0.0.1:5556");
                client.SendFrame("hello");

                bool firstRun = true;

                // talk
                while (true)
                {
                    // receive reward
                    string reward = client.ReceiveFrameString();
                    if (reward == "-1")
                    {
                        reward = "-";
                    }
                    else if (reward == "1")
                    {
                        reward = "+";
                    }
                    else
                    {
                        reward = " ";
                    }

                    if (firstRun)
                    {
                        reward   = string.Empty;
                        firstRun = false;
                    }
                    else
                    {
                        if (!Interactive)
                        {
                            Learner.RegisterReward(reward);
                        }
                    }

                    // receive teacher/env char
                    string teacherChar = client.ReceiveFrameString();

                    Display.ShowStep(reward, teacherChar);

                    // reply
                    string reply;
                    if (Interactive)
                    {
                        var key = Console.ReadKey();
                        reply = key.KeyChar.ToString();
                    }
                    else
                    {
                        reply = Learner.Answer(teacherChar);
                    }

                    Display.ShowReply(reply);
                    client.SendFrame(reply);
                }
            }
        }