1#!/usr/bin/env python3
2import os
3from pathlib import Path
4import tempfile
5import time
6from unittest.mock import patch
7
8import router
9
10
11def main():
12 with tempfile.TemporaryDirectory(prefix="snowglobe-router-health-") as temporary:
13 root = Path(temporary)
14 (root / "proof").write_text("a" * 64)
15 (root / "routes").mkdir()
16 environment = {"SNOWGLOBE_DOMAIN": "snowglobe.test", "SNOWGLOBE_DASHBOARD_PORT": "1",
17 "SNOWGLOBE_PROXY_TOKEN_FILE": str(root / "proof"), "SNOWGLOBE_STATE": temporary}
18 status = {}
19
20 def nomad(path, _):
21 if path == "/v1/services":
22 return [{"Namespace": "default", "Services": [{"ServiceName": "plain"}]}]
23 if path.startswith("/v1/service/"):
24 return [{"ServiceName": "plain", "JobID": "plain", "AllocID": "alloc", "Address": "127.0.0.1",
25 "Port": 2, "Tags": ["caddy-host=plain.snowglobe.test"]}]
26 return {"http": {"Status": status["alloc"]}}
27
28 def routed():
29 return "plain.snowglobe.test {" in router.render("fixture")
30
31 with patch.dict(os.environ, environment, clear=True), patch.object(router, "nomad", nomad), \
32 patch.object(router, "ROUTE_DIR", str(root / "routes")), patch.object(router, "HEALTH_GRACE", 0.3):
33 status["alloc"] = "pending"
34 assert not routed(), "an allocation that never passed was routed"
35 status["alloc"] = "success"
36 assert routed()
37 status["alloc"] = "failure"
38 assert routed(), "one failed check dropped the route"
39 time.sleep(0.4)
40 assert not routed(), "a failing allocation stayed routed"
41 status["alloc"] = "success"
42 assert routed()
43 print("A route survives a short check failure and drops after the grace period.")
44
45
46if __name__ == "__main__":
47 main()