71a9f963affdfed0efa4241accad45a78725d1c9
[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
14 os.umask(0077)
15
16 t = arvados.current_task().tmpdir
17
18 api = arvados.api('v1')
19
20 os.chdir(arvados.current_task().tmpdir)
21 os.mkdir("tmpdir")
22 os.mkdir("output")
23
24 os.chdir("output")
25
26 if len(arvados.current_task()['parameters']) > 0:
27     p = arvados.current_task()['parameters']
28 else:
29     p = arvados.current_job()['script_parameters']
30
31 links = []
32
33 def sub_link(v):
34     r = os.path.basename(v)
35     os.symlink(os.path.join(os.environ['TASK_KEEPMOUNT'], v) , r)
36     links.append(r)
37     return r
38
39 def sub_tmpdir(v):
40     return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
41
42 def sub_cores(v):
43      return os.environ['CRUNCH_NODE_SLOTS']
44
45 subst.default_subs["link "] = sub_link
46 subst.default_subs["tmpdir"] = sub_tmpdir
47 subst.default_subs["node.cores"] = sub_cores
48
49 rcode = 1
50
51 def machine_progress(bytes_written, bytes_expected):
52     return "run-command: {} written {} total\n".format(
53         bytes_written, -1 if (bytes_expected is None) else bytes_expected)
54
55 class SigHandler(object):
56     def __init__(self):
57         self.sig = None
58
59     def send_signal(self, sp, signum, sig):
60         sp.send_signal(signum)
61         self.sig = signum
62
63 try:
64     cmd = []
65     for c in p["command"]:
66         cmd.append(subst.do_substitution(p, c))
67
68     stdoutname = None
69     stdoutfile = None
70     if "stdout" in p:
71         stdoutname = subst.do_substitution(p, p["stdout"])
72         stdoutfile = open(stdoutname, "wb")
73
74     print("run-command: {}{}".format(' '.join(cmd), (" > " + stdoutname) if stdoutname != None else ""))
75
76     sp = subprocess.Popen(cmd, shell=False, stdout=stdoutfile)
77     sig = SigHandler()
78
79     # forward signals to the process.
80     signal.signal(signal.SIGINT, lambda signum, frame: sig.send_signal(sp, signum))
81     signal.signal(signal.SIGTERM, lambda signum, frame: sig.send_signal(sp, signum))
82     signal.signal(signal.SIGQUIT, lambda signum, frame: sig.send_signal(sp, signum))
83
84     # wait for process to complete.
85     rcode = sp.wait()
86
87     print("sig is %s" % sig.sig)
88
89     if len(sig) > 0:
90         print("run-command: terminating on signal %s" % sig[0])
91         sys.exit(rcode)
92     else:
93         print("run-command: completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
94
95 except Exception as e:
96     print("run-command: caught exception: {}".format(e))
97
98 finally:
99     # restore default signal handlers.
100     signal.signal(signal.SIGINT, signal.SIG_DFL)
101     signal.signal(signal.SIGTERM, signal.SIG_DFL)
102     signal.signal(signal.SIGQUIT, signal.SIG_DFL)
103
104     for l in links:
105         os.unlink(l)
106
107     print("run-command: the follow output files will be saved to keep:")
108
109     subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"])
110
111     print("run-command: start writing output to keep")
112
113     done = False
114     resume_cache = put.ResumeCache(os.path.join(arvados.current_task().tmpdir, "upload-output-checkpoint"))
115     reporter = put.progress_writer(machine_progress)
116     bytes_expected = put.expected_bytes_for(".")
117     while not done:
118         try:
119             out = put.ArvPutCollectionWriter(resume_cache, reporter, bytes_expected)
120             out.do_queued_work()
121             out.write_directory_tree(".", max_manifest_depth=0)
122             outuuid = out.finish()
123             api.job_tasks().update(uuid=arvados.current_task()['uuid'],
124                                                  body={
125                                                      'output':outuuid,
126                                                      'success': (rcode == 0),
127                                                      'progress':1.0
128                                                  }).execute()
129             done = True
130         except KeyboardInterrupt:
131             print("run-command: terminating on signal SIGINT")
132             done = True
133         except Exception as e:
134             print("run-command: caught exception: {}".format(e))
135             time.sleep(5)
136
137 sys.exit(rcode)