21718: Update cwltool dependency
[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.request, urllib.parse, urllib.error
9 import time
10 import datetime
11 import ciso8601
12 import uuid
13 import math
14 import re
15
16 import arvados_cwl.util
17 import ruamel.yaml
18
19 from cwltool.errors import WorkflowException
20 from cwltool.process import UnsupportedRequirement, shortname
21 from cwltool.utils import aslist, adjustFileObjs, adjustDirObjs, visit_class
22 from cwltool.job import JobBase
23
24 import arvados.collection
25
26 import crunchstat_summary.summarizer
27 import crunchstat_summary.reader
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, make_builder
32 from .fsaccess import CollectionFetcher
33 from .pathmapper import NoFollowPathMapper, trim_listing
34 from .perf import Perf
35 from ._version import __version__
36
37 logger = logging.getLogger('arvados.cwl-runner')
38 metrics = logging.getLogger('arvados.cwl-runner.metrics')
39
40 def cleanup_name_for_collection(name):
41     return name.replace("/", " ")
42
43 class ArvadosContainer(JobBase):
44     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
45
46     def __init__(self, runner, job_runtime,
47                  builder,   # type: Builder
48                  joborder,  # type: Dict[Text, Union[Dict[Text, Any], List, Text]]
49                  make_path_mapper,  # type: Callable[..., PathMapper]
50                  requirements,      # type: List[Dict[Text, Text]]
51                  hints,     # type: List[Dict[Text, Text]]
52                  name       # type: Text
53     ):
54         super(ArvadosContainer, self).__init__(builder, joborder, make_path_mapper, requirements, hints, name)
55         self.arvrunner = runner
56         self.job_runtime = job_runtime
57         self.running = False
58         self.uuid = None
59         self.attempt_count = 0
60
61     def update_pipeline_component(self, r):
62         pass
63
64     def _required_env(self):
65         env = {}
66         env["HOME"] = self.outdir
67         env["TMPDIR"] = self.tmpdir
68         return env
69
70     def run(self, toplevelRuntimeContext):
71         # ArvadosCommandTool subclasses from cwltool.CommandLineTool,
72         # which calls makeJobRunner() to get a new ArvadosContainer
73         # object.  The fields that define execution such as
74         # command_line, environment, etc are set on the
75         # ArvadosContainer object by CommandLineTool.job() before
76         # run() is called.
77
78         runtimeContext = self.job_runtime
79
80         if runtimeContext.submit_request_uuid:
81             container_request = self.arvrunner.api.container_requests().get(
82                 uuid=runtimeContext.submit_request_uuid
83             ).execute(num_retries=self.arvrunner.num_retries)
84         else:
85             container_request = {}
86
87         container_request["command"] = self.command_line
88         container_request["name"] = self.name
89         container_request["output_path"] = self.outdir
90         container_request["cwd"] = self.outdir
91         container_request["priority"] = runtimeContext.priority
92         container_request["state"] = "Uncommitted"
93         container_request.setdefault("properties", {})
94
95         container_request["properties"]["cwl_input"] = self.joborder
96
97         runtime_constraints = {}
98
99         if runtimeContext.project_uuid:
100             container_request["owner_uuid"] = runtimeContext.project_uuid
101
102         if self.arvrunner.secret_store.has_secret(self.command_line):
103             raise WorkflowException("Secret material leaked on command line, only file literals may contain secrets")
104
105         if self.arvrunner.secret_store.has_secret(self.environment):
106             raise WorkflowException("Secret material leaked in environment, only file literals may contain secrets")
107
108         resources = self.builder.resources
109         if resources is not None:
110             runtime_constraints["vcpus"] = math.ceil(resources.get("cores", 1))
111             runtime_constraints["ram"] = math.ceil(resources.get("ram") * 2**20)
112
113         mounts = {
114             self.outdir: {
115                 "kind": "tmp",
116                 "capacity": math.ceil(resources.get("outdirSize", 0) * 2**20)
117             },
118             self.tmpdir: {
119                 "kind": "tmp",
120                 "capacity": math.ceil(resources.get("tmpdirSize", 0) * 2**20)
121             }
122         }
123         secret_mounts = {}
124         scheduling_parameters = {}
125
126         rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
127         rf.sort(key=lambda k: k.resolved)
128         prevdir = None
129         for resolved, target, tp, stg in rf:
130             if not stg:
131                 continue
132             if prevdir and target.startswith(prevdir):
133                 continue
134             if tp == "Directory":
135                 targetdir = target
136             else:
137                 targetdir = os.path.dirname(target)
138             sp = resolved.split("/", 1)
139             pdh = sp[0][5:]   # remove "keep:"
140             mounts[targetdir] = {
141                 "kind": "collection",
142                 "portable_data_hash": pdh
143             }
144             if pdh in self.pathmapper.pdh_to_uuid:
145                 mounts[targetdir]["uuid"] = self.pathmapper.pdh_to_uuid[pdh]
146             if len(sp) == 2:
147                 if tp == "Directory":
148                     path = sp[1]
149                 else:
150                     path = os.path.dirname(sp[1])
151                 if path and path != "/":
152                     mounts[targetdir]["path"] = path
153             prevdir = targetdir + "/"
154
155         intermediate_collection_info = arvados_cwl.util.get_intermediate_collection_info(self.name, runtimeContext.current_container, runtimeContext.intermediate_output_ttl)
156
157         with Perf(metrics, "generatefiles %s" % self.name):
158             if self.generatefiles["listing"]:
159                 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
160                                                     keep_client=self.arvrunner.keep_client,
161                                                     num_retries=self.arvrunner.num_retries)
162                 generatemapper = NoFollowPathMapper(self.generatefiles["listing"], "", "",
163                                                     separateDirs=False)
164
165                 sorteditems = sorted(generatemapper.items(), key=lambda n: n[1].target)
166
167                 logger.debug("generatemapper is %s", sorteditems)
168
169                 with Perf(metrics, "createfiles %s" % self.name):
170                     for f, p in sorteditems:
171                         if not p.target:
172                             continue
173
174                         if p.target.startswith("/"):
175                             dst = p.target[len(self.outdir)+1:] if p.target.startswith(self.outdir+"/") else p.target[1:]
176                         else:
177                             dst = p.target
178
179                         if p.type in ("File", "Directory", "WritableFile", "WritableDirectory"):
180                             if p.resolved.startswith("_:"):
181                                 vwd.mkdirs(dst)
182                             else:
183                                 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
184                                 vwd.copy(path or ".", dst, source_collection=source)
185                         elif p.type == "CreateFile":
186                             if self.arvrunner.secret_store.has_secret(p.resolved):
187                                 mountpoint = p.target if p.target.startswith("/") else os.path.join(self.outdir, p.target)
188                                 secret_mounts[mountpoint] = {
189                                     "kind": "text",
190                                     "content": self.arvrunner.secret_store.retrieve(p.resolved)
191                                 }
192                             else:
193                                 with vwd.open(dst, "w") as n:
194                                     n.write(p.resolved)
195
196                 def keepemptydirs(p):
197                     if isinstance(p, arvados.collection.RichCollectionBase):
198                         if len(p) == 0:
199                             p.open(".keep", "w").close()
200                         else:
201                             for c in p:
202                                 keepemptydirs(p[c])
203
204                 keepemptydirs(vwd)
205
206                 if not runtimeContext.current_container:
207                     runtimeContext.current_container = arvados_cwl.util.get_current_container(self.arvrunner.api, self.arvrunner.num_retries, logger)
208                 vwd.save_new(name=intermediate_collection_info["name"],
209                              owner_uuid=runtimeContext.project_uuid,
210                              ensure_unique_name=True,
211                              trash_at=intermediate_collection_info["trash_at"],
212                              properties=intermediate_collection_info["properties"])
213
214                 prev = None
215                 for f, p in sorteditems:
216                     if (not p.target or self.arvrunner.secret_store.has_secret(p.resolved) or
217                         (prev is not None and p.target.startswith(prev))):
218                         continue
219                     if p.target.startswith("/"):
220                         dst = p.target[len(self.outdir)+1:] if p.target.startswith(self.outdir+"/") else p.target[1:]
221                     else:
222                         dst = p.target
223                     mountpoint = p.target if p.target.startswith("/") else os.path.join(self.outdir, p.target)
224                     mounts[mountpoint] = {"kind": "collection",
225                                           "portable_data_hash": vwd.portable_data_hash(),
226                                           "path": dst}
227                     if p.type.startswith("Writable"):
228                         mounts[mountpoint]["writable"] = True
229                     prev = p.target + "/"
230
231         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
232         if self.environment:
233             container_request["environment"].update(self.environment)
234
235         if self.stdin:
236             sp = self.stdin[6:].split("/", 1)
237             mounts["stdin"] = {"kind": "collection",
238                                 "portable_data_hash": sp[0],
239                                 "path": sp[1]}
240
241         if self.stderr:
242             mounts["stderr"] = {"kind": "file",
243                                 "path": "%s/%s" % (self.outdir, self.stderr)}
244
245         if self.stdout:
246             mounts["stdout"] = {"kind": "file",
247                                 "path": "%s/%s" % (self.outdir, self.stdout)}
248
249         (docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
250
251         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
252                                                                     docker_req,
253                                                                     runtimeContext.pull_image,
254                                                                     runtimeContext)
255
256         network_req, _ = self.get_requirement("NetworkAccess")
257         if network_req:
258             runtime_constraints["API"] = network_req["networkAccess"]
259
260         api_req, _ = self.get_requirement("http://arvados.org/cwl#APIRequirement")
261         if api_req:
262             runtime_constraints["API"] = True
263
264         use_disk_cache = (self.arvrunner.api.config()["Containers"].get("DefaultKeepCacheRAM", 0) == 0)
265
266         keep_cache_type_req, _ = self.get_requirement("http://arvados.org/cwl#KeepCacheTypeRequirement")
267         if keep_cache_type_req:
268             if "keepCacheType" in keep_cache_type_req:
269                 if keep_cache_type_req["keepCacheType"] == "ram_cache":
270                     use_disk_cache = False
271
272         runtime_req, _ = self.get_requirement("http://arvados.org/cwl#RuntimeConstraints")
273         if runtime_req:
274             if "keep_cache" in runtime_req:
275                 if use_disk_cache:
276                     # If DefaultKeepCacheRAM is zero it means we should use disk cache.
277                     runtime_constraints["keep_cache_disk"] = math.ceil(runtime_req["keep_cache"] * 2**20)
278                 else:
279                     runtime_constraints["keep_cache_ram"] = math.ceil(runtime_req["keep_cache"] * 2**20)
280             if "outputDirType" in runtime_req:
281                 if runtime_req["outputDirType"] == "local_output_dir":
282                     # Currently the default behavior.
283                     pass
284                 elif runtime_req["outputDirType"] == "keep_output_dir":
285                     mounts[self.outdir]= {
286                         "kind": "collection",
287                         "writable": True
288                     }
289
290         partition_req, _ = self.get_requirement("http://arvados.org/cwl#PartitionRequirement")
291         if partition_req:
292             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
293
294         intermediate_output_req, _ = self.get_requirement("http://arvados.org/cwl#IntermediateOutput")
295         if intermediate_output_req:
296             self.output_ttl = intermediate_output_req["outputTTL"]
297         else:
298             self.output_ttl = self.arvrunner.intermediate_output_ttl
299
300         if self.output_ttl < 0:
301             raise WorkflowException("Invalid value %d for output_ttl, cannot be less than zero" % container_request["output_ttl"])
302
303
304         if self.arvrunner.api._rootDesc["revision"] >= "20210628":
305             storage_class_req, _ = self.get_requirement("http://arvados.org/cwl#OutputStorageClass")
306             if storage_class_req and storage_class_req.get("intermediateStorageClass"):
307                 container_request["output_storage_classes"] = aslist(storage_class_req["intermediateStorageClass"])
308             else:
309                 container_request["output_storage_classes"] = runtimeContext.intermediate_storage_classes.strip().split(",")
310
311         cuda_req, _ = self.get_requirement("http://commonwl.org/cwltool#CUDARequirement")
312         if cuda_req:
313             runtime_constraints["cuda"] = {
314                 "device_count": resources.get("cudaDeviceCount", 1),
315                 "driver_version": cuda_req["cudaVersionMin"],
316                 "hardware_capability": aslist(cuda_req["cudaComputeCapability"])[0]
317             }
318
319         if runtimeContext.enable_preemptible is False:
320             scheduling_parameters["preemptible"] = False
321         else:
322             preemptible_req, _ = self.get_requirement("http://arvados.org/cwl#UsePreemptible")
323             if preemptible_req:
324                 scheduling_parameters["preemptible"] = preemptible_req["usePreemptible"]
325             elif runtimeContext.enable_preemptible is True:
326                 scheduling_parameters["preemptible"] = True
327             elif runtimeContext.enable_preemptible is None:
328                 pass
329
330         if self.timelimit is not None and self.timelimit > 0:
331             scheduling_parameters["max_run_time"] = self.timelimit
332
333         extra_submit_params = {}
334         if runtimeContext.submit_runner_cluster:
335             extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
336
337         container_request["output_name"] = cleanup_name_for_collection("Output from step %s" % (self.name))
338         container_request["output_ttl"] = self.output_ttl
339         container_request["mounts"] = mounts
340         container_request["secret_mounts"] = secret_mounts
341         container_request["runtime_constraints"] = runtime_constraints
342         container_request["scheduling_parameters"] = scheduling_parameters
343
344         enable_reuse = runtimeContext.enable_reuse
345         if enable_reuse:
346             reuse_req, _ = self.get_requirement("WorkReuse")
347             if reuse_req:
348                 enable_reuse = reuse_req["enableReuse"]
349             reuse_req, _ = self.get_requirement("http://arvados.org/cwl#ReuseRequirement")
350             if reuse_req:
351                 enable_reuse = reuse_req["enableReuse"]
352         container_request["use_existing"] = enable_reuse
353
354         properties_req, _ = self.get_requirement("http://arvados.org/cwl#ProcessProperties")
355         if properties_req:
356             for pr in properties_req["processProperties"]:
357                 container_request["properties"][pr["propertyName"]] = self.builder.do_eval(pr["propertyValue"])
358
359         output_properties_req, _ = self.get_requirement("http://arvados.org/cwl#OutputCollectionProperties")
360         if output_properties_req:
361             if self.arvrunner.api._rootDesc["revision"] >= "20220510":
362                 container_request["output_properties"] = {}
363                 for pr in output_properties_req["outputProperties"]:
364                     container_request["output_properties"][pr["propertyName"]] = self.builder.do_eval(pr["propertyValue"])
365             else:
366                 logger.warning("%s API revision is %s, revision %s is required to support setting properties on output collections.",
367                                self.arvrunner.label(self), self.arvrunner.api._rootDesc["revision"], "20220510")
368
369         ram_multiplier = [1]
370
371         oom_retry_req, _ = self.get_requirement("http://arvados.org/cwl#OutOfMemoryRetry")
372         if oom_retry_req:
373             if oom_retry_req.get('memoryRetryMultiplier'):
374                 ram_multiplier.append(oom_retry_req.get('memoryRetryMultiplier'))
375             elif oom_retry_req.get('memoryRetryMultipler'):
376                 ram_multiplier.append(oom_retry_req.get('memoryRetryMultipler'))
377             else:
378                 ram_multiplier.append(2)
379
380         if runtimeContext.runnerjob.startswith("arvwf:"):
381             wfuuid = runtimeContext.runnerjob[6:runtimeContext.runnerjob.index("#")]
382             wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
383             if container_request["name"] == "main":
384                 container_request["name"] = wfrecord["name"]
385             container_request["properties"]["template_uuid"] = wfuuid
386
387         if self.attempt_count == 0:
388             self.output_callback = self.arvrunner.get_wrapped_callback(self.output_callback)
389
390         try:
391             ram = runtime_constraints["ram"]
392
393             self.uuid = runtimeContext.submit_request_uuid
394
395             for i in ram_multiplier:
396                 runtime_constraints["ram"] = ram * i
397
398                 if self.uuid:
399                     response = self.arvrunner.api.container_requests().update(
400                         uuid=self.uuid,
401                         body=container_request,
402                         **extra_submit_params
403                     ).execute(num_retries=self.arvrunner.num_retries)
404                 else:
405                     response = self.arvrunner.api.container_requests().create(
406                         body=container_request,
407                         **extra_submit_params
408                     ).execute(num_retries=self.arvrunner.num_retries)
409                     self.uuid = response["uuid"]
410
411                 if response["container_uuid"] is not None:
412                     break
413
414             if response["container_uuid"] is None:
415                 runtime_constraints["ram"] = ram * ram_multiplier[self.attempt_count]
416
417             container_request["state"] = "Committed"
418             response = self.arvrunner.api.container_requests().update(
419                 uuid=self.uuid,
420                 body=container_request,
421                 **extra_submit_params
422             ).execute(num_retries=self.arvrunner.num_retries)
423
424             self.arvrunner.process_submitted(self)
425             self.attempt_count += 1
426
427             if response["state"] == "Final":
428                 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
429             else:
430                 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
431         except Exception as e:
432             logger.exception("%s error submitting container\n%s", self.arvrunner.label(self), e)
433             logger.debug("Container request was %s", container_request)
434             self.output_callback({}, "permanentFail")
435
436     def out_of_memory_retry(self, record, container):
437         oom_retry_req, _ = self.get_requirement("http://arvados.org/cwl#OutOfMemoryRetry")
438         if oom_retry_req is None:
439             return False
440
441         # Sometimes it gets killed with no warning
442         if container["exit_code"] == 137:
443             return True
444
445         logc = arvados.collection.CollectionReader(record["log_uuid"],
446                                                    api_client=self.arvrunner.api,
447                                                    keep_client=self.arvrunner.keep_client,
448                                                    num_retries=self.arvrunner.num_retries)
449
450         loglines = [""]
451         def callback(v1, v2, v3):
452             loglines[0] = v3
453
454         done.logtail(logc, callback, "", maxlen=1000)
455
456         # Check allocation failure
457         oom_matches = oom_retry_req.get('memoryErrorRegex') or r'(bad_alloc|out ?of ?memory|memory ?error|container using over 9.% of memory)'
458         if re.search(oom_matches, loglines[0], re.IGNORECASE | re.MULTILINE):
459             return True
460
461         return False
462
463     def done(self, record):
464         outputs = {}
465         retried = False
466         rcode = None
467         try:
468             container = self.arvrunner.api.containers().get(
469                 uuid=record["container_uuid"]
470             ).execute(num_retries=self.arvrunner.num_retries)
471             if container["state"] == "Complete":
472                 rcode = container["exit_code"]
473                 if self.successCodes and rcode in self.successCodes:
474                     processStatus = "success"
475                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
476                     processStatus = "temporaryFail"
477                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
478                     processStatus = "permanentFail"
479                 elif rcode == 0:
480                     processStatus = "success"
481                 else:
482                     processStatus = "permanentFail"
483
484                 if processStatus == "permanentFail" and self.attempt_count == 1 and self.out_of_memory_retry(record, container):
485                     logger.warning("%s Container failed with out of memory error, retrying with more RAM.",
486                                  self.arvrunner.label(self))
487                     self.job_runtime.submit_request_uuid = None
488                     self.uuid = None
489                     self.run(None)
490                     retried = True
491                     return
492
493                 if rcode == 137:
494                     logger.warning("%s Container may have been killed for using too much RAM.  Try resubmitting with a higher 'ramMin' or use the arv:OutOfMemoryRetry feature.",
495                                  self.arvrunner.label(self))
496             else:
497                 processStatus = "permanentFail"
498
499             logc = None
500             if record["log_uuid"]:
501                 logc = arvados.collection.Collection(record["log_uuid"],
502                                                      api_client=self.arvrunner.api,
503                                                      keep_client=self.arvrunner.keep_client,
504                                                      num_retries=self.arvrunner.num_retries)
505
506             if processStatus == "permanentFail" and logc is not None:
507                 label = self.arvrunner.label(self)
508                 done.logtail(
509                     logc, logger.error,
510                     "%s (%s) error log:" % (label, record["uuid"]), maxlen=40, include_crunchrun=(rcode is None or rcode > 127))
511
512             if record["output_uuid"]:
513                 if self.arvrunner.trash_intermediate or self.arvrunner.intermediate_output_ttl:
514                     # Compute the trash time to avoid requesting the collection record.
515                     trash_at = ciso8601.parse_datetime_as_naive(record["modified_at"]) + datetime.timedelta(0, self.arvrunner.intermediate_output_ttl)
516                     aftertime = " at %s" % trash_at.strftime("%Y-%m-%d %H:%M:%S UTC") if self.arvrunner.intermediate_output_ttl else ""
517                     orpart = ", or" if self.arvrunner.trash_intermediate and self.arvrunner.intermediate_output_ttl else ""
518                     oncomplete = " upon successful completion of the workflow" if self.arvrunner.trash_intermediate else ""
519                     logger.info("%s Intermediate output %s (%s) will be trashed%s%s%s." % (
520                         self.arvrunner.label(self), record["output_uuid"], container["output"], aftertime, orpart, oncomplete))
521                 self.arvrunner.add_intermediate_output(record["output_uuid"])
522
523             if container["output"]:
524                 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
525
526             properties = record["properties"].copy()
527             properties["cwl_output"] = outputs
528             self.arvrunner.api.container_requests().update(
529                 uuid=self.uuid,
530                 body={"container_request": {"properties": properties}}
531             ).execute(num_retries=self.arvrunner.num_retries)
532
533             if logc is not None and self.job_runtime.enable_usage_report is not False:
534                 try:
535                     summarizer = crunchstat_summary.summarizer.ContainerRequestSummarizer(
536                         record,
537                         collection_object=logc,
538                         label=self.name,
539                         arv=self.arvrunner.api)
540                     summarizer.run()
541                     with logc.open("usage_report.html", "wt") as mr:
542                         mr.write(summarizer.html_report())
543                     logc.save()
544
545                     # Post warnings about nodes that are under-utilized.
546                     for rc in summarizer._recommend_gen(lambda x: x):
547                         self.job_runtime.usage_report_notes.append(rc)
548
549                 except Exception as e:
550                     logger.warning("%s unable to generate resource usage report",
551                                  self.arvrunner.label(self),
552                                  exc_info=(e if self.arvrunner.debug else False))
553
554         except WorkflowException as e:
555             # Only include a stack trace if in debug mode.
556             # A stack trace may obfuscate more useful output about the workflow.
557             logger.error("%s unable to collect output from %s:\n%s",
558                          self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
559             processStatus = "permanentFail"
560         except Exception:
561             logger.exception("%s while getting output object:", self.arvrunner.label(self))
562             processStatus = "permanentFail"
563         finally:
564             if not retried:
565                 self.output_callback(outputs, processStatus)
566
567
568 class RunnerContainer(Runner):
569     """Submit and manage a container that runs arvados-cwl-runner."""
570
571     def arvados_job_spec(self, runtimeContext, git_info):
572         """Create an Arvados container request for this workflow.
573
574         The returned dict can be used to create a container passed as
575         the +body+ argument to container_requests().create().
576         """
577
578         adjustDirObjs(self.job_order, trim_listing)
579         visit_class(self.job_order, ("File", "Directory"), trim_anonymous_location)
580         visit_class(self.job_order, ("File", "Directory"), remove_redundant_fields)
581
582         secret_mounts = {}
583         for param in sorted(self.job_order.keys()):
584             if self.secret_store.has_secret(self.job_order[param]):
585                 mnt = "/secrets/s%d" % len(secret_mounts)
586                 secret_mounts[mnt] = {
587                     "kind": "text",
588                     "content": self.secret_store.retrieve(self.job_order[param])
589                 }
590                 self.job_order[param] = {"$include": mnt}
591
592         container_image = arvados_jobs_image(self.arvrunner, self.jobs_image, runtimeContext)
593
594         workflow_runner_req, _ = self.embedded_tool.get_requirement("http://arvados.org/cwl#WorkflowRunnerResources")
595         if workflow_runner_req and workflow_runner_req.get("acrContainerImage"):
596             container_image = workflow_runner_req.get("acrContainerImage")
597
598         container_req = {
599             "name": self.name,
600             "output_path": "/var/spool/cwl",
601             "cwd": "/var/spool/cwl",
602             "priority": self.priority,
603             "state": "Committed",
604             "container_image": container_image,
605             "mounts": {
606                 "/var/lib/cwl/cwl.input.json": {
607                     "kind": "json",
608                     "content": self.job_order
609                 },
610                 "stdout": {
611                     "kind": "file",
612                     "path": "/var/spool/cwl/cwl.output.json"
613                 },
614                 "/var/spool/cwl": {
615                     "kind": "collection",
616                     "writable": True
617                 }
618             },
619             "secret_mounts": secret_mounts,
620             "runtime_constraints": {
621                 "vcpus": math.ceil(self.submit_runner_cores),
622                 "ram": 1024*1024 * (math.ceil(self.submit_runner_ram) + math.ceil(self.collection_cache_size)),
623                 "API": True
624             },
625             "use_existing": self.reuse_runner,
626             "properties": {}
627         }
628
629         if self.embedded_tool.tool.get("id", "").startswith("keep:"):
630             sp = self.embedded_tool.tool["id"].split('/')
631             workflowcollection = sp[0][5:]
632             workflowname = "/".join(sp[1:])
633             workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
634             container_req["mounts"]["/var/lib/cwl/workflow"] = {
635                 "kind": "collection",
636                 "portable_data_hash": "%s" % workflowcollection
637             }
638         elif self.embedded_tool.tool.get("id", "").startswith("arvwf:"):
639             uuid, frg = urllib.parse.urldefrag(self.embedded_tool.tool["id"])
640             workflowpath = "/var/lib/cwl/workflow.json#" + frg
641             packedtxt = self.loadingContext.loader.fetch_text(uuid)
642             yaml = ruamel.yaml.YAML(typ='safe', pure=True)
643             packed = yaml.load(packedtxt)
644             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
645                 "kind": "json",
646                 "content": packed
647             }
648             container_req["properties"]["template_uuid"] = self.embedded_tool.tool["id"][6:33]
649         elif self.embedded_tool.tool.get("id", "").startswith("file:"):
650             raise WorkflowException("Tool id '%s' is a local file but expected keep: or arvwf:" % self.embedded_tool.tool.get("id"))
651         else:
652             main = self.loadingContext.loader.idx["_:main"]
653             if main.get("id") == "_:main":
654                 del main["id"]
655             workflowpath = "/var/lib/cwl/workflow.json#main"
656             container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
657                 "kind": "json",
658                 "content": main
659             }
660
661         container_req["properties"].update({k.replace("http://arvados.org/cwl#", "arv:"): v for k, v in git_info.items()})
662
663         properties_req, _ = self.embedded_tool.get_requirement("http://arvados.org/cwl#ProcessProperties")
664         if properties_req:
665             builder = make_builder(self.job_order, self.embedded_tool.hints, self.embedded_tool.requirements, runtimeContext, self.embedded_tool.metadata)
666             for pr in properties_req["processProperties"]:
667                 container_req["properties"][pr["propertyName"]] = builder.do_eval(pr["propertyValue"])
668
669         # --local means execute the workflow instead of submitting a container request
670         # --api=containers means use the containers API
671         # --no-log-timestamps means don't add timestamps (the logging infrastructure does this)
672         # --disable-validate because we already validated so don't need to do it again
673         # --eval-timeout is the timeout for javascript invocation
674         # --parallel-task-count is the number of threads to use for job submission
675         # --enable/disable-reuse sets desired job reuse
676         # --collection-cache-size sets aside memory to store collections
677         command = ["arvados-cwl-runner",
678                    "--local",
679                    "--api=containers",
680                    "--no-log-timestamps",
681                    "--disable-validate",
682                    "--disable-color",
683                    "--eval-timeout=%s" % self.arvrunner.eval_timeout,
684                    "--thread-count=%s" % self.arvrunner.thread_count,
685                    "--enable-reuse" if self.enable_reuse else "--disable-reuse",
686                    "--collection-cache-size=%s" % self.collection_cache_size]
687
688         if self.output_name:
689             command.append("--output-name=" + self.output_name)
690             container_req["output_name"] = self.output_name
691
692         if self.output_tags:
693             command.append("--output-tags=" + self.output_tags)
694
695         if runtimeContext.debug:
696             command.append("--debug")
697
698         if runtimeContext.storage_classes != "default" and runtimeContext.storage_classes:
699             command.append("--storage-classes=" + runtimeContext.storage_classes)
700
701         if runtimeContext.intermediate_storage_classes != "default" and runtimeContext.intermediate_storage_classes:
702             command.append("--intermediate-storage-classes=" + runtimeContext.intermediate_storage_classes)
703
704         if runtimeContext.on_error:
705             command.append("--on-error=" + self.on_error)
706
707         if runtimeContext.intermediate_output_ttl:
708             command.append("--intermediate-output-ttl=%d" % runtimeContext.intermediate_output_ttl)
709
710         if runtimeContext.trash_intermediate:
711             command.append("--trash-intermediate")
712
713         if runtimeContext.project_uuid:
714             command.append("--project-uuid="+runtimeContext.project_uuid)
715
716         if self.enable_dev:
717             command.append("--enable-dev")
718
719         if runtimeContext.enable_preemptible is True:
720             command.append("--enable-preemptible")
721
722         if runtimeContext.enable_preemptible is False:
723             command.append("--disable-preemptible")
724
725         if runtimeContext.varying_url_params:
726             command.append("--varying-url-params="+runtimeContext.varying_url_params)
727
728         if runtimeContext.prefer_cached_downloads:
729             command.append("--prefer-cached-downloads")
730
731         if runtimeContext.enable_usage_report is True:
732             command.append("--enable-usage-report")
733
734         if runtimeContext.enable_usage_report is False:
735             command.append("--disable-usage-report")
736
737         if self.fast_parser:
738             command.append("--fast-parser")
739
740         command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
741
742         container_req["command"] = command
743
744         return container_req
745
746
747     def run(self, runtimeContext):
748         runtimeContext.keepprefix = "keep:"
749         job_spec = self.arvados_job_spec(runtimeContext, self.git_info)
750         if runtimeContext.project_uuid:
751             job_spec["owner_uuid"] = runtimeContext.project_uuid
752
753         extra_submit_params = {}
754         if runtimeContext.submit_runner_cluster:
755             extra_submit_params["cluster_id"] = runtimeContext.submit_runner_cluster
756
757         if runtimeContext.submit_request_uuid:
758             if "cluster_id" in extra_submit_params:
759                 # Doesn't make sense for "update" and actually fails
760                 del extra_submit_params["cluster_id"]
761             response = self.arvrunner.api.container_requests().update(
762                 uuid=runtimeContext.submit_request_uuid,
763                 body=job_spec,
764                 **extra_submit_params
765             ).execute(num_retries=self.arvrunner.num_retries)
766         else:
767             response = self.arvrunner.api.container_requests().create(
768                 body=job_spec,
769                 **extra_submit_params
770             ).execute(num_retries=self.arvrunner.num_retries)
771
772         self.uuid = response["uuid"]
773         self.arvrunner.process_submitted(self)
774
775         logger.info("%s submitted container_request %s", self.arvrunner.label(self), response["uuid"])
776
777         workbench2 = self.arvrunner.api.config()["Services"]["Workbench2"]["ExternalURL"]
778         if workbench2:
779             url = "{}processes/{}".format(workbench2, response["uuid"])
780             logger.info("Monitor workflow progress at %s", url)
781
782
783     def done(self, record):
784         try:
785             container = self.arvrunner.api.containers().get(
786                 uuid=record["container_uuid"]
787             ).execute(num_retries=self.arvrunner.num_retries)
788             container["log"] = record["log_uuid"]
789         except Exception:
790             logger.exception("%s while getting runner container", self.arvrunner.label(self))
791             self.arvrunner.output_callback({}, "permanentFail")
792         else:
793             super(RunnerContainer, self).done(container)