submission_processor.py 6.83 KB
Newer Older
1
import json
Peter Stanko's avatar
Peter Stanko committed
2
import secrets
Peter Stanko's avatar
Peter Stanko committed
3
from pathlib import Path
4
from typing import Optional
Peter Stanko's avatar
Peter Stanko committed
5

6
from storage import UploadedEntity, entities
Peter Stanko's avatar
Peter Stanko committed
7

8
from portal import logger
Peter Stanko's avatar
Peter Stanko committed
9
from portal.database import Project, Submission, SubmissionState, Worker
Peter Stanko's avatar
Peter Stanko committed
10
from portal.database.models import WorkerState
11
from portal.service import errors
Peter Stanko's avatar
Peter Stanko committed
12

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


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

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

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

    @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
50
        self._save_submission()
Peter Stanko's avatar
Peter Stanko committed
51
52

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

    def get_delay_for_submission(self):
Peter Stanko's avatar
Peter Stanko committed
57
        log.info(f"[ASYNC] Submission delay {self.submission.log_name}: {self.submission}")
Peter Stanko's avatar
Peter Stanko committed
58
59
60
61
62
63
64
        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
65
        self.submission.scheduled_for = delay
66
        self._save_submission()
Peter Stanko's avatar
Peter Stanko committed
67
68
69
        start_processing_submission.apply_async(args=args, countdown=delay)

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

    def download_submission(self):
Peter Stanko's avatar
Peter Stanko committed
76
        file_params = self.params['file_params']
77
        log.info(f"[ASYNC] Uploading submission: {self.submission.log_name} with {file_params}")
78

Peter Stanko's avatar
Peter Stanko committed
79
        updated_entity: UploadedEntity = self.storage. \
Peter Stanko's avatar
Peter Stanko committed
80
            submissions.create(entity_id=self.submission.id, **file_params)
Peter Stanko's avatar
Peter Stanko committed
81
82
83
        self.submission_store_ended(version=updated_entity.version)

    def clone(self, target):
84
        log.info(f"[ASYNC] Cloning submission: {self.submission.log_name} to {target.log_name}")
Peter Stanko's avatar
Peter Stanko committed
85
86
87
88
89
        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
90
        log.info(f"[ASYNC] Sending submission to worker: {self.submission.log_name}")
Peter Stanko's avatar
Peter Stanko committed
91
        worker = self.schedule_submission_to_worker()
92
93
        if worker:
            self.execute_submission(worker)
Peter Stanko's avatar
Peter Stanko committed
94

Peter Stanko's avatar
Peter Stanko committed
95
96
    def upload_result(self, path, file_params):
        log.info(f"[ASYNC] Uploading result for the submission "
97
                 f"{self.submission.log_name} with {file_params}")
Peter Stanko's avatar
Peter Stanko committed
98
        self.storage.results.create(entity_id=self.submission.id, **file_params)
Peter Stanko's avatar
Peter Stanko committed
99
100
101
102
        Path(path).unlink()
        self.reset_task_id(SubmissionState.FINISHED)

    def process_submission(self):
103
        log.info(f"[ASYNC] Processing submission {self.submission.log_name}")
104
105
106
107
108
        try:
            self.download_submission()
        except Exception as ex:
            log.error(f"[PROC] Storage submission download aborted due error: {ex}")
            self.abort_submission('Unable to download a submission')
Peter Stanko's avatar
Peter Stanko committed
109
        self.dispatch_submission_processing()
110
111

    def revoke_task(self):
112
        log.info(f'[ASYNC] Submission processing cancelled {self.submission.log_name}')
113
114
115
116
117
        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
118

Peter Stanko's avatar
Peter Stanko committed
119
120
121
122
123
124
    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
125
126
    # TODO implement - @mdujava
    # STUB: Select initialized worker
127
    def schedule_submission_to_worker(self) -> Optional[Worker]:
Peter Stanko's avatar
Peter Stanko committed
128
129
130
131
132
        """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
133
        workers = self._get_avail_workers()
Peter Stanko's avatar
Peter Stanko committed
134
135
        if not workers:
            self._worker_not_available()
136
            return None
Peter Stanko's avatar
Peter Stanko committed
137
        worker = secrets.choice(workers)  # randomly select a worker
Peter Stanko's avatar
Peter Stanko committed
138
        log.debug(f"[SCHED] Scheduling submission to worker -> {worker.log_name}")
Peter Stanko's avatar
Peter Stanko committed
139
140
141
        return worker

    def execute_submission(self, worker: Worker):
Peter Stanko's avatar
Peter Stanko committed
142
        worker_client = self._rest.workers(worker).worker_client
143
144
        self.submission.change_state(SubmissionState.IN_PROGRESS)
        self._save_submission()
Peter Stanko's avatar
Peter Stanko committed
145
146
147
        worker_client.execute_submission(self.submission)

    def _worker_not_available(self):
148
        log.warning(f"[PROC] Worker is no available for submission: {self.submission.log_name}")
149
150
151
152

    def process_result(self):
        storage_entity = self.storage.results.get(self.submission.id)
        # @mdujava - here put submission processing
Peter Stanko's avatar
Peter Stanko committed
153
        return self._submission_result_processing(storage_entity)
154
155
156
157
158
159
160
161
162
163

    def _submission_result_processing(self, storage_entity: entities.Entity):
        suite_stats = storage_entity.get('suite-stats.json')
        if not suite_stats.exists():
            log.error(f"[PROC] Suite stats for the {self.submission.log_name} have not been found.")
            raise errors.SuiteStatsNotExists(self.submission.id)
        stats = json.loads(suite_stats.read_text('utf-8'))
        return self._parse_stats(stats)

    def _parse_stats(self, stats: dict):
Peter Stanko's avatar
Peter Stanko committed
164
        log.debug(f"[PROC] Processing the stats: {stats}")
165
166
        points = stats.get('final_points', 0)
        result = stats.get('result', 'none').lower()
Peter Stanko's avatar
Peter Stanko committed
167
        log.debug(f"[PROC] Processing stats: points={points}, result={result}")
168
169
170
        self.submission.result = result
        self.submission.points = points
        return self.submission
171
172
173
174

    def abort_submission(self, message: str = 'Unknown error!'):
        self.submission.note['error'] = message
        self.reset_task_id(SubmissionState.ABORTED)
175
176
177

    def _save_submission(self):
        self._rest.submissions.write_entity(self.submission)