8784: Fix test for latest firefox.
[arvados.git] / sdk / python / arvados / commands / run.py
1 from __future__ import print_function
2 from __future__ import absolute_import
3 from builtins import range
4 from past.builtins import basestring
5 from builtins import object
6 import arvados
7 import arvados.commands.ws as ws
8 import argparse
9 import json
10 import re
11 import os
12 import stat
13 from . import put
14 import time
15 import subprocess
16 import logging
17 import sys
18 import errno
19 import arvados.commands._util as arv_cmd
20 import arvados.collection
21
22 from arvados._version import __version__
23
24 logger = logging.getLogger('arvados.arv-run')
25 logger.setLevel(logging.INFO)
26
27 arvrun_parser = argparse.ArgumentParser(parents=[arv_cmd.retry_opt])
28 arvrun_parser.add_argument('--dry-run', action="store_true",
29                            help="Print out the pipeline that would be submitted and exit")
30 arvrun_parser.add_argument('--local', action="store_true",
31                            help="Run locally using arv-run-pipeline-instance")
32 arvrun_parser.add_argument('--docker-image', type=str,
33                            help="Docker image to use, otherwise use instance default.")
34 arvrun_parser.add_argument('--ignore-rcode', action="store_true",
35                            help="Commands that return non-zero return codes should not be considered failed.")
36 arvrun_parser.add_argument('--no-reuse', action="store_true",
37                            help="Do not reuse past jobs.")
38 arvrun_parser.add_argument('--no-wait', action="store_true",
39                            help="Do not wait and display logs after submitting command, just exit.")
40 arvrun_parser.add_argument('--project-uuid', type=str,
41                            help="Parent project of the pipeline")
42 arvrun_parser.add_argument('--git-dir', type=str, default="",
43                            help="Git repository passed to arv-crunch-job when using --local")
44 arvrun_parser.add_argument('--repository', type=str, default="arvados",
45                            help="repository field of component, default 'arvados'")
46 arvrun_parser.add_argument('--script-version', type=str, default="master",
47                            help="script_version field of component, default 'master'")
48 arvrun_parser.add_argument('--version', action='version',
49                            version="%s %s" % (sys.argv[0], __version__),
50                            help='Print version and exit.')
51 arvrun_parser.add_argument('args', nargs=argparse.REMAINDER)
52
53 class ArvFile(object):
54     def __init__(self, prefix, fn):
55         self.prefix = prefix
56         self.fn = fn
57
58     def __hash__(self):
59         return (self.prefix+self.fn).__hash__()
60
61     def __eq__(self, other):
62         return (self.prefix == other.prefix) and (self.fn == other.fn)
63
64 class UploadFile(ArvFile):
65     pass
66
67 # Determine if a file is in a collection, and return a tuple consisting of the
68 # portable data hash and the path relative to the root of the collection.
69 # Return None if the path isn't with an arv-mount collection or there was is error.
70 def is_in_collection(root, branch):
71     try:
72         if root == "/":
73             return (None, None)
74         fn = os.path.join(root, ".arvados#collection")
75         if os.path.exists(fn):
76             with file(fn, 'r') as f:
77                 c = json.load(f)
78             return (c["portable_data_hash"], branch)
79         else:
80             sp = os.path.split(root)
81             return is_in_collection(sp[0], os.path.join(sp[1], branch))
82     except (IOError, OSError):
83         return (None, None)
84
85 # Determine the project to place the output of this command by searching upward
86 # for arv-mount psuedofile indicating the project.  If the cwd isn't within
87 # an arv-mount project or there is an error, return current_user.
88 def determine_project(root, current_user):
89     try:
90         if root == "/":
91             return current_user
92         fn = os.path.join(root, ".arvados#project")
93         if os.path.exists(fn):
94             with file(fn, 'r') as f:
95                 c = json.load(f)
96             if 'writable_by' in c and current_user in c['writable_by']:
97                 return c["uuid"]
98             else:
99                 return current_user
100         else:
101             sp = os.path.split(root)
102             return determine_project(sp[0], current_user)
103     except (IOError, OSError):
104         return current_user
105
106 # Determine if string corresponds to a file, and if that file is part of a
107 # arv-mounted collection or only local to the machine.  Returns one of
108 # ArvFile() (file already exists in a collection), UploadFile() (file needs to
109 # be uploaded to a collection), or simply returns prefix+fn (which yields the
110 # original parameter string).
111 def statfile(prefix, fn, fnPattern="$(file %s/%s)", dirPattern="$(dir %s/%s/)", raiseOSError=False):
112     absfn = os.path.abspath(fn)
113     try:
114         st = os.stat(absfn)
115         sp = os.path.split(absfn)
116         (pdh, branch) = is_in_collection(sp[0], sp[1])
117         if pdh:
118             if stat.S_ISREG(st.st_mode):
119                 return ArvFile(prefix, fnPattern % (pdh, branch))
120             elif stat.S_ISDIR(st.st_mode):
121                 return ArvFile(prefix, dirPattern % (pdh, branch))
122             else:
123                 raise Exception("%s is not a regular file or directory" % absfn)
124         else:
125             # trim leading '/' for path prefix test later
126             return UploadFile(prefix, absfn[1:])
127     except OSError as e:
128         if e.errno == errno.ENOENT and not raiseOSError:
129             pass
130         else:
131             raise
132
133     return prefix+fn
134
135 def write_file(collection, pathprefix, fn):
136     with open(os.path.join(pathprefix, fn)) as src:
137         dst = collection.open(fn, "w")
138         r = src.read(1024*128)
139         while r:
140             dst.write(r)
141             r = src.read(1024*128)
142         dst.close(flush=False)
143
144 def uploadfiles(files, api, dry_run=False, num_retries=0,
145                 project=None,
146                 fnPattern="$(file %s/%s)",
147                 name=None,
148                 collection=None):
149     # Find the smallest path prefix that includes all the files that need to be uploaded.
150     # This starts at the root and iteratively removes common parent directory prefixes
151     # until all file paths no longer have a common parent.
152     if files:
153         n = True
154         pathprefix = "/"
155         while n:
156             pathstep = None
157             for c in files:
158                 if pathstep is None:
159                     sp = c.fn.split('/')
160                     if len(sp) < 2:
161                         # no parent directories left
162                         n = False
163                         break
164                     # path step takes next directory
165                     pathstep = sp[0] + "/"
166                 else:
167                     # check if pathstep is common prefix for all files
168                     if not c.fn.startswith(pathstep):
169                         n = False
170                         break
171             if n:
172                 # pathstep is common parent directory for all files, so remove the prefix
173                 # from each path
174                 pathprefix += pathstep
175                 for c in files:
176                     c.fn = c.fn[len(pathstep):]
177
178         logger.info("Upload local files: \"%s\"", '" "'.join([c.fn for c in files]))
179
180     if dry_run:
181         logger.info("$(input) is %s", pathprefix.rstrip('/'))
182         pdh = "$(input)"
183     else:
184         files = sorted(files, key=lambda x: x.fn)
185         if collection is None:
186             collection = arvados.collection.Collection(api_client=api, num_retries=num_retries)
187         prev = ""
188         for f in files:
189             localpath = os.path.join(pathprefix, f.fn)
190             if prev and localpath.startswith(prev+"/"):
191                 # If this path is inside an already uploaded subdirectory,
192                 # don't redundantly re-upload it.
193                 # e.g. we uploaded /tmp/foo and the next file is /tmp/foo/bar
194                 # skip it because it starts with "/tmp/foo/"
195                 continue
196             prev = localpath
197             if os.path.isfile(localpath):
198                 write_file(collection, pathprefix, f.fn)
199             elif os.path.isdir(localpath):
200                 for root, dirs, iterfiles in os.walk(localpath):
201                     root = root[len(pathprefix):]
202                     for src in iterfiles:
203                         write_file(collection, pathprefix, os.path.join(root, src))
204
205         filters=[["portable_data_hash", "=", collection.portable_data_hash()]]
206         if name:
207             filters.append(["name", "like", name+"%"])
208         if project:
209             filters.append(["owner_uuid", "=", project])
210
211         exists = api.collections().list(filters=filters, limit=1).execute(num_retries=num_retries)
212
213         if exists["items"]:
214             item = exists["items"][0]
215             pdh = item["portable_data_hash"]
216             logger.info("Using collection %s (%s)", pdh, item["uuid"])
217         elif len(collection) > 0:
218             collection.save_new(name=name, owner_uuid=project, ensure_unique_name=True)
219             pdh = collection.portable_data_hash()
220             logger.info("Uploaded to %s (%s)", pdh, collection.manifest_locator())
221
222     for c in files:
223         c.keepref = "%s/%s" % (pdh, c.fn)
224         c.fn = fnPattern % (pdh, c.fn)
225
226
227 def main(arguments=None):
228     args = arvrun_parser.parse_args(arguments)
229
230     if len(args.args) == 0:
231         arvrun_parser.print_help()
232         return
233
234     starting_args = args.args
235
236     reading_into = 2
237
238     # Parse the command arguments into 'slots'.
239     # All words following '>' are output arguments and are collected into slots[0].
240     # All words following '<' are input arguments and are collected into slots[1].
241     # slots[2..] store the parameters of each command in the pipeline.
242     #
243     # e.g. arv-run foo arg1 arg2 '|' bar arg3 arg4 '<' input1 input2 input3 '>' output.txt
244     # will be parsed into:
245     #   [['output.txt'],
246     #    ['input1', 'input2', 'input3'],
247     #    ['foo', 'arg1', 'arg2'],
248     #    ['bar', 'arg3', 'arg4']]
249     slots = [[], [], []]
250     for c in args.args:
251         if c.startswith('>'):
252             reading_into = 0
253             if len(c) > 1:
254                 slots[reading_into].append(c[1:])
255         elif c.startswith('<'):
256             reading_into = 1
257             if len(c) > 1:
258                 slots[reading_into].append(c[1:])
259         elif c == '|':
260             reading_into = len(slots)
261             slots.append([])
262         else:
263             slots[reading_into].append(c)
264
265     if slots[0] and len(slots[0]) > 1:
266         logger.error("Can only specify a single stdout file (run-command substitutions are permitted)")
267         return
268
269     if not args.dry_run:
270         api = arvados.api('v1')
271         if args.project_uuid:
272             project = args.project_uuid
273         else:
274             project = determine_project(os.getcwd(), api.users().current().execute()["uuid"])
275
276     # Identify input files.  Look at each parameter and test to see if there is
277     # a file by that name.  This uses 'patterns' to look for within
278     # command line arguments, such as --foo=file.txt or -lfile.txt
279     patterns = [re.compile("([^=]+=)(.*)"),
280                 re.compile("(-[A-Za-z])(.+)")]
281     for j, command in enumerate(slots[1:]):
282         for i, a in enumerate(command):
283             if j > 0 and i == 0:
284                 # j == 0 is stdin, j > 0 is commands
285                 # always skip program executable (i == 0) in commands
286                 pass
287             elif a.startswith('\\'):
288                 # if it starts with a \ then don't do any interpretation
289                 command[i] = a[1:]
290             else:
291                 # See if it looks like a file
292                 command[i] = statfile('', a)
293
294                 # If a file named command[i] was found, it would now be an
295                 # ArvFile or UploadFile.  If command[i] is a basestring, that
296                 # means it doesn't correspond exactly to a file, so do some
297                 # pattern matching.
298                 if isinstance(command[i], basestring):
299                     for p in patterns:
300                         m = p.match(a)
301                         if m:
302                             command[i] = statfile(m.group(1), m.group(2))
303                             break
304
305     files = [c for command in slots[1:] for c in command if isinstance(c, UploadFile)]
306     if files:
307         uploadfiles(files, api, dry_run=args.dry_run, num_retries=args.retries, project=project)
308
309     for i in range(1, len(slots)):
310         slots[i] = [("%s%s" % (c.prefix, c.fn)) if isinstance(c, ArvFile) else c for c in slots[i]]
311
312     component = {
313         "script": "run-command",
314         "script_version": args.script_version,
315         "repository": args.repository,
316         "script_parameters": {
317         },
318         "runtime_constraints": {}
319     }
320
321     if args.docker_image:
322         component["runtime_constraints"]["docker_image"] = args.docker_image
323
324     task_foreach = []
325     group_parser = argparse.ArgumentParser()
326     group_parser.add_argument('-b', '--batch-size', type=int)
327     group_parser.add_argument('args', nargs=argparse.REMAINDER)
328
329     for s in range(2, len(slots)):
330         for i in range(0, len(slots[s])):
331             if slots[s][i] == '--':
332                 inp = "input%i" % (s-2)
333                 groupargs = group_parser.parse_args(slots[2][i+1:])
334                 if groupargs.batch_size:
335                     component["script_parameters"][inp] = {"value": {"batch":groupargs.args, "size":groupargs.batch_size}}
336                     slots[s] = slots[s][0:i] + [{"foreach": inp, "command": "$(%s)" % inp}]
337                 else:
338                     component["script_parameters"][inp] = groupargs.args
339                     slots[s] = slots[s][0:i] + ["$(%s)" % inp]
340                 task_foreach.append(inp)
341                 break
342             if slots[s][i] == '\--':
343                 slots[s][i] = '--'
344
345     if slots[0]:
346         component["script_parameters"]["task.stdout"] = slots[0][0]
347     if slots[1]:
348         task_foreach.append("stdin")
349         component["script_parameters"]["stdin"] = slots[1]
350         component["script_parameters"]["task.stdin"] = "$(stdin)"
351
352     if task_foreach:
353         component["script_parameters"]["task.foreach"] = task_foreach
354
355     component["script_parameters"]["command"] = slots[2:]
356     if args.ignore_rcode:
357         component["script_parameters"]["task.ignore_rcode"] = args.ignore_rcode
358
359     pipeline = {
360         "name": "arv-run " + " | ".join([s[0] for s in slots[2:]]),
361         "description": "@" + " ".join(starting_args) + "@",
362         "components": {
363             "command": component
364         },
365         "state": "RunningOnClient" if args.local else "RunningOnServer"
366     }
367
368     if args.dry_run:
369         print(json.dumps(pipeline, indent=4))
370     else:
371         pipeline["owner_uuid"] = project
372         pi = api.pipeline_instances().create(body=pipeline, ensure_unique_name=True).execute()
373         logger.info("Running pipeline %s", pi["uuid"])
374
375         if args.local:
376             subprocess.call(["arv-run-pipeline-instance", "--instance", pi["uuid"], "--run-jobs-here"] + (["--no-reuse"] if args.no_reuse else []))
377         elif not args.no_wait:
378             ws.main(["--pipeline", pi["uuid"]])
379
380         pi = api.pipeline_instances().get(uuid=pi["uuid"]).execute()
381         logger.info("Pipeline is %s", pi["state"])
382         if "output_uuid" in pi["components"]["command"]:
383             logger.info("Output is %s", pi["components"]["command"]["output_uuid"])
384         else:
385             logger.info("No output")
386
387 if __name__ == '__main__':
388     main()