| 1 |
from time import sleep |
| 2 |
|
| 3 |
from tasks import identity_task, mul, wait_for_revoke, xsum |
| 4 |
from visitors import MonitoringIdStampingVisitor |
| 5 |
|
| 6 |
from celery.canvas import Signature, chain, chord, group |
| 7 |
from celery.result import AsyncResult |
| 8 |
|
| 9 |
|
| 10 |
def create_canvas(n: int) -> Signature: |
| 11 |
"""Creates a canvas to calculate: n * sum(1..n) * 10 |
| 12 |
For example, if n = 3, the result is 3 * (1 + 2 + 3) * 10 = 180 |
| 13 |
""" |
| 14 |
canvas = chain( |
| 15 |
group(identity_task.s(i) for i in range(1, n+1)) | xsum.s(), |
| 16 |
chord(group(mul.s(10) for _ in range(1, n+1)), xsum.s()), |
| 17 |
) |
| 18 |
|
| 19 |
return canvas |
| 20 |
|
| 21 |
|
| 22 |
def revoke_by_headers(result: AsyncResult, terminate: bool) -> None: |
| 23 |
"""Revokes the last task in the workflow by its stamped header |
| 24 |
|
| 25 |
Arguments: |
| 26 |
result (AsyncResult): Can be either a frozen or a running result |
| 27 |
terminate (bool): If True, the revoked task will be terminated |
| 28 |
""" |
| 29 |
result.revoke_by_stamped_headers({'mystamp': 'I am a stamp!'}, terminate=terminate) |
| 30 |
|
| 31 |
|
| 32 |
def prepare_workflow() -> Signature: |
| 33 |
"""Creates a canvas that waits "n * sum(1..n) * 10" in seconds, |
| 34 |
with n = 3. |
| 35 |
|
| 36 |
The canvas itself is stamped with a unique monitoring id stamp per task. |
| 37 |
The waiting task is stamped with different consistent stamp, which is used |
| 38 |
to revoke the task by its stamped header. |
| 39 |
""" |
| 40 |
canvas = create_canvas(n=3) |
| 41 |
canvas = canvas | wait_for_revoke.s() |
| 42 |
canvas.stamp(MonitoringIdStampingVisitor()) |
| 43 |
return canvas |
| 44 |
|
| 45 |
|
| 46 |
def run_then_revoke(): |
| 47 |
"""Runs the workflow and lets the waiting task run for a while. |
| 48 |
Then, the waiting task is revoked by its stamped header. |
| 49 |
|
| 50 |
The expected outcome is that the canvas will be calculated to the end, |
| 51 |
but the waiting task will be revoked and terminated *during its run*. |
| 52 |
|
| 53 |
See worker logs for more details. |
| 54 |
""" |
| 55 |
canvas = prepare_workflow() |
| 56 |
result = canvas.delay() |
| 57 |
print('Wait 5 seconds, then revoke the last task by its stamped header: "mystamp": "I am a stamp!"') |
| 58 |
sleep(5) |
| 59 |
print('Revoking the last task...') |
| 60 |
revoke_by_headers(result, terminate=True) |
| 61 |
|
| 62 |
|
| 63 |
def revoke_then_run(): |
| 64 |
"""Revokes the waiting task by its stamped header before it runs. |
| 65 |
Then, run the workflow, which will not run the waiting task that was revoked. |
| 66 |
|
| 67 |
The expected outcome is that the canvas will be calculated to the end, |
| 68 |
but the waiting task will not run at all. |
| 69 |
|
| 70 |
See worker logs for more details. |
| 71 |
""" |
| 72 |
canvas = prepare_workflow() |
| 73 |
result = canvas.freeze() |
| 74 |
revoke_by_headers(result, terminate=False) |
| 75 |
result = canvas.delay() |