protocol.rst 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. .. _message-protocol:
  2. ===================
  3. Message Protocol
  4. ===================
  5. .. contents::
  6. :local:
  7. .. _message-protocol-task:
  8. .. _internals-task-message-protocol:
  9. Task messages
  10. =============
  11. .. _message-protocol-task-v2:
  12. Version 2
  13. ---------
  14. Definition
  15. ~~~~~~~~~~
  16. .. code-block:: python
  17. properties = {
  18. 'correlation_id': uuid task_id,
  19. 'content_type': string mimetype,
  20. 'content_encoding': string encoding,
  21. # optional
  22. 'reply_to': string queue_or_url,
  23. }
  24. headers = {
  25. 'lang': string 'py'
  26. 'task': string task,
  27. 'id': uuid task_id,
  28. 'root_id': uuid root_id,
  29. 'parent_id': uuid parent_id,
  30. 'group': uuid group_id,
  31. # optional
  32. 'meth': string method_name,
  33. 'shadow': string alias_name,
  34. 'eta': iso8601 eta,
  35. 'expires'; iso8601 expires,
  36. 'retries': int retries,
  37. 'timelimit': (soft, hard),
  38. 'argsrepr': str repr(args),
  39. 'kwargsrepr': str repr(kwargs),
  40. 'origin': str nodename,
  41. }
  42. body = (
  43. object[] args,
  44. Mapping kwargs,
  45. Mapping embed {
  46. 'callbacks': Signature[] callbacks,
  47. 'errbacks': Signature[] errbacks,
  48. 'chain': Signature[] chain,
  49. 'chord': Signature chord_callback,
  50. }
  51. )
  52. Example
  53. ~~~~~~~
  54. This example sends a task message using version 2 of the protocol:
  55. .. code-block:: python
  56. # chain: add(add(add(2, 2), 4), 8) == 2 + 2 + 4 + 8
  57. import json
  58. import os
  59. import socket
  60. task_id = uuid()
  61. args = (2, 2)
  62. kwargs = {}
  63. basic_publish(
  64. message=json.dumps((args, kwargs, None),
  65. application_headers={
  66. 'lang': 'py',
  67. 'task': 'proj.tasks.add',
  68. 'argsrepr': repr(args),
  69. 'kwargsrepr': repr(kwargs),
  70. 'origin': '@'.join([os.getpid(), socket.gethostname()])
  71. }
  72. properties={
  73. 'correlation_id': task_id,
  74. 'content_type': 'application/json',
  75. 'content_encoding': 'utf-8',
  76. }
  77. )
  78. Changes from version 1
  79. ~~~~~~~~~~~~~~~~~~~~~~
  80. - Protocol version detected by the presence of a ``task`` message header.
  81. - Support for multiple languages via the ``lang`` header.
  82. Worker may redirect the message to a worker that supports
  83. the language.
  84. - Meta-data moved to headers.
  85. This means that workers/intermediates can inspect the message
  86. and make decisions based on the headers without decoding
  87. the payload (which may be language specific, e.g. serialized by the
  88. Python specific pickle serializer).
  89. - Always UTC
  90. There's no ``utc`` flag anymore, so any time information missing timezone
  91. will be expected to be in UTC time.
  92. - Body is only for language specific data.
  93. - Python stores args/kwargs and embedded signatures in body.
  94. - If a message uses raw encoding then the raw data
  95. will be passed as a single argument to the function.
  96. - Java/C, etc. can use a Thrift/protobuf document as the body
  97. - Dispatches to actor based on ``task``, ``meth`` headers
  98. ``meth`` is unused by python, but may be used in the future
  99. to specify class+method pairs.
  100. - Chain gains a dedicated field.
  101. Reducing the chain into a recursive ``callbacks`` argument
  102. causes problems when the recursion limit is exceeded.
  103. This is fixed in the new message protocol by specifying
  104. a list of signatures, each task will then pop a task off the list
  105. when sending the next message:
  106. .. code-block:: python
  107. execute_task(message)
  108. chain = embed['chain']
  109. if chain:
  110. sig = maybe_signature(chain.pop())
  111. sig.apply_async(chain=chain)
  112. - ``correlation_id`` replaces ``task_id`` field.
  113. - ``root_id`` and ``parent_id`` fields helps keep track of work-flows.
  114. - ``shadow`` lets you specify a different name for logs, monitors
  115. can be used for e.g. meta tasks that calls any function:
  116. .. code-block:: python
  117. from celery.utils.imports import qualname
  118. class PickleTask(Task):
  119. def unpack_args(self, fun, args=()):
  120. return fun, args
  121. def apply_async(self, args, kwargs, **options):
  122. fun, real_args = self.unpack_args(*args)
  123. return super(PickleTask, self).apply_async(
  124. (fun, real_args, kwargs), shadow=qualname(fun), **options
  125. )
  126. @app.task(base=PickleTask)
  127. def call(fun, args, kwargs):
  128. return fun(*args, **kwargs)
  129. .. _message-protocol-task-v1:
  130. .. _task-message-protocol-v1:
  131. Version 1
  132. ---------
  133. In version 1 of the protocol all fields are stored in the message body,
  134. which means workers and intermediate consumers must deserialize the payload
  135. to read the fields.
  136. Message body
  137. ~~~~~~~~~~~~
  138. * ``task``
  139. :`string`:
  140. Name of the task. **required**
  141. * ``id``
  142. :`string`:
  143. Unique id of the task (UUID). **required**
  144. * ``args``
  145. :`list`:
  146. List of arguments. Will be an empty list if not provided.
  147. * ``kwargs``
  148. :`dictionary`:
  149. Dictionary of keyword arguments. Will be an empty dictionary if not
  150. provided.
  151. * ``retries``
  152. :`int`:
  153. Current number of times this task has been retried.
  154. Defaults to `0` if not specified.
  155. * ``eta``
  156. :`string` (ISO 8601):
  157. Estimated time of arrival. This is the date and time in ISO 8601
  158. format. If not provided the message is not scheduled, but will be
  159. executed asap.
  160. * ``expires``
  161. :`string` (ISO 8601):
  162. .. versionadded:: 2.0.2
  163. Expiration date. This is the date and time in ISO 8601 format.
  164. If not provided the message will never expire. The message
  165. will be expired when the message is received and the expiration date
  166. has been exceeded.
  167. * ``taskset``
  168. :`string`:
  169. The group this task is part of (if any).
  170. * ``chord``
  171. :`Signature`:
  172. .. versionadded:: 2.3
  173. Signifies that this task is one of the header parts of a chord. The value
  174. of this key is the body of the cord that should be executed when all of
  175. the tasks in the header has returned.
  176. * ``utc``
  177. :`bool`:
  178. .. versionadded:: 2.5
  179. If true time uses the UTC timezone, if not the current local timezone
  180. should be used.
  181. * ``callbacks``
  182. :`<list>Signature`:
  183. .. versionadded:: 3.0
  184. A list of signatures to call if the task exited successfully.
  185. * ``errbacks``
  186. :`<list>Signature`:
  187. .. versionadded:: 3.0
  188. A list of signatures to call if an error occurs while executing the task.
  189. * ``timelimit``
  190. :`<tuple>(float, float)`:
  191. .. versionadded:: 3.1
  192. Task execution time limit settings. This is a tuple of hard and soft time
  193. limit value (`int`/`float` or :const:`None` for no limit).
  194. Example value specifying a soft time limit of 3 seconds, and a hard time
  195. limit of 10 seconds::
  196. {'timelimit': (3.0, 10.0)}
  197. Example message
  198. ~~~~~~~~~~~~~~~
  199. This is an example invocation of a `celery.task.ping` task in json
  200. format:
  201. .. code-block:: javascript
  202. {"id": "4cc7438e-afd4-4f8f-a2f3-f46567e7ca77",
  203. "task": "celery.task.PingTask",
  204. "args": [],
  205. "kwargs": {},
  206. "retries": 0,
  207. "eta": "2009-11-17T12:30:56.527191"}
  208. Task Serialization
  209. ------------------
  210. Several types of serialization formats are supported using the
  211. `content_type` message header.
  212. The MIME-types supported by default are shown in the following table.
  213. =============== =================================
  214. Scheme MIME Type
  215. =============== =================================
  216. json application/json
  217. yaml application/x-yaml
  218. pickle application/x-python-serialize
  219. msgpack application/x-msgpack
  220. =============== =================================
  221. .. _message-protocol-event:
  222. Event Messages
  223. ==============
  224. Event messages are always JSON serialized and can contain arbitrary message
  225. body fields.
  226. Since version 4.0. the body can consist of either a single mapping (one event),
  227. or a list of mappings (multiple events).
  228. There are also standard fields that must always be present in an event
  229. message:
  230. Standard body fields
  231. --------------------
  232. - *string* ``type``
  233. The type of event. This is a string containing the *category* and
  234. *action* separated by a dash delimiter (e.g. ``task-succeeded``).
  235. - *string* ``hostname``
  236. The fully qualified hostname of where the event occurred at.
  237. - *unsigned long long* ``clock``
  238. The logical clock value for this event (Lamport time-stamp).
  239. - *float* ``timestamp``
  240. The UNIX time-stamp corresponding to the time of when the event occurred.
  241. - *signed short* ``utcoffset``
  242. This field describes the timezone of the originating host, and is
  243. specified as the number of hours ahead of/behind UTC. E.g. ``-2`` or
  244. ``+1``.
  245. - *unsigned long long* ``pid``
  246. The process id of the process the event originated in.
  247. Standard event types
  248. --------------------
  249. For a list of standard event types and their fields see the
  250. :ref:`event-reference`.
  251. Example message
  252. ---------------
  253. This is the message fields for a ``task-succeeded`` event:
  254. .. code-block:: python
  255. properties = {
  256. 'routing_key': 'task.succeeded',
  257. 'exchange': 'celeryev',
  258. 'content_type': 'application/json',
  259. 'content_encoding': 'utf-8',
  260. 'delivery_mode': 1,
  261. }
  262. headers = {
  263. 'hostname': 'worker1@george.vandelay.com',
  264. }
  265. body = {
  266. 'type': 'task-succeeded',
  267. 'hostname': 'worker1@george.vandelay.com',
  268. 'pid': 6335,
  269. 'clock': 393912923921,
  270. 'timestamp': 1401717709.101747,
  271. 'utcoffset': -1,
  272. 'uuid': '9011d855-fdd1-4f8f-adb3-a413b499eafb',
  273. 'retval': '4',
  274. 'runtime': 0.0003212,
  275. )