zeromq: reset REQ/REP socket state
Asked Answered
P

5

15

When you use the simple ZeroMQ REQ/REP pattern you depend on a fixed send()->recv() / recv()->send() sequence. As this article describes you get into trouble when a participant disconnects in the middle of a request because then you can't just start over with receiving the next request from another connection but the state machine would force you to send a request to the disconnected one.

Has there emerged a more elegant way to solve this since the mentioned article has been written?

Is reconnecting the only way to solve this (apart from not using REQ/REP but use another pattern)

Politic answered 13/11, 2014 at 17:57 Comment(1)
You might want to switch to one of the ROUTER/DEALER based Reliable Request Response (AKA pirate) patterns described in the guideHandicraft
C
7

The good news is that, as of ZMQ 3.0 and later (the modern era), you can set a timeout on a socket. As others have noted elsewhere, you must do this after you have created the socket, but before you connect it:

zmq_req_socket.setsockopt( zmq.RCVTIMEO, 500 ) # milliseconds

Then, when you actually try to receive the reply (after you have sent a message to the REP socket), you can catch the error that will be asserted if the timeout is exceeded:

 try:
   send( message, 0 )
   send_failed = False

 except zmq.Again:
   logging.warning( "Image send failed." )
   send_failed = True

However! When this happens, as observed elsewhere, your socket will be in a funny state, because it will still be expecting the response. At this point, I cannot find anything that works reliably other than just restarting the socket. Note that if you disconnect() the socket and then re connect() it, it will still be in this bad state. Thus you need to

def reset_my_socket:
  zmq_req_socket.close()
  zmq_req_socket = zmq_context.socket( zmq.REQ )
  zmq_req_socket.setsockopt( zmq.RCVTIMEO, 500 ) # milliseconds
  zmq_req_socket.connect( zmq_endpoint )

You will also notice that because I close()d the socket, the receive timeout option was "lost", so it is important set that on the new socket.

I hope this helps. And I hope that this does not turn out to be the best answer to this question. :)

Chadwell answered 30/3, 2015 at 22:14 Comment(1)
This still leaves the REP socket in a bad state, because it attempted to send a reply that was never received.Lundeen
C
51

As the accepted answer seem so terribly sad to me, I did some research and have found that everything we need was actually in the documentation.

The .setsockopt() with the correct parameter can help you resetting your socket state-machine without brutally destroy it and rebuild another on top of the previous one dead body.

(yeah I like the image).

ZMQ_REQ_CORRELATE: match replies with requests
The default behaviour of REQ sockets is to rely on the ordering of messages to match requests and responses and that is usually sufficient. When this option is set to 1, the REQ socket will prefix outgoing messages with an extra frame containing a request id. That means the full message is (request id, 0, user frames…). The REQ socket will discard all incoming messages that don't begin with these two frames.
Option value type int
Option value unit 0, 1
Default value 0
Applicable socket types ZMQ_REQ

ZMQ_REQ_RELAXED: relax strict alternation between request and reply
By default, a REQ socket does not allow initiating a new request with zmq_send(3) until the reply to the previous one has been received. When set to 1, sending another message is allowed and has the effect of disconnecting the underlying connection to the peer from which the reply was expected, triggering a reconnection attempt on transports that support it. The request-reply state machine is reset and a new request is sent to the next available peer.
If set to 1, also enable ZMQ_REQ_CORRELATE to ensure correct matching of requests and replies. Otherwise a late reply to an aborted request can be reported as the reply to the superseding request.
Option value type int
Option value unit 0, 1
Default value 0
Applicable socket types ZMQ_REQ

A complete documentation is here

Cadenza answered 23/3, 2016 at 17:46 Comment(0)
C
7

The good news is that, as of ZMQ 3.0 and later (the modern era), you can set a timeout on a socket. As others have noted elsewhere, you must do this after you have created the socket, but before you connect it:

zmq_req_socket.setsockopt( zmq.RCVTIMEO, 500 ) # milliseconds

Then, when you actually try to receive the reply (after you have sent a message to the REP socket), you can catch the error that will be asserted if the timeout is exceeded:

 try:
   send( message, 0 )
   send_failed = False

 except zmq.Again:
   logging.warning( "Image send failed." )
   send_failed = True

However! When this happens, as observed elsewhere, your socket will be in a funny state, because it will still be expecting the response. At this point, I cannot find anything that works reliably other than just restarting the socket. Note that if you disconnect() the socket and then re connect() it, it will still be in this bad state. Thus you need to

