11 import arvados.commands.put as put
20 t = arvados.current_task().tmpdir
22 api = arvados.api('v1')
24 os.chdir(arvados.current_task().tmpdir)
31 jobp = arvados.current_job()['script_parameters']
32 if len(arvados.current_task()['parameters']) > 0:
33 p = arvados.current_task()['parameters']
38 r = os.path.basename(v)
39 os.symlink(os.path.join(os.environ['TASK_KEEPMOUNT'], v) , r)
44 return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
47 return os.environ['CRUNCH_NODE_SLOTS']
50 return os.environ['JOB_UUID']
53 return os.environ['TASK_UUID']
55 subst.default_subs["link "] = sub_link
56 subst.default_subs["task.tmpdir"] = sub_tmpdir
57 subst.default_subs["node.cores"] = sub_cores
58 subst.default_subs["job.id"] = sub_jobid
59 subst.default_subs["task.id"] = sub_taskid
63 def machine_progress(bytes_written, bytes_expected):
64 return "run-command: wrote {} total {}\n".format(
65 bytes_written, -1 if (bytes_expected is None) else bytes_expected)
67 class SigHandler(object):
71 def send_signal(self, sp, signum):
72 sp.send_signal(signum)
75 def expand_item(p, c):
76 if isinstance(c, dict):
77 if "foreach" in c and "command" in c:
79 items = get_items(p, p[var])
84 r.extend(expand_list(params, c["command"]))
86 elif isinstance(c, list):
87 return expand_list(p, c)
88 elif isinstance(c, str):
89 return [subst.do_substitution(p, c)]
93 def expand_list(p, l):
94 return [exp for arg in l for exp in expand_item(p, arg)]
96 def get_items(p, value):
97 if isinstance(value, list):
98 return expand_list(p, value)
100 fn = subst.do_substitution(p, value)
101 mode = os.stat(fn).st_mode
102 prefix = fn[len(os.environ['TASK_KEEPMOUNT'])+1:]
104 if stat.S_ISDIR(mode):
105 items = ["$(dir %s/%s/)" % (prefix, l) for l in os.listdir(fn)]
106 elif stat.S_ISREG(mode):
108 items = [line for line in f]
117 if "task.foreach" in jobp:
118 if arvados.current_task()['sequence'] == 0:
119 var = jobp["task.foreach"]
120 items = get_items(jobp, jobp[var])
121 print("run-command: parallelizing on %s with items %s" % (var, items))
124 params = copy.copy(jobp)
126 arvados.api().job_tasks().create(body={
127 'job_uuid': arvados.current_job()['uuid'],
128 'created_by_job_task_uuid': arvados.current_task()['uuid'],
133 arvados.current_task().set_output(None)
140 cmd = expand_list(p, p["command"])
142 if "save.stdout" in p:
143 stdoutname = subst.do_substitution(p, p["save.stdout"])
144 stdoutfile = open(stdoutname, "wb")
146 print("run-command: {}{}".format(' '.join(cmd), (" > " + stdoutname) if stdoutname != None else ""))
148 except Exception as e:
149 print("run-command: caught exception:")
150 traceback.print_exc(file=sys.stdout)
151 print("run-command: task parameters was:")
156 sp = subprocess.Popen(cmd, shell=False, stdout=stdoutfile)
159 # forward signals to the process.
160 signal.signal(signal.SIGINT, lambda signum, frame: sig.send_signal(sp, signum))
161 signal.signal(signal.SIGTERM, lambda signum, frame: sig.send_signal(sp, signum))
162 signal.signal(signal.SIGQUIT, lambda signum, frame: sig.send_signal(sp, signum))
164 # wait for process to complete.
168 print("run-command: terminating on signal %s" % sig.sig)
171 print("run-command: completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
173 except Exception as e:
174 print("run-command: caught exception:")
175 traceback.print_exc(file=sys.stdout)
177 # restore default signal handlers.
178 signal.signal(signal.SIGINT, signal.SIG_DFL)
179 signal.signal(signal.SIGTERM, signal.SIG_DFL)
180 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
185 print("run-command: the following output files will be saved to keep:")
187 subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"])
189 print("run-command: start writing output to keep")
192 resume_cache = put.ResumeCache(os.path.join(arvados.current_task().tmpdir, "upload-output-checkpoint"))
193 reporter = put.progress_writer(machine_progress)
194 bytes_expected = put.expected_bytes_for(".")
197 out = put.ArvPutCollectionWriter.from_cache(resume_cache, reporter, bytes_expected)
199 out.write_directory_tree(".", max_manifest_depth=0)
200 outuuid = out.finish()
201 api.job_tasks().update(uuid=arvados.current_task()['uuid'],
204 'success': (rcode == 0),
208 except KeyboardInterrupt:
209 print("run-command: terminating on signal 2")
211 except Exception as e:
212 print("run-command: caught exception:")
213 traceback.print_exc(file=sys.stdout)