-
Notifications
You must be signed in to change notification settings - Fork 16
/
background.py
213 lines (169 loc) · 6.27 KB
/
background.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import traceback
from copy import deepcopy
from typing import Iterable
from typing import TYPE_CHECKING
from portality.constants import BgjobOutcomeStatus
if TYPE_CHECKING:
from portality.models import BackgroundJob
from flask_login import login_user
from huey import RedisHuey
from portality import constants
from portality import models
from portality.bll import DOAJ
from portality.core import app
class BackgroundException(Exception):
pass
class RetryException(Exception):
pass
class BackgroundSummary(object):
def __init__(self, job_id, affected=None, error=None):
self.job_id = job_id
self.affected = affected if affected is not None else {}
self.error = error
def as_dict(self):
return {
"job_id": self.job_id,
"affected": self.affected,
"error": self.error
}
class BackgroundApi(object):
"""
~~BackgroundTasks:Feature~~
"""
@classmethod
def execute(self, background_task: 'BackgroundTask'):
# ~~->BackgroundTask:Process~~
# ~~->BackgroundJob:Model~~
job = background_task.background_job
ctx = None
acc = None
if job.user is not None:
ctx = app.test_request_context("/")
ctx.push()
# ~~-> Account:Model~~
acc = models.Account.pull(job.user) # FIXME: what happens when this is the "system" user
if acc is not None:
login_user(acc)
job.start()
job.add_audit_message("Job Started")
job.save()
try:
background_task.run()
if job.outcome_status == BgjobOutcomeStatus.Pending:
job.outcome_status = BgjobOutcomeStatus.Success
except RetryException:
if job.reference is None:
job.reference = {}
retries = job.reference.get("retries", 0)
job.reference["retries"] = retries + 1
job.save()
raise
except Exception as e:
job.fail()
job.add_audit_message("Error in Job Run")
job.add_audit_message("Caught in job runner during run: " + traceback.format_exc())
job.add_audit_message("Job Run Completed")
job.add_audit_message("Cleanup Started")
try:
background_task.cleanup()
except Exception as e:
job.fail()
job.add_audit_message("Error in Cleanup Run")
job.add_audit_message("Caught in job runner during cleanup: " + traceback.format_exc())
job.add_audit_message("Job Cleanup Completed")
job.add_audit_message("Job Finished")
if not job.is_failed():
job.success()
job.save()
# trigger a status change event
jdata = deepcopy(job.data)
del jdata["audit"]
eventsSvc = DOAJ.eventsService()
eventsSvc.trigger(models.Event(constants.BACKGROUND_JOB_FINISHED, job.user, {
"job": jdata
}))
if ctx is not None:
ctx.pop()
class BackgroundTask(object):
"""
All background tasks should extend from this object and override at least the following methods:
- run
- cleanup
- prepare (class method)
~~BackgroundTask:Process~~
"""
__action__ = None
""" static member variable defining the name of this task """
def __init__(self, background_job: 'BackgroundJob'):
self._background_job = background_job
@property
def background_job(self) -> 'BackgroundJob':
return self._background_job
def run(self):
"""
Execute the task as specified by the background_job
:return:
"""
raise NotImplementedError()
def cleanup(self):
"""
Cleanup after a successful OR failed run of the task
:return:
"""
raise NotImplementedError()
@classmethod
def prepare(cls, username, **kwargs):
"""
Take an arbitrary set of keyword arguments and return an instance of a BackgroundJob,
or fail with a suitable exception
:param username: the user creating the job
:param kwargs: arbitrary keyword arguments pertaining to this task type
:return: a BackgroundJob instance representing this task
"""
raise NotImplementedError()
@classmethod
def submit(cls, background_job):
"""
Submit the specified BackgroundJob to the background queue
:param background_job: the BackgroundJob instance
:return:
"""
raise NotImplementedError()
@classmethod
def get_param(cls, params, param_name, default=None):
return params.get('{}__{}'.format(cls.__action__, param_name), default)
@classmethod
def set_param(cls, params, param_name, value):
params['{}__{}'.format(cls.__action__, param_name)] = value
@classmethod
def create_job_params(cls, **raw_param_dict: dict):
new_param = {}
for k, v in raw_param_dict.items():
cls.set_param(new_param, k, v)
return new_param
@classmethod
def create_raw_param_dict(cls, job_params: dict, key_list: Iterable[str]):
raw_param_dict = {k: cls.get_param(job_params, k)
for k in key_list}
return raw_param_dict
@classmethod
def set_reference(cls, refs, ref_name, value):
refs['{}__{}'.format(cls.__action__, ref_name)] = value
@classmethod
def create_huey_helper(cls, task_queue: RedisHuey):
from portality.tasks.helpers import background_helper
return background_helper.RedisHueyTaskHelper(task_queue, cls.__action__)
class AdminBackgroundTask(BackgroundTask):
"""~~AdminBackgroundTask:Process->BackgroundTask:Process~~"""
@classmethod
def check_admin_privilege(cls, username):
# ~~->Account:Model~~
a = models.Account.pull(username)
if a is None:
# very unlikely, as they would have had to log in to get to here..
raise BackgroundException('Admin account that is being used to prepare this job does not exist.')
if not a.has_role('admin'):
raise BackgroundException('Account {} is not permitted to run this background task.'.format(username))
@classmethod
def prepare(cls, username, **kwargs):
cls.check_admin_privilege(username)