feat: expose Jeannie API metrics
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-10-16 13:54:33 -06:00
parent df6ae89e7d
commit dd89e19e37
2 changed files with 100 additions and 9 deletions

View File

@ -47,12 +47,36 @@ type execution struct {
EndedAt *time.Time `json:"ended_at,omitempty"`
}
type requestMetric struct {
count uint64
totalDuration time.Duration
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(body []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(body)
}
type server struct {
mu sync.RWMutex
exec map[string]*execution
repoRoot string
token string
temporal client.Client
mu sync.RWMutex
exec map[string]*execution
repoRoot string
token string
temporal client.Client
requests map[string]*requestMetric
authFailures uint64
}
func main() {
@ -61,7 +85,12 @@ func main() {
root, _ = os.Getwd()
}
root, _ = filepath.Abs(root)
s := &server{exec: make(map[string]*execution), repoRoot: root, token: os.Getenv("JEANNIE_SERVER_TOKEN")}
s := &server{
exec: make(map[string]*execution),
repoRoot: root,
token: os.Getenv("JEANNIE_SERVER_TOKEN"),
requests: make(map[string]*requestMetric),
}
if os.Getenv("JEANNIE_EXECUTION_MODE") == "temporal" {
address := os.Getenv("JEANNIE_TEMPORAL_ADDRESS")
if address == "" {
@ -77,6 +106,7 @@ func main() {
}
mux := http.NewServeMux()
mux.HandleFunc("/v1/health", s.auth(s.health))
mux.HandleFunc("/metrics", s.auth(s.metrics))
mux.HandleFunc("/v1/commands", s.auth(s.commands))
mux.HandleFunc("/v1/execute", s.auth(s.execute))
mux.HandleFunc("/v1/executions/", s.auth(s.execution))
@ -88,7 +118,7 @@ func main() {
fmt.Fprintln(os.Stderr, "JEANNIE_SERVER_TOKEN is required when the API is not loopback-bound")
os.Exit(2)
}
httpServer := &http.Server{Addr: addr, Handler: logging(mux), ReadHeaderTimeout: 5 * time.Second}
httpServer := &http.Server{Addr: addr, Handler: s.logging(mux), ReadHeaderTimeout: 5 * time.Second}
fmt.Printf("Jeannie API listening on %s\n", addr)
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
fmt.Fprintln(os.Stderr, err)
@ -99,6 +129,9 @@ func main() {
func (s *server) auth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if s.token != "" && r.Header.Get("Authorization") != "Bearer "+s.token {
s.mu.Lock()
s.authFailures++
s.mu.Unlock()
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
return
}
@ -106,6 +139,39 @@ func (s *server) auth(next http.HandlerFunc) http.HandlerFunc {
}
}
func (s *server) metrics(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
s.mu.RLock()
defer s.mu.RUnlock()
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
fmt.Fprintln(w, "# HELP jeannie_http_requests_total Total HTTP requests handled by Jeannie.")
fmt.Fprintln(w, "# TYPE jeannie_http_requests_total counter")
for key, metric := range s.requests {
parts := strings.SplitN(key, "|", 3)
if len(parts) != 3 {
continue
}
method, path, status := parts[0], parts[1], parts[2]
fmt.Fprintf(w, "jeannie_http_requests_total{method=%q,path=%q,status=%q} %d\n", method, path, status, metric.count)
}
fmt.Fprintln(w, "# HELP jeannie_http_request_duration_seconds_sum Total HTTP request duration in seconds.")
fmt.Fprintln(w, "# TYPE jeannie_http_request_duration_seconds_sum counter")
for key, metric := range s.requests {
parts := strings.SplitN(key, "|", 3)
if len(parts) != 3 {
continue
}
method, path, status := parts[0], parts[1], parts[2]
fmt.Fprintf(w, "jeannie_http_request_duration_seconds_sum{method=%q,path=%q,status=%q} %f\n", method, path, status, metric.totalDuration.Seconds())
}
fmt.Fprintln(w, "# HELP jeannie_auth_failures_total Total rejected authentication attempts.")
fmt.Fprintln(w, "# TYPE jeannie_auth_failures_total counter")
fmt.Fprintf(w, "jeannie_auth_failures_total %d\n", s.authFailures)
}
func (s *server) health(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
@ -272,9 +338,29 @@ func writeJSON(w http.ResponseWriter, status int, value any) {
_ = json.NewEncoder(w).Encode(value)
}
func logging(next http.Handler) http.Handler {
func (s *server) logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
capture := &statusWriter{ResponseWriter: w}
fmt.Printf("%s %s %s\n", time.Now().UTC().Format(time.RFC3339), r.Method, r.URL.Path)
next.ServeHTTP(w, r)
next.ServeHTTP(capture, r)
status := capture.status
if status == 0 {
status = http.StatusOK
}
path := r.URL.Path
if strings.HasPrefix(path, "/v1/executions/") {
path = "/v1/executions/:id"
}
key := fmt.Sprintf("%s|%s|%d", r.Method, path, status)
s.mu.Lock()
metric := s.requests[key]
if metric == nil {
metric = &requestMetric{}
s.requests[key] = metric
}
metric.count++
metric.totalDuration += time.Since(started)
s.mu.Unlock()
})
}

View File

@ -25,6 +25,11 @@ stored in memory and command output is returned through
GET /v1/executions/{id}. It is not a public edge service and does not accept
arbitrary shell commands.
The authenticated `GET /metrics` endpoint exposes Prometheus-compatible HTTP
request counters, request duration totals, and authentication-failure counts.
It is served by the Debian API process, so metrics remain available while
Kubernetes is stopped; Prometheus may scrape it when the cluster is healthy.
## Edge API gateway
The canonical public route publishes the Debian API directly through the OCI