-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathtasks.py
More file actions
1952 lines (1635 loc) · 61.5 KB
/
tasks.py
File metadata and controls
1952 lines (1635 loc) · 61.5 KB
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import gzip
import itertools
import json
import shlex
import subprocess
import tarfile
import uuid
import zlib
from base64 import b64decode, b64encode
from binascii import hexlify
from lzma import LZMAError
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
import boto3
from billiard.exceptions import (
SoftTimeLimitExceeded as CelerySoftTimeLimitExceeded,
)
from celery import signature
from celery.utils.log import get_task_logger
from dateutil.relativedelta import relativedelta
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.db import transaction
from django.db.models import Count, DateTimeField, ExpressionWrapper, F, Q
from django.db.transaction import on_commit
from django.utils.module_loading import import_string
from django.utils.timezone import now
from lambda_tasks.decorators import lambda_task
from lambda_tasks.logging import task_logger
from lambda_tasks.timeouts import SoftTimeLimitExceeded
from grandchallenge.cases.models import (
DICOMImageSetUpload,
DICOMImageSetUploadStatusChoices,
Image,
RawImageUploadSession,
)
from grandchallenge.components.backends.amazon_ecs import ECSTaskOrchestrator
from grandchallenge.components.backends.exceptions import (
CIVNotEditableException,
ComponentException,
RetryStep,
RetryTask,
TaskCancelled,
)
from grandchallenge.components.emails import (
send_docker_not_made_active,
send_invalid_dockerfile_email,
)
from grandchallenge.components.exceptions import InstanceInUse, PriorStepFailed
from grandchallenge.components.registry import _get_registry_auth_config
from grandchallenge.core.celery import (
_retry,
acks_late_2xlarge_task,
acks_late_micro_short_task,
)
from grandchallenge.core.error_messages import SystemErrorMessages
from grandchallenge.core.exceptions import LockNotAcquiredException
from grandchallenge.core.templatetags.remove_whitespace import oxford_comma
from grandchallenge.core.utils.error_messages import (
format_validation_error_message,
)
from grandchallenge.core.utils.query import check_lock_acquired
from grandchallenge.uploads.models import UserUpload
logger = get_task_logger(__name__)
@acks_late_2xlarge_task
@transaction.atomic
def update_all_container_image_shims():
"""Updates existing images to new versions of sagemaker shim"""
for app_label, model_name in (
("algorithms", "algorithmimage"),
("evaluation", "method"),
):
model = apps.get_model(app_label=app_label, model_name=model_name)
for instance in model.objects.executable_images().exclude(
latest_shimmed_version=settings.COMPONENTS_SAGEMAKER_SHIM_VERSION
):
on_commit(
update_container_image_shim.signature(
kwargs={
"pk": str(instance.pk),
"app_label": instance._meta.app_label,
"model_name": instance._meta.model_name,
}
).apply_async
)
@acks_late_2xlarge_task
def assign_docker_image_from_upload(
*, pk: uuid.UUID, app_label: str, model_name: str
):
model = apps.get_model(app_label=app_label, model_name=model_name)
instance = model.objects.get(pk=pk)
with transaction.atomic():
instance.user_upload.copy_object(to_field=instance.image)
instance.user_upload.delete()
@acks_late_2xlarge_task
def validate_docker_image( # noqa C901
*, pk: uuid.UUID, app_label: str, model_name: str, mark_as_desired: bool
):
model = apps.get_model(app_label=app_label, model_name=model_name)
instance = model.objects.get(pk=pk)
instance.import_status = instance.ImportStatusChoices.STARTED
instance.save()
if instance.is_manifest_valid is None:
try:
_validate_docker_image_manifest(instance=instance)
instance.is_manifest_valid = True
instance.save()
except ValidationError as error:
instance.is_manifest_valid = False
instance.status = oxford_comma(error)
instance.import_status = instance.ImportStatusChoices.FAILED
instance.save()
send_invalid_dockerfile_email(container_image=instance)
return
elif instance.is_manifest_valid is False:
# Nothing to do
return
upload_to_registry_and_sagemaker(
app_label=app_label,
model_name=model_name,
pk=pk,
mark_as_desired=mark_as_desired,
)
@acks_late_2xlarge_task
def upload_to_registry_and_sagemaker(
*, pk: uuid.UUID, app_label: str, model_name: str, mark_as_desired: bool
):
model = apps.get_model(app_label=app_label, model_name=model_name)
instance = model.objects.get(pk=pk)
instance.import_status = instance.ImportStatusChoices.STARTED
instance.save()
if not instance.is_in_registry:
try:
push_container_image(instance=instance)
instance.is_in_registry = True
instance.save()
except ValidationError as error:
instance.is_in_registry = False
instance.status = oxford_comma(error)
instance.import_status = instance.ImportStatusChoices.FAILED
instance.save()
send_invalid_dockerfile_email(container_image=instance)
return
if instance.SHIM_IMAGE and (
instance.latest_shimmed_version
!= settings.COMPONENTS_SAGEMAKER_SHIM_VERSION
):
shim_container_image(instance=instance)
instance.save()
instance.import_status = instance.ImportStatusChoices.COMPLETED
instance.save()
if mark_as_desired:
try:
instance.mark_desired_version()
except ValidationError as error:
send_docker_not_made_active(
container_image=instance, error_message=str(error)
)
@acks_late_2xlarge_task
def update_container_image_shim(
*,
pk: uuid.UUID,
app_label: str,
model_name: str,
):
model = apps.get_model(app_label=app_label, model_name=model_name)
instance = model.objects.get(pk=pk)
if (
instance.is_in_registry
and instance.SHIM_IMAGE
and (
instance.latest_shimmed_version
!= settings.COMPONENTS_SAGEMAKER_SHIM_VERSION
)
):
existing_shimmed_repo_tag = instance.shimmed_repo_tag
remove_tag_from_registry(repo_tag=existing_shimmed_repo_tag)
instance.latest_shimmed_version = ""
instance.save()
shim_container_image(instance=instance)
instance.save()
@acks_late_2xlarge_task
def remove_inactive_container_images():
"""Removes inactive container images from the registry"""
for app_label, model_name, related_name in (
("algorithms", "algorithm", "algorithm_container_images"),
("evaluation", "phase", "method_set"),
("workstations", "workstation", "workstationimage_set"),
):
model = apps.get_model(app_label=app_label, model_name=model_name)
for instance in model.objects.all():
queryset = getattr(instance, related_name).filter(
is_in_registry=True
)
if instance.active_image:
queryset = queryset.exclude(pk=instance.active_image.pk)
for image in queryset:
on_commit(
remove_container_image_from_registry.signature(
kwargs={
"pk": image.pk,
"app_label": image._meta.app_label,
"model_name": image._meta.model_name,
}
).apply_async
)
@acks_late_2xlarge_task
@transaction.atomic
def delete_failed_import_container_images():
from grandchallenge.algorithms.models import AlgorithmImage
from grandchallenge.components.models import ComponentImage
from grandchallenge.evaluation.models import Method
from grandchallenge.workstations.models import WorkstationImage
for model in (AlgorithmImage, Method, WorkstationImage):
for image in model.objects.filter(
is_removed=False,
import_status=ComponentImage.ImportStatusChoices.FAILED,
).iterator():
on_commit(
delete_container_image.signature(
kwargs={
"pk": image.pk,
"app_label": image._meta.app_label,
"model_name": image._meta.model_name,
}
).apply_async
)
@acks_late_2xlarge_task
@transaction.atomic
def delete_old_unsuccessful_container_images():
from grandchallenge.algorithms.models import AlgorithmImage, Job
from grandchallenge.evaluation.models import Evaluation, Method
from grandchallenge.workstations.models import WorkstationImage
querysets = [
WorkstationImage.objects.filter(
is_removed=False, created__lt=now() - relativedelta(years=1)
),
Method.objects.filter(
is_removed=False, created__lt=now() - relativedelta(years=1)
)
.annotate(
successful_evaluation_count=Count(
"evaluation", filter=Q(evaluation__status=Evaluation.SUCCESS)
)
)
.filter(successful_evaluation_count=0),
AlgorithmImage.objects.filter(
is_removed=False, created__lt=now() - relativedelta(months=3)
)
.annotate(
successful_job_count=Count(
"job", filter=Q(job__status=Job.SUCCESS)
)
)
.filter(successful_job_count=0),
]
for queryset in querysets:
for image in queryset.iterator():
on_commit(
delete_container_image.signature(
kwargs={
"pk": image.pk,
"app_label": image._meta.app_label,
"model_name": image._meta.model_name,
}
).apply_async
)
@acks_late_2xlarge_task(ignore_errors=(InstanceInUse,))
def remove_container_image_from_registry(
*, pk: uuid.UUID, app_label: str, model_name: str
):
"""Remove a container image from the registry"""
model = apps.get_model(app_label=app_label, model_name=model_name)
instance = model.objects.get(pk=pk)
from grandchallenge.algorithms.models import AlgorithmImage, Job
from grandchallenge.evaluation.models import Evaluation, Method
from grandchallenge.workstations.models import Session, WorkstationImage
if isinstance(instance, Method):
instance_in_use = (
Evaluation.objects.filter(
method=instance,
)
.active()
.exists()
)
elif isinstance(instance, AlgorithmImage):
instance_in_use = (
Evaluation.objects.filter(
submission__algorithm_image=instance,
)
.active()
.exists()
or Job.objects.filter(
algorithm_image=instance,
)
.active()
.exists()
)
elif isinstance(instance, WorkstationImage):
instance_in_use = (
Session.objects.filter(workstation_image=instance)
.active()
.exists()
)
else:
raise RuntimeError("Unknown instance type")
if instance_in_use:
raise InstanceInUse
if instance.latest_shimmed_version:
remove_tag_from_registry(repo_tag=instance.shimmed_repo_tag)
instance.latest_shimmed_version = ""
instance.is_desired_version = False
instance.save()
if instance.is_in_registry:
remove_tag_from_registry(repo_tag=instance.original_repo_tag)
instance.is_in_registry = False
instance.is_desired_version = False
instance.save()
@acks_late_2xlarge_task(ignore_errors=(InstanceInUse,))
def delete_container_image(*, pk: uuid.UUID, app_label: str, model_name: str):
from grandchallenge.algorithms.models import AlgorithmImage, Job
from grandchallenge.components.models import ComponentImage
from grandchallenge.evaluation.models import Evaluation, Method
from grandchallenge.workstations.models import WorkstationImage
remove_container_image_from_registry(
pk=pk, app_label=app_label, model_name=model_name
)
model = apps.get_model(app_label=app_label, model_name=model_name)
instance = model.objects.get(pk=pk)
if instance.import_status == ComponentImage.ImportStatusChoices.FAILED:
should_be_protected = False
elif isinstance(instance, Method):
should_be_protected = Evaluation.objects.filter(
method=instance,
status=Evaluation.SUCCESS,
).exists()
elif isinstance(instance, AlgorithmImage):
should_be_protected = Job.objects.filter(
algorithm_image=instance,
status=Job.SUCCESS,
).exists()
elif isinstance(instance, WorkstationImage):
should_be_protected = instance.created > (
now() - relativedelta(years=1)
)
else:
raise RuntimeError("Unknown instance type")
if should_be_protected:
raise InstanceInUse
if instance.image:
instance.image.delete(save=False)
instance.is_removed = True
instance.is_desired_version = False
instance.save()
def push_container_image(*, instance):
if not instance.is_manifest_valid:
raise RuntimeError("Cannot push invalid instance to registry")
try:
with NamedTemporaryFile(suffix=".tar") as o:
with instance.image.open(mode="rb") as im:
# Rewrite to tar as crane cannot handle gz
_decompress_tarball(in_fileobj=im, out_fileobj=o)
_repo_login_and_run(
command=["crane", "push", o.name, instance.original_repo_tag]
)
except OSError:
raise ValidationError(
"The container image is too large, please reduce the size by "
"optimizing the layers of the container image."
)
def remove_tag_from_registry(*, repo_tag):
if settings.COMPONENTS_REGISTRY_INSECURE:
raise NotImplementedError
else:
client = boto3.client(
"ecr", region_name=settings.COMPONENTS_AMAZON_ECR_REGION
)
repo_name, image_tag = repo_tag.rsplit(":", 1)
repo_name = repo_name.replace(
f"{settings.COMPONENTS_REGISTRY_URL}/", "", 1
)
client.batch_delete_image(
repositoryName=repo_name,
imageIds=[
{"imageTag": image_tag},
],
)
def _repo_login_and_run(*, command):
"""Logs in to a repo and runs a crane command"""
if settings.COMPONENTS_REGISTRY_INSECURE:
# Do not login to insecure registries
command.append("--insecure")
clean_command = shlex.join(command)
else:
auth_config = _get_registry_auth_config()
login_command = shlex.join(
[
"crane",
"auth",
"login",
settings.COMPONENTS_REGISTRY_URL,
"-u",
auth_config["username"],
"-p",
auth_config["password"],
]
)
clean_command = f"{login_command} && {shlex.join(command)}"
return subprocess.run(
["/bin/sh", "-c", clean_command],
check=True,
capture_output=True,
text=True,
)
def shim_container_image(*, instance):
"""Patches a container image with the SageMaker Shim executable"""
if not instance.is_in_registry:
raise RuntimeError(
"The instance must be in the registry to create a SageMaker model"
)
# Set the new version, so we can then get the value of the new tag.
# Do not save the instance until the container image has been mutated.
instance.latest_shimmed_version = (
settings.COMPONENTS_SAGEMAKER_SHIM_VERSION
)
new_repo_tag = instance.shimmed_repo_tag
original_repo_tag = instance.original_repo_tag
original_config = _get_container_image_config(
original_repo_tag=original_repo_tag
)
env_vars = _get_shim_env_vars(original_config=original_config)
_mutate_container_image(
original_repo_tag=original_repo_tag,
new_repo_tag=new_repo_tag,
version=instance.latest_shimmed_version,
env_vars=env_vars,
)
def encode_b64j(*, val):
"""Base64 encode a JSON serialised value"""
return b64encode(json.dumps(val).encode("utf-8")).decode("utf-8")
def _get_container_image_config(*, original_repo_tag):
"""Get the configuration of an existing container image"""
output = _repo_login_and_run(
command=["crane", "config", original_repo_tag]
)
return json.loads(output.stdout)
def _get_shim_env_vars(*, original_config):
"""Get the environment variables for a shimmed container image"""
cmd = original_config["config"].get("Cmd")
entrypoint = original_config["config"].get("Entrypoint")
user = original_config["config"]["User"]
return {
"GRAND_CHALLENGE_COMPONENT_CMD_B64J": encode_b64j(val=cmd),
"GRAND_CHALLENGE_COMPONENT_ENTRYPOINT_B64J": encode_b64j(
val=entrypoint
),
"GRAND_CHALLENGE_COMPONENT_USER": user,
}
def _mutate_container_image(
*, original_repo_tag, new_repo_tag, version, env_vars
):
"""Add the SageMaker Shim executable to a container image"""
with TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
new_layer = tmp_path / "sagemaker-shim.tar"
with tarfile.open(new_layer, "w") as f:
def _set_root_500_perms(
tarinfo,
):
tarinfo.uid = 0
tarinfo.gid = 0
tarinfo.mode = 0o500
return tarinfo
f.add(
name=(
f"{settings.COMPONENTS_SAGEMAKER_SHIM_LOCATION}/"
f"sagemaker-shim-{version}-Linux-x86_64"
),
arcname="/sagemaker-shim",
filter=_set_root_500_perms,
)
for dir in ["/input", "/output", "/tmp"]:
# staticx will unpack into /tmp
tarinfo = tarfile.TarInfo(dir)
tarinfo.type = tarfile.DIRTYPE
tarinfo.uid = 0
tarinfo.gid = 0
tarinfo.mode = 0o755 if dir == "/input" else 0o777
f.addfile(tarinfo=tarinfo)
_repo_login_and_run(
command=[
"crane",
"mutate",
original_repo_tag,
# Running as root is required on SageMaker Training
# due to the permissions of most of the filesystem
# including /tmp which we need to use
"--user",
"0",
"--cmd",
"",
"--entrypoint",
"/sagemaker-shim",
"--tag",
new_repo_tag,
"--append",
str(new_layer),
*itertools.chain(
*[["--env", f"{k}={v}"] for k, v in env_vars.items()]
),
]
)
def _decompress_tarball(*, in_fileobj, out_fileobj):
"""Create an uncompress tarball from a (compressed) tarball"""
with (
tarfile.open(fileobj=in_fileobj, mode="r") as it,
tarfile.open(fileobj=out_fileobj, mode="w|") as ot,
):
for member in it.getmembers():
extracted = it.extractfile(member)
ot.addfile(member, extracted)
def _validate_docker_image_manifest(*, instance) -> str:
config_and_sha256 = _get_image_config_and_sha256(instance=instance)
config = config_and_sha256["config"]
image_sha256 = config_and_sha256["image_sha256"]
instance.image_sha256 = f"sha256:{image_sha256}"
user = str(config["config"].get("User", "")).lower()
if (
user in ["", "root", "0"]
or user.startswith("0:")
or user.startswith("root:")
):
raise ValidationError(
"The container runs as root. Please add a user, group and "
"USER instruction to your Dockerfile, rebuild, test and "
"upload the container again, see "
"https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user"
)
architecture = config.get("architecture")
_, desired_arch = settings.COMPONENTS_CONTAINER_PLATFORM.split("/")
if architecture != desired_arch:
raise ValidationError(
f"Architecture type {architecture!r} is not supported. "
"Please provide a container image built for "
f"{desired_arch!r}."
)
instance.api_method = _get_image_api_method(config=config)
if instance._meta.model_name != "method":
# TODO Methods are currently allowed to be duplicated
model = apps.get_model(
app_label=instance._meta.app_label,
model_name=instance._meta.model_name,
)
if (
model.objects.filter(image_sha256=instance.image_sha256)
.exclude(pk=instance.pk)
.exists()
):
raise ValidationError(
"This container image has already been uploaded. "
"Please re-activate the existing container image or upload a new version."
)
def _get_image_config_and_sha256(*, instance):
try:
with (
instance.image.open(mode="rb") as im,
tarfile.open(fileobj=im, mode="r") as open_tarfile,
):
container_image_files = {
tarinfo.name: tarinfo
for tarinfo in open_tarfile.getmembers()
if tarinfo.isfile()
}
image_manifest = _get_image_manifest(
container_image_files=container_image_files,
open_tarfile=open_tarfile,
)
return _get_image_config_file(
image_manifest=image_manifest,
container_image_files=container_image_files,
open_tarfile=open_tarfile,
)
except (
EOFError,
zlib.error,
gzip.BadGzipFile,
LZMAError,
tarfile.ReadError,
MemoryError,
):
raise ValidationError("Could not decompress the container image file.")
def _get_image_manifest(*, container_image_files, open_tarfile):
try:
manifest = json.loads(
open_tarfile.extractfile(
container_image_files["manifest.json"]
).read()
)
except KeyError:
raise ValidationError(
"Could not find manifest.json in the container image file. "
"Was this created with docker save?"
)
if len(manifest) != 1:
raise ValidationError(
f"The container image file should only have 1 image. "
f"This file contains {len(manifest)}."
)
return manifest[0]
def _get_image_config_file(
*, image_manifest, container_image_files, open_tarfile
):
config_filename = image_manifest["Config"]
try:
config = json.loads(
open_tarfile.extractfile(
container_image_files[config_filename]
).read()
)
except KeyError:
raise ValidationError(
"Could not find the config file in the container image file. "
"Was this created with docker save?"
)
if config_filename.endswith(".json"):
# Docker <25 container image
image_sha256 = config_filename.split(".")[0]
else:
# Docker >=25 container image
image_sha256 = image_manifest["Config"].split("/")[-1]
if image_sha256.startswith("sha256:"):
# Images created by crane have a sha256 prefix
image_sha256 = image_sha256[7:]
if len(image_sha256) != 64:
raise ValidationError(
"The container image file does not have a valid sha256 hash."
)
return {"image_sha256": image_sha256, "config": config}
def _get_image_api_method(*, config):
from grandchallenge.components.models import APIMethodChoices
label = "org.grand-challenge.api-method"
allowed_values = APIMethodChoices.values
labels = config["config"].get("Labels") or {}
for key, value in labels.items():
if str(key).lower().strip() == label:
cleaned_value = (
str(value).lower().replace("'", "").replace('"', "").strip()
)
if cleaned_value in allowed_values:
return cleaned_value
else:
raise ValidationError(
f"The label {label} must be one of {allowed_values}, instead we found '{value}'."
)
else:
return APIMethodChoices.EXEC
def lock_for_utilization_update(*, algorithm_image_pk):
from grandchallenge.algorithms.models import AlgorithmImage
# Lock the algorithm and algorithm image to avoid conflicts
# when modifying JobUtilization objects
with check_lock_acquired():
AlgorithmImage.objects.filter(pk=algorithm_image_pk).select_related(
"algorithm"
).select_for_update(
nowait=True,
no_key=True,
).get()
@acks_late_2xlarge_task(retry_on=(LockNotAcquiredException,))
@transaction.atomic
def provision_job(
*, job_pk: uuid.UUID, job_app_label: str, job_model_name: str, backend: str
):
model = apps.get_model(app_label=job_app_label, model_name=job_model_name)
with check_lock_acquired():
job = model.objects.select_for_update(nowait=True).get(pk=job_pk)
executor = job.get_executor(backend=backend)
if not job.inputs_complete or job.status not in [job.PENDING, job.RETRY]:
raise RuntimeError("Job is not ready for provisioning")
try:
executor.provision(
input_civs=job.inputs.prefetch_related(
"interface", "image__files"
).all(),
input_prefixes=job.input_prefixes,
)
except ComponentException as e:
job.update_status(
status=job.FAILURE,
error_message=str(e),
detailed_error_message=e.message_details,
)
except Exception:
job.update_status(
status=job.FAILURE,
error_message=SystemErrorMessages.UNEXPECTED_ERROR,
)
logger.error("Could not provision job", exc_info=True)
else:
job.update_status(status=job.PROVISIONED)
on_commit(execute_job.signature(**job.signature_kwargs).apply_async)
@acks_late_micro_short_task(retry_on=(RetryStep,))
def execute_job(
*,
job_pk: uuid.UUID,
job_app_label: str,
job_model_name: str,
backend: str,
):
"""
Executes the component job, can block with some backends.
`execute_job` can raise `ComponentException` in which case
the job will be marked as failed and the error returned to the user.
Job must be in the PROVISIONED state.
Once the job has executed it will be in the EXECUTING or FAILURE states.
"""
model = apps.get_model(app_label=job_app_label, model_name=job_model_name)
job = model.objects.get(pk=job_pk)
executor = job.get_executor(backend=backend)
if job.status == job.PROVISIONED:
job.update_status(status=job.EXECUTING)
else:
on_commit(
deprovision_job.signature(**job.signature_kwargs).apply_async
)
raise PriorStepFailed("Job is not set to be executed")
if not job.container.can_execute:
# TODO matching on this error message is used, perhaps it should be cancelled instead, see #4119
msg = f"Container Image {job.container.pk} was not ready to be used"
job.update_status(status=job.FAILURE, error_message=msg)
raise PriorStepFailed(msg)
try:
executor.execute()
except RetryStep:
job.update_status(status=job.PROVISIONED)
raise
except ComponentException as e:
job.update_status(
status=job.FAILURE,
stdout=executor.stdout,
stderr=executor.stderr,
error_message=str(e),
detailed_error_message=e.message_details,
)
except (
CelerySoftTimeLimitExceeded,
SoftTimeLimitExceeded,
):
job.update_status(
status=job.FAILURE,
stdout=executor.stdout,
stderr=executor.stderr,
error_message=SystemErrorMessages.TIME_LIMIT_EXCEEDED,
)
except Exception:
job.update_status(
status=job.FAILURE,
stdout=executor.stdout,
stderr=executor.stderr,
error_message=SystemErrorMessages.UNEXPECTED_ERROR,
)
raise
def get_update_status_kwargs(*, executor=None):
if executor is not None:
return {
"stdout": executor.stdout,
"stderr": executor.stderr,
"utilization_duration": executor.utilization_duration,
"exec_duration": executor.exec_duration,
"invoke_duration": executor.invoke_duration,
"compute_cost_euro_millicents": executor.compute_cost_euro_millicents,
"runtime_metrics": executor.runtime_metrics,
}
else:
return {}
@lambda_task(retry_on=(RetryStep, LockNotAcquiredException))
def handle_event(*, event: dict, backend: str):
"""
Receives events when tasks have stops and determines what to do next.
In the case of transient failure the job could be scheduled again
on the backend. If the job is complete then sets stdout and stderr.
`handle_event` is expected to raise `ComponentException` in which case
the job will be marked as failed and the error returned to the user.
Job must be in the EXECUTING state.
Once the job has executed it will be in the EXECUTED or FAILURE states.
"""
Backend = import_string(backend) # noqa: N806
job_name = Backend.get_job_name(event=event)
job_params = Backend.get_job_params(job_name=job_name)
model = apps.get_model(
app_label=job_params.app_label,
model_name=job_params.model_name,
)
with check_lock_acquired():
job = model.objects.select_for_update(nowait=True).get(
pk=job_params.pk, attempt=job_params.attempt
)
executor = job.get_executor(backend=backend)
if job.status != job.EXECUTING:
# Nothing to do
return
if hasattr(job, "algorithm_image"):
lock_for_utilization_update(algorithm_image_pk=job.algorithm_image_id)
try:
executor.handle_event(event=event)
except TaskCancelled:
job.update_status(
status=job.CANCELLED, **get_update_status_kwargs(executor=executor)
)
return
except RetryStep:
raise
except RetryTask:
job.update_status(status=job.PROVISIONED)
_retry(
task=retry_task, signature_kwargs=job.signature_kwargs, retries=0
)
except ComponentException as e:
job.update_status(
status=job.FAILURE,
error_message=str(e),
detailed_error_message=e.message_details,
**get_update_status_kwargs(executor=executor),
)
except Exception as error:
job.update_status(
status=job.FAILURE,
error_message=SystemErrorMessages.UNEXPECTED_ERROR,
**get_update_status_kwargs(executor=executor),
)
logger.error(str(error), exc_info=True)
else:
job.update_status(
status=job.EXECUTED,
**get_update_status_kwargs(executor=executor),
)
on_commit(
parse_job_outputs.signature(**job.signature_kwargs).apply_async
)
@acks_late_2xlarge_task(retry_on=(LockNotAcquiredException,))
@transaction.atomic
def parse_job_outputs(
*, job_pk: uuid.UUID, job_app_label: str, job_model_name: str, backend: str
):
model = apps.get_model(app_label=job_app_label, model_name=job_model_name)
with check_lock_acquired():
job = model.objects.select_for_update(nowait=True).get(pk=job_pk)
executor = job.get_executor(backend=backend)
if job.status != job.EXECUTED:
raise RuntimeError("Job is not ready for output parsing")