17286: Tweak output if neither workbench2 or workbench1 is defined
[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.process import shortname, UnsupportedRequirement, use_custom_schema
26 from cwltool.utils import adjustFileObjs, adjustDirObjs, get_listing
27
28 import arvados
29 import arvados.config
30 from arvados.keep import KeepClient
31 from arvados.errors import ApiError
32 import arvados.commands._util as arv_cmd
33 from arvados.api import OrderedJsonModel
34
35 from .perf import Perf
36 from ._version import __version__
37 from .executor import ArvCwlExecutor
38
39 # These aren't used directly in this file but
40 # other code expects to import them from here
41 from .arvcontainer import ArvadosContainer
42 from .arvtool import ArvadosCommandTool
43 from .fsaccess import CollectionFsAccess, CollectionCache, CollectionFetcher
44 from .util import get_current_container
45 from .executor import RuntimeStatusLoggingHandler, DEFAULT_PRIORITY
46 from .arvworkflow import ArvadosWorkflow
47
48 logger = logging.getLogger('arvados.cwl-runner')
49 metrics = logging.getLogger('arvados.cwl-runner.metrics')
50 logger.setLevel(logging.INFO)
51
52 arvados.log_handler.setFormatter(logging.Formatter(
53         '%(asctime)s %(name)s %(levelname)s: %(message)s',
54         '%Y-%m-%d %H:%M:%S'))
55
56 def versionstring():
57     """Print version string of key packages for provenance and debugging."""
58
59     arvcwlpkg = pkg_resources.require("arvados-cwl-runner")
60     arvpkg = pkg_resources.require("arvados-python-client")
61     cwlpkg = pkg_resources.require("cwltool")
62
63     return "%s %s, %s %s, %s %s" % (sys.argv[0], arvcwlpkg[0].version,
64                                     "arvados-python-client", arvpkg[0].version,
65                                     "cwltool", cwlpkg[0].version)
66
67
68 def arg_parser():  # type: () -> argparse.ArgumentParser
69     parser = argparse.ArgumentParser(description='Arvados executor for Common Workflow Language')
70
71     parser.add_argument("--basedir",
72                         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).")
73     parser.add_argument("--outdir", default=os.path.abspath('.'),
74                         help="Output directory, default current directory")
75
76     parser.add_argument("--eval-timeout",
77                         help="Time to wait for a Javascript expression to evaluate before giving an error, default 20s.",
78                         type=float,
79                         default=20)
80
81     exgroup = parser.add_mutually_exclusive_group()
82     exgroup.add_argument("--print-dot", action="store_true",
83                          help="Print workflow visualization in graphviz format and exit")
84     exgroup.add_argument("--version", action="version", help="Print version and exit", version=versionstring())
85     exgroup.add_argument("--validate", action="store_true", help="Validate CWL document only.")
86
87     exgroup = parser.add_mutually_exclusive_group()
88     exgroup.add_argument("--verbose", action="store_true", help="Default logging")
89     exgroup.add_argument("--quiet", action="store_true", help="Only print warnings and errors.")
90     exgroup.add_argument("--debug", action="store_true", help="Print even more logging")
91
92     parser.add_argument("--metrics", action="store_true", help="Print timing metrics")
93
94     parser.add_argument("--tool-help", action="store_true", help="Print command line help for tool")
95
96     exgroup = parser.add_mutually_exclusive_group()
97     exgroup.add_argument("--enable-reuse", action="store_true",
98                         default=True, dest="enable_reuse",
99                         help="Enable container reuse (default)")
100     exgroup.add_argument("--disable-reuse", action="store_false",
101                         default=True, dest="enable_reuse",
102                         help="Disable container reuse")
103
104     parser.add_argument("--project-uuid", metavar="UUID", help="Project that will own the workflow containers, if not provided, will go to home project.")
105     parser.add_argument("--output-name", help="Name to use for collection that stores the final output.", default=None)
106     parser.add_argument("--output-tags", help="Tags for the final output collection separated by commas, e.g., '--output-tags tag0,tag1,tag2'.", default=None)
107     parser.add_argument("--ignore-docker-for-reuse", action="store_true",
108                         help="Ignore Docker image version when deciding whether to reuse past containers.",
109                         default=False)
110
111     exgroup = parser.add_mutually_exclusive_group()
112     exgroup.add_argument("--submit", action="store_true", help="Submit workflow to run on Arvados.",
113                         default=True, dest="submit")
114     exgroup.add_argument("--local", action="store_false", help="Run workflow on local host (submits containers to Arvados).",
115                         default=True, dest="submit")
116     exgroup.add_argument("--create-template", action="store_true", help="(Deprecated) synonym for --create-workflow.",
117                          dest="create_workflow")
118     exgroup.add_argument("--create-workflow", action="store_true", help="Register an Arvados workflow that can be run from Workbench")
119     exgroup.add_argument("--update-workflow", metavar="UUID", help="Update an existing Arvados workflow with the given UUID.")
120
121     exgroup = parser.add_mutually_exclusive_group()
122     exgroup.add_argument("--wait", action="store_true", help="After submitting workflow runner, wait for completion.",
123                         default=True, dest="wait")
124     exgroup.add_argument("--no-wait", action="store_false", help="Submit workflow runner and exit.",
125                         default=True, dest="wait")
126
127     exgroup = parser.add_mutually_exclusive_group()
128     exgroup.add_argument("--log-timestamps", action="store_true", help="Prefix logging lines with timestamp",
129                         default=True, dest="log_timestamps")
130     exgroup.add_argument("--no-log-timestamps", action="store_false", help="No timestamp on logging lines",
131                         default=True, dest="log_timestamps")
132
133     parser.add_argument("--api",
134                         default=None, dest="work_api",
135                         choices=("containers",),
136                         help="Select work submission API.  Only supports 'containers'")
137
138     parser.add_argument("--compute-checksum", action="store_true", default=False,
139                         help="Compute checksum of contents while collecting outputs",
140                         dest="compute_checksum")
141
142     parser.add_argument("--submit-runner-ram", type=int,
143                         help="RAM (in MiB) required for the workflow runner job (default 1024)",
144                         default=None)
145
146     parser.add_argument("--submit-runner-image",
147                         help="Docker image for workflow runner job, default arvados/jobs:%s" % __version__,
148                         default=None)
149
150     parser.add_argument("--always-submit-runner", action="store_true",
151                         help="When invoked with --submit --wait, always submit a runner to manage the workflow, even when only running a single CommandLineTool",
152                         default=False)
153
154     exgroup = parser.add_mutually_exclusive_group()
155     exgroup.add_argument("--submit-request-uuid",
156                          default=None,
157                          help="Update and commit to supplied container request instead of creating a new one.",
158                          metavar="UUID")
159     exgroup.add_argument("--submit-runner-cluster",
160                          help="Submit workflow runner to a remote cluster",
161                          default=None,
162                          metavar="CLUSTER_ID")
163
164     parser.add_argument("--collection-cache-size", type=int,
165                         default=None,
166                         help="Collection cache size (in MiB, default 256).")
167
168     parser.add_argument("--name",
169                         help="Name to use for workflow execution instance.",
170                         default=None)
171
172     parser.add_argument("--on-error",
173                         help="Desired workflow behavior when a step fails.  One of 'stop' (do not submit any more steps) or "
174                         "'continue' (may submit other steps that are not downstream from the error). Default is 'continue'.",
175                         default="continue", choices=("stop", "continue"))
176
177     parser.add_argument("--enable-dev", action="store_true",
178                         help="Enable loading and running development versions "
179                              "of the CWL standards.", default=False)
180     parser.add_argument('--storage-classes', default="default",
181                         help="Specify comma separated list of storage classes to be used when saving workflow output to Keep.")
182
183     parser.add_argument("--intermediate-output-ttl", type=int, metavar="N",
184                         help="If N > 0, intermediate output collections will be trashed N seconds after creation.  Default is 0 (don't trash).",
185                         default=0)
186
187     parser.add_argument("--priority", type=int,
188                         help="Workflow priority (range 1..1000, higher has precedence over lower)",
189                         default=DEFAULT_PRIORITY)
190
191     parser.add_argument("--disable-validate", dest="do_validate",
192                         action="store_false", default=True,
193                         help=argparse.SUPPRESS)
194
195     parser.add_argument("--disable-color", dest="enable_color",
196                         action="store_false", default=True,
197                         help=argparse.SUPPRESS)
198
199     parser.add_argument("--disable-js-validation",
200                         action="store_true", default=False,
201                         help=argparse.SUPPRESS)
202
203     parser.add_argument("--thread-count", type=int,
204                         default=4, help="Number of threads to use for job submit and output collection.")
205
206     parser.add_argument("--http-timeout", type=int,
207                         default=5*60, dest="http_timeout", help="API request timeout in seconds. Default is 300 seconds (5 minutes).")
208
209     parser.add_argument(
210         "--skip-schemas",
211         action="store_true",
212         help="Skip loading of schemas",
213         default=False,
214         dest="skip_schemas",
215     )
216
217     exgroup = parser.add_mutually_exclusive_group()
218     exgroup.add_argument("--trash-intermediate", action="store_true",
219                         default=False, dest="trash_intermediate",
220                          help="Immediately trash intermediate outputs on workflow success.")
221     exgroup.add_argument("--no-trash-intermediate", action="store_false",
222                         default=False, dest="trash_intermediate",
223                         help="Do not trash intermediate outputs (default).")
224
225     parser.add_argument("workflow", default=None, help="The workflow to execute")
226     parser.add_argument("job_order", nargs=argparse.REMAINDER, help="The input object to the workflow.")
227
228     return parser
229
230 def add_arv_hints():
231     cwltool.command_line_tool.ACCEPTLIST_EN_RELAXED_RE = re.compile(r".*")
232     cwltool.command_line_tool.ACCEPTLIST_RE = cwltool.command_line_tool.ACCEPTLIST_EN_RELAXED_RE
233     supported_versions = ["v1.0", "v1.1", "v1.2"]
234     for s in supported_versions:
235         res = pkg_resources.resource_stream(__name__, 'arv-cwl-schema-%s.yml' % s)
236         customschema = res.read().decode('utf-8')
237         use_custom_schema(s, "http://arvados.org/cwl", customschema)
238         res.close()
239     cwltool.process.supportedProcessRequirements.extend([
240         "http://arvados.org/cwl#RunInSingleContainer",
241         "http://arvados.org/cwl#OutputDirType",
242         "http://arvados.org/cwl#RuntimeConstraints",
243         "http://arvados.org/cwl#PartitionRequirement",
244         "http://arvados.org/cwl#APIRequirement",
245         "http://commonwl.org/cwltool#LoadListingRequirement",
246         "http://arvados.org/cwl#IntermediateOutput",
247         "http://arvados.org/cwl#ReuseRequirement",
248         "http://arvados.org/cwl#ClusterTarget"
249     ])
250
251 def exit_signal_handler(sigcode, frame):
252     logger.error(str(u"Caught signal {}, exiting.").format(sigcode))
253     sys.exit(-sigcode)
254
255 def main(args, stdout, stderr, api_client=None, keep_client=None,
256          install_sig_handlers=True):
257     parser = arg_parser()
258
259     job_order_object = None
260     arvargs = parser.parse_args(args)
261
262     if len(arvargs.storage_classes.strip().split(',')) > 1:
263         logger.error(str(u"Multiple storage classes are not supported currently."))
264         return 1
265
266     arvargs.use_container = True
267     arvargs.relax_path_checks = True
268     arvargs.print_supported_versions = False
269
270     if install_sig_handlers:
271         arv_cmd.install_signal_handlers()
272
273     if arvargs.update_workflow:
274         if arvargs.update_workflow.find('-7fd4e-') == 5:
275             want_api = 'containers'
276         else:
277             want_api = None
278         if want_api and arvargs.work_api and want_api != arvargs.work_api:
279             logger.error(str(u'--update-workflow arg {!r} uses {!r} API, but --api={!r} specified').format(
280                 arvargs.update_workflow, want_api, arvargs.work_api))
281             return 1
282         arvargs.work_api = want_api
283
284     if (arvargs.create_workflow or arvargs.update_workflow) and not arvargs.job_order:
285         job_order_object = ({}, "")
286
287     add_arv_hints()
288
289     for key, val in viewitems(cwltool.argparser.get_default_args()):
290         if not hasattr(arvargs, key):
291             setattr(arvargs, key, val)
292
293     try:
294         if api_client is None:
295             api_client = arvados.safeapi.ThreadSafeApiCache(
296                 api_params={"model": OrderedJsonModel(), "timeout": arvargs.http_timeout},
297                 keep_params={"num_retries": 4})
298             keep_client = api_client.keep
299             # Make an API object now so errors are reported early.
300             api_client.users().current().execute()
301         if keep_client is None:
302             keep_client = arvados.keep.KeepClient(api_client=api_client, num_retries=4)
303         executor = ArvCwlExecutor(api_client, arvargs, keep_client=keep_client, num_retries=4)
304     except Exception:
305         logger.exception("Error creating the Arvados CWL Executor")
306         return 1
307
308     # Note that unless in debug mode, some stack traces related to user
309     # workflow errors may be suppressed.
310     if arvargs.debug:
311         logger.setLevel(logging.DEBUG)
312         logging.getLogger('arvados').setLevel(logging.DEBUG)
313
314     if arvargs.quiet:
315         logger.setLevel(logging.WARN)
316         logging.getLogger('arvados').setLevel(logging.WARN)
317         logging.getLogger('arvados.arv-run').setLevel(logging.WARN)
318
319     if arvargs.metrics:
320         metrics.setLevel(logging.DEBUG)
321         logging.getLogger("cwltool.metrics").setLevel(logging.DEBUG)
322
323     if arvargs.log_timestamps:
324         arvados.log_handler.setFormatter(logging.Formatter(
325             '%(asctime)s %(name)s %(levelname)s: %(message)s',
326             '%Y-%m-%d %H:%M:%S'))
327     else:
328         arvados.log_handler.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s'))
329
330     if stdout is sys.stdout:
331         # cwltool.main has code to work around encoding issues with
332         # sys.stdout and unix pipes (they default to ASCII encoding,
333         # we want utf-8), so when stdout is sys.stdout set it to None
334         # to take advantage of that.  Don't override it for all cases
335         # since we still want to be able to capture stdout for the
336         # unit tests.
337         stdout = None
338
339     return cwltool.main.main(args=arvargs,
340                              stdout=stdout,
341                              stderr=stderr,
342                              executor=executor.arv_executor,
343                              versionfunc=versionstring,
344                              job_order_object=job_order_object,
345                              logger_handler=arvados.log_handler,
346                              custom_schema_callback=add_arv_hints,
347                              loadingContext=executor.loadingContext,
348                              runtimeContext=executor.runtimeContext,
349                              input_required=not (arvargs.create_workflow or arvargs.update_workflow))