Creating A CoordinatorΒΆ
The principal object provided by tooz is the coordinator. It allows you to use various features, such as group membership, leader election or distributed locking.
The features provided by tooz coordinator are implemented using different drivers. When creating a coordinator, you need to specify which back-end driver you want it to use. Different drivers may provide different set of capabilities.
If a driver does not support a feature, it will raise a
NotImplemented
exception.
This example program loads a basic coordinator using the ZooKeeper based driver.
from tooz import coordination
coordinator = coordination.get_coordinator('zake://', b'host-1')
coordinator.start()
coordinator.stop()
The second argument passed to the coordinator must be a unique identifier identifying the running program.
After the coordinator is created, it can be used to use the various features provided.
In order to keep the connection to the coordination server active, you must
call regularly the heartbeat()
method. This will ensure that the coordinator is not considered dead by
other program participating in the coordination.
import time
from tooz import coordination
ALIVE_TIME = 5
coordinator = coordination.get_coordinator('zake://', b'host-1')
coordinator.start()
start = time.time()
while time.time() - start < ALIVE_TIME:
coordinator.heartbeat()
time.sleep(0.1)
coordinator.stop()
We use a pretty simple mechanism in this example to send a heartbeat every once in a while, but depending on your application, you may want to send the heartbeat at different moment or intervals.
Note that certain drivers, such as memcached are heavily based on timeout, so the interval used to run the heartbeat is important.