-
Notifications
You must be signed in to change notification settings - Fork 24
/
testutils.py
183 lines (144 loc) · 5.03 KB
/
testutils.py
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
import logging
import re
import shlex
import subprocess as sp
import sys
import time
from itertools import chain
import psutil
import yaml
scripts = "../scripts"
if scripts not in sys.path:
sys.path.append(scripts)
import util # noqa: F401 E402
from util import backoff_delay, NSDict # noqa: F401 E402
log = logging.getLogger()
log.setLevel(logging.INFO)
def term_proc(proc):
try:
psproc = psutil.Process(proc.pid)
except psutil.NoSuchProcess:
log.debug(f"process with pid {proc.pid} doesn't exist")
return
for child in psproc.children(recursive=True):
child.terminate()
try:
child.wait(timeout=1)
except psutil.TimeoutExpired:
log.error(f"killing {child.pid}")
child.kill()
proc.terminate()
try:
proc.wait(timeout=1)
except sp.TimeoutExpired:
log.error(f"killing {proc.pid}")
proc.kill()
def run(
cmd,
wait=0,
quiet=False,
get_stdout=False,
shell=False,
universal_newlines=True,
**kwargs,
):
"""run in subprocess. Optional wait after return."""
if not quiet:
log.debug(f"run: {cmd}")
if get_stdout:
kwargs["stdout"] = sp.PIPE
args = cmd if shell else shlex.split(cmd)
ret = sp.run(args, shell=shell, universal_newlines=universal_newlines, **kwargs)
if wait:
time.sleep(wait)
return ret
def run_out(cmd, **kwargs):
kwargs["get_stdout"] = True
kwargs["universal_newlines"] = True
return run(cmd, **kwargs).stdout
def spawn(cmd, quiet=False, shell=False, **kwargs):
"""nonblocking spawn of subprocess"""
if not quiet:
log.debug(f"spawn: {cmd}")
kwargs["universal_newlines"] = True
args = cmd if shell else shlex.split(cmd)
return sp.Popen(args, shell=shell, **kwargs)
def wait_until(check, *args, max_wait=None):
if max_wait is None:
max_wait = 360
for wait in backoff_delay(1, timeout=max_wait):
if check(*args):
return True
time.sleep(wait)
return False
def wait_job_state(cluster, job_id, *states, max_wait=None):
states = set(states)
states_str = "{{ {} }}".format(", ".join(states))
def is_job_state():
state_arr = cluster.get_job(job_id)["job_state"]
log.info(f"job {job_id}: {state_arr} waiting for {states_str}")
return len(state_arr) == 1 and state_arr[0] in states
assert wait_until(is_job_state, max_wait=max_wait)
return cluster.get_job(job_id)
def wait_node_flags_subset(cluster, nodename, state, *flags, max_wait=None):
flags = set(flags)
flags_str = "+".join(chain([state], flags))
def check_node_flags():
info = cluster.get_node(nodename)
node_state, *node_flags = info["state"]
node_state = node_state.lower()
node_flags = set(node_flags)
log.info(
f"waiting for node {nodename} to be {flags_str}; state={node_state} flags={','.join(node_flags)}"
)
return node_state == state and (flags <= node_flags)
assert wait_until(check_node_flags, max_wait=max_wait)
return cluster.get_node(nodename)
def wait_node_flags_any(cluster, nodename, state, *flags, max_wait=None):
flags = set(flags)
flags_str = "{state}+{flags}".format(state=state, flags=" or ".join(flags))
def check_node_flags():
info = cluster.get_node(nodename)
node_state, *node_flags = info["state"]
node_state = node_state.lower()
node_flags = set(node_flags)
log.info(
f"waiting for node {nodename} to be {flags_str}; state={node_state} flags={','.join(node_flags)}"
)
return node_state == state and (flags & node_flags)
assert wait_until(check_node_flags, max_wait=max_wait)
return cluster.get_node(nodename)
def wait_node_state(cluster, nodename, *states, max_wait=None):
states = set(states)
states_str = "{{ {} }}".format(", ".join(states))
def is_node_state():
state, *flags = cluster.get_node(nodename)["state"]
state = state.lower()
log.info(f"node {nodename}: {state} waiting for {states_str}")
return state in states
assert wait_until(is_node_state, max_wait=max_wait)
return cluster.get_node(nodename)
# https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical
def all_equal(coll):
"""Return true if coll is empty or all elements are equal"""
it = iter(coll)
try:
first = next(it)
except StopIteration:
return True
return all(first == x for x in it)
batch_id = re.compile(r"^Submitted batch job (\d+)$")
def sbatch(cluster, cmd):
log.info(cmd)
submit = cluster.login_exec(cmd)
m = batch_id.match(submit.stdout)
if submit.exit_status or m is None:
raise Exception(f"job submit failed: {yaml.safe_dump(submit.to_dict())}")
assert m is not None
job_id = int(m[1])
return job_id
def get_zone(instance):
zone = yaml.safe_load(
run_out(f"gcloud compute instances describe {instance} --format=yaml(zone)")
)["zone"]
return zone