test_cost_check_instances.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. """Stack instances (step 2b of the stage 2 design): a second site of the same
  2. stack code is a data-only manifest the gate prices and reconciles.
  3. Fixtures only. No real instance exists in the repository.
  4. """
  5. import json
  6. import sys
  7. from pathlib import Path
  8. import pytest
  9. import yaml
  10. ROOT = Path(__file__).resolve().parents[1]
  11. sys.path.insert(0, str(ROOT / "scripts"))
  12. import cost_check
  13. DO_PRICES = {
  14. "backups_fraction": 0.2,
  15. "backups_fraction_verified": False,
  16. "droplets": {"s-1vcpu-1gb": 6},
  17. }
  18. AWS_PRICES = json.loads((ROOT / "docs/cost-prices/aws.json").read_text())
  19. DO_CONNECTOR = (
  20. 'module "c{i}" {{\n source = "../../modules/twingate-connector"\n'
  21. " size = local.c.size\n}}\n"
  22. )
  23. AWS_CONNECTOR = (
  24. 'module "c{i}" {{\n source = "../../../modules/aws/twingate-connector"\n'
  25. " instance_type = local.c.type\n}}\n"
  26. )
  27. def droplets(n):
  28. return [
  29. {"name": f"d{i}", "kind": "droplet", "size": "s-1vcpu-1gb", "backups": False}
  30. for i in range(n)
  31. ]
  32. def aws_instances(n):
  33. return [
  34. {
  35. "name": f"a{i}",
  36. "kind": "instance",
  37. "type": "t4g.micro",
  38. "root_gb": 8,
  39. "public_ip": True,
  40. }
  41. for i in range(n)
  42. ]
  43. def write_json(path, data):
  44. path.parent.mkdir(parents=True, exist_ok=True)
  45. path.write_text(json.dumps(data))
  46. def build(tmp_path, *, do_cap=12.0, aws=False, extra_providers=None, sites=None):
  47. """A repo with the base DigitalOcean 10-access stack (two connectors)."""
  48. do = {
  49. "approved_monthly_total": do_cap,
  50. "active": True,
  51. "allowed_sources": {
  52. "digitalocean_droplet": ["modules/twingate-connector/main.tf"]
  53. },
  54. }
  55. if sites is not None:
  56. do["sites"] = sites
  57. providers = {"digitalocean": do}
  58. if aws:
  59. providers["aws"] = {
  60. "approved_monthly_total": 60.0,
  61. "active": False,
  62. "allowed_sources": {
  63. "aws_instance": ["modules/aws/twingate-connector/main.tf"]
  64. },
  65. }
  66. providers.update(extra_providers or {})
  67. write_json(tmp_path / "docs/cost-prices.json", DO_PRICES)
  68. write_json(tmp_path / "docs/cost-prices/aws.json", AWS_PRICES)
  69. write_json(
  70. tmp_path / "docs/stages/approved.json",
  71. {"stage": 1, "ceiling": 30.0, "providers": providers},
  72. )
  73. for rel, body in (
  74. (
  75. "modules/twingate-connector/main.tf",
  76. 'resource "digitalocean_droplet" "a" {}\n',
  77. ),
  78. *(
  79. [
  80. (
  81. "modules/aws/twingate-connector/main.tf",
  82. 'resource "aws_instance" "a" {}\n',
  83. )
  84. ]
  85. if aws
  86. else []
  87. ),
  88. ):
  89. p = tmp_path / rel
  90. p.parent.mkdir(parents=True, exist_ok=True)
  91. p.write_text(body)
  92. write_json(tmp_path / "stacks/10-access/cost.json", {"resources": droplets(2)})
  93. (tmp_path / "stacks/10-access/main.tf").write_text(
  94. "".join(DO_CONNECTOR.format(i=i) for i in range(2))
  95. )
  96. if aws:
  97. write_json(
  98. tmp_path / "stacks/aws/10-access/cost.json", {"resources": aws_instances(2)}
  99. )
  100. (tmp_path / "stacks/aws/10-access/main.tf").write_text(
  101. "".join(AWS_CONNECTOR.format(i=i) for i in range(2))
  102. )
  103. return tmp_path
  104. def add_site(
  105. root,
  106. key="tor2",
  107. stack="10-access",
  108. machines=2,
  109. instance_of="stacks/10-access",
  110. resources=None,
  111. **extra,
  112. ):
  113. data = {"resources": droplets(machines) if resources is None else resources}
  114. if instance_of is not None:
  115. data["instance_of"] = instance_of
  116. data.update(extra)
  117. write_json(root / f"stacks/sites/{key}/{stack}/cost.json", data)
  118. return root / f"stacks/sites/{key}/{stack}"
  119. def add_and_cap(tmp_path, cap, **kw):
  120. root = build(tmp_path, do_cap=cap)
  121. add_site(root, **kw)
  122. return root
  123. def run(root, capsys):
  124. code = cost_check.main(["--root", str(root)])
  125. out = capsys.readouterr()
  126. return code, out.out, out.err
  127. def fails_with(root, capsys, text):
  128. code, out, err = run(root, capsys)
  129. assert code == 1, err
  130. assert text in err + out, err
  131. # ---- pricing ----------------------------------------------------------------
  132. def test_instance_is_priced_into_its_provider(tmp_path, capsys):
  133. root = add_and_cap(tmp_path, 24.0)
  134. code, out, err = run(root, capsys)
  135. assert code == 0, err
  136. assert "digitalocean: planned $24.00/mo, approved $24.00" in out
  137. def test_a_second_site_over_the_approved_total_fails(tmp_path, capsys):
  138. root = add_and_cap(tmp_path, 12.0)
  139. fails_with(root, capsys, "digitalocean: planned $24.00 is above approved $12.00")
  140. def test_instance_provider_comes_from_instance_of_not_its_path(tmp_path):
  141. root = build(tmp_path, aws=True)
  142. add_site(
  143. root,
  144. key="east",
  145. stack="aws/10-access",
  146. instance_of="stacks/aws/10-access",
  147. resources=aws_instances(2),
  148. )
  149. totals = cost_check.provider_totals(root)
  150. assert totals["digitalocean"] == 12.0
  151. assert totals["aws"] == pytest.approx(41.69, abs=0.01)
  152. # ---- instance_of validation ---------------------------------------------------
  153. def test_missing_instance_of_fails(tmp_path, capsys):
  154. root = build(tmp_path, do_cap=24.0)
  155. add_site(root, instance_of=None)
  156. fails_with(root, capsys, "instance_of is missing")
  157. @pytest.mark.parametrize(
  158. "bad",
  159. [
  160. 7,
  161. "",
  162. "stacks/10-access/",
  163. "../stacks/10-access",
  164. "/stacks/10-access",
  165. "stacks//10-access",
  166. "stacks/./10-access",
  167. ],
  168. )
  169. def test_malformed_instance_of_fails(tmp_path, capsys, bad):
  170. root = build(tmp_path, do_cap=24.0)
  171. add_site(root, instance_of=bad)
  172. fails_with(root, capsys, "instance_of")
  173. def test_instance_of_naming_no_stack_fails(tmp_path, capsys):
  174. root = build(tmp_path, do_cap=24.0)
  175. add_site(root, stack="20-telemetry", instance_of="stacks/20-telemetry")
  176. fails_with(root, capsys, "names no stack directory with its own cost.json")
  177. def test_instance_of_naming_a_stack_without_manifest_fails(tmp_path, capsys):
  178. root = build(tmp_path, do_cap=24.0)
  179. (root / "stacks/20-telemetry").mkdir()
  180. add_site(root, stack="20-telemetry", instance_of="stacks/20-telemetry")
  181. fails_with(root, capsys, "names no stack directory with its own cost.json")
  182. def test_instance_of_naming_another_instance_fails(tmp_path, capsys):
  183. root = build(tmp_path, do_cap=36.0)
  184. add_site(root, key="tor2")
  185. add_site(root, key="tor3", instance_of="stacks/sites/tor2/10-access")
  186. fails_with(root, capsys, "must not point into stacks/sites")
  187. def test_instance_path_must_mirror_instance_of(tmp_path, capsys):
  188. root = build(tmp_path, do_cap=24.0)
  189. write_json(root / "stacks/00-foundation/cost.json", {"resources": []})
  190. add_site(root, stack="00-foundation", instance_of="stacks/10-access")
  191. fails_with(root, capsys, "must sit at stacks/sites/<resource_key>/10-access")
  192. def test_instance_of_outside_sites_fails(tmp_path, capsys):
  193. root = build(tmp_path, do_cap=12.0)
  194. write_json(
  195. root / "stacks/10-access/cost.json",
  196. {"resources": droplets(2), "instance_of": "stacks/10-access"},
  197. )
  198. fails_with(root, capsys, "instance_of is only allowed under stacks/sites/")
  199. def test_manifest_directly_under_sites_fails(tmp_path, capsys):
  200. root = build(tmp_path, do_cap=24.0)
  201. write_json(
  202. root / "stacks/sites/cost.json",
  203. {"resources": droplets(2), "instance_of": "stacks/10-access"},
  204. )
  205. fails_with(root, capsys, "stacks/sites/<resource_key>/")
  206. @pytest.mark.parametrize("key", ["Tor2", "tor_2", "-tor2", "tor 2"])
  207. def test_resource_key_shape_is_enforced(tmp_path, capsys, key):
  208. root = build(tmp_path, do_cap=24.0)
  209. add_site(root, key=key)
  210. code, _out, err = run(root, capsys)
  211. assert code == 1, err
  212. assert "resource_key" in err or "stack directory name" in err
  213. # ---- instances carry no code --------------------------------------------------
  214. @pytest.mark.parametrize("name", ["main.tf", "x.tofu", "override.tf"])
  215. def test_instance_with_opentofu_files_fails(tmp_path, capsys, name):
  216. root = build(tmp_path, do_cap=24.0)
  217. inst = add_site(root)
  218. (inst / name).write_text("# empty\n")
  219. fails_with(root, capsys, "instances carry no code")
  220. def test_opentofu_file_in_a_site_dir_without_manifest_fails(tmp_path, capsys):
  221. root = build(tmp_path, do_cap=12.0)
  222. d = root / "stacks/sites/tor2"
  223. d.mkdir(parents=True)
  224. (d / "x.tf").write_text("# empty\n")
  225. fails_with(root, capsys, "instances carry no code")
  226. # ---- reconciliation with the stack named in instance_of -----------------------
  227. @pytest.mark.parametrize("machines", [1, 3])
  228. def test_machine_count_must_equal_connector_blocks_of_the_named_stack(
  229. tmp_path, capsys, machines
  230. ):
  231. root = build(tmp_path, do_cap=40.0)
  232. add_site(root, machines=machines)
  233. fails_with(root, capsys, "twingate-connector module block(s)")
  234. def test_instance_count_reconciles_with_matching_machines(tmp_path, capsys):
  235. root = add_and_cap(tmp_path, 24.0)
  236. code, _, err = run(root, capsys)
  237. assert code == 0, err
  238. def test_base_stack_reconciliation_is_unchanged_by_instances(tmp_path, capsys):
  239. root = build(tmp_path, do_cap=40.0)
  240. add_site(root)
  241. write_json(root / "stacks/10-access/cost.json", {"resources": droplets(3)})
  242. fails_with(
  243. root, capsys, "stacks/10-access: 2 twingate-connector module block(s) but 3"
  244. )
  245. # ---- ids and the config.yml mapping -------------------------------------------
  246. def test_stack_id_mapping_rule():
  247. f = cost_check.stack_id
  248. assert f("stacks/10-access", None) == "cah-10-access"
  249. assert f("stacks/00-foundation", None) == "cah-00-foundation"
  250. assert f("stacks/aws/10-access", None) == "cah-aws-10-access"
  251. assert f("stacks/sites/tor2/10-access", "stacks/10-access") == "cah-10-access-tor2"
  252. assert (
  253. f("stacks/sites/east/aws/10-access", "stacks/aws/10-access")
  254. == "cah-aws-10-access-east"
  255. )
  256. def test_two_manifests_for_one_stack_id_fail(tmp_path, capsys):
  257. root = build(tmp_path, do_cap=40.0)
  258. add_site(root)
  259. # A base stack literally named 10-access-tor2 claims the same id.
  260. write_json(root / "stacks/10-access-tor2/cost.json", {"resources": []})
  261. fails_with(root, capsys, "duplicate stack id cah-10-access-tor2")
  262. def config_problems(root):
  263. """The design's test, now also part of the gate itself."""
  264. return cost_check.config_problems(root)
  265. def write_config(root, *ids):
  266. p = root / ".spacelift/config.yml"
  267. p.parent.mkdir(parents=True, exist_ok=True)
  268. p.write_text(
  269. yaml.safe_dump(
  270. {"version": "1", "stacks": {i: {"before_init": []} for i in ids}}
  271. )
  272. )
  273. def test_every_real_config_stack_has_exactly_one_manifest():
  274. assert config_problems(ROOT) == []
  275. def test_config_entries_for_a_base_and_an_instance_each_match_one_manifest(tmp_path):
  276. root = build(tmp_path, do_cap=24.0)
  277. add_site(root)
  278. write_config(root, "cah-10-access", "cah-10-access-tor2")
  279. assert config_problems(root) == []
  280. def test_config_entry_with_no_manifest_fails(tmp_path):
  281. root = build(tmp_path, do_cap=24.0)
  282. write_config(root, "cah-10-access", "cah-10-access-tor2")
  283. assert config_problems(root) == [
  284. ".spacelift/config.yml stack id cah-10-access-tor2 has 0 manifest(s), expected exactly 1"
  285. ]
  286. def test_config_entry_with_two_manifests_fails(tmp_path):
  287. root = build(tmp_path, do_cap=40.0)
  288. add_site(root)
  289. write_json(root / "stacks/10-access-tor2/cost.json", {"resources": []})
  290. write_config(root, "cah-10-access-tor2")
  291. assert config_problems(root) == [
  292. ".spacelift/config.yml stack id cah-10-access-tor2 has 2 manifest(s), expected exactly 1"
  293. ]
  294. def test_an_instance_without_instance_of_matches_no_id(tmp_path):
  295. root = build(tmp_path, do_cap=24.0)
  296. add_site(root, instance_of=None)
  297. write_config(root, "cah-10-access-tor2")
  298. assert config_problems(root) != []
  299. # ---- per-provider sites map ---------------------------------------------------
  300. def sites_repo(tmp_path, cap, sites, *keys):
  301. root = build(tmp_path, do_cap=cap, sites=sites)
  302. for k in keys:
  303. add_site(root, key=k)
  304. return root
  305. def test_site_missing_from_a_present_map_fails(tmp_path, capsys):
  306. root = sites_repo(
  307. tmp_path, 24.0, {"tor3": {"approved_monthly_total": 12.0}}, "tor2"
  308. )
  309. fails_with(
  310. root, capsys, "site tor2 has a manifest but is not in the approved sites map"
  311. )
  312. def test_site_in_the_map_passes(tmp_path, capsys):
  313. root = sites_repo(
  314. tmp_path, 24.0, {"tor2": {"approved_monthly_total": 12.0}}, "tor2"
  315. )
  316. code, _, err = run(root, capsys)
  317. assert code == 0, err
  318. def test_site_over_its_own_approved_total_fails(tmp_path, capsys):
  319. root = sites_repo(tmp_path, 30.0, {"tor2": {"approved_monthly_total": 6.0}}, "tor2")
  320. fails_with(
  321. root,
  322. capsys,
  323. "digitalocean: site tor2 planned $12.00 is above its approved $6.00",
  324. )
  325. def test_sites_summing_above_the_provider_figure_fail(tmp_path, capsys):
  326. root = sites_repo(
  327. tmp_path,
  328. 20.0,
  329. {
  330. "tor2": {"approved_monthly_total": 12.0},
  331. "tor3": {"approved_monthly_total": 12.0},
  332. },
  333. "tor2",
  334. )
  335. fails_with(
  336. root,
  337. capsys,
  338. "approved sites add up to $24.00, above the provider approved $20.00",
  339. )
  340. def test_base_stack_must_fit_provider_figure_minus_sites(tmp_path, capsys):
  341. # Provider 20, site tor2 approved 12: the base stack (12) has only 8.
  342. root = sites_repo(
  343. tmp_path, 20.0, {"tor2": {"approved_monthly_total": 12.0}}, "tor2"
  344. )
  345. fails_with(
  346. root,
  347. capsys,
  348. "base stacks planned $12.00 are above approved $20.00 minus sites $12.00",
  349. )
  350. def test_without_a_map_behaviour_is_unchanged(tmp_path, capsys):
  351. root = sites_repo(tmp_path, 24.0, None, "tor2", "tor3")
  352. fails_with(root, capsys, "planned $36.00 is above approved $24.00")
  353. @pytest.mark.parametrize(
  354. "sites",
  355. [
  356. [],
  357. {"tor2": 12.0},
  358. {"tor2": {}},
  359. {"tor2": {"approved_monthly_total": -1}},
  360. {"tor2": {"approved_monthly_total": "12"}},
  361. {"tor2": {"approved_monthly_total": float("nan")}},
  362. {"Tor 2": {"approved_monthly_total": 1.0}},
  363. ],
  364. )
  365. def test_malformed_sites_map_fails_closed(tmp_path, capsys, sites):
  366. root = build(tmp_path, do_cap=24.0, sites=sites)
  367. add_site(root)
  368. code, _, err = run(root, capsys)
  369. assert code == 1, err
  370. def test_active_ceiling_uses_the_provider_figure_not_the_sites(tmp_path, capsys):
  371. # Provider 24 (sites 12 inside it) + another active provider 12 = 36 > 30.
  372. root = build(
  373. tmp_path,
  374. do_cap=24.0,
  375. sites={"tor2": {"approved_monthly_total": 12.0}},
  376. extra_providers={"gcp": {"approved_monthly_total": 12.0, "active": True}},
  377. )
  378. add_site(root)
  379. fails_with(
  380. root, capsys, "the approved figures of the active providers add up to $36.00"
  381. )
  382. def test_real_repo_still_passes_with_no_instances(capsys):
  383. code, out, err = run(ROOT, capsys)
  384. assert code == 0, err
  385. assert "digitalocean: planned $12.00/mo, approved $12.00" in out
  386. assert not (ROOT / "stacks/sites").exists()