Example #1
0
    def bind(self, app):
        was_bound, self.__bound__ = self.__bound__, True
        self._app = app
        conf = app.conf

        for attr_name, config_name in self.from_config:
            if getattr(self, attr_name, None) is None:
                setattr(self, attr_name, conf[config_name])
        if self.accept_magic_kwargs is None:
            self.accept_magic_kwargs = app.accept_magic_kwargs
        if self.backend is None:
            self.backend = app.backend

        # decorate with annotations from config.
        if not was_bound:
            self.annotate()

        from celery.utils.threads import LocalStack
        self.request_stack = LocalStack()
        self.request_stack.push(Context())

        # PeriodicTask uses this to add itself to the PeriodicTask schedule.
        self.on_bound(app)

        return app
Example #2
0
    def bind(self, app):
        was_bound, self.__bound__ = self.__bound__, True
        self._app = app
        conf = app.conf
        self._exec_options = None  # clear option cache

        for attr_name, config_name in self.from_config:
            if getattr(self, attr_name, None) is None:
                setattr(self, attr_name, conf[config_name])

        # decorate with annotations from config.
        if not was_bound:
            self.annotate()

            from celery.utils.threads import LocalStack
            self.request_stack = LocalStack()

        # PeriodicTask uses this to add itself to the PeriodicTask schedule.
        self.on_bound(app)

        return app
Example #3
0
class Task(object):
    """Task base class.

    When called tasks apply the :meth:`run` method.  This method must
    be defined by all tasks (that is unless the :meth:`__call__` method
    is overridden).

    """
    __trace__ = None
    __v2_compat__ = False  # set by old base in celery.task.base

    ErrorMail = ErrorMail
    MaxRetriesExceededError = MaxRetriesExceededError

    #: Execution strategy used, or the qualified name of one.
    Strategy = 'celery.worker.strategy:default'

    #: This is the instance bound to if the task is a method of a class.
    __self__ = None

    #: The application instance associated with this task class.
    _app = None

    #: Name of the task.
    name = None

    #: If :const:`True` the task is an abstract base class.
    abstract = True

    #: Maximum number of retries before giving up.  If set to :const:`None`,
    #: it will **never** stop retrying.
    max_retries = 3

    #: Default time in seconds before a retry of the task should be
    #: executed.  3 minutes by default.
    default_retry_delay = 3 * 60

    #: Rate limit for this task type.  Examples: :const:`None` (no rate
    #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks
    #: a minute),`'100/h'` (hundred tasks an hour)
    rate_limit = None

    #: If enabled the worker will not store task state and return values
    #: for this task.  Defaults to the :setting:`CELERY_IGNORE_RESULT`
    #: setting.
    ignore_result = None

    #: If enabled the request will keep track of subtasks started by
    #: this task, and this information will be sent with the result
    #: (``result.children``).
    trail = True

    #: When enabled errors will be stored even if the task is otherwise
    #: configured to ignore results.
    store_errors_even_if_ignored = None

    #: If enabled an email will be sent to :setting:`ADMINS` whenever a task
    #: of this type fails.
    send_error_emails = None

    #: The name of a serializer that are registered with
    #: :mod:`kombu.serialization.registry`.  Default is `'pickle'`.
    serializer = None

    #: Hard time limit.
    #: Defaults to the :setting:`CELERYD_TASK_TIME_LIMIT` setting.
    time_limit = None

    #: Soft time limit.
    #: Defaults to the :setting:`CELERYD_TASK_SOFT_TIME_LIMIT` setting.
    soft_time_limit = None

    #: The result store backend used for this task.
    backend = None

    #: If disabled this task won't be registered automatically.
    autoregister = True

    #: If enabled the task will report its status as 'started' when the task
    #: is executed by a worker.  Disabled by default as the normal behaviour
    #: is to not report that level of granularity.  Tasks are either pending,
    #: finished, or waiting to be retried.
    #:
    #: Having a 'started' status can be useful for when there are long
    #: running tasks and there is a need to report which task is currently
    #: running.
    #:
    #: The application default can be overridden using the
    #: :setting:`CELERY_TRACK_STARTED` setting.
    track_started = None

    #: When enabled messages for this task will be acknowledged **after**
    #: the task has been executed, and not *just before* which is the
    #: default behavior.
    #:
    #: Please note that this means the task may be executed twice if the
    #: worker crashes mid execution (which may be acceptable for some
    #: applications).
    #:
    #: The application default can be overridden with the
    #: :setting:`CELERY_ACKS_LATE` setting.
    acks_late = None

    #: Tuple of expected exceptions.
    #:
    #: These are errors that are expected in normal operation
    #: and that should not be regarded as a real error by the worker.
    #: Currently this means that the state will be updated to an error
    #: state, but the worker will not log the event as an error.
    throws = ()

    #: Default task expiry time.
    expires = None

    #: Some may expect a request to exist even if the task has not been
    #: called.  This should probably be deprecated.
    _default_request = None

    _exec_options = None

    __bound__ = False

    from_config = (
        ('send_error_emails', 'CELERY_SEND_TASK_ERROR_EMAILS'),
        ('serializer', 'CELERY_TASK_SERIALIZER'),
        ('rate_limit', 'CELERY_DEFAULT_RATE_LIMIT'),
        ('track_started', 'CELERY_TRACK_STARTED'),
        ('acks_late', 'CELERY_ACKS_LATE'),
        ('ignore_result', 'CELERY_IGNORE_RESULT'),
        ('store_errors_even_if_ignored',
            'CELERY_STORE_ERRORS_EVEN_IF_IGNORED'),
    )

    #: ignored
    accept_magic_kwargs = False

    _backend = None  # set by backend property.

    __bound__ = False

    # - Tasks are lazily bound, so that configuration is not set
    # - until the task is actually used

    @classmethod
    def bind(self, app):
        was_bound, self.__bound__ = self.__bound__, True
        self._app = app
        conf = app.conf
        self._exec_options = None  # clear option cache

        for attr_name, config_name in self.from_config:
            if getattr(self, attr_name, None) is None:
                setattr(self, attr_name, conf[config_name])

        # decorate with annotations from config.
        if not was_bound:
            self.annotate()

            from celery.utils.threads import LocalStack
            self.request_stack = LocalStack()

        # PeriodicTask uses this to add itself to the PeriodicTask schedule.
        self.on_bound(app)

        return app

    @classmethod
    def on_bound(self, app):
        """This method can be defined to do additional actions when the
        task class is bound to an app."""
        pass

    @classmethod
    def _get_app(self):
        if self._app is None:
            self._app = current_app
        if not self.__bound__:
            # The app property's __set__  method is not called
            # if Task.app is set (on the class), so must bind on use.
            self.bind(self._app)
        return self._app
    app = class_property(_get_app, bind)

    @classmethod
    def annotate(self):
        for d in resolve_all_annotations(self.app.annotations, self):
            for key, value in items(d):
                if key.startswith('@'):
                    self.add_around(key[1:], value)
                else:
                    setattr(self, key, value)

    @classmethod
    def add_around(self, attr, around):
        orig = getattr(self, attr)
        if getattr(orig, '__wrapped__', None):
            orig = orig.__wrapped__
        meth = around(orig)
        meth.__wrapped__ = orig
        setattr(self, attr, meth)

    def __call__(self, *args, **kwargs):
        _task_stack.push(self)
        self.push_request()
        try:
            # add self if this is a bound task
            if self.__self__ is not None:
                return self.run(self.__self__, *args, **kwargs)
            return self.run(*args, **kwargs)
        finally:
            self.pop_request()
            _task_stack.pop()

    def __reduce__(self):
        # - tasks are pickled into the name of the task only, and the reciever
        # - simply grabs it from the local registry.
        # - in later versions the module of the task is also included,
        # - and the receiving side tries to import that module so that
        # - it will work even if the task has not been registered.
        mod = type(self).__module__
        mod = mod if mod and mod in sys.modules else None
        return (_unpickle_task_v2, (self.name, mod), None)

    def run(self, *args, **kwargs):
        """The body of the task executed by workers."""
        raise NotImplementedError('Tasks must define the run method.')

    def start_strategy(self, app, consumer, **kwargs):
        return instantiate(self.Strategy, self, app, consumer, **kwargs)

    def delay(self, *args, **kwargs):
        """Star argument version of :meth:`apply_async`.

        Does not support the extra options enabled by :meth:`apply_async`.

        :param \*args: positional arguments passed on to the task.
        :param \*\*kwargs: keyword arguments passed on to the task.

        :returns :class:`celery.result.AsyncResult`:

        """
        return self.apply_async(args, kwargs)

    def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,
                    link=None, link_error=None, **options):
        """Apply tasks asynchronously by sending a message.

        :keyword args: The positional arguments to pass on to the
                       task (a :class:`list` or :class:`tuple`).

        :keyword kwargs: The keyword arguments to pass on to the
                         task (a :class:`dict`)

        :keyword countdown: Number of seconds into the future that the
                            task should execute. Defaults to immediate
                            execution.

        :keyword eta: A :class:`~datetime.datetime` object describing
                      the absolute time and date of when the task should
                      be executed.  May not be specified if `countdown`
                      is also supplied.

        :keyword expires: Either a :class:`int`, describing the number of
                          seconds, or a :class:`~datetime.datetime` object
                          that describes the absolute time and date of when
                          the task should expire.  The task will not be
                          executed after the expiration time.

        :keyword connection: Re-use existing broker connection instead
                             of establishing a new one.

        :keyword retry: If enabled sending of the task message will be retried
                        in the event of connection loss or failure.  Default
                        is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
                        setting.  Note you need to handle the
                        producer/connection manually for this to work.

        :keyword retry_policy:  Override the retry policy used.  See the
                                :setting:`CELERY_TASK_PUBLISH_RETRY` setting.

        :keyword routing_key: Custom routing key used to route the task to a
                              worker server. If in combination with a
                              ``queue`` argument only used to specify custom
                              routing keys to topic exchanges.

        :keyword queue: The queue to route the task to.  This must be a key
                        present in :setting:`CELERY_QUEUES`, or
                        :setting:`CELERY_CREATE_MISSING_QUEUES` must be
                        enabled.  See :ref:`guide-routing` for more
                        information.

        :keyword exchange: Named custom exchange to send the task to.
                           Usually not used in combination with the ``queue``
                           argument.

        :keyword priority: The task priority, a number between 0 and 9.
                           Defaults to the :attr:`priority` attribute.

        :keyword serializer: A string identifying the default
                             serialization method to use.  Can be `pickle`,
                             `json`, `yaml`, `msgpack` or any custom
                             serialization method that has been registered
                             with :mod:`kombu.serialization.registry`.
                             Defaults to the :attr:`serializer` attribute.

        :keyword compression: A string identifying the compression method
                              to use.  Can be one of ``zlib``, ``bzip2``,
                              or any custom compression methods registered with
                              :func:`kombu.compression.register`. Defaults to
                              the :setting:`CELERY_MESSAGE_COMPRESSION`
                              setting.
        :keyword link: A single, or a list of tasks to apply if the
                       task exits successfully.
        :keyword link_error: A single, or a list of tasks to apply
                      if an error occurs while executing the task.

        :keyword producer: :class:`kombu.Producer` instance to use.
        :keyword add_to_parent: If set to True (default) and the task
            is applied while executing another task, then the result
            will be appended to the parent tasks ``request.children``
            attribute.  Trailing can also be disabled by default using the
            :attr:`trail` attribute
        :keyword publisher: Deprecated alias to ``producer``.

        Also supports all keyword arguments supported by
        :meth:`kombu.Producer.publish`.

        .. note::
            If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
            be replaced by a local :func:`apply` call instead.

        """
        try:
            check_arguments = self.__header__
        except AttributeError:
            pass
        else:
            check_arguments(*args or (), **kwargs or {})

        app = self._get_app()
        if app.conf.CELERY_ALWAYS_EAGER:
            return self.apply(args, kwargs, task_id=task_id or uuid(),
                              link=link, link_error=link_error, **options)
        # add 'self' if this is a "task_method".
        if self.__self__ is not None:
            args = args if isinstance(args, tuple) else tuple(args or ())
            args = (self.__self__, ) + args
        return app.send_task(
            self.name, args, kwargs, task_id=task_id, producer=producer,
            link=link, link_error=link_error, result_cls=self.AsyncResult,
            **dict(self._get_exec_options(), **options)
        )

    def signature_from_request(self, request=None, args=None, kwargs=None,
                               queue=None, **extra_options):
        request = self.request if request is None else request
        args = request.args if args is None else args
        kwargs = request.kwargs if kwargs is None else kwargs
        limit_hard, limit_soft = request.timelimit or (None, None)
        options = {
            'task_id': request.id,
            'link': request.callbacks,
            'link_error': request.errbacks,
            'group_id': request.group,
            'chord': request.chord,
            'soft_time_limit': limit_soft,
            'time_limit': limit_hard,
            'reply_to': request.reply_to,
        }
        options.update(
            {'queue': queue} if queue else (request.delivery_info or {})
        )
        return self.signature(
            args, kwargs, options, type=self, **extra_options
        )
    subtask_from_request = signature_from_request

    def retry(self, args=None, kwargs=None, exc=None, throw=True,
              eta=None, countdown=None, max_retries=None, **options):
        """Retry the task.

        :param args: Positional arguments to retry with.
        :param kwargs: Keyword arguments to retry with.
        :keyword exc: Custom exception to report when the max restart
            limit has been exceeded (default:
            :exc:`~@MaxRetriesExceededError`).

            If this argument is set and retry is called while
            an exception was raised (``sys.exc_info()`` is set)
            it will attempt to reraise the current exception.

            If no exception was raised it will raise the ``exc``
            argument provided.
        :keyword countdown: Time in seconds to delay the retry for.
        :keyword eta: Explicit time and date to run the retry at
                      (must be a :class:`~datetime.datetime` instance).
        :keyword max_retries: If set, overrides the default retry limit.
            A value of :const:`None`, means "use the default", so if you want infinite
            retries you would have to set the :attr:`max_retries` attribute of the
            task to :const:`None` first.
        :keyword time_limit: If set, overrides the default time limit.
        :keyword soft_time_limit: If set, overrides the default soft
                                  time limit.
        :keyword \*\*options: Any extra options to pass on to
                              meth:`apply_async`.
        :keyword throw: If this is :const:`False`, do not raise the
                        :exc:`~@Retry` exception,
                        that tells the worker to mark the task as being
                        retried.  Note that this means the task will be
                        marked as failed if the task raises an exception,
                        or successful if it returns.

        :raises celery.exceptions.Retry: To tell the worker that
            the task has been re-sent for retry. This always happens,
            unless the `throw` keyword argument has been explicitly set
            to :const:`False`, and is considered normal operation.

        **Example**

        .. code-block:: python

            >>> from imaginary_twitter_lib import Twitter
            >>> from proj.celery import app

            >>> @app.task()
            ... def tweet(auth, message):
            ...     twitter = Twitter(oauth=auth)
            ...     try:
            ...         twitter.post_status_update(message)
            ...     except twitter.FailWhale as exc:
            ...         # Retry in 5 minutes.
            ...         raise tweet.retry(countdown=60 * 5, exc=exc)

        Although the task will never return above as `retry` raises an
        exception to notify the worker, we use `raise` in front of the retry
        to convey that the rest of the block will not be executed.

        """
        request = self.request
        retries = request.retries + 1
        max_retries = self.max_retries if max_retries is None else max_retries

        # Not in worker or emulated by (apply/always_eager),
        # so just raise the original exception.
        if request.called_directly:
            maybe_reraise()  # raise orig stack if PyErr_Occurred
            raise exc or Retry('Task can be retried', None)

        if not eta and countdown is None:
            countdown = self.default_retry_delay

        is_eager = request.is_eager
        S = self.signature_from_request(
            request, args, kwargs,
            countdown=countdown, eta=eta, retries=retries,
            **options
        )

        if max_retries is not None and retries > max_retries:
            if exc:
                # first try to reraise the original exception
                maybe_reraise()
                # or if not in an except block then raise the custom exc.
                raise exc
            raise self.MaxRetriesExceededError(
                "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
                    self.name, request.id, S.args, S.kwargs))

        ret = Retry(exc=exc, when=eta or countdown)

        if is_eager:
            # if task was executed eagerly using apply(),
            # then the retry must also be executed eagerly.
            S.apply().get()
            return ret

        try:
            S.apply_async()
        except Exception as exc:
            raise Reject(exc, requeue=False)
        if throw:
            raise ret
        return ret

    def apply(self, args=None, kwargs=None,
              link=None, link_error=None, **options):
        """Execute this task locally, by blocking until the task returns.

        :param args: positional arguments passed on to the task.
        :param kwargs: keyword arguments passed on to the task.
        :keyword throw: Re-raise task exceptions.  Defaults to
                        the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
                        setting.

        :rtype :class:`celery.result.EagerResult`:

        """
        # trace imports Task, so need to import inline.
        from celery.app.trace import build_tracer

        app = self._get_app()
        args = args or ()
        # add 'self' if this is a bound method.
        if self.__self__ is not None:
            args = (self.__self__, ) + tuple(args)
        kwargs = kwargs or {}
        task_id = options.get('task_id') or uuid()
        retries = options.get('retries', 0)
        throw = app.either('CELERY_EAGER_PROPAGATES_EXCEPTIONS',
                           options.pop('throw', None))

        # Make sure we get the task instance, not class.
        task = app._tasks[self.name]

        request = {'id': task_id,
                   'retries': retries,
                   'is_eager': True,
                   'logfile': options.get('logfile'),
                   'loglevel': options.get('loglevel', 0),
                   'callbacks': maybe_list(link),
                   'errbacks': maybe_list(link_error),
                   'headers': options.get('headers'),
                   'delivery_info': {'is_eager': True}}
        tb = None
        tracer = build_tracer(
            task.name, task, eager=True,
            propagate=throw, app=self._get_app(),
        )
        ret = tracer(task_id, args, kwargs, request)
        retval = ret.retval
        if isinstance(retval, ExceptionInfo):
            retval, tb = retval.exception, retval.traceback
        state = states.SUCCESS if ret.info is None else ret.info.state
        return EagerResult(task_id, retval, state, traceback=tb)

    def AsyncResult(self, task_id, **kwargs):
        """Get AsyncResult instance for this kind of task.

        :param task_id: Task id to get result for.

        """
        return self._get_app().AsyncResult(task_id, backend=self.backend,
                                           task_name=self.name, **kwargs)

    def signature(self, args=None, *starargs, **starkwargs):
        """Return :class:`~celery.signature` object for
        this task, wrapping arguments and execution options
        for a single task invocation."""
        starkwargs.setdefault('app', self.app)
        return signature(self, args, *starargs, **starkwargs)
    subtask = signature

    def s(self, *args, **kwargs):
        """``.s(*a, **k) -> .signature(a, k)``"""
        return self.signature(args, kwargs)

    def si(self, *args, **kwargs):
        """``.si(*a, **k) -> .signature(a, k, immutable=True)``"""
        return self.signature(args, kwargs, immutable=True)

    def chunks(self, it, n):
        """Creates a :class:`~celery.canvas.chunks` task for this task."""
        from celery import chunks
        return chunks(self.s(), it, n, app=self.app)

    def map(self, it):
        """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
        from celery import xmap
        return xmap(self.s(), it, app=self.app)

    def starmap(self, it):
        """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
        from celery import xstarmap
        return xstarmap(self.s(), it, app=self.app)

    def send_event(self, type_, **fields):
        req = self.request
        with self.app.events.default_dispatcher(hostname=req.hostname) as d:
            return d.send(type_, uuid=req.id, **fields)

    def replace(self, sig):
        """Replace the current task, with a new task inheriting the
        same task id.

        :param sig: :class:`@signature`

        Note: This will raise :exc:`~@Ignore`, so the best practice
        is to always use ``raise self.replace_in_chord(...)`` to convey
        to the reader that the task will not continue after being replaced.

        :param: Signature of new task.

        """
        chord = self.request.chord
        if isinstance(sig, group):
            sig |= self.app.tasks['celery.accumulate'].s(index=0).set(
                chord=chord,
            )
            chord = None
        sig.freeze(self.request.id,
                   group_id=self.request.group,
                   chord=chord,
                   root_id=self.request.root_id)
        sig.delay()
        raise Ignore('Chord member replaced by new task')

    def add_to_chord(self, sig, lazy=False):
        """Add signature to the chord the current task is a member of.

        :param sig: Signature to extend chord with.
        :param lazy: If enabled the new task will not actually be called,
                      and ``sig.delay()`` must be called manually.

        Currently only supported by the Redis result backend when
        ``?new_join=1`` is enabled.

        """
        if not self.request.chord:
            raise ValueError('Current task is not member of any chord')
        result = sig.freeze(group_id=self.request.group,
                            chord=self.request.chord,
                            root_id=self.request.root_id)
        self.backend.add_to_chord(self.request.group, result)
        return sig.delay() if not lazy else sig

    def update_state(self, task_id=None, state=None, meta=None):
        """Update task state.

        :keyword task_id: Id of the task to update, defaults to the
                          id of the current task
        :keyword state: New state (:class:`str`).
        :keyword meta: State metadata (:class:`dict`).



        """
        if task_id is None:
            task_id = self.request.id
        self.backend.store_result(task_id, meta, state)

    def on_success(self, retval, task_id, args, kwargs):
        """Success handler.

        Run by the worker if the task executes successfully.

        :param retval: The return value of the task.
        :param task_id: Unique id of the executed task.
        :param args: Original arguments for the executed task.
        :param kwargs: Original keyword arguments for the executed task.

        The return value of this handler is ignored.

        """
        pass

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        """Retry handler.

        This is run by the worker when the task is to be retried.

        :param exc: The exception sent to :meth:`retry`.
        :param task_id: Unique id of the retried task.
        :param args: Original arguments for the retried task.
        :param kwargs: Original keyword arguments for the retried task.

        :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
                        instance, containing the traceback.

        The return value of this handler is ignored.

        """
        pass

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        """Error handler.

        This is run by the worker when the task fails.

        :param exc: The exception raised by the task.
        :param task_id: Unique id of the failed task.
        :param args: Original arguments for the task that failed.
        :param kwargs: Original keyword arguments for the task
                       that failed.

        :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
                        instance, containing the traceback.

        The return value of this handler is ignored.

        """
        pass

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        """Handler called after the task returns.

        :param status: Current task state.
        :param retval: Task return value/exception.
        :param task_id: Unique id of the task.
        :param args: Original arguments for the task that failed.
        :param kwargs: Original keyword arguments for the task
                       that failed.

        :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
                        instance, containing the traceback (if any).

        The return value of this handler is ignored.

        """
        pass

    def send_error_email(self, context, exc, **kwargs):
        if self.send_error_emails and \
                not getattr(self, 'disable_error_emails', None):
            self.ErrorMail(self, **kwargs).send(context, exc)

    def add_trail(self, result):
        if self.trail:
            self.request.children.append(result)
        return result

    def push_request(self, *args, **kwargs):
        self.request_stack.push(Context(*args, **kwargs))

    def pop_request(self):
        self.request_stack.pop()

    def __repr__(self):
        """`repr(task)`"""
        return _reprtask(self, R_SELF_TASK if self.__self__ else R_INSTANCE)

    def _get_request(self):
        """Get current request object."""
        req = self.request_stack.top
        if req is None:
            # task was not called, but some may still expect a request
            # to be there, perhaps that should be deprecated.
            if self._default_request is None:
                self._default_request = Context()
            return self._default_request
        return req
    request = property(_get_request)

    def _get_exec_options(self):
        if self._exec_options is None:
            self._exec_options = extract_exec_options(self)
        return self._exec_options

    @property
    def backend(self):
        backend = self._backend
        if backend is None:
            return self.app.backend
        return backend

    @backend.setter
    def backend(self, value):  # noqa
        self._backend = value

    @property
    def __name__(self):
        return self.__class__.__name__
