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