Debian Codegraph @

js/src/tests/lib/tasks_unix.py

raw
1 # A unix-oriented process dispatcher. Uses a single thread with select and
2 # waitpid to dispatch tasks. This avoids several deadlocks that are possible
3 # with fork/exec + threads + Python.
4
5 import errno
6 import os
7 import select
8 import signal
9 import sys
10 from datetime import datetime, timedelta
11
12 from .adaptor import xdr_annotate
13 from .progressbar import ProgressBar
14 from .results import NullTestOutput, TestOutput, escape_cmdline
15
16
17 class Task:
18 def __init__(self, test, prefix, tempdir, pid, stdout, stderr):
19 self.test = test
20 self.cmd = test.get_command(prefix, tempdir)
21 self.pid = pid
22 self.stdout = stdout
23 self.stderr = stderr
24 self.start = datetime.now()
25 self.out = []
26 self.err = []
27
28
29 def spawn_test(test, prefix, tempdir, passthrough, run_skipped, show_cmd):
30 """Spawn one child, return a task struct."""
31 if not test.enable and not run_skipped:
32 return None
33
34 cmd = test.get_command(prefix, tempdir)
35 if show_cmd:
36 print(escape_cmdline(cmd))
37
38 if passthrough:
39 os.execvp(cmd[0], cmd)
40 return
41
42 (rout, wout) = os.pipe()
43 (rerr, werr) = os.pipe()
44
45 file_actions = [
46 (os.POSIX_SPAWN_CLOSE, rout),
47 (os.POSIX_SPAWN_CLOSE, rerr),
48 (os.POSIX_SPAWN_DUP2, wout, 1),
49 (os.POSIX_SPAWN_DUP2, werr, 2),
50 ]
51 pid = os.posix_spawnp(cmd[0], cmd, os.environ, file_actions=file_actions)
52
53 os.close(wout)
54 os.close(werr)
55 return Task(test, prefix, tempdir, pid, rout, rerr)
56
57
58 def get_max_wait(tasks, timeout):
59 """
60 Return the maximum time we can wait before any task should time out.
61 """
62
63 # If we have a progress-meter, we need to wake up to update it frequently.
64 wait = ProgressBar.update_granularity()
65
66 # If a timeout is supplied, we need to wake up for the first task to
67 # timeout if that is sooner.
68 if timeout:
69 now = datetime.now()
70 timeout_delta = timedelta(seconds=timeout)
71 for task in tasks:
72 remaining = task.start + timeout_delta - now
73 if remaining < wait:
74 wait = remaining
75
76 # Return the wait time in seconds, clamped between zero and max_wait.
77 return max(wait.total_seconds(), 0)
78
79
80 def flush_input(fd, frags):
81 """
82 Read any pages sitting in the file descriptor 'fd' into the list 'frags'.
83 """
84 rv = os.read(fd, 4096)
85 frags.append(rv)
86 while len(rv) == 4096:
87 # If read() returns a full buffer, it may indicate there was 1 buffer
88 # worth of data, or that there is more data to read. Poll the socket
89 # before we read again to ensure that we will not block indefinitly.
90 readable, _, _ = select.select([fd], [], [], 0)
91 if not readable:
92 return
93
94 rv = os.read(fd, 4096)
95 frags.append(rv)
96
97
98 def read_input(tasks, timeout):
99 """
100 Select on input or errors from the given task list for a max of timeout
101 seconds.
102 """
103 rlist = []
104 exlist = []
105 outmap = {} # Fast access to fragment list given fd.
106 for t in tasks:
107 rlist.append(t.stdout)
108 rlist.append(t.stderr)
109 outmap[t.stdout] = t.out
110 outmap[t.stderr] = t.err
111 # This will trigger with a close event when the child dies, allowing
112 # us to respond immediately and not leave cores idle.
113 exlist.append(t.stdout)
114
115 readable = []
116 try:
117 readable, _, _ = select.select(rlist, [], exlist, timeout)
118 except OverflowError:
119 print >> sys.stderr, "timeout value", timeout
120 raise
121
122 for fd in readable:
123 flush_input(fd, outmap[fd])
124
125
126 def remove_task(tasks, pid):
127 """
128 Remove a task from the tasks list and return it.
129 """
130 index = None
131 for i, t in enumerate(tasks):
132 if t.pid == pid:
133 index = i
134 break
135 else:
136 raise KeyError(f"No such pid: {pid}")
137
138 out = tasks[index]
139 tasks.pop(index)
140 return out
141
142
143 def timed_out(task, timeout):
144 """
145 Return a timedelta with the amount we are overdue, or False if the timeout
146 has not yet been reached (or timeout is falsy, indicating there is no
147 timeout.)
148 """
149 if not timeout:
150 return False
151
152 elapsed = datetime.now() - task.start
153 over = elapsed - timedelta(seconds=timeout)
154 return over if over.total_seconds() > 0 else False
155
156
157 def reap_zombies(tasks, timeout):
158 """
159 Search for children of this process that have finished. If they are tasks,
160 then this routine will clean up the child. This method returns a new task
161 list that has had the ended tasks removed, followed by the list of finished
162 tasks.
163 """
164 finished = []
165 while True:
166 try:
167 pid, status = os.waitpid(0, os.WNOHANG)
168 if pid == 0:
169 break
170 except OSError as e:
171 if e.errno == errno.ECHILD:
172 break
173 raise e
174
175 ended = remove_task(tasks, pid)
176 flush_input(ended.stdout, ended.out)
177 flush_input(ended.stderr, ended.err)
178 os.close(ended.stdout)
179 os.close(ended.stderr)
180
181 returncode = os.WEXITSTATUS(status)
182 if os.WIFSIGNALED(status):
183 returncode = -os.WTERMSIG(status)
184
185 finished.append(
186 TestOutput(
187 ended.test,
188 ended.cmd,
189 b"".join(ended.out).decode("utf-8", "replace"),
190 b"".join(ended.err).decode("utf-8", "replace"),
191 returncode,
192 (datetime.now() - ended.start).total_seconds(),
193 timed_out(ended, timeout),
194 {"pid": ended.pid},
195 )
196 )
197 return tasks, finished
198
199
200 def kill_undead(tasks, timeout):
201 """
202 Signal all children that are over the given timeout. Use SIGABRT first to
203 generate a stack dump. If it still doesn't die for another 30 seconds, kill
204 with SIGKILL.
205 """
206 for task in tasks:
207 over = timed_out(task, timeout)
208 if over:
209 if over.total_seconds() < 30:
210 os.kill(task.pid, signal.SIGABRT)
211 else:
212 os.kill(task.pid, signal.SIGKILL)
213
214
215 def run_all_tests(tests, prefix, tempdir, pb, options):
216 # Copy and reverse for fast pop off end.
217 tests = list(tests)
218 tests = tests[:]
219 tests.reverse()
220
221 # The set of currently running tests.
222 tasks = []
223
224 # Piggy back on the first test to generate the XDR content needed for all
225 # other tests to run. To avoid read/write races, we temporarily limit the
226 # number of workers.
227 wait_for_encoding = False
228 worker_count = options.worker_count
229 if options.use_xdr and len(tests) > 1:
230 # The next loop pops tests, thus we iterate over the tests in reversed
231 # order.
232 tests = list(xdr_annotate(reversed(tests), options))
233 tests = tests[:]
234 tests.reverse()
235 wait_for_encoding = True
236 worker_count = 1
237
238 def running_heavy_test():
239 return any(task.test.heavy for task in tasks)
240
241 heavy_tests = [t for t in tests if t.heavy]
242 light_tests = [t for t in tests if not t.heavy]
243
244 encoding_test = None
245 while light_tests or heavy_tests or tasks:
246 new_tests = []
247 max_new_tests = worker_count - len(tasks)
248 if (
249 heavy_tests
250 and not running_heavy_test()
251 and len(new_tests) < max_new_tests
252 and not wait_for_encoding
253 ):
254 # Schedule a heavy test if available.
255 new_tests.append(heavy_tests.pop())
256 while light_tests and len(new_tests) < max_new_tests:
257 # Schedule as many more light tests as we can.
258 new_tests.append(light_tests.pop())
259
260 assert len(tasks) + len(new_tests) <= worker_count
261 assert len([x for x in new_tests if x.heavy]) <= 1
262
263 for test in new_tests:
264 task = spawn_test(
265 test,
266 prefix,
267 tempdir,
268 options.passthrough,
269 options.run_skipped,
270 options.show_cmd,
271 )
272 if task:
273 tasks.append(task)
274 if not encoding_test:
275 encoding_test = test
276 else:
277 yield NullTestOutput(test)
278
279 timeout = get_max_wait(tasks, options.timeout)
280 read_input(tasks, timeout)
281
282 kill_undead(tasks, options.timeout)
283 tasks, finished = reap_zombies(tasks, options.timeout)
284
285 for out in finished:
286 yield out
287 if wait_for_encoding and out.test == encoding_test:
288 assert encoding_test.selfhosted_xdr_mode == "encode"
289 wait_for_encoding = False
290 worker_count = options.worker_count
291
292 # If we did not finish any tasks, poke the progress bar to show that
293 # the test harness is at least not frozen.
294 if len(finished) == 0:
295 pb.poke()