naparuba/shinken — pull request #739 by thomascellerier (2013-02-14 15:47:15+00:00)
Title: Add topics to ZeroMQ broker

The ZeroMQ broker will now publish messages using b.type as the topic and b.data as the message data (serialized with either JSON or Msgpack).
Clients can now filter by topic, for example using "log" or "services_".

Also fixed module imports to import optional modules only when necessary and return an error if zmq is not installed.

Example client code:

```python
import zmq
import sys

# Serialization method
method = ""
if len(sys.argv) < 2 or sys.argv[1] == "json":
import json
method = "json"
elif sys.argv[1] == "msgpack":
import msgpack
method = "msgpack"
else:
print("Invalid serialization method.")
sys.exit(-1)

# ZeroMQ endpoint
sub_endpoint = "tcp://127.0.0.1:12345"
if len(sys.argv) > 2:
sub_endpoint = sys.argv[2]

# ZeroMQ Suscription Topic
topic = ""
if len(sys.argv) > 3:
topic = sys.argv[3]

# Subscribe
context = zmq.Context()
s_sub = context.socket(zmq.SUB)
s_sub.setsockopt(zmq.SUBSCRIBE, topic)
s_sub.connect(sub_endpoint)
print("Listening for shinken notifications.")

# Process incoming messages
while True:
topic = s_sub.recv()
print("Got msg on topic: " + topic)
data = s_sub.recv()
if method == "json":
json_data = json.loads(data)
pretty_msg = json.dumps(json_data, sort_keys=True, indent=4)
print(pretty_msg)
elif method == "msgpack":
msg = msgpack.unpackb(data, use_list=False)
print(msg)
s_sub.close()
context.term()
```

Usage

```bash
python listen_shinken.py "json" "tcp://127.0.0.1:12345" "host"
```