blob: 8791d2d1842646061d31e2293cf9014533286c81 [file] [log] [blame]
mblighb0fab822007-07-25 16:40:19 +00001__author__ = """Copyright Andy Whitcroft, Martin J. Bligh - 2006, 2007"""
2
3import sys, os, subprocess
4
5
6def parallel(tasklist):
7 """Run an set of predefined subcommands in parallel"""
8 pids = []
9 error = False
10 for task in tasklist:
11 task.fork_start()
12 for task in tasklist:
13 status = task.fork_waitfor()
14 if status != 0:
15 error = True
16 if error:
17 raise "One or more subcommands failed"
18
19
20def parallel_simple(function, arglist):
21 """Each element in the arglist used to create a subcommand object,
22 where that arg is used both as a subdir name, and a single argument
23 to pass to "function".
24 We create a subcommand object for each element in the list,
25 then execute those subcommand objects in parallel."""
26 subcommands = []
27 for arg in arglist:
mbligh0c9e7822007-07-25 22:47:51 +000028 args = [arg]
29 subdir = str(arg)
30 subcommands.append(subcommand(function, args, subdir))
mblighb0fab822007-07-25 16:40:19 +000031 parallel(subcommands)
32
33
34def __where_art_thy_filehandles():
35 os.system("ls -l /proc/%d/fd >> /dev/tty" % os.getpid())
36
mblighdc735a22007-08-02 16:54:37 +000037
mblighb0fab822007-07-25 16:40:19 +000038def __print_to_tty(string):
39 open('/dev/tty', 'w').write(string + '\n')
40
41
42def __redirect_stream(fd, output):
43 newfd = os.open(output, os.O_WRONLY | os.O_CREAT)
44 os.dup2(newfd, fd)
45 os.close(newfd)
46 if fd == 1:
47 sys.stdout = os.fdopen(fd, 'w')
48 if fd == 2:
49 sys.stderr = os.fdopen(fd, 'w')
50
51
52def _redirect_stream_tee(fd, output, tag):
53 """Use the low-level fork & pipe operations here to get a fd,
54 not a filehandle. This ensures that we get both the
55 filehandle and fd for stdout/stderr redirected correctly."""
56 r, w = os.pipe()
57 pid = os.fork()
58 if pid: # Parent
59 os.dup2(w, fd)
60 os.close(r)
61 os.close(w)
62 if fd == 1:
63 sys.stdout = os.fdopen(fd, 'w', 1)
64 if fd == 2:
65 sys.stderr = os.fdopen(fd, 'w', 1)
66 return
67 else: # Child
68 os.close(w)
69 log = open(output, 'w')
70 f = os.fdopen(r, 'r')
71 for line in iter(f.readline, ''):
72 # Tee straight to file
73 log.write(line)
74 log.flush()
75 # Prepend stdout with the tag
76 print tag + ' : ' + line,
77 sys.stdout.flush()
78 log.close()
79 os._exit(0)
80
81
82class subcommand:
83 def __init__(self, func, args, subdir, tee=True):
84 # func(args) - the subcommand to run
85 # subdir - the subdirectory to log results in
86 self.subdir = os.path.abspath(subdir)
87 if os.path.exists(self.subdir):
88 os.system("rm -rf %s" % self.subdir)
89 os.mkdir(self.subdir)
90 self.debug = os.path.join(self.subdir, 'debug')
91 self.stdout = os.path.join(self.debug, 'stdout')
92 self.stderr = os.path.join(self.debug, 'stderr')
93 os.mkdir(self.debug)
94 self.func = func
95 self.args = args
96 self.lambda_function = lambda: func(*args)
97 self.pid = None
98 self.tee = tee
99
100
101 def redirect_output(self):
102 tag = os.path.basename(self.subdir)
103 _redirect_stream_tee(1, self.stdout, tag)
104 _redirect_stream_tee(2, self.stderr, tag)
105
106
107 def fork_start(self):
108 sys.stdout.flush()
109 sys.stderr.flush()
110 self.pid = os.fork()
111
112 if self.pid: # I am the parent
113 return
114
115 # We are the child from this point on. Never return.
116 os.chdir(self.subdir)
117 self.redirect_output()
118
119 try:
120 self.lambda_function()
121
122 except:
123 raise
124 sys.stdout.flush()
125 sys.stderr.flush()
126 os._exit(1)
127
128 sys.stdout.flush()
129 sys.stderr.flush()
130 os._exit(0)
131
132
133 def fork_waitfor(self):
134 (pid, status) = os.waitpid(self.pid, 0)
135
136 if status != 0:
137 print "subcommand failed pid %d" % pid
138 print "%s(%s)" % (self.func, self.args)
139 print "rc=%d" % status
140 print
141 if os.path.exists(self.stderr):
142 for line in open(self.stderr).readlines():
143 print line,
144 print "\n--------------------------------------------\n"
145 return status