protocol.rst 9.1 KB

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