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