Example #4
0
class Task(object):
    """Task base class.

    When called tasks apply the :meth:`run` method.  This method must
    be defined by all tasks (that is unless the :meth:`__call__` method
    is overridden).
    """
    __trace__ = None
    __v2_compat__ = False  # set by old base in celery.task.base

    MaxRetriesExceededError = MaxRetriesExceededError
    OperationalError = OperationalError

    #: Execution strategy used, or the qualified name of one.
    Strategy = 'celery.worker.strategy:default'

    #: This is the instance bound to if the task is a method of a class.
    __self__ = None

    #: The application instance associated with this task class.
    _app = None

    #: Name of the task.
    name = None

    #: Maximum number of retries before giving up.  If set to :const:`None`,
    #: it will **never** stop retrying.
    max_retries = 3

    #: Default time in seconds before a retry of the task should be
    #: executed.  3 minutes by default.
    default_retry_delay = 3 * 60

    #: Rate limit for this task type.  Examples: :const:`None` (no rate
    #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks
    #: a minute),`'100/h'` (hundred tasks an hour)
    rate_limit = None

    #: If enabled the worker won't store task state and return values
    #: for this task.  Defaults to the :setting:`task_ignore_result`
    #: setting.
    ignore_result = None

    #: If enabled the request will keep track of subtasks started by
    #: this task, and this information will be sent with the result
    #: (``result.children``).
    trail = True

    #: If enabled the worker will send monitoring events related to
    #: this task (but only if the worker is configured to send
    #: task related events).
    #: Note that this has no effect on the task-failure event case
    #: where a task is not registered (as it will have no task class
    #: to check this flag).
    send_events = True

    #: When enabled errors will be stored even if the task is otherwise
    #: configured to ignore results.
    store_errors_even_if_ignored = None

    #: The name of a serializer that are registered with
    #: :mod:`kombu.serialization.registry`.  Default is `'pickle'`.
    serializer = None

    #: Hard time limit.
    #: Defaults to the :setting:`task_time_limit` setting.
    time_limit = None

    #: Soft time limit.
    #: Defaults to the :setting:`task_soft_time_limit` setting.
    soft_time_limit = None

    #: The result store backend used for this task.
    backend = None

    #: If disabled this task won't be registered automatically.
    autoregister = True

    #: If enabled the task will report its status as 'started' when the task
    #: is executed by a worker.  Disabled by default as the normal behavior
    #: is to not report that level of granularity.  Tasks are either pending,
    #: finished, or waiting to be retried.
    #:
    #: Having a 'started' status can be useful for when there are long
    #: running tasks and there's a need to report what task is currently
    #: running.
    #:
    #: The application default can be overridden using the
    #: :setting:`task_track_started` setting.
    track_started = None

    #: When enabled messages for this task will be acknowledged **after**
    #: the task has been executed, and not *just before* (the
    #: default behavior).
    #:
    #: Please note that this means the task may be executed twice if the
    #: worker crashes mid execution.
    #:
    #: The application default can be overridden with the
    #: :setting:`task_acks_late` setting.
    acks_late = None

    #: Even if :attr:`acks_late` is enabled, the worker will
    #: acknowledge tasks when the worker process executing them abruptly
    #: exits or is signaled (e.g., :sig:`KILL`/:sig:`INT`, etc).
    #:
    #: Setting this to true allows the message to be re-queued instead,
    #: so that the task will execute again by the same worker, or another
    #: worker.
    #:
    #: Warning: Enabling this can cause message loops; make sure you know
    #: what you're doing.
    reject_on_worker_lost = None

    #: Tuple of expected exceptions.
    #:
    #: These are errors that are expected in normal operation
    #: and that shouldn't be regarded as a real error by the worker.
    #: Currently this means that the state will be updated to an error
    #: state, but the worker won't log the event as an error.
    throws = ()

    #: Default task expiry time.
    expires = None

    #: Max length of result representation used in logs and events.
    resultrepr_maxsize = 1024

    #: Task request stack, the current request will be the topmost.
    request_stack = None

    #: Some may expect a request to exist even if the task hasn't been
    #: called.  This should probably be deprecated.
    _default_request = None

    #: Deprecated attribute ``abstract`` here for compatibility.
    abstract = True

    _exec_options = None

    __bound__ = False

    from_config = (
        ('serializer', 'task_serializer'),
        ('rate_limit', 'task_default_rate_limit'),
        ('track_started', 'task_track_started'),
        ('acks_late', 'task_acks_late'),
        ('reject_on_worker_lost', 'task_reject_on_worker_lost'),
        ('ignore_result', 'task_ignore_result'),
        ('store_errors_even_if_ignored', 'task_store_errors_even_if_ignored'),
    )

    _backend = None  # set by backend property.

    # - Tasks are lazily bound, so that configuration is not set
    # - until the task is actually used

    @classmethod
    def bind(self, app):
        was_bound, self.__bound__ = self.__bound__, True
        self._app = app
        conf = app.conf
        self._exec_options = None  # clear option cache

        for attr_name, config_name in self.from_config:
            if getattr(self, attr_name, None) is None:
                setattr(self, attr_name, conf[config_name])

        # decorate with annotations from config.
        if not was_bound:
            self.annotate()

            from celery.utils.threads import LocalStack
            self.request_stack = LocalStack()

        # PeriodicTask uses this to add itself to the PeriodicTask schedule.
        self.on_bound(app)

        return app

    @classmethod
    def on_bound(self, app):
        """This method can be defined to do additional actions when the
        task class is bound to an app."""
        pass

    @classmethod
    def _get_app(self):
        if self._app is None:
            self._app = current_app
        if not self.__bound__:
            # The app property's __set__  method is not called
            # if Task.app is set (on the class), so must bind on use.
            self.bind(self._app)
        return self._app
    app = class_property(_get_app, bind)

    @classmethod
    def annotate(self):
        for d in resolve_all_annotations(self.app.annotations, self):
            for key, value in items(d):
                if key.startswith('@'):
                    self.add_around(key[1:], value)
                else:
                    setattr(self, key, value)

    @classmethod
    def add_around(self, attr, around):
        orig = getattr(self, attr)
        if getattr(orig, '__wrapped__', None):
            orig = orig.__wrapped__
        meth = around(orig)
        meth.__wrapped__ = orig
        setattr(self, attr, meth)

    def __call__(self, *args, **kwargs):
        _task_stack.push(self)
        self.push_request(args=args, kwargs=kwargs)
        try:
            # add self if this is a bound task
            if self.__self__ is not None:
                return self.run(self.__self__, *args, **kwargs)
            return self.run(*args, **kwargs)
        finally:
            self.pop_request()
            _task_stack.pop()

    def __reduce__(self):
        # - tasks are pickled into the name of the task only, and the reciever
        # - simply grabs it from the local registry.
        # - in later versions the module of the task is also included,
        # - and the receiving side tries to import that module so that
        # - it will work even if the task hasn't been registered.
        mod = type(self).__module__
        mod = mod if mod and mod in sys.modules else None
        return (_unpickle_task_v2, (self.name, mod), None)

    def run(self, *args, **kwargs):
        """The body of the task executed by workers."""
        raise NotImplementedError('Tasks must define the run method.')

    def start_strategy(self, app, consumer, **kwargs):
        return instantiate(self.Strategy, self, app, consumer, **kwargs)

    def delay(self, *args, **kwargs):
        """Star argument version of :meth:`apply_async`.

        Does not support the extra options enabled by :meth:`apply_async`.

        Arguments:
            *args (Any): Positional arguments passed on to the task.
            **kwargs (Any): Keyword arguments passed on to the task.
        Returns:
            celery.result.AsyncResult: Future promise.
        """
        return self.apply_async(args, kwargs)

    def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,
                    link=None, link_error=None, shadow=None, **options):
        """Apply tasks asynchronously by sending a message.

        Arguments:
            args (Tuple): The positional arguments to pass on to the task.

            kwargs (Dict): The keyword arguments to pass on to the task.

            countdown (float): Number of seconds into the future that the
                task should execute.  Defaults to immediate execution.

            eta (~datetime.datetime): Absolute time and date of when the task
                should be executed.  May not be specified if `countdown`
                is also supplied.

            expires (float, ~datetime.datetime): Datetime or
                seconds in the future for the task should expire.
                The task won't be executed after the expiration time.

            shadow (str): Override task name used in logs/monitoring.
                Default is retrieved from :meth:`shadow_name`.

            connection (kombu.Connection): Re-use existing broker connection
                instead of acquiring one from the connection pool.

            retry (bool): If enabled sending of the task message will be
                retried in the event of connection loss or failure.
                Default is taken from the :setting:`task_publish_retry`
                setting.  Note that you need to handle the
                producer/connection manually for this to work.

            retry_policy (Mapping): Override the retry policy used.
                See the :setting:`task_publish_retry_policy` setting.

            queue (str, kombu.Queue): The queue to route the task to.
                This must be a key present in :setting:`task_queues`, or
                :setting:`task_create_missing_queues` must be
                enabled.  See :ref:`guide-routing` for more
                information.

            exchange (str, kombu.Exchange): Named custom exchange to send the
                task to.  Usually not used in combination with the ``queue``
                argument.

            routing_key (str): Custom routing key used to route the task to a
                worker server.  If in combination with a ``queue`` argument
                only used to specify custom routing keys to topic exchanges.

            priority (int): The task priority, a number between 0 and 9.
                Defaults to the :attr:`priority` attribute.

            serializer (str): Serialization method to use.
                Can be `pickle`, `json`, `yaml`, `msgpack` or any custom
                serialization method that's been registered
                with :mod:`kombu.serialization.registry`.
                Defaults to the :attr:`serializer` attribute.

            compression (str): Optional compression method
                to use.  Can be one of ``zlib``, ``bzip2``,
                or any custom compression methods registered with
                :func:`kombu.compression.register`.
                Defaults to the :setting:`task_compression` setting.

            link (~@Signature): A single, or a list of tasks signatures
                to apply if the task returns successfully.

            link_error (~@Signature): A single, or a list of task signatures
                to apply if an error occurs while executing the task.

            producer (kombu.Producer): custom producer to use when publishing
                the task.

            add_to_parent (bool): If set to True (default) and the task
                is applied while executing another task, then the result
                will be appended to the parent tasks ``request.children``
                attribute.  Trailing can also be disabled by default using the
                :attr:`trail` attribute

            publisher (kombu.Producer): Deprecated alias to ``producer``.

            headers (Dict): Message headers to be included in the message.

        Returns:
            ~@AsyncResult: Future promise.

        Note:
            Also supports all keyword arguments supported by
            :meth:`kombu.Producer.publish`.
        """
        try:
            check_arguments = self.__header__
        except AttributeError:  # pragma: no cover
            pass
        else:
            check_arguments(*(args or ()), **(kwargs or {}))

        app = self._get_app()
        if app.conf.task_always_eager:
            return self.apply(args, kwargs, task_id=task_id or uuid(),
                              link=link, link_error=link_error, **options)
        # add 'self' if this is a "task_method".
        if self.__self__ is not None:
            args = args if isinstance(args, tuple) else tuple(args or ())
            args = (self.__self__,) + args
            shadow = shadow or self.shadow_name(args, kwargs, options)

        preopts = self._get_exec_options()
        options = dict(preopts, **options) if options else preopts
        return app.send_task(
            self.name, args, kwargs, task_id=task_id, producer=producer,
            link=link, link_error=link_error, result_cls=self.AsyncResult,
            shadow=shadow, task_type=self,
            **options
        )

    def shadow_name(self, args, kwargs, options):
        """Override for custom task name in worker logs/monitoring.

        Example:
            .. code-block:: python

                from celery.utils.imports import qualname

                def shadow_name(task, args, kwargs, options):
                    return qualname(args[0])

                @app.task(shadow_name=shadow_name, serializer='pickle')
                def apply_function_async(fun, *args, **kwargs):
                    return fun(*args, **kwargs)

        Arguments:
            args (Tuple): Task positional arguments.
            kwargs (Dict): Task keyword arguments.
            options (Dict): Task execution options.
        """
        pass

    def signature_from_request(self, request=None, args=None, kwargs=None,
                               queue=None, **extra_options):
        request = self.request if request is None else request
        args = request.args if args is None else args
        kwargs = request.kwargs if kwargs is None else kwargs
        options = request.as_execution_options()
        options.update(
            {'queue': queue} if queue else (request.delivery_info or {}),
        )
        return self.signature(
            args, kwargs, options, type=self, **extra_options
        )
    subtask_from_request = signature_from_request  # XXX compat

    def retry(self, args=None, kwargs=None, exc=None, throw=True,
              eta=None, countdown=None, max_retries=None, **options):
        """Retry the task.

        Example:
            >>> from imaginary_twitter_lib import Twitter
            >>> from proj.celery import app

            >>> @app.task(bind=True)
            ... def tweet(self, auth, message):
            ...     twitter = Twitter(oauth=auth)
            ...     try:
            ...         twitter.post_status_update(message)
            ...     except twitter.FailWhale as exc:
            ...         # Retry in 5 minutes.
            ...         raise self.retry(countdown=60 * 5, exc=exc)

        Note:
            Although the task will never return above as `retry` raises an
            exception to notify the worker, we use `raise` in front of the
            retry to convey that the rest of the block won't be executed.

        Arguments:
            args (Tuple): Positional arguments to retry with.
            kwargs (Dict): Keyword arguments to retry with.
            exc (Exception): Custom exception to report when the max restart
                limit has been exceeded (default:
                :exc:`~@MaxRetriesExceededError`).

                If this argument is set and retry is called while
                an exception was raised (``sys.exc_info()`` is set)
                it will attempt to re-raise the current exception.

                If no exception was raised it will raise the ``exc``
                argument provided.
            countdown (float): Time in seconds to delay the retry for.
            eta (~datetime.dateime): Explicit time and date to run the
                retry at.
            max_retries (int): If set, overrides the default retry limit for
                this execution.  Changes to this parameter don't propagate to
                subsequent task retry attempts.  A value of :const:`None`,
                means "use the default", so if you want infinite retries you'd
                have to set the :attr:`max_retries` attribute of the task to
                :const:`None` first.
            time_limit (int): If set, overrides the default time limit.
            soft_time_limit (int): If set, overrides the default soft
                time limit.
            throw (bool): If this is :const:`False`, don't raise the
                :exc:`~@Retry` exception, that tells the worker to mark
                the task as being retried.  Note that this means the task
                will be marked as failed if the task raises an exception,
                or successful if it returns after the retry call.
            **options (Any): Extra options to pass on to :meth:`apply_async`.

        Raises:
            celery.exceptions.Retry:
                To tell the worker that the task has been re-sent for retry.
                This always happens, unless the `throw` keyword argument
                has been explicitly set to :const:`False`, and is considered
                normal operation.
        """
        request = self.request
        retries = request.retries + 1
        max_retries = self.max_retries if max_retries is None else max_retries

        # Not in worker or emulated by (apply/always_eager),
        # so just raise the original exception.
        if request.called_directly:
            # raises orig stack if PyErr_Occurred,
            # and augments with exc' if that argument is defined.
            raise_with_context(exc or Retry('Task can be retried', None))

        if not eta and countdown is None:
            countdown = self.default_retry_delay

        is_eager = request.is_eager
        S = self.signature_from_request(
            request, args, kwargs,
            countdown=countdown, eta=eta, retries=retries,
            **options
        )

        if max_retries is not None and retries > max_retries:
            if exc:
                # On Py3: will augment any current exception with
                # the exc' argument provided (raise exc from orig)
                raise_with_context(exc)
            raise self.MaxRetriesExceededError(
                "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
                    self.name, request.id, S.args, S.kwargs))

        ret = Retry(exc=exc, when=eta or countdown)

        if is_eager:
            # if task was executed eagerly using apply(),
            # then the retry must also be executed eagerly.
            S.apply().get()
            if throw:
                raise ret
            return ret

        try:
            S.apply_async()
        except Exception as exc:
            raise Reject(exc, requeue=False)
        if throw:
            raise ret
        return ret

    def apply(self, args=None, kwargs=None,
              link=None, link_error=None,
              task_id=None, retries=None, throw=None,
              logfile=None, loglevel=None, headers=None, **options):
        """Execute this task locally, by blocking until the task returns.

        Arguments:
            args (Tuple): positional arguments passed on to the task.
            kwargs (Dict): keyword arguments passed on to the task.
            throw (bool): Re-raise task exceptions.
                Defaults to the :setting:`task_eager_propagates` setting.

        Returns:
            celery.result.EagerResult: pre-evaluated result.
        """
        # trace imports Task, so need to import inline.
        from celery.app.trace import build_tracer

        app = self._get_app()
        args = args or ()
        # add 'self' if this is a bound method.
        if self.__self__ is not None:
            args = (self.__self__,) + tuple(args)
        kwargs = kwargs or {}
        task_id = task_id or uuid()
        retries = retries or 0
        if throw is None:
            throw = app.conf.task_eager_propagates

        # Make sure we get the task instance, not class.
        task = app._tasks[self.name]

        request = {
            'id': task_id,
            'retries': retries,
            'is_eager': True,
            'logfile': logfile,
            'loglevel': loglevel or 0,
            'callbacks': maybe_list(link),
            'errbacks': maybe_list(link_error),
            'headers': headers,
            'delivery_info': {'is_eager': True},
        }
        tb = None
        tracer = build_tracer(
            task.name, task, eager=True,
            propagate=throw, app=self._get_app(),
        )
        ret = tracer(task_id, args, kwargs, request)
        retval = ret.retval
        if isinstance(retval, ExceptionInfo):
            retval, tb = retval.exception, retval.traceback
        state = states.SUCCESS if ret.info is None else ret.info.state
        return EagerResult(task_id, retval, state, traceback=tb)

    def AsyncResult(self, task_id, **kwargs):
        """Get AsyncResult instance for this kind of task.

        Arguments:
            task_id (str): Task id to get result for.
        """
        return self._get_app().AsyncResult(task_id, backend=self.backend,
                                           task_name=self.name, **kwargs)

    def signature(self, args=None, *starargs, **starkwargs):
        """Return :class:`~celery.signature` object for
        this task, wrapping arguments and execution options
        for a single task invocation."""
        starkwargs.setdefault('app', self.app)
        return signature(self, args, *starargs, **starkwargs)
    subtask = signature

    def s(self, *args, **kwargs):
        """``.s(*a, **k) -> .signature(a, k)``"""
        return self.signature(args, kwargs)

    def si(self, *args, **kwargs):
        """``.si(*a, **k) -> .signature(a, k, immutable=True)``"""
        return self.signature(args, kwargs, immutable=True)

    def chunks(self, it, n):
        """Creates a :class:`~celery.canvas.chunks` task for this task."""
        from celery import chunks
        return chunks(self.s(), it, n, app=self.app)

    def map(self, it):
        """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
        from celery import xmap
        return xmap(self.s(), it, app=self.app)

    def starmap(self, it):
        """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
        from celery import xstarmap
        return xstarmap(self.s(), it, app=self.app)

    def send_event(self, type_, **fields):
        req = self.request
        with self.app.events.default_dispatcher(hostname=req.hostname) as d:
            return d.send(type_, uuid=req.id, **fields)

    def replace(self, sig):
        """Replace the current task, with a new task inheriting the
        same task id.

        .. versionadded:: 4.0

        Arguments:
            sig (~@Signature): signature to replace with.

        Raises:
            ~@Ignore: This is always raised, so the best practice
            is to always use ``raise self.replace(...)`` to convey
            to the reader that the task won't continue after being replaced.
        """
        chord = self.request.chord
        if 'chord' in sig.options:
            if chord:
                chord = sig.options['chord'] | chord
            else:
                chord = sig.options['chord']

        if isinstance(sig, group):
            sig |= self.app.tasks['celery.accumulate'].s(index=0).set(
                chord=chord,
                link=self.request.callbacks,
                link_error=self.request.errbacks,
            )
            chord = None

        if self.request.chain:
            for t in self.request.chain:
                sig |= signature(t)

        sig.freeze(self.request.id,
                   group_id=self.request.group,
                   chord=chord,
                   root_id=self.request.root_id)

        sig.delay()
        raise Ignore('Replaced by new task')

    def add_to_chord(self, sig, lazy=False):
        """Add signature to the chord the current task is a member of.

        .. versionadded:: 4.0

        Currently only supported by the Redis result backend.

        Arguments:
            sig (~@Signature): Signature to extend chord with.
            lazy (bool): If enabled the new task won't actually be called,
                and ``sig.delay()`` must be called manually.
        """
        if not self.request.chord:
            raise ValueError('Current task is not member of any chord')
        result = sig.freeze(group_id=self.request.group,
                            chord=self.request.chord,
                            root_id=self.request.root_id)
        self.backend.add_to_chord(self.request.group, result)
        return sig.delay() if not lazy else sig

    def update_state(self, task_id=None, state=None, meta=None):
        """Update task state.

        Arguments:
            task_id (str): Id of the task to update.
                Defaults to the id of the current task.
            state (str): New state.
            meta (Dict): State meta-data.
        """
        if task_id is None:
            task_id = self.request.id
        self.backend.store_result(task_id, meta, state)

    def on_success(self, retval, task_id, args, kwargs):
        """Success handler.

        Run by the worker if the task executes successfully.

        Arguments:
            retval (Any): The return value of the task.
            task_id (str): Unique id of the executed task.
            args (Tuple): Original arguments for the executed task.
            kwargs (Dict): Original keyword arguments for the executed task.

        Returns:
            None: The return value of this handler is ignored.
        """
        pass

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        """Retry handler.

        This is run by the worker when the task is to be retried.

        Arguments:
            exc (Exception): The exception sent to :meth:`retry`.
            task_id (str): Unique id of the retried task.
            args (Tuple): Original arguments for the retried task.
            kwargs (Dict): Original keyword arguments for the retried task.
            einfo (~billiard.einfo.ExceptionInfo): Exception information.

        Returns:
            None: The return value of this handler is ignored.
        """
        pass

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        """Error handler.

        This is run by the worker when the task fails.

        Arguments:
            exc (Exception): The exception raised by the task.
            task_id (str): Unique id of the failed task.
            args (Tuple): Original arguments for the task that failed.
            kwargs (Dict): Original keyword arguments for the task that failed.
            einfo (~billiard.einfo.ExceptionInfo): Exception information.

        Returns:
            None: The return value of this handler is ignored.
        """
        pass

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        """Handler called after the task returns.

        Arguments:
            status (str): Current task state.
            retval (Any): Task return value/exception.
            task_id (str): Unique id of the task.
            args (Tuple): Original arguments for the task.
            kwargs (Dict): Original keyword arguments for the task.
            einfo (~billiard.einfo.ExceptionInfo): Exception information.

        Returns:
            None: The return value of this handler is ignored.
        """
        pass

    def add_trail(self, result):
        if self.trail:
            self.request.children.append(result)
        return result

    def push_request(self, *args, **kwargs):
        self.request_stack.push(Context(*args, **kwargs))

    def pop_request(self):
        self.request_stack.pop()

    def __repr__(self):
        """`repr(task)`"""
        return _reprtask(self, R_SELF_TASK if self.__self__ else R_INSTANCE)

    def _get_request(self):
        """Get current request object."""
        req = self.request_stack.top
        if req is None:
            # task was not called, but some may still expect a request
            # to be there, perhaps that should be deprecated.
            if self._default_request is None:
                self._default_request = Context()
            return self._default_request
        return req
    request = property(_get_request)

    def _get_exec_options(self):
        if self._exec_options is None:
            self._exec_options = extract_exec_options(self)
        return self._exec_options

    @property
    def backend(self):
        backend = self._backend
        if backend is None:
            return self.app.backend
        return backend

    @backend.setter
    def backend(self, value):  # noqa
        self._backend = value

    @property
    def __name__(self):
        return self.__class__.__name__