def reset_my_socket:
  zmq_req_socket.close()
  zmq_req_socket = zmq_context.socket( zmq.REQ )
  zmq_req_socket.setsockopt( zmq.RCVTIMEO, 500 ) # milliseconds
  zmq_req_socket.connect( zmq_endpoint )

You will also notice that because I close()d the socket, the receive timeout option was "lost", so it is important set that on the new socket.

I hope this helps. And I hope that this does not turn out to be the best answer to this question. :)

Chadwell answered 30/3, 2015 at 22:14 Comment(1)
This still leaves the REP socket in a bad state, because it attempted to send a reply that was never received.Lundeen
M
1

There is one solution to this and that is adding timeouts to all calls. Since ZeroMQ by itself does not really provide simple timeout functionality I recommend using a subclass of the ZeroMQ socket that adds a timeout parameter to all important calls.

So, instead of calling s.recv() you would call s.recv(timeout=5.0) and if a response does not come back within that 5 second window it will return None and stop blocking. I had made a futile attempt at this when I run into this problem.

Mental answered 13/11, 2014 at 18:11 Comment(3)
I have currently no zeromq 4 here to test it with python but I believe that this approach you recommend will solve the problem with infinitive waiting but not with the state machine. You will then be able to call recv() again but not send(). You would then get an exception like zmq.error.ZMQError: Operation cannot be accomplished in current state. Tell me if I'm wrong (I will try it anyway but I have to install a recent version of pyzmq)Politic
My experience is the same as you describe frans. If the REQ socket has made a send() call but never receives a response, then it is stuck waiting for a response from somewhere. So I can confirm your intuition empirically.Chadwell
As I commented above, the REP socket will still be stuck in a bad state, even if you reset the REQ socket. It's stuck in reply mode, instead of receive mode.Lundeen
S
1

I'm actually looking into this at the moment, because I am retro fitting a legacy system.

I am coming across code constantly that "needs" to know about the state of the connection. However the thing is I want to move to the message passing paradigm that the library promotes.

I found the following function : zmq_socket_monitor

What it does is monitor the socket passed to it and generate events that are then passed to an "inproc" endpoint - at that point you can add handling code to actually do something.

There is also an example (actually test code) here : github

I have not got any specific code to give at the moment (maybe at the end of the week) but my intention is to respond to the connect and disconnects such that I can actually perform any resetting of logic required.

Hope this helps, and despite quoting 4.2 docs, I am using 4.0.4 which seems to have the functionality as well.

Note I notice you talk about python above, but the question is tagged C++ so that's where my answer is coming from...

Scintillant answered 21/11, 2014 at 15:0 Comment(0)
S
0

Update: I'm updating this answer with this excellent resource here: https://blog.cloudflare.com/when-tcp-sockets-refuse-to-die/ Socket programming is complicated so do checkout the references in this post.

None of the answers here seem accurate or useful. The OP is not looking for information on BSD socket programming. He is trying to figure out how to robustly handle accept()ed client-socket failures in ZMQ on the REP socket to prevent the server from hanging or crashing.

As already noted -- this problem is complicated by the fact that ZMQ tries to pretend that the servers listen()ing socket is the same as an accept()ed socket (and there is no where in the documentation that describes how to set basic timeouts on such sockets.)

My answer:

After doing a lot of digging through the code, the only relevant socket options passed along to accept()ed socks seem to be keep alive options from the parent listen()er. So the solution is to set the following options on the listen socket before calling send or recv:

void zmq_setup(zmq::context_t** context, zmq::socket_t** socket, const char* endpoint)
{
    // Free old references.
    if(*socket != NULL)
    {
        (**socket).close();
        (**socket).~socket_t();
    }
    if(*context != NULL)
    {
        // Shutdown all previous server client-sockets.
        zmq_ctx_destroy((*context));
        (**context).~context_t();
    }

    *context = new zmq::context_t(1);
    *socket = new zmq::socket_t(**context, ZMQ_REP);

    // Enable TCP keep alive.
    int is_tcp_keep_alive = 1;
    (**socket).setsockopt(ZMQ_TCP_KEEPALIVE, &is_tcp_keep_alive, sizeof(is_tcp_keep_alive));

    // Only send 2 probes to check if client is still alive.
    int tcp_probe_no = 2;
    (**socket).setsockopt(ZMQ_TCP_KEEPALIVE_CNT, &tcp_probe_no, sizeof(tcp_probe_no));

    // How long does a con need to be "idle" for in seconds.
    int tcp_idle_timeout = 1;
    (**socket).setsockopt(ZMQ_TCP_KEEPALIVE_IDLE, &tcp_idle_timeout, sizeof(tcp_idle_timeout));

    // Time in seconds between individual keep alive probes.
    int tcp_probe_interval = 1;
    (**socket).setsockopt(ZMQ_TCP_KEEPALIVE_INTVL, &tcp_probe_interval, sizeof(tcp_probe_interval));

    // Discard pending messages in buf on close.
    int is_linger = 0;
    (**socket).setsockopt(ZMQ_LINGER, &is_linger, sizeof(is_linger));

    // TCP user timeout on unacknowledged send buffer
    int is_user_timeout = 2;
    (**socket).setsockopt(ZMQ_TCP_MAXRT, &is_user_timeout, sizeof(is_user_timeout));

    // Start internal enclave event server.
    printf("Host: Starting enclave event server\n");
    (**socket).bind(endpoint);
}

