11100: Implement & document arv:IntermediateOutput hint.
[arvados.git] / sdk / cwl / arvados_cwl / arvcontainer.py
1 import logging
2 import json
3 import os
4 import urllib
5
6 import ruamel.yaml as yaml
7
8 from cwltool.errors import WorkflowException
9 from cwltool.process import get_feature, UnsupportedRequirement, shortname
10 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs
11 from cwltool.utils import aslist
12
13 import arvados.collection
14
15 from .arvdocker import arv_docker_get_image
16 from . import done
17 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_anonymous_location
18 from .fsaccess import CollectionFetcher
19 from .pathmapper import NoFollowPathMapper, trim_listing
20 from .perf import Perf
21
22 logger = logging.getLogger('arvados.cwl-runner')
23 metrics = logging.getLogger('arvados.cwl-runner.metrics')
24
25 class ArvadosContainer(object):
26     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
27
28     def __init__(self, runner):
29         self.arvrunner = runner
30         self.running = False
31         self.uuid = None
32
33     def update_pipeline_component(self, r):
34         pass
35
36     def run(self, dry_run=False, pull_image=True, **kwargs):
37         container_request = {
38             "command": self.command_line,
39             "owner_uuid": self.arvrunner.project_uuid,
40             "name": self.name,
41             "output_path": self.outdir,
42             "cwd": self.outdir,
43             "priority": 1,
44             "state": "Committed",
45             "properties": {},
46         }
47         runtime_constraints = {}
48
49         resources = self.builder.resources
50         if resources is not None:
51             runtime_constraints["vcpus"] = resources.get("cores", 1)
52             runtime_constraints["ram"] = resources.get("ram") * 2**20
53
54         mounts = {
55             self.outdir: {
56                 "kind": "tmp",
57                 "capacity": resources.get("outdirSize", 0) * 2**20
58             },
59             self.tmpdir: {
60                 "kind": "tmp",
61                 "capacity": resources.get("tmpdirSize", 0) * 2**20
62             }
63         }
64         scheduling_parameters = {}
65
66         rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
67         rf.sort(key=lambda k: k.resolved)
68         prevdir = None
69         for resolved, target, tp, stg in rf:
70             if not stg:
71                 continue
72             if prevdir and target.startswith(prevdir):
73                 continue
74             if tp == "Directory":
75                 targetdir = target
76             else:
77                 targetdir = os.path.dirname(target)
78             sp = resolved.split("/", 1)
79             pdh = sp[0][5:]   # remove "keep:"
80             mounts[targetdir] = {
81                 "kind": "collection",
82                 "portable_data_hash": pdh
83             }
84             if len(sp) == 2:
85                 if tp == "Directory":
86                     path = sp[1]
87                 else:
88                     path = os.path.dirname(sp[1])
89                 if path and path != "/":
90                     mounts[targetdir]["path"] = path
91             prevdir = targetdir + "/"
92
93         with Perf(metrics, "generatefiles %s" % self.name):
94             if self.generatefiles["listing"]:
95                 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
96                                                     keep_client=self.arvrunner.keep_client,
97                                                     num_retries=self.arvrunner.num_retries)
98                 generatemapper = NoFollowPathMapper([self.generatefiles], "", "",
99                                                     separateDirs=False)
100
101                 with Perf(metrics, "createfiles %s" % self.name):
102                     for f, p in generatemapper.items():
103                         if not p.target:
104                             pass
105                         elif p.type in ("File", "Directory"):
106                             source, path = self.arvrunner.fs_access.get_collection(p.resolved)
107                             vwd.copy(path, p.target, source_collection=source)
108                         elif p.type == "CreateFile":
109                             with vwd.open(p.target, "w") as n:
110                                 n.write(p.resolved.encode("utf-8"))
111
112                 with Perf(metrics, "generatefiles.save_new %s" % self.name):
113                     vwd.save_new()
114
115                 for f, p in generatemapper.items():
116                     if not p.target:
117                         continue
118                     mountpoint = "%s/%s" % (self.outdir, p.target)
119                     mounts[mountpoint] = {"kind": "collection",
120                                           "portable_data_hash": vwd.portable_data_hash(),
121                                           "path": p.target}
122
123         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
124         if self.environment:
125             container_request["environment"].update(self.environment)
126
127         if self.stdin:
128             sp = self.stdin[6:].split("/", 1)
129             mounts["stdin"] = {"kind": "collection",
130                                 "portable_data_hash": sp[0],
131                                 "path": sp[1]}
132
133         if self.stderr:
134             mounts["stderr"] = {"kind": "file",
135                                 "path": "%s/%s" % (self.outdir, self.stderr)}
136
137         if self.stdout:
138             mounts["stdout"] = {"kind": "file",
139                                 "path": "%s/%s" % (self.outdir, self.stdout)}
140
141         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
142         if not docker_req:
143             docker_req = {"dockerImageId": "arvados/jobs"}
144
145         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
146                                                                      docker_req,
147                                                                      pull_image,
148                                                                      self.arvrunner.project_uuid)
149
150         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
151         if api_req:
152             runtime_constraints["API"] = True
153
154         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
155         if runtime_req:
156             if "keep_cache" in runtime_req:
157                 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
158             if "outputDirType" in runtime_req:
159                 if runtime_req["outputDirType"] == "local_output_dir":
160                     # Currently the default behavior.
161                     pass
162                 elif runtime_req["outputDirType"] == "keep_output_dir":
163                     mounts[self.outdir]= {
164                         "kind": "collection",
165                         "writable": True
166                     }
167
168         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
169         if partition_req:
170             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
171
172         intermediate_output_req, _ = get_feature(self, "http://arvados.org/cwl#IntermediateOutput")
173         if intermediate_output_req:
174             self.output_ttl = intermediate_output_req["outputTTL"]
175         else:
176             self.output_ttl = self.arvrunner.intermediate_output_ttl
177
178         if self.output_ttl < 0:
179             raise WorkflowError("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
180
181         container_request["output_ttl"] = self.output_ttl
182         container_request["mounts"] = mounts
183         container_request["runtime_constraints"] = runtime_constraints
184         container_request["use_existing"] = kwargs.get("enable_reuse", True)
185         container_request["scheduling_parameters"] = scheduling_parameters
186
187         if kwargs.get("runnerjob", "").startswith("arvwf:"):
188             wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
189             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
190             if container_request["name"] == "main":
191                 container_request["name"] = wfrecord["name"]
192             container_request["properties"]["template_uuid"] = wfuuid
193
194         try:
195             response = self.arvrunner.api.container_requests().create(
196                 body=container_request
197             ).execute(num_retries=self.arvrunner.num_retries)
198
199             self.uuid = response["uuid"]
200             self.arvrunner.processes[self.uuid] = self
201
202             if response["state"] == "Final":
203                 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
204                 self.done(response)
205             else:
206                 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
207         except Exception as e:
208             logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
209             self.output_callback({}, "permanentFail")
210
211     def done(self, record):
212         try:
213             if self.output_ttl:
214                 self.arvrunner.add_intermediate_output(record["output_uuid"])
215
216             container = self.arvrunner.api.containers().get(
217                 uuid=record["container_uuid"]
218             ).execute(num_retries=self.arvrunner.num_retries)
219             if container["state"] == "Complete":
220                 rcode = container["exit_code"]
221                 if self.successCodes and rcode in self.successCodes:
222                     processStatus = "success"
223                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
224                     processStatus = "temporaryFail"
225                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
226                     processStatus = "permanentFail"
227                 elif rcode == 0:
228                     processStatus = "success"
229                 else:
230                     processStatus = "permanentFail"
231             else:
232                 processStatus = "permanentFail"
233
234             if processStatus == "permanentFail":
235                 logc = arvados.collection.CollectionReader(container["log"],
236                                                            api_client=self.arvrunner.api,
237                                                            keep_client=self.arvrunner.keep_client,
238                                                            num_retries=self.arvrunner.num_retries)
239                 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
240
241             outputs = {}
242             if container["output"]:
243                 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
244         except WorkflowException as e:
245             logger.error("%s unable to collect output from %s:\n%s",
246                          self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
247             processStatus = "permanentFail"
248         except Exception as e:
249             logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
250             processStatus = "permanentFail"
251         finally:
252             self.output_callback(outputs, processStatus)
253             if record["uuid"] in self.arvrunner.processes:
254                 del self.arvrunner.processes[record["uuid"]]
255
256
257 class RunnerContainer(Runner):
258     """Submit and manage a container that runs arvados-cwl-runner."""
259
260     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
261         """Create an Arvados container request for this workflow.
262
263         The returned dict can be used to create a container passed as
264         the +body+ argument to container_requests().create().
265         """
266
267         adjustDirObjs(self.job_order, trim_listing)
268         adjustFileObjs(self.job_order, trim_anonymous_location)
269         adjustDirObjs(self.job_order, trim_anonymous_location)
270
271         container_req = {
272             "owner_uuid": self.arvrunner.project_uuid,
273             "name": self.name,
274             "output_path": "/var/spool/cwl",
275             "cwd": "/var/spool/cwl",
276             "priority": 1,
277             "state": "Committed",
278             "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
279             "mounts": {
280                 "/var/lib/cwl/cwl.input.json": {
281                     "kind": "json",
282                     "content": self.job_order
283                 },
284                 "stdout": {
285                     "kind": "file",
286                     "path": "/var/spool/cwl/cwl.output.json"
287                 },
288                 "/var/spool/cwl": {
289                     "kind": "collection",
290                     "writable": True
291                 }
292             },
293             "runtime_constraints": {
294                 "vcpus": 1,
295                 "ram": 1024*1024 * self.submit_runner_ram,
296                 "API": True
297             },
298             "properties": {}
299         }
300
301         if self.tool.tool.get("id", "").startswith("keep:"):
302             sp = self.tool.tool["id"].split('/')
303             workflowcollection = sp[0][5:]
304             workflowname = "/".join(sp[1:])
305             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
306             container_req["mounts"]["/var/lib/cwl/workflow"] = {
307                 "kind": "collection",
308                 "portable_data_hash": "%s" % workflowcollection
309             }
310         else:
311             packed = packed_workflow(self.arvrunner, self.tool)
312             workflowpath = "/var/lib/cwl/workflow.json#main"
313             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
314                 "kind": "json",
315                 "content": packed
316             }
317             if self.tool.tool.get("id", "").startswith("arvwf:"):
318                 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
319
320         command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
321         if self.output_name:
322             command.append("--output-name=" + self.output_name)
323             container_req["output_name"] = self.output_name
324
325         if self.output_tags:
326             command.append("--output-tags=" + self.output_tags)
327
328         if kwargs.get("debug"):
329             command.append("--debug")
330
331         if self.enable_reuse:
332             command.append("--enable-reuse")
333         else:
334             command.append("--disable-reuse")
335
336         if self.on_error:
337             command.append("--on-error=" + self.on_error)
338
339         if self.intermediate_output_ttl:
340             command.append("--intermediate-output-ttl=%d" % self.intermediate_output_ttl)
341
342         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
343
344         container_req["command"] = command
345
346         return container_req
347
348
349     def run(self, *args, **kwargs):
350         kwargs["keepprefix"] = "keep:"
351         job_spec = self.arvados_job_spec(*args, **kwargs)
352         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
353
354         response = self.arvrunner.api.container_requests().create(
355             body=job_spec
356         ).execute(num_retries=self.arvrunner.num_retries)
357
358         self.uuid = response["uuid"]
359         self.arvrunner.processes[self.uuid] = self
360
361         logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
362
363         if response["state"] == "Final":
364             self.done(response)
365
366     def done(self, record):
367         try:
368             container = self.arvrunner.api.containers().get(
369                 uuid=record["container_uuid"]
370             ).execute(num_retries=self.arvrunner.num_retries)
371         except Exception as e:
372             logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
373             self.arvrunner.output_callback({}, "permanentFail")
374         else:
375             super(RunnerContainer, self).done(container)
376         finally:
377             if record["uuid"] in self.arvrunner.processes:
378                 del self.arvrunner.processes[record["uuid"]]