Example #5
0
class Task(object):
    """Task base class.

    When called tasks apply the :meth:`run` method.  This method must
    be defined by all tasks (that is unless the :meth:`__call__` method
    is overridden).

    """
    __metaclass__ = TaskType
    __trace__ = None

    ErrorMail = ErrorMail
    MaxRetriesExceededError = MaxRetriesExceededError

    #: Execution strategy used, or the qualified name of one.
    Strategy = 'celery.worker.strategy:default'

    #: This is the instance bound to if the task is a method of a class.
    __self__ = None

    #: The application instance associated with this task class.
    _app = None

    #: Name of the task.
    name = None

    #: If :const:`True` the task is an abstract base class.
    abstract = True

    #: If disabled the worker will not forward magic keyword arguments.
    #: Deprecated and scheduled for removal in v4.0.
    accept_magic_kwargs = False

    #: Maximum number of retries before giving up.  If set to :const:`None`,
    #: it will **never** stop retrying.
    max_retries = 3

    #: Default time in seconds before a retry of the task should be
    #: executed.  3 minutes by default.
    default_retry_delay = 3 * 60

    #: Rate limit for this task type.  Examples: :const:`None` (no rate
    #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks
    #: a minute),`'100/h'` (hundred tasks an hour)
    rate_limit = None

    #: If enabled the worker will not store task state and return values
    #: for this task.  Defaults to the :setting:`CELERY_IGNORE_RESULT`
    #: setting.
    ignore_result = False

    #: When enabled errors will be stored even if the task is otherwise
    #: configured to ignore results.
    store_errors_even_if_ignored = False

    #: If enabled an email will be sent to :setting:`ADMINS` whenever a task
    #: of this type fails.
    send_error_emails = False

    #: The name of a serializer that are registered with
    #: :mod:`kombu.serialization.registry`.  Default is `'pickle'`.
    serializer = None

    #: Hard time limit.
    #: Defaults to the :setting:`CELERY_TASK_TIME_LIMIT` setting.
    time_limit = None

    #: Soft time limit.
    #: Defaults to the :setting:`CELERY_TASK_SOFT_TIME_LIMIT` setting.
    soft_time_limit = None

    #: The result store backend used for this task.
    backend = None

    #: If disabled this task won't be registered automatically.
    autoregister = True

    #: If enabled the task will report its status as 'started' when the task
    #: is executed by a worker.  Disabled by default as the normal behaviour
    #: is to not report that level of granularity.  Tasks are either pending,
    #: finished, or waiting to be retried.
    #:
    #: Having a 'started' status can be useful for when there are long
    #: running tasks and there is a need to report which task is currently
    #: running.
    #:
    #: The application default can be overridden using the
    #: :setting:`CELERY_TRACK_STARTED` setting.
    track_started = False

    #: When enabled messages for this task will be acknowledged **after**
    #: the task has been executed, and not *just before* which is the
    #: default behavior.
    #:
    #: Please note that this means the task may be executed twice if the
    #: worker crashes mid execution (which may be acceptable for some
    #: applications).
    #:
    #: The application default can be overridden with the
    #: :setting:`CELERY_ACKS_LATE` setting.
    acks_late = None

    #: Default task expiry time.
    expires = None

    __bound__ = False

    from_config = (
        ('send_error_emails', 'CELERY_SEND_TASK_ERROR_EMAILS'),
        ('serializer', 'CELERY_TASK_SERIALIZER'),
        ('rate_limit', 'CELERY_DEFAULT_RATE_LIMIT'),
        ('track_started', 'CELERY_TRACK_STARTED'),
        ('acks_late', 'CELERY_ACKS_LATE'),
        ('ignore_result', 'CELERY_IGNORE_RESULT'),
        ('store_errors_even_if_ignored',
            'CELERY_STORE_ERRORS_EVEN_IF_IGNORED'),
    )

    __bound__ = False

    # - Tasks are lazily bound, so that configuration is not set
    # - until the task is actually used

    @classmethod
    def bind(self, app):
        was_bound, self.__bound__ = self.__bound__, True
        self._app = app
        conf = app.conf

        for attr_name, config_name in self.from_config:
            if getattr(self, attr_name, None) is None:
                setattr(self, attr_name, conf[config_name])
        if self.accept_magic_kwargs is None:
            self.accept_magic_kwargs = app.accept_magic_kwargs
        if self.backend is None:
            self.backend = app.backend

        # decorate with annotations from config.
        if not was_bound:
            self.annotate()

        from celery.utils.threads import LocalStack
        self.request_stack = LocalStack()
        self.request_stack.push(Context())

        # PeriodicTask uses this to add itself to the PeriodicTask schedule.
        self.on_bound(app)

        return app

    @classmethod
    def on_bound(self, app):
        """This method can be defined to do additional actions when the
        task class is bound to an app."""
        pass

    @classmethod
    def _get_app(self):
        if not self.__bound__ or self._app is None:
            # The app property's __set__  method is not called
            # if Task.app is set (on the class), so must bind on use.
            self.bind(current_app)
        return self._app
    app = class_property(_get_app, bind)

    @classmethod
    def annotate(self):
        for d in resolve_all_annotations(self.app.annotations, self):
            for key, value in d.iteritems():
                if key.startswith('@'):
                    self.add_around(key[1:], value)
                else:
                    setattr(self, key, value)

    @classmethod
    def add_around(self, attr, around):
        orig = getattr(self, attr)
        if getattr(orig, '__wrapped__', None):
            orig = orig.__wrapped__
        meth = around(orig)
        meth.__wrapped__ = orig
        setattr(self, attr, meth)

    def __call__(self, *args, **kwargs):
        _task_stack.push(self)
        self.push_request()
        try:
            return self.run(*args, **kwargs)
        finally:
            self.pop_request()
            _task_stack.pop()

    # - tasks are pickled into the name of the task only, and the reciever
    # - simply grabs it from the local registry.
    def __reduce__(self):
        return (_unpickle_task, (self.name, ), None)

    def run(self, *args, **kwargs):
        """The body of the task executed by workers."""
        raise NotImplementedError('Tasks must define the run method.')

    def start_strategy(self, app, consumer):
        return instantiate(self.Strategy, self, app, consumer)

    def delay(self, *args, **kwargs):
        """Star argument version of :meth:`apply_async`.

        Does not support the extra options enabled by :meth:`apply_async`.

        :param \*args: positional arguments passed on to the task.
        :param \*\*kwargs: keyword arguments passed on to the task.

        :returns :class:`celery.result.AsyncResult`:

        """
        return self.apply_async(args, kwargs)

    def apply_async(self, args=None, kwargs=None,
            task_id=None, producer=None, connection=None, router=None,
            link=None, link_error=None, publisher=None, add_to_parent=True,
            **options):
        """Apply tasks asynchronously by sending a message.

        :keyword args: The positional arguments to pass on to the
                       task (a :class:`list` or :class:`tuple`).

        :keyword kwargs: The keyword arguments to pass on to the
                         task (a :class:`dict`)

        :keyword countdown: Number of seconds into the future that the
                            task should execute. Defaults to immediate
                            execution (do not confuse with the
                            `immediate` flag, as they are unrelated).

        :keyword eta: A :class:`~datetime.datetime` object describing
                      the absolute time and date of when the task should
                      be executed.  May not be specified if `countdown`
                      is also supplied.  (Do not confuse this with the
                      `immediate` flag, as they are unrelated).

        :keyword expires: Either a :class:`int`, describing the number of
                          seconds, or a :class:`~datetime.datetime` object
                          that describes the absolute time and date of when
                          the task should expire.  The task will not be
                          executed after the expiration time.

        :keyword connection: Re-use existing broker connection instead
                             of establishing a new one.

        :keyword retry: If enabled sending of the task message will be retried
                        in the event of connection loss or failure.  Default
                        is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
                        setting.  Note you need to handle the
                        producer/connection manually for this to work.

        :keyword retry_policy:  Override the retry policy used.  See the
                                :setting:`CELERY_TASK_PUBLISH_RETRY` setting.

        :keyword routing_key: The routing key used to route the task to a
                              worker server.  Defaults to the
                              :attr:`routing_key` attribute.

        :keyword exchange: The named exchange to send the task to.
                           Defaults to the :attr:`exchange` attribute.

        :keyword exchange_type: The exchange type to initialize the exchange
                                if not already declared.  Defaults to the
                                :attr:`exchange_type` attribute.

        :keyword immediate: Request immediate delivery.  Will raise an
                            exception if the task cannot be routed to a worker
                            immediately.  (Do not confuse this parameter with
                            the `countdown` and `eta` settings, as they are
                            unrelated).  Defaults to the :attr:`immediate`
                            attribute.

        :keyword mandatory: Mandatory routing. Raises an exception if
                            there's no running workers able to take on this
                            task.  Defaults to the :attr:`mandatory`
                            attribute.

        :keyword priority: The task priority, a number between 0 and 9.
                           Defaults to the :attr:`priority` attribute.

        :keyword serializer: A string identifying the default
                             serialization method to use.  Can be `pickle`,
                             `json`, `yaml`, `msgpack` or any custom
                             serialization method that has been registered
                             with :mod:`kombu.serialization.registry`.
                             Defaults to the :attr:`serializer` attribute.

        :keyword compression: A string identifying the compression method
                              to use.  Can be one of ``zlib``, ``bzip2``,
                              or any custom compression methods registered with
                              :func:`kombu.compression.register`. Defaults to
                              the :setting:`CELERY_MESSAGE_COMPRESSION`
                              setting.
        :keyword link: A single, or a list of subtasks to apply if the
                       task exits successfully.
        :keyword link_error: A single, or a list of subtasks to apply
                      if an error occurs while executing the task.

        :keyword producer: :class:[email protected]` instance to use.
        :keyword add_to_parent: If set to True (default) and the task
            is applied while executing another task, then the result
            will be appended to the parent tasks ``request.children``
            attribute.
        :keyword publisher: Deprecated alias to ``producer``.

        .. note::
            If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
            be replaced by a local :func:`apply` call instead.

        """
        producer = producer or publisher
        app = self._get_app()
        router = router or self.app.amqp.router
        conf = app.conf

        # add 'self' if this is a bound method.
        if self.__self__ is not None:
            args = (self.__self__, ) + tuple(args)

        if conf.CELERY_ALWAYS_EAGER:
            return self.apply(args, kwargs, task_id=task_id, **options)
        options = dict(extract_exec_options(self), **options)
        options = router.route(options, self.name, args, kwargs)

        if connection:
            producer = app.amqp.TaskProducer(connection)
        with app.default_producer(producer) as P:
            evd = None
            if conf.CELERY_SEND_TASK_SENT_EVENT:
                evd = app.events.Dispatcher(channel=P.channel,
                                            buffer_while_offline=False)

            task_id = P.publish_task(self.name, args, kwargs,
                                     task_id=task_id,
                                     event_dispatcher=evd,
                                     callbacks=maybe_list(link),
                                     errbacks=maybe_list(link_error),
                                     **options)
        result = self.AsyncResult(task_id)
        if add_to_parent:
            parent = get_current_worker_task()
            if parent:
                parent.request.children.append(result)
        return result

    def retry(self, args=None, kwargs=None, exc=None, throw=True,
            eta=None, countdown=None, max_retries=None, **options):
        """Retry the task.

        :param args: Positional arguments to retry with.
        :param kwargs: Keyword arguments to retry with.
        :keyword exc: Optional exception to raise instead of
                      :exc:`~celery.exceptions.MaxRetriesExceededError`
                      when the max restart limit has been exceeded.
        :keyword countdown: Time in seconds to delay the retry for.
        :keyword eta: Explicit time and date to run the retry at
                      (must be a :class:`~datetime.datetime` instance).
        :keyword max_retries: If set, overrides the default retry limit.
        :keyword \*\*options: Any extra options to pass on to
                              meth:`apply_async`.
        :keyword throw: If this is :const:`False`, do not raise the
                        :exc:`~celery.exceptions.RetryTaskError` exception,
                        that tells the worker to mark the task as being
                        retried.  Note that this means the task will be
                        marked as failed if the task raises an exception,
                        or successful if it returns.

        :raises celery.exceptions.RetryTaskError: To tell the worker that
            the task has been re-sent for retry. This always happens,
            unless the `throw` keyword argument has been explicitly set
            to :const:`False`, and is considered normal operation.

        **Example**

        .. code-block:: python

            >>> @task()
            >>> def tweet(auth, message):
            ...     twitter = Twitter(oauth=auth)
            ...     try:
            ...         twitter.post_status_update(message)
            ...     except twitter.FailWhale, exc:
            ...         # Retry in 5 minutes.
            ...         raise tweet.retry(countdown=60 * 5, exc=exc)

        Although the task will never return above as `retry` raises an
        exception to notify the worker, we use `return` in front of the retry
        to convey that the rest of the block will not be executed.

        """
        request = self.request
        max_retries = self.max_retries if max_retries is None else max_retries
        args = request.args if args is None else args
        kwargs = request.kwargs if kwargs is None else kwargs
        delivery_info = request.delivery_info

        # Not in worker or emulated by (apply/always_eager),
        # so just raise the original exception.
        if request.called_directly:
            maybe_reraise()
            raise exc or RetryTaskError('Task can be retried', None)

        if delivery_info:
            options.setdefault('exchange', delivery_info.get('exchange'))
            options.setdefault('routing_key', delivery_info.get('routing_key'))

        if not eta and countdown is None:
            countdown = self.default_retry_delay

        options.update({'retries': request.retries + 1,
                        'task_id': request.id,
                        'countdown': countdown,
                        'eta': eta})

        if max_retries is not None and options['retries'] > max_retries:
            if exc:
                maybe_reraise()
            raise self.MaxRetriesExceededError(
                    """Can't retry %s[%s] args:%s kwargs:%s""" % (
                        self.name, options['task_id'], args, kwargs))

        # If task was executed eagerly using apply(),
        # then the retry must also be executed eagerly.
        if request.is_eager:
            self.apply(args=args, kwargs=kwargs, **options).get()
        else:
            self.apply_async(args=args, kwargs=kwargs, **options)
        ret = RetryTaskError(exc=exc, when=eta or countdown)
        if throw:
            raise ret
        return ret

    def apply(self, args=None, kwargs=None, **options):
        """Execute this task locally, by blocking until the task returns.

        :param args: positional arguments passed on to the task.
        :param kwargs: keyword arguments passed on to the task.
        :keyword throw: Re-raise task exceptions.  Defaults to
                        the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
                        setting.

        :rtype :class:`celery.result.EagerResult`:

        """
        # trace imports Task, so need to import inline.
        from celery.task.trace import eager_trace_task

        app = self._get_app()
        args = args or []
        kwargs = kwargs or {}
        task_id = options.get('task_id') or uuid()
        retries = options.get('retries', 0)
        throw = app.either('CELERY_EAGER_PROPAGATES_EXCEPTIONS',
                           options.pop('throw', None))

        # Make sure we get the task instance, not class.
        task = app._tasks[self.name]

        request = {'id': task_id,
                   'retries': retries,
                   'is_eager': True,
                   'logfile': options.get('logfile'),
                   'loglevel': options.get('loglevel', 0),
                   'delivery_info': {'is_eager': True}}
        if self.accept_magic_kwargs:
            default_kwargs = {'task_name': task.name,
                              'task_id': task_id,
                              'task_retries': retries,
                              'task_is_eager': True,
                              'logfile': options.get('logfile'),
                              'loglevel': options.get('loglevel', 0),
                              'delivery_info': {'is_eager': True}}
            supported_keys = fun_takes_kwargs(task.run, default_kwargs)
            extend_with = dict((key, val)
                                    for key, val in default_kwargs.items()
                                        if key in supported_keys)
            kwargs.update(extend_with)

        tb = None
        retval, info = eager_trace_task(task, task_id, args, kwargs,
                                        request=request, propagate=throw)
        if isinstance(retval, ExceptionInfo):
            retval, tb = retval.exception, retval.traceback
        state = states.SUCCESS if info is None else info.state
        return EagerResult(task_id, retval, state, traceback=tb)

    def AsyncResult(self, task_id):
        """Get AsyncResult instance for this kind of task.

        :param task_id: Task id to get result for.

        """
        return self._get_app().AsyncResult(task_id, backend=self.backend,
                                                    task_name=self.name)

    def subtask(self, *args, **kwargs):
        """Returns :class:`~celery.subtask` object for
        this task, wrapping arguments and execution options
        for a single task invocation."""
        from celery.canvas import subtask
        return subtask(self, *args, **kwargs)

    def s(self, *args, **kwargs):
        """``.s(*a, **k) -> .subtask(a, k)``"""
        return self.subtask(args, kwargs)

    def si(self, *args, **kwargs):
        """``.si(*a, **k) -> .subtask(a, k, immutable=True)``"""
        return self.subtask(args, kwargs, immutable=True)

    def chunks(self, it, n):
        """Creates a :class:`~celery.canvas.chunks` task for this task."""
        from celery import chunks
        return chunks(self.s(), it, n)

    def map(self, it):
        """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
        from celery import xmap
        return xmap(self.s(), it)

    def starmap(self, it):
        """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
        from celery import xstarmap
        return xstarmap(self.s(), it)

    def update_state(self, task_id=None, state=None, meta=None):
        """Update task state.

        :keyword task_id: Id of the task to update, defaults to the
                          id of the current task
        :keyword state: New state (:class:`str`).
        :keyword meta: State metadata (:class:`dict`).



        """
        if task_id is None:
            task_id = self.request.id
        self.backend.store_result(task_id, meta, state)

    def on_success(self, retval, task_id, args, kwargs):
        """Success handler.

        Run by the worker if the task executes successfully.

        :param retval: The return value of the task.
        :param task_id: Unique id of the executed task.
        :param args: Original arguments for the executed task.
        :param kwargs: Original keyword arguments for the executed task.

        The return value of this handler is ignored.

        """
        pass

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        """Retry handler.

        This is run by the worker when the task is to be retried.

        :param exc: The exception sent to :meth:`retry`.
        :param task_id: Unique id of the retried task.
        :param args: Original arguments for the retried task.
        :param kwargs: Original keyword arguments for the retried task.

        :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
                        instance, containing the traceback.

        The return value of this handler is ignored.

        """
        pass

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        """Error handler.

        This is run by the worker when the task fails.

        :param exc: The exception raised by the task.
        :param task_id: Unique id of the failed task.
        :param args: Original arguments for the task that failed.
        :param kwargs: Original keyword arguments for the task
                       that failed.

        :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
                        instance, containing the traceback.

        The return value of this handler is ignored.

        """
        pass

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        """Handler called after the task returns.

        :param status: Current task state.
        :param retval: Task return value/exception.
        :param task_id: Unique id of the task.
        :param args: Original arguments for the task that failed.
        :param kwargs: Original keyword arguments for the task
                       that failed.

        :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
                        instance, containing the traceback (if any).

        The return value of this handler is ignored.

        """
        pass

    def send_error_email(self, context, exc, **kwargs):
        if self.send_error_emails and \
                not getattr(self, 'disable_error_emails', None):
            self.ErrorMail(self, **kwargs).send(context, exc)

    def execute(self, request, pool, loglevel, logfile, **kwargs):
        """The method the worker calls to execute the task.

        :param request: A :class:`~celery.worker.job.Request`.
        :param pool: A task pool.
        :param loglevel: Current loglevel.
        :param logfile: Name of the currently used logfile.

        :keyword consumer: The :class:`~celery.worker.consumer.Consumer`.

        """
        request.execute_using_pool(pool, loglevel, logfile)

    def push_request(self, *args, **kwargs):
        self.request_stack.push(Context(*args, **kwargs))

    def pop_request(self):
        self.request_stack.pop()

    def __repr__(self):
        """`repr(task)`"""
        return '<@task: %s>' % (self.name, )

    @property
    def request(self):
        """Current request object."""
        return self.request_stack.top

    @property
    def __name__(self):
        return self.__class__.__name__
