-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
test.py
384 lines (333 loc) · 11.6 KB
/
test.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
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
382
383
384
import enum
import os
import json
import time
from typing import Optional, List, Dict
from dataclasses import dataclass
import boto3
from botocore.exceptions import ClientError
from github import Repository
from ray_release.configs.global_config import get_global_config
from ray_release.result import (
ResultStatus,
Result,
)
from ray_release.logger import logger
from ray_release.util import dict_hash
AWS_TEST_KEY = "ray_tests"
AWS_TEST_RESULT_KEY = "ray_test_results"
DEFAULT_PYTHON_VERSION = tuple(
int(v) for v in os.environ.get("RELEASE_PY", "3.8").split(".")
)
DATAPLANE_ECR_REPO = "anyscale/ray"
DATAPLANE_ECR_ML_REPO = "anyscale/ray-ml"
def _convert_env_list_to_dict(env_list: List[str]) -> Dict[str, str]:
env_dict = {}
for env in env_list:
# an env can be "a=b" or just "a"
eq_pos = env.find("=")
if eq_pos < 0:
env_dict[env] = os.environ.get(env, "")
else:
env_dict[env[:eq_pos]] = env[eq_pos + 1 :]
return env_dict
class TestState(enum.Enum):
"""
Overall state of the test
"""
JAILED = "jailed"
FAILING = "failing"
CONSITENTLY_FAILING = "consistently_failing"
PASSING = "passing"
@dataclass
class TestResult:
status: str
commit: str
url: str
timestamp: int
@classmethod
def from_result(cls, result: Result):
return cls(
status=result.status,
commit=os.environ.get("BUILDKITE_COMMIT", ""),
url=result.buildkite_url,
timestamp=int(time.time() * 1000),
)
@classmethod
def from_dict(cls, result: dict):
return cls(
status=result["status"],
commit=result["commit"],
url=result["url"],
timestamp=result["timestamp"],
)
def is_failing(self) -> bool:
return not self.is_passing()
def is_passing(self) -> bool:
return self.status == ResultStatus.SUCCESS.value
class Test(dict):
"""A class represents a test to run on buildkite"""
KEY_GITHUB_ISSUE_NUMBER = "github_issue_number"
KEY_BISECT_BUILD_NUMBER = "bisect_build_number"
KEY_BISECT_BLAMED_COMMIT = "bisect_blamed_commit"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.test_results = None
def is_jailed_with_open_issue(self, ray_github: Repository) -> bool:
"""
Returns whether this test is jailed with open issue.
"""
# is jailed
state = self.get_state()
if state != TestState.JAILED:
return False
# has open issue
issue_number = self.get(self.KEY_GITHUB_ISSUE_NUMBER)
if issue_number is None:
return False
issue = ray_github.get_issue(issue_number)
return issue.state == "open"
def is_stable(self) -> bool:
"""
Returns whether this test is stable.
"""
return self.get("stable", True)
def is_gce(self) -> bool:
"""
Returns whether this test is running on GCE.
"""
return self.get("env") == "gce"
def is_byod_cluster(self) -> bool:
"""
Returns whether this test is running on a BYOD cluster.
"""
return self["cluster"].get("byod") is not None
def get_byod_type(self) -> Optional[str]:
"""
Returns the type of the BYOD cluster.
"""
if not self.is_byod_cluster():
return None
return self["cluster"]["byod"].get("type", "cpu")
def get_byod_post_build_script(self) -> Optional[str]:
"""
Returns the post-build script for the BYOD cluster.
"""
if not self.is_byod_cluster():
return None
return self["cluster"]["byod"].get("post_build_script")
def get_byod_runtime_env(self) -> Dict[str, str]:
"""
Returns the runtime environment variables for the BYOD cluster.
"""
if not self.is_byod_cluster():
return {}
return _convert_env_list_to_dict(self["cluster"]["byod"].get("runtime_env", []))
def get_byod_pips(self) -> List[str]:
"""
Returns the list of pips for the BYOD cluster.
"""
if not self.is_byod_cluster():
return []
return self["cluster"]["byod"].get("pip", [])
def get_name(self) -> str:
"""
Returns the name of the test.
"""
return self["name"]
def get_oncall(self) -> str:
"""
Returns the oncall for the test.
"""
return self["team"]
def update_from_s3(self) -> None:
"""
Update test object with data field from s3
"""
try:
data = (
boto3.client("s3")
.get_object(
Bucket=get_global_config()["state_machine_aws_bucket"],
Key=f"{AWS_TEST_KEY}/{self.get_name()}.json",
)
.get("Body")
.read()
.decode("utf-8")
)
except ClientError as e:
logger.warning(f"Failed to update data for {self.get_name()} from s3: {e}")
return
self.update(json.loads(data))
def get_state(self) -> TestState:
"""
Returns the state of the test.
"""
return TestState(self.get("state", TestState.PASSING.value))
def set_state(self, state: TestState) -> None:
"""
Sets the state of the test.
"""
self["state"] = state.value
def get_python_version(self) -> str:
"""
Returns the python version to use for this test. If not specified, use
the default python version.
"""
return self.get("python", ".".join(str(v) for v in DEFAULT_PYTHON_VERSION))
def get_byod_base_image_tag(self) -> str:
"""
Returns the byod image tag to use for this test.
"""
byod_image_tag = os.environ.get("RAY_IMAGE_TAG")
if byod_image_tag:
# Use the image tag specified in the environment variable.
# TODO(can): this is a temporary backdoor that should be removed
# once civ2 is fully rolled out.
return byod_image_tag
commit = os.environ.get(
"COMMIT_TO_TEST",
os.environ["BUILDKITE_COMMIT"],
)
branch = os.environ.get(
"BRANCH_TO_TEST",
os.environ["BUILDKITE_BRANCH"],
)
pr = os.environ.get("BUILDKITE_PULL_REQUEST", "false")
assert (
pr != "false" or branch == "master" or branch.startswith("releases/")
), f"Invalid branch name {branch}"
ray_version = commit[:6]
if pr != "false":
ray_version = f"pr-{pr}.{ray_version}"
elif branch.startswith("releases/"):
release_name = branch[len("releases/") :]
ray_version = f"{release_name}.{ray_version}"
python_version = f"py{self.get_python_version().replace('.', '')}"
return f"{ray_version}-{python_version}-{self.get_byod_type()}"
def get_byod_image_tag(self) -> str:
"""
Returns the byod custom image tag to use for this test.
"""
if not self.require_custom_byod_image():
return self.get_byod_base_image_tag()
custom_info = {
"post_build_script": self.get_byod_post_build_script(),
}
return f"{self.get_byod_base_image_tag()}-{dict_hash(custom_info)}"
def use_byod_ml_image(self) -> bool:
"""Returns whether to use the ML image for this test."""
return self.get_byod_type() == "gpu"
def get_byod_repo(self) -> str:
"""
Returns the byod repo to use for this test.
"""
if self.use_byod_ml_image():
return DATAPLANE_ECR_ML_REPO
return DATAPLANE_ECR_REPO
def get_byod_ecr(self) -> str:
"""
Returns the anyscale byod ecr to use for this test.
"""
if self.is_gce():
return get_global_config()["byod_gcp_cr"]
byod_ecr = get_global_config()["byod_aws_cr"]
if byod_ecr:
return byod_ecr
return get_global_config()["byod_ecr"]
def get_ray_image(self) -> str:
"""
Returns the ray docker image to use for this test.
"""
config = get_global_config()
repo = self.get_byod_repo()
if repo == DATAPLANE_ECR_REPO:
repo_name = config["byod_ray_cr_repo"]
elif repo == DATAPLANE_ECR_ML_REPO:
repo_name = config["byod_ray_ml_cr_repo"]
else:
raise ValueError(f"Unknown repo {repo}")
ecr = config["byod_ray_ecr"]
tag = self.get_byod_base_image_tag()
return f"{ecr}/{repo_name}:{tag}"
def get_anyscale_base_byod_image(self) -> str:
"""
Returns the anyscale byod image to use for this test.
"""
return (
f"{self.get_byod_ecr()}/"
f"{self.get_byod_repo()}:{self.get_byod_base_image_tag()}"
)
def require_custom_byod_image(self) -> bool:
"""
Returns whether this test requires a custom byod image.
"""
return self.get_byod_post_build_script() is not None
def get_anyscale_byod_image(self) -> str:
"""
Returns the anyscale byod image to use for this test.
"""
return (
f"{self.get_byod_ecr()}/"
f"{self.get_byod_repo()}:{self.get_byod_image_tag()}"
)
def get_test_results(
self, limit: int = 10, refresh: bool = False
) -> List[TestResult]:
"""
Get test result from test object, or s3
:param limit: limit of test results to return
:param refresh: whether to refresh the test results from s3
"""
if self.test_results is not None and not refresh:
return self.test_results
s3_client = boto3.client("s3")
files = sorted(
s3_client.list_objects_v2(
Bucket=get_global_config()["state_machine_aws_bucket"],
Prefix=f"{AWS_TEST_RESULT_KEY}/{self.get_name()}-",
).get("Contents", []),
key=lambda file: int(file["LastModified"].strftime("%s")),
reverse=True,
)[:limit]
self.test_results = [
TestResult.from_dict(
json.loads(
s3_client.get_object(
Bucket=get_global_config()["state_machine_aws_bucket"],
Key=file["Key"],
)
.get("Body")
.read()
.decode("utf-8")
)
)
for file in files
]
return self.test_results
def persist_result_to_s3(self, result: Result) -> bool:
"""
Persist test result object to s3
"""
boto3.client("s3").put_object(
Bucket=get_global_config()["state_machine_aws_bucket"],
Key=f"{AWS_TEST_RESULT_KEY}/"
f"{self.get_name()}-{int(time.time() * 1000)}.json",
Body=json.dumps(TestResult.from_result(result).__dict__),
)
def persist_to_s3(self) -> bool:
"""
Persist test object to s3
"""
boto3.client("s3").put_object(
Bucket=get_global_config()["state_machine_aws_bucket"],
Key=f"{AWS_TEST_KEY}/{self.get_name()}.json",
Body=json.dumps(self),
)
class TestDefinition(dict):
"""
A class represents a definition of a test, such as test name, group, etc. Comparing
to the test class, there are additional field, for example variations, which can be
used to define several variations of a test.
"""
pass