diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ded9821..71e8bc9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -206,6 +206,9 @@ jobs: curl -sf localhost:7733/agents | grep -q '"agent":"test-agent"' curl -sf localhost:7733/agents | grep -q '"agent":"file-agent"' curl -sf localhost:7733/agents | grep -q '"id":"oh-my-pi"' + # The file goes again: the reports folder is in the real home folder, which every later test's service reads + # too (Linux/tests/wait.sh counts the sessions it finds). + rm -f "$folder/file-agent.jsonl" # The other pages answer. curl -sf "localhost:7733/performance?range=today" | grep -q '"range":"today"' curl -sf "localhost:7733/costs?range=all" | grep -q '"twins"' @@ -341,6 +344,10 @@ jobs: # Model folders of Ollama, LM Studio, Hugging Face and llama.cpp in a home folder of its own: the files are # found with their sizes, and a model that never ran gets an estimate from its file. No model is loaded. run: sh Linux/tests/models.sh .build/release/tokenmeter + - name: OpenTelemetry export + # A stand-in collector: nothing is sent until the export is on, then the figures of /metrics arrive under the + # same names with the headers given, a refusal is told, and switching it off stops the sending. + run: sh Linux/tests/otlp.sh .build/release/tokenmeter - name: The idle service stays within its budget # Processor time, wake-ups, open files and memory of a service with nothing to watch, over a minute. # The stand-in engines of the steps above are stopped first: with them it has work to do. diff --git a/Android/build.sh b/Android/build.sh index 7fb28a9..6817c7f 100755 --- a/Android/build.sh +++ b/Android/build.sh @@ -20,7 +20,7 @@ platform=${ANDROID_PLATFORM:-35} jar=$sdk/platforms/android-$platform/android.jar [ -f "$jar" ] || { echo "No $jar: install the platform with sdkmanager \"platforms;android-$platform\"." >&2; exit 1; } tools=$(ls -d "$sdk"/build-tools/* | sort -V | tail -1) -version=${APP_VERSION:-0.9.10} +version=${APP_VERSION:-0.9.11} IFS=. read -r major minor patch <<<"$version.0.0" code=$((major * 10000 + minor * 100 + ${patch%%[^0-9]*})) diff --git a/App/Alerts.swift b/App/Alerts.swift index 83ba22c..cb78207 100644 --- a/App/Alerts.swift +++ b/App/Alerts.swift @@ -79,6 +79,7 @@ final class AlertCenter { private func check() { sendHeld() AlertHeartbeat.tick() + OTLPExport.tick() TargetStore.shared.tick() SpendLedger.shared.tick() checkInsights() diff --git a/App/Metric.swift b/App/Metric.swift new file mode 100644 index 0000000..350919a --- /dev/null +++ b/App/Metric.swift @@ -0,0 +1,46 @@ +import Foundation + +/// One figure other programs read, with a value for each thing it is about (a server, a kind of token, a target): +/// what `GET /metrics` writes as Prometheus text and what the OpenTelemetry export sends (App/OTLP.swift). +struct Metric: Equatable { + struct Label: Equatable { + var key: String + var value: String + init(_ key: String, _ value: String) { + self.key = key + self.value = value + } + } + + struct Point: Equatable { + var labels: [Label] + var value: Double + /// For a counter: when its count began (the server's start), where that is known. + var since: Date? = nil + } + + /// "tokenmeter_generation_tokens_per_second". + var name: String + var help: String + /// A count that only rises until the server restarts, rather than a level. + var counter = false + var points: [Point] + + /// The Prometheus text format, version 0.0.4. + static func prometheus(_ metrics: [Metric]) -> String { + func escape(_ value: String) -> String { + value.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + } + var lines: [String] = [] + for metric in metrics where !metric.points.isEmpty { + lines.append("# HELP \(metric.name) \(metric.help)") + lines.append("# TYPE \(metric.name) \(metric.counter ? "counter" : "gauge")") + for point in metric.points { + let labels = point.labels.isEmpty ? "" : "{" + point.labels.map { "\($0.key)=\"\(escape($0.value))\"" }.joined(separator: ",") + "}" + lines.append("\(metric.name)\(labels) \(StatusReport.number(point.value))") + } + } + return lines.isEmpty ? "" : lines.joined(separator: "\n") + "\n" + } +} diff --git a/App/OTLP.swift b/App/OTLP.swift new file mode 100644 index 0000000..05a8e7b --- /dev/null +++ b/App/OTLP.swift @@ -0,0 +1,194 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +/// The OpenTelemetry export: the figures of `GET /metrics`, sent to a collector of your own (an OpenTelemetry +/// Collector or Grafana Alloy, which pass them on to wherever you keep metrics) as OTLP over HTTP with a JSON body, +/// under the same names. Off until an address is given and the switch is on. Counts, speeds and sizes only: no prompt, no reply +/// and no client's name is in them. The machine's name and each server's model name are. +enum OTLP { + /// Where the figures go: the address as given when it already ends in `/v1/metrics`, else that path under + /// it ("http://localhost:4318" becomes "http://localhost:4318/v1/metrics"). Nil when it isn't an http(s) address. + static func endpoint(_ text: String) -> URL? { + let text = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard var parts = URLComponents(string: text), let scheme = parts.scheme?.lowercased(), ["http", "https"].contains(scheme), + let host = parts.host, !host.isEmpty else { return nil } + var path = parts.path + while path.hasSuffix("/") { path.removeLast() } + if !path.hasSuffix("/v1/metrics") { path += "/v1/metrics" } + parts.path = path + return parts.url + } + + /// The headers sent along, one on a line or several between commas: "Name: value" or "Name=value" (as the + /// OTEL_EXPORTER_OTLP_HEADERS variable writes them). Lines without a name or a value are left out. + static func headers(_ text: String) -> [(name: String, value: String)] { + var found: [(name: String, value: String)] = [] + for line in text.split(whereSeparator: { $0 == "\n" || $0 == "," }) { + guard let cut = line.firstIndex(where: { $0 == ":" || $0 == "=" }) else { continue } + let name = line[.. String { String(UInt64(max(0, date.timeIntervalSince1970) * 1_000_000_000)) } + + private static func attribute(_ key: String, _ value: String) -> [String: Any] { ["key": key, "value": ["stringValue": value]] } + + /// One export as OTLP's JSON: a level is a gauge, a count a cumulative sum that began when its server started + /// (`started`, the service's own start, where the server doesn't say). + static func payload(_ metrics: [Metric], host: String, version: String, started: Date, now: Date) -> [String: Any] { + let sent: [[String: Any]] = metrics.filter { !$0.points.isEmpty }.map { metric in + let points: [[String: Any]] = metric.points.map { point in + var one: [String: Any] = ["timeUnixNano": nanos(now), "asDouble": point.value] + if !point.labels.isEmpty { one["attributes"] = point.labels.map { attribute($0.key, $0.value) } } + if metric.counter { one["startTimeUnixNano"] = nanos(min(point.since ?? started, now)) } + return one + } + var entry: [String: Any] = ["name": metric.name, "description": metric.help] + if metric.counter { + entry["sum"] = ["dataPoints": points, "aggregationTemporality": 2, "isMonotonic": true] as [String: Any] + } else { + entry["gauge"] = ["dataPoints": points] + } + return entry + } + // (`service.instance.id` is what Prometheus calls `instance` when it takes OTLP in, so the board's machine + // picker works for figures that came either way.) + let resource: [String: Any] = ["attributes": [attribute("service.name", "tokenmeter"), attribute("service.version", version), + attribute("service.instance.id", host), attribute("host.name", host)]] + let scope: [String: Any] = ["scope": ["name": "tokenmeter", "version": version], "metrics": sent] + return ["resourceMetrics": [["resource": resource, "scopeMetrics": [scope]] as [String: Any]]] + } + + static func body(_ metrics: [Metric], host: String, version: String, started: Date, now: Date) -> Data { + (try? JSONSerialization.data(withJSONObject: payload(metrics, host: host, version: version, started: started, now: now), options: [.sortedKeys])) ?? Data("{}".utf8) + } + + static func points(_ metrics: [Metric]) -> Int { metrics.reduce(0) { $0 + $1.points.count } } +} + +/// The export's settings and its sender: called every few seconds with the alerts' own check, it sends when the +/// export is on and its time has come. +@MainActor +enum OTLPExport { + nonisolated static let enabledKey = "otlpEnabled" + nonisolated static let endpointKey = "otlpEndpoint" + nonisolated static let headersKey = "otlpHeaders" + nonisolated static let secondsKey = "otlpSeconds" + nonisolated static let usualSeconds = 60 + nonisolated static let seconds = 10...3600 + + private(set) static var last: (at: Date, problem: String?, points: Int)? + private static var due = Date.distantPast + private static var sending = false + private static let started = Date() + + static var enabled: Bool { Prefs.defaults.bool(forKey: enabledKey) } + static var address: String { Prefs.defaults.string(forKey: endpointKey) ?? "" } + static var headerText: String { Prefs.defaults.string(forKey: headersKey) ?? "" } + static var every: Int { + let kept = Prefs.defaults.integer(forKey: secondsKey) + return kept == 0 ? usualSeconds : min(max(kept, seconds.lowerBound), seconds.upperBound) + } + + /// What is sent: the status page's figures and the targets'. + static func metrics() -> [Metric] { StatusReport.current(history: false).metrics() + TargetStore.shared.metrics() } + + static func tick(now: Date = Date()) { + guard enabled, !sending, now >= due, let target = OTLP.endpoint(address) else { return } + due = now.addingTimeInterval(TimeInterval(every)) + let metrics = metrics() + let body = OTLP.body(metrics, host: StatusReport.machineName, version: StatusReport.appVersion, started: started, now: now) + let headers = OTLP.headers(headerText) + sending = true + Task { @MainActor in + let problem = await send(body, to: target, headers: headers) + last = (Date(), problem, OTLP.points(metrics)) + sending = false + } + } + + /// Sends at the next check, after a setting changed, so Settings shows at once whether it works. + static func sendSoon() { due = .distantPast } + + private static func send(_ body: Data, to url: URL, headers: [(name: String, value: String)]) async -> String? { + var request = URLRequest(url: url) + request.httpMethod = "POST" + request.timeoutInterval = 15 + request.httpBody = body + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue("Tokenmeter", forHTTPHeaderField: "User-Agent") + for header in headers { request.setValue(header.value, forHTTPHeaderField: header.name) } + do { + let (_, response) = try await HTTPFetch.data(for: request) + let code = (response as? HTTPURLResponse)?.statusCode ?? 0 + return (200..<300).contains(code) ? nil : "It answered HTTP \(code)" + } catch { + return "Couldn't reach \(url.host ?? "it"): \(error.localizedDescription)" + } + } + + static var status: String? { + guard enabled, let last else { return nil } + let time = DateFormatter.localizedString(from: last.at, dateStyle: .none, timeStyle: .medium) + return last.problem.map { "Last sent at \(time): \($0)." } ?? "Last sent at \(time), \(last.points) values." + } + + /// Keeps the settings among `fields` (`enabled`, `endpoint`, `headers`, `seconds`); nil when they were kept, + /// else what is wrong with them. + static func apply(_ fields: [String: Any]) -> String? { + let defaults = Prefs.defaults + let address = (fields["endpoint"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) + if let address, !address.isEmpty, OTLP.endpoint(address) == nil { + return "The collector's address starts with http:// or https://, such as http://localhost:4318." + } + let turnedOn = fields["enabled"] as? Bool + if turnedOn == true, (address ?? self.address).isEmpty { + return "Give the collector's address first, such as http://localhost:4318." + } + var every: Int? + if fields["seconds"] != nil { + guard let wanted = JSONValue.int(fields["seconds"]), seconds.contains(wanted) else { + return "Send every \(seconds.lowerBound) to \(seconds.upperBound) seconds." + } + every = wanted + } + if let address { + defaults.set(address, forKey: endpointKey) + if address.isEmpty { defaults.set(false, forKey: enabledKey) } + } + if let text = fields["headers"] as? String { + defaults.set(OTLP.headers(text).map { "\($0.name): \($0.value)" }.joined(separator: "\n"), forKey: headersKey) + } + if let every { defaults.set(every, forKey: secondsKey) } + if let turnedOn, !(address ?? self.address).isEmpty { defaults.set(turnedOn, forKey: enabledKey) } + defaults.synchronize() + last = nil + sendSoon() + return nil + } +} + +/// `GET /otlp`: the export's settings as Settings shows them. A header's value is never given back, only its name. +struct OTLPAnswer: Codable, Equatable { + var enabled: Bool + var endpoint: String + /// Where the figures are posted, with the path added; nil while there is no address. + var target: String? + var headerNames: [String] + var seconds: Int + var status: String? + /// How many values one export holds now. + var points: Int + + @MainActor static var current: OTLPAnswer { + OTLPAnswer(enabled: OTLPExport.enabled, endpoint: OTLPExport.address, target: OTLP.endpoint(OTLPExport.address)?.absoluteString, + headerNames: OTLP.headers(OTLPExport.headerText).map(\.name), seconds: OTLPExport.every, status: OTLPExport.status, + points: OTLP.points(OTLPExport.metrics())) + } +} diff --git a/App/SettingsIndex.swift b/App/SettingsIndex.swift index 1e22ad5..30672ff 100644 --- a/App/SettingsIndex.swift +++ b/App/SettingsIndex.swift @@ -72,6 +72,7 @@ enum SettingsIndex { add("heartbeat", .alerts, "Heartbeat", "heartbeat healthchecks uptime kuma better stack dead man switch power lost machine down ping") add("everyMachine", .alerts, "Alerts on Other Machines", "other machines mesh every machine copy channels use these channels remote another machine alerts settings for") add("status", .machines, "Status Endpoint", "keep this machine to itself metrics prometheus json let other machines read address port network") + add("otlp", .machines, "OpenTelemetry Export", "otlp opentelemetry otel collector grafana alloy datadog honeycomb metrics export send push prometheus dashboard") add("machines", .machines, "Other Machines", "add machine fleet remote computer mesh page") add("proxy", .proxy, "Engine Proxy", "proxy clients docker vm port forward listen open to network inference model requests") add("mcpProxy", .proxy, "MCP Proxy", "proxy mcp server tool calls agent time wrap mcp-wrap local command") diff --git a/App/SettingsPage.swift b/App/SettingsPage.swift index 8d6fa64..f2d1e84 100644 --- a/App/SettingsPage.swift +++ b/App/SettingsPage.swift @@ -861,6 +861,74 @@ struct HeartbeatSettings: View { } } +/// Network › OpenTelemetry Export: the figures of `/metrics` sent to a collector of the user's own +/// (App/OTLP.swift). The service keeps the settings and does the sending (`GET` and `POST /otlp`). +struct OTLPSettings: View { + @State private var answer: OTLPAnswer? + @State private var address = "" + @State private var headers = "" + @State private var problem: String? + + private static let choices: [(seconds: Int, title: String)] = [(15, "15 seconds"), (30, "30 seconds"), (60, "Minute"), (300, "5 minutes")] + + var body: some View { + let on = Binding(get: { answer?.enabled ?? false }, set: { change(["enabled": $0]) }) + let every = Binding(get: { answer?.seconds ?? OTLPExport.usualSeconds }, set: { change(["seconds": $0]) }) + let names: [String] = answer?.headerNames ?? [] + let hint: String = names.isEmpty ? "x-honeycomb-team: your-key" : "Saved: " + names.joined(separator: ", ") + return Section { + Toggle("Send Metrics to a Collector", isOn: on).disabled((answer?.endpoint ?? "").isEmpty) + TextField("Collector", text: $address, prompt: Text("http://localhost:4318")) + .onSubmit { change(["endpoint": address.trimmingCharacters(in: .whitespacesAndNewlines)]) } + SecureField("Headers", text: $headers, prompt: Text(hint)) + .onSubmit { + guard !headers.isEmpty else { return } + change(["headers": headers]) + headers = "" + } + Picker("Send Every", selection: every) { + ForEach(Self.choices, id: \.seconds) { choice in Text(choice.title).tag(choice.seconds) } + } + if !names.isEmpty { + Button("Forget Headers") { change(["headers": ""]) } + } + if let line = problem ?? answer?.status { + Text(line).font(.sized(.caption)).foregroundStyle(problem != nil || line.contains(": ") ? Color.red : Color.secondary) + } + } header: { + Text("OpenTelemetry Export") + } footer: { + Text("Sends the figures of `/metrics` to a collector of your own (an OpenTelemetry Collector or Grafana Alloy, and through it Grafana, Datadog or Honeycomb) as OTLP over HTTP with a JSON body, under the same names, so one Grafana board reads either. Counts, speeds and sizes only: never a prompt, a reply or a client's name. This Mac's name and the model names are sent. Off until you switch it on; each machine sends its own.") + } + .onAppear { load() } + } + + private func change(_ fields: [String: Any]) { + guard let reply = ServiceLink.request("POST", "/otlp", json: fields) else { + problem = "The service didn't answer. Is it running?" + return + } + if reply.code == 200 { + problem = nil + answer = try? JSONDecoder().decode(OTLPAnswer.self, from: reply.body) + } else { + problem = String(decoding: reply.body, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) + } + // What the first sending said shows a few seconds later. + Task { @MainActor in + try? await Task.sleep(nanoseconds: 7_000_000_000) + load() + } + } + + private func load() { + guard let reply = ServiceLink.request("GET", "/otlp"), reply.code == 200, + let now = try? JSONDecoder().decode(OTLPAnswer.self, from: reply.body) else { return } + answer = now + if address.isEmpty { address = now.endpoint } + } +} + /// Network: the status endpoint and whether this Mac keeps to itself. Other machines and what they may read /// are on the Mesh page. struct MachineSettings: View { @@ -898,6 +966,7 @@ struct MachineSettings: View { // The background service answers other machines unless it was told not to; the switch shows that. if ServiceLink.isClient, Prefs.defaults.object(forKey: StatusEndpoint.Key.network) == nil { statusNetwork = true } } + OTLPSettings().id("otlp") Section { HStack { Text("Adding machines, letting one in and what they may read are on the Mesh page now.") diff --git a/App/StatusJSON.swift b/App/StatusJSON.swift index 8a900bf..b0dd6ab 100644 --- a/App/StatusJSON.swift +++ b/App/StatusJSON.swift @@ -250,53 +250,55 @@ struct StatusReport: Codable, Equatable { // MARK: Prometheus - /// The same figures in the Prometheus text format (`GET /metrics`), for Grafana and the like. - func prometheus() -> String { - var lines: [String] = [] - func gauge(_ name: String, _ help: String, _ values: [(labels: String, value: Double)], type: String = "gauge") { - guard !values.isEmpty else { return } - lines.append("# HELP tokenmeter_\(name) \(help)") - lines.append("# TYPE tokenmeter_\(name) \(type)") - for entry in values { lines.append("tokenmeter_\(name)\(entry.labels) \(Self.number(entry.value))") } - } - func escape(_ value: String) -> String { - value.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") - .replacingOccurrences(of: "\n", with: "\\n") + /// The figures other programs read, each with its points: the Prometheus page (`GET /metrics`) writes them as + /// text, the OpenTelemetry export (App/OTLP.swift) sends the same ones under the same names. Counts, speeds and + /// sizes only: no prompt, no reply and no client's name is among them. + func metrics() -> [Metric] { + var found: [Metric] = [] + func gauge(_ name: String, _ help: String, _ points: [Metric.Point], counter: Bool = false) { + guard !points.isEmpty else { return } + found.append(Metric(name: "tokenmeter_" + name, help: help, counter: counter, points: points)) } - func labels(_ server: Server) -> String { - "{engine=\"\(escape(server.engine))\",model=\"\(escape(server.model))\",host=\"\(escape(server.host))\",port=\"\(server.port)\"}" + func labels(_ server: Server) -> [Metric.Label] { + [.init("engine", server.engine), .init("model", server.model), .init("host", server.host), .init("port", String(server.port))] } - func each(_ value: (Server) -> Double?) -> [(labels: String, value: Double)] { - servers.compactMap { server in value(server).map { (labels(server), $0) } } + func each(_ value: (Server) -> Double?, since: Bool = false) -> [Metric.Point] { + servers.compactMap { server in value(server).map { Metric.Point(labels: labels(server), value: $0, since: since ? server.startedAt : nil) } } } - gauge("servers_online", "Servers answering now.", [("", Double(totals.online))]) + func one(_ value: Double?) -> [Metric.Point] { value.map { [Metric.Point(labels: [], value: $0)] } ?? [] } + gauge("servers_online", "Servers answering now.", one(Double(totals.online))) gauge("server_up", "1 while the server is online.", each { $0.isUp ? 1 : 0 }) gauge("generation_tokens_per_second", "Tokens being written per second.", each(\.generationTPS)) gauge("prompt_tokens_per_second", "Prompt tokens being read per second.", each(\.promptTPS)) gauge("active_requests", "Requests being served.", each { $0.activeRequests.map { Double($0) } }) gauge("deferred_requests", "Requests waiting for a slot.", each { $0.deferredRequests.map { Double($0) } }) - gauge("tokens_generated_total", "Tokens written since the server started.", each { $0.tokensGenerated.map { Double($0) } }, type: "counter") - gauge("prompt_tokens_total", "Prompt tokens read since the server started.", each { $0.promptTokens.map { Double($0) } }, type: "counter") - gauge("requests_total", "Requests served since the server started.", each { $0.requestsServed.map { Double($0) } }, type: "counter") + gauge("tokens_generated_total", "Tokens written since the server started.", each({ $0.tokensGenerated.map { Double($0) } }, since: true), counter: true) + gauge("prompt_tokens_total", "Prompt tokens read since the server started.", each({ $0.promptTokens.map { Double($0) } }, since: true), counter: true) + gauge("requests_total", "Requests served since the server started.", each({ $0.requestsServed.map { Double($0) } }, since: true), counter: true) gauge("first_token_seconds", "Typical (median) seconds from a request's arrival to its first token.", each { $0.extras?.firstToken }) gauge("draft_acceptance_ratio", "Share of drafted tokens the main model accepted (speculative decoding).", each { $0.extras?.draftAcceptance }) gauge("model_memory_gigabytes", "Memory the model uses.", each(\.memoryUsedGB)) gauge("context_used_ratio", "Share of the usable context in use, 0 to 1.", each(\.contextUsedFraction)) - gauge("gpu_utilization_percent", "GPU load, 0 to 100.", system.gpuPercent.map { [("", $0)] } ?? []) - gauge("gpu_memory_gigabytes", "Memory in use by the GPU.", system.gpuMemoryGB.map { [("", $0)] } ?? []) - gauge("power_watts", "What the processor and graphics draw now.", system.powerWatts.map { [("", $0)] } ?? []) - gauge("memory_available_gigabytes", "Memory the system can hand out without swapping.", [("", system.memoryAvailableGB)]) - gauge("memory_total_gigabytes", "Physical memory.", [("", system.memoryTotalGB)]) - gauge("memory_pressure_level", "1 normal, 2 elevated, 4 critical.", [("", Double(system.memoryPressure))]) - gauge("swap_used_gigabytes", "Swap in use.", [("", system.swapUsedGB)]) - gauge("today_tokens", "Tokens counted today, prompt and output.", [("{kind=\"prompt\"}", Double(today.prompt)), - ("{kind=\"cached\"}", Double(today.cached)), - ("{kind=\"output\"}", Double(today.output))]) - gauge("today_requests", "Requests counted today.", [("", Double(today.requests))]) - return lines.joined(separator: "\n") + "\n" + gauge("gpu_utilization_percent", "GPU load, 0 to 100.", one(system.gpuPercent)) + gauge("gpu_memory_gigabytes", "Memory in use by the GPU.", one(system.gpuMemoryGB)) + gauge("power_watts", "What the processor and graphics draw now.", one(system.powerWatts)) + gauge("memory_available_gigabytes", "Memory the system can hand out without swapping.", one(system.memoryAvailableGB)) + gauge("memory_total_gigabytes", "Physical memory.", one(system.memoryTotalGB)) + gauge("memory_pressure_level", "1 normal, 2 elevated, 4 critical.", one(Double(system.memoryPressure))) + gauge("swap_used_gigabytes", "Swap in use.", one(system.swapUsedGB)) + gauge("today_tokens", "Tokens counted today, prompt and output.", [ + Metric.Point(labels: [.init("kind", "prompt")], value: Double(today.prompt)), + Metric.Point(labels: [.init("kind", "cached")], value: Double(today.cached)), + Metric.Point(labels: [.init("kind", "output")], value: Double(today.output)), + ]) + gauge("today_requests", "Requests counted today.", one(Double(today.requests))) + return found } - private static func number(_ value: Double) -> String { + /// The same figures in the Prometheus text format (`GET /metrics`), for Grafana and the like. + func prometheus() -> String { Metric.prometheus(metrics()) } + + static func number(_ value: Double) -> String { value == value.rounded() && abs(value) < 1e15 ? String(Int64(value)) : String(value) } @@ -438,7 +440,7 @@ struct LocalResponse { extension StatusReport { /// Tokenmeter's version. The Mac app reads it from its Info.plist, which build-library-app.sh writes; the /// Linux service has no Info.plist, so it uses `releaseVersion`. Keep that in step with the build scripts. - static let releaseVersion = "0.9.10" + static let releaseVersion = "0.9.11" static var appVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? releaseVersion } diff --git a/App/TargetStore.swift b/App/TargetStore.swift index 0c9af51..27b738f 100644 --- a/App/TargetStore.swift +++ b/App/TargetStore.swift @@ -161,6 +161,31 @@ final class TargetStore { statuses = fresh } + /// The same two figures for the OpenTelemetry export (App/OTLP.swift). + func metrics() -> [Metric] { + func labels(_ target: ServiceTarget) -> [Metric.Label] { + [.init("target", target.id), .init("server", target.server), .init("model", target.model ?? ""), .init("figure", target.figure.rawValue)] + } + var left: [Metric.Point] = [], burn: [Metric.Point] = [] + for target in targets { + guard let status = statuses[target.id] else { continue } + if let value = status.budgetLeft { left.append(Metric.Point(labels: labels(target), value: value)) } + for (window, value) in [("5m", status.burn5m), ("30m", status.burn30m), ("1h", status.burn1h), ("6h", status.burn6h)] { + if let value { burn.append(Metric.Point(labels: labels(target) + [.init("window", window)], value: value)) } + } + } + var found: [Metric] = [] + if !left.isEmpty { + found.append(Metric(name: "tokenmeter_target_budget_remaining", + help: "Share of the target's error budget left over its window (1 untouched, 0 spent).", points: left)) + } + if !burn.isEmpty { + found.append(Metric(name: "tokenmeter_target_burn_rate", + help: "How fast the target spends its budget: 1 spends it exactly by the window's end.", points: burn)) + } + return found + } + /// Prometheus lines for Grafana: the budget left and the burn rates of each target. func prometheus() -> String { let list = targets diff --git a/Linux/OTLPRoutes.swift b/Linux/OTLPRoutes.swift new file mode 100644 index 0000000..9e91dc2 --- /dev/null +++ b/Linux/OTLPRoutes.swift @@ -0,0 +1,24 @@ +#if os(Linux) || TOKENMETER_SERVICE +import Foundation + +/// The OpenTelemetry export's settings (App/OTLP.swift), from this machine only: +/// - `GET /otlp`: whether it is on, the collector's address, the names of the headers sent along (never their +/// values), how often it sends and what the last sending said. +/// - `POST /otlp {"enabled"?, "endpoint"?, "headers"?, "seconds"?}`: changes them, and sends once at the next check. +/// An empty `endpoint` switches the export off. +@MainActor +enum OTLPRoutes { + static func start() { + let endpoint = StatusEndpoint.shared + endpoint.route("GET", "/otlp") { request in + if let refusal = TokenmeterService.refusal(request) { return refusal } + return TokenmeterService.json(OTLPAnswer.current) + } + endpoint.route("POST", "/otlp") { request in + if let refusal = TokenmeterService.refusal(request) { return refusal } + if let problem = OTLPExport.apply(request.fields) { return .text(problem + "\n", code: 400) } + return TokenmeterService.json(OTLPAnswer.current) + } + } +} +#endif diff --git a/Linux/Service.swift b/Linux/Service.swift index 6ba6e19..e3bba50 100644 --- a/Linux/Service.swift +++ b/Linux/Service.swift @@ -208,6 +208,7 @@ enum TokenmeterService { SpendRoutes.start() SetupRoutes.start() ModelRoutes.start() + OTLPRoutes.start() // Insights watch from the start, so changes and findings are kept while no app is open. InsightStore.shared.start() // Gizmo listens from the start, so it can react to requests while its page is closed. diff --git a/Linux/kde/app/AppVersion.js b/Linux/kde/app/AppVersion.js index dac9bb3..762d603 100644 --- a/Linux/kde/app/AppVersion.js +++ b/Linux/kde/app/AppVersion.js @@ -3,4 +3,4 @@ // update keeps saying the version it is, while the service reports its own (backend.snapshot.version). // scripts/package-linux.sh and package-flatpak.sh write it from the package's version; keep it in step with // StatusReport.releaseVersion when bumping (a unit test checks it). -var version = "0.9.10" +var version = "0.9.11" diff --git a/Linux/kde/mock/machines.json b/Linux/kde/mock/machines.json index 514842f..80cadf0 100644 --- a/Linux/kde/mock/machines.json +++ b/Linux/kde/mock/machines.json @@ -7,7 +7,7 @@ "report": { "schema": 1, "app": "Tokenmeter", - "version": "0.9.10", + "version": "0.9.11", "host": "studio", "chip": "Apple M3 Ultra", "time": "2026-11-13T19:00:00Z", diff --git a/Linux/kde/mock/otlp.json b/Linux/kde/mock/otlp.json new file mode 100644 index 0000000..c6bc11e --- /dev/null +++ b/Linux/kde/mock/otlp.json @@ -0,0 +1,11 @@ +{ + "enabled": true, + "endpoint": "http://collector.local:4318", + "target": "http://collector.local:4318/v1/metrics", + "headerNames": [ + "Authorization" + ], + "seconds": 60, + "status": "Last sent at 14:02:11, 46 values.", + "points": 46 +} \ No newline at end of file diff --git a/Linux/kde/mock/settings.json b/Linux/kde/mock/settings.json index 466438d..e3b260b 100644 --- a/Linux/kde/mock/settings.json +++ b/Linux/kde/mock/settings.json @@ -15,7 +15,7 @@ "addresses": [ "192.168.1.20" ], - "version": "0.9.10", + "version": "0.9.11", "shareHistory": false, "footprint": { "cpuPercent": 0.4, diff --git a/Linux/kde/plasmoid/metadata.json b/Linux/kde/plasmoid/metadata.json index b2cc987..e4ddc70 100644 --- a/Linux/kde/plasmoid/metadata.json +++ b/Linux/kde/plasmoid/metadata.json @@ -7,7 +7,7 @@ "Icon": "tokenmeter", "Category": "System Information", "License": "Apache-2.0", - "Version": "0.9.10", + "Version": "0.9.11", "Website": "https://github.com/tokenmeter1/Tokenmeter" }, "X-Plasma-API-Minimum-Version": "6.0", diff --git a/Linux/kde/ui/SettingsPage.qml b/Linux/kde/ui/SettingsPage.qml index 127b09e..a734d5f 100644 --- a/Linux/kde/ui/SettingsPage.qml +++ b/Linux/kde/ui/SettingsPage.qml @@ -159,6 +159,19 @@ Item { backend.get("/proxies", function (answer) { page.proxies = answer.proxies || [] }) backend.get("/mcp-proxies", function (answer) { page.mcpProxies = answer.proxies || [] }) backend.get("/gizmo", function (answer) { page.gizmo = answer }) + loadOtlp() + } + // The OpenTelemetry export (`GET /otlp`, App/OTLP.swift), and what the service said to the last change. + property var otlp: ({}) + property string otlpProblem: "" + function loadOtlp() { backend.get("/otlp", function (answer) { if (answer) page.otlp = answer }) } + function setOtlp(change) { + backend.send("POST", "/otlp", change, function (error, answer) { + page.otlpProblem = error || "" + if (answer) page.otlp = answer + else page.loadOtlp() + otlpCheck.restart() + }) } onActiveChanged: if (active) load() Component.onCompleted: { @@ -1059,6 +1072,74 @@ Item { Label { width: parent.width; wrapMode: Text.Wrap; text: page.settings.statusProblem || ""; visible: text !== ""; color: page.tones.red; font.pixelSize: Look.px(12) } } + // The same figures as /metrics, sent to a collector of the user's own. Off until an address is given. + Section { + title: "OpenTelemetry Export" + area: "machines" + part: "otlp" + note: "Sends the figures of `/metrics` to a collector of your own (an OpenTelemetry Collector or Grafana Alloy, and through it Grafana, Datadog or Honeycomb) as OTLP over HTTP with a JSON body, under the same names, so one Grafana board reads either. Counts, speeds and sizes only: never a prompt, a reply or a client's name. This machine's name and the model names are sent. Off until you switch it on; each machine sends its own." + Timer { id: otlpCheck; interval: 7000; onTriggered: page.loadOtlp() } + RowLayout { + width: parent.width + Label { text: "Send Metrics to a Collector"; Layout.fillWidth: true } + Switch { + objectName: "otlpSwitch" + checked: page.otlp.enabled === true + enabled: (page.otlp.endpoint || "") !== "" + onToggled: page.setOtlp({ enabled: checked }) + } + } + TextField { + objectName: "otlpEndpoint" + width: parent.width + Accessible.name: "Collector address" + placeholderText: "http://localhost:4318" + text: page.otlp.endpoint || "" + onEditingFinished: if (text.trim() !== (page.otlp.endpoint || "")) page.setOtlp({ endpoint: text.trim() }) + } + TextField { + objectName: "otlpHeaders" + width: parent.width + Accessible.name: "Headers" + placeholderText: (page.otlp.headerNames || []).length > 0 + ? "Saved: " + page.otlp.headerNames.join(", ") + ". Type new ones to replace them." + : "Headers, if the collector wants a key: x-honeycomb-team: your-key" + echoMode: TextInput.PasswordEchoOnEdit + onEditingFinished: if (text.trim() !== "") { page.setOtlp({ headers: text.trim() }); text = "" } + } + RowLayout { + width: parent.width + spacing: 10 + Label { text: "Send Every"; Layout.fillWidth: true } + ComboBox { + Accessible.name: "Send every" + readonly property var choices: [15, 30, 60, 300] + model: ["15 seconds", "30 seconds", "Minute", "5 minutes"] + currentIndex: Math.max(0, choices.indexOf(page.otlp.seconds || 60)) + onActivated: function (index) { page.setOtlp({ seconds: choices[index] }) } + } + Button { + text: "Forget Headers"; flat: true + visible: (page.otlp.headerNames || []).length > 0 + onClicked: page.setOtlp({ headers: "" }) + } + } + Label { + width: parent.width; wrapMode: Text.Wrap; font.pixelSize: Look.px(11); opacity: Look.dim(0.6) + visible: (page.otlp.target || "") !== "" + text: "Posted to " + (page.otlp.target || "") + ", " + (page.otlp.points || 0) + " values each time." + } + Label { + objectName: "otlpStatus" + width: parent.width; wrapMode: Text.Wrap; font.pixelSize: Look.px(12) + text: page.otlpProblem !== "" ? page.otlpProblem : (page.otlp.status || "") + visible: text !== "" + readonly property bool wrong: page.otlpProblem !== "" || text.indexOf(": ") > 0 + color: wrong ? page.tones.red : palette.windowText + opacity: wrong ? 1 : Look.dim(0.75) + } + } + // Other Machines and sharing moved to the Mesh page. Section { title: "Other Machines" diff --git a/Linux/tests/fake_collector.py b/Linux/tests/fake_collector.py new file mode 100644 index 0000000..98d3362 --- /dev/null +++ b/Linux/tests/fake_collector.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""A stand-in for an OpenTelemetry collector: keeps what is posted to /v1/metrics, and tells it back. + + fake_collector.py [key] + +POST /v1/metrics is kept (its body and its headers) and answered {"partialSuccess": {}}; with a key, a post +without the header `x-key: ` is answered 401 and counted apart. GET /got tells how many posts came, how many +were refused, and the last body and headers. Nothing else is answered. +""" +import json +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +PORT = int(sys.argv[1]) +KEY = sys.argv[2] if len(sys.argv) > 2 else None +got = {"posts": 0, "refused": 0, "paths": [], "last": None, "headers": {}} + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def answer(self, code, body): + data = json.dumps(body).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + if self.path == "/got": + self.answer(200, got) + else: + self.answer(404, {}) + + def do_POST(self): + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + got["paths"].append(self.path) + if self.path != "/v1/metrics": + return self.answer(404, {}) + if KEY and self.headers.get("x-key") != KEY: + got["refused"] += 1 + return self.answer(401, {"message": "no key"}) + got["posts"] += 1 + got["headers"] = {k.lower(): v for k, v in self.headers.items()} + try: + got["last"] = json.loads(body) + except ValueError: + got["last"] = None + self.answer(200, {"partialSuccess": {}}) + + +ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever() diff --git a/Linux/tests/otlp.sh b/Linux/tests/otlp.sh new file mode 100755 index 0000000..c1b620e --- /dev/null +++ b/Linux/tests/otlp.sh @@ -0,0 +1,99 @@ +#!/bin/sh +# The OpenTelemetry export (GET and POST /otlp), against a stand-in collector (Linux/tests/fake_collector.py) and a +# stand-in llama.cpp: nothing is sent until the export is switched on; then the figures of /metrics arrive as OTLP +# JSON under the same names, with the headers given; a collector that refuses says so in Settings; a header's value +# is never given back; and switching it off stops the sending. Starts its own service on port 7789. +# +# Linux/tests/otlp.sh [path to the tokenmeter binary] +set -eu + +tokenmeter=$(realpath "${1:-.build/release/tokenmeter}") +here=$(dirname "$(realpath "$0")") +work=$(mktemp -d) +pids= +trap 'for pid in $pids; do kill $pid 2>/dev/null || true; done; wait 2>/dev/null; rm -rf "${work:?}" || true' EXIT +fail() { + echo "FAILED: $1" >&2 + [ -f "$work/service.log" ] && { echo "--- service" >&2; tail -5 "$work/service.log" >&2; } + exit 1 +} +field() { python3 -c 'import json, sys; d = json.load(sys.stdin); print(('"$1"'))'; } +url=http://127.0.0.1:7789 +collector=http://127.0.0.1:14318 +until_is() { # url expression expected what + for _ in $(seq 1 40); do + got=$(curl -sf -m 5 "$1" | field "$2" 2>/dev/null || true) + [ "$got" = "$3" ] && return 0 + sleep 1 + done + fail "$4 (got: $got)" +} +set_otlp() { curl -s -m 10 -o "$work/answer" -w '%{http_code}' -X POST $url/otlp -d "$1"; } + +python3 "$here/fake_collector.py" 14318 sesame & +pids="$pids $!" +python3 "$here/fake_llama.py" 18089 & +pids="$pids $!" +mkdir -p "$work/home" +env HOME="$work/home" XDG_DATA_HOME="$work/home/share" XDG_CONFIG_HOME="$work/home/config" TOKENMETER_NAME=exporter \ + "$tokenmeter" serve --port 7789 >"$work/service.log" 2>&1 & +pids="$pids $!" +until_is $url/mesh 'len(d["members"])' 1 "the service didn't start" +curl -sf -m 10 -X POST $url/engines -d '{"kind":"llamacpp","name":"Stand-in","port":18089}' >/dev/null || fail "the engine wasn't added" +until_is $url/status 'len([s for s in d["servers"] if s["port"] == 18089 and s["status"] == "online"])' 1 "the stand-in server's card" + +# 1. Off by default, and nothing is sent. +curl -sf $url/otlp | field '(d["enabled"], d["endpoint"], d["headerNames"], d["seconds"], d.get("status"))' | grep -q "^(False, '', \[\], 60, None)$" \ + || fail "the export isn't off at first: $(curl -sf $url/otlp)" +[ "$(set_otlp '{"enabled":true}')" = 400 ] || fail "switched on without an address" +[ "$(set_otlp '{"endpoint":"collector:4318"}')" = 400 ] || fail "an address without http was kept" +[ "$(set_otlp '{"seconds":2}')" = 400 ] || fail "sending every 2 seconds was kept" +# An address alone doesn't start it. +[ "$(set_otlp '{"endpoint":"'$collector'","seconds":10}')" = 200 ] || fail "the address wasn't kept: $(cat "$work/answer")" +field '(d["enabled"], d["target"], d["seconds"])' < "$work/answer" | grep -q "^(False, '$collector/v1/metrics', 10)$" || fail "the address as kept: $(cat "$work/answer")" +sleep 12 +curl -sf $collector/got | field 'd["paths"]' | grep -q "^\[\]$" || fail "something was sent while the export was off: $(curl -sf $collector/got)" + +# 2. Switched on without the collector's key: it is refused, and Settings says so. +[ "$(set_otlp '{"enabled":true}')" = 200 ] || fail "the export wasn't switched on: $(cat "$work/answer")" +until_is $url/otlp '"HTTP 401" in (d.get("status") or "")' True "the refusal isn't told" + +# 3. With the key: the figures arrive, under the names of /metrics. +[ "$(set_otlp '{"headers":"x-key: sesame\nX-Scope-OrgID=tenant-1"}')" = 200 ] || fail "the headers weren't kept" +field 'd["headerNames"]' < "$work/answer" | grep -q "^\['x-key', 'X-Scope-OrgID'\]$" || fail "the headers' names: $(cat "$work/answer")" +grep -q sesame "$work/answer" && fail "a header's value was given back" +curl -sf $url/otlp | grep -q sesame && fail "a header's value was given back by GET /otlp" +until_is $collector/got 'd["posts"] >= 1' True "nothing arrived at the collector" +until_is $url/otlp '(d.get("status") or "").startswith("Last sent at") and "values" in d["status"]' True "the sending isn't told" +curl -sf $collector/got > "$work/got" +field '(d["headers"].get("x-scope-orgid"), d["headers"].get("content-type"))' < "$work/got" | grep -q "^('tenant-1', 'application/json')$" || fail "the headers sent: $(field 'd["headers"]' < "$work/got")" +names='sorted(m["name"] for m in d["last"]["resourceMetrics"][0]["scopeMetrics"][0]["metrics"])' +curl -sf $url/metrics | grep '^# TYPE tokenmeter_' | grep -v 'tokenmeter_target_' | cut -d' ' -f3 | sort > "$work/prometheus" +field "'\n'.join($names)" < "$work/got" | sort > "$work/otlp" +cmp -s "$work/prometheus" "$work/otlp" || fail "the names differ from /metrics: $(diff "$work/prometheus" "$work/otlp" | tr '\n' ' ')" +resource='{a["key"]: a["value"]["stringValue"] for a in d["last"]["resourceMetrics"][0]["resource"]["attributes"]}' +field "($resource[\"service.name\"], $resource[\"host.name\"])" < "$work/got" | grep -q "^('tokenmeter', 'exporter')$" || fail "the resource: $(field "$resource" < "$work/got")" +metric='[m for m in d["last"]["resourceMetrics"][0]["scopeMetrics"][0]["metrics"] if m["name"] == "NAME"][0]' +up=$(echo "$metric" | sed 's/NAME/tokenmeter_server_up/') +field "[(p[\"asDouble\"], sorted(a[\"key\"] for a in p[\"attributes\"])) for p in $up[\"gauge\"][\"dataPoints\"]]" < "$work/got" \ + | grep -q "^\[(1, \['engine', 'host', 'model', 'port'\])\]$" || fail "the server's point: $(field "$up" < "$work/got")" +total=$(echo "$metric" | sed 's/NAME/tokenmeter_tokens_generated_total/') +field "($total[\"sum\"][\"isMonotonic\"], $total[\"sum\"][\"aggregationTemporality\"], 'startTimeUnixNano' in $total[\"sum\"][\"dataPoints\"][0])" < "$work/got" \ + | grep -q "^(True, 2, True)$" || fail "a count isn't a cumulative sum: $(field "$total" < "$work/got")" +# Counts only: no client's name and no text of a request is among what was sent. +field 'sorted({a["key"] for m in d["last"]["resourceMetrics"][0]["scopeMetrics"][0]["metrics"] for k in ("gauge", "sum") if k in m for p in m[k]["dataPoints"] for a in p.get("attributes", [])})' < "$work/got" \ + | grep -q "^\['engine', 'host', 'kind', 'model', 'port'\]$" || fail "the attributes sent" + +# 4. It keeps sending at its pace, and stops when switched off. +first=$(field 'd["posts"]' < "$work/got") +sleep 22 +second=$(curl -sf $collector/got | field 'd["posts"]') +[ "$second" -ge $((first + 1)) ] && [ "$second" -le $((first + 4)) ] || fail "every 10 seconds: $first posts, then $second after 22 s" +[ "$(set_otlp '{"enabled":false}')" = 200 ] || fail "the export wasn't switched off" +sleep 6 +before=$(curl -sf $collector/got | field 'd["posts"]') +sleep 14 +[ "$(curl -sf $collector/got | field 'd["posts"]')" = "$before" ] || fail "it went on sending after it was switched off" +curl -sf $url/otlp | field '(d["enabled"], d.get("status"))' | grep -q "^(False, None)$" || fail "switched off, it still tells of a sending" + +echo "ok: the OpenTelemetry export is off until switched on, sends the figures of /metrics with the headers given, tells a refusal, and stops when switched off" diff --git a/Linux/tests/wait.sh b/Linux/tests/wait.sh index 590f139..d91c0e0 100644 --- a/Linux/tests/wait.sh +++ b/Linux/tests/wait.sh @@ -101,8 +101,12 @@ curl -sf "$ada/xray/tools?days=1" | field '[(t["name"], t["server"], t["calls"], # The Agents Live card: the call ended, seen by the reporter and both proxies, shown once. curl -sf "$ada/agents/live" | field '[(i["name"], i["server"]) for i in d["recent"] if i["kind"] == "tool"]' | grep -q "^\[('find', 'search')\]$" \ || fail "the live feed: $(curl -sf "$ada/agents/live")" -# The proxies' lines make no session of their own. -curl -sf "$ada/xray?days=1" | field 'sorted(s["source"] for s in d["sessions"])' | grep -q "^\['agent'\]$" || fail "the proxy's call made a session of its own" +# The proxies' lines make no session of their own. (A server that happens to run on this machine, such as another +# test's stand-in, shows as a "quiet" session of its own, which is none of the proxies' doing. Reports that other +# agents left in ~/.tokenmeter/reports, which every service of this user reads, would show here too.) +sources='sorted((s["source"], s["name"]) for s in d["sessions"] if s["source"] != "quiet")' +curl -sf "$ada/xray?days=1" | field "$sources" | grep -q "^\[('agent', 'test-agent')\]$" \ + || fail "the proxy's call made a session of its own: $(curl -sf "$ada/xray?days=1" | field "$sources")" # The Agents page and `tokenmeter tools`: the server's calls split call by call, not as averages. until_is $ada/tools '[(s["name"], s["kind"], s["machine"], (s.get("pairs") or {}).get("calls")) for s in d["servers"]]' "[('search', 'member', 'bo', 1)]" "the paired call isn't on search's row" diff --git a/Package.swift b/Package.swift index 113a609..430ad31 100644 --- a/Package.swift +++ b/Package.swift @@ -98,7 +98,7 @@ let sources = [ "App/PhaseHistory.swift", "App/Footprint.swift", "App/Saver.swift", - "App/SetupChecklist.swift", "App/SetupMap.swift", "App/ModelFiles.swift", "App/ModelsPage.swift", + "App/SetupChecklist.swift", "App/SetupMap.swift", "App/ModelFiles.swift", "App/ModelsPage.swift", "App/Metric.swift", "App/OTLP.swift", "App/ServicePackage.swift", "App/ServiceInstallerSources.swift", "App/RemoteInstall.swift", "App/Updates.swift", "App/PeerTraffic.swift", "App/ToolHosts.swift", "App/ToolCalls.swift", "App/WaitBreakdown.swift", "App/WireSplit.swift", @@ -143,7 +143,7 @@ let sources = [ "Linux/AlertRoutes.swift", "Linux/TargetRoutes.swift", "Linux/SpendRoutes.swift", - "Linux/MeshInstall.swift", "Linux/MeshUpdates.swift", "Linux/ToolRoutes.swift", "Linux/SetupRoutes.swift", "Linux/ModelRoutes.swift", + "Linux/MeshInstall.swift", "Linux/MeshUpdates.swift", "Linux/ToolRoutes.swift", "Linux/SetupRoutes.swift", "Linux/ModelRoutes.swift", "Linux/OTLPRoutes.swift", "Linux/ViewerRoutes.swift", "Linux/WebRoutes.swift", "Linux/WebSources.swift", diff --git a/README.md b/README.md index 487502a..876afb7 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,7 @@ The [wiki](docs/wiki/Home.md) has everything else: - [Install on macOS](docs/wiki/Install-macOS.md) and [on Linux](docs/wiki/Install-Linux.md), and [uninstalling](docs/wiki/Uninstall.md) - [What each page shows](docs/wiki/Features.md): Monitor, [Insights](docs/wiki/Features.md#insights), Servers, [Why Is It Slow?](docs/wiki/Features.md#why-is-it-slow) and [Dig Deeper](docs/wiki/Features.md#dig-deeper), Usage, Performance, [Sessions](docs/wiki/Features.md#sessions), [Tuning Lab](docs/wiki/Features.md#tuning-lab), [Machine Room](docs/wiki/Features.md#machine-room) - [Engines](docs/wiki/Engines.md): supported servers, adding one by hand, servers on other machines -- How-tos: [the mesh](docs/wiki/Mesh.md), [status endpoint and command line](docs/wiki/Status-Endpoint.md), [the Engine Proxy](docs/wiki/Proxy-Mode.md), [the MCP Proxy](docs/wiki/MCP-Proxy.md), [alerts](docs/wiki/Alerts.md), [coding agents](docs/wiki/Coding-Agents.md), [MCP server for agents](docs/wiki/MCP-Server.md), [Gizmo](docs/wiki/Gizmo.md), [power readings](docs/wiki/Power.md), [sharing a snapshot](docs/wiki/Sharing.md) +- How-tos: [the mesh](docs/wiki/Mesh.md), [status endpoint and command line](docs/wiki/Status-Endpoint.md), [Grafana board and OpenTelemetry export](docs/wiki/Status-Endpoint.md#grafana), [the Engine Proxy](docs/wiki/Proxy-Mode.md), [the MCP Proxy](docs/wiki/MCP-Proxy.md), [alerts](docs/wiki/Alerts.md), [coding agents](docs/wiki/Coding-Agents.md), [MCP server for agents](docs/wiki/MCP-Server.md), [Gizmo](docs/wiki/Gizmo.md), [power readings](docs/wiki/Power.md), [sharing a snapshot](docs/wiki/Sharing.md) - [Troubleshooting](docs/wiki/Troubleshooting.md) and [building from source](docs/wiki/Development.md) ## Contributing diff --git a/Tests/OTLPTests.swift b/Tests/OTLPTests.swift new file mode 100644 index 0000000..73dd3c3 --- /dev/null +++ b/Tests/OTLPTests.swift @@ -0,0 +1,82 @@ +import Foundation + +/// The OpenTelemetry export: where it posts, the headers it sends, and the body, which carries the figures of +/// `GET /metrics` under the same names. +extension Tests { + static func otlp() { + // MARK: Where it posts. + equal(OTLP.endpoint("http://localhost:4318")?.absoluteString, "http://localhost:4318/v1/metrics", "the path is added") + equal(OTLP.endpoint(" http://localhost:4318/ ")?.absoluteString, "http://localhost:4318/v1/metrics", "after a trailing slash too") + equal(OTLP.endpoint("https://otlp.example.com/v1/metrics")?.absoluteString, "https://otlp.example.com/v1/metrics", "a whole address is kept") + equal(OTLP.endpoint("https://api.example.com/otlp")?.absoluteString, "https://api.example.com/otlp/v1/metrics", "a path in front stays in front") + expect(OTLP.endpoint("localhost:4318") == nil, "an address without http is refused") + expect(OTLP.endpoint("ftp://example.com") == nil, "and another scheme") + expect(OTLP.endpoint("") == nil, "and nothing") + + // MARK: The headers. + let headers = OTLP.headers("x-honeycomb-team: abc123\nAuthorization=Bearer t0k=n, DD-API-KEY: k\nnot a header\n: empty\nname:") + equal(headers.map(\.name), ["x-honeycomb-team", "Authorization", "DD-API-KEY"], "a line or a comma apart, with a colon or an equals sign") + equal(headers.map(\.value), ["abc123", "Bearer t0k=n", "k"], "the value keeps what follows the first sign") + equal(OTLP.headers("").count, 0, "no headers") + + // MARK: The body. + let now = Date(timeIntervalSince1970: 1_800_000_000), started = Date(timeIntervalSince1970: 1_799_990_000) + let server = [Metric.Label("engine", "llama.cpp"), Metric.Label("model", "qwen \"q4\""), Metric.Label("port", "8080")] + let metrics = [ + Metric(name: "tokenmeter_generation_tokens_per_second", help: "Tokens being written per second.", points: [Metric.Point(labels: server, value: 42.5)]), + Metric(name: "tokenmeter_tokens_generated_total", help: "Tokens written since the server started.", counter: true, + points: [Metric.Point(labels: server, value: 9000, since: Date(timeIntervalSince1970: 1_799_999_000)), Metric.Point(labels: [], value: 5)]), + Metric(name: "tokenmeter_nothing", help: "No points.", points: []), + ] + equal(OTLP.points(metrics), 3, "the values in one export") + let data = OTLP.body(metrics, host: "studio", version: "0.9.11", started: started, now: now) + let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + let resources = json?["resourceMetrics"] as? [[String: Any]] + let resource = resources?.first?["resource"] as? [String: Any] + let named = (resource?["attributes"] as? [[String: Any]] ?? []).map { ($0["key"] as? String ?? "") + "=" + (($0["value"] as? [String: Any])?["stringValue"] as? String ?? "") } + equal(named, ["service.name=tokenmeter", "service.version=0.9.11", "service.instance.id=studio", "host.name=studio"], + "the resource names the service and the machine") + let scopes = resources?.first?["scopeMetrics"] as? [[String: Any]] + let sent = scopes?.first?["metrics"] as? [[String: Any]] ?? [] + equal(sent.map { $0["name"] as? String ?? "" }, ["tokenmeter_generation_tokens_per_second", "tokenmeter_tokens_generated_total"], + "the same names as /metrics, without the one that has no value") + let gauge = sent.first?["gauge"] as? [String: Any] + let level = (gauge?["dataPoints"] as? [[String: Any]])?.first + equal(level?["asDouble"] as? Double, 42.5, "a level is a gauge") + equal(level?["timeUnixNano"] as? String, "1800000000000000000", "timed in nanoseconds, as text") + expect(level?["startTimeUnixNano"] == nil, "a gauge has no start") + let labels = (level?["attributes"] as? [[String: Any]] ?? []).map { ($0["key"] as? String ?? "") + "=" + (($0["value"] as? [String: Any])?["stringValue"] as? String ?? "") } + equal(labels, ["engine=llama.cpp", "model=qwen \"q4\"", "port=8080"], "its labels are attributes") + let sum = sent.last?["sum"] as? [String: Any] + equal(sum?["aggregationTemporality"] as? Int, 2, "a count is cumulative") + equal(sum?["isMonotonic"] as? Bool, true, "and only rises") + let counts = sum?["dataPoints"] as? [[String: Any]] ?? [] + equal(counts.first?["startTimeUnixNano"] as? String, "1799999000000000000", "from when its server started") + equal(counts.last?["startTimeUnixNano"] as? String, "1799990000000000000", "or the service, where the server doesn't say") + expect(counts.last?["attributes"] == nil, "no labels, no attributes") + expect(!String(decoding: data, as: UTF8.self).contains("prompt\":\""), "nothing but names and numbers") + + // MARK: The Prometheus page from the same list. + let text = Metric.prometheus(metrics) + expect(text.contains("# TYPE tokenmeter_tokens_generated_total counter\n"), "a count is a counter") + expect(text.contains("tokenmeter_generation_tokens_per_second{engine=\"llama.cpp\",model=\"qwen \\\"q4\\\"\",port=\"8080\"} 42.5\n"), "labels escaped") + expect(text.contains("tokenmeter_tokens_generated_total 5\n"), "a whole number without a decimal, and no braces without labels") + expect(!text.contains("tokenmeter_nothing"), "a figure without values is left out") + equal(Metric.prometheus([]), "", "nothing to say") + + // MARK: The Grafana board graphs only figures that exist. + let root = FileManager.default.currentDirectoryPath + let sources = ["App/StatusJSON.swift", "App/TargetStore.swift"].compactMap { try? String(contentsOfFile: root + "/" + $0, encoding: .utf8) }.joined() + if let board = try? String(contentsOfFile: root + "/docs/grafana/tokenmeter.json", encoding: .utf8), !sources.isEmpty { + expect((try? JSONSerialization.jsonObject(with: Data(board.utf8))) != nil, "the board is JSON") + var names = Set() + for piece in board.components(separatedBy: "tokenmeter_").dropFirst() { + names.insert(String(piece.prefix { $0.isLetter || $0 == "_" })) + } + expect(names.count >= 15, "the board graphs the figures (\(names.count))") + for name in names.sorted() where !name.isEmpty { + expect(sources.contains("gauge(\"\(name)\"") || sources.contains("\"tokenmeter_\(name)\""), "the board's tokenmeter_\(name) is a figure of /metrics") + } + } + } +} diff --git a/Tests/Tests.swift b/Tests/Tests.swift index eb8a070..43fd08e 100644 --- a/Tests/Tests.swift +++ b/Tests/Tests.swift @@ -164,6 +164,7 @@ enum Tests { openAIEngine() reliability() modelsPage() + otlp() print(failures == 0 ? "\(checks) checks passed." : "\(failures) of \(checks) checks failed.") exit(failures == 0 ? 0 : 1) } diff --git a/build-library-app.sh b/build-library-app.sh index 8fe56cb..2630871 100755 --- a/build-library-app.sh +++ b/build-library-app.sh @@ -18,7 +18,7 @@ for word in "$@"; do esac done app="$project_dir/Tokenmeter.app" -version=${APP_VERSION:-0.9.10} +version=${APP_VERSION:-0.9.11} build=${APP_BUILD:-1} # SwiftUI's @State is a compiler macro in the macOS 26 SDK. The Command Line Tools ship that SDK without diff --git a/docs/grafana/tokenmeter.json b/docs/grafana/tokenmeter.json new file mode 100644 index 0000000..a4a43eb --- /dev/null +++ b/docs/grafana/tokenmeter.json @@ -0,0 +1,1194 @@ +{ + "__inputs": [ + { + "name": "DS_PROMETHEUS", + "label": "Prometheus", + "description": "The Prometheus (or Mimir, VictoriaMetrics\u2026) data source that holds Tokenmeter's figures", + "type": "datasource", + "pluginId": "prometheus", + "pluginName": "Prometheus" + } + ], + "__requires": [ + { + "type": "grafana", + "id": "grafana", + "name": "Grafana", + "version": "10.0.0" + }, + { + "type": "datasource", + "id": "prometheus", + "name": "Prometheus", + "version": "1.0.0" + }, + { + "type": "panel", + "id": "stat", + "name": "Stat", + "version": "" + }, + { + "type": "panel", + "id": "timeseries", + "name": "Time series", + "version": "" + } + ], + "title": "Tokenmeter", + "uid": "tokenmeter-overview", + "description": "Local inference as Tokenmeter sees it: speed, load, the machine and targets. Reads the figures of GET /metrics, scraped by Prometheus or sent by Tokenmeter's OpenTelemetry export under the same names.", + "tags": [ + "tokenmeter", + "llm", + "inference" + ], + "schemaVersion": 39, + "version": 1, + "editable": true, + "graphTooltip": 1, + "refresh": "30s", + "time": { + "from": "now-6h", + "to": "now" + }, + "timezone": "browser", + "templating": { + "list": [ + { + "name": "instance", + "label": "Machine", + "type": "query", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "query": { + "query": "label_values(tokenmeter_servers_online, instance)", + "refId": "instances" + }, + "definition": "label_values(tokenmeter_servers_online, instance)", + "includeAll": true, + "allValue": ".*", + "multi": true, + "refresh": 2, + "sort": 1, + "current": { + "selected": true, + "text": "All", + "value": "$__all" + } + } + ] + }, + "annotations": { + "list": [] + }, + "links": [ + { + "title": "Tokenmeter", + "url": "https://github.com/tokenmeter1/Tokenmeter", + "type": "link", + "targetBlank": true + } + ], + "panels": [ + { + "id": 1, + "type": "stat", + "title": "Servers online", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 0, + "y": 0, + "w": 4, + "h": 4 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum(tokenmeter_servers_online{instance=~\"$instance\"})", + "legendFormat": "", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "color": { + "mode": "fixed", + "fixedColor": "blue" + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto" + }, + "description": "Servers answering now, over the machines picked." + }, + { + "id": 2, + "type": "stat", + "title": "Writing now", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 4, + "y": 0, + "w": 5, + "h": 4 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum(tokenmeter_generation_tokens_per_second{instance=~\"$instance\"})", + "legendFormat": "", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "decimals": 1, + "color": { + "mode": "fixed", + "fixedColor": "blue" + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto" + }, + "description": "Tokens being written per second, every server together." + }, + { + "id": 3, + "type": "stat", + "title": "Requests running", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 9, + "y": 0, + "w": 4, + "h": 4 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum(tokenmeter_active_requests{instance=~\"$instance\"})", + "legendFormat": "", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "color": { + "mode": "fixed", + "fixedColor": "blue" + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto" + } + }, + { + "id": 4, + "type": "stat", + "title": "Requests waiting", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 13, + "y": 0, + "w": 4, + "h": 4 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum(tokenmeter_deferred_requests{instance=~\"$instance\"})", + "legendFormat": "", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "color": { + "mode": "fixed", + "fixedColor": "blue" + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto" + }, + "description": "Requests waiting for a slot." + }, + { + "id": 5, + "type": "stat", + "title": "Tokens today", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 17, + "y": 0, + "w": 4, + "h": 4 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum(tokenmeter_today_tokens{instance=~\"$instance\",kind=~\"prompt|output\"})", + "legendFormat": "", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "color": { + "mode": "fixed", + "fixedColor": "blue" + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto" + }, + "description": "Prompt and output tokens counted today." + }, + { + "id": 6, + "type": "stat", + "title": "Requests today", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 21, + "y": 0, + "w": 3, + "h": 4 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum(tokenmeter_today_requests{instance=~\"$instance\"})", + "legendFormat": "", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "color": { + "mode": "fixed", + "fixedColor": "blue" + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto" + } + }, + { + "id": 7, + "type": "row", + "title": "Speed", + "collapsed": false, + "gridPos": { + "x": 0, + "y": 4, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "id": 8, + "type": "timeseries", + "title": "Writing speed", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 0, + "y": 5, + "w": 12, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_generation_tokens_per_second{instance=~\"$instance\"}", + "legendFormat": "{{model}} :{{port}} \u00b7 {{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "description": "Tokens written per second, for each server." + }, + { + "id": 9, + "type": "timeseries", + "title": "Reading speed", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 12, + "y": 5, + "w": 12, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_prompt_tokens_per_second{instance=~\"$instance\"}", + "legendFormat": "{{model}} :{{port}} \u00b7 {{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "description": "Prompt tokens read per second, for each server." + }, + { + "id": 10, + "type": "timeseries", + "title": "Tokens written, per second over 5 minutes", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 0, + "y": 13, + "w": 8, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "rate(tokenmeter_tokens_generated_total{instance=~\"$instance\"}[5m])", + "legendFormat": "{{model}} :{{port}} \u00b7 {{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "description": "From each server's own count since it started." + }, + { + "id": 11, + "type": "timeseries", + "title": "Requests served, per minute", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 8, + "y": 13, + "w": 8, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "rate(tokenmeter_requests_total{instance=~\"$instance\"}[5m]) * 60", + "legendFormat": "{{model}} :{{port}} \u00b7 {{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + } + }, + { + "id": 12, + "type": "timeseries", + "title": "Time to first token", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 16, + "y": 13, + "w": 8, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_first_token_seconds{instance=~\"$instance\"}", + "legendFormat": "{{model}} :{{port}} \u00b7 {{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "description": "The typical (median) wait from a request's arrival to its first token, where the engine measures it." + }, + { + "id": 13, + "type": "row", + "title": "Load", + "collapsed": false, + "gridPos": { + "x": 0, + "y": 21, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "id": 14, + "type": "timeseries", + "title": "Requests running and waiting", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 0, + "y": 22, + "w": 8, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_active_requests{instance=~\"$instance\"}", + "legendFormat": "running \u00b7 {{model}} :{{port}}", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_deferred_requests{instance=~\"$instance\"}", + "legendFormat": "waiting \u00b7 {{model}} :{{port}}", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + } + }, + { + "id": 15, + "type": "timeseries", + "title": "Context in use", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 8, + "y": 22, + "w": 8, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_context_used_ratio{instance=~\"$instance\"}", + "legendFormat": "{{model}} :{{port}} \u00b7 {{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "max": 1, + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + } + }, + { + "id": 16, + "type": "timeseries", + "title": "Server up", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 16, + "y": 22, + "w": 8, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_server_up{instance=~\"$instance\"}", + "legendFormat": "{{model}} :{{port}} \u00b7 {{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "max": 1, + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "description": "1 while the server is online." + }, + { + "id": 17, + "type": "row", + "title": "Machine", + "collapsed": false, + "gridPos": { + "x": 0, + "y": 30, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "id": 18, + "type": "timeseries", + "title": "GPU load", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 0, + "y": 31, + "w": 6, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_gpu_utilization_percent{instance=~\"$instance\"}", + "legendFormat": "{{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percent", + "max": 100, + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + } + }, + { + "id": 19, + "type": "timeseries", + "title": "Power", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 6, + "y": 31, + "w": 6, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_power_watts{instance=~\"$instance\"}", + "legendFormat": "{{instance}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "watt", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "description": "What the processor and graphics draw." + }, + { + "id": 20, + "type": "timeseries", + "title": "Memory", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 12, + "y": 31, + "w": 6, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_memory_available_gigabytes{instance=~\"$instance\"}", + "legendFormat": "available \u00b7 {{instance}}", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_memory_total_gigabytes{instance=~\"$instance\"}", + "legendFormat": "total \u00b7 {{instance}}", + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_swap_used_gigabytes{instance=~\"$instance\"}", + "legendFormat": "swap \u00b7 {{instance}}", + "refId": "C" + } + ], + "fieldConfig": { + "defaults": { + "unit": "decgbytes", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + } + }, + { + "id": 21, + "type": "timeseries", + "title": "Model and GPU memory", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 18, + "y": 31, + "w": 6, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_model_memory_gigabytes{instance=~\"$instance\"}", + "legendFormat": "{{model}} :{{port}} \u00b7 {{instance}}", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_gpu_memory_gigabytes{instance=~\"$instance\"}", + "legendFormat": "GPU \u00b7 {{instance}}", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "decgbytes", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + } + }, + { + "id": 22, + "type": "row", + "title": "Targets", + "collapsed": false, + "gridPos": { + "x": 0, + "y": 39, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "id": 23, + "type": "timeseries", + "title": "Budget left", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 0, + "y": 40, + "w": 12, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_target_budget_remaining{instance=~\"$instance\"}", + "legendFormat": "{{model}} \u00b7 {{figure}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "max": 1, + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "description": "Share of each target's error budget left over its window. Empty until a target is set on the Performance page." + }, + { + "id": 24, + "type": "timeseries", + "title": "Burn rate, 1 hour", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "x": 12, + "y": 40, + "w": 12, + "h": 8 + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "tokenmeter_target_burn_rate{instance=~\"$instance\",window=\"1h\"}", + "legendFormat": "{{model}} \u00b7 {{figure}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 8, + "showPoints": "never", + "spanNulls": false + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "description": "1 spends the budget exactly by the window's end." + } + ] +} diff --git a/docs/images/grafana-board.png b/docs/images/grafana-board.png new file mode 100644 index 0000000..25c5d9b Binary files /dev/null and b/docs/images/grafana-board.png differ diff --git a/docs/wiki/Features.md b/docs/wiki/Features.md index e90a792..a3d61f3 100644 --- a/docs/wiki/Features.md +++ b/docs/wiki/Features.md @@ -522,7 +522,7 @@ Settings has six sections, the same on the Mac (buttons across the top) and on L |---|---| | General | Open at login (Mac), Show Welcome, speed in the menu bar (Mac), text size and contrast, **Storage** (what Tokenmeter keeps on disk, see below), and [updates](Mesh.md#updating-the-machines) for the whole mesh | | Alerts | The [alerts](Alerts.md) Tokenmeter notifies about, and the ntfy topic that takes them to your phone (On Your Phone) | -| Network | The [status endpoint](Status-Endpoint.md) and keeping this machine to itself. Other machines and what they may read are on the [Mesh page](Mesh.md) | +| Network | The [status endpoint](Status-Endpoint.md) and keeping this machine to itself, and since 0.9.11 the [OpenTelemetry export](Status-Endpoint.md#opentelemetry-export) (off until switched on). Other machines and what they may read are on the [Mesh page](Mesh.md) | | Proxies | The [Engine Proxy](Proxy-Mode.md) in front of an inference server and, since 0.8.7, the [MCP Proxy](MCP-Proxy.md) in front of a coding agent's MCP server, and opening either to Docker, VMs and other machines | | Gizmo | Star economy, humor, notifications, reset, and whether Gizmo is in sync with each connected machine | | About | Version, project link, and Tokenmeter's own footprint: its share of a processor core, memory, open files against the limit, and the slowest engine refresh of the last five minutes. If its open files or memory keep climbing, or it stays busy with nothing to do, Insights says so | diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 9d1a305..033fc5c 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -19,7 +19,7 @@ Tokenmeter watches the LLM inference servers on your computer, shows how fast th ## How-tos - [The mesh](Mesh.md): putting your machines together, letting one in, removing one, installing on another machine and updating them all -- [Status endpoint and the `tokenmeter` command](Status-Endpoint.md): JSON, Prometheus/Grafana, status bars, other machines +- [Status endpoint and the `tokenmeter` command](Status-Endpoint.md): JSON, Prometheus, a Grafana board to import, the OpenTelemetry export, status bars, other machines - [the Engine Proxy](Proxy-Mode.md): name the app behind each request, and count tokens for servers that report none - [The MCP Proxy](MCP-Proxy.md): time every tool call of a coding agent's MCP server, for any agent - [Alerts](Alerts.md): a notification when a server stops or memory runs out diff --git a/docs/wiki/Status-Endpoint.md b/docs/wiki/Status-Endpoint.md index 64ffc9b..766c272 100644 --- a/docs/wiki/Status-Endpoint.md +++ b/docs/wiki/Status-Endpoint.md @@ -128,3 +128,22 @@ scrape_configs: ``` The machine must let other machines read it (above). Run `tokenmeter metrics` to see the metric names to graph. + +Since 0.9.11 there is a board to import: [`docs/grafana/tokenmeter.json`](../grafana/tokenmeter.json). In Grafana choose **Dashboards › New › Import**, upload the file and pick your Prometheus data source. It shows what is being written now, speed by server, the load, the machine (GPU, power, memory) and your [targets](Targets.md), with a **Machine** picker when several machines are scraped. + +![The Grafana board](../images/grafana-board.png) + +## OpenTelemetry export + +Since 0.9.11, for those who already run a collector: **Settings › Network › OpenTelemetry Export** sends the same figures to it as OTLP over HTTP (JSON), under the same names, so the board above reads them whichever way they came. It is off until you give an address and switch it on, and each machine sends its own. + +- **Collector:** the address of an OTLP/HTTP receiver, such as `http://localhost:4318` for an OpenTelemetry Collector or Grafana Alloy on the same machine. `/v1/metrics` is added unless the address already ends in it. The body is JSON, which the OpenTelemetry Collector and Grafana Alloy take as they are; from there the figures go on to Prometheus, Grafana Cloud, Datadog, Honeycomb or wherever your collector already sends. A hosted service can be given directly where its OTLP address accepts JSON. +- **Headers:** what the receiver wants as a key, one on a line: `x-honeycomb-team: your-key` or `Authorization: Basic …`. Their values are kept by the service and never shown again, here or by `GET /otlp`. +- **Send every:** 15 seconds to 5 minutes; a minute unless changed. + +What is sent is exactly what `/metrics` lists: counts, speeds and sizes for each server (labelled with its engine, model, host and port), the machine's GPU, power and memory, today's tokens and requests, and your targets. No prompt, no reply and no client's name. The machine's name goes along as `host.name` and `service.instance.id`. Levels are sent as gauges; the three counts since a server started (`tokens_generated_total`, `prompt_tokens_total`, `requests_total`) as cumulative sums that begin when the server did. Settings shows when it last sent and what the collector answered. + +| | | +|---|---| +| `GET /otlp` | From this machine only: `enabled`, `endpoint`, `target` (where it posts), `headerNames`, `seconds`, `status` and `points` (values in one export) | +| `POST /otlp` | From this machine only: `{"enabled": true, "endpoint": "http://localhost:4318", "headers": "name: value", "seconds": 60}`, each optional. An empty `endpoint` switches the export off | diff --git a/scripts/check.sh b/scripts/check.sh index e8dd99c..13ec55b 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -29,7 +29,7 @@ project_dir=$(cd "$(dirname "$0")/.." && pwd) cd "$project_dir" # The service tests, in the workflow's order. `machines` reads a service this script starts for it. -service_tests="gpu machines mesh viewer phone-alerts alerts alert-channels alerts-remote targets-remote targets spend drills gizmo-guide tools mcp-proxy wait history-line history-store storage wire stream workload share bench other-engine models" +service_tests="gpu machines mesh viewer phone-alerts alerts alert-channels alerts-remote targets-remote targets spend drills gizmo-guide tools mcp-proxy wait history-line history-store storage wire stream workload share bench other-engine models otlp" quick_tests="wire storage history-store mesh" extra_tests="idle-budget drill-screens gizmo-screens" diff --git a/scripts/package-flatpak.sh b/scripts/package-flatpak.sh index 5596f91..a45e169 100755 --- a/scripts/package-flatpak.sh +++ b/scripts/package-flatpak.sh @@ -7,7 +7,7 @@ # Needs flatpak and flatpak-builder; the KDE runtime and SDK are fetched from Flathub. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.10} +version=${APP_VERSION:-0.9.11} arch=$(uname -m) id=io.github.tokenmeter1.tokenmeter name="Tokenmeter-$version-linux-$arch" diff --git a/scripts/package-linux.sh b/scripts/package-linux.sh index c09d58e..11b4f0d 100755 --- a/scripts/package-linux.sh +++ b/scripts/package-linux.sh @@ -4,7 +4,7 @@ # and install.sh. Needs the Swift toolchain; run it on Linux. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.10} +version=${APP_VERSION:-0.9.11} arch=$(uname -m) name="Tokenmeter-$version-linux-$arch" diff --git a/scripts/package-service.sh b/scripts/package-service.sh index 06bc2c4..0e100ff 100755 --- a/scripts/package-service.sh +++ b/scripts/package-service.sh @@ -18,7 +18,7 @@ # On a Mac, SIGN_IDENTITY signs the program with a Developer ID; without it the program is ad-hoc signed. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.10} +version=${APP_VERSION:-0.9.11} case "$(uname -s)" in Darwin) os=macos ;; Linux) os=linux ;; diff --git a/scripts/package.sh b/scripts/package.sh index f91c8cd..f1b5112 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -16,7 +16,7 @@ set -euo pipefail project_dir=${0:A:h:h} app="$project_dir/Tokenmeter.app" dist="$project_dir/dist" -export APP_VERSION=${APP_VERSION:-0.9.10} +export APP_VERSION=${APP_VERSION:-0.9.11} identity=${SIGN_IDENTITY:-} profile=${NOTARY_PROFILE:-}