#!/usr/bin/env python3 """Fills a seeded audit server with what seed.py cannot make without real runners: runners in every state, a history of finished, failed, running and cancelled CI runs with steps and logs, and an hour of host samples behind the runner graphs. Usage: scripts/audit/mock.py OUT_DIR db with the server stopped, as it holds the database scripts/audit/mock.py OUT_DIR samples with the server up """ import hashlib import json import math import os import random import secrets import sqlite3 import sys import time import urllib.request out, phase = sys.argv[1], sys.argv[2] seed = json.load(open(os.path.join(out, "seed.json"))) data = os.path.join(out, "data") SECRET = "mock-runner-secret" random.seed(7) now = time.time() def stamp(t): return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(t)) + ".000000000Z" def uid(): alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" return "01MOCK" + "".join(random.choice(alphabet) for _ in range(20)) def fill_database(): db = sqlite3.connect(os.path.join(data, "forge.db"), timeout=30) db.row_factory = sqlite3.Row # Runners: two online, one busy, one offline, one disabled. The mock ones go first: they are older # than the seeded runner, which is the one to keep. db.execute("delete from ci_runners where id like '01MOCK%'") first = db.execute("select id from ci_runners order by created_at limit 1").fetchone()["id"] db.execute( "update ci_runners set name='build-01', labels='[\"linux\",\"x86_64\",\"large\"]', secret_hash=?, last_seen_at=?," " reported_concurrency=4, reported_version='0.9.2', reported_cpus=16, reported_memory_bytes=68719476736," " reported_build='949180b', reported_memory_free=41000000000, reported_memory_budget=60000000000 where id=?", (hashlib.sha256(SECRET.encode()).hexdigest(), stamp(now - 3), first), ) runners = [first] for name, labels, seen, disabled, cpus, memory in [ ("build-02", '["linux","x86_64"]', now - 8, 0, 8, 34359738368), ("arm-builder", '["linux","arm64"]', now - 40, 0, 4, 17179869184), ("old-mac", '["macos","arm64"]', now - 86400 * 3, 0, 8, 17179869184), ("retired-box", '["linux","x86_64"]', now - 86400 * 20, 1, 2, 8589934592), ]: rid = uid() runners.append(rid) db.execute( "insert into ci_runners (id,name,labels,secret_hash,created_at,last_seen_at,disabled,reported_concurrency," "reported_version,reported_cpus,reported_memory_bytes) values (?,?,?,?,?,?,?,?,?,?,?)", (rid, name, labels, secrets.token_hex(32), stamp(now - 86400 * 40), stamp(seen), disabled, 2, "0.9.2", cpus, memory), ) # Runs: the newest last, as the numbers go up. repo = db.execute( "select r.id from repos r join users u on u.id=r.owner_id where r.name=? and u.username=?", (seed["repo"], seed["admin"]), ).fetchone()["id"] actor = db.execute("select id from users where username=?", (seed["admin"],)).fetchone()["id"] head = seed["head_oid"] first_oid = seed["first_oid"] db.execute("delete from ci_job_steps where job_id like '01MOCK%'") db.execute("delete from ci_jobs where id like '01MOCK%'") db.execute("delete from ci_runs where id like '01MOCK%'") number = (db.execute("select max(number) n from ci_runs where repo_id=?", (repo,)).fetchone()["n"] or 0) + 1 JOBS = { "test": ["Checkout", "Unit tests", "E2E tests"], "lint": ["Checkout", "Clippy", "Format"], "package": ["Build", "Package"], } PLAN = [ "success", "success", "failure", "success", "cancelled", "success", "success", "failure", "success", "success", "success", "running", ] LOG = """{step} Compiling forge-core v0.9.2 Compiling forge-git v0.9.2 Compiling forge-web v0.9.2 Finished `dev` profile in 41.08s Running unittests src/lib.rs running 214 tests test store::ci::tests::a_requeued_job_starts_with_no_steps ... ok test store::ci::tests::steps_take_the_jobs_result ... ok test wiki_e2e::follows_a_push ... {result} """ logs = os.path.join(data, "ci", "logs") os.makedirs(logs, exist_ok=True) failed_run = None running_run = None for i, state in enumerate(PLAN): start = now - (len(PLAN) - i) * 3600 * 2 run_id = uid() took = random.randint(420, 1500) finished = None if state == "running" else stamp(start + took) db.execute( "insert into ci_runs (id,repo_id,number,trigger,git_ref,commit_oid,actor_id,state,created_at,finished_at)" " values (?,?,?,?,?,?,?,?,?,?)", (run_id, repo, number, "push", "refs/heads/main", head if i % 2 else first_oid, actor, state, stamp(start), finished), ) if state == "failure": failed_run = number if state == "running": running_run = number start = now - 420 for j, (name, steps) in enumerate(JOBS.items()): job_id = uid() job_state = state if state == "failure" and name != "test": job_state = "success" if name == "lint" else "skipped" if state == "running" and name == "package": job_state = "blocked" if state == "running" and name == "lint": job_state = "success" began = start + j * 20 length = took // len(JOBS) ended = None if job_state in ("running", "blocked") else stamp(began + length) lines = [] offset = 0 step_rows = [] for k, step in enumerate(steps): step_start = began + k * length // len(steps) bad = job_state == "failure" and k == len(steps) - 1 live = job_state == "running" and k == len(steps) - 1 text = "::group::" + step + "\n" + LOG.format(step="$ " + step.lower(), result="FAILED" if bad else "ok") if bad: text += "error: stream closed before the push event arrived\n --> crates/forge-e2e/tests/e2e/wiki_e2e.rs:212:9\n" text += "::endgroup::\n" step_rows.append((job_id, k, step, stamp(step_start), None if live or bad else stamp(step_start + length // len(steps)), offset)) offset += len(text.encode()) lines.append(text) body = "".join(lines) if job_state not in ("blocked", "skipped") else "" db.execute( "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)" " values (?,?,?,?,?,?,?,?,?,?,?,?,?)", (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}', job_state, runners[j % 2] if job_state != "blocked" else None, 1 if job_state == "failure" else 0, stamp(began - 5), stamp(began), ended, stamp(now) if job_state == "running" else None, len(body.encode()), len(body.encode())), ) if body: db.executemany("insert into ci_job_steps (job_id,seq,name,started_at,finished_at,log_offset) values (?,?,?,?,?,?)", step_rows) with open(os.path.join(logs, job_id + ".log"), "w") as f: f.write(body) number += 1 db.commit() seed["runner_id"] = first seed["failed_run"] = failed_run seed["running_run"] = running_run seed["runners"] = runners json.dump(seed, open(os.path.join(out, "seed.json"), "w")) print(f"[mock] done: failed #{failed_run}, running #{running_run}") def send_samples(): # An hour of samples behind the graphs: the server keeps them in memory, so they go in as a runner's would. samples = [] for m in range(0, 3600, 10): t = now - 3600 + m wave = (math.sin(m / 400) + 1) / 2 samples.append({ "at_ms": int(t * 1000), "cpu_percent": round(15 + 70 * wave + random.uniform(-5, 5), 1), "mem_used_bytes": int((18 + 22 * wave) * 2**30), "mem_total_bytes": 64 * 2**30, "net_rx_bytes_per_s": int((2 + 40 * wave) * 2**20), "net_tx_bytes_per_s": int((1 + 12 * wave) * 2**20), "running_jobs": int(wave * 4), }) request = urllib.request.Request( seed["base"] + "/api/v1/ci/runners/metrics", json.dumps({"samples": samples}).encode(), {"Content-Type": "application/json", "Authorization": "Bearer " + SECRET}, ) try: print("[mock] samples", urllib.request.urlopen(request).status) except OSError as e: print("[mock] samples failed:", e) if phase == "db": fill_database() else: send_samples()