submission_processor.py 7.54 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 portal import logger
Peter Stanko's avatar
Peter Stanko committed
7
from portal.database import Project, Submission, SubmissionState, Worker
8
from portal.database.enums import WorkerState
9
from portal.service import errors
10
from portal.storage import UploadedEntity, entities
11
from portal.service.submissions import SubmissionsService
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


class SubmissionProcessor:
17
    def __init__(self, submission: Submission):
Peter Stanko's avatar
Peter Stanko committed
18
        self._submission = submission
Peter Stanko's avatar
Peter Stanko committed
19
        from portal.service.services_collection import ServicesCollection
20
        self._services = ServicesCollection()
Peter Stanko's avatar
Peter Stanko committed
21

22
23
24
25
    @property
    def submission_service(self) -> SubmissionsService:
        return self._services.submissions(self.submission)

Peter Stanko's avatar
Peter Stanko committed
26
27
28
29
30
31
    @property
    def submission(self) -> Submission:
        return self._submission

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

    @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):
45
46
        from portal import storage_wrapper
        return storage_wrapper
Peter Stanko's avatar
Peter Stanko committed
47

Peter Stanko's avatar
Peter Stanko committed
48
    def reset_task_id(self, state=None, message: str = None):
Peter Stanko's avatar
Peter Stanko committed
49
        if state is not None:
50
            self.submission_service.set_state(state, message=message)
Peter Stanko's avatar
Peter Stanko committed
51
52

        self.submission.async_task_id = None
53
        self._save_submission()
Peter Stanko's avatar
Peter Stanko committed
54
55

    def submission_enqueue_ended(self):
56
        log.info(f"[ASYNC] Submission enqueue ended {self.submission.log_name}: {self.submission}")
Peter Stanko's avatar
Peter Stanko committed
57
        self.reset_task_id(state=SubmissionState.QUEUED, message="Submission queue ended.")
Peter Stanko's avatar
Peter Stanko committed
58
59

    def get_delay_for_submission(self):
Peter Stanko's avatar
Peter Stanko committed
60
        log.info(f"[ASYNC] Submission delay {self.submission.log_name}: {self.submission}")
Peter Stanko's avatar
Peter Stanko committed
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()
66
        args = (self.submission.id,)
Peter Stanko's avatar
Peter Stanko committed
67
        from .tasks import start_processing_submission
68
        self.submission.scheduled_for = delay
69
        self._save_submission()
Peter Stanko's avatar
Peter Stanko committed
70
71
72
        start_processing_submission.apply_async(args=args, countdown=delay)

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

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

Peter Stanko's avatar
Peter Stanko committed
82
        updated_entity: UploadedEntity = self.storage. \
Peter Stanko's avatar
Peter Stanko committed
83
            submissions.create(dirname=self.submission.storage_dirname, **file_params)
Peter Stanko's avatar
Peter Stanko committed
84
85
86
        self.submission_store_ended(version=updated_entity.version)

    def clone(self, target):
87
        log.info(f"[ASYNC] Cloning submission: {self.submission.log_name} to {target.log_name}")
Peter Stanko's avatar
Peter Stanko committed
88
        self.storage.submissions.clone(self.submission.storage_dirname, target.id)
Peter Stanko's avatar
Peter Stanko committed
89
90
91
92
        self.submission_store_ended(version=self.submission.source_hash)

    def send_to_worker(self):
        # TODO: implement processing
93
        log.info(f"[ASYNC] Sending submission to worker: {self.submission.log_name}")
Peter Stanko's avatar
Peter Stanko committed
94
        worker = self.schedule_submission_to_worker()
95
96
        if worker:
            self.execute_submission(worker)
97
98
99
100
        else:
            log.warning(f"[EXEC] Worker not available to process submission: "
                        f"{self.submission.log_name}")
        self.abort_submission("No Worker available")
Peter Stanko's avatar
Peter Stanko committed
101

Peter Stanko's avatar
Peter Stanko committed
102
103
    def upload_result(self, path, file_params):
        log.info(f"[ASYNC] Uploading result for the submission "
104
                 f"{self.submission.log_name} with {file_params}")
