redis-py icon indicating copy to clipboard operation
redis-py copied to clipboard

Long running listen expires after certain days

Open sriman opened this issue 10 years ago • 12 comments

Hi Guys,

trigger = rtunnel.pubsub()
trigger.subscribe('PUSH_NOTIFICATION_GCM_REQUEST')

while True:
       try:
        for request in trigger.listen():
            write_stdout('\n\n Daemon Start: %s - %s UTC'% (request, datetime.utcnow()))

            if request['type'] == 'message':
                queue = rtunnel.lrange("PUSH_NOTIFICATION_GCM_QUEUE", 0, -1)

                for message in queue:
                    message = json.loads(message)

                    if self.sendPushNotification(message):
                        rtunnel.lpop("PUSH_NOTIFICATION_GCM_QUEUE")
                        write_stdout('\n\nSuccess: \n  message: %s at %s UTC'% (message, datetime.utcnow()))
                    else:
                        write_stderr('\n\nError: \n  message: %s at %s UTC'% (message, datetime.utcnow()))

            write_stdout('\n\n Daemon End - %s UTC'% datetime.utcnow())

    except(KeyboardInterrupt, SystemExit):
        sys.exit()
    except:
        write_stderr('\n\nException %s occured at %s UTC'% (traceback.format_exc(), datetime.utcnow()))

I am using AWS elasticCache and running this code using supervisor, What my problem is my listener is not listening if the listener is kept quiet for long (say 4 or 5 days). and once we look for sending messages after 4 or days using "publish" the listener is not working (i.e) not executing the code "trigger.listen():" .

will the listener timeouts after certain hours or days ?

But once we rerun the above code the listener is working perfectly(listening the publish message).

Actually we are having 2 nodes in AWS elastic cache, but for these pubsub we are using master node, so no chance of disconnecting.

We are using 2.10.3 version of redis-py.

Any help will be greatly appreciated.

sriman avatar Jan 20 '16 12:01 sriman

Hi @sriman,

redis-py won't explicitly close or time out a connection unless you specify a socket_timeout value when creating the client and/or connection. Your code above doesn't show how rtunnel is created, so I can't tell. But I'd look into that first.

If you aren't specifying a socket_timeout value, then it's likely that something is interrupting the connection at the network level. This could be a TCP timeout or a random hiccup within the AWS network. You could try using redis-py's TCP keepalive option by passing socket_keepalive=True.

andymccurdy avatar Jan 21 '16 04:01 andymccurdy

Thanks Andy for your valuable reply, will try this.

On Thu, Jan 21, 2016 at 10:09 AM, Andy McCurdy [email protected] wrote:

Hi @sriman https://github.com/sriman,

redis-py won't explicitly close or time out a connection unless you specify a socket_timeout value when creating the client and/or connection. Your code above doesn't show how rtunnel is created, so I can't tell. But I'd look into that first.

If you aren't specifying a socket_timeout value, then it's likely that something is interrupting the connection at the network level. This could be a TCP timeout or a random hiccup within the AWS network. You could try using redis-py's TCP keepalive option by passing socket_keepalive=True.

— Reply to this email directly or view it on GitHub https://github.com/andymccurdy/redis-py/issues/705#issuecomment-173449304 .

sriman

sriman avatar Jan 21 '16 05:01 sriman

my issue is similar but I am watching it and even if it is timing out the behavior is strange..

def __init__(self):
    self.ps = self.redis.master.pubsub(ignore_subscribe_messages=True)
    self.ps.psubscribe('endpoint|advertise')

def _watch_redis(self):
    toteser = 0
    while self.is_active:
        toteser = toteser + 1
        message = self.ps.get_message()
        if message:
            try:
                self._message_handler(message)
            except ex.RedisPubSubError:
                LOG.exception('redis pubsub error')
        else:
            time.sleep(0.01)

        if not toteser % 500:
            LOG.debug('watch redis thread is running \\o/')
            toteser = 0

I have these functions in a class and _watch_redis() is spawned in a thread. I assumed this thread was failing, so I set up the logging to ensure it was always running, and even linked that thread to another function to log and restart it if it dies. What I have noticed is that the _watch_redis() thread runs indefinitely, never being interrupted/restarted, and will log 'watch redis thread is running \o/' every 5 seconds forever, but it appears the client has failed silently and the call to self.ps.get_message() is silently ignoring the issue and returning None.

