context.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # coding: utf-8
  2. """Python bindings for 0MQ."""
  3. # Copyright (C) PyZMQ Developers
  4. # Distributed under the terms of the Modified BSD License.
  5. import atexit
  6. import os
  7. from threading import Lock
  8. from weakref import WeakSet
  9. from zmq.backend import Context as ContextBase
  10. from . import constants
  11. from .attrsettr import AttributeSetter
  12. from .constants import ENOTSUP, LINGER, ctx_opt_names
  13. from .socket import Socket
  14. from zmq.error import ZMQError
  15. # notice when exiting, to avoid triggering term on exit
  16. _exiting = False
  17. def _notice_atexit():
  18. global _exiting
  19. _exiting = True
  20. atexit.register(_notice_atexit)
  21. class Context(ContextBase, AttributeSetter):
  22. """Create a zmq Context
  23. A zmq Context creates sockets via its ``ctx.socket`` method.
  24. """
  25. sockopts = None
  26. _instance = None
  27. _instance_lock = Lock()
  28. _instance_pid = None
  29. _shadow = False
  30. _sockets = None
  31. def __init__(self, io_threads=1, **kwargs):
  32. super(Context, self).__init__(io_threads=io_threads, **kwargs)
  33. if kwargs.get('shadow', False):
  34. self._shadow = True
  35. else:
  36. self._shadow = False
  37. self.sockopts = {}
  38. self._sockets = WeakSet()
  39. def __del__(self):
  40. """deleting a Context should terminate it, without trying non-threadsafe destroy"""
  41. # Calling locals() here conceals issue #1167 on Windows CPython 3.5.4.
  42. locals()
  43. if not self._shadow and not _exiting:
  44. self.term()
  45. def __enter__(self):
  46. return self
  47. def __exit__(self, *args, **kwargs):
  48. self.term()
  49. def __copy__(self, memo=None):
  50. """Copying a Context creates a shadow copy"""
  51. return self.__class__.shadow(self.underlying)
  52. __deepcopy__ = __copy__
  53. @classmethod
  54. def shadow(cls, address):
  55. """Shadow an existing libzmq context
  56. address is the integer address of the libzmq context
  57. or an FFI pointer to it.
  58. .. versionadded:: 14.1
  59. """
  60. from zmq.utils.interop import cast_int_addr
  61. address = cast_int_addr(address)
  62. return cls(shadow=address)
  63. @classmethod
  64. def shadow_pyczmq(cls, ctx):
  65. """Shadow an existing pyczmq context
  66. ctx is the FFI `zctx_t *` pointer
  67. .. versionadded:: 14.1
  68. """
  69. from pyczmq import zctx
  70. from zmq.utils.interop import cast_int_addr
  71. underlying = zctx.underlying(ctx)
  72. address = cast_int_addr(underlying)
  73. return cls(shadow=address)
  74. # static method copied from tornado IOLoop.instance
  75. @classmethod
  76. def instance(cls, io_threads=1):
  77. """Returns a global Context instance.
  78. Most single-threaded applications have a single, global Context.
  79. Use this method instead of passing around Context instances
  80. throughout your code.
  81. A common pattern for classes that depend on Contexts is to use
  82. a default argument to enable programs with multiple Contexts
  83. but not require the argument for simpler applications::
  84. class MyClass(object):
  85. def __init__(self, context=None):
  86. self.context = context or Context.instance()
  87. .. versionchanged:: 18.1
  88. When called in a subprocess after forking,
  89. a new global instance is created instead of inheriting
  90. a Context that won't work from the parent process.
  91. """
  92. if (
  93. cls._instance is None
  94. or cls._instance_pid != os.getpid()
  95. or cls._instance.closed
  96. ):
  97. with cls._instance_lock:
  98. if (
  99. cls._instance is None
  100. or cls._instance_pid != os.getpid()
  101. or cls._instance.closed
  102. ):
  103. cls._instance = cls(io_threads=io_threads)
  104. cls._instance_pid = os.getpid()
  105. return cls._instance
  106. def term(self):
  107. """Close or terminate the context.
  108. Context termination is performed in the following steps:
  109. - Any blocking operations currently in progress on sockets open within context shall
  110. raise :class:`zmq.ContextTerminated`.
  111. With the exception of socket.close(), any further operations on sockets open within this context
  112. shall raise :class:`zmq.ContextTerminated`.
  113. - After interrupting all blocking calls, term shall block until the following conditions are satisfied:
  114. - All sockets open within context have been closed.
  115. - For each socket within context, all messages sent on the socket have either been
  116. physically transferred to a network peer,
  117. or the socket's linger period set with the zmq.LINGER socket option has expired.
  118. For further details regarding socket linger behaviour refer to libzmq documentation for ZMQ_LINGER.
  119. This can be called to close the context by hand. If this is not called,
  120. the context will automatically be closed when it is garbage collected.
  121. """
  122. return super(Context, self).term()
  123. #-------------------------------------------------------------------------
  124. # Hooks for ctxopt completion
  125. #-------------------------------------------------------------------------
  126. def __dir__(self):
  127. keys = dir(self.__class__)
  128. for collection in (
  129. ctx_opt_names,
  130. ):
  131. keys.extend(collection)
  132. return keys
  133. #-------------------------------------------------------------------------
  134. # Creating Sockets
  135. #-------------------------------------------------------------------------
  136. def _add_socket(self, socket):
  137. self._sockets.add(socket)
  138. def _rm_socket(self, socket):
  139. if self._sockets:
  140. self._sockets.discard(socket)
  141. def destroy(self, linger=None):
  142. """Close all sockets associated with this context and then terminate
  143. the context.
  144. .. warning::
  145. destroy involves calling ``zmq_close()``, which is **NOT** threadsafe.
  146. If there are active sockets in other threads, this must not be called.
  147. Parameters
  148. ----------
  149. linger : int, optional
  150. If specified, set LINGER on sockets prior to closing them.
  151. """
  152. if self.closed:
  153. return
  154. sockets = self._sockets
  155. self._sockets = WeakSet()
  156. for s in sockets:
  157. if s and not s.closed:
  158. if linger is not None:
  159. s.setsockopt(LINGER, linger)
  160. s.close()
  161. self.term()
  162. @property
  163. def _socket_class(self):
  164. return Socket
  165. def socket(self, socket_type, **kwargs):
  166. """Create a Socket associated with this Context.
  167. Parameters
  168. ----------
  169. socket_type : int
  170. The socket type, which can be any of the 0MQ socket types:
  171. REQ, REP, PUB, SUB, PAIR, DEALER, ROUTER, PULL, PUSH, etc.
  172. kwargs:
  173. will be passed to the __init__ method of the socket class.
  174. """
  175. if self.closed:
  176. raise ZMQError(ENOTSUP)
  177. s = self._socket_class(self, socket_type, **kwargs)
  178. for opt, value in self.sockopts.items():
  179. try:
  180. s.setsockopt(opt, value)
  181. except ZMQError:
  182. # ignore ZMQErrors, which are likely for socket options
  183. # that do not apply to a particular socket type, e.g.
  184. # SUBSCRIBE for non-SUB sockets.
  185. pass
  186. self._add_socket(s)
  187. return s
  188. def setsockopt(self, opt, value):
  189. """set default socket options for new sockets created by this Context
  190. .. versionadded:: 13.0
  191. """
  192. self.sockopts[opt] = value
  193. def getsockopt(self, opt):
  194. """get default socket options for new sockets created by this Context
  195. .. versionadded:: 13.0
  196. """
  197. return self.sockopts[opt]
  198. def _set_attr_opt(self, name, opt, value):
  199. """set default sockopts as attributes"""
  200. if name in constants.ctx_opt_names:
  201. return self.set(opt, value)
  202. else:
  203. self.sockopts[opt] = value
  204. def _get_attr_opt(self, name, opt):
  205. """get default sockopts as attributes"""
  206. if name in constants.ctx_opt_names:
  207. return self.get(opt)
  208. else:
  209. if opt not in self.sockopts:
  210. raise AttributeError(name)
  211. else:
  212. return self.sockopts[opt]
  213. def __delattr__(self, key):
  214. """delete default sockopts as attributes"""
  215. key = key.upper()
  216. try:
  217. opt = getattr(constants, key)
  218. except AttributeError:
  219. raise AttributeError("no such socket option: %s" % key)
  220. else:
  221. if opt not in self.sockopts:
  222. raise AttributeError(key)
  223. else:
  224. del self.sockopts[opt]
  225. __all__ = ['Context']