cost_raise.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #!/usr/bin/env python3
  2. """Propose (or make) a change to one phase's cost ceiling in approved.json.
  3. python3 -I scripts/cost_raise.py --phase stage-3 --ceiling 36 --reason 'why'
  4. By default this is a dry run: it prints the diff of docs/stages/approved.json
  5. that the change would make and the problems the cost gate finds in the result.
  6. With --write it edits the file, but only when the gate's checks pass.
  7. It changes the phase entry (ceiling, reason, decided) and, with --make-current,
  8. which phase is current. It never touches a provider's approved_monthly_total:
  9. raise that separately, in the same pull request, so a reviewer sees both
  10. numbers. A new phase id is appended (or placed with --after). A ceiling lower
  11. than the phase before it needs --lowers. See docs/cost.md, "To raise the
  12. ceiling".
  13. """
  14. from __future__ import annotations
  15. import argparse
  16. import contextlib
  17. import copy
  18. import datetime
  19. import difflib
  20. import fcntl
  21. import hashlib
  22. import importlib.util
  23. import json
  24. import math
  25. import os
  26. import sys
  27. import tempfile
  28. from pathlib import Path
  29. APPROVED = "docs/stages/approved.json"
  30. def load_gate():
  31. """The cost gate module, imported by path (the script runs under python -I)."""
  32. path = Path(__file__).resolve().parent / "cost_check.py"
  33. spec = importlib.util.spec_from_file_location("cost_check", path)
  34. module = importlib.util.module_from_spec(spec)
  35. spec.loader.exec_module(module)
  36. return module
  37. def render(doc):
  38. return json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
  39. def propose(approved, phase, ceiling, reason, decided, *, make_current=False,
  40. lowers=False, after=None, cascade=False): # fmt: skip
  41. """A new approved.json document with the phase set; the input is untouched."""
  42. doc = copy.deepcopy(approved)
  43. if "phases" not in doc:
  44. raise ValueError(
  45. "approved.json has no phases map (legacy top-level ceiling); migrate it first"
  46. )
  47. phases = doc["phases"]
  48. entry = {"ceiling": ceiling, "reason": reason, "decided": decided}
  49. if phase in phases:
  50. old = phases[phase]
  51. entry["status"] = old.get("status", "planned")
  52. else:
  53. entry["status"] = "planned"
  54. if lowers:
  55. entry["lowers"] = True
  56. if phase in phases:
  57. phases[phase] = entry
  58. elif after is not None:
  59. if after not in phases:
  60. raise ValueError(f"--after {after}: no such phase")
  61. rebuilt = {}
  62. for key, value in phases.items():
  63. rebuilt[key] = value
  64. if key == after:
  65. rebuilt[phase] = entry
  66. doc["phases"] = rebuilt
  67. else:
  68. phases[phase] = entry
  69. if cascade:
  70. # Walk the phases after the edited one in order. A phase that would now
  71. # be a quiet decrease is raised to its predecessor; a deliberate
  72. # decrease ("lowers") is kept while it still is one, and its flag is
  73. # dropped only when it no longer goes below its predecessor.
  74. seen, prev = False, None
  75. for key, value in doc["phases"].items():
  76. if key == phase:
  77. seen, prev = True, ceiling
  78. continue
  79. if not seen:
  80. continue
  81. own = value.get("ceiling")
  82. if isinstance(own, bool) or not isinstance(own, (int, float)):
  83. prev = None
  84. continue
  85. if prev is not None:
  86. if value.get("lowers"):
  87. if own >= prev:
  88. value.pop("lowers")
  89. elif own < prev:
  90. value["ceiling"] = prev
  91. value["reason"] = (
  92. f"{str(value.get('reason', '')).rstrip()} "
  93. f"Raised to ${prev:.2f} together with {phase}."
  94. ).strip()
  95. value["decided"] = decided
  96. prev = value["ceiling"]
  97. if make_current:
  98. for key, value in doc["phases"].items():
  99. if value.get("status") == "current":
  100. value["status"] = "done"
  101. doc["phases"][phase]["status"] = "current"
  102. doc["current_phase"] = phase
  103. return doc
  104. class Conflict(Exception):
  105. """approved.json changed between reading it and writing it."""
  106. def digest(data):
  107. return hashlib.sha256(data).hexdigest()
  108. def inputs_digest(root):
  109. """One hash over everything the gate reads besides approved.json: the stacks
  110. and modules trees (manifests and OpenTofu files), the price tables and the
  111. Spacelift config. Used to notice that an input changed while a change was
  112. being validated."""
  113. root = Path(root)
  114. h = hashlib.sha256()
  115. files = []
  116. for top in ("stacks", "modules", "docs/cost-prices"):
  117. base = root / top
  118. if base.is_dir():
  119. files += [
  120. f
  121. for f in base.rglob("*")
  122. if f.is_file() and ".terraform" not in f.relative_to(root).parts
  123. ]
  124. for single in ("docs/cost-prices.json", ".spacelift/config.yml", APPROVED):
  125. if (root / single).is_file():
  126. files.append(root / single)
  127. for f in sorted(set(files)):
  128. h.update(f.relative_to(root).as_posix().encode() + b"\0")
  129. h.update(f.read_bytes() + b"\0")
  130. return h.hexdigest()
  131. @contextlib.contextmanager
  132. def locked(directory):
  133. """An exclusive advisory lock on a directory, so two cost_raise runs queue."""
  134. fd = os.open(directory, os.O_RDONLY)
  135. try:
  136. fcntl.flock(fd, fcntl.LOCK_EX)
  137. yield
  138. finally:
  139. os.close(fd)
  140. def replace_file(path, text, expected_digest, recheck=None):
  141. """Replace `path` with `text`. The caller holds the directory lock.
  142. Refuses if the file no longer has the content that was read, or if
  143. `recheck()` returns a message (a gate input changed). Writes a temporary
  144. file in the same directory, fsyncs it and renames it over the target."""
  145. if digest(path.read_bytes()) != expected_digest:
  146. raise Conflict(
  147. f"{path.name} changed since it was read; nothing written, run again"
  148. )
  149. if recheck is not None:
  150. message = recheck()
  151. if message:
  152. raise Conflict(message)
  153. mode = path.stat().st_mode & 0o7777
  154. fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
  155. try:
  156. with os.fdopen(fd, "w", encoding="utf-8") as handle:
  157. handle.write(text)
  158. handle.flush()
  159. os.fsync(handle.fileno())
  160. os.chmod(tmp, mode)
  161. os.replace(tmp, path)
  162. except BaseException:
  163. if os.path.exists(tmp):
  164. os.unlink(tmp)
  165. raise
  166. dirfd = os.open(path.parent, os.O_RDONLY)
  167. try:
  168. os.fsync(dirfd)
  169. finally:
  170. os.close(dirfd)
  171. def write_checked(path, text, expected_digest, recheck=None):
  172. """replace_file() under the directory lock."""
  173. with locked(path.parent):
  174. replace_file(path, text, expected_digest, recheck)
  175. def gate_problems(gate, root, doc):
  176. return gate.gate_problems(root, doc)[0]
  177. def effective(gate, doc):
  178. try:
  179. pid, ceiling, _ = gate.current_ceiling(doc)
  180. return f"phase {pid} ${ceiling:.2f}"
  181. except (ValueError, KeyError, TypeError):
  182. return "unreadable"
  183. def main(argv=None):
  184. parser = argparse.ArgumentParser(
  185. description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
  186. )
  187. parser.add_argument("--root", default=".")
  188. parser.add_argument("--phase", required=True, help="phase id, for example stage-3")
  189. parser.add_argument("--ceiling", required=True, type=float, help="dollars per month")
  190. parser.add_argument("--reason", required=True, help="why this ceiling")
  191. parser.add_argument("--decided", help="ISO date of the decision (default: today)")
  192. parser.add_argument(
  193. "--make-current",
  194. action="store_true",
  195. help="also make this phase the current one (the old current phase becomes done)",
  196. )
  197. parser.add_argument(
  198. "--lowers",
  199. action="store_true",
  200. help="this ceiling is deliberately lower than the phase before it",
  201. )
  202. parser.add_argument("--after", help="place a new phase after this phase id")
  203. parser.add_argument(
  204. "--cascade",
  205. action="store_true",
  206. help="also raise every later phase whose ceiling is now lower (each keeps its reason, with a note, and gets the new date); "
  207. "without it a raise that leaves a later phase lower fails the gate's no-quiet-decrease rule",
  208. )
  209. parser.add_argument("--write", action="store_true", help="edit the file (default: dry run)")
  210. args = parser.parse_args(argv)
  211. if not math.isfinite(args.ceiling) or args.ceiling < 0:
  212. print("cost-raise: --ceiling must be a finite number, zero or more", file=sys.stderr)
  213. return 2
  214. decided = args.decided or datetime.date.today().isoformat()
  215. root = Path(args.root)
  216. path = root / APPROVED
  217. lock = locked(path.parent) if args.write else contextlib.nullcontext()
  218. try:
  219. with lock:
  220. return run(args, gate_loader=load_gate, root=root, path=path, decided=decided)
  221. except (OSError, ValueError, KeyError, TypeError, AttributeError, OverflowError) as err:
  222. print(f"cost-raise: cannot propose the change: {err}", file=sys.stderr)
  223. return 1
  224. def run(args, *, gate_loader, root, path, decided):
  225. gate = gate_loader()
  226. raw = path.read_bytes()
  227. seen_inputs = inputs_digest(root)
  228. before = gate.parse_json(raw.decode("utf-8"))
  229. after = propose(
  230. before,
  231. args.phase,
  232. args.ceiling,
  233. args.reason,
  234. decided,
  235. make_current=args.make_current,
  236. lowers=args.lowers,
  237. after=args.after,
  238. cascade=args.cascade,
  239. )
  240. # Everything the gate itself checks, not just totals and approvals:
  241. # allowlist, structure, the config invariant, phases, then lifecycle.
  242. problems = gate_problems(gate, root, after)
  243. problems += gate.transition_problems(before, after)
  244. was, now = effective(gate, before), effective(gate, after)
  245. print(
  246. f"EFFECTIVE CEILING: {was} -> {now}"
  247. if was != now
  248. else f"EFFECTIVE CEILING: unchanged, {now}"
  249. )
  250. diff = "".join(
  251. difflib.unified_diff(
  252. render(before).splitlines(keepends=True),
  253. render(after).splitlines(keepends=True),
  254. fromfile=f"a/{APPROVED}",
  255. tofile=f"b/{APPROVED}",
  256. )
  257. )
  258. print(diff or "cost-raise: no change")
  259. for problem in problems:
  260. print(f"cost-raise: the gate would fail: {problem}", file=sys.stderr)
  261. if problems:
  262. return 1
  263. if args.write:
  264. def inputs_unchanged():
  265. if inputs_digest(root) != seen_inputs:
  266. return (
  267. "a file the cost gate reads changed while the change was being "
  268. "checked; nothing written, run again"
  269. )
  270. return None
  271. try:
  272. replace_file(path, render(after), digest(raw), inputs_unchanged)
  273. except (Conflict, OSError) as err:
  274. print(f"cost-raise: {err}", file=sys.stderr)
  275. return 1
  276. print(f"cost-raise: wrote {APPROVED}")
  277. else:
  278. print("cost-raise: dry run, nothing written (add --write)")
  279. print(
  280. "cost-raise: a provider's approved_monthly_total is not changed by this; "
  281. "raise it separately in the same pull request"
  282. )
  283. return 0
  284. if __name__ == "__main__":
  285. sys.exit(main())