Peter Stanko's avatar
Peter Stanko committed
105
        self.storage.results.create(dirname=self.submission.storage_dirname, **file_params)
Peter Stanko's avatar
Peter Stanko committed
106
        Path(path).unlink()
Peter Stanko's avatar
Peter Stanko committed
107
        self.reset_task_id(SubmissionState.FINISHED, message="Upload result ended")
Peter Stanko's avatar
Peter Stanko committed
108
109

    def process_submission(self):
110
        log.info(f"[ASYNC] Processing submission {self.submission.log_name}")
111
112
113
114
115
        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')
116
            return None
Peter Stanko's avatar
Peter Stanko committed
117
        self.dispatch_submission_processing()
118
119

    def revoke_task(self):
120
        log.info(f'[ASYNC] Submission processing cancelled {self.submission.log_name}')
121
122
123
        task_id = self.submission.async_task_id
        if task_id:
            self.celery.control.revoke(task_id=task_id, terminate=True)
Peter Stanko's avatar
Peter Stanko committed
124
            self.reset_task_id(state=SubmissionState.CANCELLED, message="Submission cancelled")
125
        # TODO: Storage clean up
Peter Stanko's avatar
Peter Stanko committed
126

Peter Stanko's avatar
Peter Stanko committed
127
128
    def _get_avail_workers(self):
        course = self.submission.course
129
        workers = self._services.workers.find_all()
Peter Stanko's avatar
Peter Stanko committed
130
131
132
        return [worker for worker in workers
                if worker.state == WorkerState.READY and course in worker.courses]

Peter Stanko's avatar
Peter Stanko committed
133
134
    # TODO implement - @mdujava
    # STUB: Select initialized worker
135
    def schedule_submission_to_worker(self) -> Optional[Worker]:
Peter Stanko's avatar
Peter Stanko committed
136
137
138
139
140
        """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
141
        workers = self._get_avail_workers()
Peter Stanko's avatar
Peter Stanko committed
142
143
        if not workers:
            self._worker_not_available()
144
            return None
Peter Stanko's avatar
Peter Stanko committed
145
        worker = secrets.choice(workers)  # randomly select a worker
Peter Stanko's avatar
Peter Stanko committed
146
        log.debug(f"[SCHED] Scheduling submission to worker -> {worker.log_name}")
Peter Stanko's avatar
Peter Stanko committed
147
148
149
        return worker

    def execute_submission(self, worker: Worker):
150
        worker_client = self._services.workers(worker).worker_client
Peter Stanko's avatar
Peter Stanko committed
151
        message = "Executing submission using worker"
152
        self.submission_service.set_state(SubmissionState.IN_PROGRESS, message=message)
153
        self._save_submission()
Peter Stanko's avatar
Peter Stanko committed
154
155
156
        worker_client.execute_submission(self.submission)

    def _worker_not_available(self):
157
        log.warning(f"[PROC] Worker is no available for submission: {self.submission.log_name}")
158
159

    def process_result(self):
160
        storage_entity = self.storage.results.get(self.submission.storage_dirname)
161
        # @mdujava - here put submission processing
Peter Stanko's avatar
Peter Stanko committed
162
        return self._submission_result_processing(storage_entity)
163
164
165
166
167

    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.")
168
            raise errors.SuiteStatsNotExists(self.submission.storage_dirname)
169
170
171
172
        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
173
        log.debug(f"[PROC] Processing the stats: {stats}")
174
175
        points = stats.get('final_points', 0)
        result = stats.get('result', 'none').lower()
Peter Stanko's avatar
Peter Stanko committed
176
        log.debug(f"[PROC] Processing stats: points={points}, result={result}")
177
178
179
        self.submission.result = result
        self.submission.points = points
        return self.submission
180
181

    def abort_submission(self, message: str = 'Unknown error!'):
182
        self.submission_service.set_state(SubmissionState.ABORTED, message=message)
183
184

    def _save_submission(self):
185
        self._services.submissions.write_entity(self.submission)