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