21700: Install Bundler system-wide in Rails postinst
[arvados.git] / sdk / cwl / arvados_cwl / arvdocker.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 import logging
6 import sys
7 import threading
8 import copy
9 import re
10 import subprocess
11
12 from schema_salad.sourceline import SourceLine
13
14 import cwltool.docker
15 from cwltool.errors import WorkflowException
16 import arvados.commands.keepdocker
17
18 logger = logging.getLogger('arvados.cwl-runner')
19
20 def determine_image_id(dockerImageId):
21     for line in (
22         subprocess.check_output(  # nosec
23             ["docker", "images", "--no-trunc", "--all"]
24         )
25         .decode("utf-8")
26         .splitlines()
27     ):
28         try:
29             match = re.match(r"^([^ ]+)\s+([^ ]+)\s+([^ ]+)", line)
30             split = dockerImageId.split(":")
31             if len(split) == 1:
32                 split.append("latest")
33             elif len(split) == 2:
34                 #  if split[1] doesn't  match valid tag names, it is a part of repository
35                 if not re.match(r"[\w][\w.-]{0,127}", split[1]):
36                     split[0] = split[0] + ":" + split[1]
37                     split[1] = "latest"
38             elif len(split) == 3:
39                 if re.match(r"[\w][\w.-]{0,127}", split[2]):
40                     split[0] = split[0] + ":" + split[1]
41                     split[1] = split[2]
42                     del split[2]
43
44             # check for repository:tag match or image id match
45             if match and (
46                 (split[0] == match.group(1) and split[1] == match.group(2))
47                 or dockerImageId == match.group(3)
48             ):
49                 return match.group(3)
50         except ValueError:
51             pass
52
53     return None
54
55
56 def arv_docker_get_image(api_client, dockerRequirement, pull_image, runtimeContext):
57     """Check if a Docker image is available in Keep, if not, upload it using arv-keepdocker."""
58
59     project_uuid = runtimeContext.project_uuid
60     force_pull = runtimeContext.force_docker_pull
61     tmp_outdir_prefix = runtimeContext.tmp_outdir_prefix
62     match_local_docker = runtimeContext.match_local_docker
63     copy_deps = runtimeContext.copy_deps
64     cached_lookups = runtimeContext.cached_docker_lookups
65
66     if "http://arvados.org/cwl#dockerCollectionPDH" in dockerRequirement:
67         return dockerRequirement["http://arvados.org/cwl#dockerCollectionPDH"]
68
69     if "dockerImageId" not in dockerRequirement and "dockerPull" in dockerRequirement:
70         dockerRequirement = copy.deepcopy(dockerRequirement)
71         dockerRequirement["dockerImageId"] = dockerRequirement["dockerPull"]
72         if hasattr(dockerRequirement, 'lc'):
73             dockerRequirement.lc.data["dockerImageId"] = dockerRequirement.lc.data["dockerPull"]
74
75     if dockerRequirement["dockerImageId"] in cached_lookups:
76         return cached_lookups[dockerRequirement["dockerImageId"]]
77
78     with SourceLine(dockerRequirement, "dockerImageId", WorkflowException, logger.isEnabledFor(logging.DEBUG)):
79         sp = dockerRequirement["dockerImageId"].split(":")
80         image_name = sp[0]
81         image_tag = sp[1] if len(sp) > 1 else "latest"
82
83         out_of_project_images = arvados.commands.keepdocker.list_images_in_arv(api_client, 3,
84                                                                 image_name=image_name,
85                                                                 image_tag=image_tag,
86                                                                 project_uuid=None)
87
88         if copy_deps:
89             # Only images that are available in the destination project
90             images = arvados.commands.keepdocker.list_images_in_arv(api_client, 3,
91                                                                     image_name=image_name,
92                                                                     image_tag=image_tag,
93                                                                     project_uuid=project_uuid)
94         else:
95             images = out_of_project_images
96
97         if match_local_docker:
98             local_image_id = determine_image_id(dockerRequirement["dockerImageId"])
99             if local_image_id:
100                 # find it in the list
101                 found = False
102                 for i in images:
103                     if i[1]["dockerhash"] == local_image_id:
104                         found = True
105                         images = [i]
106                         break
107                 if not found:
108                     # force re-upload.
109                     images = []
110
111                 for i in out_of_project_images:
112                     if i[1]["dockerhash"] == local_image_id:
113                         found = True
114                         out_of_project_images = [i]
115                         break
116                 if not found:
117                     # force re-upload.
118                     out_of_project_images = []
119
120         if not images:
121             if not out_of_project_images:
122                 # Fetch Docker image if necessary.
123                 try:
124                     dockerjob = cwltool.docker.DockerCommandLineJob(None, None, None, None, None, None)
125                     result = dockerjob.get_image(dockerRequirement, pull_image,
126                                                                   force_pull, tmp_outdir_prefix)
127                     if not result:
128                         raise WorkflowException("Docker image '%s' not available" % dockerRequirement["dockerImageId"])
129                 except OSError as e:
130                     raise WorkflowException("While trying to get Docker image '%s', failed to execute 'docker': %s" % (dockerRequirement["dockerImageId"], e))
131
132             # Upload image to Arvados
133             args = []
134             if project_uuid:
135                 args.append("--project-uuid="+project_uuid)
136             args.append(image_name)
137             args.append(image_tag)
138             logger.info("Uploading Docker image %s:%s", image_name, image_tag)
139             try:
140                 arvados.commands.put.api_client = api_client
141                 arvados.commands.keepdocker.main(args, stdout=sys.stderr, install_sig_handlers=False, api=api_client)
142             except SystemExit as e:
143                 # If e.code is None or zero, then keepdocker exited normally and we can continue
144                 if e.code:
145                     raise WorkflowException("keepdocker exited with code %s" % e.code)
146
147             images = arvados.commands.keepdocker.list_images_in_arv(api_client, 3,
148                                                                     image_name=image_name,
149                                                                     image_tag=image_tag,
150                                                                     project_uuid=project_uuid)
151
152         if not images:
153             raise WorkflowException("Could not find Docker image %s:%s" % (image_name, image_tag))
154
155         pdh = api_client.collections().get(uuid=images[0][0]).execute()["portable_data_hash"]
156
157         cached_lookups[dockerRequirement["dockerImageId"]] = pdh
158
159     return pdh