tr3buchet avatar Feb 05 '16 19:02 tr3buchet

@tr3buchet The behavior you're seeing is likely the cause of a network interruption. If something on your network is closing the tcp connection other than the client or server, the client will receive no indication.

Have you tried enabling any of the TCP keepalive options?

andymccurdy avatar Feb 05 '16 19:02 andymccurdy

@andymccurdy I'm grepping through your code to see how the socket keepalive and keepalive options work right this second actually.

tr3buchet avatar Feb 05 '16 19:02 tr3buchet

@andymccurdy sorry for the delay. I've got better information now

I've enabled TCP socket keepalive and set proper options, but the real issue for me was here.

get_message() is what I was using to check for messages and that select statement in can_read() ensured that nothing ever raises when the socket goes down/stale even while reading from the socket 100 times a second. can_read() will happily return None forever and our client has no way of knowing if there are actually no messages or if the socket is not readable because it has gone down/stale.

Instead of subclassing Connection and overloading can_read() so I can call get_message() and raise if the socket is broken, I switched to using listen() which calls can_read() with blocking=False which skips the select statement and eventually in the parser class just does a readline() on the socket buffer and should raise as expected if something is wrong with the socket. I still need test this however to make sure it does raise so my pubsub listener thread will die and I can handle restarting it appropriately.

Using TCP keepalive may help with whatever connection issues, but that is an environmental issue. It will not fix redis-py not raising when a PubSub client tries to read a stale socket with PubSub.get_message().

The way I am listening now is here. The thread running this function is linked to a function which logs appropriately, cleans up, and then starts a new listener thread should the original die for any reason. This is my redis client configuration. I made it because we have multiple code bases that need to our use sentinel backed redis master/slaves. I wanted the code bases to have a unified way of creating a client and managing connections. Managing the connections is important because we have tens of thousands of clients that on fairly large intervals fetch what they need from and then quickly/easily disconnect from redis altogether to greatly decrease the burden on the redis nodes. PubSub use isn't in the readme yet, but it works just fine as you can see.

tr3buchet avatar Feb 17 '16 23:02 tr3buchet

I attempted to use listen() with no keep alive options to see what would happen. After 48 hours or so, the pubsub object is no longer listening, and no uncaught exceptions were raised. I'm going to start subclassing at this point to replace blocks of code that are catching exceptions to see where things are getting lost.

tr3buchet avatar Feb 22 '16 16:02 tr3buchet

Are you using a socket_timeout? If so, I would expect you to see a TimeoutError raised when the connection gets severed. Without a socket_timeout you'll never see an error as listen() is ultimately blocked forever on socket.recv (or socket.recv_into) in one of the Parser classes.

Python sockets often don't get notified about a connection being severed while blocked trying to recv data.

andymccurdy avatar Feb 22 '16 17:02 andymccurdy

Actually, you'd also receive a TimeoutError when no messages are sent to the channels being listened on for the socket_timeout period as well.

If you use the retry_on_timeout option, the connection will attempt to reconnect and rejoin all the channels/patterns it was previously listening to, then re-attempt the recv. However, any messages sent between the disconnect/reconnect would be lost.

andymccurdy avatar Feb 22 '16 17:02 andymccurdy

If you use the retry_on_timeout option, the connection will attempt to reconnect and rejoin all the channels/patterns it was previously listening to, then re-attempt the recv. However, any messages sent between the disconnect/reconnect would be lost.

Is there a way of figuring out a disconnect/reconnect happened when blocking on listen() when using retry_on_timeout or should I disable this option and handle TimeoutError myself in this case?

charettes avatar Jun 02 '16 17:06 charettes

I am seeing a similar problem (using version 2.10.5) where pubsub connections aren't reconnecting even after explicit disconnections by the server, not a network timeout. In my test I start a listener to a Redis server on localhost, then restart the server and the listener no longer gets messages. I tried with retry_on_timeout=True in case it applied to non-timeout connection loss as well, but that didn't fix it. Anything I should dig into?

Update: figured it out. Filed as a separate issue: #816.

jkarneges avatar Jan 15 '17 05:01 jkarneges

This issue is marked stale. It will be closed in 30 days if it is not updated.

github-actions[bot] avatar Jul 27 '20 00:07 github-actions[bot]