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