20462: Refactor "common prefix" function & fix fencepost errors
[arvados.git] / sdk / cwl / arvados_cwl / __init__.py
1 #!/usr/bin/env python3
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: Apache-2.0
5
6 # Implement cwl-runner interface for submitting and running work on Arvados, using
7 # the Crunch containers API.
8
9 from future.utils import viewitems
10 from builtins import str
11
12 import argparse
13 import logging
14 import os
15 import sys
16 import re
17 import pkg_resources  # part of setuptools
18
19 from schema_salad.sourceline import SourceLine
20 import schema_salad.validate as validate
21 import cwltool.main
22 import cwltool.workflow
23 import cwltool.process
24 import cwltool.argparser
25 from cwltool.errors import WorkflowException
26 from cwltool.process import shortname, UnsupportedRequirement, use_custom_schema
27 from cwltool.utils import adjustFileObjs, adjustDirObjs, get_listing
28
29 import arvados
30 import arvados.config
31 from arvados.keep import KeepClient
32 from arvados.errors import ApiError
33 import arvados.commands._util as arv_cmd
34 from arvados.api import OrderedJsonModel
35
36 from .perf import Perf
37 from ._version import __version__
38 from .executor import ArvCwlExecutor
39 from .fsaccess import workflow_uuid_pattern
40
41 # These aren't used directly in this file but
42 # other code expects to import them from here
43 from .arvcontainer import ArvadosContainer
44 from .arvtool import ArvadosCommandTool
45 from .fsaccess import CollectionFsAccess, CollectionCache, CollectionFetcher
46 from .util import get_current_container
47 from .executor import RuntimeStatusLoggingHandler, DEFAULT_PRIORITY
48 from .arvworkflow import ArvadosWorkflow
49
50 logger = logging.getLogger('arvados.cwl-runner')
51 metrics = logging.getLogger('arvados.cwl-runner.metrics')
52 logger.setLevel(logging.INFO)
53
54 arvados.log_handler.setFormatter(logging.Formatter(
55         '%(asctime)s %(name)s %(levelname)s: %(message)s',
56         '%Y-%m-%d %H:%M:%S'))
57
58 def versionstring():
59     """Print version string of key packages for provenance and debugging."""
60
61     arvcwlpkg = pkg_resources.require("arvados-cwl-runner")
62     arvpkg = pkg_resources.require("arvados-python-client")
63     cwlpkg = pkg_resources.require("cwltool")
64
65     return "%s %s, %s %s, %s %s" % (sys.argv[0], arvcwlpkg[0].version,
66                                     "arvados-python-client", arvpkg[0].version,
67                                     "cwltool", cwlpkg[0].version)
68
69
70 def arg_parser():  # type: () -> argparse.ArgumentParser
71     parser = argparse.ArgumentParser(description='Arvados executor for Common Workflow Language')
72
73     parser.add_argument("--basedir",
74                         help="Base directory used to resolve relative references in the input, default to directory of input object file or current directory (if inputs piped/provided on command line).")
75     parser.add_argument("--outdir", default=os.path.abspath('.'),
76                         help="Output directory, default current directory")
77
78     parser.add_argument("--eval-timeout",
79                         help="Time to wait for a Javascript expression to evaluate before giving an error, default 20s.",
80                         type=float,
81                         default=20)
82
83     exgroup = parser.add_mutually_exclusive_group()
84     exgroup.add_argument("--print-dot", action="store_true",
85                          help="Print workflow visualization in graphviz format and exit")
86     exgroup.add_argument("--version", action="version", help="Print version and exit", version=versionstring())
87     exgroup.add_argument("--validate", action="store_true", help="Validate CWL document only.")
88
89     exgroup = parser.add_mutually_exclusive_group()
90     exgroup.add_argument("--verbose", action="store_true", help="Default logging")
91     exgroup.add_argument("--quiet", action="store_true", help="Only print warnings and errors.")
92     exgroup.add_argument("--debug", action="store_true", help="Print even more logging")
93
94     parser.add_argument("--metrics", action="store_true", help="Print timing metrics")
95
96     parser.add_argument("--tool-help", action="store_true", help="Print command line help for tool")
97
98     exgroup = parser.add_mutually_exclusive_group()
99     exgroup.add_argument("--enable-reuse", action="store_true",
100                         default=True, dest="enable_reuse",
101                         help="Enable container reuse (default)")
102     exgroup.add_argument("--disable-reuse", action="store_false",
103                         default=True, dest="enable_reuse",
104                         help="Disable container reuse")
105
106     parser.add_argument("--project-uuid", metavar="UUID", help="Project that will own the workflow containers, if not provided, will go to home project.")
107     parser.add_argument("--output-name", help="Name to use for collection that stores the final output.", default=None)
108     parser.add_argument("--output-tags", help="Tags for the final output collection separated by commas, e.g., '--output-tags tag0,tag1,tag2'.", default=None)
109     parser.add_argument("--ignore-docker-for-reuse", action="store_true",
110                         help="Ignore Docker image version when deciding whether to reuse past containers.",
111                         default=False)
112
113     exgroup = parser.add_mutually_exclusive_group()
114     exgroup.add_argument("--submit", action="store_true", help="Submit workflow to run on Arvados.",
115                         default=True, dest="submit")
116     exgroup.add_argument("--local", action="store_false", help="Run workflow on local host (submits containers to Arvados).",
117                         default=True, dest="submit")
118     exgroup.add_argument("--create-template", action="store_true", help="(Deprecated) synonym for --create-workflow.",
119                          dest="create_workflow")
120     exgroup.add_argument("--create-workflow", action="store_true", help="Register an Arvados workflow that can be run from Workbench")
121     exgroup.add_argument("--update-workflow", metavar="UUID", help="Update an existing Arvados workflow with the given UUID.")
122
123     exgroup = parser.add_mutually_exclusive_group()
124     exgroup.add_argument("--wait", action="store_true", help="After submitting workflow runner, wait for completion.",
125                         default=True, dest="wait")
126     exgroup.add_argument("--no-wait", action="store_false", help="Submit workflow runner and exit.",
127                         default=True, dest="wait")
128
129     exgroup = parser.add_mutually_exclusive_group()
130     exgroup.add_argument("--log-timestamps", action="store_true", help="Prefix logging lines with timestamp",
131                         default=True, dest="log_timestamps")
132     exgroup.add_argument("--no-log-timestamps", action="store_false", help="No timestamp on logging lines",
133                         default=True, dest="log_timestamps")
134
135     parser.add_argument("--api",
136                         default=None, dest="work_api",
137                         choices=("containers",),
138                         help="Select work submission API.  Only supports 'containers'")
139
140     parser.add_argument("--compute-checksum", action="store_true", default=False,
141                         help="Compute checksum of contents while collecting outputs",
142                         dest="compute_checksum")
143
144     parser.add_argument("--submit-runner-ram", type=int,
145                         help="RAM (in MiB) required for the workflow runner job (default 1024)",
146                         default=None)
147
148     parser.add_argument("--submit-runner-image",
149                         help="Docker image for workflow runner job, default arvados/jobs:%s" % __version__,
150                         default=None)
151
152     parser.add_argument("--always-submit-runner", action="store_true",
153                         help="When invoked with --submit --wait, always submit a runner to manage the workflow, even when only running a single CommandLineTool",
154                         default=False)
155
156     parser.add_argument("--match-submitter-images", action="store_true",
157                         default=False, dest="match_local_docker",
158                         help="Where Arvados has more than one Docker image of the same name, use image from the Docker instance on the submitting node.")
159
160     exgroup = parser.add_mutually_exclusive_group()
161     exgroup.add_argument("--submit-request-uuid",
162                          default=None,
163                          help="Update and commit to supplied container request instead of creating a new one.",
164                          metavar="UUID")
165     exgroup.add_argument("--submit-runner-cluster",
166                          help="Submit workflow runner to a remote cluster",
167                          default=None,
168                          metavar="CLUSTER_ID")
169
170     parser.add_argument("--collection-cache-size", type=int,
171                         default=None,
172                         help="Collection cache size (in MiB, default 256).")
173
174     parser.add_argument("--name",
175                         help="Name to use for workflow execution instance.",
176                         default=None)
177
178     parser.add_argument("--on-error",
179                         help="Desired workflow behavior when a step fails.  One of 'stop' (do not submit any more steps) or "
180                         "'continue' (may submit other steps that are not downstream from the error). Default is 'continue'.",
181                         default="continue", choices=("stop", "continue"))
182
183     parser.add_argument("--enable-dev", action="store_true",
184                         help="Enable loading and running development versions "
185                              "of the CWL standards.", default=False)
186     parser.add_argument('--storage-classes', default="default",
187                         help="Specify comma separated list of storage classes to be used when saving final workflow output to Keep.")
188     parser.add_argument('--intermediate-storage-classes', default="default",
189                         help="Specify comma separated list of storage classes to be used when saving intermediate workflow output to Keep.")
190
191     parser.add_argument("--intermediate-output-ttl", type=int, metavar="N",
192                         help="If N > 0, intermediate output collections will be trashed N seconds after creation.  Default is 0 (don't trash).",
193                         default=0)
194
195     parser.add_argument("--priority", type=int,
196                         help="Workflow priority (range 1..1000, higher has precedence over lower)",
197                         default=DEFAULT_PRIORITY)
198
199     parser.add_argument("--disable-validate", dest="do_validate",
200                         action="store_false", default=True,
201                         help=argparse.SUPPRESS)
202
203     parser.add_argument("--disable-git", dest="git_info",
204                         action="store_false", default=True,
205                         help=argparse.SUPPRESS)
206
207     parser.add_argument("--disable-color", dest="enable_color",
208                         action="store_false", default=True,
209                         help=argparse.SUPPRESS)
210
211     parser.add_argument("--disable-js-validation",
212                         action="store_true", default=False,
213                         help=argparse.SUPPRESS)
214
215     parser.add_argument("--fast-parser", dest="fast_parser",
216                         action="store_true", default=False,
217                         help=argparse.SUPPRESS)
218
219     parser.add_argument("--thread-count", type=int,
220                         default=0, help="Number of threads to use for job submit and output collection.")
221
222     parser.add_argument("--http-timeout", type=int,
223                         default=5*60, dest="http_timeout", help="API request timeout in seconds. Default is 300 seconds (5 minutes).")
224
225     parser.add_argument("--defer-downloads", action="store_true", default=False,
226                         help="When submitting a workflow, defer downloading HTTP URLs to workflow launch instead of downloading to Keep before submit.")
227
228     parser.add_argument("--varying-url-params", type=str, default="",
229                         help="A comma separated list of URL query parameters that should be ignored when storing HTTP URLs in Keep.")
230
231     parser.add_argument("--prefer-cached-downloads", action="store_true", default=False,
232                         help="If a HTTP URL is found in Keep, skip upstream URL freshness check (will not notice if the upstream has changed, but also not error if upstream is unavailable).")
233
234     exgroup = parser.add_mutually_exclusive_group()
235     exgroup.add_argument("--enable-preemptible", dest="enable_preemptible", default=None, action="store_true", help="Use preemptible instances. Control individual steps with arv:UsePreemptible hint.")
236     exgroup.add_argument("--disable-preemptible", dest="enable_preemptible", default=None, action="store_false", help="Don't use preemptible instances.")
237
238     exgroup = parser.add_mutually_exclusive_group()
239     exgroup.add_argument("--copy-deps", dest="copy_deps", default=None, action="store_true", help="Copy dependencies into the destination project.")
240     exgroup.add_argument("--no-copy-deps", dest="copy_deps", default=None, action="store_false", help="Leave dependencies where they are.")
241
242     parser.add_argument(
243         "--skip-schemas",
244         action="store_true",
245         help="Skip loading of schemas",
246         default=False,
247         dest="skip_schemas",
248     )
249
250     exgroup = parser.add_mutually_exclusive_group()
251     exgroup.add_argument("--trash-intermediate", action="store_true",
252                         default=False, dest="trash_intermediate",
253                          help="Immediately trash intermediate outputs on workflow success.")
254     exgroup.add_argument("--no-trash-intermediate", action="store_false",
255                         default=False, dest="trash_intermediate",
256                         help="Do not trash intermediate outputs (default).")
257
258     parser.add_argument("workflow", default=None, help="The workflow to execute")
259     parser.add_argument("job_order", nargs=argparse.REMAINDER, help="The input object to the workflow.")
260
261     return parser
262
263 def add_arv_hints():
264     cwltool.command_line_tool.ACCEPTLIST_EN_RELAXED_RE = re.compile(r".*")
265     cwltool.command_line_tool.ACCEPTLIST_RE = cwltool.command_line_tool.ACCEPTLIST_EN_RELAXED_RE
266     supported_versions = ["v1.0", "v1.1", "v1.2"]
267     for s in supported_versions:
268         res = pkg_resources.resource_stream(__name__, 'arv-cwl-schema-%s.yml' % s)
269         customschema = res.read().decode('utf-8')
270         use_custom_schema(s, "http://arvados.org/cwl", customschema)
271         res.close()
272     cwltool.process.supportedProcessRequirements.extend([
273         "http://arvados.org/cwl#RunInSingleContainer",
274         "http://arvados.org/cwl#OutputDirType",
275         "http://arvados.org/cwl#RuntimeConstraints",
276         "http://arvados.org/cwl#PartitionRequirement",
277         "http://arvados.org/cwl#APIRequirement",
278         "http://commonwl.org/cwltool#LoadListingRequirement",
279         "http://arvados.org/cwl#IntermediateOutput",
280         "http://arvados.org/cwl#ReuseRequirement",
281         "http://arvados.org/cwl#ClusterTarget",
282         "http://arvados.org/cwl#OutputStorageClass",
283         "http://arvados.org/cwl#ProcessProperties",
284         "http://commonwl.org/cwltool#CUDARequirement",
285         "http://arvados.org/cwl#UsePreemptible",
286         "http://arvados.org/cwl#OutputCollectionProperties",
287         "http://arvados.org/cwl#KeepCacheTypeRequirement",
288         "http://arvados.org/cwl#OutOfMemoryRetry",
289     ])
290
291 def exit_signal_handler(sigcode, frame):
292     logger.error(str(u"Caught signal {}, exiting.").format(sigcode))
293     sys.exit(-sigcode)
294
295 def main(args=sys.argv[1:],
296          stdout=sys.stdout,
297          stderr=sys.stderr,
298          api_client=None,
299          keep_client=None,
300          install_sig_handlers=True):
301     parser = arg_parser()
302
303     job_order_object = None
304     arvargs = parser.parse_args(args)
305
306     arvargs.use_container = True
307     arvargs.relax_path_checks = True
308     arvargs.print_supported_versions = False
309
310     if install_sig_handlers:
311         arv_cmd.install_signal_handlers()
312
313     if arvargs.update_workflow:
314         if arvargs.update_workflow.find('-7fd4e-') == 5:
315             want_api = 'containers'
316         else:
317             want_api = None
318         if want_api and arvargs.work_api and want_api != arvargs.work_api:
319             logger.error(str(u'--update-workflow arg {!r} uses {!r} API, but --api={!r} specified').format(
320                 arvargs.update_workflow, want_api, arvargs.work_api))
321             return 1
322         arvargs.work_api = want_api
323
324     if (arvargs.create_workflow or arvargs.update_workflow) and not arvargs.job_order:
325         job_order_object = ({}, "")
326
327     add_arv_hints()
328
329     for key, val in viewitems(cwltool.argparser.get_default_args()):
330         if not hasattr(arvargs, key):
331             setattr(arvargs, key, val)
332
333     try:
334         if api_client is None:
335             api_client = arvados.safeapi.ThreadSafeApiCache(
336                 api_params={"model": OrderedJsonModel(), "timeout": arvargs.http_timeout},
337                 keep_params={"num_retries": 4},
338                 version='v1',
339             )
340             keep_client = api_client.keep
341             # Make an API object now so errors are reported early.
342             api_client.users().current().execute()
343         if keep_client is None:
344             block_cache = arvados.keep.KeepBlockCache(disk_cache=True)
345             keep_client = arvados.keep.KeepClient(api_client=api_client, num_retries=4, block_cache=block_cache)
346         executor = ArvCwlExecutor(api_client, arvargs, keep_client=keep_client, num_retries=4, stdout=stdout)
347     except WorkflowException as e:
348         logger.error(e, exc_info=(sys.exc_info()[1] if arvargs.debug else False))
349         return 1
350     except Exception:
351         logger.exception("Error creating the Arvados CWL Executor")
352         return 1
353
354     # Note that unless in debug mode, some stack traces related to user
355     # workflow errors may be suppressed.
356
357     # Set the logging on most modules INFO (instead of default which is WARNING)
358     logger.setLevel(logging.INFO)
359     logging.getLogger('arvados').setLevel(logging.INFO)
360     logging.getLogger('arvados.keep').setLevel(logging.WARNING)
361
362     if arvargs.debug:
363         logger.setLevel(logging.DEBUG)
364         logging.getLogger('arvados').setLevel(logging.DEBUG)
365
366     if arvargs.quiet:
367         logger.setLevel(logging.WARN)
368         logging.getLogger('arvados').setLevel(logging.WARN)
369         logging.getLogger('arvados.arv-run').setLevel(logging.WARN)
370
371     if arvargs.metrics:
372         metrics.setLevel(logging.DEBUG)
373         logging.getLogger("cwltool.metrics").setLevel(logging.DEBUG)
374
375     if arvargs.log_timestamps:
376         arvados.log_handler.setFormatter(logging.Formatter(
377             '%(asctime)s %(name)s %(levelname)s: %(message)s',
378             '%Y-%m-%d %H:%M:%S'))
379     else:
380         arvados.log_handler.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s'))
381
382     if stdout is sys.stdout:
383         # cwltool.main has code to work around encoding issues with
384         # sys.stdout and unix pipes (they default to ASCII encoding,
385         # we want utf-8), so when stdout is sys.stdout set it to None
386         # to take advantage of that.  Don't override it for all cases
387         # since we still want to be able to capture stdout for the
388         # unit tests.
389         stdout = None
390
391     if arvargs.workflow.startswith("arvwf:") or workflow_uuid_pattern.match(arvargs.workflow) or arvargs.workflow.startswith("keep:"):
392         executor.loadingContext.do_validate = False
393         if arvargs.submit:
394             executor.fast_submit = True
395
396     return cwltool.main.main(args=arvargs,
397                              stdout=stdout,
398                              stderr=stderr,
399                              executor=executor.arv_executor,
400                              versionfunc=versionstring,
401                              job_order_object=job_order_object,
402                              logger_handler=arvados.log_handler,
403                              custom_schema_callback=add_arv_hints,
404                              loadingContext=executor.loadingContext,
405                              runtimeContext=executor.toplevel_runtimeContext,
406                              input_required=not (arvargs.create_workflow or arvargs.update_workflow))