Print traceback on exception
[arvados.git] / crunch_scripts / run-command
1 #!/usr/bin/env python
2
3 import arvados
4 import re
5 import os
6 import subprocess
7 import sys
8 import shutil
9 import subst
10 import time
11 import arvados.commands.put as put
12 import signal
13 import stat
14 import copy
15 import traceback
16
17 os.umask(0077)
18
19 t = arvados.current_task().tmpdir
20
21 api = arvados.api('v1')
22
23 os.chdir(arvados.current_task().tmpdir)
24 os.mkdir("tmpdir")
25 os.mkdir("output")
26
27 os.chdir("output")
28
29 taskp = None
30 jobp = arvados.current_job()['script_parameters']
31 if len(arvados.current_task()['parameters']) > 0:
32     p = arvados.current_task()['parameters']
33
34 links = []
35
36 def sub_link(v):
37     r = os.path.basename(v)
38     os.symlink(os.path.join(os.environ['TASK_KEEPMOUNT'], v) , r)
39     links.append(r)
40     return r
41
42 def sub_tmpdir(v):
43     return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
44
45 def sub_cores(v):
46      return os.environ['CRUNCH_NODE_SLOTS']
47
48 def sub_jobid(v):
49      return os.environ['JOB_UUID']
50
51 def sub_taskid(v):
52      return os.environ['TASK_UUID']
53
54 subst.default_subs["link "] = sub_link
55 subst.default_subs["task.tmpdir"] = sub_tmpdir
56 subst.default_subs["node.cores"] = sub_cores
57 subst.default_subs["job.id"] = sub_jobid
58 subst.default_subs["task.id"] = sub_taskid
59
60 rcode = 1
61
62 def machine_progress(bytes_written, bytes_expected):
63     return "run-command: wrote {} total {}\n".format(
64         bytes_written, -1 if (bytes_expected is None) else bytes_expected)
65
66 class SigHandler(object):
67     def __init__(self):
68         self.sig = None
69
70     def send_signal(self, sp, signum):
71         sp.send_signal(signum)
72         self.sig = signum
73
74 def expand_item(p, c):
75     if isinstance(c, dict):
76         if "foreach" in c and "command" in c:
77             var = c["foreach"]
78             items = get_items(p, p[var])
79             r = []
80             for i in items:
81                 params = copy.copy(p)
82                 params[var] = i
83                 r.extend(expand_list(params, c["command"]))
84             return r
85     elif isinstance(c, list):
86         return expand_list(p, c)
87     elif isinstance(c, str):
88         return [subst.do_substitution(p, c)]
89
90     return []
91
92 def expand_list(p, l):
93     return [exp for arg in l for exp in expand_item(p, arg)]
94
95 def get_items(p, value):
96     if isinstance(value, list):
97         return expand_list(p, value)
98
99     fn = subst.do_substitution(p, value)
100     mode = os.stat(fn).st_mode
101     prefix = fn[len(os.environ['TASK_KEEPMOUNT'])+1:]
102     if mode != None:
103         if stat.S_ISDIR(mode):
104             items = ["$(dir %s/%s)" % (prefix, l) for l in os.listdir(fn)]
105         elif stat.S_ISREG(mode):
106             with open(fn) as f:
107                 items = [line for line in f]
108         return items
109     else:
110         return None
111
112 if "task.foreach" in jobp:
113     if arvados.current_task()['sequence'] == 0:
114         var = jobp["task.foreach"]
115         items = get_items(jobp, jobp[var])
116         if items != None:
117             print("run-command: parallelizing on %s with items %s" % (var, items))
118
119             for i in items:
120                 params = copy.copy(jobp)
121                 params[var] = i
122                 arvados.api().job_tasks().create(body={
123                     'job_uuid': arvados.current_job()['uuid'],
124                     'created_by_job_task_uuid': arvados.current_task()['uuid'],
125                     'sequence': 1,
126                     'parameters': params
127                     }
128                 ).execute()
129             arvados.current_task().set_output(None)
130             sys.exit(0)
131         else:
132             sys.exit(1)
133 else:
134     p = jobp
135
136 try:
137     cmd = expand_list(p, p["command"])
138
139     stdoutname = None
140     stdoutfile = None
141     if "save.stdout" in p:
142         stdoutname = subst.do_substitution(p, p["save.stdout"])
143         stdoutfile = open(stdoutname, "wb")
144
145     print("run-command: {}{}".format(' '.join(cmd), (" > " + stdoutname) if stdoutname != None else ""))
146
147     sp = subprocess.Popen(cmd, shell=False, stdout=stdoutfile)
148     sig = SigHandler()
149
150     # forward signals to the process.
151     signal.signal(signal.SIGINT, lambda signum, frame: sig.send_signal(sp, signum))
152     signal.signal(signal.SIGTERM, lambda signum, frame: sig.send_signal(sp, signum))
153     signal.signal(signal.SIGQUIT, lambda signum, frame: sig.send_signal(sp, signum))
154
155     # wait for process to complete.
156     rcode = sp.wait()
157
158     if sig.sig != None:
159         print("run-command: terminating on signal %s" % sig.sig)
160         sys.exit(2)
161     else:
162         print("run-command: completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
163
164 except Exception as e:
165     print("run-command: caught exception:")
166     traceback.print_exc(file=sys.stdout)
167
168 # restore default signal handlers.
169 signal.signal(signal.SIGINT, signal.SIG_DFL)
170 signal.signal(signal.SIGTERM, signal.SIG_DFL)
171 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
172
173 for l in links:
174     os.unlink(l)
175
176 print("run-command: the following output files will be saved to keep:")
177
178 subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"])
179
180 print("run-command: start writing output to keep")
181
182 done = False
183 resume_cache = put.ResumeCache(os.path.join(arvados.current_task().tmpdir, "upload-output-checkpoint"))
184 reporter = put.progress_writer(machine_progress)
185 bytes_expected = put.expected_bytes_for(".")
186 while not done:
187     try:
188         out = put.ArvPutCollectionWriter.from_cache(resume_cache, reporter, bytes_expected)
189         out.do_queued_work()
190         out.write_directory_tree(".", max_manifest_depth=0)
191         outuuid = out.finish()
192         api.job_tasks().update(uuid=arvados.current_task()['uuid'],
193                                              body={
194                                                  'output':outuuid,
195                                                  'success': (rcode == 0),
196                                                  'progress':1.0
197                                              }).execute()
198         done = True
199     except KeyboardInterrupt:
200         print("run-command: terminating on signal 2")
201         sys.exit(2)
202     except Exception as e:
203         print("run-command: caught exception:")
204         traceback.print_exc(file=sys.stdout)
205         time.sleep(5)
206
207 sys.exit(rcode)