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