Final touches before deployment, celery installed
This commit is contained in:
1 parent
544f5324e0
commit
a2e9d8f879
1212 files changed
+133114
-73
No files matched your search
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/home/williedynamite/projects/django_lottopy/django_lottopy/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from celery.__main__ import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
||||
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,47 @@
|
||||
Copyright (c) 2015-2016 Ask Solem & contributors. All rights reserved.
|
||||
Copyright (c) 2012-2014 GoPivotal, Inc. All rights reserved.
|
||||
Copyright (c) 2009, 2010, 2011, 2012 Ask Solem, and individual contributors. All rights reserved.
|
||||
Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>. All rights reserved.
|
||||
|
||||
py-amqp is licensed under The BSD License (3 Clause, also known as
|
||||
the new BSD license). The license is an OSI approved Open Source
|
||||
license and is GPL-compatible(1).
|
||||
|
||||
The license text can also be found here:
|
||||
http://www.opensource.org/licenses/BSD-3-Clause
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Ask Solem, nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Ask Solem OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
Footnotes
|
||||
=========
|
||||
(1) A GPL-compatible license makes it possible to
|
||||
combine Celery with other software that is released
|
||||
under the GPL, it does not mean that we're distributing
|
||||
Celery under the GPL license. The BSD license, unlike the GPL,
|
||||
let you distribute a modified version without making your
|
||||
changes open source.
|
||||
@@ -0,0 +1,241 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: amqp
|
||||
Version: 5.1.1
|
||||
Summary: Low-level AMQP client for Python (fork of amqplib).
|
||||
Home-page: http://github.com/celery/py-amqp
|
||||
Author: Barry Pederson
|
||||
Author-email: pyamqp@celeryproject.org
|
||||
Maintainer: Asif Saif Uddin, Matus Valo
|
||||
License: BSD
|
||||
Keywords: amqp rabbitmq cloudamqp messaging
|
||||
Platform: any
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3 :: Only
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: Implementation :: CPython
|
||||
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
||||
Classifier: License :: OSI Approved :: BSD License
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Operating System :: OS Independent
|
||||
Requires-Python: >=3.6
|
||||
Description-Content-Type: text/x-rst
|
||||
License-File: LICENSE
|
||||
Requires-Dist: vine (>=5.0.0)
|
||||
|
||||
=====================================================================
|
||||
Python AMQP 0.9.1 client library
|
||||
=====================================================================
|
||||
|
||||
|build-status| |coverage| |license| |wheel| |pyversion| |pyimp|
|
||||
|
||||
:Version: 5.1.1
|
||||
:Web: https://amqp.readthedocs.io/
|
||||
:Download: https://pypi.org/project/amqp/
|
||||
:Source: http://github.com/celery/py-amqp/
|
||||
:Keywords: amqp, rabbitmq
|
||||
|
||||
About
|
||||
=====
|
||||
|
||||
This is a fork of amqplib_ which was originally written by Barry Pederson.
|
||||
It is maintained by the Celery_ project, and used by `kombu`_ as a pure python
|
||||
alternative when `librabbitmq`_ is not available.
|
||||
|
||||
This library should be API compatible with `librabbitmq`_.
|
||||
|
||||
.. _amqplib: https://pypi.org/project/amqplib/
|
||||
.. _Celery: http://celeryproject.org/
|
||||
.. _kombu: https://kombu.readthedocs.io/
|
||||
.. _librabbitmq: https://pypi.org/project/librabbitmq/
|
||||
|
||||
Differences from `amqplib`_
|
||||
===========================
|
||||
|
||||
- Supports draining events from multiple channels (``Connection.drain_events``)
|
||||
- Support for timeouts
|
||||
- Channels are restored after channel error, instead of having to close the
|
||||
connection.
|
||||
- Support for heartbeats
|
||||
|
||||
- ``Connection.heartbeat_tick(rate=2)`` must called at regular intervals
|
||||
(half of the heartbeat value if rate is 2).
|
||||
- Or some other scheme by using ``Connection.send_heartbeat``.
|
||||
- Supports RabbitMQ extensions:
|
||||
- Consumer Cancel Notifications
|
||||
- by default a cancel results in ``ChannelError`` being raised
|
||||
- but not if a ``on_cancel`` callback is passed to ``basic_consume``.
|
||||
- Publisher confirms
|
||||
- ``Channel.confirm_select()`` enables publisher confirms.
|
||||
- ``Channel.events['basic_ack'].append(my_callback)`` adds a callback
|
||||
to be called when a message is confirmed. This callback is then
|
||||
called with the signature ``(delivery_tag, multiple)``.
|
||||
- Exchange-to-exchange bindings: ``exchange_bind`` / ``exchange_unbind``.
|
||||
- ``Channel.confirm_select()`` enables publisher confirms.
|
||||
- ``Channel.events['basic_ack'].append(my_callback)`` adds a callback
|
||||
to be called when a message is confirmed. This callback is then
|
||||
called with the signature ``(delivery_tag, multiple)``.
|
||||
- Authentication Failure Notifications
|
||||
Instead of just closing the connection abruptly on invalid
|
||||
credentials, py-amqp will raise an ``AccessRefused`` error
|
||||
when connected to rabbitmq-server 3.2.0 or greater.
|
||||
- Support for ``basic_return``
|
||||
- Uses AMQP 0-9-1 instead of 0-8.
|
||||
- ``Channel.access_request`` and ``ticket`` arguments to methods
|
||||
**removed**.
|
||||
- Supports the ``arguments`` argument to ``basic_consume``.
|
||||
- ``internal`` argument to ``exchange_declare`` removed.
|
||||
- ``auto_delete`` argument to ``exchange_declare`` deprecated
|
||||
- ``insist`` argument to ``Connection`` removed.
|
||||
- ``Channel.alerts`` has been removed.
|
||||
- Support for ``Channel.basic_recover_async``.
|
||||
- ``Channel.basic_recover`` deprecated.
|
||||
- Exceptions renamed to have idiomatic names:
|
||||
- ``AMQPException`` -> ``AMQPError``
|
||||
- ``AMQPConnectionException`` -> ConnectionError``
|
||||
- ``AMQPChannelException`` -> ChannelError``
|
||||
- ``Connection.known_hosts`` removed.
|
||||
- ``Connection`` no longer supports redirects.
|
||||
- ``exchange`` argument to ``queue_bind`` can now be empty
|
||||
to use the "default exchange".
|
||||
- Adds ``Connection.is_alive`` that tries to detect
|
||||
whether the connection can still be used.
|
||||
- Adds ``Connection.connection_errors`` and ``.channel_errors``,
|
||||
a list of recoverable errors.
|
||||
- Exposes the underlying socket as ``Connection.sock``.
|
||||
- Adds ``Channel.no_ack_consumers`` to keep track of consumer tags
|
||||
that set the no_ack flag.
|
||||
- Slightly better at error recovery
|
||||
|
||||
Quick overview
|
||||
==============
|
||||
|
||||
Simple producer publishing messages to ``test`` queue using default exchange:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import amqp
|
||||
|
||||
with amqp.Connection('broker.example.com') as c:
|
||||
ch = c.channel()
|
||||
ch.basic_publish(amqp.Message('Hello World'), routing_key='test')
|
||||
|
||||
Producer publishing to ``test_exchange`` exchange with publisher confirms enabled and using virtual_host ``test_vhost``:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import amqp
|
||||
|
||||
with amqp.Connection(
|
||||
'broker.example.com', exchange='test_exchange',
|
||||
confirm_publish=True, virtual_host='test_vhost'
|
||||
) as c:
|
||||
ch = c.channel()
|
||||
ch.basic_publish(amqp.Message('Hello World'), routing_key='test')
|
||||
|
||||
Consumer with acknowledgments enabled:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import amqp
|
||||
|
||||
with amqp.Connection('broker.example.com') as c:
|
||||
ch = c.channel()
|
||||
def on_message(message):
|
||||
print('Received message (delivery tag: {}): {}'.format(message.delivery_tag, message.body))
|
||||
ch.basic_ack(message.delivery_tag)
|
||||
ch.basic_consume(queue='test', callback=on_message)
|
||||
while True:
|
||||
c.drain_events()
|
||||
|
||||
|
||||
Consumer with acknowledgments disabled:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import amqp
|
||||
|
||||
with amqp.Connection('broker.example.com') as c:
|
||||
ch = c.channel()
|
||||
def on_message(message):
|
||||
print('Received message (delivery tag: {}): {}'.format(message.delivery_tag, message.body))
|
||||
ch.basic_consume(queue='test', callback=on_message, no_ack=True)
|
||||
while True:
|
||||
c.drain_events()
|
||||
|
||||
Speedups
|
||||
========
|
||||
|
||||
This library has **experimental** support of speedups. Speedups are implemented using Cython. To enable speedups, ``CELERY_ENABLE_SPEEDUPS`` environment variable must be set during building/installation.
|
||||
Currently speedups can be installed:
|
||||
|
||||
1. using source package (using ``--no-binary`` switch):
|
||||
|
||||
.. code:: shell
|
||||
|
||||
CELERY_ENABLE_SPEEDUPS=true pip install --no-binary :all: amqp
|
||||
|
||||
|
||||
2. building directly source code:
|
||||
|
||||
.. code:: shell
|
||||
|
||||
CELERY_ENABLE_SPEEDUPS=true python setup.py install
|
||||
|
||||
Further
|
||||
=======
|
||||
|
||||
- Differences between AMQP 0.8 and 0.9.1
|
||||
|
||||
http://www.rabbitmq.com/amqp-0-8-to-0-9-1.html
|
||||
|
||||
- AMQP 0.9.1 Quick Reference
|
||||
|
||||
http://www.rabbitmq.com/amqp-0-9-1-quickref.html
|
||||
|
||||
- RabbitMQ Extensions
|
||||
|
||||
http://www.rabbitmq.com/extensions.html
|
||||
|
||||
- For more information about AMQP, visit
|
||||
|
||||
http://www.amqp.org
|
||||
|
||||
- For other Python client libraries see:
|
||||
|
||||
http://www.rabbitmq.com/devtools.html#python-dev
|
||||
|
||||
.. |build-status| image:: https://api.travis-ci.com/celery/py-amqp.png?branch=master
|
||||
:alt: Build status
|
||||
:target: https://travis-ci.com/celery/py-amqp
|
||||
|
||||
.. |coverage| image:: https://codecov.io/github/celery/py-amqp/coverage.svg?branch=master
|
||||
:target: https://codecov.io/github/celery/py-amqp?branch=master
|
||||
|
||||
.. |license| image:: https://img.shields.io/pypi/l/amqp.svg
|
||||
:alt: BSD License
|
||||
:target: https://opensource.org/licenses/BSD-3-Clause
|
||||
|
||||
.. |wheel| image:: https://img.shields.io/pypi/wheel/amqp.svg
|
||||
:alt: Python AMQP can be installed via wheel
|
||||
:target: https://pypi.org/project/amqp/
|
||||
|
||||
.. |pyversion| image:: https://img.shields.io/pypi/pyversions/amqp.svg
|
||||
:alt: Supported Python versions.
|
||||
:target: https://pypi.org/project/amqp/
|
||||
|
||||
.. |pyimp| image:: https://img.shields.io/pypi/implementation/amqp.svg
|
||||
:alt: Support Python implementations.
|
||||
:target: https://pypi.org/project/amqp/
|
||||
|
||||
py-amqp as part of the Tidelift Subscription
|
||||
============================================
|
||||
|
||||
The maintainers of py-amqp and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/pypi-amqp?utm_source=pypi-amqp&utm_medium=referral&utm_campaign=readme&utm_term=repo)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
amqp-5.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
amqp-5.1.1.dist-info/LICENSE,sha256=9e9fEoLq4ZMcdGRfhxm2xps9aizyd7_aJJqCcM1HOvM,2372
|
||||
amqp-5.1.1.dist-info/METADATA,sha256=U0V_hIpM3GJaDCdXXI_LGo1jZJFydz6_b29E2aohLmc,8867
|
||||
amqp-5.1.1.dist-info/RECORD,,
|
||||
amqp-5.1.1.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
|
||||
amqp-5.1.1.dist-info/top_level.txt,sha256=tWQNmFVhU4UtDgB6Yy2lKqRz7LtOrRcN8_bPFVcVVR8,5
|
||||
amqp/__init__.py,sha256=-o4VeUXiY-qfYQNUKLRc2ry9pYi6a4HEjMTwXsX_ios,2365
|
||||
amqp/__pycache__/__init__.cpython-310.pyc,,
|
||||
amqp/__pycache__/abstract_channel.cpython-310.pyc,,
|
||||
amqp/__pycache__/basic_message.cpython-310.pyc,,
|
||||
amqp/__pycache__/channel.cpython-310.pyc,,
|
||||
amqp/__pycache__/connection.cpython-310.pyc,,
|
||||
amqp/__pycache__/exceptions.cpython-310.pyc,,
|
||||
amqp/__pycache__/method_framing.cpython-310.pyc,,
|
||||
amqp/__pycache__/platform.cpython-310.pyc,,
|
||||
amqp/__pycache__/protocol.cpython-310.pyc,,
|
||||
amqp/__pycache__/sasl.cpython-310.pyc,,
|
||||
amqp/__pycache__/serialization.cpython-310.pyc,,
|
||||
amqp/__pycache__/spec.cpython-310.pyc,,
|
||||
amqp/__pycache__/transport.cpython-310.pyc,,
|
||||
amqp/__pycache__/utils.cpython-310.pyc,,
|
||||
amqp/abstract_channel.py,sha256=D_OEWvX48yKUzMYm_sN-IDRQmqIGvegi9KlJriqttBc,4941
|
||||
amqp/basic_message.py,sha256=Q8DV31tuuphloTETPHiJFwNg6b5M6pccJ0InJ4MZUz8,3357
|
||||
amqp/channel.py,sha256=XzCuKPy9qFMiTsnqksKpFIh9PUcKZm3uIXm1RFCeZQs,74475
|
||||
amqp/connection.py,sha256=e_FbJYzI1_ekUbWzlQ6kIHOn8sM2Npen10WH3TFv0A8,27347
|
||||
amqp/exceptions.py,sha256=yqjoFIRue2rvK7kMdvkKsGOD6dMOzzzT3ZzBwoGWAe4,7166
|
||||
amqp/method_framing.py,sha256=avnw90X9t4995HpHoZV4-1V73UEbzUKJ83pHEicAqWY,6734
|
||||
amqp/platform.py,sha256=cyLevv6E15P9zhMo_fV84p67Q_A8fdsTq9amjvlUwqE,2379
|
||||
amqp/protocol.py,sha256=Di3y6qqhnOV4QtkeYKO-zryfWqwl3F1zUxDOmVSsAp0,291
|
||||
amqp/sasl.py,sha256=6AbsnxlbAyoiYxDezoQTfm-E0t_TJyHXpqGJ0KlPkI4,5986
|
||||
amqp/serialization.py,sha256=xzzXmmQ45fGUuSCxGTEMizmRQTmzaz3Z7YYfpxmfXuY,17162
|
||||
amqp/spec.py,sha256=2ZjbL4FR4Fv67HA7HUI9hLUIvAv3A4ZH6GRPzrMRyWg,2121
|
||||
amqp/transport.py,sha256=MyiYBerBqAMFCM-fyZgPXiCha3dz-2S6Z9cGO8IZyTg,22826
|
||||
amqp/utils.py,sha256=JjjY040LwsDUc1zmKP2VTzXBioVXy48DUZtWB8PaPy0,1456
|
||||
@@ -0,0 +1,5 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.37.1)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
amqp
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Low-level AMQP client for Python (fork of amqplib)."""
|
||||
# Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>
|
||||
|
||||
import re
|
||||
from collections import namedtuple
|
||||
|
||||
__version__ = '5.1.1'
|
||||
__author__ = 'Barry Pederson'
|
||||
__maintainer__ = 'Asif Saif Uddin, Matus Valo'
|
||||
__contact__ = 'pyamqp@celeryproject.org'
|
||||
__homepage__ = 'http://github.com/celery/py-amqp'
|
||||
__docformat__ = 'restructuredtext'
|
||||
|
||||
# -eof meta-
|
||||
|
||||
version_info_t = namedtuple('version_info_t', (
|
||||
'major', 'minor', 'micro', 'releaselevel', 'serial',
|
||||
))
|
||||
|
||||
# bumpversion can only search for {current_version}
|
||||
# so we have to parse the version here.
|
||||
_temp = re.match(
|
||||
r'(\d+)\.(\d+).(\d+)(.+)?', __version__).groups()
|
||||
VERSION = version_info = version_info_t(
|
||||
int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '')
|
||||
del(_temp)
|
||||
del(re)
|
||||
|
||||
from .basic_message import Message # noqa
|
||||
from .channel import Channel # noqa
|
||||
from .connection import Connection # noqa
|
||||
from .exceptions import (AccessRefused, AMQPError, # noqa
|
||||
AMQPNotImplementedError, ChannelError, ChannelNotOpen,
|
||||
ConnectionError, ConnectionForced, ConsumerCancelled,
|
||||
ContentTooLarge, FrameError, FrameSyntaxError,
|
||||
InternalError, InvalidCommand, InvalidPath,
|
||||
IrrecoverableChannelError,
|
||||
IrrecoverableConnectionError, NoConsumers, NotAllowed,
|
||||
NotFound, PreconditionFailed, RecoverableChannelError,
|
||||
RecoverableConnectionError, ResourceError,
|
||||
ResourceLocked, UnexpectedFrame, error_for_code)
|
||||
from .utils import promise # noqa
|
||||
|
||||
__all__ = (
|
||||
'Connection',
|
||||
'Channel',
|
||||
'Message',
|
||||
'promise',
|
||||
'AMQPError',
|
||||
'ConnectionError',
|
||||
'RecoverableConnectionError',
|
||||
'IrrecoverableConnectionError',
|
||||
'ChannelError',
|
||||
'RecoverableChannelError',
|
||||
'IrrecoverableChannelError',
|
||||
'ConsumerCancelled',
|
||||
'ContentTooLarge',
|
||||
'NoConsumers',
|
||||
'ConnectionForced',
|
||||
'InvalidPath',
|
||||
'AccessRefused',
|
||||
'NotFound',
|
||||
'ResourceLocked',
|
||||
'PreconditionFailed',
|
||||
'FrameError',
|
||||
'FrameSyntaxError',
|
||||
'InvalidCommand',
|
||||
'ChannelNotOpen',
|
||||
'UnexpectedFrame',
|
||||
'ResourceError',
|
||||
'NotAllowed',
|
||||
'AMQPNotImplementedError',
|
||||
'InternalError',
|
||||
'error_for_code',
|
||||
)
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Code common to Connection and Channel objects."""
|
||||
# Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>)
|
||||
|
||||
import logging
|
||||
|
||||
from vine import ensure_promise, promise
|
||||
|
||||
from .exceptions import AMQPNotImplementedError, RecoverableConnectionError
|
||||
from .serialization import dumps, loads
|
||||
|
||||
__all__ = ('AbstractChannel',)
|
||||
|
||||
AMQP_LOGGER = logging.getLogger('amqp')
|
||||
|
||||
IGNORED_METHOD_DURING_CHANNEL_CLOSE = """\
|
||||
Received method %s during closing channel %s. This method will be ignored\
|
||||
"""
|
||||
|
||||
|
||||
class AbstractChannel:
|
||||
"""Superclass for Connection and Channel.
|
||||
|
||||
The connection is treated as channel 0, then comes
|
||||
user-created channel objects.
|
||||
|
||||
The subclasses must have a _METHOD_MAP class property, mapping
|
||||
between AMQP method signatures and Python methods.
|
||||
"""
|
||||
|
||||
def __init__(self, connection, channel_id):
|
||||
self.is_closing = False
|
||||
self.connection = connection
|
||||
self.channel_id = channel_id
|
||||
connection.channels[channel_id] = self
|
||||
self.method_queue = [] # Higher level queue for methods
|
||||
self.auto_decode = False
|
||||
self._pending = {}
|
||||
self._callbacks = {}
|
||||
|
||||
self._setup_listeners()
|
||||
|
||||
__slots__ = (
|
||||
"is_closing",
|
||||
"connection",
|
||||
"channel_id",
|
||||
"method_queue",
|
||||
"auto_decode",
|
||||
"_pending",
|
||||
"_callbacks",
|
||||
# adding '__dict__' to get dynamic assignment
|
||||
"__dict__",
|
||||
"__weakref__",
|
||||
)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc_info):
|
||||
self.close()
|
||||
|
||||
def send_method(self, sig,
|
||||
format=None, args=None, content=None,
|
||||
wait=None, callback=None, returns_tuple=False):
|
||||
p = promise()
|
||||
conn = self.connection
|
||||
if conn is None:
|
||||
raise RecoverableConnectionError('connection already closed')
|
||||
args = dumps(format, args) if format else ''
|
||||
try:
|
||||
conn.frame_writer(1, self.channel_id, sig, args, content)
|
||||
except StopIteration:
|
||||
raise RecoverableConnectionError('connection already closed')
|
||||
|
||||
# TODO temp: callback should be after write_method ... ;)
|
||||
if callback:
|
||||
p.then(callback)
|
||||
p()
|
||||
if wait:
|
||||
return self.wait(wait, returns_tuple=returns_tuple)
|
||||
return p
|
||||
|
||||
def close(self):
|
||||
"""Close this Channel or Connection."""
|
||||
raise NotImplementedError('Must be overridden in subclass')
|
||||
|
||||
def wait(self, method, callback=None, timeout=None, returns_tuple=False):
|
||||
p = ensure_promise(callback)
|
||||
pending = self._pending
|
||||
prev_p = []
|
||||
if not isinstance(method, list):
|
||||
method = [method]
|
||||
|
||||
for m in method:
|
||||
prev_p.append(pending.get(m))
|
||||
pending[m] = p
|
||||
|
||||
try:
|
||||
while not p.ready:
|
||||
self.connection.drain_events(timeout=timeout)
|
||||
|
||||
if p.value:
|
||||
args, kwargs = p.value
|
||||
args = args[1:] # We are not returning method back
|
||||
return args if returns_tuple else (args and args[0])
|
||||
finally:
|
||||
for i, m in enumerate(method):
|
||||
if prev_p[i] is not None:
|
||||
pending[m] = prev_p[i]
|
||||
else:
|
||||
pending.pop(m, None)
|
||||
|
||||
def dispatch_method(self, method_sig, payload, content):
|
||||
if self.is_closing and method_sig not in (
|
||||
self._ALLOWED_METHODS_WHEN_CLOSING
|
||||
):
|
||||
# When channel.close() was called we must ignore all methods except
|
||||
# Channel.close and Channel.CloseOk
|
||||
AMQP_LOGGER.warning(
|
||||
IGNORED_METHOD_DURING_CHANNEL_CLOSE,
|
||||
method_sig, self.channel_id
|
||||
)
|
||||
return
|
||||
|
||||
if content and \
|
||||
self.auto_decode and \
|
||||
hasattr(content, 'content_encoding'):
|
||||
try:
|
||||
content.body = content.body.decode(content.content_encoding)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
amqp_method = self._METHODS[method_sig]
|
||||
except KeyError:
|
||||
raise AMQPNotImplementedError(
|
||||
f'Unknown AMQP method {method_sig!r}')
|
||||
|
||||
try:
|
||||
listeners = [self._callbacks[method_sig]]
|
||||
except KeyError:
|
||||
listeners = []
|
||||
one_shot = None
|
||||
try:
|
||||
one_shot = self._pending.pop(method_sig)
|
||||
except KeyError:
|
||||
if not listeners:
|
||||
return
|
||||
|
||||
args = []
|
||||
if amqp_method.args:
|
||||
args, _ = loads(amqp_method.args, payload, 4)
|
||||
if amqp_method.content:
|
||||
args.append(content)
|
||||
|
||||
for listener in listeners:
|
||||
listener(*args)
|
||||
|
||||
if one_shot:
|
||||
one_shot(method_sig, *args)
|
||||
|
||||
#: Placeholder, the concrete implementations will have to
|
||||
#: supply their own versions of _METHOD_MAP
|
||||
_METHODS = {}
|
||||
@@ -0,0 +1,122 @@
|
||||
"""AMQP Messages."""
|
||||
# Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>
|
||||
from .serialization import GenericContent
|
||||
# Intended to fix #85: ImportError: cannot import name spec
|
||||
# Encountered on python 2.7.3
|
||||
# "The submodules often need to refer to each other. For example, the
|
||||
# surround [sic] module might use the echo module. In fact, such
|
||||
# references are so common that the import statement first looks in
|
||||
# the containing package before looking in the standard module search
|
||||
# path."
|
||||
# Source:
|
||||
# http://stackoverflow.com/a/14216937/4982251
|
||||
from .spec import Basic
|
||||
|
||||
__all__ = ('Message',)
|
||||
|
||||
|
||||
class Message(GenericContent):
|
||||
"""A Message for use with the Channel.basic_* methods.
|
||||
|
||||
Expected arg types
|
||||
|
||||
body: string
|
||||
children: (not supported)
|
||||
|
||||
Keyword properties may include:
|
||||
|
||||
content_type: shortstr
|
||||
MIME content type
|
||||
|
||||
content_encoding: shortstr
|
||||
MIME content encoding
|
||||
|
||||
application_headers: table
|
||||
Message header field table, a dict with string keys,
|
||||
and string | int | Decimal | datetime | dict values.
|
||||
|
||||
delivery_mode: octet
|
||||
Non-persistent (1) or persistent (2)
|
||||
|
||||
priority: octet
|
||||
The message priority, 0 to 9
|
||||
|
||||
correlation_id: shortstr
|
||||
The application correlation identifier
|
||||
|
||||
reply_to: shortstr
|
||||
The destination to reply to
|
||||
|
||||
expiration: shortstr
|
||||
Message expiration specification
|
||||
|
||||
message_id: shortstr
|
||||
The application message identifier
|
||||
|
||||
timestamp: unsigned long
|
||||
The message timestamp
|
||||
|
||||
type: shortstr
|
||||
The message type name
|
||||
|
||||
user_id: shortstr
|
||||
The creating user id
|
||||
|
||||
app_id: shortstr
|
||||
The creating application id
|
||||
|
||||
cluster_id: shortstr
|
||||
Intra-cluster routing identifier
|
||||
|
||||
Unicode bodies are encoded according to the 'content_encoding'
|
||||
argument. If that's None, it's set to 'UTF-8' automatically.
|
||||
|
||||
Example::
|
||||
|
||||
msg = Message('hello world',
|
||||
content_type='text/plain',
|
||||
application_headers={'foo': 7})
|
||||
"""
|
||||
|
||||
CLASS_ID = Basic.CLASS_ID
|
||||
|
||||
#: Instances of this class have these attributes, which
|
||||
#: are passed back and forth as message properties between
|
||||
#: client and server
|
||||
PROPERTIES = [
|
||||
('content_type', 's'),
|
||||
('content_encoding', 's'),
|
||||
('application_headers', 'F'),
|
||||
('delivery_mode', 'o'),
|
||||
('priority', 'o'),
|
||||
('correlation_id', 's'),
|
||||
('reply_to', 's'),
|
||||
('expiration', 's'),
|
||||
('message_id', 's'),
|
||||
('timestamp', 'L'),
|
||||
('type', 's'),
|
||||
('user_id', 's'),
|
||||
('app_id', 's'),
|
||||
('cluster_id', 's')
|
||||
]
|
||||
|
||||
def __init__(self, body='', children=None, channel=None, **properties):
|
||||
super().__init__(**properties)
|
||||
#: set by basic_consume/basic_get
|
||||
self.delivery_info = None
|
||||
self.body = body
|
||||
self.channel = channel
|
||||
|
||||
__slots__ = (
|
||||
"delivery_info",
|
||||
"body",
|
||||
"channel",
|
||||
)
|
||||
|
||||
@property
|
||||
def headers(self):
|
||||
return self.properties.get('application_headers')
|
||||
|
||||
@property
|
||||
def delivery_tag(self):
|
||||
return self.delivery_info.get('delivery_tag')
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,778 @@
|
||||
"""AMQP Connections."""
|
||||
# Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>
|
||||
|
||||
import logging
|
||||
import socket
|
||||
import uuid
|
||||
import warnings
|
||||
from array import array
|
||||
from time import monotonic
|
||||
|
||||
from vine import ensure_promise
|
||||
|
||||
from . import __version__, sasl, spec
|
||||
from .abstract_channel import AbstractChannel
|
||||
from .channel import Channel
|
||||
from .exceptions import (AMQPDeprecationWarning, ChannelError, ConnectionError,
|
||||
ConnectionForced, RecoverableChannelError,
|
||||
RecoverableConnectionError, ResourceError,
|
||||
error_for_code)
|
||||
from .method_framing import frame_handler, frame_writer
|
||||
from .transport import Transport
|
||||
|
||||
try:
|
||||
from ssl import SSLError
|
||||
except ImportError: # pragma: no cover
|
||||
class SSLError(Exception): # noqa
|
||||
pass
|
||||
|
||||
W_FORCE_CONNECT = """\
|
||||
The .{attr} attribute on the connection was accessed before
|
||||
the connection was established. This is supported for now, but will
|
||||
be deprecated in amqp 2.2.0.
|
||||
|
||||
Since amqp 2.0 you have to explicitly call Connection.connect()
|
||||
before using the connection.
|
||||
"""
|
||||
|
||||
START_DEBUG_FMT = """
|
||||
Start from server, version: %d.%d, properties: %s, mechanisms: %s, locales: %s
|
||||
""".strip()
|
||||
|
||||
__all__ = ('Connection',)
|
||||
|
||||
AMQP_LOGGER = logging.getLogger('amqp')
|
||||
AMQP_HEARTBEAT_LOGGER = logging.getLogger(
|
||||
'amqp.connection.Connection.heartbeat_tick'
|
||||
)
|
||||
|
||||
#: Default map for :attr:`Connection.library_properties`
|
||||
LIBRARY_PROPERTIES = {
|
||||
'product': 'py-amqp',
|
||||
'product_version': __version__,
|
||||
}
|
||||
|
||||
#: Default map for :attr:`Connection.negotiate_capabilities`
|
||||
NEGOTIATE_CAPABILITIES = {
|
||||
'consumer_cancel_notify': True,
|
||||
'connection.blocked': True,
|
||||
'authentication_failure_close': True,
|
||||
}
|
||||
|
||||
|
||||
class Connection(AbstractChannel):
|
||||
"""AMQP Connection.
|
||||
|
||||
The connection class provides methods for a client to establish a
|
||||
network connection to a server, and for both peers to operate the
|
||||
connection thereafter.
|
||||
|
||||
GRAMMAR::
|
||||
|
||||
connection = open-connection *use-connection close-connection
|
||||
open-connection = C:protocol-header
|
||||
S:START C:START-OK
|
||||
*challenge
|
||||
S:TUNE C:TUNE-OK
|
||||
C:OPEN S:OPEN-OK
|
||||
challenge = S:SECURE C:SECURE-OK
|
||||
use-connection = *channel
|
||||
close-connection = C:CLOSE S:CLOSE-OK
|
||||
/ S:CLOSE C:CLOSE-OK
|
||||
Create a connection to the specified host, which should be
|
||||
a 'host[:port]', such as 'localhost', or '1.2.3.4:5672'
|
||||
(defaults to 'localhost', if a port is not specified then
|
||||
5672 is used)
|
||||
|
||||
Authentication can be controlled by passing one or more
|
||||
`amqp.sasl.SASL` instances as the `authentication` parameter, or
|
||||
setting the `login_method` string to one of the supported methods:
|
||||
'GSSAPI', 'EXTERNAL', 'AMQPLAIN', or 'PLAIN'.
|
||||
Otherwise authentication will be performed using any supported method
|
||||
preferred by the server. Userid and passwords apply to AMQPLAIN and
|
||||
PLAIN authentication, whereas on GSSAPI only userid will be used as the
|
||||
client name. For EXTERNAL authentication both userid and password are
|
||||
ignored.
|
||||
|
||||
The 'ssl' parameter may be simply True/False, or
|
||||
a dictionary of options to pass to :class:`ssl.SSLContext` such as
|
||||
requiring certain certificates. For details, refer ``ssl`` parameter of
|
||||
:class:`~amqp.transport.SSLTransport`.
|
||||
|
||||
The "socket_settings" parameter is a dictionary defining tcp
|
||||
settings which will be applied as socket options.
|
||||
|
||||
When "confirm_publish" is set to True, the channel is put to
|
||||
confirm mode. In this mode, each published message is
|
||||
confirmed using Publisher confirms RabbitMQ extension.
|
||||
"""
|
||||
|
||||
Channel = Channel
|
||||
|
||||
#: Mapping of protocol extensions to enable.
|
||||
#: The server will report these in server_properties[capabilities],
|
||||
#: and if a key in this map is present the client will tell the
|
||||
#: server to either enable or disable the capability depending
|
||||
#: on the value set in this map.
|
||||
#: For example with:
|
||||
#: negotiate_capabilities = {
|
||||
#: 'consumer_cancel_notify': True,
|
||||
#: }
|
||||
#: The client will enable this capability if the server reports
|
||||
#: support for it, but if the value is False the client will
|
||||
#: disable the capability.
|
||||
negotiate_capabilities = NEGOTIATE_CAPABILITIES
|
||||
|
||||
#: These are sent to the server to announce what features
|
||||
#: we support, type of client etc.
|
||||
library_properties = LIBRARY_PROPERTIES
|
||||
|
||||
#: Final heartbeat interval value (in float seconds) after negotiation
|
||||
heartbeat = None
|
||||
|
||||
#: Original heartbeat interval value proposed by client.
|
||||
client_heartbeat = None
|
||||
|
||||
#: Original heartbeat interval proposed by server.
|
||||
server_heartbeat = None
|
||||
|
||||
#: Time of last heartbeat sent (in monotonic time, if available).
|
||||
last_heartbeat_sent = 0
|
||||
|
||||
#: Time of last heartbeat received (in monotonic time, if available).
|
||||
last_heartbeat_received = 0
|
||||
|
||||
#: Number of successful writes to socket.
|
||||
bytes_sent = 0
|
||||
|
||||
#: Number of successful reads from socket.
|
||||
bytes_recv = 0
|
||||
|
||||
#: Number of bytes sent to socket at the last heartbeat check.
|
||||
prev_sent = None
|
||||
|
||||
#: Number of bytes received from socket at the last heartbeat check.
|
||||
prev_recv = None
|
||||
|
||||
_METHODS = {
|
||||
spec.method(spec.Connection.Start, 'ooFSS'),
|
||||
spec.method(spec.Connection.OpenOk),
|
||||
spec.method(spec.Connection.Secure, 's'),
|
||||
spec.method(spec.Connection.Tune, 'BlB'),
|
||||
spec.method(spec.Connection.Close, 'BsBB'),
|
||||
spec.method(spec.Connection.Blocked),
|
||||
spec.method(spec.Connection.Unblocked),
|
||||
spec.method(spec.Connection.CloseOk),
|
||||
}
|
||||
_METHODS = {m.method_sig: m for m in _METHODS}
|
||||
|
||||
_ALLOWED_METHODS_WHEN_CLOSING = (
|
||||
spec.Connection.Close, spec.Connection.CloseOk
|
||||
)
|
||||
|
||||
connection_errors = (
|
||||
ConnectionError,
|
||||
socket.error,
|
||||
IOError,
|
||||
OSError,
|
||||
)
|
||||
channel_errors = (ChannelError,)
|
||||
recoverable_connection_errors = (
|
||||
RecoverableConnectionError,
|
||||
socket.error,
|
||||
IOError,
|
||||
OSError,
|
||||
)
|
||||
recoverable_channel_errors = (
|
||||
RecoverableChannelError,
|
||||
)
|
||||
|
||||
def __init__(self, host='localhost:5672', userid='guest', password='guest',
|
||||
login_method=None, login_response=None,
|
||||
authentication=(),
|
||||
virtual_host='/', locale='en_US', client_properties=None,
|
||||
ssl=False, connect_timeout=None, channel_max=None,
|
||||
frame_max=None, heartbeat=0, on_open=None, on_blocked=None,
|
||||
on_unblocked=None, confirm_publish=False,
|
||||
on_tune_ok=None, read_timeout=None, write_timeout=None,
|
||||
socket_settings=None, frame_handler=frame_handler,
|
||||
frame_writer=frame_writer, **kwargs):
|
||||
self._connection_id = uuid.uuid4().hex
|
||||
channel_max = channel_max or 65535
|
||||
frame_max = frame_max or 131072
|
||||
if authentication:
|
||||
if isinstance(authentication, sasl.SASL):
|
||||
authentication = (authentication,)
|
||||
self.authentication = authentication
|
||||
elif login_method is not None:
|
||||
if login_method == 'GSSAPI':
|
||||
auth = sasl.GSSAPI(userid)
|
||||
elif login_method == 'EXTERNAL':
|
||||
auth = sasl.EXTERNAL()
|
||||
elif login_method == 'AMQPLAIN':
|
||||
if userid is None or password is None:
|
||||
raise ValueError(
|
||||
"Must supply authentication or userid/password")
|
||||
auth = sasl.AMQPLAIN(userid, password)
|
||||
elif login_method == 'PLAIN':
|
||||
if userid is None or password is None:
|
||||
raise ValueError(
|
||||
"Must supply authentication or userid/password")
|
||||
auth = sasl.PLAIN(userid, password)
|
||||
elif login_response is not None:
|
||||
auth = sasl.RAW(login_method, login_response)
|
||||
else:
|
||||
raise ValueError("Invalid login method", login_method)
|
||||
self.authentication = (auth,)
|
||||
else:
|
||||
self.authentication = (sasl.GSSAPI(userid, fail_soft=True),
|
||||
sasl.EXTERNAL(),
|
||||
sasl.AMQPLAIN(userid, password),
|
||||
sasl.PLAIN(userid, password))
|
||||
|
||||
self.client_properties = dict(
|
||||
self.library_properties, **client_properties or {}
|
||||
)
|
||||
self.locale = locale
|
||||
self.host = host
|
||||
self.virtual_host = virtual_host
|
||||
self.on_tune_ok = ensure_promise(on_tune_ok)
|
||||
|
||||
self.frame_handler_cls = frame_handler
|
||||
self.frame_writer_cls = frame_writer
|
||||
|
||||
self._handshake_complete = False
|
||||
|
||||
self.channels = {}
|
||||
# The connection object itself is treated as channel 0
|
||||
super().__init__(self, 0)
|
||||
|
||||
self._frame_writer = None
|
||||
self._on_inbound_frame = None
|
||||
self._transport = None
|
||||
|
||||
# Properties set in the Tune method
|
||||
self.channel_max = channel_max
|
||||
self.frame_max = frame_max
|
||||
self.client_heartbeat = heartbeat
|
||||
|
||||
self.confirm_publish = confirm_publish
|
||||
self.ssl = ssl
|
||||
self.read_timeout = read_timeout
|
||||
self.write_timeout = write_timeout
|
||||
self.socket_settings = socket_settings
|
||||
|
||||
# Callbacks
|
||||
self.on_blocked = on_blocked
|
||||
self.on_unblocked = on_unblocked
|
||||
self.on_open = ensure_promise(on_open)
|
||||
|
||||
self._used_channel_ids = array('H')
|
||||
|
||||
# Properties set in the Start method
|
||||
self.version_major = 0
|
||||
self.version_minor = 0
|
||||
self.server_properties = {}
|
||||
self.mechanisms = []
|
||||
self.locales = []
|
||||
|
||||
self.connect_timeout = connect_timeout
|
||||
|
||||
def __repr__(self):
|
||||
if self._transport:
|
||||
return f'<AMQP Connection: {self.host}/{self.virtual_host} '\
|
||||
f'using {self._transport} at {id(self):#x}>'
|
||||
else:
|
||||
return f'<AMQP Connection: {self.host}/{self.virtual_host} '\
|
||||
f'(disconnected) at {id(self):#x}>'
|
||||
|
||||
def __enter__(self):
|
||||
self.connect()
|
||||
return self
|
||||
|
||||
def __exit__(self, *eargs):
|
||||
self.close()
|
||||
|
||||
def then(self, on_success, on_error=None):
|
||||
return self.on_open.then(on_success, on_error)
|
||||
|
||||
def _setup_listeners(self):
|
||||
self._callbacks.update({
|
||||
spec.Connection.Start: self._on_start,
|
||||
spec.Connection.OpenOk: self._on_open_ok,
|
||||
spec.Connection.Secure: self._on_secure,
|
||||
spec.Connection.Tune: self._on_tune,
|
||||
spec.Connection.Close: self._on_close,
|
||||
spec.Connection.Blocked: self._on_blocked,
|
||||
spec.Connection.Unblocked: self._on_unblocked,
|
||||
spec.Connection.CloseOk: self._on_close_ok,
|
||||
})
|
||||
|
||||
def connect(self, callback=None):
|
||||
# Let the transport.py module setup the actual
|
||||
# socket connection to the broker.
|
||||
#
|
||||
if self.connected:
|
||||
return callback() if callback else None
|
||||
try:
|
||||
self.transport = self.Transport(
|
||||
self.host, self.connect_timeout, self.ssl,
|
||||
self.read_timeout, self.write_timeout,
|
||||
socket_settings=self.socket_settings,
|
||||
)
|
||||
self.transport.connect()
|
||||
self.on_inbound_frame = self.frame_handler_cls(
|
||||
self, self.on_inbound_method)
|
||||
self.frame_writer = self.frame_writer_cls(self, self.transport)
|
||||
|
||||
while not self._handshake_complete:
|
||||
self.drain_events(timeout=self.connect_timeout)
|
||||
|
||||
except (OSError, SSLError):
|
||||
self.collect()
|
||||
raise
|
||||
|
||||
def _warn_force_connect(self, attr):
|
||||
warnings.warn(AMQPDeprecationWarning(
|
||||
W_FORCE_CONNECT.format(attr=attr)))
|
||||
|
||||
@property
|
||||
def transport(self):
|
||||
if self._transport is None:
|
||||
self._warn_force_connect('transport')
|
||||
self.connect()
|
||||
return self._transport
|
||||
|
||||
@transport.setter
|
||||
def transport(self, transport):
|
||||
self._transport = transport
|
||||
|
||||
@property
|
||||
def on_inbound_frame(self):
|
||||
if self._on_inbound_frame is None:
|
||||
self._warn_force_connect('on_inbound_frame')
|
||||
self.connect()
|
||||
return self._on_inbound_frame
|
||||
|
||||
@on_inbound_frame.setter
|
||||
def on_inbound_frame(self, on_inbound_frame):
|
||||
self._on_inbound_frame = on_inbound_frame
|
||||
|
||||
@property
|
||||
def frame_writer(self):
|
||||
if self._frame_writer is None:
|
||||
self._warn_force_connect('frame_writer')
|
||||
self.connect()
|
||||
return self._frame_writer
|
||||
|
||||
@frame_writer.setter
|
||||
def frame_writer(self, frame_writer):
|
||||
self._frame_writer = frame_writer
|
||||
|
||||
def _on_start(self, version_major, version_minor, server_properties,
|
||||
mechanisms, locales, argsig='FsSs'):
|
||||
client_properties = self.client_properties
|
||||
self.version_major = version_major
|
||||
self.version_minor = version_minor
|
||||
self.server_properties = server_properties
|
||||
if isinstance(mechanisms, str):
|
||||
mechanisms = mechanisms.encode('utf-8')
|
||||
self.mechanisms = mechanisms.split(b' ')
|
||||
self.locales = locales.split(' ')
|
||||
AMQP_LOGGER.debug(
|
||||
START_DEBUG_FMT,
|
||||
self.version_major, self.version_minor,
|
||||
self.server_properties, self.mechanisms, self.locales,
|
||||
)
|
||||
|
||||
# Negotiate protocol extensions (capabilities)
|
||||
scap = server_properties.get('capabilities') or {}
|
||||
cap = client_properties.setdefault('capabilities', {})
|
||||
cap.update({
|
||||
wanted_cap: enable_cap
|
||||
for wanted_cap, enable_cap in self.negotiate_capabilities.items()
|
||||
if scap.get(wanted_cap)
|
||||
})
|
||||
if not cap:
|
||||
# no capabilities, server may not react well to having
|
||||
# this key present in client_properties, so we remove it.
|
||||
client_properties.pop('capabilities', None)
|
||||
|
||||
for authentication in self.authentication:
|
||||
if authentication.mechanism in self.mechanisms:
|
||||
login_response = authentication.start(self)
|
||||
if login_response is not NotImplemented:
|
||||
break
|
||||
else:
|
||||
raise ConnectionError(
|
||||
"Couldn't find appropriate auth mechanism "
|
||||
"(can offer: {}; available: {})".format(
|
||||
b", ".join(m.mechanism
|
||||
for m in self.authentication
|
||||
if m.mechanism).decode(),
|
||||
b", ".join(self.mechanisms).decode()))
|
||||
|
||||
self.send_method(
|
||||
spec.Connection.StartOk, argsig,
|
||||
(client_properties, authentication.mechanism,
|
||||
login_response, self.locale),
|
||||
)
|
||||
|
||||
def _on_secure(self, challenge):
|
||||
pass
|
||||
|
||||
def _on_tune(self, channel_max, frame_max, server_heartbeat, argsig='BlB'):
|
||||
client_heartbeat = self.client_heartbeat or 0
|
||||
self.channel_max = channel_max or self.channel_max
|
||||
self.frame_max = frame_max or self.frame_max
|
||||
self.server_heartbeat = server_heartbeat or 0
|
||||
|
||||
# negotiate the heartbeat interval to the smaller of the
|
||||
# specified values
|
||||
if self.server_heartbeat == 0 or client_heartbeat == 0:
|
||||
self.heartbeat = max(self.server_heartbeat, client_heartbeat)
|
||||
else:
|
||||
self.heartbeat = min(self.server_heartbeat, client_heartbeat)
|
||||
|
||||
# Ignore server heartbeat if client_heartbeat is disabled
|
||||
if not self.client_heartbeat:
|
||||
self.heartbeat = 0
|
||||
|
||||
self.send_method(
|
||||
spec.Connection.TuneOk, argsig,
|
||||
(self.channel_max, self.frame_max, self.heartbeat),
|
||||
callback=self._on_tune_sent,
|
||||
)
|
||||
|
||||
def _on_tune_sent(self, argsig='ssb'):
|
||||
self.send_method(
|
||||
spec.Connection.Open, argsig, (self.virtual_host, '', False),
|
||||
)
|
||||
|
||||
def _on_open_ok(self):
|
||||
self._handshake_complete = True
|
||||
self.on_open(self)
|
||||
|
||||
def Transport(self, host, connect_timeout,
|
||||
ssl=False, read_timeout=None, write_timeout=None,
|
||||
socket_settings=None, **kwargs):
|
||||
return Transport(
|
||||
host, connect_timeout=connect_timeout, ssl=ssl,
|
||||
read_timeout=read_timeout, write_timeout=write_timeout,
|
||||
socket_settings=socket_settings, **kwargs)
|
||||
|
||||
@property
|
||||
def connected(self):
|
||||
return self._transport and self._transport.connected
|
||||
|
||||
def collect(self):
|
||||
if self._transport:
|
||||
self._transport.close()
|
||||
|
||||
if self.channels:
|
||||
# Copy all the channels except self since the channels
|
||||
# dictionary changes during the collection process.
|
||||
channels = [
|
||||
ch for ch in self.channels.values()
|
||||
if ch is not self
|
||||
]
|
||||
|
||||
for ch in channels:
|
||||
ch.collect()
|
||||
self._transport = self.connection = self.channels = None
|
||||
|
||||
def _get_free_channel_id(self):
|
||||
# Cast to a set for fast lookups, and keep stored as an array for lower memory usage.
|
||||
used_channel_ids = set(self._used_channel_ids)
|
||||
|
||||
for channel_id in range(1, self.channel_max + 1):
|
||||
if channel_id not in used_channel_ids:
|
||||
self._used_channel_ids.append(channel_id)
|
||||
return channel_id
|
||||
|
||||
raise ResourceError(
|
||||
'No free channel ids, current={}, channel_max={}'.format(
|
||||
len(self.channels), self.channel_max), spec.Channel.Open)
|
||||
|
||||
def _claim_channel_id(self, channel_id):
|
||||
if channel_id in self._used_channel_ids:
|
||||
raise ConnectionError(f'Channel {channel_id!r} already open')
|
||||
else:
|
||||
self._used_channel_ids.append(channel_id)
|
||||
return channel_id
|
||||
|
||||
def channel(self, channel_id=None, callback=None):
|
||||
"""Create new channel.
|
||||
|
||||
Fetch a Channel object identified by the numeric channel_id, or
|
||||
create that object if it doesn't already exist.
|
||||
"""
|
||||
if self.channels is None:
|
||||
raise RecoverableConnectionError('Connection already closed.')
|
||||
|
||||
try:
|
||||
return self.channels[channel_id]
|
||||
except KeyError:
|
||||
channel = self.Channel(self, channel_id, on_open=callback)
|
||||
channel.open()
|
||||
return channel
|
||||
|
||||
def is_alive(self):
|
||||
raise NotImplementedError('Use AMQP heartbeats')
|
||||
|
||||
def drain_events(self, timeout=None):
|
||||
# read until message is ready
|
||||
while not self.blocking_read(timeout):
|
||||
pass
|
||||
|
||||
def blocking_read(self, timeout=None):
|
||||
with self.transport.having_timeout(timeout):
|
||||
frame = self.transport.read_frame()
|
||||
return self.on_inbound_frame(frame)
|
||||
|
||||
def on_inbound_method(self, channel_id, method_sig, payload, content):
|
||||
if self.channels is None:
|
||||
raise RecoverableConnectionError('Connection already closed')
|
||||
|
||||
return self.channels[channel_id].dispatch_method(
|
||||
method_sig, payload, content,
|
||||
)
|
||||
|
||||
def close(self, reply_code=0, reply_text='', method_sig=(0, 0),
|
||||
argsig='BsBB'):
|
||||
"""Request a connection close.
|
||||
|
||||
This method indicates that the sender wants to close the
|
||||
connection. This may be due to internal conditions (e.g. a
|
||||
forced shut-down) or due to an error handling a specific
|
||||
method, i.e. an exception. When a close is due to an
|
||||
exception, the sender provides the class and method id of the
|
||||
method which caused the exception.
|
||||
|
||||
RULE:
|
||||
|
||||
After sending this method any received method except the
|
||||
Close-OK method MUST be discarded.
|
||||
|
||||
RULE:
|
||||
|
||||
The peer sending this method MAY use a counter or timeout
|
||||
to detect failure of the other peer to respond correctly
|
||||
with the Close-OK method.
|
||||
|
||||
RULE:
|
||||
|
||||
When a server receives the Close method from a client it
|
||||
MUST delete all server-side resources associated with the
|
||||
client's context. A client CANNOT reconnect to a context
|
||||
after sending or receiving a Close method.
|
||||
|
||||
PARAMETERS:
|
||||
reply_code: short
|
||||
|
||||
The reply code. The AMQ reply codes are defined in AMQ
|
||||
RFC 011.
|
||||
|
||||
reply_text: shortstr
|
||||
|
||||
The localised reply text. This text can be logged as an
|
||||
aid to resolving issues.
|
||||
|
||||
class_id: short
|
||||
|
||||
failing method class
|
||||
|
||||
When the close is provoked by a method exception, this
|
||||
is the class of the method.
|
||||
|
||||
method_id: short
|
||||
|
||||
failing method ID
|
||||
|
||||
When the close is provoked by a method exception, this
|
||||
is the ID of the method.
|
||||
"""
|
||||
if self._transport is None:
|
||||
# already closed
|
||||
return
|
||||
|
||||
try:
|
||||
self.is_closing = True
|
||||
return self.send_method(
|
||||
spec.Connection.Close, argsig,
|
||||
(reply_code, reply_text, method_sig[0], method_sig[1]),
|
||||
wait=spec.Connection.CloseOk,
|
||||
)
|
||||
except (OSError, SSLError):
|
||||
# close connection
|
||||
self.collect()
|
||||
raise
|
||||
finally:
|
||||
self.is_closing = False
|
||||
|
||||
def _on_close(self, reply_code, reply_text, class_id, method_id):
|
||||
"""Request a connection close.
|
||||
|
||||
This method indicates that the sender wants to close the
|
||||
connection. This may be due to internal conditions (e.g. a
|
||||
forced shut-down) or due to an error handling a specific
|
||||
method, i.e. an exception. When a close is due to an
|
||||
exception, the sender provides the class and method id of the
|
||||
method which caused the exception.
|
||||
|
||||
RULE:
|
||||
|
||||
After sending this method any received method except the
|
||||
Close-OK method MUST be discarded.
|
||||
|
||||
RULE:
|
||||
|
||||
The peer sending this method MAY use a counter or timeout
|
||||
to detect failure of the other peer to respond correctly
|
||||
with the Close-OK method.
|
||||
|
||||
RULE:
|
||||
|
||||
When a server receives the Close method from a client it
|
||||
MUST delete all server-side resources associated with the
|
||||
client's context. A client CANNOT reconnect to a context
|
||||
after sending or receiving a Close method.
|
||||
|
||||
PARAMETERS:
|
||||
reply_code: short
|
||||
|
||||
The reply code. The AMQ reply codes are defined in AMQ
|
||||
RFC 011.
|
||||
|
||||
reply_text: shortstr
|
||||
|
||||
The localised reply text. This text can be logged as an
|
||||
aid to resolving issues.
|
||||
|
||||
class_id: short
|
||||
|
||||
failing method class
|
||||
|
||||
When the close is provoked by a method exception, this
|
||||
is the class of the method.
|
||||
|
||||
method_id: short
|
||||
|
||||
failing method ID
|
||||
|
||||
When the close is provoked by a method exception, this
|
||||
is the ID of the method.
|
||||
"""
|
||||
self._x_close_ok()
|
||||
raise error_for_code(reply_code, reply_text,
|
||||
(class_id, method_id), ConnectionError)
|
||||
|
||||
def _x_close_ok(self):
|
||||
"""Confirm a connection close.
|
||||
|
||||
This method confirms a Connection.Close method and tells the
|
||||
recipient that it is safe to release resources for the
|
||||
connection and close the socket.
|
||||
|
||||
RULE:
|
||||
A peer that detects a socket closure without having
|
||||
received a Close-Ok handshake method SHOULD log the error.
|
||||
"""
|
||||
self.send_method(spec.Connection.CloseOk, callback=self._on_close_ok)
|
||||
|
||||
def _on_close_ok(self):
|
||||
"""Confirm a connection close.
|
||||
|
||||
This method confirms a Connection.Close method and tells the
|
||||
recipient that it is safe to release resources for the
|
||||
connection and close the socket.
|
||||
|
||||
RULE:
|
||||
|
||||
A peer that detects a socket closure without having
|
||||
received a Close-Ok handshake method SHOULD log the error.
|
||||
"""
|
||||
self.collect()
|
||||
|
||||
def _on_blocked(self):
|
||||
"""Callback called when connection blocked.
|
||||
|
||||
Notes:
|
||||
This is an RabbitMQ Extension.
|
||||
"""
|
||||
reason = 'connection blocked, see broker logs'
|
||||
if self.on_blocked:
|
||||
return self.on_blocked(reason)
|
||||
|
||||
def _on_unblocked(self):
|
||||
if self.on_unblocked:
|
||||
return self.on_unblocked()
|
||||
|
||||
def send_heartbeat(self):
|
||||
self.frame_writer(8, 0, None, None, None)
|
||||
|
||||
def heartbeat_tick(self, rate=2):
|
||||
"""Send heartbeat packets if necessary.
|
||||
|
||||
Raises:
|
||||
~amqp.exceptions.ConnectionForvced: if none have been
|
||||
received recently.
|
||||
|
||||
Note:
|
||||
This should be called frequently, on the order of
|
||||
once per second.
|
||||
|
||||
Keyword Arguments:
|
||||
rate (int): Previously used, but ignored now.
|
||||
"""
|
||||
AMQP_HEARTBEAT_LOGGER.debug('heartbeat_tick : for connection %s',
|
||||
self._connection_id)
|
||||
if not self.heartbeat:
|
||||
return
|
||||
|
||||
# treat actual data exchange in either direction as a heartbeat
|
||||
sent_now = self.bytes_sent
|
||||
recv_now = self.bytes_recv
|
||||
if self.prev_sent is None or self.prev_sent != sent_now:
|
||||
self.last_heartbeat_sent = monotonic()
|
||||
if self.prev_recv is None or self.prev_recv != recv_now:
|
||||
self.last_heartbeat_received = monotonic()
|
||||
|
||||
now = monotonic()
|
||||
AMQP_HEARTBEAT_LOGGER.debug(
|
||||
'heartbeat_tick : Prev sent/recv: %s/%s, '
|
||||
'now - %s/%s, monotonic - %s, '
|
||||
'last_heartbeat_sent - %s, heartbeat int. - %s '
|
||||
'for connection %s',
|
||||
self.prev_sent, self.prev_recv,
|
||||
sent_now, recv_now, now,
|
||||
self.last_heartbeat_sent,
|
||||
self.heartbeat,
|
||||
self._connection_id,
|
||||
)
|
||||
|
||||
self.prev_sent, self.prev_recv = sent_now, recv_now
|
||||
|
||||
# send a heartbeat if it's time to do so
|
||||
if now > self.last_heartbeat_sent + self.heartbeat:
|
||||
AMQP_HEARTBEAT_LOGGER.debug(
|
||||
'heartbeat_tick: sending heartbeat for connection %s',
|
||||
self._connection_id)
|
||||
self.send_heartbeat()
|
||||
self.last_heartbeat_sent = monotonic()
|
||||
|
||||
# if we've missed two intervals' heartbeats, fail; this gives the
|
||||
# server enough time to send heartbeats a little late
|
||||
two_heartbeats = 2 * self.heartbeat
|
||||
two_heartbeats_interval = self.last_heartbeat_received + two_heartbeats
|
||||
heartbeats_missed = two_heartbeats_interval < monotonic()
|
||||
if self.last_heartbeat_received and heartbeats_missed:
|
||||
raise ConnectionForced('Too many heartbeats missed')
|
||||
|
||||
@property
|
||||
def sock(self):
|
||||
return self.transport.sock
|
||||
|
||||
@property
|
||||
def server_capabilities(self):
|
||||
return self.server_properties.get('capabilities') or {}
|
||||
@@ -0,0 +1,288 @@
|
||||
"""Exceptions used by amqp."""
|
||||
# Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>
|
||||
|
||||
from struct import pack, unpack
|
||||
|
||||
__all__ = (
|
||||
'AMQPError',
|
||||
'ConnectionError', 'ChannelError',
|
||||
'RecoverableConnectionError', 'IrrecoverableConnectionError',
|
||||
'RecoverableChannelError', 'IrrecoverableChannelError',
|
||||
'ConsumerCancelled', 'ContentTooLarge', 'NoConsumers',
|
||||
'ConnectionForced', 'InvalidPath', 'AccessRefused', 'NotFound',
|
||||
'ResourceLocked', 'PreconditionFailed', 'FrameError', 'FrameSyntaxError',
|
||||
'InvalidCommand', 'ChannelNotOpen', 'UnexpectedFrame', 'ResourceError',
|
||||
'NotAllowed', 'AMQPNotImplementedError', 'InternalError',
|
||||
'MessageNacked',
|
||||
'AMQPDeprecationWarning',
|
||||
)
|
||||
|
||||
|
||||
class AMQPDeprecationWarning(UserWarning):
|
||||
"""Warning for deprecated things."""
|
||||
|
||||
|
||||
class MessageNacked(Exception):
|
||||
"""Message was nacked by broker."""
|
||||
|
||||
|
||||
class AMQPError(Exception):
|
||||
"""Base class for all AMQP exceptions."""
|
||||
|
||||
code = 0
|
||||
|
||||
def __init__(self, reply_text=None, method_sig=None,
|
||||
method_name=None, reply_code=None):
|
||||
self.message = reply_text
|
||||
self.reply_code = reply_code or self.code
|
||||
self.reply_text = reply_text
|
||||
self.method_sig = method_sig
|
||||
self.method_name = method_name or ''
|
||||
if method_sig and not self.method_name:
|
||||
self.method_name = METHOD_NAME_MAP.get(method_sig, '')
|
||||
Exception.__init__(self, reply_code,
|
||||
reply_text, method_sig, self.method_name)
|
||||
|
||||
def __str__(self):
|
||||
if self.method:
|
||||
return '{0.method}: ({0.reply_code}) {0.reply_text}'.format(self)
|
||||
return self.reply_text or '<{}: unknown error>'.format(
|
||||
type(self).__name__
|
||||
)
|
||||
|
||||
@property
|
||||
def method(self):
|
||||
return self.method_name or self.method_sig
|
||||
|
||||
|
||||
class ConnectionError(AMQPError):
|
||||
"""AMQP Connection Error."""
|
||||
|
||||
|
||||
class ChannelError(AMQPError):
|
||||
"""AMQP Channel Error."""
|
||||
|
||||
|
||||
class RecoverableChannelError(ChannelError):
|
||||
"""Exception class for recoverable channel errors."""
|
||||
|
||||
|
||||
class IrrecoverableChannelError(ChannelError):
|
||||
"""Exception class for irrecoverable channel errors."""
|
||||
|
||||
|
||||
class RecoverableConnectionError(ConnectionError):
|
||||
"""Exception class for recoverable connection errors."""
|
||||
|
||||
|
||||
class IrrecoverableConnectionError(ConnectionError):
|
||||
"""Exception class for irrecoverable connection errors."""
|
||||
|
||||
|
||||
class Blocked(RecoverableConnectionError):
|
||||
"""AMQP Connection Blocked Predicate."""
|
||||
|
||||
|
||||
class ConsumerCancelled(RecoverableConnectionError):
|
||||
"""AMQP Consumer Cancelled Predicate."""
|
||||
|
||||
|
||||
class ContentTooLarge(RecoverableChannelError):
|
||||
"""AMQP Content Too Large Error."""
|
||||
|
||||
code = 311
|
||||
|
||||
|
||||
class NoConsumers(RecoverableChannelError):
|
||||
"""AMQP No Consumers Error."""
|
||||
|
||||
code = 313
|
||||
|
||||
|
||||
class ConnectionForced(RecoverableConnectionError):
|
||||
"""AMQP Connection Forced Error."""
|
||||
|
||||
code = 320
|
||||
|
||||
|
||||
class InvalidPath(IrrecoverableConnectionError):
|
||||
"""AMQP Invalid Path Error."""
|
||||
|
||||
code = 402
|
||||
|
||||
|
||||
class AccessRefused(IrrecoverableChannelError):
|
||||
"""AMQP Access Refused Error."""
|
||||
|
||||
code = 403
|
||||
|
||||
|
||||
class NotFound(IrrecoverableChannelError):
|
||||
"""AMQP Not Found Error."""
|
||||
|
||||
code = 404
|
||||
|
||||
|
||||
class ResourceLocked(RecoverableChannelError):
|
||||
"""AMQP Resource Locked Error."""
|
||||
|
||||
code = 405
|
||||
|
||||
|
||||
class PreconditionFailed(IrrecoverableChannelError):
|
||||
"""AMQP Precondition Failed Error."""
|
||||
|
||||
code = 406
|
||||
|
||||
|
||||
class FrameError(IrrecoverableConnectionError):
|
||||
"""AMQP Frame Error."""
|
||||
|
||||
code = 501
|
||||
|
||||
|
||||
class FrameSyntaxError(IrrecoverableConnectionError):
|
||||
"""AMQP Frame Syntax Error."""
|
||||
|
||||
code = 502
|
||||
|
||||
|
||||
class InvalidCommand(IrrecoverableConnectionError):
|
||||
"""AMQP Invalid Command Error."""
|
||||
|
||||
code = 503
|
||||
|
||||
|
||||
class ChannelNotOpen(IrrecoverableConnectionError):
|
||||
"""AMQP Channel Not Open Error."""
|
||||
|
||||
code = 504
|
||||
|
||||
|
||||
class UnexpectedFrame(IrrecoverableConnectionError):
|
||||
"""AMQP Unexpected Frame."""
|
||||
|
||||
code = 505
|
||||
|
||||
|
||||
class ResourceError(RecoverableConnectionError):
|
||||
"""AMQP Resource Error."""
|
||||
|
||||
code = 506
|
||||
|
||||
|
||||
class NotAllowed(IrrecoverableConnectionError):
|
||||
"""AMQP Not Allowed Error."""
|
||||
|
||||
code = 530
|
||||
|
||||
|
||||
class AMQPNotImplementedError(IrrecoverableConnectionError):
|
||||
"""AMQP Not Implemented Error."""
|
||||
|
||||
code = 540
|
||||
|
||||
|
||||
class InternalError(IrrecoverableConnectionError):
|
||||
"""AMQP Internal Error."""
|
||||
|
||||
code = 541
|
||||
|
||||
|
||||
ERROR_MAP = {
|
||||
311: ContentTooLarge,
|
||||
313: NoConsumers,
|
||||
320: ConnectionForced,
|
||||
402: InvalidPath,
|
||||
403: AccessRefused,
|
||||
404: NotFound,
|
||||
405: ResourceLocked,
|
||||
406: PreconditionFailed,
|
||||
501: FrameError,
|
||||
502: FrameSyntaxError,
|
||||
503: InvalidCommand,
|
||||
504: ChannelNotOpen,
|
||||
505: UnexpectedFrame,
|
||||
506: ResourceError,
|
||||
530: NotAllowed,
|
||||
540: AMQPNotImplementedError,
|
||||
541: InternalError,
|
||||
}
|
||||
|
||||
|
||||
def error_for_code(code, text, method, default):
|
||||
try:
|
||||
return ERROR_MAP[code](text, method, reply_code=code)
|
||||
except KeyError:
|
||||
return default(text, method, reply_code=code)
|
||||
|
||||
|
||||
METHOD_NAME_MAP = {
|
||||
(10, 10): 'Connection.start',
|
||||
(10, 11): 'Connection.start_ok',
|
||||
(10, 20): 'Connection.secure',
|
||||
(10, 21): 'Connection.secure_ok',
|
||||
(10, 30): 'Connection.tune',
|
||||
(10, 31): 'Connection.tune_ok',
|
||||
(10, 40): 'Connection.open',
|
||||
(10, 41): 'Connection.open_ok',
|
||||
(10, 50): 'Connection.close',
|
||||
(10, 51): 'Connection.close_ok',
|
||||
(20, 10): 'Channel.open',
|
||||
(20, 11): 'Channel.open_ok',
|
||||
(20, 20): 'Channel.flow',
|
||||
(20, 21): 'Channel.flow_ok',
|
||||
(20, 40): 'Channel.close',
|
||||
(20, 41): 'Channel.close_ok',
|
||||
(30, 10): 'Access.request',
|
||||
(30, 11): 'Access.request_ok',
|
||||
(40, 10): 'Exchange.declare',
|
||||
(40, 11): 'Exchange.declare_ok',
|
||||
(40, 20): 'Exchange.delete',
|
||||
(40, 21): 'Exchange.delete_ok',
|
||||
(40, 30): 'Exchange.bind',
|
||||
(40, 31): 'Exchange.bind_ok',
|
||||
(40, 40): 'Exchange.unbind',
|
||||
(40, 41): 'Exchange.unbind_ok',
|
||||
(50, 10): 'Queue.declare',
|
||||
(50, 11): 'Queue.declare_ok',
|
||||
(50, 20): 'Queue.bind',
|
||||
(50, 21): 'Queue.bind_ok',
|
||||
(50, 30): 'Queue.purge',
|
||||
(50, 31): 'Queue.purge_ok',
|
||||
(50, 40): 'Queue.delete',
|
||||
(50, 41): 'Queue.delete_ok',
|
||||
(50, 50): 'Queue.unbind',
|
||||
(50, 51): 'Queue.unbind_ok',
|
||||
(60, 10): 'Basic.qos',
|
||||
(60, 11): 'Basic.qos_ok',
|
||||
(60, 20): 'Basic.consume',
|
||||
(60, 21): 'Basic.consume_ok',
|
||||
(60, 30): 'Basic.cancel',
|
||||
(60, 31): 'Basic.cancel_ok',
|
||||
(60, 40): 'Basic.publish',
|
||||
(60, 50): 'Basic.return',
|
||||
(60, 60): 'Basic.deliver',
|
||||
(60, 70): 'Basic.get',
|
||||
(60, 71): 'Basic.get_ok',
|
||||
(60, 72): 'Basic.get_empty',
|
||||
(60, 80): 'Basic.ack',
|
||||
(60, 90): 'Basic.reject',
|
||||
(60, 100): 'Basic.recover_async',
|
||||
(60, 110): 'Basic.recover',
|
||||
(60, 111): 'Basic.recover_ok',
|
||||
(60, 120): 'Basic.nack',
|
||||
(90, 10): 'Tx.select',
|
||||
(90, 11): 'Tx.select_ok',
|
||||
(90, 20): 'Tx.commit',
|
||||
(90, 21): 'Tx.commit_ok',
|
||||
(90, 30): 'Tx.rollback',
|
||||
(90, 31): 'Tx.rollback_ok',
|
||||
(85, 10): 'Confirm.select',
|
||||
(85, 11): 'Confirm.select_ok',
|
||||
}
|
||||
|
||||
|
||||
for _method_id, _method_name in list(METHOD_NAME_MAP.items()):
|
||||
METHOD_NAME_MAP[unpack('>I', pack('>HH', *_method_id))[0]] = \
|
||||
_method_name
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Convert between frames and higher-level AMQP methods."""
|
||||
# Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>
|
||||
|
||||
from collections import defaultdict
|
||||
from struct import pack, pack_into, unpack_from
|
||||
|
||||
from . import spec
|
||||
from .basic_message import Message
|
||||
from .exceptions import UnexpectedFrame
|
||||
from .utils import str_to_bytes
|
||||
|
||||
__all__ = ('frame_handler', 'frame_writer')
|
||||
|
||||
#: Set of methods that require both a content frame and a body frame.
|
||||
_CONTENT_METHODS = frozenset([
|
||||
spec.Basic.Return,
|
||||
spec.Basic.Deliver,
|
||||
spec.Basic.GetOk,
|
||||
])
|
||||
|
||||
|
||||
#: Number of bytes reserved for protocol in a content frame.
|
||||
#: We use this to calculate when a frame exceeeds the max frame size,
|
||||
#: and if it does not the message will fit into the preallocated buffer.
|
||||
FRAME_OVERHEAD = 40
|
||||
|
||||
|
||||
def frame_handler(connection, callback,
|
||||
unpack_from=unpack_from, content_methods=_CONTENT_METHODS):
|
||||
"""Create closure that reads frames."""
|
||||
expected_types = defaultdict(lambda: 1)
|
||||
partial_messages = {}
|
||||
|
||||
def on_frame(frame):
|
||||
frame_type, channel, buf = frame
|
||||
connection.bytes_recv += 1
|
||||
if frame_type not in (expected_types[channel], 8):
|
||||
raise UnexpectedFrame(
|
||||
'Received frame {} while expecting type: {}'.format(
|
||||
frame_type, expected_types[channel]),
|
||||
)
|
||||
elif frame_type == 1:
|
||||
method_sig = unpack_from('>HH', buf, 0)
|
||||
|
||||
if method_sig in content_methods:
|
||||
# Save what we've got so far and wait for the content-header
|
||||
partial_messages[channel] = Message(
|
||||
frame_method=method_sig, frame_args=buf,
|
||||
)
|
||||
expected_types[channel] = 2
|
||||
return False
|
||||
|
||||
callback(channel, method_sig, buf, None)
|
||||
|
||||
elif frame_type == 2:
|
||||
msg = partial_messages[channel]
|
||||
msg.inbound_header(buf)
|
||||
|
||||
if not msg.ready:
|
||||
# wait for the content-body
|
||||
expected_types[channel] = 3
|
||||
return False
|
||||
|
||||
# bodyless message, we're done
|
||||
expected_types[channel] = 1
|
||||
partial_messages.pop(channel, None)
|
||||
callback(channel, msg.frame_method, msg.frame_args, msg)
|
||||
|
||||
elif frame_type == 3:
|
||||
msg = partial_messages[channel]
|
||||
msg.inbound_body(buf)
|
||||
if not msg.ready:
|
||||
# wait for the rest of the content-body
|
||||
return False
|
||||
expected_types[channel] = 1
|
||||
partial_messages.pop(channel, None)
|
||||
callback(channel, msg.frame_method, msg.frame_args, msg)
|
||||
elif frame_type == 8:
|
||||
# bytes_recv already updated
|
||||
return False
|
||||
return True
|
||||
|
||||
return on_frame
|
||||
|
||||
|
||||
class Buffer:
|
||||
def __init__(self, buf):
|
||||
self.buf = buf
|
||||
|
||||
@property
|
||||
def buf(self):
|
||||
return self._buf
|
||||
|
||||
@buf.setter
|
||||
def buf(self, buf):
|
||||
self._buf = buf
|
||||
# Using a memoryview allows slicing without copying underlying data.
|
||||
# Slicing this is much faster than slicing the bytearray directly.
|
||||
# More details: https://stackoverflow.com/a/34257357
|
||||
self.view = memoryview(buf)
|
||||
|
||||
|
||||
def frame_writer(connection, transport,
|
||||
pack=pack, pack_into=pack_into, range=range, len=len,
|
||||
bytes=bytes, str_to_bytes=str_to_bytes, text_t=str):
|
||||
"""Create closure that writes frames."""
|
||||
write = transport.write
|
||||
|
||||
buffer_store = Buffer(bytearray(connection.frame_max - 8))
|
||||
|
||||
def write_frame(type_, channel, method_sig, args, content):
|
||||
chunk_size = connection.frame_max - 8
|
||||
offset = 0
|
||||
properties = None
|
||||
args = str_to_bytes(args)
|
||||
if content:
|
||||
body = content.body
|
||||
if isinstance(body, str):
|
||||
encoding = content.properties.setdefault(
|
||||
'content_encoding', 'utf-8')
|
||||
body = body.encode(encoding)
|
||||
properties = content._serialize_properties()
|
||||
bodylen = len(body)
|
||||
properties_len = len(properties) or 0
|
||||
framelen = len(args) + properties_len + bodylen + FRAME_OVERHEAD
|
||||
bigbody = framelen > chunk_size
|
||||
else:
|
||||
body, bodylen, bigbody = None, 0, 0
|
||||
|
||||
if bigbody:
|
||||
# ## SLOW: string copy and write for every frame
|
||||
frame = (b''.join([pack('>HH', *method_sig), args])
|
||||
if type_ == 1 else b'') # encode method frame
|
||||
framelen = len(frame)
|
||||
write(pack('>BHI%dsB' % framelen,
|
||||
type_, channel, framelen, frame, 0xce))
|
||||
if body:
|
||||
frame = b''.join([
|
||||
pack('>HHQ', method_sig[0], 0, len(body)),
|
||||
properties,
|
||||
])
|
||||
framelen = len(frame)
|
||||
write(pack('>BHI%dsB' % framelen,
|
||||
2, channel, framelen, frame, 0xce))
|
||||
|
||||
for i in range(0, bodylen, chunk_size):
|
||||
frame = body[i:i + chunk_size]
|
||||
framelen = len(frame)
|
||||
write(pack('>BHI%dsB' % framelen,
|
||||
3, channel, framelen,
|
||||
frame, 0xce))
|
||||
|
||||
else:
|
||||
# frame_max can be updated via connection._on_tune. If
|
||||
# it became larger, then we need to resize the buffer
|
||||
# to prevent overflow.
|
||||
if chunk_size > len(buffer_store.buf):
|
||||
buffer_store.buf = bytearray(chunk_size)
|
||||
buf = buffer_store.buf
|
||||
|
||||
# ## FAST: pack into buffer and single write
|
||||
frame = (b''.join([pack('>HH', *method_sig), args])
|
||||
if type_ == 1 else b'')
|
||||
framelen = len(frame)
|
||||
pack_into('>BHI%dsB' % framelen, buf, offset,
|
||||
type_, channel, framelen, frame, 0xce)
|
||||
offset += 8 + framelen
|
||||
if body is not None:
|
||||
frame = b''.join([
|
||||
pack('>HHQ', method_sig[0], 0, len(body)),
|
||||
properties,
|
||||
])
|
||||
framelen = len(frame)
|
||||
|
||||
pack_into('>BHI%dsB' % framelen, buf, offset,
|
||||
2, channel, framelen, frame, 0xce)
|
||||
offset += 8 + framelen
|
||||
|
||||
bodylen = len(body)
|
||||
if bodylen > 0:
|
||||
framelen = bodylen
|
||||
pack_into('>BHI%dsB' % framelen, buf, offset,
|
||||
3, channel, framelen, body, 0xce)
|
||||
offset += 8 + framelen
|
||||
|
||||
write(buffer_store.view[:offset])
|
||||
|
||||
connection.bytes_sent += 1
|
||||
return write_frame
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Platform compatibility."""
|
||||
|
||||
import platform
|
||||
import re
|
||||
import sys
|
||||
# Jython does not have this attribute
|
||||
import typing
|
||||
|
||||
try:
|
||||
from socket import SOL_TCP
|
||||
except ImportError: # pragma: no cover
|
||||
from socket import IPPROTO_TCP as SOL_TCP # noqa
|
||||
|
||||
|
||||
RE_NUM = re.compile(r'(\d+).+')
|
||||
|
||||
|
||||
def _linux_version_to_tuple(s: str) -> typing.Tuple[int, int, int]:
|
||||
return tuple(map(_versionatom, s.split('.')[:3]))
|
||||
|
||||
|
||||
def _versionatom(s: str) -> int:
|
||||
if s.isdigit():
|
||||
return int(s)
|
||||
match = RE_NUM.match(s)
|
||||
return int(match.groups()[0]) if match else 0
|
||||
|
||||
|
||||
# available socket options for TCP level
|
||||
KNOWN_TCP_OPTS = {
|
||||
'TCP_CORK', 'TCP_DEFER_ACCEPT', 'TCP_KEEPCNT',
|
||||
'TCP_KEEPIDLE', 'TCP_KEEPINTVL', 'TCP_LINGER2',
|
||||
'TCP_MAXSEG', 'TCP_NODELAY', 'TCP_QUICKACK',
|
||||
'TCP_SYNCNT', 'TCP_USER_TIMEOUT', 'TCP_WINDOW_CLAMP',
|
||||
}
|
||||
|
||||
LINUX_VERSION = None
|
||||
if sys.platform.startswith('linux'):
|
||||
LINUX_VERSION = _linux_version_to_tuple(platform.release())
|
||||
if LINUX_VERSION < (2, 6, 37):
|
||||
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
|
||||
|
||||
# Windows Subsystem for Linux is an edge-case: the Python socket library
|
||||
# returns most TCP_* enums, but they aren't actually supported
|
||||
if platform.release().endswith("Microsoft"):
|
||||
KNOWN_TCP_OPTS = {'TCP_NODELAY', 'TCP_KEEPIDLE', 'TCP_KEEPINTVL',
|
||||
'TCP_KEEPCNT'}
|
||||
|
||||
elif sys.platform.startswith('darwin'):
|
||||
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
|
||||
|
||||
elif 'bsd' in sys.platform:
|
||||
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
|
||||
|
||||
# According to MSDN Windows platforms support getsockopt(TCP_MAXSSEG) but not
|
||||
# setsockopt(TCP_MAXSEG) on IPPROTO_TCP sockets.
|
||||
elif sys.platform.startswith('win'):
|
||||
KNOWN_TCP_OPTS = {'TCP_NODELAY'}
|
||||
|
||||
elif sys.platform.startswith('cygwin'):
|
||||
KNOWN_TCP_OPTS = {'TCP_NODELAY'}
|
||||
|
||||
# illumos does not allow to set the TCP_MAXSEG socket option,
|
||||
# even if the Oracle documentation says otherwise.
|
||||
# TCP_USER_TIMEOUT does not exist on Solaris 11.4
|
||||
elif sys.platform.startswith('sunos'):
|
||||
KNOWN_TCP_OPTS.remove('TCP_MAXSEG')
|
||||
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
|
||||
|
||||
# aix does not allow to set the TCP_MAXSEG
|
||||
# or the TCP_USER_TIMEOUT socket options.
|
||||
elif sys.platform.startswith('aix'):
|
||||
KNOWN_TCP_OPTS.remove('TCP_MAXSEG')
|
||||
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
|
||||
__all__ = (
|
||||
'LINUX_VERSION',
|
||||
'SOL_TCP',
|
||||
'KNOWN_TCP_OPTS',
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Protocol data."""
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
queue_declare_ok_t = namedtuple(
|
||||
'queue_declare_ok_t', ('queue', 'message_count', 'consumer_count'),
|
||||
)
|
||||
|
||||
basic_return_t = namedtuple(
|
||||
'basic_return_t',
|
||||
('reply_code', 'reply_text', 'exchange', 'routing_key', 'message'),
|
||||
)
|
||||
@@ -0,0 +1,191 @@
|
||||
"""SASL mechanisms for AMQP authentication."""
|
||||
|
||||
import socket
|
||||
import warnings
|
||||
from io import BytesIO
|
||||
|
||||
from amqp.serialization import _write_table
|
||||
|
||||
|
||||
class SASL:
|
||||
"""The base class for all amqp SASL authentication mechanisms.
|
||||
|
||||
You should sub-class this if you're implementing your own authentication.
|
||||
"""
|
||||
|
||||
@property
|
||||
def mechanism(self):
|
||||
"""Return a bytes containing the SASL mechanism name."""
|
||||
raise NotImplementedError
|
||||
|
||||
def start(self, connection):
|
||||
"""Return the first response to a SASL challenge as a bytes object."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class PLAIN(SASL):
|
||||
"""PLAIN SASL authentication mechanism.
|
||||
|
||||
See https://tools.ietf.org/html/rfc4616 for details
|
||||
"""
|
||||
|
||||
mechanism = b'PLAIN'
|
||||
|
||||
def __init__(self, username, password):
|
||||
self.username, self.password = username, password
|
||||
|
||||
__slots__ = (
|
||||
"username",
|
||||
"password",
|
||||
)
|
||||
|
||||
def start(self, connection):
|
||||
if self.username is None or self.password is None:
|
||||
return NotImplemented
|
||||
login_response = BytesIO()
|
||||
login_response.write(b'\0')
|
||||
login_response.write(self.username.encode('utf-8'))
|
||||
login_response.write(b'\0')
|
||||
login_response.write(self.password.encode('utf-8'))
|
||||
return login_response.getvalue()
|
||||
|
||||
|
||||
class AMQPLAIN(SASL):
|
||||
"""AMQPLAIN SASL authentication mechanism.
|
||||
|
||||
This is a non-standard mechanism used by AMQP servers.
|
||||
"""
|
||||
|
||||
mechanism = b'AMQPLAIN'
|
||||
|
||||
def __init__(self, username, password):
|
||||
self.username, self.password = username, password
|
||||
|
||||
__slots__ = (
|
||||
"username",
|
||||
"password",
|
||||
)
|
||||
|
||||
def start(self, connection):
|
||||
if self.username is None or self.password is None:
|
||||
return NotImplemented
|
||||
login_response = BytesIO()
|
||||
_write_table({b'LOGIN': self.username, b'PASSWORD': self.password},
|
||||
login_response.write, [])
|
||||
# Skip the length at the beginning
|
||||
return login_response.getvalue()[4:]
|
||||
|
||||
|
||||
def _get_gssapi_mechanism():
|
||||
try:
|
||||
import gssapi
|
||||
import gssapi.raw.misc # Fail if the old python-gssapi is installed
|
||||
except ImportError:
|
||||
class FakeGSSAPI(SASL):
|
||||
"""A no-op SASL mechanism for when gssapi isn't available."""
|
||||
|
||||
mechanism = None
|
||||
|
||||
def __init__(self, client_name=None, service=b'amqp',
|
||||
rdns=False, fail_soft=False):
|
||||
if not fail_soft:
|
||||
raise NotImplementedError(
|
||||
"You need to install the `gssapi` module for GSSAPI "
|
||||
"SASL support")
|
||||
|
||||
def start(self): # pragma: no cover
|
||||
return NotImplemented
|
||||
return FakeGSSAPI
|
||||
else:
|
||||
class GSSAPI(SASL):
|
||||
"""GSSAPI SASL authentication mechanism.
|
||||
|
||||
See https://tools.ietf.org/html/rfc4752 for details
|
||||
"""
|
||||
|
||||
mechanism = b'GSSAPI'
|
||||
|
||||
def __init__(self, client_name=None, service=b'amqp',
|
||||
rdns=False, fail_soft=False):
|
||||
if client_name and not isinstance(client_name, bytes):
|
||||
client_name = client_name.encode('ascii')
|
||||
self.client_name = client_name
|
||||
self.fail_soft = fail_soft
|
||||
self.service = service
|
||||
self.rdns = rdns
|
||||
|
||||
__slots__ = (
|
||||
"client_name",
|
||||
"fail_soft",
|
||||
"service",
|
||||
"rdns"
|
||||
)
|
||||
|
||||
def get_hostname(self, connection):
|
||||
sock = connection.transport.sock
|
||||
if self.rdns and sock.family in (socket.AF_INET,
|
||||
socket.AF_INET6):
|
||||
peer = sock.getpeername()
|
||||
hostname, _, _ = socket.gethostbyaddr(peer[0])
|
||||
else:
|
||||
hostname = connection.transport.host
|
||||
if not isinstance(hostname, bytes):
|
||||
hostname = hostname.encode('ascii')
|
||||
return hostname
|
||||
|
||||
def start(self, connection):
|
||||
try:
|
||||
if self.client_name:
|
||||
creds = gssapi.Credentials(
|
||||
name=gssapi.Name(self.client_name))
|
||||
else:
|
||||
creds = None
|
||||
hostname = self.get_hostname(connection)
|
||||
name = gssapi.Name(b'@'.join([self.service, hostname]),
|
||||
gssapi.NameType.hostbased_service)
|
||||
context = gssapi.SecurityContext(name=name, creds=creds)
|
||||
return context.step(None)
|
||||
except gssapi.raw.misc.GSSError:
|
||||
if self.fail_soft:
|
||||
return NotImplemented
|
||||
else:
|
||||
raise
|
||||
return GSSAPI
|
||||
|
||||
|
||||
GSSAPI = _get_gssapi_mechanism()
|
||||
|
||||
|
||||
class EXTERNAL(SASL):
|
||||
"""EXTERNAL SASL mechanism.
|
||||
|
||||
Enables external authentication, i.e. not handled through this protocol.
|
||||
Only passes 'EXTERNAL' as authentication mechanism, but no further
|
||||
authentication data.
|
||||
"""
|
||||
|
||||
mechanism = b'EXTERNAL'
|
||||
|
||||
def start(self, connection):
|
||||
return b''
|
||||
|
||||
|
||||
class RAW(SASL):
|
||||
"""A generic custom SASL mechanism.
|
||||
|
||||
This mechanism takes a mechanism name and response to send to the server,
|
||||
so can be used for simple custom authentication schemes.
|
||||
"""
|
||||
|
||||
mechanism = None
|
||||
|
||||
def __init__(self, mechanism, response):
|
||||
assert isinstance(mechanism, bytes)
|
||||
assert isinstance(response, bytes)
|
||||
self.mechanism, self.response = mechanism, response
|
||||
warnings.warn("Passing login_method and login_response to Connection "
|
||||
"is deprecated. Please implement a SASL subclass "
|
||||
"instead.", DeprecationWarning)
|
||||
|
||||
def start(self, connection):
|
||||
return self.response
|
||||
@@ -0,0 +1,582 @@
|
||||
"""Convert between bytestreams and higher-level AMQP types.
|
||||
|
||||
2007-11-05 Barry Pederson <bp@barryp.org>
|
||||
|
||||
"""
|
||||
# Copyright (C) 2007 Barry Pederson <bp@barryp.org>
|
||||
|
||||
import calendar
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
from struct import pack, unpack_from
|
||||
|
||||
from .exceptions import FrameSyntaxError
|
||||
from .spec import Basic
|
||||
from .utils import bytes_to_str as pstr_t
|
||||
from .utils import str_to_bytes
|
||||
|
||||
ILLEGAL_TABLE_TYPE = """\
|
||||
Table type {0!r} not handled by amqp.
|
||||
"""
|
||||
|
||||
ILLEGAL_TABLE_TYPE_WITH_KEY = """\
|
||||
Table type {0!r} for key {1!r} not handled by amqp. [value: {2!r}]
|
||||
"""
|
||||
|
||||
ILLEGAL_TABLE_TYPE_WITH_VALUE = """\
|
||||
Table type {0!r} not handled by amqp. [value: {1!r}]
|
||||
"""
|
||||
|
||||
|
||||
def _read_item(buf, offset):
|
||||
ftype = chr(buf[offset])
|
||||
offset += 1
|
||||
|
||||
# 'S': long string
|
||||
if ftype == 'S':
|
||||
slen, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
try:
|
||||
val = pstr_t(buf[offset:offset + slen])
|
||||
except UnicodeDecodeError:
|
||||
val = buf[offset:offset + slen]
|
||||
|
||||
offset += slen
|
||||
# 's': short string
|
||||
elif ftype == 's':
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
val = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
# 'x': Bytes Array
|
||||
elif ftype == 'x':
|
||||
blen, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
val = buf[offset:offset + blen]
|
||||
offset += blen
|
||||
# 'b': short-short int
|
||||
elif ftype == 'b':
|
||||
val, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
# 'B': short-short unsigned int
|
||||
elif ftype == 'B':
|
||||
val, = unpack_from('>b', buf, offset)
|
||||
offset += 1
|
||||
# 'U': short int
|
||||
elif ftype == 'U':
|
||||
val, = unpack_from('>h', buf, offset)
|
||||
offset += 2
|
||||
# 'u': short unsigned int
|
||||
elif ftype == 'u':
|
||||
val, = unpack_from('>H', buf, offset)
|
||||
offset += 2
|
||||
# 'I': long int
|
||||
elif ftype == 'I':
|
||||
val, = unpack_from('>i', buf, offset)
|
||||
offset += 4
|
||||
# 'i': long unsigned int
|
||||
elif ftype == 'i':
|
||||
val, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
# 'L': long long int
|
||||
elif ftype == 'L':
|
||||
val, = unpack_from('>q', buf, offset)
|
||||
offset += 8
|
||||
# 'l': long long unsigned int
|
||||
elif ftype == 'l':
|
||||
val, = unpack_from('>Q', buf, offset)
|
||||
offset += 8
|
||||
# 'f': float
|
||||
elif ftype == 'f':
|
||||
val, = unpack_from('>f', buf, offset)
|
||||
offset += 4
|
||||
# 'd': double
|
||||
elif ftype == 'd':
|
||||
val, = unpack_from('>d', buf, offset)
|
||||
offset += 8
|
||||
# 'D': decimal
|
||||
elif ftype == 'D':
|
||||
d, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
n, = unpack_from('>i', buf, offset)
|
||||
offset += 4
|
||||
val = Decimal(n) / Decimal(10 ** d)
|
||||
# 'F': table
|
||||
elif ftype == 'F':
|
||||
tlen, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
limit = offset + tlen
|
||||
val = {}
|
||||
while offset < limit:
|
||||
keylen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
key = pstr_t(buf[offset:offset + keylen])
|
||||
offset += keylen
|
||||
val[key], offset = _read_item(buf, offset)
|
||||
# 'A': array
|
||||
elif ftype == 'A':
|
||||
alen, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
limit = offset + alen
|
||||
val = []
|
||||
while offset < limit:
|
||||
v, offset = _read_item(buf, offset)
|
||||
val.append(v)
|
||||
# 't' (bool)
|
||||
elif ftype == 't':
|
||||
val, = unpack_from('>B', buf, offset)
|
||||
val = bool(val)
|
||||
offset += 1
|
||||
# 'T': timestamp
|
||||
elif ftype == 'T':
|
||||
val, = unpack_from('>Q', buf, offset)
|
||||
offset += 8
|
||||
val = datetime.utcfromtimestamp(val)
|
||||
# 'V': void
|
||||
elif ftype == 'V':
|
||||
val = None
|
||||
else:
|
||||
raise FrameSyntaxError(
|
||||
'Unknown value in table: {!r} ({!r})'.format(
|
||||
ftype, type(ftype)))
|
||||
return val, offset
|
||||
|
||||
|
||||
def loads(format, buf, offset):
|
||||
"""Deserialize amqp format.
|
||||
|
||||
bit = b
|
||||
octet = o
|
||||
short = B
|
||||
long = l
|
||||
long long = L
|
||||
float = f
|
||||
shortstr = s
|
||||
longstr = S
|
||||
table = F
|
||||
array = A
|
||||
timestamp = T
|
||||
"""
|
||||
bitcount = bits = 0
|
||||
|
||||
values = []
|
||||
append = values.append
|
||||
format = pstr_t(format)
|
||||
|
||||
for p in format:
|
||||
if p == 'b':
|
||||
if not bitcount:
|
||||
bits = ord(buf[offset:offset + 1])
|
||||
offset += 1
|
||||
bitcount = 8
|
||||
val = (bits & 1) == 1
|
||||
bits >>= 1
|
||||
bitcount -= 1
|
||||
elif p == 'o':
|
||||
bitcount = bits = 0
|
||||
val, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
elif p == 'B':
|
||||
bitcount = bits = 0
|
||||
val, = unpack_from('>H', buf, offset)
|
||||
offset += 2
|
||||
elif p == 'l':
|
||||
bitcount = bits = 0
|
||||
val, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
elif p == 'L':
|
||||
bitcount = bits = 0
|
||||
val, = unpack_from('>Q', buf, offset)
|
||||
offset += 8
|
||||
elif p == 'f':
|
||||
bitcount = bits = 0
|
||||
val, = unpack_from('>f', buf, offset)
|
||||
offset += 4
|
||||
elif p == 's':
|
||||
bitcount = bits = 0
|
||||
slen, = unpack_from('B', buf, offset)
|
||||
offset += 1
|
||||
val = buf[offset:offset + slen].decode('utf-8', 'surrogatepass')
|
||||
offset += slen
|
||||
elif p == 'S':
|
||||
bitcount = bits = 0
|
||||
slen, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
val = buf[offset:offset + slen].decode('utf-8', 'surrogatepass')
|
||||
offset += slen
|
||||
elif p == 'x':
|
||||
blen, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
val = buf[offset:offset + blen]
|
||||
offset += blen
|
||||
elif p == 'F':
|
||||
bitcount = bits = 0
|
||||
tlen, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
limit = offset + tlen
|
||||
val = {}
|
||||
while offset < limit:
|
||||
keylen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
key = pstr_t(buf[offset:offset + keylen])
|
||||
offset += keylen
|
||||
val[key], offset = _read_item(buf, offset)
|
||||
elif p == 'A':
|
||||
bitcount = bits = 0
|
||||
alen, = unpack_from('>I', buf, offset)
|
||||
offset += 4
|
||||
limit = offset + alen
|
||||
val = []
|
||||
while offset < limit:
|
||||
aval, offset = _read_item(buf, offset)
|
||||
val.append(aval)
|
||||
elif p == 'T':
|
||||
bitcount = bits = 0
|
||||
val, = unpack_from('>Q', buf, offset)
|
||||
offset += 8
|
||||
val = datetime.utcfromtimestamp(val)
|
||||
else:
|
||||
raise FrameSyntaxError(ILLEGAL_TABLE_TYPE.format(p))
|
||||
append(val)
|
||||
return values, offset
|
||||
|
||||
|
||||
def _flushbits(bits, write):
|
||||
if bits:
|
||||
write(pack('B' * len(bits), *bits))
|
||||
bits[:] = []
|
||||
return 0
|
||||
|
||||
|
||||
def dumps(format, values):
|
||||
"""Serialize AMQP arguments.
|
||||
|
||||
Notes:
|
||||
bit = b
|
||||
octet = o
|
||||
short = B
|
||||
long = l
|
||||
long long = L
|
||||
shortstr = s
|
||||
longstr = S
|
||||
byte array = x
|
||||
table = F
|
||||
array = A
|
||||
"""
|
||||
bitcount = 0
|
||||
bits = []
|
||||
out = BytesIO()
|
||||
write = out.write
|
||||
|
||||
format = pstr_t(format)
|
||||
|
||||
for i, val in enumerate(values):
|
||||
p = format[i]
|
||||
if p == 'b':
|
||||
val = 1 if val else 0
|
||||
shift = bitcount % 8
|
||||
if shift == 0:
|
||||
bits.append(0)
|
||||
bits[-1] |= (val << shift)
|
||||
bitcount += 1
|
||||
elif p == 'o':
|
||||
bitcount = _flushbits(bits, write)
|
||||
write(pack('B', val))
|
||||
elif p == 'B':
|
||||
bitcount = _flushbits(bits, write)
|
||||
write(pack('>H', int(val)))
|
||||
elif p == 'l':
|
||||
bitcount = _flushbits(bits, write)
|
||||
write(pack('>I', val))
|
||||
elif p == 'L':
|
||||
bitcount = _flushbits(bits, write)
|
||||
write(pack('>Q', val))
|
||||
elif p == 'f':
|
||||
bitcount = _flushbits(bits, write)
|
||||
write(pack('>f', val))
|
||||
elif p == 's':
|
||||
val = val or ''
|
||||
bitcount = _flushbits(bits, write)
|
||||
if isinstance(val, str):
|
||||
val = val.encode('utf-8', 'surrogatepass')
|
||||
write(pack('B', len(val)))
|
||||
write(val)
|
||||
elif p == 'S' or p == 'x':
|
||||
val = val or ''
|
||||
bitcount = _flushbits(bits, write)
|
||||
if isinstance(val, str):
|
||||
val = val.encode('utf-8', 'surrogatepass')
|
||||
write(pack('>I', len(val)))
|
||||
write(val)
|
||||
elif p == 'F':
|
||||
bitcount = _flushbits(bits, write)
|
||||
_write_table(val or {}, write, bits)
|
||||
elif p == 'A':
|
||||
bitcount = _flushbits(bits, write)
|
||||
_write_array(val or [], write, bits)
|
||||
elif p == 'T':
|
||||
write(pack('>Q', int(calendar.timegm(val.utctimetuple()))))
|
||||
_flushbits(bits, write)
|
||||
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _write_table(d, write, bits):
|
||||
out = BytesIO()
|
||||
twrite = out.write
|
||||
for k, v in d.items():
|
||||
if isinstance(k, str):
|
||||
k = k.encode('utf-8', 'surrogatepass')
|
||||
twrite(pack('B', len(k)))
|
||||
twrite(k)
|
||||
try:
|
||||
_write_item(v, twrite, bits)
|
||||
except ValueError:
|
||||
raise FrameSyntaxError(
|
||||
ILLEGAL_TABLE_TYPE_WITH_KEY.format(type(v), k, v))
|
||||
table_data = out.getvalue()
|
||||
write(pack('>I', len(table_data)))
|
||||
write(table_data)
|
||||
|
||||
|
||||
def _write_array(list_, write, bits):
|
||||
out = BytesIO()
|
||||
awrite = out.write
|
||||
for v in list_:
|
||||
try:
|
||||
_write_item(v, awrite, bits)
|
||||
except ValueError:
|
||||
raise FrameSyntaxError(
|
||||
ILLEGAL_TABLE_TYPE_WITH_VALUE.format(type(v), v))
|
||||
array_data = out.getvalue()
|
||||
write(pack('>I', len(array_data)))
|
||||
write(array_data)
|
||||
|
||||
|
||||
def _write_item(v, write, bits):
|
||||
if isinstance(v, (str, bytes)):
|
||||
if isinstance(v, str):
|
||||
v = v.encode('utf-8', 'surrogatepass')
|
||||
write(pack('>cI', b'S', len(v)))
|
||||
write(v)
|
||||
elif isinstance(v, bool):
|
||||
write(pack('>cB', b't', int(v)))
|
||||
elif isinstance(v, float):
|
||||
write(pack('>cd', b'd', v))
|
||||
elif isinstance(v, int):
|
||||
if v > 2147483647 or v < -2147483647:
|
||||
write(pack('>cq', b'L', v))
|
||||
else:
|
||||
write(pack('>ci', b'I', v))
|
||||
elif isinstance(v, Decimal):
|
||||
sign, digits, exponent = v.as_tuple()
|
||||
v = 0
|
||||
for d in digits:
|
||||
v = (v * 10) + d
|
||||
if sign:
|
||||
v = -v
|
||||
write(pack('>cBi', b'D', -exponent, v))
|
||||
elif isinstance(v, datetime):
|
||||
write(
|
||||
pack('>cQ', b'T', int(calendar.timegm(v.utctimetuple()))))
|
||||
elif isinstance(v, dict):
|
||||
write(b'F')
|
||||
_write_table(v, write, bits)
|
||||
elif isinstance(v, (list, tuple)):
|
||||
write(b'A')
|
||||
_write_array(v, write, bits)
|
||||
elif v is None:
|
||||
write(b'V')
|
||||
else:
|
||||
raise ValueError()
|
||||
|
||||
|
||||
def decode_properties_basic(buf, offset):
|
||||
"""Decode basic properties."""
|
||||
properties = {}
|
||||
|
||||
flags, = unpack_from('>H', buf, offset)
|
||||
offset += 2
|
||||
|
||||
if flags & 0x8000:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['content_type'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x4000:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['content_encoding'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x2000:
|
||||
_f, offset = loads('F', buf, offset)
|
||||
properties['application_headers'], = _f
|
||||
if flags & 0x1000:
|
||||
properties['delivery_mode'], = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
if flags & 0x0800:
|
||||
properties['priority'], = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
if flags & 0x0400:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['correlation_id'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x0200:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['reply_to'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x0100:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['expiration'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x0080:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['message_id'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x0040:
|
||||
properties['timestamp'], = unpack_from('>Q', buf, offset)
|
||||
offset += 8
|
||||
if flags & 0x0020:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['type'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x0010:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['user_id'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x0008:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['app_id'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
if flags & 0x0004:
|
||||
slen, = unpack_from('>B', buf, offset)
|
||||
offset += 1
|
||||
properties['cluster_id'] = pstr_t(buf[offset:offset + slen])
|
||||
offset += slen
|
||||
return properties, offset
|
||||
|
||||
|
||||
PROPERTY_CLASSES = {
|
||||
Basic.CLASS_ID: decode_properties_basic,
|
||||
}
|
||||
|
||||
|
||||
class GenericContent:
|
||||
"""Abstract base class for AMQP content.
|
||||
|
||||
Subclasses should override the PROPERTIES attribute.
|
||||
"""
|
||||
|
||||
CLASS_ID = None
|
||||
PROPERTIES = [('dummy', 's')]
|
||||
|
||||
def __init__(self, frame_method=None, frame_args=None, **props):
|
||||
self.frame_method = frame_method
|
||||
self.frame_args = frame_args
|
||||
|
||||
self.properties = props
|
||||
self._pending_chunks = []
|
||||
self.body_received = 0
|
||||
self.body_size = 0
|
||||
self.ready = False
|
||||
|
||||
__slots__ = (
|
||||
"frame_method",
|
||||
"frame_args",
|
||||
"properties",
|
||||
"_pending_chunks",
|
||||
"body_received",
|
||||
"body_size",
|
||||
"ready",
|
||||
# adding '__dict__' to get dynamic assignment
|
||||
"__dict__",
|
||||
"__weakref__",
|
||||
)
|
||||
|
||||
def __getattr__(self, name):
|
||||
# Look for additional properties in the 'properties'
|
||||
# dictionary, and if present - the 'delivery_info' dictionary.
|
||||
if name == '__setstate__':
|
||||
# Allows pickling/unpickling to work
|
||||
raise AttributeError('__setstate__')
|
||||
|
||||
if name in self.properties:
|
||||
return self.properties[name]
|
||||
raise AttributeError(name)
|
||||
|
||||
def _load_properties(self, class_id, buf, offset):
|
||||
"""Load AMQP properties.
|
||||
|
||||
Given the raw bytes containing the property-flags and property-list
|
||||
from a content-frame-header, parse and insert into a dictionary
|
||||
stored in this object as an attribute named 'properties'.
|
||||
"""
|
||||
# Read 16-bit shorts until we get one with a low bit set to zero
|
||||
props, offset = PROPERTY_CLASSES[class_id](buf, offset)
|
||||
self.properties = props
|
||||
return offset
|
||||
|
||||
def _serialize_properties(self):
|
||||
"""Serialize AMQP properties.
|
||||
|
||||
Serialize the 'properties' attribute (a dictionary) into
|
||||
the raw bytes making up a set of property flags and a
|
||||
property list, suitable for putting into a content frame header.
|
||||
"""
|
||||
shift = 15
|
||||
flag_bits = 0
|
||||
flags = []
|
||||
sformat, svalues = [], []
|
||||
props = self.properties
|
||||
for key, proptype in self.PROPERTIES:
|
||||
val = props.get(key, None)
|
||||
if val is not None:
|
||||
if shift == 0:
|
||||
flags.append(flag_bits)
|
||||
flag_bits = 0
|
||||
shift = 15
|
||||
|
||||
flag_bits |= (1 << shift)
|
||||
if proptype != 'bit':
|
||||
sformat.append(str_to_bytes(proptype))
|
||||
svalues.append(val)
|
||||
|
||||
shift -= 1
|
||||
flags.append(flag_bits)
|
||||
result = BytesIO()
|
||||
write = result.write
|
||||
for flag_bits in flags:
|
||||
write(pack('>H', flag_bits))
|
||||
write(dumps(b''.join(sformat), svalues))
|
||||
|
||||
return result.getvalue()
|
||||
|
||||
def inbound_header(self, buf, offset=0):
|
||||
class_id, self.body_size = unpack_from('>HxxQ', buf, offset)
|
||||
offset += 12
|
||||
self._load_properties(class_id, buf, offset)
|
||||
if not self.body_size:
|
||||
self.ready = True
|
||||
return offset
|
||||
|
||||
def inbound_body(self, buf):
|
||||
chunks = self._pending_chunks
|
||||
self.body_received += len(buf)
|
||||
if self.body_received >= self.body_size:
|
||||
if chunks:
|
||||
chunks.append(buf)
|
||||
self.body = bytes().join(chunks)
|
||||
chunks[:] = []
|
||||
else:
|
||||
self.body = buf
|
||||
self.ready = True
|
||||
else:
|
||||
chunks.append(buf)
|
||||
@@ -0,0 +1,121 @@
|
||||
"""AMQP Spec."""
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
method_t = namedtuple('method_t', ('method_sig', 'args', 'content'))
|
||||
|
||||
|
||||
def method(method_sig, args=None, content=False):
|
||||
"""Create amqp method specification tuple."""
|
||||
return method_t(method_sig, args, content)
|
||||
|
||||
|
||||
class Connection:
|
||||
"""AMQ Connection class."""
|
||||
|
||||
CLASS_ID = 10
|
||||
|
||||
Start = (10, 10)
|
||||
StartOk = (10, 11)
|
||||
Secure = (10, 20)
|
||||
SecureOk = (10, 21)
|
||||
Tune = (10, 30)
|
||||
TuneOk = (10, 31)
|
||||
Open = (10, 40)
|
||||
OpenOk = (10, 41)
|
||||
Close = (10, 50)
|
||||
CloseOk = (10, 51)
|
||||
Blocked = (10, 60)
|
||||
Unblocked = (10, 61)
|
||||
|
||||
|
||||
class Channel:
|
||||
"""AMQ Channel class."""
|
||||
|
||||
CLASS_ID = 20
|
||||
|
||||
Open = (20, 10)
|
||||
OpenOk = (20, 11)
|
||||
Flow = (20, 20)
|
||||
FlowOk = (20, 21)
|
||||
Close = (20, 40)
|
||||
CloseOk = (20, 41)
|
||||
|
||||
|
||||
class Exchange:
|
||||
"""AMQ Exchange class."""
|
||||
|
||||
CLASS_ID = 40
|
||||
|
||||
Declare = (40, 10)
|
||||
DeclareOk = (40, 11)
|
||||
Delete = (40, 20)
|
||||
DeleteOk = (40, 21)
|
||||
Bind = (40, 30)
|
||||
BindOk = (40, 31)
|
||||
Unbind = (40, 40)
|
||||
UnbindOk = (40, 51)
|
||||
|
||||
|
||||
class Queue:
|
||||
"""AMQ Queue class."""
|
||||
|
||||
CLASS_ID = 50
|
||||
|
||||
Declare = (50, 10)
|
||||
DeclareOk = (50, 11)
|
||||
Bind = (50, 20)
|
||||
BindOk = (50, 21)
|
||||
Purge = (50, 30)
|
||||
PurgeOk = (50, 31)
|
||||
Delete = (50, 40)
|
||||
DeleteOk = (50, 41)
|
||||
Unbind = (50, 50)
|
||||
UnbindOk = (50, 51)
|
||||
|
||||
|
||||
class Basic:
|
||||
"""AMQ Basic class."""
|
||||
|
||||
CLASS_ID = 60
|
||||
|
||||
Qos = (60, 10)
|
||||
QosOk = (60, 11)
|
||||
Consume = (60, 20)
|
||||
ConsumeOk = (60, 21)
|
||||
Cancel = (60, 30)
|
||||
CancelOk = (60, 31)
|
||||
Publish = (60, 40)
|
||||
Return = (60, 50)
|
||||
Deliver = (60, 60)
|
||||
Get = (60, 70)
|
||||
GetOk = (60, 71)
|
||||
GetEmpty = (60, 72)
|
||||
Ack = (60, 80)
|
||||
Nack = (60, 120)
|
||||
Reject = (60, 90)
|
||||
RecoverAsync = (60, 100)
|
||||
Recover = (60, 110)
|
||||
RecoverOk = (60, 111)
|
||||
|
||||
|
||||
class Confirm:
|
||||
"""AMQ Confirm class."""
|
||||
|
||||
CLASS_ID = 85
|
||||
|
||||
Select = (85, 10)
|
||||
SelectOk = (85, 11)
|
||||
|
||||
|
||||
class Tx:
|
||||
"""AMQ Tx class."""
|
||||
|
||||
CLASS_ID = 90
|
||||
|
||||
Select = (90, 10)
|
||||
SelectOk = (90, 11)
|
||||
Commit = (90, 20)
|
||||
CommitOk = (90, 21)
|
||||
Rollback = (90, 30)
|
||||
RollbackOk = (90, 31)
|
||||
@@ -0,0 +1,674 @@
|
||||
"""Transport implementation."""
|
||||
# Copyright (C) 2009 Barry Pederson <bp@barryp.org>
|
||||
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
from contextlib import contextmanager
|
||||
from ssl import SSLError
|
||||
from struct import pack, unpack
|
||||
|
||||
from .exceptions import UnexpectedFrame
|
||||
from .platform import KNOWN_TCP_OPTS, SOL_TCP
|
||||
from .utils import set_cloexec
|
||||
|
||||
_UNAVAIL = {errno.EAGAIN, errno.EINTR, errno.ENOENT, errno.EWOULDBLOCK}
|
||||
|
||||
AMQP_PORT = 5672
|
||||
|
||||
EMPTY_BUFFER = bytes()
|
||||
|
||||
SIGNED_INT_MAX = 0x7FFFFFFF
|
||||
|
||||
# Yes, Advanced Message Queuing Protocol Protocol is redundant
|
||||
AMQP_PROTOCOL_HEADER = b'AMQP\x00\x00\x09\x01'
|
||||
|
||||
# Match things like: [fe80::1]:5432, from RFC 2732
|
||||
IPV6_LITERAL = re.compile(r'\[([\.0-9a-f:]+)\](?::(\d+))?')
|
||||
|
||||
DEFAULT_SOCKET_SETTINGS = {
|
||||
'TCP_NODELAY': 1,
|
||||
'TCP_USER_TIMEOUT': 1000,
|
||||
'TCP_KEEPIDLE': 60,
|
||||
'TCP_KEEPINTVL': 10,
|
||||
'TCP_KEEPCNT': 9,
|
||||
}
|
||||
|
||||
|
||||
def to_host_port(host, default=AMQP_PORT):
|
||||
"""Convert hostname:port string to host, port tuple."""
|
||||
port = default
|
||||
m = IPV6_LITERAL.match(host)
|
||||
if m:
|
||||
host = m.group(1)
|
||||
if m.group(2):
|
||||
port = int(m.group(2))
|
||||
else:
|
||||
if ':' in host:
|
||||
host, port = host.rsplit(':', 1)
|
||||
port = int(port)
|
||||
return host, port
|
||||
|
||||
|
||||
class _AbstractTransport:
|
||||
"""Common superclass for TCP and SSL transports.
|
||||
|
||||
PARAMETERS:
|
||||
host: str
|
||||
|
||||
Broker address in format ``HOSTNAME:PORT``.
|
||||
|
||||
connect_timeout: int
|
||||
|
||||
Timeout of creating new connection.
|
||||
|
||||
read_timeout: int
|
||||
|
||||
sets ``SO_RCVTIMEO`` parameter of socket.
|
||||
|
||||
write_timeout: int
|
||||
|
||||
sets ``SO_SNDTIMEO`` parameter of socket.
|
||||
|
||||
socket_settings: dict
|
||||
|
||||
dictionary containing `optname` and ``optval`` passed to
|
||||
``setsockopt(2)``.
|
||||
|
||||
raise_on_initial_eintr: bool
|
||||
|
||||
when True, ``socket.timeout`` is raised
|
||||
when exception is received during first read. See ``_read()`` for
|
||||
details.
|
||||
"""
|
||||
|
||||
def __init__(self, host, connect_timeout=None,
|
||||
read_timeout=None, write_timeout=None,
|
||||
socket_settings=None, raise_on_initial_eintr=True, **kwargs):
|
||||
self.connected = False
|
||||
self.sock = None
|
||||
self.raise_on_initial_eintr = raise_on_initial_eintr
|
||||
self._read_buffer = EMPTY_BUFFER
|
||||
self.host, self.port = to_host_port(host)
|
||||
self.connect_timeout = connect_timeout
|
||||
self.read_timeout = read_timeout
|
||||
self.write_timeout = write_timeout
|
||||
self.socket_settings = socket_settings
|
||||
|
||||
__slots__ = (
|
||||
"connection",
|
||||
"sock",
|
||||
"raise_on_initial_eintr",
|
||||
"_read_buffer",
|
||||
"host",
|
||||
"port",
|
||||
"connect_timeout",
|
||||
"read_timeout",
|
||||
"write_timeout",
|
||||
"socket_settings",
|
||||
# adding '__dict__' to get dynamic assignment
|
||||
"__dict__",
|
||||
"__weakref__",
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
if self.sock:
|
||||
src = f'{self.sock.getsockname()[0]}:{self.sock.getsockname()[1]}'
|
||||
dst = f'{self.sock.getpeername()[0]}:{self.sock.getpeername()[1]}'
|
||||
return f'<{type(self).__name__}: {src} -> {dst} at {id(self):#x}>'
|
||||
else:
|
||||
return f'<{type(self).__name__}: (disconnected) at {id(self):#x}>'
|
||||
|
||||
def connect(self):
|
||||
try:
|
||||
# are we already connected?
|
||||
if self.connected:
|
||||
return
|
||||
self._connect(self.host, self.port, self.connect_timeout)
|
||||
self._init_socket(
|
||||
self.socket_settings, self.read_timeout, self.write_timeout,
|
||||
)
|
||||
# we've sent the banner; signal connect
|
||||
# EINTR, EAGAIN, EWOULDBLOCK would signal that the banner
|
||||
# has _not_ been sent
|
||||
self.connected = True
|
||||
except (OSError, SSLError):
|
||||
# if not fully connected, close socket, and reraise error
|
||||
if self.sock and not self.connected:
|
||||
self.sock.close()
|
||||
self.sock = None
|
||||
raise
|
||||
|
||||
@contextmanager
|
||||
def having_timeout(self, timeout):
|
||||
if timeout is None:
|
||||
yield self.sock
|
||||
else:
|
||||
sock = self.sock
|
||||
prev = sock.gettimeout()
|
||||
if prev != timeout:
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
yield self.sock
|
||||
except SSLError as exc:
|
||||
if 'timed out' in str(exc):
|
||||
# http://bugs.python.org/issue10272
|
||||
raise socket.timeout()
|
||||
elif 'The operation did not complete' in str(exc):
|
||||
# Non-blocking SSL sockets can throw SSLError
|
||||
raise socket.timeout()
|
||||
raise
|
||||
except OSError as exc:
|
||||
if exc.errno == errno.EWOULDBLOCK:
|
||||
raise socket.timeout()
|
||||
raise
|
||||
finally:
|
||||
if timeout != prev:
|
||||
sock.settimeout(prev)
|
||||
|
||||
def _connect(self, host, port, timeout):
|
||||
entries = socket.getaddrinfo(
|
||||
host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, SOL_TCP,
|
||||
)
|
||||
for i, res in enumerate(entries):
|
||||
af, socktype, proto, canonname, sa = res
|
||||
try:
|
||||
self.sock = socket.socket(af, socktype, proto)
|
||||
try:
|
||||
set_cloexec(self.sock, True)
|
||||
except NotImplementedError:
|
||||
pass
|
||||
self.sock.settimeout(timeout)
|
||||
self.sock.connect(sa)
|
||||
except socket.error:
|
||||
if self.sock:
|
||||
self.sock.close()
|
||||
self.sock = None
|
||||
if i + 1 >= len(entries):
|
||||
raise
|
||||
else:
|
||||
break
|
||||
|
||||
def _init_socket(self, socket_settings, read_timeout, write_timeout):
|
||||
self.sock.settimeout(None) # set socket back to blocking mode
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
||||
self._set_socket_options(socket_settings)
|
||||
|
||||
# set socket timeouts
|
||||
for timeout, interval in ((socket.SO_SNDTIMEO, write_timeout),
|
||||
(socket.SO_RCVTIMEO, read_timeout)):
|
||||
if interval is not None:
|
||||
sec = int(interval)
|
||||
usec = int((interval - sec) * 1000000)
|
||||
self.sock.setsockopt(
|
||||
socket.SOL_SOCKET, timeout,
|
||||
pack('ll', sec, usec),
|
||||
)
|
||||
self._setup_transport()
|
||||
|
||||
self._write(AMQP_PROTOCOL_HEADER)
|
||||
|
||||
def _get_tcp_socket_defaults(self, sock):
|
||||
tcp_opts = {}
|
||||
for opt in KNOWN_TCP_OPTS:
|
||||
enum = None
|
||||
if opt == 'TCP_USER_TIMEOUT':
|
||||
try:
|
||||
from socket import TCP_USER_TIMEOUT as enum
|
||||
except ImportError:
|
||||
# should be in Python 3.6+ on Linux.
|
||||
enum = 18
|
||||
elif hasattr(socket, opt):
|
||||
enum = getattr(socket, opt)
|
||||
|
||||
if enum:
|
||||
if opt in DEFAULT_SOCKET_SETTINGS:
|
||||
tcp_opts[enum] = DEFAULT_SOCKET_SETTINGS[opt]
|
||||
elif hasattr(socket, opt):
|
||||
tcp_opts[enum] = sock.getsockopt(
|
||||
SOL_TCP, getattr(socket, opt))
|
||||
return tcp_opts
|
||||
|
||||
def _set_socket_options(self, socket_settings):
|
||||
tcp_opts = self._get_tcp_socket_defaults(self.sock)
|
||||
if socket_settings:
|
||||
tcp_opts.update(socket_settings)
|
||||
for opt, val in tcp_opts.items():
|
||||
self.sock.setsockopt(SOL_TCP, opt, val)
|
||||
|
||||
def _read(self, n, initial=False):
|
||||
"""Read exactly n bytes from the peer."""
|
||||
raise NotImplementedError('Must be overridden in subclass')
|
||||
|
||||
def _setup_transport(self):
|
||||
"""Do any additional initialization of the class."""
|
||||
pass
|
||||
|
||||
def _shutdown_transport(self):
|
||||
"""Do any preliminary work in shutting down the connection."""
|
||||
pass
|
||||
|
||||
def _write(self, s):
|
||||
"""Completely write a string to the peer."""
|
||||
raise NotImplementedError('Must be overridden in subclass')
|
||||
|
||||
def close(self):
|
||||
if self.sock is not None:
|
||||
try:
|
||||
self._shutdown_transport()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Call shutdown first to make sure that pending messages
|
||||
# reach the AMQP broker if the program exits after
|
||||
# calling this method.
|
||||
try:
|
||||
self.sock.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
try:
|
||||
self.sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
self.sock = None
|
||||
self.connected = False
|
||||
|
||||
def read_frame(self, unpack=unpack):
|
||||
"""Parse AMQP frame.
|
||||
|
||||
Frame has following format::
|
||||
|
||||
0 1 3 7 size+7 size+8
|
||||
+------+---------+---------+ +-------------+ +-----------+
|
||||
| type | channel | size | | payload | | frame-end |
|
||||
+------+---------+---------+ +-------------+ +-----------+
|
||||
octet short long 'size' octets octet
|
||||
|
||||
"""
|
||||
read = self._read
|
||||
read_frame_buffer = EMPTY_BUFFER
|
||||
try:
|
||||
frame_header = read(7, True)
|
||||
read_frame_buffer += frame_header
|
||||
frame_type, channel, size = unpack('>BHI', frame_header)
|
||||
# >I is an unsigned int, but the argument to sock.recv is signed,
|
||||
# so we know the size can be at most 2 * SIGNED_INT_MAX
|
||||
if size > SIGNED_INT_MAX:
|
||||
part1 = read(SIGNED_INT_MAX)
|
||||
|
||||
try:
|
||||
part2 = read(size - SIGNED_INT_MAX)
|
||||
except (socket.timeout, OSError, SSLError):
|
||||
# In case this read times out, we need to make sure to not
|
||||
# lose part1 when we retry the read
|
||||
read_frame_buffer += part1
|
||||
raise
|
||||
|
||||
payload = b''.join([part1, part2])
|
||||
else:
|
||||
payload = read(size)
|
||||
read_frame_buffer += payload
|
||||
frame_end = ord(read(1))
|
||||
except socket.timeout:
|
||||
self._read_buffer = read_frame_buffer + self._read_buffer
|
||||
raise
|
||||
except (OSError, SSLError) as exc:
|
||||
if (
|
||||
isinstance(exc, socket.error) and os.name == 'nt'
|
||||
and exc.errno == errno.EWOULDBLOCK # noqa
|
||||
):
|
||||
# On windows we can get a read timeout with a winsock error
|
||||
# code instead of a proper socket.timeout() error, see
|
||||
# https://github.com/celery/py-amqp/issues/320
|
||||
self._read_buffer = read_frame_buffer + self._read_buffer
|
||||
raise socket.timeout()
|
||||
|
||||
if isinstance(exc, SSLError) and 'timed out' in str(exc):
|
||||
# Don't disconnect for ssl read time outs
|
||||
# http://bugs.python.org/issue10272
|
||||
self._read_buffer = read_frame_buffer + self._read_buffer
|
||||
raise socket.timeout()
|
||||
|
||||
if exc.errno not in _UNAVAIL:
|
||||
self.connected = False
|
||||
raise
|
||||
# frame-end octet must contain '\xce' value
|
||||
if frame_end == 206:
|
||||
return frame_type, channel, payload
|
||||
else:
|
||||
raise UnexpectedFrame(
|
||||
f'Received frame_end {frame_end:#04x} while expecting 0xce')
|
||||
|
||||
def write(self, s):
|
||||
try:
|
||||
self._write(s)
|
||||
except socket.timeout:
|
||||
raise
|
||||
except OSError as exc:
|
||||
if exc.errno not in _UNAVAIL:
|
||||
self.connected = False
|
||||
raise
|
||||
|
||||
|
||||
class SSLTransport(_AbstractTransport):
|
||||
"""Transport that works over SSL.
|
||||
|
||||
PARAMETERS:
|
||||
host: str
|
||||
|
||||
Broker address in format ``HOSTNAME:PORT``.
|
||||
|
||||
connect_timeout: int
|
||||
|
||||
Timeout of creating new connection.
|
||||
|
||||
ssl: bool|dict
|
||||
|
||||
parameters of TLS subsystem.
|
||||
- when ``ssl`` is not dictionary, defaults of TLS are used
|
||||
- otherwise:
|
||||
- if ``ssl`` dictionary contains ``context`` key,
|
||||
:attr:`~SSLTransport._wrap_context` is used for wrapping
|
||||
socket. ``context`` is a dictionary passed to
|
||||
:attr:`~SSLTransport._wrap_context` as context parameter.
|
||||
All others items from ``ssl`` argument are passed as
|
||||
``sslopts``.
|
||||
- if ``ssl`` dictionary does not contain ``context`` key,
|
||||
:attr:`~SSLTransport._wrap_socket_sni` is used for
|
||||
wrapping socket. All items in ``ssl`` argument are
|
||||
passed to :attr:`~SSLTransport._wrap_socket_sni` as
|
||||
parameters.
|
||||
|
||||
kwargs:
|
||||
|
||||
additional arguments of
|
||||
:class:`~amqp.transport._AbstractTransport` class
|
||||
"""
|
||||
|
||||
def __init__(self, host, connect_timeout=None, ssl=None, **kwargs):
|
||||
self.sslopts = ssl if isinstance(ssl, dict) else {}
|
||||
self._read_buffer = EMPTY_BUFFER
|
||||
super().__init__(
|
||||
host, connect_timeout=connect_timeout, **kwargs)
|
||||
|
||||
__slots__ = (
|
||||
"sslopts",
|
||||
)
|
||||
|
||||
def _setup_transport(self):
|
||||
"""Wrap the socket in an SSL object."""
|
||||
self.sock = self._wrap_socket(self.sock, **self.sslopts)
|
||||
self.sock.do_handshake()
|
||||
self._quick_recv = self.sock.read
|
||||
|
||||
def _wrap_socket(self, sock, context=None, **sslopts):
|
||||
if context:
|
||||
return self._wrap_context(sock, sslopts, **context)
|
||||
return self._wrap_socket_sni(sock, **sslopts)
|
||||
|
||||
def _wrap_context(self, sock, sslopts, check_hostname=None, **ctx_options):
|
||||
"""Wrap socket without SNI headers.
|
||||
|
||||
PARAMETERS:
|
||||
sock: socket.socket
|
||||
|
||||
Socket to be wrapped.
|
||||
|
||||
sslopts: dict
|
||||
|
||||
Parameters of :attr:`ssl.SSLContext.wrap_socket`.
|
||||
|
||||
check_hostname
|
||||
|
||||
Whether to match the peer cert’s hostname. See
|
||||
:attr:`ssl.SSLContext.check_hostname` for details.
|
||||
|
||||
ctx_options
|
||||
|
||||
Parameters of :attr:`ssl.create_default_context`.
|
||||
"""
|
||||
ctx = ssl.create_default_context(**ctx_options)
|
||||
ctx.check_hostname = check_hostname
|
||||
return ctx.wrap_socket(sock, **sslopts)
|
||||
|
||||
def _wrap_socket_sni(self, sock, keyfile=None, certfile=None,
|
||||
server_side=False, cert_reqs=None,
|
||||
ca_certs=None, do_handshake_on_connect=False,
|
||||
suppress_ragged_eofs=True, server_hostname=None,
|
||||
ciphers=None, ssl_version=None):
|
||||
"""Socket wrap with SNI headers.
|
||||
|
||||
stdlib :attr:`ssl.SSLContext.wrap_socket` method augmented with support
|
||||
for setting the server_hostname field required for SNI hostname header.
|
||||
|
||||
PARAMETERS:
|
||||
sock: socket.socket
|
||||
|
||||
Socket to be wrapped.
|
||||
|
||||
keyfile: str
|
||||
|
||||
Path to the private key
|
||||
|
||||
certfile: str
|
||||
|
||||
Path to the certificate
|
||||
|
||||
server_side: bool
|
||||
|
||||
Identifies whether server-side or client-side
|
||||
behavior is desired from this socket. See
|
||||
:attr:`~ssl.SSLContext.wrap_socket` for details.
|
||||
|
||||
cert_reqs: ssl.VerifyMode
|
||||
|
||||
When set to other than :attr:`ssl.CERT_NONE`, peers certificate
|
||||
is checked. Possible values are :attr:`ssl.CERT_NONE`,
|
||||
:attr:`ssl.CERT_OPTIONAL` and :attr:`ssl.CERT_REQUIRED`.
|
||||
|
||||
ca_certs: str
|
||||
|
||||
Path to “certification authority” (CA) certificates
|
||||
used to validate other peers’ certificates when ``cert_reqs``
|
||||
is other than :attr:`ssl.CERT_NONE`.
|
||||
|
||||
do_handshake_on_connect: bool
|
||||
|
||||
Specifies whether to do the SSL
|
||||
handshake automatically. See
|
||||
:attr:`~ssl.SSLContext.wrap_socket` for details.
|
||||
|
||||
suppress_ragged_eofs (bool):
|
||||
|
||||
See :attr:`~ssl.SSLContext.wrap_socket` for details.
|
||||
|
||||
server_hostname: str
|
||||
|
||||
Specifies the hostname of the service which
|
||||
we are connecting to. See :attr:`~ssl.SSLContext.wrap_socket`
|
||||
for details.
|
||||
|
||||
ciphers: str
|
||||
|
||||
Available ciphers for sockets created with this
|
||||
context. See :attr:`ssl.SSLContext.set_ciphers`
|
||||
|
||||
ssl_version:
|
||||
|
||||
Protocol of the SSL Context. The value is one of
|
||||
``ssl.PROTOCOL_*`` constants.
|
||||
"""
|
||||
opts = {
|
||||
'sock': sock,
|
||||
'server_side': server_side,
|
||||
'do_handshake_on_connect': do_handshake_on_connect,
|
||||
'suppress_ragged_eofs': suppress_ragged_eofs,
|
||||
'server_hostname': server_hostname,
|
||||
}
|
||||
|
||||
if ssl_version is None:
|
||||
ssl_version = (
|
||||
ssl.PROTOCOL_TLS_SERVER
|
||||
if server_side
|
||||
else ssl.PROTOCOL_TLS_CLIENT
|
||||
)
|
||||
|
||||
context = ssl.SSLContext(ssl_version)
|
||||
|
||||
if certfile is not None:
|
||||
context.load_cert_chain(certfile, keyfile)
|
||||
if ca_certs is not None:
|
||||
context.load_verify_locations(ca_certs)
|
||||
if ciphers is not None:
|
||||
context.set_ciphers(ciphers)
|
||||
# Set SNI headers if supported.
|
||||
# Must set context.check_hostname before setting context.verify_mode
|
||||
# to avoid setting context.verify_mode=ssl.CERT_NONE while
|
||||
# context.check_hostname is still True (the default value in context
|
||||
# if client-side) which results in the following exception:
|
||||
# ValueError: Cannot set verify_mode to CERT_NONE when check_hostname
|
||||
# is enabled.
|
||||
try:
|
||||
context.check_hostname = (
|
||||
ssl.HAS_SNI and server_hostname is not None
|
||||
)
|
||||
except AttributeError:
|
||||
pass # ask forgiveness not permission
|
||||
|
||||
# See note above re: ordering for context.check_hostname and
|
||||
# context.verify_mode assignments.
|
||||
if cert_reqs is not None:
|
||||
context.verify_mode = cert_reqs
|
||||
|
||||
if ca_certs is None and context.verify_mode != ssl.CERT_NONE:
|
||||
purpose = (
|
||||
ssl.Purpose.CLIENT_AUTH
|
||||
if server_side
|
||||
else ssl.Purpose.SERVER_AUTH
|
||||
)
|
||||
context.load_default_certs(purpose)
|
||||
|
||||
sock = context.wrap_socket(**opts)
|
||||
return sock
|
||||
|
||||
def _shutdown_transport(self):
|
||||
"""Unwrap a SSL socket, so we can call shutdown()."""
|
||||
if self.sock is not None:
|
||||
self.sock = self.sock.unwrap()
|
||||
|
||||
def _read(self, n, initial=False,
|
||||
_errnos=(errno.ENOENT, errno.EAGAIN, errno.EINTR)):
|
||||
# According to SSL_read(3), it can at most return 16kb of data.
|
||||
# Thus, we use an internal read buffer like TCPTransport._read
|
||||
# to get the exact number of bytes wanted.
|
||||
recv = self._quick_recv
|
||||
rbuf = self._read_buffer
|
||||
try:
|
||||
while len(rbuf) < n:
|
||||
try:
|
||||
s = recv(n - len(rbuf)) # see note above
|
||||
except OSError as exc:
|
||||
# ssl.sock.read may cause ENOENT if the
|
||||
# operation couldn't be performed (Issue celery#1414).
|
||||
if exc.errno in _errnos:
|
||||
if initial and self.raise_on_initial_eintr:
|
||||
raise socket.timeout()
|
||||
continue
|
||||
raise
|
||||
if not s:
|
||||
raise OSError('Server unexpectedly closed connection')
|
||||
rbuf += s
|
||||
except: # noqa
|
||||
self._read_buffer = rbuf
|
||||
raise
|
||||
result, self._read_buffer = rbuf[:n], rbuf[n:]
|
||||
return result
|
||||
|
||||
def _write(self, s):
|
||||
"""Write a string out to the SSL socket fully."""
|
||||
write = self.sock.write
|
||||
while s:
|
||||
try:
|
||||
n = write(s)
|
||||
except ValueError:
|
||||
# AG: sock._sslobj might become null in the meantime if the
|
||||
# remote connection has hung up.
|
||||
# In python 3.4, a ValueError is raised is self._sslobj is
|
||||
# None.
|
||||
n = 0
|
||||
if not n:
|
||||
raise OSError('Socket closed')
|
||||
s = s[n:]
|
||||
|
||||
|
||||
class TCPTransport(_AbstractTransport):
|
||||
"""Transport that deals directly with TCP socket.
|
||||
|
||||
All parameters are :class:`~amqp.transport._AbstractTransport` class.
|
||||
"""
|
||||
|
||||
def _setup_transport(self):
|
||||
# Setup to _write() directly to the socket, and
|
||||
# do our own buffered reads.
|
||||
self._write = self.sock.sendall
|
||||
self._read_buffer = EMPTY_BUFFER
|
||||
self._quick_recv = self.sock.recv
|
||||
|
||||
def _read(self, n, initial=False, _errnos=(errno.EAGAIN, errno.EINTR)):
|
||||
"""Read exactly n bytes from the socket."""
|
||||
recv = self._quick_recv
|
||||
rbuf = self._read_buffer
|
||||
try:
|
||||
while len(rbuf) < n:
|
||||
try:
|
||||
s = recv(n - len(rbuf))
|
||||
except OSError as exc:
|
||||
if exc.errno in _errnos:
|
||||
if initial and self.raise_on_initial_eintr:
|
||||
raise socket.timeout()
|
||||
continue
|
||||
raise
|
||||
if not s:
|
||||
raise OSError('Server unexpectedly closed connection')
|
||||
rbuf += s
|
||||
except: # noqa
|
||||
self._read_buffer = rbuf
|
||||
raise
|
||||
|
||||
result, self._read_buffer = rbuf[:n], rbuf[n:]
|
||||
return result
|
||||
|
||||
|
||||
def Transport(host, connect_timeout=None, ssl=False, **kwargs):
|
||||
"""Create transport.
|
||||
|
||||
Given a few parameters from the Connection constructor,
|
||||
select and create a subclass of
|
||||
:class:`~amqp.transport._AbstractTransport`.
|
||||
|
||||
PARAMETERS:
|
||||
|
||||
host: str
|
||||
|
||||
Broker address in format ``HOSTNAME:PORT``.
|
||||
|
||||
connect_timeout: int
|
||||
|
||||
Timeout of creating new connection.
|
||||
|
||||
ssl: bool|dict
|
||||
|
||||
If set, :class:`~amqp.transport.SSLTransport` is used
|
||||
and ``ssl`` parameter is passed to it. Otherwise
|
||||
:class:`~amqp.transport.TCPTransport` is used.
|
||||
|
||||
kwargs:
|
||||
|
||||
additional arguments of :class:`~amqp.transport._AbstractTransport`
|
||||
class
|
||||
"""
|
||||
transport = SSLTransport if ssl else TCPTransport
|
||||
return transport(host, connect_timeout=connect_timeout, ssl=ssl, **kwargs)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Compatibility utilities."""
|
||||
import logging
|
||||
from logging import NullHandler
|
||||
|
||||
# enables celery 3.1.23 to start again
|
||||
from vine import promise # noqa
|
||||
from vine.utils import wraps
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError: # pragma: no cover
|
||||
fcntl = None # noqa
|
||||
|
||||
|
||||
def set_cloexec(fd, cloexec):
|
||||
"""Set flag to close fd after exec."""
|
||||
if fcntl is None:
|
||||
return
|
||||
try:
|
||||
FD_CLOEXEC = fcntl.FD_CLOEXEC
|
||||
except AttributeError:
|
||||
raise NotImplementedError(
|
||||
'close-on-exec flag not supported on this platform',
|
||||
)
|
||||
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
|
||||
if cloexec:
|
||||
flags |= FD_CLOEXEC
|
||||
else:
|
||||
flags &= ~FD_CLOEXEC
|
||||
return fcntl.fcntl(fd, fcntl.F_SETFD, flags)
|
||||
|
||||
|
||||
def coro(gen):
|
||||
"""Decorator to mark generator as a co-routine."""
|
||||
@wraps(gen)
|
||||
def _boot(*args, **kwargs):
|
||||
co = gen(*args, **kwargs)
|
||||
next(co)
|
||||
return co
|
||||
|
||||
return _boot
|
||||
|
||||
|
||||
def str_to_bytes(s):
|
||||
"""Convert str to bytes."""
|
||||
if isinstance(s, str):
|
||||
return s.encode('utf-8', 'surrogatepass')
|
||||
return s
|
||||
|
||||
|
||||
def bytes_to_str(s):
|
||||
"""Convert bytes to str."""
|
||||
if isinstance(s, bytes):
|
||||
return s.decode('utf-8', 'surrogatepass')
|
||||
return s
|
||||
|
||||
|
||||
def get_logger(logger):
|
||||
"""Get logger by name."""
|
||||
if isinstance(logger, str):
|
||||
logger = logging.getLogger(logger)
|
||||
if not logger.handlers:
|
||||
logger.addHandler(NullHandler())
|
||||
return logger
|
||||
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,29 @@
|
||||
Copyright (c) 2006-2008, R Oudkerk and Contributors
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
3. Neither the name of author nor the names of any contributors may be
|
||||
used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGE.
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: billiard
|
||||
Version: 3.6.4.0
|
||||
Summary: Python multiprocessing fork with improvements and bugfixes
|
||||
Home-page: https://github.com/celery/billiard
|
||||
Author: R Oudkerk / Python Software Foundation
|
||||
Author-email: python-dev@python.org
|
||||
Maintainer: Asif Saif Uddin
|
||||
Maintainer-email: auvipy@gmail.com
|
||||
License: BSD
|
||||
Keywords: multiprocessing pool process
|
||||
Platform: UNKNOWN
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: C
|
||||
Classifier: Programming Language :: Python :: 2
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.5
|
||||
Classifier: Programming Language :: Python :: 3.6
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
Classifier: Programming Language :: Python :: Implementation :: CPython
|
||||
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
||||
Classifier: Operating System :: Microsoft :: Windows
|
||||
Classifier: Operating System :: POSIX
|
||||
Classifier: License :: OSI Approved :: BSD License
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Classifier: Topic :: System :: Distributed Computing
|
||||
Description-Content-Type: text/markdown
|
||||
|
||||
========
|
||||
billiard
|
||||
========
|
||||
:version: 3.6.4.0
|
||||
|
||||
|build-status-lin| |build-status-win| |license| |wheel| |pyversion| |pyimp|
|
||||
|
||||
.. |build-status-lin| image:: https://secure.travis-ci.org/celery/billiard.png?branch=master
|
||||
:alt: Build status on Linux
|
||||
:target: https://travis-ci.org/celery/billiard
|
||||
|
||||
.. |build-status-win| image:: https://ci.appveyor.com/api/projects/status/github/celery/billiard?png=true&branch=master
|
||||
:alt: Build status on Windows
|
||||
:target: https://ci.appveyor.com/project/ask/billiard
|
||||
|
||||
.. |license| image:: https://img.shields.io/pypi/l/billiard.svg
|
||||
:alt: BSD License
|
||||
:target: https://opensource.org/licenses/BSD-3-Clause
|
||||
|
||||
.. |wheel| image:: https://img.shields.io/pypi/wheel/billiard.svg
|
||||
:alt: Billiard can be installed via wheel
|
||||
:target: https://pypi.org/project/billiard/
|
||||
|
||||
.. |pyversion| image:: https://img.shields.io/pypi/pyversions/billiard.svg
|
||||
:alt: Supported Python versions.
|
||||
:target: https://pypi.org/project/billiard/
|
||||
|
||||
.. |pyimp| image:: https://img.shields.io/pypi/implementation/billiard.svg
|
||||
:alt: Support Python implementations.
|
||||
:target: https://pypi.org/project/billiard/
|
||||
|
||||
About
|
||||
-----
|
||||
|
||||
``billiard`` is a fork of the Python 2.7 `multiprocessing <https://docs.python.org/library/multiprocessing.html>`_
|
||||
package. The multiprocessing package itself is a renamed and updated version of
|
||||
R Oudkerk's `pyprocessing <https://pypi.org/project/processing/>`_ package.
|
||||
This standalone variant draws its fixes/improvements from python-trunk and provides
|
||||
additional bug fixes and improvements.
|
||||
|
||||
- This package would not be possible if not for the contributions of not only
|
||||
the current maintainers but all of the contributors to the original pyprocessing
|
||||
package listed `here <http://pyprocessing.berlios.de/doc/THANKS.html>`_.
|
||||
|
||||
- Also, it is a fork of the multiprocessing backport package by Christian Heims.
|
||||
|
||||
- It includes the no-execv patch contributed by R. Oudkerk.
|
||||
|
||||
- And the Pool improvements previously located in `Celery`_.
|
||||
|
||||
- Billiard is used in and is a dependency for `Celery`_ and is maintained by the
|
||||
Celery team.
|
||||
|
||||
.. _`Celery`: http://celeryproject.org
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
|
||||
The documentation for ``billiard`` is available on `Read the Docs <https://billiard.readthedocs.io>`_.
|
||||
|
||||
Bug reporting
|
||||
-------------
|
||||
|
||||
Please report bugs related to multiprocessing at the
|
||||
`Python bug tracker <https://bugs.python.org/>`_. Issues related to billiard
|
||||
should be reported at https://github.com/celery/billiard/issues.
|
||||
|
||||
billiard is part of the Tidelift Subscription
|
||||
---------------------------------------------
|
||||
|
||||
The maintainers of ``billiard`` and thousands of other packages are working
|
||||
with Tidelift to deliver commercial support and maintenance for the open source
|
||||
dependencies you use to build your applications. Save time, reduce risk, and
|
||||
improve code health, while paying the maintainers of the exact dependencies you
|
||||
use. `Learn more`_.
|
||||
|
||||
.. _`Learn more`: https://tidelift.com/subscription/pkg/pypi-billiard?utm_source=pypi-billiard&utm_medium=referral&utm_campaign=readme&utm_term=repo
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
billiard-3.6.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
billiard-3.6.4.0.dist-info/LICENSE.txt,sha256=ZjLlmsq9u77CYoN9RHJKBlMYlJ8ALv0GAtZCcRrjpFc,1483
|
||||
billiard-3.6.4.0.dist-info/METADATA,sha256=vuSGzLNS74m40sl9XXGu1OqEb4SHQuz4JWa6pyNZ7zI,4480
|
||||
billiard-3.6.4.0.dist-info/RECORD,,
|
||||
billiard-3.6.4.0.dist-info/WHEEL,sha256=g4nMs7d-Xl9-xC9XovUrsDHGXt-FT0E17Yqo92DEfvY,92
|
||||
billiard-3.6.4.0.dist-info/top_level.txt,sha256=52Kkdlqn9Np8pbpkTVd_1KZTZLGjupUzhUw8QsW-B-U,9
|
||||
billiard/__init__.py,sha256=5ZCRrQvZQ0e189Dx_5QzyXm-s2QflZOAwMbiMSdeLlE,1598
|
||||
billiard/__pycache__/__init__.cpython-310.pyc,,
|
||||
billiard/__pycache__/_ext.cpython-310.pyc,,
|
||||
billiard/__pycache__/_win.cpython-310.pyc,,
|
||||
billiard/__pycache__/common.cpython-310.pyc,,
|
||||
billiard/__pycache__/compat.cpython-310.pyc,,
|
||||
billiard/__pycache__/connection.cpython-310.pyc,,
|
||||
billiard/__pycache__/context.cpython-310.pyc,,
|
||||
billiard/__pycache__/einfo.cpython-310.pyc,,
|
||||
billiard/__pycache__/exceptions.cpython-310.pyc,,
|
||||
billiard/__pycache__/five.cpython-310.pyc,,
|
||||
billiard/__pycache__/forkserver.cpython-310.pyc,,
|
||||
billiard/__pycache__/heap.cpython-310.pyc,,
|
||||
billiard/__pycache__/managers.cpython-310.pyc,,
|
||||
billiard/__pycache__/pool.cpython-310.pyc,,
|
||||
billiard/__pycache__/popen_fork.cpython-310.pyc,,
|
||||
billiard/__pycache__/popen_forkserver.cpython-310.pyc,,
|
||||
billiard/__pycache__/popen_spawn_posix.cpython-310.pyc,,
|
||||
billiard/__pycache__/popen_spawn_win32.cpython-310.pyc,,
|
||||
billiard/__pycache__/process.cpython-310.pyc,,
|
||||
billiard/__pycache__/queues.cpython-310.pyc,,
|
||||
billiard/__pycache__/reduction.cpython-310.pyc,,
|
||||
billiard/__pycache__/resource_sharer.cpython-310.pyc,,
|
||||
billiard/__pycache__/semaphore_tracker.cpython-310.pyc,,
|
||||
billiard/__pycache__/sharedctypes.cpython-310.pyc,,
|
||||
billiard/__pycache__/spawn.cpython-310.pyc,,
|
||||
billiard/__pycache__/synchronize.cpython-310.pyc,,
|
||||
billiard/__pycache__/util.cpython-310.pyc,,
|
||||
billiard/_ext.py,sha256=JE-Yc_T1SSZ40pnEQSY7P2gVsjnF4fGO1nCPZqMnSlg,912
|
||||
billiard/_win.py,sha256=Qb6pNOyqkjTQJbieQ9laK34maNymXRl7YllXV33vc6I,2982
|
||||
billiard/common.py,sha256=0MvDZ1K0ttqTPeJ0H8CVeckK6NcwZQ6ZWfYP7RdEav4,4556
|
||||
billiard/compat.py,sha256=4hUPL5yMXaoTnw9zHG0Mt_O2ciT75zk9NmZVsNbWsFM,8938
|
||||
billiard/connection.py,sha256=KE-sIfd6GJ_U3TagV5_oTl04MfUjuqobaceXFuYAg-c,32759
|
||||
billiard/context.py,sha256=b9WZwt_jUlhhh1_8dbuAc-veMso6DGgmr6zsAhaeVGs,13202
|
||||
billiard/dummy/__init__.py,sha256=IVBv7GdN40dJjT7qRGfNB6dUtqkJjztZRUeIWQx3lh0,4680
|
||||
billiard/dummy/__pycache__/__init__.cpython-310.pyc,,
|
||||
billiard/dummy/__pycache__/connection.cpython-310.pyc,,
|
||||
billiard/dummy/connection.py,sha256=i2_VZhEkcfLazb_Pi-Qk7K_6eK4N0ieBYT99rnBHHS4,2954
|
||||
billiard/einfo.py,sha256=EctNy7BxU02lmADS6CIY_Y-0uFBIF0vwsAKkBJf55uw,3671
|
||||
billiard/exceptions.py,sha256=U1I3miQnFdEr-GpYswFk-tI8pnuRj9fRwFEB6kmpVvs,1312
|
||||
billiard/five.py,sha256=LIXMZrpp7tmM-9gxtxGEdhJ2q_h97Bt1VFm2gehKYF0,5544
|
||||
billiard/forkserver.py,sha256=Wgpz2mDIR6rLg8M2vAPvt3bkWVad6Kq422qgI_08yD0,8346
|
||||
billiard/heap.py,sha256=tcdgH5eM9zJHY747zEYm4wMLqdCfjoaYWZKkasrG33c,9349
|
||||
billiard/managers.py,sha256=U3ZyW1zzXjoDnjkHi52RT83h2GaXcEcKIuNzTHNHGHU,36841
|
||||
billiard/pool.py,sha256=9_v_BU9gskUJgE9EB4pU-9yXDHuTNpfS6m-c2J1egpE,69071
|
||||
billiard/popen_fork.py,sha256=a8Rn2ILCNIcHxFSwqbVSHFaPL_TTp2Ez5osXFDS3-4o,2600
|
||||
billiard/popen_forkserver.py,sha256=Ow8Rr6WjrYrJqsNE5ljnNEAbgleXyQXurn59qNlmDIs,1829
|
||||
billiard/popen_spawn_posix.py,sha256=Z2jsrtRWd-LAGacckULHyvxOpE61Ne7fp-Mel3FRvR8,1981
|
||||
billiard/popen_spawn_win32.py,sha256=8_cHhSa9jiwkDU7txMVJctjGuj0UoZxm9CF5Hj0s_0s,3591
|
||||
billiard/process.py,sha256=PRJDWKPQHUByPTtU1BtmFh6FOCfIbhkysaVjW9e6ndY,11138
|
||||
billiard/queues.py,sha256=ckMNodfWoYrKA6fAR3Hwamj4HZdwzAumYYQOpseUPxY,12778
|
||||
billiard/reduction.py,sha256=VXGE8g4pzhaPrIefdo-_LVTP-hIRvxo2mMOk9MveDYo,9429
|
||||
billiard/resource_sharer.py,sha256=OuKRJ2k0IwMUn8ykZ4lJ1p30X9sPc_UbHToXnJmqXf8,5361
|
||||
billiard/semaphore_tracker.py,sha256=PEhEgEJ8v7KbyYjzkmgxosRqnP3w50oC2Q9gHUeCEQU,4893
|
||||
billiard/sharedctypes.py,sha256=HuxgwfqDq5zapUBhe_JhASbowcLJ_ZAdky95sYRxtw8,6746
|
||||
billiard/spawn.py,sha256=xBVAxE0cWzVZEpGhzm28xFTEZJcHJDRzW1M7jpvhJIg,11779
|
||||
billiard/synchronize.py,sha256=lyhels1MI2syYyLqGTpnrexjlnmzCF6h43UKt8YwBHM,13041
|
||||
billiard/util.py,sha256=YAwBHvTST0iTyoLJ4Zo8HskwpCKtzvkd_nM_jZYgXL8,6021
|
||||
@@ -0,0 +1,5 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.34.2)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
billiard
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Python multiprocessing fork with improvements and bugfixes"""
|
||||
#
|
||||
# Package analogous to 'threading.py' but using processes
|
||||
#
|
||||
# multiprocessing/__init__.py
|
||||
#
|
||||
# This package is intended to duplicate the functionality (and much of
|
||||
# the API) of threading.py but uses processes instead of threads. A
|
||||
# subpackage 'multiprocessing.dummy' has the same API but is a simple
|
||||
# wrapper for 'threading'.
|
||||
#
|
||||
# Try calling `multiprocessing.doc.main()` to read the html
|
||||
# documentation in a webbrowser.
|
||||
#
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
from . import context
|
||||
|
||||
VERSION = (3, 6, 4, 0)
|
||||
__version__ = '.'.join(map(str, VERSION[0:4])) + "".join(VERSION[4:])
|
||||
__author__ = 'R Oudkerk / Python Software Foundation'
|
||||
__author_email__ = 'python-dev@python.org'
|
||||
__maintainer__ = 'Asif Saif Uddin'
|
||||
__contact__ = "auvipy@gmail.com"
|
||||
__homepage__ = "https://github.com/celery/billiard"
|
||||
__docformat__ = "restructuredtext"
|
||||
|
||||
# -eof meta-
|
||||
|
||||
#
|
||||
# Copy stuff from default context
|
||||
#
|
||||
|
||||
globals().update((name, getattr(context._default_context, name))
|
||||
for name in context._default_context.__all__)
|
||||
__all__ = context._default_context.__all__
|
||||
|
||||
#
|
||||
# XXX These should not really be documented or public.
|
||||
#
|
||||
|
||||
SUBDEBUG = 5
|
||||
SUBWARNING = 25
|
||||
|
||||
#
|
||||
# Alias for main module -- will be reset by bootstrapping child processes
|
||||
#
|
||||
|
||||
if '__main__' in sys.modules:
|
||||
sys.modules['__mp_main__'] = sys.modules['__main__']
|
||||
|
||||
|
||||
def ensure_multiprocessing():
|
||||
from ._ext import ensure_multiprocessing
|
||||
return ensure_multiprocessing()
|
||||
@@ -0,0 +1,34 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
|
||||
supports_exec = True
|
||||
|
||||
from .compat import _winapi as win32 # noqa
|
||||
|
||||
if sys.platform.startswith("java"):
|
||||
_billiard = None
|
||||
else:
|
||||
try:
|
||||
import _billiard # noqa
|
||||
except ImportError:
|
||||
import _multiprocessing as _billiard # noqa
|
||||
supports_exec = False
|
||||
|
||||
|
||||
def ensure_multiprocessing():
|
||||
if _billiard is None:
|
||||
raise NotImplementedError("multiprocessing not supported")
|
||||
|
||||
|
||||
def ensure_SemLock():
|
||||
try:
|
||||
from _billiard import SemLock # noqa
|
||||
except ImportError:
|
||||
try:
|
||||
from _multiprocessing import SemLock # noqa
|
||||
except ImportError:
|
||||
raise ImportError("""\
|
||||
This platform lacks a functioning sem_open implementation, therefore,
|
||||
the required synchronization primitives needed will not function,
|
||||
see issue 3770.""")
|
||||
@@ -0,0 +1,116 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
billiard._win
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
Windows utilities to terminate process groups.
|
||||
|
||||
"""
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
|
||||
# psutil is painfully slow in win32. So to avoid adding big
|
||||
# dependencies like pywin32 a ctypes based solution is preferred
|
||||
|
||||
# Code based on the winappdbg project http://winappdbg.sourceforge.net/
|
||||
# (BSD License)
|
||||
from ctypes import (
|
||||
byref, sizeof, windll,
|
||||
Structure, WinError, POINTER,
|
||||
c_size_t, c_char, c_void_p,
|
||||
)
|
||||
from ctypes.wintypes import DWORD, LONG
|
||||
|
||||
ERROR_NO_MORE_FILES = 18
|
||||
INVALID_HANDLE_VALUE = c_void_p(-1).value
|
||||
|
||||
|
||||
class PROCESSENTRY32(Structure):
|
||||
_fields_ = [
|
||||
('dwSize', DWORD),
|
||||
('cntUsage', DWORD),
|
||||
('th32ProcessID', DWORD),
|
||||
('th32DefaultHeapID', c_size_t),
|
||||
('th32ModuleID', DWORD),
|
||||
('cntThreads', DWORD),
|
||||
('th32ParentProcessID', DWORD),
|
||||
('pcPriClassBase', LONG),
|
||||
('dwFlags', DWORD),
|
||||
('szExeFile', c_char * 260),
|
||||
]
|
||||
LPPROCESSENTRY32 = POINTER(PROCESSENTRY32)
|
||||
|
||||
|
||||
def CreateToolhelp32Snapshot(dwFlags=2, th32ProcessID=0):
|
||||
hSnapshot = windll.kernel32.CreateToolhelp32Snapshot(dwFlags,
|
||||
th32ProcessID)
|
||||
if hSnapshot == INVALID_HANDLE_VALUE:
|
||||
raise WinError()
|
||||
return hSnapshot
|
||||
|
||||
|
||||
def Process32First(hSnapshot, pe=None):
|
||||
return _Process32n(windll.kernel32.Process32First, hSnapshot, pe)
|
||||
|
||||
|
||||
def Process32Next(hSnapshot, pe=None):
|
||||
return _Process32n(windll.kernel32.Process32Next, hSnapshot, pe)
|
||||
|
||||
|
||||
def _Process32n(fun, hSnapshot, pe=None):
|
||||
if pe is None:
|
||||
pe = PROCESSENTRY32()
|
||||
pe.dwSize = sizeof(PROCESSENTRY32)
|
||||
success = fun(hSnapshot, byref(pe))
|
||||
if not success:
|
||||
if windll.kernel32.GetLastError() == ERROR_NO_MORE_FILES:
|
||||
return
|
||||
raise WinError()
|
||||
return pe
|
||||
|
||||
|
||||
def get_all_processes_pids():
|
||||
"""Return a dictionary with all processes pids as keys and their
|
||||
parents as value. Ignore processes with no parents.
|
||||
"""
|
||||
h = CreateToolhelp32Snapshot()
|
||||
parents = {}
|
||||
pe = Process32First(h)
|
||||
while pe:
|
||||
if pe.th32ParentProcessID:
|
||||
parents[pe.th32ProcessID] = pe.th32ParentProcessID
|
||||
pe = Process32Next(h, pe)
|
||||
|
||||
return parents
|
||||
|
||||
|
||||
def get_processtree_pids(pid, include_parent=True):
|
||||
"""Return a list with all the pids of a process tree"""
|
||||
parents = get_all_processes_pids()
|
||||
all_pids = list(parents.keys())
|
||||
pids = {pid}
|
||||
while 1:
|
||||
pids_new = pids.copy()
|
||||
|
||||
for _pid in all_pids:
|
||||
if parents[_pid] in pids:
|
||||
pids_new.add(_pid)
|
||||
|
||||
if pids_new == pids:
|
||||
break
|
||||
|
||||
pids = pids_new.copy()
|
||||
|
||||
if not include_parent:
|
||||
pids.remove(pid)
|
||||
|
||||
return list(pids)
|
||||
|
||||
|
||||
def kill_processtree(pid, signum):
|
||||
"""Kill a process and all its descendants"""
|
||||
family_pids = get_processtree_pids(pid)
|
||||
|
||||
for _pid in family_pids:
|
||||
os.kill(_pid, signum)
|
||||
@@ -0,0 +1,169 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module contains utilities added by billiard, to keep
|
||||
"non-core" functionality out of ``.util``."""
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
|
||||
import pickle as pypickle
|
||||
try:
|
||||
import cPickle as cpickle
|
||||
except ImportError: # pragma: no cover
|
||||
cpickle = None # noqa
|
||||
|
||||
from .exceptions import RestartFreqExceeded
|
||||
from .five import monotonic
|
||||
|
||||
pickle = cpickle or pypickle
|
||||
pickle_load = pickle.load
|
||||
pickle_loads = pickle.loads
|
||||
|
||||
# cPickle.loads does not support buffer() objects,
|
||||
# but we can just create a StringIO and use load.
|
||||
if sys.version_info[0] == 3:
|
||||
from io import BytesIO
|
||||
else:
|
||||
try:
|
||||
from cStringIO import StringIO as BytesIO # noqa
|
||||
except ImportError:
|
||||
from StringIO import StringIO as BytesIO # noqa
|
||||
|
||||
SIGMAP = dict(
|
||||
(getattr(signal, n), n) for n in dir(signal) if n.startswith('SIG')
|
||||
)
|
||||
for _alias_sig in ('SIGHUP', 'SIGABRT'):
|
||||
try:
|
||||
# Alias for deprecated signal overwrites the name we want
|
||||
SIGMAP[getattr(signal, _alias_sig)] = _alias_sig
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
|
||||
TERM_SIGNAL, TERM_SIGNAME = signal.SIGTERM, 'SIGTERM'
|
||||
REMAP_SIGTERM = os.environ.get('REMAP_SIGTERM')
|
||||
if REMAP_SIGTERM:
|
||||
TERM_SIGNAL, TERM_SIGNAME = (
|
||||
getattr(signal, REMAP_SIGTERM), REMAP_SIGTERM)
|
||||
|
||||
|
||||
TERMSIGS_IGNORE = {'SIGTERM'} if REMAP_SIGTERM else set()
|
||||
TERMSIGS_FORCE = {'SIGQUIT'} if REMAP_SIGTERM else set()
|
||||
|
||||
EX_SOFTWARE = 70
|
||||
|
||||
TERMSIGS_DEFAULT = {
|
||||
'SIGHUP',
|
||||
'SIGQUIT',
|
||||
TERM_SIGNAME,
|
||||
'SIGUSR1',
|
||||
'SIGUSR2'
|
||||
}
|
||||
|
||||
TERMSIGS_FULL = {
|
||||
'SIGHUP',
|
||||
'SIGQUIT',
|
||||
'SIGTRAP',
|
||||
'SIGABRT',
|
||||
'SIGEMT',
|
||||
'SIGSYS',
|
||||
'SIGPIPE',
|
||||
'SIGALRM',
|
||||
TERM_SIGNAME,
|
||||
'SIGXCPU',
|
||||
'SIGXFSZ',
|
||||
'SIGVTALRM',
|
||||
'SIGPROF',
|
||||
'SIGUSR1',
|
||||
'SIGUSR2',
|
||||
}
|
||||
|
||||
#: set by signal handlers just before calling exit.
|
||||
#: if this is true after the sighandler returns it means that something
|
||||
#: went wrong while terminating the process, and :func:`os._exit`
|
||||
#: must be called ASAP.
|
||||
_should_have_exited = [False]
|
||||
|
||||
|
||||
def human_status(status):
|
||||
if (status or 0) < 0:
|
||||
try:
|
||||
return 'signal {0} ({1})'.format(-status, SIGMAP[-status])
|
||||
except KeyError:
|
||||
return 'signal {0}'.format(-status)
|
||||
return 'exitcode {0}'.format(status)
|
||||
|
||||
|
||||
def pickle_loads(s, load=pickle_load):
|
||||
# used to support buffer objects
|
||||
return load(BytesIO(s))
|
||||
|
||||
|
||||
def maybe_setsignal(signum, handler):
|
||||
try:
|
||||
signal.signal(signum, handler)
|
||||
except (OSError, AttributeError, ValueError, RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _shutdown_cleanup(signum, frame):
|
||||
# we will exit here so if the signal is received a second time
|
||||
# we can be sure that something is very wrong and we may be in
|
||||
# a crashing loop.
|
||||
if _should_have_exited[0]:
|
||||
os._exit(EX_SOFTWARE)
|
||||
maybe_setsignal(signum, signal.SIG_DFL)
|
||||
_should_have_exited[0] = True
|
||||
sys.exit(-(256 - signum))
|
||||
|
||||
|
||||
def signum(sig):
|
||||
return getattr(signal, sig, None)
|
||||
|
||||
|
||||
def _should_override_term_signal(sig, current):
|
||||
return (
|
||||
sig in TERMSIGS_FORCE or
|
||||
(current is not None and current != signal.SIG_IGN)
|
||||
)
|
||||
|
||||
|
||||
def reset_signals(handler=_shutdown_cleanup, full=False):
|
||||
for sig in TERMSIGS_FULL if full else TERMSIGS_DEFAULT:
|
||||
num = signum(sig)
|
||||
if num:
|
||||
if _should_override_term_signal(sig, signal.getsignal(num)):
|
||||
maybe_setsignal(num, handler)
|
||||
for sig in TERMSIGS_IGNORE:
|
||||
num = signum(sig)
|
||||
if num:
|
||||
maybe_setsignal(num, signal.SIG_IGN)
|
||||
|
||||
|
||||
class restart_state(object):
|
||||
RestartFreqExceeded = RestartFreqExceeded
|
||||
|
||||
def __init__(self, maxR, maxT):
|
||||
self.maxR, self.maxT = maxR, maxT
|
||||
self.R, self.T = 0, None
|
||||
|
||||
def step(self, now=None):
|
||||
now = monotonic() if now is None else now
|
||||
R = self.R
|
||||
if self.T and now - self.T >= self.maxT:
|
||||
# maxT passed, reset counter and time passed.
|
||||
self.T, self.R = now, 0
|
||||
elif self.maxR and self.R >= self.maxR:
|
||||
# verify that R has a value as the result handler
|
||||
# resets this when a job is accepted. If a job is accepted
|
||||
# the startup probably went fine (startup restart burst
|
||||
# protection)
|
||||
if self.R: # pragma: no cover
|
||||
self.R = 0 # reset in case someone catches the error
|
||||
raise self.RestartFreqExceeded("%r in %rs" % (R, self.maxT))
|
||||
# first run sets T
|
||||
if self.T is None:
|
||||
self.T = now
|
||||
self.R += 1
|
||||
@@ -0,0 +1,312 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import errno
|
||||
import numbers
|
||||
import os
|
||||
import sys
|
||||
|
||||
from .five import range, zip_longest
|
||||
|
||||
if sys.platform == 'win32':
|
||||
try:
|
||||
import _winapi # noqa
|
||||
except ImportError: # pragma: no cover
|
||||
from _multiprocessing import win32 as _winapi # noqa
|
||||
else:
|
||||
_winapi = None # noqa
|
||||
|
||||
try:
|
||||
import resource
|
||||
except ImportError: # pragma: no cover
|
||||
resource = None
|
||||
|
||||
try:
|
||||
from io import UnsupportedOperation
|
||||
FILENO_ERRORS = (AttributeError, ValueError, UnsupportedOperation)
|
||||
except ImportError: # pragma: no cover
|
||||
# Py2
|
||||
FILENO_ERRORS = (AttributeError, ValueError) # noqa
|
||||
|
||||
|
||||
if sys.version_info > (2, 7, 5):
|
||||
buf_t, is_new_buffer = memoryview, True # noqa
|
||||
else:
|
||||
buf_t, is_new_buffer = buffer, False # noqa
|
||||
|
||||
if hasattr(os, 'write'):
|
||||
__write__ = os.write
|
||||
|
||||
if is_new_buffer:
|
||||
|
||||
def send_offset(fd, buf, offset):
|
||||
return __write__(fd, buf[offset:])
|
||||
|
||||
else: # Py<2.7.6
|
||||
|
||||
def send_offset(fd, buf, offset): # noqa
|
||||
return __write__(fd, buf_t(buf, offset))
|
||||
|
||||
else: # non-posix platform
|
||||
|
||||
def send_offset(fd, buf, offset): # noqa
|
||||
raise NotImplementedError('send_offset')
|
||||
|
||||
|
||||
try:
|
||||
fsencode = os.fsencode
|
||||
fsdecode = os.fsdecode
|
||||
except AttributeError:
|
||||
def _fscodec():
|
||||
encoding = sys.getfilesystemencoding()
|
||||
if encoding == 'mbcs':
|
||||
errors = 'strict'
|
||||
else:
|
||||
errors = 'surrogateescape'
|
||||
|
||||
def fsencode(filename):
|
||||
"""
|
||||
Encode filename to the filesystem encoding with 'surrogateescape'
|
||||
error handler, return bytes unchanged. On Windows, use 'strict'
|
||||
error handler if the file system encoding is 'mbcs' (which is the
|
||||
default encoding).
|
||||
"""
|
||||
if isinstance(filename, bytes):
|
||||
return filename
|
||||
elif isinstance(filename, str):
|
||||
return filename.encode(encoding, errors)
|
||||
else:
|
||||
raise TypeError("expect bytes or str, not %s"
|
||||
% type(filename).__name__)
|
||||
|
||||
def fsdecode(filename):
|
||||
"""
|
||||
Decode filename from the filesystem encoding with 'surrogateescape'
|
||||
error handler, return str unchanged. On Windows, use 'strict' error
|
||||
handler if the file system encoding is 'mbcs' (which is the default
|
||||
encoding).
|
||||
"""
|
||||
if isinstance(filename, str):
|
||||
return filename
|
||||
elif isinstance(filename, bytes):
|
||||
return filename.decode(encoding, errors)
|
||||
else:
|
||||
raise TypeError("expect bytes or str, not %s"
|
||||
% type(filename).__name__)
|
||||
|
||||
return fsencode, fsdecode
|
||||
|
||||
fsencode, fsdecode = _fscodec()
|
||||
del _fscodec
|
||||
|
||||
|
||||
if sys.version_info[0] == 3:
|
||||
bytes = bytes
|
||||
else:
|
||||
_bytes = bytes
|
||||
|
||||
# the 'bytes' alias in Python2 does not support an encoding argument.
|
||||
|
||||
class bytes(_bytes): # noqa
|
||||
|
||||
def __new__(cls, *args):
|
||||
if len(args) > 1:
|
||||
return _bytes(args[0]).encode(*args[1:])
|
||||
return _bytes(*args)
|
||||
|
||||
|
||||
def maybe_fileno(f):
|
||||
"""Get object fileno, or :const:`None` if not defined."""
|
||||
if isinstance(f, numbers.Integral):
|
||||
return f
|
||||
try:
|
||||
return f.fileno()
|
||||
except FILENO_ERRORS:
|
||||
pass
|
||||
|
||||
|
||||
def get_fdmax(default=None):
|
||||
"""Return the maximum number of open file descriptors
|
||||
on this system.
|
||||
|
||||
:keyword default: Value returned if there's no file
|
||||
descriptor limit.
|
||||
|
||||
"""
|
||||
try:
|
||||
return os.sysconf('SC_OPEN_MAX')
|
||||
except:
|
||||
pass
|
||||
if resource is None: # Windows
|
||||
return default
|
||||
fdmax = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
|
||||
if fdmax == resource.RLIM_INFINITY:
|
||||
return default
|
||||
return fdmax
|
||||
|
||||
|
||||
def uniq(it):
|
||||
"""Return all unique elements in ``it``, preserving order."""
|
||||
seen = set()
|
||||
return (seen.add(obj) or obj for obj in it if obj not in seen)
|
||||
|
||||
|
||||
try:
|
||||
closerange = os.closerange
|
||||
except AttributeError:
|
||||
|
||||
def closerange(fd_low, fd_high): # noqa
|
||||
for fd in reversed(range(fd_low, fd_high)):
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EBADF:
|
||||
raise
|
||||
|
||||
def close_open_fds(keep=None):
|
||||
# must make sure this is 0-inclusive (Issue #celery/1882)
|
||||
keep = list(uniq(sorted(
|
||||
f for f in map(maybe_fileno, keep or []) if f is not None
|
||||
)))
|
||||
maxfd = get_fdmax(default=2048)
|
||||
kL, kH = iter([-1] + keep), iter(keep + [maxfd])
|
||||
for low, high in zip_longest(kL, kH):
|
||||
if low + 1 != high:
|
||||
closerange(low + 1, high)
|
||||
else:
|
||||
def close_open_fds(keep=None): # noqa
|
||||
keep = [maybe_fileno(f)
|
||||
for f in (keep or []) if maybe_fileno(f) is not None]
|
||||
for fd in reversed(range(get_fdmax(default=2048))):
|
||||
if fd not in keep:
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EBADF:
|
||||
raise
|
||||
|
||||
|
||||
def get_errno(exc):
|
||||
""":exc:`socket.error` and :exc:`IOError` first got
|
||||
the ``.errno`` attribute in Py2.7"""
|
||||
try:
|
||||
return exc.errno
|
||||
except AttributeError:
|
||||
try:
|
||||
# e.args = (errno, reason)
|
||||
if isinstance(exc.args, tuple) and len(exc.args) == 2:
|
||||
return exc.args[0]
|
||||
except AttributeError:
|
||||
pass
|
||||
return 0
|
||||
|
||||
try:
|
||||
import _posixsubprocess
|
||||
except ImportError:
|
||||
def spawnv_passfds(path, args, passfds):
|
||||
if sys.platform != 'win32':
|
||||
# when not using _posixsubprocess (on earlier python) and not on
|
||||
# windows, we want to keep stdout/stderr open...
|
||||
passfds = passfds + [
|
||||
maybe_fileno(sys.stdout),
|
||||
maybe_fileno(sys.stderr),
|
||||
]
|
||||
pid = os.fork()
|
||||
if not pid:
|
||||
close_open_fds(keep=sorted(f for f in passfds if f))
|
||||
os.execv(fsencode(path), args)
|
||||
return pid
|
||||
else:
|
||||
def spawnv_passfds(path, args, passfds):
|
||||
passfds = sorted(passfds)
|
||||
errpipe_read, errpipe_write = os.pipe()
|
||||
try:
|
||||
args = [
|
||||
args, [fsencode(path)], True, tuple(passfds), None, None,
|
||||
-1, -1, -1, -1, -1, -1, errpipe_read, errpipe_write,
|
||||
False, False]
|
||||
if sys.version_info >= (3, 9):
|
||||
args.extend((None, None, None, -1)) # group, extra_groups, user, umask
|
||||
args.append(None) # preexec_fn
|
||||
return _posixsubprocess.fork_exec(*args)
|
||||
finally:
|
||||
os.close(errpipe_read)
|
||||
os.close(errpipe_write)
|
||||
|
||||
|
||||
if sys.platform == 'win32':
|
||||
|
||||
def setblocking(handle, blocking):
|
||||
raise NotImplementedError('setblocking not implemented on win32')
|
||||
|
||||
def isblocking(handle):
|
||||
raise NotImplementedError('isblocking not implemented on win32')
|
||||
|
||||
else:
|
||||
from os import O_NONBLOCK
|
||||
from fcntl import fcntl, F_GETFL, F_SETFL
|
||||
|
||||
def isblocking(handle): # noqa
|
||||
return not (fcntl(handle, F_GETFL) & O_NONBLOCK)
|
||||
|
||||
def setblocking(handle, blocking): # noqa
|
||||
flags = fcntl(handle, F_GETFL, 0)
|
||||
fcntl(
|
||||
handle, F_SETFL,
|
||||
flags & (~O_NONBLOCK) if blocking else flags | O_NONBLOCK,
|
||||
)
|
||||
|
||||
|
||||
E_PSUTIL_MISSING = """
|
||||
On Windows, the ability to inspect memory usage requires the psutil library.
|
||||
|
||||
You can install it using pip:
|
||||
|
||||
$ pip install psutil
|
||||
"""
|
||||
|
||||
|
||||
E_RESOURCE_MISSING = """
|
||||
Your platform ({0}) does not seem to have the `resource.getrusage' function.
|
||||
|
||||
Please open an issue so that we can add support for this platform.
|
||||
"""
|
||||
|
||||
|
||||
if sys.platform == 'win32':
|
||||
|
||||
try:
|
||||
import psutil
|
||||
except ImportError: # pragma: no cover
|
||||
psutil = None # noqa
|
||||
|
||||
def mem_rss():
|
||||
# type () -> int
|
||||
if psutil is None:
|
||||
raise ImportError(E_PSUTIL_MISSING.strip())
|
||||
return int(psutil.Process(os.getpid()).memory_info()[0] / 1024.0)
|
||||
|
||||
else:
|
||||
try:
|
||||
from resource import getrusage, RUSAGE_SELF
|
||||
except ImportError: # pragma: no cover
|
||||
getrusage = RUSAGE_SELF = None # noqa
|
||||
|
||||
if 'bsd' in sys.platform or sys.platform == 'darwin':
|
||||
# On BSD platforms :man:`getrusage(2)` ru_maxrss field is in bytes.
|
||||
|
||||
def maxrss_to_kb(v):
|
||||
# type: (SupportsInt) -> int
|
||||
return int(v) / 1024.0
|
||||
|
||||
else:
|
||||
# On Linux it's kilobytes.
|
||||
|
||||
def maxrss_to_kb(v):
|
||||
# type: (SupportsInt) -> int
|
||||
return int(v)
|
||||
|
||||
def mem_rss():
|
||||
# type () -> int
|
||||
if resource is None:
|
||||
raise ImportError(E_RESOURCE_MISSING.strip().format(sys.platform))
|
||||
return maxrss_to_kb(getrusage(RUSAGE_SELF).ru_maxrss)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,422 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import warnings
|
||||
|
||||
from . import process
|
||||
|
||||
__all__ = [] # things are copied from here to __init__.py
|
||||
|
||||
|
||||
W_NO_EXECV = """\
|
||||
force_execv is not supported as the billiard C extension \
|
||||
is not installed\
|
||||
"""
|
||||
|
||||
|
||||
#
|
||||
# Exceptions
|
||||
#
|
||||
|
||||
from .exceptions import ( # noqa
|
||||
ProcessError,
|
||||
BufferTooShort,
|
||||
TimeoutError,
|
||||
AuthenticationError,
|
||||
TimeLimitExceeded,
|
||||
SoftTimeLimitExceeded,
|
||||
WorkerLostError,
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# Base type for contexts
|
||||
#
|
||||
|
||||
class BaseContext(object):
|
||||
|
||||
ProcessError = ProcessError
|
||||
BufferTooShort = BufferTooShort
|
||||
TimeoutError = TimeoutError
|
||||
AuthenticationError = AuthenticationError
|
||||
TimeLimitExceeded = TimeLimitExceeded
|
||||
SoftTimeLimitExceeded = SoftTimeLimitExceeded
|
||||
WorkerLostError = WorkerLostError
|
||||
|
||||
current_process = staticmethod(process.current_process)
|
||||
active_children = staticmethod(process.active_children)
|
||||
|
||||
if hasattr(os, 'cpu_count'):
|
||||
def cpu_count(self):
|
||||
'''Returns the number of CPUs in the system'''
|
||||
num = os.cpu_count()
|
||||
if num is None:
|
||||
raise NotImplementedError('cannot determine number of cpus')
|
||||
else:
|
||||
return num
|
||||
else:
|
||||
def cpu_count(self): # noqa
|
||||
if sys.platform == 'win32':
|
||||
try:
|
||||
num = int(os.environ['NUMBER_OF_PROCESSORS'])
|
||||
except (ValueError, KeyError):
|
||||
num = 0
|
||||
elif 'bsd' in sys.platform or sys.platform == 'darwin':
|
||||
comm = '/sbin/sysctl -n hw.ncpu'
|
||||
if sys.platform == 'darwin':
|
||||
comm = '/usr' + comm
|
||||
try:
|
||||
with os.popen(comm) as p:
|
||||
num = int(p.read())
|
||||
except ValueError:
|
||||
num = 0
|
||||
else:
|
||||
try:
|
||||
num = os.sysconf('SC_NPROCESSORS_ONLN')
|
||||
except (ValueError, OSError, AttributeError):
|
||||
num = 0
|
||||
|
||||
if num >= 1:
|
||||
return num
|
||||
else:
|
||||
raise NotImplementedError('cannot determine number of cpus')
|
||||
|
||||
def Manager(self):
|
||||
'''Returns a manager associated with a running server process
|
||||
|
||||
The managers methods such as `Lock()`, `Condition()` and `Queue()`
|
||||
can be used to create shared objects.
|
||||
'''
|
||||
from .managers import SyncManager
|
||||
m = SyncManager(ctx=self.get_context())
|
||||
m.start()
|
||||
return m
|
||||
|
||||
def Pipe(self, duplex=True, rnonblock=False, wnonblock=False):
|
||||
'''Returns two connection object connected by a pipe'''
|
||||
from .connection import Pipe
|
||||
return Pipe(duplex, rnonblock, wnonblock)
|
||||
|
||||
def Lock(self):
|
||||
'''Returns a non-recursive lock object'''
|
||||
from .synchronize import Lock
|
||||
return Lock(ctx=self.get_context())
|
||||
|
||||
def RLock(self):
|
||||
'''Returns a recursive lock object'''
|
||||
from .synchronize import RLock
|
||||
return RLock(ctx=self.get_context())
|
||||
|
||||
def Condition(self, lock=None):
|
||||
'''Returns a condition object'''
|
||||
from .synchronize import Condition
|
||||
return Condition(lock, ctx=self.get_context())
|
||||
|
||||
def Semaphore(self, value=1):
|
||||
'''Returns a semaphore object'''
|
||||
from .synchronize import Semaphore
|
||||
return Semaphore(value, ctx=self.get_context())
|
||||
|
||||
def BoundedSemaphore(self, value=1):
|
||||
'''Returns a bounded semaphore object'''
|
||||
from .synchronize import BoundedSemaphore
|
||||
return BoundedSemaphore(value, ctx=self.get_context())
|
||||
|
||||
def Event(self):
|
||||
'''Returns an event object'''
|
||||
from .synchronize import Event
|
||||
return Event(ctx=self.get_context())
|
||||
|
||||
def Barrier(self, parties, action=None, timeout=None):
|
||||
'''Returns a barrier object'''
|
||||
from .synchronize import Barrier
|
||||
return Barrier(parties, action, timeout, ctx=self.get_context())
|
||||
|
||||
def Queue(self, maxsize=0):
|
||||
'''Returns a queue object'''
|
||||
from .queues import Queue
|
||||
return Queue(maxsize, ctx=self.get_context())
|
||||
|
||||
def JoinableQueue(self, maxsize=0):
|
||||
'''Returns a queue object'''
|
||||
from .queues import JoinableQueue
|
||||
return JoinableQueue(maxsize, ctx=self.get_context())
|
||||
|
||||
def SimpleQueue(self):
|
||||
'''Returns a queue object'''
|
||||
from .queues import SimpleQueue
|
||||
return SimpleQueue(ctx=self.get_context())
|
||||
|
||||
def Pool(self, processes=None, initializer=None, initargs=(),
|
||||
maxtasksperchild=None, timeout=None, soft_timeout=None,
|
||||
lost_worker_timeout=None, max_restarts=None,
|
||||
max_restart_freq=1, on_process_up=None, on_process_down=None,
|
||||
on_timeout_set=None, on_timeout_cancel=None, threads=True,
|
||||
semaphore=None, putlocks=False, allow_restart=False):
|
||||
'''Returns a process pool object'''
|
||||
from .pool import Pool
|
||||
return Pool(processes, initializer, initargs, maxtasksperchild,
|
||||
timeout, soft_timeout, lost_worker_timeout,
|
||||
max_restarts, max_restart_freq, on_process_up,
|
||||
on_process_down, on_timeout_set, on_timeout_cancel,
|
||||
threads, semaphore, putlocks, allow_restart,
|
||||
context=self.get_context())
|
||||
|
||||
def RawValue(self, typecode_or_type, *args):
|
||||
'''Returns a shared object'''
|
||||
from .sharedctypes import RawValue
|
||||
return RawValue(typecode_or_type, *args)
|
||||
|
||||
def RawArray(self, typecode_or_type, size_or_initializer):
|
||||
'''Returns a shared array'''
|
||||
from .sharedctypes import RawArray
|
||||
return RawArray(typecode_or_type, size_or_initializer)
|
||||
|
||||
def Value(self, typecode_or_type, *args, **kwargs):
|
||||
'''Returns a synchronized shared object'''
|
||||
from .sharedctypes import Value
|
||||
lock = kwargs.get('lock', True)
|
||||
return Value(typecode_or_type, *args, lock=lock,
|
||||
ctx=self.get_context())
|
||||
|
||||
def Array(self, typecode_or_type, size_or_initializer, *args, **kwargs):
|
||||
'''Returns a synchronized shared array'''
|
||||
from .sharedctypes import Array
|
||||
lock = kwargs.get('lock', True)
|
||||
return Array(typecode_or_type, size_or_initializer, lock=lock,
|
||||
ctx=self.get_context())
|
||||
|
||||
def freeze_support(self):
|
||||
'''Check whether this is a fake forked process in a frozen executable.
|
||||
If so then run code specified by commandline and exit.
|
||||
'''
|
||||
if sys.platform == 'win32' and getattr(sys, 'frozen', False):
|
||||
from .spawn import freeze_support
|
||||
freeze_support()
|
||||
|
||||
def get_logger(self):
|
||||
'''Return package logger -- if it does not already exist then
|
||||
it is created.
|
||||
'''
|
||||
from .util import get_logger
|
||||
return get_logger()
|
||||
|
||||
def log_to_stderr(self, level=None):
|
||||
'''Turn on logging and add a handler which prints to stderr'''
|
||||
from .util import log_to_stderr
|
||||
return log_to_stderr(level)
|
||||
|
||||
def allow_connection_pickling(self):
|
||||
'''Install support for sending connections and sockets
|
||||
between processes
|
||||
'''
|
||||
# This is undocumented. In previous versions of multiprocessing
|
||||
# its only effect was to make socket objects inheritable on Windows.
|
||||
from . import connection # noqa
|
||||
|
||||
def set_executable(self, executable):
|
||||
'''Sets the path to a python.exe or pythonw.exe binary used to run
|
||||
child processes instead of sys.executable when using the 'spawn'
|
||||
start method. Useful for people embedding Python.
|
||||
'''
|
||||
from .spawn import set_executable
|
||||
set_executable(executable)
|
||||
|
||||
def set_forkserver_preload(self, module_names):
|
||||
'''Set list of module names to try to load in forkserver process.
|
||||
This is really just a hint.
|
||||
'''
|
||||
from .forkserver import set_forkserver_preload
|
||||
set_forkserver_preload(module_names)
|
||||
|
||||
def get_context(self, method=None):
|
||||
if method is None:
|
||||
return self
|
||||
try:
|
||||
ctx = _concrete_contexts[method]
|
||||
except KeyError:
|
||||
raise ValueError('cannot find context for %r' % method)
|
||||
ctx._check_available()
|
||||
return ctx
|
||||
|
||||
def get_start_method(self, allow_none=False):
|
||||
return self._name
|
||||
|
||||
def set_start_method(self, method=None):
|
||||
raise ValueError('cannot set start method of concrete context')
|
||||
|
||||
def forking_is_enabled(self):
|
||||
# XXX for compatibility with billiard <3.4
|
||||
return (self.get_start_method() or 'fork') == 'fork'
|
||||
|
||||
def forking_enable(self, value):
|
||||
# XXX for compatibility with billiard <3.4
|
||||
if not value:
|
||||
from ._ext import supports_exec
|
||||
if supports_exec:
|
||||
self.set_start_method('spawn', force=True)
|
||||
else:
|
||||
warnings.warn(RuntimeWarning(W_NO_EXECV))
|
||||
|
||||
def _check_available(self):
|
||||
pass
|
||||
|
||||
#
|
||||
# Type of default context -- underlying context can be set at most once
|
||||
#
|
||||
|
||||
|
||||
class Process(process.BaseProcess):
|
||||
_start_method = None
|
||||
|
||||
@staticmethod
|
||||
def _Popen(process_obj):
|
||||
return _default_context.get_context().Process._Popen(process_obj)
|
||||
|
||||
|
||||
class DefaultContext(BaseContext):
|
||||
Process = Process
|
||||
|
||||
def __init__(self, context):
|
||||
self._default_context = context
|
||||
self._actual_context = None
|
||||
|
||||
def get_context(self, method=None):
|
||||
if method is None:
|
||||
if self._actual_context is None:
|
||||
self._actual_context = self._default_context
|
||||
return self._actual_context
|
||||
else:
|
||||
return super(DefaultContext, self).get_context(method)
|
||||
|
||||
def set_start_method(self, method, force=False):
|
||||
if self._actual_context is not None and not force:
|
||||
raise RuntimeError('context has already been set')
|
||||
if method is None and force:
|
||||
self._actual_context = None
|
||||
return
|
||||
self._actual_context = self.get_context(method)
|
||||
|
||||
def get_start_method(self, allow_none=False):
|
||||
if self._actual_context is None:
|
||||
if allow_none:
|
||||
return None
|
||||
self._actual_context = self._default_context
|
||||
return self._actual_context._name
|
||||
|
||||
def get_all_start_methods(self):
|
||||
if sys.platform == 'win32':
|
||||
return ['spawn']
|
||||
else:
|
||||
from . import reduction
|
||||
if reduction.HAVE_SEND_HANDLE:
|
||||
return ['fork', 'spawn', 'forkserver']
|
||||
else:
|
||||
return ['fork', 'spawn']
|
||||
|
||||
DefaultContext.__all__ = list(x for x in dir(DefaultContext) if x[0] != '_')
|
||||
|
||||
#
|
||||
# Context types for fixed start method
|
||||
#
|
||||
|
||||
if sys.platform != 'win32':
|
||||
|
||||
class ForkProcess(process.BaseProcess):
|
||||
_start_method = 'fork'
|
||||
|
||||
@staticmethod
|
||||
def _Popen(process_obj):
|
||||
from .popen_fork import Popen
|
||||
return Popen(process_obj)
|
||||
|
||||
class SpawnProcess(process.BaseProcess):
|
||||
_start_method = 'spawn'
|
||||
|
||||
@staticmethod
|
||||
def _Popen(process_obj):
|
||||
from .popen_spawn_posix import Popen
|
||||
return Popen(process_obj)
|
||||
|
||||
class ForkServerProcess(process.BaseProcess):
|
||||
_start_method = 'forkserver'
|
||||
|
||||
@staticmethod
|
||||
def _Popen(process_obj):
|
||||
from .popen_forkserver import Popen
|
||||
return Popen(process_obj)
|
||||
|
||||
class ForkContext(BaseContext):
|
||||
_name = 'fork'
|
||||
Process = ForkProcess
|
||||
|
||||
class SpawnContext(BaseContext):
|
||||
_name = 'spawn'
|
||||
Process = SpawnProcess
|
||||
|
||||
class ForkServerContext(BaseContext):
|
||||
_name = 'forkserver'
|
||||
Process = ForkServerProcess
|
||||
|
||||
def _check_available(self):
|
||||
from . import reduction
|
||||
if not reduction.HAVE_SEND_HANDLE:
|
||||
raise ValueError('forkserver start method not available')
|
||||
|
||||
_concrete_contexts = {
|
||||
'fork': ForkContext(),
|
||||
'spawn': SpawnContext(),
|
||||
'forkserver': ForkServerContext(),
|
||||
}
|
||||
_default_context = DefaultContext(_concrete_contexts['fork'])
|
||||
|
||||
else:
|
||||
|
||||
class SpawnProcess(process.BaseProcess):
|
||||
_start_method = 'spawn'
|
||||
|
||||
@staticmethod
|
||||
def _Popen(process_obj):
|
||||
from .popen_spawn_win32 import Popen
|
||||
return Popen(process_obj)
|
||||
|
||||
class SpawnContext(BaseContext):
|
||||
_name = 'spawn'
|
||||
Process = SpawnProcess
|
||||
|
||||
_concrete_contexts = {
|
||||
'spawn': SpawnContext(),
|
||||
}
|
||||
_default_context = DefaultContext(_concrete_contexts['spawn'])
|
||||
|
||||
#
|
||||
# Force the start method
|
||||
#
|
||||
|
||||
|
||||
def _force_start_method(method):
|
||||
_default_context._actual_context = _concrete_contexts[method]
|
||||
|
||||
#
|
||||
# Check that the current thread is spawning a child process
|
||||
#
|
||||
|
||||
_tls = threading.local()
|
||||
|
||||
|
||||
def get_spawning_popen():
|
||||
return getattr(_tls, 'spawning_popen', None)
|
||||
|
||||
|
||||
def set_spawning_popen(popen):
|
||||
_tls.spawning_popen = popen
|
||||
|
||||
|
||||
def assert_spawning(obj):
|
||||
if get_spawning_popen() is None:
|
||||
raise RuntimeError(
|
||||
'%s objects should only be shared between processes'
|
||||
' through inheritance' % type(obj).__name__
|
||||
)
|
||||
@@ -0,0 +1,167 @@
|
||||
#
|
||||
# Support for the API of the multiprocessing package using threads
|
||||
#
|
||||
# multiprocessing/dummy/__init__.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# 2. Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
# 3. Neither the name of author nor the names of any contributors may be
|
||||
# used to endorse or promote products derived from this software
|
||||
# without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
# SUCH DAMAGE.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
#
|
||||
# Imports
|
||||
#
|
||||
|
||||
import threading
|
||||
import sys
|
||||
import weakref
|
||||
import array
|
||||
|
||||
from threading import Lock, RLock, Semaphore, BoundedSemaphore
|
||||
from threading import Event
|
||||
|
||||
from billiard.five import Queue
|
||||
|
||||
from billiard.connection import Pipe
|
||||
|
||||
__all__ = [
|
||||
'Process', 'current_process', 'active_children', 'freeze_support',
|
||||
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
|
||||
'Event', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue'
|
||||
]
|
||||
|
||||
|
||||
class DummyProcess(threading.Thread):
|
||||
|
||||
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
|
||||
threading.Thread.__init__(self, group, target, name, args, kwargs)
|
||||
self._pid = None
|
||||
self._children = weakref.WeakKeyDictionary()
|
||||
self._start_called = False
|
||||
self._parent = current_process()
|
||||
|
||||
def start(self):
|
||||
assert self._parent is current_process()
|
||||
self._start_called = True
|
||||
if hasattr(self._parent, '_children'):
|
||||
self._parent._children[self] = None
|
||||
threading.Thread.start(self)
|
||||
|
||||
@property
|
||||
def exitcode(self):
|
||||
if self._start_called and not self.is_alive():
|
||||
return 0
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
try:
|
||||
_Condition = threading._Condition
|
||||
except AttributeError: # Py3
|
||||
_Condition = threading.Condition # noqa
|
||||
|
||||
|
||||
class Condition(_Condition):
|
||||
if sys.version_info[0] == 3:
|
||||
notify_all = _Condition.notifyAll
|
||||
else:
|
||||
notify_all = _Condition.notifyAll.__func__
|
||||
|
||||
|
||||
Process = DummyProcess
|
||||
current_process = threading.current_thread
|
||||
current_process()._children = weakref.WeakKeyDictionary()
|
||||
|
||||
|
||||
def active_children():
|
||||
children = current_process()._children
|
||||
for p in list(children):
|
||||
if not p.is_alive():
|
||||
children.pop(p, None)
|
||||
return list(children)
|
||||
|
||||
|
||||
def freeze_support():
|
||||
pass
|
||||
|
||||
|
||||
class Namespace(object):
|
||||
|
||||
def __init__(self, **kwds):
|
||||
self.__dict__.update(kwds)
|
||||
|
||||
def __repr__(self):
|
||||
items = list(self.__dict__.items())
|
||||
temp = []
|
||||
for name, value in items:
|
||||
if not name.startswith('_'):
|
||||
temp.append('%s=%r' % (name, value))
|
||||
temp.sort()
|
||||
return '%s(%s)' % (self.__class__.__name__, str.join(', ', temp))
|
||||
|
||||
|
||||
dict = dict
|
||||
list = list
|
||||
|
||||
|
||||
def Array(typecode, sequence, lock=True):
|
||||
return array.array(typecode, sequence)
|
||||
|
||||
|
||||
class Value(object):
|
||||
|
||||
def __init__(self, typecode, value, lock=True):
|
||||
self._typecode = typecode
|
||||
self._value = value
|
||||
|
||||
def _get(self):
|
||||
return self._value
|
||||
|
||||
def _set(self, value):
|
||||
self._value = value
|
||||
value = property(_get, _set)
|
||||
|
||||
def __repr__(self):
|
||||
return '<%r(%r, %r)>' % (type(self).__name__,
|
||||
self._typecode, self._value)
|
||||
|
||||
|
||||
def Manager():
|
||||
return sys.modules[__name__]
|
||||
|
||||
|
||||
def shutdown():
|
||||
pass
|
||||
|
||||
|
||||
def Pool(processes=None, initializer=None, initargs=()):
|
||||
from billiard.pool import ThreadPool
|
||||
return ThreadPool(processes, initializer, initargs)
|
||||
|
||||
|
||||
JoinableQueue = Queue
|
||||
@@ -0,0 +1,93 @@
|
||||
#
|
||||
# Analogue of `multiprocessing.connection` which uses queues instead of sockets
|
||||
#
|
||||
# multiprocessing/dummy/connection.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# 2. Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
# 3. Neither the name of author nor the names of any contributors may be
|
||||
# used to endorse or promote products derived from this software
|
||||
# without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
# SUCH DAMAGE.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
from billiard.five import Queue
|
||||
|
||||
__all__ = ['Client', 'Listener', 'Pipe']
|
||||
|
||||
families = [None]
|
||||
|
||||
|
||||
class Listener(object):
|
||||
|
||||
def __init__(self, address=None, family=None, backlog=1):
|
||||
self._backlog_queue = Queue(backlog)
|
||||
|
||||
def accept(self):
|
||||
return Connection(*self._backlog_queue.get())
|
||||
|
||||
def close(self):
|
||||
self._backlog_queue = None
|
||||
|
||||
address = property(lambda self: self._backlog_queue)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc_info):
|
||||
self.close()
|
||||
|
||||
|
||||
def Client(address):
|
||||
_in, _out = Queue(), Queue()
|
||||
address.put((_out, _in))
|
||||
return Connection(_in, _out)
|
||||
|
||||
|
||||
def Pipe(duplex=True):
|
||||
a, b = Queue(), Queue()
|
||||
return Connection(a, b), Connection(b, a)
|
||||
|
||||
|
||||
class Connection(object):
|
||||
|
||||
def __init__(self, _in, _out):
|
||||
self._out = _out
|
||||
self._in = _in
|
||||
self.send = self.send_bytes = _out.put
|
||||
self.recv = self.recv_bytes = _in.get
|
||||
|
||||
def poll(self, timeout=0.0):
|
||||
if self._in.qsize() > 0:
|
||||
return True
|
||||
if timeout <= 0.0:
|
||||
return False
|
||||
self._in.not_empty.acquire()
|
||||
self._in.not_empty.wait(timeout)
|
||||
self._in.not_empty.release()
|
||||
return self._in.qsize() > 0
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
@@ -0,0 +1,135 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
__all__ = ['ExceptionInfo', 'Traceback']
|
||||
|
||||
DEFAULT_MAX_FRAMES = sys.getrecursionlimit() // 8
|
||||
|
||||
|
||||
class _Code(object):
|
||||
|
||||
def __init__(self, code):
|
||||
self.co_filename = code.co_filename
|
||||
self.co_name = code.co_name
|
||||
self.co_argcount = code.co_argcount
|
||||
self.co_cellvars = ()
|
||||
self.co_firstlineno = code.co_firstlineno
|
||||
self.co_flags = code.co_flags
|
||||
self.co_freevars = ()
|
||||
self.co_code = b''
|
||||
self.co_lnotab = b''
|
||||
self.co_names = code.co_names
|
||||
self.co_nlocals = code.co_nlocals
|
||||
self.co_stacksize = code.co_stacksize
|
||||
self.co_varnames = ()
|
||||
|
||||
|
||||
class _Frame(object):
|
||||
Code = _Code
|
||||
|
||||
def __init__(self, frame):
|
||||
self.f_builtins = {}
|
||||
self.f_globals = {
|
||||
"__file__": frame.f_globals.get("__file__", "__main__"),
|
||||
"__name__": frame.f_globals.get("__name__"),
|
||||
"__loader__": None,
|
||||
}
|
||||
self.f_locals = fl = {}
|
||||
try:
|
||||
fl["__traceback_hide__"] = frame.f_locals["__traceback_hide__"]
|
||||
except KeyError:
|
||||
pass
|
||||
self.f_back = None
|
||||
self.f_trace = None
|
||||
self.f_exc_traceback = None
|
||||
self.f_exc_type = None
|
||||
self.f_exc_value = None
|
||||
self.f_code = self.Code(frame.f_code)
|
||||
self.f_lineno = frame.f_lineno
|
||||
self.f_lasti = frame.f_lasti
|
||||
# don't want to hit https://bugs.python.org/issue21967
|
||||
self.f_restricted = False
|
||||
|
||||
|
||||
class _Object(object):
|
||||
|
||||
def __init__(self, **kw):
|
||||
[setattr(self, k, v) for k, v in kw.items()]
|
||||
|
||||
|
||||
class _Truncated(object):
|
||||
|
||||
def __init__(self):
|
||||
self.tb_lineno = -1
|
||||
self.tb_frame = _Object(
|
||||
f_globals={"__file__": "",
|
||||
"__name__": "",
|
||||
"__loader__": None},
|
||||
f_fileno=None,
|
||||
f_code=_Object(co_filename="...",
|
||||
co_name="[rest of traceback truncated]"),
|
||||
)
|
||||
self.tb_next = None
|
||||
self.tb_lasti = 0
|
||||
|
||||
|
||||
class Traceback(object):
|
||||
Frame = _Frame
|
||||
|
||||
def __init__(self, tb, max_frames=DEFAULT_MAX_FRAMES, depth=0):
|
||||
self.tb_frame = self.Frame(tb.tb_frame)
|
||||
self.tb_lineno = tb.tb_lineno
|
||||
self.tb_lasti = tb.tb_lasti
|
||||
self.tb_next = None
|
||||
if tb.tb_next is not None:
|
||||
if depth <= max_frames:
|
||||
self.tb_next = Traceback(tb.tb_next, max_frames, depth + 1)
|
||||
else:
|
||||
self.tb_next = _Truncated()
|
||||
|
||||
|
||||
class ExceptionInfo(object):
|
||||
"""Exception wrapping an exception and its traceback.
|
||||
|
||||
:param exc_info: The exception info tuple as returned by
|
||||
:func:`sys.exc_info`.
|
||||
|
||||
"""
|
||||
|
||||
#: Exception type.
|
||||
type = None
|
||||
|
||||
#: Exception instance.
|
||||
exception = None
|
||||
|
||||
#: Pickleable traceback instance for use with :mod:`traceback`
|
||||
tb = None
|
||||
|
||||
#: String representation of the traceback.
|
||||
traceback = None
|
||||
|
||||
#: Set to true if this is an internal error.
|
||||
internal = False
|
||||
|
||||
def __init__(self, exc_info=None, internal=False):
|
||||
self.type, self.exception, tb = exc_info or sys.exc_info()
|
||||
try:
|
||||
self.tb = Traceback(tb)
|
||||
self.traceback = ''.join(
|
||||
traceback.format_exception(self.type, self.exception, tb),
|
||||
)
|
||||
self.internal = internal
|
||||
finally:
|
||||
del(tb)
|
||||
|
||||
def __str__(self):
|
||||
return self.traceback
|
||||
|
||||
def __repr__(self):
|
||||
return "<%s: %r>" % (self.__class__.__name__, self.exception, )
|
||||
|
||||
@property
|
||||
def exc_info(self):
|
||||
return self.type, self.exception, self.tb
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
try:
|
||||
from multiprocessing import (
|
||||
ProcessError,
|
||||
BufferTooShort,
|
||||
TimeoutError,
|
||||
AuthenticationError,
|
||||
)
|
||||
except ImportError:
|
||||
class ProcessError(Exception): # noqa
|
||||
pass
|
||||
|
||||
class BufferTooShort(ProcessError): # noqa
|
||||
pass
|
||||
|
||||
class TimeoutError(ProcessError): # noqa
|
||||
pass
|
||||
|
||||
class AuthenticationError(ProcessError): # noqa
|
||||
pass
|
||||
|
||||
|
||||
class TimeLimitExceeded(Exception):
|
||||
"""The time limit has been exceeded and the job has been terminated."""
|
||||
|
||||
def __str__(self):
|
||||
return "TimeLimitExceeded%s" % (self.args, )
|
||||
|
||||
|
||||
class SoftTimeLimitExceeded(Exception):
|
||||
"""The soft time limit has been exceeded. This exception is raised
|
||||
to give the task a chance to clean up."""
|
||||
|
||||
def __str__(self):
|
||||
return "SoftTimeLimitExceeded%s" % (self.args, )
|
||||
|
||||
|
||||
class WorkerLostError(Exception):
|
||||
"""The worker processing a job has exited prematurely."""
|
||||
|
||||
|
||||
class Terminated(Exception):
|
||||
"""The worker processing a job has been terminated by user request."""
|
||||
|
||||
|
||||
class RestartFreqExceeded(Exception):
|
||||
"""Restarts too fast."""
|
||||
|
||||
|
||||
class CoroStop(Exception):
|
||||
"""Coroutine exit, as opposed to StopIteration which may
|
||||
mean it should be restarted."""
|
||||
pass
|
||||
@@ -0,0 +1,191 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
celery.five
|
||||
~~~~~~~~~~~
|
||||
|
||||
Compatibility implementations of features
|
||||
only available in newer Python versions.
|
||||
|
||||
|
||||
"""
|
||||
from __future__ import absolute_import
|
||||
|
||||
# ############# py3k #########################################################
|
||||
import sys
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
try:
|
||||
reload = reload # noqa
|
||||
except NameError: # pragma: no cover
|
||||
try:
|
||||
from importlib import reload # noqa
|
||||
except ImportError: # pragma: no cover
|
||||
from imp import reload # noqa
|
||||
|
||||
try:
|
||||
from UserList import UserList # noqa
|
||||
except ImportError: # pragma: no cover
|
||||
from collections import UserList # noqa
|
||||
|
||||
try:
|
||||
from UserDict import UserDict # noqa
|
||||
except ImportError: # pragma: no cover
|
||||
from collections import UserDict # noqa
|
||||
|
||||
# ############# time.monotonic ###############################################
|
||||
|
||||
if sys.version_info < (3, 3):
|
||||
|
||||
import platform
|
||||
SYSTEM = platform.system()
|
||||
|
||||
try:
|
||||
import ctypes
|
||||
except ImportError: # pragma: no cover
|
||||
ctypes = None # noqa
|
||||
|
||||
if SYSTEM == 'Darwin' and ctypes is not None:
|
||||
from ctypes.util import find_library
|
||||
libSystem = ctypes.CDLL(find_library('libSystem.dylib'))
|
||||
CoreServices = ctypes.CDLL(find_library('CoreServices'),
|
||||
use_errno=True)
|
||||
mach_absolute_time = libSystem.mach_absolute_time
|
||||
mach_absolute_time.restype = ctypes.c_uint64
|
||||
absolute_to_nanoseconds = CoreServices.AbsoluteToNanoseconds
|
||||
absolute_to_nanoseconds.restype = ctypes.c_uint64
|
||||
absolute_to_nanoseconds.argtypes = [ctypes.c_uint64]
|
||||
|
||||
def _monotonic():
|
||||
return absolute_to_nanoseconds(mach_absolute_time()) * 1e-9
|
||||
|
||||
elif SYSTEM == 'Linux' and ctypes is not None:
|
||||
# from stackoverflow:
|
||||
# questions/1205722/how-do-i-get-monotonic-time-durations-in-python
|
||||
import ctypes
|
||||
import os
|
||||
|
||||
CLOCK_MONOTONIC = 1 # see <linux/time.h>
|
||||
|
||||
class timespec(ctypes.Structure):
|
||||
_fields_ = [
|
||||
('tv_sec', ctypes.c_long),
|
||||
('tv_nsec', ctypes.c_long),
|
||||
]
|
||||
|
||||
librt = ctypes.CDLL('librt.so.1', use_errno=True)
|
||||
clock_gettime = librt.clock_gettime
|
||||
clock_gettime.argtypes = [
|
||||
ctypes.c_int, ctypes.POINTER(timespec),
|
||||
]
|
||||
|
||||
def _monotonic(): # noqa
|
||||
t = timespec()
|
||||
if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(t)) != 0:
|
||||
errno_ = ctypes.get_errno()
|
||||
raise OSError(errno_, os.strerror(errno_))
|
||||
return t.tv_sec + t.tv_nsec * 1e-9
|
||||
else:
|
||||
from time import time as _monotonic
|
||||
|
||||
try:
|
||||
from time import monotonic
|
||||
except ImportError:
|
||||
monotonic = _monotonic # noqa
|
||||
|
||||
if PY3:
|
||||
import builtins
|
||||
|
||||
from queue import Queue, Empty, Full
|
||||
from itertools import zip_longest
|
||||
from io import StringIO, BytesIO
|
||||
|
||||
map = map
|
||||
string = str
|
||||
string_t = str
|
||||
long_t = int
|
||||
text_t = str
|
||||
range = range
|
||||
int_types = (int, )
|
||||
|
||||
def items(d):
|
||||
return d.items()
|
||||
|
||||
def keys(d):
|
||||
return d.keys()
|
||||
|
||||
def values(d):
|
||||
return d.values()
|
||||
|
||||
def nextfun(it):
|
||||
return it.__next__
|
||||
|
||||
exec_ = getattr(builtins, 'exec')
|
||||
|
||||
def reraise(tp, value, tb=None):
|
||||
if value.__traceback__ is not tb:
|
||||
raise value.with_traceback(tb)
|
||||
raise value
|
||||
|
||||
class WhateverIO(StringIO):
|
||||
|
||||
def write(self, data):
|
||||
if isinstance(data, bytes):
|
||||
data = data.encode()
|
||||
StringIO.write(self, data)
|
||||
|
||||
else:
|
||||
import __builtin__ as builtins # noqa
|
||||
from Queue import Queue, Empty, Full # noqa
|
||||
from itertools import imap as map, izip_longest as zip_longest # noqa
|
||||
from StringIO import StringIO # noqa
|
||||
string = unicode # noqa
|
||||
string_t = basestring # noqa
|
||||
text_t = unicode
|
||||
long_t = long # noqa
|
||||
range = xrange
|
||||
int_types = (int, long)
|
||||
|
||||
def items(d): # noqa
|
||||
return d.iteritems()
|
||||
|
||||
def keys(d): # noqa
|
||||
return d.iterkeys()
|
||||
|
||||
def values(d): # noqa
|
||||
return d.itervalues()
|
||||
|
||||
def nextfun(it): # noqa
|
||||
return it.next
|
||||
|
||||
def exec_(code, globs=None, locs=None):
|
||||
"""Execute code in a namespace."""
|
||||
if globs is None:
|
||||
frame = sys._getframe(1)
|
||||
globs = frame.f_globals
|
||||
if locs is None:
|
||||
locs = frame.f_locals
|
||||
del frame
|
||||
elif locs is None:
|
||||
locs = globs
|
||||
exec("""exec code in globs, locs""")
|
||||
|
||||
exec_("""def reraise(tp, value, tb=None): raise tp, value, tb""")
|
||||
|
||||
BytesIO = WhateverIO = StringIO # noqa
|
||||
|
||||
|
||||
def with_metaclass(Type, skip_attrs=set(['__dict__', '__weakref__'])):
|
||||
"""Class decorator to set metaclass.
|
||||
|
||||
Works with both Python 2 and Python 3 and it does not add
|
||||
an extra class in the lookup order like ``six.with_metaclass`` does
|
||||
(that is -- it copies the original class instead of using inheritance).
|
||||
|
||||
"""
|
||||
|
||||
def _clone_with_metaclass(Class):
|
||||
attrs = dict((key, value) for key, value in items(vars(Class))
|
||||
if key not in skip_attrs)
|
||||
return Type(Class.__name__, Class.__bases__, attrs)
|
||||
|
||||
return _clone_with_metaclass
|
||||
@@ -0,0 +1,266 @@
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
import errno
|
||||
import os
|
||||
import selectors
|
||||
import signal
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
|
||||
from . import connection
|
||||
from . import process
|
||||
from . import reduction
|
||||
from . import semaphore_tracker
|
||||
from . import spawn
|
||||
from . import util
|
||||
|
||||
from .compat import spawnv_passfds
|
||||
|
||||
__all__ = ['ensure_running', 'get_inherited_fds', 'connect_to_new_process',
|
||||
'set_forkserver_preload']
|
||||
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
MAXFDS_TO_SEND = 256
|
||||
UNSIGNED_STRUCT = struct.Struct('Q') # large enough for pid_t
|
||||
|
||||
#
|
||||
# Forkserver class
|
||||
#
|
||||
|
||||
|
||||
class ForkServer(object):
|
||||
|
||||
def __init__(self):
|
||||
self._forkserver_address = None
|
||||
self._forkserver_alive_fd = None
|
||||
self._inherited_fds = None
|
||||
self._lock = threading.Lock()
|
||||
self._preload_modules = ['__main__']
|
||||
|
||||
def set_forkserver_preload(self, modules_names):
|
||||
'''Set list of module names to try to load in forkserver process.'''
|
||||
if not all(type(mod) is str for mod in self._preload_modules):
|
||||
raise TypeError('module_names must be a list of strings')
|
||||
self._preload_modules = modules_names
|
||||
|
||||
def get_inherited_fds(self):
|
||||
'''Return list of fds inherited from parent process.
|
||||
|
||||
This returns None if the current process was not started by fork
|
||||
server.
|
||||
'''
|
||||
return self._inherited_fds
|
||||
|
||||
def connect_to_new_process(self, fds):
|
||||
'''Request forkserver to create a child process.
|
||||
|
||||
Returns a pair of fds (status_r, data_w). The calling process can read
|
||||
the child process's pid and (eventually) its returncode from status_r.
|
||||
The calling process should write to data_w the pickled preparation and
|
||||
process data.
|
||||
'''
|
||||
self.ensure_running()
|
||||
if len(fds) + 4 >= MAXFDS_TO_SEND:
|
||||
raise ValueError('too many fds')
|
||||
with socket.socket(socket.AF_UNIX) as client:
|
||||
client.connect(self._forkserver_address)
|
||||
parent_r, child_w = os.pipe()
|
||||
child_r, parent_w = os.pipe()
|
||||
allfds = [child_r, child_w, self._forkserver_alive_fd,
|
||||
semaphore_tracker.getfd()]
|
||||
allfds += fds
|
||||
try:
|
||||
reduction.sendfds(client, allfds)
|
||||
return parent_r, parent_w
|
||||
except:
|
||||
os.close(parent_r)
|
||||
os.close(parent_w)
|
||||
raise
|
||||
finally:
|
||||
os.close(child_r)
|
||||
os.close(child_w)
|
||||
|
||||
def ensure_running(self):
|
||||
'''Make sure that a fork server is running.
|
||||
|
||||
This can be called from any process. Note that usually a child
|
||||
process will just reuse the forkserver started by its parent, so
|
||||
ensure_running() will do nothing.
|
||||
'''
|
||||
with self._lock:
|
||||
semaphore_tracker.ensure_running()
|
||||
if self._forkserver_alive_fd is not None:
|
||||
return
|
||||
|
||||
cmd = ('from billiard.forkserver import main; ' +
|
||||
'main(%d, %d, %r, **%r)')
|
||||
|
||||
if self._preload_modules:
|
||||
desired_keys = {'main_path', 'sys_path'}
|
||||
data = spawn.get_preparation_data('ignore')
|
||||
data = {
|
||||
x: y for (x, y) in data.items() if x in desired_keys
|
||||
}
|
||||
else:
|
||||
data = {}
|
||||
|
||||
with socket.socket(socket.AF_UNIX) as listener:
|
||||
address = connection.arbitrary_address('AF_UNIX')
|
||||
listener.bind(address)
|
||||
os.chmod(address, 0o600)
|
||||
listener.listen()
|
||||
|
||||
# all client processes own the write end of the "alive" pipe;
|
||||
# when they all terminate the read end becomes ready.
|
||||
alive_r, alive_w = os.pipe()
|
||||
try:
|
||||
fds_to_pass = [listener.fileno(), alive_r]
|
||||
cmd %= (listener.fileno(), alive_r, self._preload_modules,
|
||||
data)
|
||||
exe = spawn.get_executable()
|
||||
args = [exe] + util._args_from_interpreter_flags()
|
||||
args += ['-c', cmd]
|
||||
spawnv_passfds(exe, args, fds_to_pass)
|
||||
except:
|
||||
os.close(alive_w)
|
||||
raise
|
||||
finally:
|
||||
os.close(alive_r)
|
||||
self._forkserver_address = address
|
||||
self._forkserver_alive_fd = alive_w
|
||||
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
|
||||
def main(listener_fd, alive_r, preload, main_path=None, sys_path=None):
|
||||
'''Run forkserver.'''
|
||||
if preload:
|
||||
if '__main__' in preload and main_path is not None:
|
||||
process.current_process()._inheriting = True
|
||||
try:
|
||||
spawn.import_main_path(main_path)
|
||||
finally:
|
||||
del process.current_process()._inheriting
|
||||
for modname in preload:
|
||||
try:
|
||||
__import__(modname)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# close sys.stdin
|
||||
if sys.stdin is not None:
|
||||
try:
|
||||
sys.stdin.close()
|
||||
sys.stdin = open(os.devnull)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
|
||||
# ignoring SIGCHLD means no need to reap zombie processes
|
||||
handler = signal.signal(signal.SIGCHLD, signal.SIG_IGN)
|
||||
with socket.socket(socket.AF_UNIX, fileno=listener_fd) as listener, \
|
||||
selectors.DefaultSelector() as selector:
|
||||
_forkserver._forkserver_address = listener.getsockname()
|
||||
selector.register(listener, selectors.EVENT_READ)
|
||||
selector.register(alive_r, selectors.EVENT_READ)
|
||||
|
||||
while True:
|
||||
try:
|
||||
while True:
|
||||
rfds = [key.fileobj for (key, events) in selector.select()]
|
||||
if rfds:
|
||||
break
|
||||
|
||||
if alive_r in rfds:
|
||||
# EOF because no more client processes left
|
||||
assert os.read(alive_r, 1) == b''
|
||||
raise SystemExit
|
||||
|
||||
assert listener in rfds
|
||||
with listener.accept()[0] as s:
|
||||
code = 1
|
||||
if os.fork() == 0:
|
||||
try:
|
||||
_serve_one(s, listener, alive_r, handler)
|
||||
except Exception:
|
||||
sys.excepthook(*sys.exc_info())
|
||||
sys.stderr.flush()
|
||||
finally:
|
||||
os._exit(code)
|
||||
except OSError as e:
|
||||
if e.errno != errno.ECONNABORTED:
|
||||
raise
|
||||
|
||||
|
||||
def __unpack_fds(child_r, child_w, alive, stfd, *inherited):
|
||||
return child_r, child_w, alive, stfd, inherited
|
||||
|
||||
|
||||
def _serve_one(s, listener, alive_r, handler):
|
||||
# close unnecessary stuff and reset SIGCHLD handler
|
||||
listener.close()
|
||||
os.close(alive_r)
|
||||
signal.signal(signal.SIGCHLD, handler)
|
||||
|
||||
# receive fds from parent process
|
||||
fds = reduction.recvfds(s, MAXFDS_TO_SEND + 1)
|
||||
s.close()
|
||||
assert len(fds) <= MAXFDS_TO_SEND
|
||||
|
||||
(child_r, child_w, _forkserver._forkserver_alive_fd,
|
||||
stfd, _forkserver._inherited_fds) = __unpack_fds(*fds)
|
||||
semaphore_tracker._semaphore_tracker._fd = stfd
|
||||
|
||||
# send pid to client processes
|
||||
write_unsigned(child_w, os.getpid())
|
||||
|
||||
# reseed random number generator
|
||||
if 'random' in sys.modules:
|
||||
import random
|
||||
random.seed()
|
||||
|
||||
# run process object received over pipe
|
||||
code = spawn._main(child_r)
|
||||
|
||||
# write the exit code to the pipe
|
||||
write_unsigned(child_w, code)
|
||||
|
||||
#
|
||||
# Read and write unsigned numbers
|
||||
#
|
||||
|
||||
|
||||
def read_unsigned(fd):
|
||||
data = b''
|
||||
length = UNSIGNED_STRUCT.size
|
||||
while len(data) < length:
|
||||
s = os.read(fd, length - len(data))
|
||||
if not s:
|
||||
raise EOFError('unexpected EOF')
|
||||
data += s
|
||||
return UNSIGNED_STRUCT.unpack(data)[0]
|
||||
|
||||
|
||||
def write_unsigned(fd, n):
|
||||
msg = UNSIGNED_STRUCT.pack(n)
|
||||
while msg:
|
||||
nbytes = os.write(fd, msg)
|
||||
if nbytes == 0:
|
||||
raise RuntimeError('should not get here')
|
||||
msg = msg[nbytes:]
|
||||
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
_forkserver = ForkServer()
|
||||
ensure_running = _forkserver.ensure_running
|
||||
get_inherited_fds = _forkserver.get_inherited_fds
|
||||
connect_to_new_process = _forkserver.connect_to_new_process
|
||||
set_forkserver_preload = _forkserver.set_forkserver_preload
|
||||
@@ -0,0 +1,289 @@
|
||||
#
|
||||
# Module which supports allocation of memory from an mmap
|
||||
#
|
||||
# multiprocessing/heap.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import bisect
|
||||
import errno
|
||||
import io
|
||||
import mmap
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import tempfile
|
||||
|
||||
from . import context
|
||||
from . import reduction
|
||||
from . import util
|
||||
|
||||
from ._ext import _billiard, win32
|
||||
|
||||
__all__ = ['BufferWrapper']
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
#
|
||||
# Inheritable class which wraps an mmap, and from which blocks can be allocated
|
||||
#
|
||||
|
||||
if sys.platform == 'win32':
|
||||
|
||||
class Arena(object):
|
||||
|
||||
_rand = tempfile._RandomNameSequence()
|
||||
|
||||
def __init__(self, size):
|
||||
self.size = size
|
||||
for i in range(100):
|
||||
name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
|
||||
buf = mmap.mmap(-1, size, tagname=name)
|
||||
if win32.GetLastError() == 0:
|
||||
break
|
||||
# we have reopened a preexisting map
|
||||
buf.close()
|
||||
else:
|
||||
exc = IOError('Cannot find name for new mmap')
|
||||
exc.errno = errno.EEXIST
|
||||
raise exc
|
||||
self.name = name
|
||||
self.buffer = buf
|
||||
self._state = (self.size, self.name)
|
||||
|
||||
def __getstate__(self):
|
||||
context.assert_spawning(self)
|
||||
return self._state
|
||||
|
||||
def __setstate__(self, state):
|
||||
self.size, self.name = self._state = state
|
||||
self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
|
||||
# XXX Temporarily preventing buildbot failures while determining
|
||||
# XXX the correct long-term fix. See issue #23060
|
||||
# assert win32.GetLastError() == win32.ERROR_ALREADY_EXISTS
|
||||
|
||||
else:
|
||||
|
||||
class Arena(object):
|
||||
|
||||
def __init__(self, size, fd=-1):
|
||||
self.size = size
|
||||
self.fd = fd
|
||||
if fd == -1:
|
||||
if PY3:
|
||||
self.fd, name = tempfile.mkstemp(
|
||||
prefix='pym-%d-' % (os.getpid(),),
|
||||
dir=util.get_temp_dir(),
|
||||
)
|
||||
|
||||
os.unlink(name)
|
||||
util.Finalize(self, os.close, (self.fd,))
|
||||
with io.open(self.fd, 'wb', closefd=False) as f:
|
||||
bs = 1024 * 1024
|
||||
if size >= bs:
|
||||
zeros = b'\0' * bs
|
||||
for _ in range(size // bs):
|
||||
f.write(zeros)
|
||||
del(zeros)
|
||||
f.write(b'\0' * (size % bs))
|
||||
assert f.tell() == size
|
||||
else:
|
||||
name = tempfile.mktemp(
|
||||
prefix='pym-%d-' % (os.getpid(),),
|
||||
dir=util.get_temp_dir(),
|
||||
)
|
||||
self.fd = os.open(
|
||||
name, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o600,
|
||||
)
|
||||
util.Finalize(self, os.close, (self.fd,))
|
||||
os.unlink(name)
|
||||
os.ftruncate(self.fd, size)
|
||||
self.buffer = mmap.mmap(self.fd, self.size)
|
||||
|
||||
def reduce_arena(a):
|
||||
if a.fd == -1:
|
||||
raise ValueError('Arena is unpicklable because'
|
||||
'forking was enabled when it was created')
|
||||
return rebuild_arena, (a.size, reduction.DupFd(a.fd))
|
||||
|
||||
def rebuild_arena(size, dupfd):
|
||||
return Arena(size, dupfd.detach())
|
||||
|
||||
reduction.register(Arena, reduce_arena)
|
||||
|
||||
#
|
||||
# Class allowing allocation of chunks of memory from arenas
|
||||
#
|
||||
|
||||
|
||||
class Heap(object):
|
||||
|
||||
_alignment = 8
|
||||
|
||||
def __init__(self, size=mmap.PAGESIZE):
|
||||
self._lastpid = os.getpid()
|
||||
self._lock = threading.Lock()
|
||||
self._size = size
|
||||
self._lengths = []
|
||||
self._len_to_seq = {}
|
||||
self._start_to_block = {}
|
||||
self._stop_to_block = {}
|
||||
self._allocated_blocks = set()
|
||||
self._arenas = []
|
||||
# list of pending blocks to free - see free() comment below
|
||||
self._pending_free_blocks = []
|
||||
|
||||
@staticmethod
|
||||
def _roundup(n, alignment):
|
||||
# alignment must be a power of 2
|
||||
mask = alignment - 1
|
||||
return (n + mask) & ~mask
|
||||
|
||||
def _malloc(self, size):
|
||||
# returns a large enough block -- it might be much larger
|
||||
i = bisect.bisect_left(self._lengths, size)
|
||||
if i == len(self._lengths):
|
||||
length = self._roundup(max(self._size, size), mmap.PAGESIZE)
|
||||
self._size *= 2
|
||||
util.info('allocating a new mmap of length %d', length)
|
||||
arena = Arena(length)
|
||||
self._arenas.append(arena)
|
||||
return (arena, 0, length)
|
||||
else:
|
||||
length = self._lengths[i]
|
||||
seq = self._len_to_seq[length]
|
||||
block = seq.pop()
|
||||
if not seq:
|
||||
del self._len_to_seq[length], self._lengths[i]
|
||||
|
||||
(arena, start, stop) = block
|
||||
del self._start_to_block[(arena, start)]
|
||||
del self._stop_to_block[(arena, stop)]
|
||||
return block
|
||||
|
||||
def _free(self, block):
|
||||
# free location and try to merge with neighbours
|
||||
(arena, start, stop) = block
|
||||
|
||||
try:
|
||||
prev_block = self._stop_to_block[(arena, start)]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
start, _ = self._absorb(prev_block)
|
||||
|
||||
try:
|
||||
next_block = self._start_to_block[(arena, stop)]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
_, stop = self._absorb(next_block)
|
||||
|
||||
block = (arena, start, stop)
|
||||
length = stop - start
|
||||
|
||||
try:
|
||||
self._len_to_seq[length].append(block)
|
||||
except KeyError:
|
||||
self._len_to_seq[length] = [block]
|
||||
bisect.insort(self._lengths, length)
|
||||
|
||||
self._start_to_block[(arena, start)] = block
|
||||
self._stop_to_block[(arena, stop)] = block
|
||||
|
||||
def _absorb(self, block):
|
||||
# deregister this block so it can be merged with a neighbour
|
||||
(arena, start, stop) = block
|
||||
del self._start_to_block[(arena, start)]
|
||||
del self._stop_to_block[(arena, stop)]
|
||||
|
||||
length = stop - start
|
||||
seq = self._len_to_seq[length]
|
||||
seq.remove(block)
|
||||
if not seq:
|
||||
del self._len_to_seq[length]
|
||||
self._lengths.remove(length)
|
||||
|
||||
return start, stop
|
||||
|
||||
def _free_pending_blocks(self):
|
||||
# Free all the blocks in the pending list - called with the lock held
|
||||
while 1:
|
||||
try:
|
||||
block = self._pending_free_blocks.pop()
|
||||
except IndexError:
|
||||
break
|
||||
self._allocated_blocks.remove(block)
|
||||
self._free(block)
|
||||
|
||||
def free(self, block):
|
||||
# free a block returned by malloc()
|
||||
# Since free() can be called asynchronously by the GC, it could happen
|
||||
# that it's called while self._lock is held: in that case,
|
||||
# self._lock.acquire() would deadlock (issue #12352). To avoid that, a
|
||||
# trylock is used instead, and if the lock can't be acquired
|
||||
# immediately, the block is added to a list of blocks to be freed
|
||||
# synchronously sometimes later from malloc() or free(), by calling
|
||||
# _free_pending_blocks() (appending and retrieving from a list is not
|
||||
# strictly thread-safe but under cPython it's atomic
|
||||
# thanks to the GIL).
|
||||
assert os.getpid() == self._lastpid
|
||||
if not self._lock.acquire(False):
|
||||
# can't acquire the lock right now, add the block to the list of
|
||||
# pending blocks to free
|
||||
self._pending_free_blocks.append(block)
|
||||
else:
|
||||
# we hold the lock
|
||||
try:
|
||||
self._free_pending_blocks()
|
||||
self._allocated_blocks.remove(block)
|
||||
self._free(block)
|
||||
finally:
|
||||
self._lock.release()
|
||||
|
||||
def malloc(self, size):
|
||||
# return a block of right size (possibly rounded up)
|
||||
assert 0 <= size < sys.maxsize
|
||||
if os.getpid() != self._lastpid:
|
||||
self.__init__() # reinitialize after fork
|
||||
with self._lock:
|
||||
self._free_pending_blocks()
|
||||
size = self._roundup(max(size, 1), self._alignment)
|
||||
(arena, start, stop) = self._malloc(size)
|
||||
new_stop = start + size
|
||||
if new_stop < stop:
|
||||
self._free((arena, new_stop, stop))
|
||||
block = (arena, start, new_stop)
|
||||
self._allocated_blocks.add(block)
|
||||
return block
|
||||
|
||||
#
|
||||
# Class representing a chunk of an mmap -- can be inherited
|
||||
#
|
||||
|
||||
|
||||
class BufferWrapper(object):
|
||||
|
||||
_heap = Heap()
|
||||
|
||||
def __init__(self, size):
|
||||
assert 0 <= size < sys.maxsize
|
||||
block = BufferWrapper._heap.malloc(size)
|
||||
self._state = (block, size)
|
||||
util.Finalize(self, BufferWrapper._heap.free, args=(block,))
|
||||
|
||||
def get_address(self):
|
||||
(arena, start, stop), size = self._state
|
||||
address, length = _billiard.address_of_buffer(arena.buffer)
|
||||
assert size <= length
|
||||
return address + start
|
||||
|
||||
def get_size(self):
|
||||
return self._state[1]
|
||||
|
||||
def create_memoryview(self):
|
||||
(arena, start, stop), size = self._state
|
||||
return memoryview(arena.buffer)[start:start + size]
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,91 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import sys
|
||||
import errno
|
||||
|
||||
from .common import TERM_SIGNAL
|
||||
|
||||
__all__ = ['Popen']
|
||||
|
||||
#
|
||||
# Start child process using fork
|
||||
#
|
||||
|
||||
|
||||
class Popen(object):
|
||||
method = 'fork'
|
||||
sentinel = None
|
||||
|
||||
def __init__(self, process_obj):
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
self.returncode = None
|
||||
self._launch(process_obj)
|
||||
|
||||
def duplicate_for_child(self, fd):
|
||||
return fd
|
||||
|
||||
def poll(self, flag=os.WNOHANG):
|
||||
if self.returncode is None:
|
||||
while True:
|
||||
try:
|
||||
pid, sts = os.waitpid(self.pid, flag)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EINTR:
|
||||
continue
|
||||
# Child process not yet created. See #1731717
|
||||
# e.errno == errno.ECHILD == 10
|
||||
return None
|
||||
else:
|
||||
break
|
||||
if pid == self.pid:
|
||||
if os.WIFSIGNALED(sts):
|
||||
self.returncode = -os.WTERMSIG(sts)
|
||||
else:
|
||||
assert os.WIFEXITED(sts)
|
||||
self.returncode = os.WEXITSTATUS(sts)
|
||||
return self.returncode
|
||||
|
||||
def wait(self, timeout=None):
|
||||
if self.returncode is None:
|
||||
if timeout is not None:
|
||||
from .connection import wait
|
||||
if not wait([self.sentinel], timeout):
|
||||
return None
|
||||
# This shouldn't block if wait() returned successfully.
|
||||
return self.poll(os.WNOHANG if timeout == 0.0 else 0)
|
||||
return self.returncode
|
||||
|
||||
def terminate(self):
|
||||
if self.returncode is None:
|
||||
try:
|
||||
os.kill(self.pid, TERM_SIGNAL)
|
||||
except OSError as exc:
|
||||
if getattr(exc, 'errno', None) != errno.ESRCH:
|
||||
if self.wait(timeout=0.1) is None:
|
||||
raise
|
||||
|
||||
def _launch(self, process_obj):
|
||||
code = 1
|
||||
parent_r, child_w = os.pipe()
|
||||
self.pid = os.fork()
|
||||
if self.pid == 0:
|
||||
try:
|
||||
os.close(parent_r)
|
||||
if 'random' in sys.modules:
|
||||
import random
|
||||
random.seed()
|
||||
code = process_obj._bootstrap()
|
||||
finally:
|
||||
os._exit(code)
|
||||
else:
|
||||
os.close(child_w)
|
||||
self.sentinel = parent_r
|
||||
|
||||
def close(self):
|
||||
if self.sentinel is not None:
|
||||
try:
|
||||
os.close(self.sentinel)
|
||||
finally:
|
||||
self.sentinel = None
|
||||
@@ -0,0 +1,70 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
from . import reduction
|
||||
from . import context
|
||||
from . import forkserver
|
||||
from . import popen_fork
|
||||
from . import spawn
|
||||
|
||||
__all__ = ['Popen']
|
||||
|
||||
#
|
||||
# Wrapper for an fd used while launching a process
|
||||
#
|
||||
|
||||
|
||||
class _DupFd(object):
|
||||
|
||||
def __init__(self, ind):
|
||||
self.ind = ind
|
||||
|
||||
def detach(self):
|
||||
return forkserver.get_inherited_fds()[self.ind]
|
||||
|
||||
#
|
||||
# Start child process using a server process
|
||||
#
|
||||
|
||||
|
||||
class Popen(popen_fork.Popen):
|
||||
method = 'forkserver'
|
||||
DupFd = _DupFd
|
||||
|
||||
def __init__(self, process_obj):
|
||||
self._fds = []
|
||||
super(Popen, self).__init__(process_obj)
|
||||
|
||||
def duplicate_for_child(self, fd):
|
||||
self._fds.append(fd)
|
||||
return len(self._fds) - 1
|
||||
|
||||
def _launch(self, process_obj):
|
||||
prep_data = spawn.get_preparation_data(process_obj._name)
|
||||
buf = io.BytesIO()
|
||||
context.set_spawning_popen(self)
|
||||
try:
|
||||
reduction.dump(prep_data, buf)
|
||||
reduction.dump(process_obj, buf)
|
||||
finally:
|
||||
context.set_spawning_popen(None)
|
||||
|
||||
self.sentinel, w = forkserver.connect_to_new_process(self._fds)
|
||||
with io.open(w, 'wb', closefd=True) as f:
|
||||
f.write(buf.getbuffer())
|
||||
self.pid = forkserver.read_unsigned(self.sentinel)
|
||||
|
||||
def poll(self, flag=os.WNOHANG):
|
||||
if self.returncode is None:
|
||||
from .connection import wait
|
||||
timeout = 0 if flag == os.WNOHANG else None
|
||||
if not wait([self.sentinel], timeout):
|
||||
return None
|
||||
try:
|
||||
self.returncode = forkserver.read_unsigned(self.sentinel)
|
||||
except (OSError, EOFError):
|
||||
# The process ended abnormally perhaps because of a signal
|
||||
self.returncode = 255
|
||||
return self.returncode
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
from . import context
|
||||
from . import popen_fork
|
||||
from . import reduction
|
||||
from . import spawn
|
||||
|
||||
from .compat import spawnv_passfds
|
||||
|
||||
__all__ = ['Popen']
|
||||
|
||||
|
||||
#
|
||||
# Wrapper for an fd used while launching a process
|
||||
#
|
||||
|
||||
class _DupFd(object):
|
||||
|
||||
def __init__(self, fd):
|
||||
self.fd = fd
|
||||
|
||||
def detach(self):
|
||||
return self.fd
|
||||
|
||||
#
|
||||
# Start child process using a fresh interpreter
|
||||
#
|
||||
|
||||
|
||||
class Popen(popen_fork.Popen):
|
||||
method = 'spawn'
|
||||
DupFd = _DupFd
|
||||
|
||||
def __init__(self, process_obj):
|
||||
self._fds = []
|
||||
super(Popen, self).__init__(process_obj)
|
||||
|
||||
def duplicate_for_child(self, fd):
|
||||
self._fds.append(fd)
|
||||
return fd
|
||||
|
||||
def _launch(self, process_obj):
|
||||
os.environ["MULTIPROCESSING_FORKING_DISABLE"] = "1"
|
||||
spawn._Django_old_layout_hack__save()
|
||||
from . import semaphore_tracker
|
||||
tracker_fd = semaphore_tracker.getfd()
|
||||
self._fds.append(tracker_fd)
|
||||
prep_data = spawn.get_preparation_data(process_obj._name)
|
||||
fp = io.BytesIO()
|
||||
context.set_spawning_popen(self)
|
||||
try:
|
||||
reduction.dump(prep_data, fp)
|
||||
reduction.dump(process_obj, fp)
|
||||
finally:
|
||||
context.set_spawning_popen(None)
|
||||
|
||||
parent_r = child_w = child_r = parent_w = None
|
||||
try:
|
||||
parent_r, child_w = os.pipe()
|
||||
child_r, parent_w = os.pipe()
|
||||
cmd = spawn.get_command_line(tracker_fd=tracker_fd,
|
||||
pipe_handle=child_r)
|
||||
self._fds.extend([child_r, child_w])
|
||||
self.pid = spawnv_passfds(
|
||||
spawn.get_executable(), cmd, self._fds,
|
||||
)
|
||||
self.sentinel = parent_r
|
||||
with io.open(parent_w, 'wb', closefd=False) as f:
|
||||
f.write(fp.getvalue())
|
||||
finally:
|
||||
for fd in (child_r, child_w, parent_w):
|
||||
if fd is not None:
|
||||
os.close(fd)
|
||||
@@ -0,0 +1,123 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
import os
|
||||
import msvcrt
|
||||
import signal
|
||||
import sys
|
||||
|
||||
from . import context
|
||||
from . import spawn
|
||||
from . import reduction
|
||||
|
||||
from .compat import _winapi
|
||||
|
||||
__all__ = ['Popen']
|
||||
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
TERMINATE = 0x10000
|
||||
WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False))
|
||||
WINSERVICE = sys.executable.lower().endswith("pythonservice.exe")
|
||||
|
||||
#
|
||||
# We define a Popen class similar to the one from subprocess, but
|
||||
# whose constructor takes a process object as its argument.
|
||||
#
|
||||
|
||||
|
||||
if sys.platform == 'win32':
|
||||
try:
|
||||
from _winapi import CreateProcess, GetExitCodeProcess
|
||||
close_thread_handle = _winapi.CloseHandle
|
||||
except ImportError: # Py2.7
|
||||
from _subprocess import CreateProcess, GetExitCodeProcess
|
||||
|
||||
def close_thread_handle(handle):
|
||||
handle.Close()
|
||||
|
||||
|
||||
class Popen(object):
|
||||
'''
|
||||
Start a subprocess to run the code of a process object
|
||||
'''
|
||||
method = 'spawn'
|
||||
sentinel = None
|
||||
|
||||
def __init__(self, process_obj):
|
||||
os.environ["MULTIPROCESSING_FORKING_DISABLE"] = "1"
|
||||
spawn._Django_old_layout_hack__save()
|
||||
prep_data = spawn.get_preparation_data(process_obj._name)
|
||||
|
||||
# read end of pipe will be "stolen" by the child process
|
||||
# -- see spawn_main() in spawn.py.
|
||||
rhandle, whandle = _winapi.CreatePipe(None, 0)
|
||||
wfd = msvcrt.open_osfhandle(whandle, 0)
|
||||
cmd = spawn.get_command_line(parent_pid=os.getpid(),
|
||||
pipe_handle=rhandle)
|
||||
cmd = ' '.join('"%s"' % x for x in cmd)
|
||||
|
||||
with io.open(wfd, 'wb', closefd=True) as to_child:
|
||||
# start process
|
||||
try:
|
||||
hp, ht, pid, tid = CreateProcess(
|
||||
spawn.get_executable(), cmd,
|
||||
None, None, False, 0, None, None, None)
|
||||
close_thread_handle(ht)
|
||||
except:
|
||||
_winapi.CloseHandle(rhandle)
|
||||
raise
|
||||
|
||||
# set attributes of self
|
||||
self.pid = pid
|
||||
self.returncode = None
|
||||
self._handle = hp
|
||||
self.sentinel = int(hp)
|
||||
|
||||
# send information to child
|
||||
context.set_spawning_popen(self)
|
||||
try:
|
||||
reduction.dump(prep_data, to_child)
|
||||
reduction.dump(process_obj, to_child)
|
||||
finally:
|
||||
context.set_spawning_popen(None)
|
||||
|
||||
def close(self):
|
||||
if self.sentinel is not None:
|
||||
try:
|
||||
_winapi.CloseHandle(self.sentinel)
|
||||
finally:
|
||||
self.sentinel = None
|
||||
|
||||
def duplicate_for_child(self, handle):
|
||||
assert self is context.get_spawning_popen()
|
||||
return reduction.duplicate(handle, self.sentinel)
|
||||
|
||||
def wait(self, timeout=None):
|
||||
if self.returncode is None:
|
||||
if timeout is None:
|
||||
msecs = _winapi.INFINITE
|
||||
else:
|
||||
msecs = max(0, int(timeout * 1000 + 0.5))
|
||||
|
||||
res = _winapi.WaitForSingleObject(int(self._handle), msecs)
|
||||
if res == _winapi.WAIT_OBJECT_0:
|
||||
code = GetExitCodeProcess(self._handle)
|
||||
if code == TERMINATE:
|
||||
code = -signal.SIGTERM
|
||||
self.returncode = code
|
||||
|
||||
return self.returncode
|
||||
|
||||
def poll(self):
|
||||
return self.wait(timeout=0)
|
||||
|
||||
def terminate(self):
|
||||
if self.returncode is None:
|
||||
try:
|
||||
_winapi.TerminateProcess(int(self._handle), TERMINATE)
|
||||
except OSError:
|
||||
if self.wait(timeout=1.0) is None:
|
||||
raise
|
||||
@@ -0,0 +1,404 @@
|
||||
#
|
||||
# Module providing the `Process` class which emulates `threading.Thread`
|
||||
#
|
||||
# multiprocessing/process.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
#
|
||||
# Imports
|
||||
#
|
||||
|
||||
import os
|
||||
import sys
|
||||
import signal
|
||||
import itertools
|
||||
import logging
|
||||
import threading
|
||||
from _weakrefset import WeakSet
|
||||
|
||||
from multiprocessing import process as _mproc
|
||||
|
||||
from .five import items, string_t
|
||||
|
||||
try:
|
||||
ORIGINAL_DIR = os.path.abspath(os.getcwd())
|
||||
except OSError:
|
||||
ORIGINAL_DIR = None
|
||||
|
||||
__all__ = ['BaseProcess', 'Process', 'current_process', 'active_children']
|
||||
|
||||
#
|
||||
# Public functions
|
||||
#
|
||||
|
||||
|
||||
def current_process():
|
||||
'''
|
||||
Return process object representing the current process
|
||||
'''
|
||||
return _current_process
|
||||
|
||||
|
||||
def _set_current_process(process):
|
||||
global _current_process
|
||||
_current_process = _mproc._current_process = process
|
||||
|
||||
|
||||
def _cleanup():
|
||||
# check for processes which have finished
|
||||
for p in list(_children):
|
||||
if p._popen.poll() is not None:
|
||||
_children.discard(p)
|
||||
|
||||
|
||||
def _maybe_flush(f):
|
||||
try:
|
||||
f.flush()
|
||||
except (AttributeError, EnvironmentError, NotImplementedError):
|
||||
pass
|
||||
|
||||
|
||||
def active_children(_cleanup=_cleanup):
|
||||
'''
|
||||
Return list of process objects corresponding to live child processes
|
||||
'''
|
||||
try:
|
||||
_cleanup()
|
||||
except TypeError:
|
||||
# called after gc collect so _cleanup does not exist anymore
|
||||
return []
|
||||
return list(_children)
|
||||
|
||||
|
||||
class BaseProcess(object):
|
||||
'''
|
||||
Process objects represent activity that is run in a separate process
|
||||
|
||||
The class is analagous to `threading.Thread`
|
||||
'''
|
||||
|
||||
def _Popen(self):
|
||||
raise NotImplementedError()
|
||||
|
||||
def __init__(self, group=None, target=None, name=None,
|
||||
args=(), kwargs={}, daemon=None, **_kw):
|
||||
assert group is None, 'group argument must be None for now'
|
||||
count = next(_process_counter)
|
||||
self._identity = _current_process._identity + (count, )
|
||||
self._config = _current_process._config.copy()
|
||||
self._parent_pid = os.getpid()
|
||||
self._popen = None
|
||||
self._target = target
|
||||
self._args = tuple(args)
|
||||
self._kwargs = dict(kwargs)
|
||||
self._name = (
|
||||
name or type(self).__name__ + '-' +
|
||||
':'.join(str(i) for i in self._identity)
|
||||
)
|
||||
if daemon is not None:
|
||||
self.daemon = daemon
|
||||
if _dangling is not None:
|
||||
_dangling.add(self)
|
||||
|
||||
self._controlled_termination = False
|
||||
|
||||
def run(self):
|
||||
'''
|
||||
Method to be run in sub-process; can be overridden in sub-class
|
||||
'''
|
||||
if self._target:
|
||||
self._target(*self._args, **self._kwargs)
|
||||
|
||||
def start(self):
|
||||
'''
|
||||
Start child process
|
||||
'''
|
||||
assert self._popen is None, 'cannot start a process twice'
|
||||
assert self._parent_pid == os.getpid(), \
|
||||
'can only start a process object created by current process'
|
||||
_cleanup()
|
||||
self._popen = self._Popen(self)
|
||||
self._sentinel = self._popen.sentinel
|
||||
_children.add(self)
|
||||
|
||||
def close(self):
|
||||
if self._popen is not None:
|
||||
self._popen.close()
|
||||
|
||||
def terminate(self):
|
||||
'''
|
||||
Terminate process; sends SIGTERM signal or uses TerminateProcess()
|
||||
'''
|
||||
self._popen.terminate()
|
||||
|
||||
def terminate_controlled(self):
|
||||
self._controlled_termination = True
|
||||
self.terminate()
|
||||
|
||||
def join(self, timeout=None):
|
||||
'''
|
||||
Wait until child process terminates
|
||||
'''
|
||||
assert self._parent_pid == os.getpid(), 'can only join a child process'
|
||||
assert self._popen is not None, 'can only join a started process'
|
||||
res = self._popen.wait(timeout)
|
||||
if res is not None:
|
||||
_children.discard(self)
|
||||
self.close()
|
||||
|
||||
def is_alive(self):
|
||||
'''
|
||||
Return whether process is alive
|
||||
'''
|
||||
if self is _current_process:
|
||||
return True
|
||||
assert self._parent_pid == os.getpid(), 'can only test a child process'
|
||||
if self._popen is None:
|
||||
return False
|
||||
self._popen.poll()
|
||||
return self._popen.returncode is None
|
||||
|
||||
def _is_alive(self):
|
||||
if self._popen is None:
|
||||
return False
|
||||
return self._popen.poll() is None
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name
|
||||
|
||||
@name.setter
|
||||
def name(self, name): # noqa
|
||||
assert isinstance(name, string_t), 'name must be a string'
|
||||
self._name = name
|
||||
|
||||
@property
|
||||
def daemon(self):
|
||||
'''
|
||||
Return whether process is a daemon
|
||||
'''
|
||||
return self._config.get('daemon', False)
|
||||
|
||||
@daemon.setter # noqa
|
||||
def daemon(self, daemonic):
|
||||
'''
|
||||
Set whether process is a daemon
|
||||
'''
|
||||
assert self._popen is None, 'process has already started'
|
||||
self._config['daemon'] = daemonic
|
||||
|
||||
@property
|
||||
def authkey(self):
|
||||
return self._config['authkey']
|
||||
|
||||
@authkey.setter # noqa
|
||||
def authkey(self, authkey):
|
||||
'''
|
||||
Set authorization key of process
|
||||
'''
|
||||
self._config['authkey'] = AuthenticationString(authkey)
|
||||
|
||||
@property
|
||||
def exitcode(self):
|
||||
'''
|
||||
Return exit code of process or `None` if it has yet to stop
|
||||
'''
|
||||
if self._popen is None:
|
||||
return self._popen
|
||||
return self._popen.poll()
|
||||
|
||||
@property
|
||||
def ident(self):
|
||||
'''
|
||||
Return identifier (PID) of process or `None` if it has yet to start
|
||||
'''
|
||||
if self is _current_process:
|
||||
return os.getpid()
|
||||
else:
|
||||
return self._popen and self._popen.pid
|
||||
|
||||
pid = ident
|
||||
|
||||
@property
|
||||
def sentinel(self):
|
||||
'''
|
||||
Return a file descriptor (Unix) or handle (Windows) suitable for
|
||||
waiting for process termination.
|
||||
'''
|
||||
try:
|
||||
return self._sentinel
|
||||
except AttributeError:
|
||||
raise ValueError("process not started")
|
||||
|
||||
@property
|
||||
def _counter(self):
|
||||
# compat for 2.7
|
||||
return _process_counter
|
||||
|
||||
@property
|
||||
def _children(self):
|
||||
# compat for 2.7
|
||||
return _children
|
||||
|
||||
@property
|
||||
def _authkey(self):
|
||||
# compat for 2.7
|
||||
return self.authkey
|
||||
|
||||
@property
|
||||
def _daemonic(self):
|
||||
# compat for 2.7
|
||||
return self.daemon
|
||||
|
||||
@property
|
||||
def _tempdir(self):
|
||||
# compat for 2.7
|
||||
return self._config.get('tempdir')
|
||||
|
||||
def __repr__(self):
|
||||
if self is _current_process:
|
||||
status = 'started'
|
||||
elif self._parent_pid != os.getpid():
|
||||
status = 'unknown'
|
||||
elif self._popen is None:
|
||||
status = 'initial'
|
||||
else:
|
||||
if self._popen.poll() is not None:
|
||||
status = self.exitcode
|
||||
else:
|
||||
status = 'started'
|
||||
|
||||
if type(status) is int:
|
||||
if status == 0:
|
||||
status = 'stopped'
|
||||
else:
|
||||
status = 'stopped[%s]' % _exitcode_to_name.get(status, status)
|
||||
|
||||
return '<%s(%s, %s%s)>' % (type(self).__name__, self._name,
|
||||
status, self.daemon and ' daemon' or '')
|
||||
|
||||
##
|
||||
|
||||
def _bootstrap(self):
|
||||
from . import util, context
|
||||
global _current_process, _process_counter, _children
|
||||
|
||||
try:
|
||||
if self._start_method is not None:
|
||||
context._force_start_method(self._start_method)
|
||||
_process_counter = itertools.count(1)
|
||||
_children = set()
|
||||
if sys.stdin is not None:
|
||||
try:
|
||||
sys.stdin.close()
|
||||
sys.stdin = open(os.devnull)
|
||||
except (EnvironmentError, OSError, ValueError):
|
||||
pass
|
||||
old_process = _current_process
|
||||
_set_current_process(self)
|
||||
|
||||
# Re-init logging system.
|
||||
# Workaround for https://bugs.python.org/issue6721/#msg140215
|
||||
# Python logging module uses RLock() objects which are broken
|
||||
# after fork. This can result in a deadlock (Celery Issue #496).
|
||||
loggerDict = logging.Logger.manager.loggerDict
|
||||
logger_names = list(loggerDict.keys())
|
||||
logger_names.append(None) # for root logger
|
||||
for name in logger_names:
|
||||
if not name or not isinstance(loggerDict[name],
|
||||
logging.PlaceHolder):
|
||||
for handler in logging.getLogger(name).handlers:
|
||||
handler.createLock()
|
||||
logging._lock = threading.RLock()
|
||||
|
||||
try:
|
||||
util._finalizer_registry.clear()
|
||||
util._run_after_forkers()
|
||||
finally:
|
||||
# delay finalization of the old process object until after
|
||||
# _run_after_forkers() is executed
|
||||
del old_process
|
||||
util.info('child process %s calling self.run()', self.pid)
|
||||
try:
|
||||
self.run()
|
||||
exitcode = 0
|
||||
finally:
|
||||
util._exit_function()
|
||||
except SystemExit as exc:
|
||||
if not exc.args:
|
||||
exitcode = 1
|
||||
elif isinstance(exc.args[0], int):
|
||||
exitcode = exc.args[0]
|
||||
else:
|
||||
sys.stderr.write(str(exc.args[0]) + '\n')
|
||||
_maybe_flush(sys.stderr)
|
||||
exitcode = 0 if isinstance(exc.args[0], str) else 1
|
||||
except:
|
||||
exitcode = 1
|
||||
if not util.error('Process %s', self.name, exc_info=True):
|
||||
import traceback
|
||||
sys.stderr.write('Process %s:\n' % self.name)
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
util.info('process %s exiting with exitcode %d',
|
||||
self.pid, exitcode)
|
||||
_maybe_flush(sys.stdout)
|
||||
_maybe_flush(sys.stderr)
|
||||
|
||||
return exitcode
|
||||
|
||||
#
|
||||
# We subclass bytes to avoid accidental transmission of auth keys over network
|
||||
#
|
||||
|
||||
|
||||
class AuthenticationString(bytes):
|
||||
|
||||
def __reduce__(self):
|
||||
from .context import get_spawning_popen
|
||||
|
||||
if get_spawning_popen() is None:
|
||||
raise TypeError(
|
||||
'Pickling an AuthenticationString object is '
|
||||
'disallowed for security reasons')
|
||||
return AuthenticationString, (bytes(self),)
|
||||
|
||||
#
|
||||
# Create object representing the main process
|
||||
#
|
||||
|
||||
|
||||
class _MainProcess(BaseProcess):
|
||||
|
||||
def __init__(self):
|
||||
self._identity = ()
|
||||
self._name = 'MainProcess'
|
||||
self._parent_pid = None
|
||||
self._popen = None
|
||||
self._config = {'authkey': AuthenticationString(os.urandom(32)),
|
||||
'semprefix': '/mp'}
|
||||
|
||||
_current_process = _MainProcess()
|
||||
_process_counter = itertools.count(1)
|
||||
_children = set()
|
||||
del _MainProcess
|
||||
|
||||
|
||||
Process = BaseProcess
|
||||
|
||||
#
|
||||
# Give names to some return codes
|
||||
#
|
||||
|
||||
_exitcode_to_name = {}
|
||||
|
||||
for name, signum in items(signal.__dict__):
|
||||
if name[:3] == 'SIG' and '_' not in name:
|
||||
_exitcode_to_name[-signum] = name
|
||||
|
||||
# For debug and leak testing
|
||||
_dangling = WeakSet()
|
||||
@@ -0,0 +1,403 @@
|
||||
#
|
||||
# Module implementing queues
|
||||
#
|
||||
# multiprocessing/queues.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
import os
|
||||
import threading
|
||||
import collections
|
||||
import weakref
|
||||
import errno
|
||||
|
||||
from . import connection
|
||||
from . import context
|
||||
|
||||
from .compat import get_errno
|
||||
from .five import monotonic, Empty, Full
|
||||
from .util import (
|
||||
debug, error, info, Finalize, register_after_fork, is_exiting,
|
||||
)
|
||||
from .reduction import ForkingPickler
|
||||
|
||||
__all__ = ['Queue', 'SimpleQueue', 'JoinableQueue']
|
||||
|
||||
|
||||
class Queue(object):
|
||||
'''
|
||||
Queue type using a pipe, buffer and thread
|
||||
'''
|
||||
def __init__(self, maxsize=0, *args, **kwargs):
|
||||
try:
|
||||
ctx = kwargs['ctx']
|
||||
except KeyError:
|
||||
raise TypeError('missing 1 required keyword-only argument: ctx')
|
||||
if maxsize <= 0:
|
||||
# Can raise ImportError (see issues #3770 and #23400)
|
||||
from .synchronize import SEM_VALUE_MAX as maxsize # noqa
|
||||
self._maxsize = maxsize
|
||||
self._reader, self._writer = connection.Pipe(duplex=False)
|
||||
self._rlock = ctx.Lock()
|
||||
self._opid = os.getpid()
|
||||
if sys.platform == 'win32':
|
||||
self._wlock = None
|
||||
else:
|
||||
self._wlock = ctx.Lock()
|
||||
self._sem = ctx.BoundedSemaphore(maxsize)
|
||||
# For use by concurrent.futures
|
||||
self._ignore_epipe = False
|
||||
|
||||
self._after_fork()
|
||||
|
||||
if sys.platform != 'win32':
|
||||
register_after_fork(self, Queue._after_fork)
|
||||
|
||||
def __getstate__(self):
|
||||
context.assert_spawning(self)
|
||||
return (self._ignore_epipe, self._maxsize, self._reader, self._writer,
|
||||
self._rlock, self._wlock, self._sem, self._opid)
|
||||
|
||||
def __setstate__(self, state):
|
||||
(self._ignore_epipe, self._maxsize, self._reader, self._writer,
|
||||
self._rlock, self._wlock, self._sem, self._opid) = state
|
||||
self._after_fork()
|
||||
|
||||
def _after_fork(self):
|
||||
debug('Queue._after_fork()')
|
||||
self._notempty = threading.Condition(threading.Lock())
|
||||
self._buffer = collections.deque()
|
||||
self._thread = None
|
||||
self._jointhread = None
|
||||
self._joincancelled = False
|
||||
self._closed = False
|
||||
self._close = None
|
||||
self._send_bytes = self._writer.send
|
||||
self._recv = self._reader.recv
|
||||
self._send_bytes = self._writer.send_bytes
|
||||
self._recv_bytes = self._reader.recv_bytes
|
||||
self._poll = self._reader.poll
|
||||
|
||||
def put(self, obj, block=True, timeout=None):
|
||||
assert not self._closed
|
||||
if not self._sem.acquire(block, timeout):
|
||||
raise Full
|
||||
|
||||
with self._notempty:
|
||||
if self._thread is None:
|
||||
self._start_thread()
|
||||
self._buffer.append(obj)
|
||||
self._notempty.notify()
|
||||
|
||||
def get(self, block=True, timeout=None):
|
||||
if block and timeout is None:
|
||||
with self._rlock:
|
||||
res = self._recv_bytes()
|
||||
self._sem.release()
|
||||
|
||||
else:
|
||||
if block:
|
||||
deadline = monotonic() + timeout
|
||||
if not self._rlock.acquire(block, timeout):
|
||||
raise Empty
|
||||
try:
|
||||
if block:
|
||||
timeout = deadline - monotonic()
|
||||
if timeout < 0 or not self._poll(timeout):
|
||||
raise Empty
|
||||
elif not self._poll():
|
||||
raise Empty
|
||||
res = self._recv_bytes()
|
||||
self._sem.release()
|
||||
finally:
|
||||
self._rlock.release()
|
||||
# unserialize the data after having released the lock
|
||||
return ForkingPickler.loads(res)
|
||||
|
||||
def qsize(self):
|
||||
# Raises NotImplementedError on macOS because
|
||||
# of broken sem_getvalue()
|
||||
return self._maxsize - self._sem._semlock._get_value()
|
||||
|
||||
def empty(self):
|
||||
return not self._poll()
|
||||
|
||||
def full(self):
|
||||
return self._sem._semlock._is_zero()
|
||||
|
||||
def get_nowait(self):
|
||||
return self.get(False)
|
||||
|
||||
def put_nowait(self, obj):
|
||||
return self.put(obj, False)
|
||||
|
||||
def close(self):
|
||||
self._closed = True
|
||||
try:
|
||||
self._reader.close()
|
||||
finally:
|
||||
close = self._close
|
||||
if close:
|
||||
self._close = None
|
||||
close()
|
||||
|
||||
def join_thread(self):
|
||||
debug('Queue.join_thread()')
|
||||
assert self._closed
|
||||
if self._jointhread:
|
||||
self._jointhread()
|
||||
|
||||
def cancel_join_thread(self):
|
||||
debug('Queue.cancel_join_thread()')
|
||||
self._joincancelled = True
|
||||
try:
|
||||
self._jointhread.cancel()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def _start_thread(self):
|
||||
debug('Queue._start_thread()')
|
||||
|
||||
# Start thread which transfers data from buffer to pipe
|
||||
self._buffer.clear()
|
||||
self._thread = threading.Thread(
|
||||
target=Queue._feed,
|
||||
args=(self._buffer, self._notempty, self._send_bytes,
|
||||
self._wlock, self._writer.close, self._ignore_epipe),
|
||||
name='QueueFeederThread'
|
||||
)
|
||||
self._thread.daemon = True
|
||||
|
||||
debug('doing self._thread.start()')
|
||||
self._thread.start()
|
||||
debug('... done self._thread.start()')
|
||||
|
||||
# On process exit we will wait for data to be flushed to pipe.
|
||||
#
|
||||
# However, if this process created the queue then all
|
||||
# processes which use the queue will be descendants of this
|
||||
# process. Therefore waiting for the queue to be flushed
|
||||
# is pointless once all the child processes have been joined.
|
||||
created_by_this_process = (self._opid == os.getpid())
|
||||
if not self._joincancelled and not created_by_this_process:
|
||||
self._jointhread = Finalize(
|
||||
self._thread, Queue._finalize_join,
|
||||
[weakref.ref(self._thread)],
|
||||
exitpriority=-5
|
||||
)
|
||||
|
||||
# Send sentinel to the thread queue object when garbage collected
|
||||
self._close = Finalize(
|
||||
self, Queue._finalize_close,
|
||||
[self._buffer, self._notempty],
|
||||
exitpriority=10
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _finalize_join(twr):
|
||||
debug('joining queue thread')
|
||||
thread = twr()
|
||||
if thread is not None:
|
||||
thread.join()
|
||||
debug('... queue thread joined')
|
||||
else:
|
||||
debug('... queue thread already dead')
|
||||
|
||||
@staticmethod
|
||||
def _finalize_close(buffer, notempty):
|
||||
debug('telling queue thread to quit')
|
||||
with notempty:
|
||||
buffer.append(_sentinel)
|
||||
notempty.notify()
|
||||
|
||||
@staticmethod
|
||||
def _feed(buffer, notempty, send_bytes, writelock, close, ignore_epipe):
|
||||
debug('starting thread to feed data to pipe')
|
||||
|
||||
nacquire = notempty.acquire
|
||||
nrelease = notempty.release
|
||||
nwait = notempty.wait
|
||||
bpopleft = buffer.popleft
|
||||
sentinel = _sentinel
|
||||
if sys.platform != 'win32':
|
||||
wacquire = writelock.acquire
|
||||
wrelease = writelock.release
|
||||
else:
|
||||
wacquire = None
|
||||
|
||||
try:
|
||||
while 1:
|
||||
nacquire()
|
||||
try:
|
||||
if not buffer:
|
||||
nwait()
|
||||
finally:
|
||||
nrelease()
|
||||
try:
|
||||
while 1:
|
||||
obj = bpopleft()
|
||||
if obj is sentinel:
|
||||
debug('feeder thread got sentinel -- exiting')
|
||||
close()
|
||||
return
|
||||
|
||||
# serialize the data before acquiring the lock
|
||||
obj = ForkingPickler.dumps(obj)
|
||||
if wacquire is None:
|
||||
send_bytes(obj)
|
||||
else:
|
||||
wacquire()
|
||||
try:
|
||||
send_bytes(obj)
|
||||
finally:
|
||||
wrelease()
|
||||
except IndexError:
|
||||
pass
|
||||
except Exception as exc:
|
||||
if ignore_epipe and get_errno(exc) == errno.EPIPE:
|
||||
return
|
||||
# Since this runs in a daemon thread the resources it uses
|
||||
# may be become unusable while the process is cleaning up.
|
||||
# We ignore errors which happen after the process has
|
||||
# started to cleanup.
|
||||
try:
|
||||
if is_exiting():
|
||||
info('error in queue thread: %r', exc, exc_info=True)
|
||||
else:
|
||||
if not error('error in queue thread: %r', exc,
|
||||
exc_info=True):
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_sentinel = object()
|
||||
|
||||
|
||||
class JoinableQueue(Queue):
|
||||
'''
|
||||
A queue type which also supports join() and task_done() methods
|
||||
|
||||
Note that if you do not call task_done() for each finished task then
|
||||
eventually the counter's semaphore may overflow causing Bad Things
|
||||
to happen.
|
||||
'''
|
||||
|
||||
def __init__(self, maxsize=0, *args, **kwargs):
|
||||
try:
|
||||
ctx = kwargs['ctx']
|
||||
except KeyError:
|
||||
raise TypeError('missing 1 required keyword argument: ctx')
|
||||
Queue.__init__(self, maxsize, ctx=ctx)
|
||||
self._unfinished_tasks = ctx.Semaphore(0)
|
||||
self._cond = ctx.Condition()
|
||||
|
||||
def __getstate__(self):
|
||||
return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks)
|
||||
|
||||
def __setstate__(self, state):
|
||||
Queue.__setstate__(self, state[:-2])
|
||||
self._cond, self._unfinished_tasks = state[-2:]
|
||||
|
||||
def put(self, obj, block=True, timeout=None):
|
||||
assert not self._closed
|
||||
if not self._sem.acquire(block, timeout):
|
||||
raise Full
|
||||
|
||||
with self._notempty:
|
||||
with self._cond:
|
||||
if self._thread is None:
|
||||
self._start_thread()
|
||||
self._buffer.append(obj)
|
||||
self._unfinished_tasks.release()
|
||||
self._notempty.notify()
|
||||
|
||||
def task_done(self):
|
||||
with self._cond:
|
||||
if not self._unfinished_tasks.acquire(False):
|
||||
raise ValueError('task_done() called too many times')
|
||||
if self._unfinished_tasks._semlock._is_zero():
|
||||
self._cond.notify_all()
|
||||
|
||||
def join(self):
|
||||
with self._cond:
|
||||
if not self._unfinished_tasks._semlock._is_zero():
|
||||
self._cond.wait()
|
||||
|
||||
|
||||
class _SimpleQueue(object):
|
||||
'''
|
||||
Simplified Queue type -- really just a locked pipe
|
||||
'''
|
||||
|
||||
def __init__(self, rnonblock=False, wnonblock=False, ctx=None):
|
||||
self._reader, self._writer = connection.Pipe(
|
||||
duplex=False, rnonblock=rnonblock, wnonblock=wnonblock,
|
||||
)
|
||||
self._poll = self._reader.poll
|
||||
self._rlock = self._wlock = None
|
||||
|
||||
def empty(self):
|
||||
return not self._poll()
|
||||
|
||||
def __getstate__(self):
|
||||
context.assert_spawning(self)
|
||||
return (self._reader, self._writer, self._rlock, self._wlock)
|
||||
|
||||
def __setstate__(self, state):
|
||||
(self._reader, self._writer, self._rlock, self._wlock) = state
|
||||
|
||||
def get_payload(self):
|
||||
return self._reader.recv_bytes()
|
||||
|
||||
def send_payload(self, value):
|
||||
self._writer.send_bytes(value)
|
||||
|
||||
def get(self):
|
||||
# unserialize the data after having released the lock
|
||||
return ForkingPickler.loads(self.get_payload())
|
||||
|
||||
def put(self, obj):
|
||||
# serialize the data before acquiring the lock
|
||||
self.send_payload(ForkingPickler.dumps(obj))
|
||||
|
||||
def close(self):
|
||||
if self._reader is not None:
|
||||
try:
|
||||
self._reader.close()
|
||||
finally:
|
||||
self._reader = None
|
||||
|
||||
if self._writer is not None:
|
||||
try:
|
||||
self._writer.close()
|
||||
finally:
|
||||
self._writer = None
|
||||
|
||||
|
||||
class SimpleQueue(_SimpleQueue):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
try:
|
||||
ctx = kwargs['ctx']
|
||||
except KeyError:
|
||||
raise TypeError('missing required keyword argument: ctx')
|
||||
self._reader, self._writer = connection.Pipe(duplex=False)
|
||||
self._rlock = ctx.Lock()
|
||||
self._wlock = ctx.Lock() if sys.platform != 'win32' else None
|
||||
|
||||
def get_payload(self):
|
||||
with self._rlock:
|
||||
return self._reader.recv_bytes()
|
||||
|
||||
def send_payload(self, value):
|
||||
if self._wlock is None:
|
||||
# writes to a message oriented win32 pipe are atomic
|
||||
self._writer.send_bytes(value)
|
||||
else:
|
||||
with self._wlock:
|
||||
self._writer.send_bytes(value)
|
||||
@@ -0,0 +1,294 @@
|
||||
#
|
||||
# Module which deals with pickling of objects.
|
||||
#
|
||||
# multiprocessing/reduction.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import functools
|
||||
import io
|
||||
import os
|
||||
import pickle
|
||||
import socket
|
||||
import sys
|
||||
|
||||
from . import context
|
||||
|
||||
__all__ = ['send_handle', 'recv_handle', 'ForkingPickler', 'register', 'dump']
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
|
||||
HAVE_SEND_HANDLE = (sys.platform == 'win32' or
|
||||
(hasattr(socket, 'CMSG_LEN') and
|
||||
hasattr(socket, 'SCM_RIGHTS') and
|
||||
hasattr(socket.socket, 'sendmsg')))
|
||||
|
||||
#
|
||||
# Pickler subclass
|
||||
#
|
||||
|
||||
|
||||
if PY3:
|
||||
import copyreg
|
||||
|
||||
class ForkingPickler(pickle.Pickler):
|
||||
'''Pickler subclass used by multiprocessing.'''
|
||||
_extra_reducers = {}
|
||||
_copyreg_dispatch_table = copyreg.dispatch_table
|
||||
|
||||
def __init__(self, *args):
|
||||
super(ForkingPickler, self).__init__(*args)
|
||||
self.dispatch_table = self._copyreg_dispatch_table.copy()
|
||||
self.dispatch_table.update(self._extra_reducers)
|
||||
|
||||
@classmethod
|
||||
def register(cls, type, reduce):
|
||||
'''Register a reduce function for a type.'''
|
||||
cls._extra_reducers[type] = reduce
|
||||
|
||||
@classmethod
|
||||
def dumps(cls, obj, protocol=None):
|
||||
buf = io.BytesIO()
|
||||
cls(buf, protocol).dump(obj)
|
||||
return buf.getbuffer()
|
||||
|
||||
@classmethod
|
||||
def loadbuf(cls, buf, protocol=None):
|
||||
return cls.loads(buf.getbuffer())
|
||||
|
||||
loads = pickle.loads
|
||||
|
||||
else:
|
||||
|
||||
class ForkingPickler(pickle.Pickler): # noqa
|
||||
'''Pickler subclass used by multiprocessing.'''
|
||||
dispatch = pickle.Pickler.dispatch.copy()
|
||||
|
||||
@classmethod
|
||||
def register(cls, type, reduce):
|
||||
'''Register a reduce function for a type.'''
|
||||
def dispatcher(self, obj):
|
||||
rv = reduce(obj)
|
||||
self.save_reduce(obj=obj, *rv)
|
||||
cls.dispatch[type] = dispatcher
|
||||
|
||||
@classmethod
|
||||
def dumps(cls, obj, protocol=None):
|
||||
buf = io.BytesIO()
|
||||
cls(buf, protocol).dump(obj)
|
||||
return buf.getvalue()
|
||||
|
||||
@classmethod
|
||||
def loadbuf(cls, buf, protocol=None):
|
||||
return cls.loads(buf.getvalue())
|
||||
|
||||
@classmethod
|
||||
def loads(cls, buf, loads=pickle.loads):
|
||||
if isinstance(buf, io.BytesIO):
|
||||
buf = buf.getvalue()
|
||||
return loads(buf)
|
||||
register = ForkingPickler.register
|
||||
|
||||
|
||||
def dump(obj, file, protocol=None):
|
||||
'''Replacement for pickle.dump() using ForkingPickler.'''
|
||||
ForkingPickler(file, protocol).dump(obj)
|
||||
|
||||
#
|
||||
# Platform specific definitions
|
||||
#
|
||||
|
||||
if sys.platform == 'win32':
|
||||
# Windows
|
||||
__all__ += ['DupHandle', 'duplicate', 'steal_handle']
|
||||
from .compat import _winapi
|
||||
|
||||
def duplicate(handle, target_process=None, inheritable=False):
|
||||
'''Duplicate a handle. (target_process is a handle not a pid!)'''
|
||||
if target_process is None:
|
||||
target_process = _winapi.GetCurrentProcess()
|
||||
return _winapi.DuplicateHandle(
|
||||
_winapi.GetCurrentProcess(), handle, target_process,
|
||||
0, inheritable, _winapi.DUPLICATE_SAME_ACCESS)
|
||||
|
||||
def steal_handle(source_pid, handle):
|
||||
'''Steal a handle from process identified by source_pid.'''
|
||||
source_process_handle = _winapi.OpenProcess(
|
||||
_winapi.PROCESS_DUP_HANDLE, False, source_pid)
|
||||
try:
|
||||
return _winapi.DuplicateHandle(
|
||||
source_process_handle, handle,
|
||||
_winapi.GetCurrentProcess(), 0, False,
|
||||
_winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE)
|
||||
finally:
|
||||
_winapi.CloseHandle(source_process_handle)
|
||||
|
||||
def send_handle(conn, handle, destination_pid):
|
||||
'''Send a handle over a local connection.'''
|
||||
dh = DupHandle(handle, _winapi.DUPLICATE_SAME_ACCESS, destination_pid)
|
||||
conn.send(dh)
|
||||
|
||||
def recv_handle(conn):
|
||||
'''Receive a handle over a local connection.'''
|
||||
return conn.recv().detach()
|
||||
|
||||
class DupHandle(object):
|
||||
'''Picklable wrapper for a handle.'''
|
||||
def __init__(self, handle, access, pid=None):
|
||||
if pid is None:
|
||||
# We just duplicate the handle in the current process and
|
||||
# let the receiving process steal the handle.
|
||||
pid = os.getpid()
|
||||
proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid)
|
||||
try:
|
||||
self._handle = _winapi.DuplicateHandle(
|
||||
_winapi.GetCurrentProcess(),
|
||||
handle, proc, access, False, 0)
|
||||
finally:
|
||||
_winapi.CloseHandle(proc)
|
||||
self._access = access
|
||||
self._pid = pid
|
||||
|
||||
def detach(self):
|
||||
'''Get the handle. This should only be called once.'''
|
||||
# retrieve handle from process which currently owns it
|
||||
if self._pid == os.getpid():
|
||||
# The handle has already been duplicated for this process.
|
||||
return self._handle
|
||||
# We must steal the handle from the process whose pid is self._pid.
|
||||
proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False,
|
||||
self._pid)
|
||||
try:
|
||||
return _winapi.DuplicateHandle(
|
||||
proc, self._handle, _winapi.GetCurrentProcess(),
|
||||
self._access, False, _winapi.DUPLICATE_CLOSE_SOURCE)
|
||||
finally:
|
||||
_winapi.CloseHandle(proc)
|
||||
|
||||
else:
|
||||
# Unix
|
||||
__all__ += ['DupFd', 'sendfds', 'recvfds']
|
||||
import array
|
||||
|
||||
# On macOS we should acknowledge receipt of fds -- see Issue14669
|
||||
ACKNOWLEDGE = sys.platform == 'darwin'
|
||||
|
||||
def sendfds(sock, fds):
|
||||
'''Send an array of fds over an AF_UNIX socket.'''
|
||||
fds = array.array('i', fds)
|
||||
msg = bytes([len(fds) % 256])
|
||||
sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
|
||||
if ACKNOWLEDGE and sock.recv(1) != b'A':
|
||||
raise RuntimeError('did not receive acknowledgement of fd')
|
||||
|
||||
def recvfds(sock, size):
|
||||
'''Receive an array of fds over an AF_UNIX socket.'''
|
||||
a = array.array('i')
|
||||
bytes_size = a.itemsize * size
|
||||
msg, ancdata, flags, addr = sock.recvmsg(
|
||||
1, socket.CMSG_LEN(bytes_size),
|
||||
)
|
||||
if not msg and not ancdata:
|
||||
raise EOFError
|
||||
try:
|
||||
if ACKNOWLEDGE:
|
||||
sock.send(b'A')
|
||||
if len(ancdata) != 1:
|
||||
raise RuntimeError(
|
||||
'received %d items of ancdata' % len(ancdata),
|
||||
)
|
||||
cmsg_level, cmsg_type, cmsg_data = ancdata[0]
|
||||
if (cmsg_level == socket.SOL_SOCKET and
|
||||
cmsg_type == socket.SCM_RIGHTS):
|
||||
if len(cmsg_data) % a.itemsize != 0:
|
||||
raise ValueError
|
||||
a.frombytes(cmsg_data)
|
||||
assert len(a) % 256 == msg[0]
|
||||
return list(a)
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
raise RuntimeError('Invalid data received')
|
||||
|
||||
def send_handle(conn, handle, destination_pid): # noqa
|
||||
'''Send a handle over a local connection.'''
|
||||
fd = conn.fileno()
|
||||
with socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) as s:
|
||||
sendfds(s, [handle])
|
||||
|
||||
def recv_handle(conn): # noqa
|
||||
'''Receive a handle over a local connection.'''
|
||||
fd = conn.fileno()
|
||||
with socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) as s:
|
||||
return recvfds(s, 1)[0]
|
||||
|
||||
def DupFd(fd):
|
||||
'''Return a wrapper for an fd.'''
|
||||
popen_obj = context.get_spawning_popen()
|
||||
if popen_obj is not None:
|
||||
return popen_obj.DupFd(popen_obj.duplicate_for_child(fd))
|
||||
elif HAVE_SEND_HANDLE:
|
||||
from . import resource_sharer
|
||||
return resource_sharer.DupFd(fd)
|
||||
else:
|
||||
raise ValueError('SCM_RIGHTS appears not to be available')
|
||||
|
||||
#
|
||||
# Try making some callable types picklable
|
||||
#
|
||||
|
||||
|
||||
def _reduce_method(m):
|
||||
if m.__self__ is None:
|
||||
return getattr, (m.__class__, m.__func__.__name__)
|
||||
else:
|
||||
return getattr, (m.__self__, m.__func__.__name__)
|
||||
|
||||
|
||||
class _C:
|
||||
def f(self):
|
||||
pass
|
||||
register(type(_C().f), _reduce_method)
|
||||
|
||||
|
||||
def _reduce_method_descriptor(m):
|
||||
return getattr, (m.__objclass__, m.__name__)
|
||||
register(type(list.append), _reduce_method_descriptor)
|
||||
register(type(int.__add__), _reduce_method_descriptor)
|
||||
|
||||
|
||||
def _reduce_partial(p):
|
||||
return _rebuild_partial, (p.func, p.args, p.keywords or {})
|
||||
|
||||
|
||||
def _rebuild_partial(func, args, keywords):
|
||||
return functools.partial(func, *args, **keywords)
|
||||
register(functools.partial, _reduce_partial)
|
||||
|
||||
#
|
||||
# Make sockets picklable
|
||||
#
|
||||
|
||||
if sys.platform == 'win32':
|
||||
|
||||
def _reduce_socket(s):
|
||||
from .resource_sharer import DupSocket
|
||||
return _rebuild_socket, (DupSocket(s),)
|
||||
|
||||
def _rebuild_socket(ds):
|
||||
return ds.detach()
|
||||
register(socket.socket, _reduce_socket)
|
||||
|
||||
else:
|
||||
|
||||
def _reduce_socket(s): # noqa
|
||||
df = DupFd(s.fileno())
|
||||
return _rebuild_socket, (df, s.family, s.type, s.proto)
|
||||
|
||||
def _rebuild_socket(df, family, type, proto): # noqa
|
||||
fd = df.detach()
|
||||
return socket.socket(family, type, proto, fileno=fd)
|
||||
register(socket.socket, _reduce_socket)
|
||||
@@ -0,0 +1,163 @@
|
||||
#
|
||||
# We use a background thread for sharing fds on Unix, and for sharing
|
||||
# sockets on Windows.
|
||||
#
|
||||
# A client which wants to pickle a resource registers it with the resource
|
||||
# sharer and gets an identifier in return. The unpickling process will connect
|
||||
# to the resource sharer, sends the identifier and its pid, and then receives
|
||||
# the resource.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
|
||||
from . import process
|
||||
from . import reduction
|
||||
from . import util
|
||||
|
||||
__all__ = ['stop']
|
||||
|
||||
|
||||
if sys.platform == 'win32':
|
||||
__all__ += ['DupSocket']
|
||||
|
||||
class DupSocket(object):
|
||||
'''Picklable wrapper for a socket.'''
|
||||
|
||||
def __init__(self, sock):
|
||||
new_sock = sock.dup()
|
||||
|
||||
def send(conn, pid):
|
||||
share = new_sock.share(pid)
|
||||
conn.send_bytes(share)
|
||||
self._id = _resource_sharer.register(send, new_sock.close)
|
||||
|
||||
def detach(self):
|
||||
'''Get the socket. This should only be called once.'''
|
||||
with _resource_sharer.get_connection(self._id) as conn:
|
||||
share = conn.recv_bytes()
|
||||
return socket.fromshare(share)
|
||||
|
||||
else:
|
||||
__all__ += ['DupFd']
|
||||
|
||||
class DupFd(object):
|
||||
'''Wrapper for fd which can be used at any time.'''
|
||||
def __init__(self, fd):
|
||||
new_fd = os.dup(fd)
|
||||
|
||||
def send(conn, pid):
|
||||
reduction.send_handle(conn, new_fd, pid)
|
||||
|
||||
def close():
|
||||
os.close(new_fd)
|
||||
self._id = _resource_sharer.register(send, close)
|
||||
|
||||
def detach(self):
|
||||
'''Get the fd. This should only be called once.'''
|
||||
with _resource_sharer.get_connection(self._id) as conn:
|
||||
return reduction.recv_handle(conn)
|
||||
|
||||
|
||||
class _ResourceSharer(object):
|
||||
'''Manager for resouces using background thread.'''
|
||||
def __init__(self):
|
||||
self._key = 0
|
||||
self._cache = {}
|
||||
self._old_locks = []
|
||||
self._lock = threading.Lock()
|
||||
self._listener = None
|
||||
self._address = None
|
||||
self._thread = None
|
||||
util.register_after_fork(self, _ResourceSharer._afterfork)
|
||||
|
||||
def register(self, send, close):
|
||||
'''Register resource, returning an identifier.'''
|
||||
with self._lock:
|
||||
if self._address is None:
|
||||
self._start()
|
||||
self._key += 1
|
||||
self._cache[self._key] = (send, close)
|
||||
return (self._address, self._key)
|
||||
|
||||
@staticmethod
|
||||
def get_connection(ident):
|
||||
'''Return connection from which to receive identified resource.'''
|
||||
from .connection import Client
|
||||
address, key = ident
|
||||
c = Client(address, authkey=process.current_process().authkey)
|
||||
c.send((key, os.getpid()))
|
||||
return c
|
||||
|
||||
def stop(self, timeout=None):
|
||||
'''Stop the background thread and clear registered resources.'''
|
||||
from .connection import Client
|
||||
with self._lock:
|
||||
if self._address is not None:
|
||||
c = Client(self._address,
|
||||
authkey=process.current_process().authkey)
|
||||
c.send(None)
|
||||
c.close()
|
||||
self._thread.join(timeout)
|
||||
if self._thread.is_alive():
|
||||
util.sub_warning('_ResourceSharer thread did '
|
||||
'not stop when asked')
|
||||
self._listener.close()
|
||||
self._thread = None
|
||||
self._address = None
|
||||
self._listener = None
|
||||
for key, (send, close) in self._cache.items():
|
||||
close()
|
||||
self._cache.clear()
|
||||
|
||||
def _afterfork(self):
|
||||
for key, (send, close) in self._cache.items():
|
||||
close()
|
||||
self._cache.clear()
|
||||
# If self._lock was locked at the time of the fork, it may be broken
|
||||
# -- see issue 6721. Replace it without letting it be gc'ed.
|
||||
self._old_locks.append(self._lock)
|
||||
self._lock = threading.Lock()
|
||||
if self._listener is not None:
|
||||
self._listener.close()
|
||||
self._listener = None
|
||||
self._address = None
|
||||
self._thread = None
|
||||
|
||||
def _start(self):
|
||||
from .connection import Listener
|
||||
assert self._listener is None
|
||||
util.debug('starting listener and thread for sending handles')
|
||||
self._listener = Listener(authkey=process.current_process().authkey)
|
||||
self._address = self._listener.address
|
||||
t = threading.Thread(target=self._serve)
|
||||
t.daemon = True
|
||||
t.start()
|
||||
self._thread = t
|
||||
|
||||
def _serve(self):
|
||||
if hasattr(signal, 'pthread_sigmask'):
|
||||
signal.pthread_sigmask(signal.SIG_BLOCK, range(1, signal.NSIG))
|
||||
while 1:
|
||||
try:
|
||||
with self._listener.accept() as conn:
|
||||
msg = conn.recv()
|
||||
if msg is None:
|
||||
break
|
||||
key, destination_pid = msg
|
||||
send, close = self._cache.pop(key)
|
||||
try:
|
||||
send(conn, destination_pid)
|
||||
finally:
|
||||
close()
|
||||
except:
|
||||
if not util.is_exiting():
|
||||
sys.excepthook(*sys.exc_info())
|
||||
|
||||
|
||||
_resource_sharer = _ResourceSharer()
|
||||
stop = _resource_sharer.stop
|
||||
@@ -0,0 +1,147 @@
|
||||
#
|
||||
# On Unix we run a server process which keeps track of unlinked
|
||||
# semaphores. The server ignores SIGINT and SIGTERM and reads from a
|
||||
# pipe. Every other process of the program has a copy of the writable
|
||||
# end of the pipe, so we get EOF when all other processes have exited.
|
||||
# Then the server process unlinks any remaining semaphore names.
|
||||
#
|
||||
# This is important because the system only supports a limited number
|
||||
# of named semaphores, and they will not be automatically removed till
|
||||
# the next reboot. Without this semaphore tracker process, "killall
|
||||
# python" would probably leave unlinked semaphores.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
import warnings
|
||||
from ._ext import _billiard
|
||||
|
||||
from . import spawn
|
||||
from . import util
|
||||
|
||||
from .compat import spawnv_passfds
|
||||
|
||||
__all__ = ['ensure_running', 'register', 'unregister']
|
||||
|
||||
|
||||
class SemaphoreTracker(object):
|
||||
|
||||
def __init__(self):
|
||||
self._lock = threading.Lock()
|
||||
self._fd = None
|
||||
|
||||
def getfd(self):
|
||||
self.ensure_running()
|
||||
return self._fd
|
||||
|
||||
def ensure_running(self):
|
||||
'''Make sure that semaphore tracker process is running.
|
||||
|
||||
This can be run from any process. Usually a child process will use
|
||||
the semaphore created by its parent.'''
|
||||
with self._lock:
|
||||
if self._fd is not None:
|
||||
return
|
||||
fds_to_pass = []
|
||||
try:
|
||||
fds_to_pass.append(sys.stderr.fileno())
|
||||
except Exception:
|
||||
pass
|
||||
cmd = 'from billiard.semaphore_tracker import main;main(%d)'
|
||||
r, w = os.pipe()
|
||||
try:
|
||||
fds_to_pass.append(r)
|
||||
# process will out live us, so no need to wait on pid
|
||||
exe = spawn.get_executable()
|
||||
args = [exe] + util._args_from_interpreter_flags()
|
||||
args += ['-c', cmd % r]
|
||||
spawnv_passfds(exe, args, fds_to_pass)
|
||||
except:
|
||||
os.close(w)
|
||||
raise
|
||||
else:
|
||||
self._fd = w
|
||||
finally:
|
||||
os.close(r)
|
||||
|
||||
def register(self, name):
|
||||
'''Register name of semaphore with semaphore tracker.'''
|
||||
self._send('REGISTER', name)
|
||||
|
||||
def unregister(self, name):
|
||||
'''Unregister name of semaphore with semaphore tracker.'''
|
||||
self._send('UNREGISTER', name)
|
||||
|
||||
def _send(self, cmd, name):
|
||||
self.ensure_running()
|
||||
msg = '{0}:{1}\n'.format(cmd, name).encode('ascii')
|
||||
if len(name) > 512:
|
||||
# posix guarantees that writes to a pipe of less than PIPE_BUF
|
||||
# bytes are atomic, and that PIPE_BUF >= 512
|
||||
raise ValueError('name too long')
|
||||
nbytes = os.write(self._fd, msg)
|
||||
assert nbytes == len(msg)
|
||||
|
||||
|
||||
_semaphore_tracker = SemaphoreTracker()
|
||||
ensure_running = _semaphore_tracker.ensure_running
|
||||
register = _semaphore_tracker.register
|
||||
unregister = _semaphore_tracker.unregister
|
||||
getfd = _semaphore_tracker.getfd
|
||||
|
||||
|
||||
def main(fd):
|
||||
'''Run semaphore tracker.'''
|
||||
# protect the process from ^C and "killall python" etc
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
|
||||
for f in (sys.stdin, sys.stdout):
|
||||
try:
|
||||
f.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cache = set()
|
||||
try:
|
||||
# keep track of registered/unregistered semaphores
|
||||
with io.open(fd, 'rb') as f:
|
||||
for line in f:
|
||||
try:
|
||||
cmd, name = line.strip().split(b':')
|
||||
if cmd == b'REGISTER':
|
||||
cache.add(name)
|
||||
elif cmd == b'UNREGISTER':
|
||||
cache.remove(name)
|
||||
else:
|
||||
raise RuntimeError('unrecognized command %r' % cmd)
|
||||
except Exception:
|
||||
try:
|
||||
sys.excepthook(*sys.exc_info())
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
# all processes have terminated; cleanup any remaining semaphores
|
||||
if cache:
|
||||
try:
|
||||
warnings.warn('semaphore_tracker: There appear to be %d '
|
||||
'leaked semaphores to clean up at shutdown' %
|
||||
len(cache))
|
||||
except Exception:
|
||||
pass
|
||||
for name in cache:
|
||||
# For some reason the process which created and registered this
|
||||
# semaphore has failed to unregister it. Presumably it has died.
|
||||
# We therefore unlink it.
|
||||
try:
|
||||
name = name.decode('ascii')
|
||||
try:
|
||||
_billiard.sem_unlink(name)
|
||||
except Exception as e:
|
||||
warnings.warn('semaphore_tracker: %r: %s' % (name, e))
|
||||
finally:
|
||||
pass
|
||||
@@ -0,0 +1,260 @@
|
||||
#
|
||||
# Module which supports allocation of ctypes objects from shared memory
|
||||
#
|
||||
# multiprocessing/sharedctypes.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import ctypes
|
||||
import sys
|
||||
import weakref
|
||||
|
||||
from . import heap
|
||||
from . import get_context
|
||||
from .context import assert_spawning
|
||||
from .five import int_types
|
||||
from .reduction import ForkingPickler
|
||||
|
||||
__all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized']
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
typecode_to_type = {
|
||||
'c': ctypes.c_char, 'u': ctypes.c_wchar,
|
||||
'b': ctypes.c_byte, 'B': ctypes.c_ubyte,
|
||||
'h': ctypes.c_short, 'H': ctypes.c_ushort,
|
||||
'i': ctypes.c_int, 'I': ctypes.c_uint,
|
||||
'l': ctypes.c_long, 'L': ctypes.c_ulong,
|
||||
'f': ctypes.c_float, 'd': ctypes.c_double
|
||||
}
|
||||
|
||||
|
||||
def _new_value(type_):
|
||||
size = ctypes.sizeof(type_)
|
||||
wrapper = heap.BufferWrapper(size)
|
||||
return rebuild_ctype(type_, wrapper, None)
|
||||
|
||||
|
||||
def RawValue(typecode_or_type, *args):
|
||||
'''
|
||||
Returns a ctypes object allocated from shared memory
|
||||
'''
|
||||
type_ = typecode_to_type.get(typecode_or_type, typecode_or_type)
|
||||
obj = _new_value(type_)
|
||||
ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj))
|
||||
obj.__init__(*args)
|
||||
return obj
|
||||
|
||||
|
||||
def RawArray(typecode_or_type, size_or_initializer):
|
||||
'''
|
||||
Returns a ctypes array allocated from shared memory
|
||||
'''
|
||||
type_ = typecode_to_type.get(typecode_or_type, typecode_or_type)
|
||||
if isinstance(size_or_initializer, int_types):
|
||||
type_ = type_ * size_or_initializer
|
||||
obj = _new_value(type_)
|
||||
ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj))
|
||||
return obj
|
||||
else:
|
||||
type_ = type_ * len(size_or_initializer)
|
||||
result = _new_value(type_)
|
||||
result.__init__(*size_or_initializer)
|
||||
return result
|
||||
|
||||
|
||||
def Value(typecode_or_type, *args, **kwds):
|
||||
'''
|
||||
Return a synchronization wrapper for a Value
|
||||
'''
|
||||
lock = kwds.pop('lock', None)
|
||||
ctx = kwds.pop('ctx', None)
|
||||
if kwds:
|
||||
raise ValueError(
|
||||
'unrecognized keyword argument(s): %s' % list(kwds.keys()))
|
||||
obj = RawValue(typecode_or_type, *args)
|
||||
if lock is False:
|
||||
return obj
|
||||
if lock in (True, None):
|
||||
ctx = ctx or get_context()
|
||||
lock = ctx.RLock()
|
||||
if not hasattr(lock, 'acquire'):
|
||||
raise AttributeError("'%r' has no method 'acquire'" % lock)
|
||||
return synchronized(obj, lock, ctx=ctx)
|
||||
|
||||
|
||||
def Array(typecode_or_type, size_or_initializer, **kwds):
|
||||
'''
|
||||
Return a synchronization wrapper for a RawArray
|
||||
'''
|
||||
lock = kwds.pop('lock', None)
|
||||
ctx = kwds.pop('ctx', None)
|
||||
if kwds:
|
||||
raise ValueError(
|
||||
'unrecognized keyword argument(s): %s' % list(kwds.keys()))
|
||||
obj = RawArray(typecode_or_type, size_or_initializer)
|
||||
if lock is False:
|
||||
return obj
|
||||
if lock in (True, None):
|
||||
ctx = ctx or get_context()
|
||||
lock = ctx.RLock()
|
||||
if not hasattr(lock, 'acquire'):
|
||||
raise AttributeError("'%r' has no method 'acquire'" % lock)
|
||||
return synchronized(obj, lock, ctx=ctx)
|
||||
|
||||
|
||||
def copy(obj):
|
||||
new_obj = _new_value(type(obj))
|
||||
ctypes.pointer(new_obj)[0] = obj
|
||||
return new_obj
|
||||
|
||||
|
||||
def synchronized(obj, lock=None, ctx=None):
|
||||
assert not isinstance(obj, SynchronizedBase), 'object already synchronized'
|
||||
ctx = ctx or get_context()
|
||||
|
||||
if isinstance(obj, ctypes._SimpleCData):
|
||||
return Synchronized(obj, lock, ctx)
|
||||
elif isinstance(obj, ctypes.Array):
|
||||
if obj._type_ is ctypes.c_char:
|
||||
return SynchronizedString(obj, lock, ctx)
|
||||
return SynchronizedArray(obj, lock, ctx)
|
||||
else:
|
||||
cls = type(obj)
|
||||
try:
|
||||
scls = class_cache[cls]
|
||||
except KeyError:
|
||||
names = [field[0] for field in cls._fields_]
|
||||
d = dict((name, make_property(name)) for name in names)
|
||||
classname = 'Synchronized' + cls.__name__
|
||||
scls = class_cache[cls] = type(classname, (SynchronizedBase,), d)
|
||||
return scls(obj, lock, ctx)
|
||||
|
||||
#
|
||||
# Functions for pickling/unpickling
|
||||
#
|
||||
|
||||
|
||||
def reduce_ctype(obj):
|
||||
assert_spawning(obj)
|
||||
if isinstance(obj, ctypes.Array):
|
||||
return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_)
|
||||
else:
|
||||
return rebuild_ctype, (type(obj), obj._wrapper, None)
|
||||
|
||||
|
||||
def rebuild_ctype(type_, wrapper, length):
|
||||
if length is not None:
|
||||
type_ = type_ * length
|
||||
ForkingPickler.register(type_, reduce_ctype)
|
||||
if PY3:
|
||||
buf = wrapper.create_memoryview()
|
||||
obj = type_.from_buffer(buf)
|
||||
else:
|
||||
obj = type_.from_address(wrapper.get_address())
|
||||
obj._wrapper = wrapper
|
||||
return obj
|
||||
|
||||
#
|
||||
# Function to create properties
|
||||
#
|
||||
|
||||
|
||||
def make_property(name):
|
||||
try:
|
||||
return prop_cache[name]
|
||||
except KeyError:
|
||||
d = {}
|
||||
exec(template % ((name, ) * 7), d)
|
||||
prop_cache[name] = d[name]
|
||||
return d[name]
|
||||
|
||||
|
||||
template = '''
|
||||
def get%s(self):
|
||||
self.acquire()
|
||||
try:
|
||||
return self._obj.%s
|
||||
finally:
|
||||
self.release()
|
||||
def set%s(self, value):
|
||||
self.acquire()
|
||||
try:
|
||||
self._obj.%s = value
|
||||
finally:
|
||||
self.release()
|
||||
%s = property(get%s, set%s)
|
||||
'''
|
||||
|
||||
prop_cache = {}
|
||||
class_cache = weakref.WeakKeyDictionary()
|
||||
|
||||
#
|
||||
# Synchronized wrappers
|
||||
#
|
||||
|
||||
|
||||
class SynchronizedBase(object):
|
||||
|
||||
def __init__(self, obj, lock=None, ctx=None):
|
||||
self._obj = obj
|
||||
if lock:
|
||||
self._lock = lock
|
||||
else:
|
||||
ctx = ctx or get_context(force=True)
|
||||
self._lock = ctx.RLock()
|
||||
self.acquire = self._lock.acquire
|
||||
self.release = self._lock.release
|
||||
|
||||
def __enter__(self):
|
||||
return self._lock.__enter__()
|
||||
|
||||
def __exit__(self, *args):
|
||||
return self._lock.__exit__(*args)
|
||||
|
||||
def __reduce__(self):
|
||||
assert_spawning(self)
|
||||
return synchronized, (self._obj, self._lock)
|
||||
|
||||
def get_obj(self):
|
||||
return self._obj
|
||||
|
||||
def get_lock(self):
|
||||
return self._lock
|
||||
|
||||
def __repr__(self):
|
||||
return '<%s wrapper for %s>' % (type(self).__name__, self._obj)
|
||||
|
||||
|
||||
class Synchronized(SynchronizedBase):
|
||||
value = make_property('value')
|
||||
|
||||
|
||||
class SynchronizedArray(SynchronizedBase):
|
||||
|
||||
def __len__(self):
|
||||
return len(self._obj)
|
||||
|
||||
def __getitem__(self, i):
|
||||
with self:
|
||||
return self._obj[i]
|
||||
|
||||
def __setitem__(self, i, value):
|
||||
with self:
|
||||
self._obj[i] = value
|
||||
|
||||
def __getslice__(self, start, stop):
|
||||
with self:
|
||||
return self._obj[start:stop]
|
||||
|
||||
def __setslice__(self, start, stop, values):
|
||||
with self:
|
||||
self._obj[start:stop] = values
|
||||
|
||||
|
||||
class SynchronizedString(SynchronizedArray):
|
||||
value = make_property('value')
|
||||
raw = make_property('raw')
|
||||
@@ -0,0 +1,390 @@
|
||||
#
|
||||
# Code used to start processes when using the spawn or forkserver
|
||||
# start methods.
|
||||
#
|
||||
# multiprocessing/spawn.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
import os
|
||||
import pickle
|
||||
import sys
|
||||
import runpy
|
||||
import types
|
||||
import warnings
|
||||
|
||||
from . import get_start_method, set_start_method
|
||||
from . import process
|
||||
from . import util
|
||||
|
||||
__all__ = ['_main', 'freeze_support', 'set_executable', 'get_executable',
|
||||
'get_preparation_data', 'get_command_line', 'import_main_path']
|
||||
|
||||
W_OLD_DJANGO_LAYOUT = """\
|
||||
Will add directory %r to path! This is necessary to accommodate \
|
||||
pre-Django 1.4 layouts using setup_environ.
|
||||
You can skip this warning by adding a DJANGO_SETTINGS_MODULE=settings \
|
||||
environment variable.
|
||||
"""
|
||||
|
||||
#
|
||||
# _python_exe is the assumed path to the python executable.
|
||||
# People embedding Python want to modify it.
|
||||
#
|
||||
|
||||
if sys.platform != 'win32':
|
||||
WINEXE = False
|
||||
WINSERVICE = False
|
||||
else:
|
||||
WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False))
|
||||
WINSERVICE = sys.executable.lower().endswith("pythonservice.exe")
|
||||
|
||||
if WINSERVICE:
|
||||
_python_exe = os.path.join(sys.exec_prefix, 'python.exe')
|
||||
else:
|
||||
_python_exe = sys.executable
|
||||
|
||||
|
||||
def _module_parent_dir(mod):
|
||||
dir, filename = os.path.split(_module_dir(mod))
|
||||
if dir == os.curdir or not dir:
|
||||
dir = os.getcwd()
|
||||
return dir
|
||||
|
||||
|
||||
def _module_dir(mod):
|
||||
if '__init__.py' in mod.__file__:
|
||||
return os.path.dirname(mod.__file__)
|
||||
return mod.__file__
|
||||
|
||||
|
||||
def _Django_old_layout_hack__save():
|
||||
if 'DJANGO_PROJECT_DIR' not in os.environ:
|
||||
try:
|
||||
settings_name = os.environ['DJANGO_SETTINGS_MODULE']
|
||||
except KeyError:
|
||||
return # not using Django.
|
||||
|
||||
conf_settings = sys.modules.get('django.conf.settings')
|
||||
configured = conf_settings and conf_settings.configured
|
||||
try:
|
||||
project_name, _ = settings_name.split('.', 1)
|
||||
except ValueError:
|
||||
return # not modified by setup_environ
|
||||
|
||||
project = __import__(project_name)
|
||||
try:
|
||||
project_dir = os.path.normpath(_module_parent_dir(project))
|
||||
except AttributeError:
|
||||
return # dynamically generated module (no __file__)
|
||||
if configured:
|
||||
warnings.warn(UserWarning(
|
||||
W_OLD_DJANGO_LAYOUT % os.path.realpath(project_dir)
|
||||
))
|
||||
os.environ['DJANGO_PROJECT_DIR'] = project_dir
|
||||
|
||||
|
||||
def _Django_old_layout_hack__load():
|
||||
try:
|
||||
sys.path.append(os.environ['DJANGO_PROJECT_DIR'])
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
|
||||
def set_executable(exe):
|
||||
global _python_exe
|
||||
_python_exe = exe
|
||||
|
||||
|
||||
def get_executable():
|
||||
return _python_exe
|
||||
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
|
||||
def is_forking(argv):
|
||||
'''
|
||||
Return whether commandline indicates we are forking
|
||||
'''
|
||||
if len(argv) >= 2 and argv[1] == '--billiard-fork':
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def freeze_support():
|
||||
'''
|
||||
Run code for process object if this in not the main process
|
||||
'''
|
||||
if is_forking(sys.argv):
|
||||
kwds = {}
|
||||
for arg in sys.argv[2:]:
|
||||
name, value = arg.split('=')
|
||||
if value == 'None':
|
||||
kwds[name] = None
|
||||
else:
|
||||
kwds[name] = int(value)
|
||||
spawn_main(**kwds)
|
||||
sys.exit()
|
||||
|
||||
|
||||
def get_command_line(**kwds):
|
||||
'''
|
||||
Returns prefix of command line used for spawning a child process
|
||||
'''
|
||||
if getattr(sys, 'frozen', False):
|
||||
return ([sys.executable, '--billiard-fork'] +
|
||||
['%s=%r' % item for item in kwds.items()])
|
||||
else:
|
||||
prog = 'from billiard.spawn import spawn_main; spawn_main(%s)'
|
||||
prog %= ', '.join('%s=%r' % item for item in kwds.items())
|
||||
opts = util._args_from_interpreter_flags()
|
||||
return [_python_exe] + opts + ['-c', prog, '--billiard-fork']
|
||||
|
||||
|
||||
def spawn_main(pipe_handle, parent_pid=None, tracker_fd=None):
|
||||
'''
|
||||
Run code specified by data received over pipe
|
||||
'''
|
||||
assert is_forking(sys.argv)
|
||||
if sys.platform == 'win32':
|
||||
import msvcrt
|
||||
from .reduction import steal_handle
|
||||
new_handle = steal_handle(parent_pid, pipe_handle)
|
||||
fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY)
|
||||
else:
|
||||
from . import semaphore_tracker
|
||||
semaphore_tracker._semaphore_tracker._fd = tracker_fd
|
||||
fd = pipe_handle
|
||||
exitcode = _main(fd)
|
||||
sys.exit(exitcode)
|
||||
|
||||
|
||||
def _setup_logging_in_child_hack():
|
||||
# Huge hack to make logging before Process.run work.
|
||||
try:
|
||||
os.environ["MP_MAIN_FILE"] = sys.modules["__main__"].__file__
|
||||
except KeyError:
|
||||
pass
|
||||
except AttributeError:
|
||||
pass
|
||||
loglevel = os.environ.get("_MP_FORK_LOGLEVEL_")
|
||||
logfile = os.environ.get("_MP_FORK_LOGFILE_") or None
|
||||
format = os.environ.get("_MP_FORK_LOGFORMAT_")
|
||||
if loglevel:
|
||||
from . import util
|
||||
import logging
|
||||
logger = util.get_logger()
|
||||
logger.setLevel(int(loglevel))
|
||||
if not logger.handlers:
|
||||
logger._rudimentary_setup = True
|
||||
logfile = logfile or sys.__stderr__
|
||||
if hasattr(logfile, "write"):
|
||||
handler = logging.StreamHandler(logfile)
|
||||
else:
|
||||
handler = logging.FileHandler(logfile)
|
||||
formatter = logging.Formatter(
|
||||
format or util.DEFAULT_LOGGING_FORMAT,
|
||||
)
|
||||
handler.setFormatter(formatter)
|
||||
logger.addHandler(handler)
|
||||
|
||||
|
||||
def _main(fd):
|
||||
_Django_old_layout_hack__load()
|
||||
with io.open(fd, 'rb', closefd=True) as from_parent:
|
||||
process.current_process()._inheriting = True
|
||||
try:
|
||||
preparation_data = pickle.load(from_parent)
|
||||
prepare(preparation_data)
|
||||
_setup_logging_in_child_hack()
|
||||
self = pickle.load(from_parent)
|
||||
finally:
|
||||
del process.current_process()._inheriting
|
||||
return self._bootstrap()
|
||||
|
||||
|
||||
def _check_not_importing_main():
|
||||
if getattr(process.current_process(), '_inheriting', False):
|
||||
raise RuntimeError('''
|
||||
An attempt has been made to start a new process before the
|
||||
current process has finished its bootstrapping phase.
|
||||
|
||||
This probably means that you are not using fork to start your
|
||||
child processes and you have forgotten to use the proper idiom
|
||||
in the main module:
|
||||
|
||||
if __name__ == '__main__':
|
||||
freeze_support()
|
||||
...
|
||||
|
||||
The "freeze_support()" line can be omitted if the program
|
||||
is not going to be frozen to produce an executable.''')
|
||||
|
||||
|
||||
def get_preparation_data(name):
|
||||
'''
|
||||
Return info about parent needed by child to unpickle process object
|
||||
'''
|
||||
_check_not_importing_main()
|
||||
d = dict(
|
||||
log_to_stderr=util._log_to_stderr,
|
||||
authkey=process.current_process().authkey,
|
||||
)
|
||||
|
||||
if util._logger is not None:
|
||||
d['log_level'] = util._logger.getEffectiveLevel()
|
||||
|
||||
sys_path = sys.path[:]
|
||||
try:
|
||||
i = sys_path.index('')
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
sys_path[i] = process.ORIGINAL_DIR
|
||||
|
||||
d.update(
|
||||
name=name,
|
||||
sys_path=sys_path,
|
||||
sys_argv=sys.argv,
|
||||
orig_dir=process.ORIGINAL_DIR,
|
||||
dir=os.getcwd(),
|
||||
start_method=get_start_method(),
|
||||
)
|
||||
|
||||
# Figure out whether to initialise main in the subprocess as a module
|
||||
# or through direct execution (or to leave it alone entirely)
|
||||
main_module = sys.modules['__main__']
|
||||
try:
|
||||
main_mod_name = main_module.__spec__.name
|
||||
except AttributeError:
|
||||
main_mod_name = main_module.__name__
|
||||
if main_mod_name is not None:
|
||||
d['init_main_from_name'] = main_mod_name
|
||||
elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
|
||||
main_path = getattr(main_module, '__file__', None)
|
||||
if main_path is not None:
|
||||
if (not os.path.isabs(main_path) and
|
||||
process.ORIGINAL_DIR is not None):
|
||||
main_path = os.path.join(process.ORIGINAL_DIR, main_path)
|
||||
d['init_main_from_path'] = os.path.normpath(main_path)
|
||||
|
||||
return d
|
||||
|
||||
#
|
||||
# Prepare current process
|
||||
#
|
||||
|
||||
|
||||
old_main_modules = []
|
||||
|
||||
|
||||
def prepare(data):
|
||||
'''
|
||||
Try to get current process ready to unpickle process object
|
||||
'''
|
||||
if 'name' in data:
|
||||
process.current_process().name = data['name']
|
||||
|
||||
if 'authkey' in data:
|
||||
process.current_process().authkey = data['authkey']
|
||||
|
||||
if 'log_to_stderr' in data and data['log_to_stderr']:
|
||||
util.log_to_stderr()
|
||||
|
||||
if 'log_level' in data:
|
||||
util.get_logger().setLevel(data['log_level'])
|
||||
|
||||
if 'sys_path' in data:
|
||||
sys.path = data['sys_path']
|
||||
|
||||
if 'sys_argv' in data:
|
||||
sys.argv = data['sys_argv']
|
||||
|
||||
if 'dir' in data:
|
||||
os.chdir(data['dir'])
|
||||
|
||||
if 'orig_dir' in data:
|
||||
process.ORIGINAL_DIR = data['orig_dir']
|
||||
|
||||
if 'start_method' in data:
|
||||
set_start_method(data['start_method'])
|
||||
|
||||
if 'init_main_from_name' in data:
|
||||
_fixup_main_from_name(data['init_main_from_name'])
|
||||
elif 'init_main_from_path' in data:
|
||||
_fixup_main_from_path(data['init_main_from_path'])
|
||||
|
||||
# Multiprocessing module helpers to fix up the main module in
|
||||
# spawned subprocesses
|
||||
|
||||
|
||||
def _fixup_main_from_name(mod_name):
|
||||
# __main__.py files for packages, directories, zip archives, etc, run
|
||||
# their "main only" code unconditionally, so we don't even try to
|
||||
# populate anything in __main__, nor do we make any changes to
|
||||
# __main__ attributes
|
||||
current_main = sys.modules['__main__']
|
||||
if mod_name == "__main__" or mod_name.endswith(".__main__"):
|
||||
return
|
||||
|
||||
# If this process was forked, __main__ may already be populated
|
||||
try:
|
||||
current_main_name = current_main.__spec__.name
|
||||
except AttributeError:
|
||||
current_main_name = current_main.__name__
|
||||
|
||||
if current_main_name == mod_name:
|
||||
return
|
||||
|
||||
# Otherwise, __main__ may contain some non-main code where we need to
|
||||
# support unpickling it properly. We rerun it as __mp_main__ and make
|
||||
# the normal __main__ an alias to that
|
||||
old_main_modules.append(current_main)
|
||||
main_module = types.ModuleType("__mp_main__")
|
||||
main_content = runpy.run_module(mod_name,
|
||||
run_name="__mp_main__",
|
||||
alter_sys=True)
|
||||
main_module.__dict__.update(main_content)
|
||||
sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
|
||||
|
||||
|
||||
def _fixup_main_from_path(main_path):
|
||||
# If this process was forked, __main__ may already be populated
|
||||
current_main = sys.modules['__main__']
|
||||
|
||||
# Unfortunately, the main ipython launch script historically had no
|
||||
# "if __name__ == '__main__'" guard, so we work around that
|
||||
# by treating it like a __main__.py file
|
||||
# See https://github.com/ipython/ipython/issues/4698
|
||||
main_name = os.path.splitext(os.path.basename(main_path))[0]
|
||||
if main_name == 'ipython':
|
||||
return
|
||||
|
||||
# Otherwise, if __file__ already has the setting we expect,
|
||||
# there's nothing more to do
|
||||
if getattr(current_main, '__file__', None) == main_path:
|
||||
return
|
||||
|
||||
# If the parent process has sent a path through rather than a module
|
||||
# name we assume it is an executable script that may contain
|
||||
# non-main code that needs to be executed
|
||||
old_main_modules.append(current_main)
|
||||
main_module = types.ModuleType("__mp_main__")
|
||||
main_content = runpy.run_path(main_path,
|
||||
run_name="__mp_main__")
|
||||
main_module.__dict__.update(main_content)
|
||||
sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
|
||||
|
||||
|
||||
def import_main_path(main_path):
|
||||
'''
|
||||
Set sys.modules['__main__'] to module at main_path
|
||||
'''
|
||||
_fixup_main_from_path(main_path)
|
||||
@@ -0,0 +1,437 @@
|
||||
#
|
||||
# Module implementing synchronization primitives
|
||||
#
|
||||
# multiprocessing/synchronize.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import errno
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
|
||||
from . import context
|
||||
from . import process
|
||||
from . import util
|
||||
|
||||
from ._ext import _billiard, ensure_SemLock
|
||||
from .five import range, monotonic
|
||||
|
||||
__all__ = [
|
||||
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event',
|
||||
]
|
||||
|
||||
# Try to import the mp.synchronize module cleanly, if it fails
|
||||
# raise ImportError for platforms lacking a working sem_open implementation.
|
||||
# See issue 3770
|
||||
ensure_SemLock()
|
||||
|
||||
#
|
||||
# Constants
|
||||
#
|
||||
|
||||
RECURSIVE_MUTEX, SEMAPHORE = list(range(2))
|
||||
SEM_VALUE_MAX = _billiard.SemLock.SEM_VALUE_MAX
|
||||
|
||||
try:
|
||||
sem_unlink = _billiard.SemLock.sem_unlink
|
||||
except AttributeError: # pragma: no cover
|
||||
try:
|
||||
# Py3.4+ implements sem_unlink and the semaphore must be named
|
||||
from _multiprocessing import sem_unlink # noqa
|
||||
except ImportError:
|
||||
sem_unlink = None # noqa
|
||||
|
||||
#
|
||||
# Base class for semaphores and mutexes; wraps `_billiard.SemLock`
|
||||
#
|
||||
|
||||
|
||||
def _semname(sl):
|
||||
try:
|
||||
return sl.name
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
|
||||
class SemLock(object):
|
||||
_rand = tempfile._RandomNameSequence()
|
||||
|
||||
def __init__(self, kind, value, maxvalue, ctx=None):
|
||||
if ctx is None:
|
||||
ctx = context._default_context.get_context()
|
||||
name = ctx.get_start_method()
|
||||
unlink_now = sys.platform == 'win32' or name == 'fork'
|
||||
if sem_unlink:
|
||||
for i in range(100):
|
||||
try:
|
||||
sl = self._semlock = _billiard.SemLock(
|
||||
kind, value, maxvalue, self._make_name(), unlink_now,
|
||||
)
|
||||
except (OSError, IOError) as exc:
|
||||
if getattr(exc, 'errno', None) != errno.EEXIST:
|
||||
raise
|
||||
else:
|
||||
break
|
||||
else:
|
||||
exc = IOError('cannot find file for semaphore')
|
||||
exc.errno = errno.EEXIST
|
||||
raise exc
|
||||
else:
|
||||
sl = self._semlock = _billiard.SemLock(kind, value, maxvalue)
|
||||
|
||||
util.debug('created semlock with handle %s', sl.handle)
|
||||
self._make_methods()
|
||||
|
||||
if sem_unlink:
|
||||
|
||||
if sys.platform != 'win32':
|
||||
def _after_fork(obj):
|
||||
obj._semlock._after_fork()
|
||||
util.register_after_fork(self, _after_fork)
|
||||
|
||||
if _semname(self._semlock) is not None:
|
||||
# We only get here if we are on Unix with forking
|
||||
# disabled. When the object is garbage collected or the
|
||||
# process shuts down we unlink the semaphore name
|
||||
from .semaphore_tracker import register
|
||||
register(self._semlock.name)
|
||||
util.Finalize(self, SemLock._cleanup, (self._semlock.name,),
|
||||
exitpriority=0)
|
||||
|
||||
@staticmethod
|
||||
def _cleanup(name):
|
||||
from .semaphore_tracker import unregister
|
||||
sem_unlink(name)
|
||||
unregister(name)
|
||||
|
||||
def _make_methods(self):
|
||||
self.acquire = self._semlock.acquire
|
||||
self.release = self._semlock.release
|
||||
|
||||
def __enter__(self):
|
||||
return self._semlock.__enter__()
|
||||
|
||||
def __exit__(self, *args):
|
||||
return self._semlock.__exit__(*args)
|
||||
|
||||
def __getstate__(self):
|
||||
context.assert_spawning(self)
|
||||
sl = self._semlock
|
||||
if sys.platform == 'win32':
|
||||
h = context.get_spawning_popen().duplicate_for_child(sl.handle)
|
||||
else:
|
||||
h = sl.handle
|
||||
state = (h, sl.kind, sl.maxvalue)
|
||||
try:
|
||||
state += (sl.name, )
|
||||
except AttributeError:
|
||||
pass
|
||||
return state
|
||||
|
||||
def __setstate__(self, state):
|
||||
self._semlock = _billiard.SemLock._rebuild(*state)
|
||||
util.debug('recreated blocker with handle %r', state[0])
|
||||
self._make_methods()
|
||||
|
||||
@staticmethod
|
||||
def _make_name():
|
||||
return '%s-%s' % (process.current_process()._config['semprefix'],
|
||||
next(SemLock._rand))
|
||||
|
||||
|
||||
class Semaphore(SemLock):
|
||||
|
||||
def __init__(self, value=1, ctx=None):
|
||||
SemLock.__init__(self, SEMAPHORE, value, SEM_VALUE_MAX, ctx=ctx)
|
||||
|
||||
def get_value(self):
|
||||
return self._semlock._get_value()
|
||||
|
||||
def __repr__(self):
|
||||
try:
|
||||
value = self._semlock._get_value()
|
||||
except Exception:
|
||||
value = 'unknown'
|
||||
return '<%s(value=%s)>' % (self.__class__.__name__, value)
|
||||
|
||||
|
||||
class BoundedSemaphore(Semaphore):
|
||||
|
||||
def __init__(self, value=1, ctx=None):
|
||||
SemLock.__init__(self, SEMAPHORE, value, value, ctx=ctx)
|
||||
|
||||
def __repr__(self):
|
||||
try:
|
||||
value = self._semlock._get_value()
|
||||
except Exception:
|
||||
value = 'unknown'
|
||||
return '<%s(value=%s, maxvalue=%s)>' % (
|
||||
self.__class__.__name__, value, self._semlock.maxvalue)
|
||||
|
||||
|
||||
class Lock(SemLock):
|
||||
'''
|
||||
Non-recursive lock.
|
||||
'''
|
||||
|
||||
def __init__(self, ctx=None):
|
||||
SemLock.__init__(self, SEMAPHORE, 1, 1, ctx=ctx)
|
||||
|
||||
def __repr__(self):
|
||||
try:
|
||||
if self._semlock._is_mine():
|
||||
name = process.current_process().name
|
||||
if threading.current_thread().name != 'MainThread':
|
||||
name += '|' + threading.current_thread().name
|
||||
elif self._semlock._get_value() == 1:
|
||||
name = 'None'
|
||||
elif self._semlock._count() > 0:
|
||||
name = 'SomeOtherThread'
|
||||
else:
|
||||
name = 'SomeOtherProcess'
|
||||
except Exception:
|
||||
name = 'unknown'
|
||||
return '<%s(owner=%s)>' % (self.__class__.__name__, name)
|
||||
|
||||
|
||||
class RLock(SemLock):
|
||||
'''
|
||||
Recursive lock
|
||||
'''
|
||||
|
||||
def __init__(self, ctx=None):
|
||||
SemLock.__init__(self, RECURSIVE_MUTEX, 1, 1, ctx=ctx)
|
||||
|
||||
def __repr__(self):
|
||||
try:
|
||||
if self._semlock._is_mine():
|
||||
name = process.current_process().name
|
||||
if threading.current_thread().name != 'MainThread':
|
||||
name += '|' + threading.current_thread().name
|
||||
count = self._semlock._count()
|
||||
elif self._semlock._get_value() == 1:
|
||||
name, count = 'None', 0
|
||||
elif self._semlock._count() > 0:
|
||||
name, count = 'SomeOtherThread', 'nonzero'
|
||||
else:
|
||||
name, count = 'SomeOtherProcess', 'nonzero'
|
||||
except Exception:
|
||||
name, count = 'unknown', 'unknown'
|
||||
return '<%s(%s, %s)>' % (self.__class__.__name__, name, count)
|
||||
|
||||
|
||||
class Condition(object):
|
||||
'''
|
||||
Condition variable
|
||||
'''
|
||||
|
||||
def __init__(self, lock=None, ctx=None):
|
||||
assert ctx
|
||||
self._lock = lock or ctx.RLock()
|
||||
self._sleeping_count = ctx.Semaphore(0)
|
||||
self._woken_count = ctx.Semaphore(0)
|
||||
self._wait_semaphore = ctx.Semaphore(0)
|
||||
self._make_methods()
|
||||
|
||||
def __getstate__(self):
|
||||
context.assert_spawning(self)
|
||||
return (self._lock, self._sleeping_count,
|
||||
self._woken_count, self._wait_semaphore)
|
||||
|
||||
def __setstate__(self, state):
|
||||
(self._lock, self._sleeping_count,
|
||||
self._woken_count, self._wait_semaphore) = state
|
||||
self._make_methods()
|
||||
|
||||
def __enter__(self):
|
||||
return self._lock.__enter__()
|
||||
|
||||
def __exit__(self, *args):
|
||||
return self._lock.__exit__(*args)
|
||||
|
||||
def _make_methods(self):
|
||||
self.acquire = self._lock.acquire
|
||||
self.release = self._lock.release
|
||||
|
||||
def __repr__(self):
|
||||
try:
|
||||
num_waiters = (self._sleeping_count._semlock._get_value() -
|
||||
self._woken_count._semlock._get_value())
|
||||
except Exception:
|
||||
num_waiters = 'unknown'
|
||||
return '<%s(%s, %s)>' % (
|
||||
self.__class__.__name__, self._lock, num_waiters)
|
||||
|
||||
def wait(self, timeout=None):
|
||||
assert self._lock._semlock._is_mine(), \
|
||||
'must acquire() condition before using wait()'
|
||||
|
||||
# indicate that this thread is going to sleep
|
||||
self._sleeping_count.release()
|
||||
|
||||
# release lock
|
||||
count = self._lock._semlock._count()
|
||||
for i in range(count):
|
||||
self._lock.release()
|
||||
|
||||
try:
|
||||
# wait for notification or timeout
|
||||
return self._wait_semaphore.acquire(True, timeout)
|
||||
finally:
|
||||
# indicate that this thread has woken
|
||||
self._woken_count.release()
|
||||
|
||||
# reacquire lock
|
||||
for i in range(count):
|
||||
self._lock.acquire()
|
||||
|
||||
def notify(self):
|
||||
assert self._lock._semlock._is_mine(), 'lock is not owned'
|
||||
assert not self._wait_semaphore.acquire(False)
|
||||
|
||||
# to take account of timeouts since last notify() we subtract
|
||||
# woken_count from sleeping_count and rezero woken_count
|
||||
while self._woken_count.acquire(False):
|
||||
res = self._sleeping_count.acquire(False)
|
||||
assert res
|
||||
|
||||
if self._sleeping_count.acquire(False): # try grabbing a sleeper
|
||||
self._wait_semaphore.release() # wake up one sleeper
|
||||
self._woken_count.acquire() # wait for sleeper to wake
|
||||
|
||||
# rezero _wait_semaphore in case a timeout just happened
|
||||
self._wait_semaphore.acquire(False)
|
||||
|
||||
def notify_all(self):
|
||||
assert self._lock._semlock._is_mine(), 'lock is not owned'
|
||||
assert not self._wait_semaphore.acquire(False)
|
||||
|
||||
# to take account of timeouts since last notify*() we subtract
|
||||
# woken_count from sleeping_count and rezero woken_count
|
||||
while self._woken_count.acquire(False):
|
||||
res = self._sleeping_count.acquire(False)
|
||||
assert res
|
||||
|
||||
sleepers = 0
|
||||
while self._sleeping_count.acquire(False):
|
||||
self._wait_semaphore.release() # wake up one sleeper
|
||||
sleepers += 1
|
||||
|
||||
if sleepers:
|
||||
for i in range(sleepers):
|
||||
self._woken_count.acquire() # wait for a sleeper to wake
|
||||
|
||||
# rezero wait_semaphore in case some timeouts just happened
|
||||
while self._wait_semaphore.acquire(False):
|
||||
pass
|
||||
|
||||
def wait_for(self, predicate, timeout=None):
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
if timeout is not None:
|
||||
endtime = monotonic() + timeout
|
||||
else:
|
||||
endtime = None
|
||||
waittime = None
|
||||
while not result:
|
||||
if endtime is not None:
|
||||
waittime = endtime - monotonic()
|
||||
if waittime <= 0:
|
||||
break
|
||||
self.wait(waittime)
|
||||
result = predicate()
|
||||
return result
|
||||
|
||||
|
||||
class Event(object):
|
||||
|
||||
def __init__(self, ctx=None):
|
||||
assert ctx
|
||||
self._cond = ctx.Condition(ctx.Lock())
|
||||
self._flag = ctx.Semaphore(0)
|
||||
|
||||
def is_set(self):
|
||||
with self._cond:
|
||||
if self._flag.acquire(False):
|
||||
self._flag.release()
|
||||
return True
|
||||
return False
|
||||
|
||||
def set(self):
|
||||
with self._cond:
|
||||
self._flag.acquire(False)
|
||||
self._flag.release()
|
||||
self._cond.notify_all()
|
||||
|
||||
def clear(self):
|
||||
with self._cond:
|
||||
self._flag.acquire(False)
|
||||
|
||||
def wait(self, timeout=None):
|
||||
with self._cond:
|
||||
if self._flag.acquire(False):
|
||||
self._flag.release()
|
||||
else:
|
||||
self._cond.wait(timeout)
|
||||
|
||||
if self._flag.acquire(False):
|
||||
self._flag.release()
|
||||
return True
|
||||
return False
|
||||
|
||||
#
|
||||
# Barrier
|
||||
#
|
||||
|
||||
|
||||
if hasattr(threading, 'Barrier'):
|
||||
|
||||
class Barrier(threading.Barrier):
|
||||
|
||||
def __init__(self, parties, action=None, timeout=None, ctx=None):
|
||||
assert ctx
|
||||
import struct
|
||||
from .heap import BufferWrapper
|
||||
wrapper = BufferWrapper(struct.calcsize('i') * 2)
|
||||
cond = ctx.Condition()
|
||||
self.__setstate__((parties, action, timeout, cond, wrapper))
|
||||
self._state = 0
|
||||
self._count = 0
|
||||
|
||||
def __setstate__(self, state):
|
||||
(self._parties, self._action, self._timeout,
|
||||
self._cond, self._wrapper) = state
|
||||
self._array = self._wrapper.create_memoryview().cast('i')
|
||||
|
||||
def __getstate__(self):
|
||||
return (self._parties, self._action, self._timeout,
|
||||
self._cond, self._wrapper)
|
||||
|
||||
@property
|
||||
def _state(self):
|
||||
return self._array[0]
|
||||
|
||||
@_state.setter
|
||||
def _state(self, value): # noqa
|
||||
self._array[0] = value
|
||||
|
||||
@property
|
||||
def _count(self):
|
||||
return self._array[1]
|
||||
|
||||
@_count.setter
|
||||
def _count(self, value): # noqa
|
||||
self._array[1] = value
|
||||
|
||||
|
||||
else:
|
||||
|
||||
class Barrier(object): # noqa
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
raise NotImplementedError('Barrier only supported on Py3')
|
||||
@@ -0,0 +1,233 @@
|
||||
#
|
||||
# Module providing various facilities to other parts of the package
|
||||
#
|
||||
# billiard/util.py
|
||||
#
|
||||
# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
|
||||
# Licensed to PSF under a Contributor Agreement.
|
||||
#
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
import errno
|
||||
import functools
|
||||
import atexit
|
||||
|
||||
try:
|
||||
import cffi
|
||||
except ImportError:
|
||||
import ctypes
|
||||
|
||||
try:
|
||||
from subprocess import _args_from_interpreter_flags # noqa
|
||||
except ImportError: # pragma: no cover
|
||||
def _args_from_interpreter_flags(): # noqa
|
||||
"""Return a list of command-line arguments reproducing the current
|
||||
settings in sys.flags and sys.warnoptions."""
|
||||
flag_opt_map = {
|
||||
'debug': 'd',
|
||||
'optimize': 'O',
|
||||
'dont_write_bytecode': 'B',
|
||||
'no_user_site': 's',
|
||||
'no_site': 'S',
|
||||
'ignore_environment': 'E',
|
||||
'verbose': 'v',
|
||||
'bytes_warning': 'b',
|
||||
'hash_randomization': 'R',
|
||||
'py3k_warning': '3',
|
||||
}
|
||||
args = []
|
||||
for flag, opt in flag_opt_map.items():
|
||||
v = getattr(sys.flags, flag)
|
||||
if v > 0:
|
||||
args.append('-' + opt * v)
|
||||
for opt in sys.warnoptions:
|
||||
args.append('-W' + opt)
|
||||
return args
|
||||
|
||||
from multiprocessing.util import ( # noqa
|
||||
_afterfork_registry,
|
||||
_afterfork_counter,
|
||||
_exit_function,
|
||||
_finalizer_registry,
|
||||
_finalizer_counter,
|
||||
Finalize,
|
||||
ForkAwareLocal,
|
||||
ForkAwareThreadLock,
|
||||
get_temp_dir,
|
||||
is_exiting,
|
||||
register_after_fork,
|
||||
_run_after_forkers,
|
||||
_run_finalizers,
|
||||
)
|
||||
|
||||
from .compat import get_errno
|
||||
|
||||
__all__ = [
|
||||
'sub_debug', 'debug', 'info', 'sub_warning', 'get_logger',
|
||||
'log_to_stderr', 'get_temp_dir', 'register_after_fork',
|
||||
'is_exiting', 'Finalize', 'ForkAwareThreadLock', 'ForkAwareLocal',
|
||||
'SUBDEBUG', 'SUBWARNING',
|
||||
]
|
||||
|
||||
|
||||
# Constants from prctl.h
|
||||
PR_GET_PDEATHSIG = 2
|
||||
PR_SET_PDEATHSIG = 1
|
||||
|
||||
#
|
||||
# Logging
|
||||
#
|
||||
|
||||
NOTSET = 0
|
||||
SUBDEBUG = 5
|
||||
DEBUG = 10
|
||||
INFO = 20
|
||||
SUBWARNING = 25
|
||||
WARNING = 30
|
||||
ERROR = 40
|
||||
|
||||
LOGGER_NAME = 'multiprocessing'
|
||||
DEFAULT_LOGGING_FORMAT = '[%(levelname)s/%(processName)s] %(message)s'
|
||||
|
||||
_logger = None
|
||||
_log_to_stderr = False
|
||||
|
||||
|
||||
def sub_debug(msg, *args, **kwargs):
|
||||
if _logger:
|
||||
_logger.log(SUBDEBUG, msg, *args, **kwargs)
|
||||
|
||||
|
||||
def debug(msg, *args, **kwargs):
|
||||
if _logger:
|
||||
_logger.log(DEBUG, msg, *args, **kwargs)
|
||||
|
||||
|
||||
def info(msg, *args, **kwargs):
|
||||
if _logger:
|
||||
_logger.log(INFO, msg, *args, **kwargs)
|
||||
|
||||
|
||||
def sub_warning(msg, *args, **kwargs):
|
||||
if _logger:
|
||||
_logger.log(SUBWARNING, msg, *args, **kwargs)
|
||||
|
||||
def warning(msg, *args, **kwargs):
|
||||
if _logger:
|
||||
_logger.log(WARNING, msg, *args, **kwargs)
|
||||
|
||||
def error(msg, *args, **kwargs):
|
||||
if _logger:
|
||||
_logger.log(ERROR, msg, *args, **kwargs)
|
||||
|
||||
|
||||
def get_logger():
|
||||
'''
|
||||
Returns logger used by multiprocessing
|
||||
'''
|
||||
global _logger
|
||||
import logging
|
||||
|
||||
logging._acquireLock()
|
||||
try:
|
||||
if not _logger:
|
||||
|
||||
_logger = logging.getLogger(LOGGER_NAME)
|
||||
_logger.propagate = 0
|
||||
logging.addLevelName(SUBDEBUG, 'SUBDEBUG')
|
||||
logging.addLevelName(SUBWARNING, 'SUBWARNING')
|
||||
|
||||
# XXX multiprocessing should cleanup before logging
|
||||
if hasattr(atexit, 'unregister'):
|
||||
atexit.unregister(_exit_function)
|
||||
atexit.register(_exit_function)
|
||||
else:
|
||||
atexit._exithandlers.remove((_exit_function, (), {}))
|
||||
atexit._exithandlers.append((_exit_function, (), {}))
|
||||
finally:
|
||||
logging._releaseLock()
|
||||
|
||||
return _logger
|
||||
|
||||
|
||||
def log_to_stderr(level=None):
|
||||
'''
|
||||
Turn on logging and add a handler which prints to stderr
|
||||
'''
|
||||
global _log_to_stderr
|
||||
import logging
|
||||
|
||||
logger = get_logger()
|
||||
formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
|
||||
handler = logging.StreamHandler()
|
||||
handler.setFormatter(formatter)
|
||||
logger.addHandler(handler)
|
||||
|
||||
if level:
|
||||
logger.setLevel(level)
|
||||
_log_to_stderr = True
|
||||
return _logger
|
||||
|
||||
|
||||
def get_pdeathsig():
|
||||
"""
|
||||
Return the current value of the parent process death signal
|
||||
"""
|
||||
if not sys.platform.startswith('linux'):
|
||||
# currently we support only linux platform.
|
||||
raise OSError()
|
||||
try:
|
||||
if 'cffi' in sys.modules:
|
||||
ffi = cffi.FFI()
|
||||
ffi.cdef("int prctl (int __option, ...);")
|
||||
arg = ffi.new("int *")
|
||||
C = ffi.dlopen(None)
|
||||
C.prctl(PR_GET_PDEATHSIG, arg)
|
||||
return arg[0]
|
||||
else:
|
||||
sig = ctypes.c_int()
|
||||
libc = ctypes.cdll.LoadLibrary("libc.so.6")
|
||||
libc.prctl(PR_GET_PDEATHSIG, ctypes.byref(sig))
|
||||
return sig.value
|
||||
except Exception:
|
||||
raise OSError()
|
||||
|
||||
|
||||
def set_pdeathsig(sig):
|
||||
"""
|
||||
Set the parent process death signal of the calling process to sig
|
||||
(either a signal value in the range 1..maxsig, or 0 to clear).
|
||||
This is the signal that the calling process will get when its parent dies.
|
||||
This value is cleared for the child of a fork(2) and
|
||||
(since Linux 2.4.36 / 2.6.23) when executing a set-user-ID or set-group-ID binary.
|
||||
"""
|
||||
if not sys.platform.startswith('linux'):
|
||||
# currently we support only linux platform.
|
||||
raise OSError()
|
||||
try:
|
||||
if 'cffi' in sys.modules:
|
||||
ffi = cffi.FFI()
|
||||
ffi.cdef("int prctl (int __option, ...);")
|
||||
C = ffi.dlopen(None)
|
||||
C.prctl(PR_SET_PDEATHSIG, ffi.cast("int", sig))
|
||||
else:
|
||||
libc = ctypes.cdll.LoadLibrary("libc.so.6")
|
||||
libc.prctl(PR_SET_PDEATHSIG, sig)
|
||||
except Exception:
|
||||
raise OSError()
|
||||
|
||||
def _eintr_retry(func):
|
||||
'''
|
||||
Automatic retry after EINTR.
|
||||
'''
|
||||
|
||||
@functools.wraps(func)
|
||||
def wrapped(*args, **kwargs):
|
||||
while 1:
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except OSError as exc:
|
||||
if get_errno(exc) != errno.EINTR:
|
||||
raise
|
||||
return wrapped
|
||||
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,54 @@
|
||||
Copyright (c) 2015-2016 Ask Solem & contributors. All rights reserved.
|
||||
Copyright (c) 2012-2014 GoPivotal, Inc. All rights reserved.
|
||||
Copyright (c) 2009, 2010, 2011, 2012 Ask Solem, and individual contributors. All rights reserved.
|
||||
|
||||
Celery is licensed under The BSD License (3 Clause, also known as
|
||||
the new BSD license). The license is an OSI approved Open Source
|
||||
license and is GPL-compatible(1).
|
||||
|
||||
The license text can also be found here:
|
||||
http://www.opensource.org/licenses/BSD-3-Clause
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Ask Solem, nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Ask Solem OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
Documentation License
|
||||
=====================
|
||||
|
||||
The documentation portion of Celery (the rendered contents of the
|
||||
"docs" directory of a software distribution or checkout) is supplied
|
||||
under the "Creative Commons Attribution-ShareAlike 4.0
|
||||
International" (CC BY-SA 4.0) License as described by
|
||||
https://creativecommons.org/licenses/by-sa/4.0/
|
||||
|
||||
Footnotes
|
||||
=========
|
||||
(1) A GPL-compatible license makes it possible to
|
||||
combine Celery with other software that is released
|
||||
under the GPL, it does not mean that we're distributing
|
||||
Celery under the GPL license. The BSD license, unlike the GPL,
|
||||
let you distribute a modified version without making your
|
||||
changes open source.
|
||||
@@ -0,0 +1,647 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: celery
|
||||
Version: 5.2.7
|
||||
Summary: Distributed Task Queue.
|
||||
Home-page: http://celeryproject.org
|
||||
Author: Ask Solem
|
||||
Author-email: auvipy@gmail.com
|
||||
License: BSD
|
||||
Project-URL: Documentation, https://docs.celeryproject.org/en/latest/index.html
|
||||
Project-URL: Changelog, https://docs.celeryproject.org/en/stable/changelog.html
|
||||
Project-URL: Code, https://github.com/celery/celery
|
||||
Project-URL: Tracker, https://github.com/celery/celery/issues
|
||||
Project-URL: Funding, https://opencollective.com/celery
|
||||
Keywords: task job queue distributed messaging actor
|
||||
Platform: any
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: License :: OSI Approved :: BSD License
|
||||
Classifier: Topic :: System :: Distributed Computing
|
||||
Classifier: Topic :: Software Development :: Object Brokering
|
||||
Classifier: Framework :: Celery
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3 :: Only
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: Implementation :: CPython
|
||||
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
||||
Classifier: Operating System :: OS Independent
|
||||
Requires-Python: >=3.7
|
||||
License-File: LICENSE
|
||||
Requires-Dist: pytz (>=2021.3)
|
||||
Requires-Dist: billiard (<4.0,>=3.6.4.0)
|
||||
Requires-Dist: kombu (<6.0,>=5.2.3)
|
||||
Requires-Dist: vine (<6.0,>=5.0.0)
|
||||
Requires-Dist: click (<9.0,>=8.0.3)
|
||||
Requires-Dist: click-didyoumean (>=0.0.3)
|
||||
Requires-Dist: click-repl (>=0.2.0)
|
||||
Requires-Dist: click-plugins (>=1.1.1)
|
||||
Requires-Dist: importlib-metadata (>=1.4.0) ; python_version < "3.8"
|
||||
Provides-Extra: arangodb
|
||||
Requires-Dist: pyArango (>=1.3.2) ; extra == 'arangodb'
|
||||
Provides-Extra: auth
|
||||
Requires-Dist: cryptography ; extra == 'auth'
|
||||
Provides-Extra: azureblockblob
|
||||
Requires-Dist: azure-storage-blob (==12.9.0) ; extra == 'azureblockblob'
|
||||
Provides-Extra: brotli
|
||||
Requires-Dist: brotli (>=1.0.0) ; (platform_python_implementation == "CPython") and extra == 'brotli'
|
||||
Requires-Dist: brotlipy (>=0.7.0) ; (platform_python_implementation == "PyPy") and extra == 'brotli'
|
||||
Provides-Extra: cassandra
|
||||
Requires-Dist: cassandra-driver (<3.21.0) ; extra == 'cassandra'
|
||||
Provides-Extra: consul
|
||||
Requires-Dist: python-consul2 ; extra == 'consul'
|
||||
Provides-Extra: cosmosdbsql
|
||||
Requires-Dist: pydocumentdb (==2.3.2) ; extra == 'cosmosdbsql'
|
||||
Provides-Extra: couchbase
|
||||
Requires-Dist: couchbase (>=3.0.0) ; (platform_python_implementation != "PyPy" and (platform_system != "Windows" or python_version < "3.10")) and extra == 'couchbase'
|
||||
Provides-Extra: couchdb
|
||||
Requires-Dist: pycouchdb ; extra == 'couchdb'
|
||||
Provides-Extra: django
|
||||
Requires-Dist: Django (>=1.11) ; extra == 'django'
|
||||
Provides-Extra: dynamodb
|
||||
Requires-Dist: boto3 (>=1.9.178) ; extra == 'dynamodb'
|
||||
Provides-Extra: elasticsearch
|
||||
Requires-Dist: elasticsearch ; extra == 'elasticsearch'
|
||||
Provides-Extra: eventlet
|
||||
Requires-Dist: eventlet (>=0.32.0) ; (python_version < "3.10") and extra == 'eventlet'
|
||||
Provides-Extra: gevent
|
||||
Requires-Dist: gevent (>=1.5.0) ; extra == 'gevent'
|
||||
Provides-Extra: librabbitmq
|
||||
Requires-Dist: librabbitmq (>=1.5.0) ; extra == 'librabbitmq'
|
||||
Provides-Extra: memcache
|
||||
Requires-Dist: pylibmc ; (platform_system != "Windows") and extra == 'memcache'
|
||||
Provides-Extra: mongodb
|
||||
Requires-Dist: pymongo[srv] (>=3.11.1) ; extra == 'mongodb'
|
||||
Provides-Extra: msgpack
|
||||
Requires-Dist: msgpack ; extra == 'msgpack'
|
||||
Provides-Extra: pymemcache
|
||||
Requires-Dist: python-memcached ; extra == 'pymemcache'
|
||||
Provides-Extra: pyro
|
||||
Requires-Dist: pyro4 ; extra == 'pyro'
|
||||
Provides-Extra: pytest
|
||||
Requires-Dist: pytest-celery ; extra == 'pytest'
|
||||
Provides-Extra: redis
|
||||
Requires-Dist: redis (!=4.0.0,!=4.0.1,>=3.4.1) ; extra == 'redis'
|
||||
Provides-Extra: s3
|
||||
Requires-Dist: boto3 (>=1.9.125) ; extra == 's3'
|
||||
Provides-Extra: slmq
|
||||
Requires-Dist: softlayer-messaging (>=1.0.3) ; extra == 'slmq'
|
||||
Provides-Extra: solar
|
||||
Requires-Dist: ephem ; (platform_python_implementation != "PyPy") and extra == 'solar'
|
||||
Provides-Extra: sqlalchemy
|
||||
Requires-Dist: sqlalchemy ; extra == 'sqlalchemy'
|
||||
Provides-Extra: sqs
|
||||
Requires-Dist: kombu[sqs] ; extra == 'sqs'
|
||||
Provides-Extra: tblib
|
||||
Requires-Dist: tblib (>=1.3.0) ; (python_version < "3.8.0") and extra == 'tblib'
|
||||
Requires-Dist: tblib (>=1.5.0) ; (python_version >= "3.8.0") and extra == 'tblib'
|
||||
Provides-Extra: yaml
|
||||
Requires-Dist: PyYAML (>=3.10) ; extra == 'yaml'
|
||||
Provides-Extra: zookeeper
|
||||
Requires-Dist: kazoo (>=1.3.1) ; extra == 'zookeeper'
|
||||
Provides-Extra: zstd
|
||||
Requires-Dist: zstandard ; extra == 'zstd'
|
||||
|
||||
.. image:: http://docs.celeryproject.org/en/latest/_images/celery-banner-small.png
|
||||
|
||||
|build-status| |coverage| |license| |wheel| |pyversion| |pyimp| |ocbackerbadge| |ocsponsorbadge|
|
||||
|
||||
:Version: 5.2.7 (dawn-chorus)
|
||||
:Web: https://docs.celeryproject.org/en/stable/index.html
|
||||
:Download: https://pypi.org/project/celery/
|
||||
:Source: https://github.com/celery/celery/
|
||||
:Keywords: task, queue, job, async, rabbitmq, amqp, redis,
|
||||
python, distributed, actors
|
||||
|
||||
Donations
|
||||
=========
|
||||
|
||||
This project relies on your generous donations.
|
||||
|
||||
If you are using Celery to create a commercial product, please consider becoming our `backer`_ or our `sponsor`_ to ensure Celery's future.
|
||||
|
||||
.. _`backer`: https://opencollective.com/celery#backer
|
||||
.. _`sponsor`: https://opencollective.com/celery#sponsor
|
||||
|
||||
For enterprise
|
||||
==============
|
||||
|
||||
Available as part of the Tidelift Subscription.
|
||||
|
||||
The maintainers of ``celery`` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. `Learn more. <https://tidelift.com/subscription/pkg/pypi-celery?utm_source=pypi-celery&utm_medium=referral&utm_campaign=enterprise&utm_term=repo>`_
|
||||
|
||||
What's a Task Queue?
|
||||
====================
|
||||
|
||||
Task queues are used as a mechanism to distribute work across threads or
|
||||
machines.
|
||||
|
||||
A task queue's input is a unit of work, called a task, dedicated worker
|
||||
processes then constantly monitor the queue for new work to perform.
|
||||
|
||||
Celery communicates via messages, usually using a broker
|
||||
to mediate between clients and workers. To initiate a task a client puts a
|
||||
message on the queue, the broker then delivers the message to a worker.
|
||||
|
||||
A Celery system can consist of multiple workers and brokers, giving way
|
||||
to high availability and horizontal scaling.
|
||||
|
||||
Celery is written in Python, but the protocol can be implemented in any
|
||||
language. In addition to Python there's node-celery_ for Node.js,
|
||||
a `PHP client`_, `gocelery`_ for golang, and rusty-celery_ for Rust.
|
||||
|
||||
Language interoperability can also be achieved by using webhooks
|
||||
in such a way that the client enqueues an URL to be requested by a worker.
|
||||
|
||||
.. _node-celery: https://github.com/mher/node-celery
|
||||
.. _`PHP client`: https://github.com/gjedeer/celery-php
|
||||
.. _`gocelery`: https://github.com/gocelery/gocelery
|
||||
.. _rusty-celery: https://github.com/rusty-celery/rusty-celery
|
||||
|
||||
What do I need?
|
||||
===============
|
||||
|
||||
Celery version 5.2.0 runs on,
|
||||
|
||||
- Python (3.7, 3.8, 3.9, 3.10)
|
||||
- PyPy3.7 (7.3.7+)
|
||||
|
||||
|
||||
This is the version of celery which will support Python 3.7 or newer.
|
||||
|
||||
If you're running an older version of Python, you need to be running
|
||||
an older version of Celery:
|
||||
|
||||
- Python 2.6: Celery series 3.1 or earlier.
|
||||
- Python 2.5: Celery series 3.0 or earlier.
|
||||
- Python 2.4: Celery series 2.2 or earlier.
|
||||
- Python 2.7: Celery 4.x series.
|
||||
- Python 3.6: Celery 5.1 or earlier.
|
||||
|
||||
Celery is a project with minimal funding,
|
||||
so we don't support Microsoft Windows.
|
||||
Please don't open any issues related to that platform.
|
||||
|
||||
*Celery* is usually used with a message broker to send and receive messages.
|
||||
The RabbitMQ, Redis transports are feature complete,
|
||||
but there's also experimental support for a myriad of other solutions, including
|
||||
using SQLite for local development.
|
||||
|
||||
*Celery* can run on a single machine, on multiple machines, or even
|
||||
across datacenters.
|
||||
|
||||
Get Started
|
||||
===========
|
||||
|
||||
If this is the first time you're trying to use Celery, or you're
|
||||
new to Celery v5.2.0 coming from previous versions then you should read our
|
||||
getting started tutorials:
|
||||
|
||||
- `First steps with Celery`_
|
||||
|
||||
Tutorial teaching you the bare minimum needed to get started with Celery.
|
||||
|
||||
- `Next steps`_
|
||||
|
||||
A more complete overview, showing more features.
|
||||
|
||||
.. _`First steps with Celery`:
|
||||
http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html
|
||||
|
||||
.. _`Next steps`:
|
||||
http://docs.celeryproject.org/en/latest/getting-started/next-steps.html
|
||||
|
||||
You can also get started with Celery by using a hosted broker transport CloudAMQP. The largest hosting provider of RabbitMQ is a proud sponsor of Celery.
|
||||
|
||||
Celery is...
|
||||
=============
|
||||
|
||||
- **Simple**
|
||||
|
||||
Celery is easy to use and maintain, and does *not need configuration files*.
|
||||
|
||||
It has an active, friendly community you can talk to for support,
|
||||
like at our `mailing-list`_, or the IRC channel.
|
||||
|
||||
Here's one of the simplest applications you can make:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from celery import Celery
|
||||
|
||||
app = Celery('hello', broker='amqp://guest@localhost//')
|
||||
|
||||
@app.task
|
||||
def hello():
|
||||
return 'hello world'
|
||||
|
||||
- **Highly Available**
|
||||
|
||||
Workers and clients will automatically retry in the event
|
||||
of connection loss or failure, and some brokers support
|
||||
HA in way of *Primary/Primary* or *Primary/Replica* replication.
|
||||
|
||||
- **Fast**
|
||||
|
||||
A single Celery process can process millions of tasks a minute,
|
||||
with sub-millisecond round-trip latency (using RabbitMQ,
|
||||
py-librabbitmq, and optimized settings).
|
||||
|
||||
- **Flexible**
|
||||
|
||||
Almost every part of *Celery* can be extended or used on its own,
|
||||
Custom pool implementations, serializers, compression schemes, logging,
|
||||
schedulers, consumers, producers, broker transports, and much more.
|
||||
|
||||
It supports...
|
||||
================
|
||||
|
||||
- **Message Transports**
|
||||
|
||||
- RabbitMQ_, Redis_, Amazon SQS
|
||||
|
||||
- **Concurrency**
|
||||
|
||||
- Prefork, Eventlet_, gevent_, single threaded (``solo``)
|
||||
|
||||
- **Result Stores**
|
||||
|
||||
- AMQP, Redis
|
||||
- memcached
|
||||
- SQLAlchemy, Django ORM
|
||||
- Apache Cassandra, IronCache, Elasticsearch
|
||||
|
||||
- **Serialization**
|
||||
|
||||
- *pickle*, *json*, *yaml*, *msgpack*.
|
||||
- *zlib*, *bzip2* compression.
|
||||
- Cryptographic message signing.
|
||||
|
||||
.. _`Eventlet`: http://eventlet.net/
|
||||
.. _`gevent`: http://gevent.org/
|
||||
|
||||
.. _RabbitMQ: https://rabbitmq.com
|
||||
.. _Redis: https://redis.io
|
||||
.. _SQLAlchemy: http://sqlalchemy.org
|
||||
|
||||
Framework Integration
|
||||
=====================
|
||||
|
||||
Celery is easy to integrate with web frameworks, some of which even have
|
||||
integration packages:
|
||||
|
||||
+--------------------+------------------------+
|
||||
| `Django`_ | not needed |
|
||||
+--------------------+------------------------+
|
||||
| `Pyramid`_ | `pyramid_celery`_ |
|
||||
+--------------------+------------------------+
|
||||
| `Pylons`_ | `celery-pylons`_ |
|
||||
+--------------------+------------------------+
|
||||
| `Flask`_ | not needed |
|
||||
+--------------------+------------------------+
|
||||
| `web2py`_ | `web2py-celery`_ |
|
||||
+--------------------+------------------------+
|
||||
| `Tornado`_ | `tornado-celery`_ |
|
||||
+--------------------+------------------------+
|
||||
|
||||
The integration packages aren't strictly necessary, but they can make
|
||||
development easier, and sometimes they add important hooks like closing
|
||||
database connections at ``fork``.
|
||||
|
||||
.. _`Django`: https://djangoproject.com/
|
||||
.. _`Pylons`: http://pylonsproject.org/
|
||||
.. _`Flask`: http://flask.pocoo.org/
|
||||
.. _`web2py`: http://web2py.com/
|
||||
.. _`Bottle`: https://bottlepy.org/
|
||||
.. _`Pyramid`: http://docs.pylonsproject.org/en/latest/docs/pyramid.html
|
||||
.. _`pyramid_celery`: https://pypi.org/project/pyramid_celery/
|
||||
.. _`celery-pylons`: https://pypi.org/project/celery-pylons/
|
||||
.. _`web2py-celery`: https://code.google.com/p/web2py-celery/
|
||||
.. _`Tornado`: http://www.tornadoweb.org/
|
||||
.. _`tornado-celery`: https://github.com/mher/tornado-celery/
|
||||
|
||||
.. _celery-documentation:
|
||||
|
||||
Documentation
|
||||
=============
|
||||
|
||||
The `latest documentation`_ is hosted at Read The Docs, containing user guides,
|
||||
tutorials, and an API reference.
|
||||
|
||||
最新的中文文档托管在 https://www.celerycn.io/ 中,包含用户指南、教程、API接口等。
|
||||
|
||||
.. _`latest documentation`: http://docs.celeryproject.org/en/latest/
|
||||
|
||||
.. _celery-installation:
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
You can install Celery either via the Python Package Index (PyPI)
|
||||
or from source.
|
||||
|
||||
To install using ``pip``:
|
||||
|
||||
::
|
||||
|
||||
|
||||
$ pip install -U Celery
|
||||
|
||||
.. _bundles:
|
||||
|
||||
Bundles
|
||||
-------
|
||||
|
||||
Celery also defines a group of bundles that can be used
|
||||
to install Celery and the dependencies for a given feature.
|
||||
|
||||
You can specify these in your requirements or on the ``pip``
|
||||
command-line by using brackets. Multiple bundles can be specified by
|
||||
separating them by commas.
|
||||
|
||||
::
|
||||
|
||||
|
||||
$ pip install "celery[amqp]"
|
||||
|
||||
$ pip install "celery[amqp,redis,auth,msgpack]"
|
||||
|
||||
The following bundles are available:
|
||||
|
||||
Serializers
|
||||
~~~~~~~~~~~
|
||||
|
||||
:``celery[auth]``:
|
||||
for using the ``auth`` security serializer.
|
||||
|
||||
:``celery[msgpack]``:
|
||||
for using the msgpack serializer.
|
||||
|
||||
:``celery[yaml]``:
|
||||
for using the yaml serializer.
|
||||
|
||||
Concurrency
|
||||
~~~~~~~~~~~
|
||||
|
||||
:``celery[eventlet]``:
|
||||
for using the ``eventlet`` pool.
|
||||
|
||||
:``celery[gevent]``:
|
||||
for using the ``gevent`` pool.
|
||||
|
||||
Transports and Backends
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
:``celery[amqp]``:
|
||||
for using the RabbitMQ amqp python library.
|
||||
|
||||
:``celery[redis]``:
|
||||
for using Redis as a message transport or as a result backend.
|
||||
|
||||
:``celery[sqs]``:
|
||||
for using Amazon SQS as a message transport.
|
||||
|
||||
:``celery[tblib``]:
|
||||
for using the ``task_remote_tracebacks`` feature.
|
||||
|
||||
:``celery[memcache]``:
|
||||
for using Memcached as a result backend (using ``pylibmc``)
|
||||
|
||||
:``celery[pymemcache]``:
|
||||
for using Memcached as a result backend (pure-Python implementation).
|
||||
|
||||
:``celery[cassandra]``:
|
||||
for using Apache Cassandra as a result backend with DataStax driver.
|
||||
|
||||
:``celery[azureblockblob]``:
|
||||
for using Azure Storage as a result backend (using ``azure-storage``)
|
||||
|
||||
:``celery[s3]``:
|
||||
for using S3 Storage as a result backend.
|
||||
|
||||
:``celery[couchbase]``:
|
||||
for using Couchbase as a result backend.
|
||||
|
||||
:``celery[arangodb]``:
|
||||
for using ArangoDB as a result backend.
|
||||
|
||||
:``celery[elasticsearch]``:
|
||||
for using Elasticsearch as a result backend.
|
||||
|
||||
:``celery[riak]``:
|
||||
for using Riak as a result backend.
|
||||
|
||||
:``celery[cosmosdbsql]``:
|
||||
for using Azure Cosmos DB as a result backend (using ``pydocumentdb``)
|
||||
|
||||
:``celery[zookeeper]``:
|
||||
for using Zookeeper as a message transport.
|
||||
|
||||
:``celery[sqlalchemy]``:
|
||||
for using SQLAlchemy as a result backend (*supported*).
|
||||
|
||||
:``celery[pyro]``:
|
||||
for using the Pyro4 message transport (*experimental*).
|
||||
|
||||
:``celery[slmq]``:
|
||||
for using the SoftLayer Message Queue transport (*experimental*).
|
||||
|
||||
:``celery[consul]``:
|
||||
for using the Consul.io Key/Value store as a message transport or result backend (*experimental*).
|
||||
|
||||
:``celery[django]``:
|
||||
specifies the lowest version possible for Django support.
|
||||
|
||||
You should probably not use this in your requirements, it's here
|
||||
for informational purposes only.
|
||||
|
||||
|
||||
.. _celery-installing-from-source:
|
||||
|
||||
Downloading and installing from source
|
||||
--------------------------------------
|
||||
|
||||
Download the latest version of Celery from PyPI:
|
||||
|
||||
https://pypi.org/project/celery/
|
||||
|
||||
You can install it by doing the following,:
|
||||
|
||||
::
|
||||
|
||||
|
||||
$ tar xvfz celery-0.0.0.tar.gz
|
||||
$ cd celery-0.0.0
|
||||
$ python setup.py build
|
||||
# python setup.py install
|
||||
|
||||
The last command must be executed as a privileged user if
|
||||
you aren't currently using a virtualenv.
|
||||
|
||||
.. _celery-installing-from-git:
|
||||
|
||||
Using the development version
|
||||
-----------------------------
|
||||
|
||||
With pip
|
||||
~~~~~~~~
|
||||
|
||||
The Celery development version also requires the development
|
||||
versions of ``kombu``, ``amqp``, ``billiard``, and ``vine``.
|
||||
|
||||
You can install the latest snapshot of these using the following
|
||||
pip commands:
|
||||
|
||||
::
|
||||
|
||||
|
||||
$ pip install https://github.com/celery/celery/zipball/master#egg=celery
|
||||
$ pip install https://github.com/celery/billiard/zipball/master#egg=billiard
|
||||
$ pip install https://github.com/celery/py-amqp/zipball/master#egg=amqp
|
||||
$ pip install https://github.com/celery/kombu/zipball/master#egg=kombu
|
||||
$ pip install https://github.com/celery/vine/zipball/master#egg=vine
|
||||
|
||||
With git
|
||||
~~~~~~~~
|
||||
|
||||
Please see the Contributing section.
|
||||
|
||||
.. _getting-help:
|
||||
|
||||
Getting Help
|
||||
============
|
||||
|
||||
.. _mailing-list:
|
||||
|
||||
Mailing list
|
||||
------------
|
||||
|
||||
For discussions about the usage, development, and future of Celery,
|
||||
please join the `celery-users`_ mailing list.
|
||||
|
||||
.. _`celery-users`: https://groups.google.com/group/celery-users/
|
||||
|
||||
.. _irc-channel:
|
||||
|
||||
IRC
|
||||
---
|
||||
|
||||
Come chat with us on IRC. The **#celery** channel is located at the
|
||||
`Libera Chat`_ network.
|
||||
|
||||
.. _`Libera Chat`: https://libera.chat/
|
||||
|
||||
.. _bug-tracker:
|
||||
|
||||
Bug tracker
|
||||
===========
|
||||
|
||||
If you have any suggestions, bug reports, or annoyances please report them
|
||||
to our issue tracker at https://github.com/celery/celery/issues/
|
||||
|
||||
.. _wiki:
|
||||
|
||||
Wiki
|
||||
====
|
||||
|
||||
https://github.com/celery/celery/wiki
|
||||
|
||||
Credits
|
||||
=======
|
||||
|
||||
.. _contributing-short:
|
||||
|
||||
Contributors
|
||||
------------
|
||||
|
||||
This project exists thanks to all the people who contribute. Development of
|
||||
`celery` happens at GitHub: https://github.com/celery/celery
|
||||
|
||||
You're highly encouraged to participate in the development
|
||||
of `celery`. If you don't like GitHub (for some reason) you're welcome
|
||||
to send regular patches.
|
||||
|
||||
Be sure to also read the `Contributing to Celery`_ section in the
|
||||
documentation.
|
||||
|
||||
.. _`Contributing to Celery`:
|
||||
http://docs.celeryproject.org/en/master/contributing.html
|
||||
|
||||
|oc-contributors|
|
||||
|
||||
.. |oc-contributors| image:: https://opencollective.com/celery/contributors.svg?width=890&button=false
|
||||
:target: https://github.com/celery/celery/graphs/contributors
|
||||
|
||||
Backers
|
||||
-------
|
||||
|
||||
Thank you to all our backers! 🙏 [`Become a backer`_]
|
||||
|
||||
.. _`Become a backer`: https://opencollective.com/celery#backer
|
||||
|
||||
|oc-backers|
|
||||
|
||||
.. |oc-backers| image:: https://opencollective.com/celery/backers.svg?width=890
|
||||
:target: https://opencollective.com/celery#backers
|
||||
|
||||
Sponsors
|
||||
--------
|
||||
|
||||
Support this project by becoming a sponsor. Your logo will show up here with a
|
||||
link to your website. [`Become a sponsor`_]
|
||||
|
||||
.. _`Become a sponsor`: https://opencollective.com/celery#sponsor
|
||||
|
||||
|oc-sponsors|
|
||||
|
||||
.. |oc-sponsors| image:: https://opencollective.com/celery/sponsor/0/avatar.svg
|
||||
:target: https://opencollective.com/celery/sponsor/0/website
|
||||
|
||||
.. _license:
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
This software is licensed under the `New BSD License`. See the ``LICENSE``
|
||||
file in the top distribution directory for the full license text.
|
||||
|
||||
.. # vim: syntax=rst expandtab tabstop=4 shiftwidth=4 shiftround
|
||||
|
||||
.. |build-status| image:: https://github.com/celery/celery/actions/workflows/python-package.yml/badge.svg
|
||||
:alt: Build status
|
||||
:target: https://github.com/celery/celery/actions/workflows/python-package.yml
|
||||
|
||||
.. |coverage| image:: https://codecov.io/github/celery/celery/coverage.svg?branch=master
|
||||
:target: https://codecov.io/github/celery/celery?branch=master
|
||||
|
||||
.. |license| image:: https://img.shields.io/pypi/l/celery.svg
|
||||
:alt: BSD License
|
||||
:target: https://opensource.org/licenses/BSD-3-Clause
|
||||
|
||||
.. |wheel| image:: https://img.shields.io/pypi/wheel/celery.svg
|
||||
:alt: Celery can be installed via wheel
|
||||
:target: https://pypi.org/project/celery/
|
||||
|
||||
.. |pyversion| image:: https://img.shields.io/pypi/pyversions/celery.svg
|
||||
:alt: Supported Python versions.
|
||||
:target: https://pypi.org/project/celery/
|
||||
|
||||
.. |pyimp| image:: https://img.shields.io/pypi/implementation/celery.svg
|
||||
:alt: Supported Python implementations.
|
||||
:target: https://pypi.org/project/celery/
|
||||
|
||||
.. |ocbackerbadge| image:: https://opencollective.com/celery/backers/badge.svg
|
||||
:alt: Backers on Open Collective
|
||||
:target: #backers
|
||||
|
||||
.. |ocsponsorbadge| image:: https://opencollective.com/celery/sponsors/badge.svg
|
||||
:alt: Sponsors on Open Collective
|
||||
:target: #sponsors
|
||||
|
||||
.. |downloads| image:: https://pepy.tech/badge/celery
|
||||
:alt: Downloads
|
||||
:target: https://pepy.tech/project/celery
|
||||
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
../../../bin/celery,sha256=vi5_5hLUOvwxt4qOW_WBDzeVdIACtocuCBAlccrBgCg,268
|
||||
celery-5.2.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
celery-5.2.7.dist-info/LICENSE,sha256=OPfyaTUqhatgAqmGqGPC73aDk2xXbtiejt3gvKB6yMc,2631
|
||||
celery-5.2.7.dist-info/METADATA,sha256=xb-r2ZILAJnQZnqkYJYd8hC400B_0q_zaaipqT37FaM,20295
|
||||
celery-5.2.7.dist-info/RECORD,,
|
||||
celery-5.2.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
celery-5.2.7.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
|
||||
celery-5.2.7.dist-info/entry_points.txt,sha256=y-9XhDI_sXAtYn8ayrWDhRcZmiY4tsmIoa5braB_WVA,49
|
||||
celery-5.2.7.dist-info/top_level.txt,sha256=sQQ-a5HNsZIi2A8DiKQnB1HODFMfmrzIAZIE8t_XiOA,7
|
||||
celery/__init__.py,sha256=kQXw46gg5rImVmRtZTRG1NsAx8xe_ambj6EsiQmZvWQ,5978
|
||||
celery/__main__.py,sha256=-2sIMgK0_-22t6i19645vA-CfBFvHnzIuZ8les4AmdE,401
|
||||
celery/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/__pycache__/__main__.cpython-310.pyc,,
|
||||
celery/__pycache__/_state.cpython-310.pyc,,
|
||||
celery/__pycache__/beat.cpython-310.pyc,,
|
||||
celery/__pycache__/bootsteps.cpython-310.pyc,,
|
||||
celery/__pycache__/canvas.cpython-310.pyc,,
|
||||
celery/__pycache__/exceptions.cpython-310.pyc,,
|
||||
celery/__pycache__/local.cpython-310.pyc,,
|
||||
celery/__pycache__/platforms.cpython-310.pyc,,
|
||||
celery/__pycache__/result.cpython-310.pyc,,
|
||||
celery/__pycache__/schedules.cpython-310.pyc,,
|
||||
celery/__pycache__/signals.cpython-310.pyc,,
|
||||
celery/__pycache__/states.cpython-310.pyc,,
|
||||
celery/_state.py,sha256=k7T9CzeYR5PZSr0MjSVvFs6zpfkZal9Brl8xu-vPpXk,5029
|
||||
celery/app/__init__.py,sha256=iadhB_pmHYrlqaOMge-aO2CLQKxlG18yHaNYtiHL-3Y,2459
|
||||
celery/app/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/app/__pycache__/amqp.cpython-310.pyc,,
|
||||
celery/app/__pycache__/annotations.cpython-310.pyc,,
|
||||
celery/app/__pycache__/autoretry.cpython-310.pyc,,
|
||||
celery/app/__pycache__/backends.cpython-310.pyc,,
|
||||
celery/app/__pycache__/base.cpython-310.pyc,,
|
||||
celery/app/__pycache__/builtins.cpython-310.pyc,,
|
||||
celery/app/__pycache__/control.cpython-310.pyc,,
|
||||
celery/app/__pycache__/defaults.cpython-310.pyc,,
|
||||
celery/app/__pycache__/events.cpython-310.pyc,,
|
||||
celery/app/__pycache__/log.cpython-310.pyc,,
|
||||
celery/app/__pycache__/registry.cpython-310.pyc,,
|
||||
celery/app/__pycache__/routes.cpython-310.pyc,,
|
||||
celery/app/__pycache__/task.cpython-310.pyc,,
|
||||
celery/app/__pycache__/trace.cpython-310.pyc,,
|
||||
celery/app/__pycache__/utils.cpython-310.pyc,,
|
||||
celery/app/amqp.py,sha256=usxS_TMBWWRyHgDCTj-KHHpG7IREqB8YhqdH30kB9Pg,22985
|
||||
celery/app/annotations.py,sha256=93zuKNCE7pcMD3K5tM5HMeVCQ5lfJR_0htFpottgOeU,1445
|
||||
celery/app/autoretry.py,sha256=0RJAnhBl6PZss-xApBakTSaTHCwvOrg3sxiFJJ2Mvr0,2287
|
||||
celery/app/backends.py,sha256=_8yWU5m25OG-6U0Cjk7p5PBqbdXnZmdaEFyUDkkQO88,2750
|
||||
celery/app/base.py,sha256=7vhtjPCTdANy4vNFKxTCfUg0kuN8dhWxbMh_yeE2YyA,48394
|
||||
celery/app/builtins.py,sha256=gnOyE07M8zgxatTmb0D0vKztx1sQZaRi_hO_d-FLNUs,6673
|
||||
celery/app/control.py,sha256=rNz_QF8XDrDzK26PmhNM8BFVUAnU_XlR53QBOH9cM5E,27841
|
||||
celery/app/defaults.py,sha256=1CeMGFLsml3ZguZtFuKVMTgiEU9MxrC3iP63-Lomht4,14687
|
||||
celery/app/events.py,sha256=9ZyjdhUVvrt6xLdOMOVTPN7gjydLWQGNr4hvFoProuA,1326
|
||||
celery/app/log.py,sha256=TdLLTKeanwtPYGP2Yp7R71GbYG--vrj7DzPo3RGd3ZA,9148
|
||||
celery/app/registry.py,sha256=imdGUFb9CS4iiZ1pxAwcQAbe1JKKjyv9WTy94qHHQvk,2001
|
||||
celery/app/routes.py,sha256=DMdr5nmEnqJWXkLFIzWWxM2sz9ZYeA--8FeSaxKcBCg,4527
|
||||
celery/app/task.py,sha256=p0VH5OC1W3S1oXGoDU-hTh-AYWfRSVoPeHqwxWPNgHs,41604
|
||||
celery/app/trace.py,sha256=GmqOFy09-EC7rh3w3w0eyZzTgvrOMkTResJONdEky6U,27365
|
||||
celery/app/utils.py,sha256=sGqiAc10BSOWi_fmtgvixo04batVDwuFr2SFPriDkyU,13185
|
||||
celery/apps/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
celery/apps/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/apps/__pycache__/beat.cpython-310.pyc,,
|
||||
celery/apps/__pycache__/multi.cpython-310.pyc,,
|
||||
celery/apps/__pycache__/worker.cpython-310.pyc,,
|
||||
celery/apps/beat.py,sha256=jp8ZHMenzmaJ6WNNsLciXxSk_5sSyRCQo1Kyut1Ufeg,5145
|
||||
celery/apps/multi.py,sha256=MTRwjZNfve8ZMxdQlXyS16A3iFYzrt1DbS9jeojPb8U,16398
|
||||
celery/apps/worker.py,sha256=I5jZO1x5RTH-zcvjCE1YfA4JoQOhItQ7_TVN5ccRo9E,13463
|
||||
celery/backends/__init__.py,sha256=1kN92df1jDp3gC6mrGEZI2eE-kOEUIKdOOHRAdry2a0,23
|
||||
celery/backends/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/arangodb.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/asynchronous.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/azureblockblob.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/base.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/cache.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/cassandra.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/consul.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/cosmosdbsql.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/couchbase.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/couchdb.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/dynamodb.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/elasticsearch.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/filesystem.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/mongodb.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/redis.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/rpc.cpython-310.pyc,,
|
||||
celery/backends/__pycache__/s3.cpython-310.pyc,,
|
||||
celery/backends/arangodb.py,sha256=-UvpMlq0YcXGyJLmd99TEphp1TlwT-grwnrO56eWq5E,7737
|
||||
celery/backends/asynchronous.py,sha256=1_tCrURDVg0FvZhRzlRGYwTmsdWK14nBzvPulhwJeR4,10309
|
||||
celery/backends/azureblockblob.py,sha256=faVvwyxYRKhQpBnZvPNGgxja3mFNu8NxtW4j_222-w0,5168
|
||||
celery/backends/base.py,sha256=3ZGFacUPKQ1WH0AxiJNTjW2LBLCDZpW_tGM7pO5z1BQ,42695
|
||||
celery/backends/cache.py,sha256=Jqp7f_likS8azJupnjSNrstDoppyRcpZGdtmVgckbe8,4817
|
||||
celery/backends/cassandra.py,sha256=Xt4jw8dhaRdRQIO36H2ZJdetZpni8-nry1IAJaEDUlo,7890
|
||||
celery/backends/consul.py,sha256=oAB_94ftS95mjycQ4YL4zIdA-tGmwFyq3B0OreyBPNQ,3816
|
||||
celery/backends/cosmosdbsql.py,sha256=jMvoVdExNBsZ1seLhvThEZZpH_CcYo2AWtJJry9XZUg,6839
|
||||
celery/backends/couchbase.py,sha256=xRw4mbgjfyNtfd1X1mox3cPbcR4-emeJ6Re56F-X0Gk,3173
|
||||
celery/backends/couchdb.py,sha256=M_z0zgNFPwFw89paa5kIQ9x9o7VRPwuKCLZgoFhFDpA,2935
|
||||
celery/backends/database/__init__.py,sha256=ukNFAyO1PK8F9bm9S9VzDydCJVgAB3N-pSLufYyuQig,7771
|
||||
celery/backends/database/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/backends/database/__pycache__/models.cpython-310.pyc,,
|
||||
celery/backends/database/__pycache__/session.cpython-310.pyc,,
|
||||
celery/backends/database/models.py,sha256=_6WZMv53x8I1iBRCa4hY35LaBUeLIZJzDusjvS-8aAg,3351
|
||||
celery/backends/database/session.py,sha256=3zu7XwYoE52aS6dsSmJanqlvS6ssjet7hSNUbliwnLo,3011
|
||||
celery/backends/dynamodb.py,sha256=pX0qAo1HiajbznWd0EykV9suQn3O49BqxB9RXwIzN1o,17254
|
||||
celery/backends/elasticsearch.py,sha256=Wdua6fUyMjiUT1ZjOmi04nGqKBFtdmQEAmkFs89kAGg,8339
|
||||
celery/backends/filesystem.py,sha256=JS6mWmYi7BZOcazd2qoBWAFi7iD0Awi-OFEcvvOuCok,3762
|
||||
celery/backends/mongodb.py,sha256=_qWNuqfaYShexHcH6-dfQx4J3LUpGQgEDCImSCgAhRg,10725
|
||||
celery/backends/redis.py,sha256=j1qejSfq7JB1OxdEDGOythbrxMp_Lm69fRxmWXq1f4E,25879
|
||||
celery/backends/rpc.py,sha256=Pfzjpz7znOfmHRERuQfOlTW-entAsl803oc1-EWpnTY,12077
|
||||
celery/backends/s3.py,sha256=MUL4-bEHCcTL53XXyb020zyLYTr44DDjOh6BXtkp9lQ,2752
|
||||
celery/beat.py,sha256=1VzGn2431HNyjg6u_joaJqrWlzOvFK93So60s1x4a3E,24394
|
||||
celery/bin/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
celery/bin/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/amqp.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/base.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/beat.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/call.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/celery.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/control.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/events.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/graph.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/list.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/logtool.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/migrate.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/multi.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/purge.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/result.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/shell.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/upgrade.cpython-310.pyc,,
|
||||
celery/bin/__pycache__/worker.cpython-310.pyc,,
|
||||
celery/bin/amqp.py,sha256=GRyqsBHtR4ubEdjjPYD8cpGg4uPkHJ889wtzSklRxMg,10030
|
||||
celery/bin/base.py,sha256=dBYhih3Qh8bQ99-FJd4gJuYGI43Udmp1YVplL1qc_G8,8543
|
||||
celery/bin/beat.py,sha256=Iyn8Qz8vVCePCw5jhLC3X-YxxzOlwG2mYKt6VqyuDWE,2583
|
||||
celery/bin/call.py,sha256=CTr4YC3Lt83UUw4U3Hqm4Z4XWol7dflGXXcOf8p-liA,2399
|
||||
celery/bin/celery.py,sha256=4JH2_Y9E-HRPgGWuNeU-r548yuI90F8vL30bA2sBSts,6767
|
||||
celery/bin/control.py,sha256=0r69bCXUDGjy_WI_mI1Dj--_iP8byI7Ljvrxj2tBS9Y,7089
|
||||
celery/bin/events.py,sha256=KGq_RdSpLjYd1wkyeliQPWZPXwxMosq1_Fk9cbtsG2M,2825
|
||||
celery/bin/graph.py,sha256=Ld2dKSxIdWHxFXrjsTXAUBj6jb02AVGyTPXDUZA_gvo,5796
|
||||
celery/bin/list.py,sha256=2OKPiXn6sgum_02RH1d_TBoXcpNcNsooT98Ht9pWuaY,1058
|
||||
celery/bin/logtool.py,sha256=sqK4LfuAtHuVD7OTsKbKfvB2OkfOD-K37ac9i_F8NIs,4267
|
||||
celery/bin/migrate.py,sha256=3BcuNiigoqsE8PNtMYuZ3162LYeV9b3ILP2VggAyR0o,2139
|
||||
celery/bin/multi.py,sha256=AKKMnm__5b2jIiOtZBeEsHUDrXLBE5RTlJeTMQk6Ir8,15364
|
||||
celery/bin/purge.py,sha256=WudoOOROcIh3yFVb2vHyZ9pRkrpKoebE_gFJz4rXQxw,2578
|
||||
celery/bin/result.py,sha256=TK2k84Mqh1nQ3XIOT_EN3Y4Y3h5ZcJIH8MEU-YIgJIE,1007
|
||||
celery/bin/shell.py,sha256=HxSoyFIpwEY9vp6bt6_5XDN4R2hfm0bVO7Ska2Y7R60,4809
|
||||
celery/bin/upgrade.py,sha256=S9QjG6Dq87G0JE3hro3Ri_1AexQddql_4X6Fcsj_340,3095
|
||||
celery/bin/worker.py,sha256=JaxyT0Wa_IyI7G9l5chaJ2URcQ8MA0d9C7tqkNFSixQ,12789
|
||||
celery/bootsteps.py,sha256=ddrxGDRCc2ra2ug0X5NBEI3fqPjkSlNRiYSXg2vGCq0,12297
|
||||
celery/canvas.py,sha256=ZmhtB6_wWsM_Atpcy6v07Y0l_-5AQJ3_VmytoI3YZ48,63287
|
||||
celery/concurrency/__init__.py,sha256=VbmcXYILbO6wUYaIS3zocU_XhUArX8Pt36yXuqFJJKY,995
|
||||
celery/concurrency/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/concurrency/__pycache__/asynpool.cpython-310.pyc,,
|
||||
celery/concurrency/__pycache__/base.cpython-310.pyc,,
|
||||
celery/concurrency/__pycache__/eventlet.cpython-310.pyc,,
|
||||
celery/concurrency/__pycache__/gevent.cpython-310.pyc,,
|
||||
celery/concurrency/__pycache__/prefork.cpython-310.pyc,,
|
||||
celery/concurrency/__pycache__/solo.cpython-310.pyc,,
|
||||
celery/concurrency/__pycache__/thread.cpython-310.pyc,,
|
||||
celery/concurrency/asynpool.py,sha256=Imb_7zNJuSdSsS6q710FOyqsO138tp_O_ysjMjXj5xU,50997
|
||||
celery/concurrency/base.py,sha256=MXjG1Aft74cXG5c7VL1afmDA68ZBz0HqunhRSD55JVE,4373
|
||||
celery/concurrency/eventlet.py,sha256=i4Xn3Kqg0cxbMyw7_aCTVCi7EOA5aLEiRdkb1xMTpvM,5126
|
||||
celery/concurrency/gevent.py,sha256=AkZ8Vn0Cx8m5Gk7j1OKP0Dc8NBpFW-hyc-yXrwGBCrs,3407
|
||||
celery/concurrency/prefork.py,sha256=BEswWP6p_cgflkGyPGdvQpobu71G2Lr3AQW7jnexChA,5789
|
||||
celery/concurrency/solo.py,sha256=WcOi0h4sJlE7WbR7DbHwZiHRE1-jlwMPW_4ENckQFKk,693
|
||||
celery/concurrency/thread.py,sha256=n-7ayKpyM80nRIQcxUVJo1yZLezI4n5IjWkfkXqTA6g,1248
|
||||
celery/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
celery/contrib/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/contrib/__pycache__/abortable.cpython-310.pyc,,
|
||||
celery/contrib/__pycache__/migrate.cpython-310.pyc,,
|
||||
celery/contrib/__pycache__/pytest.cpython-310.pyc,,
|
||||
celery/contrib/__pycache__/rdb.cpython-310.pyc,,
|
||||
celery/contrib/__pycache__/sphinx.cpython-310.pyc,,
|
||||
celery/contrib/abortable.py,sha256=ugEGSW0AO10Cee5sFrZMLL2H2r1b_ubbCXcbJNMjyw0,5091
|
||||
celery/contrib/migrate.py,sha256=-kCp6B4C6-HdK9YGDxjSDyROF_0VLIV5PzVJXmhJKrw,14163
|
||||
celery/contrib/pytest.py,sha256=Ngxpp9pTMJP5BzSEuWDw6CpPo7Z8f-ZQFSScWtxKVww,6747
|
||||
celery/contrib/rdb.py,sha256=Ek_FGkFUelOjxF0pG1Kc4pwfPdamWhGBCrco_G8ZbRw,5023
|
||||
celery/contrib/sphinx.py,sha256=2qLMuKpKm5Kwtvjfx_brDDjonIMaZptypMMuhDWShRc,3410
|
||||
celery/contrib/testing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
celery/contrib/testing/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/contrib/testing/__pycache__/app.cpython-310.pyc,,
|
||||
celery/contrib/testing/__pycache__/manager.cpython-310.pyc,,
|
||||
celery/contrib/testing/__pycache__/mocks.cpython-310.pyc,,
|
||||
celery/contrib/testing/__pycache__/tasks.cpython-310.pyc,,
|
||||
celery/contrib/testing/__pycache__/worker.cpython-310.pyc,,
|
||||
celery/contrib/testing/app.py,sha256=nOcIjxGleSGp1HG9g3NqkeqOpvB_J370BqRldY1g97o,3017
|
||||
celery/contrib/testing/manager.py,sha256=1ACTOa35nwUIqKDq9WZpBGnBXZpgs6yDOVlKqtAWaYU,7723
|
||||
celery/contrib/testing/mocks.py,sha256=awhxvErtp9C5XMGbJXcpNsK2gODb87lES_SvgKaMYb4,4158
|
||||
celery/contrib/testing/tasks.py,sha256=pJM3aabw7udcppz4QNeUg1-6nlnbklrT-hP5JXmL-gM,208
|
||||
celery/contrib/testing/worker.py,sha256=Ewzz8HZRfC5mYgDpOsYyx9UHewbqO4xJcGdgmtiO1pU,5569
|
||||
celery/events/__init__.py,sha256=9d2cviCw5zIsZ3AvQJkx77HPTlxmVIahRR7Qa54nQnU,477
|
||||
celery/events/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/events/__pycache__/cursesmon.cpython-310.pyc,,
|
||||
celery/events/__pycache__/dispatcher.cpython-310.pyc,,
|
||||
celery/events/__pycache__/dumper.cpython-310.pyc,,
|
||||
celery/events/__pycache__/event.cpython-310.pyc,,
|
||||
celery/events/__pycache__/receiver.cpython-310.pyc,,
|
||||
celery/events/__pycache__/snapshot.cpython-310.pyc,,
|
||||
celery/events/__pycache__/state.cpython-310.pyc,,
|
||||
celery/events/cursesmon.py,sha256=z92gxRgnW5NJu9h6o4EAqLIDLu8HNjxn_nivP__3C_Q,18037
|
||||
celery/events/dispatcher.py,sha256=7b3-3d_6ukvRNajyfiHMX1YvoWNIzaB6zS3-zEUQhG4,8987
|
||||
celery/events/dumper.py,sha256=7zOVmAVfG2HXW79Fuvpo_0C2cjztTzgIXnaiUc4NL8c,3116
|
||||
celery/events/event.py,sha256=nt1yRUzDrYp9YLbsIJD3eo_AoMhT5sQtZAX-vEkq4Q8,1736
|
||||
celery/events/receiver.py,sha256=7dVvezYkBQOtyI-rH77-5QDJztPLB933VF7NgmezSuU,4998
|
||||
celery/events/snapshot.py,sha256=OLQuxx1af29LKnYKDoTesnPfK_5dFx3zCZ7JSdg9t7A,3294
|
||||
celery/events/state.py,sha256=ss9tQCo_IKE9gwYTAjwwsBiwPVavCte-43IJj89ycB8,25750
|
||||
celery/exceptions.py,sha256=uCD2SnbL6aOcyMGA5E1Eqw0IWDGUzQ-FJktuLlor7tE,9030
|
||||
celery/fixups/__init__.py,sha256=7ctNaKHiOa2fVePcdKPU9J-_bQ0k1jFHaoZlCHXY0vU,14
|
||||
celery/fixups/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/fixups/__pycache__/django.cpython-310.pyc,,
|
||||
celery/fixups/django.py,sha256=SlC-AdxBWkMYQoH6TB4A4dcIMIgZUbpdoJLJrJbGQ5U,6588
|
||||
celery/loaders/__init__.py,sha256=LnRTWk8pz2r7BUj2VUJiBstPjSBwCP0gUDRkbchGW24,490
|
||||
celery/loaders/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/loaders/__pycache__/app.cpython-310.pyc,,
|
||||
celery/loaders/__pycache__/base.cpython-310.pyc,,
|
||||
celery/loaders/__pycache__/default.cpython-310.pyc,,
|
||||
celery/loaders/app.py,sha256=xqRpRDJkGmTW21N_7zx5F4Na-GCTbNs6Q6tGfInnZnU,199
|
||||
celery/loaders/base.py,sha256=D4a73XmRVw-iLGQqHjeHd9sreideDhb7NVW2_KUjNfE,8861
|
||||
celery/loaders/default.py,sha256=TZq6zR4tg_20sVJAuSwSBLVRHRyfevHkHhUYrNRYkTU,1520
|
||||
celery/local.py,sha256=tT3j-aMWbakh7wSuAeP1EzgjuxgtXHNBtORgWvLXfL8,16312
|
||||
celery/platforms.py,sha256=VOOds3YPv8sOTlKopLD6Y7Prh6tlwonyo8jt9S9wAJQ,25564
|
||||
celery/result.py,sha256=1NVXQOdsAZWbVr3XGxJvVpPjQSAnFyHQKrADMNlu6xc,34179
|
||||
celery/schedules.py,sha256=pd76afTlCgt2S9BaTSmX_cylzlvTrrv_j6aRYQInmVA,29251
|
||||
celery/security/__init__.py,sha256=BdtPN8PyVbNytifqz5rxfLjQx5ltFxJo8WwM-MSLCtM,2274
|
||||
celery/security/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/security/__pycache__/certificate.cpython-310.pyc,,
|
||||
celery/security/__pycache__/key.cpython-310.pyc,,
|
||||
celery/security/__pycache__/serialization.cpython-310.pyc,,
|
||||
celery/security/__pycache__/utils.cpython-310.pyc,,
|
||||
celery/security/certificate.py,sha256=X8Y32ssuEkEh8K0cTPXDzHHhLxEayEXX2ggDXeGFjpU,2991
|
||||
celery/security/key.py,sha256=AP-8kBfqaT8a6IpZsf2qALTCVB36RsoqN7e555VF6mw,1042
|
||||
celery/security/serialization.py,sha256=bOPi_ugy9EhmneLjjALvt-ZrwFCtPqQwH7f4zcqdq3I,4206
|
||||
celery/security/utils.py,sha256=VJuWxLZFKXQXzlBczuxo94wXWSULnXwbO_5ul_hwse0,845
|
||||
celery/signals.py,sha256=CgnwpZUNMZZqKIKOrCjsDnmxCSHSNgRXIjZFZ0uqlt4,4273
|
||||
celery/states.py,sha256=iIBdd02UPwDKTIYm9MGlIgHGBmrr9AzGgvbeBkPgSyU,3260
|
||||
celery/utils/__init__.py,sha256=lIJjBxvXCspC-ib-XasdEPlB0xAQc16P0eOPb0gWsL0,935
|
||||
celery/utils/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/abstract.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/collections.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/debug.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/deprecated.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/functional.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/graph.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/imports.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/iso8601.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/log.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/nodenames.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/objects.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/saferepr.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/serialization.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/sysinfo.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/term.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/text.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/threads.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/time.cpython-310.pyc,,
|
||||
celery/utils/__pycache__/timer2.cpython-310.pyc,,
|
||||
celery/utils/abstract.py,sha256=xN2Qr-TEp12P8AYO6WigxFr5p8kJPUUb0f5UX3FtHjI,2874
|
||||
celery/utils/collections.py,sha256=QWTMwJf0sWvE1QAkaUQwFNfSnDo44aFDpCurKU48CIw,25635
|
||||
celery/utils/debug.py,sha256=9g5U0NlTvlP9OFwjxfyXgihfzD-Kk_fcy7QDjhkqapw,4709
|
||||
celery/utils/deprecated.py,sha256=4asPe222TWJh8mcL53Ob6Y7XROPgqv23nCR-EUHJoBo,3620
|
||||
celery/utils/dispatch/__init__.py,sha256=s0_ZpvFWXw1cecEue1vj-MpOPQUPE41g5s-YsjnX6mo,74
|
||||
celery/utils/dispatch/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/utils/dispatch/__pycache__/signal.cpython-310.pyc,,
|
||||
celery/utils/dispatch/signal.py,sha256=LcmfBabnRAOR-wiADWQfBT-gN3Lzi29JpAcCvMLNNX4,13603
|
||||
celery/utils/functional.py,sha256=jX0PzVjGnzAKqSYdLCdPj67vW7sWCLgdj61UdSFVIeA,11762
|
||||
celery/utils/graph.py,sha256=oP25YXsQfND-VwF-MGolOGX0GbReIzVc9SJfIP1rUIc,9041
|
||||
celery/utils/imports.py,sha256=HEJWtHkRLN43Kva4WNsPROB47MIS_tjw27If5W0-NjY,4801
|
||||
celery/utils/iso8601.py,sha256=GaYiljjWBC42I1MXK2wljO2rupplPIibIcnSGWb7Pzs,2776
|
||||
celery/utils/log.py,sha256=_O-qrGkhPsSlwnGO4M-xM85dV26pr1eBbxWCIYUd6po,8809
|
||||
celery/utils/nodenames.py,sha256=URBwdtWR_CF8Ldf6tjxE4y7rl0KxFFD36HjjZcrwQ5Y,2858
|
||||
celery/utils/objects.py,sha256=NZ_Nx0ehrJut91sruAI2kVGyjhaDQR_ntTmF9Om_SI8,4215
|
||||
celery/utils/saferepr.py,sha256=SAFxeh0_oquPJFKzADklT1twCei4GnJsvAhdT09fPvM,9175
|
||||
celery/utils/serialization.py,sha256=E26LbVSyEbXncF9hrz9a3xBlkVGpP1g1fmDYGC4eOF8,8043
|
||||
celery/utils/static/__init__.py,sha256=KwDq8hA-Xd721HldwJJ34ExwrIEyngEoSIzeAnqc5CA,299
|
||||
celery/utils/static/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/utils/static/celery_128.png,sha256=8NmZxCALQPp3KVOsOPfJVaNLvwwLYqiS5ViOc6x0SGU,2556
|
||||
celery/utils/sysinfo.py,sha256=LYdGzxbF357PrYNw31_9f8CEvrldtb0VAWIFclBtCnA,1085
|
||||
celery/utils/term.py,sha256=iHs42Ou4NEv57gxLWXqDNeT21YouhjK02vJ0bbltD5k,4568
|
||||
celery/utils/text.py,sha256=qYD21O_ItBWiS6dwi0d2AvdUUnhJqNyVvkGQYUgoOF4,5816
|
||||
celery/utils/threads.py,sha256=MIaWXDAAVr3qrH17OQwigzvKLWh-b4M-y_nkJFOjqnQ,9592
|
||||
celery/utils/time.py,sha256=rZHhbvzAEI5vag63jQUIArbqZYBMTO7IpZ2vPgqrQzQ,12372
|
||||
celery/utils/timer2.py,sha256=xv_7x_bDtILx4regqEm1ppQNenozSwOXi-21qQ4EJG4,4813
|
||||
celery/worker/__init__.py,sha256=EKUgWOMq_1DfWb-OaAWv4rNLd7gi91aidefMjHMoxzI,95
|
||||
celery/worker/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/autoscale.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/components.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/control.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/heartbeat.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/loops.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/pidbox.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/request.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/state.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/strategy.cpython-310.pyc,,
|
||||
celery/worker/__pycache__/worker.cpython-310.pyc,,
|
||||
celery/worker/autoscale.py,sha256=kzb1GTwRyw9DZFjwIvHrcLdJxuIGI8HaHdtvtr31i9A,4593
|
||||
celery/worker/components.py,sha256=Zlu5I0maDCaF1qSNtwS8jJe2okISsQc5KFvfuzBiZvs,7517
|
||||
celery/worker/consumer/__init__.py,sha256=yKaGZtBzYKADZMzbSq14_AUYpT4QAY9nRRCf73DDhqc,391
|
||||
celery/worker/consumer/__pycache__/__init__.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/agent.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/connection.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/consumer.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/control.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/events.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/gossip.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/heart.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/mingle.cpython-310.pyc,,
|
||||
celery/worker/consumer/__pycache__/tasks.cpython-310.pyc,,
|
||||
celery/worker/consumer/agent.py,sha256=bThS8ZVeuybAyqNe8jmdN6RgaJhDq0llewosGrO85-c,525
|
||||
celery/worker/consumer/connection.py,sha256=a7g23wmzevkEiMjjjD8Kt4scihf_NgkpR4gcuksys9M,1026
|
||||
celery/worker/consumer/consumer.py,sha256=ygyBVrOa7EWS3xQuD6F9833uTISCEhqjm1-TtlQZsU8,22951
|
||||
celery/worker/consumer/control.py,sha256=0NiJ9P-AHdv134mXkgRgU9hfhdJ_P7HKb7z9A4Xqa2Q,946
|
||||
celery/worker/consumer/events.py,sha256=FgDwbV0Jbj9aWPbV3KAUtsXZq4JvZEfrWfnrYgvkMgo,2054
|
||||
celery/worker/consumer/gossip.py,sha256=g-WJL2rr_q9aM_SaTUrQlPj2ONf8vHs2LvmyRQtDMEU,6833
|
||||
celery/worker/consumer/heart.py,sha256=IenkkliKk6sAk2a1NfYyh-doNDlmFWGRiaJd5e8ALpI,930
|
||||
celery/worker/consumer/mingle.py,sha256=UG8K6sXF1KUJXNiJ4eMHUMIg4_7K1tDWqYRNfd9Nz9k,2519
|
||||
celery/worker/consumer/tasks.py,sha256=lYjn-Mt2ZulQyO1lwSoMRzCKeWd8f955H_VfGG0-cyg,1959
|
||||
celery/worker/control.py,sha256=gqd3NO81v99MN889-XMjJYObq1oOX-0yT-ZzNdMQKJY,16885
|
||||
celery/worker/heartbeat.py,sha256=sTV_d0RB9M6zsXIvLZ7VU6teUfX3IK1ITynDpxMS298,2107
|
||||
celery/worker/loops.py,sha256=W9ayCwYXOA0aCxPPotXc49uA_n7CnMsDRPJVUNb8bZM,4433
|
||||
celery/worker/pidbox.py,sha256=LcQsKDkd8Z93nQxk0SOLulB8GLEfIjPkN-J0pGk7dfM,3630
|
||||
celery/worker/request.py,sha256=yW6wzKJLWTdmc179oHoTlmcQuHH-PuVMeoz6-DAOZVc,25214
|
||||
celery/worker/state.py,sha256=CjxPzNlrN1PJ1zRsz0M616KZIkChS1JzB-8Xabaizh0,8177
|
||||
celery/worker/strategy.py,sha256=ql2jbCu7ctrDbxxuWPRo0XFKQJrJv_m_uErb9NpnEAI,7349
|
||||
celery/worker/worker.py,sha256=xVWqd88ZSAgi6kq_ZWuwmII5hE5YFQt-tORhUsdsDpc,14513
|
||||
File renamed without changes.
@@ -0,0 +1,5 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.37.1)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[console_scripts]
|
||||
celery = celery.__main__:main
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
celery
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Distributed Task Queue."""
|
||||
# :copyright: (c) 2016-2026 Asif Saif Uddin, celery core and individual
|
||||
# contributors, All rights reserved.
|
||||
# :copyright: (c) 2015-2016 Ask Solem. All rights reserved.
|
||||
# :copyright: (c) 2012-2014 GoPivotal, Inc., All rights reserved.
|
||||
# :copyright: (c) 2009 - 2012 Ask Solem and individual contributors,
|
||||
# All rights reserved.
|
||||
# :license: BSD (3 Clause), see LICENSE for more details.
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections import namedtuple
|
||||
|
||||
# Lazy loading
|
||||
from . import local
|
||||
|
||||
SERIES = 'dawn-chorus'
|
||||
|
||||
__version__ = '5.2.7'
|
||||
__author__ = 'Ask Solem'
|
||||
__contact__ = 'auvipy@gmail.com'
|
||||
__homepage__ = 'http://celeryproject.org'
|
||||
__docformat__ = 'restructuredtext'
|
||||
__keywords__ = 'task job queue distributed messaging actor'
|
||||
|
||||
# -eof meta-
|
||||
|
||||
__all__ = (
|
||||
'Celery', 'bugreport', 'shared_task', 'Task',
|
||||
'current_app', 'current_task', 'maybe_signature',
|
||||
'chain', 'chord', 'chunks', 'group', 'signature',
|
||||
'xmap', 'xstarmap', 'uuid',
|
||||
)
|
||||
|
||||
VERSION_BANNER = f'{__version__} ({SERIES})'
|
||||
|
||||
version_info_t = namedtuple('version_info_t', (
|
||||
'major', 'minor', 'micro', 'releaselevel', 'serial',
|
||||
))
|
||||
|
||||
# bumpversion can only search for {current_version}
|
||||
# so we have to parse the version here.
|
||||
_temp = re.match(
|
||||
r'(\d+)\.(\d+).(\d+)(.+)?', __version__).groups()
|
||||
VERSION = version_info = version_info_t(
|
||||
int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '')
|
||||
del _temp
|
||||
del re
|
||||
|
||||
if os.environ.get('C_IMPDEBUG'): # pragma: no cover
|
||||
import builtins
|
||||
|
||||
def debug_import(name, locals=None, globals=None,
|
||||
fromlist=None, level=-1, real_import=builtins.__import__):
|
||||
glob = globals or getattr(sys, 'emarfteg_'[::-1])(1).f_globals
|
||||
importer_name = glob and glob.get('__name__') or 'unknown'
|
||||
print(f'-- {importer_name} imports {name}')
|
||||
return real_import(name, locals, globals, fromlist, level)
|
||||
builtins.__import__ = debug_import
|
||||
|
||||
# This is never executed, but tricks static analyzers (PyDev, PyCharm,
|
||||
# pylint, etc.) into knowing the types of these symbols, and what
|
||||
# they contain.
|
||||
STATICA_HACK = True
|
||||
globals()['kcah_acitats'[::-1].upper()] = False
|
||||
if STATICA_HACK: # pragma: no cover
|
||||
from celery._state import current_app, current_task
|
||||
from celery.app import shared_task
|
||||
from celery.app.base import Celery
|
||||
from celery.app.task import Task
|
||||
from celery.app.utils import bugreport
|
||||
from celery.canvas import (chain, chord, chunks, group, # noqa
|
||||
maybe_signature, signature, subtask, xmap,
|
||||
xstarmap)
|
||||
from celery.utils import uuid
|
||||
|
||||
# Eventlet/gevent patching must happen before importing
|
||||
# anything else, so these tools must be at top-level.
|
||||
|
||||
|
||||
def _find_option_with_arg(argv, short_opts=None, long_opts=None):
|
||||
"""Search argv for options specifying short and longopt alternatives.
|
||||
|
||||
Returns:
|
||||
str: value for option found
|
||||
Raises:
|
||||
KeyError: if option not found.
|
||||
"""
|
||||
for i, arg in enumerate(argv):
|
||||
if arg.startswith('-'):
|
||||
if long_opts and arg.startswith('--'):
|
||||
name, sep, val = arg.partition('=')
|
||||
if name in long_opts:
|
||||
return val if sep else argv[i + 1]
|
||||
if short_opts and arg in short_opts:
|
||||
return argv[i + 1]
|
||||
raise KeyError('|'.join(short_opts or [] + long_opts or []))
|
||||
|
||||
|
||||
def _patch_eventlet():
|
||||
import eventlet.debug
|
||||
|
||||
eventlet.monkey_patch()
|
||||
blockdetect = float(os.environ.get('EVENTLET_NOBLOCK', 0))
|
||||
if blockdetect:
|
||||
eventlet.debug.hub_blocking_detection(blockdetect, blockdetect)
|
||||
|
||||
|
||||
def _patch_gevent():
|
||||
import gevent.monkey
|
||||
import gevent.signal
|
||||
|
||||
gevent.monkey.patch_all()
|
||||
|
||||
|
||||
def maybe_patch_concurrency(argv=None, short_opts=None,
|
||||
long_opts=None, patches=None):
|
||||
"""Apply eventlet/gevent monkeypatches.
|
||||
|
||||
With short and long opt alternatives that specify the command line
|
||||
option to set the pool, this makes sure that anything that needs
|
||||
to be patched is completed as early as possible.
|
||||
(e.g., eventlet/gevent monkey patches).
|
||||
"""
|
||||
argv = argv if argv else sys.argv
|
||||
short_opts = short_opts if short_opts else ['-P']
|
||||
long_opts = long_opts if long_opts else ['--pool']
|
||||
patches = patches if patches else {'eventlet': _patch_eventlet,
|
||||
'gevent': _patch_gevent}
|
||||
try:
|
||||
pool = _find_option_with_arg(argv, short_opts, long_opts)
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
patcher = patches[pool]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
patcher()
|
||||
|
||||
# set up eventlet/gevent environments ASAP
|
||||
from celery import concurrency
|
||||
if pool in concurrency.get_available_pool_names():
|
||||
concurrency.get_implementation(pool)
|
||||
|
||||
|
||||
# this just creates a new module, that imports stuff on first attribute
|
||||
# access. This makes the library faster to use.
|
||||
old_module, new_module = local.recreate_module( # pragma: no cover
|
||||
__name__,
|
||||
by_module={
|
||||
'celery.app': ['Celery', 'bugreport', 'shared_task'],
|
||||
'celery.app.task': ['Task'],
|
||||
'celery._state': ['current_app', 'current_task'],
|
||||
'celery.canvas': [
|
||||
'Signature', 'chain', 'chord', 'chunks', 'group',
|
||||
'signature', 'maybe_signature', 'subtask',
|
||||
'xmap', 'xstarmap',
|
||||
],
|
||||
'celery.utils': ['uuid'],
|
||||
},
|
||||
__package__='celery', __file__=__file__,
|
||||
__path__=__path__, __doc__=__doc__, __version__=__version__,
|
||||
__author__=__author__, __contact__=__contact__,
|
||||
__homepage__=__homepage__, __docformat__=__docformat__, local=local,
|
||||
VERSION=VERSION, SERIES=SERIES, VERSION_BANNER=VERSION_BANNER,
|
||||
version_info_t=version_info_t,
|
||||
version_info=version_info,
|
||||
maybe_patch_concurrency=maybe_patch_concurrency,
|
||||
_find_option_with_arg=_find_option_with_arg,
|
||||
)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Entry-point for the :program:`celery` umbrella command."""
|
||||
|
||||
import sys
|
||||
|
||||
from . import maybe_patch_concurrency
|
||||
|
||||
__all__ = ('main',)
|
||||
|
||||
|
||||
def main():
|
||||
"""Entrypoint to the ``celery`` umbrella command."""
|
||||
if 'multi' not in sys.argv:
|
||||
maybe_patch_concurrency()
|
||||
from celery.bin.celery import main as _main
|
||||
sys.exit(_main())
|
||||
|
||||
|
||||
if __name__ == '__main__': # pragma: no cover
|
||||
main()
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Internal state.
|
||||
|
||||
This is an internal module containing thread state
|
||||
like the ``current_app``, and ``current_task``.
|
||||
|
||||
This module shouldn't be used directly.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import weakref
|
||||
|
||||
from celery.local import Proxy
|
||||
from celery.utils.threads import LocalStack
|
||||
|
||||
__all__ = (
|
||||
'set_default_app', 'get_current_app', 'get_current_task',
|
||||
'get_current_worker_task', 'current_app', 'current_task',
|
||||
'connect_on_app_finalize',
|
||||
)
|
||||
|
||||
#: Global default app used when no current app.
|
||||
default_app = None
|
||||
|
||||
#: Function returning the app provided or the default app if none.
|
||||
#:
|
||||
#: The environment variable :envvar:`CELERY_TRACE_APP` is used to
|
||||
#: trace app leaks. When enabled an exception is raised if there
|
||||
#: is no active app.
|
||||
app_or_default = None
|
||||
|
||||
#: List of all app instances (weakrefs), mustn't be used directly.
|
||||
_apps = weakref.WeakSet()
|
||||
|
||||
#: Global set of functions to call whenever a new app is finalized.
|
||||
#: Shared tasks, and built-in tasks are created by adding callbacks here.
|
||||
_on_app_finalizers = set()
|
||||
|
||||
_task_join_will_block = False
|
||||
|
||||
|
||||
def connect_on_app_finalize(callback):
|
||||
"""Connect callback to be called when any app is finalized."""
|
||||
_on_app_finalizers.add(callback)
|
||||
return callback
|
||||
|
||||
|
||||
def _announce_app_finalized(app):
|
||||
callbacks = set(_on_app_finalizers)
|
||||
for callback in callbacks:
|
||||
callback(app)
|
||||
|
||||
|
||||
def _set_task_join_will_block(blocks):
|
||||
global _task_join_will_block
|
||||
_task_join_will_block = blocks
|
||||
|
||||
|
||||
def task_join_will_block():
|
||||
return _task_join_will_block
|
||||
|
||||
|
||||
class _TLS(threading.local):
|
||||
#: Apps with the :attr:`~celery.app.base.BaseApp.set_as_current` attribute
|
||||
#: sets this, so it will always contain the last instantiated app,
|
||||
#: and is the default app returned by :func:`app_or_default`.
|
||||
current_app = None
|
||||
|
||||
|
||||
_tls = _TLS()
|
||||
|
||||
_task_stack = LocalStack()
|
||||
|
||||
|
||||
#: Function used to push a task to the thread local stack
|
||||
#: keeping track of the currently executing task.
|
||||
#: You must remember to pop the task after.
|
||||
push_current_task = _task_stack.push
|
||||
|
||||
#: Function used to pop a task from the thread local stack
|
||||
#: keeping track of the currently executing task.
|
||||
pop_current_task = _task_stack.pop
|
||||
|
||||
|
||||
def set_default_app(app):
|
||||
"""Set default app."""
|
||||
global default_app
|
||||
default_app = app
|
||||
|
||||
|
||||
def _get_current_app():
|
||||
if default_app is None:
|
||||
#: creates the global fallback app instance.
|
||||
from celery.app.base import Celery
|
||||
set_default_app(Celery(
|
||||
'default', fixups=[], set_as_current=False,
|
||||
loader=os.environ.get('CELERY_LOADER') or 'default',
|
||||
))
|
||||
return _tls.current_app or default_app
|
||||
|
||||
|
||||
def _set_current_app(app):
|
||||
_tls.current_app = app
|
||||
|
||||
|
||||
if os.environ.get('C_STRICT_APP'): # pragma: no cover
|
||||
def get_current_app():
|
||||
"""Return the current app."""
|
||||
raise RuntimeError('USES CURRENT APP')
|
||||
elif os.environ.get('C_WARN_APP'): # pragma: no cover
|
||||
def get_current_app():
|
||||
import traceback
|
||||
print('-- USES CURRENT_APP', file=sys.stderr) # +
|
||||
traceback.print_stack(file=sys.stderr)
|
||||
return _get_current_app()
|
||||
else:
|
||||
get_current_app = _get_current_app
|
||||
|
||||
|
||||
def get_current_task():
|
||||
"""Currently executing task."""
|
||||
return _task_stack.top
|
||||
|
||||
|
||||
def get_current_worker_task():
|
||||
"""Currently executing task, that was applied by the worker.
|
||||
|
||||
This is used to differentiate between the actual task
|
||||
executed by the worker and any task that was called within
|
||||
a task (using ``task.__call__`` or ``task.apply``)
|
||||
"""
|
||||
for task in reversed(_task_stack.stack):
|
||||
if not task.request.called_directly:
|
||||
return task
|
||||
|
||||
|
||||
#: Proxy to current app.
|
||||
current_app = Proxy(get_current_app)
|
||||
|
||||
#: Proxy to current task.
|
||||
current_task = Proxy(get_current_task)
|
||||
|
||||
|
||||
def _register_app(app):
|
||||
_apps.add(app)
|
||||
|
||||
|
||||
def _deregister_app(app):
|
||||
_apps.discard(app)
|
||||
|
||||
|
||||
def _get_active_apps():
|
||||
return _apps
|
||||
|
||||
|
||||
def _app_or_default(app=None):
|
||||
if app is None:
|
||||
return get_current_app()
|
||||
return app
|
||||
|
||||
|
||||
def _app_or_default_trace(app=None): # pragma: no cover
|
||||
from traceback import print_stack
|
||||
try:
|
||||
from billiard.process import current_process
|
||||
except ImportError:
|
||||
current_process = None
|
||||
if app is None:
|
||||
if getattr(_tls, 'current_app', None):
|
||||
print('-- RETURNING TO CURRENT APP --') # +
|
||||
print_stack()
|
||||
return _tls.current_app
|
||||
if not current_process or current_process()._name == 'MainProcess':
|
||||
raise Exception('DEFAULT APP')
|
||||
print('-- RETURNING TO DEFAULT APP --') # +
|
||||
print_stack()
|
||||
return default_app
|
||||
return app
|
||||
|
||||
|
||||
def enable_trace():
|
||||
"""Enable tracing of app instances."""
|
||||
global app_or_default
|
||||
app_or_default = _app_or_default_trace
|
||||
|
||||
|
||||
def disable_trace():
|
||||
"""Disable tracing of app instances."""
|
||||
global app_or_default
|
||||
app_or_default = _app_or_default
|
||||
|
||||
|
||||
if os.environ.get('CELERY_TRACE_APP'): # pragma: no cover
|
||||
enable_trace()
|
||||
else:
|
||||
disable_trace()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Celery Application."""
|
||||
from celery import _state
|
||||
from celery._state import (app_or_default, disable_trace, enable_trace,
|
||||
pop_current_task, push_current_task)
|
||||
from celery.local import Proxy
|
||||
|
||||
from .base import Celery
|
||||
from .utils import AppPickler
|
||||
|
||||
__all__ = (
|
||||
'Celery', 'AppPickler', 'app_or_default', 'default_app',
|
||||
'bugreport', 'enable_trace', 'disable_trace', 'shared_task',
|
||||
'push_current_task', 'pop_current_task',
|
||||
)
|
||||
|
||||
#: Proxy always returning the app set as default.
|
||||
default_app = Proxy(lambda: _state.default_app)
|
||||
|
||||
|
||||
def bugreport(app=None):
|
||||
"""Return information useful in bug reports."""
|
||||
return (app or _state.get_current_app()).bugreport()
|
||||
|
||||
|
||||
def shared_task(*args, **kwargs):
|
||||
"""Create shared task (decorator).
|
||||
|
||||
This can be used by library authors to create tasks that'll work
|
||||
for any app environment.
|
||||
|
||||
Returns:
|
||||
~celery.local.Proxy: A proxy that always takes the task from the
|
||||
current apps task registry.
|
||||
|
||||
Example:
|
||||
|
||||
>>> from celery import Celery, shared_task
|
||||
>>> @shared_task
|
||||
... def add(x, y):
|
||||
... return x + y
|
||||
...
|
||||
>>> app1 = Celery(broker='amqp://')
|
||||
>>> add.app is app1
|
||||
True
|
||||
>>> app2 = Celery(broker='redis://')
|
||||
>>> add.app is app2
|
||||
True
|
||||
"""
|
||||
def create_shared_task(**options):
|
||||
|
||||
def __inner(fun):
|
||||
name = options.get('name')
|
||||
# Set as shared task so that unfinalized apps,
|
||||
# and future apps will register a copy of this task.
|
||||
_state.connect_on_app_finalize(
|
||||
lambda app: app._task_from_fun(fun, **options)
|
||||
)
|
||||
|
||||
# Force all finalized apps to take this task as well.
|
||||
for app in _state._get_active_apps():
|
||||
if app.finalized:
|
||||
with app._finalize_mutex:
|
||||
app._task_from_fun(fun, **options)
|
||||
|
||||
# Return a proxy that always gets the task from the current
|
||||
# apps task registry.
|
||||
def task_by_cons():
|
||||
app = _state.get_current_app()
|
||||
return app.tasks[
|
||||
name or app.gen_task_name(fun.__name__, fun.__module__)
|
||||
]
|
||||
return Proxy(task_by_cons)
|
||||
return __inner
|
||||
|
||||
if len(args) == 1 and callable(args[0]):
|
||||
return create_shared_task(**kwargs)(args[0])
|
||||
return create_shared_task(*args, **kwargs)
|
||||
@@ -0,0 +1,607 @@
|
||||
"""Sending/Receiving Messages (Kombu integration)."""
|
||||
import numbers
|
||||
from collections import namedtuple
|
||||
from collections.abc import Mapping
|
||||
from datetime import timedelta
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
from kombu import Connection, Consumer, Exchange, Producer, Queue, pools
|
||||
from kombu.common import Broadcast
|
||||
from kombu.utils.functional import maybe_list
|
||||
from kombu.utils.objects import cached_property
|
||||
|
||||
from celery import signals
|
||||
from celery.utils.nodenames import anon_nodename
|
||||
from celery.utils.saferepr import saferepr
|
||||
from celery.utils.text import indent as textindent
|
||||
from celery.utils.time import maybe_make_aware
|
||||
|
||||
from . import routes as _routes
|
||||
|
||||
__all__ = ('AMQP', 'Queues', 'task_message')
|
||||
|
||||
#: earliest date supported by time.mktime.
|
||||
INT_MIN = -2147483648
|
||||
|
||||
#: Human readable queue declaration.
|
||||
QUEUE_FORMAT = """
|
||||
.> {0.name:<16} exchange={0.exchange.name}({0.exchange.type}) \
|
||||
key={0.routing_key}
|
||||
"""
|
||||
|
||||
task_message = namedtuple('task_message',
|
||||
('headers', 'properties', 'body', 'sent_event'))
|
||||
|
||||
|
||||
def utf8dict(d, encoding='utf-8'):
|
||||
return {k.decode(encoding) if isinstance(k, bytes) else k: v
|
||||
for k, v in d.items()}
|
||||
|
||||
|
||||
class Queues(dict):
|
||||
"""Queue name⇒ declaration mapping.
|
||||
|
||||
Arguments:
|
||||
queues (Iterable): Initial list/tuple or dict of queues.
|
||||
create_missing (bool): By default any unknown queues will be
|
||||
added automatically, but if this flag is disabled the occurrence
|
||||
of unknown queues in `wanted` will raise :exc:`KeyError`.
|
||||
max_priority (int): Default x-max-priority for queues with none set.
|
||||
"""
|
||||
|
||||
#: If set, this is a subset of queues to consume from.
|
||||
#: The rest of the queues are then used for routing only.
|
||||
_consume_from = None
|
||||
|
||||
def __init__(self, queues=None, default_exchange=None,
|
||||
create_missing=True, autoexchange=None,
|
||||
max_priority=None, default_routing_key=None):
|
||||
super().__init__()
|
||||
self.aliases = WeakValueDictionary()
|
||||
self.default_exchange = default_exchange
|
||||
self.default_routing_key = default_routing_key
|
||||
self.create_missing = create_missing
|
||||
self.autoexchange = Exchange if autoexchange is None else autoexchange
|
||||
self.max_priority = max_priority
|
||||
if queues is not None and not isinstance(queues, Mapping):
|
||||
queues = {q.name: q for q in queues}
|
||||
queues = queues or {}
|
||||
for name, q in queues.items():
|
||||
self.add(q) if isinstance(q, Queue) else self.add_compat(name, **q)
|
||||
|
||||
def __getitem__(self, name):
|
||||
try:
|
||||
return self.aliases[name]
|
||||
except KeyError:
|
||||
return super().__getitem__(name)
|
||||
|
||||
def __setitem__(self, name, queue):
|
||||
if self.default_exchange and not queue.exchange:
|
||||
queue.exchange = self.default_exchange
|
||||
super().__setitem__(name, queue)
|
||||
if queue.alias:
|
||||
self.aliases[queue.alias] = queue
|
||||
|
||||
def __missing__(self, name):
|
||||
if self.create_missing:
|
||||
return self.add(self.new_missing(name))
|
||||
raise KeyError(name)
|
||||
|
||||
def add(self, queue, **kwargs):
|
||||
"""Add new queue.
|
||||
|
||||
The first argument can either be a :class:`kombu.Queue` instance,
|
||||
or the name of a queue. If the former the rest of the keyword
|
||||
arguments are ignored, and options are simply taken from the queue
|
||||
instance.
|
||||
|
||||
Arguments:
|
||||
queue (kombu.Queue, str): Queue to add.
|
||||
exchange (kombu.Exchange, str):
|
||||
if queue is str, specifies exchange name.
|
||||
routing_key (str): if queue is str, specifies binding key.
|
||||
exchange_type (str): if queue is str, specifies type of exchange.
|
||||
**options (Any): Additional declaration options used when
|
||||
queue is a str.
|
||||
"""
|
||||
if not isinstance(queue, Queue):
|
||||
return self.add_compat(queue, **kwargs)
|
||||
return self._add(queue)
|
||||
|
||||
def add_compat(self, name, **options):
|
||||
# docs used to use binding_key as routing key
|
||||
options.setdefault('routing_key', options.get('binding_key'))
|
||||
if options['routing_key'] is None:
|
||||
options['routing_key'] = name
|
||||
return self._add(Queue.from_dict(name, **options))
|
||||
|
||||
def _add(self, queue):
|
||||
if queue.exchange is None or queue.exchange.name == '':
|
||||
queue.exchange = self.default_exchange
|
||||
if not queue.routing_key:
|
||||
queue.routing_key = self.default_routing_key
|
||||
if self.max_priority is not None:
|
||||
if queue.queue_arguments is None:
|
||||
queue.queue_arguments = {}
|
||||
self._set_max_priority(queue.queue_arguments)
|
||||
self[queue.name] = queue
|
||||
return queue
|
||||
|
||||
def _set_max_priority(self, args):
|
||||
if 'x-max-priority' not in args and self.max_priority is not None:
|
||||
return args.update({'x-max-priority': self.max_priority})
|
||||
|
||||
def format(self, indent=0, indent_first=True):
|
||||
"""Format routing table into string for log dumps."""
|
||||
active = self.consume_from
|
||||
if not active:
|
||||
return ''
|
||||
info = [QUEUE_FORMAT.strip().format(q)
|
||||
for _, q in sorted(active.items())]
|
||||
if indent_first:
|
||||
return textindent('\n'.join(info), indent)
|
||||
return info[0] + '\n' + textindent('\n'.join(info[1:]), indent)
|
||||
|
||||
def select_add(self, queue, **kwargs):
|
||||
"""Add new task queue that'll be consumed from.
|
||||
|
||||
The queue will be active even when a subset has been selected
|
||||
using the :option:`celery worker -Q` option.
|
||||
"""
|
||||
q = self.add(queue, **kwargs)
|
||||
if self._consume_from is not None:
|
||||
self._consume_from[q.name] = q
|
||||
return q
|
||||
|
||||
def select(self, include):
|
||||
"""Select a subset of currently defined queues to consume from.
|
||||
|
||||
Arguments:
|
||||
include (Sequence[str], str): Names of queues to consume from.
|
||||
"""
|
||||
if include:
|
||||
self._consume_from = {
|
||||
name: self[name] for name in maybe_list(include)
|
||||
}
|
||||
|
||||
def deselect(self, exclude):
|
||||
"""Deselect queues so that they won't be consumed from.
|
||||
|
||||
Arguments:
|
||||
exclude (Sequence[str], str): Names of queues to avoid
|
||||
consuming from.
|
||||
"""
|
||||
if exclude:
|
||||
exclude = maybe_list(exclude)
|
||||
if self._consume_from is None:
|
||||
# using all queues
|
||||
return self.select(k for k in self if k not in exclude)
|
||||
# using selection
|
||||
for queue in exclude:
|
||||
self._consume_from.pop(queue, None)
|
||||
|
||||
def new_missing(self, name):
|
||||
return Queue(name, self.autoexchange(name), name)
|
||||
|
||||
@property
|
||||
def consume_from(self):
|
||||
if self._consume_from is not None:
|
||||
return self._consume_from
|
||||
return self
|
||||
|
||||
|
||||
class AMQP:
|
||||
"""App AMQP API: app.amqp."""
|
||||
|
||||
Connection = Connection
|
||||
Consumer = Consumer
|
||||
Producer = Producer
|
||||
|
||||
#: compat alias to Connection
|
||||
BrokerConnection = Connection
|
||||
|
||||
queues_cls = Queues
|
||||
|
||||
#: Cached and prepared routing table.
|
||||
_rtable = None
|
||||
|
||||
#: Underlying producer pool instance automatically
|
||||
#: set by the :attr:`producer_pool`.
|
||||
_producer_pool = None
|
||||
|
||||
# Exchange class/function used when defining automatic queues.
|
||||
# For example, you can use ``autoexchange = lambda n: None`` to use the
|
||||
# AMQP default exchange: a shortcut to bypass routing
|
||||
# and instead send directly to the queue named in the routing key.
|
||||
autoexchange = None
|
||||
|
||||
#: Max size of positional argument representation used for
|
||||
#: logging purposes.
|
||||
argsrepr_maxsize = 1024
|
||||
|
||||
#: Max size of keyword argument representation used for logging purposes.
|
||||
kwargsrepr_maxsize = 1024
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
self.task_protocols = {
|
||||
1: self.as_task_v1,
|
||||
2: self.as_task_v2,
|
||||
}
|
||||
self.app._conf.bind_to(self._handle_conf_update)
|
||||
|
||||
@cached_property
|
||||
def create_task_message(self):
|
||||
return self.task_protocols[self.app.conf.task_protocol]
|
||||
|
||||
@cached_property
|
||||
def send_task_message(self):
|
||||
return self._create_task_sender()
|
||||
|
||||
def Queues(self, queues, create_missing=None,
|
||||
autoexchange=None, max_priority=None):
|
||||
# Create new :class:`Queues` instance, using queue defaults
|
||||
# from the current configuration.
|
||||
conf = self.app.conf
|
||||
default_routing_key = conf.task_default_routing_key
|
||||
if create_missing is None:
|
||||
create_missing = conf.task_create_missing_queues
|
||||
if max_priority is None:
|
||||
max_priority = conf.task_queue_max_priority
|
||||
if not queues and conf.task_default_queue:
|
||||
queues = (Queue(conf.task_default_queue,
|
||||
exchange=self.default_exchange,
|
||||
routing_key=default_routing_key),)
|
||||
autoexchange = (self.autoexchange if autoexchange is None
|
||||
else autoexchange)
|
||||
return self.queues_cls(
|
||||
queues, self.default_exchange, create_missing,
|
||||
autoexchange, max_priority, default_routing_key,
|
||||
)
|
||||
|
||||
def Router(self, queues=None, create_missing=None):
|
||||
"""Return the current task router."""
|
||||
return _routes.Router(self.routes, queues or self.queues,
|
||||
self.app.either('task_create_missing_queues',
|
||||
create_missing), app=self.app)
|
||||
|
||||
def flush_routes(self):
|
||||
self._rtable = _routes.prepare(self.app.conf.task_routes)
|
||||
|
||||
def TaskConsumer(self, channel, queues=None, accept=None, **kw):
|
||||
if accept is None:
|
||||
accept = self.app.conf.accept_content
|
||||
return self.Consumer(
|
||||
channel, accept=accept,
|
||||
queues=queues or list(self.queues.consume_from.values()),
|
||||
**kw
|
||||
)
|
||||
|
||||
def as_task_v2(self, task_id, name, args=None, kwargs=None,
|
||||
countdown=None, eta=None, group_id=None, group_index=None,
|
||||
expires=None, retries=0, chord=None,
|
||||
callbacks=None, errbacks=None, reply_to=None,
|
||||
time_limit=None, soft_time_limit=None,
|
||||
create_sent_event=False, root_id=None, parent_id=None,
|
||||
shadow=None, chain=None, now=None, timezone=None,
|
||||
origin=None, ignore_result=False, argsrepr=None, kwargsrepr=None):
|
||||
args = args or ()
|
||||
kwargs = kwargs or {}
|
||||
if not isinstance(args, (list, tuple)):
|
||||
raise TypeError('task args must be a list or tuple')
|
||||
if not isinstance(kwargs, Mapping):
|
||||
raise TypeError('task keyword arguments must be a mapping')
|
||||
if countdown: # convert countdown to ETA
|
||||
self._verify_seconds(countdown, 'countdown')
|
||||
now = now or self.app.now()
|
||||
timezone = timezone or self.app.timezone
|
||||
eta = maybe_make_aware(
|
||||
now + timedelta(seconds=countdown), tz=timezone,
|
||||
)
|
||||
if isinstance(expires, numbers.Real):
|
||||
self._verify_seconds(expires, 'expires')
|
||||
now = now or self.app.now()
|
||||
timezone = timezone or self.app.timezone
|
||||
expires = maybe_make_aware(
|
||||
now + timedelta(seconds=expires), tz=timezone,
|
||||
)
|
||||
if not isinstance(eta, str):
|
||||
eta = eta and eta.isoformat()
|
||||
# If we retry a task `expires` will already be ISO8601-formatted.
|
||||
if not isinstance(expires, str):
|
||||
expires = expires and expires.isoformat()
|
||||
|
||||
if argsrepr is None:
|
||||
argsrepr = saferepr(args, self.argsrepr_maxsize)
|
||||
if kwargsrepr is None:
|
||||
kwargsrepr = saferepr(kwargs, self.kwargsrepr_maxsize)
|
||||
|
||||
if not root_id: # empty root_id defaults to task_id
|
||||
root_id = task_id
|
||||
|
||||
return task_message(
|
||||
headers={
|
||||
'lang': 'py',
|
||||
'task': name,
|
||||
'id': task_id,
|
||||
'shadow': shadow,
|
||||
'eta': eta,
|
||||
'expires': expires,
|
||||
'group': group_id,
|
||||
'group_index': group_index,
|
||||
'retries': retries,
|
||||
'timelimit': [time_limit, soft_time_limit],
|
||||
'root_id': root_id,
|
||||
'parent_id': parent_id,
|
||||
'argsrepr': argsrepr,
|
||||
'kwargsrepr': kwargsrepr,
|
||||
'origin': origin or anon_nodename(),
|
||||
'ignore_result': ignore_result,
|
||||
},
|
||||
properties={
|
||||
'correlation_id': task_id,
|
||||
'reply_to': reply_to or '',
|
||||
},
|
||||
body=(
|
||||
args, kwargs, {
|
||||
'callbacks': callbacks,
|
||||
'errbacks': errbacks,
|
||||
'chain': chain,
|
||||
'chord': chord,
|
||||
},
|
||||
),
|
||||
sent_event={
|
||||
'uuid': task_id,
|
||||
'root_id': root_id,
|
||||
'parent_id': parent_id,
|
||||
'name': name,
|
||||
'args': argsrepr,
|
||||
'kwargs': kwargsrepr,
|
||||
'retries': retries,
|
||||
'eta': eta,
|
||||
'expires': expires,
|
||||
} if create_sent_event else None,
|
||||
)
|
||||
|
||||
def as_task_v1(self, task_id, name, args=None, kwargs=None,
|
||||
countdown=None, eta=None, group_id=None, group_index=None,
|
||||
expires=None, retries=0,
|
||||
chord=None, callbacks=None, errbacks=None, reply_to=None,
|
||||
time_limit=None, soft_time_limit=None,
|
||||
create_sent_event=False, root_id=None, parent_id=None,
|
||||
shadow=None, now=None, timezone=None,
|
||||
**compat_kwargs):
|
||||
args = args or ()
|
||||
kwargs = kwargs or {}
|
||||
utc = self.utc
|
||||
if not isinstance(args, (list, tuple)):
|
||||
raise TypeError('task args must be a list or tuple')
|
||||
if not isinstance(kwargs, Mapping):
|
||||
raise TypeError('task keyword arguments must be a mapping')
|
||||
if countdown: # convert countdown to ETA
|
||||
self._verify_seconds(countdown, 'countdown')
|
||||
now = now or self.app.now()
|
||||
eta = now + timedelta(seconds=countdown)
|
||||
if isinstance(expires, numbers.Real):
|
||||
self._verify_seconds(expires, 'expires')
|
||||
now = now or self.app.now()
|
||||
expires = now + timedelta(seconds=expires)
|
||||
eta = eta and eta.isoformat()
|
||||
expires = expires and expires.isoformat()
|
||||
|
||||
return task_message(
|
||||
headers={},
|
||||
properties={
|
||||
'correlation_id': task_id,
|
||||
'reply_to': reply_to or '',
|
||||
},
|
||||
body={
|
||||
'task': name,
|
||||
'id': task_id,
|
||||
'args': args,
|
||||
'kwargs': kwargs,
|
||||
'group': group_id,
|
||||
'group_index': group_index,
|
||||
'retries': retries,
|
||||
'eta': eta,
|
||||
'expires': expires,
|
||||
'utc': utc,
|
||||
'callbacks': callbacks,
|
||||
'errbacks': errbacks,
|
||||
'timelimit': (time_limit, soft_time_limit),
|
||||
'taskset': group_id,
|
||||
'chord': chord,
|
||||
},
|
||||
sent_event={
|
||||
'uuid': task_id,
|
||||
'name': name,
|
||||
'args': saferepr(args),
|
||||
'kwargs': saferepr(kwargs),
|
||||
'retries': retries,
|
||||
'eta': eta,
|
||||
'expires': expires,
|
||||
} if create_sent_event else None,
|
||||
)
|
||||
|
||||
def _verify_seconds(self, s, what):
|
||||
if s < INT_MIN:
|
||||
raise ValueError(f'{what} is out of range: {s!r}')
|
||||
return s
|
||||
|
||||
def _create_task_sender(self):
|
||||
default_retry = self.app.conf.task_publish_retry
|
||||
default_policy = self.app.conf.task_publish_retry_policy
|
||||
default_delivery_mode = self.app.conf.task_default_delivery_mode
|
||||
default_queue = self.default_queue
|
||||
queues = self.queues
|
||||
send_before_publish = signals.before_task_publish.send
|
||||
before_receivers = signals.before_task_publish.receivers
|
||||
send_after_publish = signals.after_task_publish.send
|
||||
after_receivers = signals.after_task_publish.receivers
|
||||
|
||||
send_task_sent = signals.task_sent.send # XXX compat
|
||||
sent_receivers = signals.task_sent.receivers
|
||||
|
||||
default_evd = self._event_dispatcher
|
||||
default_exchange = self.default_exchange
|
||||
|
||||
default_rkey = self.app.conf.task_default_routing_key
|
||||
default_serializer = self.app.conf.task_serializer
|
||||
default_compressor = self.app.conf.result_compression
|
||||
|
||||
def send_task_message(producer, name, message,
|
||||
exchange=None, routing_key=None, queue=None,
|
||||
event_dispatcher=None,
|
||||
retry=None, retry_policy=None,
|
||||
serializer=None, delivery_mode=None,
|
||||
compression=None, declare=None,
|
||||
headers=None, exchange_type=None, **kwargs):
|
||||
retry = default_retry if retry is None else retry
|
||||
headers2, properties, body, sent_event = message
|
||||
if headers:
|
||||
headers2.update(headers)
|
||||
if kwargs:
|
||||
properties.update(kwargs)
|
||||
|
||||
qname = queue
|
||||
if queue is None and exchange is None:
|
||||
queue = default_queue
|
||||
if queue is not None:
|
||||
if isinstance(queue, str):
|
||||
qname, queue = queue, queues[queue]
|
||||
else:
|
||||
qname = queue.name
|
||||
|
||||
if delivery_mode is None:
|
||||
try:
|
||||
delivery_mode = queue.exchange.delivery_mode
|
||||
except AttributeError:
|
||||
pass
|
||||
delivery_mode = delivery_mode or default_delivery_mode
|
||||
|
||||
if exchange_type is None:
|
||||
try:
|
||||
exchange_type = queue.exchange.type
|
||||
except AttributeError:
|
||||
exchange_type = 'direct'
|
||||
|
||||
# convert to anon-exchange, when exchange not set and direct ex.
|
||||
if (not exchange or not routing_key) and exchange_type == 'direct':
|
||||
exchange, routing_key = '', qname
|
||||
elif exchange is None:
|
||||
# not topic exchange, and exchange not undefined
|
||||
exchange = queue.exchange.name or default_exchange
|
||||
routing_key = routing_key or queue.routing_key or default_rkey
|
||||
if declare is None and queue and not isinstance(queue, Broadcast):
|
||||
declare = [queue]
|
||||
|
||||
# merge default and custom policy
|
||||
retry = default_retry if retry is None else retry
|
||||
_rp = (dict(default_policy, **retry_policy) if retry_policy
|
||||
else default_policy)
|
||||
|
||||
if before_receivers:
|
||||
send_before_publish(
|
||||
sender=name, body=body,
|
||||
exchange=exchange, routing_key=routing_key,
|
||||
declare=declare, headers=headers2,
|
||||
properties=properties, retry_policy=retry_policy,
|
||||
)
|
||||
ret = producer.publish(
|
||||
body,
|
||||
exchange=exchange,
|
||||
routing_key=routing_key,
|
||||
serializer=serializer or default_serializer,
|
||||
compression=compression or default_compressor,
|
||||
retry=retry, retry_policy=_rp,
|
||||
delivery_mode=delivery_mode, declare=declare,
|
||||
headers=headers2,
|
||||
**properties
|
||||
)
|
||||
if after_receivers:
|
||||
send_after_publish(sender=name, body=body, headers=headers2,
|
||||
exchange=exchange, routing_key=routing_key)
|
||||
if sent_receivers: # XXX deprecated
|
||||
if isinstance(body, tuple): # protocol version 2
|
||||
send_task_sent(
|
||||
sender=name, task_id=headers2['id'], task=name,
|
||||
args=body[0], kwargs=body[1],
|
||||
eta=headers2['eta'], taskset=headers2['group'],
|
||||
)
|
||||
else: # protocol version 1
|
||||
send_task_sent(
|
||||
sender=name, task_id=body['id'], task=name,
|
||||
args=body['args'], kwargs=body['kwargs'],
|
||||
eta=body['eta'], taskset=body['taskset'],
|
||||
)
|
||||
if sent_event:
|
||||
evd = event_dispatcher or default_evd
|
||||
exname = exchange
|
||||
if isinstance(exname, Exchange):
|
||||
exname = exname.name
|
||||
sent_event.update({
|
||||
'queue': qname,
|
||||
'exchange': exname,
|
||||
'routing_key': routing_key,
|
||||
})
|
||||
evd.publish('task-sent', sent_event,
|
||||
producer, retry=retry, retry_policy=retry_policy)
|
||||
return ret
|
||||
return send_task_message
|
||||
|
||||
@cached_property
|
||||
def default_queue(self):
|
||||
return self.queues[self.app.conf.task_default_queue]
|
||||
|
||||
@cached_property
|
||||
def queues(self):
|
||||
"""Queue name⇒ declaration mapping."""
|
||||
return self.Queues(self.app.conf.task_queues)
|
||||
|
||||
@queues.setter
|
||||
def queues(self, queues):
|
||||
return self.Queues(queues)
|
||||
|
||||
@property
|
||||
def routes(self):
|
||||
if self._rtable is None:
|
||||
self.flush_routes()
|
||||
return self._rtable
|
||||
|
||||
@cached_property
|
||||
def router(self):
|
||||
return self.Router()
|
||||
|
||||
@router.setter
|
||||
def router(self, value):
|
||||
return value
|
||||
|
||||
@property
|
||||
def producer_pool(self):
|
||||
if self._producer_pool is None:
|
||||
self._producer_pool = pools.producers[
|
||||
self.app.connection_for_write()]
|
||||
self._producer_pool.limit = self.app.pool.limit
|
||||
return self._producer_pool
|
||||
publisher_pool = producer_pool # compat alias
|
||||
|
||||
@cached_property
|
||||
def default_exchange(self):
|
||||
return Exchange(self.app.conf.task_default_exchange,
|
||||
self.app.conf.task_default_exchange_type)
|
||||
|
||||
@cached_property
|
||||
def utc(self):
|
||||
return self.app.conf.enable_utc
|
||||
|
||||
@cached_property
|
||||
def _event_dispatcher(self):
|
||||
# We call Dispatcher.publish with a custom producer
|
||||
# so don't need the diuspatcher to be enabled.
|
||||
return self.app.events.Dispatcher(enabled=False)
|
||||
|
||||
def _handle_conf_update(self, *args, **kwargs):
|
||||
if ('task_routes' in kwargs or 'task_routes' in args):
|
||||
self.flush_routes()
|
||||
self.router = self.Router()
|
||||
return
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Task Annotations.
|
||||
|
||||
Annotations is a nice term for monkey-patching task classes
|
||||
in the configuration.
|
||||
|
||||
This prepares and performs the annotations in the
|
||||
:setting:`task_annotations` setting.
|
||||
"""
|
||||
from celery.utils.functional import firstmethod, mlazy
|
||||
from celery.utils.imports import instantiate
|
||||
|
||||
_first_match = firstmethod('annotate')
|
||||
_first_match_any = firstmethod('annotate_any')
|
||||
|
||||
__all__ = ('MapAnnotation', 'prepare', 'resolve_all')
|
||||
|
||||
|
||||
class MapAnnotation(dict):
|
||||
"""Annotation map: task_name => attributes."""
|
||||
|
||||
def annotate_any(self):
|
||||
try:
|
||||
return dict(self['*'])
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
def annotate(self, task):
|
||||
try:
|
||||
return dict(self[task.name])
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
|
||||
def prepare(annotations):
|
||||
"""Expand the :setting:`task_annotations` setting."""
|
||||
def expand_annotation(annotation):
|
||||
if isinstance(annotation, dict):
|
||||
return MapAnnotation(annotation)
|
||||
elif isinstance(annotation, str):
|
||||
return mlazy(instantiate, annotation)
|
||||
return annotation
|
||||
|
||||
if annotations is None:
|
||||
return ()
|
||||
elif not isinstance(annotations, (list, tuple)):
|
||||
annotations = (annotations,)
|
||||
return [expand_annotation(anno) for anno in annotations]
|
||||
|
||||
|
||||
def resolve_all(anno, task):
|
||||
"""Resolve all pending annotations."""
|
||||
return (x for x in (_first_match(anno, task), _first_match_any(anno)) if x)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Tasks auto-retry functionality."""
|
||||
from vine.utils import wraps
|
||||
|
||||
from celery.exceptions import Ignore, Retry
|
||||
from celery.utils.time import get_exponential_backoff_interval
|
||||
|
||||
|
||||
def add_autoretry_behaviour(task, **options):
|
||||
"""Wrap task's `run` method with auto-retry functionality."""
|
||||
autoretry_for = tuple(
|
||||
options.get('autoretry_for',
|
||||
getattr(task, 'autoretry_for', ()))
|
||||
)
|
||||
retry_kwargs = options.get(
|
||||
'retry_kwargs', getattr(task, 'retry_kwargs', {})
|
||||
)
|
||||
retry_backoff = int(
|
||||
options.get('retry_backoff',
|
||||
getattr(task, 'retry_backoff', False))
|
||||
)
|
||||
retry_backoff_max = int(
|
||||
options.get('retry_backoff_max',
|
||||
getattr(task, 'retry_backoff_max', 600))
|
||||
)
|
||||
retry_jitter = options.get(
|
||||
'retry_jitter', getattr(task, 'retry_jitter', True)
|
||||
)
|
||||
|
||||
if autoretry_for and not hasattr(task, '_orig_run'):
|
||||
|
||||
@wraps(task.run)
|
||||
def run(*args, **kwargs):
|
||||
try:
|
||||
return task._orig_run(*args, **kwargs)
|
||||
except Ignore:
|
||||
# If Ignore signal occurs task shouldn't be retried,
|
||||
# even if it suits autoretry_for list
|
||||
raise
|
||||
except Retry:
|
||||
raise
|
||||
except autoretry_for as exc:
|
||||
if retry_backoff:
|
||||
retry_kwargs['countdown'] = \
|
||||
get_exponential_backoff_interval(
|
||||
factor=retry_backoff,
|
||||
retries=task.request.retries,
|
||||
maximum=retry_backoff_max,
|
||||
full_jitter=retry_jitter)
|
||||
# Override max_retries
|
||||
if hasattr(task, 'override_max_retries'):
|
||||
retry_kwargs['max_retries'] = getattr(task,
|
||||
'override_max_retries',
|
||||
task.max_retries)
|
||||
ret = task.retry(exc=exc, **retry_kwargs)
|
||||
# Stop propagation
|
||||
if hasattr(task, 'override_max_retries'):
|
||||
delattr(task, 'override_max_retries')
|
||||
raise ret
|
||||
|
||||
task._orig_run, task.run = task.run, run
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Backend selection."""
|
||||
import sys
|
||||
import types
|
||||
|
||||
from celery._state import current_app
|
||||
from celery.exceptions import ImproperlyConfigured, reraise
|
||||
from celery.utils.imports import load_extension_class_names, symbol_by_name
|
||||
|
||||
__all__ = ('by_name', 'by_url')
|
||||
|
||||
UNKNOWN_BACKEND = """
|
||||
Unknown result backend: {0!r}. Did you spell that correctly? ({1!r})
|
||||
"""
|
||||
|
||||
BACKEND_ALIASES = {
|
||||
'amqp': 'celery.backends.amqp:AMQPBackend',
|
||||
'rpc': 'celery.backends.rpc.RPCBackend',
|
||||
'cache': 'celery.backends.cache:CacheBackend',
|
||||
'redis': 'celery.backends.redis:RedisBackend',
|
||||
'rediss': 'celery.backends.redis:RedisBackend',
|
||||
'sentinel': 'celery.backends.redis:SentinelBackend',
|
||||
'mongodb': 'celery.backends.mongodb:MongoBackend',
|
||||
'db': 'celery.backends.database:DatabaseBackend',
|
||||
'database': 'celery.backends.database:DatabaseBackend',
|
||||
'elasticsearch': 'celery.backends.elasticsearch:ElasticsearchBackend',
|
||||
'cassandra': 'celery.backends.cassandra:CassandraBackend',
|
||||
'couchbase': 'celery.backends.couchbase:CouchbaseBackend',
|
||||
'couchdb': 'celery.backends.couchdb:CouchBackend',
|
||||
'cosmosdbsql': 'celery.backends.cosmosdbsql:CosmosDBSQLBackend',
|
||||
'riak': 'celery.backends.riak:RiakBackend',
|
||||
'file': 'celery.backends.filesystem:FilesystemBackend',
|
||||
'disabled': 'celery.backends.base:DisabledBackend',
|
||||
'consul': 'celery.backends.consul:ConsulBackend',
|
||||
'dynamodb': 'celery.backends.dynamodb:DynamoDBBackend',
|
||||
'azureblockblob': 'celery.backends.azureblockblob:AzureBlockBlobBackend',
|
||||
'arangodb': 'celery.backends.arangodb:ArangoDbBackend',
|
||||
's3': 'celery.backends.s3:S3Backend',
|
||||
}
|
||||
|
||||
|
||||
def by_name(backend=None, loader=None,
|
||||
extension_namespace='celery.result_backends'):
|
||||
"""Get backend class by name/alias."""
|
||||
backend = backend or 'disabled'
|
||||
loader = loader or current_app.loader
|
||||
aliases = dict(BACKEND_ALIASES, **loader.override_backends)
|
||||
aliases.update(load_extension_class_names(extension_namespace))
|
||||
try:
|
||||
cls = symbol_by_name(backend, aliases)
|
||||
except ValueError as exc:
|
||||
reraise(ImproperlyConfigured, ImproperlyConfigured(
|
||||
UNKNOWN_BACKEND.strip().format(backend, exc)), sys.exc_info()[2])
|
||||
if isinstance(cls, types.ModuleType):
|
||||
raise ImproperlyConfigured(UNKNOWN_BACKEND.strip().format(
|
||||
backend, 'is a Python module, not a backend class.'))
|
||||
return cls
|
||||
|
||||
|
||||
def by_url(backend=None, loader=None):
|
||||
"""Get backend class by URL."""
|
||||
url = None
|
||||
if backend and '://' in backend:
|
||||
url = backend
|
||||
scheme, _, _ = url.partition('://')
|
||||
if '+' in scheme:
|
||||
backend, url = url.split('+', 1)
|
||||
else:
|
||||
backend = scheme
|
||||
return by_name(backend, loader), url
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,187 @@
|
||||
"""Built-in Tasks.
|
||||
|
||||
The built-in tasks are always available in all app instances.
|
||||
"""
|
||||
from celery._state import connect_on_app_finalize
|
||||
from celery.utils.log import get_logger
|
||||
|
||||
__all__ = ()
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_backend_cleanup_task(app):
|
||||
"""Task used to clean up expired results.
|
||||
|
||||
If the configured backend requires periodic cleanup this task is also
|
||||
automatically configured to run every day at 4am (requires
|
||||
:program:`celery beat` to be running).
|
||||
"""
|
||||
@app.task(name='celery.backend_cleanup', shared=False, lazy=False)
|
||||
def backend_cleanup():
|
||||
app.backend.cleanup()
|
||||
return backend_cleanup
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_accumulate_task(app):
|
||||
"""Task used by Task.replace when replacing task with group."""
|
||||
@app.task(bind=True, name='celery.accumulate', shared=False, lazy=False)
|
||||
def accumulate(self, *args, **kwargs):
|
||||
index = kwargs.get('index')
|
||||
return args[index] if index is not None else args
|
||||
return accumulate
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_unlock_chord_task(app):
|
||||
"""Task used by result backends without native chord support.
|
||||
|
||||
Will joins chord by creating a task chain polling the header
|
||||
for completion.
|
||||
"""
|
||||
from celery.canvas import maybe_signature
|
||||
from celery.exceptions import ChordError
|
||||
from celery.result import allow_join_result, result_from_tuple
|
||||
|
||||
@app.task(name='celery.chord_unlock', max_retries=None, shared=False,
|
||||
default_retry_delay=app.conf.result_chord_retry_interval, ignore_result=True, lazy=False, bind=True)
|
||||
def unlock_chord(self, group_id, callback, interval=None,
|
||||
max_retries=None, result=None,
|
||||
Result=app.AsyncResult, GroupResult=app.GroupResult,
|
||||
result_from_tuple=result_from_tuple, **kwargs):
|
||||
if interval is None:
|
||||
interval = self.default_retry_delay
|
||||
|
||||
# check if the task group is ready, and if so apply the callback.
|
||||
callback = maybe_signature(callback, app)
|
||||
deps = GroupResult(
|
||||
group_id,
|
||||
[result_from_tuple(r, app=app) for r in result],
|
||||
app=app,
|
||||
)
|
||||
j = deps.join_native if deps.supports_native_join else deps.join
|
||||
|
||||
try:
|
||||
ready = deps.ready()
|
||||
except Exception as exc:
|
||||
raise self.retry(
|
||||
exc=exc, countdown=interval, max_retries=max_retries,
|
||||
)
|
||||
else:
|
||||
if not ready:
|
||||
raise self.retry(countdown=interval, max_retries=max_retries)
|
||||
|
||||
callback = maybe_signature(callback, app=app)
|
||||
try:
|
||||
with allow_join_result():
|
||||
ret = j(
|
||||
timeout=app.conf.result_chord_join_timeout,
|
||||
propagate=True,
|
||||
)
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
try:
|
||||
culprit = next(deps._failed_join_report())
|
||||
reason = f'Dependency {culprit.id} raised {exc!r}'
|
||||
except StopIteration:
|
||||
reason = repr(exc)
|
||||
logger.exception('Chord %r raised: %r', group_id, exc)
|
||||
app.backend.chord_error_from_stack(callback, ChordError(reason))
|
||||
else:
|
||||
try:
|
||||
callback.delay(ret)
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.exception('Chord %r raised: %r', group_id, exc)
|
||||
app.backend.chord_error_from_stack(
|
||||
callback,
|
||||
exc=ChordError(f'Callback error: {exc!r}'),
|
||||
)
|
||||
return unlock_chord
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_map_task(app):
|
||||
from celery.canvas import signature
|
||||
|
||||
@app.task(name='celery.map', shared=False, lazy=False)
|
||||
def xmap(task, it):
|
||||
task = signature(task, app=app).type
|
||||
return [task(item) for item in it]
|
||||
return xmap
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_starmap_task(app):
|
||||
from celery.canvas import signature
|
||||
|
||||
@app.task(name='celery.starmap', shared=False, lazy=False)
|
||||
def xstarmap(task, it):
|
||||
task = signature(task, app=app).type
|
||||
return [task(*item) for item in it]
|
||||
return xstarmap
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_chunk_task(app):
|
||||
from celery.canvas import chunks as _chunks
|
||||
|
||||
@app.task(name='celery.chunks', shared=False, lazy=False)
|
||||
def chunks(task, it, n):
|
||||
return _chunks.apply_chunks(task, it, n)
|
||||
return chunks
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_group_task(app):
|
||||
"""No longer used, but here for backwards compatibility."""
|
||||
from celery.canvas import maybe_signature
|
||||
from celery.result import result_from_tuple
|
||||
|
||||
@app.task(name='celery.group', bind=True, shared=False, lazy=False)
|
||||
def group(self, tasks, result, group_id, partial_args, add_to_parent=True):
|
||||
app = self.app
|
||||
result = result_from_tuple(result, app)
|
||||
# any partial args are added to all tasks in the group
|
||||
taskit = (maybe_signature(task, app=app).clone(partial_args)
|
||||
for i, task in enumerate(tasks))
|
||||
with app.producer_or_acquire() as producer:
|
||||
[stask.apply_async(group_id=group_id, producer=producer,
|
||||
add_to_parent=False) for stask in taskit]
|
||||
parent = app.current_worker_task
|
||||
if add_to_parent and parent:
|
||||
parent.add_trail(result)
|
||||
return result
|
||||
return group
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_chain_task(app):
|
||||
"""No longer used, but here for backwards compatibility."""
|
||||
@app.task(name='celery.chain', shared=False, lazy=False)
|
||||
def chain(*args, **kwargs):
|
||||
raise NotImplementedError('chain is not a real task')
|
||||
return chain
|
||||
|
||||
|
||||
@connect_on_app_finalize
|
||||
def add_chord_task(app):
|
||||
"""No longer used, but here for backwards compatibility."""
|
||||
from celery import chord as _chord
|
||||
from celery import group
|
||||
from celery.canvas import maybe_signature
|
||||
|
||||
@app.task(name='celery.chord', bind=True, ignore_result=False,
|
||||
shared=False, lazy=False)
|
||||
def chord(self, header, body, partial_args=(), interval=None,
|
||||
countdown=1, max_retries=None, eager=False, **kwargs):
|
||||
app = self.app
|
||||
# - convert back to group if serialized
|
||||
tasks = header.tasks if isinstance(header, group) else header
|
||||
header = group([
|
||||
maybe_signature(s, app=app) for s in tasks
|
||||
], app=self.app)
|
||||
body = maybe_signature(body, app=app)
|
||||
ch = _chord(header, body)
|
||||
return ch.run(header, body, partial_args, app, interval,
|
||||
countdown, max_retries, **kwargs)
|
||||
return chord
|
||||
@@ -0,0 +1,744 @@
|
||||
"""Worker Remote Control Client.
|
||||
|
||||
Client for worker remote control commands.
|
||||
Server implementation is in :mod:`celery.worker.control`.
|
||||
There are two types of remote control commands:
|
||||
|
||||
* Inspect commands: Does not have side effects, will usually just return some value
|
||||
found in the worker, like the list of currently registered tasks, the list of active tasks, etc.
|
||||
Commands are accessible via :class:`Inspect` class.
|
||||
|
||||
* Control commands: Performs side effects, like adding a new queue to consume from.
|
||||
Commands are accessible via :class:`Control` class.
|
||||
"""
|
||||
import warnings
|
||||
|
||||
from billiard.common import TERM_SIGNAME
|
||||
from kombu.matcher import match
|
||||
from kombu.pidbox import Mailbox
|
||||
from kombu.utils.compat import register_after_fork
|
||||
from kombu.utils.functional import lazy
|
||||
from kombu.utils.objects import cached_property
|
||||
|
||||
from celery.exceptions import DuplicateNodenameWarning
|
||||
from celery.utils.log import get_logger
|
||||
from celery.utils.text import pluralize
|
||||
|
||||
__all__ = ('Inspect', 'Control', 'flatten_reply')
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
W_DUPNODE = """\
|
||||
Received multiple replies from node {0}: {1}.
|
||||
Please make sure you give each node a unique nodename using
|
||||
the celery worker `-n` option.\
|
||||
"""
|
||||
|
||||
|
||||
def flatten_reply(reply):
|
||||
"""Flatten node replies.
|
||||
|
||||
Convert from a list of replies in this format::
|
||||
|
||||
[{'a@example.com': reply},
|
||||
{'b@example.com': reply}]
|
||||
|
||||
into this format::
|
||||
|
||||
{'a@example.com': reply,
|
||||
'b@example.com': reply}
|
||||
"""
|
||||
nodes, dupes = {}, set()
|
||||
for item in reply:
|
||||
[dupes.add(name) for name in item if name in nodes]
|
||||
nodes.update(item)
|
||||
if dupes:
|
||||
warnings.warn(DuplicateNodenameWarning(
|
||||
W_DUPNODE.format(
|
||||
pluralize(len(dupes), 'name'), ', '.join(sorted(dupes)),
|
||||
),
|
||||
))
|
||||
return nodes
|
||||
|
||||
|
||||
def _after_fork_cleanup_control(control):
|
||||
try:
|
||||
control._after_fork()
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.info('after fork raised exception: %r', exc, exc_info=1)
|
||||
|
||||
|
||||
class Inspect:
|
||||
"""API for inspecting workers.
|
||||
|
||||
This class provides proxy for accessing Inspect API of workers. The API is
|
||||
defined in :py:mod:`celery.worker.control`
|
||||
"""
|
||||
|
||||
app = None
|
||||
|
||||
def __init__(self, destination=None, timeout=1.0, callback=None,
|
||||
connection=None, app=None, limit=None, pattern=None,
|
||||
matcher=None):
|
||||
self.app = app or self.app
|
||||
self.destination = destination
|
||||
self.timeout = timeout
|
||||
self.callback = callback
|
||||
self.connection = connection
|
||||
self.limit = limit
|
||||
self.pattern = pattern
|
||||
self.matcher = matcher
|
||||
|
||||
def _prepare(self, reply):
|
||||
if reply:
|
||||
by_node = flatten_reply(reply)
|
||||
if (self.destination and
|
||||
not isinstance(self.destination, (list, tuple))):
|
||||
return by_node.get(self.destination)
|
||||
if self.pattern:
|
||||
pattern = self.pattern
|
||||
matcher = self.matcher
|
||||
return {node: reply for node, reply in by_node.items()
|
||||
if match(node, pattern, matcher)}
|
||||
return by_node
|
||||
|
||||
def _request(self, command, **kwargs):
|
||||
return self._prepare(self.app.control.broadcast(
|
||||
command,
|
||||
arguments=kwargs,
|
||||
destination=self.destination,
|
||||
callback=self.callback,
|
||||
connection=self.connection,
|
||||
limit=self.limit,
|
||||
timeout=self.timeout, reply=True,
|
||||
pattern=self.pattern, matcher=self.matcher,
|
||||
))
|
||||
|
||||
def report(self):
|
||||
"""Return human readable report for each worker.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: {'ok': REPORT_STRING}}``.
|
||||
"""
|
||||
return self._request('report')
|
||||
|
||||
def clock(self):
|
||||
"""Get the Clock value on workers.
|
||||
|
||||
>>> app.control.inspect().clock()
|
||||
{'celery@node1': {'clock': 12}}
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: CLOCK_VALUE}``.
|
||||
"""
|
||||
return self._request('clock')
|
||||
|
||||
def active(self, safe=None):
|
||||
"""Return list of tasks currently executed by workers.
|
||||
|
||||
Arguments:
|
||||
safe (Boolean): Set to True to disable deserialization.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: [TASK_INFO,...]}``.
|
||||
|
||||
See Also:
|
||||
For ``TASK_INFO`` details see :func:`query_task` return value.
|
||||
|
||||
"""
|
||||
return self._request('active', safe=safe)
|
||||
|
||||
def scheduled(self, safe=None):
|
||||
"""Return list of scheduled tasks with details.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: [TASK_SCHEDULED_INFO,...]}``.
|
||||
|
||||
Here is the list of ``TASK_SCHEDULED_INFO`` fields:
|
||||
|
||||
* ``eta`` - scheduled time for task execution as string in ISO 8601 format
|
||||
* ``priority`` - priority of the task
|
||||
* ``request`` - field containing ``TASK_INFO`` value.
|
||||
|
||||
See Also:
|
||||
For more details about ``TASK_INFO`` see :func:`query_task` return value.
|
||||
"""
|
||||
return self._request('scheduled')
|
||||
|
||||
def reserved(self, safe=None):
|
||||
"""Return list of currently reserved tasks, not including scheduled/active.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: [TASK_INFO,...]}``.
|
||||
|
||||
See Also:
|
||||
For ``TASK_INFO`` details see :func:`query_task` return value.
|
||||
"""
|
||||
return self._request('reserved')
|
||||
|
||||
def stats(self):
|
||||
"""Return statistics of worker.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: STAT_INFO}``.
|
||||
|
||||
Here is the list of ``STAT_INFO`` fields:
|
||||
|
||||
* ``broker`` - Section for broker information.
|
||||
* ``connect_timeout`` - Timeout in seconds (int/float) for establishing a new connection.
|
||||
* ``heartbeat`` - Current heartbeat value (set by client).
|
||||
* ``hostname`` - Node name of the remote broker.
|
||||
* ``insist`` - No longer used.
|
||||
* ``login_method`` - Login method used to connect to the broker.
|
||||
* ``port`` - Port of the remote broker.
|
||||
* ``ssl`` - SSL enabled/disabled.
|
||||
* ``transport`` - Name of transport used (e.g., amqp or redis)
|
||||
* ``transport_options`` - Options passed to transport.
|
||||
* ``uri_prefix`` - Some transports expects the host name to be a URL.
|
||||
E.g. ``redis+socket:///tmp/redis.sock``.
|
||||
In this example the URI-prefix will be redis.
|
||||
* ``userid`` - User id used to connect to the broker with.
|
||||
* ``virtual_host`` - Virtual host used.
|
||||
* ``clock`` - Value of the workers logical clock. This is a positive integer
|
||||
and should be increasing every time you receive statistics.
|
||||
* ``uptime`` - Numbers of seconds since the worker controller was started
|
||||
* ``pid`` - Process id of the worker instance (Main process).
|
||||
* ``pool`` - Pool-specific section.
|
||||
* ``max-concurrency`` - Max number of processes/threads/green threads.
|
||||
* ``max-tasks-per-child`` - Max number of tasks a thread may execute before being recycled.
|
||||
* ``processes`` - List of PIDs (or thread-id’s).
|
||||
* ``put-guarded-by-semaphore`` - Internal
|
||||
* ``timeouts`` - Default values for time limits.
|
||||
* ``writes`` - Specific to the prefork pool, this shows the distribution
|
||||
of writes to each process in the pool when using async I/O.
|
||||
* ``prefetch_count`` - Current prefetch count value for the task consumer.
|
||||
* ``rusage`` - System usage statistics. The fields available may be different on your platform.
|
||||
From :manpage:`getrusage(2)`:
|
||||
|
||||
* ``stime`` - Time spent in operating system code on behalf of this process.
|
||||
* ``utime`` - Time spent executing user instructions.
|
||||
* ``maxrss`` - The maximum resident size used by this process (in kilobytes).
|
||||
* ``idrss`` - Amount of non-shared memory used for data (in kilobytes times
|
||||
ticks of execution)
|
||||
* ``isrss`` - Amount of non-shared memory used for stack space
|
||||
(in kilobytes times ticks of execution)
|
||||
* ``ixrss`` - Amount of memory shared with other processes
|
||||
(in kilobytes times ticks of execution).
|
||||
* ``inblock`` - Number of times the file system had to read from the disk
|
||||
on behalf of this process.
|
||||
* ``oublock`` - Number of times the file system has to write to disk
|
||||
on behalf of this process.
|
||||
* ``majflt`` - Number of page faults that were serviced by doing I/O.
|
||||
* ``minflt`` - Number of page faults that were serviced without doing I/O.
|
||||
* ``msgrcv`` - Number of IPC messages received.
|
||||
* ``msgsnd`` - Number of IPC messages sent.
|
||||
* ``nvcsw`` - Number of times this process voluntarily invoked a context switch.
|
||||
* ``nivcsw`` - Number of times an involuntary context switch took place.
|
||||
* ``nsignals`` - Number of signals received.
|
||||
* ``nswap`` - The number of times this process was swapped entirely
|
||||
out of memory.
|
||||
* ``total`` - Map of task names and the total number of tasks with that type
|
||||
the worker has accepted since start-up.
|
||||
"""
|
||||
return self._request('stats')
|
||||
|
||||
def revoked(self):
|
||||
"""Return list of revoked tasks.
|
||||
|
||||
>>> app.control.inspect().revoked()
|
||||
{'celery@node1': ['16f527de-1c72-47a6-b477-c472b92fef7a']}
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: [TASK_ID, ...]}``.
|
||||
"""
|
||||
return self._request('revoked')
|
||||
|
||||
def registered(self, *taskinfoitems):
|
||||
"""Return all registered tasks per worker.
|
||||
|
||||
>>> app.control.inspect().registered()
|
||||
{'celery@node1': ['task1', 'task1']}
|
||||
>>> app.control.inspect().registered('serializer', 'max_retries')
|
||||
{'celery@node1': ['task_foo [serializer=json max_retries=3]', 'tasb_bar [serializer=json max_retries=3]']}
|
||||
|
||||
Arguments:
|
||||
taskinfoitems (Sequence[str]): List of :class:`~celery.app.task.Task`
|
||||
attributes to include.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: [TASK1_INFO, ...]}``.
|
||||
"""
|
||||
return self._request('registered', taskinfoitems=taskinfoitems)
|
||||
registered_tasks = registered
|
||||
|
||||
def ping(self, destination=None):
|
||||
"""Ping all (or specific) workers.
|
||||
|
||||
>>> app.control.inspect().ping()
|
||||
{'celery@node1': {'ok': 'pong'}, 'celery@node2': {'ok': 'pong'}}
|
||||
>>> app.control.inspect().ping(destination=['celery@node1'])
|
||||
{'celery@node1': {'ok': 'pong'}}
|
||||
|
||||
Arguments:
|
||||
destination (List): If set, a list of the hosts to send the
|
||||
command to, when empty broadcast to all workers.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: {'ok': 'pong'}}``.
|
||||
|
||||
See Also:
|
||||
:meth:`broadcast` for supported keyword arguments.
|
||||
"""
|
||||
if destination:
|
||||
self.destination = destination
|
||||
return self._request('ping')
|
||||
|
||||
def active_queues(self):
|
||||
"""Return information about queues from which worker consumes tasks.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: [QUEUE_INFO, QUEUE_INFO,...]}``.
|
||||
|
||||
Here is the list of ``QUEUE_INFO`` fields:
|
||||
|
||||
* ``name``
|
||||
* ``exchange``
|
||||
* ``name``
|
||||
* ``type``
|
||||
* ``arguments``
|
||||
* ``durable``
|
||||
* ``passive``
|
||||
* ``auto_delete``
|
||||
* ``delivery_mode``
|
||||
* ``no_declare``
|
||||
* ``routing_key``
|
||||
* ``queue_arguments``
|
||||
* ``binding_arguments``
|
||||
* ``consumer_arguments``
|
||||
* ``durable``
|
||||
* ``exclusive``
|
||||
* ``auto_delete``
|
||||
* ``no_ack``
|
||||
* ``alias``
|
||||
* ``bindings``
|
||||
* ``no_declare``
|
||||
* ``expires``
|
||||
* ``message_ttl``
|
||||
* ``max_length``
|
||||
* ``max_length_bytes``
|
||||
* ``max_priority``
|
||||
|
||||
See Also:
|
||||
See the RabbitMQ/AMQP documentation for more details about
|
||||
``queue_info`` fields.
|
||||
Note:
|
||||
The ``queue_info`` fields are RabbitMQ/AMQP oriented.
|
||||
Not all fields applies for other transports.
|
||||
"""
|
||||
return self._request('active_queues')
|
||||
|
||||
def query_task(self, *ids):
|
||||
"""Return detail of tasks currently executed by workers.
|
||||
|
||||
Arguments:
|
||||
*ids (str): IDs of tasks to be queried.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: {TASK_ID: [STATE, TASK_INFO]}}``.
|
||||
|
||||
Here is the list of ``TASK_INFO`` fields:
|
||||
* ``id`` - ID of the task
|
||||
* ``name`` - Name of the task
|
||||
* ``args`` - Positinal arguments passed to the task
|
||||
* ``kwargs`` - Keyword arguments passed to the task
|
||||
* ``type`` - Type of the task
|
||||
* ``hostname`` - Hostname of the worker processing the task
|
||||
* ``time_start`` - Time of processing start
|
||||
* ``acknowledged`` - True when task was acknowledged to broker
|
||||
* ``delivery_info`` - Dictionary containing delivery information
|
||||
* ``exchange`` - Name of exchange where task was published
|
||||
* ``routing_key`` - Routing key used when task was published
|
||||
* ``priority`` - Priority used when task was published
|
||||
* ``redelivered`` - True if the task was redelivered
|
||||
* ``worker_pid`` - PID of worker processin the task
|
||||
|
||||
"""
|
||||
# signature used be unary: query_task(ids=[id1, id2])
|
||||
# we need this to preserve backward compatibility.
|
||||
if len(ids) == 1 and isinstance(ids[0], (list, tuple)):
|
||||
ids = ids[0]
|
||||
return self._request('query_task', ids=ids)
|
||||
|
||||
def conf(self, with_defaults=False):
|
||||
"""Return configuration of each worker.
|
||||
|
||||
Arguments:
|
||||
with_defaults (bool): if set to True, method returns also
|
||||
configuration options with default values.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{HOSTNAME: WORKER_CONFIGURATION}``.
|
||||
|
||||
See Also:
|
||||
``WORKER_CONFIGURATION`` is a dictionary containing current configuration options.
|
||||
See :ref:`configuration` for possible values.
|
||||
"""
|
||||
return self._request('conf', with_defaults=with_defaults)
|
||||
|
||||
def hello(self, from_node, revoked=None):
|
||||
return self._request('hello', from_node=from_node, revoked=revoked)
|
||||
|
||||
def memsample(self):
|
||||
"""Return sample current RSS memory usage.
|
||||
|
||||
Note:
|
||||
Requires the psutils library.
|
||||
"""
|
||||
return self._request('memsample')
|
||||
|
||||
def memdump(self, samples=10):
|
||||
"""Dump statistics of previous memsample requests.
|
||||
|
||||
Note:
|
||||
Requires the psutils library.
|
||||
"""
|
||||
return self._request('memdump', samples=samples)
|
||||
|
||||
def objgraph(self, type='Request', n=200, max_depth=10):
|
||||
"""Create graph of uncollected objects (memory-leak debugging).
|
||||
|
||||
Arguments:
|
||||
n (int): Max number of objects to graph.
|
||||
max_depth (int): Traverse at most n levels deep.
|
||||
type (str): Name of object to graph. Default is ``"Request"``.
|
||||
|
||||
Returns:
|
||||
Dict: Dictionary ``{'filename': FILENAME}``
|
||||
|
||||
Note:
|
||||
Requires the objgraph library.
|
||||
"""
|
||||
return self._request('objgraph', num=n, max_depth=max_depth, type=type)
|
||||
|
||||
|
||||
class Control:
|
||||
"""Worker remote control client."""
|
||||
|
||||
Mailbox = Mailbox
|
||||
|
||||
def __init__(self, app=None):
|
||||
self.app = app
|
||||
self.mailbox = self.Mailbox(
|
||||
app.conf.control_exchange,
|
||||
type='fanout',
|
||||
accept=app.conf.accept_content,
|
||||
serializer=app.conf.task_serializer,
|
||||
producer_pool=lazy(lambda: self.app.amqp.producer_pool),
|
||||
queue_ttl=app.conf.control_queue_ttl,
|
||||
reply_queue_ttl=app.conf.control_queue_ttl,
|
||||
queue_expires=app.conf.control_queue_expires,
|
||||
reply_queue_expires=app.conf.control_queue_expires,
|
||||
)
|
||||
register_after_fork(self, _after_fork_cleanup_control)
|
||||
|
||||
def _after_fork(self):
|
||||
del self.mailbox.producer_pool
|
||||
|
||||
@cached_property
|
||||
def inspect(self):
|
||||
"""Create new :class:`Inspect` instance."""
|
||||
return self.app.subclass_with_self(Inspect, reverse='control.inspect')
|
||||
|
||||
def purge(self, connection=None):
|
||||
"""Discard all waiting tasks.
|
||||
|
||||
This will ignore all tasks waiting for execution, and they will
|
||||
be deleted from the messaging server.
|
||||
|
||||
Arguments:
|
||||
connection (kombu.Connection): Optional specific connection
|
||||
instance to use. If not provided a connection will
|
||||
be acquired from the connection pool.
|
||||
|
||||
Returns:
|
||||
int: the number of tasks discarded.
|
||||
"""
|
||||
with self.app.connection_or_acquire(connection) as conn:
|
||||
return self.app.amqp.TaskConsumer(conn).purge()
|
||||
discard_all = purge
|
||||
|
||||
def election(self, id, topic, action=None, connection=None):
|
||||
self.broadcast(
|
||||
'election', connection=connection, destination=None,
|
||||
arguments={
|
||||
'id': id, 'topic': topic, 'action': action,
|
||||
},
|
||||
)
|
||||
|
||||
def revoke(self, task_id, destination=None, terminate=False,
|
||||
signal=TERM_SIGNAME, **kwargs):
|
||||
"""Tell all (or specific) workers to revoke a task by id (or list of ids).
|
||||
|
||||
If a task is revoked, the workers will ignore the task and
|
||||
not execute it after all.
|
||||
|
||||
Arguments:
|
||||
task_id (Union(str, list)): Id of the task to revoke
|
||||
(or list of ids).
|
||||
terminate (bool): Also terminate the process currently working
|
||||
on the task (if any).
|
||||
signal (str): Name of signal to send to process if terminate.
|
||||
Default is TERM.
|
||||
|
||||
See Also:
|
||||
:meth:`broadcast` for supported keyword arguments.
|
||||
"""
|
||||
return self.broadcast('revoke', destination=destination, arguments={
|
||||
'task_id': task_id,
|
||||
'terminate': terminate,
|
||||
'signal': signal,
|
||||
}, **kwargs)
|
||||
|
||||
def terminate(self, task_id,
|
||||
destination=None, signal=TERM_SIGNAME, **kwargs):
|
||||
"""Tell all (or specific) workers to terminate a task by id (or list of ids).
|
||||
|
||||
See Also:
|
||||
This is just a shortcut to :meth:`revoke` with the terminate
|
||||
argument enabled.
|
||||
"""
|
||||
return self.revoke(
|
||||
task_id,
|
||||
destination=destination, terminate=True, signal=signal, **kwargs)
|
||||
|
||||
def ping(self, destination=None, timeout=1.0, **kwargs):
|
||||
"""Ping all (or specific) workers.
|
||||
|
||||
>>> app.control.ping()
|
||||
[{'celery@node1': {'ok': 'pong'}}, {'celery@node2': {'ok': 'pong'}}]
|
||||
>>> app.control.ping(destination=['celery@node2'])
|
||||
[{'celery@node2': {'ok': 'pong'}}]
|
||||
|
||||
Returns:
|
||||
List[Dict]: List of ``{HOSTNAME: {'ok': 'pong'}}`` dictionaries.
|
||||
|
||||
See Also:
|
||||
:meth:`broadcast` for supported keyword arguments.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'ping', reply=True, arguments={}, destination=destination,
|
||||
timeout=timeout, **kwargs)
|
||||
|
||||
def rate_limit(self, task_name, rate_limit, destination=None, **kwargs):
|
||||
"""Tell workers to set a new rate limit for task by type.
|
||||
|
||||
Arguments:
|
||||
task_name (str): Name of task to change rate limit for.
|
||||
rate_limit (int, str): The rate limit as tasks per second,
|
||||
or a rate limit string (`'100/m'`, etc.
|
||||
see :attr:`celery.app.task.Task.rate_limit` for
|
||||
more information).
|
||||
|
||||
See Also:
|
||||
:meth:`broadcast` for supported keyword arguments.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'rate_limit',
|
||||
destination=destination,
|
||||
arguments={
|
||||
'task_name': task_name,
|
||||
'rate_limit': rate_limit,
|
||||
},
|
||||
**kwargs)
|
||||
|
||||
def add_consumer(self, queue,
|
||||
exchange=None, exchange_type='direct', routing_key=None,
|
||||
options=None, destination=None, **kwargs):
|
||||
"""Tell all (or specific) workers to start consuming from a new queue.
|
||||
|
||||
Only the queue name is required as if only the queue is specified
|
||||
then the exchange/routing key will be set to the same name (
|
||||
like automatic queues do).
|
||||
|
||||
Note:
|
||||
This command does not respect the default queue/exchange
|
||||
options in the configuration.
|
||||
|
||||
Arguments:
|
||||
queue (str): Name of queue to start consuming from.
|
||||
exchange (str): Optional name of exchange.
|
||||
exchange_type (str): Type of exchange (defaults to 'direct')
|
||||
command to, when empty broadcast to all workers.
|
||||
routing_key (str): Optional routing key.
|
||||
options (Dict): Additional options as supported
|
||||
by :meth:`kombu.entity.Queue.from_dict`.
|
||||
|
||||
See Also:
|
||||
:meth:`broadcast` for supported keyword arguments.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'add_consumer',
|
||||
destination=destination,
|
||||
arguments=dict({
|
||||
'queue': queue,
|
||||
'exchange': exchange,
|
||||
'exchange_type': exchange_type,
|
||||
'routing_key': routing_key,
|
||||
}, **options or {}),
|
||||
**kwargs
|
||||
)
|
||||
|
||||
def cancel_consumer(self, queue, destination=None, **kwargs):
|
||||
"""Tell all (or specific) workers to stop consuming from ``queue``.
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'cancel_consumer', destination=destination,
|
||||
arguments={'queue': queue}, **kwargs)
|
||||
|
||||
def time_limit(self, task_name, soft=None, hard=None,
|
||||
destination=None, **kwargs):
|
||||
"""Tell workers to set time limits for a task by type.
|
||||
|
||||
Arguments:
|
||||
task_name (str): Name of task to change time limits for.
|
||||
soft (float): New soft time limit (in seconds).
|
||||
hard (float): New hard time limit (in seconds).
|
||||
**kwargs (Any): arguments passed on to :meth:`broadcast`.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'time_limit',
|
||||
arguments={
|
||||
'task_name': task_name,
|
||||
'hard': hard,
|
||||
'soft': soft,
|
||||
},
|
||||
destination=destination,
|
||||
**kwargs)
|
||||
|
||||
def enable_events(self, destination=None, **kwargs):
|
||||
"""Tell all (or specific) workers to enable events.
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'enable_events', arguments={}, destination=destination, **kwargs)
|
||||
|
||||
def disable_events(self, destination=None, **kwargs):
|
||||
"""Tell all (or specific) workers to disable events.
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'disable_events', arguments={}, destination=destination, **kwargs)
|
||||
|
||||
def pool_grow(self, n=1, destination=None, **kwargs):
|
||||
"""Tell all (or specific) workers to grow the pool by ``n``.
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'pool_grow', arguments={'n': n}, destination=destination, **kwargs)
|
||||
|
||||
def pool_shrink(self, n=1, destination=None, **kwargs):
|
||||
"""Tell all (or specific) workers to shrink the pool by ``n``.
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'pool_shrink', arguments={'n': n},
|
||||
destination=destination, **kwargs)
|
||||
|
||||
def autoscale(self, max, min, destination=None, **kwargs):
|
||||
"""Change worker(s) autoscale setting.
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`.
|
||||
"""
|
||||
return self.broadcast(
|
||||
'autoscale', arguments={'max': max, 'min': min},
|
||||
destination=destination, **kwargs)
|
||||
|
||||
def shutdown(self, destination=None, **kwargs):
|
||||
"""Shutdown worker(s).
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`
|
||||
"""
|
||||
return self.broadcast(
|
||||
'shutdown', arguments={}, destination=destination, **kwargs)
|
||||
|
||||
def pool_restart(self, modules=None, reload=False, reloader=None,
|
||||
destination=None, **kwargs):
|
||||
"""Restart the execution pools of all or specific workers.
|
||||
|
||||
Keyword Arguments:
|
||||
modules (Sequence[str]): List of modules to reload.
|
||||
reload (bool): Flag to enable module reloading. Default is False.
|
||||
reloader (Any): Function to reload a module.
|
||||
destination (Sequence[str]): List of worker names to send this
|
||||
command to.
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`
|
||||
"""
|
||||
return self.broadcast(
|
||||
'pool_restart',
|
||||
arguments={
|
||||
'modules': modules,
|
||||
'reload': reload,
|
||||
'reloader': reloader,
|
||||
},
|
||||
destination=destination, **kwargs)
|
||||
|
||||
def heartbeat(self, destination=None, **kwargs):
|
||||
"""Tell worker(s) to send a heartbeat immediately.
|
||||
|
||||
See Also:
|
||||
Supports the same arguments as :meth:`broadcast`
|
||||
"""
|
||||
return self.broadcast(
|
||||
'heartbeat', arguments={}, destination=destination, **kwargs)
|
||||
|
||||
def broadcast(self, command, arguments=None, destination=None,
|
||||
connection=None, reply=False, timeout=1.0, limit=None,
|
||||
callback=None, channel=None, pattern=None, matcher=None,
|
||||
**extra_kwargs):
|
||||
"""Broadcast a control command to the celery workers.
|
||||
|
||||
Arguments:
|
||||
command (str): Name of command to send.
|
||||
arguments (Dict): Keyword arguments for the command.
|
||||
destination (List): If set, a list of the hosts to send the
|
||||
command to, when empty broadcast to all workers.
|
||||
connection (kombu.Connection): Custom broker connection to use,
|
||||
if not set, a connection will be acquired from the pool.
|
||||
reply (bool): Wait for and return the reply.
|
||||
timeout (float): Timeout in seconds to wait for the reply.
|
||||
limit (int): Limit number of replies.
|
||||
callback (Callable): Callback called immediately for
|
||||
each reply received.
|
||||
pattern (str): Custom pattern string to match
|
||||
matcher (Callable): Custom matcher to run the pattern to match
|
||||
"""
|
||||
with self.app.connection_or_acquire(connection) as conn:
|
||||
arguments = dict(arguments or {}, **extra_kwargs)
|
||||
if pattern and matcher:
|
||||
# tests pass easier without requiring pattern/matcher to
|
||||
# always be sent in
|
||||
return self.mailbox(conn)._broadcast(
|
||||
command, arguments, destination, reply, timeout,
|
||||
limit, callback, channel=channel,
|
||||
pattern=pattern, matcher=matcher,
|
||||
)
|
||||
else:
|
||||
return self.mailbox(conn)._broadcast(
|
||||
command, arguments, destination, reply, timeout,
|
||||
limit, callback, channel=channel,
|
||||
)
|
||||
@@ -0,0 +1,408 @@
|
||||
"""Configuration introspection and defaults."""
|
||||
from collections import deque, namedtuple
|
||||
from datetime import timedelta
|
||||
|
||||
from celery.utils.functional import memoize
|
||||
from celery.utils.serialization import strtobool
|
||||
|
||||
__all__ = ('Option', 'NAMESPACES', 'flatten', 'find')
|
||||
|
||||
|
||||
DEFAULT_POOL = 'prefork'
|
||||
|
||||
DEFAULT_ACCEPT_CONTENT = ['json']
|
||||
DEFAULT_PROCESS_LOG_FMT = """
|
||||
[%(asctime)s: %(levelname)s/%(processName)s] %(message)s
|
||||
""".strip()
|
||||
DEFAULT_TASK_LOG_FMT = """[%(asctime)s: %(levelname)s/%(processName)s] \
|
||||
%(task_name)s[%(task_id)s]: %(message)s"""
|
||||
|
||||
DEFAULT_SECURITY_DIGEST = 'sha256'
|
||||
|
||||
|
||||
OLD_NS = {'celery_{0}'}
|
||||
OLD_NS_BEAT = {'celerybeat_{0}'}
|
||||
OLD_NS_WORKER = {'celeryd_{0}'}
|
||||
|
||||
searchresult = namedtuple('searchresult', ('namespace', 'key', 'type'))
|
||||
|
||||
|
||||
def Namespace(__old__=None, **options):
|
||||
if __old__ is not None:
|
||||
for key, opt in options.items():
|
||||
if not opt.old:
|
||||
opt.old = {o.format(key) for o in __old__}
|
||||
return options
|
||||
|
||||
|
||||
def old_ns(ns):
|
||||
return {f'{ns}_{{0}}'}
|
||||
|
||||
|
||||
class Option:
|
||||
"""Describes a Celery configuration option."""
|
||||
|
||||
alt = None
|
||||
deprecate_by = None
|
||||
remove_by = None
|
||||
old = set()
|
||||
typemap = {'string': str, 'int': int, 'float': float, 'any': lambda v: v,
|
||||
'bool': strtobool, 'dict': dict, 'tuple': tuple}
|
||||
|
||||
def __init__(self, default=None, *args, **kwargs):
|
||||
self.default = default
|
||||
self.type = kwargs.get('type') or 'string'
|
||||
for attr, value in kwargs.items():
|
||||
setattr(self, attr, value)
|
||||
|
||||
def to_python(self, value):
|
||||
return self.typemap[self.type](value)
|
||||
|
||||
def __repr__(self):
|
||||
return '<Option: type->{} default->{!r}>'.format(self.type,
|
||||
self.default)
|
||||
|
||||
|
||||
NAMESPACES = Namespace(
|
||||
accept_content=Option(DEFAULT_ACCEPT_CONTENT, type='list', old=OLD_NS),
|
||||
result_accept_content=Option(None, type='list'),
|
||||
enable_utc=Option(True, type='bool'),
|
||||
imports=Option((), type='tuple', old=OLD_NS),
|
||||
include=Option((), type='tuple', old=OLD_NS),
|
||||
timezone=Option(type='string', old=OLD_NS),
|
||||
beat=Namespace(
|
||||
__old__=OLD_NS_BEAT,
|
||||
|
||||
max_loop_interval=Option(0, type='float'),
|
||||
schedule=Option({}, type='dict'),
|
||||
scheduler=Option('celery.beat:PersistentScheduler'),
|
||||
schedule_filename=Option('celerybeat-schedule'),
|
||||
sync_every=Option(0, type='int'),
|
||||
),
|
||||
broker=Namespace(
|
||||
url=Option(None, type='string'),
|
||||
read_url=Option(None, type='string'),
|
||||
write_url=Option(None, type='string'),
|
||||
transport=Option(type='string'),
|
||||
transport_options=Option({}, type='dict'),
|
||||
connection_timeout=Option(4, type='float'),
|
||||
connection_retry=Option(True, type='bool'),
|
||||
connection_max_retries=Option(100, type='int'),
|
||||
failover_strategy=Option(None, type='string'),
|
||||
heartbeat=Option(120, type='int'),
|
||||
heartbeat_checkrate=Option(3.0, type='int'),
|
||||
login_method=Option(None, type='string'),
|
||||
pool_limit=Option(10, type='int'),
|
||||
use_ssl=Option(False, type='bool'),
|
||||
|
||||
host=Option(type='string'),
|
||||
port=Option(type='int'),
|
||||
user=Option(type='string'),
|
||||
password=Option(type='string'),
|
||||
vhost=Option(type='string'),
|
||||
),
|
||||
cache=Namespace(
|
||||
__old__=old_ns('celery_cache'),
|
||||
|
||||
backend=Option(),
|
||||
backend_options=Option({}, type='dict'),
|
||||
),
|
||||
cassandra=Namespace(
|
||||
entry_ttl=Option(type='float'),
|
||||
keyspace=Option(type='string'),
|
||||
port=Option(type='string'),
|
||||
read_consistency=Option(type='string'),
|
||||
servers=Option(type='list'),
|
||||
table=Option(type='string'),
|
||||
write_consistency=Option(type='string'),
|
||||
auth_provider=Option(type='string'),
|
||||
auth_kwargs=Option(type='string'),
|
||||
options=Option({}, type='dict'),
|
||||
),
|
||||
s3=Namespace(
|
||||
access_key_id=Option(type='string'),
|
||||
secret_access_key=Option(type='string'),
|
||||
bucket=Option(type='string'),
|
||||
base_path=Option(type='string'),
|
||||
endpoint_url=Option(type='string'),
|
||||
region=Option(type='string'),
|
||||
),
|
||||
azureblockblob=Namespace(
|
||||
container_name=Option('celery', type='string'),
|
||||
retry_initial_backoff_sec=Option(2, type='int'),
|
||||
retry_increment_base=Option(2, type='int'),
|
||||
retry_max_attempts=Option(3, type='int'),
|
||||
base_path=Option('', type='string'),
|
||||
connection_timeout=Option(20, type='int'),
|
||||
read_timeout=Option(120, type='int'),
|
||||
),
|
||||
control=Namespace(
|
||||
queue_ttl=Option(300.0, type='float'),
|
||||
queue_expires=Option(10.0, type='float'),
|
||||
exchange=Option('celery', type='string'),
|
||||
),
|
||||
couchbase=Namespace(
|
||||
__old__=old_ns('celery_couchbase'),
|
||||
|
||||
backend_settings=Option(None, type='dict'),
|
||||
),
|
||||
arangodb=Namespace(
|
||||
__old__=old_ns('celery_arangodb'),
|
||||
backend_settings=Option(None, type='dict')
|
||||
),
|
||||
mongodb=Namespace(
|
||||
__old__=old_ns('celery_mongodb'),
|
||||
|
||||
backend_settings=Option(type='dict'),
|
||||
),
|
||||
cosmosdbsql=Namespace(
|
||||
database_name=Option('celerydb', type='string'),
|
||||
collection_name=Option('celerycol', type='string'),
|
||||
consistency_level=Option('Session', type='string'),
|
||||
max_retry_attempts=Option(9, type='int'),
|
||||
max_retry_wait_time=Option(30, type='int'),
|
||||
),
|
||||
event=Namespace(
|
||||
__old__=old_ns('celery_event'),
|
||||
|
||||
queue_expires=Option(60.0, type='float'),
|
||||
queue_ttl=Option(5.0, type='float'),
|
||||
queue_prefix=Option('celeryev'),
|
||||
serializer=Option('json'),
|
||||
exchange=Option('celeryev', type='string'),
|
||||
),
|
||||
redis=Namespace(
|
||||
__old__=old_ns('celery_redis'),
|
||||
|
||||
backend_use_ssl=Option(type='dict'),
|
||||
db=Option(type='int'),
|
||||
host=Option(type='string'),
|
||||
max_connections=Option(type='int'),
|
||||
username=Option(type='string'),
|
||||
password=Option(type='string'),
|
||||
port=Option(type='int'),
|
||||
socket_timeout=Option(120.0, type='float'),
|
||||
socket_connect_timeout=Option(None, type='float'),
|
||||
retry_on_timeout=Option(False, type='bool'),
|
||||
socket_keepalive=Option(False, type='bool'),
|
||||
),
|
||||
result=Namespace(
|
||||
__old__=old_ns('celery_result'),
|
||||
|
||||
backend=Option(type='string'),
|
||||
cache_max=Option(
|
||||
-1,
|
||||
type='int', old={'celery_max_cached_results'},
|
||||
),
|
||||
compression=Option(type='str'),
|
||||
exchange=Option('celeryresults'),
|
||||
exchange_type=Option('direct'),
|
||||
expires=Option(
|
||||
timedelta(days=1),
|
||||
type='float', old={'celery_task_result_expires'},
|
||||
),
|
||||
persistent=Option(None, type='bool'),
|
||||
extended=Option(False, type='bool'),
|
||||
serializer=Option('json'),
|
||||
backend_transport_options=Option({}, type='dict'),
|
||||
chord_retry_interval=Option(1.0, type='float'),
|
||||
chord_join_timeout=Option(3.0, type='float'),
|
||||
backend_max_sleep_between_retries_ms=Option(10000, type='int'),
|
||||
backend_max_retries=Option(float("inf"), type='float'),
|
||||
backend_base_sleep_between_retries_ms=Option(10, type='int'),
|
||||
backend_always_retry=Option(False, type='bool'),
|
||||
),
|
||||
elasticsearch=Namespace(
|
||||
__old__=old_ns('celery_elasticsearch'),
|
||||
|
||||
retry_on_timeout=Option(type='bool'),
|
||||
max_retries=Option(type='int'),
|
||||
timeout=Option(type='float'),
|
||||
save_meta_as_text=Option(True, type='bool'),
|
||||
),
|
||||
security=Namespace(
|
||||
__old__=old_ns('celery_security'),
|
||||
|
||||
certificate=Option(type='string'),
|
||||
cert_store=Option(type='string'),
|
||||
key=Option(type='string'),
|
||||
digest=Option(DEFAULT_SECURITY_DIGEST, type='string'),
|
||||
),
|
||||
database=Namespace(
|
||||
url=Option(old={'celery_result_dburi'}),
|
||||
engine_options=Option(
|
||||
type='dict', old={'celery_result_engine_options'},
|
||||
),
|
||||
short_lived_sessions=Option(
|
||||
False, type='bool', old={'celery_result_db_short_lived_sessions'},
|
||||
),
|
||||
table_schemas=Option(type='dict'),
|
||||
table_names=Option(type='dict', old={'celery_result_db_tablenames'}),
|
||||
),
|
||||
task=Namespace(
|
||||
__old__=OLD_NS,
|
||||
acks_late=Option(False, type='bool'),
|
||||
acks_on_failure_or_timeout=Option(True, type='bool'),
|
||||
always_eager=Option(False, type='bool'),
|
||||
annotations=Option(type='any'),
|
||||
compression=Option(type='string', old={'celery_message_compression'}),
|
||||
create_missing_queues=Option(True, type='bool'),
|
||||
inherit_parent_priority=Option(False, type='bool'),
|
||||
default_delivery_mode=Option(2, type='string'),
|
||||
default_queue=Option('celery'),
|
||||
default_exchange=Option(None, type='string'), # taken from queue
|
||||
default_exchange_type=Option('direct'),
|
||||
default_routing_key=Option(None, type='string'), # taken from queue
|
||||
default_rate_limit=Option(type='string'),
|
||||
default_priority=Option(None, type='string'),
|
||||
eager_propagates=Option(
|
||||
False, type='bool', old={'celery_eager_propagates_exceptions'},
|
||||
),
|
||||
ignore_result=Option(False, type='bool'),
|
||||
store_eager_result=Option(False, type='bool'),
|
||||
protocol=Option(2, type='int', old={'celery_task_protocol'}),
|
||||
publish_retry=Option(
|
||||
True, type='bool', old={'celery_task_publish_retry'},
|
||||
),
|
||||
publish_retry_policy=Option(
|
||||
{'max_retries': 3,
|
||||
'interval_start': 0,
|
||||
'interval_max': 1,
|
||||
'interval_step': 0.2},
|
||||
type='dict', old={'celery_task_publish_retry_policy'},
|
||||
),
|
||||
queues=Option(type='dict'),
|
||||
queue_max_priority=Option(None, type='int'),
|
||||
reject_on_worker_lost=Option(type='bool'),
|
||||
remote_tracebacks=Option(False, type='bool'),
|
||||
routes=Option(type='any'),
|
||||
send_sent_event=Option(
|
||||
False, type='bool', old={'celery_send_task_sent_event'},
|
||||
),
|
||||
serializer=Option('json', old={'celery_task_serializer'}),
|
||||
soft_time_limit=Option(
|
||||
type='float', old={'celeryd_task_soft_time_limit'},
|
||||
),
|
||||
time_limit=Option(
|
||||
type='float', old={'celeryd_task_time_limit'},
|
||||
),
|
||||
store_errors_even_if_ignored=Option(False, type='bool'),
|
||||
track_started=Option(False, type='bool'),
|
||||
),
|
||||
worker=Namespace(
|
||||
__old__=OLD_NS_WORKER,
|
||||
agent=Option(None, type='string'),
|
||||
autoscaler=Option('celery.worker.autoscale:Autoscaler'),
|
||||
cancel_long_running_tasks_on_connection_loss=Option(
|
||||
False, type='bool'
|
||||
),
|
||||
concurrency=Option(None, type='int'),
|
||||
consumer=Option('celery.worker.consumer:Consumer', type='string'),
|
||||
direct=Option(False, type='bool', old={'celery_worker_direct'}),
|
||||
disable_rate_limits=Option(
|
||||
False, type='bool', old={'celery_disable_rate_limits'},
|
||||
),
|
||||
deduplicate_successful_tasks=Option(
|
||||
False, type='bool'
|
||||
),
|
||||
enable_remote_control=Option(
|
||||
True, type='bool', old={'celery_enable_remote_control'},
|
||||
),
|
||||
hijack_root_logger=Option(True, type='bool'),
|
||||
log_color=Option(type='bool'),
|
||||
log_format=Option(DEFAULT_PROCESS_LOG_FMT),
|
||||
lost_wait=Option(10.0, type='float', old={'celeryd_worker_lost_wait'}),
|
||||
max_memory_per_child=Option(type='int'),
|
||||
max_tasks_per_child=Option(type='int'),
|
||||
pool=Option(DEFAULT_POOL),
|
||||
pool_putlocks=Option(True, type='bool'),
|
||||
pool_restarts=Option(False, type='bool'),
|
||||
proc_alive_timeout=Option(4.0, type='float'),
|
||||
prefetch_multiplier=Option(4, type='int'),
|
||||
redirect_stdouts=Option(
|
||||
True, type='bool', old={'celery_redirect_stdouts'},
|
||||
),
|
||||
redirect_stdouts_level=Option(
|
||||
'WARNING', old={'celery_redirect_stdouts_level'},
|
||||
),
|
||||
send_task_events=Option(
|
||||
False, type='bool', old={'celery_send_events'},
|
||||
),
|
||||
state_db=Option(),
|
||||
task_log_format=Option(DEFAULT_TASK_LOG_FMT),
|
||||
timer=Option(type='string'),
|
||||
timer_precision=Option(1.0, type='float'),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _flatten_keys(ns, key, opt):
|
||||
return [(ns + key, opt)]
|
||||
|
||||
|
||||
def _to_compat(ns, key, opt):
|
||||
if opt.old:
|
||||
return [
|
||||
(oldkey.format(key).upper(), ns + key, opt)
|
||||
for oldkey in opt.old
|
||||
]
|
||||
return [((ns + key).upper(), ns + key, opt)]
|
||||
|
||||
|
||||
def flatten(d, root='', keyfilter=_flatten_keys):
|
||||
"""Flatten settings."""
|
||||
stack = deque([(root, d)])
|
||||
while stack:
|
||||
ns, options = stack.popleft()
|
||||
for key, opt in options.items():
|
||||
if isinstance(opt, dict):
|
||||
stack.append((ns + key + '_', opt))
|
||||
else:
|
||||
yield from keyfilter(ns, key, opt)
|
||||
|
||||
|
||||
DEFAULTS = {
|
||||
key: opt.default for key, opt in flatten(NAMESPACES)
|
||||
}
|
||||
__compat = list(flatten(NAMESPACES, keyfilter=_to_compat))
|
||||
_OLD_DEFAULTS = {old_key: opt.default for old_key, _, opt in __compat}
|
||||
_TO_OLD_KEY = {new_key: old_key for old_key, new_key, _ in __compat}
|
||||
_TO_NEW_KEY = {old_key: new_key for old_key, new_key, _ in __compat}
|
||||
__compat = None
|
||||
|
||||
SETTING_KEYS = set(DEFAULTS.keys())
|
||||
_OLD_SETTING_KEYS = set(_TO_NEW_KEY.keys())
|
||||
|
||||
|
||||
def find_deprecated_settings(source): # pragma: no cover
|
||||
from celery.utils import deprecated
|
||||
for name, opt in flatten(NAMESPACES):
|
||||
if (opt.deprecate_by or opt.remove_by) and getattr(source, name, None):
|
||||
deprecated.warn(description=f'The {name!r} setting',
|
||||
deprecation=opt.deprecate_by,
|
||||
removal=opt.remove_by,
|
||||
alternative=f'Use the {opt.alt} instead')
|
||||
return source
|
||||
|
||||
|
||||
@memoize(maxsize=None)
|
||||
def find(name, namespace='celery'):
|
||||
"""Find setting by name."""
|
||||
# - Try specified name-space first.
|
||||
namespace = namespace.lower()
|
||||
try:
|
||||
return searchresult(
|
||||
namespace, name.lower(), NAMESPACES[namespace][name.lower()],
|
||||
)
|
||||
except KeyError:
|
||||
# - Try all the other namespaces.
|
||||
for ns, opts in NAMESPACES.items():
|
||||
if ns.lower() == name.lower():
|
||||
return searchresult(None, ns, opts)
|
||||
elif isinstance(opts, dict):
|
||||
try:
|
||||
return searchresult(ns, name.lower(), opts[name.lower()])
|
||||
except KeyError:
|
||||
pass
|
||||
# - See if name is a qualname last.
|
||||
return searchresult(None, name.lower(), DEFAULTS[name.lower()])
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Implementation for the app.events shortcuts."""
|
||||
from contextlib import contextmanager
|
||||
|
||||
from kombu.utils.objects import cached_property
|
||||
|
||||
|
||||
class Events:
|
||||
"""Implements app.events."""
|
||||
|
||||
receiver_cls = 'celery.events.receiver:EventReceiver'
|
||||
dispatcher_cls = 'celery.events.dispatcher:EventDispatcher'
|
||||
state_cls = 'celery.events.state:State'
|
||||
|
||||
def __init__(self, app=None):
|
||||
self.app = app
|
||||
|
||||
@cached_property
|
||||
def Receiver(self):
|
||||
return self.app.subclass_with_self(
|
||||
self.receiver_cls, reverse='events.Receiver')
|
||||
|
||||
@cached_property
|
||||
def Dispatcher(self):
|
||||
return self.app.subclass_with_self(
|
||||
self.dispatcher_cls, reverse='events.Dispatcher')
|
||||
|
||||
@cached_property
|
||||
def State(self):
|
||||
return self.app.subclass_with_self(
|
||||
self.state_cls, reverse='events.State')
|
||||
|
||||
@contextmanager
|
||||
def default_dispatcher(self, hostname=None, enabled=True,
|
||||
buffer_while_offline=False):
|
||||
with self.app.amqp.producer_pool.acquire(block=True) as prod:
|
||||
# pylint: disable=too-many-function-args
|
||||
# This is a property pylint...
|
||||
with self.Dispatcher(prod.connection, hostname, enabled,
|
||||
prod.channel, buffer_while_offline) as d:
|
||||
yield d
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Logging configuration.
|
||||
|
||||
The Celery instances logging section: ``Celery.log``.
|
||||
|
||||
Sets up logging for the worker and other programs,
|
||||
redirects standard outs, colors log output, patches logging
|
||||
related compatibility fixes, and so on.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import warnings
|
||||
from logging.handlers import WatchedFileHandler
|
||||
|
||||
from kombu.utils.encoding import set_default_encoding_file
|
||||
|
||||
from celery import signals
|
||||
from celery._state import get_current_task
|
||||
from celery.exceptions import CDeprecationWarning, CPendingDeprecationWarning
|
||||
from celery.local import class_property
|
||||
from celery.platforms import isatty
|
||||
from celery.utils.log import (ColorFormatter, LoggingProxy, get_logger,
|
||||
get_multiprocessing_logger, mlevel,
|
||||
reset_multiprocessing_logger)
|
||||
from celery.utils.nodenames import node_format
|
||||
from celery.utils.term import colored
|
||||
|
||||
__all__ = ('TaskFormatter', 'Logging')
|
||||
|
||||
MP_LOG = os.environ.get('MP_LOG', False)
|
||||
|
||||
|
||||
class TaskFormatter(ColorFormatter):
|
||||
"""Formatter for tasks, adding the task name and id."""
|
||||
|
||||
def format(self, record):
|
||||
task = get_current_task()
|
||||
if task and task.request:
|
||||
record.__dict__.update(task_id=task.request.id,
|
||||
task_name=task.name)
|
||||
else:
|
||||
record.__dict__.setdefault('task_name', '???')
|
||||
record.__dict__.setdefault('task_id', '???')
|
||||
return super().format(record)
|
||||
|
||||
|
||||
class Logging:
|
||||
"""Application logging setup (app.log)."""
|
||||
|
||||
#: The logging subsystem is only configured once per process.
|
||||
#: setup_logging_subsystem sets this flag, and subsequent calls
|
||||
#: will do nothing.
|
||||
_setup = False
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
self.loglevel = mlevel(logging.WARN)
|
||||
self.format = self.app.conf.worker_log_format
|
||||
self.task_format = self.app.conf.worker_task_log_format
|
||||
self.colorize = self.app.conf.worker_log_color
|
||||
|
||||
def setup(self, loglevel=None, logfile=None, redirect_stdouts=False,
|
||||
redirect_level='WARNING', colorize=None, hostname=None):
|
||||
loglevel = mlevel(loglevel)
|
||||
handled = self.setup_logging_subsystem(
|
||||
loglevel, logfile, colorize=colorize, hostname=hostname,
|
||||
)
|
||||
if not handled:
|
||||
if redirect_stdouts:
|
||||
self.redirect_stdouts(redirect_level)
|
||||
os.environ.update(
|
||||
CELERY_LOG_LEVEL=str(loglevel) if loglevel else '',
|
||||
CELERY_LOG_FILE=str(logfile) if logfile else '',
|
||||
)
|
||||
warnings.filterwarnings('always', category=CDeprecationWarning)
|
||||
warnings.filterwarnings('always', category=CPendingDeprecationWarning)
|
||||
logging.captureWarnings(True)
|
||||
return handled
|
||||
|
||||
def redirect_stdouts(self, loglevel=None, name='celery.redirected'):
|
||||
self.redirect_stdouts_to_logger(
|
||||
get_logger(name), loglevel=loglevel
|
||||
)
|
||||
os.environ.update(
|
||||
CELERY_LOG_REDIRECT='1',
|
||||
CELERY_LOG_REDIRECT_LEVEL=str(loglevel or ''),
|
||||
)
|
||||
|
||||
def setup_logging_subsystem(self, loglevel=None, logfile=None, format=None,
|
||||
colorize=None, hostname=None, **kwargs):
|
||||
if self.already_setup:
|
||||
return
|
||||
if logfile and hostname:
|
||||
logfile = node_format(logfile, hostname)
|
||||
Logging._setup = True
|
||||
loglevel = mlevel(loglevel or self.loglevel)
|
||||
format = format or self.format
|
||||
colorize = self.supports_color(colorize, logfile)
|
||||
reset_multiprocessing_logger()
|
||||
receivers = signals.setup_logging.send(
|
||||
sender=None, loglevel=loglevel, logfile=logfile,
|
||||
format=format, colorize=colorize,
|
||||
)
|
||||
|
||||
if not receivers:
|
||||
root = logging.getLogger()
|
||||
|
||||
if self.app.conf.worker_hijack_root_logger:
|
||||
root.handlers = []
|
||||
get_logger('celery').handlers = []
|
||||
get_logger('celery.task').handlers = []
|
||||
get_logger('celery.redirected').handlers = []
|
||||
|
||||
# Configure root logger
|
||||
self._configure_logger(
|
||||
root, logfile, loglevel, format, colorize, **kwargs
|
||||
)
|
||||
|
||||
# Configure the multiprocessing logger
|
||||
self._configure_logger(
|
||||
get_multiprocessing_logger(),
|
||||
logfile, loglevel if MP_LOG else logging.ERROR,
|
||||
format, colorize, **kwargs
|
||||
)
|
||||
|
||||
signals.after_setup_logger.send(
|
||||
sender=None, logger=root,
|
||||
loglevel=loglevel, logfile=logfile,
|
||||
format=format, colorize=colorize,
|
||||
)
|
||||
|
||||
# then setup the root task logger.
|
||||
self.setup_task_loggers(loglevel, logfile, colorize=colorize)
|
||||
|
||||
try:
|
||||
stream = logging.getLogger().handlers[0].stream
|
||||
except (AttributeError, IndexError):
|
||||
pass
|
||||
else:
|
||||
set_default_encoding_file(stream)
|
||||
|
||||
# This is a hack for multiprocessing's fork+exec, so that
|
||||
# logging before Process.run works.
|
||||
logfile_name = logfile if isinstance(logfile, str) else ''
|
||||
os.environ.update(_MP_FORK_LOGLEVEL_=str(loglevel),
|
||||
_MP_FORK_LOGFILE_=logfile_name,
|
||||
_MP_FORK_LOGFORMAT_=format)
|
||||
return receivers
|
||||
|
||||
def _configure_logger(self, logger, logfile, loglevel,
|
||||
format, colorize, **kwargs):
|
||||
if logger is not None:
|
||||
self.setup_handlers(logger, logfile, format,
|
||||
colorize, **kwargs)
|
||||
if loglevel:
|
||||
logger.setLevel(loglevel)
|
||||
|
||||
def setup_task_loggers(self, loglevel=None, logfile=None, format=None,
|
||||
colorize=None, propagate=False, **kwargs):
|
||||
"""Setup the task logger.
|
||||
|
||||
If `logfile` is not specified, then `sys.stderr` is used.
|
||||
|
||||
Will return the base task logger object.
|
||||
"""
|
||||
loglevel = mlevel(loglevel or self.loglevel)
|
||||
format = format or self.task_format
|
||||
colorize = self.supports_color(colorize, logfile)
|
||||
|
||||
logger = self.setup_handlers(
|
||||
get_logger('celery.task'),
|
||||
logfile, format, colorize,
|
||||
formatter=TaskFormatter, **kwargs
|
||||
)
|
||||
logger.setLevel(loglevel)
|
||||
# this is an int for some reason, better to not question why.
|
||||
logger.propagate = int(propagate)
|
||||
signals.after_setup_task_logger.send(
|
||||
sender=None, logger=logger,
|
||||
loglevel=loglevel, logfile=logfile,
|
||||
format=format, colorize=colorize,
|
||||
)
|
||||
return logger
|
||||
|
||||
def redirect_stdouts_to_logger(self, logger, loglevel=None,
|
||||
stdout=True, stderr=True):
|
||||
"""Redirect :class:`sys.stdout` and :class:`sys.stderr` to logger.
|
||||
|
||||
Arguments:
|
||||
logger (logging.Logger): Logger instance to redirect to.
|
||||
loglevel (int, str): The loglevel redirected message
|
||||
will be logged as.
|
||||
"""
|
||||
proxy = LoggingProxy(logger, loglevel)
|
||||
if stdout:
|
||||
sys.stdout = proxy
|
||||
if stderr:
|
||||
sys.stderr = proxy
|
||||
return proxy
|
||||
|
||||
def supports_color(self, colorize=None, logfile=None):
|
||||
colorize = self.colorize if colorize is None else colorize
|
||||
if self.app.IS_WINDOWS:
|
||||
# Windows does not support ANSI color codes.
|
||||
return False
|
||||
if colorize or colorize is None:
|
||||
# Only use color if there's no active log file
|
||||
# and stderr is an actual terminal.
|
||||
return logfile is None and isatty(sys.stderr)
|
||||
return colorize
|
||||
|
||||
def colored(self, logfile=None, enabled=None):
|
||||
return colored(enabled=self.supports_color(enabled, logfile))
|
||||
|
||||
def setup_handlers(self, logger, logfile, format, colorize,
|
||||
formatter=ColorFormatter, **kwargs):
|
||||
if self._is_configured(logger):
|
||||
return logger
|
||||
handler = self._detect_handler(logfile)
|
||||
handler.setFormatter(formatter(format, use_color=colorize))
|
||||
logger.addHandler(handler)
|
||||
return logger
|
||||
|
||||
def _detect_handler(self, logfile=None):
|
||||
"""Create handler from filename, an open stream or `None` (stderr)."""
|
||||
logfile = sys.__stderr__ if logfile is None else logfile
|
||||
if hasattr(logfile, 'write'):
|
||||
return logging.StreamHandler(logfile)
|
||||
return WatchedFileHandler(logfile, encoding='utf-8')
|
||||
|
||||
def _has_handler(self, logger):
|
||||
return any(
|
||||
not isinstance(h, logging.NullHandler)
|
||||
for h in logger.handlers or []
|
||||
)
|
||||
|
||||
def _is_configured(self, logger):
|
||||
return self._has_handler(logger) and not getattr(
|
||||
logger, '_rudimentary_setup', False)
|
||||
|
||||
def get_default_logger(self, name='celery', **kwargs):
|
||||
return get_logger(name)
|
||||
|
||||
@class_property
|
||||
def already_setup(self):
|
||||
return self._setup
|
||||
|
||||
@already_setup.setter
|
||||
def already_setup(self, was_setup):
|
||||
self._setup = was_setup
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Registry of available tasks."""
|
||||
import inspect
|
||||
from importlib import import_module
|
||||
|
||||
from celery._state import get_current_app
|
||||
from celery.app.autoretry import add_autoretry_behaviour
|
||||
from celery.exceptions import InvalidTaskError, NotRegistered
|
||||
|
||||
__all__ = ('TaskRegistry',)
|
||||
|
||||
|
||||
class TaskRegistry(dict):
|
||||
"""Map of registered tasks."""
|
||||
|
||||
NotRegistered = NotRegistered
|
||||
|
||||
def __missing__(self, key):
|
||||
raise self.NotRegistered(key)
|
||||
|
||||
def register(self, task):
|
||||
"""Register a task in the task registry.
|
||||
|
||||
The task will be automatically instantiated if not already an
|
||||
instance. Name must be configured prior to registration.
|
||||
"""
|
||||
if task.name is None:
|
||||
raise InvalidTaskError(
|
||||
'Task class {!r} must specify .name attribute'.format(
|
||||
type(task).__name__))
|
||||
task = inspect.isclass(task) and task() or task
|
||||
add_autoretry_behaviour(task)
|
||||
self[task.name] = task
|
||||
|
||||
def unregister(self, name):
|
||||
"""Unregister task by name.
|
||||
|
||||
Arguments:
|
||||
name (str): name of the task to unregister, or a
|
||||
:class:`celery.app.task.Task` with a valid `name` attribute.
|
||||
|
||||
Raises:
|
||||
celery.exceptions.NotRegistered: if the task is not registered.
|
||||
"""
|
||||
try:
|
||||
self.pop(getattr(name, 'name', name))
|
||||
except KeyError:
|
||||
raise self.NotRegistered(name)
|
||||
|
||||
# -- these methods are irrelevant now and will be removed in 4.0
|
||||
def regular(self):
|
||||
return self.filter_types('regular')
|
||||
|
||||
def periodic(self):
|
||||
return self.filter_types('periodic')
|
||||
|
||||
def filter_types(self, type):
|
||||
return {name: task for name, task in self.items()
|
||||
if getattr(task, 'type', 'regular') == type}
|
||||
|
||||
|
||||
def _unpickle_task(name):
|
||||
return get_current_app().tasks[name]
|
||||
|
||||
|
||||
def _unpickle_task_v2(name, module=None):
|
||||
if module:
|
||||
import_module(module)
|
||||
return get_current_app().tasks[name]
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Task Routing.
|
||||
|
||||
Contains utilities for working with task routers, (:setting:`task_routes`).
|
||||
"""
|
||||
import fnmatch
|
||||
import re
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Mapping
|
||||
|
||||
from kombu import Queue
|
||||
|
||||
from celery.exceptions import QueueNotFound
|
||||
from celery.utils.collections import lpmerge
|
||||
from celery.utils.functional import maybe_evaluate, mlazy
|
||||
from celery.utils.imports import symbol_by_name
|
||||
|
||||
try:
|
||||
Pattern = re._pattern_type
|
||||
except AttributeError: # pragma: no cover
|
||||
# for support Python 3.7
|
||||
Pattern = re.Pattern
|
||||
|
||||
__all__ = ('MapRoute', 'Router', 'prepare')
|
||||
|
||||
|
||||
class MapRoute:
|
||||
"""Creates a router out of a :class:`dict`."""
|
||||
|
||||
def __init__(self, map):
|
||||
map = map.items() if isinstance(map, Mapping) else map
|
||||
self.map = {}
|
||||
self.patterns = OrderedDict()
|
||||
for k, v in map:
|
||||
if isinstance(k, Pattern):
|
||||
self.patterns[k] = v
|
||||
elif '*' in k:
|
||||
self.patterns[re.compile(fnmatch.translate(k))] = v
|
||||
else:
|
||||
self.map[k] = v
|
||||
|
||||
def __call__(self, name, *args, **kwargs):
|
||||
try:
|
||||
return dict(self.map[name])
|
||||
except KeyError:
|
||||
pass
|
||||
except ValueError:
|
||||
return {'queue': self.map[name]}
|
||||
for regex, route in self.patterns.items():
|
||||
if regex.match(name):
|
||||
try:
|
||||
return dict(route)
|
||||
except ValueError:
|
||||
return {'queue': route}
|
||||
|
||||
|
||||
class Router:
|
||||
"""Route tasks based on the :setting:`task_routes` setting."""
|
||||
|
||||
def __init__(self, routes=None, queues=None,
|
||||
create_missing=False, app=None):
|
||||
self.app = app
|
||||
self.queues = {} if queues is None else queues
|
||||
self.routes = [] if routes is None else routes
|
||||
self.create_missing = create_missing
|
||||
|
||||
def route(self, options, name, args=(), kwargs=None, task_type=None):
|
||||
kwargs = {} if not kwargs else kwargs
|
||||
options = self.expand_destination(options) # expands 'queue'
|
||||
if self.routes:
|
||||
route = self.lookup_route(name, args, kwargs, options, task_type)
|
||||
if route: # expands 'queue' in route.
|
||||
return lpmerge(self.expand_destination(route), options)
|
||||
if 'queue' not in options:
|
||||
options = lpmerge(self.expand_destination(
|
||||
self.app.conf.task_default_queue), options)
|
||||
return options
|
||||
|
||||
def expand_destination(self, route):
|
||||
# Route can be a queue name: convenient for direct exchanges.
|
||||
if isinstance(route, str):
|
||||
queue, route = route, {}
|
||||
else:
|
||||
# can use defaults from configured queue, but override specific
|
||||
# things (like the routing_key): great for topic exchanges.
|
||||
queue = route.pop('queue', None)
|
||||
|
||||
if queue:
|
||||
if isinstance(queue, Queue):
|
||||
route['queue'] = queue
|
||||
else:
|
||||
try:
|
||||
route['queue'] = self.queues[queue]
|
||||
except KeyError:
|
||||
raise QueueNotFound(
|
||||
f'Queue {queue!r} missing from task_queues')
|
||||
return route
|
||||
|
||||
def lookup_route(self, name,
|
||||
args=None, kwargs=None, options=None, task_type=None):
|
||||
query = self.query_router
|
||||
for router in self.routes:
|
||||
route = query(router, name, args, kwargs, options, task_type)
|
||||
if route is not None:
|
||||
return route
|
||||
|
||||
def query_router(self, router, task, args, kwargs, options, task_type):
|
||||
router = maybe_evaluate(router)
|
||||
if hasattr(router, 'route_for_task'):
|
||||
# pre 4.0 router class
|
||||
return router.route_for_task(task, args, kwargs)
|
||||
return router(task, args, kwargs, options, task=task_type)
|
||||
|
||||
|
||||
def expand_router_string(router):
|
||||
router = symbol_by_name(router)
|
||||
if hasattr(router, 'route_for_task'):
|
||||
# need to instantiate pre 4.0 router classes
|
||||
router = router()
|
||||
return router
|
||||
|
||||
|
||||
def prepare(routes):
|
||||
"""Expand the :setting:`task_routes` setting."""
|
||||
|
||||
def expand_route(route):
|
||||
if isinstance(route, (Mapping, list, tuple)):
|
||||
return MapRoute(route)
|
||||
if isinstance(route, str):
|
||||
return mlazy(expand_router_string, route)
|
||||
return route
|
||||
|
||||
if routes is None:
|
||||
return ()
|
||||
if not isinstance(routes, (list, tuple)):
|
||||
routes = (routes,)
|
||||
return [expand_route(route) for route in routes]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,737 @@
|
||||
"""Trace task execution.
|
||||
|
||||
This module defines how the task execution is traced:
|
||||
errors are recorded, handlers are applied and so on.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from collections import namedtuple
|
||||
from warnings import warn
|
||||
|
||||
from billiard.einfo import ExceptionInfo
|
||||
from kombu.exceptions import EncodeError
|
||||
from kombu.serialization import loads as loads_message
|
||||
from kombu.serialization import prepare_accept_content
|
||||
from kombu.utils.encoding import safe_repr, safe_str
|
||||
|
||||
from celery import current_app, group, signals, states
|
||||
from celery._state import _task_stack
|
||||
from celery.app.task import Context
|
||||
from celery.app.task import Task as BaseTask
|
||||
from celery.exceptions import (BackendGetMetaError, Ignore, InvalidTaskError,
|
||||
Reject, Retry)
|
||||
from celery.result import AsyncResult
|
||||
from celery.utils.log import get_logger
|
||||
from celery.utils.nodenames import gethostname
|
||||
from celery.utils.objects import mro_lookup
|
||||
from celery.utils.saferepr import saferepr
|
||||
from celery.utils.serialization import (get_pickleable_etype,
|
||||
get_pickleable_exception,
|
||||
get_pickled_exception)
|
||||
|
||||
# ## ---
|
||||
# This is the heart of the worker, the inner loop so to speak.
|
||||
# It used to be split up into nice little classes and methods,
|
||||
# but in the end it only resulted in bad performance and horrible tracebacks,
|
||||
# so instead we now use one closure per task class.
|
||||
|
||||
# pylint: disable=redefined-outer-name
|
||||
# We cache globals and attribute lookups, so disable this warning.
|
||||
# pylint: disable=broad-except
|
||||
# We know what we're doing...
|
||||
|
||||
|
||||
__all__ = (
|
||||
'TraceInfo', 'build_tracer', 'trace_task',
|
||||
'setup_worker_optimizations', 'reset_worker_optimizations',
|
||||
)
|
||||
|
||||
from celery.worker.state import successful_requests
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
#: Format string used to log task receipt.
|
||||
LOG_RECEIVED = """\
|
||||
Task %(name)s[%(id)s] received\
|
||||
"""
|
||||
|
||||
#: Format string used to log task success.
|
||||
LOG_SUCCESS = """\
|
||||
Task %(name)s[%(id)s] succeeded in %(runtime)ss: %(return_value)s\
|
||||
"""
|
||||
|
||||
#: Format string used to log task failure.
|
||||
LOG_FAILURE = """\
|
||||
Task %(name)s[%(id)s] %(description)s: %(exc)s\
|
||||
"""
|
||||
|
||||
#: Format string used to log task internal error.
|
||||
LOG_INTERNAL_ERROR = """\
|
||||
Task %(name)s[%(id)s] %(description)s: %(exc)s\
|
||||
"""
|
||||
|
||||
#: Format string used to log task ignored.
|
||||
LOG_IGNORED = """\
|
||||
Task %(name)s[%(id)s] %(description)s\
|
||||
"""
|
||||
|
||||
#: Format string used to log task rejected.
|
||||
LOG_REJECTED = """\
|
||||
Task %(name)s[%(id)s] %(exc)s\
|
||||
"""
|
||||
|
||||
#: Format string used to log task retry.
|
||||
LOG_RETRY = """\
|
||||
Task %(name)s[%(id)s] retry: %(exc)s\
|
||||
"""
|
||||
|
||||
log_policy_t = namedtuple(
|
||||
'log_policy_t',
|
||||
('format', 'description', 'severity', 'traceback', 'mail'),
|
||||
)
|
||||
|
||||
log_policy_reject = log_policy_t(LOG_REJECTED, 'rejected', logging.WARN, 1, 1)
|
||||
log_policy_ignore = log_policy_t(LOG_IGNORED, 'ignored', logging.INFO, 0, 0)
|
||||
log_policy_internal = log_policy_t(
|
||||
LOG_INTERNAL_ERROR, 'INTERNAL ERROR', logging.CRITICAL, 1, 1,
|
||||
)
|
||||
log_policy_expected = log_policy_t(
|
||||
LOG_FAILURE, 'raised expected', logging.INFO, 0, 0,
|
||||
)
|
||||
log_policy_unexpected = log_policy_t(
|
||||
LOG_FAILURE, 'raised unexpected', logging.ERROR, 1, 1,
|
||||
)
|
||||
|
||||
send_prerun = signals.task_prerun.send
|
||||
send_postrun = signals.task_postrun.send
|
||||
send_success = signals.task_success.send
|
||||
STARTED = states.STARTED
|
||||
SUCCESS = states.SUCCESS
|
||||
IGNORED = states.IGNORED
|
||||
REJECTED = states.REJECTED
|
||||
RETRY = states.RETRY
|
||||
FAILURE = states.FAILURE
|
||||
EXCEPTION_STATES = states.EXCEPTION_STATES
|
||||
IGNORE_STATES = frozenset({IGNORED, RETRY, REJECTED})
|
||||
|
||||
#: set by :func:`setup_worker_optimizations`
|
||||
_localized = []
|
||||
_patched = {}
|
||||
|
||||
trace_ok_t = namedtuple('trace_ok_t', ('retval', 'info', 'runtime', 'retstr'))
|
||||
|
||||
|
||||
def info(fmt, context):
|
||||
"""Log 'fmt % context' with severity 'INFO'.
|
||||
|
||||
'context' is also passed in extra with key 'data' for custom handlers.
|
||||
"""
|
||||
logger.info(fmt, context, extra={'data': context})
|
||||
|
||||
|
||||
def task_has_custom(task, attr):
|
||||
"""Return true if the task overrides ``attr``."""
|
||||
return mro_lookup(task.__class__, attr, stop={BaseTask, object},
|
||||
monkey_patched=['celery.app.task'])
|
||||
|
||||
|
||||
def get_log_policy(task, einfo, exc):
|
||||
if isinstance(exc, Reject):
|
||||
return log_policy_reject
|
||||
elif isinstance(exc, Ignore):
|
||||
return log_policy_ignore
|
||||
elif einfo.internal:
|
||||
return log_policy_internal
|
||||
else:
|
||||
if task.throws and isinstance(exc, task.throws):
|
||||
return log_policy_expected
|
||||
return log_policy_unexpected
|
||||
|
||||
|
||||
def get_task_name(request, default):
|
||||
"""Use 'shadow' in request for the task name if applicable."""
|
||||
# request.shadow could be None or an empty string.
|
||||
# If so, we should use default.
|
||||
return getattr(request, 'shadow', None) or default
|
||||
|
||||
|
||||
class TraceInfo:
|
||||
"""Information about task execution."""
|
||||
|
||||
__slots__ = ('state', 'retval')
|
||||
|
||||
def __init__(self, state, retval=None):
|
||||
self.state = state
|
||||
self.retval = retval
|
||||
|
||||
def handle_error_state(self, task, req,
|
||||
eager=False, call_errbacks=True):
|
||||
if task.ignore_result:
|
||||
store_errors = task.store_errors_even_if_ignored
|
||||
elif eager and task.store_eager_result:
|
||||
store_errors = True
|
||||
else:
|
||||
store_errors = not eager
|
||||
|
||||
return {
|
||||
RETRY: self.handle_retry,
|
||||
FAILURE: self.handle_failure,
|
||||
}[self.state](task, req,
|
||||
store_errors=store_errors,
|
||||
call_errbacks=call_errbacks)
|
||||
|
||||
def handle_reject(self, task, req, **kwargs):
|
||||
self._log_error(task, req, ExceptionInfo())
|
||||
|
||||
def handle_ignore(self, task, req, **kwargs):
|
||||
self._log_error(task, req, ExceptionInfo())
|
||||
|
||||
def handle_retry(self, task, req, store_errors=True, **kwargs):
|
||||
"""Handle retry exception."""
|
||||
# the exception raised is the Retry semi-predicate,
|
||||
# and it's exc' attribute is the original exception raised (if any).
|
||||
type_, _, tb = sys.exc_info()
|
||||
try:
|
||||
reason = self.retval
|
||||
einfo = ExceptionInfo((type_, reason, tb))
|
||||
if store_errors:
|
||||
task.backend.mark_as_retry(
|
||||
req.id, reason.exc, einfo.traceback, request=req,
|
||||
)
|
||||
task.on_retry(reason.exc, req.id, req.args, req.kwargs, einfo)
|
||||
signals.task_retry.send(sender=task, request=req,
|
||||
reason=reason, einfo=einfo)
|
||||
info(LOG_RETRY, {
|
||||
'id': req.id,
|
||||
'name': get_task_name(req, task.name),
|
||||
'exc': str(reason),
|
||||
})
|
||||
return einfo
|
||||
finally:
|
||||
del tb
|
||||
|
||||
def handle_failure(self, task, req, store_errors=True, call_errbacks=True):
|
||||
"""Handle exception."""
|
||||
_, _, tb = sys.exc_info()
|
||||
try:
|
||||
exc = self.retval
|
||||
# make sure we only send pickleable exceptions back to parent.
|
||||
einfo = ExceptionInfo()
|
||||
einfo.exception = get_pickleable_exception(einfo.exception)
|
||||
einfo.type = get_pickleable_etype(einfo.type)
|
||||
|
||||
task.backend.mark_as_failure(
|
||||
req.id, exc, einfo.traceback,
|
||||
request=req, store_result=store_errors,
|
||||
call_errbacks=call_errbacks,
|
||||
)
|
||||
|
||||
task.on_failure(exc, req.id, req.args, req.kwargs, einfo)
|
||||
signals.task_failure.send(sender=task, task_id=req.id,
|
||||
exception=exc, args=req.args,
|
||||
kwargs=req.kwargs,
|
||||
traceback=tb,
|
||||
einfo=einfo)
|
||||
self._log_error(task, req, einfo)
|
||||
return einfo
|
||||
finally:
|
||||
del tb
|
||||
|
||||
def _log_error(self, task, req, einfo):
|
||||
eobj = einfo.exception = get_pickled_exception(einfo.exception)
|
||||
exception, traceback, exc_info, sargs, skwargs = (
|
||||
safe_repr(eobj),
|
||||
safe_str(einfo.traceback),
|
||||
einfo.exc_info,
|
||||
safe_repr(req.args),
|
||||
safe_repr(req.kwargs),
|
||||
)
|
||||
policy = get_log_policy(task, einfo, eobj)
|
||||
|
||||
context = {
|
||||
'hostname': req.hostname,
|
||||
'id': req.id,
|
||||
'name': get_task_name(req, task.name),
|
||||
'exc': exception,
|
||||
'traceback': traceback,
|
||||
'args': sargs,
|
||||
'kwargs': skwargs,
|
||||
'description': policy.description,
|
||||
'internal': einfo.internal,
|
||||
}
|
||||
|
||||
logger.log(policy.severity, policy.format.strip(), context,
|
||||
exc_info=exc_info if policy.traceback else None,
|
||||
extra={'data': context})
|
||||
|
||||
|
||||
def traceback_clear(exc=None):
|
||||
# Cleared Tb, but einfo still has a reference to Traceback.
|
||||
# exc cleans up the Traceback at the last moment that can be revealed.
|
||||
tb = None
|
||||
if exc is not None:
|
||||
if hasattr(exc, '__traceback__'):
|
||||
tb = exc.__traceback__
|
||||
else:
|
||||
_, _, tb = sys.exc_info()
|
||||
else:
|
||||
_, _, tb = sys.exc_info()
|
||||
|
||||
while tb is not None:
|
||||
try:
|
||||
tb.tb_frame.clear()
|
||||
tb.tb_frame.f_locals
|
||||
except RuntimeError:
|
||||
# Ignore the exception raised if the frame is still executing.
|
||||
pass
|
||||
tb = tb.tb_next
|
||||
|
||||
|
||||
def build_tracer(name, task, loader=None, hostname=None, store_errors=True,
|
||||
Info=TraceInfo, eager=False, propagate=False, app=None,
|
||||
monotonic=time.monotonic, trace_ok_t=trace_ok_t,
|
||||
IGNORE_STATES=IGNORE_STATES):
|
||||
"""Return a function that traces task execution.
|
||||
|
||||
Catches all exceptions and updates result backend with the
|
||||
state and result.
|
||||
|
||||
If the call was successful, it saves the result to the task result
|
||||
backend, and sets the task status to `"SUCCESS"`.
|
||||
|
||||
If the call raises :exc:`~@Retry`, it extracts
|
||||
the original exception, uses that as the result and sets the task state
|
||||
to `"RETRY"`.
|
||||
|
||||
If the call results in an exception, it saves the exception as the task
|
||||
result, and sets the task state to `"FAILURE"`.
|
||||
|
||||
Return a function that takes the following arguments:
|
||||
|
||||
:param uuid: The id of the task.
|
||||
:param args: List of positional args to pass on to the function.
|
||||
:param kwargs: Keyword arguments mapping to pass on to the function.
|
||||
:keyword request: Request dict.
|
||||
|
||||
"""
|
||||
|
||||
# pylint: disable=too-many-statements
|
||||
|
||||
# If the task doesn't define a custom __call__ method
|
||||
# we optimize it away by simply calling the run method directly,
|
||||
# saving the extra method call and a line less in the stack trace.
|
||||
fun = task if task_has_custom(task, '__call__') else task.run
|
||||
|
||||
loader = loader or app.loader
|
||||
ignore_result = task.ignore_result
|
||||
track_started = task.track_started
|
||||
track_started = not eager and (task.track_started and not ignore_result)
|
||||
|
||||
# #6476
|
||||
if eager and not ignore_result and task.store_eager_result:
|
||||
publish_result = True
|
||||
else:
|
||||
publish_result = not eager and not ignore_result
|
||||
|
||||
deduplicate_successful_tasks = ((app.conf.task_acks_late or task.acks_late)
|
||||
and app.conf.worker_deduplicate_successful_tasks
|
||||
and app.backend.persistent)
|
||||
|
||||
hostname = hostname or gethostname()
|
||||
inherit_parent_priority = app.conf.task_inherit_parent_priority
|
||||
|
||||
loader_task_init = loader.on_task_init
|
||||
loader_cleanup = loader.on_process_cleanup
|
||||
|
||||
task_before_start = None
|
||||
task_on_success = None
|
||||
task_after_return = None
|
||||
if task_has_custom(task, 'before_start'):
|
||||
task_before_start = task.before_start
|
||||
if task_has_custom(task, 'on_success'):
|
||||
task_on_success = task.on_success
|
||||
if task_has_custom(task, 'after_return'):
|
||||
task_after_return = task.after_return
|
||||
|
||||
pid = os.getpid()
|
||||
|
||||
request_stack = task.request_stack
|
||||
push_request = request_stack.push
|
||||
pop_request = request_stack.pop
|
||||
push_task = _task_stack.push
|
||||
pop_task = _task_stack.pop
|
||||
_does_info = logger.isEnabledFor(logging.INFO)
|
||||
resultrepr_maxsize = task.resultrepr_maxsize
|
||||
|
||||
prerun_receivers = signals.task_prerun.receivers
|
||||
postrun_receivers = signals.task_postrun.receivers
|
||||
success_receivers = signals.task_success.receivers
|
||||
|
||||
from celery import canvas
|
||||
signature = canvas.maybe_signature # maybe_ does not clone if already
|
||||
|
||||
def on_error(request, exc, uuid, state=FAILURE, call_errbacks=True):
|
||||
if propagate:
|
||||
raise
|
||||
I = Info(state, exc)
|
||||
R = I.handle_error_state(
|
||||
task, request, eager=eager, call_errbacks=call_errbacks,
|
||||
)
|
||||
return I, R, I.state, I.retval
|
||||
|
||||
def trace_task(uuid, args, kwargs, request=None):
|
||||
# R - is the possibly prepared return value.
|
||||
# I - is the Info object.
|
||||
# T - runtime
|
||||
# Rstr - textual representation of return value
|
||||
# retval - is the always unmodified return value.
|
||||
# state - is the resulting task state.
|
||||
|
||||
# This function is very long because we've unrolled all the calls
|
||||
# for performance reasons, and because the function is so long
|
||||
# we want the main variables (I, and R) to stand out visually from the
|
||||
# the rest of the variables, so breaking PEP8 is worth it ;)
|
||||
R = I = T = Rstr = retval = state = None
|
||||
task_request = None
|
||||
time_start = monotonic()
|
||||
try:
|
||||
try:
|
||||
kwargs.items
|
||||
except AttributeError:
|
||||
raise InvalidTaskError(
|
||||
'Task keyword arguments is not a mapping')
|
||||
|
||||
task_request = Context(request or {}, args=args,
|
||||
called_directly=False, kwargs=kwargs)
|
||||
|
||||
redelivered = (task_request.delivery_info
|
||||
and task_request.delivery_info.get('redelivered', False))
|
||||
if deduplicate_successful_tasks and redelivered:
|
||||
if task_request.id in successful_requests:
|
||||
return trace_ok_t(R, I, T, Rstr)
|
||||
r = AsyncResult(task_request.id, app=app)
|
||||
|
||||
try:
|
||||
state = r.state
|
||||
except BackendGetMetaError:
|
||||
pass
|
||||
else:
|
||||
if state == SUCCESS:
|
||||
info(LOG_IGNORED, {
|
||||
'id': task_request.id,
|
||||
'name': get_task_name(task_request, name),
|
||||
'description': 'Task already completed successfully.'
|
||||
})
|
||||
return trace_ok_t(R, I, T, Rstr)
|
||||
|
||||
push_task(task)
|
||||
root_id = task_request.root_id or uuid
|
||||
task_priority = task_request.delivery_info.get('priority') if \
|
||||
inherit_parent_priority else None
|
||||
push_request(task_request)
|
||||
try:
|
||||
# -*- PRE -*-
|
||||
if prerun_receivers:
|
||||
send_prerun(sender=task, task_id=uuid, task=task,
|
||||
args=args, kwargs=kwargs)
|
||||
loader_task_init(uuid, task)
|
||||
if track_started:
|
||||
task.backend.store_result(
|
||||
uuid, {'pid': pid, 'hostname': hostname}, STARTED,
|
||||
request=task_request,
|
||||
)
|
||||
|
||||
# -*- TRACE -*-
|
||||
try:
|
||||
if task_before_start:
|
||||
task_before_start(uuid, args, kwargs)
|
||||
|
||||
R = retval = fun(*args, **kwargs)
|
||||
state = SUCCESS
|
||||
except Reject as exc:
|
||||
I, R = Info(REJECTED, exc), ExceptionInfo(internal=True)
|
||||
state, retval = I.state, I.retval
|
||||
I.handle_reject(task, task_request)
|
||||
traceback_clear(exc)
|
||||
except Ignore as exc:
|
||||
I, R = Info(IGNORED, exc), ExceptionInfo(internal=True)
|
||||
state, retval = I.state, I.retval
|
||||
I.handle_ignore(task, task_request)
|
||||
traceback_clear(exc)
|
||||
except Retry as exc:
|
||||
I, R, state, retval = on_error(
|
||||
task_request, exc, uuid, RETRY, call_errbacks=False)
|
||||
traceback_clear(exc)
|
||||
except Exception as exc:
|
||||
I, R, state, retval = on_error(task_request, exc, uuid)
|
||||
traceback_clear(exc)
|
||||
except BaseException:
|
||||
raise
|
||||
else:
|
||||
try:
|
||||
# callback tasks must be applied before the result is
|
||||
# stored, so that result.children is populated.
|
||||
|
||||
# groups are called inline and will store trail
|
||||
# separately, so need to call them separately
|
||||
# so that the trail's not added multiple times :(
|
||||
# (Issue #1936)
|
||||
callbacks = task.request.callbacks
|
||||
if callbacks:
|
||||
if len(task.request.callbacks) > 1:
|
||||
sigs, groups = [], []
|
||||
for sig in callbacks:
|
||||
sig = signature(sig, app=app)
|
||||
if isinstance(sig, group):
|
||||
groups.append(sig)
|
||||
else:
|
||||
sigs.append(sig)
|
||||
for group_ in groups:
|
||||
group_.apply_async(
|
||||
(retval,),
|
||||
parent_id=uuid, root_id=root_id,
|
||||
priority=task_priority
|
||||
)
|
||||
if sigs:
|
||||
group(sigs, app=app).apply_async(
|
||||
(retval,),
|
||||
parent_id=uuid, root_id=root_id,
|
||||
priority=task_priority
|
||||
)
|
||||
else:
|
||||
signature(callbacks[0], app=app).apply_async(
|
||||
(retval,), parent_id=uuid, root_id=root_id,
|
||||
priority=task_priority
|
||||
)
|
||||
|
||||
# execute first task in chain
|
||||
chain = task_request.chain
|
||||
if chain:
|
||||
_chsig = signature(chain.pop(), app=app)
|
||||
_chsig.apply_async(
|
||||
(retval,), chain=chain,
|
||||
parent_id=uuid, root_id=root_id,
|
||||
priority=task_priority
|
||||
)
|
||||
task.backend.mark_as_done(
|
||||
uuid, retval, task_request, publish_result,
|
||||
)
|
||||
except EncodeError as exc:
|
||||
I, R, state, retval = on_error(task_request, exc, uuid)
|
||||
else:
|
||||
Rstr = saferepr(R, resultrepr_maxsize)
|
||||
T = monotonic() - time_start
|
||||
if task_on_success:
|
||||
task_on_success(retval, uuid, args, kwargs)
|
||||
if success_receivers:
|
||||
send_success(sender=task, result=retval)
|
||||
if _does_info:
|
||||
info(LOG_SUCCESS, {
|
||||
'id': uuid,
|
||||
'name': get_task_name(task_request, name),
|
||||
'return_value': Rstr,
|
||||
'runtime': T,
|
||||
'args': safe_repr(args),
|
||||
'kwargs': safe_repr(kwargs),
|
||||
})
|
||||
|
||||
# -* POST *-
|
||||
if state not in IGNORE_STATES:
|
||||
if task_after_return:
|
||||
task_after_return(
|
||||
state, retval, uuid, args, kwargs, None,
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
if postrun_receivers:
|
||||
send_postrun(sender=task, task_id=uuid, task=task,
|
||||
args=args, kwargs=kwargs,
|
||||
retval=retval, state=state)
|
||||
finally:
|
||||
pop_task()
|
||||
pop_request()
|
||||
if not eager:
|
||||
try:
|
||||
task.backend.process_cleanup()
|
||||
loader_cleanup()
|
||||
except (KeyboardInterrupt, SystemExit, MemoryError):
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.error('Process cleanup failed: %r', exc,
|
||||
exc_info=True)
|
||||
except MemoryError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
_signal_internal_error(task, uuid, args, kwargs, request, exc)
|
||||
if eager:
|
||||
raise
|
||||
R = report_internal_error(task, exc)
|
||||
if task_request is not None:
|
||||
I, _, _, _ = on_error(task_request, exc, uuid)
|
||||
return trace_ok_t(R, I, T, Rstr)
|
||||
|
||||
return trace_task
|
||||
|
||||
|
||||
def trace_task(task, uuid, args, kwargs, request=None, **opts):
|
||||
"""Trace task execution."""
|
||||
request = {} if not request else request
|
||||
try:
|
||||
if task.__trace__ is None:
|
||||
task.__trace__ = build_tracer(task.name, task, **opts)
|
||||
return task.__trace__(uuid, args, kwargs, request)
|
||||
except Exception as exc:
|
||||
_signal_internal_error(task, uuid, args, kwargs, request, exc)
|
||||
return trace_ok_t(report_internal_error(task, exc), TraceInfo(FAILURE, exc), 0.0, None)
|
||||
|
||||
|
||||
def _signal_internal_error(task, uuid, args, kwargs, request, exc):
|
||||
"""Send a special `internal_error` signal to the app for outside body errors."""
|
||||
try:
|
||||
_, _, tb = sys.exc_info()
|
||||
einfo = ExceptionInfo()
|
||||
einfo.exception = get_pickleable_exception(einfo.exception)
|
||||
einfo.type = get_pickleable_etype(einfo.type)
|
||||
signals.task_internal_error.send(
|
||||
sender=task,
|
||||
task_id=uuid,
|
||||
args=args,
|
||||
kwargs=kwargs,
|
||||
request=request,
|
||||
exception=exc,
|
||||
traceback=tb,
|
||||
einfo=einfo,
|
||||
)
|
||||
finally:
|
||||
del tb
|
||||
|
||||
|
||||
def trace_task_ret(name, uuid, request, body, content_type,
|
||||
content_encoding, loads=loads_message, app=None,
|
||||
**extra_request):
|
||||
app = app or current_app._get_current_object()
|
||||
embed = None
|
||||
if content_type:
|
||||
accept = prepare_accept_content(app.conf.accept_content)
|
||||
args, kwargs, embed = loads(
|
||||
body, content_type, content_encoding, accept=accept,
|
||||
)
|
||||
else:
|
||||
args, kwargs, embed = body
|
||||
hostname = gethostname()
|
||||
request.update({
|
||||
'args': args, 'kwargs': kwargs,
|
||||
'hostname': hostname, 'is_eager': False,
|
||||
}, **embed or {})
|
||||
R, I, T, Rstr = trace_task(app.tasks[name],
|
||||
uuid, args, kwargs, request, app=app)
|
||||
return (1, R, T) if I else (0, Rstr, T)
|
||||
|
||||
|
||||
def fast_trace_task(task, uuid, request, body, content_type,
|
||||
content_encoding, loads=loads_message, _loc=None,
|
||||
hostname=None, **_):
|
||||
_loc = _localized if not _loc else _loc
|
||||
embed = None
|
||||
tasks, accept, hostname = _loc
|
||||
if content_type:
|
||||
args, kwargs, embed = loads(
|
||||
body, content_type, content_encoding, accept=accept,
|
||||
)
|
||||
else:
|
||||
args, kwargs, embed = body
|
||||
request.update({
|
||||
'args': args, 'kwargs': kwargs,
|
||||
'hostname': hostname, 'is_eager': False,
|
||||
}, **embed or {})
|
||||
R, I, T, Rstr = tasks[task].__trace__(
|
||||
uuid, args, kwargs, request,
|
||||
)
|
||||
return (1, R, T) if I else (0, Rstr, T)
|
||||
|
||||
|
||||
def report_internal_error(task, exc):
|
||||
_type, _value, _tb = sys.exc_info()
|
||||
try:
|
||||
_value = task.backend.prepare_exception(exc, 'pickle')
|
||||
exc_info = ExceptionInfo((_type, _value, _tb), internal=True)
|
||||
warn(RuntimeWarning(
|
||||
'Exception raised outside body: {!r}:\n{}'.format(
|
||||
exc, exc_info.traceback)))
|
||||
return exc_info
|
||||
finally:
|
||||
del _tb
|
||||
|
||||
|
||||
def setup_worker_optimizations(app, hostname=None):
|
||||
"""Setup worker related optimizations."""
|
||||
hostname = hostname or gethostname()
|
||||
|
||||
# make sure custom Task.__call__ methods that calls super
|
||||
# won't mess up the request/task stack.
|
||||
_install_stack_protection()
|
||||
|
||||
# all new threads start without a current app, so if an app is not
|
||||
# passed on to the thread it will fall back to the "default app",
|
||||
# which then could be the wrong app. So for the worker
|
||||
# we set this to always return our app. This is a hack,
|
||||
# and means that only a single app can be used for workers
|
||||
# running in the same process.
|
||||
app.set_current()
|
||||
app.set_default()
|
||||
|
||||
# evaluate all task classes by finalizing the app.
|
||||
app.finalize()
|
||||
|
||||
# set fast shortcut to task registry
|
||||
_localized[:] = [
|
||||
app._tasks,
|
||||
prepare_accept_content(app.conf.accept_content),
|
||||
hostname,
|
||||
]
|
||||
|
||||
app.use_fast_trace_task = True
|
||||
|
||||
|
||||
def reset_worker_optimizations(app=current_app):
|
||||
"""Reset previously configured optimizations."""
|
||||
try:
|
||||
delattr(BaseTask, '_stackprotected')
|
||||
except AttributeError:
|
||||
pass
|
||||
try:
|
||||
BaseTask.__call__ = _patched.pop('BaseTask.__call__')
|
||||
except KeyError:
|
||||
pass
|
||||
app.use_fast_trace_task = False
|
||||
|
||||
|
||||
def _install_stack_protection():
|
||||
# Patches BaseTask.__call__ in the worker to handle the edge case
|
||||
# where people override it and also call super.
|
||||
#
|
||||
# - The worker optimizes away BaseTask.__call__ and instead
|
||||
# calls task.run directly.
|
||||
# - so with the addition of current_task and the request stack
|
||||
# BaseTask.__call__ now pushes to those stacks so that
|
||||
# they work when tasks are called directly.
|
||||
#
|
||||
# The worker only optimizes away __call__ in the case
|
||||
# where it hasn't been overridden, so the request/task stack
|
||||
# will blow if a custom task class defines __call__ and also
|
||||
# calls super().
|
||||
if not getattr(BaseTask, '_stackprotected', False):
|
||||
_patched['BaseTask.__call__'] = orig = BaseTask.__call__
|
||||
|
||||
def __protected_call__(self, *args, **kwargs):
|
||||
stack = self.request_stack
|
||||
req = stack.top
|
||||
if req and not req._protected and \
|
||||
len(stack) == 1 and not req.called_directly:
|
||||
req._protected = 1
|
||||
return self.run(*args, **kwargs)
|
||||
return orig(self, *args, **kwargs)
|
||||
BaseTask.__call__ = __protected_call__
|
||||
BaseTask._stackprotected = True
|
||||
@@ -0,0 +1,416 @@
|
||||
"""App utilities: Compat settings, bug-report tool, pickling apps."""
|
||||
import os
|
||||
import platform as _platform
|
||||
import re
|
||||
from collections import namedtuple
|
||||
from collections.abc import Mapping
|
||||
from copy import deepcopy
|
||||
from types import ModuleType
|
||||
|
||||
from kombu.utils.url import maybe_sanitize_url
|
||||
|
||||
from celery.exceptions import ImproperlyConfigured
|
||||
from celery.platforms import pyimplementation
|
||||
from celery.utils.collections import ConfigurationView
|
||||
from celery.utils.imports import import_from_cwd, qualname, symbol_by_name
|
||||
from celery.utils.text import pretty
|
||||
|
||||
from .defaults import (_OLD_DEFAULTS, _OLD_SETTING_KEYS, _TO_NEW_KEY,
|
||||
_TO_OLD_KEY, DEFAULTS, SETTING_KEYS, find)
|
||||
|
||||
__all__ = (
|
||||
'Settings', 'appstr', 'bugreport',
|
||||
'filter_hidden_settings', 'find_app',
|
||||
)
|
||||
|
||||
#: Format used to generate bug-report information.
|
||||
BUGREPORT_INFO = """
|
||||
software -> celery:{celery_v} kombu:{kombu_v} py:{py_v}
|
||||
billiard:{billiard_v} {driver_v}
|
||||
platform -> system:{system} arch:{arch}
|
||||
kernel version:{kernel_version} imp:{py_i}
|
||||
loader -> {loader}
|
||||
settings -> transport:{transport} results:{results}
|
||||
|
||||
{human_settings}
|
||||
"""
|
||||
|
||||
HIDDEN_SETTINGS = re.compile(
|
||||
'API|TOKEN|KEY|SECRET|PASS|PROFANITIES_LIST|SIGNATURE|DATABASE',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
E_MIX_OLD_INTO_NEW = """
|
||||
|
||||
Cannot mix new and old setting keys, please rename the
|
||||
following settings to the new format:
|
||||
|
||||
{renames}
|
||||
|
||||
"""
|
||||
|
||||
E_MIX_NEW_INTO_OLD = """
|
||||
|
||||
Cannot mix new setting names with old setting names, please
|
||||
rename the following settings to use the old format:
|
||||
|
||||
{renames}
|
||||
|
||||
Or change all of the settings to use the new format :)
|
||||
|
||||
"""
|
||||
|
||||
FMT_REPLACE_SETTING = '{replace:<36} -> {with_}'
|
||||
|
||||
|
||||
def appstr(app):
|
||||
"""String used in __repr__ etc, to id app instances."""
|
||||
return f'{app.main or "__main__"} at {id(app):#x}'
|
||||
|
||||
|
||||
class Settings(ConfigurationView):
|
||||
"""Celery settings object.
|
||||
|
||||
.. seealso:
|
||||
|
||||
:ref:`configuration` for a full list of configuration keys.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, *args, deprecated_settings=None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.deprecated_settings = deprecated_settings
|
||||
|
||||
@property
|
||||
def broker_read_url(self):
|
||||
return (
|
||||
os.environ.get('CELERY_BROKER_READ_URL') or
|
||||
self.get('broker_read_url') or
|
||||
self.broker_url
|
||||
)
|
||||
|
||||
@property
|
||||
def broker_write_url(self):
|
||||
return (
|
||||
os.environ.get('CELERY_BROKER_WRITE_URL') or
|
||||
self.get('broker_write_url') or
|
||||
self.broker_url
|
||||
)
|
||||
|
||||
@property
|
||||
def broker_url(self):
|
||||
return (
|
||||
os.environ.get('CELERY_BROKER_URL') or
|
||||
self.first('broker_url', 'broker_host')
|
||||
)
|
||||
|
||||
@property
|
||||
def result_backend(self):
|
||||
return (
|
||||
os.environ.get('CELERY_RESULT_BACKEND') or
|
||||
self.first('result_backend', 'CELERY_RESULT_BACKEND')
|
||||
)
|
||||
|
||||
@property
|
||||
def task_default_exchange(self):
|
||||
return self.first(
|
||||
'task_default_exchange',
|
||||
'task_default_queue',
|
||||
)
|
||||
|
||||
@property
|
||||
def task_default_routing_key(self):
|
||||
return self.first(
|
||||
'task_default_routing_key',
|
||||
'task_default_queue',
|
||||
)
|
||||
|
||||
@property
|
||||
def timezone(self):
|
||||
# this way we also support django's time zone.
|
||||
return self.first('timezone', 'time_zone')
|
||||
|
||||
def without_defaults(self):
|
||||
"""Return the current configuration, but without defaults."""
|
||||
# the last stash is the default settings, so just skip that
|
||||
return Settings({}, self.maps[:-1])
|
||||
|
||||
def value_set_for(self, key):
|
||||
return key in self.without_defaults()
|
||||
|
||||
def find_option(self, name, namespace=''):
|
||||
"""Search for option by name.
|
||||
|
||||
Example:
|
||||
>>> from proj.celery import app
|
||||
>>> app.conf.find_option('disable_rate_limits')
|
||||
('worker', 'prefetch_multiplier',
|
||||
<Option: type->bool default->False>))
|
||||
|
||||
Arguments:
|
||||
name (str): Name of option, cannot be partial.
|
||||
namespace (str): Preferred name-space (``None`` by default).
|
||||
Returns:
|
||||
Tuple: of ``(namespace, key, type)``.
|
||||
"""
|
||||
return find(name, namespace)
|
||||
|
||||
def find_value_for_key(self, name, namespace='celery'):
|
||||
"""Shortcut to ``get_by_parts(*find_option(name)[:-1])``."""
|
||||
return self.get_by_parts(*self.find_option(name, namespace)[:-1])
|
||||
|
||||
def get_by_parts(self, *parts):
|
||||
"""Return the current value for setting specified as a path.
|
||||
|
||||
Example:
|
||||
>>> from proj.celery import app
|
||||
>>> app.conf.get_by_parts('worker', 'disable_rate_limits')
|
||||
False
|
||||
"""
|
||||
return self['_'.join(part for part in parts if part)]
|
||||
|
||||
def finalize(self):
|
||||
# See PendingConfiguration in celery/app/base.py
|
||||
# first access will read actual configuration.
|
||||
try:
|
||||
self['__bogus__']
|
||||
except KeyError:
|
||||
pass
|
||||
return self
|
||||
|
||||
def table(self, with_defaults=False, censored=True):
|
||||
filt = filter_hidden_settings if censored else lambda v: v
|
||||
dict_members = dir(dict)
|
||||
self.finalize()
|
||||
settings = self if with_defaults else self.without_defaults()
|
||||
return filt({
|
||||
k: v for k, v in settings.items()
|
||||
if not k.startswith('_') and k not in dict_members
|
||||
})
|
||||
|
||||
def humanize(self, with_defaults=False, censored=True):
|
||||
"""Return a human readable text showing configuration changes."""
|
||||
return '\n'.join(
|
||||
f'{key}: {pretty(value, width=50)}'
|
||||
for key, value in self.table(with_defaults, censored).items())
|
||||
|
||||
def maybe_warn_deprecated_settings(self):
|
||||
# TODO: Remove this method in Celery 6.0
|
||||
if self.deprecated_settings:
|
||||
from celery.app.defaults import _TO_NEW_KEY
|
||||
from celery.utils import deprecated
|
||||
for setting in self.deprecated_settings:
|
||||
deprecated.warn(description=f'The {setting!r} setting',
|
||||
removal='6.0.0',
|
||||
alternative=f'Use the {_TO_NEW_KEY[setting]} instead')
|
||||
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _new_key_to_old(key, convert=_TO_OLD_KEY.get):
|
||||
return convert(key, key)
|
||||
|
||||
|
||||
def _old_key_to_new(key, convert=_TO_NEW_KEY.get):
|
||||
return convert(key, key)
|
||||
|
||||
|
||||
_settings_info_t = namedtuple('settings_info_t', (
|
||||
'defaults', 'convert', 'key_t', 'mix_error',
|
||||
))
|
||||
|
||||
_settings_info = _settings_info_t(
|
||||
DEFAULTS, _TO_NEW_KEY, _old_key_to_new, E_MIX_OLD_INTO_NEW,
|
||||
)
|
||||
_old_settings_info = _settings_info_t(
|
||||
_OLD_DEFAULTS, _TO_OLD_KEY, _new_key_to_old, E_MIX_NEW_INTO_OLD,
|
||||
)
|
||||
|
||||
|
||||
def detect_settings(conf, preconf=None, ignore_keys=None, prefix=None,
|
||||
all_keys=None, old_keys=None):
|
||||
preconf = {} if not preconf else preconf
|
||||
ignore_keys = set() if not ignore_keys else ignore_keys
|
||||
all_keys = SETTING_KEYS if not all_keys else all_keys
|
||||
old_keys = _OLD_SETTING_KEYS if not old_keys else old_keys
|
||||
|
||||
source = conf
|
||||
if conf is None:
|
||||
source, conf = preconf, {}
|
||||
have = set(source.keys()) - ignore_keys
|
||||
is_in_new = have.intersection(all_keys)
|
||||
is_in_old = have.intersection(old_keys)
|
||||
|
||||
info = None
|
||||
if is_in_new:
|
||||
# have new setting names
|
||||
info, left = _settings_info, is_in_old
|
||||
if is_in_old and len(is_in_old) > len(is_in_new):
|
||||
# Majority of the settings are old.
|
||||
info, left = _old_settings_info, is_in_new
|
||||
if is_in_old:
|
||||
# have old setting names, or a majority of the names are old.
|
||||
if not info:
|
||||
info, left = _old_settings_info, is_in_new
|
||||
if is_in_new and len(is_in_new) > len(is_in_old):
|
||||
# Majority of the settings are new
|
||||
info, left = _settings_info, is_in_old
|
||||
else:
|
||||
# no settings, just use new format.
|
||||
info, left = _settings_info, is_in_old
|
||||
|
||||
if prefix:
|
||||
# always use new format if prefix is used.
|
||||
info, left = _settings_info, set()
|
||||
|
||||
# only raise error for keys that the user didn't provide two keys
|
||||
# for (e.g., both ``result_expires`` and ``CELERY_TASK_RESULT_EXPIRES``).
|
||||
really_left = {key for key in left if info.convert[key] not in have}
|
||||
if really_left:
|
||||
# user is mixing old/new, or new/old settings, give renaming
|
||||
# suggestions.
|
||||
raise ImproperlyConfigured(info.mix_error.format(renames='\n'.join(
|
||||
FMT_REPLACE_SETTING.format(replace=key, with_=info.convert[key])
|
||||
for key in sorted(really_left)
|
||||
)))
|
||||
|
||||
preconf = {info.convert.get(k, k): v for k, v in preconf.items()}
|
||||
defaults = dict(deepcopy(info.defaults), **preconf)
|
||||
return Settings(
|
||||
preconf, [conf, defaults],
|
||||
(_old_key_to_new, _new_key_to_old),
|
||||
deprecated_settings=is_in_old,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
|
||||
class AppPickler:
|
||||
"""Old application pickler/unpickler (< 3.1)."""
|
||||
|
||||
def __call__(self, cls, *args):
|
||||
kwargs = self.build_kwargs(*args)
|
||||
app = self.construct(cls, **kwargs)
|
||||
self.prepare(app, **kwargs)
|
||||
return app
|
||||
|
||||
def prepare(self, app, **kwargs):
|
||||
app.conf.update(kwargs['changes'])
|
||||
|
||||
def build_kwargs(self, *args):
|
||||
return self.build_standard_kwargs(*args)
|
||||
|
||||
def build_standard_kwargs(self, main, changes, loader, backend, amqp,
|
||||
events, log, control, accept_magic_kwargs,
|
||||
config_source=None):
|
||||
return {'main': main, 'loader': loader, 'backend': backend,
|
||||
'amqp': amqp, 'changes': changes, 'events': events,
|
||||
'log': log, 'control': control, 'set_as_current': False,
|
||||
'config_source': config_source}
|
||||
|
||||
def construct(self, cls, **kwargs):
|
||||
return cls(**kwargs)
|
||||
|
||||
|
||||
def _unpickle_app(cls, pickler, *args):
|
||||
"""Rebuild app for versions 2.5+."""
|
||||
return pickler()(cls, *args)
|
||||
|
||||
|
||||
def _unpickle_app_v2(cls, kwargs):
|
||||
"""Rebuild app for versions 3.1+."""
|
||||
kwargs['set_as_current'] = False
|
||||
return cls(**kwargs)
|
||||
|
||||
|
||||
def filter_hidden_settings(conf):
|
||||
"""Filter sensitive settings."""
|
||||
def maybe_censor(key, value, mask='*' * 8):
|
||||
if isinstance(value, Mapping):
|
||||
return filter_hidden_settings(value)
|
||||
if isinstance(key, str):
|
||||
if HIDDEN_SETTINGS.search(key):
|
||||
return mask
|
||||
elif 'broker_url' in key.lower():
|
||||
from kombu import Connection
|
||||
return Connection(value).as_uri(mask=mask)
|
||||
elif 'backend' in key.lower():
|
||||
return maybe_sanitize_url(value, mask=mask)
|
||||
|
||||
return value
|
||||
|
||||
return {k: maybe_censor(k, v) for k, v in conf.items()}
|
||||
|
||||
|
||||
def bugreport(app):
|
||||
"""Return a string containing information useful in bug-reports."""
|
||||
import billiard
|
||||
import kombu
|
||||
|
||||
import celery
|
||||
|
||||
try:
|
||||
conn = app.connection()
|
||||
driver_v = '{}:{}'.format(conn.transport.driver_name,
|
||||
conn.transport.driver_version())
|
||||
transport = conn.transport_cls
|
||||
except Exception: # pylint: disable=broad-except
|
||||
transport = driver_v = ''
|
||||
|
||||
return BUGREPORT_INFO.format(
|
||||
system=_platform.system(),
|
||||
arch=', '.join(x for x in _platform.architecture() if x),
|
||||
kernel_version=_platform.release(),
|
||||
py_i=pyimplementation(),
|
||||
celery_v=celery.VERSION_BANNER,
|
||||
kombu_v=kombu.__version__,
|
||||
billiard_v=billiard.__version__,
|
||||
py_v=_platform.python_version(),
|
||||
driver_v=driver_v,
|
||||
transport=transport,
|
||||
results=maybe_sanitize_url(app.conf.result_backend or 'disabled'),
|
||||
human_settings=app.conf.humanize(),
|
||||
loader=qualname(app.loader.__class__),
|
||||
)
|
||||
|
||||
|
||||
def find_app(app, symbol_by_name=symbol_by_name, imp=import_from_cwd):
|
||||
"""Find app by name."""
|
||||
from .base import Celery
|
||||
|
||||
try:
|
||||
sym = symbol_by_name(app, imp=imp)
|
||||
except AttributeError:
|
||||
# last part was not an attribute, but a module
|
||||
sym = imp(app)
|
||||
if isinstance(sym, ModuleType) and ':' not in app:
|
||||
try:
|
||||
found = sym.app
|
||||
if isinstance(found, ModuleType):
|
||||
raise AttributeError()
|
||||
except AttributeError:
|
||||
try:
|
||||
found = sym.celery
|
||||
if isinstance(found, ModuleType):
|
||||
raise AttributeError(
|
||||
"attribute 'celery' is the celery module not the instance of celery")
|
||||
except AttributeError:
|
||||
if getattr(sym, '__path__', None):
|
||||
try:
|
||||
return find_app(
|
||||
f'{app}.celery',
|
||||
symbol_by_name=symbol_by_name, imp=imp,
|
||||
)
|
||||
except ImportError:
|
||||
pass
|
||||
for suspect in vars(sym).values():
|
||||
if isinstance(suspect, Celery):
|
||||
return suspect
|
||||
raise
|
||||
else:
|
||||
return found
|
||||
else:
|
||||
return found
|
||||
return sym
|
||||
Whitespace-only changes.
@@ -0,0 +1,152 @@
|
||||
"""Beat command-line program.
|
||||
|
||||
This module is the 'program-version' of :mod:`celery.beat`.
|
||||
|
||||
It does everything necessary to run that module
|
||||
as an actual application, like installing signal handlers
|
||||
and so on.
|
||||
"""
|
||||
import numbers
|
||||
import socket
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
from celery import VERSION_BANNER, beat, platforms
|
||||
from celery.utils.imports import qualname
|
||||
from celery.utils.log import LOG_LEVELS, get_logger
|
||||
from celery.utils.time import humanize_seconds
|
||||
|
||||
__all__ = ('Beat',)
|
||||
|
||||
STARTUP_INFO_FMT = """
|
||||
LocalTime -> {timestamp}
|
||||
Configuration ->
|
||||
. broker -> {conninfo}
|
||||
. loader -> {loader}
|
||||
. scheduler -> {scheduler}
|
||||
{scheduler_info}
|
||||
. logfile -> {logfile}@%{loglevel}
|
||||
. maxinterval -> {hmax_interval} ({max_interval}s)
|
||||
""".strip()
|
||||
|
||||
logger = get_logger('celery.beat')
|
||||
|
||||
|
||||
class Beat:
|
||||
"""Beat as a service."""
|
||||
|
||||
Service = beat.Service
|
||||
app = None
|
||||
|
||||
def __init__(self, max_interval=None, app=None,
|
||||
socket_timeout=30, pidfile=None, no_color=None,
|
||||
loglevel='WARN', logfile=None, schedule=None,
|
||||
scheduler=None,
|
||||
scheduler_cls=None, # XXX use scheduler
|
||||
redirect_stdouts=None,
|
||||
redirect_stdouts_level=None, **kwargs):
|
||||
self.app = app = app or self.app
|
||||
either = self.app.either
|
||||
self.loglevel = loglevel
|
||||
self.logfile = logfile
|
||||
self.schedule = either('beat_schedule_filename', schedule)
|
||||
self.scheduler_cls = either(
|
||||
'beat_scheduler', scheduler, scheduler_cls)
|
||||
self.redirect_stdouts = either(
|
||||
'worker_redirect_stdouts', redirect_stdouts)
|
||||
self.redirect_stdouts_level = either(
|
||||
'worker_redirect_stdouts_level', redirect_stdouts_level)
|
||||
|
||||
self.max_interval = max_interval
|
||||
self.socket_timeout = socket_timeout
|
||||
self.no_color = no_color
|
||||
self.colored = app.log.colored(
|
||||
self.logfile,
|
||||
enabled=not no_color if no_color is not None else no_color,
|
||||
)
|
||||
self.pidfile = pidfile
|
||||
|
||||
if not isinstance(self.loglevel, numbers.Integral):
|
||||
self.loglevel = LOG_LEVELS[self.loglevel.upper()]
|
||||
|
||||
def run(self):
|
||||
print(str(self.colored.cyan(
|
||||
f'celery beat v{VERSION_BANNER} is starting.')))
|
||||
self.init_loader()
|
||||
self.set_process_title()
|
||||
self.start_scheduler()
|
||||
|
||||
def setup_logging(self, colorize=None):
|
||||
if colorize is None and self.no_color is not None:
|
||||
colorize = not self.no_color
|
||||
self.app.log.setup(self.loglevel, self.logfile,
|
||||
self.redirect_stdouts, self.redirect_stdouts_level,
|
||||
colorize=colorize)
|
||||
|
||||
def start_scheduler(self):
|
||||
if self.pidfile:
|
||||
platforms.create_pidlock(self.pidfile)
|
||||
service = self.Service(
|
||||
app=self.app,
|
||||
max_interval=self.max_interval,
|
||||
scheduler_cls=self.scheduler_cls,
|
||||
schedule_filename=self.schedule,
|
||||
)
|
||||
|
||||
print(self.banner(service))
|
||||
|
||||
self.setup_logging()
|
||||
if self.socket_timeout:
|
||||
logger.debug('Setting default socket timeout to %r',
|
||||
self.socket_timeout)
|
||||
socket.setdefaulttimeout(self.socket_timeout)
|
||||
try:
|
||||
self.install_sync_handler(service)
|
||||
service.start()
|
||||
except Exception as exc:
|
||||
logger.critical('beat raised exception %s: %r',
|
||||
exc.__class__, exc,
|
||||
exc_info=True)
|
||||
raise
|
||||
|
||||
def banner(self, service):
|
||||
c = self.colored
|
||||
return str(
|
||||
c.blue('__ ', c.magenta('-'),
|
||||
c.blue(' ... __ '), c.magenta('-'),
|
||||
c.blue(' _\n'),
|
||||
c.reset(self.startup_info(service))),
|
||||
)
|
||||
|
||||
def init_loader(self):
|
||||
# Run the worker init handler.
|
||||
# (Usually imports task modules and such.)
|
||||
self.app.loader.init_worker()
|
||||
self.app.finalize()
|
||||
|
||||
def startup_info(self, service):
|
||||
scheduler = service.get_scheduler(lazy=True)
|
||||
return STARTUP_INFO_FMT.format(
|
||||
conninfo=self.app.connection().as_uri(),
|
||||
timestamp=datetime.now().replace(microsecond=0),
|
||||
logfile=self.logfile or '[stderr]',
|
||||
loglevel=LOG_LEVELS[self.loglevel],
|
||||
loader=qualname(self.app.loader),
|
||||
scheduler=qualname(scheduler),
|
||||
scheduler_info=scheduler.info,
|
||||
hmax_interval=humanize_seconds(scheduler.max_interval),
|
||||
max_interval=scheduler.max_interval,
|
||||
)
|
||||
|
||||
def set_process_title(self):
|
||||
arg_start = 'manage' in sys.argv[0] and 2 or 1
|
||||
platforms.set_process_title(
|
||||
'celery beat', info=' '.join(sys.argv[arg_start:]),
|
||||
)
|
||||
|
||||
def install_sync_handler(self, service):
|
||||
"""Install a `SIGTERM` + `SIGINT` handler saving the schedule."""
|
||||
def _sync(signum, frame):
|
||||
service.sync()
|
||||
raise SystemExit()
|
||||
platforms.signals.update(SIGTERM=_sync, SIGINT=_sync)
|
||||
@@ -0,0 +1,507 @@
|
||||
"""Start/stop/manage workers."""
|
||||
import errno
|
||||
import os
|
||||
import shlex
|
||||
import signal
|
||||
import sys
|
||||
from collections import OrderedDict, UserList, defaultdict
|
||||
from functools import partial
|
||||
from subprocess import Popen
|
||||
from time import sleep
|
||||
|
||||
from kombu.utils.encoding import from_utf8
|
||||
from kombu.utils.objects import cached_property
|
||||
|
||||
from celery.platforms import IS_WINDOWS, Pidfile, signal_name
|
||||
from celery.utils.nodenames import (gethostname, host_format, node_format,
|
||||
nodesplit)
|
||||
from celery.utils.saferepr import saferepr
|
||||
|
||||
__all__ = ('Cluster', 'Node')
|
||||
|
||||
CELERY_EXE = 'celery'
|
||||
|
||||
|
||||
def celery_exe(*args):
|
||||
return ' '.join((CELERY_EXE,) + args)
|
||||
|
||||
|
||||
def build_nodename(name, prefix, suffix):
|
||||
hostname = suffix
|
||||
if '@' in name:
|
||||
nodename = host_format(name)
|
||||
shortname, hostname = nodesplit(nodename)
|
||||
name = shortname
|
||||
else:
|
||||
shortname = f'{prefix}{name}'
|
||||
nodename = host_format(
|
||||
f'{shortname}@{hostname}',
|
||||
)
|
||||
return name, nodename, hostname
|
||||
|
||||
|
||||
def build_expander(nodename, shortname, hostname):
|
||||
return partial(
|
||||
node_format,
|
||||
name=nodename,
|
||||
N=shortname,
|
||||
d=hostname,
|
||||
h=nodename,
|
||||
i='%i',
|
||||
I='%I',
|
||||
)
|
||||
|
||||
|
||||
def format_opt(opt, value):
|
||||
if not value:
|
||||
return opt
|
||||
if opt.startswith('--'):
|
||||
return f'{opt}={value}'
|
||||
return f'{opt} {value}'
|
||||
|
||||
|
||||
def _kwargs_to_command_line(kwargs):
|
||||
return {
|
||||
('--{}'.format(k.replace('_', '-'))
|
||||
if len(k) > 1 else f'-{k}'): f'{v}'
|
||||
for k, v in kwargs.items()
|
||||
}
|
||||
|
||||
|
||||
class NamespacedOptionParser:
|
||||
|
||||
def __init__(self, args):
|
||||
self.args = args
|
||||
self.options = OrderedDict()
|
||||
self.values = []
|
||||
self.passthrough = ''
|
||||
self.namespaces = defaultdict(lambda: OrderedDict())
|
||||
|
||||
def parse(self):
|
||||
rargs = [arg for arg in self.args if arg]
|
||||
pos = 0
|
||||
while pos < len(rargs):
|
||||
arg = rargs[pos]
|
||||
if arg == '--':
|
||||
self.passthrough = ' '.join(rargs[pos:])
|
||||
break
|
||||
elif arg[0] == '-':
|
||||
if arg[1] == '-':
|
||||
self.process_long_opt(arg[2:])
|
||||
else:
|
||||
value = None
|
||||
if len(rargs) > pos + 1 and rargs[pos + 1][0] != '-':
|
||||
value = rargs[pos + 1]
|
||||
pos += 1
|
||||
self.process_short_opt(arg[1:], value)
|
||||
else:
|
||||
self.values.append(arg)
|
||||
pos += 1
|
||||
|
||||
def process_long_opt(self, arg, value=None):
|
||||
if '=' in arg:
|
||||
arg, value = arg.split('=', 1)
|
||||
self.add_option(arg, value, short=False)
|
||||
|
||||
def process_short_opt(self, arg, value=None):
|
||||
self.add_option(arg, value, short=True)
|
||||
|
||||
def optmerge(self, ns, defaults=None):
|
||||
if defaults is None:
|
||||
defaults = self.options
|
||||
return OrderedDict(defaults, **self.namespaces[ns])
|
||||
|
||||
def add_option(self, name, value, short=False, ns=None):
|
||||
prefix = short and '-' or '--'
|
||||
dest = self.options
|
||||
if ':' in name:
|
||||
name, ns = name.split(':')
|
||||
dest = self.namespaces[ns]
|
||||
dest[prefix + name] = value
|
||||
|
||||
|
||||
class Node:
|
||||
"""Represents a node in a cluster."""
|
||||
|
||||
def __init__(self, name,
|
||||
cmd=None, append=None, options=None, extra_args=None):
|
||||
self.name = name
|
||||
self.cmd = cmd or f"-m {celery_exe('worker', '--detach')}"
|
||||
self.append = append
|
||||
self.extra_args = extra_args or ''
|
||||
self.options = self._annotate_with_default_opts(
|
||||
options or OrderedDict())
|
||||
self.expander = self._prepare_expander()
|
||||
self.argv = self._prepare_argv()
|
||||
self._pid = None
|
||||
|
||||
def _annotate_with_default_opts(self, options):
|
||||
options['-n'] = self.name
|
||||
self._setdefaultopt(options, ['--pidfile', '-p'], '/var/run/celery/%n.pid')
|
||||
self._setdefaultopt(options, ['--logfile', '-f'], '/var/log/celery/%n%I.log')
|
||||
self._setdefaultopt(options, ['--executable'], sys.executable)
|
||||
return options
|
||||
|
||||
def _setdefaultopt(self, d, alt, value):
|
||||
for opt in alt[1:]:
|
||||
try:
|
||||
return d[opt]
|
||||
except KeyError:
|
||||
pass
|
||||
value = d.setdefault(alt[0], os.path.normpath(value))
|
||||
dir_path = os.path.dirname(value)
|
||||
if dir_path and not os.path.exists(dir_path):
|
||||
os.makedirs(dir_path)
|
||||
return value
|
||||
|
||||
def _prepare_expander(self):
|
||||
shortname, hostname = self.name.split('@', 1)
|
||||
return build_expander(
|
||||
self.name, shortname, hostname)
|
||||
|
||||
def _prepare_argv(self):
|
||||
cmd = self.expander(self.cmd).split(' ')
|
||||
i = cmd.index('celery') + 1
|
||||
|
||||
options = self.options.copy()
|
||||
for opt, value in self.options.items():
|
||||
if opt in (
|
||||
'-A', '--app',
|
||||
'-b', '--broker',
|
||||
'--result-backend',
|
||||
'--loader',
|
||||
'--config',
|
||||
'--workdir',
|
||||
'-C', '--no-color',
|
||||
'-q', '--quiet',
|
||||
):
|
||||
cmd.insert(i, format_opt(opt, self.expander(value)))
|
||||
|
||||
options.pop(opt)
|
||||
|
||||
cmd = [' '.join(cmd)]
|
||||
argv = tuple(
|
||||
cmd +
|
||||
[format_opt(opt, self.expander(value))
|
||||
for opt, value in options.items()] +
|
||||
[self.extra_args]
|
||||
)
|
||||
if self.append:
|
||||
argv += (self.expander(self.append),)
|
||||
return argv
|
||||
|
||||
def alive(self):
|
||||
return self.send(0)
|
||||
|
||||
def send(self, sig, on_error=None):
|
||||
pid = self.pid
|
||||
if pid:
|
||||
try:
|
||||
os.kill(pid, sig)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.ESRCH:
|
||||
raise
|
||||
maybe_call(on_error, self)
|
||||
return False
|
||||
return True
|
||||
maybe_call(on_error, self)
|
||||
|
||||
def start(self, env=None, **kwargs):
|
||||
return self._waitexec(
|
||||
self.argv, path=self.executable, env=env, **kwargs)
|
||||
|
||||
def _waitexec(self, argv, path=sys.executable, env=None,
|
||||
on_spawn=None, on_signalled=None, on_failure=None):
|
||||
argstr = self.prepare_argv(argv, path)
|
||||
maybe_call(on_spawn, self, argstr=' '.join(argstr), env=env)
|
||||
pipe = Popen(argstr, env=env)
|
||||
return self.handle_process_exit(
|
||||
pipe.wait(),
|
||||
on_signalled=on_signalled,
|
||||
on_failure=on_failure,
|
||||
)
|
||||
|
||||
def handle_process_exit(self, retcode, on_signalled=None, on_failure=None):
|
||||
if retcode < 0:
|
||||
maybe_call(on_signalled, self, -retcode)
|
||||
return -retcode
|
||||
elif retcode > 0:
|
||||
maybe_call(on_failure, self, retcode)
|
||||
return retcode
|
||||
|
||||
def prepare_argv(self, argv, path):
|
||||
args = ' '.join([path] + list(argv))
|
||||
return shlex.split(from_utf8(args), posix=not IS_WINDOWS)
|
||||
|
||||
def getopt(self, *alt):
|
||||
for opt in alt:
|
||||
try:
|
||||
return self.options[opt]
|
||||
except KeyError:
|
||||
pass
|
||||
raise KeyError(alt[0])
|
||||
|
||||
def __repr__(self):
|
||||
return f'<{type(self).__name__}: {self.name}>'
|
||||
|
||||
@cached_property
|
||||
def pidfile(self):
|
||||
return self.expander(self.getopt('--pidfile', '-p'))
|
||||
|
||||
@cached_property
|
||||
def logfile(self):
|
||||
return self.expander(self.getopt('--logfile', '-f'))
|
||||
|
||||
@property
|
||||
def pid(self):
|
||||
if self._pid is not None:
|
||||
return self._pid
|
||||
try:
|
||||
return Pidfile(self.pidfile).read_pid()
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
@pid.setter
|
||||
def pid(self, value):
|
||||
self._pid = value
|
||||
|
||||
@cached_property
|
||||
def executable(self):
|
||||
return self.options['--executable']
|
||||
|
||||
@cached_property
|
||||
def argv_with_executable(self):
|
||||
return (self.executable,) + self.argv
|
||||
|
||||
@classmethod
|
||||
def from_kwargs(cls, name, **kwargs):
|
||||
return cls(name, options=_kwargs_to_command_line(kwargs))
|
||||
|
||||
|
||||
def maybe_call(fun, *args, **kwargs):
|
||||
if fun is not None:
|
||||
fun(*args, **kwargs)
|
||||
|
||||
|
||||
class MultiParser:
|
||||
Node = Node
|
||||
|
||||
def __init__(self, cmd='celery worker',
|
||||
append='', prefix='', suffix='',
|
||||
range_prefix='celery'):
|
||||
self.cmd = cmd
|
||||
self.append = append
|
||||
self.prefix = prefix
|
||||
self.suffix = suffix
|
||||
self.range_prefix = range_prefix
|
||||
|
||||
def parse(self, p):
|
||||
names = p.values
|
||||
options = dict(p.options)
|
||||
ranges = len(names) == 1
|
||||
prefix = self.prefix
|
||||
cmd = options.pop('--cmd', self.cmd)
|
||||
append = options.pop('--append', self.append)
|
||||
hostname = options.pop('--hostname', options.pop('-n', gethostname()))
|
||||
prefix = options.pop('--prefix', prefix) or ''
|
||||
suffix = options.pop('--suffix', self.suffix) or hostname
|
||||
suffix = '' if suffix in ('""', "''") else suffix
|
||||
range_prefix = options.pop('--range-prefix', '') or self.range_prefix
|
||||
if ranges:
|
||||
try:
|
||||
names, prefix = self._get_ranges(names), range_prefix
|
||||
except ValueError:
|
||||
pass
|
||||
self._update_ns_opts(p, names)
|
||||
self._update_ns_ranges(p, ranges)
|
||||
|
||||
return (
|
||||
self._node_from_options(
|
||||
p, name, prefix, suffix, cmd, append, options)
|
||||
for name in names
|
||||
)
|
||||
|
||||
def _node_from_options(self, p, name, prefix,
|
||||
suffix, cmd, append, options):
|
||||
namespace, nodename, _ = build_nodename(name, prefix, suffix)
|
||||
namespace = nodename if nodename in p.namespaces else namespace
|
||||
return Node(nodename, cmd, append,
|
||||
p.optmerge(namespace, options), p.passthrough)
|
||||
|
||||
def _get_ranges(self, names):
|
||||
noderange = int(names[0])
|
||||
return [str(n) for n in range(1, noderange + 1)]
|
||||
|
||||
def _update_ns_opts(self, p, names):
|
||||
# Numbers in args always refers to the index in the list of names.
|
||||
# (e.g., `start foo bar baz -c:1` where 1 is foo, 2 is bar, and so on).
|
||||
for ns_name, ns_opts in list(p.namespaces.items()):
|
||||
if ns_name.isdigit():
|
||||
ns_index = int(ns_name) - 1
|
||||
if ns_index < 0:
|
||||
raise KeyError(f'Indexes start at 1 got: {ns_name!r}')
|
||||
try:
|
||||
p.namespaces[names[ns_index]].update(ns_opts)
|
||||
except IndexError:
|
||||
raise KeyError(f'No node at index {ns_name!r}')
|
||||
|
||||
def _update_ns_ranges(self, p, ranges):
|
||||
for ns_name, ns_opts in list(p.namespaces.items()):
|
||||
if ',' in ns_name or (ranges and '-' in ns_name):
|
||||
for subns in self._parse_ns_range(ns_name, ranges):
|
||||
p.namespaces[subns].update(ns_opts)
|
||||
p.namespaces.pop(ns_name)
|
||||
|
||||
def _parse_ns_range(self, ns, ranges=False):
|
||||
ret = []
|
||||
for space in ',' in ns and ns.split(',') or [ns]:
|
||||
if ranges and '-' in space:
|
||||
start, stop = space.split('-')
|
||||
ret.extend(
|
||||
str(n) for n in range(int(start), int(stop) + 1)
|
||||
)
|
||||
else:
|
||||
ret.append(space)
|
||||
return ret
|
||||
|
||||
|
||||
class Cluster(UserList):
|
||||
"""Represent a cluster of workers."""
|
||||
|
||||
def __init__(self, nodes, cmd=None, env=None,
|
||||
on_stopping_preamble=None,
|
||||
on_send_signal=None,
|
||||
on_still_waiting_for=None,
|
||||
on_still_waiting_progress=None,
|
||||
on_still_waiting_end=None,
|
||||
on_node_start=None,
|
||||
on_node_restart=None,
|
||||
on_node_shutdown_ok=None,
|
||||
on_node_status=None,
|
||||
on_node_signal=None,
|
||||
on_node_signal_dead=None,
|
||||
on_node_down=None,
|
||||
on_child_spawn=None,
|
||||
on_child_signalled=None,
|
||||
on_child_failure=None):
|
||||
self.nodes = nodes
|
||||
self.cmd = cmd or celery_exe('worker')
|
||||
self.env = env
|
||||
|
||||
self.on_stopping_preamble = on_stopping_preamble
|
||||
self.on_send_signal = on_send_signal
|
||||
self.on_still_waiting_for = on_still_waiting_for
|
||||
self.on_still_waiting_progress = on_still_waiting_progress
|
||||
self.on_still_waiting_end = on_still_waiting_end
|
||||
self.on_node_start = on_node_start
|
||||
self.on_node_restart = on_node_restart
|
||||
self.on_node_shutdown_ok = on_node_shutdown_ok
|
||||
self.on_node_status = on_node_status
|
||||
self.on_node_signal = on_node_signal
|
||||
self.on_node_signal_dead = on_node_signal_dead
|
||||
self.on_node_down = on_node_down
|
||||
self.on_child_spawn = on_child_spawn
|
||||
self.on_child_signalled = on_child_signalled
|
||||
self.on_child_failure = on_child_failure
|
||||
|
||||
def start(self):
|
||||
return [self.start_node(node) for node in self]
|
||||
|
||||
def start_node(self, node):
|
||||
maybe_call(self.on_node_start, node)
|
||||
retcode = self._start_node(node)
|
||||
maybe_call(self.on_node_status, node, retcode)
|
||||
return retcode
|
||||
|
||||
def _start_node(self, node):
|
||||
return node.start(
|
||||
self.env,
|
||||
on_spawn=self.on_child_spawn,
|
||||
on_signalled=self.on_child_signalled,
|
||||
on_failure=self.on_child_failure,
|
||||
)
|
||||
|
||||
def send_all(self, sig):
|
||||
for node in self.getpids(on_down=self.on_node_down):
|
||||
maybe_call(self.on_node_signal, node, signal_name(sig))
|
||||
node.send(sig, self.on_node_signal_dead)
|
||||
|
||||
def kill(self):
|
||||
return self.send_all(signal.SIGKILL)
|
||||
|
||||
def restart(self, sig=signal.SIGTERM):
|
||||
retvals = []
|
||||
|
||||
def restart_on_down(node):
|
||||
maybe_call(self.on_node_restart, node)
|
||||
retval = self._start_node(node)
|
||||
maybe_call(self.on_node_status, node, retval)
|
||||
retvals.append(retval)
|
||||
|
||||
self._stop_nodes(retry=2, on_down=restart_on_down, sig=sig)
|
||||
return retvals
|
||||
|
||||
def stop(self, retry=None, callback=None, sig=signal.SIGTERM):
|
||||
return self._stop_nodes(retry=retry, on_down=callback, sig=sig)
|
||||
|
||||
def stopwait(self, retry=2, callback=None, sig=signal.SIGTERM):
|
||||
return self._stop_nodes(retry=retry, on_down=callback, sig=sig)
|
||||
|
||||
def _stop_nodes(self, retry=None, on_down=None, sig=signal.SIGTERM):
|
||||
on_down = on_down if on_down is not None else self.on_node_down
|
||||
nodes = list(self.getpids(on_down=on_down))
|
||||
if nodes:
|
||||
for node in self.shutdown_nodes(nodes, sig=sig, retry=retry):
|
||||
maybe_call(on_down, node)
|
||||
|
||||
def shutdown_nodes(self, nodes, sig=signal.SIGTERM, retry=None):
|
||||
P = set(nodes)
|
||||
maybe_call(self.on_stopping_preamble, nodes)
|
||||
to_remove = set()
|
||||
for node in P:
|
||||
maybe_call(self.on_send_signal, node, signal_name(sig))
|
||||
if not node.send(sig, self.on_node_signal_dead):
|
||||
to_remove.add(node)
|
||||
yield node
|
||||
P -= to_remove
|
||||
if retry:
|
||||
maybe_call(self.on_still_waiting_for, P)
|
||||
its = 0
|
||||
while P:
|
||||
to_remove = set()
|
||||
for node in P:
|
||||
its += 1
|
||||
maybe_call(self.on_still_waiting_progress, P)
|
||||
if not node.alive():
|
||||
maybe_call(self.on_node_shutdown_ok, node)
|
||||
to_remove.add(node)
|
||||
yield node
|
||||
maybe_call(self.on_still_waiting_for, P)
|
||||
break
|
||||
P -= to_remove
|
||||
if P and not its % len(P):
|
||||
sleep(float(retry))
|
||||
maybe_call(self.on_still_waiting_end)
|
||||
|
||||
def find(self, name):
|
||||
for node in self:
|
||||
if node.name == name:
|
||||
return node
|
||||
raise KeyError(name)
|
||||
|
||||
def getpids(self, on_down=None):
|
||||
for node in self:
|
||||
if node.pid:
|
||||
yield node
|
||||
else:
|
||||
maybe_call(on_down, node)
|
||||
|
||||
def __repr__(self):
|
||||
return '<{name}({0}): {1}>'.format(
|
||||
len(self), saferepr([n.name for n in self]),
|
||||
name=type(self).__name__,
|
||||
)
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
return self.nodes
|
||||
@@ -0,0 +1,391 @@
|
||||
"""Worker command-line program.
|
||||
|
||||
This module is the 'program-version' of :mod:`celery.worker`.
|
||||
|
||||
It does everything necessary to run that module
|
||||
as an actual application, like installing signal handlers,
|
||||
platform tweaks, and so on.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import platform as _platform
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from functools import partial
|
||||
|
||||
from billiard.common import REMAP_SIGTERM
|
||||
from billiard.process import current_process
|
||||
from kombu.utils.encoding import safe_str
|
||||
|
||||
from celery import VERSION_BANNER, platforms, signals
|
||||
from celery.app import trace
|
||||
from celery.exceptions import WorkerShutdown, WorkerTerminate
|
||||
from celery.loaders.app import AppLoader
|
||||
from celery.platforms import EX_FAILURE, EX_OK, check_privileges, isatty
|
||||
from celery.utils import static, term
|
||||
from celery.utils.debug import cry
|
||||
from celery.utils.imports import qualname
|
||||
from celery.utils.log import get_logger, in_sighandler, set_in_sighandler
|
||||
from celery.utils.text import pluralize
|
||||
from celery.worker import WorkController
|
||||
|
||||
__all__ = ('Worker',)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
is_jython = sys.platform.startswith('java')
|
||||
is_pypy = hasattr(sys, 'pypy_version_info')
|
||||
|
||||
ARTLINES = [
|
||||
' --------------',
|
||||
'--- ***** -----',
|
||||
'-- ******* ----',
|
||||
'- *** --- * ---',
|
||||
'- ** ----------',
|
||||
'- ** ----------',
|
||||
'- ** ----------',
|
||||
'- ** ----------',
|
||||
'- *** --- * ---',
|
||||
'-- ******* ----',
|
||||
'--- ***** -----',
|
||||
' --------------',
|
||||
]
|
||||
|
||||
BANNER = """\
|
||||
{hostname} v{version}
|
||||
|
||||
{platform} {timestamp}
|
||||
|
||||
[config]
|
||||
.> app: {app}
|
||||
.> transport: {conninfo}
|
||||
.> results: {results}
|
||||
.> concurrency: {concurrency}
|
||||
.> task events: {events}
|
||||
|
||||
[queues]
|
||||
{queues}
|
||||
"""
|
||||
|
||||
EXTRA_INFO_FMT = """
|
||||
[tasks]
|
||||
{tasks}
|
||||
"""
|
||||
|
||||
|
||||
def active_thread_count():
|
||||
from threading import enumerate
|
||||
return sum(1 for t in enumerate()
|
||||
if not t.name.startswith('Dummy-'))
|
||||
|
||||
|
||||
def safe_say(msg):
|
||||
print(f'\n{msg}', file=sys.__stderr__, flush=True)
|
||||
|
||||
|
||||
class Worker(WorkController):
|
||||
"""Worker as a program."""
|
||||
|
||||
def on_before_init(self, quiet=False, **kwargs):
|
||||
self.quiet = quiet
|
||||
trace.setup_worker_optimizations(self.app, self.hostname)
|
||||
|
||||
# this signal can be used to set up configuration for
|
||||
# workers by name.
|
||||
signals.celeryd_init.send(
|
||||
sender=self.hostname, instance=self,
|
||||
conf=self.app.conf, options=kwargs,
|
||||
)
|
||||
check_privileges(self.app.conf.accept_content)
|
||||
|
||||
def on_after_init(self, purge=False, no_color=None,
|
||||
redirect_stdouts=None, redirect_stdouts_level=None,
|
||||
**kwargs):
|
||||
self.redirect_stdouts = self.app.either(
|
||||
'worker_redirect_stdouts', redirect_stdouts)
|
||||
self.redirect_stdouts_level = self.app.either(
|
||||
'worker_redirect_stdouts_level', redirect_stdouts_level)
|
||||
super().setup_defaults(**kwargs)
|
||||
self.purge = purge
|
||||
self.no_color = no_color
|
||||
self._isatty = isatty(sys.stdout)
|
||||
self.colored = self.app.log.colored(
|
||||
self.logfile,
|
||||
enabled=not no_color if no_color is not None else no_color
|
||||
)
|
||||
|
||||
def on_init_blueprint(self):
|
||||
self._custom_logging = self.setup_logging()
|
||||
# apply task execution optimizations
|
||||
# -- This will finalize the app!
|
||||
trace.setup_worker_optimizations(self.app, self.hostname)
|
||||
|
||||
def on_start(self):
|
||||
app = self.app
|
||||
super().on_start()
|
||||
|
||||
# this signal can be used to, for example, change queues after
|
||||
# the -Q option has been applied.
|
||||
signals.celeryd_after_setup.send(
|
||||
sender=self.hostname, instance=self, conf=app.conf,
|
||||
)
|
||||
|
||||
if self.purge:
|
||||
self.purge_messages()
|
||||
|
||||
if not self.quiet:
|
||||
self.emit_banner()
|
||||
|
||||
self.set_process_status('-active-')
|
||||
self.install_platform_tweaks(self)
|
||||
if not self._custom_logging and self.redirect_stdouts:
|
||||
app.log.redirect_stdouts(self.redirect_stdouts_level)
|
||||
|
||||
# TODO: Remove the following code in Celery 6.0
|
||||
# This qualifies as a hack for issue #6366.
|
||||
warn_deprecated = True
|
||||
config_source = app._config_source
|
||||
if isinstance(config_source, str):
|
||||
# Don't raise the warning when the settings originate from
|
||||
# django.conf:settings
|
||||
warn_deprecated = config_source.lower() not in [
|
||||
'django.conf:settings',
|
||||
]
|
||||
|
||||
if warn_deprecated:
|
||||
if app.conf.maybe_warn_deprecated_settings():
|
||||
logger.warning(
|
||||
"Please run `celery upgrade settings path/to/settings.py` "
|
||||
"to avoid these warnings and to allow a smoother upgrade "
|
||||
"to Celery 6.0."
|
||||
)
|
||||
|
||||
def emit_banner(self):
|
||||
# Dump configuration to screen so we have some basic information
|
||||
# for when users sends bug reports.
|
||||
use_image = term.supports_images()
|
||||
if use_image:
|
||||
print(term.imgcat(static.logo()))
|
||||
print(safe_str(''.join([
|
||||
str(self.colored.cyan(
|
||||
' \n', self.startup_info(artlines=not use_image))),
|
||||
str(self.colored.reset(self.extra_info() or '')),
|
||||
])), file=sys.__stdout__, flush=True)
|
||||
|
||||
def on_consumer_ready(self, consumer):
|
||||
signals.worker_ready.send(sender=consumer)
|
||||
logger.info('%s ready.', safe_str(self.hostname))
|
||||
|
||||
def setup_logging(self, colorize=None):
|
||||
if colorize is None and self.no_color is not None:
|
||||
colorize = not self.no_color
|
||||
return self.app.log.setup(
|
||||
self.loglevel, self.logfile,
|
||||
redirect_stdouts=False, colorize=colorize, hostname=self.hostname,
|
||||
)
|
||||
|
||||
def purge_messages(self):
|
||||
with self.app.connection_for_write() as connection:
|
||||
count = self.app.control.purge(connection=connection)
|
||||
if count: # pragma: no cover
|
||||
print(f"purge: Erased {count} {pluralize(count, 'message')} from the queue.\n", flush=True)
|
||||
|
||||
def tasklist(self, include_builtins=True, sep='\n', int_='celery.'):
|
||||
return sep.join(
|
||||
f' . {task}' for task in sorted(self.app.tasks)
|
||||
if (not task.startswith(int_) if not include_builtins else task)
|
||||
)
|
||||
|
||||
def extra_info(self):
|
||||
if self.loglevel is None:
|
||||
return
|
||||
if self.loglevel <= logging.INFO:
|
||||
include_builtins = self.loglevel <= logging.DEBUG
|
||||
tasklist = self.tasklist(include_builtins=include_builtins)
|
||||
return EXTRA_INFO_FMT.format(tasks=tasklist)
|
||||
|
||||
def startup_info(self, artlines=True):
|
||||
app = self.app
|
||||
concurrency = str(self.concurrency)
|
||||
appr = '{}:{:#x}'.format(app.main or '__main__', id(app))
|
||||
if not isinstance(app.loader, AppLoader):
|
||||
loader = qualname(app.loader)
|
||||
if loader.startswith('celery.loaders'): # pragma: no cover
|
||||
loader = loader[14:]
|
||||
appr += f' ({loader})'
|
||||
if self.autoscale:
|
||||
max, min = self.autoscale
|
||||
concurrency = f'{{min={min}, max={max}}}'
|
||||
pool = self.pool_cls
|
||||
if not isinstance(pool, str):
|
||||
pool = pool.__module__
|
||||
concurrency += f" ({pool.split('.')[-1]})"
|
||||
events = 'ON'
|
||||
if not self.task_events:
|
||||
events = 'OFF (enable -E to monitor tasks in this worker)'
|
||||
|
||||
banner = BANNER.format(
|
||||
app=appr,
|
||||
hostname=safe_str(self.hostname),
|
||||
timestamp=datetime.now().replace(microsecond=0),
|
||||
version=VERSION_BANNER,
|
||||
conninfo=self.app.connection().as_uri(),
|
||||
results=self.app.backend.as_uri(),
|
||||
concurrency=concurrency,
|
||||
platform=safe_str(_platform.platform()),
|
||||
events=events,
|
||||
queues=app.amqp.queues.format(indent=0, indent_first=False),
|
||||
).splitlines()
|
||||
|
||||
# integrate the ASCII art.
|
||||
if artlines:
|
||||
for i, _ in enumerate(banner):
|
||||
try:
|
||||
banner[i] = ' '.join([ARTLINES[i], banner[i]])
|
||||
except IndexError:
|
||||
banner[i] = ' ' * 16 + banner[i]
|
||||
return '\n'.join(banner) + '\n'
|
||||
|
||||
def install_platform_tweaks(self, worker):
|
||||
"""Install platform specific tweaks and workarounds."""
|
||||
if self.app.IS_macOS:
|
||||
self.macOS_proxy_detection_workaround()
|
||||
|
||||
# Install signal handler so SIGHUP restarts the worker.
|
||||
if not self._isatty:
|
||||
# only install HUP handler if detached from terminal,
|
||||
# so closing the terminal window doesn't restart the worker
|
||||
# into the background.
|
||||
if self.app.IS_macOS:
|
||||
# macOS can't exec from a process using threads.
|
||||
# See https://github.com/celery/celery/issues#issue/152
|
||||
install_HUP_not_supported_handler(worker)
|
||||
else:
|
||||
install_worker_restart_handler(worker)
|
||||
install_worker_term_handler(worker)
|
||||
install_worker_term_hard_handler(worker)
|
||||
install_worker_int_handler(worker)
|
||||
install_cry_handler()
|
||||
install_rdb_handler()
|
||||
|
||||
def macOS_proxy_detection_workaround(self):
|
||||
"""See https://github.com/celery/celery/issues#issue/161."""
|
||||
os.environ.setdefault('celery_dummy_proxy', 'set_by_celeryd')
|
||||
|
||||
def set_process_status(self, info):
|
||||
return platforms.set_mp_process_title(
|
||||
'celeryd',
|
||||
info=f'{info} ({platforms.strargv(sys.argv)})',
|
||||
hostname=self.hostname,
|
||||
)
|
||||
|
||||
|
||||
def _shutdown_handler(worker, sig='TERM', how='Warm',
|
||||
exc=WorkerShutdown, callback=None, exitcode=EX_OK):
|
||||
def _handle_request(*args):
|
||||
with in_sighandler():
|
||||
from celery.worker import state
|
||||
if current_process()._name == 'MainProcess':
|
||||
if callback:
|
||||
callback(worker)
|
||||
safe_say(f'worker: {how} shutdown (MainProcess)')
|
||||
signals.worker_shutting_down.send(
|
||||
sender=worker.hostname, sig=sig, how=how,
|
||||
exitcode=exitcode,
|
||||
)
|
||||
if active_thread_count() > 1:
|
||||
setattr(state, {'Warm': 'should_stop',
|
||||
'Cold': 'should_terminate'}[how], exitcode)
|
||||
else:
|
||||
raise exc(exitcode)
|
||||
_handle_request.__name__ = str(f'worker_{how}')
|
||||
platforms.signals[sig] = _handle_request
|
||||
|
||||
|
||||
if REMAP_SIGTERM == "SIGQUIT":
|
||||
install_worker_term_handler = partial(
|
||||
_shutdown_handler, sig='SIGTERM', how='Cold', exc=WorkerTerminate, exitcode=EX_FAILURE,
|
||||
)
|
||||
else:
|
||||
install_worker_term_handler = partial(
|
||||
_shutdown_handler, sig='SIGTERM', how='Warm', exc=WorkerShutdown,
|
||||
)
|
||||
|
||||
if not is_jython: # pragma: no cover
|
||||
install_worker_term_hard_handler = partial(
|
||||
_shutdown_handler, sig='SIGQUIT', how='Cold', exc=WorkerTerminate,
|
||||
exitcode=EX_FAILURE,
|
||||
)
|
||||
else: # pragma: no cover
|
||||
install_worker_term_handler = \
|
||||
install_worker_term_hard_handler = lambda *a, **kw: None
|
||||
|
||||
|
||||
def on_SIGINT(worker):
|
||||
safe_say('worker: Hitting Ctrl+C again will terminate all running tasks!')
|
||||
install_worker_term_hard_handler(worker, sig='SIGINT')
|
||||
|
||||
|
||||
if not is_jython: # pragma: no cover
|
||||
install_worker_int_handler = partial(
|
||||
_shutdown_handler, sig='SIGINT', callback=on_SIGINT,
|
||||
exitcode=EX_FAILURE,
|
||||
)
|
||||
else: # pragma: no cover
|
||||
def install_worker_int_handler(*args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
def _reload_current_worker():
|
||||
platforms.close_open_fds([
|
||||
sys.__stdin__, sys.__stdout__, sys.__stderr__,
|
||||
])
|
||||
os.execv(sys.executable, [sys.executable] + sys.argv)
|
||||
|
||||
|
||||
def install_worker_restart_handler(worker, sig='SIGHUP'):
|
||||
|
||||
def restart_worker_sig_handler(*args):
|
||||
"""Signal handler restarting the current python program."""
|
||||
set_in_sighandler(True)
|
||||
safe_say(f"Restarting celery worker ({' '.join(sys.argv)})")
|
||||
import atexit
|
||||
atexit.register(_reload_current_worker)
|
||||
from celery.worker import state
|
||||
state.should_stop = EX_OK
|
||||
platforms.signals[sig] = restart_worker_sig_handler
|
||||
|
||||
|
||||
def install_cry_handler(sig='SIGUSR1'):
|
||||
# PyPy does not have sys._current_frames
|
||||
if is_pypy: # pragma: no cover
|
||||
return
|
||||
|
||||
def cry_handler(*args):
|
||||
"""Signal handler logging the stack-trace of all active threads."""
|
||||
with in_sighandler():
|
||||
safe_say(cry())
|
||||
platforms.signals[sig] = cry_handler
|
||||
|
||||
|
||||
def install_rdb_handler(envvar='CELERY_RDBSIG',
|
||||
sig='SIGUSR2'): # pragma: no cover
|
||||
|
||||
def rdb_handler(*args):
|
||||
"""Signal handler setting a rdb breakpoint at the current frame."""
|
||||
with in_sighandler():
|
||||
from celery.contrib.rdb import _frame, set_trace
|
||||
|
||||
# gevent does not pass standard signal handler args
|
||||
frame = args[1] if args else _frame().f_back
|
||||
set_trace(frame)
|
||||
if os.environ.get(envvar):
|
||||
platforms.signals[sig] = rdb_handler
|
||||
|
||||
|
||||
def install_HUP_not_supported_handler(worker, sig='SIGHUP'):
|
||||
|
||||
def warn_on_HUP_handler(signum, frame):
|
||||
with in_sighandler():
|
||||
safe_say('{sig} not supported: Restarting with {sig} is '
|
||||
'unstable on this platform!'.format(sig=sig))
|
||||
platforms.signals[sig] = warn_on_HUP_handler
|
||||
@@ -0,0 +1 @@
|
||||
"""Result Backends."""
|
||||
@@ -0,0 +1,232 @@
|
||||
"""ArangoDb result store backend."""
|
||||
|
||||
# pylint: disable=W1202,W0703
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
from kombu.utils.objects import cached_property
|
||||
from kombu.utils.url import _parse_url
|
||||
|
||||
from celery.exceptions import ImproperlyConfigured
|
||||
|
||||
from .base import KeyValueStoreBackend
|
||||
|
||||
try:
|
||||
from pyArango import connection as py_arango_connection
|
||||
from pyArango.theExceptions import AQLQueryError
|
||||
except ImportError:
|
||||
py_arango_connection = AQLQueryError = None
|
||||
|
||||
__all__ = ('ArangoDbBackend',)
|
||||
|
||||
|
||||
class ArangoDbBackend(KeyValueStoreBackend):
|
||||
"""ArangoDb backend.
|
||||
|
||||
Sample url
|
||||
"arangodb://username:password@host:port/database/collection"
|
||||
*arangodb_backend_settings* is where the settings are present
|
||||
(in the app.conf)
|
||||
Settings should contain the host, port, username, password, database name,
|
||||
collection name else the default will be chosen.
|
||||
Default database name and collection name is celery.
|
||||
|
||||
Raises
|
||||
------
|
||||
celery.exceptions.ImproperlyConfigured:
|
||||
if module :pypi:`pyArango` is not available.
|
||||
|
||||
"""
|
||||
|
||||
host = '127.0.0.1'
|
||||
port = '8529'
|
||||
database = 'celery'
|
||||
collection = 'celery'
|
||||
username = None
|
||||
password = None
|
||||
# protocol is not supported in backend url (http is taken as default)
|
||||
http_protocol = 'http'
|
||||
verify = False
|
||||
|
||||
# Use str as arangodb key not bytes
|
||||
key_t = str
|
||||
|
||||
def __init__(self, url=None, *args, **kwargs):
|
||||
"""Parse the url or load the settings from settings object."""
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if py_arango_connection is None:
|
||||
raise ImproperlyConfigured(
|
||||
'You need to install the pyArango library to use the '
|
||||
'ArangoDb backend.',
|
||||
)
|
||||
|
||||
self.url = url
|
||||
|
||||
if url is None:
|
||||
host = port = database = collection = username = password = None
|
||||
else:
|
||||
(
|
||||
_schema, host, port, username, password,
|
||||
database_collection, _query
|
||||
) = _parse_url(url)
|
||||
if database_collection is None:
|
||||
database = collection = None
|
||||
else:
|
||||
database, collection = database_collection.split('/')
|
||||
|
||||
config = self.app.conf.get('arangodb_backend_settings', None)
|
||||
if config is not None:
|
||||
if not isinstance(config, dict):
|
||||
raise ImproperlyConfigured(
|
||||
'ArangoDb backend settings should be grouped in a dict',
|
||||
)
|
||||
else:
|
||||
config = {}
|
||||
|
||||
self.host = host or config.get('host', self.host)
|
||||
self.port = int(port or config.get('port', self.port))
|
||||
self.http_protocol = config.get('http_protocol', self.http_protocol)
|
||||
self.verify = config.get('verify', self.verify)
|
||||
self.database = database or config.get('database', self.database)
|
||||
self.collection = \
|
||||
collection or config.get('collection', self.collection)
|
||||
self.username = username or config.get('username', self.username)
|
||||
self.password = password or config.get('password', self.password)
|
||||
self.arangodb_url = "{http_protocol}://{host}:{port}".format(
|
||||
http_protocol=self.http_protocol, host=self.host, port=self.port
|
||||
)
|
||||
self._connection = None
|
||||
|
||||
@property
|
||||
def connection(self):
|
||||
"""Connect to the arangodb server."""
|
||||
if self._connection is None:
|
||||
self._connection = py_arango_connection.Connection(
|
||||
arangoURL=self.arangodb_url, username=self.username,
|
||||
password=self.password, verify=self.verify
|
||||
)
|
||||
return self._connection
|
||||
|
||||
@property
|
||||
def db(self):
|
||||
"""Database Object to the given database."""
|
||||
return self.connection[self.database]
|
||||
|
||||
@cached_property
|
||||
def expires_delta(self):
|
||||
return timedelta(seconds=self.expires)
|
||||
|
||||
def get(self, key):
|
||||
try:
|
||||
logging.debug(
|
||||
'RETURN DOCUMENT("{collection}/{key}").task'.format(
|
||||
collection=self.collection, key=key
|
||||
)
|
||||
)
|
||||
query = self.db.AQLQuery(
|
||||
'RETURN DOCUMENT("{collection}/{key}").task'.format(
|
||||
collection=self.collection, key=key
|
||||
)
|
||||
)
|
||||
result = query.response["result"][0]
|
||||
if result is None:
|
||||
return None
|
||||
return json.dumps(result)
|
||||
except AQLQueryError as aql_err:
|
||||
logging.error(aql_err)
|
||||
return None
|
||||
except Exception as err:
|
||||
logging.error(err)
|
||||
return None
|
||||
|
||||
def set(self, key, value):
|
||||
"""Insert a doc with value into task attribute and _key as key."""
|
||||
try:
|
||||
logging.debug(
|
||||
'INSERT {{ task: {task}, _key: "{key}" }} INTO {collection}'
|
||||
.format(
|
||||
collection=self.collection, key=key, task=value
|
||||
)
|
||||
)
|
||||
self.db.AQLQuery(
|
||||
'INSERT {{ task: {task}, _key: "{key}" }} INTO {collection}'
|
||||
.format(
|
||||
collection=self.collection, key=key, task=value
|
||||
)
|
||||
)
|
||||
except AQLQueryError as aql_err:
|
||||
logging.error(aql_err)
|
||||
except Exception as err:
|
||||
logging.error(err)
|
||||
|
||||
def mget(self, keys):
|
||||
try:
|
||||
json_keys = json.dumps(keys)
|
||||
logging.debug(
|
||||
"""
|
||||
FOR key in {keys}
|
||||
RETURN DOCUMENT(CONCAT("{collection}/", key).task
|
||||
""".format(
|
||||
collection=self.collection, keys=json_keys
|
||||
)
|
||||
)
|
||||
query = self.db.AQLQuery(
|
||||
"""
|
||||
FOR key in {keys}
|
||||
RETURN DOCUMENT(CONCAT("{collection}/", key).task
|
||||
""".format(
|
||||
collection=self.collection, keys=json_keys
|
||||
)
|
||||
)
|
||||
results = []
|
||||
while True:
|
||||
results.extend(query.response['result'])
|
||||
query.nextBatch()
|
||||
except StopIteration:
|
||||
values = [
|
||||
result if result is None else json.dumps(result)
|
||||
for result in results
|
||||
]
|
||||
return values
|
||||
except AQLQueryError as aql_err:
|
||||
logging.error(aql_err)
|
||||
return [None] * len(keys)
|
||||
except Exception as err:
|
||||
logging.error(err)
|
||||
return [None] * len(keys)
|
||||
|
||||
def delete(self, key):
|
||||
try:
|
||||
logging.debug(
|
||||
'REMOVE {{ _key: "{key}" }} IN {collection}'.format(
|
||||
key=key, collection=self.collection
|
||||
)
|
||||
)
|
||||
self.db.AQLQuery(
|
||||
'REMOVE {{ _key: "{key}" }} IN {collection}'.format(
|
||||
key=key, collection=self.collection
|
||||
)
|
||||
)
|
||||
except AQLQueryError as aql_err:
|
||||
logging.error(aql_err)
|
||||
except Exception as err:
|
||||
logging.error(err)
|
||||
|
||||
def cleanup(self):
|
||||
"""Delete expired meta-data."""
|
||||
remove_before = (self.app.now() - self.expires_delta).isoformat()
|
||||
try:
|
||||
query = (
|
||||
'FOR item IN {collection} '
|
||||
'FILTER item.task.date_done < "{remove_before}" '
|
||||
'REMOVE item IN {collection}'
|
||||
).format(collection=self.collection, remove_before=remove_before)
|
||||
logging.debug(query)
|
||||
self.db.AQLQuery(query)
|
||||
except AQLQueryError as aql_err:
|
||||
logging.error(aql_err)
|
||||
except Exception as err:
|
||||
logging.error(err)
|
||||
@@ -0,0 +1,333 @@
|
||||
"""Async I/O backend support utilities."""
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from queue import Empty
|
||||
from time import sleep
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
from kombu.utils.compat import detect_environment
|
||||
|
||||
from celery import states
|
||||
from celery.exceptions import TimeoutError
|
||||
from celery.utils.threads import THREAD_TIMEOUT_MAX
|
||||
|
||||
__all__ = (
|
||||
'AsyncBackendMixin', 'BaseResultConsumer', 'Drainer',
|
||||
'register_drainer',
|
||||
)
|
||||
|
||||
drainers = {}
|
||||
|
||||
|
||||
def register_drainer(name):
|
||||
"""Decorator used to register a new result drainer type."""
|
||||
def _inner(cls):
|
||||
drainers[name] = cls
|
||||
return cls
|
||||
return _inner
|
||||
|
||||
|
||||
@register_drainer('default')
|
||||
class Drainer:
|
||||
"""Result draining service."""
|
||||
|
||||
def __init__(self, result_consumer):
|
||||
self.result_consumer = result_consumer
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
def stop(self):
|
||||
pass
|
||||
|
||||
def drain_events_until(self, p, timeout=None, interval=1, on_interval=None, wait=None):
|
||||
wait = wait or self.result_consumer.drain_events
|
||||
time_start = time.monotonic()
|
||||
|
||||
while 1:
|
||||
# Total time spent may exceed a single call to wait()
|
||||
if timeout and time.monotonic() - time_start >= timeout:
|
||||
raise socket.timeout()
|
||||
try:
|
||||
yield self.wait_for(p, wait, timeout=interval)
|
||||
except socket.timeout:
|
||||
pass
|
||||
if on_interval:
|
||||
on_interval()
|
||||
if p.ready: # got event on the wanted channel.
|
||||
break
|
||||
|
||||
def wait_for(self, p, wait, timeout=None):
|
||||
wait(timeout=timeout)
|
||||
|
||||
|
||||
class greenletDrainer(Drainer):
|
||||
spawn = None
|
||||
_g = None
|
||||
_drain_complete_event = None # event, sended (and recreated) after every drain_events iteration
|
||||
|
||||
def _create_drain_complete_event(self):
|
||||
"""create new self._drain_complete_event object"""
|
||||
pass
|
||||
|
||||
def _send_drain_complete_event(self):
|
||||
"""raise self._drain_complete_event for wakeup .wait_for"""
|
||||
pass
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._started = threading.Event()
|
||||
self._stopped = threading.Event()
|
||||
self._shutdown = threading.Event()
|
||||
self._create_drain_complete_event()
|
||||
|
||||
def run(self):
|
||||
self._started.set()
|
||||
while not self._stopped.is_set():
|
||||
try:
|
||||
self.result_consumer.drain_events(timeout=1)
|
||||
self._send_drain_complete_event()
|
||||
self._create_drain_complete_event()
|
||||
except socket.timeout:
|
||||
pass
|
||||
self._shutdown.set()
|
||||
|
||||
def start(self):
|
||||
if not self._started.is_set():
|
||||
self._g = self.spawn(self.run)
|
||||
self._started.wait()
|
||||
|
||||
def stop(self):
|
||||
self._stopped.set()
|
||||
self._send_drain_complete_event()
|
||||
self._shutdown.wait(THREAD_TIMEOUT_MAX)
|
||||
|
||||
def wait_for(self, p, wait, timeout=None):
|
||||
self.start()
|
||||
if not p.ready:
|
||||
self._drain_complete_event.wait(timeout=timeout)
|
||||
|
||||
|
||||
@register_drainer('eventlet')
|
||||
class eventletDrainer(greenletDrainer):
|
||||
|
||||
def spawn(self, func):
|
||||
from eventlet import sleep, spawn
|
||||
g = spawn(func)
|
||||
sleep(0)
|
||||
return g
|
||||
|
||||
def _create_drain_complete_event(self):
|
||||
from eventlet.event import Event
|
||||
self._drain_complete_event = Event()
|
||||
|
||||
def _send_drain_complete_event(self):
|
||||
self._drain_complete_event.send()
|
||||
|
||||
|
||||
@register_drainer('gevent')
|
||||
class geventDrainer(greenletDrainer):
|
||||
|
||||
def spawn(self, func):
|
||||
import gevent
|
||||
g = gevent.spawn(func)
|
||||
gevent.sleep(0)
|
||||
return g
|
||||
|
||||
def _create_drain_complete_event(self):
|
||||
from gevent.event import Event
|
||||
self._drain_complete_event = Event()
|
||||
|
||||
def _send_drain_complete_event(self):
|
||||
self._drain_complete_event.set()
|
||||
self._create_drain_complete_event()
|
||||
|
||||
|
||||
class AsyncBackendMixin:
|
||||
"""Mixin for backends that enables the async API."""
|
||||
|
||||
def _collect_into(self, result, bucket):
|
||||
self.result_consumer.buckets[result] = bucket
|
||||
|
||||
def iter_native(self, result, no_ack=True, **kwargs):
|
||||
self._ensure_not_eager()
|
||||
|
||||
results = result.results
|
||||
if not results:
|
||||
raise StopIteration()
|
||||
|
||||
# we tell the result consumer to put consumed results
|
||||
# into these buckets.
|
||||
bucket = deque()
|
||||
for node in results:
|
||||
if not hasattr(node, '_cache'):
|
||||
bucket.append(node)
|
||||
elif node._cache:
|
||||
bucket.append(node)
|
||||
else:
|
||||
self._collect_into(node, bucket)
|
||||
|
||||
for _ in self._wait_for_pending(result, no_ack=no_ack, **kwargs):
|
||||
while bucket:
|
||||
node = bucket.popleft()
|
||||
if not hasattr(node, '_cache'):
|
||||
yield node.id, node.children
|
||||
else:
|
||||
yield node.id, node._cache
|
||||
while bucket:
|
||||
node = bucket.popleft()
|
||||
yield node.id, node._cache
|
||||
|
||||
def add_pending_result(self, result, weak=False, start_drainer=True):
|
||||
if start_drainer:
|
||||
self.result_consumer.drainer.start()
|
||||
try:
|
||||
self._maybe_resolve_from_buffer(result)
|
||||
except Empty:
|
||||
self._add_pending_result(result.id, result, weak=weak)
|
||||
return result
|
||||
|
||||
def _maybe_resolve_from_buffer(self, result):
|
||||
result._maybe_set_cache(self._pending_messages.take(result.id))
|
||||
|
||||
def _add_pending_result(self, task_id, result, weak=False):
|
||||
concrete, weak_ = self._pending_results
|
||||
if task_id not in weak_ and result.id not in concrete:
|
||||
(weak_ if weak else concrete)[task_id] = result
|
||||
self.result_consumer.consume_from(task_id)
|
||||
|
||||
def add_pending_results(self, results, weak=False):
|
||||
self.result_consumer.drainer.start()
|
||||
return [self.add_pending_result(result, weak=weak, start_drainer=False)
|
||||
for result in results]
|
||||
|
||||
def remove_pending_result(self, result):
|
||||
self._remove_pending_result(result.id)
|
||||
self.on_result_fulfilled(result)
|
||||
return result
|
||||
|
||||
def _remove_pending_result(self, task_id):
|
||||
for mapping in self._pending_results:
|
||||
mapping.pop(task_id, None)
|
||||
|
||||
def on_result_fulfilled(self, result):
|
||||
self.result_consumer.cancel_for(result.id)
|
||||
|
||||
def wait_for_pending(self, result,
|
||||
callback=None, propagate=True, **kwargs):
|
||||
self._ensure_not_eager()
|
||||
for _ in self._wait_for_pending(result, **kwargs):
|
||||
pass
|
||||
return result.maybe_throw(callback=callback, propagate=propagate)
|
||||
|
||||
def _wait_for_pending(self, result,
|
||||
timeout=None, on_interval=None, on_message=None,
|
||||
**kwargs):
|
||||
return self.result_consumer._wait_for_pending(
|
||||
result, timeout=timeout,
|
||||
on_interval=on_interval, on_message=on_message,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
@property
|
||||
def is_async(self):
|
||||
return True
|
||||
|
||||
|
||||
class BaseResultConsumer:
|
||||
"""Manager responsible for consuming result messages."""
|
||||
|
||||
def __init__(self, backend, app, accept,
|
||||
pending_results, pending_messages):
|
||||
self.backend = backend
|
||||
self.app = app
|
||||
self.accept = accept
|
||||
self._pending_results = pending_results
|
||||
self._pending_messages = pending_messages
|
||||
self.on_message = None
|
||||
self.buckets = WeakKeyDictionary()
|
||||
self.drainer = drainers[detect_environment()](self)
|
||||
|
||||
def start(self, initial_task_id, **kwargs):
|
||||
raise NotImplementedError()
|
||||
|
||||
def stop(self):
|
||||
pass
|
||||
|
||||
def drain_events(self, timeout=None):
|
||||
raise NotImplementedError()
|
||||
|
||||
def consume_from(self, task_id):
|
||||
raise NotImplementedError()
|
||||
|
||||
def cancel_for(self, task_id):
|
||||
raise NotImplementedError()
|
||||
|
||||
def _after_fork(self):
|
||||
self.buckets.clear()
|
||||
self.buckets = WeakKeyDictionary()
|
||||
self.on_message = None
|
||||
self.on_after_fork()
|
||||
|
||||
def on_after_fork(self):
|
||||
pass
|
||||
|
||||
def drain_events_until(self, p, timeout=None, on_interval=None):
|
||||
return self.drainer.drain_events_until(
|
||||
p, timeout=timeout, on_interval=on_interval)
|
||||
|
||||
def _wait_for_pending(self, result,
|
||||
timeout=None, on_interval=None, on_message=None,
|
||||
**kwargs):
|
||||
self.on_wait_for_pending(result, timeout=timeout, **kwargs)
|
||||
prev_on_m, self.on_message = self.on_message, on_message
|
||||
try:
|
||||
for _ in self.drain_events_until(
|
||||
result.on_ready, timeout=timeout,
|
||||
on_interval=on_interval):
|
||||
yield
|
||||
sleep(0)
|
||||
except socket.timeout:
|
||||
raise TimeoutError('The operation timed out.')
|
||||
finally:
|
||||
self.on_message = prev_on_m
|
||||
|
||||
def on_wait_for_pending(self, result, timeout=None, **kwargs):
|
||||
pass
|
||||
|
||||
def on_out_of_band_result(self, message):
|
||||
self.on_state_change(message.payload, message)
|
||||
|
||||
def _get_pending_result(self, task_id):
|
||||
for mapping in self._pending_results:
|
||||
try:
|
||||
return mapping[task_id]
|
||||
except KeyError:
|
||||
pass
|
||||
raise KeyError(task_id)
|
||||
|
||||
def on_state_change(self, meta, message):
|
||||
if self.on_message:
|
||||
self.on_message(meta)
|
||||
if meta['status'] in states.READY_STATES:
|
||||
task_id = meta['task_id']
|
||||
try:
|
||||
result = self._get_pending_result(task_id)
|
||||
except KeyError:
|
||||
# send to buffer in case we received this result
|
||||
# before it was added to _pending_results.
|
||||
self._pending_messages.put(task_id, meta)
|
||||
else:
|
||||
result._maybe_set_cache(meta)
|
||||
buckets = self.buckets
|
||||
try:
|
||||
# remove bucket for this result, since it's fulfilled
|
||||
bucket = buckets.pop(result)
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
# send to waiter via bucket
|
||||
bucket.append(result)
|
||||
sleep(0)
|
||||
@@ -0,0 +1,166 @@
|
||||
"""The Azure Storage Block Blob backend for Celery."""
|
||||
from kombu.utils import cached_property
|
||||
from kombu.utils.encoding import bytes_to_str
|
||||
|
||||
from celery.exceptions import ImproperlyConfigured
|
||||
from celery.utils.log import get_logger
|
||||
|
||||
from .base import KeyValueStoreBackend
|
||||
|
||||
try:
|
||||
import azure.storage.blob as azurestorage
|
||||
from azure.core.exceptions import (ResourceExistsError,
|
||||
ResourceNotFoundError)
|
||||
from azure.storage.blob import BlobServiceClient
|
||||
except ImportError:
|
||||
azurestorage = None
|
||||
|
||||
__all__ = ("AzureBlockBlobBackend",)
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
AZURE_BLOCK_BLOB_CONNECTION_PREFIX = 'azureblockblob://'
|
||||
|
||||
|
||||
class AzureBlockBlobBackend(KeyValueStoreBackend):
|
||||
"""Azure Storage Block Blob backend for Celery."""
|
||||
|
||||
def __init__(self,
|
||||
url=None,
|
||||
container_name=None,
|
||||
*args,
|
||||
**kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if azurestorage is None or azurestorage.__version__ < '12':
|
||||
raise ImproperlyConfigured(
|
||||
"You need to install the azure-storage-blob v12 library to"
|
||||
"use the AzureBlockBlob backend")
|
||||
|
||||
conf = self.app.conf
|
||||
|
||||
self._connection_string = self._parse_url(url)
|
||||
|
||||
self._container_name = (
|
||||
container_name or
|
||||
conf["azureblockblob_container_name"])
|
||||
|
||||
self.base_path = conf.get('azureblockblob_base_path', '')
|
||||
self._connection_timeout = conf.get(
|
||||
'azureblockblob_connection_timeout', 20
|
||||
)
|
||||
self._read_timeout = conf.get('azureblockblob_read_timeout', 120)
|
||||
|
||||
@classmethod
|
||||
def _parse_url(cls, url, prefix=AZURE_BLOCK_BLOB_CONNECTION_PREFIX):
|
||||
connection_string = url[len(prefix):]
|
||||
if not connection_string:
|
||||
raise ImproperlyConfigured("Invalid URL")
|
||||
|
||||
return connection_string
|
||||
|
||||
@cached_property
|
||||
def _blob_service_client(self):
|
||||
"""Return the Azure Storage Blob service client.
|
||||
|
||||
If this is the first call to the property, the client is created and
|
||||
the container is created if it doesn't yet exist.
|
||||
|
||||
"""
|
||||
client = BlobServiceClient.from_connection_string(
|
||||
self._connection_string,
|
||||
connection_timeout=self._connection_timeout,
|
||||
read_timeout=self._read_timeout
|
||||
)
|
||||
|
||||
try:
|
||||
client.create_container(name=self._container_name)
|
||||
msg = f"Container created with name {self._container_name}."
|
||||
except ResourceExistsError:
|
||||
msg = f"Container with name {self._container_name} already." \
|
||||
"exists. This will not be created."
|
||||
LOGGER.info(msg)
|
||||
|
||||
return client
|
||||
|
||||
def get(self, key):
|
||||
"""Read the value stored at the given key.
|
||||
|
||||
Args:
|
||||
key: The key for which to read the value.
|
||||
"""
|
||||
key = bytes_to_str(key)
|
||||
LOGGER.debug("Getting Azure Block Blob %s/%s", self._container_name, key)
|
||||
|
||||
blob_client = self._blob_service_client.get_blob_client(
|
||||
container=self._container_name,
|
||||
blob=f'{self.base_path}{key}',
|
||||
)
|
||||
|
||||
try:
|
||||
return blob_client.download_blob().readall().decode()
|
||||
except ResourceNotFoundError:
|
||||
return None
|
||||
|
||||
def set(self, key, value):
|
||||
"""Store a value for a given key.
|
||||
|
||||
Args:
|
||||
key: The key at which to store the value.
|
||||
value: The value to store.
|
||||
|
||||
"""
|
||||
key = bytes_to_str(key)
|
||||
LOGGER.debug(f"Creating azure blob at {self._container_name}/{key}")
|
||||
|
||||
blob_client = self._blob_service_client.get_blob_client(
|
||||
container=self._container_name,
|
||||
blob=f'{self.base_path}{key}',
|
||||
)
|
||||
|
||||
blob_client.upload_blob(value, overwrite=True)
|
||||
|
||||
def mget(self, keys):
|
||||
"""Read all the values for the provided keys.
|
||||
|
||||
Args:
|
||||
keys: The list of keys to read.
|
||||
|
||||
"""
|
||||
return [self.get(key) for key in keys]
|
||||
|
||||
def delete(self, key):
|
||||
"""Delete the value at a given key.
|
||||
|
||||
Args:
|
||||
key: The key of the value to delete.
|
||||
|
||||
"""
|
||||
key = bytes_to_str(key)
|
||||
LOGGER.debug(f"Deleting azure blob at {self._container_name}/{key}")
|
||||
|
||||
blob_client = self._blob_service_client.get_blob_client(
|
||||
container=self._container_name,
|
||||
blob=f'{self.base_path}{key}',
|
||||
)
|
||||
|
||||
blob_client.delete_blob()
|
||||
|
||||
def as_uri(self, include_password=False):
|
||||
if include_password:
|
||||
return (
|
||||
f'{AZURE_BLOCK_BLOB_CONNECTION_PREFIX}'
|
||||
f'{self._connection_string}'
|
||||
)
|
||||
|
||||
connection_string_parts = self._connection_string.split(';')
|
||||
account_key_prefix = 'AccountKey='
|
||||
redacted_connection_string_parts = [
|
||||
f'{account_key_prefix}**' if part.startswith(account_key_prefix)
|
||||
else part
|
||||
for part in connection_string_parts
|
||||
]
|
||||
|
||||
return (
|
||||
f'{AZURE_BLOCK_BLOB_CONNECTION_PREFIX}'
|
||||
f'{";".join(redacted_connection_string_parts)}'
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,163 @@
|
||||
"""Memcached and in-memory cache result backend."""
|
||||
from kombu.utils.encoding import bytes_to_str, ensure_bytes
|
||||
from kombu.utils.objects import cached_property
|
||||
|
||||
from celery.exceptions import ImproperlyConfigured
|
||||
from celery.utils.functional import LRUCache
|
||||
|
||||
from .base import KeyValueStoreBackend
|
||||
|
||||
__all__ = ('CacheBackend',)
|
||||
|
||||
_imp = [None]
|
||||
|
||||
REQUIRES_BACKEND = """\
|
||||
The Memcached backend requires either pylibmc or python-memcached.\
|
||||
"""
|
||||
|
||||
UNKNOWN_BACKEND = """\
|
||||
The cache backend {0!r} is unknown,
|
||||
Please use one of the following backends instead: {1}\
|
||||
"""
|
||||
|
||||
# Global shared in-memory cache for in-memory cache client
|
||||
# This is to share cache between threads
|
||||
_DUMMY_CLIENT_CACHE = LRUCache(limit=5000)
|
||||
|
||||
|
||||
def import_best_memcache():
|
||||
if _imp[0] is None:
|
||||
is_pylibmc, memcache_key_t = False, bytes_to_str
|
||||
try:
|
||||
import pylibmc as memcache
|
||||
is_pylibmc = True
|
||||
except ImportError:
|
||||
try:
|
||||
import memcache
|
||||
except ImportError:
|
||||
raise ImproperlyConfigured(REQUIRES_BACKEND)
|
||||
_imp[0] = (is_pylibmc, memcache, memcache_key_t)
|
||||
return _imp[0]
|
||||
|
||||
|
||||
def get_best_memcache(*args, **kwargs):
|
||||
# pylint: disable=unpacking-non-sequence
|
||||
# This is most definitely a sequence, but pylint thinks it's not.
|
||||
is_pylibmc, memcache, key_t = import_best_memcache()
|
||||
Client = _Client = memcache.Client
|
||||
|
||||
if not is_pylibmc:
|
||||
def Client(*args, **kwargs):
|
||||
kwargs.pop('behaviors', None)
|
||||
return _Client(*args, **kwargs)
|
||||
|
||||
return Client, key_t
|
||||
|
||||
|
||||
class DummyClient:
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.cache = _DUMMY_CLIENT_CACHE
|
||||
|
||||
def get(self, key, *args, **kwargs):
|
||||
return self.cache.get(key)
|
||||
|
||||
def get_multi(self, keys):
|
||||
cache = self.cache
|
||||
return {k: cache[k] for k in keys if k in cache}
|
||||
|
||||
def set(self, key, value, *args, **kwargs):
|
||||
self.cache[key] = value
|
||||
|
||||
def delete(self, key, *args, **kwargs):
|
||||
self.cache.pop(key, None)
|
||||
|
||||
def incr(self, key, delta=1):
|
||||
return self.cache.incr(key, delta)
|
||||
|
||||
def touch(self, key, expire):
|
||||
pass
|
||||
|
||||
|
||||
backends = {
|
||||
'memcache': get_best_memcache,
|
||||
'memcached': get_best_memcache,
|
||||
'pylibmc': get_best_memcache,
|
||||
'memory': lambda: (DummyClient, ensure_bytes),
|
||||
}
|
||||
|
||||
|
||||
class CacheBackend(KeyValueStoreBackend):
|
||||
"""Cache result backend."""
|
||||
|
||||
servers = None
|
||||
supports_autoexpire = True
|
||||
supports_native_join = True
|
||||
implements_incr = True
|
||||
|
||||
def __init__(self, app, expires=None, backend=None,
|
||||
options=None, url=None, **kwargs):
|
||||
options = {} if not options else options
|
||||
super().__init__(app, **kwargs)
|
||||
self.url = url
|
||||
|
||||
self.options = dict(self.app.conf.cache_backend_options,
|
||||
**options)
|
||||
|
||||
self.backend = url or backend or self.app.conf.cache_backend
|
||||
if self.backend:
|
||||
self.backend, _, servers = self.backend.partition('://')
|
||||
self.servers = servers.rstrip('/').split(';')
|
||||
self.expires = self.prepare_expires(expires, type=int)
|
||||
try:
|
||||
self.Client, self.key_t = backends[self.backend]()
|
||||
except KeyError:
|
||||
raise ImproperlyConfigured(UNKNOWN_BACKEND.format(
|
||||
self.backend, ', '.join(backends)))
|
||||
self._encode_prefixes() # rencode the keyprefixes
|
||||
|
||||
def get(self, key):
|
||||
return self.client.get(key)
|
||||
|
||||
def mget(self, keys):
|
||||
return self.client.get_multi(keys)
|
||||
|
||||
def set(self, key, value):
|
||||
return self.client.set(key, value, self.expires)
|
||||
|
||||
def delete(self, key):
|
||||
return self.client.delete(key)
|
||||
|
||||
def _apply_chord_incr(self, header_result_args, body, **kwargs):
|
||||
chord_key = self.get_key_for_chord(header_result_args[0])
|
||||
self.client.set(chord_key, 0, time=self.expires)
|
||||
return super()._apply_chord_incr(
|
||||
header_result_args, body, **kwargs)
|
||||
|
||||
def incr(self, key):
|
||||
return self.client.incr(key)
|
||||
|
||||
def expire(self, key, value):
|
||||
return self.client.touch(key, value)
|
||||
|
||||
@cached_property
|
||||
def client(self):
|
||||
return self.Client(self.servers, **self.options)
|
||||
|
||||
def __reduce__(self, args=(), kwargs=None):
|
||||
kwargs = {} if not kwargs else kwargs
|
||||
servers = ';'.join(self.servers)
|
||||
backend = f'{self.backend}://{servers}/'
|
||||
kwargs.update(
|
||||
{'backend': backend,
|
||||
'expires': self.expires,
|
||||
'options': self.options})
|
||||
return super().__reduce__(args, kwargs)
|
||||
|
||||
def as_uri(self, *args, **kwargs):
|
||||
"""Return the backend as an URI.
|
||||
|
||||
This properly handles the case of multiple servers.
|
||||
"""
|
||||
servers = ';'.join(self.servers)
|
||||
return f'{self.backend}://{servers}/'
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Apache Cassandra result store backend using the DataStax driver."""
|
||||
import threading
|
||||
|
||||
from celery import states
|
||||
from celery.exceptions import ImproperlyConfigured
|
||||
from celery.utils.log import get_logger
|
||||
|
||||
from .base import BaseBackend
|
||||
|
||||
try: # pragma: no cover
|
||||
import cassandra
|
||||
import cassandra.auth
|
||||
import cassandra.cluster
|
||||
import cassandra.query
|
||||
except ImportError: # pragma: no cover
|
||||
cassandra = None
|
||||
|
||||
|
||||
__all__ = ('CassandraBackend',)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
E_NO_CASSANDRA = """
|
||||
You need to install the cassandra-driver library to
|
||||
use the Cassandra backend. See https://github.com/datastax/python-driver
|
||||
"""
|
||||
|
||||
E_NO_SUCH_CASSANDRA_AUTH_PROVIDER = """
|
||||
CASSANDRA_AUTH_PROVIDER you provided is not a valid auth_provider class.
|
||||
See https://datastax.github.io/python-driver/api/cassandra/auth.html.
|
||||
"""
|
||||
|
||||
Q_INSERT_RESULT = """
|
||||
INSERT INTO {table} (
|
||||
task_id, status, result, date_done, traceback, children) VALUES (
|
||||
%s, %s, %s, %s, %s, %s) {expires};
|
||||
"""
|
||||
|
||||
Q_SELECT_RESULT = """
|
||||
SELECT status, result, date_done, traceback, children
|
||||
FROM {table}
|
||||
WHERE task_id=%s
|
||||
LIMIT 1
|
||||
"""
|
||||
|
||||
Q_CREATE_RESULT_TABLE = """
|
||||
CREATE TABLE {table} (
|
||||
task_id text,
|
||||
status text,
|
||||
result blob,
|
||||
date_done timestamp,
|
||||
traceback blob,
|
||||
children blob,
|
||||
PRIMARY KEY ((task_id), date_done)
|
||||
) WITH CLUSTERING ORDER BY (date_done DESC);
|
||||
"""
|
||||
|
||||
Q_EXPIRES = """
|
||||
USING TTL {0}
|
||||
"""
|
||||
|
||||
|
||||
def buf_t(x):
|
||||
return bytes(x, 'utf8')
|
||||
|
||||
|
||||
class CassandraBackend(BaseBackend):
|
||||
"""Cassandra backend utilizing DataStax driver.
|
||||
|
||||
Raises:
|
||||
celery.exceptions.ImproperlyConfigured:
|
||||
if module :pypi:`cassandra-driver` is not available,
|
||||
or if the :setting:`cassandra_servers` setting is not set.
|
||||
"""
|
||||
|
||||
#: List of Cassandra servers with format: ``hostname``.
|
||||
servers = None
|
||||
|
||||
supports_autoexpire = True # autoexpire supported via entry_ttl
|
||||
|
||||
def __init__(self, servers=None, keyspace=None, table=None, entry_ttl=None,
|
||||
port=9042, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
if not cassandra:
|
||||
raise ImproperlyConfigured(E_NO_CASSANDRA)
|
||||
|
||||
conf = self.app.conf
|
||||
self.servers = servers or conf.get('cassandra_servers', None)
|
||||
self.port = port or conf.get('cassandra_port', None)
|
||||
self.keyspace = keyspace or conf.get('cassandra_keyspace', None)
|
||||
self.table = table or conf.get('cassandra_table', None)
|
||||
self.cassandra_options = conf.get('cassandra_options', {})
|
||||
|
||||
if not self.servers or not self.keyspace or not self.table:
|
||||
raise ImproperlyConfigured('Cassandra backend not configured.')
|
||||
|
||||
expires = entry_ttl or conf.get('cassandra_entry_ttl', None)
|
||||
|
||||
self.cqlexpires = (
|
||||
Q_EXPIRES.format(expires) if expires is not None else '')
|
||||
|
||||
read_cons = conf.get('cassandra_read_consistency') or 'LOCAL_QUORUM'
|
||||
write_cons = conf.get('cassandra_write_consistency') or 'LOCAL_QUORUM'
|
||||
|
||||
self.read_consistency = getattr(
|
||||
cassandra.ConsistencyLevel, read_cons,
|
||||
cassandra.ConsistencyLevel.LOCAL_QUORUM)
|
||||
self.write_consistency = getattr(
|
||||
cassandra.ConsistencyLevel, write_cons,
|
||||
cassandra.ConsistencyLevel.LOCAL_QUORUM)
|
||||
|
||||
self.auth_provider = None
|
||||
auth_provider = conf.get('cassandra_auth_provider', None)
|
||||
auth_kwargs = conf.get('cassandra_auth_kwargs', None)
|
||||
if auth_provider and auth_kwargs:
|
||||
auth_provider_class = getattr(cassandra.auth, auth_provider, None)
|
||||
if not auth_provider_class:
|
||||
raise ImproperlyConfigured(E_NO_SUCH_CASSANDRA_AUTH_PROVIDER)
|
||||
self.auth_provider = auth_provider_class(**auth_kwargs)
|
||||
|
||||
self._cluster = None
|
||||
self._session = None
|
||||
self._write_stmt = None
|
||||
self._read_stmt = None
|
||||
self._lock = threading.RLock()
|
||||
|
||||
def _get_connection(self, write=False):
|
||||
"""Prepare the connection for action.
|
||||
|
||||
Arguments:
|
||||
write (bool): are we a writer?
|
||||
"""
|
||||
if self._session is not None:
|
||||
return
|
||||
self._lock.acquire()
|
||||
try:
|
||||
if self._session is not None:
|
||||
return
|
||||
self._cluster = cassandra.cluster.Cluster(
|
||||
self.servers, port=self.port,
|
||||
auth_provider=self.auth_provider,
|
||||
**self.cassandra_options)
|
||||
self._session = self._cluster.connect(self.keyspace)
|
||||
|
||||
# We're forced to do concatenation below, as formatting would
|
||||
# blow up on superficial %s that'll be processed by Cassandra
|
||||
self._write_stmt = cassandra.query.SimpleStatement(
|
||||
Q_INSERT_RESULT.format(
|
||||
table=self.table, expires=self.cqlexpires),
|
||||
)
|
||||
self._write_stmt.consistency_level = self.write_consistency
|
||||
|
||||
self._read_stmt = cassandra.query.SimpleStatement(
|
||||
Q_SELECT_RESULT.format(table=self.table),
|
||||
)
|
||||
self._read_stmt.consistency_level = self.read_consistency
|
||||
|
||||
if write:
|
||||
# Only possible writers "workers" are allowed to issue
|
||||
# CREATE TABLE. This is to prevent conflicting situations
|
||||
# where both task-creator and task-executor would issue it
|
||||
# at the same time.
|
||||
|
||||
# Anyway; if you're doing anything critical, you should
|
||||
# have created this table in advance, in which case
|
||||
# this query will be a no-op (AlreadyExists)
|
||||
make_stmt = cassandra.query.SimpleStatement(
|
||||
Q_CREATE_RESULT_TABLE.format(table=self.table),
|
||||
)
|
||||
make_stmt.consistency_level = self.write_consistency
|
||||
|
||||
try:
|
||||
self._session.execute(make_stmt)
|
||||
except cassandra.AlreadyExists:
|
||||
pass
|
||||
|
||||
except cassandra.OperationTimedOut:
|
||||
# a heavily loaded or gone Cassandra cluster failed to respond.
|
||||
# leave this class in a consistent state
|
||||
if self._cluster is not None:
|
||||
self._cluster.shutdown() # also shuts down _session
|
||||
|
||||
self._cluster = None
|
||||
self._session = None
|
||||
raise # we did fail after all - reraise
|
||||
finally:
|
||||
self._lock.release()
|
||||
|
||||
def _store_result(self, task_id, result, state,
|
||||
traceback=None, request=None, **kwargs):
|
||||
"""Store return value and state of an executed task."""
|
||||
self._get_connection(write=True)
|
||||
|
||||
self._session.execute(self._write_stmt, (
|
||||
task_id,
|
||||
state,
|
||||
buf_t(self.encode(result)),
|
||||
self.app.now(),
|
||||
buf_t(self.encode(traceback)),
|
||||
buf_t(self.encode(self.current_task_children(request)))
|
||||
))
|
||||
|
||||
def as_uri(self, include_password=True):
|
||||
return 'cassandra://'
|
||||
|
||||
def _get_task_meta_for(self, task_id):
|
||||
"""Get task meta-data for a task by id."""
|
||||
self._get_connection()
|
||||
|
||||
res = self._session.execute(self._read_stmt, (task_id, )).one()
|
||||
if not res:
|
||||
return {'status': states.PENDING, 'result': None}
|
||||
|
||||
status, result, date_done, traceback, children = res
|
||||
|
||||
return self.meta_from_decoded({
|
||||
'task_id': task_id,
|
||||
'status': status,
|
||||
'result': self.decode(result),
|
||||
'date_done': date_done,
|
||||
'traceback': self.decode(traceback),
|
||||
'children': self.decode(children),
|
||||
})
|
||||
|
||||
def __reduce__(self, args=(), kwargs=None):
|
||||
kwargs = {} if not kwargs else kwargs
|
||||
kwargs.update(
|
||||
{'servers': self.servers,
|
||||
'keyspace': self.keyspace,
|
||||
'table': self.table})
|
||||
return super().__reduce__(args, kwargs)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Consul result store backend.
|
||||
|
||||
- :class:`ConsulBackend` implements KeyValueStoreBackend to store results
|
||||
in the key-value store of Consul.
|
||||
"""
|
||||
from kombu.utils.encoding import bytes_to_str
|
||||
from kombu.utils.url import parse_url
|
||||
|
||||
from celery.backends.base import KeyValueStoreBackend
|
||||
from celery.exceptions import ImproperlyConfigured
|
||||
from celery.utils.log import get_logger
|
||||
|
||||
try:
|
||||
import consul
|
||||
except ImportError:
|
||||
consul = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
__all__ = ('ConsulBackend',)
|
||||
|
||||
CONSUL_MISSING = """\
|
||||
You need to install the python-consul library in order to use \
|
||||
the Consul result store backend."""
|
||||
|
||||
|
||||
class ConsulBackend(KeyValueStoreBackend):
|
||||
"""Consul.io K/V store backend for Celery."""
|
||||
|
||||
consul = consul
|
||||
|
||||
supports_autoexpire = True
|
||||
|
||||
consistency = 'consistent'
|
||||
path = None
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if self.consul is None:
|
||||
raise ImproperlyConfigured(CONSUL_MISSING)
|
||||
#
|
||||
# By default, for correctness, we use a client connection per
|
||||
# operation. If set, self.one_client will be used for all operations.
|
||||
# This provides for the original behaviour to be selected, and is
|
||||
# also convenient for mocking in the unit tests.
|
||||
#
|
||||
self.one_client = None
|
||||
self._init_from_params(**parse_url(self.url))
|
||||
|
||||
def _init_from_params(self, hostname, port, virtual_host, **params):
|
||||
logger.debug('Setting on Consul client to connect to %s:%d',
|
||||
hostname, port)
|
||||
self.path = virtual_host
|
||||
self.hostname = hostname
|
||||
self.port = port
|
||||
#
|
||||
# Optionally, allow a single client connection to be used to reduce
|
||||
# the connection load on Consul by adding a "one_client=1" parameter
|
||||
# to the URL.
|
||||
#
|
||||
if params.get('one_client', None):
|
||||
self.one_client = self.client()
|
||||
|
||||
def client(self):
|
||||
return self.one_client or consul.Consul(host=self.hostname,
|
||||
port=self.port,
|
||||
consistency=self.consistency)
|
||||
|
||||
def _key_to_consul_key(self, key):
|
||||
key = bytes_to_str(key)
|
||||
return key if self.path is None else f'{self.path}/{key}'
|
||||
|
||||
def get(self, key):
|
||||
key = self._key_to_consul_key(key)
|
||||
logger.debug('Trying to fetch key %s from Consul', key)
|
||||
try:
|
||||
_, data = self.client().kv.get(key)
|
||||
return data['Value']
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
def mget(self, keys):
|
||||
for key in keys:
|
||||
yield self.get(key)
|
||||
|
||||
def set(self, key, value):
|
||||
"""Set a key in Consul.
|
||||
|
||||
Before creating the key it will create a session inside Consul
|
||||
where it creates a session with a TTL
|
||||
|
||||
The key created afterwards will reference to the session's ID.
|
||||
|
||||
If the session expires it will remove the key so that results
|
||||
can auto expire from the K/V store
|
||||
"""
|
||||
session_name = bytes_to_str(key)
|
||||
|
||||
key = self._key_to_consul_key(key)
|
||||
|
||||
logger.debug('Trying to create Consul session %s with TTL %d',
|
||||
session_name, self.expires)
|
||||
client = self.client()
|
||||
session_id = client.session.create(name=session_name,
|
||||
behavior='delete',
|
||||
ttl=self.expires)
|
||||
logger.debug('Created Consul session %s', session_id)
|
||||
|
||||
logger.debug('Writing key %s to Consul', key)
|
||||
return client.kv.put(key=key, value=value, acquire=session_id)
|
||||
|
||||
def delete(self, key):
|
||||
key = self._key_to_consul_key(key)
|
||||
logger.debug('Removing key %s from Consul', key)
|
||||
return self.client().kv.delete(key)
|
||||
@@ -0,0 +1,219 @@
|
||||
"""The CosmosDB/SQL backend for Celery (experimental)."""
|
||||
from kombu.utils import cached_property
|
||||
from kombu.utils.encoding import bytes_to_str
|
||||
from kombu.utils.url import _parse_url
|
||||
|
||||
from celery.exceptions import ImproperlyConfigured
|
||||
from celery.utils.log import get_logger
|
||||
|
||||
from .base import KeyValueStoreBackend
|
||||
|
||||
try:
|
||||
import pydocumentdb
|
||||
from pydocumentdb.document_client import DocumentClient
|
||||
from pydocumentdb.documents import (ConnectionPolicy, ConsistencyLevel,
|
||||
PartitionKind)
|
||||
from pydocumentdb.errors import HTTPFailure
|
||||
from pydocumentdb.retry_options import RetryOptions
|
||||
except ImportError: # pragma: no cover
|
||||
pydocumentdb = DocumentClient = ConsistencyLevel = PartitionKind = \
|
||||
HTTPFailure = ConnectionPolicy = RetryOptions = None
|
||||
|
||||
__all__ = ("CosmosDBSQLBackend",)
|
||||
|
||||
|
||||
ERROR_NOT_FOUND = 404
|
||||
ERROR_EXISTS = 409
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
|
||||
|
||||
class CosmosDBSQLBackend(KeyValueStoreBackend):
|
||||
"""CosmosDB/SQL backend for Celery."""
|
||||
|
||||
def __init__(self,
|
||||
url=None,
|
||||
database_name=None,
|
||||
collection_name=None,
|
||||
consistency_level=None,
|
||||
max_retry_attempts=None,
|
||||
max_retry_wait_time=None,
|
||||
*args,
|
||||
**kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if pydocumentdb is None:
|
||||
raise ImproperlyConfigured(
|
||||
"You need to install the pydocumentdb library to use the "
|
||||
"CosmosDB backend.")
|
||||
|
||||
conf = self.app.conf
|
||||
|
||||
self._endpoint, self._key = self._parse_url(url)
|
||||
|
||||
self._database_name = (
|
||||
database_name or
|
||||
conf["cosmosdbsql_database_name"])
|
||||
|
||||
self._collection_name = (
|
||||
collection_name or
|
||||
conf["cosmosdbsql_collection_name"])
|
||||
|
||||
try:
|
||||
self._consistency_level = getattr(
|
||||
ConsistencyLevel,
|
||||
consistency_level or
|
||||
conf["cosmosdbsql_consistency_level"])
|
||||
except AttributeError:
|
||||
raise ImproperlyConfigured("Unknown CosmosDB consistency level")
|
||||
|
||||
self._max_retry_attempts = (
|
||||
max_retry_attempts or
|
||||
conf["cosmosdbsql_max_retry_attempts"])
|
||||
|
||||
self._max_retry_wait_time = (
|
||||
max_retry_wait_time or
|
||||
conf["cosmosdbsql_max_retry_wait_time"])
|
||||
|
||||
@classmethod
|
||||
def _parse_url(cls, url):
|
||||
_, host, port, _, password, _, _ = _parse_url(url)
|
||||
|
||||
if not host or not password:
|
||||
raise ImproperlyConfigured("Invalid URL")
|
||||
|
||||
if not port:
|
||||
port = 443
|
||||
|
||||
scheme = "https" if port == 443 else "http"
|
||||
endpoint = f"{scheme}://{host}:{port}"
|
||||
return endpoint, password
|
||||
|
||||
@cached_property
|
||||
def _client(self):
|
||||
"""Return the CosmosDB/SQL client.
|
||||
|
||||
If this is the first call to the property, the client is created and
|
||||
the database and collection are initialized if they don't yet exist.
|
||||
|
||||
"""
|
||||
connection_policy = ConnectionPolicy()
|
||||
connection_policy.RetryOptions = RetryOptions(
|
||||
max_retry_attempt_count=self._max_retry_attempts,
|
||||
max_wait_time_in_seconds=self._max_retry_wait_time)
|
||||
|
||||
client = DocumentClient(
|
||||
self._endpoint,
|
||||
{"masterKey": self._key},
|
||||
connection_policy=connection_policy,
|
||||
consistency_level=self._consistency_level)
|
||||
|
||||
self._create_database_if_not_exists(client)
|
||||
self._create_collection_if_not_exists(client)
|
||||
|
||||
return client
|
||||
|
||||
def _create_database_if_not_exists(self, client):
|
||||
try:
|
||||
client.CreateDatabase({"id": self._database_name})
|
||||
except HTTPFailure as ex:
|
||||
if ex.status_code != ERROR_EXISTS:
|
||||
raise
|
||||
else:
|
||||
LOGGER.info("Created CosmosDB database %s",
|
||||
self._database_name)
|
||||
|
||||
def _create_collection_if_not_exists(self, client):
|
||||
try:
|
||||
client.CreateCollection(
|
||||
self._database_link,
|
||||
{"id": self._collection_name,
|
||||
"partitionKey": {"paths": ["/id"],
|
||||
"kind": PartitionKind.Hash}})
|
||||
except HTTPFailure as ex:
|
||||
if ex.status_code != ERROR_EXISTS:
|
||||
raise
|
||||
else:
|
||||
LOGGER.info("Created CosmosDB collection %s/%s",
|
||||
self._database_name, self._collection_name)
|
||||
|
||||
@cached_property
|
||||
def _database_link(self):
|
||||
return "dbs/" + self._database_name
|
||||
|
||||
@cached_property
|
||||
def _collection_link(self):
|
||||
return self._database_link + "/colls/" + self._collection_name
|
||||
|
||||
def _get_document_link(self, key):
|
||||
return self._collection_link + "/docs/" + key
|
||||
|
||||
@classmethod
|
||||
def _get_partition_key(cls, key):
|
||||
if not key or key.isspace():
|
||||
raise ValueError("Key cannot be none, empty or whitespace.")
|
||||
|
||||
return {"partitionKey": key}
|
||||
|
||||
def get(self, key):
|
||||
"""Read the value stored at the given key.
|
||||
|
||||
Args:
|
||||
key: The key for which to read the value.
|
||||
|
||||
"""
|
||||
key = bytes_to_str(key)
|
||||
LOGGER.debug("Getting CosmosDB document %s/%s/%s",
|
||||
self._database_name, self._collection_name, key)
|
||||
|
||||
try:
|
||||
document = self._client.ReadDocument(
|
||||
self._get_document_link(key),
|
||||
self._get_partition_key(key))
|
||||
except HTTPFailure as ex:
|
||||
if ex.status_code != ERROR_NOT_FOUND:
|
||||
raise
|
||||
return None
|
||||
else:
|
||||
return document.get("value")
|
||||
|
||||
def set(self, key, value):
|
||||
"""Store a value for a given key.
|
||||
|
||||
Args:
|
||||
key: The key at which to store the value.
|
||||
value: The value to store.
|
||||
|
||||
"""
|
||||
key = bytes_to_str(key)
|
||||
LOGGER.debug("Creating CosmosDB document %s/%s/%s",
|
||||
self._database_name, self._collection_name, key)
|
||||
|
||||
self._client.CreateDocument(
|
||||
self._collection_link,
|
||||
{"id": key, "value": value},
|
||||
self._get_partition_key(key))
|
||||
|
||||
def mget(self, keys):
|
||||
"""Read all the values for the provided keys.
|
||||
|
||||
Args:
|
||||
keys: The list of keys to read.
|
||||
|
||||
"""
|
||||
return [self.get(key) for key in keys]
|
||||
|
||||
def delete(self, key):
|
||||
"""Delete the value at a given key.
|
||||
|
||||
Args:
|
||||
key: The key of the value to delete.
|
||||
|
||||
"""
|
||||
key = bytes_to_str(key)
|
||||
LOGGER.debug("Deleting CosmosDB document %s/%s/%s",
|
||||
self._database_name, self._collection_name, key)
|
||||
|
||||
self._client.DeleteDocument(
|
||||
self._get_document_link(key),
|
||||
self._get_partition_key(key))
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Couchbase result store backend."""
|
||||
|
||||
from kombu.utils.url import _parse_url
|
||||
|
||||
from celery.exceptions import ImproperlyConfigured
|
||||
|
||||
from .base import KeyValueStoreBackend
|
||||
|
||||
try:
|
||||
from couchbase.auth import PasswordAuthenticator
|
||||
from couchbase.cluster import Cluster, ClusterOptions
|
||||
from couchbase_core._libcouchbase import FMT_AUTO
|
||||
except ImportError:
|
||||
Cluster = PasswordAuthenticator = ClusterOptions = None
|
||||
|
||||
__all__ = ('CouchbaseBackend',)
|
||||
|
||||
|
||||
class CouchbaseBackend(KeyValueStoreBackend):
|
||||
"""Couchbase backend.
|
||||
|
||||
Raises:
|
||||
celery.exceptions.ImproperlyConfigured:
|
||||
if module :pypi:`couchbase` is not available.
|
||||
"""
|
||||
|
||||
bucket = 'default'
|
||||
host = 'localhost'
|
||||
port = 8091
|
||||
username = None
|
||||
password = None
|
||||
quiet = False
|
||||
supports_autoexpire = True
|
||||
|
||||
timeout = 2.5
|
||||
|
||||
# Use str as couchbase key not bytes
|
||||
key_t = str
|
||||
|
||||
def __init__(self, url=None, *args, **kwargs):
|
||||
kwargs.setdefault('expires_type', int)
|
||||
super().__init__(*args, **kwargs)
|
||||
self.url = url
|
||||
|
||||
if Cluster is None:
|
||||
raise ImproperlyConfigured(
|
||||
'You need to install the couchbase library to use the '
|
||||
'Couchbase backend.',
|
||||
)
|
||||
|
||||
uhost = uport = uname = upass = ubucket = None
|
||||
if url:
|
||||
_, uhost, uport, uname, upass, ubucket, _ = _parse_url(url)
|
||||
ubucket = ubucket.strip('/') if ubucket else None
|
||||
|
||||
config = self.app.conf.get('couchbase_backend_settings', None)
|
||||
if config is not None:
|
||||
if not isinstance(config, dict):
|
||||
raise ImproperlyConfigured(
|
||||
'Couchbase backend settings should be grouped in a dict',
|
||||
)
|
||||
else:
|
||||
config = {}
|
||||
|
||||
self.host = uhost or config.get('host', self.host)
|
||||
self.port = int(uport or config.get('port', self.port))
|
||||
self.bucket = ubucket or config.get('bucket', self.bucket)
|
||||
self.username = uname or config.get('username', self.username)
|
||||
self.password = upass or config.get('password', self.password)
|
||||
|
||||
self._connection = None
|
||||
|
||||
def _get_connection(self):
|
||||
"""Connect to the Couchbase server."""
|
||||
if self._connection is None:
|
||||
if self.host and self.port:
|
||||
uri = f"couchbase://{self.host}:{self.port}"
|
||||
else:
|
||||
uri = f"couchbase://{self.host}"
|
||||
if self.username and self.password:
|
||||
opt = PasswordAuthenticator(self.username, self.password)
|
||||
else:
|
||||
opt = None
|
||||
|
||||
cluster = Cluster(uri, opt)
|
||||
|
||||
bucket = cluster.bucket(self.bucket)
|
||||
|
||||
self._connection = bucket.default_collection()
|
||||
return self._connection
|
||||
|
||||
@property
|
||||
def connection(self):
|
||||
return self._get_connection()
|
||||
|
||||
def get(self, key):
|
||||
return self.connection.get(key).content
|
||||
|
||||
def set(self, key, value):
|
||||
self.connection.upsert(key, value, ttl=self.expires, format=FMT_AUTO)
|
||||
|
||||
def mget(self, keys):
|
||||
return self.connection.get_multi(keys)
|
||||
|
||||
def delete(self, key):
|
||||
self.connection.remove(key)
|
||||
Loaded 100 of 1212 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user