8000 test(scaling): hold the Proxmox and SSH fakes to the real APIs by adeelahmad · Pull Request #659 · adeelahmad/lense · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ request, to another check that proves the same thing; loosening a requirement or
| DigitalOcean and Hetzner Cloud: credentials checked, list prices, machines launched with a one-use join token, watched, found by tag and deleted; a group waits for the mesh's install line before launching | [test_scaling_clouds.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_scaling_clouds.py) `test_a_digitalocean_group_waits_for_the_install_line_then_launches_droplets`, `test_hetzner_prices_in_euros_and_its_errors_read_as_hetzners`, `test_the_cloud_drivers_are_listed_and_need_the_mesh` |
| Lambda: GPU instances launched with the account's SSH key and a one-use join token in their user-data, tagged with Lens's tag and the unit, priced from Lambda's list, watched (an instance Lambda takes back counts as gone), found by tag across pages and terminated; every request and answer held to Lambda's published API document | [test_scaling_clouds.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_scaling_clouds.py) `test_a_lambda_group_launches_gpu_instances_that_join_over_the_mesh`, `test_lambda_needs_an_ssh_key_and_pages_through_instances`, `test_lens_reads_only_fields_the_clouds_answer_with` |
| A group of machines elsewhere counts only the jobs a worker node takes, and never launches one for others | [test_scaling_clouds.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_scaling_clouds.py) `test_a_group_elsewhere_counts_only_the_jobs_a_node_takes` |
| Proxmox VE: clones of a VM template, started and booted through the guest agent, found by tag, stopped and deleted; a clone whose agent never answers says so | [test_scaling_proxmox.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_scaling_proxmox.py) `test_proxmox_clones_boots_through_the_guest_agent_and_deletes`, `test_a_clone_whose_agent_never_answers_says_so`, `test_a_clone_still_booting_is_pending` |
| Proxmox VE: clones of a VM template, started and booted through the guest agent, found by tag, stopped and deleted; a clone whose agent never answers says so; every request and answer held to Proxmox's own API schema | [test_scaling_proxmox.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_scaling_proxmox.py) `test_proxmox_clones_boots_through_the_guest_agent_and_deletes`, `test_a_clone_whose_agent_never_answers_says_so`, `test_a_clone_still_booting_is_pending`, `test_lens_reads_only_fields_proxmox_answers_with` |
| Linux hosts over SSH: host keys trusted on first use and held to, workers started per host with a script that removes itself, found, counted and stopped | [test_scaling_ssh.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_scaling_ssh.py) `test_host_specs`, `test_ssh_trusts_host_keys_on_first_use_and_holds_to_them`, `test_ssh_starts_counts_and_stops_workers` |
| AWS EC2 units launch as spot or on-demand instances, hardened (IMDSv2, encrypted disk, terminate on shutdown), with only the mesh's one-time join line in their user-data | [test_scaling_aws.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/domain/test_scaling_aws.py) `test_a_spot_unit_launches_hardened_and_priced_in_its_zone`, `test_the_driver_is_offered_and_its_settings_are_checked` |
| A spot unit falls back to on demand when AWS has none; without a price or the mesh, nothing launches | [test_scaling_aws.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/domain/test_scaling_aws.py) `test_without_spot_capacity_it_falls_back_to_on_demand_unless_told_not_to`, `test_a_unit_without_a_price_or_the_mesh_launches_nothing` |
Expand Down
4 changes: 3 additions & 1 deletion docs/scaling.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,9 @@ scaler go from launch to scale-in as they would on a real account; Lens's signed
botocore's own model of SageMaker's runtime API. moto has no Bedrock provisioned throughput, so botocore's Stubber
answers for Bedrock, holding each request and answer to AWS's model of Bedrock's API and each name Lens sends to the
model's patterns; Lens's Converse calls are held to it the same way.
Proxmox and SSH hosts have no published document to hold their fakes to yet.
Proxmox's fake is held the same way to Proxmox's own schema of its API, converted from its API viewer (forms
read by the types the schema gives). SSH hosts have no API document: each test host is a real SSH server (Paramiko's, a
test-only dependency) that checks the client's key and runs the driver's commands in a real shell.