Example #6
0
class Task(object):
    """Task base class.

    When called tasks apply the :meth:`run` method.  This method must
    be defined by all tasks (that is unless the :meth:`__call__` method
    is overridden).

    """
    __trace__ = None
    __v2_compat__ = False  # set by old base in celery.task.base

    ErrorMail = ErrorMail
    MaxRetriesExceededError = MaxRetriesExceededError

    #: Execution strategy used, or the qualified name of one.
    Strategy = 'celery.worker.strategy:default'

    #: This is the instance bound to if the task is a method of a class.
    __self__ = None

    #: The application instance associated with this task class.
    _app = None

    #: Name of the task.
    name = None

    #: If :const:`True` the task is an abstract base class.
    abstract = True

    #: Maximum number of retries before giving up.  If set to :const:`None`,
    #: it will **never** stop retrying.
    max_retries = 3

    #: Default time in seconds before a retry of the task should be
    #: executed.  3 minutes by default.
    default_retry_delay = 3 * 60

    #: Rate limit for this task type.  Examples: :const:`None` (no rate
    #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks
    #: a minute),`'100/h'` (hundred tasks an hour)
    rate_limit = None

    #: If enabled the worker will not store task state and return values
    #: for this task.  Defaults to the :setting:`CELERY_IGNORE_RESULT`
    #: setting.
    ignore_result = None

    #: If enabled the request will keep track of subtasks started by
    #: this task, and this information will be sent with the result
    #: (``result.children``).
    trail = True

    #: When enabled errors will be stored even if the task is otherwise
    #: configured to ignore results.
    store_errors_even_if_ignored = None

    #: If enabled an email will be sent to :setting:`ADMINS` whenever a task
    #: of this type fails.
    send_error_emails = None

    #: The name of a serializer that are registered with
    #: :mod:`kombu.serialization.registry`.  Default is `'pickle'`.
    serializer = None

    #: Hard time limit.
    #: Defaults to the :setting:`CELERYD_TASK_TIME_LIMIT` setting.
    time_limit = None

    #: Soft time limit.
    #: Defaults to the :setting:`CELERYD_TASK_SOFT_TIME_LIMIT` setting.
    soft_time_limit = None

    #: The result store backend used for this task.
    backend = None

    #: If disabled this task won't be registered automatically.
    autoregister = True

    #: If enabled the task will report its status as 'started' when the task
    #: is executed by a worker.  Disabled by default as the normal behaviour
    #: is to not report that level of granularity.  Tasks are either pending,
    #: finished, or waiting to be retried.
    #:
    #: Having a 'started' status can be useful for when there are long
    #: running tasks and there is a need to report which task is currently
    #: running.
    #:
    #: The application default can be overridden using the
    #: :setting:`CELERY_TRACK_STARTED` setting.
    track_started = None

    #: When enabled messages for this task will be acknowledged **after**
    #: the task has been executed, and not *just before* which is the
    #: default behavior.
    #:
    #: Please note that this means the task may be executed twice if the
    #: worker crashes mid execution (which may be acceptable for some
    #: applications).
    #:
    #: The application default can be overridden with the
    #: :setting:`CELERY_ACKS_LATE` setting.
    acks_late = None

    #: Tuple of expected exceptions.
    #:
    #: These are errors that are expected in normal operation
    #: and that should not be regarded as a real error by the worker.
    #: Currently this means that the state will be updated to an error
    #: state, but the worker will not log the event as an error.
    throws = ()

    #: Default task expiry time.
    expires = None

    #: Some may expect a request to exist even if the task has not been
    #: called.  This should probably be deprecated.
    _default_request = None

    _exec_options = None

    __bound__ = False

    from_config = (
        ('send_error_emails', 'CELERY_SEND_TASK_ERROR_EMAILS'),
        ('serializer', 'CELERY_TASK_SERIALIZER'),
        ('rate_limit', 'CELERY_DEFAULT_RATE_LIMIT'),
        ('track_started', 'CELERY_TRACK_STARTED'),
        ('acks_late', 'CELERY_ACKS_LATE'),
        ('ignore_result', 'CELERY_IGNORE_RESULT'),
        ('store_errors_even_if_ignored',
         'CELERY_STORE_ERRORS_EVEN_IF_IGNORED'),
    )

    #: ignored
    accept_magic_kwargs = False

    _backend = None  # set by backend property.

    __bound__ = False

    # - Tasks are lazily bound, so that configuration is not set
    # - until the task is actually used

    @classmethod
    def bind(self, app):
        was_bound, self.__bound__ = self.__bound__, True
        self._app = app
        conf = app.conf
        self._exec_options = None  # clear option cache

        for attr_name, config_name in self.from_config:
            if getattr(self, attr_name, None) is None:
                setattr(self, attr_name, conf[config_name])

        # decorate with annotations from config.
        if not was_bound:
            self.annotate()

            from celery.utils.threads import LocalStack
            self.request_stack = LocalStack()

        # PeriodicTask uses this to add itself to the PeriodicTask schedule.
        self.on_bound(app)

        return app

    @classmethod
    def on_bound(self, app):
        """This method can be defined to do additional actions when the
        task class is bound to an app."""
        pass

    @classmethod
    def _get_app(self):
        if self._app is None:
            self._app = current_app
        if not self.__bound__:
            # The app property's __set__  method is not called
            # if Task.app is set (on the class), so must bind on use.
            self.bind(self._app)
        return self._app

    app = class_property(_get_app, bind)

    @classmethod
    def annotate(self):
        for d in resolve_all_annotations(self.app.annotations, self):
            for key, value in items(d):
                if key.startswith('@'):
                    self.add_around(key[1:], value)
                else:
                    setattr(self, key, value)

    @classmethod
    def add_around(self, attr, around):
        orig = getattr(self, attr)
        if getattr(orig, '__wrapped__', None):
            orig = orig.__wrapped__
        meth = around(orig)
        meth.__wrapped__ = orig
        setattr(self, attr, meth)

    def __call__(self, *args, **kwargs):
        _task_stack.push(self)
        self.push_request(args=args, kwargs=kwargs)
        try:
            # add self if this is a bound task
            if self.__self__ is not None:
                return self.run(self.__self__, *args, **kwargs)
            return self.run(*args, **kwargs)
        finally:
            self.pop_request()
            _task_stack.pop()

    def __reduce__(self):
        # - tasks are pickled into the name of the task only, and the reciever
        # - simply grabs it from the local registry.
        # - in later versions the module of the task is also included,
        # - and the receiving side tries to import that module so that
        # - it will work even if the task has not been registered.
        mod = type(self).__module__
        mod = mod if mod and mod in sys.modules else None
        return (_unpickle_task_v2, (self.name, mod), None)

    def run(self, *args, **kwargs):
        """The body of the task executed by workers."""
        raise NotImplementedError('Tasks must define the run method.')

    def start_strategy(self, app, consumer, **kwargs):
        return instantiate(self.Strategy, self, app, consumer, **kwargs)

    def delay(self, *args, **kwargs):
        """Star argument version of :meth:`apply_async`.

        Does not support the extra options enabled by :meth:`apply_async`.

        :param \*args: positional arguments passed on to the task.
        :param \*\*kwargs: keyword arguments passed on to the task.

        :returns :class:`celery.result.AsyncResult`:

        """
        return self.apply_async(args, kwargs)

    def apply_async(self,
                    args=None,
                    kwargs=None,
                    task_id=None,
                    producer=None,
                    link=None,
                    link_error=None,
                    shadow=None,
                    **options):
        """Apply tasks asynchronously by sending a message.

        :keyword args: The positional arguments to pass on to the
                       task (a :class:`list` or :class:`tuple`).

        :keyword kwargs: The keyword arguments to pass on to the
                         task (a :class:`dict`)

        :keyword countdown: Number of seconds into the future that the
                            task should execute. Defaults to immediate
                            execution.

        :keyword eta: A :class:`~datetime.datetime` object describing
                      the absolute time and date of when the task should
                      be executed.  May not be specified if `countdown`
                      is also supplied.

        :keyword expires: Either a :class:`int`, describing the number of
                          seconds, or a :class:`~datetime.datetime` object
                          that describes the absolute time and date of when
                          the task should expire.  The task will not be
                          executed after the expiration time.

        :keyword shadow: Override task name used in logs/monitoring
            (default from :meth:`shadow_name`).

        :keyword connection: Re-use existing broker connection instead
                             of establishing a new one.

        :keyword retry: If enabled sending of the task message will be retried
                        in the event of connection loss or failure.  Default
                        is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
                        setting.  Note that you need to handle the
                        producer/connection manually for this to work.

        :keyword retry_policy:  Override the retry policy used.  See the
                                :setting:`CELERY_TASK_PUBLISH_RETRY_POLICY`
                                setting.

        :keyword routing_key: Custom routing key used to route the task to a
                              worker server. If in combination with a
                              ``queue`` argument only used to specify custom
                              routing keys to topic exchanges.

        :keyword queue: The queue to route the task to.  This must be a key
                        present in :setting:`CELERY_QUEUES`, or
                        :setting:`CELERY_CREATE_MISSING_QUEUES` must be
                        enabled.  See :ref:`guide-routing` for more
                        information.

        :keyword exchange: Named custom exchange to send the task to.
                           Usually not used in combination with the ``queue``
                           argument.

        :keyword priority: The task priority, a number between 0 and 9.
                           Defaults to the :attr:`priority` attribute.

        :keyword serializer: A string identifying the default
                             serialization method to use.  Can be `pickle`,
                             `json`, `yaml`, `msgpack` or any custom
                             serialization method that has been registered
                             with :mod:`kombu.serialization.registry`.
                             Defaults to the :attr:`serializer` attribute.

        :keyword compression: A string identifying the compression method
                              to use.  Can be one of ``zlib``, ``bzip2``,
                              or any custom compression methods registered with
                              :func:`kombu.compression.register`. Defaults to
                              the :setting:`CELERY_MESSAGE_COMPRESSION`
                              setting.
        :keyword link: A single, or a list of tasks to apply if the
                       task exits successfully.
        :keyword link_error: A single, or a list of tasks to apply
                      if an error occurs while executing the task.

        :keyword producer: :class:`kombu.Producer` instance to use.
        :keyword add_to_parent: If set to True (default) and the task
            is applied while executing another task, then the result
            will be appended to the parent tasks ``request.children``
            attribute.  Trailing can also be disabled by default using the
            :attr:`trail` attribute
        :keyword publisher: Deprecated alias to ``producer``.

        :rtype :class:`celery.result.AsyncResult`: if
            :setting:`CELERY_ALWAYS_EAGER` is not set, otherwise
            :class:`celery.result.EagerResult`:

        Also supports all keyword arguments supported by
        :meth:`kombu.Producer.publish`.

        .. note::
            If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
            be replaced by a local :func:`apply` call instead.

        """
        try:
            check_arguments = self.__header__
        except AttributeError:
            pass
        else:
            check_arguments(*args or (), **kwargs or {})

        app = self._get_app()
        if app.conf.CELERY_ALWAYS_EAGER:
            return self.apply(args,
                              kwargs,
                              task_id=task_id or uuid(),
                              link=link,
                              link_error=link_error,
                              **options)
        # add 'self' if this is a "task_method".
        if self.__self__ is not None:
            args = args if isinstance(args, tuple) else tuple(args or ())
            args = (self.__self__, ) + args

        preopts = self._get_exec_options()
        options = dict(preopts, **options) if options else preopts
        return app.send_task(self.name,
                             args,
                             kwargs,
                             task_id=task_id,
                             producer=producer,
                             link=link,
                             link_error=link_error,
                             result_cls=self.AsyncResult,
                             shadow=shadow
                             or self.shadow_name(args, kwargs, options),
                             **options)

    def shadow_name(self, args, kwargs, options):
        """Override for custom task name in worker logs/monitoring.

        :param args: Task positional arguments.
        :param kwargs: Task keyword arguments.
        :param options: Task execution options.

        **Example**:

        .. code-block:: python

            from celery.utils.imports import qualname

            def shadow_name(task, args, kwargs, options):
                return qualname(args[0])

            @app.task(shadow_name=shadow_name, serializer='pickle')
            def apply_function_async(fun, *args, **kwargs):
                return fun(*args, **kwargs)

        """
        pass

    def signature_from_request(self,
                               request=None,
                               args=None,
                               kwargs=None,
                               queue=None,
                               **extra_options):
        request = self.request if request is None else request
        args = request.args if args is None else args
        kwargs = request.kwargs if kwargs is None else kwargs
        limit_hard, limit_soft = request.timelimit or (None, None)
        options = {
            'task_id': request.id,
            'link': request.callbacks,
            'link_error': request.errbacks,
            'group_id': request.group,
            'chord': request.chord,
            'soft_time_limit': limit_soft,
            'time_limit': limit_hard,
            'reply_to': request.reply_to,
        }
        options.update({'queue': queue} if queue else (
            request.delivery_info or {}))
        return self.signature(args,
                              kwargs,
                              options,
                              type=self,
                              **extra_options)

    subtask_from_request = signature_from_request

    def retry(self,
              args=None,
              kwargs=None,
              exc=None,
              throw=True,
              eta=None,
              countdown=None,
              max_retries=None,
              **options):
        """Retry the task.

        :param args: Positional arguments to retry with.
        :param kwargs: Keyword arguments to retry with.
        :keyword exc: Custom exception to report when the max restart
            limit has been exceeded (default:
            :exc:`~@MaxRetriesExceededError`).

            If this argument is set and retry is called while
            an exception was raised (``sys.exc_info()`` is set)
            it will attempt to reraise the current exception.

            If no exception was raised it will raise the ``exc``
            argument provided.
        :keyword countdown: Time in seconds to delay the retry for.
        :keyword eta: Explicit time and date to run the retry at
                      (must be a :class:`~datetime.datetime` instance).
        :keyword max_retries: If set, overrides the default retry limit.
            A value of :const:`None`, means "use the default", so if you want
            infinite retries you would have to set the :attr:`max_retries`
            attribute of the task to :const:`None` first.
        :keyword time_limit: If set, overrides the default time limit.
        :keyword soft_time_limit: If set, overrides the default soft
                                  time limit.
        :keyword \*\*options: Any extra options to pass on to
                              meth:`apply_async`.
        :keyword throw: If this is :const:`False`, do not raise the
                        :exc:`~@Retry` exception,
                        that tells the worker to mark the task as being
                        retried.  Note that this means the task will be
                        marked as failed if the task raises an exception,
                        or successful if it returns.

        :raises celery.exceptions.Retry: To tell the worker that
            the task has been re-sent for retry. This always happens,
            unless the `throw` keyword argument has been explicitly set
            to :const:`False`, and is considered normal operation.

        **Example**

        .. code-block:: python

            >>> from imaginary_twitter_lib import Twitter
            >>> from proj.celery import app

            >>> @app.task(bind=True)
            ... def tweet(self, auth, message):
            ...     twitter = Twitter(oauth=auth)
            ...     try:
            ...         twitter.post_status_update(message)
            ...     except twitter.FailWhale as exc:
            ...         # Retry in 5 minutes.
            ...         raise self.retry(countdown=60 * 5, exc=exc)

        Although the task will never return above as `retry` raises an
        exception to notify the worker, we use `raise` in front of the retry
        to convey that the rest of the block will not be executed.

        """
        request = self.request
        retries = request.retries + 1
        max_retries = self.max_retries if max_retries is None else max_retries

        # Not in worker or emulated by (apply/always_eager),
        # so just raise the original exception.
        if request.called_directly:
            maybe_reraise()  # raise orig stack if PyErr_Occurred
            raise exc or Retry('Task can be retried', None)

        if not eta and countdown is None:
            countdown = self.default_retry_delay

        is_eager = request.is_eager
        S = self.signature_from_request(request,
                                        args,
                                        kwargs,
                                        countdown=countdown,
                                        eta=eta,
                                        retries=retries,
                                        **options)

        if max_retries is not None and retries > max_retries:
            if exc:
                # first try to reraise the original exception
                maybe_reraise()
                # or if not in an except block then raise the custom exc.
                raise exc
            raise self.MaxRetriesExceededError(
                "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
                    self.name, request.id, S.args, S.kwargs))

        ret = Retry(exc=exc, when=eta or countdown)

        if is_eager:
            # if task was executed eagerly using apply(),
            # then the retry must also be executed eagerly.
            S.apply().get()
            if throw:
                raise ret
            return ret

        try:
            S.apply_async()
        except Exception as exc:
            raise Reject(exc, requeue=False)
        if throw:
            raise ret
        return ret

    def apply(self,
              args=None,
              kwargs=None,
              link=None,
              link_error=None,
              **options):
        """Execute this task locally, by blocking until the task returns.

        :param args: positional arguments passed on to the task.
        :param kwargs: keyword arguments passed on to the task.
        :keyword throw: Re-raise task exceptions.  Defaults to
                        the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
                        setting.

        :rtype :class:`celery.result.EagerResult`:

        """
        # trace imports Task, so need to import inline.
        from celery.app.trace import build_tracer

        app = self._get_app()
        args = args or ()
        # add 'self' if this is a bound method.
        if self.__self__ is not None:
            args = (self.__self__, ) + tuple(args)
        kwargs = kwargs or {}
        task_id = options.get('task_id') or uuid()
        retries = options.get('retries', 0)
        throw = app.either('CELERY_EAGER_PROPAGATES_EXCEPTIONS',
                           options.pop('throw', None))

        # Make sure we get the task instance, not class.
        task = app._tasks[self.name]

        request = {
            'id': task_id,
            'retries': retries,
            'is_eager': True,
            'logfile': options.get('logfile'),
            'loglevel': options.get('loglevel', 0),
            'callbacks': maybe_list(link),
            'errbacks': maybe_list(link_error),
            'headers': options.get('headers'),
            'delivery_info': {
                'is_eager': True
            }
        }
        tb = None
        tracer = build_tracer(
            task.name,
            task,
            eager=True,
            propagate=throw,
            app=self._get_app(),
        )
        ret = tracer(task_id, args, kwargs, request)
        retval = ret.retval
        if isinstance(retval, ExceptionInfo):
            retval, tb = retval.exception, retval.traceback
        state = states.SUCCESS if ret.info is None else ret.info.state
        return EagerResult(task_id, retval, state, traceback=tb)

    def AsyncResult(self, task_id, **kwargs):
        """Get AsyncResult instance for this kind of task.

        :param task_id: Task id to get result for.

        """
        return self._get_app().AsyncResult(task_id,
                                           backend=self.backend,
                                           task_name=self.name,
                                           **kwargs)

    def signature(self, args=None, *starargs, **starkwargs):
        """Return :class:`~celery.signature` object for
        this task, wrapping arguments and execution options
        for a single task invocation."""
        starkwargs.setdefault('app', self.app)
        return signature(self, args, *starargs, **starkwargs)

    subtask = signature

    def s(self, *args, **kwargs):
        """``.s(*a, **k) -> .signature(a, k)``"""
        return self.signature(args, kwargs)

    def si(self, *args, **kwargs):
        """``.si(*a, **k) -> .signature(a, k, immutable=True)``"""
        return self.signature(args, kwargs, immutable=True)

    def chunks(self, it, n):
        """Creates a :class:`~celery.canvas.chunks` task for this task."""
        from celery import chunks
        return chunks(self.s(), it, n, app=self.app)

    def map(self, it):
        """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
        from celery import xmap
        return xmap(self.s(), it, app=self.app)

    def starmap(self, it):
        """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
        from celery import xstarmap
        return xstarmap(self.s(), it, app=self.app)

    def send_event(self, type_, **fields):
        req = self.request
        with self.app.events.default_dispatcher(hostname=req.hostname) as d:
            return d.send(type_, uuid=req.id, **fields)

    def replace(self, sig):
        """Replace the current task, with a new task inheriting the
        same task id.

        :param sig: :class:`@signature`

        Note: This will raise :exc:`~@Ignore`, so the best practice
        is to always use ``raise self.replace_in_chord(...)`` to convey
        to the reader that the task will not continue after being replaced.

        :param: Signature of new task.

        """
        chord = self.request.chord
        if isinstance(sig, group):
            sig |= self.app.tasks['celery.accumulate'].s(index=0).set(
                chord=chord, )
            chord = None
        sig.freeze(self.request.id,
                   group_id=self.request.group,
                   chord=chord,
                   root_id=self.request.root_id)
        sig.delay()
        raise Ignore('Chord member replaced by new task')

    def add_to_chord(self, sig, lazy=False):
        """Add signature to the chord the current task is a member of.

        :param sig: Signature to extend chord with.
        :param lazy: If enabled the new task will not actually be called,
                      and ``sig.delay()`` must be called manually.

        Currently only supported by the Redis result backend when
        ``?new_join=1`` is enabled.

        """
        if not self.request.chord:
            raise ValueError('Current task is not member of any chord')
        result = sig.freeze(group_id=self.request.group,
                            chord=self.request.chord,
                            root_id=self.request.root_id)
        self.backend.add_to_chord(self.request.group, result)
        return sig.delay() if not lazy else sig

    def update_state(self, task_id=None, state=None, meta=None):
        """Update task state.

        :keyword task_id: Id of the task to update, defaults to the
                          id of the current task
        :keyword state: New state (:class:`str`).
        :keyword meta: State metadata (:class:`dict`).



        """
        if task_id is None:
            task_id = self.request.id
        self.backend.store_result(task_id, meta, state)

    def on_success(self, retval, task_id, args, kwargs):
        """Success handler.

        Run by the worker if the task executes successfully.

        :param retval: The return value of the task.
        :param task_id: Unique id of the executed task.
        :param args: Original arguments for the executed task.
        :param kwargs: Original keyword arguments for the executed task.

        The return value of this handler is ignored.

        """
        pass

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        """Retry handler.

        This is run by the worker when the task is to be retried.

        :param exc: The exception sent to :meth:`retry`.
        :param task_id: Unique id of the retried task.
        :param args: Original arguments for the retried task.
        :param kwargs: Original keyword arguments for the retried task.

        :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
                        instance, containing the traceback.

        The return value of this handler is ignored.

        """
        pass

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        """Error handler.

        This is run by the worker when the task fails.

        :param exc: The exception raised by the task.
        :param task_id: Unique id of the failed task.
        :param args: Original arguments for the task that failed.
        :param kwargs: Original keyword arguments for the task
                       that failed.

        :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
                        instance, containing the traceback.

        The return value of this handler is ignored.

        """
        pass

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        """Handler called after the task returns.

        :param status: Current task state.
        :param retval: Task return value/exception.
        :param task_id: Unique id of the task.
        :param args: Original arguments for the task.
        :param kwargs: Original keyword arguments for the task.

        :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
                        instance, containing the traceback (if any).

        The return value of this handler is ignored.

        """
        pass

    def send_error_email(self, context, exc, **kwargs):
        if self.send_error_emails and \
                not getattr(self, 'disable_error_emails', None):
            self.ErrorMail(self, **kwargs).send(context, exc)

    def add_trail(self, result):
        if self.trail:
            self.request.children.append(result)
        return result

    def push_request(self, *args, **kwargs):
        self.request_stack.push(Context(*args, **kwargs))

    def pop_request(self):
        self.request_stack.pop()

    def __repr__(self):
        """`repr(task)`"""
        return _reprtask(self, R_SELF_TASK if self.__self__ else R_INSTANCE)

    def _get_request(self):
        """Get current request object."""
        req = self.request_stack.top
        if req is None:
            # task was not called, but some may still expect a request
            # to be there, perhaps that should be deprecated.
            if self._default_request is None:
                self._default_request = Context()
            return self._default_request
        return req

    request = property(_get_request)

    def _get_exec_options(self):
        if self._exec_options is None:
            self._exec_options = extract_exec_options(self)
        return self._exec_options

    @property
    def backend(self):
        backend = self._backend
        if backend is None:
            return self.app.backend
        return backend

    @backend.setter
    def backend(self, value):  # noqa
        self._backend = value

    @property
    def __name__(self):
        return self.__class__.__name__
