4 import arvados.commands.ws as ws
15 import arvados.commands._util as arv_cmd
17 from arvados._version import __version__
19 logger = logging.getLogger('arvados.arv-run')
20 logger.setLevel(logging.INFO)
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)
48 class ArvFile(object):
49 def __init__(self, prefix, fn):
54 return (self.prefix+self.fn).__hash__()
56 def __eq__(self, other):
57 return (self.prefix == other.prefix) and (self.fn == other.fn)
59 class UploadFile(ArvFile):
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):
69 fn = os.path.join(root, ".arvados#collection")
70 if os.path.exists(fn):
71 with file(fn, 'r') as f:
73 return (c["portable_data_hash"], branch)
75 sp = os.path.split(root)
76 return is_in_collection(sp[0], os.path.join(sp[1], branch))
77 except (IOError, OSError):
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):
87 fn = os.path.join(root, ".arvados#project")
88 if os.path.exists(fn):
89 with file(fn, 'r') as f:
91 if 'writable_by' in c and current_user in c['writable_by']:
96 sp = os.path.split(root)
97 return determine_project(sp[0], current_user)
98 except (IOError, OSError):
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):
110 if stat.S_ISREG(st.st_mode):
111 sp = os.path.split(absfn)
112 (pdh, branch) = is_in_collection(sp[0], sp[1])
114 return ArvFile(prefix, fnPattern % (pdh, branch))
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])
122 return ArvFile(prefix, dirPattern % (pdh, branch))
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.
138 # no parent directories left
141 # path step takes next directory
142 pathstep = sp[0] + "/"
144 # check if pathstep is common prefix for all files
145 if not c.fn.startswith(pathstep):
149 # pathstep is common parent directory for all files, so remove the prefix
151 pathprefix += pathstep
153 c.fn = c.fn[len(pathstep):]
158 logger.info("Upload local files: \"%s\"", '" "'.join([c.fn for c in files]))
161 logger.info("$(input) is %s", pathprefix.rstrip('/'))
164 files = sorted(files, key=lambda x: x.fn)
165 collection = arvados.CollectionWriter(api, num_retries=num_retries)
168 sp = os.path.split(f.fn)
171 collection.start_new_stream(stream)
172 collection.write_file(f.fn, sp[1])
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)
178 item = exists["items"][0]
179 logger.info("Using collection %s", item["uuid"])
181 body = {"owner_uuid": project, "manifest_text": collection.manifest_text()}
184 item = api.collections().create(body=body, ensure_unique_name=True).execute()
185 logger.info("Uploaded to %s", item["uuid"])
187 pdh = item["portable_data_hash"]
190 c.keepref = "%s/%s" % (pdh, c.fn)
191 c.fn = fnPattern % (pdh, c.fn)
196 def main(arguments=None):
197 args = arvrun_parser.parse_args(arguments)
199 if len(args.args) == 0:
200 arvrun_parser.print_help()
203 starting_args = args.args
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.
212 # e.g. arv-run foo arg1 arg2 '|' bar arg3 arg4 '<' input1 input2 input3 '>' output.txt
213 # will be parsed into:
215 # ['input1', 'input2', 'input3'],
216 # ['foo', 'arg1', 'arg2'],
217 # ['bar', 'arg3', 'arg4']]
220 if c.startswith('>'):
223 slots[reading_into].append(c[1:])
224 elif c.startswith('<'):
227 slots[reading_into].append(c[1:])
229 reading_into = len(slots)
232 slots[reading_into].append(c)
234 if slots[0] and len(slots[0]) > 1:
235 logger.error("Can only specify a single stdout file (run-command substitutions are permitted)")
239 api = arvados.api('v1')
240 if args.project_uuid:
241 project = args.project_uuid
243 project = determine_project(os.getcwd(), api.users().current().execute()["uuid"])
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):
253 # j == 0 is stdin, j > 0 is commands
254 # always skip program executable (i == 0) in commands
256 elif a.startswith('\\'):
257 # if it starts with a \ then don't do any interpretation
260 # See if it looks like a file
261 command[i] = statfile('', a)
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
267 if isinstance(command[i], basestring):
271 command[i] = statfile(m.group(1), m.group(2))
274 files = [c for command in slots[1:] for c in command if isinstance(c, UploadFile)]
276 uploadfiles(files, api, dry_run=args.dry_run, num_retries=args.retries, project=project)
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]]
282 "script": "run-command",
283 "script_version": args.script_version,
284 "repository": args.repository,
285 "script_parameters": {
287 "runtime_constraints": {}
290 if args.docker_image:
291 component["runtime_constraints"]["docker_image"] = args.docker_image
294 group_parser = argparse.ArgumentParser()
295 group_parser.add_argument('-b', '--batch-size', type=int)
296 group_parser.add_argument('args', nargs=argparse.REMAINDER)
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}]
307 component["script_parameters"][inp] = groupargs.args
308 slots[s] = slots[s][0:i] + ["$(%s)" % inp]
309 task_foreach.append(inp)
311 if slots[s][i] == '\--':
315 component["script_parameters"]["task.stdout"] = slots[0][0]
317 task_foreach.append("stdin")
318 component["script_parameters"]["stdin"] = slots[1]
319 component["script_parameters"]["task.stdin"] = "$(stdin)"
322 component["script_parameters"]["task.foreach"] = task_foreach
324 component["script_parameters"]["command"] = slots[2:]
325 if args.ignore_rcode:
326 component["script_parameters"]["task.ignore_rcode"] = args.ignore_rcode
329 "name": "arv-run " + " | ".join([s[0] for s in slots[2:]]),
330 "description": "@" + " ".join(starting_args) + "@",
334 "state": "RunningOnClient" if args.local else "RunningOnServer"
338 print(json.dumps(pipeline, indent=4))
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"])
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"]])
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"])
354 logger.info("No output")
356 if __name__ == '__main__':