In
Chapter 3 - Advanced Request-Reply Patterns and
Chapter 4 - Reliable Request-Reply Patterns we looked at advanced use of ZeroMQ’s request-reply pattern. If you managed to digest all that, congratulations. In this chapter we’ll focus on publish-subscribe and extend ZeroMQ’s core pub-sub pattern with higher-level patterns for performance, reliability, state distribution, and monitoring.
We’ll cover:
When to use publish-subscribe
How to handle too-slow subscribers (the Suicidal Snail pattern)
How to design high-speed subscribers (the Black Box pattern)
How to monitor a pub-sub network (the Espresso pattern)
How to build a shared key-value store (the Clone pattern)
How to use reactors to simplify complex servers
How to use the Binary Star pattern to add failover to a server
ZeroMQ’s low-level patterns have their different characters. Pub-sub addresses an old messaging problem, which is multicast or group messaging. It has that unique mix of meticulous simplicity and brutal indifference that characterizes ZeroMQ. It’s worth understanding the trade-offs that pub-sub makes, how these benefit us, and how we can work around them if needed.
First, PUB sends each message to “all of many”, whereas PUSH and DEALER rotate messages to “one of many”. You cannot simply replace PUSH with PUB or vice versa and hope that things will work. This bears repeating because people seem to quite often suggest doing this.
More profoundly, pub-sub is aimed at scalability. This means large volumes of data, sent rapidly to many recipients. If you need millions of messages per second sent to thousands of points, you’ll appreciate pub-sub a lot more than if you need a few messages a second sent to a handful of recipients.
To get scalability, pub-sub uses the same trick as push-pull, which is to get rid of back-chatter. This means that recipients don’t talk back to senders. There are some exceptions, e.g., SUB sockets will send subscriptions to PUB sockets, but it’s anonymous and infrequent.
Killing back-chatter is essential to real scalability. With pub-sub, it’s how the pattern can map cleanly to the PGM multicast protocol, which is handled by the network switch. In other words, subscribers don’t connect to the publisher at all, they connect to a multicast group on the switch, to which the publisher sends its messages.
When we remove back-chatter, our overall message flow becomes much simpler, which lets us make simpler APIs, simpler protocols, and in general reach many more people. But we also remove any possibility to coordinate senders and receivers. What this means is:
Publishers can’t tell when subscribers are successfully connected, both on initial connections, and on reconnections after network failures.
Subscribers can’t tell publishers anything that would allow publishers to control the rate of messages they send. Publishers only have one setting, which is full-speed, and subscribers must either keep up or lose messages.
Publishers can’t tell when subscribers have disappeared due to processes crashing, networks breaking, and so on.
The downside is that we actually need all of these if we want to do reliable multicast. The ZeroMQ pub-sub pattern will lose messages arbitrarily when a subscriber is connecting, when a network failure occurs, or just if the subscriber or network can’t keep up with the publisher.
The upside is that there are many use cases where almost reliable multicast is just fine. When we need this back-chatter, we can either switch to using ROUTER-DEALER (which I tend to do for most normal volume cases), or we can add a separate channel for synchronization (we’ll see an example of this later in this chapter).
Pub-sub is like a radio broadcast; you miss everything before you join, and then how much information you get depends on the quality of your reception. Surprisingly, this model is useful and widespread because it maps perfectly to real world distribution of information. Think of Facebook and Twitter, the BBC World Service, and the sports results.
As we did for request-reply, let’s define reliability in terms of what can go wrong. Here are the classic failure cases for pub-sub:
Subscribers join late, so they miss messages the server already sent.
Subscribers can fetch messages too slowly, so queues build up and then overflow.
Subscribers can drop off and lose messages while they are away.
Subscribers can crash and restart, and lose whatever data they already received.
Networks can become overloaded and drop data (specifically, for PGM).
Networks can become too slow, so publisher-side queues overflow and publishers crash.
A lot more can go wrong but these are the typical failures we see in a realistic system. Since v3.x, ZeroMQ forces default limits on its internal buffers (the so-called high-water mark or HWM), so publisher crashes are rarer unless you deliberately set the HWM to infinite.
All of these failure cases have answers, though not always simple ones. Reliability requires complexity that most of us don’t need, most of the time, which is why ZeroMQ doesn’t attempt to provide it out of the box (even if there was one global design for reliability, which there isn’t).
Let’s start this chapter by looking at a way to trace pub-sub networks. In
Chapter 2 - Sockets and Patterns we saw a simple proxy that used these to do transport bridging. The zmq_proxy() method has three arguments: a frontend and backend socket that it bridges together, and a capture socket to which it will send all messages.
packageguide;
importjava.util.Random;
importorg.zeromq.*;
importorg.zeromq.ZMQ.Socket;
importorg.zeromq.ZThread.IAttachedRunnable;
// Espresso Pattern
// This shows how to capture data using a pub-sub proxy
publicclassespresso
{
// The subscriber thread requests messages starting with
// A and B, then reads and counts incoming messages.
privatestaticclassSubscriberimplements IAttachedRunnable
{
@Overridepublicvoidrun(Object[] args, ZContext ctx, Socket pipe)
{
// Subscribe to "A" and "B"
Socket subscriber = ctx.createSocket(SocketType.SUB);
subscriber.connect("tcp://localhost:6001");
subscriber.subscribe("A".getBytes(ZMQ.CHARSET));
subscriber.subscribe("B".getBytes(ZMQ.CHARSET));
int count = 0;
while (count < 5) {
String string = subscriber.recvStr();
if (string == null)
break; // Interrupted
count++;
}
ctx.destroySocket(subscriber);
}
}
// .split publisher thread
// The publisher sends random messages starting with A-J:
privatestaticclassPublisherimplements IAttachedRunnable
{
@Overridepublicvoidrun(Object[] args, ZContext ctx, Socket pipe)
{
Socket publisher = ctx.createSocket(SocketType.PUB);
publisher.bind("tcp://*:6000");
Random rand = new Random(System.currentTimeMillis());
while (!Thread.currentThread().isInterrupted()) {
String string = String.format("%c-%05d", 'A' + rand.nextInt(10), rand.nextInt(100000));
if (!publisher.send(string))
break; // Interrupted
try {
Thread.sleep(100); // Wait for 1/10th second
}
catch (InterruptedException e) {
}
}
ctx.destroySocket(publisher);
}
}
// .split listener thread
// The listener receives all messages flowing through the proxy, on its
// pipe. In CZMQ, the pipe is a pair of ZMQ_PAIR sockets that connect
// attached child threads. In other languages your mileage may vary:
privatestaticclassListenerimplements IAttachedRunnable
{
@Overridepublicvoidrun(Object[] args, ZContext ctx, Socket pipe)
{
// Print everything that arrives on pipe
while (true) {
ZFrame frame = ZFrame.recvFrame(pipe);
if (frame == null)
break; // Interrupted
frame.print(null);
frame.destroy();
}
}
}
// .split main thread
// The main task starts the subscriber and publisher, and then sets
// itself up as a listening proxy. The listener runs as a child thread:
publicstaticvoidmain(String[] argv)
{
try (ZContext ctx = new ZContext()) {
// Start child threads
ZThread.fork(ctx, new Publisher());
ZThread.fork(ctx, new Subscriber());
Socket subscriber = ctx.createSocket(SocketType.XSUB);
subscriber.connect("tcp://localhost:6000");
Socket publisher = ctx.createSocket(SocketType.XPUB);
publisher.bind("tcp://*:6001");
Socket listener = ZThread.fork(ctx, new Listener());
ZMQ.proxy(subscriber, publisher, listener);
System.out.println(" interrupted");
// NB: child threads exit here when the context is closed
}
}
}
# Espresso Pattern# This shows how to capture data using a pub-sub proxy#importtimefromrandomimport randint
fromstringimport ascii_uppercase as uppercase
fromthreadingimport Thread
importzmqfromzmq.devicesimport monitored_queue
fromzhelpersimport zpipe
# The subscriber thread requests messages starting with# A and B, then reads and counts incoming messages.defsubscriber_thread():
ctx = zmq.Context.instance()
# Subscribe to "A" and "B"
subscriber = ctx.socket(zmq.SUB)
subscriber.connect("tcp://localhost:6001")
subscriber.setsockopt(zmq.SUBSCRIBE, b"A")
subscriber.setsockopt(zmq.SUBSCRIBE, b"B")
count = 0while count < 5:
try:
msg = subscriber.recv_multipart()
except zmq.ZMQError as e:
if e.errno == zmq.ETERM:
break# Interruptedelse:
raise
count += 1print ("Subscriber received %d messages" % count)
# publisher thread# The publisher sends random messages starting with A-J:defpublisher_thread():
ctx = zmq.Context.instance()
publisher = ctx.socket(zmq.PUB)
publisher.bind("tcp://*:6000")
while True:
string = "%s-%05d" % (uppercase[randint(0,10)], randint(0,100000))
try:
publisher.send(string.encode('utf-8'))
except zmq.ZMQError as e:
if e.errno == zmq.ETERM:
break# Interruptedelse:
raise
time.sleep(0.1) # Wait for 1/10th second# listener thread# The listener receives all messages flowing through the proxy, on its# pipe. Here, the pipe is a pair of ZMQ_PAIR sockets that connects# attached child threads via inproc. In other languages your mileage may vary:deflistener_thread (pipe):
# Print everything that arrives on pipewhile True:
try:
print (pipe.recv_multipart())
except zmq.ZMQError as e:
if e.errno == zmq.ETERM:
break# Interrupted# main thread# The main task starts the subscriber and publisher, and then sets# itself up as a listening proxy. The listener runs as a child thread:defmain ():
# Start child threads
ctx = zmq.Context.instance()
p_thread = Thread(target=publisher_thread)
s_thread = Thread(target=subscriber_thread)
p_thread.start()
s_thread.start()
pipe = zpipe(ctx)
subscriber = ctx.socket(zmq.XSUB)
subscriber.connect("tcp://localhost:6000")
publisher = ctx.socket(zmq.XPUB)
publisher.bind("tcp://*:6001")
l_thread = Thread(target=listener_thread, args=(pipe[1],))
l_thread.start()
try:
monitored_queue(subscriber, publisher, pipe[0], b'pub', b'sub')
except KeyboardInterrupt:
print ("Interrupted")
del subscriber, publisher, pipe
ctx.term()
if __name__ == '__main__':
main()
Espresso works by creating a listener thread that reads a PAIR socket and prints anything it gets. That PAIR socket is one end of a pipe; the other end (another PAIR) is the socket we pass to zmq_proxy(). In practice, you’d filter interesting messages to get the essence of what you want to track (hence the name of the pattern).
The subscriber thread subscribes to “A” and “B”, receives five messages, and then destroys its socket. When you run the example, the listener prints two subscription messages, five data messages, two unsubscribe messages, and then silence:
This shows neatly how the publisher socket stops sending data when there are no subscribers for it. The publisher thread is still sending messages. The socket just drops them silently.
If you’ve used commercial pub-sub systems, you may be used to some features that are missing in the fast and cheerful ZeroMQ pub-sub model. One of these is last value caching (LVC). This solves the problem of how a new subscriber catches up when it joins the network. The theory is that publishers get notified when a new subscriber joins and subscribes to some specific topics. The publisher can then rebroadcast the last message for those topics.
I’ve already explained why publishers don’t get notified when there are new subscribers, because in large pub-sub systems, the volumes of data make it pretty much impossible. To make really large-scale pub-sub networks, you need a protocol like PGM that exploits an upscale Ethernet switch’s ability to multicast data to thousands of subscribers. Trying to do a TCP unicast from the publisher to each of thousands of subscribers just doesn’t scale. You get weird spikes, unfair distribution (some subscribers getting the message before others), network congestion, and general unhappiness.
PGM is a one-way protocol: the publisher sends a message to a multicast address at the switch, which then rebroadcasts that to all interested subscribers. The publisher never sees when subscribers join or leave: this all happens in the switch, which we don’t really want to start reprogramming.
However, in a lower-volume network with a few dozen subscribers and a limited number of topics, we can use TCP and then the XSUB and XPUB sockets do talk to each other as we just saw in the Espresso pattern.
Can we make an LVC using ZeroMQ? The answer is yes, if we make a proxy that sits between the publisher and subscribers; an analog for the PGM switch, but one we can program ourselves.
I’ll start by making a publisher and subscriber that highlight the worst case scenario. This publisher is pathological. It starts by immediately sending messages to each of a thousand topics, and then it sends one update a second to a random topic. A subscriber connects, and subscribes to a topic. Without LVC, a subscriber would have to wait an average of 500 seconds to get any data. To add some drama, let’s pretend there’s an escaped convict called Gregor threatening to rip the head off Roger the toy bunny if we can’t fix that 8.3 minutes’ delay.
Here’s the publisher code. Note that it has the command line option to connect to some address, but otherwise binds to an endpoint. We’ll use this later to connect to our last value cache:
// Pathological publisher
// Sends out 1,000 topics and then one random update per second
#include"czmq.h"intmain (int argc, char *argv [])
{
zctx_t *context = zctx_new ();
void *publisher = zsocket_new (context, ZMQ_PUB);
if (argc == 2)
zsocket_bind (publisher, argv [1]);
else
zsocket_bind (publisher, "tcp://*:5556");
// Ensure subscriber connection has time to complete
sleep (1);
// Send out all 1,000 topic messages
int topic_nbr;
for (topic_nbr = 0; topic_nbr < 1000; topic_nbr++) {
zstr_sendfm (publisher, "%03d", topic_nbr);
zstr_send (publisher, "Save Roger");
}
// Send one random update per second
srandom ((unsigned) time (NULL));
while (!zctx_interrupted) {
sleep (1);
zstr_sendfm (publisher, "%03d", randof (1000));
zstr_send (publisher, "Off with his head!");
}
zctx_destroy (&context);
return0;
}
pathopub: Pathologic Publisher in C++
// Pathological publisher
// Sends out 1,000 topics and then one random update per second
#include<thread>#include<chrono>#include"zhelpers.hpp"intmain (int argc, char *argv [])
{
zmq::context_t context(1);
zmq::socket_t publisher(context, ZMQ_PUB);
// Initialize random number generator
srandom ((unsigned) time (NULL));
if (argc == 2)
publisher.bind(argv [1]);
else
publisher.bind("tcp://*:5556");
// Ensure subscriber connection has time to complete
std::this_thread::sleep_for(std::chrono::seconds(1));
// Send out all 1,000 topic messages
int topic_nbr;
for (topic_nbr = 0; topic_nbr < 1000; topic_nbr++) {
std::stringstream ss;
ss << std::dec << std::setw(3) << std::setfill('0') << topic_nbr;
s_sendmore (publisher, ss.str());
s_send (publisher, std::string("Save Roger"));
}
// Send one random update per second
while (1) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::stringstream ss;
ss << std::dec << std::setw(3) << std::setfill('0') << within(1000);
s_sendmore (publisher, ss.str());
s_send (publisher, std::string("Off with his head!"));
}
return0;
}
packageguide;
importjava.util.Random;
importorg.zeromq.SocketType;
importorg.zeromq.ZContext;
importorg.zeromq.ZMQ;
importorg.zeromq.ZMQ.Socket;
// Pathological publisher
// Sends out 1,000 topics and then one random update per second
publicclasspathopub
{
publicstaticvoidmain(String[] args) throws Exception
{
try (ZContext context = new ZContext()) {
Socket publisher = context.createSocket(SocketType.PUB);
if (args.length == 1)
publisher.connect(args[0]);
else publisher.bind("tcp://*:5556");
// Ensure subscriber connection has time to complete
Thread.sleep(1000);
// Send out all 1,000 topic messages
int topicNbr;
for (topicNbr = 0; topicNbr < 1000; topicNbr++) {
publisher.send(String.format("%03d", topicNbr), ZMQ.SNDMORE);
publisher.send("Save Roger");
}
// Send one random update per second
Random rand = new Random(System.currentTimeMillis());
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(1000);
publisher.send(
String.format("%03d", rand.nextInt(1000)), ZMQ.SNDMORE
);
publisher.send("Off with his head!");
}
}
}
}
## Pathological publisher# Sends out 1,000 topics and then one random update per second#importsysimporttimefromrandomimport randint
importzmqdefmain(url=None):
ctx = zmq.Context.instance()
publisher = ctx.socket(zmq.PUB)
if url:
publisher.bind(url)
else:
publisher.bind("tcp://*:5556")
# Ensure subscriber connection has time to complete
time.sleep(1)
# Send out all 1,000 topic messagesfor topic_nbr inrange(1000):
publisher.send_multipart([
b"%03d" % topic_nbr,
b"Save Roger",
])
while True:
# Send one random update per secondtry:
time.sleep(1)
publisher.send_multipart([
b"%03d" % randint(0,999),
b"Off with his head!",
])
except KeyboardInterrupt:
print"interrupted"breakif __name__ == '__main__':
main(sys.argv[1] iflen(sys.argv) > 1else None)
#!/usr/bin/env ruby## Pathological publisher# Sends out 1,000 topics and then one random update per second#require'ffi-rzmq'
context = ZMQ::Context.new
TOPIC_COUNT = 1_000
publisher = context.socket(ZMQ::PUB)
ifARGV[0]
publisher.bind(ARGV[0])
else
publisher.bind("tcp://*:5556")
end# Ensure subscriber connection has time to completesleep1TOPIC_COUNT.times do |n|
topic = "%03d" % [n]
publisher.send_strings([topic, "Save Roger"])
endloopdosleep1
topic = "%03d" % [rand(1000)]
publisher.send_strings([topic, "Off with his head!"])
end
## Pathological subscriber# Subscribes to one random topic and prints received messages#importsysimporttimefromrandomimport randint
importzmqdefmain(url=None):
ctx = zmq.Context.instance()
subscriber = ctx.socket(zmq.SUB)
if url is None:
url = "tcp://localhost:5556"
subscriber.connect(url)
subscription = b"%03d" % randint(0,999)
subscriber.setsockopt(zmq.SUBSCRIBE, subscription)
while True:
topic, data = subscriber.recv_multipart()
assert topic == subscription
print data
if __name__ == '__main__':
main(sys.argv[1] iflen(sys.argv) > 1else None)
#!/usr/bin/env ruby## Pathological subscriber# Subscribes to one random topic and prints received messages#require'ffi-rzmq'
context = ZMQ::Context.new
subscriber = context.socket(ZMQ::SUB)
subscriber.connect(ARGV[0] || "tcp://localhost:5556")
topic = "%03d" % [rand(1000)]
subscriber.setsockopt(ZMQ::SUBSCRIBE, topic)
loopdo
subscriber.recv_strings(parts = [])
topic, data = parts
puts"#{topic}: #{data}"end
Try building and running these: first the subscriber, then the publisher. You’ll see the subscriber reports getting “Save Roger” as you’d expect:
./pathosub &
./pathopub
It’s when you run a second subscriber that you understand Roger’s predicament. You have to leave it an awful long time before it reports getting any data. So, here’s our last value cache. As I promised, it’s a proxy that binds to two sockets and then handles messages on both:
// Last value cache
// Uses XPUB subscription messages to re-send data
#include"czmq.h"intmain (void)
{
zctx_t *context = zctx_new ();
void *frontend = zsocket_new (context, ZMQ_SUB);
zsocket_connect (frontend, "tcp://*:5557");
void *backend = zsocket_new (context, ZMQ_XPUB);
zsocket_bind (backend, "tcp://*:5558");
// Subscribe to every single topic from publisher
zsocket_set_subscribe (frontend, "");
// Store last instance of each topic in a cache
zhash_t *cache = zhash_new ();
// .split main poll loop
// We route topic updates from frontend to backend, and
// we handle subscriptions by sending whatever we cached,
// if anything:
while (true) {
zmq_pollitem_t items [] = {
{ frontend, 0, ZMQ_POLLIN, 0 },
{ backend, 0, ZMQ_POLLIN, 0 }
};
if (zmq_poll (items, 2, 1000 * ZMQ_POLL_MSEC) == -1)
break; // Interrupted
// Any new topic data we cache and then forward
if (items [0].revents & ZMQ_POLLIN) {
char *topic = zstr_recv (frontend);
char *current = zstr_recv (frontend);
if (!topic)
break;
char *previous = zhash_lookup (cache, topic);
if (previous) {
zhash_delete (cache, topic);
free (previous);
}
zhash_insert (cache, topic, current);
zstr_sendm (backend, topic);
zstr_send (backend, current);
free (topic);
}
// .split handle subscriptions
// When we get a new subscription, we pull data from the cache:
if (items [1].revents & ZMQ_POLLIN) {
zframe_t *frame = zframe_recv (backend);
if (!frame)
break;
// Event is one byte 0=unsub or 1=sub, followed by topic
byte *event = zframe_data (frame);
if (event [0] == 1) {
char *topic = zmalloc (zframe_size (frame));
memcpy (topic, event + 1, zframe_size (frame) - 1);
printf ("Sending cached topic %s\n", topic);
char *previous = zhash_lookup (cache, topic);
if (previous) {
zstr_sendm (backend, topic);
zstr_send (backend, previous);
}
free (topic);
}
zframe_destroy (&frame);
}
}
zctx_destroy (&context);
zhash_destroy (&cache);
return0;
}
lvcache: Last Value Caching Proxy in C++
// Last value cache
// Uses XPUB subscription messages to re-send data
#include<unordered_map>#include"zhelpers.hpp"intmain ()
{
zmq::context_t context(1);
zmq::socket_t frontend(context, ZMQ_SUB);
zmq::socket_t backend(context, ZMQ_XPUB);
frontend.connect("tcp://localhost:5557");
backend.bind("tcp://*:5558");
// Subscribe to every single topic from publisher
frontend.set(zmq::sockopt::subscribe, "");
// Store last instance of each topic in a cache
std::unordered_map<std::string, std::string> cache_map;
zmq::pollitem_t items[2] = {
{ static_cast<void*>(frontend), 0, ZMQ_POLLIN, 0 },
{ static_cast<void*>(backend), 0, ZMQ_POLLIN, 0 }
};
// .split main poll loop
// We route topic updates from frontend to backend, and we handle
// subscriptions by sending whatever we cached, if anything:
while (1)
{
if (zmq::poll(items, 2, 1000) == -1)
break; // Interrupted
// Any new topic data we cache and then forward
if (items[0].revents & ZMQ_POLLIN)
{
std::string topic = s_recv(frontend);
std::string data = s_recv(frontend);
if (topic.empty())
break;
cache_map[topic] = data;
s_sendmore(backend, topic);
s_send(backend, data);
}
// .split handle subscriptions
// When we get a new subscription, we pull data from the cache:
if (items[1].revents & ZMQ_POLLIN) {
zmq::message_t msg;
backend.recv(&msg);
if (msg.size() == 0)
break;
// Event is one byte 0=unsub or 1=sub, followed by topic
uint8_t *event = (uint8_t *)msg.data();
if (event[0] == 1) {
std::string topic((char *)(event+1), msg.size()-1);
auto i = cache_map.find(topic);
if (i != cache_map.end())
{
s_sendmore(backend, topic);
s_send(backend, i->second);
}
}
}
}
return0;
}
packageguide;
importjava.util.HashMap;
importjava.util.Map;
importorg.zeromq.SocketType;
importorg.zeromq.ZContext;
importorg.zeromq.ZFrame;
importorg.zeromq.ZMQ;
importorg.zeromq.ZMQ.Poller;
importorg.zeromq.ZMQ.Socket;
// Last value cache
// Uses XPUB subscription messages to re-send data
publicclasslvcache
{
publicstaticvoidmain(String[] args)
{
try (ZContext context = new ZContext()) {
Socket frontend = context.createSocket(SocketType.SUB);
frontend.bind("tcp://*:5557");
Socket backend = context.createSocket(SocketType.XPUB);
backend.bind("tcp://*:5558");
// Subscribe to every single topic from publisher
frontend.subscribe(ZMQ.SUBSCRIPTION_ALL);
// Store last instance of each topic in a cache
Map<String, String> cache = new HashMap<String, String>();
Poller poller = context.createPoller(2);
poller.register(frontend, Poller.POLLIN);
poller.register(backend, Poller.POLLIN);
// .split main poll loop
// We route topic updates from frontend to backend, and we handle
// subscriptions by sending whatever we cached, if anything:
while (true) {
if (poller.poll(1000) == -1)
break; // Interrupted
// Any new topic data we cache and then forward
if (poller.pollin(0)) {
String topic = frontend.recvStr();
String current = frontend.recvStr();
if (topic == null)
break;
cache.put(topic, current);
backend.sendMore(topic);
backend.send(current);
}
// .split handle subscriptions
// When we get a new subscription, we pull data from the cache:
if (poller.pollin(1)) {
ZFrame frame = ZFrame.recvFrame(backend);
if (frame == null)
break;
// Event is one byte 0=unsub or 1=sub, followed by topic
byte[] event = frame.getData();
if (event[0] == 1) {
String topic = new String(event, 1, event.length - 1, ZMQ.CHARSET);
System.out.printf("Sending cached topic %s\n", topic);
String previous = cache.get(topic);
if (previous != null) {
backend.sendMore(topic);
backend.send(previous);
}
}
frame.destroy();
}
}
}
}
}
## Last value cache# Uses XPUB subscription messages to re-send data#importzmqdefmain():
ctx = zmq.Context.instance()
frontend = ctx.socket(zmq.SUB)
frontend.connect("tcp://*:5557")
backend = ctx.socket(zmq.XPUB)
backend.bind("tcp://*:5558")
# Subscribe to every single topic from publisher
frontend.setsockopt(zmq.SUBSCRIBE, b"")
# Store last instance of each topic in a cache
cache = {}
# main poll loop# We route topic updates from frontend to backend, and# we handle subscriptions by sending whatever we cached,# if anything:
poller = zmq.Poller()
poller.register(frontend, zmq.POLLIN)
poller.register(backend, zmq.POLLIN)
while True:
try:
events = dict(poller.poll(1000))
except KeyboardInterrupt:
print("interrupted")
break# Any new topic data we cache and then forwardif frontend in events:
msg = frontend.recv_multipart()
topic, current = msg
cache[topic] = current
backend.send_multipart(msg)
# handle subscriptions# When we get a new subscription we pull data from the cache:if backend in events:
event = backend.recv()
# Event is one byte 0=unsub or 1=sub, followed by topicif event[0] == 1:
topic = event[1:]
if topic in cache:
print ("Sending cached topic %s" % topic)
backend.send_multipart([ topic, cache[topic] ])
if __name__ == '__main__':
main()
#!/usr/bin/env ruby## Last value cache# Uses XPUB subscription messages to re-send data#require'ffi-rzmq'
context = ZMQ::Context.new
frontend = context.socket(ZMQ::SUB)
frontend.connect("tcp://*:5557")
backend = context.socket(ZMQ::XPUB)
backend.bind("tcp://*:5558")
# Subscribe to every single topic from publisher
frontend.setsockopt(ZMQ::SUBSCRIBE, "")
# Store last instance of each topic in a cache
cache = {}
# We route topic updates from frontend to backend, and we handle subscriptions# by sending whatever we cached, if anything:
poller = ZMQ::Poller.new
[frontend, backend].each { |sock| poller.register_readable sock }
loopdo
poller.poll(1000)
poller.readables.each do |sock|
if sock == frontend
# Any new topic data we cache and then forward
frontend.recv_strings(parts = [])
topic, data = parts
cache[topic] = data
backend.send_strings(parts)
elsif sock == backend
# When we get a new subscription we pull data from the cache:
backend.recv_strings(parts = [])
event, _ = parts
# Event is one byte 0=unsub or 1=sub, followed by topicif event[0].ord == 1
topic = event[1..-1]
puts"Sending cached topic #{topic}"
previous = cache[topic]
backend.send_strings([topic, previous]) if previous
endendendend
And now run as many instances of the subscriber as you want to try, each time connecting to the proxy on port 5558:
./pathosub tcp://localhost:5558
Each subscriber happily reports “Save Roger”, and Gregor the Escaped Convict slinks back to his seat for dinner and a nice cup of hot milk, which is all he really wanted in the first place.
One note: by default, the XPUB socket does not report duplicate subscriptions, which is what you want when you’re naively connecting an XPUB to an XSUB. Our example sneakily gets around this by using random topics so the chance of it not working is one in a million. In a real LVC proxy, you’ll want to use the ZMQ_XPUB_VERBOSE option that we implement in
Chapter 6 - The ZeroMQ Community as an exercise.
A common problem you will hit when using the pub-sub pattern in real life is the slow subscriber. In an ideal world, we stream data at full speed from publishers to subscribers. In reality, subscriber applications are often written in interpreted languages, or just do a lot of work, or are just badly written, to the extent that they can’t keep up with publishers.
How do we handle a slow subscriber? The ideal fix is to make the subscriber faster, but that might take work and time. Some of the classic strategies for handling a slow subscriber are:
Queue messages on the publisher. This is what Gmail does when I don’t read my email for a couple of hours. But in high-volume messaging, pushing queues upstream has the thrilling but unprofitable result of making publishers run out of memory and crash–especially if there are lots of subscribers and it’s not possible to flush to disk for performance reasons.
Queue messages on the subscriber. This is much better, and it’s what ZeroMQ does by default if the network can keep up with things. If anyone’s going to run out of memory and crash, it’ll be the subscriber rather than the publisher, which is fair. This is perfect for “peaky” streams where a subscriber can’t keep up for a while, but can catch up when the stream slows down. However, it’s no answer to a subscriber that’s simply too slow in general.
Stop queuing new messages after a while. This is what Gmail does when my mailbox overflows its precious gigabytes of space. New messages just get rejected or dropped. This is a great strategy from the perspective of the publisher, and it’s what ZeroMQ does when the publisher sets a HWM. However, it still doesn’t help us fix the slow subscriber. Now we just get gaps in our message stream.
Punish slow subscribers with disconnect. This is what Hotmail (remember that?) did when I didn’t log in for two weeks, which is why I was on my fifteenth Hotmail account when it hit me that there was perhaps a better way. It’s a nice brutal strategy that forces subscribers to sit up and pay attention and would be ideal, but ZeroMQ doesn’t do this, and there’s no way to layer it on top because subscribers are invisible to publisher applications.
None of these classic strategies fit, so we need to get creative. Rather than disconnect the publisher, let’s convince the subscriber to kill itself. This is the Suicidal Snail pattern. When a subscriber detects that it’s running too slowly (where “too slowly” is presumably a configured option that really means “so slowly that if you ever get here, shout really loudly because I need to know, so I can fix this!"), it croaks and dies.
How can a subscriber detect this? One way would be to sequence messages (number them in order) and use a HWM at the publisher. Now, if the subscriber detects a gap (i.e., the numbering isn’t consecutive), it knows something is wrong. We then tune the HWM to the “croak and die if you hit this” level.
There are two problems with this solution. One, if we have many publishers, how do we sequence messages? The solution is to give each publisher a unique ID and add that to the sequencing. Second, if subscribers use ZMQ_SUBSCRIBE filters, they will get gaps by definition. Our precious sequencing will be for nothing.
Some use cases won’t use filters, and sequencing will work for them. But a more general solution is that the publisher timestamps each message. When a subscriber gets a message, it checks the time, and if the difference is more than, say, one second, it does the “croak and die” thing, possibly firing off a squawk to some operator console first.
The Suicide Snail pattern works especially when subscribers have their own clients and service-level agreements and need to guarantee certain maximum latencies. Aborting a subscriber may not seem like a constructive way to guarantee a maximum latency, but it’s the assertion model. Abort today, and the problem will be fixed. Allow late data to flow downstream, and the problem may cause wider damage and take longer to appear on the radar.
// Suicidal Snail
#include"czmq.h"// This is our subscriber. It connects to the publisher and subscribes
// to everything. It sleeps for a short time between messages to
// simulate doing too much work. If a message is more than one second
// late, it croaks.
#define MAX_ALLOWED_DELAY 1000 // msecs
staticvoidsubscriber (void *args, zctx_t *ctx, void *pipe)
{
// Subscribe to everything
void *subscriber = zsocket_new (ctx, ZMQ_SUB);
zsocket_set_subscribe (subscriber, "");
zsocket_connect (subscriber, "tcp://localhost:5556");
// Get and process messages
while (true) {
char *string = zstr_recv (subscriber);
printf("%s\n", string);
int64_t clock;
int terms = sscanf (string, "%" PRId64, &clock);
assert (terms == 1);
free (string);
// Suicide snail logic
if (zclock_time () - clock > MAX_ALLOWED_DELAY) {
fprintf (stderr, "E: subscriber cannot keep up, aborting\n");
break;
}
// Work for 1 msec plus some random additional time
zclock_sleep (1 + randof (2));
}
zstr_send (pipe, "gone and died");
}
// .split publisher task
// This is our publisher task. It publishes a time-stamped message to its
// PUB socket every millisecond:
staticvoidpublisher (void *args, zctx_t *ctx, void *pipe)
{
// Prepare publisher
void *publisher = zsocket_new (ctx, ZMQ_PUB);
zsocket_bind (publisher, "tcp://*:5556");
while (true) {
// Send current clock (msecs) to subscribers
char string [20];
sprintf (string, "%" PRId64, zclock_time ());
zstr_send (publisher, string);
char *signal = zstr_recv_nowait (pipe);
if (signal) {
free (signal);
break;
}
zclock_sleep (1); // 1msec wait
}
}
// .split main task
// The main task simply starts a client and a server, and then
// waits for the client to signal that it has died:
intmain (void)
{
zctx_t *ctx = zctx_new ();
void *pubpipe = zthread_fork (ctx, publisher, NULL);
void *subpipe = zthread_fork (ctx, subscriber, NULL);
free (zstr_recv (subpipe));
zstr_send (pubpipe, "break");
zclock_sleep (100);
zctx_destroy (&ctx);
return0;
}
suisnail: Suicidal Snail in C++
//
// Suicidal Snail
//
// Andreas Hoelzlwimmer <andreas.hoelzlwimmer@fh-hagenberg.at>
#include"zhelpers.hpp"#include<thread>// ---------------------------------------------------------------------
// This is our subscriber
// It connects to the publisher and subscribes to everything. It
// sleeps for a short time between messages to simulate doing too
// much work. If a message is more than 1 second late, it croaks.
#define MAX_ALLOWED_DELAY 1000 // msecs
namespace {
bool Exit = false;
};
staticvoid *
subscriber () {
zmq::context_t context(1);
// Subscribe to everything
zmq::socket_t subscriber(context, ZMQ_SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.set(zmq::sockopt::subscribe, "");
std::stringstream ss;
// Get and process messages
while (1) {
ss.clear();
ss.str(s_recv (subscriber));
int64_t clock;
assert ((ss >> clock));
constauto delay = s_clock () - clock;
// Suicide snail logic
if (delay> MAX_ALLOWED_DELAY) {
std::cerr << "E: subscriber cannot keep up, aborting. Delay=" <<delay<< std::endl;
break;
}
// Work for 1 msec plus some random additional time
s_sleep(1000*(1+within(2)));
}
Exit = true;
return (NULL);
}
// ---------------------------------------------------------------------
// This is our server task
// It publishes a time-stamped message to its pub socket every 1ms.
staticvoid *
publisher () {
zmq::context_t context (1);
// Prepare publisher
zmq::socket_t publisher(context, ZMQ_PUB);
publisher.bind("tcp://*:5556");
std::stringstream ss;
while (!Exit) {
// Send current clock (msecs) to subscribers
ss.str("");
ss << s_clock();
s_send (publisher, ss.str());
s_sleep(1);
}
return0;
}
// This main thread simply starts a client, and a server, and then
// waits for the client to croak.
//
intmain (void)
{
std::thread server_thread(&publisher);
std::thread client_thread(&subscriber);
client_thread.join();
server_thread.join();
return0;
}
packageguide;
importjava.util.Random;
// Suicidal Snail
importorg.zeromq.SocketType;
importorg.zeromq.ZContext;
importorg.zeromq.ZMQ;
importorg.zeromq.ZMQ.Socket;
importorg.zeromq.ZThread;
importorg.zeromq.ZThread.IAttachedRunnable;
publicclasssuisnail
{
privatestaticfinallong MAX_ALLOWED_DELAY = 1000; // msecs
privatestatic Random rand = new Random(System.currentTimeMillis());
// This is our subscriber. It connects to the publisher and subscribes to
// everything. It sleeps for a short time between messages to simulate
// doing too much work. If a message is more than one second late, it
// croaks.
privatestaticclassSubscriberimplements IAttachedRunnable
{
@Overridepublicvoidrun(Object[] args, ZContext ctx, Socket pipe)
{
// Subscribe to everything
Socket subscriber = ctx.createSocket(SocketType.SUB);
subscriber.subscribe(ZMQ.SUBSCRIPTION_ALL);
subscriber.connect("tcp://localhost:5556");
// Get and process messages
while (true) {
String string = subscriber.recvStr();
System.out.printf("%s\n", string);
long clock = Long.parseLong(string);
// Suicide snail logic
if (System.currentTimeMillis() - clock > MAX_ALLOWED_DELAY) {
System.err.println(
"E: subscriber cannot keep up, aborting"
);
break;
}
// Work for 1 msec plus some random additional time
try {
Thread.sleep(1000 + rand.nextInt(2000));
}
catch (InterruptedException e) {
break;
}
}
pipe.send("gone and died");
}
}
// .split publisher task
// This is our publisher task. It publishes a time-stamped message to its
// PUB socket every millisecond:
privatestaticclassPublisherimplements IAttachedRunnable
{
@Overridepublicvoidrun(Object[] args, ZContext ctx, Socket pipe)
{
// Prepare publisher
Socket publisher = ctx.createSocket(SocketType.PUB);
publisher.bind("tcp://*:5556");
while (true) {
// Send current clock (msecs) to subscribers
String string = String.format("%d", System.currentTimeMillis());
publisher.send(string);
String signal = pipe.recvStr(ZMQ.DONTWAIT);
if (signal != null) {
break;
}
try {
Thread.sleep(1);
}
catch (InterruptedException e) {
}
}
}
}
// .split main task
// The main task simply starts a client and a server, and then waits for
// the client to signal that it has died:
publicstaticvoidmain(String[] args) throws Exception
{
try (ZContext ctx = new ZContext()) {
Socket pubpipe = ZThread.fork(ctx, new Publisher());
Socket subpipe = ZThread.fork(ctx, new Subscriber());
subpipe.recvStr();
pubpipe.send("break");
Thread.sleep(100);
}
}
}
---- Suicidal Snail---- Author: Robert G. Jakabosky <bobby@sharedrealm.com>--
require"zmq"
require"zmq.threads"
require"zhelpers"-- ----------------------------------------------------------------------- This is our subscriber-- It connects to the publisher and subscribes to everything. It-- sleeps for a short time between messages to simulate doing too-- much work. If a message is more than 1 second late, it croaks.local subscriber = [[
require"zmq"
require"zhelpers"
local MAX_ALLOWED_DELAY = 1000 -- msecs
local context = zmq.init(1)
-- Subscribe to everything
local subscriber = context:socket(zmq.SUB)
subscriber:connect("tcp://localhost:5556")
subscriber:setopt(zmq.SUBSCRIBE, "", 0)
-- Get and process messages
while true do
local msg = subscriber:recv()
local clock = tonumber(msg)
-- Suicide snail logic
if (s_clock () - clock > MAX_ALLOWED_DELAY) then
fprintf (io.stderr, "E: subscriber cannot keep up, aborting\n")
break
end
-- Work for 1 msec plus some random additional time
s_sleep (1 + randof (2))
end
subscriber:close()
context:term()
]]-- ----------------------------------------------------------------------- This is our server task-- It publishes a time-stamped message to its pub socket every 1ms.local publisher = [[
require"zmq"
require"zhelpers"
local context = zmq.init(1)
-- Prepare publisher
local publisher = context:socket(zmq.PUB)
publisher:bind("tcp://*:5556")
while true do
-- Send current clock (msecs) to subscribers
publisher:send(tostring(s_clock()))
s_sleep (1); -- 1msec wait
end
publisher:close()
context:term()
]]-- This main thread simply starts a client, and a server, and then-- waits for the client to croak.--local server_thread = zmq.threads.runstring(nil, publisher)
server_thread:start(true)
local client_thread = zmq.threads.runstring(nil, subscriber)
client_thread:start()
client_thread:join()
<?php/* Suicidal Snail
*
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*//* ---------------------------------------------------------------------
* This is our subscriber
* It connects to the publisher and subscribes to everything. It
* sleeps for a short time between messages to simulate doing too
* much work. If a message is more than 1 second late, it croaks.
*/
define("MAX_ALLOWED_DELAY", 100); // msecs
functionsubscriber()
{
$context = new ZMQContext();
// Subscribe to everything
$subscriber = new ZMQSocket($context, ZMQ::SOCKET_SUB);
$subscriber->connect("tcp://localhost:5556");
$subscriber->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, "");
// Get and process messages
while (true) {
$clock = $subscriber->recv();
// Suicide snail logic
if (microtime(true)*100 - $clock*100 > MAX_ALLOWED_DELAY) {
echo"E: subscriber cannot keep up, aborting", PHP_EOL;
break;
}
// Work for 1 msec plus some random additional time
usleep(1000 + rand(0, 1000));
}
}
/* ---------------------------------------------------------------------
* This is our server task
* It publishes a time-stamped message to its pub socket every 1ms.
*/functionpublisher()
{
$context = new ZMQContext();
// Prepare publisher
$publisher = new ZMQSocket($context, ZMQ::SOCKET_PUB);
$publisher->bind("tcp://*:5556");
while (true) {
// Send current clock (msecs) to subscribers
$publisher->send(microtime(true));
usleep(1000); // 1msec wait
}
}
/*
* This main thread simply starts a client, and a server, and then
* waits for the client to croak.
*/$pid = pcntl_fork();
if ($pid == 0) {
publisher();
exit();
}
$pid = pcntl_fork();
if ($pid == 0) {
subscriber();
exit();
}
suisnail: Suicidal Snail in Python
"""
Suicidal Snail
Author: Min RK <benjaminrk@gmail.com>
"""from__future__import print_function
importsysimportthreadingimporttimefrompickleimport dumps, loads
importrandomimportzmqfromzhelpersimport zpipe
# ---------------------------------------------------------------------# This is our subscriber# It connects to the publisher and subscribes to everything. It# sleeps for a short time between messages to simulate doing too# much work. If a message is more than 1 second late, it croaks.
MAX_ALLOWED_DELAY = 1.0# secsdefsubscriber(pipe):
# Subscribe to everything
ctx = zmq.Context.instance()
sub = ctx.socket(zmq.SUB)
sub.setsockopt(zmq.SUBSCRIBE, b'')
sub.connect("tcp://localhost:5556")
# Get and process messageswhile True:
clock = loads(sub.recv())
# Suicide snail logicif (time.time() - clock > MAX_ALLOWED_DELAY):
print("E: subscriber cannot keep up, aborting", file=sys.stderr)
break# Work for 1 msec plus some random additional time
time.sleep(1e-3 * (1+2*random.random()))
pipe.send(b"gone and died")
# ---------------------------------------------------------------------# This is our server task# It publishes a time-stamped message to its pub socket every 1ms.defpublisher(pipe):
# Prepare publisher
ctx = zmq.Context.instance()
pub = ctx.socket(zmq.PUB)
pub.bind("tcp://*:5556")
while True:
# Send current clock (secs) to subscribers
pub.send(dumps(time.time()))
try:
signal = pipe.recv(zmq.DONTWAIT)
except zmq.ZMQError as e:
if e.errno == zmq.EAGAIN:
# nothing to recvpasselse:
raiseelse:
# received break messagebreak
time.sleep(1e-3) # 1msec wait# This main thread simply starts a client, and a server, and then# waits for the client to signal it's died.defmain():
ctx = zmq.Context.instance()
pub_pipe, pub_peer = zpipe(ctx)
sub_pipe, sub_peer = zpipe(ctx)
pub_thread = threading.Thread(target=publisher, args=(pub_peer,))
pub_thread.daemon=True
pub_thread.start()
sub_thread = threading.Thread(target=subscriber, args=(sub_peer,))
sub_thread.daemon=True
sub_thread.start()
# wait for sub to finish
sub_pipe.recv()
# tell pub to halt
pub_pipe.send(b"break")
time.sleep(0.1)
if __name__ == '__main__':
main()
## Suicidal Snail
#
package require zmq
if{[llength$argv] == 0}{set argv [list driver]}elseif{[llength$argv] != 1}{puts"Usage: suisnail.tcl <driver|sub|pub>"exit1}lassign$argv what
set MAX_ALLOWED_DELAY 1000;# msecs
set tclsh [info nameofexecutable]expr{srand([pid])}switch -exact -- $what{sub{# This is our subscriber
# It connects to the publisher and subscribes to everything. It
# sleeps for a short time between messages to simulate doing too
# much work. If a message is more than 1 second late, it croaks.
zmq context context
zmq socket subpipe context PAIR
subpipe connect "ipc://subpipe.ipc"# Subscribe to everything
zmq socket subscriber context SUB
subscriber setsockopt SUBSCRIBE ""subscriber connect "tcp://localhost:5556"# Get and process messages
while{1}{set string [subscriber recv]puts"$string (delay = [expr {[clock milliseconds] - $string}])"if{[clock milliseconds]-$string > $::MAX_ALLOWED_DELAY}{puts stderr "E: subscriber cannot keep up, aborting"break}after[expr{1+int(rand()*2)}]}subpipe send "gone and died"subscriber close
subpipe close
context term
}pub{# This is our server task
# It publishes a time-stamped message to its pub socket every 1ms.
zmq context context
zmq socket pubpipe context PAIR
pubpipe connect "ipc://pubpipe.ipc"# Prepare publisher
zmq socket publisher context PUB
publisher bind "tcp://*:5556"while{1}{# Send current clock (msecs) to subscribers
publisher send [clock milliseconds]if{"POLLIN"in[pubpipe getsockopt EVENTS]}{break}after1;# 1msec wait
}publisher close
pubpipe close
context term
}driver{zmq context context
zmq socket pubpipe context PAIR
pubpipe bind "ipc://pubpipe.ipc"zmq socket subpipe context PAIR
subpipe bind "ipc://subpipe.ipc"puts"Start publisher, output redirected to publisher.log"exec$tclsh suisnail.tcl pub > publisher.log 2>@1 &
puts"Start subscriber, output redirected to subscriber.log"exec$tclsh suisnail.tcl sub > subscriber.log 2>@1 &
subpipe recv
pubpipe send "break"after100pubpipe close
subpipe close
context term
}}
Here are some things to note about the Suicidal Snail example:
The message here consists simply of the current system clock as a number of milliseconds. In a realistic application, you’d have at least a message header with the timestamp and a message body with data.
The example has subscriber and publisher in a single process as two threads. In reality, they would be separate processes. Using threads is just convenient for the demonstration.
Now lets look at one way to make our subscribers faster. A common use case for pub-sub is distributing large data streams like market data coming from stock exchanges. A typical setup would have a publisher connected to a stock exchange, taking price quotes, and sending them out to a number of subscribers. If there are a handful of subscribers, we could use TCP. If we have a larger number of subscribers, we’d probably use reliable multicast, i.e., PGM.
Let’s imagine our feed has an average of 100,000 100-byte messages a second. That’s a typical rate, after filtering market data we don’t need to send on to subscribers. Now we decide to record a day’s data (maybe 250 GB in 8 hours), and then replay it to a simulation network, i.e., a small group of subscribers. While 100K messages a second is easy for a ZeroMQ application, we want to replay it much faster.
So we set up our architecture with a bunch of boxes–one for the publisher and one for each subscriber. These are well-specified boxes–eight cores, twelve for the publisher.
And as we pump data into our subscribers, we notice two things:
When we do even the slightest amount of work with a message, it slows down our subscriber to the point where it can’t catch up with the publisher again.
We’re hitting a ceiling, at both publisher and subscriber, to around 6M messages a second, even after careful optimization and TCP tuning.
The first thing we have to do is break our subscriber into a multithreaded design so that we can do work with messages in one set of threads, while reading messages in another. Typically, we don’t want to process every message the same way. Rather, the subscriber will filter some messages, perhaps by prefix key. When a message matches some criteria, the subscriber will call a worker to deal with it. In ZeroMQ terms, this means sending the message to a worker thread.
So the subscriber looks something like a queue device. We could use various sockets to connect the subscriber and workers. If we assume one-way traffic and workers that are all identical, we can use PUSH and PULL and delegate all the routing work to ZeroMQ. This is the simplest and fastest approach.
The subscriber talks to the publisher over TCP or PGM. The subscriber talks to its workers, which are all in the same process, over inproc:@<//>@.
Now to break that ceiling. The subscriber thread hits 100% of CPU and because it is one thread, it cannot use more than one core. A single thread will always hit a ceiling, be it at 2M, 6M, or more messages per second. We want to split the work across multiple threads that can run in parallel.
The approach used by many high-performance products, which works here, is sharding. Using sharding, we split the work into parallel and independent streams, such as half of the topic keys in one stream, and half in another. We could use many streams, but performance won’t scale unless we have free cores. So let’s see how to shard into two streams.
With two streams, working at full speed, we would configure ZeroMQ as follows:
Two I/O threads, rather than one.
Two network interfaces (NIC), one per subscriber.
Each I/O thread bound to a specific NIC.
Two subscriber threads, bound to specific cores.
Two SUB sockets, one per subscriber thread.
The remaining cores assigned to worker threads.
Worker threads connected to both subscriber PUSH sockets.
Ideally, we want to match the number of fully-loaded threads in our architecture with the number of cores. When threads start to fight for cores and CPU cycles, the cost of adding more threads outweighs the benefits. There would be no benefit, for example, in creating more I/O threads.
As a larger worked example, we’ll take the problem of making a reliable pub-sub architecture. We’ll develop this in stages. The goal is to allow a set of applications to share some common state. Here are our technical challenges:
We have a large set of client applications, say thousands or tens of thousands.
They will join and leave the network arbitrarily.
These applications must share a single eventually-consistent state.
Any application can update the state at any point in time.
Let’s say that updates are reasonably low-volume. We don’t have real time goals. The whole state can fit into memory. Some plausible use cases are:
A configuration that is shared by a group of cloud servers.
Some game state shared by a group of players.
Exchange rate data that is updated in real time and available to applications.
A first decision we have to make is whether we work with a central server or not. It makes a big difference in the resulting design. The trade-offs are these:
Conceptually, a central server is simpler to understand because networks are not naturally symmetrical. With a central server, we avoid all questions of discovery, bind versus connect, and so on.
Generally, a fully-distributed architecture is technically more challenging but ends up with simpler protocols. That is, each node must act as server and client in the right way, which is delicate. When done right, the results are simpler than using a central server. We saw this in the Freelance pattern in
Chapter 4 - Reliable Request-Reply Patterns.
A central server will become a bottleneck in high-volume use cases. If handling scale in the order of millions of messages a second is required, we should aim for decentralization right away.
Ironically, a centralized architecture will scale to more nodes more easily than a decentralized one. That is, it’s easier to connect 10,000 nodes to one server than to each other.
So, for the Clone pattern we’ll work with a server that publishes state updates and a set of clients that represent applications.
We’ll develop Clone in stages, solving one problem at a time. First, let’s look at how to update a shared state across a set of clients. We need to decide how to represent our state, as well as the updates. The simplest plausible format is a key-value store, where one key-value pair represents an atomic unit of change in the shared state.
We have a simple pub-sub example in
Chapter 1 - Basics, the weather server and client. Let’s change the server to send key-value pairs, and the client to store these in a hash table. This lets us send updates from one server to a set of clients using the classic pub-sub model.
An update is either a new key-value pair, a modified value for an existing key, or a deleted key. We can assume for now that the whole store fits in memory and that applications access it by key, such as by using a hash table or dictionary. For larger stores and some kind of persistence we’d probably store the state in a database, but that’s not relevant here.
#include<iostream>#include<unordered_map>#include"kvsimple.hpp"usingnamespace std;
intmain() {
// Prepare our context and publisher socket
zmq::context_t ctx(1);
zmq::socket_t publisher(ctx, ZMQ_PUB);
publisher.bind("tcp://*:5555");
s_sleep(5000); // Sleep for a short while to allow connections to be established
// Initialize key-value map and sequence
unordered_map<string,string> kvmap;
int64_t sequence = 0;
srand(time(NULL));
s_catch_signals();
while (!s_interrupted) {
// Distribute as key-value message
string key = to_string(within(10000));
string body = to_string(within(1000000));
kvmsg kv(key, sequence, (unsignedchar *)body.c_str());
kv.send(publisher); // Send key-value message
// Store key-value pair in map
kvmap[key] = body;
sequence++;
// Sleep for a short while before sending the next message
s_sleep(1000);
}
cout << "Interrupted" << endl;
cout << sequence << " messages out" << endl;
return0;
}
## Clone server Model One
#
lappend auto_path .
package require KVSimple
# Prepare our context and publisher socket
zmq context context
set pub [zmq socket publisher context PUB]$pubbind"tcp://*:5556"after200set sequence 0expr srand([pid])while{1}{# Distribute as key-value message
set kvmsg [KVSimple new [incr sequence]]$kvmsgset_key[expr{int(rand()*10000)}]$kvmsgset_body[expr{int(rand()*1000000)}]$kvmsgsend$pub$kvmsgstore kvmap
puts[$kvmsgdump]after500}$pubclosecontext term
Here are some things to note about this first model:
All the hard work is done in a kvmsg class. This class works with key-value message objects, which are multipart ZeroMQ messages structured as three frames: a key (a ZeroMQ string), a sequence number (64-bit value, in network byte order), and a binary body (holds everything else).
The server generates messages with a randomized 4-digit key, which lets us simulate a large but not enormous hash table (10K entries).
We don’t implement deletions in this version: all messages are inserts or updates.
The server does a 200 millisecond pause after binding its socket. This is to prevent slow joiner syndrome, where the subscriber loses messages as it connects to the server’s socket. We’ll remove that in later versions of the Clone code.
We’ll use the terms publisher and subscriber in the code to refer to sockets. This will help later when we have multiple sockets doing different things.
Here is the kvmsg class, in the simplest form that works for now:
# =====================================================================
# kvsimple - simple key-value message class for example applications
# =====================================================================
lappend auto_path .
package require TclOO
package require zmq
package require mdp
package provide KVSimple 1.0# Keys are short strings
set KVMSG_KEY_MAX 255# Message is formatted on wire as 3 frames:
# frame 0: key (0MQ string)
# frame 1: sequence (8 bytes, network order)
# frame 2: body (blob)
set FRAME_KEY 0set FRAME_SEQ 1set FRAME_BODY 2set KVMSG_FRAMES 3oo::class create KVSimple {variable frame key
# Constructor, sets sequence as provided
constructor{{isequence0}}{set frame [list]my set_sequence $isequence}destructor{}# Reads key-value message from socket
method recv {socket}{set frame [list]# Read all frames off the wire
for{set frame_nbr 0}{$frame_nbr < $::KVMSG_FRAMES}{incr frame_nbr}{lappend frame [$socketrecv]# Verify multipart framing
if{![$socketgetsockopt RCVMORE]}{break}}}# Send key-value message to socket; any empty frames are sent as such.
method send {socket}{for{set frame_nbr 0}{$frame_nbr < $::KVMSG_FRAMES}{incr frame_nbr}{if{$frame_nbr == ($::KVMSG_FRAMES-1)}{$socketsend[lindex$frame$frame_nbr]}else{$socketsendmore[lindex$frame$frame_nbr]}}}# Return key from last read message, if any, else NULL
method key {}{if{[llength$frame] > $::FRAME_KEY}{if{![info exists key]}{set size [string length [lindex$frame$::FRAME_KEY]]if{$size > $::KVMSG_KEY_MAX}{set size $::KVMSG_KEY_MAX}set key [string range [lindex$frame$::FRAME_KEY]0[expr{$size-1}]]}return$key}else{return{}}}# Return sequence nbr from last read message, if any
method sequence {}{if{[llength$frame] > $::FRAME_SEQ}{set s [lindex$frame$::FRAME_SEQ]if{[string length $s] != 8}{error"sequence frame must have length 8"}binary scan [lindex$frame$::FRAME_SEQ] W r
return$r}else{return0}}# Return body from last read message, if any, else NULL
method body {}{if{[llength$frame] > $::FRAME_BODY}{return[lindex$frame$::FRAME_BODY]}else{return{}}}# Return body size from last read message, if any, else zero
method size {}{if{[llength$frame] > $::FRAME_BODY}{return[string length [lindex$frame$::FRAME_BODY]]}else{return{}}}# Set message key as provided
method set_key {ikey}{while{[llength$frame] <= $::FRAME_KEY}{lappend frame {}}lset frame $::FRAME_KEY$ikey}# Set message sequence number
method set_sequence {isequence}{while{[llength$frame] <= $::FRAME_SEQ}{lappend frame {}}set sequence [binary format W $isequence]lset frame $::FRAME_SEQ$sequence}# Set message body
method set_body {ibody}{while{[llength$frame] <= $::FRAME_KEY}{lappend frame {}}lset frame $::FRAME_BODY$ibody}# Set message key using printf format
method fmt_key {format args}{my set_key [format$format{*}$args]}# Set message body using printf format
method fmt_body {format args}{my set_body [format$format{*}$args]}# Store entire kvmsg into hash map, if key/value are set
# Nullifies kvmsg reference, and destroys automatically when no longer
# needed.
method store {hashnm}{upvar$hashnm hash
if{[info exists hash([my key])]}{$hash([my key])destroy}set hash([my key])[self]}# Dump message to stderr, for debugging and tracing
method dump {}{set rt ""append rt [format{[seq:%lld]}[my sequence]]append rt [format{[key:%s]}[my key]]append rt [format{[size:%d]}[my size]]set size [my size]set body [my body]for{set i 0}{$i < $size}{incr i}{set c [lindex$body$i]if{[string is ascii $c]}{append rt $c}else{append rt [binary scan H2 $c]}}return$rt}}namespace eval ::KVSimpleTest {proc test {verbose}{puts -nonewline " * kvmsg: "# Prepare our context and sockets
zmq context context
set os [zmq socket output context DEALER]output bind "ipc://kvmsg_selftest.ipc"set is [zmq socket input context DEALER]input connect "ipc://kvmsg_selftest.ipc"# Test send and receive of simple message
set kvmsg [KVSimple new 1]$kvmsgset_key"key"$kvmsgset_body"body"if{$verbose}{puts[$kvmsgdump]}$kvmsgsend$os$kvmsgstore kvmap
$kvmsgrecv$isif{$verbose}{puts[$kvmsgdump]}if{[$kvmsgkey]ne"key"}{error"Unexpected key: [$kvmsg key]"}$kvmsgstore kvmap
# Shutdown and destroy all objects
input close
output close
context term
puts"OK"}}#::KVSimpleTest::test 1
Later, we’ll make a more sophisticated kvmsg class that will work in real applications.
Both the server and client maintain hash tables, but this first model only works properly if we start all clients before the server and the clients never crash. That’s very artificial.
So now we have our second problem: how to deal with late-joining clients or clients that crash and then restart.
In order to allow a late (or recovering) client to catch up with a server, it has to get a snapshot of the server’s state. Just as we’ve reduced “message” to mean “a sequenced key-value pair”, we can reduce “state” to mean “a hash table”. To get the server state, a client opens a DEALER socket and asks for it explicitly.
To make this work, we have to solve a problem of timing. Getting a state snapshot will take a certain time, possibly fairly long if the snapshot is large. We need to correctly apply updates to the snapshot. But the server won’t know when to start sending us updates. One way would be to start subscribing, get a first update, and then ask for “state for update N”. This would require the server storing one snapshot for each update, which isn’t practical.
So we will do the synchronization in the client, as follows:
The client first subscribes to updates and then makes a state request. This guarantees that the state is going to be newer than the oldest update it has.
The client waits for the server to reply with state, and meanwhile queues all updates. It does this simply by not reading them: ZeroMQ keeps them queued on the socket queue.
When the client receives its state update, it begins once again to read updates. However, it discards any updates that are older than the state update. So if the state update includes updates up to 200, the client will discard updates up to 201.
The client then applies updates to its own state snapshot.
It’s a simple model that exploits ZeroMQ’s own internal queues. Here’s the server:
## Clone server Model Two
#
lappend auto_path .
package require KVSimple
if{[llength$argv] == 0}{set argv "pub"}elseif{[llength$argv] != 1}{puts"Usage: clonesrv2.tcl <pub|upd>"exit1}lassign$argv what
set tclsh [info nameofexecutable]expr srand([pid])switch -exact -- $what{pub{# Prepare our context and publisher socket
zmq context context
set pub [zmq socket publisher context PUB]$pubbind"tcp://*:5557"set upd [zmq socket updates context PAIR]$updbind"ipc://updates.ipc"set sequence 0# Start state manager and wait for synchronization signal
exec$tclsh clonesrv2.tcl upd > upd.log 2>@1 &
$updrecvwhile{1}{# Distribute as key-value message
set kvmsg [KVSimple new [incr sequence]]$kvmsgset_key[expr{int(rand()*10000)}]$kvmsgset_body[expr{int(rand()*1000000)}]$kvmsgsend$pub$kvmsgsend$updputs[$kvmsgdump]after500}$pubclose$updclosecontext term
}upd{zmq context context
set upd [zmq socket updates context PAIR]$updconnect"ipc://updates.ipc"$updsend"READY"set snp [zmq socket snapshot context ROUTER]$snpbind"tcp://*:5556"set sequence 0;# Current snapshot version number
# Apply state update from main thread
proc apply_state_update {upd}{global kvmap sequence
set kvmsg [KVSimple new]$kvmsgrecv$updset sequence [$kvmsgsequence]$kvmsgstore kvmap
}# Execute state snapshot request
proc execute_state_snapshot_request {snp}{global kvmap sequence
set identity [$snprecv]# Request is in second frame of message
set request [$snprecv]if{$requestne"ICANHAZ?"}{puts"E: bad request, aborting"exit1}# Send state snapshot to client
# For each entry in kvmap, send kvmsg to client
foreach{key value}[array get kvmap]{# Send one state snapshot key-value pair to a socket
# Hash item data is our kvmsg object, ready to send
$snpsendmore$identity$valuesend$snp}# Now send END message with sequence number
puts"Sending state snapshot=$sequence"$snpsendmore$identityset kvmsg [KVSimple new $sequence]$kvmsgset_key"KTHXBAI"$kvmsgset_body""$kvmsgsend$snp$kvmsgdestroy}$updreadable[list apply_state_update $upd]$snpreadable[list execute_state_snapshot_request $snp]vwait forever
$updclose$snpclosecontext term
}}
Here are some things to note about these two programs:
The server uses two tasks. One thread produces the updates (randomly) and sends these to the main PUB socket, while the other thread handles state requests on the ROUTER socket. The two communicate across PAIR sockets over an inproc:@<//>@ connection.
The client is really simple. In C, it consists of about fifty lines of code. A lot of the heavy lifting is done in the kvmsg class. Even so, the basic Clone pattern is easier to implement than it seemed at first.
We don’t use anything fancy for serializing the state. The hash table holds a set of kvmsg objects, and the server sends these, as a batch of messages, to the client requesting state. If multiple clients request state at once, each will get a different snapshot.
We assume that the client has exactly one server to talk to. The server must be running; we do not try to solve the question of what happens if the server crashes.
Right now, these two programs don’t do anything real, but they correctly synchronize state. It’s a neat example of how to mix different patterns: PAIR-PAIR, PUB-SUB, and ROUTER-DEALER.
In our second model, changes to the key-value store came from the server itself. This is a centralized model that is useful, for example if we have a central configuration file we want to distribute, with local caching on each node. A more interesting model takes updates from clients, not the server. The server thus becomes a stateless broker. This gives us some benefits:
We’re less worried about the reliability of the server. If it crashes, we can start a new instance and feed it new values.
We can use the key-value store to share knowledge between active peers.
To send updates from clients back to the server, we could use a variety of socket patterns. The simplest plausible solution is a PUSH-PULL combination.
Why don’t we allow clients to publish updates directly to each other? While this would reduce latency, it would remove the guarantee of consistency. You can’t get consistent shared state if you allow the order of updates to change depending on who receives them. Say we have two clients, changing different keys. This will work fine. But if the two clients try to change the same key at roughly the same time, they’ll end up with different notions of its value.
There are a few strategies for obtaining consistency when changes happen in multiple places at once. We’ll use the approach of centralizing all change. No matter the precise timing of the changes that clients make, they are all pushed through the server, which enforces a single sequence according to the order in which it gets updates.
By mediating all changes, the server can also add a unique sequence number to all updates. With unique sequencing, clients can detect the nastier failures, including network congestion and queue overflow. If a client discovers that its incoming message stream has a hole, it can take action. It seems sensible that the client contact the server and ask for the missing messages, but in practice that isn’t useful. If there are holes, they’re caused by network stress, and adding more stress to the network will make things worse. All the client can do is warn its users that it is “unable to continue”, stop, and not restart until someone has manually checked the cause of the problem.
We’ll now generate state updates in the client. Here’s the server:
## Clone server Model Three
#
lappend auto_path .
package require KVSimple
# Prepare our context and sockets
zmq context context
set snp [zmq socket snapshot context ROUTER]$snpbind"tcp://*:5556"set pub [zmq socket publisher context PUB]$pubbind"tcp://*:5557"set col [zmq socket collector context PULL]$colbind"tcp://*:5558"set sequence 0# Apply state update sent from client
proc apply_state_update {col pub}{global sequence kvmap
set kvmsg [KVSimple new]$kvmsgrecv$col$kvmsgset_sequence[incr sequence]$kvmsgsend$pub$kvmsgstore kvmap
puts"Publishing update $sequence"}# Execute state snapshot request
proc execute_state_snapshot_request {snp}{global sequence
set identity [$snprecv]# Request is in second frame of message
set request [$snprecv]if{$requestne"ICANHAZ?"}{puts"E: bad request, aborting"exit1}# Send state snapshot to client
# For each entry in kvmap, send kvmsg to client
foreach{key value}[array get kvmap]{# Send one state snapshot key-value pair to a socket
# Hash item data is our kvmsg object, ready to send
$snpsendmore$identity$valuesend$snp}# Now send END message with sequence number
puts"I: sending snapshot=$sequence"$snpsendmore$identityset kvmsg [KVSimple new $sequence]$kvmsgset_key"KTHXBAI"$kvmsgset_body""$kvmsgsend$snp$kvmsgdestroy}$colreadable[list apply_state_update $col$pub]$snpreadable[list execute_state_snapshot_request $snp]vwait forever
$colclose$pubclose$snpclosecontext term
Here are some things to note about this third design:
The server has collapsed to a single task. It manages a PULL socket for incoming updates, a ROUTER socket for state requests, and a PUB socket for outgoing updates.
The client uses a simple tickless timer to send a random update to the server once a second. In a real implementation, we would drive updates from application code.
As we grow the number of clients, the size of our shared store will also grow. It stops being reasonable to send everything to every client. This is the classic story with pub-sub: when you have a very small number of clients, you can send every message to all clients. As you grow the architecture, this becomes inefficient. Clients specialize in different areas.
So even when working with a shared store, some clients will want to work only with a part of that store, which we call a subtree. The client has to request the subtree when it makes a state request, and it must specify the same subtree when it subscribes to updates.
There are a couple of common syntaxes for trees. One is the path hierarchy, and another is the topic tree. These look like this:
Path hierarchy: /some/list/of/paths
Topic tree: some.list.of.topics
We’ll use the path hierarchy, and extend our client and server so that a client can work with a single subtree. Once you see how to work with a single subtree you’ll be able to extend this yourself to handle multiple subtrees, if your use case demands it.
Here’s the server implementing subtrees, a small variation on Model Three:
## Clone server Model Four
#
lappend auto_path .
package require KVSimple
# Prepare our context and sockets
zmq context context
set snp [zmq socket snapshot context ROUTER]$snpbind"tcp://*:5556"set pub [zmq socket publisher context PUB]$pubbind"tcp://*:5557"set col [zmq socket collector context PULL]$colbind"tcp://*:5558"set sequence 0# Apply state update sent from client
proc apply_state_update {col pub}{global sequence kvmap
set kvmsg [KVSimple new]$kvmsgrecv$col$kvmsgset_sequence[incr sequence]$kvmsgsend$pub$kvmsgstore kvmap
puts"I: publishing update $sequence"}# Execute state snapshot request
proc execute_state_snapshot_request {snp}{global sequence
set identity [$snprecv]# Request is in second frame of message
set request [$snprecv]if{$requestne"ICANHAZ?"}{puts"E: bad request, aborting"exit1}set subtree [$snprecv]# Send state snapshot to client
# For each entry in kvmap, send kvmsg to client
foreach{key value}[array get kvmap]{# Send one state snapshot key-value pair to a socket
# Hash item data is our kvmsg object, ready to send
if{[string match $subtree* [$valuekey]]}{$snpsendmore$identity$valuesend$snp}}# Now send END message with sequence number
puts"I: sending snapshot=$sequence"$snpsendmore$identityset kvmsg [KVSimple new $sequence]$kvmsgset_key"KTHXBAI"$kvmsgset_body$subtree$kvmsgsend$snp$kvmsgdestroy}$colreadable[list apply_state_update $col$pub]$snpreadable[list execute_state_snapshot_request $snp]vwait forever
$colclose$pubclose$snpclosecontext term
An ephemeral value is one that expires automatically unless regularly refreshed. If you think of Clone being used for a registration service, then ephemeral values would let you do dynamic values. A node joins the network, publishes its address, and refreshes this regularly. If the node dies, its address eventually gets removed.
The usual abstraction for ephemeral values is to attach them to a session, and delete them when the session ends. In Clone, sessions would be defined by clients, and would end if the client died. A simpler alternative is to attach a time to live (TTL) to ephemeral values, which the server uses to expire values that haven’t been refreshed in time.
A good design principle that I use whenever possible is to not invent concepts that are not absolutely essential. If we have very large numbers of ephemeral values, sessions will offer better performance. If we use a handful of ephemeral values, it’s fine to set a TTL on each one. If we use masses of ephemeral values, it’s more efficient to attach them to sessions and expire them in bulk. This isn’t a problem we face at this stage, and may never face, so sessions go out the window.
Now we will implement ephemeral values. First, we need a way to encode the TTL in the key-value message. We could add a frame. The problem with using ZeroMQ frames for properties is that each time we want to add a new property, we have to change the message structure. It breaks compatibility. So let’s add a properties frame to the message, and write the code to let us get and put property values.
Next, we need a way to say, “delete this value”. Up until now, servers and clients have always blindly inserted or updated new values into their hash table. We’ll say that if the value is empty, that means “delete this key”.
Here’s a more complete version of the kvmsg class, which implements the properties frame (and adds a UUID frame, which we’ll need later on). It also handles empty values by deleting the key from the hash, if necessary:
# =====================================================================
# kvmsg - key-value message class for example applications
lappend auto_path .
package require TclOO
package require uuid
package require zmq
package provide KVMsg 1.0# Keys are short strings
set KVMSG_KEY_MAX 255# Message is formatted on wire as 5 frames:
# frame 0: key (0MQ string)
# frame 1: sequence (8 bytes, network order)
# frame 2: uuid (blob, 16 bytes)
# frame 3: properties (0MQ string)
# frame 4: body (blob)
set FRAME_KEY 0set FRAME_SEQ 1set FRAME_UUID 2set FRAME_PROPS 3set FRAME_BODY 4set KVMSG_FRAMES 5oo::class create KVMsg {variable frame key props
# Constructor, sets sequence as provided
constructor{{isequence0}}{set frame [list]#props array
my set_sequence $isequence}destructor{}method set_frame {iframe}{set frame $iframe}method set_props {ipropsnm}{upvar$ipropsnm iprops
unset -nocomplain props
foreay{k v}[array get iprops]{set props($k)$v}}# Serialize list of properties to a message frame
method encode_props {}{while{[llength$frame] < $::FRAME_PROPS}{lappend frame {}}if{[array size props]}{set s ""foreach k [lsort -dictionary [array names props]]{append s "$k=$props($k)\n"}lset frame $::FRAME_PROPS$s}}# Rebuild properties list from message frame
method decode_props {}{unset -nocomplain props
foreach s [split[string trimright [lindex$frame$::FRAME_PROPS]\n]\n]{lassign[split$s=] k v
set props($k)$v}}# Create duplicate of kvmsg
method dup {}{set kvmsg [KVMsg new 0]$kvmsgset_frame$frame$kvmsgset_props props
return$kvmsg}# Reads key-value message from socket
method recv {socket}{set frame [list]# Read all frames off the wire
for{set frame_nbr 0}{$frame_nbr < $::KVMSG_FRAMES}{incr frame_nbr}{lappend frame [$socketrecv]# Verify multipart framing
if{![$socketgetsockopt RCVMORE]}{break}}my decode_props
}# Send key-value message to socket; any empty frames are sent as such.
method send {socket}{my encode_props
for{set frame_nbr 0}{$frame_nbr < $::KVMSG_FRAMES}{incr frame_nbr}{if{$frame_nbr == ($::KVMSG_FRAMES-1)}{$socketsend[lindex$frame$frame_nbr]}else{$socketsendmore[lindex$frame$frame_nbr]}}}# Return key from last read message, if any, else NULL
method key {}{if{[llength$frame] > $::FRAME_KEY}{if{![info exists key]}{set size [string length [lindex$frame$::FRAME_KEY]]if{$size > $::KVMSG_KEY_MAX}{set size $::KVMSG_KEY_MAX}set key [string range [lindex$frame$::FRAME_KEY]0[expr{$size-1}]]}return$key}else{return{}}}# Return sequence nbr from last read message, if any
method sequence {}{if{[llength$frame] > $::FRAME_SEQ}{set s [lindex$frame$::FRAME_SEQ]if{[string length $s] != 8}{error"sequence frame must have length 8"}binary scan [lindex$frame$::FRAME_SEQ] W r
return$r}else{return0}}# Return UUID from last read message, if any, else NULL
method body {}{if{[llength$frame] > $::FRAME_UUID}{return[lindex$frame$::FRAME_UUID]}else{return{}}}# Return body from last read message, if any, else NULL
method body {}{if{[llength$frame] > $::FRAME_BODY}{return[lindex$frame$::FRAME_BODY]}else{return{}}}# Return body size from last read message, if any, else zero
method size {}{if{[llength$frame] > $::FRAME_BODY}{return[string length [lindex$frame$::FRAME_BODY]]}else{return{}}}# Set message key as provided
method set_key {ikey}{while{[llength$frame] <= $::FRAME_KEY}{lappend frame {}}lset frame $::FRAME_KEY$ikey}# Set message sequence number
method set_sequence {isequence}{while{[llength$frame] <= $::FRAME_SEQ}{lappend frame {}}set sequence [binary format W $isequence]lset frame $::FRAME_SEQ$sequence}# Set message UUID to generated value
method set_uuid {}{while{[llength$frame] <= $::FRAME_UUID}{lappend frame {}}lset frame $::FRAME_UUID[uuid::uuid generate]}# Set message body
method set_body {ibody}{while{[llength$frame] <= $::FRAME_BODY}{lappend frame {}}lset frame $::FRAME_BODY$ibody}# Set message key using printf format
method fmt_key {format args}{my set_key [format$format{*}$args]}# Set message body using printf format
method fmt_body {format args}{my set_body [format$format{*}$args]}# Get message property, if set, else ""
method get_prop {name}{if{[info exists props($name)]}{return$props($name)}return""}# Set message property
# Names cannot contain '='.
method set_prop {name value}{if{[string first "="$name] >= 0}{error"property name can not contain a '=' character"}set props($name)$value}# Store entire kvmsg into hash map, if key/value are set.
# Nullifies kvmsg reference, and destroys automatically when no longer
# needed. If value is empty, deletes any previous value from store.
method store {hashnm}{upvar$hashnm hash
if{[my size]}{if{[info exists hash([my key])]}{$hash([my key])destroy}set hash([my key])[self]}else{if{[info exists hash([my key])]}{$hash([my key])destroyunset -nocomplain hash([my key])}}}# Dump message to stderr, for debugging and tracing
method dump {}{set rt ""append rt [format{[seq:%lld]}[my sequence]]append rt [format{[key:%s]}[my key]]append rt [format{[size:%d]}[my size]]if{[array size props]}{append rt "\["}foreach k [lsort -dictionary [array names props]]{append rt "$k=$props($k);"}if{[array size props]}{append rt "\]"}set size [my size]set body [my body]for{set i 0}{$i < $size}{incr i}{set c [lindex$body$i]if{[string is ascii $c]}{append rt $c}else{append rt [binary scan H2 $c]}}return$rt}}namespace eval ::KVMsgTest {proc test {verbose}{puts -nonewline " * kvmsg: "# Prepare our context and sockets
zmq context context
set os [zmq socket output context DEALER]output bind "ipc://kvmsg_selftest.ipc"set is [zmq socket input context DEALER]input connect "ipc://kvmsg_selftest.ipc"# Test send and receive of simple message
set kvmsg [KVMsg new 1]$kvmsgset_key"key"$kvmsgset_uuid$kvmsgset_body"body"if{$verbose}{puts[$kvmsgdump]}$kvmsgsend$os$kvmsgstore kvmap
$kvmsgrecv$isif{$verbose}{puts[$kvmsgdump]}if{[$kvmsgkey]ne"key"}{error"Unexpected key: [$kvmsg key]"}$kvmsgdestroy# Test send and receive of message with properties
set kvmsg [KVMsg new 2]$kvmsgset_prop"prop1""value1"$kvmsgset_prop"prop2""value2"$kvmsgset_prop"prop3""value3"$kvmsgset_key"key"$kvmsgset_uuid$kvmsgset_body"body"if{$verbose}{puts[$kvmsgdump]}$kvmsgsend$os$kvmsgrecv$isif{$verbose}{puts[$kvmsgdump]}if{[$kvmsgkey]ne"key"}{error"Unexpected key: [$kvmsg key]"}if{[$kvmsgget_prop"prop2"]ne"value2"}{error"Unexpected property value: [$kvmsg get_prop "prop2"]"}$kvmsgdestroy# Shutdown and destroy all objects
input close
output close
context term
puts"OK"}}#::KVMsgTest::test 1
The Model Five client is almost identical to Model Four. It uses the full kvmsg class now, and sets a randomized ttl property (measured in seconds) on each message:
Until now, we have used a poll loop in the server. In this next model of the server, we switch to using a reactor. In C, we use CZMQ’s zloop class. Using a reactor makes the code more verbose, but easier to understand and build out because each piece of the server is handled by a separate reactor handler.
We use a single thread and pass a server object around to the reactor handlers. We could have organized the server as multiple threads, each handling one socket or timer, but that works better when threads don’t have to share data. In this case all work is centered around the server’s hashmap, so one thread is simpler.
There are three reactor handlers:
One to handle snapshot requests coming on the ROUTER socket;
One to handle incoming updates from clients, coming on the PULL socket;
One to expire ephemeral values that have passed their TTL.
## Clone server Model Five
#
lappend auto_path .
package require TclOO
package require mdp
package require KVMsg
oo::class create CloneServer {variable ctx kvmap sequence snapshot publisher collector afterid
constructor{port}{# Set up our clone server sockets
set sequence 0set ctx [zmq context cloneserver_context_[mdp::contextid]]set snapshot [zmq socket clonserver_snapshot[mdp::socketid]$ctx ROUTER]set publisher [zmq socket cloneserver_publisher_[mdp::socketid]$ctx PUB]set collector [zmq socket cloneserver_collector_[mdp::socketid]$ctx PULL]$snapshotbind"tcp://*:$port"$publisherbind"tcp://*:[expr {$port+1}]"$collectorbind"tcp://*:[expr {$port+2}]"# Register our handlers with reactor
my register
}destructor{$snapshotclose$publisherclose$collectorclose$ctxterm}method register {}{$snapshotreadable[list[self] s_snapshot]$collectorreadable[list[self] s_collector]set afterid [after1000[list[self] s_flush_ttl]]}method unregister {}{$snapshotreadable{}$collectorreadable{}catch{after cancel $afterid}}# Send snapshots to clients who ask for them
method s_snapshot {}{set identity [$snapshotrecv]if{[string length $identity]}{set request [$snapshotrecv]if{$requesteq"ICANHAZ?"}{set subtree [$snapshotrecv]}else{puts"E: bad request, aborting"}if{[info exists subtree]}{# Send state to client
foreach{key value}[array get kvmap]{# Send one state snapshot key-value pair to a socket
# Hash item data is our kvmsg object, ready to send
if{[string match $subtree* [$valuekey]]}{$snapshotsendmore$identity$valuesend$snapshot}}# Now send END message with sequence number
puts"I: sending snapshot=$sequence"$snapshotsendmore$identityset kvmsg [KVMsg new $sequence]$kvmsgset_key"KTHXBAI"$kvmsgset_body$subtree$kvmsgsend$snapshot$kvmsgdestroy}}}# Collect updates from clients
method s_collector {}{set kvmsg [KVMsg new]$kvmsgrecv$collector$kvmsgset_sequence[incr sequence]$kvmsgsend$publisherset ttl [$kvmsgget_prop"ttl"]if{$ttl}{$kvmsgset_prop"ttl"[expr{[clock milliseconds] + $ttl * 1000}]$kvmsgstore kvmap
puts"I: publishing update=$sequence"}}# Purge ephemeral values that have expired
method s_flush_ttl {}{foreach{key value}[array names kvmap]{# If key-value pair has expired, delete it and publish the
# fact to listening clients.
if{[clock milliseconds] >= [$valueget_prop"ttl"]}{$valueset_sequence[incr sequence]$valueset_body""$valuesend$publisher$valuestor kvmap
puts"I: publishing delete=$sequence"}}}}set server [CloneServer new 5556]# Run reactor until process interrupted
vwait forever
$serverdestroy
The Clone models we’ve explored up to now have been relatively simple. Now we’re going to get into unpleasantly complex territory, which has me getting up for another espresso. You should appreciate that making “reliable” messaging is complex enough that you always need to ask, “Do we actually need this?” before jumping into it. If you can get away with unreliable or with “good enough” reliability, you can make a huge win in terms of cost and complexity. Sure, you may lose some data now and then. It is often a good trade-off. Having said, that, and… sips… because the espresso is really good, let’s jump in.
As you play with the last model, you’ll stop and restart the server. It might look like it recovers, but of course it’s applying updates to an empty state instead of the proper current state. Any new client joining the network will only get the latest updates instead of the full historical record.
What we want is a way for the server to recover from being killed, or crashing. We also need to provide backup in case the server is out of commission for any length of time. When someone asks for “reliability”, ask them to list the failures they want to handle. In our case, these are:
The server process crashes and is automatically or manually restarted. The process loses its state and has to get it back from somewhere.
The server machine dies and is offline for a significant time. Clients have to switch to an alternate server somewhere.
The server process or machine gets disconnected from the network, e.g., a switch dies or a datacenter gets knocked out. It may come back at some point, but in the meantime clients need an alternate server.
Our first step is to add a second server. We can use the Binary Star pattern from
Chapter 4 - Reliable Request-Reply Patterns to organize these into primary and backup. Binary Star is a reactor, so it’s useful that we already refactored the last server model into a reactor style.
We need to ensure that updates are not lost if the primary server crashes. The simplest technique is to send them to both servers. The backup server can then act as a client, and keep its state synchronized by receiving updates as all clients do. It’ll also get new updates from clients. It can’t yet store these in its hash table, but it can hold onto them for a while.
So, Model Six introduces the following changes over Model Five:
We use a pub-sub flow instead of a push-pull flow for client updates sent to the servers. This takes care of fanning out the updates to both servers. Otherwise we’d have to use two DEALER sockets.
We add heartbeats to server updates (to clients), so that a client can detect when the primary server has died. It can then switch over to the backup server.
We connect the two servers using the Binary Star bstar reactor class. Binary Star relies on the clients to vote by making an explicit request to the server they consider active. We’ll use snapshot requests as the voting mechanism.
We make all update messages uniquely identifiable by adding a UUID field. The client generates this, and the server propagates it back on republished updates.
The passive server keeps a “pending list” of updates that it has received from clients, but not yet from the active server; or updates it’s received from the active server, but not yet from the clients. The list is ordered from oldest to newest, so that it is easy to remove updates off the head.
It’s useful to design the client logic as a finite state machine. The client cycles through three states:
The client opens and connects its sockets, and then requests a snapshot from the first server. To avoid request storms, it will ask any given server only twice. One request might get lost, which would be bad luck. Two getting lost would be carelessness.
The client waits for a reply (snapshot data) from the current server, and if it gets it, it stores it. If there is no reply within some timeout, it fails over to the next server.
When the client has gotten its snapshot, it waits for and processes updates. Again, if it doesn’t hear anything from the server within some timeout, it fails over to the next server.
The client loops forever. It’s quite likely during startup or failover that some clients may be trying to talk to the primary server while others are trying to talk to the backup server. The Binary Star state machine handles this, hopefully accurately. It’s hard to prove software correct; instead we hammer it until we can’t prove it wrong.
Failover happens as follows:
The client detects that primary server is no longer sending heartbeats, and concludes that it has died. The client connects to the backup server and requests a new state snapshot.
The backup server starts to receive snapshot requests from clients, and detects that primary server has gone, so it takes over as primary.
The backup server applies its pending list to its own hash table, and then starts to process state snapshot requests.
When the primary server comes back online, it will:
Start up as passive server, and connect to the backup server as a Clone client.
Start to receive updates from clients, via its SUB socket.
We make a few assumptions:
At least one server will keep running. If both servers crash, we lose all server state and there’s no way to recover it.
Multiple clients do not update the same hash keys at the same time. Client updates will arrive at the two servers in a different order. Therefore, the backup server may apply updates from its pending list in a different order than the primary server would or did. Updates from one client will always arrive in the same order on both servers, so that is safe.
Thus the architecture for our high-availability server pair using the Binary Star pattern has two servers and a set of clients that talk to both servers.
Here is the sixth and last model of the Clone server:
// Clone server Model Six
// Lets us build this source without creating a library
#include"bstar.c"#include"kvmsg.c"// .split definitions
// We define a set of reactor handlers and our server object structure:
// Bstar reactor handlers
staticints_snapshots (zloop_t *loop, zmq_pollitem_t *poller, void *args);
staticints_collector (zloop_t *loop, zmq_pollitem_t *poller, void *args);
staticints_flush_ttl (zloop_t *loop, int timer_id, void *args);
staticints_send_hugz (zloop_t *loop, int timer_id, void *args);
staticints_new_active (zloop_t *loop, zmq_pollitem_t *poller, void *args);
staticints_new_passive (zloop_t *loop, zmq_pollitem_t *poller, void *args);
staticints_subscriber (zloop_t *loop, zmq_pollitem_t *poller, void *args);
// Our server is defined by these properties
typedefstruct {
zctx_t *ctx; // Context wrapper
zhash_t *kvmap; // Key-value store
bstar_t *bstar; // Bstar reactor core
int64_t sequence; // How many updates we're at
int port; // Main port we're working on
int peer; // Main port of our peer
void *publisher; // Publish updates and hugz
void *collector; // Collect updates from clients
void *subscriber; // Get updates from peer
zlist_t *pending; // Pending updates from clients
bool primary; // true if we're primary
bool active; // true if we're active
bool passive; // true if we're passive
} clonesrv_t;
// .split main task setup
// The main task parses the command line to decide whether to start
// as a primary or backup server. We're using the Binary Star pattern
// for reliability. This interconnects the two servers so they can
// agree on which one is primary and which one is backup. To allow the
// two servers to run on the same box, we use different ports for
// primary and backup. Ports 5003/5004 are used to interconnect the
// servers. Ports 5556/5566 are used to receive voting events (snapshot
// requests in the clone pattern). Ports 5557/5567 are used by the
// publisher, and ports 5558/5568 are used by the collector:
intmain (int argc, char *argv [])
{
clonesrv_t *self = (clonesrv_t *) zmalloc (sizeof (clonesrv_t));
if (argc == 2 && streq (argv [1], "-p")) {
zclock_log ("I: primary active, waiting for backup (passive)");
self->bstar = bstar_new (BSTAR_PRIMARY, "tcp://*:5003",
"tcp://localhost:5004");
bstar_voter (self->bstar, "tcp://*:5556",
ZMQ_ROUTER, s_snapshots, self);
self->port = 5556;
self->peer = 5566;
self->primary = true;
}
elseif (argc == 2 && streq (argv [1], "-b")) {
zclock_log ("I: backup passive, waiting for primary (active)");
self->bstar = bstar_new (BSTAR_BACKUP, "tcp://*:5004",
"tcp://localhost:5003");
bstar_voter (self->bstar, "tcp://*:5566",
ZMQ_ROUTER, s_snapshots, self);
self->port = 5566;
self->peer = 5556;
self->primary = false;
}
else {
printf ("Usage: clonesrv6 { -p | -b }\n");
free (self);
exit (0);
}
// Primary server will become first active
if (self->primary)
self->kvmap = zhash_new ();
self->ctx = zctx_new ();
self->pending = zlist_new ();
bstar_set_verbose (self->bstar, true);
// Set up our clone server sockets
self->publisher = zsocket_new (self->ctx, ZMQ_PUB);
self->collector = zsocket_new (self->ctx, ZMQ_SUB);
zsocket_set_subscribe (self->collector, "");
zsocket_bind (self->publisher, "tcp://*:%d", self->port + 1);
zsocket_bind (self->collector, "tcp://*:%d", self->port + 2);
// Set up our own clone client interface to peer
self->subscriber = zsocket_new (self->ctx, ZMQ_SUB);
zsocket_set_subscribe (self->subscriber, "");
zsocket_connect (self->subscriber,
"tcp://localhost:%d", self->peer + 1);
// .split main task body
// After we've setup our sockets, we register our binary star
// event handlers, and then start the bstar reactor. This finishes
// when the user presses Ctrl-C or when the process receives a SIGINT
// interrupt:
// Register state change handlers
bstar_new_active (self->bstar, s_new_active, self);
bstar_new_passive (self->bstar, s_new_passive, self);
// Register our other handlers with the bstar reactor
zmq_pollitem_t poller = { self->collector, 0, ZMQ_POLLIN };
zloop_poller (bstar_zloop (self->bstar), &poller, s_collector, self);
zloop_timer (bstar_zloop (self->bstar), 1000, 0, s_flush_ttl, self);
zloop_timer (bstar_zloop (self->bstar), 1000, 0, s_send_hugz, self);
// Start the bstar reactor
bstar_start (self->bstar);
// Interrupted, so shut down
while (zlist_size (self->pending)) {
kvmsg_t *kvmsg = (kvmsg_t *) zlist_pop (self->pending);
kvmsg_destroy (&kvmsg);
}
zlist_destroy (&self->pending);
bstar_destroy (&self->bstar);
zhash_destroy (&self->kvmap);
zctx_destroy (&self->ctx);
free (self);
return0;
}
// We handle ICANHAZ? requests exactly as in the clonesrv5 example.
// .skip
// Routing information for a key-value snapshot
typedefstruct {
void *socket; // ROUTER socket to send to
zframe_t *identity; // Identity of peer who requested state
char *subtree; // Client subtree specification
} kvroute_t;
// Send one state snapshot key-value pair to a socket
// Hash item data is our kvmsg object, ready to send
staticints_send_single (constchar *key, void *data, void *args)
{
kvroute_t *kvroute = (kvroute_t *) args;
kvmsg_t *kvmsg = (kvmsg_t *) data;
if (strlen (kvroute->subtree) <= strlen (kvmsg_key (kvmsg))
&& memcmp (kvroute->subtree,
kvmsg_key (kvmsg), strlen (kvroute->subtree)) == 0) {
zframe_send (&kvroute->identity, // Choose recipient
kvroute->socket, ZFRAME_MORE + ZFRAME_REUSE);
kvmsg_send (kvmsg, kvroute->socket);
}
return0;
}
staticints_snapshots (zloop_t *loop, zmq_pollitem_t *poller, void *args)
{
clonesrv_t *self = (clonesrv_t *) args;
zframe_t *identity = zframe_recv (poller->socket);
if (identity) {
// Request is in second frame of message
char *request = zstr_recv (poller->socket);
char *subtree = NULL;
if (streq (request, "ICANHAZ?")) {
free (request);
subtree = zstr_recv (poller->socket);
}
else
printf ("E: bad request, aborting\n");
if (subtree) {
// Send state socket to client
kvroute_t routing = { poller->socket, identity, subtree };
zhash_foreach (self->kvmap, s_send_single, &routing);
// Now send END message with sequence number
zclock_log ("I: sending shapshot=%d", (int) self->sequence);
zframe_send (&identity, poller->socket, ZFRAME_MORE);
kvmsg_t *kvmsg = kvmsg_new (self->sequence);
kvmsg_set_key (kvmsg, "KTHXBAI");
kvmsg_set_body (kvmsg, (byte *) subtree, 0);
kvmsg_send (kvmsg, poller->socket);
kvmsg_destroy (&kvmsg);
free (subtree);
}
zframe_destroy(&identity);
}
return0;
}
// .until
// .split collect updates
// The collector is more complex than in the clonesrv5 example because the
// way it processes updates depends on whether we're active or passive.
// The active applies them immediately to its kvmap, whereas the passive
// queues them as pending:
// If message was already on pending list, remove it and return true,
// else return false.
staticints_was_pending (clonesrv_t *self, kvmsg_t *kvmsg)
{
kvmsg_t *held = (kvmsg_t *) zlist_first (self->pending);
while (held) {
if (memcmp (kvmsg_uuid (kvmsg),
kvmsg_uuid (held), sizeof (uuid_t)) == 0) {
zlist_remove (self->pending, held);
returntrue;
}
held = (kvmsg_t *) zlist_next (self->pending);
}
returnfalse;
}
staticints_collector (zloop_t *loop, zmq_pollitem_t *poller, void *args)
{
clonesrv_t *self = (clonesrv_t *) args;
kvmsg_t *kvmsg = kvmsg_recv (poller->socket);
if (kvmsg) {
if (self->active) {
kvmsg_set_sequence (kvmsg, ++self->sequence);
kvmsg_send (kvmsg, self->publisher);
int ttl = atoi (kvmsg_get_prop (kvmsg, "ttl"));
if (ttl)
kvmsg_set_prop (kvmsg, "ttl",
"%" PRId64, zclock_time () + ttl * 1000);
kvmsg_store (&kvmsg, self->kvmap);
zclock_log ("I: publishing update=%d", (int) self->sequence);
}
else {
// If we already got message from active, drop it, else
// hold on pending list
if (s_was_pending (self, kvmsg))
kvmsg_destroy (&kvmsg);
else
zlist_append (self->pending, kvmsg);
}
}
return0;
}
// We purge ephemeral values using exactly the same code as in
// the previous clonesrv5 example.
// .skip
// If key-value pair has expired, delete it and publish the
// fact to listening clients.
staticints_flush_single (constchar *key, void *data, void *args)
{
clonesrv_t *self = (clonesrv_t *) args;
kvmsg_t *kvmsg = (kvmsg_t *) data;
int64_t ttl;
sscanf (kvmsg_get_prop (kvmsg, "ttl"), "%" PRId64, &ttl);
if (ttl && zclock_time () >= ttl) {
kvmsg_set_sequence (kvmsg, ++self->sequence);
kvmsg_set_body (kvmsg, (byte *) "", 0);
kvmsg_send (kvmsg, self->publisher);
kvmsg_store (&kvmsg, self->kvmap);
zclock_log ("I: publishing delete=%d", (int) self->sequence);
}
return0;
}
staticints_flush_ttl (zloop_t *loop, int timer_id, void *args)
{
clonesrv_t *self = (clonesrv_t *) args;
if (self->kvmap)
zhash_foreach (self->kvmap, s_flush_single, args);
return0;
}
// .until
// .split heartbeating
// We send a HUGZ message once a second to all subscribers so that they
// can detect if our server dies. They'll then switch over to the backup
// server, which will become active:
staticints_send_hugz (zloop_t *loop, int timer_id, void *args)
{
clonesrv_t *self = (clonesrv_t *) args;
kvmsg_t *kvmsg = kvmsg_new (self->sequence);
kvmsg_set_key (kvmsg, "HUGZ");
kvmsg_set_body (kvmsg, (byte *) "", 0);
kvmsg_send (kvmsg, self->publisher);
kvmsg_destroy (&kvmsg);
return0;
}
// .split handling state changes
// When we switch from passive to active, we apply our pending list so that
// our kvmap is up-to-date. When we switch to passive, we wipe our kvmap
// and grab a new snapshot from the active server:
staticints_new_active (zloop_t *loop, zmq_pollitem_t *unused, void *args)
{
clonesrv_t *self = (clonesrv_t *) args;
self->active = true;
self->passive = false;
// Stop subscribing to updates
zmq_pollitem_t poller = { self->subscriber, 0, ZMQ_POLLIN };
zloop_poller_end (bstar_zloop (self->bstar), &poller);
// Apply pending list to own hash table
while (zlist_size (self->pending)) {
kvmsg_t *kvmsg = (kvmsg_t *) zlist_pop (self->pending);
kvmsg_set_sequence (kvmsg, ++self->sequence);
kvmsg_send (kvmsg, self->publisher);
kvmsg_store (&kvmsg, self->kvmap);
zclock_log ("I: publishing pending=%d", (int) self->sequence);
}
return0;
}
staticints_new_passive (zloop_t *loop, zmq_pollitem_t *unused, void *args)
{
clonesrv_t *self = (clonesrv_t *) args;
zhash_destroy (&self->kvmap);
self->active = false;
self->passive = true;
// Start subscribing to updates
zmq_pollitem_t poller = { self->subscriber, 0, ZMQ_POLLIN };
zloop_poller (bstar_zloop (self->bstar), &poller, s_subscriber, self);
return0;
}
// .split subscriber handler
// When we get an update, we create a new kvmap if necessary, and then
// add our update to our kvmap. We're always passive in this case:
staticints_subscriber (zloop_t *loop, zmq_pollitem_t *poller, void *args)
{
clonesrv_t *self = (clonesrv_t *) args;
// Get state snapshot if necessary
if (self->kvmap == NULL) {
self->kvmap = zhash_new ();
void *snapshot = zsocket_new (self->ctx, ZMQ_DEALER);
zsocket_connect (snapshot, "tcp://localhost:%d", self->peer);
zclock_log ("I: asking for snapshot from: tcp://localhost:%d",
self->peer);
zstr_sendm (snapshot, "ICANHAZ?");
zstr_send (snapshot, ""); // blank subtree to get all
while (true) {
kvmsg_t *kvmsg = kvmsg_recv (snapshot);
if (!kvmsg)
break; // Interrupted
if (streq (kvmsg_key (kvmsg), "KTHXBAI")) {
self->sequence = kvmsg_sequence (kvmsg);
kvmsg_destroy (&kvmsg);
break; // Done
}
kvmsg_store (&kvmsg, self->kvmap);
}
zclock_log ("I: received snapshot=%d", (int) self->sequence);
zsocket_destroy (self->ctx, snapshot);
}
// Find and remove update off pending list
kvmsg_t *kvmsg = kvmsg_recv (poller->socket);
if (!kvmsg)
return0;
if (strneq (kvmsg_key (kvmsg), "HUGZ")) {
if (!s_was_pending (self, kvmsg)) {
// If active update came before client update, flip it
// around, store active update (with sequence) on pending
// list and use to clear client update when it comes later
zlist_append (self->pending, kvmsg_dup (kvmsg));
}
// If update is more recent than our kvmap, apply it
if (kvmsg_sequence (kvmsg) > self->sequence) {
self->sequence = kvmsg_sequence (kvmsg);
kvmsg_store (&kvmsg, self->kvmap);
zclock_log ("I: received update=%d", (int) self->sequence);
}
else
kvmsg_destroy (&kvmsg);
}
else
kvmsg_destroy (&kvmsg);
return0;
}
packageguide;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Map.Entry;
importorg.zeromq.SocketType;
importorg.zeromq.ZContext;
importorg.zeromq.ZLoop;
importorg.zeromq.ZLoop.IZLoopHandler;
importorg.zeromq.ZMQ;
importorg.zeromq.ZMQ.PollItem;
importorg.zeromq.ZMQ.Socket;
// Clone server - Model Six
publicclassclonesrv6
{
private ZContext ctx; // Context wrapper
private Map<String, kvmsg> kvmap; // Key-value store
private bstar bStar; // Bstar reactor core
privatelong sequence; // How many updates we're at
privateint port; // Main port we're working on
privateint peer; // Main port of our peer
private Socket publisher; // Publish updates and hugz
private Socket collector; // Collect updates from clients
private Socket subscriber; // Get updates from peer
private List<kvmsg> pending; // Pending updates from clients
privateboolean primary; // TRUE if we're primary
privateboolean active; // TRUE if we're active
privateboolean passive; // TRUE if we're passive
privatestaticclassSnapshotsimplements IZLoopHandler
{
@Overridepublicinthandle(ZLoop loop, PollItem item, Object arg)
{
clonesrv6 srv = (clonesrv6) arg;
Socket socket = item.getSocket();
byte[] identity = socket.recv();
if (identity != null) {
// Request is in second frame of message
String request = socket.recvStr();
String subtree = null;
if (request.equals("ICANHAZ?")) {
subtree = socket.recvStr();
}
else System.out.printf("E: bad request, aborting\n");
if (subtree != null) {
// Send state socket to client
for (Entry<String, kvmsg> entry : srv.kvmap.entrySet()) {
sendSingle(entry.getValue(), identity, subtree, socket);
}
// Now send END message with getSequence number
System.out.printf("I: sending shapshot=%d\n", srv.sequence);
socket.send(identity, ZMQ.SNDMORE);
kvmsg kvmsg = new kvmsg(srv.sequence);
kvmsg.setKey("KTHXBAI");
kvmsg.setBody(subtree.getBytes(ZMQ.CHARSET));
kvmsg.send(socket);
kvmsg.destroy();
}
}
return 0;
}
}
privatestaticclassCollectorimplements IZLoopHandler
{
@Overridepublicinthandle(ZLoop loop, PollItem item, Object arg)
{
clonesrv6 srv = (clonesrv6) arg;
Socket socket = item.getSocket();
kvmsg msg = kvmsg.recv(socket);
if (msg != null) {
if (srv.active) {
msg.setSequence(++srv.sequence);
msg.send(srv.publisher);
int ttl = Integer.parseInt(msg.getProp("ttl"));
if (ttl > 0)
msg.setProp("ttl", "%d", System.currentTimeMillis() + ttl * 1000);
msg.store(srv.kvmap);
System.out.printf("I: publishing update=%d\n", srv.sequence);
}
else {
// If we already got message from active, drop it, else
// hold on pending list
if (srv.wasPending(msg))
msg.destroy();
else srv.pending.add(msg);
}
}
return 0;
}
}
// .split heartbeating
// We send a HUGZ message once a second to all subscribers so that they
// can detect if our server dies. They'll then switch over to the backup
// server, which will become active:
privatestaticclassSendHugzimplements IZLoopHandler
{
@Overridepublicinthandle(ZLoop loop, PollItem item, Object arg)
{
clonesrv6 srv = (clonesrv6) arg;
kvmsg msg = new kvmsg(srv.sequence);
msg.setKey("HUGZ");
msg.setBody(ZMQ.MESSAGE_SEPARATOR);
msg.send(srv.publisher);
msg.destroy();
return 0;
}
}
privatestaticclassFlushTTLimplements IZLoopHandler
{
@Overridepublicinthandle(ZLoop loop, PollItem item, Object arg)
{
clonesrv6 srv = (clonesrv6) arg;
if (srv.kvmap != null) {
for (kvmsg msg : new ArrayList<kvmsg>(srv.kvmap.values())) {
srv.flushSingle(msg);
}
}
return 0;
}
}
// .split handling state changes
// When we switch from passive to active, we apply our pending list so that
// our kvmap is up-to-date. When we switch to passive, we wipe our kvmap
// and grab a new snapshot from the active server:
privatestaticclassNewActiveimplements IZLoopHandler
{
@Overridepublicinthandle(ZLoop loop, PollItem item, Object arg)
{
clonesrv6 srv = (clonesrv6) arg;
srv.active = true;
srv.passive = false;
// Stop subscribing to updates
PollItem poller = new PollItem(srv.subscriber, ZMQ.Poller.POLLIN);
srv.bStar.zloop().removePoller(poller);
// Apply pending list to own hash table
for (kvmsg msg : srv.pending) {
msg.setSequence(++srv.sequence);
msg.send(srv.publisher);
msg.store(srv.kvmap);
System.out.printf("I: publishing pending=%d\n", srv.sequence);
}
return 0;
}
}
privatestaticclassNewPassiveimplements IZLoopHandler
{
@Overridepublicinthandle(ZLoop loop, PollItem item, Object arg)
{
clonesrv6 srv = (clonesrv6) arg;
if (srv.kvmap != null) {
for (kvmsg msg : srv.kvmap.values())
msg.destroy();
}
srv.active = false;
srv.passive = true;
// Start subscribing to updates
PollItem poller = new PollItem(srv.subscriber, ZMQ.Poller.POLLIN);
srv.bStar.zloop().addPoller(poller, new Subscriber(), srv);
return 0;
}
}
// .split subscriber handler
// When we get an update, we create a new kvmap if necessary, and then
// add our update to our kvmap. We're always passive in this case:
privatestaticclassSubscriberimplements IZLoopHandler
{
@Overridepublicinthandle(ZLoop loop, PollItem item, Object arg)
{
clonesrv6 srv = (clonesrv6) arg;
Socket socket = item.getSocket();
// Get state snapshot if necessary
if (srv.kvmap == null) {
srv.kvmap = new HashMap<String, kvmsg>();
Socket snapshot = srv.ctx.createSocket(SocketType.DEALER);
snapshot.connect(String.format("tcp://localhost:%d", srv.peer));
System.out.printf("I: asking for snapshot from: tcp://localhost:%d\n", srv.peer);
snapshot.sendMore("ICANHAZ?");
snapshot.send(""); // blank subtree to get all
while (true) {
kvmsg msg = kvmsg.recv(snapshot);
if (msg == null)
break; // Interrupted
if (msg.getKey().equals("KTHXBAI")) {
srv.sequence = msg.getSequence();
msg.destroy();
break; // Done
}
msg.store(srv.kvmap);
}
System.out.printf("I: received snapshot=%d\n", srv.sequence);
srv.ctx.destroySocket(snapshot);
}
// Find and remove update off pending list
kvmsg msg = kvmsg.recv(item.getSocket());
if (msg == null)
return 0;
if (!msg.getKey().equals("HUGZ")) {
if (!srv.wasPending(msg)) {
// If active update came before client update, flip it
// around, store active update (with sequence) on pending
// list and use to clear client update when it comes later
srv.pending.add(msg.dup());
}
// If update is more recent than our kvmap, apply it
if (msg.getSequence() > srv.sequence) {
srv.sequence = msg.getSequence();
msg.store(srv.kvmap);
System.out.printf("I: received update=%d\n", srv.sequence);
}
}
msg.destroy();
return 0;
}
}
publicclonesrv6(boolean primary)
{
if (primary) {
bStar = new bstar(true, "tcp://*:5003", "tcp://localhost:5004");
bStar.voter("tcp://*:5556", SocketType.ROUTER, new Snapshots(), this);
port = 5556;
peer = 5566;
this.primary = true;
}
else {
bStar = new bstar(false, "tcp://*:5004", "tcp://localhost:5003");
bStar.voter("tcp://*:5566", SocketType.ROUTER, new Snapshots(), this);
port = 5566;
peer = 5556;
this.primary = false;
}
// Primary server will become first active
if (primary)
kvmap = new HashMap<String, kvmsg>();
ctx = new ZContext();
pending = new ArrayList<kvmsg>();
bStar.setVerbose(true);
// Set up our clone server sockets
publisher = ctx.createSocket(SocketType.PUB);
collector = ctx.createSocket(SocketType.SUB);
collector.subscribe(ZMQ.SUBSCRIPTION_ALL);
publisher.bind(String.format("tcp://*:%d", port + 1));
collector.bind(String.format("tcp://*:%d", port + 2));
// Set up our own clone client interface to peer
subscriber = ctx.createSocket(SocketType.SUB);
subscriber.subscribe(ZMQ.SUBSCRIPTION_ALL);
subscriber.connect(String.format("tcp://localhost:%d", peer + 1));
}
// .split main task body
// After we've setup our sockets, we register our binary star
// event handlers, and then start the bstar reactor. This finishes
// when the user presses Ctrl-C or when the process receives a SIGINT
// interrupt:
publicvoidrun()
{
// Register state change handlers
bStar.newActive(new NewActive(), this);
bStar.newPassive(new NewPassive(), this);
// Register our other handlers with the bstar reactor
PollItem poller = new PollItem(collector, ZMQ.Poller.POLLIN);
bStar.zloop().addPoller(poller, new Collector(), this);
bStar.zloop().addTimer(1000, 0, new FlushTTL(), this);
bStar.zloop().addTimer(1000, 0, new SendHugz(), this);
// Start the bstar reactor
bStar.start();
// Interrupted, so shut down
for (kvmsg value : pending)
value.destroy();
bStar.destroy();
for (kvmsg value : kvmap.values())
value.destroy();
ctx.destroy();
}
// Send one state snapshot key-value pair to a socket
// Hash item data is our kvmsg object, ready to send
privatestaticvoidsendSingle(kvmsg msg, byte[] identity, String subtree, Socket socket)
{
if (msg.getKey().startsWith(subtree)) {
socket.send(identity, // Choose recipient
ZMQ.SNDMORE);
msg.send(socket);
}
}
// The collector is more complex than in the clonesrv5 example because the
// way it processes updates depends on whether we're active or passive.
// The active applies them immediately to its kvmap, whereas the passive
// queues them as pending:
// If message was already on pending list, remove it and return TRUE,
// else return FALSE.
booleanwasPending(kvmsg msg)
{
Iterator<kvmsg> it = pending.iterator();
while (it.hasNext()) {
if (java.util.Arrays.equals(msg.UUID(), it.next().UUID())) {
it.remove();
returntrue;
}
}
returnfalse;
}
// We purge ephemeral values using exactly the same code as in
// the previous clonesrv5 example.
// .skip
// If key-value pair has expired, delete it and publish the
// fact to listening clients.
privatevoidflushSingle(kvmsg msg)
{
long ttl = Long.parseLong(msg.getProp("ttl"));
if (ttl > 0 && System.currentTimeMillis() >= ttl) {
msg.setSequence(++sequence);
msg.setBody(ZMQ.MESSAGE_SEPARATOR);
msg.send(publisher);
msg.store(kvmap);
System.out.printf("I: publishing delete=%d\n", sequence);
}
}
// .split main task setup
// The main task parses the command line to decide whether to start
// as a primary or backup server. We're using the Binary Star pattern
// for reliability. This interconnects the two servers so they can
// agree on which one is primary and which one is backup. To allow the
// two servers to run on the same box, we use different ports for
// primary and backup. Ports 5003/5004 are used to interconnect the
// servers. Ports 5556/5566 are used to receive voting events (snapshot
// requests in the clone pattern). Ports 5557/5567 are used by the
// publisher, and ports 5558/5568 are used by the collector:
publicstaticvoidmain(String[] args)
{
clonesrv6 srv = null;
if (args.length == 1 && "-p".equals(args[0])) {
srv = new clonesrv6(true);
}
elseif (args.length == 1 && "-b".equals(args[0])) {
srv = new clonesrv6(false);
}
else {
System.out.printf("Usage: clonesrv4 { -p | -b }\n");
System.exit(0);
}
srv.run();
}
}
This model is only a few hundred lines of code, but it took quite a while to get working. To be accurate, building Model Six took about a full week of “Sweet god, this is just too complex for an example” hacking. We’ve assembled pretty much everything and the kitchen sink into this small application. We have failover, ephemeral values, subtrees, and so on. What surprised me was that the up-front design was pretty accurate. Still the details of writing and debugging so many socket flows is quite challenging.
The reactor-based design removes a lot of the grunt work from the code, and what remains is simpler and easier to understand. We reuse the bstar reactor from
Chapter 4 - Reliable Request-Reply Patterns. The whole server runs as one thread, so there’s no inter-thread weirdness going on–just a structure pointer (self) passed around to all handlers, which can do their thing happily. One nice side effect of using reactors is that the code, being less tightly integrated into a poll loop, is much easier to reuse. Large chunks of Model Six are taken from Model Five.
I built it piece by piece, and got each piece working properly before going onto the next one. Because there are four or five main socket flows, that meant quite a lot of debugging and testing. I debugged just by dumping messages to the console. Don’t use classic debuggers to step through ZeroMQ applications; you need to see the message flows to make any sense of what is going on.
For testing, I always try to use Valgrind, which catches memory leaks and invalid memory accesses. In C, this is a major concern, as you can’t delegate to a garbage collector. Using proper and consistent abstractions like kvmsg and CZMQ helps enormously.
While the server is pretty much a mashup of the previous model plus the Binary Star pattern, the client is quite a lot more complex. But before we get to that, let’s look at the final protocol. I’ve written this up as a specification on the ZeroMQ RFC website as the
Clustered Hashmap Protocol.
Roughly, there are two ways to design a complex protocol such as this one. One way is to separate each flow into its own set of sockets. This is the approach we used here. The advantage is that each flow is simple and clean. The disadvantage is that managing multiple socket flows at once can be quite complex. Using a reactor makes it simpler, but still, it makes a lot of moving pieces that have to fit together correctly.
The second way to make such a protocol is to use a single socket pair for everything. In this case, I’d have used ROUTER for the server and DEALER for the clients, and then done everything over that connection. It makes for a more complex protocol but at least the complexity is all in one place. In
Chapter 7 - Advanced Architecture using ZeroMQ we’ll look at an example of a protocol done over a ROUTER-DEALER combination.
Let’s take a look at the CHP specification. Note that “SHOULD”, “MUST” and “MAY” are key words we use in protocol specifications to indicate requirement levels.
Goals
CHP is meant to provide a basis for reliable pub-sub across a cluster of clients connected over a ZeroMQ network. It defines a “hashmap” abstraction consisting of key-value pairs. Any client can modify any key-value pair at any time, and changes are propagated to all clients. A client can join the network at any time.
Architecture
CHP connects a set of client applications and a set of servers. Clients connect to the server. Clients do not see each other. Clients can come and go arbitrarily.
Ports and Connections
The server MUST open three ports as follows:
A SNAPSHOT port (ZeroMQ ROUTER socket) at port number P.
A PUBLISHER port (ZeroMQ PUB socket) at port number P + 1.
A COLLECTOR port (ZeroMQ SUB socket) at port number P + 2.
The client SHOULD open at least two connections:
A SNAPSHOT connection (ZeroMQ DEALER socket) to port number P.
A SUBSCRIBER connection (ZeroMQ SUB socket) to port number P + 1.
The client MAY open a third connection, if it wants to update the hashmap:
A PUBLISHER connection (ZeroMQ PUB socket) to port number P + 2.
This extra frame is not shown in the commands explained below.
State Synchronization
The client MUST start by sending a ICANHAZ command to its snapshot connection. This command consists of two frames as follows:
Both frames are ZeroMQ strings. The subtree specification MAY be empty. If not empty, it consists of a slash followed by one or more path segments, ending in a slash.
The server MUST respond to a ICANHAZ command by sending zero or more KVSYNC commands to its snapshot port, followed with a KTHXBAI command. The server MUST prefix each command with the identity of the client, as provided by ZeroMQ with the ICANHAZ command. The KVSYNC command specifies a single key-value pair as follows:
KVSYNC command
-----------------------------------
Frame 0: key, as ZeroMQ string
Frame 1: sequence number, 8 bytes in network order
Frame 2: <empty>
Frame 3: <empty>
Frame 4: value, as blob
The sequence number has no significance and may be zero.
The sequence number MUST be the highest sequence number of the KVSYNC commands previously sent.
When the client has received a KTHXBAI command, it SHOULD start to receive messages from its subscriber connection and apply them.
Server-to-Client Updates
When the server has an update for its hashmap it MUST broadcast this on its publisher socket as a KVPUB command. The KVPUB command has this form:
KVPUB command
-----------------------------------
Frame 0: key, as ZeroMQ string
Frame 1: sequence number, 8 bytes in network order
Frame 2: UUID, 16 bytes
Frame 3: properties, as ZeroMQ string
Frame 4: value, as blob
The sequence number MUST be strictly incremental. The client MUST discard any KVPUB commands whose sequence numbers are not strictly greater than the last KTHXBAI or KVPUB command received.
The UUID is optional and frame 2 MAY be empty (size zero). The properties field is formatted as zero or more instances of “name=value” followed by a newline character. If the key-value pair has no properties, the properties field is empty.
If the value is empty, the client SHOULD delete its key-value entry with the specified key.
In the absence of other updates the server SHOULD send a HUGZ command at regular intervals, e.g., once per second. The HUGZ command has this format:
The client MAY treat the absence of HUGZ as an indicator that the server has crashed (see Reliability below).
Client-to-Server Updates
When the client has an update for its hashmap, it MAY send this to the server via its publisher connection as a KVSET command. The KVSET command has this form:
KVSET command
-----------------------------------
Frame 0: key, as ZeroMQ string
Frame 1: sequence number, 8 bytes in network order
Frame 2: UUID, 16 bytes
Frame 3: properties, as ZeroMQ string
Frame 4: value, as blob
The sequence number has no significance and may be zero. The UUID SHOULD be a universally unique identifier, if a reliable server architecture is used.
If the value is empty, the server MUST delete its key-value entry with the specified key.
The server SHOULD accept the following properties:
ttl: specifies a time-to-live in seconds. If the KVSET command has a ttl property, the server SHOULD delete the key-value pair and broadcast a KVPUB with an empty value in order to delete this from all clients when the TTL has expired.
Reliability
CHP may be used in a dual-server configuration where a backup server takes over if the primary server fails. CHP does not specify the mechanisms used for this failover but the Binary Star pattern may be helpful.
To assist server reliability, the client MAY:
Set a UUID in every KVSET command.
Detect the lack of HUGZ over a time period and use this as an indicator that the current server has failed.
Connect to a backup server and re-request a state synchronization.
Scalability and Performance
CHP is designed to be scalable to large numbers (thousands) of clients, limited only by system resources on the broker. Because all updates pass through a single server, the overall throughput will be limited to some millions of updates per second at peak, and probably less.
Security
CHP does not implement any authentication, access control, or encryption mechanisms and should not be used in any deployment where these are required.
The client stack we’ve used so far isn’t smart enough to handle this protocol properly. As soon as we start doing heartbeats, we need a client stack that can run in a background thread. In the Freelance pattern at the end of
Chapter 4 - Reliable Request-Reply Patterns we used a multithreaded API but didn’t explain it in detail. It turns out that multithreaded APIs are quite useful when you start to make more complex ZeroMQ protocols like CHP.
If you make a nontrivial protocol and you expect applications to implement it properly, most developers will get it wrong most of the time. You’re going to be left with a lot of unhappy people complaining that your protocol is too complex, too fragile, and too hard to use. Whereas if you give them a simple API to call, you have some chance of them buying in.
Our multithreaded API consists of a frontend object and a background agent, connected by two PAIR sockets. Connecting two PAIR sockets like this is so useful that your high-level binding should probably do what CZMQ does, which is package a “create new thread with a pipe that I can use to send messages to it” method.
The multithreaded APIs that we see in this book all take the same form:
The constructor for the object (clone_new) creates a context and starts a background thread connected with a pipe. It holds onto one end of the pipe so it can send commands to the background thread.
The background thread starts an agent that is essentially a zmq_poll loop reading from the pipe socket and any other sockets (here, the DEALER and SUB sockets).
The main application thread and the background thread now communicate only via ZeroMQ messages. By convention, the frontend sends string commands so that each method on the class turns into a message sent to the backend agent, like this:
If the method needs a return code, it can wait for a reply message from the agent.
If the agent needs to send asynchronous events back to the frontend, we add a recv method to the class, which waits for messages on the frontend pipe.
We may want to expose the frontend pipe socket handle to allow the class to be integrated into further poll loops. Otherwise any recv method would block the application.
The clone class has the same structure as the flcliapi class from
Chapter 4 - Reliable Request-Reply Patterns and adds the logic from the last model of the Clone client. Without ZeroMQ, this kind of multithreaded API design would be weeks of really hard work. With ZeroMQ, it was a day or two of work.
The actual API methods for the clone class are quite simple:
// Create a new clone class instance
clone_t *
clone_new (void);
// Destroy a clone class instance
voidclone_destroy (clone_t **self_p);
// Define the subtree, if any, for this clone class
voidclone_subtree (clone_t *self, char *subtree);
// Connect the clone class to one server
voidclone_connect (clone_t *self, char *address, char *service);
// Set a value in the shared hashmap
voidclone_set (clone_t *self, char *key, char *value, int ttl);
// Get a value from the shared hashmap
char *
clone_get (clone_t *self, char *key);
So here is Model Six of the clone client, which has now become just a thin shell using the clone class:
Note the connect method, which specifies one server endpoint. Under the hood, we’re in fact talking to three ports. However, as the CHP protocol says, the three ports are on consecutive port numbers:
The server state router (ROUTER) is at port P.
The server updates publisher (PUB) is at port P + 1.
The server updates subscriber (SUB) is at port P + 2.
So we can fold the three connections into one logical operation (which we implement as three separate ZeroMQ connect calls).
Let’s end with the source code for the clone stack. This is a complex piece of code, but easier to understand when you break it into the frontend object class and the backend agent. The frontend sends string commands (“SUBTREE”, “CONNECT”, “SET”, “GET”) to the agent, which handles these commands as well as talking to the server(s). Here is the agent’s logic:
Start up by getting a snapshot from the first server
When we get a snapshot switch to reading from the subscriber socket.
If we don’t get a snapshot then fail over to the second server.
Poll on the pipe and the subscriber socket.
If we got input on the pipe, handle the control message from the frontend object.
If we got input on the subscriber, store or apply the update.
If we didn’t get anything from the server within a certain time, fail over.
Repeat until the process is interrupted by Ctrl-C.
And here is the actual clone class implementation:
// clone class - Clone client API stack (multithreaded)
#include"clone.h"// If no server replies within this time, abandon request
#define GLOBAL_TIMEOUT 4000 // msecs
// =====================================================================
// Synchronous part, works in our application thread
// Structure of our class
struct _clone_t {
zctx_t *ctx; // Our context wrapper
void *pipe; // Pipe through to clone agent
};
// This is the thread that handles our real clone class
staticvoidclone_agent (void *args, zctx_t *ctx, void *pipe);
// .split constructor and destructor
// Here are the constructor and destructor for the clone class. Note that
// we create a context specifically for the pipe that connects our
// frontend to the backend agent:
clone_t *
clone_new (void)
{
clone_t
*self;
self = (clone_t *) zmalloc (sizeof (clone_t));
self->ctx = zctx_new ();
self->pipe = zthread_fork (self->ctx, clone_agent, NULL);
return self;
}
voidclone_destroy (clone_t **self_p)
{
assert (self_p);
if (*self_p) {
clone_t *self = *self_p;
zctx_destroy (&self->ctx);
free (self);
*self_p = NULL;
}
}
// .split subtree method
// Specify subtree for snapshot and updates, which we must do before
// connecting to a server as the subtree specification is sent as the
// first command to the server. Sends a [SUBTREE][subtree] command to
// the agent:
voidclone_subtree (clone_t *self, char *subtree)
{
assert (self);
zmsg_t *msg = zmsg_new ();
zmsg_addstr (msg, "SUBTREE");
zmsg_addstr (msg, subtree);
zmsg_send (&msg, self->pipe);
}
// .split connect method
// Connect to a new server endpoint. We can connect to at most two
// servers. Sends [CONNECT][endpoint][service] to the agent:
voidclone_connect (clone_t *self, char *address, char *service)
{
assert (self);
zmsg_t *msg = zmsg_new ();
zmsg_addstr (msg, "CONNECT");
zmsg_addstr (msg, address);
zmsg_addstr (msg, service);
zmsg_send (&msg, self->pipe);
}
// .split set method
// Set a new value in the shared hashmap. Sends a [SET][key][value][ttl]
// command through to the agent which does the actual work:
voidclone_set (clone_t *self, char *key, char *value, int ttl)
{
char ttlstr [10];
sprintf (ttlstr, "%d", ttl);
assert (self);
zmsg_t *msg = zmsg_new ();
zmsg_addstr (msg, "SET");
zmsg_addstr (msg, key);
zmsg_addstr (msg, value);
zmsg_addstr (msg, ttlstr);
zmsg_send (&msg, self->pipe);
}
// .split get method
// Look up value in distributed hash table. Sends [GET][key] to the agent and
// waits for a value response. If there is no value available, will eventually
// return NULL:
char *
clone_get (clone_t *self, char *key)
{
assert (self);
assert (key);
zmsg_t *msg = zmsg_new ();
zmsg_addstr (msg, "GET");
zmsg_addstr (msg, key);
zmsg_send (&msg, self->pipe);
zmsg_t *reply = zmsg_recv (self->pipe);
if (reply) {
char *value = zmsg_popstr (reply);
zmsg_destroy (&reply);
return value;
}
returnNULL;
}
// .split working with servers
// The backend agent manages a set of servers, which we implement using
// our simple class model:
typedefstruct {
char *address; // Server address
int port; // Server port
void *snapshot; // Snapshot socket
void *subscriber; // Incoming updates
uint64_t expiry; // When server expires
uint requests; // How many snapshot requests made?
} server_t;
static server_t *
server_new (zctx_t *ctx, char *address, int port, char *subtree)
{
server_t *self = (server_t *) zmalloc (sizeof (server_t));
zclock_log ("I: adding server %s:%d...", address, port);
self->address = strdup (address);
self->port = port;
self->snapshot = zsocket_new (ctx, ZMQ_DEALER);
zsocket_connect (self->snapshot, "%s:%d", address, port);
self->subscriber = zsocket_new (ctx, ZMQ_SUB);
zsocket_connect (self->subscriber, "%s:%d", address, port + 1);
zsocket_set_subscribe (self->subscriber, subtree);
zsocket_set_subscribe (self->subscriber, "HUGZ");
return self;
}
staticvoidserver_destroy (server_t **self_p)
{
assert (self_p);
if (*self_p) {
server_t *self = *self_p;
free (self->address);
free (self);
*self_p = NULL;
}
}
// .split backend agent class
// Here is the implementation of the backend agent itself:
// Number of servers to which we will talk to
#define SERVER_MAX 2
// Server considered dead if silent for this long
#define SERVER_TTL 5000 // msecs
// States we can be in
#define STATE_INITIAL 0 // Before asking server for state
#define STATE_SYNCING 1 // Getting state from server
#define STATE_ACTIVE 2 // Getting new updates from server
typedefstruct {
zctx_t *ctx; // Context wrapper
void *pipe; // Pipe back to application
zhash_t *kvmap; // Actual key/value table
char *subtree; // Subtree specification, if any
server_t *server [SERVER_MAX];
uint nbr_servers; // 0 to SERVER_MAX
uint state; // Current state
uint cur_server; // If active, server 0 or 1
int64_t sequence; // Last kvmsg processed
void *publisher; // Outgoing updates
} agent_t;
static agent_t *
agent_new (zctx_t *ctx, void *pipe)
{
agent_t *self = (agent_t *) zmalloc (sizeof (agent_t));
self->ctx = ctx;
self->pipe = pipe;
self->kvmap = zhash_new ();
self->subtree = strdup ("");
self->state = STATE_INITIAL;
self->publisher = zsocket_new (self->ctx, ZMQ_PUB);
return self;
}
staticvoidagent_destroy (agent_t **self_p)
{
assert (self_p);
if (*self_p) {
agent_t *self = *self_p;
int server_nbr;
for (server_nbr = 0; server_nbr < self->nbr_servers; server_nbr++)
server_destroy (&self->server [server_nbr]);
zhash_destroy (&self->kvmap);
free (self->subtree);
free (self);
*self_p = NULL;
}
}
// .split handling a control message
// Here we handle the different control messages from the frontend;
// SUBTREE, CONNECT, SET, and GET:
staticintagent_control_message (agent_t *self)
{
zmsg_t *msg = zmsg_recv (self->pipe);
char *command = zmsg_popstr (msg);
if (command == NULL)
return -1; // Interrupted
if (streq (command, "SUBTREE")) {
free (self->subtree);
self->subtree = zmsg_popstr (msg);
}
elseif (streq (command, "CONNECT")) {
char *address = zmsg_popstr (msg);
char *service = zmsg_popstr (msg);
if (self->nbr_servers < SERVER_MAX) {
self->server [self->nbr_servers++] = server_new (
self->ctx, address, atoi (service), self->subtree);
// We broadcast updates to all known servers
zsocket_connect (self->publisher, "%s:%d",
address, atoi (service) + 2);
}
else
zclock_log ("E: too many servers (max. %d)", SERVER_MAX);
free (address);
free (service);
}
else// .split set and get commands
// When we set a property, we push the new key-value pair onto
// all our connected servers:
if (streq (command, "SET")) {
char *key = zmsg_popstr (msg);
char *value = zmsg_popstr (msg);
char *ttl = zmsg_popstr (msg);
// Send key-value pair on to server
kvmsg_t *kvmsg = kvmsg_new (0);
kvmsg_set_key (kvmsg, key);
kvmsg_set_uuid (kvmsg);
kvmsg_fmt_body (kvmsg, "%s", value);
kvmsg_set_prop (kvmsg, "ttl", ttl);
kvmsg_send (kvmsg, self->publisher);
kvmsg_store (&kvmsg, self->kvmap);
free (key);
free (value);
free (ttl);
}
elseif (streq (command, "GET")) {
char *key = zmsg_popstr (msg);
kvmsg_t *kvmsg = (kvmsg_t *) zhash_lookup (self->kvmap, key);
byte *value = kvmsg? kvmsg_body (kvmsg): NULL;
if (value)
zmq_send (self->pipe, value, kvmsg_size (kvmsg), 0);
else
zstr_send (self->pipe, "");
free (key);
}
free (command);
zmsg_destroy (&msg);
return0;
}
// .split backend agent
// The asynchronous agent manages a server pool and handles the
// request-reply dialog when the application asks for it:
staticvoidclone_agent (void *args, zctx_t *ctx, void *pipe)
{
agent_t *self = agent_new (ctx, pipe);
while (true) {
zmq_pollitem_t poll_set [] = {
{ pipe, 0, ZMQ_POLLIN, 0 },
{ 0, 0, ZMQ_POLLIN, 0 }
};
int poll_timer = -1;
int poll_size = 2;
server_t *server = self->server [self->cur_server];
switch (self->state) {
case STATE_INITIAL:
// In this state we ask the server for a snapshot,
// if we have a server to talk to...
if (self->nbr_servers > 0) {
zclock_log ("I: waiting for server at %s:%d...",
server->address, server->port);
if (server->requests < 2) {
zstr_sendm (server->snapshot, "ICANHAZ?");
zstr_send (server->snapshot, self->subtree);
server->requests++;
}
server->expiry = zclock_time () + SERVER_TTL;
self->state = STATE_SYNCING;
poll_set [1].socket = server->snapshot;
}
else
poll_size = 1;
break;
case STATE_SYNCING:
// In this state we read from snapshot and we expect
// the server to respond, else we fail over.
poll_set [1].socket = server->snapshot;
break;
case STATE_ACTIVE:
// In this state we read from subscriber and we expect
// the server to give HUGZ, else we fail over.
poll_set [1].socket = server->subscriber;
break;
}
if (server) {
poll_timer = (server->expiry - zclock_time ())
* ZMQ_POLL_MSEC;
if (poll_timer < 0)
poll_timer = 0;
}
// .split client poll loop
// We're ready to process incoming messages; if nothing at all
// comes from our server within the timeout, that means the
// server is dead:
int rc = zmq_poll (poll_set, poll_size, poll_timer);
if (rc == -1)
break; // Context has been shut down
if (poll_set [0].revents & ZMQ_POLLIN) {
if (agent_control_message (self))
break; // Interrupted
}
elseif (poll_set [1].revents & ZMQ_POLLIN) {
kvmsg_t *kvmsg = kvmsg_recv (poll_set [1].socket);
if (!kvmsg)
break; // Interrupted
// Anything from server resets its expiry time
server->expiry = zclock_time () + SERVER_TTL;
if (self->state == STATE_SYNCING) {
// Store in snapshot until we're finished
server->requests = 0;
if (streq (kvmsg_key (kvmsg), "KTHXBAI")) {
self->sequence = kvmsg_sequence (kvmsg);
self->state = STATE_ACTIVE;
zclock_log ("I: received from %s:%d snapshot=%d",
server->address, server->port,
(int) self->sequence);
kvmsg_destroy (&kvmsg);
}
else
kvmsg_store (&kvmsg, self->kvmap);
}
elseif (self->state == STATE_ACTIVE) {
// Discard out-of-sequence updates, incl. HUGZ
if (kvmsg_sequence (kvmsg) > self->sequence) {
self->sequence = kvmsg_sequence (kvmsg);
kvmsg_store (&kvmsg, self->kvmap);
zclock_log ("I: received from %s:%d update=%d",
server->address, server->port,
(int) self->sequence);
}
else
kvmsg_destroy (&kvmsg);
}
}
else {
// Server has died, failover to next
zclock_log ("I: server at %s:%d didn't give HUGZ",
server->address, server->port);
self->cur_server = (self->cur_server + 1) % self->nbr_servers;
self->state = STATE_INITIAL;
}
}
agent_destroy (&self);
}
packageguide;
importjava.util.HashMap;
importjava.util.Map;
importorg.zeromq.*;
importorg.zeromq.ZMQ.Poller;
importorg.zeromq.ZMQ.Socket;
importorg.zeromq.ZThread.IAttachedRunnable;
publicclassclone
{
private ZContext ctx; // Our context wrapper
private Socket pipe; // Pipe through to clone agent
// .split constructor and destructor
// Here are the constructor and destructor for the clone class. Note that
// we create a context specifically for the pipe that connects our
// frontend to the backend agent:
publicclone()
{
ctx = new ZContext();
pipe = ZThread.fork(ctx, new CloneAgent());
}
publicvoiddestroy()
{
ctx.destroy();
}
// .split subtree method
// Specify subtree for snapshot and updates, which we must do before
// connecting to a server as the subtree specification is sent as the
// first command to the server. Sends a [SUBTREE][subtree] command to
// the agent:
publicvoidsubtree(String subtree)
{
ZMsg msg = new ZMsg();
msg.add("SUBTREE");
msg.add(subtree);
msg.send(pipe);
}
// .split connect method
// Connect to a new server endpoint. We can connect to at most two
// servers. Sends [CONNECT][endpoint][service] to the agent:
publicvoidconnect(String address, String service)
{
ZMsg msg = new ZMsg();
msg.add("CONNECT");
msg.add(address);
msg.add(service);
msg.send(pipe);
}
// .split set method
// Set a new value in the shared hashmap. Sends a [SET][key][value][ttl]
// command through to the agent which does the actual work:
publicvoidset(String key, String value, int ttl)
{
ZMsg msg = new ZMsg();
msg.add("SET");
msg.add(key);
msg.add(value);
msg.add(String.format("%d", ttl));
msg.send(pipe);
}
// .split get method
// Look up value in distributed hash table. Sends [GET][key] to the agent and
// waits for a value response. If there is no value available, will eventually
// return NULL:
public String get(String key)
{
ZMsg msg = new ZMsg();
msg.add("GET");
msg.add(key);
msg.send(pipe);
ZMsg reply = ZMsg.recvMsg(pipe);
if (reply != null) {
String value = reply.popString();
reply.destroy();
return value;
}
returnnull;
}
// .split working with servers
// The backend agent manages a set of servers, which we implement using
// our simple class model:
privatestaticclassServer
{
private String address; // Server address
privateint port; // Server port
private Socket snapshot; // Snapshot socket
private Socket subscriber; // Incoming updates
privatelong expiry; // When server expires
privateint requests; // How many snapshot requests made?
protectedServer(ZContext ctx, String address, int port, String subtree)
{
System.out.printf("I: adding server %s:%d...\n", address, port);
this.address = address;
this.port = port;
snapshot = ctx.createSocket(SocketType.DEALER);
snapshot.connect(String.format("%s:%d", address, port));
subscriber = ctx.createSocket(SocketType.SUB);
subscriber.connect(String.format("%s:%d", address, port + 1));
subscriber.subscribe(subtree.getBytes(ZMQ.CHARSET));
}
protectedvoiddestroy()
{
}
}
// .split backend agent class
// Here is the implementation of the backend agent itself:
// Number of servers to which we will talk to
privatefinalstaticint SERVER_MAX = 2;
// Server considered dead if silent for this long
privatefinalstaticint SERVER_TTL = 5000; // msecs
// States we can be in
privatefinalstaticint STATE_INITIAL = 0; // Before asking server for state
privatefinalstaticint STATE_SYNCING = 1; // Getting state from server
privatefinalstaticint STATE_ACTIVE = 2; // Getting new updates from server
privatestaticclassAgent
{
private ZContext ctx; // Context wrapper
private Socket pipe; // Pipe back to application
private Map<String, String> kvmap; // Actual key/value table
private String subtree; // Subtree specification, if any
private Server[] server;
privateint nbrServers; // 0 to SERVER_MAX
privateint state; // Current state
privateint curServer; // If active, server 0 or 1
privatelong sequence; // Last kvmsg processed
private Socket publisher; // Outgoing updates
protectedAgent(ZContext ctx, Socket pipe)
{
this.ctx = ctx;
this.pipe = pipe;
kvmap = new HashMap<String, String>();
subtree = "";
state = STATE_INITIAL;
publisher = ctx.createSocket(SocketType.PUB);
server = new Server[SERVER_MAX];
}
protectedvoiddestroy()
{
for (int serverNbr = 0; serverNbr < nbrServers; serverNbr++)
server[serverNbr].destroy();
}
// .split handling a control message
// Here we handle the different control messages from the frontend;
// SUBTREE, CONNECT, SET, and GET:
privatebooleancontrolMessage()
{
ZMsg msg = ZMsg.recvMsg(pipe);
String command = msg.popString();
if (command == null)
returnfalse; // Interrupted
if (command.equals("SUBTREE")) {
subtree = msg.popString();
}
elseif (command.equals("CONNECT")) {
String address = msg.popString();
String service = msg.popString();
if (nbrServers < SERVER_MAX) {
server[nbrServers++] = new Server(ctx, address, Integer.parseInt(service), subtree);
// We broadcast updates to all known servers
publisher.connect(String.format("%s:%d", address, Integer.parseInt(service) + 2));
}
else System.out.printf("E: too many servers (max. %d)\n", SERVER_MAX);
}
else// .split set and get commands
// When we set a property, we push the new key-value pair onto
// all our connected servers:
if (command.equals("SET")) {
String key = msg.popString();
String value = msg.popString();
String ttl = msg.popString();
kvmap.put(key, value);
// Send key-value pair on to server
kvmsg kvmsg = new kvmsg(0);
kvmsg.setKey(key);
kvmsg.setUUID();
kvmsg.fmtBody("%s", value);
kvmsg.setProp("ttl", ttl);
kvmsg.send(publisher);
kvmsg.destroy();
}
elseif (command.equals("GET")) {
String key = msg.popString();
String value = kvmap.get(key);
if (value != null)
pipe.send(value);
else pipe.send("");
}
msg.destroy();
returntrue;
}
}
privatestaticclassCloneAgentimplements IAttachedRunnable
{
@Overridepublicvoidrun(Object[] args, ZContext ctx, Socket pipe)
{
Agent self = new Agent(ctx, pipe);
Poller poller = ctx.createPoller(1);
poller.register(pipe, Poller.POLLIN);
while (!Thread.currentThread().isInterrupted()) {
long pollTimer = -1;
int pollSize = 2;
Server server = self.server[self.curServer];
switch (self.state) {
case STATE_INITIAL:
// In this state we ask the server for a snapshot,
// if we have a server to talk to...
if (self.nbrServers > 0) {
System.out.printf("I: waiting for server at %s:%d...\n", server.address, server.port);
if (server.requests < 2) {
server.snapshot.sendMore("ICANHAZ?");
server.snapshot.send(self.subtree);
server.requests++;
}
server.expiry = System.currentTimeMillis() + SERVER_TTL;
self.state = STATE_SYNCING;
poller.close();
poller = ctx.createPoller(2);
poller.register(pipe, Poller.POLLIN);
poller.register(server.snapshot, Poller.POLLIN);
}
else pollSize = 1;
break;
case STATE_SYNCING:
// In this state we read from snapshot and we expect
// the server to respond, else we fail over.
poller.close();
poller = ctx.createPoller(2);
poller.register(pipe, Poller.POLLIN);
poller.register(server.snapshot, Poller.POLLIN);
break;
case STATE_ACTIVE:
// In this state we read from subscriber and we expect
// the server to give hugz, else we fail over.
poller.close();
poller = ctx.createPoller(2);
poller.register(pipe, Poller.POLLIN);
poller.register(server.subscriber, Poller.POLLIN);
break;
}
if (server != null) {
pollTimer = server.expiry - System.currentTimeMillis();
if (pollTimer < 0)
pollTimer = 0;
}
// .split client poll loop
// We're ready to process incoming messages; if nothing at all
// comes from our server within the timeout, that means the
// server is dead:
int rc = poller.poll(pollTimer);
if (rc == -1)
break; // Context has been shut down
if (poller.pollin(0)) {
if (!self.controlMessage())
break; // Interrupted
}
elseif (pollSize == 2 && poller.pollin(1)) {
kvmsg msg = kvmsg.recv(poller.getSocket(1));
if (msg == null)
break; // Interrupted
// Anything from server resets its expiry time
server.expiry = System.currentTimeMillis() + SERVER_TTL;
if (self.state == STATE_SYNCING) {
// Store in snapshot until we're finished
server.requests = 0;
if (msg.getKey().equals("KTHXBAI")) {
self.sequence = msg.getSequence();
self.state = STATE_ACTIVE;
System.out.printf("I: received from %s:%d snapshot=%d\n", server.address, server.port,
self.sequence);
msg.destroy();
}
}
elseif (self.state == STATE_ACTIVE) {
// Discard out-of-sequence updates, incl. hugz
if (msg.getSequence() > self.sequence) {
self.sequence = msg.getSequence();
System.out.printf("I: received from %s:%d update=%d\n", server.address, server.port,
self.sequence);
}
else msg.destroy();
}
}
else {
// Server has died, failover to next
System.out.printf("I: server at %s:%d didn't give hugz\n", server.address, server.port);
self.curServer = (self.curServer + 1) % self.nbrServers;
self.state = STATE_INITIAL;
}
}
self.destroy();
}
}
}
"""
clone - client-side Clone Pattern class
Author: Min RK <benjaminrk@gmail.com>
"""importloggingimportthreadingimporttimeimportzmqfromzhelpersimport zpipe
fromkvmsgimport KVMsg
# If no server replies within this time, abandon request
GLOBAL_TIMEOUT = 4000# msecs# Server considered dead if silent for this long
SERVER_TTL = 5.0# secs# Number of servers we will talk to
SERVER_MAX = 2# basic log formatting:
logging.basicConfig(format="%(asctime)s%(message)s", datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO)
# =====================================================================# Synchronous part, works in our application threadclassClone(object):
ctx = None # Our Context
pipe = None # Pipe through to clone agent
agent = None # agent in a thread
_subtree = None # cache of our subtree valuedef __init__(self):
self.ctx = zmq.Context()
self.pipe, peer = zpipe(self.ctx)
self.agent = threading.Thread(target=clone_agent, args=(self.ctx,peer))
self.agent.daemon = True
self.agent.start()
# ---------------------------------------------------------------------# Clone.subtree is a property, which sets the subtree for snapshot# and updates@propertydefsubtree(self):
return self._subtree
@subtree.setterdefsubtree(self, subtree):
"""Sends [SUBTREE][subtree] to the agent"""
self._subtree = subtree
self.pipe.send_multipart([b"SUBTREE", subtree])
defconnect(self, address, port):
"""Connect to new server endpoint
Sends [CONNECT][address][port] to the agent
"""
self.pipe.send_multipart([b"CONNECT", (address.encode() ifisinstance(address, str) else address), b'%d' % port])
defset(self, key, value, ttl=0):
"""Set new value in distributed hash table
Sends [SET][key][value][ttl] to the agent
"""
self.pipe.send_multipart([b"SET", key, value, b'%i' % ttl])
defget(self, key):
"""Lookup value in distributed hash table
Sends [GET][key] to the agent and waits for a value response
If there is no clone available, will eventually return None.
"""
self.pipe.send_multipart([b"GET", key])
try:
reply = self.pipe.recv_multipart()
except KeyboardInterrupt:
returnelse:
return reply[0]
# =====================================================================# Asynchronous part, works in the background# ---------------------------------------------------------------------# Simple class for one server we talk toclassCloneServer(object):
address = None # Server address
port = None # Server port
snapshot = None # Snapshot socket
subscriber = None # Incoming updates
expiry = 0# Expires at this time
requests = 0# How many snapshot requests made?def __init__(self, ctx, address, port, subtree):
self.address = address
self.port = port
self.snapshot = ctx.socket(zmq.DEALER)
self.snapshot.linger = 0
self.snapshot.connect("%s:%i" % (address.decode(),port))
self.subscriber = ctx.socket(zmq.SUB)
self.subscriber.setsockopt(zmq.SUBSCRIBE, subtree)
self.subscriber.setsockopt(zmq.SUBSCRIBE, b'HUGZ')
self.subscriber.connect("%s:%i" % (address.decode(),port+1))
self.subscriber.linger = 0# ---------------------------------------------------------------------# Simple class for one background agent# States we can be in
STATE_INITIAL = 0# Before asking server for state
STATE_SYNCING = 1# Getting state from server
STATE_ACTIVE = 2# Getting new updates from serverclassCloneAgent(object):
ctx = None # Own context
pipe = None # Socket to talk back to application
kvmap = None # Actual key/value dict
subtree = ''# Subtree specification, if any
servers = None # list of connected Servers
state = 0# Current state
cur_server = 0# If active, index of server in list
sequence = 0# last kvmsg procesed
publisher = None # Outgoing updatesdef __init__(self, ctx, pipe):
self.ctx = ctx
self.pipe = pipe
self.kvmap = {}
self.subtree = ''
self.state = STATE_INITIAL
self.publisher = ctx.socket(zmq.PUB)
self.router = ctx.socket(zmq.ROUTER)
self.servers = []
defcontrol_message (self):
msg = self.pipe.recv_multipart()
command = msg.pop(0)
if command == b"CONNECT":
address = msg.pop(0)
port = int(msg.pop(0))
iflen(self.servers) < SERVER_MAX:
self.servers.append(CloneServer(self.ctx, address, port, self.subtree))
self.publisher.connect("%s:%i" % (address.decode(),port+2))
else:
logging.error("E: too many servers (max. %i)", SERVER_MAX)
elif command == b"SET":
key,value,sttl = msg
ttl = int(sttl)
# Send key-value pair on to server
kvmsg = KVMsg(0, key=key, body=value)
kvmsg.store(self.kvmap)
if ttl:
kvmsg[b"ttl"] = sttl
kvmsg.send(self.publisher)
elif command == b"GET":
key = msg[0]
value = self.kvmap.get(key)
self.pipe.send(value.body if value else'')
elif command == b"SUBTREE":
self.subtree = msg[0]
# ---------------------------------------------------------------------# Asynchronous agent manages server pool and handles request/reply# dialog when the application asks for it.defclone_agent(ctx, pipe):
agent = CloneAgent(ctx, pipe)
server = None
while True:
poller = zmq.Poller()
poller.register(agent.pipe, zmq.POLLIN)
poll_timer = None
server_socket = None
if agent.state == STATE_INITIAL:
# In this state we ask the server for a snapshot,# if we have a server to talk to...if agent.servers:
server = agent.servers[agent.cur_server]
logging.info ("I: waiting for server at %s:%d...",
server.address, server.port)
if (server.requests < 2):
server.snapshot.send_multipart([b"ICANHAZ?", agent.subtree])
server.requests += 1
server.expiry = time.time() + SERVER_TTL
agent.state = STATE_SYNCING
server_socket = server.snapshot
elif agent.state == STATE_SYNCING:
# In this state we read from snapshot and we expect# the server to respond, else we fail over.
server_socket = server.snapshot
elif agent.state == STATE_ACTIVE:
# In this state we read from subscriber and we expect# the server to give hugz, else we fail over.
server_socket = server.subscriber
if server_socket:
# we have a second socket to poll:
poller.register(server_socket, zmq.POLLIN)
if server isnot None:
poll_timer = 1e3 * max(0,server.expiry - time.time())
# ------------------------------------------------------------# Poll looptry:
items = dict(poller.poll(poll_timer))
except:
raise# DEBUGbreak# Context has been shut downif agent.pipe in items:
agent.control_message()
elif server_socket in items:
kvmsg = KVMsg.recv(server_socket)
# Anything from server resets its expiry time
server.expiry = time.time() + SERVER_TTL
if (agent.state == STATE_SYNCING):
# Store in snapshot until we're finished
server.requests = 0if kvmsg.key == b"KTHXBAI":
agent.sequence = kvmsg.sequence
agent.state = STATE_ACTIVE
logging.info ("I: received from %s:%d snapshot=%d",
server.address, server.port, agent.sequence)
else:
kvmsg.store(agent.kvmap)
elif (agent.state == STATE_ACTIVE):
# Discard out-of-sequence updates, incl. hugzif (kvmsg.sequence > agent.sequence):
agent.sequence = kvmsg.sequence
kvmsg.store(agent.kvmap)
action = "update"if kvmsg.body else"delete"
logging.info ("I: received from %s:%d%s=%d",
server.address, server.port, action, agent.sequence)
else:
# Server has died, failover to next
logging.info ("I: server at %s:%d didn't give hugz",
server.address, server.port)
agent.cur_server = (agent.cur_server + 1) % len(agent.servers)
agent.state = STATE_INITIAL