14198: Refactor and add support for --submit-runner-cluster
[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 import math
14
15 from arvados_cwl.util import get_current_container, get_intermediate_collection_info
16 import ruamel.yaml as yaml
17
18 from cwltool.errors import WorkflowException
19 from cwltool.process import UnsupportedRequirement, shortname
20 from cwltool.pathmapper import adjustFileObjs, adjustDirObjs, visit_class
21 from cwltool.utils import aslist
22 from cwltool.job import JobBase
23
24 import arvados.collection
25
26 from .arvdocker import arv_docker_get_image
27 from . import done
28 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_anonymous_location, remove_redundant_fields
29 from .fsaccess import CollectionFetcher
30 from .pathmapper import NoFollowPathMapper, trim_listing
31 from .perf import Perf
32
33 logger = logging.getLogger('arvados.cwl-runner')
34 metrics = logging.getLogger('arvados.cwl-runner.metrics')
35
36 class ArvadosContainer(JobBase):
37     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
38
39     def __init__(self, runner,
40                  builder,   # type: Builder
41                  joborder,  # type: Dict[Text, Union[Dict[Text, Any], List, Text]]
42                  make_path_mapper,  # type: Callable[..., PathMapper]
43                  requirements,      # type: List[Dict[Text, Text]]
44                  hints,     # type: List[Dict[Text, Text]]
45                  name       # type: Text
46     ):
47         super(ArvadosContainer, self).__init__(builder, joborder, make_path_mapper, requirements, hints, name)
48         self.arvrunner = runner
49         self.running = False
50         self.uuid = None
51
52     def update_pipeline_component(self, r):
53         pass
54
55     def run(self, runtimeContext):
56         # ArvadosCommandTool subclasses from cwltool.CommandLineTool,
57         # which calls makeJobRunner() to get a new ArvadosContainer
58         # object.  The fields that define execution such as
59         # command_line, environment, etc are set on the
60         # ArvadosContainer object by CommandLineTool.job() before
61         # run() is called.
62
63         container_request = {
64             "command": self.command_line,
65             "name": self.name,
66             "output_path": self.outdir,
67             "cwd": self.outdir,
68             "priority": runtimeContext.priority,
69             "state": "Committed",
70             "properties": {},
71         }
72         runtime_constraints = {}
73
74         if self.arvrunner.project_uuid:
75             container_request["owner_uuid"] = self.arvrunner.project_uuid
76
77         if self.arvrunner.secret_store.has_secret(self.command_line):
78             raise WorkflowException("Secret material leaked on command line, only file literals may contain secrets")
79
80         if self.arvrunner.secret_store.has_secret(self.environment):
81             raise WorkflowException("Secret material leaked in environment, only file literals may contain secrets")
82
83         resources = self.builder.resources
84         if resources is not None:
85             runtime_constraints["vcpus"] = math.ceil(resources.get("cores", 1))
86             runtime_constraints["ram"] = math.ceil(resources.get("ram") * 2**20)
87
88         mounts = {
89             self.outdir: {
90                 "kind": "tmp",
91                 "capacity": math.ceil(resources.get("outdirSize", 0) * 2**20)
92             },
93             self.tmpdir: {
94                 "kind": "tmp",
95                 "capacity": math.ceil(resources.get("tmpdirSize", 0) * 2**20)
96             }
97         }
98         secret_mounts = {}
99         scheduling_parameters = {}
100
101         rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
102         rf.sort(key=lambda k: k.resolved)
103         prevdir = None
104         for resolved, target, tp, stg in rf:
105             if not stg:
106                 continue
107             if prevdir and target.startswith(prevdir):
108                 continue
109             if tp == "Directory":
110                 targetdir = target
111             else:
112                 targetdir = os.path.dirname(target)
113             sp = resolved.split("/", 1)
114             pdh = sp[0][5:]   # remove "keep:"
115             mounts[targetdir] = {
116                 "kind": "collection",
117                 "portable_data_hash": pdh
118             }
119             if len(sp) == 2:
120                 if tp == "Directory":
121                     path = sp[1]
122                 else:
123                     path = os.path.dirname(sp[1])
124                 if path and path != "/":
125                     mounts[targetdir]["path"] = path
126             prevdir = targetdir + "/"
127
128         with Perf(metrics, "generatefiles %s" % self.name):
129             if self.generatefiles["listing"]:
130                 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
131                                                     keep_client=self.arvrunner.keep_client,
132                                                     num_retries=self.arvrunner.num_retries)
133                 generatemapper = NoFollowPathMapper([self.generatefiles], "", "",
134                                                     separateDirs=False)
135
136                 sorteditems = sorted(generatemapper.items(), None, key=lambda n: n[1].target)
137
138                 logger.debug("generatemapper is %s", sorteditems)
139
140                 with Perf(metrics, "createfiles %s" % self.name):
141                     for f, p in sorteditems:
142                         if not p.target:
143                             pass
144                         elif p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
145                             if p.resolved.startswith("_:"):
146                                 vwd.mkdirs(p.target)
147                             else:
148                                 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
149                                 vwd.copy(path, p.target, source_collection=source)
150                         elif p.type == "CreateFile":
151                             if self.arvrunner.secret_store.has_secret(p.resolved):
152                                 secret_mounts["%s/%s" % (self.outdir, p.target)] = {
153                                     "kind": "text",
154                                     "content": self.arvrunner.secret_store.retrieve(p.resolved)
155                                 }
156                             else:
157                                 with vwd.open(p.target, "w") as n:
158                                     n.write(p.resolved.encode("utf-8"))
159
160                 def keepemptydirs(p):
161                     if isinstance(p, arvados.collection.RichCollectionBase):
162                         if len(p) == 0:
163                             p.open(".keep", "w").close()
164                         else:
165                             for c in p:
166                                 keepemptydirs(p[c])
167
168                 keepemptydirs(vwd)
169
170                 if not runtimeContext.current_container:
171                     runtimeContext.current_container = get_current_container(self.arvrunner.api, self.arvrunner.num_retries, logger)
172                 info = get_intermediate_collection_info(self.name, runtimeContext.current_container, runtimeContext.intermediate_output_ttl)
173                 vwd.save_new(name=info["name"],
174                              owner_uuid=self.arvrunner.project_uuid,
175                              ensure_unique_name=True,
176                              trash_at=info["trash_at"],
177                              properties=info["properties"])
178
179                 prev = None
180                 for f, p in sorteditems:
181                     if (not p.target or self.arvrunner.secret_store.has_secret(p.resolved) or
182                         (prev is not None and p.target.startswith(prev))):
183                         continue
184                     mountpoint = "%s/%s" % (self.outdir, p.target)
185                     mounts[mountpoint] = {"kind": "collection",
186                                           "portable_data_hash": vwd.portable_data_hash(),
187                                           "path": p.target}
188                     if p.type.startswith("Writable"):
189                         mounts[mountpoint]["writable"] = True
190                     prev = p.target + "/"
191
192         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
193         if self.environment:
194             container_request["environment"].update(self.environment)
195
196         if self.stdin:
197             sp = self.stdin[6:].split("/", 1)
198             mounts["stdin"] = {"kind": "collection",
199                                 "portable_data_hash": sp[0],
200                                 "path": sp[1]}
201
202         if self.stderr:
203             mounts["stderr"] = {"kind": "file",
204                                 "path": "%s/%s" % (self.outdir, self.stderr)}
205
206         if self.stdout:
207             mounts["stdout"] = {"kind": "file",
208                                 "path": "%s/%s" % (self.outdir, self.stdout)}
209
210         (docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
211         if not docker_req:
212             docker_req = {"dockerImageId": "arvados/jobs"}
213
214         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
215                                                                     docker_req,
216                                                                     runtimeContext.pull_image,
217                                                                     self.arvrunner.project_uuid,
218                                                                     runtimeContext.submit_runner_cluster)
219
220         api_req, _ = self.get_requirement("http://arvados.org/cwl#APIRequirement")
221         if api_req:
222             runtime_constraints["API"] = True
223
224         runtime_req, _ = self.get_requirement("http://arvados.org/cwl#RuntimeConstraints")
225         if runtime_req:
226             if "keep_cache" in runtime_req:
227                 runtime_constraints["keep_cache_ram"] = math.ceil(runtime_req["keep_cache"] * 2**20)
228             if "outputDirType" in runtime_req:
229                 if runtime_req["outputDirType"] == "local_output_dir":
230                     # Currently the default behavior.
231                     pass
232                 elif runtime_req["outputDirType"] == "keep_output_dir":
233                     mounts[self.outdir]= {
234                         "kind": "collection",
235                         "writable": True
236                     }
237
238         partition_req, _ = self.get_requirement("http://arvados.org/cwl#PartitionRequirement")
239         if partition_req:
240             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
241
242         intermediate_output_req, _ = self.get_requirement("http://arvados.org/cwl#IntermediateOutput")
243         if intermediate_output_req:
244             self.output_ttl = intermediate_output_req["outputTTL"]
245         else:
246             self.output_ttl = self.arvrunner.intermediate_output_ttl
247
248         if self.output_ttl < 0:
249             raise WorkflowException("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
250
251         if self.timelimit is not None:
252             scheduling_parameters["max_run_time"] = self.timelimit
253
254         extra_submit_params = {}
255         cluster_target_req, _ = self.get_requirement("http://arvados.org/cwl#ClusterTarget")
256         if cluster_target_req:
257             cluster_id = cluster_target_req.get("clusterID")
258             if cluster_id:
259                 extra_submit_params["cluster_id"] = cluster_id
260             if cluster_target_req.get("ownerUUID"):
261                 container_request["owner_uuid"] = cluster_target_req.get("ownerUUID")
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": math.ceil(1024*1024 * self.submit_runner_ram),
414                 "API": True
415             },
416             "use_existing": self.enable_reuse,
417             "properties": {}
418         }
419
420         if self.tool.tool.get("id", "").startswith("keep:"):
421             sp = self.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.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.tool.tool.get("id", "").startswith("arvwf:"):
437                 container_req["properties"]["template_uuid"] = self.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         command = ["arvados-cwl-runner",
448                    "--local",
449                    "--api=containers",
450                    "--no-log-timestamps",
451                    "--disable-validate",
452                    "--eval-timeout=%s" % self.arvrunner.eval_timeout,
453                    "--thread-count=%s" % self.arvrunner.thread_count,
454                    "--enable-reuse" if self.enable_reuse else "--disable-reuse"]
455
456         if self.output_name:
457             command.append("--output-name=" + self.output_name)
458             container_req["output_name"] = self.output_name
459
460         if self.output_tags:
461             command.append("--output-tags=" + self.output_tags)
462
463         if runtimeContext.debug:
464             command.append("--debug")
465
466         if runtimeContext.storage_classes != "default":
467             command.append("--storage-classes=" + runtimeContext.storage_classes)
468
469         if self.on_error:
470             command.append("--on-error=" + self.on_error)
471
472         if self.intermediate_output_ttl:
473             command.append("--intermediate-output-ttl=%d" % self.intermediate_output_ttl)
474
475         if self.arvrunner.trash_intermediate:
476             command.append("--trash-intermediate")
477
478         if self.arvrunner.project_uuid:
479             command.append("--project-uuid="+self.arvrunner.project_uuid)
480
481         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
482
483         container_req["command"] = command
484
485         return container_req
486
487
488     def run(self, runtimeContext):
489         runtimeContext.keepprefix = "keep:"
490         job_spec = self.arvados_job_spec(runtimeContext)
491         if self.arvrunner.project_uuid:
492             job_spec["owner_uuid"] = self.arvrunner.project_uuid
493
494         extra_submit_params = {}
495         if runtimeContext.submit_runner_cluster:
496             extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
497
498         if runtimeContext.submit_request_uuid:
499             response = self.arvrunner.api.container_requests().update(
500                 uuid=runtimeContext.submit_request_uuid,
501                 body=job_spec,
502                 **extra_submit_params
503             ).execute(num_retries=self.arvrunner.num_retries)
504         else:
505             response = self.arvrunner.api.container_requests().create(
506                 body=job_spec,
507                 **extra_submit_params
508             ).execute(num_retries=self.arvrunner.num_retries)
509
510         self.uuid = response["uuid"]
511         self.arvrunner.process_submitted(self)
512
513         logger.info("%s submitted container_request %s", self.arvrunner.label(self), response["uuid"])
514
515     def done(self, record):
516         try:
517             container = self.arvrunner.api.containers().get(
518                 uuid=record["container_uuid"]
519             ).execute(num_retries=self.arvrunner.num_retries)
520         except Exception as e:
521             logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
522             self.arvrunner.output_callback({}, "permanentFail")
523         else:
524             super(RunnerContainer, self).done(container)