forked from It4innovations/hyperqueue
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
381 lines (326 loc) · 12.4 KB
/
conftest.py
File metadata and controls
381 lines (326 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import contextlib
import json
import os
import signal
import subprocess
import time
from dataclasses import dataclass
from typing import Iterable, List, Optional, Tuple
import pytest
from .utils.mock import ProgramMock
from .utils.wait import wait_until
pytest.register_assert_rewrite("tests.utils.table")
from .utils import parse_tables # noqa: E402
PYTEST_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(PYTEST_DIR)
def get_hq_binary(debug=True):
directory = "debug" if debug else "release"
return os.path.join(ROOT_DIR, "target", directory, "hq")
RUNNING_IN_CI = "CI" in os.environ
@dataclass
class ManagedProcess:
name: str
process: subprocess.Popen
final_check: bool = True
class Env:
def __init__(self, work_path):
self.processes = []
self.work_path = work_path
def start_process(self, name, args, env=None, catch_io=True, cwd=None, final_check=True):
cwd = str(cwd or self.work_path)
logfile = (self.work_path / name).with_suffix(".out")
print(f"Starting process {name} with logfile {logfile}")
if catch_io:
with open(logfile, "w") as out:
p = subprocess.Popen(
args,
preexec_fn=os.setsid,
stdout=out,
stderr=subprocess.STDOUT,
cwd=cwd,
env=env,
)
else:
p = subprocess.Popen(args, cwd=cwd, env=env)
self.processes.append(ManagedProcess(name=name, process=p, final_check=final_check))
return p
def check_process_exited(self, process: subprocess.Popen, expected_code=0):
def is_process_alive():
for p in self.processes:
if p.process is process:
if process.poll() is None:
return True
self.processes = [p for p in self.processes if p.process is not process]
if expected_code == "error":
assert process.returncode != 0
elif expected_code is not None:
assert process.returncode == expected_code
return False
raise Exception(f"Process with pid {process.pid} not found")
if isinstance(process, ManagedProcess):
process = process.process
wait_until(lambda: not is_process_alive())
def check_running_processes(self):
"""Checks that everything is still running"""
for p in self.processes:
if p.final_check and p.process.poll() is not None:
raise Exception("Process {0} crashed (log in {1}/{0}.out)".format(p.name, self.work_path))
def kill_all(self):
self.sort_processes_for_kill()
for p in self.processes:
# Kill the whole group since the process may spawn a child
if not p.process.poll():
try:
os.killpg(os.getpgid(p.process.pid), signal.SIGTERM)
except ProcessLookupError as e:
if p.final_check:
raise e
def get_processes_by_name(self, name: str) -> Iterable[Tuple[int, ManagedProcess]]:
for i, p in enumerate(self.processes):
if p.name == name:
yield i, p
def kill_process(self, name: str, signal: int = signal.SIGTERM) -> subprocess.Popen:
for i, p in self.get_processes_by_name(name):
del self.processes[i]
# Kill the whole group since the process may spawn a child
if p.process.returncode is None and not p.process.poll():
os.killpg(os.getpgid(p.process.pid), signal)
return p.process
else:
raise Exception("Process not found")
def sort_processes_for_kill(self):
pass
class HqEnv(Env):
def __init__(self, work_dir, mock: ProgramMock, debug=True):
Env.__init__(self, work_dir)
self.mock = mock
self.server = None
self.id_counter = 0
self.do_final_check = True
self.server_dir = ""
self.debug = debug
def no_final_check(self):
self.do_final_check = False
def make_default_env(self, log=True):
env = os.environ.copy()
if log:
env["RUST_LOG"] = "tako=trace,hyperqueue=trace"
env["RUST_BACKTRACE"] = "full"
env["HQ_TEST"] = "1"
self.mock.update_env(env)
return env
@staticmethod
def server_args(server_dir="hq-server", debug=True):
args = [
get_hq_binary(debug=debug),
"--colors",
"never",
"--server-dir",
server_dir,
]
if debug:
args.append("--debug")
args += ["server", "start"]
return args
def start_server(self, server_dir="hq-server", args=None, env=None) -> subprocess.Popen:
self.server_dir = os.path.join(self.work_path, server_dir)
environment = self.make_default_env()
if env:
environment.update(env)
server_args = self.server_args(self.server_dir, debug=self.debug)
if args:
server_args += args
process = self.start_process("server", server_args, env=environment)
time.sleep(0.2)
self.check_running_processes()
return process
def start_workers(self, count, **kwargs) -> List[subprocess.Popen]:
workers = []
for _ in range(count):
workers.append(self.start_worker(**kwargs))
return workers
def start_worker(
self,
*,
cpus="1",
env=None,
args=None,
set_hostname=True,
wait_for_start=True,
on_server_lost="stop",
server_dir=None,
work_dir: Optional[str] = None,
final_check: bool = True,
hostname=None,
expect_fail=None,
detect_resources: Optional[str] = None,
) -> Optional[subprocess.Popen]:
self.id_counter += 1
worker_id = self.id_counter
worker_env = self.make_default_env()
if work_dir is None:
work_dir = f"workdir{worker_id}"
if env:
worker_env.update(env)
worker_args = [
get_hq_binary(self.debug),
"--server-dir",
server_dir or self.server_dir,
"worker",
"start",
f"--work-dir={work_dir}",
f"--on-server-lost={on_server_lost}",
]
if detect_resources is None:
worker_args.append("--detect-resources=none")
else:
# Ignore resources on testing machine by default
worker_args.append(f"--detect-resources={detect_resources}")
if hostname is None:
hostname = f"worker{worker_id}"
if set_hostname:
worker_args += ["--hostname", hostname]
if cpus is not None:
worker_args += ["--cpus", str(cpus)]
if args:
worker_args += list(args)
if expect_fail is not None:
process = subprocess.Popen(
worker_args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=self.work_path,
)
stdout = process.communicate(timeout=5)[0].decode()
if process.returncode != 0:
if expect_fail not in stdout:
raise Exception(f"Command should failed with message '{expect_fail}' but got:\n{stdout}")
else:
return None
raise Exception("Worker process does not failed")
r = self.start_process(hostname, worker_args, final_check=final_check, env=worker_env)
if wait_for_start:
print(wait_for_start)
assert set_hostname
def wait_for_worker():
table = self.command(["worker", "list"], as_table=True)
print(table)
return hostname in table.get_column_value("Hostname")
wait_until(wait_for_worker)
return r
def stop_server(self, check_all_terminated=True):
self.command(["server", "stop"])
for _, p in self.get_processes_by_name("server"):
p.process.wait()
self.check_process_exited(p.process)
if check_all_terminated:
for p in self.processes:
self.check_process_exited(p.process, 1)
def kill_server(self):
self.kill_process("server")
def kill_worker(self, worker_id: int, signal: int = signal.SIGTERM, wait=True):
table = self.command(["worker", "info", str(worker_id)], as_table=True)
pid = table.get_row_value("Process pid")
process = self.find_process_by_pid(int(pid))
if process is None:
raise Exception(f"Worker {worker_id} not found")
process = self.kill_process(process.name, signal=signal)
if wait:
wait_until(lambda: process.poll() is not None)
def find_process_by_pid(self, pid: int) -> Optional[ManagedProcess]:
for p in self.processes:
if p.process.pid == pid:
return p
return None
def command(
self,
args,
as_table=False,
as_lines=False,
as_json=False,
cwd=None,
wait=True,
expect_fail=None,
stdin=None,
log=False,
ignore_stderr=False,
env=None,
use_server_dir=True,
cmd_prefix: Optional[List[str]] = None,
):
cmd_prefix = cmd_prefix if cmd_prefix is not None else []
if isinstance(args, str):
args = [args]
else:
args = list(args)
if isinstance(stdin, str):
stdin = stdin.encode()
final_args = cmd_prefix + [get_hq_binary(self.debug)]
if use_server_dir:
final_args += ["--server-dir", self.server_dir]
final_args += args
cwd = cwd or self.work_path
environment = self.make_default_env(log=log)
if env is not None:
environment.update(env)
stderr = subprocess.DEVNULL if ignore_stderr else subprocess.STDOUT
if not wait:
return subprocess.Popen(final_args, stderr=stderr, cwd=cwd, env=environment)
else:
process = subprocess.Popen(
final_args,
stdout=subprocess.PIPE,
stderr=stderr,
cwd=cwd,
env=environment,
stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
)
stdout = process.communicate(stdin)[0].decode()
if process.returncode != 0:
if expect_fail:
if expect_fail not in stdout:
raise Exception(f"Command should failed with message '{expect_fail}' but got:\n{stdout}")
else:
return
print(f"Process output: {stdout}")
raise Exception(f"Process failed with exit-code {process.returncode}\n\n{stdout}")
if expect_fail is not None:
raise Exception("Command should failed")
if as_table:
return parse_tables(stdout)
if as_lines:
return stdout.rstrip().split("\n")
if as_json:
try:
return json.loads(stdout)
except json.JSONDecodeError:
raise Exception(f"Cannot parse: '{stdout}' as json.")
return stdout
def final_check(self):
pass
def close(self):
pass
def sort_processes_for_kill(self):
# Kill server last to avoid workers ending too soon
self.processes.sort(key=lambda process: 1 if "server" in process.name else 0)
@pytest.fixture(autouse=False, scope="function")
def hq_env(tmp_path):
with run_hq_env(tmp_path) as env:
yield env
@contextlib.contextmanager
def run_hq_env(tmp_path, debug=True):
"""Fixture that allows to start HQ test environment"""
print("\nWorking dir", tmp_path)
os.chdir(tmp_path)
mock = ProgramMock(tmp_path.joinpath("mock"))
env = HqEnv(tmp_path, debug=debug, mock=mock)
yield env
try:
env.final_check()
env.check_running_processes()
finally:
env.close()
env.kill_all()
# Final sleep to let server port be freed, on some slow computers
# a new test is starter before the old server is properly cleaned
time.sleep(0.02)