yowsup icon indicating copy to clipboard operation
yowsup copied to clipboard

Create a periodic server ping

Open tgalal opened this issue 12 years ago • 27 comments

A connection to WhatsApp server with no ongoing traffic is kept alive through 2 methods:

The problem is whatsApp does not always send us pings, and so the connection could be dropped without us realizing (connection might actually seem open until we try to send something and then it disconnects). Therefore we need to schedule a periodic ping to send to WhatsApp, say every 2 minutes for the following reasons:

  • For WhatsApp to keep our connection alive
  • For detecting that connection is gone and recovering quickly if it ever happens

tgalal avatar Dec 04 '14 02:12 tgalal

@tgalal how do you think it should be done?

I have an experimental implementation, a thread started from YowIqProtocolLayer on EVENT_STATE_CONNECTED and stopped on DISCONNECTED, it sends a ping every 120 seconds but does not wait or handle pong responses in any way.

galmeida avatar Dec 05 '14 17:12 galmeida

Yes this actually sounds good! :+1: And if we need we can then let the layer pass the pong to upper layers in case anyone is interested. Tricky part is actually detecting that pong when it arrives, because it would look like:

<iq from="s.whatsapp.net" id="1417801071-0" type="result"> </iq>

I guess the only way to identify it is by checking if it matches that sent ping id. And now suddenly appears to me that using protocolEntity.getTag is not the best way to detect type of received entity (in upper layers). Buy anyways, that's a different thing to worry about. Just having a pinger thread would be best for now :)

tgalal avatar Dec 05 '14 17:12 tgalal

Hi,

thats how I currently implemented it: In the xxx_layer.py:

   def onEvent(self, event):
        if event.getName() == ChatLayer.EVENT_SEND_MESSAGE:
            target, text = self.getProp(self.PROP_SEND_MSG_DETAILS)
            logger.debug('onEvent: Send out to WA [{0}] {1}'.format(target,text) )
            outgoingMessageProtocolEntity = TextMessageProtocolEntity(text, to=target)
            self.toLower(outgoingMessageProtocolEntity)
        elif event.getName() == ChatLayer.EVENT_PING:
            entity = PingIqProtocolEntity(to = YowConstants.DOMAIN)
            self.toLower(entity)
            self.pingcount += 1
            # print("Pingcount: {0}").format(self.pingcount)
            if self.pingcount >= 10:
                self.pingcount = 0
                logger.info('onEvent: Pingcount reached, do disconnect')
                self.disconnect_wa()
        elif event.getName() == ChatLayer.EVENT_TERMINATE:
            logger.info('onEvent: got ChatLayer.EVENT_TERMINATE')
            self.terminate = True
            self.disconnect_wa()
        elif event.getName() == YowNetworkLayer.EVENT_STATE_DISCONNECTED:
            logger.info('onEvent: Got EVENT_STATE_DISCONNECTED')
            if not self.terminate:
                time.sleep(10)
                logger.info('onEvent: Issueing EVENT_STATE_CONNECT')
                self.getStack().broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
        else:
            logger.error('onEvent: Unknown Event: %s' % event.getName())

    def disconnect_wa(self):
        logger.info('disconnect_wa: Trigger disconnect')
        self.getStack().broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))

    @ProtocolEntityCallback("iq")
    def onIq(self, entity):
        logger.debug('onIQ: Got iq (Ping reply)')
        if self.pingcount > 0:
            self.pingcount -= 1

And in xxx_stack.py

   stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))   #sending the connect signal

    pingcount = 0
    try:.
        while True:
            # Loop: - Let Yowsup libs run only 2 seconds,.
            #       - Check for incomming messages via ZMQ, if yes, pass them out.
            #         per event to whatsup_layer.py.
            #       - Every 10th iteraton, send a ping event wo whatsup_layer.py
            # logger.debug('(re)starting main loop')
            stack.loop(timeout=2, count=1) # Let the taskloop run one time for 2 seconds.

            (target, text) = zmq.poll_message()
            if target:
                stack.setProp(ChatLayer.PROP_SEND_MSG_DETAILS, (target, text))
                stack.broadcastEvent(YowLayerEvent(ChatLayer.EVENT_SEND_MESSAGE)).

            pingcount += 1

            if pingcount > 10:
                pingcount=0
                stack.broadcastEvent(YowLayerEvent(ChatLayer.EVENT_PING)).

            # Angst-delay
            time.sleep(0.1)

    # if CTRL-C, send a disconnect. Otherwise WA will let us not in the next time
    except KeyboardInterrupt:
        stack.broadcastEvent(YowLayerEvent(ChatLayer.EVENT_TERMINATE))   #sending the disconnect signal

Of course adding a own thread should be also possible, but since I have also other things to do in the main loop (Getting my external messages which I want to send out to WA), I had to do this main loop anyway.

ThomasRgbg avatar Dec 07 '14 13:12 ThomasRgbg

@ThomasRgbg I like your solution, I think it's better not to have an extra thread just for pinging.

do you plan to send a PR? If not I will implement something similar to what you did and send the PR.

