Merge branch '10869-cwl-keep-ref' refs #10869
[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         filters=[["portable_data_hash", "=", collection.portable_data_hash()],
175                  ["name", "like", name+"%"]]
176         if project:
177             filters.append(["owner_uuid", "=", project])
178
179         exists = api.collections().list(filters=filters).execute(num_retries=num_retries)
180
181         if exists["items"]:
182             item = exists["items"][0]
183             logger.info("Using collection %s", item["uuid"])
184         else:
185             body = {"owner_uuid": project, "manifest_text": collection.manifest_text()}
186             if name is not None:
187                 body["name"] = name
188             item = api.collections().create(body=body, ensure_unique_name=True).execute()
189             logger.info("Uploaded to %s", item["uuid"])
190
191         pdh = item["portable_data_hash"]
192
193     for c in files:
194         c.keepref = "%s/%s" % (pdh, c.fn)
195         c.fn = fnPattern % (pdh, c.fn)
196
197     os.chdir(orgdir)
198
199
200 def main(arguments=None):
201     args = arvrun_parser.parse_args(arguments)
202
203     if len(args.args) == 0:
204         arvrun_parser.print_help()
205         return
206
207     starting_args = args.args
208
209     reading_into = 2
210
211     # Parse the command arguments into 'slots'.
212     # All words following '>' are output arguments and are collected into slots[0].
213     # All words following '<' are input arguments and are collected into slots[1].
214     # slots[2..] store the parameters of each command in the pipeline.
215     #
216     # e.g. arv-run foo arg1 arg2 '|' bar arg3 arg4 '<' input1 input2 input3 '>' output.txt
217     # will be parsed into:
218     #   [['output.txt'],
219     #    ['input1', 'input2', 'input3'],
220     #    ['foo', 'arg1', 'arg2'],
221     #    ['bar', 'arg3', 'arg4']]
222     slots = [[], [], []]
223     for c in args.args:
224         if c.startswith('>'):
225             reading_into = 0
226             if len(c) > 1:
227                 slots[reading_into].append(c[1:])
228         elif c.startswith('<'):
229             reading_into = 1
230             if len(c) > 1:
231                 slots[reading_into].append(c[1:])
232         elif c == '|':
233             reading_into = len(slots)
234             slots.append([])
235         else:
236             slots[reading_into].append(c)
237
238     if slots[0] and len(slots[0]) > 1:
239         logger.error("Can only specify a single stdout file (run-command substitutions are permitted)")
240         return
241
242     if not args.dry_run:
243         api = arvados.api('v1')
244         if args.project_uuid:
245             project = args.project_uuid
246         else:
247             project = determine_project(os.getcwd(), api.users().current().execute()["uuid"])
248
249     # Identify input files.  Look at each parameter and test to see if there is
250     # a file by that name.  This uses 'patterns' to look for within
251     # command line arguments, such as --foo=file.txt or -lfile.txt
252     patterns = [re.compile("([^=]+=)(.*)"),
253                 re.compile("(-[A-Za-z])(.+)")]
254     for j, command in enumerate(slots[1:]):
255         for i, a in enumerate(command):
256             if j > 0 and i == 0:
257                 # j == 0 is stdin, j > 0 is commands
258                 # always skip program executable (i == 0) in commands
259                 pass
260             elif a.startswith('\\'):
261                 # if it starts with a \ then don't do any interpretation
262                 command[i] = a[1:]
263             else:
264                 # See if it looks like a file
265                 command[i] = statfile('', a)
266
267                 # If a file named command[i] was found, it would now be an
268                 # ArvFile or UploadFile.  If command[i] is a basestring, that
269                 # means it doesn't correspond exactly to a file, so do some
270                 # pattern matching.
271                 if isinstance(command[i], basestring):
272                     for p in patterns:
273                         m = p.match(a)
274                         if m:
275                             command[i] = statfile(m.group(1), m.group(2))
276                             break
277
278     files = [c for command in slots[1:] for c in command if isinstance(c, UploadFile)]
279     if files:
280         uploadfiles(files, api, dry_run=args.dry_run, num_retries=args.retries, project=project)
281
282     for i in xrange(1, len(slots)):
283         slots[i] = [("%s%s" % (c.prefix, c.fn)) if isinstance(c, ArvFile) else c for c in slots[i]]
284
285     component = {
286         "script": "run-command",
287         "script_version": args.script_version,
288         "repository": args.repository,
289         "script_parameters": {
290         },
291         "runtime_constraints": {}
292     }
293
294     if args.docker_image:
295         component["runtime_constraints"]["docker_image"] = args.docker_image
296
297     task_foreach = []
298     group_parser = argparse.ArgumentParser()
299     group_parser.add_argument('-b', '--batch-size', type=int)
300     group_parser.add_argument('args', nargs=argparse.REMAINDER)
301
302     for s in xrange(2, len(slots)):
303         for i in xrange(0, len(slots[s])):
304             if slots[s][i] == '--':
305                 inp = "input%i" % (s-2)
306                 groupargs = group_parser.parse_args(slots[2][i+1:])
307                 if groupargs.batch_size:
308                     component["script_parameters"][inp] = {"value": {"batch":groupargs.args, "size":groupargs.batch_size}}
309                     slots[s] = slots[s][0:i] + [{"foreach": inp, "command": "$(%s)" % inp}]
310                 else:
311                     component["script_parameters"][inp] = groupargs.args
312                     slots[s] = slots[s][0:i] + ["$(%s)" % inp]
313                 task_foreach.append(inp)
314                 break
315             if slots[s][i] == '\--':
316                 slots[s][i] = '--'
317
318     if slots[0]:
319         component["script_parameters"]["task.stdout"] = slots[0][0]
320     if slots[1]:
321         task_foreach.append("stdin")
322         component["script_parameters"]["stdin"] = slots[1]
323         component["script_parameters"]["task.stdin"] = "$(stdin)"
324
325     if task_foreach:
326         component["script_parameters"]["task.foreach"] = task_foreach
327
328     component["script_parameters"]["command"] = slots[2:]
329     if args.ignore_rcode:
330         component["script_parameters"]["task.ignore_rcode"] = args.ignore_rcode
331
332     pipeline = {
333         "name": "arv-run " + " | ".join([s[0] for s in slots[2:]]),
334         "description": "@" + " ".join(starting_args) + "@",
335         "components": {
336             "command": component
337         },
338         "state": "RunningOnClient" if args.local else "RunningOnServer"
339     }
340
341     if args.dry_run:
342         print(json.dumps(pipeline, indent=4))
343     else:
344         pipeline["owner_uuid"] = project
345         pi = api.pipeline_instances().create(body=pipeline, ensure_unique_name=True).execute()
346         logger.info("Running pipeline %s", pi["uuid"])
347
348         if args.local:
349             subprocess.call(["arv-run-pipeline-instance", "--instance", pi["uuid"], "--run-jobs-here"] + (["--no-reuse"] if args.no_reuse else []))
350         elif not args.no_wait:
351             ws.main(["--pipeline", pi["uuid"]])
352
353         pi = api.pipeline_instances().get(uuid=pi["uuid"]).execute()
354         logger.info("Pipeline is %s", pi["state"])
355         if "output_uuid" in pi["components"]["command"]:
356             logger.info("Output is %s", pi["components"]["command"]["output_uuid"])
357         else:
358             logger.info("No output")
359
360 if __name__ == '__main__':
361     main()