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 taskp = 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
74 def machine_progress(bytes_written, bytes_expected):
75 return "run-command: wrote {} total {}\n".format(
76 bytes_written, -1 if (bytes_expected is None) else bytes_expected)
78 class SigHandler(object):
82 def send_signal(self, sp, signum):
83 sp.send_signal(signum)
86 def expand_item(p, c):
87 if isinstance(c, dict):
88 if "foreach" in c and "command" in c:
90 items = get_items(p, p[var])
95 r.extend(expand_list(params, c["command"]))
97 elif isinstance(c, list):
98 return expand_list(p, c)
99 elif isinstance(c, str) or isinstance(c, unicode):
100 return [subst.do_substitution(p, c)]
104 def expand_list(p, l):
105 return [exp for arg in l for exp in expand_item(p, arg)]
107 def get_items(p, value):
108 if isinstance(value, list):
109 return expand_list(p, value)
111 fn = subst.do_substitution(p, value)
112 mode = os.stat(fn).st_mode
113 prefix = fn[len(os.environ['TASK_KEEPMOUNT'])+1:]
115 if stat.S_ISDIR(mode):
116 items = ["$(dir %s/%s/)" % (prefix, l) for l in os.listdir(fn)]
117 elif stat.S_ISREG(mode):
119 items = [line for line in f]
129 if "task.foreach" in jobp:
130 if arvados.current_task()['sequence'] == 0:
131 var = jobp["task.foreach"]
132 items = get_items(jobp, jobp[var])
133 logging.info("parallelizing on %s with items %s" % (var, items))
136 params = copy.copy(jobp)
138 arvados.api().job_tasks().create(body={
139 'job_uuid': arvados.current_job()['uuid'],
140 'created_by_job_task_uuid': arvados.current_task()['uuid'],
145 arvados.current_task().set_output(None)
152 cmd = expand_list(taskp, taskp["command"])
154 if "save.stdout" in taskp:
155 stdoutname = subst.do_substitution(taskp, taskp["save.stdout"])
156 stdoutfile = open(stdoutname, "wb")
158 logging.info("{}{}".format(' '.join(cmd), (" > " + stdoutname) if stdoutname != None else ""))
160 except Exception as e:
161 logging.exception("caught exception")
162 logging.error("task parameters was:")
163 logging.error(pprint.pformat(taskp))
167 sp = subprocess.Popen(cmd, shell=False, stdout=stdoutfile)
170 # forward signals to the process.
171 signal.signal(signal.SIGINT, lambda signum, frame: sig.send_signal(sp, signum))
172 signal.signal(signal.SIGTERM, lambda signum, frame: sig.send_signal(sp, signum))
173 signal.signal(signal.SIGQUIT, lambda signum, frame: sig.send_signal(sp, signum))
175 # wait for process to complete.
179 logging.critical("terminating on signal %s" % sig.sig)
182 logging.info("completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
184 except Exception as e:
185 logging.exception("caught exception")
187 # restore default signal handlers.
188 signal.signal(signal.SIGINT, signal.SIG_DFL)
189 signal.signal(signal.SIGTERM, signal.SIG_DFL)
190 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
195 logging.info("the following output files will be saved to keep:")
197 subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"], stdout=sys.stderr)
199 logging.info("start writing output to keep")
202 resume_cache = put.ResumeCache(os.path.join(arvados.current_task().tmpdir, "upload-output-checkpoint"))
203 reporter = put.progress_writer(machine_progress)
204 bytes_expected = put.expected_bytes_for(".")
207 out = put.ArvPutCollectionWriter.from_cache(resume_cache, reporter, bytes_expected)
209 out.write_directory_tree(".", max_manifest_depth=0)
210 outuuid = out.finish()
211 api.job_tasks().update(uuid=arvados.current_task()['uuid'],
214 'success': (rcode == 0),
218 except KeyboardInterrupt:
219 logging.critical("terminating on signal 2")
221 except Exception as e:
222 logging.exception("caught exception:")