Example #7
0
class Task(object):
    """Task base class.

    When called tasks apply the :meth:`run` method.  This method must
    be defined by all tasks (that is unless the :meth:`__call__` method
    is overridden).

    """
    __metaclass__ = TaskType
    __trace__ = None
    __v2_compat__ = False  # set by old base in celery.task.base

    ErrorMail = ErrorMail
    MaxRetriesExceededError = MaxRetriesExceededError

    #: Execution strategy used, or the qualified name of one.
    Strategy = 'celery.worker.strategy:default'

    #: This is the instance bound to if the task is a method of a class.
    __self__ = None

    #: The application instance associated with this task class.
    _app = None

    #: Name of the task.
    name = None

    #: If :const:`True` the task is an abstract base class.
    abstract = True

    #: If disabled the worker will not forward magic keyword arguments.
    #: Deprecated and scheduled for removal in v4.0.
    accept_magic_kwargs = False

    #: Maximum number of retries before giving up.  If set to :const:`None`,
    #: it will **never** stop retrying.
    max_retries = 3

    #: Default time in seconds before a retry of the task should be
    #: executed.  3 minutes by default.
    default_retry_delay = 3 * 60

    #: Rate limit for this task type.  Examples: :const:`None` (no rate
    #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks
    #: a minute),`'100/h'` (hundred tasks an hour)
    rate_limit = None

    #: If enabled the worker will not store task state and return values
    #: for this task.  Defaults to the :setting:`CELERY_IGNORE_RESULT`
    #: setting.
    ignore_result = None

    #: When enabled errors will be stored even if the task is otherwise
    #: configured to ignore results.
    store_errors_even_if_ignored = None

    #: If enabled an email will be sent to :setting:`ADMINS` whenever a task
    #: of this type fails.
    send_error_emails = None

    #: The name of a serializer that are registered with
    #: :mod:`kombu.serialization.registry`.  Default is `'pickle'`.
    serializer = None

    #: Hard time limit.
    #: Defaults to the :setting:`CELERY_TASK_TIME_LIMIT` setting.
    time_limit = None

    #: Soft time limit.
    #: Defaults to the :setting:`CELERY_TASK_SOFT_TIME_LIMIT` setting.
    soft_time_limit = None

    #: The result store backend used for this task.
    backend = None

    #: If disabled this task won't be registered automatically.
    autoregister = True

    #: If enabled the task will report its status as 'started' when the task
    #: is executed by a worker.  Disabled by default as the normal behaviour
    #: is to not report that level of granularity.  Tasks are either pending,
    #: finished, or waiting to be retried.
    #:
    #: Having a 'started' status can be useful for when there are long
    #: running tasks and there is a need to report which task is currently
    #: running.
    #:
    #: The application default can be overridden using the
    #: :setting:`CELERY_TRACK_STARTED` setting.
    track_started = None

    #: When enabled messages for this task will be acknowledged **after**
    #: the task has been executed, and not *just before* which is the
    #: default behavior.
    #:
    #: Please note that this means the task may be executed twice if the
    #: worker crashes mid execution (which may be acceptable for some
    #: applications).
    #:
    #: The application default can be overridden with the
    #: :setting:`CELERY_ACKS_LATE` setting.
    acks_late = None

    #: Default task expiry time.
    expires = None

    #: Some may expect a request to exist even if the task has not been
    #: called.  This should probably be deprecated.
    _default_request = None

    __bound__ = False

    from_config = (
        ('send_error_emails', 'CELERY_SEND_TASK_ERROR_EMAILS'),
        ('serializer', 'CELERY_TASK_SERIALIZER'),
        ('rate_limit', 'CELERY_DEFAULT_RATE_LIMIT'),
        ('track_started', 'CELERY_TRACK_STARTED'),
        ('acks_late', 'CELERY_ACKS_LATE'),
        ('ignore_result', 'CELERY_IGNORE_RESULT'),
        ('store_errors_even_if_ignored',
            'CELERY_STORE_ERRORS_EVEN_IF_IGNORED'),
    )

    __bound__ = False

    # - Tasks are lazily bound, so that configuration is not set
    # - until the task is actually used

    @classmethod
    def bind(self, app):
        was_bound, self.__bound__ = self.__bound__, True
        self._app = app
        conf = app.conf

        for attr_name, config_name in self.from_config:
            if getattr(self, attr_name, None) is None:
                setattr(self, attr_name, conf[config_name])
        if self.accept_magic_kwargs is None:
            self.accept_magic_kwargs = app.accept_magic_kwargs
        if self.backend is None:
            self.backend = app.backend

        # decorate with annotations from config.
        if not was_bound:
            self.annotate()

            from celery.utils.threads import LocalStack
            self.request_stack = LocalStack()

        # PeriodicTask uses this to add itself to the PeriodicTask schedule.
        self.on_bound(app)

        return app

    @classmethod
    def on_bound(self, app):
        """This method can be defined to do additional actions when the
        task class is bound to an app."""
        pass

    @classmethod
    def _get_app(self):
        if not self.__bound__ or self._app is None:
            # The app property's __set__  method is not called
            # if Task.app is set (on the class), so must bind on use.
            self.bind(current_app)
        return self._app
    app = class_property(_get_app, bind)

    @classmethod
    def annotate(self):
        for d in resolve_all_annotations(self.app.annotations, self):
            for key, value in d.iteritems():
                if key.startswith('@'):
                    self.add_around(key[1:], value)
                else:
                    setattr(self, key, value)

    @classmethod
    def add_around(self, attr, around):
        orig = getattr(self, attr)
        if getattr(orig, '__wrapped__', None):
            orig = orig.__wrapped__
        meth = around(orig)
        meth.__wrapped__ = orig
        setattr(self, attr, meth)

    def __call__(self, *args, **kwargs):
        _task_stack.push(self)
        self.push_request()
        try:
            # add self if this is a bound task
            if self.__self__ is not None:
                return self.run(self.__self__, *args, **kwargs)
            return self.run(*args, **kwargs)
        finally:
            self.pop_request()
            _task_stack.pop()

    # - tasks are pickled into the name of the task only, and the reciever
    # - simply grabs it from the local registry.
    def __reduce__(self):
        return (_unpickle_task, (self.name, ), None)

    def run(self, *args, **kwargs):
        """The body of the task executed by workers."""
        raise NotImplementedError('Tasks must define the run method.')

    def start_strategy(self, app, consumer):
        return instantiate(self.Strategy, self, app, consumer)

    def delay(self, *args, **kwargs):
        """Star argument version of :meth:`apply_async`.

        Does not support the extra options enabled by :meth:`apply_async`.

        :param \*args: positional arguments passed on to the task.
        :param \*\*kwargs: keyword arguments passed on to the task.

        :returns :class:`celery.result.AsyncResult`:

        """
        return self.apply_async(args, kwargs)

    def apply_async(self, args=None, kwargs=None,
                    task_id=None, producer=None, connection=None, router=None,
                    link=None, link_error=None, publisher=None,
                    add_to_parent=True, **options):
        """Apply tasks asynchronously by sending a message.

        :keyword args: The positional arguments to pass on to the
                       task (a :class:`list` or :class:`tuple`).

        :keyword kwargs: The keyword arguments to pass on to the
                         task (a :class:`dict`)

        :keyword countdown: Number of seconds into the future that the
                            task should execute. Defaults to immediate
                            execution (do not confuse with the
                            `immediate` flag, as they are unrelated).

        :keyword eta: A :class:`~datetime.datetime` object describing
                      the absolute time and date of when the task should
                      be executed.  May not be specified if `countdown`
                      is also supplied.  (Do not confuse this with the
                      `immediate` flag, as they are unrelated).

        :keyword expires: Either a :class:`int`, describing the number of
                          seconds, or a :class:`~datetime.datetime` object
                          that describes the absolute time and date of when
                          the task should expire.  The task will not be
                          executed after the expiration time.

        :keyword connection: Re-use existing broker connection instead
                             of establishing a new one.

        :keyword retry: If enabled sending of the task message will be retried
                        in the event of connection loss or failure.  Default
                        is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
                        setting.  Note you need to handle the
                        producer/connection manually for this to work.

        :keyword retry_policy:  Override the retry policy used.  See the
                                :setting:`CELERY_TASK_PUBLISH_RETRY` setting.

        :keyword routing_key: Custom routing key used to route the task to a
                              worker server. If in combination with a
                              ``queue`` argument only used to specify custom
                              routing keys to topic exchanges.

        :keyword queue: The queue to route the task to.  This must be a key
                        present in :setting:`CELERY_QUEUES`, or
                        :setting:`CELERY_CREATE_MISSING_QUEUES` must be
                        enabled.  See :ref:`guide-routing` for more
                        information.

        :keyword exchange: Named custom exchange to send the task to.
                           Usually not used in combination with the ``queue``
                           argument.

        :keyword priority: The task priority, a number between 0 and 9.
                           Defaults to the :attr:`priority` attribute.

        :keyword serializer: A string identifying the default
                             serialization method to use.  Can be `pickle`,
                             `json`, `yaml`, `msgpack` or any custom
                             serialization method that has been registered
                             with :mod:`kombu.serialization.registry`.
                             Defaults to the :attr:`serializer` attribute.

        :keyword compression: A string identifying the compression method
                              to use.  Can be one of ``zlib``, ``bzip2``,
                              or any custom compression methods registered with
                              :func:`kombu.compression.register`. Defaults to
                              the :setting:`CELERY_MESSAGE_COMPRESSION`
                              setting.
        :keyword link: A single, or a list of subtasks to apply if the
                       task exits successfully.
        :keyword link_error: A single, or a list of subtasks to apply
                      if an error occurs while executing the task.

        :keyword producer: :class:[email protected]` instance to use.
        :keyword add_to_parent: If set to True (default) and the task
            is applied while executing another task, then the result
            will be appended to the parent tasks ``request.children``
            attribute.
        :keyword publisher: Deprecated alias to ``producer``.

        Also supports all keyword arguments supported by
        :meth:`kombu.messaging.Producer.publish`.

        .. note::
            If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
            be replaced by a local :func:`apply` call instead.

        """
        producer = producer or publisher
        app = self._get_app()
        router = router or self.app.amqp.router
        conf = app.conf

        # add 'self' if this is a bound method.
        if self.__self__ is not None:
            args = (self.__self__, ) + tuple(args)

        if conf.CELERY_ALWAYS_EAGER:
            return self.apply(args, kwargs, task_id=task_id, **options)
        options = dict(extract_exec_options(self), **options)
        options = router.route(options, self.name, args, kwargs)

        if connection:
            producer = app.amqp.TaskProducer(connection)
        with app.producer_or_acquire(producer) as P:
            task_id = P.publish_task(self.name, args, kwargs,
                                     task_id=task_id,
                                     callbacks=maybe_list(link),
                                     errbacks=maybe_list(link_error),
                                     **options)
        result = self.AsyncResult(task_id)
        if add_to_parent:
            parent = get_current_worker_task()
            if parent:
                parent.request.children.append(result)
        return result

    def subtask_from_request(self, request=None, args=None, kwargs=None,
                             **extra_options):

        request = self.request if request is None else request
        args = request.args if args is None else args
        kwargs = request.kwargs if kwargs is None else kwargs
        delivery_info = request.delivery_info or {}
        options = {
            'task_id': request.id,
            'link': request.callbacks,
            'link_error': request.errbacks,
            'exchange': delivery_info.get('exchange'),
            'routing_key': delivery_info.get('routing_key')
        }
        return self.subtask(args, kwargs, options, type=self, **extra_options)

    def retry(self, args=None, kwargs=None, exc=None, throw=True,
              eta=None, countdown=None, max_retries=None, **options):
        """Retry the task.

        :param args: Positional arguments to retry with.
        :param kwargs: Keyword arguments to retry with.
        :keyword exc: Custom exception to report when the max restart
            limit has been exceeded (default:
            :exc:`~celery.exceptions.MaxRetriesExceededError`).

            If this argument is set and retry is called while
            an exception was raised (``sys.exc_info()`` is set)
            it will attempt to reraise the current exception.

            If no exception was raised it will raise the ``exc``
            argument provided.
        :keyword countdown: Time in seconds to delay the retry for.
        :keyword eta: Explicit time and date to run the retry at
                      (must be a :class:`~datetime.datetime` instance).
        :keyword max_retries: If set, overrides the default retry limit.
        :keyword \*\*options: Any extra options to pass on to
                              meth:`apply_async`.
        :keyword throw: If this is :const:`False`, do not raise the
                        :exc:`~celery.exceptions.RetryTaskError` exception,
                        that tells the worker to mark the task as being
                        retried.  Note that this means the task will be
                        marked as failed if the task raises an exception,
                        or successful if it returns.

        :raises celery.exceptions.RetryTaskError: To tell the worker that
            the task has been re-sent for retry. This always happens,
            unless the `throw` keyword argument has been explicitly set
            to :const:`False`, and is considered normal operation.

        **Example**

        .. code-block:: python

            >>> @task()
            >>> def tweet(auth, message):
            ...     twitter = Twitter(oauth=auth)
            ...     try:
            ...         twitter.post_status_update(message)
            ...     except twitter.FailWhale, exc:
            ...         # Retry in 5 minutes.
            ...         raise tweet.retry(countdown=60 * 5, exc=exc)

        Although the task will never return above as `retry` raises an
        exception to notify the worker, we use `return` in front of the retry
        to convey that the rest of the block will not be executed.

        """
        request = self.request
        retries = request.retries + 1
        max_retries = self.max_retries if max_retries is None else max_retries

        # Not in worker or emulated by (apply/always_eager),
        # so just raise the original exception.
        if request.called_directly:
            maybe_reraise()  # raise orig stack if PyErr_Occurred
            raise exc or RetryTaskError('Task can be retried', None)

        if not eta and countdown is None:
            countdown = self.default_retry_delay

        S = self.subtask_from_request(
            request, args, kwargs,
            countdown=countdown, eta=eta, retries=retries,
            **options
        )

        if max_retries is not None and retries > max_retries:
            if exc:
                maybe_reraise()
            raise self.MaxRetriesExceededError(
                """Can't retry %s[%s] args:%s kwargs:%s""" % (
                    self.name, request.id, S.args, S.kwargs))

        # If task was executed eagerly using apply(),
        # then the retry must also be executed eagerly.
        S.apply().get() if request.is_eager else S.apply_async()
        ret = RetryTaskError(exc=exc, when=eta or countdown)
        if throw:
            raise ret
        return ret

    def apply(self, args=None, kwargs=None, **options):
        """Execute this task locally, by blocking until the task returns.

        :param args: positional arguments passed on to the task.
        :param kwargs: keyword arguments passed on to the task.
        :keyword throw: Re-raise task exceptions.  Defaults to
                        the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
                        setting.

        :rtype :class:`celery.result.EagerResult`:

        """
        # trace imports Task, so need to import inline.
        from celery.task.trace import eager_trace_task

        app = self._get_app()
        args = args or ()
        # add 'self' if this is a bound method.
        if self.__self__ is not None:
            args = (self.__self__, ) + tuple(args)
        kwargs = kwargs or {}
        task_id = options.get('task_id') or uuid()
        retries = options.get('retries', 0)
        throw = app.either('CELERY_EAGER_PROPAGATES_EXCEPTIONS',
                           options.pop('throw', None))

        # Make sure we get the task instance, not class.
        task = app._tasks[self.name]

        request = {'id': task_id,
                   'retries': retries,
                   'is_eager': True,
                   'logfile': options.get('logfile'),
                   'loglevel': options.get('loglevel', 0),
                   'delivery_info': {'is_eager': True}}
        if self.accept_magic_kwargs:
            default_kwargs = {'task_name': task.name,
                              'task_id': task_id,
                              'task_retries': retries,
                              'task_is_eager': True,
                              'logfile': options.get('logfile'),
                              'loglevel': options.get('loglevel', 0),
                              'delivery_info': {'is_eager': True}}
            supported_keys = fun_takes_kwargs(task.run, default_kwargs)
            extend_with = dict((key, val)
                               for key, val in default_kwargs.items()
                               if key in supported_keys)
            kwargs.update(extend_with)

        tb = None
        retval, info = eager_trace_task(task, task_id, args, kwargs,
                                        request=request, propagate=throw)
        if isinstance(retval, ExceptionInfo):
            retval, tb = retval.exception, retval.traceback
        state = states.SUCCESS if info is None else info.state
        return EagerResult(task_id, retval, state, traceback=tb)

    def AsyncResult(self, task_id, **kwargs):
        """Get AsyncResult instance for this kind of task.

        :param task_id: Task id to get result for.

        """
        return self._get_app().AsyncResult(task_id, backend=self.backend,
                                           task_name=self.name, **kwargs)

    def subtask(self, args=None, *starargs, **starkwargs):
        """Returns :class:`~celery.subtask` object for
        this task, wrapping arguments and execution options
        for a single task invocation."""
        return subtask(self, args, *starargs, **starkwargs)

    def s(self, *args, **kwargs):
        """``.s(*a, **k) -> .subtask(a, k)``"""
        return self.subtask(args, kwargs)

    def si(self, *args, **kwargs):
        """``.si(*a, **k) -> .subtask(a, k, immutable=True)``"""
        return self.subtask(args, kwargs, immutable=True)

    def chunks(self, it, n):
        """Creates a :class:`~celery.canvas.chunks` task for this task."""
        from celery import chunks
        return chunks(self.s(), it, n)

    def map(self, it):
        """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
        from celery import xmap
        return xmap(self.s(), it)

    def starmap(self, it):
        """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
        from celery import xstarmap
        return xstarmap(self.s(), it)

    def update_state(self, task_id=None, state=None, meta=None):
        """Update task state.

        :keyword task_id: Id of the task to update, defaults to the
                          id of the current task
        :keyword state: New state (:class:`str`).
        :keyword meta: State metadata (:class:`dict`).



        """
        if task_id is None:
            task_id = self.request.id
        self.backend.store_result(task_id, meta, state)

    def on_success(self, retval, task_id, args, kwargs):
        """Success handler.

        Run by the worker if the task executes successfully.

        :param retval: The return value of the task.
        :param task_id: Unique id of the executed task.
        :param args: Original arguments for the executed task.
        :param kwargs: Original keyword arguments for the executed task.

        The return value of this handler is ignored.

        """
        pass

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        """Retry handler.

        This is run by the worker when the task is to be retried.

        :param exc: The exception sent to :meth:`retry`.
        :param task_id: Unique id of the retried task.
        :param args: Original arguments for the retried task.
        :param kwargs: Original keyword arguments for the retried task.

        :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
                        instance, containing the traceback.

        The return value of this handler is ignored.

        """
        pass

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        """Error handler.

        This is run by the worker when the task fails.

        :param exc: The exception raised by the task.
        :param task_id: Unique id of the failed task.
        :param args: Original arguments for the task that failed.
        :param kwargs: Original keyword arguments for the task
                       that failed.

        :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
                        instance, containing the traceback.

        The return value of this handler is ignored.

        """
        pass

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        """Handler called after the task returns.

        :param status: Current task state.
        :param retval: Task return value/exception.
        :param task_id: Unique id of the task.
        :param args: Original arguments for the task that failed.
        :param kwargs: Original keyword arguments for the task
                       that failed.

        :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
                        instance, containing the traceback (if any).

        The return value of this handler is ignored.

        """
        pass

    def send_error_email(self, context, exc, **kwargs):
        if self.send_error_emails and \
                not getattr(self, 'disable_error_emails', None):
            self.ErrorMail(self, **kwargs).send(context, exc)

    def push_request(self, *args, **kwargs):
        self.request_stack.push(Context(*args, **kwargs))

    def pop_request(self):
        self.request_stack.pop()

    def __repr__(self):
        """`repr(task)`"""
        if self.__self__:
            return '<bound task %s of %r>' % (self.name, self.__self__)
        return '<@task: %s>' % (self.name, )

    def _get_request(self):
        """Get current request object."""
        req = self.request_stack.top
        if req is None:
            # task was not called, but some may still expect a request
            # to be there, perhaps that should be deprecated.
            if self._default_request is None:
                self._default_request = Context()
            return self._default_request
        return req
    request = property(_get_request)

    @property
    def __name__(self):
        return self.__class__.__name__
