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