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