Example #8
0
    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()


def set_default_app(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 import Celery
        set_default_app(Celery(
            'default', fixups=[], set_as_current=False,
            loader=os.environ.get('CELERY_LOADER') or 'default',
        ))
Example #9
0
class Task(object):
    """Task base class.

    When called tasks apply the :meth:`run` method.  This method must
    be defined by all tasks (that is unless the :meth:`__call__` method
    is overridden).
    """
    __trace__ = None
    __v2_compat__ = False  # set by old base in celery.task.base

    MaxRetriesExceededError = MaxRetriesExceededError
    OperationalError = OperationalError

    #: Execution strategy used, or the qualified name of one.
    Strategy = 'celery.worker.strategy:default'

    #: This is the instance bound to if the task is a method of a class.
    __self__ = None

    #: The application instance associated with this task class.
    _app = None

    #: Name of the task.
    name = None

    #: Maximum number of retries before giving up.  If set to :const:`None`,
    #: it will **never** stop retrying.
    max_retries = 3

    #: Default time in seconds before a retry of the task should be
    #: executed.  3 minutes by default.
    default_retry_delay = 3 * 60

    #: Rate limit for this task type.  Examples: :const:`None` (no rate
    #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks
    #: a minute),`'100/h'` (hundred tasks an hour)
    rate_limit = None

    #: If enabled the worker won't store task state and return values
    #: for this task.  Defaults to the :setting:`task_ignore_result`
    #: setting.
    ignore_result = None

    #: If enabled the request will keep track of subtasks started by
    #: this task, and this information will be sent with the result
    #: (``result.children``).
    trail = True

    #: When enabled errors will be stored even if the task is otherwise
    #: configured to ignore results.
    store_errors_even_if_ignored = None

    #: The name of a serializer that are registered with
    #: :mod:`kombu.serialization.registry`.  Default is `'pickle'`.
    serializer = None

    #: Hard time limit.
    #: Defaults to the :setting:`task_time_limit` setting.
    time_limit = None

    #: Soft time limit.
    #: Defaults to the :setting:`task_soft_time_limit` setting.
    soft_time_limit = None

    #: The result store backend used for this task.
    backend = None

    #: If disabled this task won't be registered automatically.
    autoregister = True

    #: If enabled the task will report its status as 'started' when the task
    #: is executed by a worker.  Disabled by default as the normal behavior
    #: is to not report that level of granularity.  Tasks are either pending,
    #: finished, or waiting to be retried.
    #:
    #: Having a 'started' status can be useful for when there are long
    #: running tasks and there's a need to report which task is currently
    #: running.
    #:
    #: The application default can be overridden using the
    #: :setting:`task_track_started` setting.
    track_started = None

    #: When enabled messages for this task will be acknowledged **after**
    #: the task has been executed, and not *just before* which is the
    #: default behavior.
    #:
    #: Please note that this means the task may be executed twice if the
    #: worker crashes mid execution (which may be acceptable for some
    #: applications).
    #:
    #: The application default can be overridden with the
    #: :setting:`task_acks_late` setting.
    acks_late = None

    #: Even if :attr:`acks_late` is enabled, the worker will
    #: acknowledge tasks when the worker process executing them abruptly
    #: exits or is signaled (e.g. :sig:`KILL`/:sig:`INT`, etc).
    #:
    #: Setting this to true allows the message to be re-queued instead,
    #: so that the task will execute again by the same worker, or another
    #: worker.
    #:
    #: Warning: Enabling this can cause message loops; make sure you know
    #: what you're doing.
    reject_on_worker_lost = None

    #: Tuple of expected exceptions.
    #:
    #: These are errors that are expected in normal operation
    #: and that shouldn't be regarded as a real error by the worker.
    #: Currently this means that the state will be updated to an error
    #: state, but the worker won't log the event as an error.
    throws = ()

    #: Default task expiry time.
    expires = None

    #: Max length of result representation used in logs and events.
    resultrepr_maxsize = 1024

    #: Task request stack, the current request will be the topmost.
    request_stack = None

    #: Some may expect a request to exist even if the task hasn't been
    #: called.  This should probably be deprecated.
    _default_request = None

    #: Deprecated attribute ``abstract`` here for compatibility.
    abstract = True

    _exec_options = None

    __bound__ = False

    from_config = (
        ('serializer', 'task_serializer'),
        ('rate_limit', 'task_default_rate_limit'),
        ('track_started', 'task_track_started'),
        ('acks_late', 'task_acks_late'),
        ('reject_on_worker_lost', 'task_reject_on_worker_lost'),
        ('ignore_result', 'task_ignore_result'),
        ('store_errors_even_if_ignored', 'task_store_errors_even_if_ignored'),
    )

    _backend = None  # set by backend property.

    # - Tasks are lazily bound, so that configuration is not set
    # - until the task is actually used

    @classmethod
    def bind(self, app):
        was_bound, self.__bound__ = self.__bound__, True
        self._app = app
        conf = app.conf
        self._exec_options = None  # clear option cache

        for attr_name, config_name in self.from_config:
            if getattr(self, attr_name, None) is None:
                setattr(self, attr_name, conf[config_name])

        # decorate with annotations from config.
        if not was_bound:
            self.annotate()

            from celery.utils.threads import LocalStack
            self.request_stack = LocalStack()

        # PeriodicTask uses this to add itself to the PeriodicTask schedule.
        self.on_bound(app)

        return app

    @classmethod
    def on_bound(self, app):
        """This method can be defined to do additional actions when the
        task class is bound to an app."""
        pass

    @classmethod
    def _get_app(self):
        if self._app is None:
            self._app = current_app
        if not self.__bound__:
            # The app property's __set__  method is not called
            # if Task.app is set (on the class), so must bind on use.
            self.bind(self._app)
        return self._app

    app = class_property(_get_app, bind)

    @classmethod
    def annotate(self):
        for d in resolve_all_annotations(self.app.annotations, self):
            for key, value in items(d):
                if key.startswith('@'):
                    self.add_around(key[1:], value)
                else:
                    setattr(self, key, value)

    @classmethod
    def add_around(self, attr, around):
        orig = getattr(self, attr)
        if getattr(orig, '__wrapped__', None):
            orig = orig.__wrapped__
        meth = around(orig)
        meth.__wrapped__ = orig
        setattr(self, attr, meth)

    def __call__(self, *args, **kwargs):
        _task_stack.push(self)
        self.push_request(args=args, kwargs=kwargs)
        try:
            # add self if this is a bound task
            if self.__self__ is not None:
                return self.run(self.__self__, *args, **kwargs)
            return self.run(*args, **kwargs)
        finally:
            self.pop_request()
            _task_stack.pop()

    def __reduce__(self):
        # - tasks are pickled into the name of the task only, and the reciever
        # - simply grabs it from the local registry.
        # - in later versions the module of the task is also included,
        # - and the receiving side tries to import that module so that
        # - it will work even if the task hasn't been registered.
        mod = type(self).__module__
        mod = mod if mod and mod in sys.modules else None
        return (_unpickle_task_v2, (self.name, mod), None)

    def run(self, *args, **kwargs):
        """The body of the task executed by workers."""
        raise NotImplementedError('Tasks must define the run method.')

    def start_strategy(self, app, consumer, **kwargs):
        return instantiate(self.Strategy, self, app, consumer, **kwargs)

    def delay(self, *args, **kwargs):
        """Star argument version of :meth:`apply_async`.

        Does not support the extra options enabled by :meth:`apply_async`.

        Arguments:
            *args (Any): Positional arguments passed on to the task.
            **kwargs (Any): Keyword arguments passed on to the task.
        Returns:
            celery.result.AsyncResult: Future promise.
        """
        return self.apply_async(args, kwargs)

    def apply_async(self,
                    args=None,
                    kwargs=None,
                    task_id=None,
                    producer=None,
                    link=None,
                    link_error=None,
                    shadow=None,
                    **options):
        """Apply tasks asynchronously by sending a message.

        Arguments:
            args (Tuple): The positional arguments to pass on to the task.

            kwargs (Dict): The keyword arguments to pass on to the task.

            countdown (float): Number of seconds into the future that the
                task should execute.  Defaults to immediate execution.

            eta (~datetime.datetime): Absolute time and date of when the task
                should be executed.  May not be specified if `countdown`
                is also supplied.

            expires (float, ~datetime.datetime): Datetime or
                seconds in the future for the task should expire.
                The task won't be executed after the expiration time.

            shadow (str): Override task name used in logs/monitoring.
                Default is retrieved from :meth:`shadow_name`.

            connection (kombu.Connection): Re-use existing broker connection
                instead of acquiring one from the connection pool.

            retry (bool): If enabled sending of the task message will be
                retried in the event of connection loss or failure.
                Default is taken from the :setting:`task_publish_retry`
                setting.  Note that you need to handle the
                producer/connection manually for this to work.

            retry_policy (Mapping): Override the retry policy used.
                See the :setting:`task_publish_retry_policy` setting.

            queue (str, kombu.Queue): The queue to route the task to.
                This must be a key present in :setting:`task_queues`, or
                :setting:`task_create_missing_queues` must be
                enabled.  See :ref:`guide-routing` for more
                information.

            exchange (str, kombu.Exchange): Named custom exchange to send the
                task to.  Usually not used in combination with the ``queue``
                argument.

            routing_key (str): Custom routing key used to route the task to a
                worker server.  If in combination with a ``queue`` argument
                only used to specify custom routing keys to topic exchanges.

            priority (int): The task priority, a number between 0 and 9.
                Defaults to the :attr:`priority` attribute.

            serializer (str): Serialization method to use.
                Can be `pickle`, `json`, `yaml`, `msgpack` or any custom
                serialization method that's been registered
                with :mod:`kombu.serialization.registry`.
                Defaults to the :attr:`serializer` attribute.

            compression (str): Optional compression method
                to use.  Can be one of ``zlib``, ``bzip2``,
                or any custom compression methods registered with
                :func:`kombu.compression.register`.
                Defaults to the :setting:`task_compression` setting.

            link (~@Signature): A single, or a list of tasks signatures
                to apply if the task returns successfully.

            link_error (~@Signature): A single, or a list of task signatures
                to apply if an error occurs while executing the task.

            producer (kombu.Producer): custom producer to use when publishing
                the task.

            add_to_parent (bool): If set to True (default) and the task
                is applied while executing another task, then the result
                will be appended to the parent tasks ``request.children``
                attribute.  Trailing can also be disabled by default using the
                :attr:`trail` attribute

            publisher (kombu.Producer): Deprecated alias to ``producer``.

            headers (Dict): Message headers to be included in the message.

        Returns:
            ~@AsyncResult: Future promise.

        Note:
            Also supports all keyword arguments supported by
            :meth:`kombu.Producer.publish`.
        """
        try:
            check_arguments = self.__header__
        except AttributeError:  # pragma: no cover
            pass
        else:
            check_arguments(*(args or ()), **(kwargs or {}))

        app = self._get_app()
        if app.conf.task_always_eager:
            return self.apply(args,
                              kwargs,
                              task_id=task_id or uuid(),
                              link=link,
                              link_error=link_error,
                              **options)
        # add 'self' if this is a "task_method".
        if self.__self__ is not None:
            args = args if isinstance(args, tuple) else tuple(args or ())
            args = (self.__self__, ) + args
            shadow = shadow or self.shadow_name(args, kwargs, options)

        preopts = self._get_exec_options()
        options = dict(preopts, **options) if options else preopts
        return app.send_task(self.name,
                             args,
                             kwargs,
                             task_id=task_id,
                             producer=producer,
                             link=link,
                             link_error=link_error,
                             result_cls=self.AsyncResult,
                             shadow=shadow,
                             task_type=self,
                             **options)

    def shadow_name(self, args, kwargs, options):
        """Override for custom task name in worker logs/monitoring.

        Example:
            .. code-block:: python

                from celery.utils.imports import qualname

                def shadow_name(task, args, kwargs, options):
                    return qualname(args[0])

                @app.task(shadow_name=shadow_name, serializer='pickle')
                def apply_function_async(fun, *args, **kwargs):
                    return fun(*args, **kwargs)

        Arguments:
            args (Tuple): Task positional arguments.
            kwargs (Dict): Task keyword arguments.
            options (Dict): Task execution options.
        """
        pass

    def signature_from_request(self,
                               request=None,
                               args=None,
                               kwargs=None,
                               queue=None,
                               **extra_options):
        request = self.request if request is None else request
        args = request.args if args is None else args
        kwargs = request.kwargs if kwargs is None else kwargs
        options = request.as_execution_options()
        options.update({'queue': queue} if queue else
                       (request.delivery_info or {}), )
        return self.signature(args,
                              kwargs,
                              options,
                              type=self,
                              **extra_options)

    subtask_from_request = signature_from_request  # XXX compat

    def retry(self,
              args=None,
              kwargs=None,
              exc=None,
              throw=True,
              eta=None,
              countdown=None,
              max_retries=None,
              **options):
        """Retry the task.

        Example:
            >>> from imaginary_twitter_lib import Twitter
            >>> from proj.celery import app

            >>> @app.task(bind=True)
            ... def tweet(self, auth, message):
            ...     twitter = Twitter(oauth=auth)
            ...     try:
            ...         twitter.post_status_update(message)
            ...     except twitter.FailWhale as exc:
            ...         # Retry in 5 minutes.
            ...         raise self.retry(countdown=60 * 5, exc=exc)

        Note:
            Although the task will never return above as `retry` raises an
            exception to notify the worker, we use `raise` in front of the
            retry to convey that the rest of the block won't be executed.

        Arguments:
            args (Tuple): Positional arguments to retry with.
            kwargs (Dict): Keyword arguments to retry with.
            exc (Exception): Custom exception to report when the max restart
                limit has been exceeded (default:
                :exc:`~@MaxRetriesExceededError`).

                If this argument is set and retry is called while
                an exception was raised (``sys.exc_info()`` is set)
                it will attempt to re-raise the current exception.

                If no exception was raised it will raise the ``exc``
                argument provided.
            countdown (float): Time in seconds to delay the retry for.
            eta (~datetime.dateime): Explicit time and date to run the
                retry at.
            max_retries (int): If set, overrides the default retry limit for
                this execution.  Changes to this parameter don't propagate to
                subsequent task retry attempts.  A value of :const:`None`,
                means "use the default", so if you want infinite retries you'd
                have to set the :attr:`max_retries` attribute of the task to
                :const:`None` first.
            time_limit (int): If set, overrides the default time limit.
            soft_time_limit (int): If set, overrides the default soft
                time limit.
            throw (bool): If this is :const:`False`, don't raise the
                :exc:`~@Retry` exception, that tells the worker to mark
                the task as being retried.  Note that this means the task
                will be marked as failed if the task raises an exception,
                or successful if it returns after the retry call.
            **options (Any): Extra options to pass on to :meth:`apply_async`.

        Raises:
            celery.exceptions.Retry:
                To tell the worker that the task has been re-sent for retry.
                This always happens, unless the `throw` keyword argument
                has been explicitly set to :const:`False`, and is considered
                normal operation.
        """
        request = self.request
        retries = request.retries + 1
        max_retries = self.max_retries if max_retries is None else max_retries

        # Not in worker or emulated by (apply/always_eager),
        # so just raise the original exception.
        if request.called_directly:
            maybe_reraise()  # raise orig stack if PyErr_Occurred
            raise exc or Retry('Task can be retried', None)

        if not eta and countdown is None:
            countdown = self.default_retry_delay

        is_eager = request.is_eager
        S = self.signature_from_request(request,
                                        args,
                                        kwargs,
                                        countdown=countdown,
                                        eta=eta,
                                        retries=retries,
                                        **options)

        if max_retries is not None and retries > max_retries:
            if exc:
                # first try to re-raise the original exception
                maybe_reraise()
                # or if not in an except block then raise the custom exc.
                raise exc
            raise self.MaxRetriesExceededError(
                "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
                    self.name, request.id, S.args, S.kwargs))

        ret = Retry(exc=exc, when=eta or countdown)

        if is_eager:
            # if task was executed eagerly using apply(),
            # then the retry must also be executed eagerly.
            S.apply().get()
            if throw:
                raise ret
            return ret

        try:
            S.apply_async()
        except Exception as exc:
            raise Reject(exc, requeue=False)
        if throw:
            raise ret
        return ret

    def apply(self,
              args=None,
              kwargs=None,
              link=None,
              link_error=None,
              task_id=None,
              retries=None,
              throw=None,
              logfile=None,
              loglevel=None,
              headers=None,
              **options):
        """Execute this task locally, by blocking until the task returns.

        Arguments:
            args (Tuple): positional arguments passed on to the task.
            kwargs (Dict): keyword arguments passed on to the task.
            throw (bool): Re-raise task exceptions.
                Defaults to the :setting:`task_eager_propagates` setting.

        Returns:
            celery.result.EagerResult: pre-evaluated result.
        """
        # trace imports Task, so need to import inline.
        from celery.app.trace import build_tracer

        app = self._get_app()
        args = args or ()
        # add 'self' if this is a bound method.
        if self.__self__ is not None:
            args = (self.__self__, ) + tuple(args)
        kwargs = kwargs or {}
        task_id = task_id or uuid()
        retries = retries or 0
        if throw is None:
            throw = app.conf.task_eager_propagates

        # Make sure we get the task instance, not class.
        task = app._tasks[self.name]

        request = {
            'id': task_id,
            'retries': retries,
            'is_eager': True,
            'logfile': logfile,
            'loglevel': loglevel or 0,
            'callbacks': maybe_list(link),
            'errbacks': maybe_list(link_error),
            'headers': headers,
            'delivery_info': {
                'is_eager': True
            },
        }
        tb = None
        tracer = build_tracer(
            task.name,
            task,
            eager=True,
            propagate=throw,
            app=self._get_app(),
        )
        ret = tracer(task_id, args, kwargs, request)
        retval = ret.retval
        if isinstance(retval, ExceptionInfo):
            retval, tb = retval.exception, retval.traceback
        state = states.SUCCESS if ret.info is None else ret.info.state
        return EagerResult(task_id, retval, state, traceback=tb)

    def AsyncResult(self, task_id, **kwargs):
        """Get AsyncResult instance for this kind of task.

        Arguments:
            task_id (str): Task id to get result for.
        """
        return self._get_app().AsyncResult(task_id,
                                           backend=self.backend,
                                           task_name=self.name,
                                           **kwargs)

    def signature(self, args=None, *starargs, **starkwargs):
        """Return :class:`~celery.signature` object for
        this task, wrapping arguments and execution options
        for a single task invocation."""
        starkwargs.setdefault('app', self.app)
        return signature(self, args, *starargs, **starkwargs)

    subtask = signature

    def s(self, *args, **kwargs):
        """``.s(*a, **k) -> .signature(a, k)``"""
        return self.signature(args, kwargs)

    def si(self, *args, **kwargs):
        """``.si(*a, **k) -> .signature(a, k, immutable=True)``"""
        return self.signature(args, kwargs, immutable=True)

    def chunks(self, it, n):
        """Creates a :class:`~celery.canvas.chunks` task for this task."""
        from celery import chunks
        return chunks(self.s(), it, n, app=self.app)

    def map(self, it):
        """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
        from celery import xmap
        return xmap(self.s(), it, app=self.app)

    def starmap(self, it):
        """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
        from celery import xstarmap
        return xstarmap(self.s(), it, app=self.app)

    def send_event(self, type_, **fields):
        req = self.request
        with self.app.events.default_dispatcher(hostname=req.hostname) as d:
            return d.send(type_, uuid=req.id, **fields)

    def replace(self, sig):
        """Replace the current task, with a new task inheriting the
        same task id.

        .. versionadded:: 4.0

        Arguments:
            sig (~@Signature): signature to replace with.

        Raises:
            ~@Ignore: This is always raised, so the best practice
            is to always use ``raise self.replace(...)`` to convey
            to the reader that the task won't continue after being replaced.
        """
        chord = self.request.chord
        if 'chord' in sig.options:
            if chord:
                chord = sig.options['chord'] | chord
            else:
                chord = sig.options['chord']

        if isinstance(sig, group):
            sig |= self.app.tasks['celery.accumulate'].s(index=0).set(
                chord=chord,
                link=self.request.callbacks,
                link_error=self.request.errbacks,
            )
            chord = None

        if self.request.chain:
            for t in self.request.chain:
                sig |= signature(t)

        sig.freeze(self.request.id,
                   group_id=self.request.group,
                   chord=chord,
                   root_id=self.request.root_id)

        sig.delay()
        raise Ignore('Replaced by new task')

    def add_to_chord(self, sig, lazy=False):
        """Add signature to the chord the current task is a member of.

        .. versionadded:: 4.0

        Currently only supported by the Redis result backend.

        Arguments:
            sig (~@Signature): Signature to extend chord with.
            lazy (bool): If enabled the new task won't actually be called,
                and ``sig.delay()`` must be called manually.
        """
        if not self.request.chord:
            raise ValueError('Current task is not member of any chord')
        result = sig.freeze(group_id=self.request.group,
                            chord=self.request.chord,
                            root_id=self.request.root_id)
        self.backend.add_to_chord(self.request.group, result)
        return sig.delay() if not lazy else sig

    def update_state(self, task_id=None, state=None, meta=None):
        """Update task state.

        Arguments:
            task_id (str): Id of the task to update.
                Defaults to the id of the current task.
            state (str): New state.
            meta (Dict): State meta-data.
        """
        if task_id is None:
            task_id = self.request.id
        self.backend.store_result(task_id, meta, state)

    def on_success(self, retval, task_id, args, kwargs):
        """Success handler.

        Run by the worker if the task executes successfully.

        Arguments:
            retval (Any): The return value of the task.
            task_id (str): Unique id of the executed task.
            args (Tuple): Original arguments for the executed task.
            kwargs (Dict): Original keyword arguments for the executed task.

        Returns:
            None: The return value of this handler is ignored.
        """
        pass

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        """Retry handler.

        This is run by the worker when the task is to be retried.

        Arguments:
            exc (Exception): The exception sent to :meth:`retry`.
            task_id (str): Unique id of the retried task.
            args (Tuple): Original arguments for the retried task.
            kwargs (Dict): Original keyword arguments for the retried task.
            einfo (~billiard.einfo.ExceptionInfo): Exception information.

        Returns:
            None: The return value of this handler is ignored.
        """
        pass

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        """Error handler.

        This is run by the worker when the task fails.

        Arguments:
            exc (Exception): The exception raised by the task.
            task_id (str): Unique id of the failed task.
            args (Tuple): Original arguments for the task that failed.
            kwargs (Dict): Original keyword arguments for the task that failed.
            einfo (~billiard.einfo.ExceptionInfo): Exception information.

        Returns:
            None: The return value of this handler is ignored.
        """
        pass

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        """Handler called after the task returns.

        Arguments:
            status (str): Current task state.
            retval (Any): Task return value/exception.
            task_id (str): Unique id of the task.
            args (Tuple): Original arguments for the task.
            kwargs (Dict): Original keyword arguments for the task.
            einfo (~billiard.einfo.ExceptionInfo): Exception information.

        Returns:
            None: The return value of this handler is ignored.
        """
        pass

    def add_trail(self, result):
        if self.trail:
            self.request.children.append(result)
        return result

    def push_request(self, *args, **kwargs):
        self.request_stack.push(Context(*args, **kwargs))

    def pop_request(self):
        self.request_stack.pop()

    def __repr__(self):
        """`repr(task)`"""
        return _reprtask(self, R_SELF_TASK if self.__self__ else R_INSTANCE)

    def _get_request(self):
        """Get current request object."""
        req = self.request_stack.top
        if req is None:
            # task was not called, but some may still expect a request
            # to be there, perhaps that should be deprecated.
            if self._default_request is None:
                self._default_request = Context()
            return self._default_request
        return req

    request = property(_get_request)

    def _get_exec_options(self):
        if self._exec_options is None:
            self._exec_options = extract_exec_options(self)
        return self._exec_options

    @property
    def backend(self):
        backend = self._backend
        if backend is None:
            return self.app.backend
        return backend

    @backend.setter
    def backend(self, value):  # noqa
        self._backend = value

    @property
    def __name__(self):
        return self.__class__.__name__
