Repository navigation
Expand file tree
/
Copy pathlocalcloud-test.py
More file actions
409 lines (397 loc) · 11.9 KB
/
Copy pathlocalcloud-test.py
File metadata and controls
409 lines (397 loc) · 11.9 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"""Run this repository's selected tests against an isolated LocalCloud container."""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import uuid
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlsplit, urlunsplit
from urllib.request import ProxyHandler, Request, build_opener
ROOT = Path(__file__).resolve().parents[1]
TEST_SPEC_JSON = r"""
{
"image": "agentcloud/localcloud:ci",
"services": [
"bigquery",
"bigtable",
"gcs"
],
"gateway_port": 5380,
"ports": [
5380,
5382,
5385,
5388,
5389,
5392
],
"endpoint_variables": [
"BIGQUERY_EMULATOR_HOST",
"BIGTABLE_EMULATOR_HOST",
"STORAGE_EMULATOR_HOST"
],
"project_variables": [
"GOOGLE_CLOUD_PROJECT"
],
"build": [
{
"cwd": ".",
"command": [
"uv",
"venv",
"--python",
"3.12",
".venv"
]
},
{
"cwd": ".",
"command": [
"make",
"PYTHON_VERSION=3.12",
"install-python-dependencies-ci"
]
},
{
"cwd": ".",
"command": [
"uv",
"pip",
"install",
"protobuf==6.33.6",
"grpcio-health-checking==1.75.1",
"grpcio-reflection==1.75.1",
"grpcio-testing==1.75.1",
"grpcio-tools==1.75.1"
]
},
{
"cwd": ".",
"command": [
".venv/bin/ruff",
"check",
"sdk/python/feast/infra/offline_stores/bigquery.py",
"sdk/python/feast/infra/offline_stores/bigquery_source.py",
"sdk/python/tests/localcloud/test_localcloud_gcp.py",
"sdk/python/tests/unit/test_bigquery_local_endpoint.py",
"scripts/localcloud-test.py"
]
},
{
"cwd": ".",
"command": [
".venv/bin/ruff",
"format",
"--check",
"sdk/python/feast/infra/offline_stores/bigquery.py",
"sdk/python/feast/infra/offline_stores/bigquery_source.py",
"sdk/python/tests/localcloud/test_localcloud_gcp.py",
"sdk/python/tests/unit/test_bigquery_local_endpoint.py",
"scripts/localcloud-test.py"
]
},
{
"cwd": ".",
"command": [
"uv",
"pip",
"check"
]
},
{
"cwd": ".",
"command": [
"git",
"diff",
"--check"
]
}
],
"config": {
"version": 1,
"context": {
"project": "repository-tests"
},
"host": {
"docker_socket": false
},
"server": {
"persistence": true,
"auto_seed": false
},
"updater": {
"enabled": false
},
"services": {
"enabled": [
"bigquery",
"bigtable",
"gcs"
]
}
},
"dedicated_lane": {
"cwd": ".",
"command": [
".venv/bin/python",
"-m",
"pytest",
"-q",
"--tb=short",
"sdk/python/tests/localcloud/test_localcloud_gcp.py"
]
},
"full_suite": {
"cwd": ".",
"command": [
"env",
"-u",
"SPARK_HOME",
"-u",
"PYSPARK_PYTHON",
"-u",
"PYSPARK_DRIVER_PYTHON",
"uv",
"run",
"--no-sync",
"python",
"-m",
"pytest",
"-q",
"--tb=short",
"-n",
"8",
"--ignore=sdk/python/tests/unit/infra/offline_stores/contrib/mongodb_offline_store",
"sdk/python/tests/unit"
]
}
}
"""
def docker(*args: str, check: bool = True) -> str:
result = subprocess.run(
["docker", *args], text=True, capture_output=True, check=False
)
if check and result.returncode:
raise RuntimeError(result.stderr.strip() or result.stdout.strip())
return result.stdout.strip()
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--full-suite",
action="store_true",
help="run the normal regression suite instead of the selected service tests",
)
parser.add_argument(
"--existing",
metavar="GATEWAY",
help="borrow an already running LocalCloud instead of starting a container",
)
parser.add_argument(
"--skip-build",
action="store_true",
help="dependencies/build were already prepared",
)
args = parser.parse_args()
manifest = json.loads(TEST_SPEC_JSON)
ident = "lc-tests-" + uuid.uuid4().hex[:12]
container_created = False
volume_created = False
project_owned = False
failed = True
gateway = args.existing
ports: dict[int, int] = {}
supplied = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
project = supplied or "lc-tests-" + uuid.uuid4().hex[:12]
if not re.fullmatch(r"[a-z][a-z0-9-]{0,29}", project):
raise RuntimeError("Invalid LocalCloud project ID")
opener = build_opener(ProxyHandler({}))
def request(method: str, path: str, body: dict | None = None) -> object:
payload = None if body is None else json.dumps(body).encode()
req = Request(
str(gateway).rstrip("/") + path,
data=payload,
method=method,
headers={
"Content-Type": "application/json",
"X-LocalCloud-User": "repository-tests",
},
)
with opener.open(req, timeout=30) as response:
return json.load(response)
def mapped_endpoint(value: str) -> str:
is_url = "://" in value
parsed = urlsplit(value if is_url else "//" + value)
port = parsed.port
if args.existing and parsed.hostname in {"localhost", "127.0.0.1"}:
return value
if (
parsed.hostname not in {"localhost", "127.0.0.1", "0.0.0.0"}
or port not in ports
):
raise RuntimeError(
"LocalCloud advertised an endpoint outside its published container ports"
)
authority = "127.0.0.1:" + str(ports[port])
return (
urlunsplit(
(parsed.scheme, authority, parsed.path, parsed.query, parsed.fragment)
)
if is_url
else authority
)
try:
if gateway is None:
docker("info", "--format", "{{.ServerVersion}}")
docker("pull", manifest["image"])
docker(
"volume", "create", "--label", "localcloud.test-owner=" + ident, ident
)
volume_created = True
command = [
"create",
"--name",
ident,
"--label",
"localcloud.test-owner=" + ident,
"--memory",
"4g",
"-e",
"LOCALCLOUD_CONSOLE=false",
"-v",
ident + ":/var/lib/localcloud",
]
for port in manifest["ports"]:
command += ["-p", "127.0.0.1::" + str(port)]
command.append(manifest["image"])
docker(*command)
container_created = True
with tempfile.TemporaryDirectory(prefix="localcloud-tests-") as temporary:
config_path = Path(temporary) / "config.json"
config_path.write_text(json.dumps(manifest["config"]))
docker(
"cp", str(config_path), ident + ":/etc/localcloud/localcloud.yaml"
)
docker("start", ident)
info = json.loads(docker("inspect", ident))[0]
ports = {
int(port.split("/")[0]): int(bindings[0]["HostPort"])
for port, bindings in info["NetworkSettings"]["Ports"].items()
if bindings
}
gateway = "http://127.0.0.1:" + str(ports[manifest["gateway_port"]])
deadline = time.monotonic() + 240
while True:
try:
readiness = request("GET", "/readiness")
if isinstance(readiness, dict) and readiness.get("ready") is True:
request("GET", "/projects")
break
except (OSError, ValueError):
pass
if (
container_created
and docker("inspect", "--format", "{{.State.Running}}", ident) != "true"
):
raise RuntimeError("LocalCloud container exited during startup")
if time.monotonic() >= deadline:
raise RuntimeError("LocalCloud did not become ready within 240 seconds")
time.sleep(2)
services = request("GET", "/services")
rows = services.get("services", []) if isinstance(services, dict) else services
enabled = {
s.get("service_id", s.get("id")) for s in rows if s.get("enabled") is True
}
if enabled != set(manifest["services"]):
raise RuntimeError(
"LocalCloud enabled services differ from this repository's test contract: "
+ str(sorted(enabled))
)
try:
request("POST", "/projects", {"project_id": project})
project_owned = not supplied
except HTTPError as exc:
if exc.code != 409 or not supplied:
raise
advertised = request("GET", "/env?format=json&project=" + project)
if (
not isinstance(advertised, dict)
or advertised.get("GOOGLE_CLOUD_PROJECT") != project
):
raise RuntimeError("LocalCloud did not advertise the selected project")
env = {
k: v
for k, v in os.environ.items()
if not k.endswith("_EMULATOR_HOST")
and k
not in {
"GOOGLE_APPLICATION_CREDENTIALS",
"GOOGLE_CLOUD_PROJECT",
"GCLOUD_PROJECT",
"GCP_PROJECT",
"GOROOT",
"SPARK_HOME",
"PYSPARK_PYTHON",
"PYSPARK_DRIVER_PYTHON",
}
}
env.update(
{
"GOOGLE_CLOUD_PROJECT": project,
"LOCALCLOUD_GATEWAY_URL": str(gateway),
"LOCALCLOUD_TEST": "1",
}
)
for variable in manifest.get("project_variables", ["GOOGLE_CLOUD_PROJECT"]):
env[variable] = project
for variable in manifest["endpoint_variables"]:
if not advertised.get(variable):
raise RuntimeError("LocalCloud did not advertise " + variable)
env[variable] = mapped_endpoint(str(advertised[variable]))
print(
"LocalCloud:",
gateway,
"project:",
project,
"services:",
", ".join(manifest["services"]),
flush=True,
)
phases = [] if args.skip_build else manifest["build"]
phases = [
*phases,
manifest["full_suite"] if args.full_suite else manifest["dedicated_lane"],
]
for phase in phases:
cwd = (ROOT / phase["cwd"]).resolve()
if not cwd.is_relative_to(ROOT):
raise RuntimeError("Test working directory escapes the repository")
print("Running:", " ".join(phase["command"]), flush=True)
result = subprocess.run(phase["command"], cwd=cwd, env=env, check=False)
if result.returncode:
return result.returncode
failed = False
return 0
finally:
try:
if project_owned:
request("DELETE", "/projects/" + project)
finally:
if container_created:
logs = docker("logs", "--tail", "100", ident, check=False)
if failed:
print(logs, file=sys.stderr)
try:
docker("rm", "-f", ident)
finally:
if volume_created:
docker("volume", "rm", ident)
elif volume_created:
docker("volume", "rm", ident)
if __name__ == "__main__":
sys.exit(main())