submission_processor.py 5.05 KB
Newer Older
Peter Stanko's avatar
Peter Stanko committed
1
import random
Peter Stanko's avatar
Peter Stanko committed
2
3
4
5
from pathlib import Path

from storage import UploadedEntity

Peter Stanko's avatar
Peter Stanko committed
6
7
8
import portal.tools.worker_client
from portal import logger, tools
from portal.database import Project, Submission, SubmissionState, Worker
Peter Stanko's avatar
Peter Stanko committed
9
from portal.database.models import WorkerState
Peter Stanko's avatar
Peter Stanko committed
10

Peter Stanko's avatar
Peter Stanko committed
11
log = logger.get_logger(__name__)
Peter Stanko's avatar
Peter Stanko committed
12
13
14
15
16
17


class SubmissionProcessor:
    def __init__(self, submission: Submission, params: dict = None):
        self._submission = submission
        self._params = params
18
19
        from portal.service.rest import RestService
        self._rest = RestService()
Peter Stanko's avatar
Peter Stanko committed
20
21
22
23
24
25
26

    @property
    def submission(self) -> Submission:
        return self._submission

    @property
    def params(self) -> dict:
Peter Stanko's avatar
Peter Stanko committed
27
        return self.submission.parameters
Peter Stanko's avatar
Peter Stanko committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

    @property
    def project(self) -> Project:
        return self.submission.project

    @property
    def celery(self):
        from portal.async_celery import celery_app
        return celery_app

    @property
    def storage(self):
        from portal import storage
        return storage

    def reset_task_id(self, state=None):
        if state is not None:
            self.submission.state = state

        self.submission.async_task_id = None
48
        self._rest.submissions.write_entity(self.submission)
Peter Stanko's avatar
Peter Stanko committed
49
50

    def submission_enqueue_ended(self):
51
        log.info(f"[ASYNC] Submission enqueue ended {self.submission.log_name}: {self.submission}")
Peter Stanko's avatar
Peter Stanko committed
52
53
54
        self.reset_task_id(state=SubmissionState.QUEUED)

    def get_delay_for_submission(self):
55
        log.debug(f"[ASYNC] Submission delay {self.submission.log_name}: {self.submission}")
Peter Stanko's avatar
Peter Stanko committed
56
57
58
59
60
61
62
63
64
65
        time_wait = self.project.config.submissions_cancellation_period
        return time_wait

    def dispatch_submission_processing(self):
        delay = self.get_delay_for_submission()
        args = (self.submission.id, self.params)
        from .tasks import start_processing_submission
        start_processing_submission.apply_async(args=args, countdown=delay)

    def submission_store_ended(self, version: str):
66
67
        log.info(f"[ASYNC] Submission preparation ended {self.submission.log_name}: "
                 f"{self.submission}")
Peter Stanko's avatar
Peter Stanko committed
68
69
70
71
        self.submission.source_hash = version
        self.reset_task_id(state=SubmissionState.READY)

    def download_submission(self):
Peter Stanko's avatar
Peter Stanko committed
72
        file_params = self.params['file_params']
73
        log.info(f"[ASYNC] Uploading submission: {self.submission.log_name} with {file_params}")
Peter Stanko's avatar
Peter Stanko committed
74
        updated_entity: UploadedEntity = self.storage. \
Peter Stanko's avatar
Peter Stanko committed
75
            submissions.create(entity_id=self.submission.id, **file_params)
Peter Stanko's avatar
Peter Stanko committed
76
77
78
        self.submission_store_ended(version=updated_entity.version)

    def clone(self, target):
79
        log.info(f"[ASYNC] Cloning submission: {self.submission.log_name} to {target.log_name}")
Peter Stanko's avatar
Peter Stanko committed
80
81
82
83
84
        self.storage.submissions.clone(self.submission.id, target.id)
        self.submission_store_ended(version=self.submission.source_hash)

    def send_to_worker(self):
        # TODO: implement processing
85
        log.info(f"[ASYNC] Sending submission to worker: {self.submission.log_name}")
Peter Stanko's avatar
Peter Stanko committed
86
87
        worker = self.schedule_submission_to_worker()
        self.execute_submission(worker)
Peter Stanko's avatar
Peter Stanko committed
88

Peter Stanko's avatar
Peter Stanko committed
89
90
    def upload_result(self, path, file_params):
        log.info(f"[ASYNC] Uploading result for the submission "
91
                 f"{self.submission.log_name} with {file_params}")
Peter Stanko's avatar
Peter Stanko committed
92
        self.storage.results.create(entity_id=self.submission.id, **file_params)
Peter Stanko's avatar
Peter Stanko committed
93
94
95
96
        Path(path).unlink()
        self.reset_task_id(SubmissionState.FINISHED)

    def process_submission(self):
97
        log.info(f"[ASYNC] Processing submission {self.submission.log_name}")
Peter Stanko's avatar
Peter Stanko committed
98
99
        self.download_submission()
        self.dispatch_submission_processing()
100
101

    def revoke_task(self):
102
        log.info(f'[ASYNC] Submission processing cancelled {self.submission.log_name}')
103
104
105
106
107
        task_id = self.submission.async_task_id
        if task_id:
            self.celery.control.revoke(task_id=task_id, terminate=True)
            self.reset_task_id(state=SubmissionState.CANCELLED)
        # TODO: Storage clean up
Peter Stanko's avatar
Peter Stanko committed
108

Peter Stanko's avatar
Peter Stanko committed
109
110
111
112
113
114
    def _get_avail_workers(self):
        course = self.submission.course
        workers = self._rest.workers.find_all()
        return [worker for worker in workers
                if worker.state == WorkerState.READY and course in worker.courses]

Peter Stanko's avatar
Peter Stanko committed
115
116
117
118
119
120
121
122
    # TODO implement - @mdujava
    # STUB: Select initialized worker
    def schedule_submission_to_worker(self) -> Worker:
        """Based on the features (worker tags) and preferences in project config
        schedule submission for the execution on initialized worker

        Returns(Worker): Worker instance on which the submission will be executed
        """
Peter Stanko's avatar
Peter Stanko committed
123
        workers = self._get_avail_workers()
Peter Stanko's avatar
Peter Stanko committed
124
125
126
127
128
129
130
131
132
133
        if not workers:
            self._worker_not_available()
        worker = random.choice(workers)  # randomly select a worker
        return worker

    def execute_submission(self, worker: Worker):
        worker_client = tools.worker_client.WorkerClient(worker=worker)
        worker_client.execute_submission(self.submission)

    def _worker_not_available(self):
134
        log.warning(f"[PROC] Worker is no available for submission: {self.submission.log_name}")
Peter Stanko's avatar
Peter Stanko committed
135
        pass