218 lines
8.5 KiB
Python
218 lines
8.5 KiB
Python
"""Host pools: placement by resources/capabilities/locality, autoscaling, idle shutdown,
|
|
budgets, TTL extension, and Docker sandboxes placed on pool hosts (fake hosts + a fake
|
|
docker CLI, so no VMs or daemon are needed)."""
|
|
|
|
import asyncio
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from pipewright import Graph
|
|
from pipewright.engine import Engine, RunOptions
|
|
from pipewright.errors import BudgetExceeded, ConfigError
|
|
from pipewright.hosts import Resources
|
|
from pipewright.store import Store
|
|
|
|
FAKE_DOCKER = str(Path(__file__).with_name("fake_docker.py"))
|
|
|
|
|
|
@pytest.fixture
|
|
def fake_docker(tmp_path, monkeypatch):
|
|
root = tmp_path / "docker"
|
|
monkeypatch.setenv("FAKE_DOCKER_ROOT", str(root))
|
|
return root
|
|
|
|
|
|
def pool_project(make_project, fake_docker, **hosts_cfg):
|
|
cfg = {"type": "fake", "max": 2, "capacity": {"cpus": 4, "memory": "8g"}, "tick": 0.05,
|
|
"docker": FAKE_DOCKER, **hosts_cfg}
|
|
return make_project({"hosts": {"vms": cfg},
|
|
"sandboxes": {"box": {"type": "docker", "hosts": "vms", "image": "img:1", "cpus": 2,
|
|
"memory": "2g", "docker": FAKE_DOCKER}}})
|
|
|
|
|
|
def test_parse_sizes():
|
|
r = Resources.parse({"cpus": 8, "memory": "16g", "disk": "512MiB"})
|
|
assert r.cpus == 8 and r.memory == 16 * 2**30 and r.disk == 512 * 2**20
|
|
assert Resources(2, 2**30).fits_in(Resources(2, 2**31)) and not Resources(3, 0).fits_in(Resources(2, 2**31))
|
|
|
|
|
|
def test_packing_and_scale_up(make_project, fake_docker):
|
|
proj = pool_project(make_project, fake_docker)
|
|
pool = proj.host_pool("vms")
|
|
|
|
async def go():
|
|
req = pool.requirements(Resources(2, 2**30))
|
|
leases = await asyncio.gather(*(pool.acquire(req) for _ in range(3)))
|
|
hosts = {lz.host.id for lz in leases}
|
|
assert len(hosts) == 2 and pool.provider.created and len(pool.provider.created) == 2
|
|
# bin packing: two leases share a host, the third has its own
|
|
per_host = sorted(sum(1 for lz in leases if lz.host.id == h) for h in hosts)
|
|
assert per_host == [1, 2]
|
|
# a fourth request fits next to the single one
|
|
lz4 = await asyncio.wait_for(pool.acquire(req), 2)
|
|
assert len(pool.provider.created) == 2
|
|
for lz in [*leases, lz4]:
|
|
lz.release()
|
|
await pool.drain()
|
|
assert sorted(pool.provider.deleted) == sorted(pool.provider.created)
|
|
|
|
asyncio.run(go())
|
|
|
|
|
|
def test_memory_is_capacity_not_slots(make_project, fake_docker):
|
|
"""Two 8 GB tasks never share a 16 GB host that keeps 1 GB for itself."""
|
|
proj = pool_project(make_project, fake_docker, capacity={"cpus": 8, "memory": "16g"},
|
|
reserve={"memory": "1g"}, max=1)
|
|
pool = proj.host_pool("vms")
|
|
|
|
async def go():
|
|
req = pool.requirements(Resources(2, 8 * 2**30))
|
|
a = await pool.acquire(req)
|
|
b = asyncio.ensure_future(pool.acquire(req))
|
|
await asyncio.sleep(0.2)
|
|
assert not b.done() # waits: max=1 and the host has 7 GB left
|
|
a.release()
|
|
lb = await asyncio.wait_for(b, 2)
|
|
lb.release()
|
|
with pytest.raises(ConfigError):
|
|
pool.requirements(Resources(1, 16 * 2**30)) # can never fit
|
|
await pool.drain()
|
|
|
|
asyncio.run(go())
|
|
|
|
|
|
def test_locality_prefers_hosts_with_image(make_project, fake_docker):
|
|
proj = pool_project(make_project, fake_docker, min=2)
|
|
pool = proj.host_pool("vms")
|
|
|
|
async def go():
|
|
await pool.scale_to(2)
|
|
h1, h2 = sorted(pool.hosts.values(), key=lambda h: h.created)
|
|
pool.add_label(h2, "image:big:1")
|
|
lz = await pool.acquire(pool.requirements(Resources(1, 0), prefer={"image:big:1"}))
|
|
assert lz.host is h2
|
|
lz.release()
|
|
await pool.drain()
|
|
|
|
asyncio.run(go())
|
|
|
|
|
|
def test_idle_shutdown_and_min(make_project, fake_docker):
|
|
proj = pool_project(make_project, fake_docker, idle_shutdown=0.1, min=1)
|
|
pool = proj.host_pool("vms")
|
|
|
|
async def go():
|
|
req = pool.requirements(Resources(4, 0))
|
|
a, b = await asyncio.gather(pool.acquire(req), pool.acquire(req))
|
|
assert len(pool.hosts) == 2
|
|
a.release()
|
|
b.release()
|
|
await asyncio.sleep(0.5)
|
|
assert len([h for h in pool.hosts.values() if h.state == "ready"]) == 1 # down to min
|
|
assert len(pool.provider.deleted) == 1
|
|
await pool.drain()
|
|
assert len(pool.provider.deleted) == 2
|
|
|
|
asyncio.run(go())
|
|
|
|
|
|
def test_budget_stops_scaling(make_project, fake_docker):
|
|
proj = pool_project(make_project, fake_docker, budget={"hours": 0.0}, max=2)
|
|
pool = proj.host_pool("vms")
|
|
|
|
async def go():
|
|
with pytest.raises(BudgetExceeded):
|
|
await asyncio.wait_for(pool.acquire(pool.requirements(Resources(1, 0))), 2)
|
|
await pool.drain()
|
|
assert not pool.provider.created
|
|
|
|
asyncio.run(go())
|
|
|
|
|
|
def test_create_failure_retried_and_ttl_extended(make_project, fake_docker):
|
|
proj = pool_project(make_project, fake_docker, fail_create=1, ttl=1, extend_margin=0.95, create_backoff=0.05)
|
|
pool = proj.host_pool("vms")
|
|
|
|
async def go():
|
|
lz = await asyncio.wait_for(pool.acquire(pool.requirements(Resources(1, 0))), 5)
|
|
assert pool.stats["failed_create"] == 1 and len(pool.provider.created) == 1
|
|
await asyncio.sleep(0.3)
|
|
assert pool.provider.extended
|
|
lz.release()
|
|
await pool.drain()
|
|
|
|
asyncio.run(go())
|
|
|
|
|
|
def test_create_limit_and_failures_are_bounded(make_project, fake_docker):
|
|
from pipewright.errors import InfraError
|
|
|
|
proj = pool_project(make_project, fake_docker, fail_create=100, create_backoff=0.01, max=2, create_retries=1)
|
|
pool = proj.host_pool("vms")
|
|
|
|
async def go():
|
|
with pytest.raises((InfraError, BudgetExceeded)):
|
|
await asyncio.wait_for(pool.acquire(pool.requirements(Resources(1, 0))), 5)
|
|
await asyncio.sleep(0.3)
|
|
assert pool.stats["failed_create"] <= pool.create_limit == 8
|
|
await pool.drain()
|
|
|
|
asyncio.run(go())
|
|
|
|
|
|
def test_kvm_runtime_setup_and_requirement(make_project, fake_docker):
|
|
proj = pool_project(make_project, fake_docker, kvm=True, docker_kvm_runtime=True,
|
|
setup=["echo setup-ran"])
|
|
pool = proj.host_pool("vms")
|
|
|
|
async def go():
|
|
lz = await pool.acquire(pool.requirements(Resources(1, 0), kvm=True))
|
|
cmds = [c for _, c in pool.provider.commands]
|
|
assert "bash -s" in cmds and "echo setup-ran" in cmds and "kvm" in lz.host.labels
|
|
lz.release()
|
|
await pool.drain()
|
|
|
|
asyncio.run(go())
|
|
proj2 = pool_project(make_project, fake_docker) # hosts without kvm
|
|
with pytest.raises(ConfigError):
|
|
proj2.host_pool("vms").requirements(Resources(1, 0), kvm=True)
|
|
|
|
|
|
def test_engine_runs_sandboxes_on_pool(make_project, fake_docker):
|
|
proj = pool_project(make_project, fake_docker, idle_shutdown=60)
|
|
g = Graph("pooled")
|
|
src = g.add("src", "source.inline", kind="t", records=[{"id": f"r{i}", "n": i} for i in range(6)])
|
|
g.add("check", "sandbox.check", input=src, pool="box", checks=[
|
|
{"name": "even", "command": f"{sys.executable} -c 'import sys; sys.exit({{{{ payload.n }}}} % 2)'",
|
|
"expect": "pass"}])
|
|
store = Store(proj.store_dir)
|
|
try:
|
|
summary = asyncio.run(Engine(g.to_spec(), proj, store).run(RunOptions()))
|
|
finally:
|
|
store.close()
|
|
assert summary["status"] == "completed", summary["errors"]
|
|
run = Store(proj.store_dir).run(summary["run_id"])
|
|
hosts = run["stats"]["hosts"]["vms"]
|
|
assert hosts["created"] == 2 and hosts["deleted"] == 2 and hosts["placed"] == 6 # 6 x 2 cpus on 4-cpu hosts
|
|
calls = [json.loads(x) for x in (fake_docker / "calls.jsonl").read_text().splitlines()]
|
|
runs = [c for c in calls if c["args"][0] == "run"]
|
|
assert len(runs) == 6 and all(c["host"].startswith("ssh://fake-vms-") for c in runs)
|
|
assert all("--cpus" in c["args"] and "2" in c["args"] for c in runs)
|
|
# the image was checked once per host, then pulled with the first container
|
|
assert len({c["host"] for c in calls if c["args"][:2] == ["image", "inspect"]}) == 2
|
|
labels = {f"r{i}": None for i in range(6)}
|
|
assert summary["funnel"]["nodes"]["check"]["events"]["ok"] == len(labels)
|
|
|
|
|
|
def test_check_reports_unknown_host_pool(make_project):
|
|
from pipewright.check import check
|
|
|
|
proj = make_project({"sandboxes": {"box": {"type": "docker", "hosts": "nope", "image": "x"}}})
|
|
g = Graph("x")
|
|
g.add("src", "source.inline", kind="t", records=[{"id": 1}])
|
|
diags = check(g.to_spec(), proj)
|
|
assert any(d.code == "PW012" and "host pool 'nope'" in d.message for d in diags)
|