|
| 1 | +from uuid import uuid4 |
| 2 | +from types import SimpleNamespace |
| 3 | + |
| 4 | +from django.db import models |
| 5 | +from django.utils.translation import gettext_lazy as _ |
| 6 | +from django.utils.timezone import now |
| 7 | + |
| 8 | +# NOTE: tasks are not registered in the database, but in a dispatcher registry |
| 9 | + |
| 10 | +TASK_STATES = SimpleNamespace( |
| 11 | + WAITING="waiting", |
| 12 | + # SKIPPED="skipped", |
| 13 | + RUNNING="running", |
| 14 | + COMPLETED="completed", |
| 15 | + FAILED="failed", |
| 16 | + # CANCELED="canceled", |
| 17 | + # CANCELING="canceling", |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +class Task(models.Model): |
| 22 | + """ |
| 23 | + Corresponds to a call of a task, as a higher-level abstraction around the dispatcher. |
| 24 | + Loosely modeled after pulpcore.Task |
| 25 | + """ |
| 26 | + uuid = models.UUIDField( |
| 27 | + primary_key=True, default=uuid4, editable=False, |
| 28 | + help_text=_('UUID that corresponds to the dispatcher task uuid') |
| 29 | + ) |
| 30 | + state = models.CharField( |
| 31 | + choices=[(s, s.title()) for s in sorted(vars(TASK_STATES).values())], |
| 32 | + default=TASK_STATES.WAITING, |
| 33 | + help_text=_('Choices of this field track with acknowledgement and completion of a task') |
| 34 | + ) |
| 35 | + name = models.TextField( |
| 36 | + help_text=_('Importable path for class or method') |
| 37 | + ) |
| 38 | + |
| 39 | + created = models.DateTimeField( |
| 40 | + auto_now_add=True, |
| 41 | + help_text=_('Time the publisher (submitter) of this task call created it, approximately the time of submission as well') |
| 42 | + ) |
| 43 | + # pulp has unblocking logic, like unblocked_at, we have no plans for that here |
| 44 | + started_at = models.DateTimeField( |
| 45 | + null=True, |
| 46 | + help_text=_('Time of acknowledgement, also approximately the time the task starts') |
| 47 | + ) |
| 48 | + finished_at = models.DateTimeField( |
| 49 | + null=True, |
| 50 | + help_text=_('Time task is cleared (whether failed or succeeded), may be unused if set to auto-delete') |
| 51 | + ) |
| 52 | + |
| 53 | + def mark_ack(self): |
| 54 | + self.state = TASK_STATES.RUNNING |
| 55 | + self.started_at = now() |
| 56 | + self.save(update_fields=['state', 'started_at']) |
| 57 | + |
| 58 | + def mark_completed(self): |
| 59 | + self.state = TASK_STATES.COMPLETED |
| 60 | + self.finished_at = now() |
| 61 | + |
| 62 | + def mark_failed(self): |
| 63 | + self.state = TASK_STATES.FAILED |
| 64 | + self.finished_at = now() |
0 commit comments