galmeida avatar Dec 08 '14 10:12 galmeida

my only concern is that a stack generally shouldn't care what layers are there or what functionalities they provide, and this way we'll be mixing a lot of layer-specific stuff into a stack

tgalal avatar Dec 08 '14 10:12 tgalal

Well, this solution is not rocket science, more a workaround.

However, the name EVENT_PING is a bid misleading. EVENT_CHECKCONNECTION is maybe a better name.

And Tarek, how about adding the capability to create periodic called tasks in the layers ? The only reason why I do this in the _stack.py is because I need to call this periodically (in my example every 10th iteration).

Galmedia, give me a week to get more familiar with Git to be able to do a pull request. (And at some point I wanted to put my whole application - a bridge between WA and a XMPP server anyway to a own repo here)

ThomasRgbg avatar Dec 08 '14 21:12 ThomasRgbg

@tgalal, @ThomasRgbg I need this code running ASAP, so I will implement it today, when I get it done I will show you my code, and if you think it's ok I will send a PR, I will use a separate thread and probably a separate layer for that.

galmeida avatar Dec 09 '14 11:12 galmeida

I have a working solution on my local branch, it was implemented like this:

  1. Modified YowIqProtocolLayer to:
    1. include a 'waiting ping list'
    2. created an onEvent() that starts the ping thread on 'EVENT_STATE_CONNECTED' and stops the thread on 'EVENT_STATE_DISCONNECTED'
    3. modified recvIq() so it removes the id from 'waiting ping list' when ping response arrives.
    4. if the 'waiting ping list' reaches a pre-defines size it sends an 'YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT)'
  2. Created a 'YowPingThread'
    1. this thread, when started, sends pings to whatsapp servers on a pre-defined interval
    2. for every ping sent, it sends the stanza id to the 'wait ping list' on YowIqProtocolLayer

As a said this solution is working very well, but I'm not sure if this logic should be inside YowIqProtocolLayer.

I also plan to implement a waiting timeout for the ping, so we can disconnect not only if the list reaches a pre defined length but also if we don't receive a response for XX seconds/minutes

When I finished this I will send the PR

Thoughts? Comments?

galmeida avatar Dec 11 '14 11:12 galmeida

@galmeida this actually sounds great! One thing, after reading your comment I decided to add (and did) YowAuthenticationProtocolLayer.EVENT_AUTHED for that. It makes more sense in this situation more that EVENT_STATE_CONNECTED. But generally your solution def takes care of the problem. Thanks a lot!

tgalal avatar Dec 12 '14 01:12 tgalal

@galmeida Did you get round to sending the PR?

msshapira avatar Jan 11 '15 06:01 msshapira

+1 - would love to see a PR for this.

viksit avatar Jan 12 '15 01:01 viksit

I will send it today but probably @tgalal will recommend some changes.

galmeida avatar Jan 12 '15 09:01 galmeida

Thanks galmeida because I am unable to leave Online

rulogarcillan avatar Jan 12 '15 22:01 rulogarcillan

@galmeida in case you have a PR, perhaps you can put it on a gist somewhere, and I (or someone else) can help out in reviewing/editing it before a formal PR? To be clear, here's the issue I'm getting with the code you've put above:

Traceback (most recent call last):
  File "run.py", line 50, in <module>
    stack.loop(timeout=2, count=1) # Let the taskloop run one time for 2 seconds.
  File "build/bdist.macosx-10.9-x86_64/egg/yowsup/stacks/yowstack.py", line 57, in loop
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/asyncore.py", line 220, in loop
    poll_fun(timeout, map)
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/asyncore.py", line 145, in poll
    r, w, e = select.select(r, w, e, timeout)
select.error: (9, 'Bad file descriptor')

From the error, it looks like that the loop isn't getting terminated properly. Any ideas on how to fix this issue?

viksit avatar Jan 14 '15 03:01 viksit

I found a bug, I'll try to fix it and upload it somewhere

galmeida avatar Jan 14 '15 10:01 galmeida

code available here: https://github.com/galmeida/yowsup/tree/auto-ping, thanks for reviewing

galmeida avatar Jan 14 '15 12:01 galmeida

@galmeida @tgalal Question: Is the current Yowsup code takes care of sending auto-ping? If not, can you share sample code? I was sending ping myself in legacy code. Ping/Pong did not work and not relible if WhatsApp does not send ping.

kuldippatel avatar Jan 15 '15 08:01 kuldippatel

@kuldippatel, please check the link in the comment above yours

galmeida avatar Jan 15 '15 14:01 galmeida

I downloaded your layer stack but the attachment in n is where I have to call to automatically reconnect, I am new to python and I'm lost

In what I call stack to automatically connect to lose connection?

ERROR from yowsup.layers.protocol_iq import YowPingThread

ImportError: cannot import name YowPingThread

rulogarcillan avatar Jan 17 '15 18:01 rulogarcillan

Also whatsapp server timeout is 900 seconds, you can schedule to ping every 14 minutes safely.

CODeRUS avatar Feb 01 '15 07:02 CODeRUS