-
Notifications
You must be signed in to change notification settings - Fork 24
/
tasks.py
540 lines (458 loc) · 19.8 KB
/
tasks.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
'''
Created on Apr 5, 2012
@author: nils
'''
from urllib.parse import urljoin
from django.conf import settings
from bioblend import galaxy
import celery
from celery.result import TaskSetResult
from celery.task import Task, task
from celery.task.sets import TaskSet
import core
from core.models import Analysis, AnalysisResult, Workflow
from file_store.models import FileStoreItem, FileExtension
from file_store.tasks import FileImportTask
import tool_manager
from .models import AnalysisStatus
logger = celery.utils.log.get_task_logger(__name__)
logger.setLevel(celery.utils.LOG_LEVELS[settings.REFINERY_LOG_LEVEL])
RETRY_INTERVAL = 5 # seconds
class AnalysisHandlerTask(Task):
abstract = True
def on_failure(self, exc, task_id, args, kwargs, einfo):
"""Set analysis status to failure in case of errors not handled in the
monitoring task
"""
error_msg = "Monitoring task for analysis with UUID '{}' failed due " \
"to unexpected error: '{}: {}'".format(
args[0], einfo.type, einfo.exception)
logger.error(error_msg)
try:
analysis = Analysis.objects.get(uuid=args[0])
except (Analysis.DoesNotExist, Analysis.MultipleObjectsReturned) as e:
logger.error("Can not retrieve analysis with UUID '%s': '%s'",
args[0], e)
return
else:
analysis.terminate_file_import_tasks()
logger.error("Setting status of analysis '%s' to failure", analysis)
analysis.set_status(Analysis.FAILURE_STATUS, error_msg)
def _check_galaxy_history_state(analysis_uuid):
"""
Monitor the state of our Galaxy history from analysis.galaxy_progress().
Fail the `run_analysis` task appropriately if we run into trouble.
Update analysis_status.galaxy_history_progress &
analysis_status.galaxy_history_state along the way
"""
analysis = _get_analysis(analysis_uuid)
analysis_status = _get_analysis_status(analysis_uuid)
try:
percent_complete = analysis.galaxy_progress()
except RuntimeError:
analysis_status.set_galaxy_history_state(AnalysisStatus.ERROR)
error_msg = (
"Analysis '{}' failed during Galaxy Workflow run".format(analysis)
)
logger.error(error_msg)
analysis.set_status(Analysis.FAILURE_STATUS, error_msg)
analysis.send_email()
get_taskset_result(
analysis_status.refinery_import_task_group_id
).delete()
get_taskset_result(
analysis_status.galaxy_import_task_group_id
).delete()
analysis.galaxy_cleanup()
return
except galaxy.client.ConnectionError:
analysis_status.set_galaxy_history_state(
AnalysisStatus.UNKNOWN
)
run_analysis.retry(countdown=RETRY_INTERVAL)
else:
# workaround to avoid moving the progress bar backward
if not analysis_status.galaxy_history_progress:
analysis_status.galaxy_history_progress = percent_complete
analysis_status.save()
elif analysis_status.galaxy_history_progress < percent_complete:
analysis_status.galaxy_history_progress = percent_complete
analysis_status.save()
if percent_complete < 100:
analysis_status.set_galaxy_history_state(AnalysisStatus.PROGRESS)
run_analysis.retry(countdown=RETRY_INTERVAL)
else:
analysis_status.set_galaxy_history_state(AnalysisStatus.OK)
def _get_analysis(analysis_uuid):
"""
Try to fetch the Analysis from the given analysis_uuid. Fail the
`run_analysis` task if we cannot properly fetch it.
"""
try:
return Analysis.objects.get(uuid=analysis_uuid)
except (Analysis.DoesNotExist,
Analysis.MultipleObjectsReturned) as e:
logger.error("Can not retrieve analysis with UUID '%s': '%s'",
analysis_uuid, e)
run_analysis.update_state(state=celery.states.FAILURE)
return
def _get_analysis_status(analysis_uuid):
"""
Fetch the AnalysisStatus instance associated with the Analysis.
Fail the `run_analysis` task appropriately if we cannot fetch it.
"""
analysis = _get_analysis(analysis_uuid)
try:
return AnalysisStatus.objects.get(analysis=analysis)
except (AnalysisStatus.DoesNotExist,
AnalysisStatus.MultipleObjectsReturned) as exc:
logger.error("Can not retrieve status for analysis '%s': '%s'",
analysis, exc)
run_analysis.update_state(state=celery.states.FAILURE)
def get_taskset_result(task_group_id):
return TaskSetResult.restore(task_group_id)
def _get_workflow_tool(analysis_uuid):
workflow_tool = tool_manager.utils.get_workflow_tool(analysis_uuid)
if workflow_tool is None:
run_analysis.update_state(state=celery.states.FAILURE)
else:
return workflow_tool
def _attach_workflow_outputs(analysis_uuid):
"""
Attach the resulting files from the Galaxy workflow execution to
our Analysis
"""
analysis = _get_analysis(analysis_uuid)
if analysis.workflow.type == Workflow.ANALYSIS_TYPE:
tasks = analysis.attach_derived_nodes_to_dataset()
logger.info(
"Starting auxiliary file creation for analysis %s'", analysis
)
TaskSet(tasks=tasks).apply_async()
elif analysis.workflow.type == Workflow.DOWNLOAD_TYPE:
analysis.attach_outputs_downloads()
else:
logger.warning("Unknown workflow type '%s' in analysis '%s'",
analysis.workflow.type, analysis.name)
def _finalize_analysis(analysis_uuid):
"""
finalize analysis after attaching outputs from galaxy to the refinery file
system
"""
analysis = _get_analysis(analysis_uuid)
analysis_status = _get_analysis_status(analysis_uuid)
analysis.set_status(Analysis.SUCCESS_STATUS)
analysis.send_email()
logger.info("Analysis '%s' finished successfully", analysis)
analysis.galaxy_cleanup()
get_taskset_result(analysis_status.refinery_import_task_group_id).delete()
get_taskset_result(analysis_status.galaxy_import_task_group_id).delete()
get_taskset_result(analysis_status.galaxy_export_task_group_id).delete()
# Update file count and file size of the corresponding data set
analysis.data_set.file_count = analysis.data_set.get_file_count()
# FIXME: line below is causing analyses to be marked as failed
# analysis.data_set.file_size = analysis.data_set.get_file_size()
analysis.data_set.save()
def _galaxy_file_export(analysis_uuid):
"""
Check on the status of the files being exported from Galaxy.
Fail the task appropriately if we cannot retrieve the status.
"""
analysis = _get_analysis(analysis_uuid)
analysis_status = _get_analysis_status(analysis_uuid)
if not analysis_status.galaxy_export_task_group_id:
galaxy_export_tasks = _get_galaxy_download_task_ids(analysis)
logger.info(
"Starting downloading of results from Galaxy for analysis "
"'%s'", analysis)
galaxy_export_taskset = TaskSet(
tasks=galaxy_export_tasks
).apply_async()
galaxy_export_taskset.save()
analysis_status.galaxy_export_task_group_id = (
galaxy_export_taskset.taskset_id
)
analysis_status.save()
run_analysis.retry(countdown=RETRY_INTERVAL)
# check if analysis results have finished downloading from Galaxy
galaxy_export_taskset = get_taskset_result(
analysis_status.galaxy_export_task_group_id
)
if not galaxy_export_taskset.ready():
logger.debug("Results download pending for analysis '%s'", analysis)
run_analysis.retry(countdown=RETRY_INTERVAL)
# all tasks must have succeeded or failed
elif not galaxy_export_taskset.successful():
error_msg = ("Analysis '{}' failed while downloading results "
"from Galaxy".format(analysis))
logger.error(error_msg)
analysis.set_status(Analysis.FAILURE_STATUS, error_msg)
analysis.send_email()
get_taskset_result(
analysis_status.refinery_import_task_group_id
).delete()
get_taskset_result(
analysis_status.galaxy_import_task_group_id
).delete()
galaxy_export_taskset.delete()
analysis.galaxy_cleanup()
@task()
def _invoke_galaxy_workflow(analysis_uuid):
tool = _get_workflow_tool(analysis_uuid)
tool.create_dataset_collection()
galaxy_workflow_invocation_data = tool.invoke_workflow()
tool.analysis.history_id = galaxy_workflow_invocation_data["history_id"]
tool.analysis.save()
tool.update_galaxy_data(
tool.GALAXY_WORKFLOW_INVOCATION_DATA,
tool.galaxy_connection.workflows.show_invocation(
tool.get_workflow_internal_id(),
galaxy_workflow_invocation_data["id"]
)
)
def _refinery_file_import(analysis_uuid):
"""
Check on the status of the files being imported into Refinery.
Fail the task appropriately if we cannot retrieve the status.
"""
analysis = _get_analysis(analysis_uuid)
analysis_status = _get_analysis_status(analysis_uuid)
if not analysis_status.refinery_import_task_group_id:
logger.info("Starting analysis '%s'", analysis)
analysis.set_status(Analysis.RUNNING_STATUS)
logger.info("Starting input file import tasks for analysis '%s'",
analysis)
refinery_import_taskset = TaskSet(
tasks=analysis.get_refinery_import_task_signatures()
).apply_async()
refinery_import_taskset.save()
analysis_status.refinery_import_task_group_id = \
refinery_import_taskset.taskset_id
analysis_status.save()
run_analysis.retry(countdown=RETRY_INTERVAL)
# check if all files were successfully imported into Refinery
refinery_import_taskset = get_taskset_result(
analysis_status.refinery_import_task_group_id
)
if not refinery_import_taskset.ready():
logger.debug("Input file import pending for analysis '%s'",
analysis)
run_analysis.retry(countdown=RETRY_INTERVAL)
elif not refinery_import_taskset.successful():
error_msg = "Analysis '{}' failed during file import".format(
analysis)
logger.error(error_msg)
analysis.set_status(Analysis.FAILURE_STATUS, error_msg)
analysis.send_email()
refinery_import_taskset.delete()
@task(base=AnalysisHandlerTask, max_retries=None)
def run_analysis(analysis_uuid):
"""
Manage file importing/exporting, execution, and Galaxy operations for
an Analysis
"""
logger.info("Executing Analysis with UUID: ""%s", analysis_uuid)
analysis = _get_analysis(analysis_uuid)
# if cancelled by user
if analysis.failed():
analysis.terminate_file_import_tasks()
return
_get_analysis_status(analysis_uuid)
_refinery_file_import(analysis_uuid)
_run_galaxy_file_import(analysis_uuid)
_run_galaxy_workflow(analysis_uuid)
_check_galaxy_history_state(analysis_uuid)
_galaxy_file_export(analysis_uuid)
_attach_workflow_outputs(analysis_uuid)
_finalize_analysis(analysis_uuid)
def _run_galaxy_file_import(analysis_uuid):
analysis = _get_analysis(analysis_uuid)
analysis_status = _get_analysis_status(analysis_uuid)
tool = _get_workflow_tool(analysis_uuid)
if not analysis_status.galaxy_import_task_group_id:
library_dict = tool.create_galaxy_library()
history_dict = tool.create_galaxy_history()
# Update Tool with information about its objects living in Galaxy
tool.update_galaxy_data(tool.GALAXY_IMPORT_HISTORY_DICT, history_dict)
tool.update_galaxy_data(tool.GALAXY_LIBRARY_DICT, library_dict)
logger.debug("Starting file imports into Galaxy")
galaxy_import_tasks = tool.get_galaxy_import_tasks()
galaxy_file_import_taskset = TaskSet(
tasks=galaxy_import_tasks
).apply_async()
galaxy_file_import_taskset.save()
analysis_status.set_galaxy_import_task_group_id(
galaxy_file_import_taskset.taskset_id
)
analysis_status.set_galaxy_import_state(AnalysisStatus.PROGRESS)
run_analysis.retry(countdown=RETRY_INTERVAL)
# Check if data files were successfully imported into Galaxy
galaxy_file_import_taskset = get_taskset_result(
analysis_status.galaxy_import_task_group_id
)
if not galaxy_file_import_taskset.ready():
logger.debug("Analysis '%s' pending in Galaxy", analysis)
run_analysis.retry(countdown=RETRY_INTERVAL)
elif not galaxy_file_import_taskset.successful():
error_msg = "Analysis '{}' failed in Galaxy".format(analysis)
logger.error(error_msg)
analysis.set_status(Analysis.FAILURE_STATUS, error_msg)
analysis_status.set_galaxy_import_state(AnalysisStatus.ERROR)
analysis.send_email()
get_taskset_result(
analysis_status.refinery_import_task_group_id
).delete()
galaxy_file_import_taskset.delete()
analysis.galaxy_cleanup()
else:
analysis_status.set_galaxy_import_state(AnalysisStatus.OK)
def _run_galaxy_workflow(analysis_uuid):
"""
Create DataSetCollection objects in galaxy, and invoke the workflow
belonging to our tool.
"""
analysis = _get_analysis(analysis_uuid)
analysis_status = _get_analysis_status(analysis_uuid)
tool = _get_workflow_tool(analysis_uuid)
if not analysis_status.galaxy_workflow_task_group_id:
logger.debug("Starting workflow execution in Galaxy")
tool.update_file_relationships_with_galaxy_history_data()
galaxy_workflow_tasks = [
_invoke_galaxy_workflow.subtask((analysis_uuid,))
]
galaxy_workflow_taskset = TaskSet(
tasks=galaxy_workflow_tasks
).apply_async()
galaxy_workflow_taskset.save()
analysis_status.set_galaxy_workflow_task_group_id(
galaxy_workflow_taskset.taskset_id
)
analysis_status.set_galaxy_history_state(AnalysisStatus.PROGRESS)
run_analysis.retry(countdown=RETRY_INTERVAL)
# Check on the status of the running galaxy workflow
galaxy_workflow_taskset = get_taskset_result(
analysis_status.galaxy_workflow_task_group_id
)
if not galaxy_workflow_taskset.ready():
logger.debug("Analysis '%s' pending in Galaxy", analysis)
run_analysis.retry(countdown=RETRY_INTERVAL)
elif not galaxy_workflow_taskset.successful():
error_msg = "Analysis '{}' failed in Galaxy".format(analysis)
logger.error(error_msg)
analysis.set_status(Analysis.FAILURE_STATUS, error_msg)
analysis_status.set_galaxy_history_state(AnalysisStatus.ERROR)
analysis.send_email()
get_taskset_result(
analysis_status.refinery_import_task_group_id
).delete()
galaxy_workflow_taskset.delete()
analysis.galaxy_cleanup()
return
@task()
def _galaxy_file_import(analysis_uuid, file_store_item_uuid, history_dict,
library_dict):
tool = _get_workflow_tool(analysis_uuid)
try:
file_store_item = FileStoreItem.objects.get(uuid=file_store_item_uuid)
except (FileStoreItem.DoesNotExist,
FileStoreItem.MultipleObjectsReturned) as e:
logger.error("Couldn't fetch FileStoreItem from UUID: %s %s",
file_store_item_uuid, e)
run_analysis.update_state(state=celery.states.FAILURE)
return
file_store_url = file_store_item.get_datafile_url()
try:
file_url_absolute = core.utils.\
build_absolute_url(file_store_url)
except ValueError:
logger.error('{} is not a relative URL'.format(str(file_store_url)))
run_analysis.update_state(state=celery.states.FAILURE)
return
except RuntimeError:
logger.error('Could not build URL for {}'.format(str(file_store_url)))
run_analysis.update_state(state=celery.states.FAILURE)
return
library_dataset_dict = tool.upload_datafile_to_library_from_url(
library_dict["id"],
file_url_absolute
)
history_dataset_dict = tool.import_library_dataset_to_history(
history_dict["id"],
library_dataset_dict[0]["id"]
)
tool = _get_workflow_tool(analysis_uuid)
number_of_files = len(tool.get_input_file_uuid_list())
single_file_percentage = (100 / number_of_files)
analysis_status = _get_analysis_status(analysis_uuid)
analysis_status.galaxy_import_progress = (
analysis_status.galaxy_import_progress + single_file_percentage
)
analysis_status.save()
if (analysis_status.galaxy_import_progress ==
single_file_percentage * number_of_files):
# Imports are complete at this point so update
# `galaxy_import_progress` to `100`.
analysis_status.galaxy_import_progress = 100
analysis_status.save()
galaxy_to_refinery_file_mapping = {
tool.REFINERY_FILE_UUID: file_store_item_uuid,
tool.GALAXY_DATASET_HISTORY_ID: history_dataset_dict["id"]
}
return galaxy_to_refinery_file_mapping
def _get_galaxy_download_task_ids(analysis):
"""Get file import tasks for Galaxy analysis results"""
logger.debug("Preparing to download analysis results from Galaxy")
task_id_list = []
# retrieving list of files to download for workflow
tool = _get_workflow_tool(analysis.uuid)
try:
download_list = tool.create_analysis_output_node_connections()
except galaxy.client.ConnectionError as exc:
error_msg = \
"Error downloading Galaxy history files for analysis '%s': %s"
logger.error(error_msg, analysis.name, exc)
analysis.set_status(Analysis.FAILURE_STATUS, error_msg)
analysis.galaxy_cleanup()
return task_id_list
galaxy_instance = analysis.workflow.workflow_engine.instance
# Iterating through files in current galaxy history
for results in download_list:
# download file if result state is "ok"
if results['state'] == 'ok':
file_extension = results['file_ext']
# size of file defined by galaxy
file_size = results['file_size']
file_store_item = FileStoreItem(source=urljoin(
galaxy_instance.base_url,
"datasets/{}/display?to_ext=txt".format(results['id'])
))
# workaround to set the correct file type for zip archives of
# FastQC HTML reports produced by Galaxy dynamically
if file_extension == 'html':
file_extension = 'zip'
result_name = "{}.{}".format(results['name'], file_extension)
# assign file type manually since it cannot be inferred from source
try:
extension = FileExtension.objects.get(name=file_extension)
except (FileExtension.DoesNotExist,
FileExtension.MultipleObjectsReturned) as exc:
logger.warn("Could not assign type to file '%s' using "
"extension '%s': %s", file_store_item,
file_extension, exc)
else:
file_store_item.filetype = extension.filetype
file_store_item.save()
# adding history files to django model
analysis.results.add(
AnalysisResult.objects.create(
analysis=analysis, file_store_uuid=file_store_item.uuid,
file_name=result_name, file_type=file_extension
)
)
# downloading analysis results into file_store
# only download files if size is greater than 1
if file_size > 0:
task_id = FileImportTask().subtask((file_store_item.uuid,
result_name,))
task_id_list.append(task_id)
return task_id_list