| 1 |
import os |
| 2 |
from collections.abc import Iterable |
| 3 |
from time import sleep |
| 4 |
|
| 5 |
from pydantic import BaseModel |
| 6 |
|
| 7 |
from celery import Signature, Task, chain, chord, group, shared_task |
| 8 |
from celery.canvas import signature |
| 9 |
from celery.exceptions import Reject, SoftTimeLimitExceeded |
| 10 |
from celery.utils.log import get_task_logger |
| 11 |
|
| 12 |
LEGACY_TASKS_DISABLED = True |
| 13 |
try: |
| 14 |
# Imports that are not available in Celery 4 |
| 15 |
from celery.canvas import StampingVisitor |
| 16 |
except ImportError: |
| 17 |
LEGACY_TASKS_DISABLED = False |
| 18 |
|
| 19 |
|
| 20 |
def get_redis_connection(): |
| 21 |
from redis import StrictRedis |
| 22 |
|
| 23 |
host = os.environ.get("REDIS_HOST", "localhost") |
| 24 |
port = os.environ.get("REDIS_PORT", 6379) |
| 25 |
return StrictRedis(host=host, port=port) |
| 26 |
|
| 27 |
|
| 28 |
logger = get_task_logger(__name__) |
| 29 |
|
| 30 |
|
| 31 |
@shared_task |
| 32 |
def identity(x): |
| 33 |
"""Return the argument.""" |
| 34 |
return x |
| 35 |
|
| 36 |
|
| 37 |
@shared_task |
| 38 |
def add(x, y, z=None): |
| 39 |
"""Add two or three numbers.""" |
| 40 |
if z: |
| 41 |
return x + y + z |
| 42 |
else: |
| 43 |
return x + y |
| 44 |
|
| 45 |
|
| 46 |
@shared_task |
| 47 |
def mul(x: int, y: int) -> int: |
| 48 |
"""Multiply two numbers""" |
| 49 |
return x * y |
| 50 |
|
| 51 |
|
| 52 |
@shared_task |
| 53 |
def write_to_file_and_return_int(file_name, i): |
| 54 |
with open(file_name, mode='a', buffering=1) as file_handle: |
| 55 |
file_handle.write(str(i)+'\n') |
| 56 |
|
| 57 |
return i |
| 58 |
|
| 59 |
|
| 60 |
@shared_task(typing=False) |
| 61 |
def add_not_typed(x, y): |
| 62 |
"""Add two numbers, but don't check arguments""" |
| 63 |
return x + y |
| 64 |
|
| 65 |
|
| 66 |
@shared_task(ignore_result=True) |
| 67 |
def add_ignore_result(x, y): |
| 68 |
"""Add two numbers.""" |
| 69 |
return x + y |
| 70 |
|
| 71 |
|
| 72 |
@shared_task |
| 73 |
def raise_error(*args): |
| 74 |
"""Deliberately raise an error.""" |
| 75 |
raise ValueError("deliberate error") |
| 76 |
|
| 77 |
|
| 78 |
@shared_task |
| 79 |
def chain_add(x, y): |
| 80 |
( |
| 81 |
add.s(x, x) | add.s(y) |
| 82 |
).apply_async() |
| 83 |
|
| 84 |
|
| 85 |
@shared_task |
| 86 |
def chord_add(x, y): |
| 87 |
chord(add.s(x, x), add.s(y)).apply_async() |
| 88 |
|
| 89 |
|
| 90 |
@shared_task |
| 91 |
def delayed_sum(numbers, pause_time=1): |
| 92 |
"""Sum the iterable of numbers.""" |
| 93 |
# Allow the task to be in STARTED state for |
| 94 |
# a limited period of time. |
| 95 |
sleep(pause_time) |
| 96 |
return sum(numbers) |
| 97 |
|
| 98 |
|
| 99 |
@shared_task |
| 100 |
def delayed_sum_with_soft_guard(numbers, pause_time=1): |
| 101 |
"""Sum the iterable of numbers.""" |
| 102 |
try: |
| 103 |
sleep(pause_time) |
| 104 |
return sum(numbers) |
| 105 |
except SoftTimeLimitExceeded: |
| 106 |
return 0 |
| 107 |
|
| 108 |
|
| 109 |
@shared_task |
| 110 |
def tsum(nums): |
| 111 |
"""Sum an iterable of numbers.""" |
| 112 |
return sum(nums) |
| 113 |
|
| 114 |
|
| 115 |
@shared_task |
| 116 |
def xsum(nums): |
| 117 |
"""Sum of ints and lists.""" |
| 118 |
return sum(sum(num) if isinstance(num, Iterable) else num for num in nums) |
| 119 |
|
| 120 |
|
| 121 |
@shared_task(bind=True) |
| 122 |
def add_replaced(self, x, y): |
| 123 |
"""Add two numbers (via the add task).""" |
| 124 |
raise self.replace(add.s(x, y)) |
| 125 |
|
| 126 |
|
| 127 |
@shared_task(bind=True) |
| 128 |
def replace_with_chain(self, *args, link_msg=None): |
| 129 |
c = chain(identity.s(*args), identity.s()) |
| 130 |
link_sig = redis_echo.s() |
| 131 |
if link_msg is not None: |
| 132 |
link_sig.args = (link_msg,) |
| 133 |
link_sig.set(immutable=True) |
| 134 |
c.link(link_sig) |
| 135 |
|
| 136 |
return self.replace(c) |
| 137 |
|
| 138 |
|
| 139 |
@shared_task(bind=True) |
| 140 |
def replace_with_chain_which_raises(self, *args, link_msg=None): |
| 141 |
c = chain(identity.s(*args), raise_error.s()) |
| 142 |
link_sig = redis_echo.s() |
| 143 |
if link_msg is not None: |
| 144 |
link_sig.args = (link_msg,) |
| 145 |
link_sig.set(immutable=True) |
| 146 |
c.link_error(link_sig) |
| 147 |
|
| 148 |
return self.replace(c) |
| 149 |
|
| 150 |
|
| 151 |
@shared_task(bind=True) |
| 152 |
def replace_with_empty_chain(self, *_): |
| 153 |
return self.replace(chain()) |
| 154 |
|
| 155 |
|
| 156 |
@shared_task(bind=True) |
| 157 |
def add_to_all(self, nums, val): |
| 158 |
"""Add the given value to all supplied numbers.""" |
| 159 |
subtasks = [add.s(num, val) for num in nums] |
| 160 |
raise self.replace(group(*subtasks)) |
| 161 |
|
| 162 |
|
| 163 |
@shared_task(bind=True) |
| 164 |
def add_to_all_to_chord(self, nums, val): |
| 165 |
for num in nums: |
| 166 |
self.add_to_chord(add.s(num, val)) |
| 167 |
return 0 |
| 168 |
|
| 169 |
|
| 170 |
@shared_task(bind=True) |
| 171 |
def add_chord_to_chord(self, nums, val): |
| 172 |
subtasks = [add.s(num, val) for num in nums] |
| 173 |
self.add_to_chord(group(subtasks) | tsum.s()) |
| 174 |
return 0 |
| 175 |
|
| 176 |
|
| 177 |
@shared_task |
| 178 |
def print_unicode(log_message='hå它 valmuefrø', print_message='hiöäüß'): |
| 179 |
"""Task that both logs and print strings containing funny characters.""" |
| 180 |
logger.warning(log_message) |
| 181 |
print(print_message) |
| 182 |
|
| 183 |
|
| 184 |
@shared_task |
| 185 |
def return_exception(e): |
| 186 |
"""Return a tuple containing the exception message and sentinel value.""" |
| 187 |
return e, True |
| 188 |
|
| 189 |
|
| 190 |
@shared_task |
| 191 |
def sleeping(i, **_): |
| 192 |
"""Task sleeping for ``i`` seconds, and returning nothing.""" |
| 193 |
sleep(i) |
| 194 |
|
| 195 |
|
| 196 |
@shared_task(bind=True) |
| 197 |
def ids(self, i): |
| 198 |
"""Returns a tuple of ``root_id``, ``parent_id`` and |
| 199 |
the argument passed as ``i``.""" |
| 200 |
return self.request.root_id, self.request.parent_id, i |
| 201 |
|
| 202 |
|
| 203 |
@shared_task(bind=True) |
| 204 |
def collect_ids(self, res, i): |
| 205 |
"""Used as a callback in a chain or group where the previous tasks |
| 206 |
are :task:`ids`: returns a tuple of:: |
| 207 |
|
| 208 |
(previous_result, (root_id, parent_id, i)) |
| 209 |
""" |
| 210 |
return res, (self.request.root_id, self.request.parent_id, i) |
| 211 |
|
| 212 |
|
| 213 |
@shared_task(bind=True, default_retry_delay=1) |
| 214 |
def retry(self, return_value=None): |
| 215 |
"""Task simulating multiple retries. |
| 216 |
|
| 217 |
When return_value is provided, the task after retries returns |
| 218 |
the result. Otherwise it fails. |
| 219 |
""" |
| 220 |
if return_value: |
| 221 |
attempt = getattr(self, 'attempt', 0) |
| 222 |
print('attempt', attempt) |
| 223 |
if attempt >= 3: |
| 224 |
delattr(self, 'attempt') |
| 225 |
return return_value |
| 226 |
self.attempt = attempt + 1 |
| 227 |
|
| 228 |
raise self.retry(exc=ExpectedException(), countdown=5) |
| 229 |
|
| 230 |
|
| 231 |
@shared_task(bind=True, default_retry_delay=1) |
| 232 |
def retry_unpickleable(self, foo, bar, *, retry_kwargs): |
| 233 |
"""Task that fails with an unpickleable exception and is retried.""" |
| 234 |
raise self.retry(exc=UnpickleableException(foo, bar), **retry_kwargs) |
| 235 |
|
| 236 |
|
| 237 |
@shared_task(bind=True, expires=120.0, max_retries=1) |
| 238 |
def retry_once(self, *args, expires=None, max_retries=1, countdown=0.1): |
| 239 |
"""Task that fails and is retried. Returns the number of retries.""" |
| 240 |
if self.request.retries: |
| 241 |
return self.request.retries |
| 242 |
raise self.retry(countdown=countdown, |
| 243 |
expires=expires, |
| 244 |
max_retries=max_retries) |
| 245 |
|
| 246 |
|
| 247 |
@shared_task(bind=True, max_retries=1) |
| 248 |
def retry_once_priority(self, *args, expires=60.0, max_retries=1, |
| 249 |
countdown=0.1): |
| 250 |
"""Task that fails and is retried. Returns the priority.""" |
| 251 |
if self.request.retries: |
| 252 |
return self.request.delivery_info['priority'] |
| 253 |
raise self.retry(countdown=countdown, |
| 254 |
max_retries=max_retries) |
| 255 |
|
| 256 |
|
| 257 |
@shared_task(bind=True, max_retries=1) |
| 258 |
def retry_once_headers(self, *args, max_retries=1, |
| 259 |
countdown=0.1): |
| 260 |
"""Task that fails and is retried. Returns headers.""" |
| 261 |
if self.request.retries: |
| 262 |
return self.request.headers |
| 263 |
raise self.retry(countdown=countdown, |
| 264 |
max_retries=max_retries) |
| 265 |
|
| 266 |
|
| 267 |
@shared_task |
| 268 |
def redis_echo(message, redis_key="redis-echo"): |
| 269 |
"""Task that appends the message to a redis list.""" |
| 270 |
redis_connection = get_redis_connection() |
| 271 |
redis_connection.rpush(redis_key, message) |
| 272 |
|
| 273 |
|
| 274 |
@shared_task(bind=True) |
| 275 |
def redis_echo_group_id(self, _, redis_key="redis-group-ids"): |
| 276 |
redis_connection = get_redis_connection() |
| 277 |
redis_connection.rpush(redis_key, self.request.group) |
| 278 |
|
| 279 |
|
| 280 |
@shared_task |
| 281 |
def redis_count(redis_key="redis-count"): |
| 282 |
"""Task that increments a specified or well-known redis key.""" |
| 283 |
redis_connection = get_redis_connection() |
| 284 |
redis_connection.incr(redis_key) |
| 285 |
|
| 286 |
|
| 287 |
@shared_task(bind=True) |
| 288 |
def second_order_replace1(self, state=False): |
| 289 |
redis_connection = get_redis_connection() |
| 290 |
if not state: |
| 291 |
redis_connection.rpush('redis-echo', 'In A') |
| 292 |
new_task = chain(second_order_replace2.s(), |
| 293 |
second_order_replace1.si(state=True)) |
| 294 |
raise self.replace(new_task) |
| 295 |
else: |
| 296 |
redis_connection.rpush('redis-echo', 'Out A') |
| 297 |
|
| 298 |
|
| 299 |
@shared_task(bind=True) |
| 300 |
def second_order_replace2(self, state=False): |
| 301 |
redis_connection = get_redis_connection() |
| 302 |
if not state: |
| 303 |
redis_connection.rpush('redis-echo', 'In B') |
| 304 |
new_task = chain(redis_echo.s("In/Out C"), |
| 305 |
second_order_replace2.si(state=True)) |
| 306 |
raise self.replace(new_task) |
| 307 |
else: |
| 308 |
redis_connection.rpush('redis-echo', 'Out B') |
| 309 |
|
| 310 |
|
| 311 |
@shared_task(bind=True) |
| 312 |
def build_chain_inside_task(self): |
| 313 |
"""Task to build a chain. |
| 314 |
|
| 315 |
This task builds a chain and returns the chain's AsyncResult |
| 316 |
to verify that Asyncresults are correctly converted into |
| 317 |
serializable objects""" |
| 318 |
test_chain = ( |
| 319 |
add.s(1, 1) | |
| 320 |
add.s(2) | |
| 321 |
group( |
| 322 |
add.s(3), |
| 323 |
add.s(4) |
| 324 |
) | |
| 325 |
add.s(5) |
| 326 |
) |
| 327 |
result = test_chain() |
| 328 |
return result |
| 329 |
|
| 330 |
|
| 331 |
class ExpectedException(Exception): |
| 332 |
"""Sentinel exception for tests.""" |
| 333 |
|
| 334 |
def __eq__(self, other): |
| 335 |
return ( |
| 336 |
other is not None and |
| 337 |
isinstance(other, ExpectedException) and |
| 338 |
self.args == other.args |
| 339 |
) |
| 340 |
|
| 341 |
def __hash__(self): |
| 342 |
return hash(self.args) |
| 343 |
|
| 344 |
|
| 345 |
class UnpickleableException(Exception): |
| 346 |
"""Exception that doesn't survive a pickling roundtrip (dump + load).""" |
| 347 |
|
| 348 |
def __init__(self, foo, bar=None): |
| 349 |
if bar is None: |
| 350 |
# We define bar with a default value in the signature so that |
| 351 |
# it's easier to add a break point here to find out when the |
| 352 |
# exception is being unpickled. |
| 353 |
raise TypeError("bar must be provided") |
| 354 |
|
| 355 |
super().__init__(foo) |
| 356 |
self.bar = bar |
| 357 |
|
| 358 |
|
| 359 |
@shared_task |
| 360 |
def fail(*args): |
| 361 |
"""Task that simply raises ExpectedException.""" |
| 362 |
args = ("Task expected to fail",) + args |
| 363 |
raise ExpectedException(*args) |
| 364 |
|
| 365 |
|
| 366 |
@shared_task() |
| 367 |
def fail_unpickleable(foo, bar): |
| 368 |
"""Task that raises an unpickleable exception.""" |
| 369 |
raise UnpickleableException(foo, bar) |
| 370 |
|
| 371 |
|
| 372 |
@shared_task(bind=True) |
| 373 |
def fail_replaced(self, *args): |
| 374 |
"""Replace this task with one which raises ExpectedException.""" |
| 375 |
raise self.replace(fail.si(*args)) |
| 376 |
|
| 377 |
|
| 378 |
@shared_task(bind=True) |
| 379 |
def return_priority(self, *_args): |
| 380 |
return "Priority: %s" % self.request.delivery_info['priority'] |
| 381 |
|
| 382 |
|
| 383 |
@shared_task(bind=True) |
| 384 |
def return_properties(self): |
| 385 |
return self.request.properties |
| 386 |
|
| 387 |
|
| 388 |
class ClassBasedAutoRetryTask(Task): |
| 389 |
name = 'auto_retry_class_task' |
| 390 |
autoretry_for = (ValueError,) |
| 391 |
retry_kwargs = {'max_retries': 1} |
| 392 |
retry_backoff = True |
| 393 |
|
| 394 |
def run(self): |
| 395 |
if self.request.retries: |
| 396 |
return self.request.retries |
| 397 |
raise ValueError() |
| 398 |
|
| 399 |
|
| 400 |
# The signatures returned by these tasks wouldn't actually run because the |
| 401 |
# arguments wouldn't be fulfilled - we never actually delay them so it's fine |
| 402 |
@shared_task |
| 403 |
def return_nested_signature_chain_chain(): |
| 404 |
return chain(chain([add.s()])) |
| 405 |
|
| 406 |
|
| 407 |
@shared_task |
| 408 |
def return_nested_signature_chain_group(): |
| 409 |
return chain(group([add.s()])) |
| 410 |
|
| 411 |
|
| 412 |
@shared_task |
| 413 |
def return_nested_signature_chain_chord(): |
| 414 |
return chain(chord([add.s()], add.s())) |
| 415 |
|
| 416 |
|
| 417 |
@shared_task |
| 418 |
def return_nested_signature_group_chain(): |
| 419 |
return group(chain([add.s()])) |
| 420 |
|
| 421 |
|
| 422 |
@shared_task |
| 423 |
def return_nested_signature_group_group(): |
| 424 |
return group(group([add.s()])) |
| 425 |
|
| 426 |
|
| 427 |
@shared_task |
| 428 |
def return_nested_signature_group_chord(): |
| 429 |
return group(chord([add.s()], add.s())) |
| 430 |
|
| 431 |
|
| 432 |
@shared_task |
| 433 |
def return_nested_signature_chord_chain(): |
| 434 |
return chord(chain([add.s()]), add.s()) |
| 435 |
|
| 436 |
|
| 437 |
@shared_task |
| 438 |
def return_nested_signature_chord_group(): |
| 439 |
return chord(group([add.s()]), add.s()) |
| 440 |
|
| 441 |
|
| 442 |
@shared_task |
| 443 |
def return_nested_signature_chord_chord(): |
| 444 |
return chord(chord([add.s()], add.s()), add.s()) |
| 445 |
|
| 446 |
|
| 447 |
@shared_task |
| 448 |
def rebuild_signature(sig_dict): |
| 449 |
sig_obj = Signature.from_dict(sig_dict) |
| 450 |
|
| 451 |
def _recurse(sig): |
| 452 |
if not isinstance(sig, Signature): |
| 453 |
raise TypeError(f"{sig!r} is not a signature object") |
| 454 |
# Most canvas types have a `tasks` attribute |
| 455 |
if isinstance(sig, (chain, group, chord)): |
| 456 |
for task in sig.tasks: |
| 457 |
_recurse(task) |
| 458 |
# `chord`s also have a `body` attribute |
| 459 |
if isinstance(sig, chord): |
| 460 |
_recurse(sig.body) |
| 461 |
_recurse(sig_obj) |
| 462 |
|
| 463 |
|
| 464 |
@shared_task |
| 465 |
def errback_old_style(request_id): |
| 466 |
redis_count(request_id) |
| 467 |
return request_id |
| 468 |
|
| 469 |
|
| 470 |
@shared_task |
| 471 |
def errback_new_style(request, exc, tb): |
| 472 |
redis_count(request.id) |
| 473 |
return request.id |
| 474 |
|
| 475 |
|
| 476 |
@shared_task |
| 477 |
def replaced_with_me(): |
| 478 |
return True |
| 479 |
|
| 480 |
|
| 481 |
class AddParameterModel(BaseModel): |
| 482 |
x: int |
| 483 |
y: int |
| 484 |
|
| 485 |
|
| 486 |
class AddResultModel(BaseModel): |
| 487 |
result: int |
| 488 |
|
| 489 |
|
| 490 |
@shared_task(pydantic=True) |
| 491 |
def add_pydantic(data: AddParameterModel) -> AddResultModel: |
| 492 |
"""Add two numbers, but with parameters and results using Pydantic model serialization.""" |
| 493 |
value = data.x + data.y |
| 494 |
return AddResultModel(result=value) |
| 495 |
|
| 496 |
|
| 497 |
@shared_task(pydantic=True) |
| 498 |
def add_pydantic_string_annotations(data: "AddParameterModel") -> "AddResultModel": |
| 499 |
"""Add two numbers, but with string-annotated Pydantic models (__future__.annotations bug).""" |
| 500 |
value = data.x + data.y |
| 501 |
return AddResultModel(result=value) |
| 502 |
|
| 503 |
|
| 504 |
if LEGACY_TASKS_DISABLED: |
| 505 |
class StampOnReplace(StampingVisitor): |
| 506 |
stamp = {"StampOnReplace": "This is the replaced task"} |
| 507 |
|
| 508 |
def on_signature(self, sig, **headers) -> dict: |
| 509 |
return self.stamp |
| 510 |
|
| 511 |
class StampedTaskOnReplace(Task): |
| 512 |
"""Custom task for stamping on replace""" |
| 513 |
|
| 514 |
def on_replace(self, sig): |
| 515 |
sig.stamp(StampOnReplace()) |
| 516 |
return super().on_replace(sig) |
| 517 |
|
| 518 |
@shared_task(bind=True, base=StampedTaskOnReplace) |
| 519 |
def replace_with_stamped_task(self: StampedTaskOnReplace, replace_with=None): |
| 520 |
if replace_with is None: |
| 521 |
replace_with = replaced_with_me.s() |
| 522 |
self.replace(signature(replace_with)) |
| 523 |
|
| 524 |
|
| 525 |
@shared_task(bind=True, acks_late=True) |
| 526 |
def store_success_then_reject(self): |
| 527 |
"""First delivery: store SUCCESS manually, then Reject to trigger redelivery. |
| 528 |
Second delivery: dedup finds SUCCESS, dispatches chain.""" |
| 529 |
from celery.backends.base import states |
| 530 |
if not self.request.delivery_info.get('redelivered'): |
| 531 |
self.backend.store_result(self.request.id, 'first-pass', states.SUCCESS) |
| 532 |
raise Reject(requeue=True) |
| 533 |
# When dedup is enabled the fast-path intercepts before reaching here, |
| 534 |
# so 'dedup-pass' is only returned when dedup is disabled. |
| 535 |
return 'dedup-pass' |
| 536 |
|
| 537 |
|
| 538 |
@shared_task(bind=True, acks_late=True) |
| 539 |
def reject_then_succeed(self): |
| 540 |
"""First delivery: Reject(requeue=True). Second delivery: succeed normally.""" |
| 541 |
if not self.request.delivery_info.get('redelivered'): |
| 542 |
raise Reject(requeue=True) |
| 543 |
return 'second-pass' |
| 544 |
|
| 545 |
|
| 546 |
@shared_task(soft_time_limit=2, time_limit=1) |
| 547 |
def soft_time_limit_must_exceed_time_limit(): |
| 548 |
pass |