Use resumable upload writing output in run-command
[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
13 os.umask(0077)
14
15 t = arvados.current_task().tmpdir
16
17 api = arvados.api('v1')
18
19 os.chdir(arvados.current_task().tmpdir)
20 os.mkdir("tmpdir")
21 os.mkdir("output")
22
23 os.chdir("output")
24
25 if len(arvados.current_task()['parameters']) > 0:
26     p = arvados.current_task()['parameters']
27 else:
28     p = arvados.current_job()['script_parameters']
29
30 links = []
31
32 def sub_link(v):
33     r = os.path.basename(v)
34     os.symlink(os.path.join(os.environ['TASK_KEEPMOUNT'], v) , r)
35     links.append(r)
36     return r
37
38 def sub_tmpdir(v):
39     return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
40
41 def sub_cores(v):
42      return os.environ['CRUNCH_NODE_SLOTS']
43
44 subst.default_subs["link "] = sub_link
45 subst.default_subs["tmpdir"] = sub_tmpdir
46 subst.default_subs["node.cores"] = sub_cores
47
48 rcode = 1
49
50 def machine_progress(bytes_written, bytes_expected):
51     return "run-command: {} written {} total\n".format(
52         bytes_written, -1 if (bytes_expected is None) else bytes_expected)
53
54 try:
55     cmd = []
56     for c in p["command"]:
57         cmd.append(subst.do_substitution(p, c))
58
59     stdoutname = None
60     stdoutfile = None
61     if "stdout" in p:
62         stdoutname = subst.do_substitution(p, p["stdout"])
63         stdoutfile = open(stdoutname, "wb")
64
65     print("run-command: {}{}".format(' '.join(cmd), (" > " + stdoutname) if stdoutname != None else ""))
66
67     rcode = subprocess.call(cmd, stdout=stdoutfile)
68
69     print("run-command: completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
70
71 except Exception as e:
72     print("run-command: caught exception: {}".format(e))
73
74 finally:
75     for l in links:
76         os.unlink(l)
77
78     print("run-command: the follow output files will be saved to keep:")
79
80     subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"])
81
82     print("run-command: start writing output to keep")
83
84     done = False
85     resume_cache = put.ResumeCache(os.path.join(arvados.current_task().tmpdir, "upload-output-checkpoint"))
86     reporter = put.progress_writer(machine_progress)
87     bytes_expected = put.expected_bytes_for(".")
88     while not done:
89         try:
90             out = put.ArvPutCollectionWriter(resume_cache, reporter, bytes_expected)
91             out.do_queued_work()
92             out.write_directory_tree(".", max_manifest_depth=0)
93             outuuid = out.finish()
94             api.job_tasks().update(uuid=arvados.current_task()['uuid'],
95                                                  body={
96                                                      'output':outuuid,
97                                                      'success': (rcode == 0),
98                                                      'progress':1.0
99                                                  }).execute()
100             done = True
101         except Exception as e:
102             print("run-command: caught exception: {}".format(e))
103             time.sleep(5)
104
105 sys.exit(rcode)