I have a very strange case with Python Kazoo library. What I did in my below code is -
As soon as I connect to Zookeeper using kazoo library, I create an ephemeral node and then keep a watch on some other node and then I keep on running the program forever in an infinite loop.. I have also added a listener to Zookeeper as well which will monitor the state as well.
Everything is working perfectly fine for me, ephemeral node is up, watch on my znode is also working fine...
Sometimes, I am seeing pretty weird behaviour. As I mentioned above, I have added a listener to zookeeper which will monitor the state and I have a print statement as well.. I always see, those print statement getting printed out as `Lost`, `Suspended` , `Connected` and after that my ephemeral nodes dies up and my watch on the znode doesn't work either.
Below is my code -
#!/usr/bin/python
from kazoo.client import KazooClient
from kazoo.client import KazooState
from kazoo.protocol.states import EventType
def watch_host(event):
print event
def my_listener(state):
if state == KazooState.LOST:
# Register somewhere that the session was lost
print "Lost"
elif state == KazooState.SUSPENDED:
# Handle being disconnected from Zookeeper
print "Suspended"
else:
# Handle being connected/reconnected to Zookeeper
print "Being Connected/Reconnected"
zk = KazooClient(hosts='
127.0.0.1:2181')
zk.start()
zk.add_listener(my_listener)
# start an ephemeral node
zk.create("/my/example/h0", b"some value", None, True)
# put a watch on my znode
children = zk.get_children("/my/example/test1", watch=watch_host)
while True:
time.sleep(5)
Is there any way to overcome this problem? I want that whenever my Zookeeper state changes to `Lost` or `Suspended` or `Connected`. I want to have my ephemeral node up by creating it again (if this is the right approach) and my watch on the znode also be working as well always. Because I will be running my program forever so for whatever reason if the Zookeeper state changes and it gets connected back again automatically, then I need to make sure my ephemeral node is also up and my watches on the znode also start working automatically..
Currently my ephemeral dies up and watches also doesn't work if the state is changing automatically..
Any idea how to overcome this problem?