monitor.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-
  2. """Module holding utility and convenience functions for zmq event monitoring."""
  3. # Copyright (C) PyZMQ Developers
  4. # Distributed under the terms of the Modified BSD License.
  5. import struct
  6. import zmq
  7. from zmq.error import _check_version
  8. def parse_monitor_message(msg):
  9. """decode zmq_monitor event messages.
  10. Parameters
  11. ----------
  12. msg : list(bytes)
  13. zmq multipart message that has arrived on a monitor PAIR socket.
  14. First frame is::
  15. 16 bit event id
  16. 32 bit event value
  17. no padding
  18. Second frame is the endpoint as a bytestring
  19. Returns
  20. -------
  21. event : dict
  22. event description as dict with the keys `event`, `value`, and `endpoint`.
  23. """
  24. if len(msg) != 2 or len(msg[0]) != 6:
  25. raise RuntimeError("Invalid event message format: %s" % msg)
  26. event = {'event': struct.unpack("=hi", msg[0])[0],
  27. 'value': struct.unpack("=hi", msg[0])[1],
  28. 'endpoint': msg[1]}
  29. return event
  30. def recv_monitor_message(socket, flags=0):
  31. """Receive and decode the given raw message from the monitoring socket and return a dict.
  32. Requires libzmq ≥ 4.0
  33. The returned dict will have the following entries:
  34. event : int, the event id as described in libzmq.zmq_socket_monitor
  35. value : int, the event value associated with the event, see libzmq.zmq_socket_monitor
  36. endpoint : string, the affected endpoint
  37. Parameters
  38. ----------
  39. socket : zmq PAIR socket
  40. The PAIR socket (created by other.get_monitor_socket()) on which to recv the message
  41. flags : bitfield (int)
  42. standard zmq recv flags
  43. Returns
  44. -------
  45. event : dict
  46. event description as dict with the keys `event`, `value`, and `endpoint`.
  47. """
  48. _check_version((4,0), 'libzmq event API')
  49. # will always return a list
  50. msg = socket.recv_multipart(flags)
  51. # 4.0-style event API
  52. return parse_monitor_message(msg)
  53. __all__ = ['parse_monitor_message', 'recv_monitor_message']