Merge branch 'master' into 10576-cwl-keep-fetcher
[arvados.git] / sdk / cwl / arvados_cwl / arvcontainer.py
1 import logging
2 import json
3 import os
4
5 import ruamel.yaml as yaml
6
7 from cwltool.errors import WorkflowException
8 from cwltool.process import get_feature, UnsupportedRequirement, shortname
9 from cwltool.pathmapper import adjustFiles
10 from cwltool.utils import aslist
11
12 import arvados.collection
13
14 from .arvdocker import arv_docker_get_image
15 from . import done
16 from .runner import Runner, arvados_jobs_image
17 from .fsaccess import CollectionFetcher
18
19 logger = logging.getLogger('arvados.cwl-runner')
20
21 class ArvadosContainer(object):
22     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
23
24     def __init__(self, runner):
25         self.arvrunner = runner
26         self.running = False
27         self.uuid = None
28
29     def update_pipeline_component(self, r):
30         pass
31
32     def run(self, dry_run=False, pull_image=True, **kwargs):
33         container_request = {
34             "command": self.command_line,
35             "owner_uuid": self.arvrunner.project_uuid,
36             "name": self.name,
37             "output_path": self.outdir,
38             "cwd": self.outdir,
39             "priority": 1,
40             "state": "Committed"
41         }
42         runtime_constraints = {}
43         mounts = {
44             self.outdir: {
45                 "kind": "tmp"
46             }
47         }
48         scheduling_parameters = {}
49
50         dirs = set()
51         for f in self.pathmapper.files():
52             _, p, tp = self.pathmapper.mapper(f)
53             if tp == "Directory" and '/' not in p[6:]:
54                 mounts[p] = {
55                     "kind": "collection",
56                     "portable_data_hash": p[6:]
57                 }
58                 dirs.add(p[6:])
59         for f in self.pathmapper.files():
60             _, p, tp = self.pathmapper.mapper(f)
61             if p[6:].split("/")[0] not in dirs:
62                 mounts[p] = {
63                     "kind": "collection",
64                     "portable_data_hash": p[6:]
65                 }
66
67         if self.generatefiles["listing"]:
68             raise UnsupportedRequirement("InitialWorkDirRequirement not supported with --api=containers")
69
70         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
71         if self.environment:
72             container_request["environment"].update(self.environment)
73
74         if self.stdin:
75             raise UnsupportedRequirement("Stdin redirection currently not suppported")
76
77         if self.stderr:
78             raise UnsupportedRequirement("Stderr redirection currently not suppported")
79
80         if self.stdout:
81             mounts["stdout"] = {"kind": "file",
82                                 "path": "%s/%s" % (self.outdir, self.stdout)}
83
84         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
85         if not docker_req:
86             docker_req = {"dockerImageId": arvados_jobs_image(self.arvrunner)}
87
88         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
89                                                                      docker_req,
90                                                                      pull_image,
91                                                                      self.arvrunner.project_uuid)
92
93         resources = self.builder.resources
94         if resources is not None:
95             runtime_constraints["vcpus"] = resources.get("cores", 1)
96             runtime_constraints["ram"] = resources.get("ram") * 2**20
97
98         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
99         if api_req:
100             runtime_constraints["API"] = True
101
102         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
103         if runtime_req:
104             if "keep_cache" in runtime_req:
105                 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"]
106
107         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
108         if partition_req:
109             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
110
111         container_request["mounts"] = mounts
112         container_request["runtime_constraints"] = runtime_constraints
113         container_request["use_existing"] = kwargs.get("enable_reuse", True)
114         container_request["scheduling_parameters"] = scheduling_parameters
115
116         try:
117             response = self.arvrunner.api.container_requests().create(
118                 body=container_request
119             ).execute(num_retries=self.arvrunner.num_retries)
120
121             self.uuid = response["uuid"]
122             self.arvrunner.processes[self.uuid] = self
123
124             logger.info("Container request %s (%s) state is %s", self.name, response["uuid"], response["state"])
125
126             if response["state"] == "Final":
127                 self.done(response)
128         except Exception as e:
129             logger.error("Got error %s" % str(e))
130             self.output_callback({}, "permanentFail")
131
132     def done(self, record):
133         try:
134             container = self.arvrunner.api.containers().get(
135                 uuid=record["container_uuid"]
136             ).execute(num_retries=self.arvrunner.num_retries)
137             if container["state"] == "Complete":
138                 rcode = container["exit_code"]
139                 if self.successCodes and rcode in self.successCodes:
140                     processStatus = "success"
141                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
142                     processStatus = "temporaryFail"
143                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
144                     processStatus = "permanentFail"
145                 elif rcode == 0:
146                     processStatus = "success"
147                 else:
148                     processStatus = "permanentFail"
149             else:
150                 processStatus = "permanentFail"
151
152             outputs = {}
153
154             if container["output"]:
155                 try:
156                     outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
157                 except Exception as e:
158                     logger.error("Got error %s" % str(e))
159                     self.output_callback({}, "permanentFail")
160             self.output_callback(outputs, processStatus)
161         finally:
162             del self.arvrunner.processes[record["uuid"]]
163
164
165 class RunnerContainer(Runner):
166     """Submit and manage a container that runs arvados-cwl-runner."""
167
168     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
169         """Create an Arvados container request for this workflow.
170
171         The returned dict can be used to create a container passed as
172         the +body+ argument to container_requests().create().
173         """
174
175         workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
176
177         container_req = {
178             "owner_uuid": self.arvrunner.project_uuid,
179             "name": self.name,
180             "output_path": "/var/spool/cwl",
181             "cwd": "/var/spool/cwl",
182             "priority": 1,
183             "state": "Committed",
184             "container_image": arvados_jobs_image(self.arvrunner),
185             "mounts": {
186                 "/var/lib/cwl/cwl.input.json": {
187                     "kind": "json",
188                     "content": self.job_order
189                 },
190                 "stdout": {
191                     "kind": "file",
192                     "path": "/var/spool/cwl/cwl.output.json"
193                 },
194                 "/var/spool/cwl": {
195                     "kind": "collection",
196                     "writable": True
197                 }
198             },
199             "runtime_constraints": {
200                 "vcpus": 1,
201                 "ram": 1024*1024 * self.submit_runner_ram,
202                 "API": True
203             },
204             "properties": {}
205         }
206
207         workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
208         if workflowcollection.startswith("keep:"):
209             workflowcollection = workflowcollection[5:workflowcollection.index('/')]
210             workflowname = os.path.basename(self.tool.tool["id"])
211             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
212             container_req["mounts"]["/var/lib/cwl/workflow"] = {
213                 "kind": "collection",
214                 "portable_data_hash": "%s" % workflowcollection
215                 }
216         elif workflowcollection.startswith("arvwf:"):
217             workflowpath = "/var/lib/cwl/workflow.json#main"
218             wfuuid = workflowcollection[6:workflowcollection.index("#")]
219             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute()
220             wfobj = yaml.safe_load(wfrecord["definition"])
221             if container_req["name"].startswith("arvwf:"):
222                 container_req["name"] = wfrecord["name"]
223             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
224                 "kind": "json",
225                 "json": wfobj
226             }
227             container_req["properties"]["template_uuid"] = wfuuid
228
229         command = ["arvados-cwl-runner", "--local", "--api=containers"]
230         if self.output_name:
231             command.append("--output-name=" + self.output_name)
232
233         if self.output_tags:
234             command.append("--output-tags=" + self.output_tags)
235
236         if self.enable_reuse:
237             command.append("--enable-reuse")
238         else:
239             command.append("--disable-reuse")
240
241         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
242
243         container_req["command"] = command
244
245         return container_req
246
247
248     def run(self, *args, **kwargs):
249         kwargs["keepprefix"] = "keep:"
250         job_spec = self.arvados_job_spec(*args, **kwargs)
251         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
252
253         response = self.arvrunner.api.container_requests().create(
254             body=job_spec
255         ).execute(num_retries=self.arvrunner.num_retries)
256
257         self.uuid = response["uuid"]
258         self.arvrunner.processes[self.uuid] = self
259
260         logger.info("Submitted container %s", response["uuid"])
261
262         if response["state"] == "Final":
263             self.done(response)
264
265     def done(self, record):
266         try:
267             container = self.arvrunner.api.containers().get(
268                 uuid=record["container_uuid"]
269             ).execute(num_retries=self.arvrunner.num_retries)
270         except Exception as e:
271             logger.exception("While getting runner container: %s", e)
272             self.arvrunner.output_callback({}, "permanentFail")
273             del self.arvrunner.processes[record["uuid"]]
274         else:
275             super(RunnerContainer, self).done(container)
276         finally:
277             del self.arvrunner.processes[record["uuid"]]