Merge branch 'thehyve/fix-crunch-documentation' Fix a typo in Crunch Dispatch install...
[arvados.git] / sdk / cwl / arvados_cwl / arvcontainer.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 import logging
6 import json
7 import os
8 import urllib
9 import time
10 import datetime
11 import ciso8601
12 import uuid
13
14 import ruamel.yaml as yaml
15
16 from cwltool.errors import WorkflowException
17 from cwltool.process import get_feature, UnsupportedRequirement, shortname
18 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
19 from cwltool.utils import aslist
20
21 import arvados.collection
22
23 from .arvdocker import arv_docker_get_image
24 from . import done
25 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_anonymous_location, remove_redundant_fields
26 from .fsaccess import CollectionFetcher
27 from .pathmapper import NoFollowPathMapper, trim_listing
28 from .perf import Perf
29
30 logger = logging.getLogger('arvados.cwl-runner')
31 metrics = logging.getLogger('arvados.cwl-runner.metrics')
32
33 class ArvadosContainer(object):
34     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
35
36     def __init__(self, runner):
37         self.arvrunner = runner
38         self.running = False
39         self.uuid = None
40
41     def update_pipeline_component(self, r):
42         pass
43
44     def run(self, dry_run=False, pull_image=True, **kwargs):
45         # ArvadosCommandTool subclasses from cwltool.CommandLineTool,
46         # which calls makeJobRunner() to get a new ArvadosContainer
47         # object.  The fields that define execution such as
48         # command_line, environment, etc are set on the
49         # ArvadosContainer object by CommandLineTool.job() before
50         # run() is called.
51
52         container_request = {
53             "command": self.command_line,
54             "owner_uuid": self.arvrunner.project_uuid,
55             "name": self.name,
56             "output_path": self.outdir,
57             "cwd": self.outdir,
58             "priority": kwargs.get("priority"),
59             "state": "Committed",
60             "properties": {},
61         }
62         runtime_constraints = {}
63
64         if self.arvrunner.secret_store.has_secret(self.command_line):
65             raise WorkflowException("Secret material leaked on command line, only file literals may contain secrets")
66
67         if self.arvrunner.secret_store.has_secret(self.environment):
68             raise WorkflowException("Secret material leaked in environment, only file literals may contain secrets")
69
70         resources = self.builder.resources
71         if resources is not None:
72             runtime_constraints["vcpus"] = resources.get("cores", 1)
73             runtime_constraints["ram"] = resources.get("ram") * 2**20
74
75         mounts = {
76             self.outdir: {
77                 "kind": "tmp",
78                 "capacity": resources.get("outdirSize", 0) * 2**20
79             },
80             self.tmpdir: {
81                 "kind": "tmp",
82                 "capacity": resources.get("tmpdirSize", 0) * 2**20
83             }
84         }
85         secret_mounts = {}
86         scheduling_parameters = {}
87
88         rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
89         rf.sort(key=lambda k: k.resolved)
90         prevdir = None
91         for resolved, target, tp, stg in rf:
92             if not stg:
93                 continue
94             if prevdir and target.startswith(prevdir):
95                 continue
96             if tp == "Directory":
97                 targetdir = target
98             else:
99                 targetdir = os.path.dirname(target)
100             sp = resolved.split("/", 1)
101             pdh = sp[0][5:]   # remove "keep:"
102             mounts[targetdir] = {
103                 "kind": "collection",
104                 "portable_data_hash": pdh
105             }
106             if len(sp) == 2:
107                 if tp == "Directory":
108                     path = sp[1]
109                 else:
110                     path = os.path.dirname(sp[1])
111                 if path and path != "/":
112                     mounts[targetdir]["path"] = path
113             prevdir = targetdir + "/"
114
115         with Perf(metrics, "generatefiles %s" % self.name):
116             if self.generatefiles["listing"]:
117                 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
118                                                     keep_client=self.arvrunner.keep_client,
119                                                     num_retries=self.arvrunner.num_retries)
120                 generatemapper = NoFollowPathMapper([self.generatefiles], "", "",
121                                                     separateDirs=False)
122
123                 sorteditems = sorted(generatemapper.items(), None, key=lambda n: n[1].target)
124
125                 logger.debug("generatemapper is %s", sorteditems)
126
127                 with Perf(metrics, "createfiles %s" % self.name):
128                     for f, p in sorteditems:
129                         if not p.target:
130                             pass
131                         elif p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
132                             if p.resolved.startswith("_:"):
133                                 vwd.mkdirs(p.target)
134                             else:
135                                 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
136                                 vwd.copy(path, p.target, source_collection=source)
137                         elif p.type == "CreateFile":
138                             if self.arvrunner.secret_store.has_secret(p.resolved):
139                                 secret_mounts["%s/%s" % (self.outdir, p.target)] = {
140                                     "kind": "text",
141                                     "content": self.arvrunner.secret_store.retrieve(p.resolved)
142                                 }
143                             else:
144                                 with vwd.open(p.target, "w") as n:
145                                     n.write(p.resolved.encode("utf-8"))
146
147                 def keepemptydirs(p):
148                     if isinstance(p, arvados.collection.RichCollectionBase):
149                         if len(p) == 0:
150                             p.open(".keep", "w").close()
151                         else:
152                             for c in p:
153                                 keepemptydirs(p[c])
154
155                 keepemptydirs(vwd)
156
157                 with Perf(metrics, "generatefiles.save_new %s" % self.name):
158                     vwd.save_new()
159
160                 prev = None
161                 for f, p in sorteditems:
162                     if (not p.target or self.arvrunner.secret_store.has_secret(p.resolved) or
163                         (prev is not None and p.target.startswith(prev))):
164                         continue
165                     mountpoint = "%s/%s" % (self.outdir, p.target)
166                     mounts[mountpoint] = {"kind": "collection",
167                                           "portable_data_hash": vwd.portable_data_hash(),
168                                           "path": p.target}
169                     if p.type.startswith("Writable"):
170                         mounts[mountpoint]["writable"] = True
171                     prev = p.target + "/"
172
173         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
174         if self.environment:
175             container_request["environment"].update(self.environment)
176
177         if self.stdin:
178             sp = self.stdin[6:].split("/", 1)
179             mounts["stdin"] = {"kind": "collection",
180                                 "portable_data_hash": sp[0],
181                                 "path": sp[1]}
182
183         if self.stderr:
184             mounts["stderr"] = {"kind": "file",
185                                 "path": "%s/%s" % (self.outdir, self.stderr)}
186
187         if self.stdout:
188             mounts["stdout"] = {"kind": "file",
189                                 "path": "%s/%s" % (self.outdir, self.stdout)}
190
191         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
192         if not docker_req:
193             docker_req = {"dockerImageId": "arvados/jobs"}
194
195         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
196                                                                      docker_req,
197                                                                      pull_image,
198                                                                      self.arvrunner.project_uuid)
199
200         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
201         if api_req:
202             runtime_constraints["API"] = True
203
204         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
205         if runtime_req:
206             if "keep_cache" in runtime_req:
207                 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
208             if "outputDirType" in runtime_req:
209                 if runtime_req["outputDirType"] == "local_output_dir":
210                     # Currently the default behavior.
211                     pass
212                 elif runtime_req["outputDirType"] == "keep_output_dir":
213                     mounts[self.outdir]= {
214                         "kind": "collection",
215                         "writable": True
216                     }
217
218         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
219         if partition_req:
220             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
221
222         intermediate_output_req, _ = get_feature(self, "http://arvados.org/cwl#IntermediateOutput")
223         if intermediate_output_req:
224             self.output_ttl = intermediate_output_req["outputTTL"]
225         else:
226             self.output_ttl = self.arvrunner.intermediate_output_ttl
227
228         if self.output_ttl < 0:
229             raise WorkflowException("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
230
231         container_request["output_ttl"] = self.output_ttl
232         container_request["mounts"] = mounts
233         container_request["secret_mounts"] = secret_mounts
234         container_request["runtime_constraints"] = runtime_constraints
235         container_request["scheduling_parameters"] = scheduling_parameters
236
237         enable_reuse = kwargs.get("enable_reuse", True)
238         if enable_reuse:
239             reuse_req, _ = get_feature(self, "http://arvados.org/cwl#ReuseRequirement")
240             if reuse_req:
241                 enable_reuse = reuse_req["enableReuse"]
242         container_request["use_existing"] = enable_reuse
243
244         if kwargs.get("runnerjob", "").startswith("arvwf:"):
245             wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
246             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
247             if container_request["name"] == "main":
248                 container_request["name"] = wfrecord["name"]
249             container_request["properties"]["template_uuid"] = wfuuid
250
251         self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
252
253         try:
254             response = self.arvrunner.api.container_requests().create(
255                 body=container_request
256             ).execute(num_retries=self.arvrunner.num_retries)
257
258             self.uuid = response["uuid"]
259             self.arvrunner.process_submitted(self)
260
261             if response["state"] == "Final":
262                 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
263             else:
264                 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
265         except Exception as e:
266             logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
267             self.output_callback({}, "permanentFail")
268
269     def done(self, record):
270         outputs = {}
271         try:
272             container = self.arvrunner.api.containers().get(
273                 uuid=record["container_uuid"]
274             ).execute(num_retries=self.arvrunner.num_retries)
275             if container["state"] == "Complete":
276                 rcode = container["exit_code"]
277                 if self.successCodes and rcode in self.successCodes:
278                     processStatus = "success"
279                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
280                     processStatus = "temporaryFail"
281                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
282                     processStatus = "permanentFail"
283                 elif rcode == 0:
284                     processStatus = "success"
285                 else:
286                     processStatus = "permanentFail"
287             else:
288                 processStatus = "permanentFail"
289
290             if processStatus == "permanentFail":
291                 logc = arvados.collection.CollectionReader(container["log"],
292                                                            api_client=self.arvrunner.api,
293                                                            keep_client=self.arvrunner.keep_client,
294                                                            num_retries=self.arvrunner.num_retries)
295                 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
296
297             if record["output_uuid"]:
298                 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
299                     # Compute the trash time to avoid requesting the collection record.
300                     trash_at = ciso8601.parse_datetime_unaware(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
301                     aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
302                     orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
303                     oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
304                     logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
305                         self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
306                 self.arvrunner.add_intermediate_output(record["output_uuid"])
307
308             if container["output"]:
309                 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
310         except WorkflowException as e:
311             logger.error("%s unable to collect output from %s:\n%s",
312                          self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
313             processStatus = "permanentFail"
314         except Exception as e:
315             logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
316             processStatus = "permanentFail"
317         finally:
318             self.output_callback(outputs, processStatus)
319
320
321 class RunnerContainer(Runner):
322     """Submit and manage a container that runs arvados-cwl-runner."""
323
324     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
325         """Create an Arvados container request for this workflow.
326
327         The returned dict can be used to create a container passed as
328         the +body+ argument to container_requests().create().
329         """
330
331         adjustDirObjs(self.job_order, trim_listing)
332         visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
333         visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
334
335         secret_mounts = {}
336         for param in sorted(self.job_order.keys()):
337             if self.secret_store.has_secret(self.job_order[param]):
338                 mnt = "/secrets/s%d" % len(secret_mounts)
339                 secret_mounts[mnt] = {
340                     "kind": "text",
341                     "content": self.secret_store.retrieve(self.job_order[param])
342                 }
343                 self.job_order[param] = {"$include": mnt}
344
345         container_req = {
346             "owner_uuid": self.arvrunner.project_uuid,
347             "name": self.name,
348             "output_path": "/var/spool/cwl",
349             "cwd": "/var/spool/cwl",
350             "priority": self.priority,
351             "state": "Committed",
352             "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
353             "mounts": {
354                 "/var/lib/cwl/cwl.input.json": {
355                     "kind": "json",
356                     "content": self.job_order
357                 },
358                 "stdout": {
359                     "kind": "file",
360                     "path": "/var/spool/cwl/cwl.output.json"
361                 },
362                 "/var/spool/cwl": {
363                     "kind": "collection",
364                     "writable": True
365                 }
366             },
367             "secret_mounts": secret_mounts,
368             "runtime_constraints": {
369                 "vcpus": 1,
370                 "ram": 1024*1024 * self.submit_runner_ram,
371                 "API": True
372             },
373             "use_existing": self.enable_reuse,
374             "properties": {}
375         }
376
377         if self.tool.tool.get("id", "").startswith("keep:"):
378             sp = self.tool.tool["id"].split('/')
379             workflowcollection = sp[0][5:]
380             workflowname = "/".join(sp[1:])
381             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
382             container_req["mounts"]["/var/lib/cwl/workflow"] = {
383                 "kind": "collection",
384                 "portable_data_hash": "%s" % workflowcollection
385             }
386         else:
387             packed = packed_workflow(self.arvrunner, self.tool, self.merged_map)
388             workflowpath = "/var/lib/cwl/workflow.json#main"
389             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
390                 "kind": "json",
391                 "content": packed
392             }
393             if self.tool.tool.get("id", "").startswith("arvwf:"):
394                 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
395
396
397         # --local means execute the workflow instead of submitting a container request
398         # --api=containers means use the containers API
399         # --no-log-timestamps means don't add timestamps (the logging infrastructure does this)
400         # --disable-validate because we already validated so don't need to do it again
401         # --eval-timeout is the timeout for javascript invocation
402         # --parallel-task-count is the number of threads to use for job submission
403         # --enable/disable-reuse sets desired job reuse
404         command = ["arvados-cwl-runner",
405                    "--local",
406                    "--api=containers",
407                    "--no-log-timestamps",
408                    "--disable-validate",
409                    "--eval-timeout=%s" % self.arvrunner.eval_timeout,
410                    "--thread-count=%s" % self.arvrunner.thread_count,
411                    "--enable-reuse" if self.enable_reuse else "--disable-reuse"]
412
413         if self.output_name:
414             command.append("--output-name=" + self.output_name)
415             container_req["output_name"] = self.output_name
416
417         if self.output_tags:
418             command.append("--output-tags=" + self.output_tags)
419
420         if kwargs.get("debug"):
421             command.append("--debug")
422
423         if self.on_error:
424             command.append("--on-error=" + self.on_error)
425
426         if self.intermediate_output_ttl:
427             command.append("--intermediate-output-ttl=%d" % self.intermediate_output_ttl)
428
429         if self.arvrunner.trash_intermediate:
430             command.append("--trash-intermediate")
431
432         if self.arvrunner.project_uuid:
433             command.append("--project-uuid="+self.arvrunner.project_uuid)
434
435         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
436
437         container_req["command"] = command
438
439         return container_req
440
441
442     def run(self, **kwargs):
443         kwargs["keepprefix"] = "keep:"
444         job_spec = self.arvados_job_spec(**kwargs)
445         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
446
447         response = self.arvrunner.api.container_requests().create(
448             body=job_spec
449         ).execute(num_retries=self.arvrunner.num_retries)
450
451         self.uuid = response["uuid"]
452         self.arvrunner.process_submitted(self)
453
454         logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
455
456     def done(self, record):
457         try:
458             container = self.arvrunner.api.containers().get(
459                 uuid=record["container_uuid"]
460             ).execute(num_retries=self.arvrunner.num_retries)
461         except Exception as e:
462             logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
463             self.arvrunner.output_callback({}, "permanentFail")
464         else:
465             super(RunnerContainer, self).done(container)