protocol.rst 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. abstract = True
  120. def unpack_args(self, fun, args=()):
  121. return fun, args
  122. def apply_async(self, args, kwargs, **options):
  123. fun, real_args = self.unpack_args(*args)
  124. return super(PickleTask, self).apply_async(
  125. (fun, real_args, kwargs), shadow=qualname(fun), **options
  126. )
  127. @app.task(base=PickleTask)
  128. def call(fun, args, kwargs):
  129. return fun(*args, **kwargs)
  130. .. _message-protocol-task-v1:
  131. .. _task-message-protocol-v1:
  132. Version 1
  133. ---------
  134. In version 1 of the protocol all fields are stored in the message body,
  135. which means workers and intermediate consumers must deserialize the payload
  136. to read the fields.
  137. Message body
  138. ~~~~~~~~~~~~
  139. * task
  140. :`string`:
  141. Name of the task. **required**
  142. * id
  143. :`string`:
  144. Unique id of the task (UUID). **required**
  145. * args
  146. :`list`:
  147. List of arguments. Will be an empty list if not provided.
  148. * kwargs
  149. :`dictionary`:
  150. Dictionary of keyword arguments. Will be an empty dictionary if not
  151. provided.
  152. * retries
  153. :`int`:
  154. Current number of times this task has been retried.
  155. Defaults to `0` if not specified.
  156. * eta
  157. :`string` (ISO 8601):
  158. Estimated time of arrival. This is the date and time in ISO 8601
  159. format. If not provided the message is not scheduled, but will be
  160. executed asap.
  161. * expires
  162. :`string` (ISO 8601):
  163. .. versionadded:: 2.0.2
  164. Expiration date. This is the date and time in ISO 8601 format.
  165. If not provided the message will never expire. The message
  166. will be expired when the message is received and the expiration date
  167. has been exceeded.
  168. * taskset
  169. :`string`:
  170. The taskset this task is part of (if any).
  171. * chord
  172. :`Signature`:
  173. .. versionadded:: 2.3
  174. Signifies that this task is one of the header parts of a chord. The value
  175. of this key is the body of the cord that should be executed when all of
  176. the tasks in the header has returned.
  177. * utc
  178. :`bool`:
  179. .. versionadded:: 2.5
  180. If true time uses the UTC timezone, if not the current local timezone
  181. should be used.
  182. * callbacks
  183. :`<list>Signature`:
  184. .. versionadded:: 3.0
  185. A list of signatures to call if the task exited successfully.
  186. * errbacks
  187. :`<list>Signature`:
  188. .. versionadded:: 3.0
  189. A list of signatures to call if an error occurs while executing the task.
  190. * timelimit
  191. :`<tuple>(float, float)`:
  192. .. versionadded:: 3.1
  193. Task execution time limit settings. This is a tuple of hard and soft time
  194. limit value (`int`/`float` or :const:`None` for no limit).
  195. Example value specifying a soft time limit of 3 seconds, and a hard time
  196. limt of 10 seconds::
  197. {'timelimit': (3.0, 10.0)}
  198. Example message
  199. ~~~~~~~~~~~~~~~
  200. This is an example invocation of a `celery.task.ping` task in JSON
  201. format:
  202. .. code-block:: javascript
  203. {"id": "4cc7438e-afd4-4f8f-a2f3-f46567e7ca77",
  204. "task": "celery.task.PingTask",
  205. "args": [],
  206. "kwargs": {},
  207. "retries": 0,
  208. "eta": "2009-11-17T12:30:56.527191"}
  209. Task Serialization
  210. ------------------
  211. Several types of serialization formats are supported using the
  212. `content_type` message header.
  213. The MIME-types supported by default are shown in the following table.
  214. =============== =================================
  215. Scheme MIME Type
  216. =============== =================================
  217. json application/json
  218. yaml application/x-yaml
  219. pickle application/x-python-serialize
  220. msgpack application/x-msgpack
  221. =============== =================================
  222. .. _message-protocol-event:
  223. Event Messages
  224. ==============
  225. Event messages are always JSON serialized and can contain arbitrary message
  226. body fields.
  227. Since version 4.0. the body can consist of either a single mapping (one event),
  228. or a list of mappings (multiple events).
  229. There are also standard fields that must always be present in an event
  230. message:
  231. Standard body fields
  232. --------------------
  233. - *string* ``type``
  234. The type of event. This is a string containing the *category* and
  235. *action* separated by a dash delimeter (e.g. ``task-succeeded``).
  236. - *string* ``hostname``
  237. The fully qualified hostname of where the event occurred at.
  238. - *unsigned long long* ``clock``
  239. The logical clock value for this event (Lamport timestamp).
  240. - *float* ``timestamp``
  241. The UNIX timestamp corresponding to the time of when the event occurred.
  242. - *signed short* ``utcoffset``
  243. This field describes the timezone of the originating host, and is
  244. specified as the number of hours ahead of/behind UTC. E.g. ``-2`` or
  245. ``+1``.
  246. - *unsigned long long* ``pid``
  247. The process id of the process the event originated in.
  248. Standard event types
  249. --------------------
  250. For a list of standard event types and their fields see the
  251. :ref:`event-reference`.
  252. Example message
  253. ---------------
  254. This is the message fields for a ``task-succeeded`` event:
  255. .. code-block:: python
  256. properties = {
  257. 'routing_key': 'task.succeeded',
  258. 'exchange': 'celeryev',
  259. 'content_type': 'application/json',
  260. 'content_encoding': 'utf-8',
  261. 'delivery_mode': 1,
  262. }
  263. headers = {
  264. 'hostname': 'worker1@george.vandelay.com',
  265. }
  266. body = {
  267. 'type': 'task-succeeded',
  268. 'hostname': 'worker1@george.vandelay.com',
  269. 'pid': 6335,
  270. 'clock': 393912923921,
  271. 'timestamp': 1401717709.101747,
  272. 'utcoffset': -1,
  273. 'uuid': '9011d855-fdd1-4f8f-adb3-a413b499eafb',
  274. 'retval': '4',
  275. 'runtime': 0.0003212,
  276. )