|
| 1 | +import prometheus.registry : Registry; |
| 2 | +import prometheus.gauge : Gauge; |
| 3 | + |
| 4 | +import core.thread : Thread; |
| 5 | +import core.time : dur; |
| 6 | +import std.conv : to; |
| 7 | +import std.process : environment; |
| 8 | +import std.exception : ErrnoException; |
| 9 | +import std.file : readText; |
| 10 | +import std.format : format; |
| 11 | +import argparse; // Andrey Zherikov's argparse (UDA-based) |
| 12 | +import std.json : JSONType, JSONValue, parseJSON; |
| 13 | +import std.logger : LogLevel, logf; |
| 14 | +import std.string : strip; |
| 15 | +import std.datetime : SysTime, Clock; |
| 16 | +import vibe.core.args : setCommandLineArgs; |
| 17 | +import vibe.d: HTTPServerSettings, URLRouter, listenHTTP, runApplication, HTTPServerRequest, HTTPServerResponse; |
| 18 | +import std.net.curl : HTTP, get; |
| 19 | + |
| 20 | +const string[] CACHIX_DEPLOY_STATES = ["Pending", "InProgress", "Cancelled", "Failed", "Succeeded"]; |
| 21 | + |
| 22 | +__gshared Gauge statusGauge; |
| 23 | +__gshared Gauge indexGauge; |
| 24 | +__gshared Gauge startedGauge; |
| 25 | +__gshared Gauge finishedGauge; |
| 26 | +__gshared Gauge inProgressDurationGauge; |
| 27 | +__gshared string gWorkspace; |
| 28 | +const string[] FINISHED_KEYS = ["endedOn", "finishedOn", "completedOn"]; |
| 29 | + |
| 30 | +void promInit() { |
| 31 | + statusGauge = new Gauge("cachix_deploy_status", "Status of the last deploy", ["workspace", "machine", "status"]); |
| 32 | + statusGauge.register; |
| 33 | + indexGauge = new Gauge("cachix_deploy_counter", "Counter/index of deploys.", ["workspace", "machine"]); |
| 34 | + indexGauge.register; |
| 35 | + startedGauge = new Gauge("cachix_deploy_last_started_time", "Unix time when the last deploy started.", ["workspace", "machine"]); |
| 36 | + startedGauge.register; |
| 37 | + finishedGauge = new Gauge("cachix_deploy_last_finished_time", "Unix time when the last deploy finished (if any).", ["workspace", "machine"]); |
| 38 | + finishedGauge.register; |
| 39 | + inProgressDurationGauge = new Gauge("cachix_deploy_in_progress_duration_seconds", "Seconds elapsed for the current in-progress deploy.", ["workspace", "machine"]); |
| 40 | + inProgressDurationGauge.register; |
| 41 | +} |
| 42 | + |
| 43 | +void promSetStatus(string agentName, string status, long indexVal) { |
| 44 | + auto ws = gWorkspace; |
| 45 | + foreach (s; CACHIX_DEPLOY_STATES) { |
| 46 | + statusGauge.set(s == status ? 1.0 : 0.0, [ws, agentName, s]); |
| 47 | + } |
| 48 | + if (indexVal != long.min) { |
| 49 | + indexGauge.set(cast(double) indexVal, [ws, agentName]); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +JSONValue httpGetJson(string url, string authToken) { |
| 54 | + logf(LogLevel.trace, "GET %s", url); |
| 55 | + auto conn = HTTP(); |
| 56 | + conn.connectTimeout = dur!"seconds"(10); |
| 57 | + conn.operationTimeout = dur!"seconds"(20); |
| 58 | + conn.addRequestHeader("Authorization", "Bearer " ~ authToken); |
| 59 | + auto bodyArr = get!(HTTP, char)(url, conn); |
| 60 | + auto body = bodyArr.idup; |
| 61 | + return parseJSON(body); |
| 62 | +} |
| 63 | + |
| 64 | +private: |
| 65 | +bool tryIsoToUnix(string iso, out double outVal) { |
| 66 | + try { |
| 67 | + auto t = SysTime.fromISOExtString(iso); |
| 68 | + outVal = cast(double) t.toUnixTime(); |
| 69 | + return true; |
| 70 | + } catch (Exception) { |
| 71 | + return false; |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +void promSetTimes(string agentName, string startedOn, string finishedOn) { |
| 76 | + auto ws = gWorkspace; |
| 77 | + double v; |
| 78 | + if (startedOn.length && tryIsoToUnix(startedOn, v)) { |
| 79 | + startedGauge.set(v, [ws, agentName]); |
| 80 | + } |
| 81 | + if (finishedOn.length && tryIsoToUnix(finishedOn, v)) { |
| 82 | + finishedGauge.set(v, [ws, agentName]); |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +void promSetInProgressDuration(string agentName, string status, string startedOn) { |
| 87 | + auto ws = gWorkspace; |
| 88 | + if (status == "InProgress") { |
| 89 | + double startUnix; |
| 90 | + if (startedOn.length && tryIsoToUnix(startedOn, startUnix)) { |
| 91 | + auto nowUnix = cast(double) Clock.currTime().toUnixTime(); |
| 92 | + auto diff = nowUnix - startUnix; |
| 93 | + if (diff < 0) diff = 0; |
| 94 | + inProgressDurationGauge.set(diff, [ws, agentName]); |
| 95 | + return; |
| 96 | + } |
| 97 | + } |
| 98 | + inProgressDurationGauge.set(0, [ws, agentName]); |
| 99 | +} |
| 100 | + |
| 101 | +void fetchMachineMetrics(string workspace, string authToken, string agentName) { |
| 102 | + auto url = format("%s/api/v1/deploy/agent/%s/%s", "https://app.cachix.org", workspace, agentName); |
| 103 | + try { |
| 104 | + auto data = httpGetJson(url, authToken); |
| 105 | + JSONValue last; |
| 106 | + if (data.type == JSONType.object && "lastDeployment" in data.object) { |
| 107 | + last = data["lastDeployment"]; |
| 108 | + } |
| 109 | + |
| 110 | + string status; |
| 111 | + long indexVal = long.min; |
| 112 | + string startedOn; |
| 113 | + string finishedOn; |
| 114 | + |
| 115 | + if (last.type == JSONType.object) { |
| 116 | + if ("status" in last.object && last["status"].type == JSONType.string) { |
| 117 | + status = last["status"].str; |
| 118 | + } |
| 119 | + if ("index" in last.object && (last["index"].type == JSONType.integer || last["index"].type == JSONType.uinteger)) { |
| 120 | + indexVal = last["index"].integer; |
| 121 | + } |
| 122 | + if ("startedOn" in last.object && last["startedOn"].type == JSONType.string) { |
| 123 | + startedOn = last["startedOn"].str; |
| 124 | + } |
| 125 | + foreach (k; FINISHED_KEYS) { |
| 126 | + if (k in last.object && last[k].type == JSONType.string) { |
| 127 | + finishedOn = last[k].str; |
| 128 | + break; |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + promSetStatus(agentName, status, indexVal); |
| 134 | + promSetTimes(agentName, startedOn, finishedOn); |
| 135 | + promSetInProgressDuration(agentName, status, startedOn); |
| 136 | + |
| 137 | + auto started = startedOn.length ? startedOn : ""; |
| 138 | + auto finished = finishedOn.length ? finishedOn : ""; |
| 139 | + auto idx = (indexVal == long.min) ? "" : to!string(indexVal); |
| 140 | + logf(LogLevel.trace, "Machine %s startedOn=%s finishedOn=%s index=%s status=%s", agentName, started, finished, idx, (status.length ? status : "")); |
| 141 | + } catch (Exception e) { |
| 142 | + logf(LogLevel.error, "Error fetching metrics for machine '%s' (%s): %s", agentName, url, e.msg); |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +void scrapeLoop(string workspace, string authToken, string[] agents, int scrapeIntervalSec) { |
| 147 | + while (true) { |
| 148 | + foreach (agentName; agents) { |
| 149 | + fetchMachineMetrics(workspace, authToken, agentName); |
| 150 | + } |
| 151 | + Thread.sleep(dur!"seconds"(scrapeIntervalSec)); |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +int main(string[] args) { |
| 156 | + struct CliArgs { |
| 157 | + @(NamedArgument(["port"]) |
| 158 | + .Description("Port to listen on (default: 9160)")) |
| 159 | + int port = 9160; |
| 160 | + |
| 161 | + @(NamedArgument(["listen-address"]) |
| 162 | + .Description("Address to bind (default: 127.0.0.1)")) |
| 163 | + string listenAddress = "127.0.0.1"; |
| 164 | + |
| 165 | + @(NamedArgument(["scrape-interval"]) |
| 166 | + .Description("Scrape interval in seconds (default: 10)")) |
| 167 | + int scrapeInterval = 10; |
| 168 | + |
| 169 | + @(NamedArgument(["auth-token-path"]) |
| 170 | + .Description("Path to Cachix auth token (required if CACHIX_AUTH_TOKEN is unset)")) |
| 171 | + string tokenPath; |
| 172 | + |
| 173 | + @(NamedArgument(["workspace"]) |
| 174 | + .Description("Cachix workspace name (required)") |
| 175 | + .Required()) |
| 176 | + string workspace; |
| 177 | + |
| 178 | + @(NamedArgument(["agent-names", "a"]) |
| 179 | + .Description("Agent names (repeatable)") |
| 180 | + .Required()) |
| 181 | + string[] agents; |
| 182 | + } |
| 183 | + |
| 184 | + CliArgs opts; |
| 185 | + auto res = CLI!(Config.init, CliArgs).parseArgs(opts, args.length > 1 ? args[1 .. $] : []); |
| 186 | + if (!res) return res.resultCode; |
| 187 | + |
| 188 | + if (args.length > 0) setCommandLineArgs([args[0]]); |
| 189 | + |
| 190 | + string authToken = environment.get("CACHIX_AUTH_TOKEN"); |
| 191 | + try { |
| 192 | + if (!authToken) authToken = readText(opts.tokenPath).strip(); |
| 193 | + } catch (Exception e) { |
| 194 | + logf(LogLevel.error, "Token file '%s' not found or unreadable.", opts.tokenPath); |
| 195 | + return 2; |
| 196 | + } |
| 197 | + |
| 198 | + gWorkspace = opts.workspace; |
| 199 | + promInit(); |
| 200 | + foreach (agentName; opts.agents) { |
| 201 | + foreach (s; CACHIX_DEPLOY_STATES) { |
| 202 | + promSetStatus(agentName, s, long.min); |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + auto settings = new HTTPServerSettings; |
| 207 | + settings.port = cast(ushort)opts.port; |
| 208 | + bool listenSpecified = opts.listenAddress.length != 0; |
| 209 | + if (listenSpecified) settings.bindAddresses = [opts.listenAddress]; |
| 210 | + |
| 211 | + auto router = new URLRouter; |
| 212 | + router.get("/metrics", (HTTPServerRequest req, HTTPServerResponse res) { |
| 213 | + string buf; |
| 214 | + foreach (m; Registry.global.metrics) { |
| 215 | + auto snap = m.collect(); |
| 216 | + buf ~= snap.encode(); |
| 217 | + } |
| 218 | + res.writeBody(cast(ubyte[])buf, "text/plain; version=0.0.4; charset=utf-8"); |
| 219 | + }); |
| 220 | + |
| 221 | + if (opts.agents.length) { |
| 222 | + auto t = new Thread({ scrapeLoop(opts.workspace, authToken, opts.agents, opts.scrapeInterval); }); |
| 223 | + t.isDaemon = true; |
| 224 | + t.start(); |
| 225 | + } else { |
| 226 | + logf(LogLevel.warning, "No --agent-names provided; only /metrics with static counters will be served."); |
| 227 | + } |
| 228 | + |
| 229 | + listenHTTP(settings, router); |
| 230 | + runApplication; |
| 231 | + return 0; |
| 232 | +} |
0 commit comments