11 import arvados.commands.put as put
17 import multiprocessing
21 t = arvados.current_task().tmpdir
23 api = arvados.api('v1')
25 os.chdir(arvados.current_task().tmpdir)
34 jobp = arvados.current_job()['script_parameters']
35 if len(arvados.current_task()['parameters']) > 0:
36 p = arvados.current_task()['parameters']
41 r = os.path.join(outdir, os.path.basename(v))
47 return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
53 return str(multiprocessing.cpu_count())
56 return os.environ['JOB_UUID']
59 return os.environ['TASK_UUID']
62 return os.environ['CRUNCH_SRC']
64 subst.default_subs["link "] = sub_link
65 subst.default_subs["task.tmpdir"] = sub_tmpdir
66 subst.default_subs["task.outdir"] = sub_outdir
67 subst.default_subs["job.srcdir"] = sub_jobsrc
68 subst.default_subs["node.cores"] = sub_cores
69 subst.default_subs["job.uuid"] = sub_jobid
70 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]
128 if "task.foreach" in jobp:
129 if arvados.current_task()['sequence'] == 0:
130 var = jobp["task.foreach"]
131 items = get_items(jobp, jobp[var])
132 print("run-command: parallelizing on %s with items %s" % (var, items))
135 params = copy.copy(jobp)
137 arvados.api().job_tasks().create(body={
138 'job_uuid': arvados.current_job()['uuid'],
139 'created_by_job_task_uuid': arvados.current_task()['uuid'],
144 arvados.current_task().set_output(None)
151 cmd = expand_list(p, p["command"])
153 if "save.stdout" in p:
154 stdoutname = subst.do_substitution(p, p["save.stdout"])
155 stdoutfile = open(stdoutname, "wb")
157 print("run-command: {}{}".format(' '.join(cmd), (" > " + stdoutname) if stdoutname != None else ""))
159 except Exception as e:
160 print("run-command: caught exception:")
161 traceback.print_exc(file=sys.stdout)
162 print("run-command: task parameters was:")
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 print("run-command: terminating on signal %s" % sig.sig)
182 print("run-command: completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
184 except Exception as e:
185 print("run-command: caught exception:")
186 traceback.print_exc(file=sys.stdout)
188 # restore default signal handlers.
189 signal.signal(signal.SIGINT, signal.SIG_DFL)
190 signal.signal(signal.SIGTERM, signal.SIG_DFL)
191 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
196 print("run-command: the following output files will be saved to keep:")
198 subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"])
200 print("run-command: start writing output to keep")
203 resume_cache = put.ResumeCache(os.path.join(arvados.current_task().tmpdir, "upload-output-checkpoint"))
204 reporter = put.progress_writer(machine_progress)
205 bytes_expected = put.expected_bytes_for(".")
208 out = put.ArvPutCollectionWriter.from_cache(resume_cache, reporter, bytes_expected)
210 out.write_directory_tree(".", max_manifest_depth=0)
211 outuuid = out.finish()
212 api.job_tasks().update(uuid=arvados.current_task()['uuid'],
215 'success': (rcode == 0),
219 except KeyboardInterrupt:
220 print("run-command: terminating on signal 2")
222 except Exception as e:
223 print("run-command: caught exception:")
224 traceback.print_exc(file=sys.stdout)