11 import arvados.commands.put as put
17 import multiprocessing
21 logging.basicConfig(format="run-command: %(message)s")
23 t = arvados.current_task().tmpdir
25 api = arvados.api('v1')
27 os.chdir(arvados.current_task().tmpdir)
36 jobp = arvados.current_job()['script_parameters']
37 if len(arvados.current_task()['parameters']) > 0:
38 p = arvados.current_task()['parameters']
43 r = os.path.join(outdir, os.path.basename(v))
49 return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
55 return str(multiprocessing.cpu_count())
58 return os.environ['JOB_UUID']
61 return os.environ['TASK_UUID']
64 return os.environ['CRUNCH_SRC']
66 subst.default_subs["link "] = sub_link
67 subst.default_subs["task.tmpdir"] = sub_tmpdir
68 subst.default_subs["task.outdir"] = sub_outdir
69 subst.default_subs["job.srcdir"] = sub_jobsrc
70 subst.default_subs["node.cores"] = sub_cores
71 subst.default_subs["job.uuid"] = sub_jobid
72 subst.default_subs["task.uuid"] = sub_taskid
76 def machine_progress(bytes_written, bytes_expected):
77 return "run-command: wrote {} total {}\n".format(
78 bytes_written, -1 if (bytes_expected is None) else bytes_expected)
80 class SigHandler(object):
84 def send_signal(self, sp, signum):
85 sp.send_signal(signum)
88 def expand_item(p, c):
89 if isinstance(c, dict):
90 if "foreach" in c and "command" in c:
92 items = get_items(p, p[var])
97 r.extend(expand_list(params, c["command"]))
99 elif isinstance(c, list):
100 return expand_list(p, c)
101 elif isinstance(c, str) or isinstance(c, unicode):
102 return [subst.do_substitution(p, c)]
106 def expand_list(p, l):
107 return [exp for arg in l for exp in expand_item(p, arg)]
109 def get_items(p, value):
110 if isinstance(value, list):
111 return expand_list(p, value)
113 fn = subst.do_substitution(p, value)
114 mode = os.stat(fn).st_mode
115 prefix = fn[len(os.environ['TASK_KEEPMOUNT'])+1:]
117 if stat.S_ISDIR(mode):
118 items = ["$(dir %s/%s/)" % (prefix, l) for l in os.listdir(fn)]
119 elif stat.S_ISREG(mode):
121 items = [line for line in f]
130 if "task.foreach" in jobp:
131 if arvados.current_task()['sequence'] == 0:
132 var = jobp["task.foreach"]
133 items = get_items(jobp, jobp[var])
134 logging.info("run-command: parallelizing on %s with items %s" % (var, items))
137 params = copy.copy(jobp)
139 arvados.api().job_tasks().create(body={
140 'job_uuid': arvados.current_job()['uuid'],
141 'created_by_job_task_uuid': arvados.current_task()['uuid'],
146 arvados.current_task().set_output(None)
153 cmd = expand_list(p, p["command"])
155 if "save.stdout" in p:
156 stdoutname = subst.do_substitution(p, p["save.stdout"])
157 stdoutfile = open(stdoutname, "wb")
159 logging.info("run-command: {}{}".format(' '.join(cmd), (" > " + stdoutname) if stdoutname != None else ""))
161 except Exception as e:
162 logging.info("run-command: caught exception:")
163 traceback.print_exc(file=sys.stdout)
164 logging.info("run-command: task parameters was:")
165 pprint.plogging.info(p)
169 sp = subprocess.Popen(cmd, shell=False, stdout=stdoutfile)
172 # forward signals to the process.
173 signal.signal(signal.SIGINT, lambda signum, frame: sig.send_signal(sp, signum))
174 signal.signal(signal.SIGTERM, lambda signum, frame: sig.send_signal(sp, signum))
175 signal.signal(signal.SIGQUIT, lambda signum, frame: sig.send_signal(sp, signum))
177 # wait for process to complete.
181 logging.warning("run-command: terminating on signal %s" % sig.sig)
184 logging.info("run-command: completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
186 except Exception as e:
187 logging.error("run-command: caught exception:")
188 traceback.print_exc(file=sys.stdout)
190 # restore default signal handlers.
191 signal.signal(signal.SIGINT, signal.SIG_DFL)
192 signal.signal(signal.SIGTERM, signal.SIG_DFL)
193 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
198 logging.info("run-command: the following output files will be saved to keep:")
200 subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"])
202 logging.info("run-command: start writing output to keep")
205 resume_cache = put.ResumeCache(os.path.join(arvados.current_task().tmpdir, "upload-output-checkpoint"))
206 reporter = put.progress_writer(machine_progress)
207 bytes_expected = put.expected_bytes_for(".")
210 out = put.ArvPutCollectionWriter.from_cache(resume_cache, reporter, bytes_expected)
212 out.write_directory_tree(".", max_manifest_depth=0)
213 outuuid = out.finish()
214 api.job_tasks().update(uuid=arvados.current_task()['uuid'],
217 'success': (rcode == 0),
221 except KeyboardInterrupt:
222 logging.error("run-command: terminating on signal 2")
224 except Exception as e:
225 logging.error("run-command: caught exception:")
226 traceback.print_exc(file=sys.stdout)