protocol.rst 9.4 KB

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