Example #10
0
    def test_instantiation(self):
        from celery.utils.threads import LocalStack

        with self.subTest("Name can't end with _orig"):
            # noinspection PyAbstractClass
            class TestTask(FireXTask):
                name = self.__module__ + "." + self.__class__.__name__ + "." \
                       + f"TestClass{REPLACEMENT_TASK_NAME_POSTFIX}"

            with self.assertRaises(IllegalTaskNameException):
                test_obj = TestTask()

        with self.subTest("Without overrides"):
            # Make sure you can instantiate without the need for the pre and post overrides
            # noinspection PyAbstractClass
            class TestTask(FireXTask):
                name = self.__module__ + "." + self.__class__.__name__ + "." + "TestClass"

                def run(self):
                    pass

            test_obj = TestTask()
            self.assertIsNotNone(test_obj, "Task object not instantiated")
            self.assertTrue(callable(test_obj.undecorated))

            test_obj.request_stack = LocalStack()  # simulate binding
            test_obj()

        with self.subTest("With overrides"):
            # create a class using the override
            class TestTask(FireXTask):
                ran = False
                pre_ran = False
                post_ran = False
                name = self.__module__ + "." + self.__class__.__name__ + "." + "TestClass"

                def pre_task_run(self):
                    TestTask.pre_ran = True

                def run(self):
                    TestTask.ran = True

                def post_task_run(self, results):
                    TestTask.post_ran = True

            test_obj = TestTask()
            self.assertIsNotNone(test_obj, "Task object not instantiated")
            self.assertTrue(callable(test_obj.undecorated))

            test_obj.request_stack = LocalStack()  # simulate binding
            test_obj()
            self.assertTrue(TestTask.pre_ran, "pre_task_run() was not called")
            self.assertTrue(TestTask.ran, "run() was not called")
            self.assertTrue(TestTask.post_ran,
                            "post_task_run() was not called")

        with self.subTest("Must have Run"):
            # noinspection PyAbstractClass
            class TestTask(FireXTask):
                name = self.__module__ + "." + self.__class__.__name__ + "." + "TestClass"

            test_obj = TestTask()
            test_obj.request_stack = LocalStack()  # simulate binding
            with self.assertRaises(NotImplementedError):
                test_obj()