This document describes the current stable version of Celery (5.7). For development docs, go here.
Source code for celery.bin.base
"""Click customizations for Celery."""
import inspect
import json
import numbers
from collections import OrderedDict
from functools import update_wrapper
from pprint import pformat
from typing import Any
import click
from click import Context, ParamType
from kombu.exceptions import OperationalError
from kombu.utils.objects import cached_property
from celery._state import get_current_app
from celery.exceptions import CeleryCommandException
from celery.platforms import EX_UNAVAILABLE
from celery.signals import user_preload_options
from celery.utils import text
from celery.utils.log import mlevel
from celery.utils.time import maybe_iso8601
try:
from pygments import highlight
from pygments.formatters import Terminal256Formatter
from pygments.lexers import PythonLexer
except ImportError:
def highlight(s, *args, **kwargs):
"""Place holder function in case pygments is missing."""
return s
LEXER = None
FORMATTER = None
else:
LEXER = PythonLexer()
FORMATTER = Terminal256Formatter()
[docs]
class CLIContext:
"""Context Object for the CLI."""
def __init__(self, app, no_color, workdir, quiet=False):
"""Initialize the CLI context."""
self.app = app or get_current_app()
self.no_color = no_color
self.quiet = quiet
self.workdir = workdir
@cached_property
def OK(self):
return self.style("OK", fg="green", bold=True)
@cached_property
def ERROR(self):
return self.style("ERROR", fg="red", bold=True)
[docs]
def style(self, message=None, **kwargs):
if self.no_color:
return message
else:
return click.style(message, **kwargs)
[docs]
def secho(self, message=None, **kwargs):
if self.no_color:
kwargs['color'] = False
click.echo(message, **kwargs)
else:
click.secho(message, **kwargs)
[docs]
def echo(self, message=None, **kwargs):
if self.no_color:
kwargs['color'] = False
click.echo(message, **kwargs)
else:
click.echo(message, **kwargs)
[docs]
def error(self, message=None, **kwargs):
kwargs['err'] = True
if self.no_color:
kwargs['color'] = False
click.echo(message, **kwargs)
else:
click.secho(message, **kwargs)
[docs]
def pretty(self, n):
if isinstance(n, list):
return self.OK, self.pretty_list(n)
if isinstance(n, dict):
if 'ok' in n or 'error' in n:
return self.pretty_dict_ok_error(n)
else:
s = json.dumps(n, sort_keys=True, indent=4)
if not self.no_color:
s = highlight(s, LEXER, FORMATTER)
return self.OK, s
if isinstance(n, str):
return self.OK, n
return self.OK, pformat(n)
[docs]
def pretty_list(self, n):
if not n:
return '- empty -'
return '\n'.join(
f'{self.style("*", fg="white")} {item}' for item in n
)
[docs]
def pretty_dict_ok_error(self, n):
try:
return (self.OK,
text.indent(self.pretty(n['ok'])[1], 4))
except KeyError:
pass
return (self.ERROR,
text.indent(self.pretty(n['error'])[1], 4))
[docs]
def say_chat(self, direction, title, body='', show_body=False):
if direction == '<-' and self.quiet:
return
dirstr = not self.quiet and f'{self.style(direction, fg="white", bold=True)} ' or ''
self.echo(f'{dirstr} {title}')
if body and show_body:
self.echo(body)
[docs]
def handle_remote_command_error(command: str, exc: Exception) -> None:
if isinstance(exc, click.ClickException):
raise
if isinstance(exc, OperationalError):
raise CeleryCommandException(
message=(
'Could not connect to the message broker. '
'Please make sure your broker (e.g., RabbitMQ or Redis) is running and '
f'the connection settings are correct. Reason: {exc}'
),
exit_code=EX_UNAVAILABLE,
) from exc
raise CeleryCommandException(
message=f'Unable to run the `{command}` command. Reason: {exc}',
exit_code=EX_UNAVAILABLE,
) from exc
def _preload_option_names(app):
return [option.name for option in app.user_options.get('preload', ())]
def _callback_accepts_keyword(fun, name):
"""Whether ``fun`` can take ``name`` without raising ``TypeError``."""
try:
parameters = inspect.signature(fun).parameters.values()
except (TypeError, ValueError):
return False
for parameter in parameters:
if parameter.kind is inspect.Parameter.VAR_KEYWORD:
return True
if parameter.kind is inspect.Parameter.POSITIONAL_ONLY:
continue
if parameter.name == name:
return True
return False
def _take_preload_options(app, kwargs, fun):
"""Copy preload values and drop only those ``fun`` cannot accept."""
taken = {}
for name in _preload_option_names(app):
if name not in kwargs:
continue
taken[name] = kwargs[name]
if not _callback_accepts_keyword(fun, name):
kwargs.pop(name)
return taken
def _handles_preload_options(fun):
seen = set()
while fun is not None and id(fun) not in seen:
seen.add(id(fun))
if getattr(fun, '_handles_preload_options', False):
return True
fun = getattr(fun, '__wrapped__', None)
return False
def _mark_preload_handler(wrapper, wrapped):
wrapper = update_wrapper(wrapper, wrapped)
wrapper._handles_preload_options = True
return wrapper
[docs]
def handle_preload_options(f):
"""Extract preload options and return a wrapped callable."""
if _handles_preload_options(f):
return f
def caller(ctx, *args, **kwargs):
app = ctx.obj.app
options = _take_preload_options(app, kwargs, f)
if options:
user_preload_options.send(sender=f, app=app, options=options)
return f(ctx, *args, **kwargs)
return _mark_preload_handler(caller, f)
[docs]
def consume_preload_options(fun):
"""Deliver preload options and drop only values the callback cannot accept.
Preload options are added to every sub-command, including commands
installed through the ``celery.commands`` entry-point group. Click
forwards them as keyword arguments. A callback with no ``**kwargs``
and no matching parameter then raises ``TypeError``. Those values are
delivered through ``user_preload_options`` instead. A callback that can
accept the name, including ``worker``, ``beat``, and ``events``, keeps it.
"""
if fun is None or _handles_preload_options(fun):
return fun
def caller(*args, **kwargs):
ctx = click.get_current_context()
app = ctx.obj.app
options = _take_preload_options(app, kwargs, fun)
if options:
user_preload_options.send(sender=fun, app=app, options=options)
return fun(*args, **kwargs)
return _mark_preload_handler(caller, fun)
[docs]
class CeleryOption(click.Option):
"""Customized option for Celery."""
[docs]
def get_default(self, ctx, *args, **kwargs):
if self.default_value_from_context:
self.default = ctx.obj[self.default_value_from_context]
return super().get_default(ctx, *args, **kwargs)
def __init__(self, *args, **kwargs):
"""Initialize a Celery option."""
self.help_group = kwargs.pop('help_group', None)
self.default_value_from_context = kwargs.pop('default_value_from_context', None)
super().__init__(*args, **kwargs)
[docs]
class CeleryCommand(click.Command):
"""Customized command for Celery."""
[docs]
def format_options(self, ctx, formatter):
"""Write all the options into the formatter if they exist."""
opts = OrderedDict()
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if rv is not None:
if hasattr(param, 'help_group') and param.help_group:
opts.setdefault(str(param.help_group), []).append(rv)
else:
opts.setdefault('Options', []).append(rv)
for name, opts_group in opts.items():
with formatter.section(name):
formatter.write_dl(opts_group)
[docs]
class DaemonOption(CeleryOption):
"""Common daemonization option"""
def __init__(self, *args, **kwargs):
super().__init__(args,
help_group=kwargs.pop("help_group", "Daemonization Options"),
callback=kwargs.pop("callback", self.daemon_setting),
**kwargs)
[docs]
def daemon_setting(self, ctx: Context, opt: CeleryOption, value: Any) -> Any:
"""
Try to fetch daemonization option from applications settings.
Use the daemon command name as prefix (eg. `worker` -> `worker_pidfile`)
"""
return value or getattr(ctx.obj.app.conf, f"{ctx.command.name}_{self.name}", None)
[docs]
class CeleryDaemonCommand(CeleryCommand):
"""Daemon commands."""
def __init__(self, *args, **kwargs):
"""Initialize a Celery command with common daemon options."""
super().__init__(*args, **kwargs)
self.params.extend((
DaemonOption("--logfile", "-f", help="Log destination; defaults to stderr"),
DaemonOption("--pidfile", help="PID file path; defaults to no PID file"),
DaemonOption("--uid", help="Drops privileges to this user ID"),
DaemonOption("--gid", help="Drops privileges to this group ID"),
DaemonOption("--umask", help="Create files and directories with this umask"),
DaemonOption("--executable", help="Override path to the Python executable"),
))
[docs]
class CommaSeparatedList(ParamType):
"""Comma separated list argument."""
name = "comma separated list"
[docs]
class JsonArray(ParamType):
"""JSON formatted array argument."""
name = "json array"
[docs]
def convert(self, value, param, ctx):
if isinstance(value, list):
return value
try:
v = json.loads(value)
except ValueError as e:
self.fail(str(e))
if not isinstance(v, list):
self.fail(f"{value} was not an array")
return v
[docs]
class JsonObject(ParamType):
"""JSON formatted object argument."""
name = "json object"
[docs]
def convert(self, value, param, ctx):
if isinstance(value, dict):
return value
try:
v = json.loads(value)
except ValueError as e:
self.fail(str(e))
if not isinstance(v, dict):
self.fail(f"{value} was not an object")
return v
[docs]
class ISO8601DateTime(ParamType):
"""ISO 8601 Date Time argument."""
name = "iso-86091"
[docs]
def convert(self, value, param, ctx):
try:
return maybe_iso8601(value)
except (TypeError, ValueError) as e:
self.fail(e)
[docs]
class ISO8601DateTimeOrFloat(ParamType):
"""ISO 8601 Date Time or float argument."""
name = "iso-86091 or float"
[docs]
def convert(self, value, param, ctx):
try:
return float(value)
except (TypeError, ValueError):
pass
try:
return maybe_iso8601(value)
except (TypeError, ValueError) as e:
self.fail(e)
[docs]
class LogLevel(click.Choice):
"""Log level option."""
def __init__(self):
"""Initialize the log level option with the relevant choices."""
super().__init__(('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'FATAL'))
[docs]
def convert(self, value, param, ctx):
if isinstance(value, numbers.Integral):
return value
value = value.upper()
value = super().convert(value, param, ctx)
return mlevel(value)
JSON_ARRAY = JsonArray()
JSON_OBJECT = JsonObject()
ISO8601 = ISO8601DateTime()
ISO8601_OR_FLOAT = ISO8601DateTimeOrFloat()
LOG_LEVEL = LogLevel()
COMMA_SEPARATED_LIST = CommaSeparatedList()