Merge branches 'swarm/rekey', 'swarm/audit-otel' and 'swarm/helm-docs'
This commit is contained in:
37 files changed
+3686
-1
No files matched your search
@@ -0,0 +1,159 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"filippo.io/age"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/buildinfo"
|
||||
"github.com/samcharles93/archie-core/internal/platform/pg"
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/events"
|
||||
)
|
||||
|
||||
const rekeyLockKey = "archie.rekey.owner"
|
||||
|
||||
// RekeyConfig holds the old and new age identities and optional backup
|
||||
// recipients used by `archie rekey`.
|
||||
type RekeyConfig struct {
|
||||
OldIdentity string
|
||||
NewIdentity string
|
||||
NewBackups []string
|
||||
}
|
||||
|
||||
// LoadRekeyConfig resolves old and new age identities from flags or
|
||||
// ARCHIE_OLD_AGE_IDENTITY[_FILE] and ARCHIE_NEW_AGE_IDENTITY[_FILE], and
|
||||
// validates that both are non-empty, valid, and distinct.
|
||||
func LoadRekeyConfig(oldIdentity, newIdentity string, newBackups []string) (RekeyConfig, error) {
|
||||
oldVal := strings.TrimSpace(oldIdentity)
|
||||
if envOld, ok, err := envOrFile("ARCHIE_OLD_AGE_IDENTITY", "ARCHIE_OLD_AGE_IDENTITY_FILE"); err != nil {
|
||||
return RekeyConfig{}, err
|
||||
} else if ok {
|
||||
oldVal = envOld
|
||||
}
|
||||
|
||||
newVal := strings.TrimSpace(newIdentity)
|
||||
if envNew, ok, err := envOrFile("ARCHIE_NEW_AGE_IDENTITY", "ARCHIE_NEW_AGE_IDENTITY_FILE"); err != nil {
|
||||
return RekeyConfig{}, err
|
||||
} else if ok {
|
||||
newVal = envNew
|
||||
}
|
||||
|
||||
backups := make([]string, len(newBackups))
|
||||
for i, b := range newBackups {
|
||||
backups[i] = strings.TrimSpace(b)
|
||||
}
|
||||
|
||||
rcfg := RekeyConfig{
|
||||
OldIdentity: oldVal,
|
||||
NewIdentity: newVal,
|
||||
NewBackups: backups,
|
||||
}
|
||||
if _, _, err := rcfg.sealers(); err != nil {
|
||||
return RekeyConfig{}, err
|
||||
}
|
||||
return rcfg, nil
|
||||
}
|
||||
|
||||
func (c RekeyConfig) sealers() (oldSealer, newSealer *seal.Sealer, err error) {
|
||||
if c.OldIdentity == "" {
|
||||
return nil, nil, errors.New("old age identity is required")
|
||||
}
|
||||
if c.NewIdentity == "" {
|
||||
return nil, nil, errors.New("new age identity is required")
|
||||
}
|
||||
oldID, err := age.ParseX25519Identity(c.OldIdentity)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("old age identity: %w", err)
|
||||
}
|
||||
newID, err := age.ParseX25519Identity(c.NewIdentity)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("new age identity: %w", err)
|
||||
}
|
||||
if oldID.String() == newID.String() {
|
||||
return nil, nil, errors.New("old and new age identities must be distinct")
|
||||
}
|
||||
oldSealer, err = seal.New(oldID.String(), nil)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("old sealer: %w", err)
|
||||
}
|
||||
newSealer, err = seal.New(newID.String(), c.NewBackups)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("new sealer: %w", err)
|
||||
}
|
||||
return oldSealer, newSealer, nil
|
||||
}
|
||||
|
||||
// Rekey rotates age sealing identities atomically across connectors credentials
|
||||
// and event HMAC secrets under a Postgres advisory lock.
|
||||
func Rekey(ctx context.Context, configPath string, rcfg RekeyConfig) error {
|
||||
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version)
|
||||
oldSealer, newSealer, err := rcfg.sealers()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dbURL, err := LoadRuntimeDBConfig(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
db, err := pg.Open(ctx, dbURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
if err := pg.VerifySchema(ctx, db); err != nil {
|
||||
return err
|
||||
}
|
||||
release, err := lockRekey(ctx, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
|
||||
tx, err := db.BeginTxx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin rekey transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
creds, err := connectors.RekeyCredentials(ctx, tx, oldSealer, newSealer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sources, err := events.RekeySources(ctx, tx, oldSealer, newSealer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit rekey transaction: %w", err)
|
||||
}
|
||||
log.InfoContext(ctx, "age sealing keys rotated",
|
||||
"credentials_rekeyed", creds,
|
||||
"sources_rekeyed", sources,
|
||||
"backup_recipients", len(rcfg.NewBackups),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
func lockRekey(ctx context.Context, db *sqlx.DB) (func(), error) {
|
||||
conn, err := db.Conn(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lock rekey: %w", err)
|
||||
}
|
||||
if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_lock(hashtextextended($1, 0))", rekeyLockKey); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("lock rekey: %w", err)
|
||||
}
|
||||
return func() {
|
||||
_, _ = conn.ExecContext(context.WithoutCancel(ctx),
|
||||
"SELECT pg_advisory_unlock(hashtextextended($1, 0))", rekeyLockKey)
|
||||
_ = conn.Close()
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"filippo.io/age"
|
||||
)
|
||||
|
||||
func genAgeIdentity(t *testing.T) *age.X25519Identity {
|
||||
t.Helper()
|
||||
id, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// TestLoadRekeyConfigValidationAndOverrides guards `archie rekey` key parsing,
|
||||
// *_FILE secret loading, ambiguity refusal, and identical-key rejection.
|
||||
func TestLoadRekeyConfigValidationAndOverrides(t *testing.T) {
|
||||
oldID := genAgeIdentity(t)
|
||||
newID := genAgeIdentity(t)
|
||||
backupID := genAgeIdentity(t)
|
||||
|
||||
dir := t.TempDir()
|
||||
oldFile := filepath.Join(dir, "old_age_key")
|
||||
newFile := filepath.Join(dir, "new_age_key")
|
||||
if err := os.WriteFile(oldFile, []byte(oldID.String()+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(newFile, []byte(newID.String()+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Run("flags", func(t *testing.T) {
|
||||
cfg, err := LoadRekeyConfig(oldID.String(), newID.String(), []string{backupID.Recipient().String()})
|
||||
if err != nil {
|
||||
t.Fatalf("LoadRekeyConfig: %v", err)
|
||||
}
|
||||
if cfg.OldIdentity != oldID.String() || cfg.NewIdentity != newID.String() || len(cfg.NewBackups) != 1 {
|
||||
t.Fatalf("unexpected RekeyConfig: %+v", cfg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("env file overrides", func(t *testing.T) {
|
||||
t.Setenv("ARCHIE_OLD_AGE_IDENTITY_FILE", oldFile)
|
||||
t.Setenv("ARCHIE_NEW_AGE_IDENTITY_FILE", newFile)
|
||||
cfg, err := LoadRekeyConfig("", "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadRekeyConfig from *_FILE: %v", err)
|
||||
}
|
||||
if cfg.OldIdentity != oldID.String() || cfg.NewIdentity != newID.String() {
|
||||
t.Fatalf("unexpected RekeyConfig from files: %+v", cfg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("both env and file rejected", func(t *testing.T) {
|
||||
t.Setenv("ARCHIE_OLD_AGE_IDENTITY", oldID.String())
|
||||
t.Setenv("ARCHIE_OLD_AGE_IDENTITY_FILE", oldFile)
|
||||
t.Setenv("ARCHIE_NEW_AGE_IDENTITY", newID.String())
|
||||
if _, err := LoadRekeyConfig("", "", nil); err == nil || !strings.Contains(err.Error(), "not both") {
|
||||
t.Fatalf("expected ambiguity error, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
oldKey string
|
||||
newKey string
|
||||
backups []string
|
||||
wantSub string
|
||||
}{
|
||||
{name: "empty old", oldKey: "", newKey: newID.String(), wantSub: "old age identity is required"},
|
||||
{name: "empty new", oldKey: oldID.String(), newKey: "", wantSub: "new age identity is required"},
|
||||
{name: "invalid old", oldKey: "not-an-age-key", newKey: newID.String(), wantSub: "old age identity"},
|
||||
{name: "invalid new", oldKey: oldID.String(), newKey: "not-an-age-key", wantSub: "new age identity"},
|
||||
{name: "invalid backup", oldKey: oldID.String(), newKey: newID.String(), backups: []string{"bad-recipient"}, wantSub: "backup recipient"},
|
||||
{name: "identical keys", oldKey: oldID.String(), newKey: oldID.String(), wantSub: "must be distinct"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := LoadRekeyConfig(tc.oldKey, tc.newKey, tc.backups)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantSub) {
|
||||
t.Fatalf("LoadRekeyConfig(%q, %q) = %v, want substring %q", tc.oldKey, tc.newKey, err, tc.wantSub)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRekeyRejectsInvalidConfigBeforeOpeningDB(t *testing.T) {
|
||||
id := genAgeIdentity(t)
|
||||
if err := Rekey(t.Context(), "", RekeyConfig{OldIdentity: id.String(), NewIdentity: id.String()}); err == nil {
|
||||
t.Fatal("expected error for identical identities")
|
||||
}
|
||||
other := genAgeIdentity(t)
|
||||
if err := Rekey(t.Context(), "", RekeyConfig{OldIdentity: id.String(), NewIdentity: other.String()}); err == nil {
|
||||
t.Fatal("expected error when database.url is missing")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA audit;
|
||||
|
||||
-- Append-only audit events. The runtime database role holds only SELECT and
|
||||
-- INSERT privileges on this schema so records cannot be modified or deleted.
|
||||
CREATE TABLE audit.events (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
at timestamptz NOT NULL DEFAULT now(),
|
||||
category text NOT NULL,
|
||||
action text NOT NULL,
|
||||
actor_id text NOT NULL,
|
||||
actor_kind text NOT NULL DEFAULT '',
|
||||
resource_kind text NOT NULL DEFAULT '',
|
||||
resource_id text NOT NULL DEFAULT '',
|
||||
outcome text NOT NULL,
|
||||
trace_id text NOT NULL DEFAULT '',
|
||||
detail jsonb NOT NULL DEFAULT '{}'
|
||||
);
|
||||
CREATE INDEX idx_audit_events_org_at ON audit.events (org_id, at DESC);
|
||||
CREATE INDEX idx_audit_events_org_category_at ON audit.events (org_id, category, at DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA audit CASCADE;
|
||||
@@ -102,6 +102,15 @@ func lockMigrate(ctx context.Context, db *sqlx.DB) (release func(), err error) {
|
||||
|
||||
func migrateLockKey() string { return "archie." + migrateLockName + ".owner" }
|
||||
|
||||
// schemaPrivileges returns the runtime DML privileges for schema. The audit
|
||||
// schema is append-only so the runtime role may never UPDATE or DELETE rows.
|
||||
func schemaPrivileges(schema string) string {
|
||||
if schema == "audit" {
|
||||
return "SELECT, INSERT"
|
||||
}
|
||||
return "SELECT, INSERT, UPDATE, DELETE"
|
||||
}
|
||||
|
||||
// grantRuntime gives the runtime role USAGE and DML on each schema, never DDL.
|
||||
func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas []string) error {
|
||||
cfg, err := pgx.ParseConfig(runtimeURL)
|
||||
@@ -111,9 +120,10 @@ func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas [
|
||||
role := pgx.Identifier{cfg.User}.Sanitize()
|
||||
for _, schema := range schemas {
|
||||
name := pgx.Identifier{schema}.Sanitize()
|
||||
privs := schemaPrivileges(schema)
|
||||
for _, stmt := range []string{
|
||||
"GRANT USAGE ON SCHEMA " + name + " TO " + role,
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA " + name + " TO " + role,
|
||||
"GRANT " + privs + " ON ALL TABLES IN SCHEMA " + name + " TO " + role,
|
||||
// A table keyed by a serial draws from a sequence, which is its
|
||||
// own grant: a module whose insert draws on one would fail DML it
|
||||
// is otherwise allowed.
|
||||
|
||||
@@ -2,6 +2,7 @@ package pg
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -41,3 +42,28 @@ func TestMissingMigrations(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSchemaPrivileges guards the append-only privilege split for the audit
|
||||
// schema so runtime database credentials can never UPDATE or DELETE audit rows.
|
||||
func TestSchemaPrivileges(t *testing.T) {
|
||||
tests := []struct {
|
||||
schema string
|
||||
want string
|
||||
}{
|
||||
{schema: "audit", want: "SELECT, INSERT"},
|
||||
{schema: "governance", want: "SELECT, INSERT, UPDATE, DELETE"},
|
||||
{schema: "runs", want: "SELECT, INSERT, UPDATE, DELETE"},
|
||||
{schema: "", want: "SELECT, INSERT, UPDATE, DELETE"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.schema, func(t *testing.T) {
|
||||
got := schemaPrivileges(tc.schema)
|
||||
if got != tc.want {
|
||||
t.Fatalf("schemaPrivileges(%q) = %q, want %q", tc.schema, got, tc.want)
|
||||
}
|
||||
if tc.schema == "audit" && (strings.Contains(got, "UPDATE") || strings.Contains(got, "DELETE")) {
|
||||
t.Fatalf("audit schema must not grant UPDATE or DELETE, got %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
// Package telemetry configures OpenTelemetry trace export, trace-correlated
|
||||
// structured logging, HTTP span middleware, and an internal Prometheus /metrics
|
||||
// endpoint using the Go standard library.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
otlpEndpointEnv = "OTEL_EXPORTER_OTLP_ENDPOINT"
|
||||
metricsMediaType = "text/plain; version=0.0.4; charset=utf-8"
|
||||
shutdownTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// Setup registers the W3C TraceContext propagator and, when
|
||||
// OTEL_EXPORTER_OTLP_ENDPOINT is set, installs an OTLP/gRPC TracerProvider.
|
||||
// The returned shutdown function flushes pending spans on exit.
|
||||
func Setup(ctx context.Context, serviceName, version string) (func(context.Context) error, error) {
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{},
|
||||
propagation.Baggage{},
|
||||
))
|
||||
if strings.TrimSpace(os.Getenv(otlpEndpointEnv)) == "" {
|
||||
return func(context.Context) error { return nil }, nil
|
||||
}
|
||||
res, err := resource.Merge(resource.Default(), resource.NewWithAttributes(
|
||||
semconv.SchemaURL,
|
||||
semconv.ServiceName(serviceName),
|
||||
semconv.ServiceVersion(version),
|
||||
semconv.ServiceInstanceID(instanceID()),
|
||||
))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("telemetry resource: %w", err)
|
||||
}
|
||||
exporter, err := otlptracegrpc.New(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("telemetry exporter: %w", err)
|
||||
}
|
||||
tp := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithBatcher(exporter),
|
||||
sdktrace.WithResource(res),
|
||||
)
|
||||
otel.SetTracerProvider(tp)
|
||||
return func(shutdownCtx context.Context) error {
|
||||
if _, hasDeadline := shutdownCtx.Deadline(); !hasDeadline {
|
||||
var cancel context.CancelFunc
|
||||
shutdownCtx, cancel = context.WithTimeout(context.WithoutCancel(shutdownCtx), shutdownTimeout)
|
||||
defer cancel()
|
||||
}
|
||||
return tp.Shutdown(shutdownCtx)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func instanceID() string {
|
||||
host, _ := os.Hostname()
|
||||
return host + "-" + strconv.Itoa(os.Getpid())
|
||||
}
|
||||
|
||||
// stampedKey marks a context whose log record already carries trace_id and
|
||||
// span_id so nested trace handlers do not emit duplicate attributes.
|
||||
type stampedKey struct{}
|
||||
|
||||
type logHandler struct {
|
||||
inner slog.Handler
|
||||
}
|
||||
|
||||
// NewLogHandler wraps base so log records emitted with an active span in ctx
|
||||
// include trace_id and span_id attributes.
|
||||
func NewLogHandler(base slog.Handler) slog.Handler {
|
||||
return logHandler{inner: base}
|
||||
}
|
||||
|
||||
func (h logHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return h.inner.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
func (h logHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() && ctx.Value(stampedKey{}) == nil {
|
||||
r.AddAttrs(
|
||||
slog.String("trace_id", sc.TraceID().String()),
|
||||
slog.String("span_id", sc.SpanID().String()),
|
||||
)
|
||||
ctx = context.WithValue(ctx, stampedKey{}, true)
|
||||
}
|
||||
return h.inner.Handle(ctx, r)
|
||||
}
|
||||
|
||||
func (h logHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return logHandler{inner: h.inner.WithAttrs(attrs)}
|
||||
}
|
||||
|
||||
func (h logHandler) WithGroup(name string) slog.Handler {
|
||||
return logHandler{inner: h.inner.WithGroup(name)}
|
||||
}
|
||||
|
||||
// Metrics tracks process-local HTTP request counts, latency sums, and Go
|
||||
// runtime metrics for Prometheus scraping.
|
||||
type Metrics struct {
|
||||
started time.Time
|
||||
inFlight atomic.Int64
|
||||
requests2xx atomic.Int64
|
||||
requests3xx atomic.Int64
|
||||
requests4xx atomic.Int64
|
||||
requests5xx atomic.Int64
|
||||
requestsOther atomic.Int64
|
||||
durationNanos atomic.Int64
|
||||
durationCount atomic.Int64
|
||||
}
|
||||
|
||||
// NewMetrics returns a Metrics collector anchored at the current time.
|
||||
func NewMetrics() *Metrics {
|
||||
return &Metrics{started: time.Now()}
|
||||
}
|
||||
|
||||
// Middleware records HTTP request counts, durations, and in-flight requests,
|
||||
// and wraps next in otelhttp.NewHandler for HTTP span creation.
|
||||
func (m *Metrics) Middleware(next http.Handler) http.Handler {
|
||||
instrumented := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
m.inFlight.Add(1)
|
||||
start := time.Now()
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
defer func() {
|
||||
m.inFlight.Add(-1)
|
||||
m.recordRequest(sw.status, time.Since(start))
|
||||
}()
|
||||
next.ServeHTTP(sw, r)
|
||||
})
|
||||
return otelhttp.NewHandler(instrumented, "http",
|
||||
otelhttp.WithFilter(func(r *http.Request) bool {
|
||||
return !isProbeOrMetrics(r.URL.Path)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
func isProbeOrMetrics(path string) bool {
|
||||
return strings.HasPrefix(path, "/health") || path == "/readyz" || path == "/startupz" || path == "/metrics"
|
||||
}
|
||||
|
||||
func (m *Metrics) recordRequest(status int, took time.Duration) {
|
||||
m.durationCount.Add(1)
|
||||
m.durationNanos.Add(took.Nanoseconds())
|
||||
switch status / 100 {
|
||||
case 2:
|
||||
m.requests2xx.Add(1)
|
||||
case 3:
|
||||
m.requests3xx.Add(1)
|
||||
case 4:
|
||||
m.requests4xx.Add(1)
|
||||
case 5:
|
||||
m.requests5xx.Add(1)
|
||||
default:
|
||||
m.requestsOther.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
wroteHeader bool
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(code int) {
|
||||
if !w.wroteHeader {
|
||||
w.status = code
|
||||
w.wroteHeader = true
|
||||
}
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(p []byte) (int, error) {
|
||||
if !w.wroteHeader {
|
||||
w.wroteHeader = true
|
||||
}
|
||||
return w.ResponseWriter.Write(p)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Unwrap() http.ResponseWriter {
|
||||
return w.ResponseWriter
|
||||
}
|
||||
|
||||
// MetricsHandler serves Prometheus text format metrics on an internal endpoint.
|
||||
func (m *Metrics) MetricsHandler() http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
var ms runtime.MemStats
|
||||
runtime.ReadMemStats(&ms)
|
||||
|
||||
uptime := time.Since(m.started).Seconds()
|
||||
durSec := float64(m.durationNanos.Load()) / float64(time.Second)
|
||||
|
||||
w.Header().Set("Content-Type", metricsMediaType)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_, _ = fmt.Fprintf(w,
|
||||
"# HELP archie_uptime_seconds Process uptime in seconds.\n"+
|
||||
"# TYPE archie_uptime_seconds gauge\n"+
|
||||
"archie_uptime_seconds %.6f\n"+
|
||||
"# HELP archie_http_requests_in_flight Current number of in-flight HTTP requests.\n"+
|
||||
"# TYPE archie_http_requests_in_flight gauge\n"+
|
||||
"archie_http_requests_in_flight %d\n"+
|
||||
"# HELP archie_http_requests_total Total number of HTTP requests handled by status class.\n"+
|
||||
"# TYPE archie_http_requests_total counter\n"+
|
||||
"archie_http_requests_total{status=\"2xx\"} %d\n"+
|
||||
"archie_http_requests_total{status=\"3xx\"} %d\n"+
|
||||
"archie_http_requests_total{status=\"4xx\"} %d\n"+
|
||||
"archie_http_requests_total{status=\"5xx\"} %d\n"+
|
||||
"archie_http_requests_total{status=\"other\"} %d\n"+
|
||||
"# HELP archie_http_request_duration_seconds Total HTTP request duration and count.\n"+
|
||||
"# TYPE archie_http_request_duration_seconds summary\n"+
|
||||
"archie_http_request_duration_seconds_sum %.6f\n"+
|
||||
"archie_http_request_duration_seconds_count %d\n"+
|
||||
"# HELP go_goroutines Number of goroutines that currently exist.\n"+
|
||||
"# TYPE go_goroutines gauge\n"+
|
||||
"go_goroutines %d\n"+
|
||||
"# HELP go_memstats_alloc_bytes Number of bytes allocated and still in use.\n"+
|
||||
"# TYPE go_memstats_alloc_bytes gauge\n"+
|
||||
"go_memstats_alloc_bytes %d\n"+
|
||||
"# HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use.\n"+
|
||||
"# TYPE go_memstats_heap_inuse_bytes gauge\n"+
|
||||
"go_memstats_heap_inuse_bytes %d\n"+
|
||||
"# HELP go_memstats_sys_bytes Number of bytes obtained from system.\n"+
|
||||
"# TYPE go_memstats_sys_bytes gauge\n"+
|
||||
"go_memstats_sys_bytes %d\n"+
|
||||
"# HELP go_gc_cycles_total Total number of completed GC cycles.\n"+
|
||||
"# TYPE go_gc_cycles_total counter\n"+
|
||||
"go_gc_cycles_total %d\n",
|
||||
uptime,
|
||||
m.inFlight.Load(),
|
||||
m.requests2xx.Load(),
|
||||
m.requests3xx.Load(),
|
||||
m.requests4xx.Load(),
|
||||
m.requests5xx.Load(),
|
||||
m.requestsOther.Load(),
|
||||
durSec,
|
||||
m.durationCount.Load(),
|
||||
runtime.NumGoroutine(),
|
||||
ms.Alloc,
|
||||
ms.HeapInuse,
|
||||
ms.Sys,
|
||||
ms.NumGC,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
json "encoding/json/v2"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// TestLogHandlerInjectsTraceAndSpanIDs guards that NewLogHandler attaches
|
||||
// trace_id and span_id once when a valid span exists in ctx, and omits them
|
||||
// when no span is active.
|
||||
func TestLogHandlerInjectsTraceAndSpanIDs(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
handler := NewLogHandler(NewLogHandler(slog.NewJSONHandler(&buf, nil)))
|
||||
logger := slog.New(handler)
|
||||
|
||||
logger.InfoContext(t.Context(), "without span")
|
||||
if strings.Contains(buf.String(), "trace_id") || strings.Contains(buf.String(), "span_id") {
|
||||
t.Fatalf("unexpected trace fields without span: %s", buf.String())
|
||||
}
|
||||
buf.Reset()
|
||||
|
||||
tp := sdktrace.NewTracerProvider()
|
||||
t.Cleanup(func() { _ = tp.Shutdown(context.Background()) })
|
||||
ctx, span := tp.Tracer("telemetry-test").Start(t.Context(), "op")
|
||||
defer span.End()
|
||||
|
||||
logger.InfoContext(ctx, "with span")
|
||||
line := buf.String()
|
||||
if strings.Count(line, `"trace_id"`) != 1 || strings.Count(line, `"span_id"`) != 1 {
|
||||
t.Fatalf("expected single trace_id and span_id fields, got: %s", line)
|
||||
}
|
||||
|
||||
var parsed map[string]any
|
||||
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &parsed); err != nil {
|
||||
t.Fatalf("unmarshal log line: %v (%s)", err, line)
|
||||
}
|
||||
if parsed["trace_id"] != span.SpanContext().TraceID().String() {
|
||||
t.Fatalf("trace_id = %v, want %s", parsed["trace_id"], span.SpanContext().TraceID().String())
|
||||
}
|
||||
if parsed["span_id"] != span.SpanContext().SpanID().String() {
|
||||
t.Fatalf("span_id = %v, want %s", parsed["span_id"], span.SpanContext().SpanID().String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestMetricsMiddlewareAndPrometheusOutput guards HTTP span creation, request
|
||||
// status counting, and Prometheus text exposition formatting.
|
||||
func TestMetricsMiddlewareAndPrometheusOutput(t *testing.T) {
|
||||
prevTP := otel.GetTracerProvider()
|
||||
tp := sdktrace.NewTracerProvider()
|
||||
otel.SetTracerProvider(tp)
|
||||
t.Cleanup(func() {
|
||||
otel.SetTracerProvider(prevTP)
|
||||
_ = tp.Shutdown(context.Background())
|
||||
})
|
||||
|
||||
m := NewMetrics()
|
||||
var sawValidSpan bool
|
||||
var probeHadSpan bool
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/ok", func(w http.ResponseWriter, r *http.Request) {
|
||||
sawValidSpan = trace.SpanContextFromContext(r.Context()).IsValid()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
mux.HandleFunc("/api/missing", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
})
|
||||
mux.HandleFunc("/api/fail", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
})
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
probeHadSpan = trace.SpanContextFromContext(r.Context()).IsValid()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
wrapped := m.Middleware(mux)
|
||||
for _, path := range []string{"/api/ok", "/api/missing", "/api/fail", "/healthz"} {
|
||||
rec := httptest.NewRecorder()
|
||||
wrapped.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil))
|
||||
}
|
||||
if !sawValidSpan {
|
||||
t.Fatal("expected otelhttp middleware to create a valid span for /api/ok")
|
||||
}
|
||||
if probeHadSpan {
|
||||
t.Fatal("expected /healthz probe to be excluded from otelhttp span creation")
|
||||
}
|
||||
|
||||
metricsRec := httptest.NewRecorder()
|
||||
m.MetricsHandler().ServeHTTP(metricsRec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/metrics", nil))
|
||||
if metricsRec.Code != http.StatusOK {
|
||||
t.Fatalf("/metrics status = %d, want 200", metricsRec.Code)
|
||||
}
|
||||
if gotCT := metricsRec.Header().Get("Content-Type"); gotCT != metricsMediaType {
|
||||
t.Fatalf("/metrics Content-Type = %q, want %q", gotCT, metricsMediaType)
|
||||
}
|
||||
|
||||
body := metricsRec.Body.String()
|
||||
for _, want := range []string{
|
||||
"archie_uptime_seconds ",
|
||||
"archie_http_requests_in_flight 0",
|
||||
`archie_http_requests_total{status="2xx"} 2`,
|
||||
`archie_http_requests_total{status="4xx"} 1`,
|
||||
`archie_http_requests_total{status="5xx"} 1`,
|
||||
"archie_http_request_duration_seconds_count 4",
|
||||
"archie_http_request_duration_seconds_sum ",
|
||||
"go_goroutines ",
|
||||
"go_memstats_alloc_bytes ",
|
||||
"go_gc_cycles_total ",
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("/metrics output missing %q:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupWithoutEndpoint guards that Setup succeeds as a no-op when
|
||||
// OTEL_EXPORTER_OTLP_ENDPOINT is unset.
|
||||
func TestSetupWithoutEndpoint(t *testing.T) {
|
||||
t.Setenv(otlpEndpointEnv, "")
|
||||
shutdown, err := Setup(t.Context(), "archie", "test")
|
||||
if err != nil {
|
||||
t.Fatalf("Setup() error = %v", err)
|
||||
}
|
||||
if err := shutdown(t.Context()); err != nil {
|
||||
t.Fatalf("shutdown() error = %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user