While a model group's unit runs, it is Lens's LLM provider (the template's `use_as_provider`, on by default): the
scaler points Settings › LLM provider at the unit's address, model and key, keeping the provider that was there
Expand Down
1 change: 1 addition & 0 deletions fastapi_backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ dev = [
"pywebrtc-audio>=0.2.0,<0.3", # the clean_audio step's WebRTC audio processing, tested on synthetic audio
"python-vaultwarden>=1.1.2,<2", # the Vaultwarden client, tested against a fake Vaultwarden
"moto[ec2]>=5.1,<6",
"paramiko>=3.5,<5",
]

[tool.hatch.build.targets.wheel]
Expand Down
57 changes: 39 additions & 18 deletions fastapi_backend/tests/api/test_scaling_proxmox.py
10000
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
"""Auto scaling on Proxmox VE (docs/scaling.md "Providers"): clones of a VM template, booted and joined through the
guest agent, against an httpx MockTransport standing in for the Proxmox API."""
guest agent, against an httpx MockTransport standing in for the Proxmox API, held to Proxmox's own published schema of
its API (tests/data/openapi/proxmox-ve.json, converted from its API viewer's): every request must be one it takes, and
every answer is built from its schemas."""

from __future__ import annotations

from urllib.parse import parse_qs

import httpx
import pytest

from app.domain import scaling
from app.domain import scaling_drivers as drivers
from tests import openapi_contract as contract
from tests.helpers import login, make_user

SPEC = contract.load("proxmox-ve")


class PVE:
"""A Proxmox node in memory: VMs by id, tasks that finish at once, a guest agent that answers once booted."""
Expand All @@ -22,44 +25,53 @@ def __init__(self):

def __call__(self, req):
path = req.url.path.removeprefix("/api2/json")
form = {k: v if len(v) > 1 else v[0] for k, v in parse_qs(req.content.decode()).items()} if req.content else {}
self.calls.append((req.method, path, form, req.headers.get("authorization")))
form = contract.form(SPEC, req.method, path, req.content) if req.content else None
self.calls.append((req.method, path, form or {}, req.headers.get("authorization")))
contract.check_request(SPEC, req.method, path, form, dict(req.url.params))
r = self.answer(req.method, path, form or {})
if r.status_code == 200:
r = httpx.Response(200, json=contract.answer(SPEC, req.method, path, 200, r.json()))
return r

def answer(self, method, path, form):
ok = lambda data: httpx.Response(200, json={"data": data}) # noqa: E731
if path == "/version":
return ok({"version": "8.2.4"})
return ok({"version": "8.2.4", "release": "8.2", "repoid": "faa83925c9641325"})
if path == "/nodes":
return ok([{"node": "pve"}])
return ok([{"node": "pve", "status": "online"}])
if path == "/cluster/nextid":
return ok(str(self.next))
return ok(self.next)
if path == "/cluster/resources":
return ok([{"node": "pve", "vmid": i, **v} for i, v in self.vms.items()])
shown = lambda v: {k: x for k, x in v.items() if k != "ran"} # noqa: E731
return ok([{"id": f"qemu/{i}", "type": "qemu", "node": "pve", "vmid": i, **shown(v)} for i, v in self.vms.items()])
if path.startswith("/nodes/pve/tasks/"):
return ok({"status": "stopped", "exitstatus": "OK"})
upid = path.rsplit("/", 2)[1]
return ok({"status": "stopped", "exitstatus": "OK", "upid": upid, "node": "pve", "type": "qmclone", "user": "lens@pve"})
parts = path.split("/") # ['', 'nodes', 'pve', 'qemu', id, ...]
vmid, rest = int(parts[4]), "/".join(parts[5:])
if rest == "clone":
self.vms[int(form["newid"])] = {"name": form["name"], "status": "stopped", "tags": ""}
self.vms[form["newid"]] = {"name": form["name"], "status": "stopped", "tags": ""}
self.next += 1
return ok("UPID:pve:clone")
return ok(f"UPID:pve:00001A2B:0001F4C3:6713A2B0:qmclone:{vmid}:lens@pve!scaling:")
vm = self.vms.get(vmid)
if vm is None:
return httpx.Response(
500, json={"data": None}, extensions={"reason_phrase": f"Configuration file '{vmid}.conf' does not exist".encode()}
)
if req.method == "DELETE":
if method == "DELETE":
del self.vms[vmid]
return ok("UPID:pve:destroy")
return ok(f"UPID:pve:00001A2C:0001F4C4:6713A2B1:qmdestroy:{vmid}:lens@pve!scaling:")
if rest == "config":
vm["tags"] = form["tags"]
return ok(None)
if rest == "status/start":
vm["status"] = "running"
return ok("UPID:pve:start")
return ok(f"UPID:pve:00001A2D:0001F4C5:6713A2B2:qmstart:{vmid}:lens@pve!scaling:")
if rest == "status/stop":
vm["status"] = "stopped"
return ok("UPID:pve:stop")
return ok(f"UPID:pve:00001A2E:0001F4C6:6713A2B3:qmstop:{vmid}:lens@pve!scaling:")
if rest == "status/current":
return ok({"status": vm["status"]})
return ok({"status": vm["status"], "vmid": vmid})
if rest == "agent/ping":
if self.agent_after > 0:
self.agent_after -= 1
Expand Down Expand Up @@ -105,7 +117,7 @@ def test_proxmox_clones_boots_through_the_guest_agent_and_deletes(client, db, cf
got = drv.launch(opened, {"vm_template": 9000, "steps": ["ocr"]}, "lens-lab-1", boot)
assert got == {"id": "pve/105"}
clone = next(c for c in pve.calls if c[1].endswith("/clone"))
assert clone[1] == "/nodes/pve/qemu/9000/clone" and clone[2] == {"newid": "105", "name": "lens-lab-1", "full": "0"}
assert clone[1] == "/nodes/pve/qemu/9000/clone" and clone[2] == {"newid": 105, "name": "lens-lab-1", "full": 0}
vm = pve.vms[105]
assert vm["status"] == "running" and vm["tags"] == "lens;lens-booted"
assert vm["ran"][:2] == ["sh", "-c"] and "export LENS_WORKER_STEPS=ocr" in vm["ran"][2] and vm["ran"][2].endswith("echo join\n")
Expand Down Expand Up @@ -140,3 +152,12 @@ def test_a_clone_still_booting_is_pending(pve):
assert drv.describe({"settings": SETTINGS, "secrets": {}}, {"name": "lens-lab-3", "external_id": "pve/200"}) == {"state": "pending"}
finally:
drv.booting.pop("lens-lab-3", None)


def test_lens_reads_only_fields_proxmox_answers_with():
contract.check_answer_fields(SPEC, "GET", "/version", 200, "data.version")
contract.check_answer_fields(SPEC, "GET", "/nodes", 200, "data.node")
contract.check_answer_fields(SPEC, "GET", "/nodes/{node}/tasks/{upid}/status", 200, "data.status", "data.exitstatus")
contract.check_answer_fields(SPEC, "GET", "/nodes/{node}/qemu/{vmid}/status/current", 200, "data.status")
for field in ("node", "vmid", "name", "tags", "template"):
contract.check_answer_fields(SPEC, "GET", "/cluster/resources", 200, f"data.{field}")
Loading
Loading
0