forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiBe869379Tahinli27 days ago290 commits

mock.py194 lines, 8.7 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Fills a seeded audit server with what seed.py cannot make without real runners: runners in every
3state, a history of finished, failed, running and cancelled CI runs with steps and logs, and an hour of
4host samples behind the runner graphs.
5
6Usage: scripts/audit/mock.py OUT_DIR db with the server stopped, as it holds the database
7 scripts/audit/mock.py OUT_DIR samples with the server up
8"""
9import hashlib
10import json
11import math
12import os
13import random
14import secrets
15import sqlite3
16import sys
17import time
18import urllib.request
19
20out, phase = sys.argv[1], sys.argv[2]
21seed = json.load(open(os.path.join(out, "seed.json")))
22data = os.path.join(out, "data")
23SECRET = "mock-runner-secret"
24random.seed(7)
25now = time.time()
26
27
28def stamp(t):
29 return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(t)) + ".000000000Z"
30
31
32def uid():
33 alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
34 return "01MOCK" + "".join(random.choice(alphabet) for _ in range(20))
35
36
37def fill_database():
38 db = sqlite3.connect(os.path.join(data, "forge.db"), timeout=30)
39 db.row_factory = sqlite3.Row
40 # Runners: two online, one busy, one offline, one disabled. The mock ones go first: they are older
41 # than the seeded runner, which is the one to keep.
42 db.execute("delete from ci_runners where id like '01MOCK%'")
43 first = db.execute("select id from ci_runners order by created_at limit 1").fetchone()["id"]
44 db.execute(
45 "update ci_runners set name='build-01', labels='[\"linux\",\"x86_64\",\"large\"]', secret_hash=?, last_seen_at=?,"
46 " reported_concurrency=4, reported_version='0.9.2', reported_cpus=16, reported_memory_bytes=68719476736,"
47 " reported_build='949180b', reported_memory_free=41000000000, reported_memory_budget=60000000000 where id=?",
48 (hashlib.sha256(SECRET.encode()).hexdigest(), stamp(now - 3), first),
49 )
50 runners = [first]
51 for name, labels, seen, disabled, cpus, memory in [
52 ("build-02", '["linux","x86_64"]', now - 8, 0, 8, 34359738368),
53 ("arm-builder", '["linux","arm64"]', now - 40, 0, 4, 17179869184),
54 ("old-mac", '["macos","arm64"]', now - 86400 * 3, 0, 8, 17179869184),
55 ("retired-box", '["linux","x86_64"]', now - 86400 * 20, 1, 2, 8589934592),
56 ]:
57 rid = uid()
58 runners.append(rid)
59 db.execute(
60 "insert into ci_runners (id,name,labels,secret_hash,created_at,last_seen_at,disabled,reported_concurrency,"
61 "reported_version,reported_cpus,reported_memory_bytes) values (?,?,?,?,?,?,?,?,?,?,?)",
62 (rid, name, labels, secrets.token_hex(32), stamp(now - 86400 * 40), stamp(seen), disabled, 2, "0.9.2", cpus, memory),
63 )
64
65 # Runs: the newest last, as the numbers go up.
66 repo = db.execute(
67 "select r.id from repos r join users u on u.id=r.owner_id where r.name=? and u.username=?",
68 (seed["repo"], seed["admin"]),
69 ).fetchone()["id"]
70 actor = db.execute("select id from users where username=?", (seed["admin"],)).fetchone()["id"]
71 head = seed["head_oid"]
72 first_oid = seed["first_oid"]
73 db.execute("delete from ci_job_steps where job_id like '01MOCK%'")
74 db.execute("delete from ci_jobs where id like '01MOCK%'")
75 db.execute("delete from ci_runs where id like '01MOCK%'")
76 number = (db.execute("select max(number) n from ci_runs where repo_id=?", (repo,)).fetchone()["n"] or 0) + 1
77 JOBS = {
78 "test": ["Checkout", "Unit tests", "E2E tests"],
79 "lint": ["Checkout", "Clippy", "Format"],
80 "package": ["Build", "Package"],
81 }
82 PLAN = [
83 "success", "success", "failure", "success", "cancelled", "success", "success", "failure",
84 "success", "success", "success", "running",
85 ]
86 LOG = """{step}
87 Compiling forge-core v0.9.2
88 Compiling forge-git v0.9.2
89 Compiling forge-web v0.9.2
90 Finished `dev` profile in 41.08s
91 Running unittests src/lib.rs
92 running 214 tests
93 test store::ci::tests::a_requeued_job_starts_with_no_steps ... ok
94 test store::ci::tests::steps_take_the_jobs_result ... ok
95 test wiki_e2e::follows_a_push ... {result}
96 """
97 logs = os.path.join(data, "ci", "logs")
98 os.makedirs(logs, exist_ok=True)
99 failed_run = None
100 running_run = None
101 for i, state in enumerate(PLAN):
102 start = now - (len(PLAN) - i) * 3600 * 2
103 run_id = uid()
104 took = random.randint(420, 1500)
105 finished = None if state == "running" else stamp(start + took)
106 db.execute(
107 "insert into ci_runs (id,repo_id,number,trigger,git_ref,commit_oid,actor_id,state,created_at,finished_at)"
108 " values (?,?,?,?,?,?,?,?,?,?)",
109 (run_id, repo, number, "push", "refs/heads/main", head if i % 2 else first_oid, actor, state, stamp(start), finished),
110 )
111 if state == "failure":
112 failed_run = number
113 if state == "running":
114 running_run = number
115 start = now - 420
116 for j, (name, steps) in enumerate(JOBS.items()):
117 job_id = uid()
118 job_state = state
119 if state == "failure" and name != "test":
120 job_state = "success" if name == "lint" else "skipped"
121 if state == "running" and name == "package":
122 job_state = "blocked"
123 if state == "running" and name == "lint":
124 job_state = "success"
125 began = start + j * 20
126 length = took // len(JOBS)
127 ended = None if job_state in ("running", "blocked") else stamp(began + length)
128 lines = []
129 offset = 0
130 step_rows = []
131 for k, step in enumerate(steps):
132 step_start = began + k * length // len(steps)
133 bad = job_state == "failure" and k == len(steps) - 1
134 live = job_state == "running" and k == len(steps) - 1
135 text = "::group::" + step + "\n" + LOG.format(step="$ " + step.lower(), result="FAILED" if bad else "ok")
136 if bad:
137 text += "error: stream closed before the push event arrived\n --> crates/forge-e2e/tests/e2e/wiki_e2e.rs:212:9\n"
138 text += "::endgroup::\n"
139 step_rows.append((job_id, k, step, stamp(step_start), None if live or bad else stamp(step_start + length // len(steps)), offset))
140 offset += len(text.encode())
141 lines.append(text)
142 body = "".join(lines) if job_state not in ("blocked", "skipped") else ""
143 db.execute(
144 "insert into ci_jobs (id,run_id,name,spec,state,runner_id,exit_code,queued_at,started_at,finished_at,heartbeat_at,log_bytes,step_scanned)"
145 " values (?,?,?,?,?,?,?,?,?,?,?,?,?)",
146 (job_id, run_id, name, '{"image":"docker.io/library/rust:1","run":"cargo test","needs":[],"secrets":[],"env":{},"artifacts":[],"runs_on":[],"cache":[],"timeout_minutes":60,"network":true}',
147 job_state, runners[j % 2] if job_state != "blocked" else None, 1 if job_state == "failure" else 0, stamp(began - 5), stamp(began), ended,
148 stamp(now) if job_state == "running" else None, len(body.encode()), len(body.encode())),
149 )
150 if body:
151 db.executemany("insert into ci_job_steps (job_id,seq,name,started_at,finished_at,log_offset) values (?,?,?,?,?,?)", step_rows)
152 with open(os.path.join(logs, job_id + ".log"), "w") as f:
153 f.write(body)
154 number += 1
155 db.commit()
156
157 seed["runner_id"] = first
158 seed["failed_run"] = failed_run
159 seed["running_run"] = running_run
160 seed["runners"] = runners
161 json.dump(seed, open(os.path.join(out, "seed.json"), "w"))
162 print(f"[mock] done: failed #{failed_run}, running #{running_run}")
163
164
165def send_samples():
166 # An hour of samples behind the graphs: the server keeps them in memory, so they go in as a runner's would.
167 samples = []
168 for m in range(0, 3600, 10):
169 t = now - 3600 + m
170 wave = (math.sin(m / 400) + 1) / 2
171 samples.append({
172 "at_ms": int(t * 1000),
173 "cpu_percent": round(15 + 70 * wave + random.uniform(-5, 5), 1),
174 "mem_used_bytes": int((18 + 22 * wave) * 2**30),
175 "mem_total_bytes": 64 * 2**30,
176 "net_rx_bytes_per_s": int((2 + 40 * wave) * 2**20),
177 "net_tx_bytes_per_s": int((1 + 12 * wave) * 2**20),
178 "running_jobs": int(wave * 4),
179 })
180 request = urllib.request.Request(
181 seed["base"] + "/api/v1/ci/runners/metrics",
182 json.dumps({"samples": samples}).encode(),
183 {"Content-Type": "application/json", "Authorization": "Bearer " + SECRET},
184 )
185 try:
186 print("[mock] samples", urllib.request.urlopen(request).status)
187 except OSError as e:
188 print("[mock] samples failed:", e)
189
190
191if phase == "db":
192 fill_database()
193else:
194 send_samples()