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