Zoo

← back to the zoo

22. The zoo checks itself

Every self-running exhibit is rechecked on a schedule, and the front page says when.

The zoo is an ordinary app: a five-minute job re-runs its exhibits and stores the results, and root's hourly check of the platform arrives in the fact platform.json.

This is the code serving the zoo right now: the bytes this very program was built from (each file is embedded when the zoo is compiled), at commit 55c71513c5 (live). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.

e22_checks_itself.odin sha256 66c59a481299 · raw

1package main
2
3// Exhibit 22. The `selfcheck` job runs every five minutes (ratcloud.conf) and re-runs every
4// self-running exhibit's check, storing each result in zoo.db. The lights on this page are that stored
5// data, never live requests. It also reads root's own hourly check of the back of house, which root
6// publishes into the fact platform.json.
7
8import "core:fmt"
9import "core:strings"
10import "ratcloud:rc"
11
12Boh_Line :: struct {
13	line, status, detail: string,
14}
15
16back_of_house :: proc() -> (at: i64, lines: []Boh_Line, ok: bool) {
17	c := jget(fact("platform.json"), "check")
18	if c == nil do return 0, nil, false
19	out := make([dynamic]Boh_Line)
20	// Lines marked "(exhibit N)" are root's view of an exhibit that has its own card.
21	for l in jarr(c, "checks") {
22		line := jstr(l, "line")
23		if strings.has_prefix(line, "(exhibit") do continue
24		append(&out, Boh_Line{line, jstr(l, "status"), jstr(l, "detail")})
25	}
26	return parse_time(jstr(c, "at")), out[:], true
27}
28
29e22 :: proc() -> Exhibit {
30	return {
31		n = 22, wing = "Operations",
32		title = "The zoo checks itself",
33		promise = "Every self-running exhibit is rechecked on a schedule, and the front page says when.",
34		block = "The zoo is an ordinary app: a five-minute job re-runs its exhibits and stores the results, and root's hourly check of the platform arrives in the fact platform.json.",
35		src = {"e22_checks_itself.odin", #load("e22_checks_itself.odin", string)},
36		files = srcs(SELF_SRC),
37		show = proc(me: ^rc.User) -> string {
38			b := strings.builder_make()
39			ms := meta_int("checked_ms")
40			rc.render_to(&b, "<p>Checked <b>{{1}}</b>{{2}}.</p>", {{"1", rc.raw(ago(meta_int("checked_at")))}, {"2", fmt.tprintf(" (took %.1f s)", f64(ms) / 1000) if ms > 0 else ""}})
41			at, lines, ok := back_of_house()
42			if !ok {
43				strings.write_string(&b, `<p class="muted">Root's check of the back of house is not published to apps yet (the fact platform.json is missing).</p>`)
44				return strings.to_string(b)
45			}
46			rc.render_to(&b, `<p>The back of house, checked by root {{1}}:</p><ul class="list">`, {{"1", rc.raw(ago(at))}})
47			for l in lines do rc.render_to(&b, `<li><span class="tag {{1}}">{{2}}</span><span>{{3}} <small class="muted">{{4}}</small></span></li>`, {{"1", "ok" if l.status == "pass" else "bad"}, {"2", l.status}, {"3", l.line}, {"4", l.detail}})
48			strings.write_string(&b, "</ul>")
49			return strings.to_string(b)
50		},
51		// Runs last in the selfcheck job, after every other exhibit.
52		check = proc() -> Check {
53			red := make([dynamic]string)
54			for &e in exhibits() do if e.n != 22 && e.kind == "self" && light(&e).color == "red" do append(&red, itoa(i64(e.n)))
55			at, lines, ok := back_of_house()
56			if !ok do return fail("root's back-of-house check is not readable: the fact platform.json is missing")
57			// The same age root's tick and the alerts call stale (ROOT_CHECK_MAX_HOURS, zoo.odin, says why).
58			if now() - at > ROOT_CHECK_MAX_HOURS * 3600 do return fail(fmt.tprintf("root's back-of-house check is %.1f hours old (root checks hourly)", f64(now() - at) / 3600))
59			bad := make([dynamic]string)
60			for l in lines do if l.status != "pass" do append(&bad, l.line)
61			if len(bad) > 0 do return fail(cat("back of house: ", strings.join(bad[:], "; ")))
62			if len(red) > 0 do return fail(cat("red: exhibit", "s " if len(red) > 1 else " ", strings.join(red[:], ", ")))
63			return pass(fmt.tprintf("every self-running exhibit is green, and root's %d back-of-house lines pass", len(lines)))
64		},
65	}
66}

main.odin sha256 0eb573c11997 · raw

1package main
2
3// The zoo: every promise in ZOO.md as an exhibit, working live, with a light. Odin on the wasm
4// runtime: one fresh instance per request and per job run.
5//
6//   /                    every exhibit and its light
7//   /api/<n>/<do>        an exhibit's JSON (check: run its check now; seen: "this worked for me")
8//   /how/<n>             the exhibit's source, the bytes this very program was built from (exhibit 19)
9//   /lights.json         every light, for tests and anyone curious
10//   /index.txt           one line per exhibit (promise and building block), for a model's brief
11//   /how/<n>.txt         exhibit n's files as plain text
12//   /platform.md         what an app gets: root's PLATFORM.md, the running version, for anyone
13//
14// nginx also asks whether a browser may listen on an `auth` channel (channel_ok); and the host runs
15// the jobs of ratcloud.conf's `cron` (job): tick, selfcheck, nightly, workbench.
16
17import "core:encoding/json"
18import "core:fmt"
19import "core:strings"
20import "core:time"
21import "ratcloud:rc"
22
23main :: proc() {
24	rc.serve(handle, channel_ok, job)
25}
26
27SELF_SRC :: Src{"main.odin", #load("main.odin", string)}
28
29channel_ok :: proc(r: ^rc.Request, channel, id: string) -> bool {
30	u, signed := rc.me()
31	me := &u if signed else nil
32	for &e in exhibits() {
33		if e.channel == nil do continue
34		if allow, mine := e.channel(channel, id, me); mine do return allow
35	}
36	return false
37}
38
39g_req: ^rc.Request
40
41handle :: proc(r: ^rc.Request, w: ^rc.Response) {
42	g_req = r
43	defer robot_done()
44	u, signed := rc.me()
45	me := &u if signed else nil
46	path := r.path
47
48	if strings.has_prefix(path, "/api/") {
49		api(r, w, me)
50		return
51	}
52	if strings.has_prefix(path, "/how/") {
53		rest := path[5:]
54		if strings.has_suffix(rest, ".txt") {how_txt(w, int(atoi(rest[:len(rest) - 4]))); return}
55		how_page(r, w, int(atoi(rest)), me)
56		return
57	}
58	switch path {
59	case "/": page(w, me); return
60	case "/lights.json": lights_json(w); return
61	case "/index.txt":
62		// A model's brief lists the exhibits, one line each.
63		rc.set_header(w, "Content-Type", "text/plain; charset=utf-8")
64		rc.set_header(w, "Cache-Control", "max-age=300")
65		for e in exhibits() do rc.write(w, fmt.tprintf("%d. %s (%s%s): %s\n", e.n, e.title, e.wing, ", not built yet" if e.kind == "waiting" else "", e.block))
66		return
67	case "/platform.md":
68		// Root publishes PLATFORM.md into every app's facts; the zoo, being the documentation, serves
69		// its copy so a model working in a clone (no facts there) reads the version that is running.
70		doc, ok := rc.fact("PLATFORM.md")
71		rc.status(w, 200 if ok else 404)
72		rc.set_header(w, "Content-Type", "text/markdown; charset=utf-8")
73		rc.set_header(w, "Cache-Control", "max-age=300")
74		rc.write(w, doc if ok else "PLATFORM.md is not published here yet.\n")
75		return
76	}
77	rc.status(w, 404)
78	rc.set_header(w, "Cache-Control", "no-store")
79	rc.render(w, NOT_FOUND_HTML, {{"head", rc.raw(rc_head())}, {"header", rc.raw(rc_header("Zoo", me, "/api/3/signout", false))}})
80}
81
82NOT_FOUND_HTML :: `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Not found · Zoo</title>{{head}}</head><body>{{header}}<main class="rc-main"><div class="rc-empty"><b>Nothing here</b><p>The zoo has no page at this address.</p><a class="button primary" href="/">Go to the zoo</a></div></main></body></html>`
83
84// ---- /api/<n>/<do> ----
85
86Api :: struct {
87	r:    ^rc.Request,
88	w:    ^rc.Response,
89	do_:  string,
90	me:   ^rc.User,
91	post: bool,
92	in_:  json.Value, // the POST's JSON body, or the query as an object of strings
93}
94
95reply :: proc(a: ^Api, v: any, status := 200) {
96	rc.status(a.w, status)
97	rc.set_header(a.w, "Cache-Control", "no-store")
98	rc.set_header(a.w, "Content-Type", "application/json")
99	rc.write(a.w, to_json(v))
100	rc.write(a.w, "\n")
101}
102reply_raw :: proc(a: ^Api, json_text: string, status := 200) {
103	rc.status(a.w, status)
104	rc.set_header(a.w, "Cache-Control", "no-store")
105	rc.set_header(a.w, "Content-Type", "application/json")
106	rc.write(a.w, json_text)
107	rc.write(a.w, "\n")
108}
109reply_err :: proc(a: ^Api, status: int, msg: string) {
110	reply_raw(a, fmt.tprintf(`{{"error":%s}}`, jq(msg)), status)
111}
112in_str :: proc(a: ^Api, k: string) -> string {return jstr(a.in_, k)}
113in_int :: proc(a: ^Api, k: string) -> i64 {return jint(a.in_, k)}
114
115api :: proc(r: ^rc.Request, w: ^rc.Response, me: ^rc.User) {
116	a := Api{r = r, w = w, me = me, post = r.method == "POST"}
117	rest := r.path[5:]
118	slash := strings.index_byte(rest, '/')
119	if slash < 0 {reply_err(&a, 404, "no such exhibit"); return}
120	n := int(atoi(rest[:slash]))
121	a.do_ = rest[slash + 1:]
122	e, ok := exhibit(n)
123	if !ok || itoa(i64(n)) != rest[:slash] {reply_err(&a, 404, "no such exhibit"); return}
124	if !rc.csrf_ok(r) {reply_err(&a, 403, "refused: not from the zoo's own page"); return}
125	if a.post {
126		body, _ := rc.body(r)
127		if v, err := json.parse(body, parse_integers = true); err == nil do a.in_ = v
128	} else {
129		o := make(json.Object)
130		for k, v in rc.query(r) do o[k] = json.String(v)
131		a.in_ = o
132	}
133	if a.do_ == "check" && e.check != nil {
134		// POST runs it now, unless it ran (or started) in the last 15 seconds: anyone can press this,
135		// and a run costs a robot sign-in, a model call, B2 and push. The slot is taken atomically, so
136		// a burst runs it once. GET (an <img> anywhere) only reads the light.
137		if a.post && claim_check(e.n, 15) do run_check(e)
138		s, found := stored(e.n)
139		if !found {
140			reply_raw(&a, fmt.tprintf(`{{"n":%d,"title":%s,"ok":false,"detail":"not checked yet","at":null,"data":null}}`, e.n, jq(e.title)))
141			return
142		}
143		reply_raw(&a, fmt.tprintf(`{{"n":%d,"title":%s,"ok":%v,"detail":%s,"at":%s,"data":%s}}`, e.n, jq(e.title), s.ok, jq(s.detail), jq(iso(s.at)), s.data if s.data != "" else "null"))
144		return
145	}
146	if a.do_ == "seen" && a.post && e.kind == "human" {
147		if me == nil {reply_err(&a, 401, "sign in first, so the zoo can say who saw it work"); return}
148		seen(e.n, me.id)
149		l := light(e)
150		reply_raw(&a, fmt.tprintf(`{{"ok":true,"light":{{"color":%s,"text":%s}}}}`, jq(l.color), jq(l.text)))
151		return
152	}
153	if e.api != nil && e.api(&a) do return
154	reply_err(&a, 404, fmt.tprintf("exhibit %d has no '%s'", e.n, a.do_))
155}
156
157// ---- /lights.json ----
158
159lights_json :: proc(w: ^rc.Response) {
160	b := strings.builder_make()
161	checked := meta_int("checked_at")
162	fmt.sbprintf(&b, `{{"env":%s,"checked":%s,"lights":[`, jq(env().env), jq(iso(checked)) if checked > 0 else "null")
163	for &e, i in exhibits() {
164		l := light(&e)
165		if i > 0 do strings.write_byte(&b, ',')
166		fmt.sbprintf(&b, `{{"n":%d,"title":%s,"kind":%s,"color":%s,"text":%s,"at":%s}}`, e.n, jq(e.title), jq(e.kind), jq(l.color), jq(l.text), jq(iso(l.at)) if l.at > 0 else "null")
167	}
168	strings.write_string(&b, `],"alerts":[`)
169	for x, i in alerts_recent(10) {
170		if i > 0 do strings.write_byte(&b, ',')
171		fmt.sbprintf(&b, `{{"at":%s,"kind":%s,"title":%s,"body":%s,"results":%s}}`, jq(iso(x.at)), jq(x.kind), jq(x.title), jq(x.body), x.results)
172	}
173	strings.write_string(&b, "]}\n")
174	rc.set_header(w, "Content-Type", "application/json")
175	rc.set_header(w, "Cache-Control", "no-store")
176	rc.write(w, strings.to_string(b))
177}
178
179// ---- the jobs (ratcloud.conf `cron`): the host runs each in a fresh instance on its schedule ----
180
181job :: proc(name: string, w: ^rc.Response) {
182	defer robot_done()
183	switch name {
184	case "tick":
185		// Exhibit 21: write the time. That is all.
186		meta_set("last_tick", itoa(now()))
187	case "selfcheck":
188		selfcheck(w)
189	case "nightly":
190		// Exhibit 8's upkeep: if a valid push replaced zoo-broken's deliberate typo, put it back.
191		res := broken_reassert()
192		res.at = now()
193		meta_set("broken.nightly", to_json(res))
194		rc.write(w, fmt.tprintf("exhibit 8 upkeep (%s): %s: %s\n", res.branch, res.result, res.detail))
195		if res.result != "still refused" && res.result != "put back" do rc.status(w, 500)
196	case "workbench":
197		// Exhibit 25's run in the robot's workbench: at most once a day, live only.
198		if said, did := e25_job(); did {
199			rc.write(w, said)
200			rc.write(w, "\n")
201			if strings.contains(said, "FAILED") do rc.status(w, 500)
202		}
203	case:
204		rc.status(w, 404)
205		rc.write(w, fmt.tprintf("no job %q\n", name))
206	}
207}
208
209// Exhibit 22's job: every five minutes, run every self-running exhibit's check and store the results
210// as lights. Exhibit 22 runs last, since it judges the others.
211selfcheck :: proc(w: ^rc.Response) {
212	t0 := time.tick_now()
213	g_in_job = true
214	last: ^Exhibit
215	for &e in exhibits() {
216		if e.n == 22 {last = &e; continue}
217		if e.check == nil || e.kind != "self" do continue
218		r := run_check(&e)
219		if !r.ok do rc.write(w, fmt.tprintf("exhibit %d: %s\n", r.n, r.detail))
220	}
221	if last != nil {
222		r := run_check(last)
223		if !r.ok do rc.write(w, fmt.tprintf("exhibit %d: %s\n", r.n, r.detail))
224	}
225	alerts_run(w)
226	meta_set("checked_at", itoa(now()))
227	meta_set("checked_ms", itoa(i64(time.duration_milliseconds(time.tick_since(t0)))))
228	rc.write(w, fmt.tprintf("checked in %d ms, memory %d KiB\n", i64(time.duration_milliseconds(time.tick_since(t0))), rc.bump_top() / 1024))
229}
230
231// The five-minute job, not a "check now" from the page (PHP's PHP_SAPI === "cli"): the rounds that
232// take minutes (18, 29, 30) start only here, where the job's own time allows them.
233g_in_job: bool