protocol.rst 9.2 KB

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