5 logger = logging.getLogger('run-command')
6 log_handler = logging.StreamHandler()
7 log_handler.setFormatter(logging.Formatter("run-command: %(message)s"))
8 logger.addHandler(log_handler)
9 logger.setLevel(logging.INFO)
17 import crunchutil.subst as subst
19 import arvados.commands.put as put
25 import multiprocessing
26 import crunchutil.robust_put as robust_put
27 import crunchutil.vwd as vwd
32 parser = argparse.ArgumentParser()
33 parser.add_argument('--dry-run', action='store_true')
34 parser.add_argument('--job-parameters', type=str, default="{}")
35 args = parser.parse_args()
40 api = arvados.api('v1')
41 t = arvados.current_task().tmpdir
42 os.chdir(arvados.current_task().tmpdir)
51 jobp = arvados.current_job()['script_parameters']
52 if len(arvados.current_task()['parameters']) > 0:
53 taskp = arvados.current_task()['parameters']
56 jobp = json.loads(args.job_parameters)
57 os.environ['JOB_UUID'] = 'zzzzz-8i9sb-1234567890abcde'
58 os.environ['TASK_UUID'] = 'zzzzz-ot0gb-1234567890abcde'
59 os.environ['CRUNCH_SRC'] = '/tmp/crunch-src'
60 os.environ['TASK_KEEPMOUNT'] = '/keep'
65 return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
71 return str(multiprocessing.cpu_count())
74 return os.environ['JOB_UUID']
77 return os.environ['TASK_UUID']
80 return os.environ['CRUNCH_SRC']
82 subst.default_subs["task.tmpdir"] = sub_tmpdir
83 subst.default_subs["task.outdir"] = sub_outdir
84 subst.default_subs["job.srcdir"] = sub_jobsrc
85 subst.default_subs["node.cores"] = sub_cores
86 subst.default_subs["job.uuid"] = sub_jobid
87 subst.default_subs["task.uuid"] = sub_taskid
89 class SigHandler(object):
93 def send_signal(self, sp, signum):
94 sp.send_signal(signum)
97 def add_to_group(gr, match):
98 m = ('^_^').join(match.groups())
101 gr[m].append(match.group(0))
103 def expand_item(p, c):
104 if isinstance(c, dict):
105 if "foreach" in c and "command" in c:
107 items = get_items(p, p[var])
110 params = copy.copy(p)
112 r.extend(expand_list(params, c["command"]))
114 if "list" in c and "index" in c and "command" in c:
116 items = get_items(p, p[var])
117 params = copy.copy(p)
118 params[var] = items[int(c["index"])]
119 return expand_list(params, c["command"])
121 pattern = re.compile(c["regex"])
123 items = get_items(p, p[c["filter"]])
124 return [i for i in items if pattern.match(i)]
126 items = get_items(p, p[c["group"]])
131 add_to_group(groups, p)
132 return [groups[k] for k in groups]
134 items = get_items(p, p[c["extract"]])
139 r.append(list(p.groups()))
141 elif isinstance(c, list):
142 return expand_list(p, c)
143 elif isinstance(c, basestring):
144 return [subst.do_substitution(p, c)]
148 def expand_list(p, l):
149 if isinstance(l, basestring):
150 return expand_item(p, l)
152 return [exp for arg in l for exp in expand_item(p, arg)]
154 def get_items(p, value):
155 if isinstance(value, dict):
156 return expand_item(p, value)
158 if isinstance(value, list):
159 return expand_list(p, value)
161 fn = subst.do_substitution(p, value)
162 mode = os.stat(fn).st_mode
163 prefix = fn[len(os.environ['TASK_KEEPMOUNT'])+1:]
165 if stat.S_ISDIR(mode):
166 items = [os.path.join(fn, l) for l in os.listdir(fn)]
167 elif stat.S_ISREG(mode):
169 items = [line.rstrip("\r\n") for line in f]
180 def recursive_foreach(params, fvars):
183 items = get_items(params, params[var])
184 logger.info("parallelizing on %s with items %s" % (var, items))
185 if items is not None:
187 params = copy.copy(params)
190 recursive_foreach(params, fvars)
193 arvados.api().job_tasks().create(body={
194 'job_uuid': arvados.current_job()['uuid'],
195 'created_by_job_task_uuid': arvados.current_task()['uuid'],
200 logger.info(expand_list(params, params["command"]))
202 logger.error("parameter %s with value %s in task.foreach yielded no items" % (var, params[var]))
206 if "task.foreach" in jobp:
207 if args.dry_run or arvados.current_task()['sequence'] == 0:
208 # This is the first task to start the other tasks and exit
209 fvars = jobp["task.foreach"]
210 if isinstance(fvars, basestring):
212 if not isinstance(fvars, list) or len(fvars) == 0:
213 logger.error("value of task.foreach must be a string or non-empty list")
215 recursive_foreach(jobp, jobp["task.foreach"])
217 if "task.vwd" in jobp:
218 # Set output of the first task to the base vwd collection so it
219 # will be merged with output fragments from the other tasks by
221 arvados.current_task().set_output(subst.do_substitution(jobp, jobp["task.vwd"]))
223 arvados.current_task().set_output(None)
226 # This is the only task so taskp/jobp are the same
230 if "task.vwd" in taskp:
231 # Populate output directory with symlinks to files in collection
232 vwd.checkout(subst.do_substitution(taskp, taskp["task.vwd"]), outdir)
234 if "task.cwd" in taskp:
235 os.chdir(subst.do_substitution(taskp, taskp["task.cwd"]))
237 cmd = expand_list(taskp, taskp["command"])
240 if "task.stdin" in taskp:
241 stdinname = subst.do_substitution(taskp, taskp["task.stdin"])
242 stdinfile = open(stdinname, "rb")
244 if "task.stdout" in taskp:
245 stdoutname = subst.do_substitution(taskp, taskp["task.stdout"])
246 stdoutfile = open(stdoutname, "wb")
248 logger.info("{}{}{}".format(' '.join(cmd), (" < " + stdinname) if stdinname is not None else "", (" > " + stdoutname) if stdoutname is not None else ""))
252 except subst.SubstitutionError as e:
254 logger.error("task parameters were:")
255 logger.error(pprint.pformat(taskp))
257 except Exception as e:
258 logger.exception("caught exception")
259 logger.error("task parameters were:")
260 logger.error(pprint.pformat(taskp))
264 sp = subprocess.Popen(cmd, shell=False, stdin=stdinfile, stdout=stdoutfile)
267 # forward signals to the process.
268 signal.signal(signal.SIGINT, lambda signum, frame: sig.send_signal(sp, signum))
269 signal.signal(signal.SIGTERM, lambda signum, frame: sig.send_signal(sp, signum))
270 signal.signal(signal.SIGQUIT, lambda signum, frame: sig.send_signal(sp, signum))
272 # wait for process to complete.
275 if sig.sig is not None:
276 logger.critical("terminating on signal %s" % sig.sig)
279 logger.info("completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
281 except Exception as e:
282 logger.exception("caught exception")
284 # restore default signal handlers.
285 signal.signal(signal.SIGINT, signal.SIG_DFL)
286 signal.signal(signal.SIGTERM, signal.SIG_DFL)
287 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
292 logger.info("the following output files will be saved to keep:")
294 subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"], stdout=sys.stderr)
296 logger.info("start writing output to keep")
298 if "task.vwd" in taskp:
299 if "task.foreach" in jobp:
300 # This is a subtask, so don't merge with the original collection, that will happen at the end
301 outcollection = vwd.checkin(subst.do_substitution(taskp, taskp["task.vwd"]), outdir, merge=False).manifest_text()
303 # Just a single task, so do merge with the original collection
304 outcollection = vwd.checkin(subst.do_substitution(taskp, taskp["task.vwd"]), outdir, merge=True).manifest_text()
306 outcollection = robust_put.upload(outdir, logger)
308 api.job_tasks().update(uuid=arvados.current_task()['uuid'],
310 'output': outcollection,
311 'success': (rcode == 0),