19688: Update tests
[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("--thread-count", type=int,
216                         default=0, help="Number of threads to use for job submit and output collection.")
217
218     parser.add_argument("--http-timeout", type=int,
219                         default=5*60, dest="http_timeout", help="API request timeout in seconds. Default is 300 seconds (5 minutes).")
220
221     exgroup = parser.add_mutually_exclusive_group()
222     exgroup.add_argument("--enable-preemptible", dest="enable_preemptible", default=None, action="store_true", help="Use preemptible instances. Control individual steps with arv:UsePreemptible hint.")
223     exgroup.add_argument("--disable-preemptible", dest="enable_preemptible", default=None, action="store_false", help="Don't use preemptible instances.")
224
225     exgroup = parser.add_mutually_exclusive_group()
226     exgroup.add_argument("--copy-deps", dest="copy_deps", default=None, action="store_true", help="Copy dependencies into the destination project.")
227     exgroup.add_argument("--no-copy-deps", dest="copy_deps", default=None, action="store_false", help="Leave dependencies where they are.")
228
229     parser.add_argument(
230         "--skip-schemas",
231         action="store_true",
232         help="Skip loading of schemas",
233         default=False,
234         dest="skip_schemas",
235     )
236
237     exgroup = parser.add_mutually_exclusive_group()
238     exgroup.add_argument("--trash-intermediate", action="store_true",
239                         default=False, dest="trash_intermediate",
240                          help="Immediately trash intermediate outputs on workflow success.")
241     exgroup.add_argument("--no-trash-intermediate", action="store_false",
242                         default=False, dest="trash_intermediate",
243                         help="Do not trash intermediate outputs (default).")
244
245     parser.add_argument("workflow", default=None, help="The workflow to execute")
246     parser.add_argument("job_order", nargs=argparse.REMAINDER, help="The input object to the workflow.")
247
248     return parser
249
250 def add_arv_hints():
251     cwltool.command_line_tool.ACCEPTLIST_EN_RELAXED_RE = re.compile(r".*")
252     cwltool.command_line_tool.ACCEPTLIST_RE = cwltool.command_line_tool.ACCEPTLIST_EN_RELAXED_RE
253     supported_versions = ["v1.0", "v1.1", "v1.2"]
254     for s in supported_versions:
255         res = pkg_resources.resource_stream(__name__, 'arv-cwl-schema-%s.yml' % s)
256         customschema = res.read().decode('utf-8')
257         use_custom_schema(s, "http://arvados.org/cwl", customschema)
258         res.close()
259     cwltool.process.supportedProcessRequirements.extend([
260         "http://arvados.org/cwl#RunInSingleContainer",
261         "http://arvados.org/cwl#OutputDirType",
262         "http://arvados.org/cwl#RuntimeConstraints",
263         "http://arvados.org/cwl#PartitionRequirement",
264         "http://arvados.org/cwl#APIRequirement",
265         "http://commonwl.org/cwltool#LoadListingRequirement",
266         "http://arvados.org/cwl#IntermediateOutput",
267         "http://arvados.org/cwl#ReuseRequirement",
268         "http://arvados.org/cwl#ClusterTarget",
269         "http://arvados.org/cwl#OutputStorageClass",
270         "http://arvados.org/cwl#ProcessProperties",
271         "http://commonwl.org/cwltool#CUDARequirement",
272         "http://arvados.org/cwl#UsePreemptible",
273         "http://arvados.org/cwl#OutputCollectionProperties",
274     ])
275
276 def exit_signal_handler(sigcode, frame):
277     logger.error(str(u"Caught signal {}, exiting.").format(sigcode))
278     sys.exit(-sigcode)
279
280 def main(args=sys.argv[1:],
281          stdout=sys.stdout,
282          stderr=sys.stderr,
283          api_client=None,
284          keep_client=None,
285          install_sig_handlers=True):
286     parser = arg_parser()
287
288     job_order_object = None
289     arvargs = parser.parse_args(args)
290
291     arvargs.use_container = True
292     arvargs.relax_path_checks = True
293     arvargs.print_supported_versions = False
294
295     if install_sig_handlers:
296         arv_cmd.install_signal_handlers()
297
298     if arvargs.update_workflow:
299         if arvargs.update_workflow.find('-7fd4e-') == 5:
300             want_api = 'containers'
301         else:
302             want_api = None
303         if want_api and arvargs.work_api and want_api != arvargs.work_api:
304             logger.error(str(u'--update-workflow arg {!r} uses {!r} API, but --api={!r} specified').format(
305                 arvargs.update_workflow, want_api, arvargs.work_api))
306             return 1
307         arvargs.work_api = want_api
308
309     if (arvargs.create_workflow or arvargs.update_workflow) and not arvargs.job_order:
310         job_order_object = ({}, "")
311
312     add_arv_hints()
313
314     for key, val in viewitems(cwltool.argparser.get_default_args()):
315         if not hasattr(arvargs, key):
316             setattr(arvargs, key, val)
317
318     try:
319         if api_client is None:
320             api_client = arvados.safeapi.ThreadSafeApiCache(
321                 api_params={"model": OrderedJsonModel(), "timeout": arvargs.http_timeout},
322                 keep_params={"num_retries": 4})
323             keep_client = api_client.keep
324             # Make an API object now so errors are reported early.
325             api_client.users().current().execute()
326         if keep_client is None:
327             keep_client = arvados.keep.KeepClient(api_client=api_client, num_retries=4)
328         executor = ArvCwlExecutor(api_client, arvargs, keep_client=keep_client, num_retries=4, stdout=stdout)
329     except WorkflowException as e:
330         logger.error(e, exc_info=(sys.exc_info()[1] if arvargs.debug else False))
331         return 1
332     except Exception:
333         logger.exception("Error creating the Arvados CWL Executor")
334         return 1
335
336     # Note that unless in debug mode, some stack traces related to user
337     # workflow errors may be suppressed.
338     if arvargs.debug:
339         logger.setLevel(logging.DEBUG)
340         logging.getLogger('arvados').setLevel(logging.DEBUG)
341
342     if arvargs.quiet:
343         logger.setLevel(logging.WARN)
344         logging.getLogger('arvados').setLevel(logging.WARN)
345         logging.getLogger('arvados.arv-run').setLevel(logging.WARN)
346
347     if arvargs.metrics:
348         metrics.setLevel(logging.DEBUG)
349         logging.getLogger("cwltool.metrics").setLevel(logging.DEBUG)
350
351     if arvargs.log_timestamps:
352         arvados.log_handler.setFormatter(logging.Formatter(
353             '%(asctime)s %(name)s %(levelname)s: %(message)s',
354             '%Y-%m-%d %H:%M:%S'))
355     else:
356         arvados.log_handler.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s'))
357
358     if stdout is sys.stdout:
359         # cwltool.main has code to work around encoding issues with
360         # sys.stdout and unix pipes (they default to ASCII encoding,
361         # we want utf-8), so when stdout is sys.stdout set it to None
362         # to take advantage of that.  Don't override it for all cases
363         # since we still want to be able to capture stdout for the
364         # unit tests.
365         stdout = None
366
367     if arvargs.submit and (arvargs.workflow.startswith("arvwf:") or workflow_uuid_pattern.match(arvargs.workflow)):
368         executor.loadingContext.do_validate = False
369         executor.fast_submit = True
370
371     return cwltool.main.main(args=arvargs,
372                              stdout=stdout,
373                              stderr=stderr,
374                              executor=executor.arv_executor,
375                              versionfunc=versionstring,
376                              job_order_object=job_order_object,
377                              logger_handler=arvados.log_handler,
378                              custom_schema_callback=add_arv_hints,
379                              loadingContext=executor.loadingContext,
380                              runtimeContext=executor.toplevel_runtimeContext,
381                              input_required=not (arvargs.create_workflow or arvargs.update_workflow))