Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"'
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion Android/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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]*}))

Expand Down
1 change: 1 addition & 0 deletions App/Alerts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ final class AlertCenter {
private func check() {
sendHeld()
AlertHeartbeat.tick()
OTLPExport.tick()
TargetStore.shared.tick()
SpendLedger.shared.tick()
checkInsights()
Expand Down
46 changes: 46 additions & 0 deletions App/Metric.swift
Original file line number Diff line number Diff line change
@@ -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"
}
}
194 changes: 194 additions & 0 deletions App/OTLP.swift
Original file line number Diff line number Diff line change
@@ -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[..<cut].trimmingCharacters(in: .whitespaces)
let value = line[line.index(after: cut)...].trimmingCharacters(in: .whitespaces)
guard !name.isEmpty, !value.isEmpty, name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }) else { continue }
found.append((name, value))
}
return found
}

private static func nanos(_ date: Date) -> 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()))
}
}
1 change: 1 addition & 0 deletions App/SettingsIndex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
69 changes: 69 additions & 0 deletions App/SettingsPage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Bool>(get: { answer?.enabled ?? false }, set: { change(["enabled": $0]) })
let every = Binding<Int>(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 {
Expand Down Expand Up @@ -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.")
Expand Down
Loading
Loading