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