9 import crunchutil.subst as subst
11 import arvados.commands.put as put
17 import multiprocessing
19 import crunchutil.robust_put as robust_put
20 import crunchutil.vwd as vwd
23 logging.basicConfig(format="run-command: %(message)s")
25 t = arvados.current_task().tmpdir
27 api = arvados.api('v1')
29 os.chdir(arvados.current_task().tmpdir)
38 jobp = arvados.current_job()['script_parameters']
39 if len(arvados.current_task()['parameters']) > 0:
40 taskp = arvados.current_task()['parameters']
45 return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
51 return str(multiprocessing.cpu_count())
54 return os.environ['JOB_UUID']
57 return os.environ['TASK_UUID']
60 return os.environ['CRUNCH_SRC']
62 subst.default_subs["task.tmpdir"] = sub_tmpdir
63 subst.default_subs["task.outdir"] = sub_outdir
64 subst.default_subs["job.srcdir"] = sub_jobsrc
65 subst.default_subs["node.cores"] = sub_cores
66 subst.default_subs["job.uuid"] = sub_jobid
67 subst.default_subs["task.uuid"] = sub_taskid
69 class SigHandler(object):
73 def send_signal(self, sp, signum):
74 sp.send_signal(signum)
77 def expand_item(p, c):
78 if isinstance(c, dict):
79 if "foreach" in c and "command" in c:
81 items = get_items(p, p[var])
86 r.extend(expand_list(params, c["command"]))
88 elif isinstance(c, list):
89 return expand_list(p, c)
90 elif isinstance(c, str) or isinstance(c, unicode):
91 return [subst.do_substitution(p, c)]
95 def expand_list(p, l):
96 return [exp for arg in l for exp in expand_item(p, arg)]
98 def get_items(p, value):
99 if isinstance(value, list):
100 return expand_list(p, value)
102 fn = subst.do_substitution(p, value)
103 mode = os.stat(fn).st_mode
104 prefix = fn[len(os.environ['TASK_KEEPMOUNT'])+1:]
106 if stat.S_ISDIR(mode):
107 items = ["$(dir %s/%s/)" % (prefix, l) for l in os.listdir(fn)]
108 elif stat.S_ISREG(mode):
110 items = [line for line in f]
122 if "task.foreach" in jobp:
123 if arvados.current_task()['sequence'] == 0:
124 var = jobp["task.foreach"]
125 items = get_items(jobp, jobp[var])
126 logging.info("parallelizing on %s with items %s" % (var, items))
127 if items is not None:
129 params = copy.copy(jobp)
131 arvados.api().job_tasks().create(body={
132 'job_uuid': arvados.current_job()['uuid'],
133 'created_by_job_task_uuid': arvados.current_task()['uuid'],
138 if "task.vwd" in jobp:
139 # Base vwd collection will be merged with output fragments from
140 # the other tasks by crunch.
141 arvados.current_task().set_output(subst.do_substitution(jobp, jobp["task.vwd"]))
143 arvados.current_task().set_output(None)
150 if "task.vwd" in taskp:
151 # Populate output directory with symlinks to files in collection
152 vwd.checkout(subst.do_substitution(taskp, taskp["task.vwd"]), outdir)
154 if "task.cwd" in taskp:
155 os.chdir(subst.do_substitution(taskp, taskp["task.cwd"]))
157 cmd = expand_list(taskp, taskp["command"])
159 if "task.stdin" in taskp:
160 stdinname = subst.do_substitution(taskp, taskp["task.stdin"])
161 stdinfile = open(stdinname, "rb")
163 if "task.stdout" in taskp:
164 stdoutname = subst.do_substitution(taskp, taskp["task.stdout"])
165 stdoutfile = open(stdoutname, "wb")
167 logging.info("{}{}{}".format(' '.join(cmd), (" < " + stdinname) if stdinname is not None else ""), (" > " + stdoutname) if stdoutname is not None else ""))
169 except Exception as e:
170 logging.exception("caught exception")
171 logging.error("task parameters was:")
172 logging.error(pprint.pformat(taskp))
176 sp = subprocess.Popen(cmd, shell=False, stdin=stdinfile, stdout=stdoutfile)
179 # forward signals to the process.
180 signal.signal(signal.SIGINT, lambda signum, frame: sig.send_signal(sp, signum))
181 signal.signal(signal.SIGTERM, lambda signum, frame: sig.send_signal(sp, signum))
182 signal.signal(signal.SIGQUIT, lambda signum, frame: sig.send_signal(sp, signum))
184 # wait for process to complete.
187 if sig.sig is not None:
188 logging.critical("terminating on signal %s" % sig.sig)
191 logging.info("completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
193 except Exception as e:
194 logging.exception("caught exception")
196 # restore default signal handlers.
197 signal.signal(signal.SIGINT, signal.SIG_DFL)
198 signal.signal(signal.SIGTERM, signal.SIG_DFL)
199 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
204 logging.info("the following output files will be saved to keep:")
206 subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"], stdout=sys.stderr)
208 logging.info("start writing output to keep")
210 if "task.vwd" in taskp:
211 if "task.foreach" in jobp:
212 # This is a subtask, so don't merge with the original collection, that will happen at the end
213 outcollection = vwd.checkin(subst.do_substitution(taskp, taskp["task.vwd"]), outdir, merge=False).manifest_text()
215 # Just a single task, so do merge with the original collection
216 outcollection = vwd.checkin(subst.do_substitution(taskp, taskp["task.vwd"]), outdir, merge=True).manifest_text()
218 outcollection = robust_put.upload(outdir)
220 api.job_tasks().update(uuid=arvados.current_task()['uuid'],
222 'output': outcollection,
223 'success': (rcode == 0),