What this does is tell the operating system to aggressively check the client socket for timeouts and reap them for cleanup when a client doesn't return a heart beat in time. The result is that the OS will send a SIGPIPE back to your program and socket errors will bubble up to send / recv - fixing a hung server. You then need to do two more things:

1. Handle SIGPIPE errors so the program doesn't crash

#include <signal.h>
#include <zmq.hpp>

// zmq_setup def here [...]

int main(int argc, char** argv) 
{
    // Ignore SIGPIPE signals.
    signal(SIGPIPE, SIG_IGN);
    // ... rest of your code after

    // (Could potentially also restart the server
    // sock on N SIGPIPEs if you're paranoid.)

    // Start server socket.
    const char* endpoint = "tcp://127.0.0.1:47357";
    zmq::context_t* context;
    zmq::socket_t* socket;
    zmq_setup(&context, &socket, endpoint);

    // Message buffers.
    zmq::message_t request;
    zmq::message_t reply;

    // ... rest of your socket code here
}

2. Check for -1 returned by send or recv and catch ZMQ errors.

// E.g. skip broken accepted sockets (pseudo-code.)
while (1):
{
    try
    {
        if ((*socket).recv(&request)) == -1)
            throw -1;
    }
    catch (...)
    {
        // Prevent any endless error loops killing CPU.
        sleep(1)

        // Reset ZMQ state machine.
        try
        {
            zmq::message_t blank_reply = zmq::message_t();
            (*socket).send (blank_reply);
        }
        catch (...)
        {
            1;
        } 

        continue;
    }

Notice the weird code that tries to send a reply on a socket failure? In ZMQ, a REP server "socket" is an endpoint to another program making a REQ socket to that server. The result is if you go do a recv on a REP socket with a hung client, the server sock becomes stuck in a broken receive loop where it will wait forever to receive a valid reply.

To force an update on the state machine, you try send a reply. ZMQ detects that the socket is broken, and removes it from its queue. The server socket becomes "unstuck", and the next recv call returns a new client from the queue.

To enable timeouts on an async client (in Python 3), the code would look something like this:

import asyncio
import zmq
import zmq.asyncio

@asyncio.coroutine
def req(endpoint):
    ms = 2000 # In milliseconds.
    sock = ctx.socket(zmq.REQ)
    sock.setsockopt(zmq.SNDTIMEO, ms)
    sock.setsockopt(zmq.RCVTIMEO, ms)
    sock.setsockopt(zmq.LINGER, ms) # Discard pending buffered socket messages on close().
    sock.setsockopt(zmq.CONNECT_TIMEOUT, ms)

    # Connect the socket.
    # Connections don't strictly happen here.
    # ZMQ waits until the socket is used (which is confusing, I know.)
    sock.connect(endpoint)

    # Send some bytes.
    yield from sock.send(b"some bytes")

    # Recv bytes and convert to unicode.
    msg = yield from sock.recv()
    msg = msg.decode(u"utf-8")  

Now you have some failure scenarios when something goes wrong.

By the way -- if anyone's curious -- the default value for TCP idle timeout in Linux seems to be 7200 seconds or 2 hours. So you would be waiting a long time for a hung server to do anything!

Sources:

Disclaimer:

I've tested this code and it seems to be working, but ZMQ does complicate testing this a fair bit because the client re-connects on failure? If anyone wants to use this solution in production, I recommend writing some basic unit tests, first.

The server code could also be improved a lot with threading or polling to be able to handle multiple clients at once. As it stands, a malicious client can temporarily take up resources from the server (3 second timeout) which isn't ideal.

Swell answered 29/6, 2019 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.