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