- Admin pprof is opt-in (AdminConfig.EnablePprof) - Client spans drop the URL query string; HostFunc bounds the host label - Config.HTTP/HTTPClient/GRPC configure the Observer's instrumentation - A panic after a partial HTTP response counts as 500 - GaugeFunc, CounterFunc and RegisterDBStats panic on duplicates - Abandoned client gRPC streams are recorded as Canceled - OTEL_EXPORTER_OTLP_PROTOCOL selects the protocol when unset - Health reports are cached for 1s; hung checks are not restarted - Environment is exported as deployment.environment.name Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
8647fdf1bb
commit
c92fd9826b
21 files changed
+457
-101
No files matched your search
@@ -81,7 +81,10 @@ The dashboard JSON is hand-maintainable; keep the `job` variable and `$__rate_in
|
||||
- **Route detection**: default `RouteFunc` reads `r.Pattern`; when the middleware wraps an `*http.ServeMux` directly it falls back to `mux.Handler(r)`. Other routers need `RouteFunc`.
|
||||
- **Panics** are recorded and re-raised (HTTP middleware, gRPC server interceptors, `Track`).
|
||||
- **Admin shutdown** waits at most 1s, then closes connections; tracer flush happens first.
|
||||
- **Idempotent registration**: identical metric definitions return the existing collector; conflicting ones panic.
|
||||
- **Idempotent registration**: identical metric definitions return the existing collector; conflicting ones panic. `GaugeFunc`, `CounterFunc` and `RegisterDBStats` always panic on a duplicate.
|
||||
- **Observer instrumentation is configured through `Config.HTTP` / `HTTPClient` / `GRPC`**; the Observer only fills empty `Metrics`, `Logger`, `TracerProvider`.
|
||||
- **Health cache**: reports are reused for `healthCacheTTL` (1s); tests needing a fresh run call `reportCache.reset()`.
|
||||
- **pprof is opt-in** (`Admin.EnablePprof`); the admin server has no authentication.
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
+5
-1
@@ -7,10 +7,14 @@
|
||||
- `TracerConfig.Protocol` (`ProtocolGRPC` / `ProtocolHTTP`), `TracerConfig.TLS`, `TracerConfig.Environment`, `TracerConfig.Disabled`, `TracerConfig.Exporter`.
|
||||
- `Trace`, `RecordError`, `TraceID` helpers.
|
||||
- `Endpoint` accepts URLs (`https://collector:4318`).
|
||||
- Resource carries `service.instance.id` and host attributes.
|
||||
- Resource carries `service.instance.id`, host attributes and `deployment.environment.name` (from `Environment`).
|
||||
- `New` / `Observer` — one call wires logger, tracer, metrics, health checks and the admin server; `Config.WithEnv` applies `OBSX_*` overrides.
|
||||
- `NewLogger`, `NewTraceHandler`; `NewHealth` (liveness/readiness, HTTP and `grpc.health.v1`).
|
||||
- `NewHTTPMiddleware`, `NewHTTPTransport`, `NewGRPCInterceptors` — config-based instrumentation with fixed metric names (`http_server_*`, `http_client_*`, `grpc_*`).
|
||||
- `Config.HTTP`, `Config.HTTPClient`, `Config.GRPC` configure the Observer's instrumentation; `HTTPClientConfig.HostFunc` bounds the `host` label.
|
||||
- `OTEL_EXPORTER_OTLP_PROTOCOL` / `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` select the protocol when `TracerConfig.Protocol` is empty.
|
||||
- Admin pprof is opt-in (`AdminConfig.EnablePprof`, `OBSX_ADMIN_ENABLE_PPROF`).
|
||||
- Health reports are cached for one second and hung checks are not restarted; client spans omit the URL query string; abandoned client gRPC streams are recorded as `Canceled`.
|
||||
- `deploy/` — Grafana dashboard and Prometheus alerts; `examples/service`.
|
||||
- Metrics: idempotent registration, `Sub`, `GaugeFunc`, `CounterFunc`, `RegisterDBStats`, OpenMetrics handler with trace exemplars.
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ go run ./examples/service # example service (:8080, admin :9090)
|
||||
- **Metrics** — Prometheus factory with namespace/subsystem, idempotent `register`, `Sub`, `GaugeFunc`, `CounterFunc`, `RegisterDBStats`; `base()` gives a namespace-free factory for built-in metrics; `observe` attaches trace exemplars
|
||||
- **NewHTTPMiddleware / NewHTTPTransport / NewGRPCInterceptors** — server/client instrumentation: spans, propagation, RED metrics, access logs
|
||||
- **Health** — liveness/readiness checks with timeouts, HTTP handlers, `grpc.health.v1` server, `SetReady`
|
||||
- **AdminHandler** — `/metrics`, `/healthz`, `/livez`, `/readyz`, `/buildinfo`, `/loglevel`, `/debug/pprof/`
|
||||
- **AdminHandler** — `/metrics`, `/healthz`, `/livez`, `/readyz`, `/buildinfo`, `/loglevel`, `/debug/pprof/` (opt-in via `Admin.EnablePprof`)
|
||||
|
||||
## Conventions
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ A runnable version lives in [`examples/service`](examples/service/main.go).
|
||||
| **Traces** | OpenTelemetry provider with OTLP gRPC or HTTP export, parent-based ratio sampling, W3C TraceContext + Baggage propagation, resource with service/host/instance attributes. Without an endpoint, spans are still created so trace IDs appear in logs. |
|
||||
| **Metrics** | Isolated Prometheus registry with Go runtime and process collectors, `service_build_info`, trace exemplars on latency histograms. |
|
||||
| **Health** | Liveness and readiness checks run concurrently with timeouts; HTTP (`/healthz`, `/readyz`) and gRPC (`grpc.health.v1`) servers. |
|
||||
| **Admin server** | `/metrics`, `/healthz`, `/livez`, `/readyz`, `/buildinfo`, `/loglevel`, `/debug/pprof/` on an internal port. |
|
||||
| **Admin server** | `/metrics`, `/healthz`, `/livez`, `/readyz`, `/buildinfo`, `/loglevel` and, with `Admin.EnablePprof`, `/debug/pprof/`. No authentication: bind it to an internal address. |
|
||||
|
||||
| Instrumentation | Usage |
|
||||
|-----------------|-------|
|
||||
@@ -96,12 +96,15 @@ Cardinality is bounded: `route` is the router template (`/orders/{id}`), never t
|
||||
**Routes.** With `http.ServeMux` (Go 1.22+ patterns) routes are detected automatically. For other routers set `RouteFunc`:
|
||||
|
||||
```go
|
||||
obsx.NewHTTPMiddleware(obsx.HTTPServerConfig{
|
||||
Metrics: o.Metrics(),
|
||||
RouteFunc: func(r *http.Request) string {
|
||||
return chi.RouteContext(r.Context()).RoutePattern()
|
||||
obsx.Config{
|
||||
HTTP: obsx.HTTPServerConfig{
|
||||
RouteFunc: func(r *http.Request) string {
|
||||
return chi.RouteContext(r.Context()).RoutePattern()
|
||||
},
|
||||
// Long-lived connections would distort latency histograms and alerts.
|
||||
Skip: func(r *http.Request) bool { return r.URL.Path == "/ws" },
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Dashboards and alerts
|
||||
@@ -123,11 +126,13 @@ Scrape the admin port (`:9090/metrics`) of every pod.
|
||||
| `ServiceVersion` | main module version from build info |
|
||||
| `Logging.Level` / `Format` / `Output` | `info` / `json` / stdout |
|
||||
| `Tracing.Endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT`; if unset, traces are not exported |
|
||||
| `Tracing.Protocol` | `grpc` (`http` for OTLP/HTTP) |
|
||||
| `Tracing.Protocol` | `OTEL_EXPORTER_OTLP_PROTOCOL`, then `grpc` (`http` for OTLP/HTTP) |
|
||||
| `Tracing.Insecure` / `TLS` | TLS with system roots; `Insecure: true` for plaintext collectors, `TLS` for a custom `tls.Config` |
|
||||
| `Tracing.Sampler` | `1.0`, parent-based |
|
||||
| `Health.Timeout` | `5s` per check |
|
||||
| `Admin.Addr` | empty — no server; mount `o.AdminHandler()` yourself |
|
||||
| `Admin.EnablePprof` | `false` |
|
||||
| `HTTP`, `HTTPClient`, `GRPC` | instrumentation settings used by the Observer: `RouteFunc`, `Skip`, `Buckets`, `Propagator`, `HostFunc` |
|
||||
|
||||
`Config.WithEnv()` lets deployments override settings without code changes:
|
||||
|
||||
@@ -143,7 +148,7 @@ Scrape the admin port (`:9090/metrics`) of every pod.
|
||||
| `OBSX_TRACING_DISABLED`, `OTEL_SDK_DISABLED` | `Tracing.Disabled` |
|
||||
| `OBSX_METRICS_NAMESPACE` | `Metrics.Namespace` |
|
||||
| `OBSX_HEALTH_TIMEOUT` | `Health.Timeout` |
|
||||
| `OBSX_ADMIN_ADDR`, `OBSX_ADMIN_DISABLE_PPROF` | `Admin.Addr`, `Admin.DisablePprof` |
|
||||
| `OBSX_ADMIN_ADDR`, `OBSX_ADMIN_ENABLE_PPROF` | `Admin.Addr`, `Admin.EnablePprof` |
|
||||
| `OBSX_DISABLE_ACCESS_LOG` | `DisableAccessLog` |
|
||||
|
||||
Standard `OTEL_EXPORTER_OTLP_*` and `OTEL_RESOURCE_ATTRIBUTES` are honored as well.
|
||||
@@ -197,6 +202,11 @@ The v1.0.0 helpers `HTTPMiddleware(metrics)`, `HTTPTransport(base)` and `LogHand
|
||||
- Creating an already registered metric with the same name, help and labels returns the existing collector instead of panicking.
|
||||
- gRPC health-check calls are not instrumented by `Observer.GRPCInterceptors` to keep probe noise out of metrics and logs.
|
||||
- HTTP client latency is measured until response headers arrive.
|
||||
- Client spans record the URL without credentials and without the query string. The `host` label is the URL host; when hosts come from users set `HTTPClient.HostFunc` to keep cardinality bounded.
|
||||
- Sampling follows the caller's trace headers. On endpoints reachable by untrusted clients set `HTTP.Propagator` / `GRPC.Propagator` to `propagation.NewCompositeTextMapPropagator()` so they cannot force sampling.
|
||||
- Health results are reused for up to one second; a check that outlives its timeout is not started again until it returns.
|
||||
- `GaugeFunc`, `CounterFunc` and `RegisterDBStats` panic on a duplicate name instead of silently keeping the first function or pool.
|
||||
- A panic after a partial HTTP response is counted as 500.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -16,9 +16,9 @@ import (
|
||||
// GET /buildinfo service name, version, revision, uptime
|
||||
// GET /loglevel current log level
|
||||
// PUT /loglevel change log level: body or ?level= "debug", "info", ...
|
||||
// /debug/pprof/ Go profiling (unless Admin.DisablePprof)
|
||||
// /debug/pprof/ Go profiling (only with Admin.EnablePprof)
|
||||
//
|
||||
// Expose it on an internal port only.
|
||||
// The handler has no authentication: expose it on an internal address only.
|
||||
func (o *Observer) AdminHandler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("GET /metrics", o.metrics.Handler())
|
||||
@@ -30,7 +30,7 @@ func (o *Observer) AdminHandler() http.Handler {
|
||||
})
|
||||
mux.Handle("/loglevel", LogLevelHandler(o.level, o.logger))
|
||||
|
||||
if !o.cfg.Admin.DisablePprof {
|
||||
if o.cfg.Admin.EnablePprof {
|
||||
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
||||
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
||||
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
||||
|
||||
@@ -23,18 +23,28 @@ type Config struct {
|
||||
Health HealthConfig // Metrics is set automatically
|
||||
Admin AdminConfig
|
||||
|
||||
// HTTP, HTTPClient and GRPC tune the instrumentation created by the
|
||||
// Observer (RouteFunc, Skip, Buckets, Propagator, HostFunc...). Metrics,
|
||||
// Logger and TracerProvider default to the Observer's own.
|
||||
HTTP HTTPServerConfig
|
||||
HTTPClient HTTPClientConfig
|
||||
GRPC GRPCConfig
|
||||
|
||||
// DisableAccessLog turns off per-request logs from the HTTP and gRPC
|
||||
// server instrumentation.
|
||||
DisableAccessLog bool
|
||||
}
|
||||
|
||||
// AdminConfig configures the internal admin HTTP server exposing /metrics,
|
||||
// /healthz, /readyz, /buildinfo, /loglevel and /debug/pprof/.
|
||||
// /healthz, /readyz, /buildinfo, /loglevel and, when enabled, /debug/pprof/.
|
||||
// The server has no authentication: bind it to an internal address.
|
||||
type AdminConfig struct {
|
||||
// Addr to listen on, e.g. ":9090". When empty no server is started; mount
|
||||
// Observer.AdminHandler on your own server instead.
|
||||
Addr string
|
||||
DisablePprof bool
|
||||
Addr string
|
||||
// EnablePprof serves /debug/pprof/. Off by default: profiling is costly
|
||||
// and the admin server is unauthenticated.
|
||||
EnablePprof bool
|
||||
}
|
||||
|
||||
func (c *Config) defaults() {
|
||||
@@ -72,7 +82,7 @@ func (c *Config) defaults() {
|
||||
// OBSX_METRICS_NAMESPACE Metrics.Namespace
|
||||
// OBSX_HEALTH_TIMEOUT Health.Timeout (Go duration, e.g. "3s")
|
||||
// OBSX_ADMIN_ADDR Admin.Addr
|
||||
// OBSX_ADMIN_DISABLE_PPROF Admin.DisablePprof
|
||||
// OBSX_ADMIN_ENABLE_PPROF Admin.EnablePprof
|
||||
// OBSX_DISABLE_ACCESS_LOG DisableAccessLog
|
||||
//
|
||||
// Standard OTEL_EXPORTER_OTLP_* and OTEL_RESOURCE_ATTRIBUTES variables are
|
||||
@@ -94,7 +104,7 @@ func (c Config) WithEnv() Config {
|
||||
envString(&c.Metrics.Namespace, "OBSX_METRICS_NAMESPACE")
|
||||
envDuration(&c.Health.Timeout, "OBSX_HEALTH_TIMEOUT")
|
||||
envString(&c.Admin.Addr, "OBSX_ADMIN_ADDR")
|
||||
envBool(&c.Admin.DisablePprof, "OBSX_ADMIN_DISABLE_PPROF")
|
||||
envBool(&c.Admin.EnablePprof, "OBSX_ADMIN_ENABLE_PPROF")
|
||||
envBool(&c.DisableAccessLog, "OBSX_DISABLE_ACCESS_LOG")
|
||||
return c
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
// ServiceVersion: "1.4.0",
|
||||
// Environment: "production",
|
||||
// Tracing: obsx.TracerConfig{Endpoint: "otel-collector:4317", Insecure: true},
|
||||
// Admin: obsx.AdminConfig{Addr: ":9090"}, // /metrics, /healthz, /readyz, pprof
|
||||
// Admin: obsx.AdminConfig{Addr: ":9090"}, // /metrics, /healthz, /readyz
|
||||
// }.WithEnv())
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
|
||||
+19
-11
@@ -2,6 +2,8 @@ package obsx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"net"
|
||||
"net/http/httptest"
|
||||
@@ -25,14 +27,13 @@ func (c *collector) Export(_ context.Context, r *coltracepb.ExportTraceServiceRe
|
||||
return &coltracepb.ExportTraceServiceResponse{}, nil
|
||||
}
|
||||
|
||||
// End to end: spans reach a real OTLP gRPC collector, over plaintext and TLS.
|
||||
// End to end: spans reach a real OTLP gRPC collector, over plaintext, TLS
|
||||
// with the standard certificate variable, and TLS with TracerConfig.TLS.
|
||||
func TestSetupTracer_Exports(t *testing.T) {
|
||||
for _, insecure := range []bool{true, false} {
|
||||
name := "tls"
|
||||
if insecure {
|
||||
name = "insecure"
|
||||
}
|
||||
for _, name := range []string{"insecure", "tls", "custom-tls"} {
|
||||
insecure := name == "insecure"
|
||||
t.Run(name, func(t *testing.T) {
|
||||
var tlsCfg *tls.Config
|
||||
prev := otel.GetTracerProvider()
|
||||
t.Cleanup(func() { otel.SetTracerProvider(prev) })
|
||||
|
||||
@@ -42,12 +43,18 @@ func TestSetupTracer_Exports(t *testing.T) {
|
||||
ts := httptest.NewTLSServer(nil)
|
||||
defer ts.Close()
|
||||
opts = append(opts, grpc.Creds(credentials.NewServerTLSFromCert(&ts.TLS.Certificates[0])))
|
||||
ca := filepath.Join(t.TempDir(), "ca.pem")
|
||||
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ts.Certificate().Raw})
|
||||
if err := os.WriteFile(ca, pemBytes, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
if name == "custom-tls" {
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(ts.Certificate())
|
||||
tlsCfg = &tls.Config{RootCAs: pool}
|
||||
} else {
|
||||
ca := filepath.Join(t.TempDir(), "ca.pem")
|
||||
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ts.Certificate().Raw})
|
||||
if err := os.WriteFile(ca, pemBytes, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_CERTIFICATE", ca)
|
||||
}
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_CERTIFICATE", ca)
|
||||
}
|
||||
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
@@ -65,6 +72,7 @@ func TestSetupTracer_Exports(t *testing.T) {
|
||||
ServiceName: "export-test",
|
||||
Endpoint: lis.Addr().String(),
|
||||
Insecure: insecure,
|
||||
TLS: tlsCfg,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -279,13 +279,16 @@ func (g *grpcInstrumentation) streamClient(ctx context.Context, desc *grpc.Strea
|
||||
g.finishClient(ctx, span, fullMethod, start, err)
|
||||
return nil, err
|
||||
}
|
||||
return &clientStream{
|
||||
s := &clientStream{
|
||||
ClientStream: cs,
|
||||
desc: desc,
|
||||
finish: func(err error) {
|
||||
g.finishClient(ctx, span, fullMethod, start, err)
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
// A caller may cancel and walk away without reading the stream to the end.
|
||||
s.stop = context.AfterFunc(ctx, func() { s.done(status.FromContextError(ctx.Err()).Err()) })
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// serverStream overrides the stream context with the traced one.
|
||||
@@ -304,21 +307,28 @@ type clientStream struct {
|
||||
desc *grpc.StreamDesc
|
||||
once sync.Once
|
||||
finish func(error)
|
||||
stop func() bool // unregisters the cancellation watcher
|
||||
}
|
||||
|
||||
func (s *clientStream) done(err error) {
|
||||
s.once.Do(func() { s.finish(err) })
|
||||
}
|
||||
|
||||
// end finishes the stream from one of its own methods.
|
||||
func (s *clientStream) end(err error) {
|
||||
s.stop()
|
||||
s.done(err)
|
||||
}
|
||||
|
||||
func (s *clientStream) RecvMsg(m any) error {
|
||||
err := s.ClientStream.RecvMsg(m)
|
||||
switch {
|
||||
case errors.Is(err, io.EOF):
|
||||
s.done(nil)
|
||||
s.end(nil)
|
||||
case err != nil:
|
||||
s.done(err)
|
||||
s.end(err)
|
||||
case !s.desc.ServerStreams:
|
||||
s.done(nil)
|
||||
s.end(nil)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -326,7 +336,7 @@ func (s *clientStream) RecvMsg(m any) error {
|
||||
func (s *clientStream) SendMsg(m any) error {
|
||||
err := s.ClientStream.SendMsg(m)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
s.done(err)
|
||||
s.end(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -334,7 +344,7 @@ func (s *clientStream) SendMsg(m any) error {
|
||||
func (s *clientStream) Header() (metadata.MD, error) {
|
||||
md, err := s.ClientStream.Header()
|
||||
if err != nil {
|
||||
s.done(err)
|
||||
s.end(err)
|
||||
}
|
||||
return md, err
|
||||
}
|
||||
|
||||
+6
-1
@@ -21,10 +21,15 @@ import (
|
||||
// startGRPC serves a grpc.health.v1 service backed by h over an in-memory
|
||||
// connection, with both server and client instrumented by ic.
|
||||
func startGRPC(t *testing.T, h *Health, ic *GRPCInterceptors) healthpb.HealthClient {
|
||||
t.Helper()
|
||||
return startGRPCServer(t, h.GRPCServer(), ic)
|
||||
}
|
||||
|
||||
func startGRPCServer(t *testing.T, impl healthpb.HealthServer, ic *GRPCInterceptors) healthpb.HealthClient {
|
||||
t.Helper()
|
||||
ln := bufconn.Listen(1 << 20)
|
||||
srv := grpc.NewServer(ic.ServerOptions()...)
|
||||
healthpb.RegisterHealthServer(srv, h.GRPCServer())
|
||||
healthpb.RegisterHealthServer(srv, impl)
|
||||
go func() { _ = srv.Serve(ln) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
healthpb "google.golang.org/grpc/health/grpc_health_v1"
|
||||
)
|
||||
|
||||
func TestHTTPMiddleware_PanicAfterWriteIs500(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
h := NewHTTPMiddleware(HTTPServerConfig{Metrics: m})(
|
||||
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("partial"))
|
||||
panic("boom")
|
||||
}))
|
||||
func() {
|
||||
defer func() { _ = recover() }()
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
|
||||
}()
|
||||
if !strings.Contains(scrape(t, m), `http_server_requests_total{code="500",method="GET",route="unmatched"} 1`) {
|
||||
t.Error("panic after a partial response not counted as 500")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMiddleware_HijackAndReadFrom(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
var logs bytes.Buffer
|
||||
logger, _ := NewLogger(LogConfig{Output: &logs})
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /ws", func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, _, err := http.NewResponseController(w).Hijack()
|
||||
if err != nil {
|
||||
t.Errorf("hijack: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
_, _ = conn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n\r\n"))
|
||||
})
|
||||
mux.HandleFunc("GET /file", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.Copy(w, strings.NewReader("hello")) // goes through ReadFrom
|
||||
})
|
||||
srv := httptest.NewServer(NewHTTPMiddleware(HTTPServerConfig{Metrics: m, Logger: logger})(mux))
|
||||
defer srv.Close()
|
||||
|
||||
conn, err := net.Dial("tcp", srv.Listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
_, _ = conn.Write([]byte("GET /ws HTTP/1.1\r\nHost: x\r\n\r\n"))
|
||||
if line, _ := bufio.NewReader(conn).ReadString('\n'); !strings.Contains(line, "101") {
|
||||
t.Fatalf("hijacked response = %q", line)
|
||||
}
|
||||
|
||||
resp, err := http.Get(srv.URL + "/file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if string(body) != "hello" {
|
||||
t.Errorf("body = %q", body)
|
||||
}
|
||||
|
||||
if !strings.Contains(scrape(t, m), `http_server_requests_total{code="101",method="GET",route="/ws"} 1`) {
|
||||
t.Errorf("hijacked request not counted as 101:\n%s", scrape(t, m))
|
||||
}
|
||||
if !strings.Contains(logs.String(), `"route":"/file","status":200`) || !strings.Contains(logs.String(), `"size":5`) {
|
||||
t.Errorf("ReadFrom size not logged: %s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransport_HostFuncAndQueryRedaction(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
tp, exp := newTestProvider(t)
|
||||
srv := httptest.NewServer(http.NotFoundHandler())
|
||||
defer srv.Close()
|
||||
|
||||
client := &http.Client{Transport: NewHTTPTransport(nil, HTTPClientConfig{
|
||||
Metrics: m,
|
||||
TracerProvider: tp,
|
||||
HostFunc: func(*http.Request) string { return "external" },
|
||||
})}
|
||||
resp, err := client.Get(srv.URL + "/hook?token=s3cret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if !strings.Contains(scrape(t, m), `http_client_requests_total{code="404",host="external",method="GET"} 1`) {
|
||||
t.Errorf("HostFunc not applied:\n%s", scrape(t, m))
|
||||
}
|
||||
for _, a := range exp.GetSpans()[0].Attributes {
|
||||
if strings.Contains(a.Value.Emit(), "s3cret") {
|
||||
t.Errorf("query string leaked into span attribute %s=%s", a.Key, a.Value.Emit())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_FuncCollectorsPanicOnDuplicate(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
m.GaugeFunc("depth", "Queue depth", func() float64 { return 1 })
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Error("second GaugeFunc with the same name must panic, not be ignored")
|
||||
}
|
||||
}()
|
||||
m.GaugeFunc("depth", "Queue depth", func() float64 { return 2 })
|
||||
}
|
||||
|
||||
type blockingHealth struct {
|
||||
healthpb.UnimplementedHealthServer
|
||||
}
|
||||
|
||||
func (blockingHealth) Watch(_ *healthpb.HealthCheckRequest, s healthpb.Health_WatchServer) error {
|
||||
<-s.Context().Done()
|
||||
return s.Context().Err()
|
||||
}
|
||||
|
||||
func TestGRPC_AbandonedClientStreamIsRecorded(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
client := startGRPCServer(t, blockingHealth{}, NewGRPCInterceptors(GRPCConfig{Metrics: m}))
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
if _, err := client.Watch(ctx, &healthpb.HealthCheckRequest{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancel() // walk away without reading the stream
|
||||
|
||||
want := `grpc_client_requests_total{code="Canceled",method="Watch",service="grpc.health.v1.Health"} 1`
|
||||
for deadline := time.Now().Add(2 * time.Second); !strings.Contains(scrape(t, m), want); time.Sleep(5 * time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("abandoned stream not recorded:\n%s", scrape(t, m))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGRPC_ServerPanicIsRecorded(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
ic := NewGRPCInterceptors(GRPCConfig{Metrics: m})
|
||||
func() {
|
||||
defer func() {
|
||||
if recover() != "boom" {
|
||||
t.Error("panic not re-raised")
|
||||
}
|
||||
}()
|
||||
_, _ = ic.UnaryServer(context.Background(), nil, &grpc.UnaryServerInfo{FullMethod: "/svc.S/M"},
|
||||
func(context.Context, any) (any, error) { panic("boom") })
|
||||
}()
|
||||
body := scrape(t, m)
|
||||
if !strings.Contains(body, `grpc_server_requests_total{code="Internal",method="M",service="svc.S"} 1`) ||
|
||||
!strings.Contains(body, "grpc_server_requests_in_flight 0") {
|
||||
t.Errorf("panic not recorded as Internal:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTracerConfig_ProtocolFromEnv(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf")
|
||||
cfg := TracerConfig{Endpoint: "http://localhost:4318"}
|
||||
cfg.defaults()
|
||||
if cfg.Protocol != "http/protobuf" {
|
||||
t.Fatalf("Protocol = %q", cfg.Protocol)
|
||||
}
|
||||
exp, err := newExporter(context.Background(), cfg)
|
||||
if err != nil || exp == nil {
|
||||
t.Fatalf("exporter = %v, err = %v", exp, err)
|
||||
}
|
||||
_ = exp.Shutdown(context.Background())
|
||||
|
||||
explicit := TracerConfig{Protocol: ProtocolGRPC}
|
||||
explicit.defaults()
|
||||
if explicit.Protocol != ProtocolGRPC {
|
||||
t.Errorf("explicit Protocol overridden by env: %q", explicit.Protocol)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealth_CachesAndDoesNotStackHungChecks(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
h := NewHealth(HealthConfig{})
|
||||
h.AddReadinessCheck("db", func(context.Context) error { calls.Add(1); return nil })
|
||||
for range 5 {
|
||||
if !h.CheckReadiness(context.Background()).Healthy() {
|
||||
t.Fatal("unhealthy")
|
||||
}
|
||||
}
|
||||
if n := calls.Load(); n != 1 {
|
||||
t.Errorf("check ran %d times within the cache window, want 1", n)
|
||||
}
|
||||
|
||||
calls.Store(0)
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
hung := NewHealth(HealthConfig{Timeout: 10 * time.Millisecond})
|
||||
hung.AddReadinessCheck("stuck", func(context.Context) error { calls.Add(1); <-release; return nil }) // ignores ctx
|
||||
hung.CheckReadiness(context.Background())
|
||||
hung.readyCache.reset()
|
||||
r := hung.CheckReadiness(context.Background())
|
||||
if r.Healthy() || !strings.Contains(r.Checks["stuck"].Error, "still in progress") {
|
||||
t.Errorf("report = %+v", r)
|
||||
}
|
||||
if n := calls.Load(); n != 1 {
|
||||
t.Errorf("hung check started %d times, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_HTTPConfigIsApplied(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{HTTP: HTTPServerConfig{
|
||||
RouteFunc: func(*http.Request) string { return "/users/{id}" },
|
||||
Skip: func(r *http.Request) bool { return r.URL.Path == "/ws" },
|
||||
}})
|
||||
h := o.HTTPMiddleware(http.NotFoundHandler())
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/users/42", nil))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/ws", nil))
|
||||
|
||||
body := scrape(t, o.Metrics())
|
||||
if !strings.Contains(body, `http_server_requests_total{code="404",method="GET",route="/users/{id}"} 1`) {
|
||||
t.Errorf("RouteFunc/Skip from Config.HTTP not applied:\n%s", body)
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,23 @@ func (c *HealthConfig) defaults() {
|
||||
type namedCheck struct {
|
||||
name string
|
||||
fn CheckFunc
|
||||
busy *atomic.Bool // a run that outlived its timeout is still in progress
|
||||
}
|
||||
|
||||
// healthCacheTTL bounds how often checks hit their dependencies, however
|
||||
// often the probes (which may be reachable by clients) are called.
|
||||
const healthCacheTTL = time.Second
|
||||
|
||||
type reportCache struct {
|
||||
mu sync.Mutex // also serializes runs
|
||||
at time.Time
|
||||
report Report
|
||||
}
|
||||
|
||||
func (c *reportCache) reset() {
|
||||
c.mu.Lock()
|
||||
c.at = time.Time{}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// Health runs liveness and readiness checks and serves them over HTTP
|
||||
@@ -57,6 +74,8 @@ type Health struct {
|
||||
liveness []namedCheck
|
||||
ready []namedCheck
|
||||
|
||||
livenessCache, readyCache reportCache
|
||||
|
||||
notReady atomic.Bool
|
||||
}
|
||||
|
||||
@@ -74,15 +93,17 @@ func NewHealth(cfg HealthConfig) *Health {
|
||||
// AddLivenessCheck registers a check that affects the liveness probe.
|
||||
func (h *Health) AddLivenessCheck(name string, fn CheckFunc) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.liveness = append(h.liveness, namedCheck{name: name, fn: fn})
|
||||
h.liveness = append(h.liveness, namedCheck{name: name, fn: fn, busy: new(atomic.Bool)})
|
||||
h.mu.Unlock()
|
||||
h.livenessCache.reset()
|
||||
}
|
||||
|
||||
// AddReadinessCheck registers a check that affects the readiness probe.
|
||||
func (h *Health) AddReadinessCheck(name string, fn CheckFunc) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.ready = append(h.ready, namedCheck{name: name, fn: fn})
|
||||
h.ready = append(h.ready, namedCheck{name: name, fn: fn, busy: new(atomic.Bool)})
|
||||
h.mu.Unlock()
|
||||
h.readyCache.reset()
|
||||
}
|
||||
|
||||
// SetReady overrides readiness. Call SetReady(false) during startup warm-up or
|
||||
@@ -109,12 +130,13 @@ type CheckResult struct {
|
||||
// Healthy reports whether all checks passed.
|
||||
func (r Report) Healthy() bool { return r.Status == StatusOK }
|
||||
|
||||
// CheckLiveness runs all liveness checks concurrently.
|
||||
// CheckLiveness runs all liveness checks concurrently. Results are reused for
|
||||
// up to a second, so frequent probes do not hammer the checked dependencies.
|
||||
func (h *Health) CheckLiveness(ctx context.Context) Report {
|
||||
h.mu.RLock()
|
||||
checks := h.liveness
|
||||
h.mu.RUnlock()
|
||||
return h.run(ctx, "liveness", checks)
|
||||
return h.run(ctx, "liveness", checks, &h.livenessCache)
|
||||
}
|
||||
|
||||
// CheckReadiness runs all readiness checks concurrently. It fails immediately
|
||||
@@ -126,22 +148,28 @@ func (h *Health) CheckReadiness(ctx context.Context) Report {
|
||||
h.mu.RLock()
|
||||
checks := h.ready
|
||||
h.mu.RUnlock()
|
||||
return h.run(ctx, "readiness", checks)
|
||||
return h.run(ctx, "readiness", checks, &h.readyCache)
|
||||
}
|
||||
|
||||
func (h *Health) run(ctx context.Context, kind string, checks []namedCheck) Report {
|
||||
func (h *Health) run(ctx context.Context, kind string, checks []namedCheck, cache *reportCache) Report {
|
||||
report := Report{Status: StatusOK}
|
||||
if len(checks) == 0 {
|
||||
return report
|
||||
}
|
||||
|
||||
cache.mu.Lock()
|
||||
defer cache.mu.Unlock()
|
||||
if !cache.at.IsZero() && time.Since(cache.at) < healthCacheTTL {
|
||||
return cache.report
|
||||
}
|
||||
|
||||
results := make([]CheckResult, len(checks))
|
||||
var wg sync.WaitGroup
|
||||
for i, c := range checks {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
results[i] = h.runOne(ctx, c.fn)
|
||||
results[i] = h.runOne(ctx, c)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
@@ -159,22 +187,30 @@ func (h *Health) run(ctx context.Context, kind string, checks []namedCheck) Repo
|
||||
h.status.WithLabelValues(c.name, kind).Set(healthy)
|
||||
}
|
||||
}
|
||||
if ctx.Err() == nil { // a cancelled caller must not fail the probe for everyone
|
||||
cache.at, cache.report = time.Now(), report
|
||||
}
|
||||
return report
|
||||
}
|
||||
|
||||
func (h *Health) runOne(ctx context.Context, fn CheckFunc) CheckResult {
|
||||
func (h *Health) runOne(ctx context.Context, c namedCheck) CheckResult {
|
||||
// A check that ignores ctx must not pile up one goroutine per probe.
|
||||
if !c.busy.CompareAndSwap(false, true) {
|
||||
return CheckResult{Status: StatusFail, Error: "previous run is still in progress", Duration: "0s"}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, h.timeout)
|
||||
defer cancel()
|
||||
|
||||
start := time.Now()
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
defer c.busy.Store(false)
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
done <- fmt.Errorf("panic: %v", rec)
|
||||
}
|
||||
}()
|
||||
done <- fn(ctx)
|
||||
done <- c.fn(ctx)
|
||||
}()
|
||||
|
||||
var err error
|
||||
|
||||
+14
-5
@@ -19,6 +19,11 @@ type HTTPClientConfig struct {
|
||||
TracerProvider trace.TracerProvider // nil: global provider
|
||||
Propagator propagation.TextMapPropagator // nil: global propagator
|
||||
Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets
|
||||
|
||||
// HostFunc returns the host metric label, default: the request URL host.
|
||||
// When hosts come from users (webhooks, fetch-by-URL) return a fixed
|
||||
// value such as "external" to keep metric cardinality bounded.
|
||||
HostFunc func(*http.Request) string
|
||||
}
|
||||
|
||||
func (c *HTTPClientConfig) defaults() {
|
||||
@@ -28,6 +33,9 @@ func (c *HTTPClientConfig) defaults() {
|
||||
if c.Propagator == nil {
|
||||
c.Propagator = otel.GetTextMapPropagator()
|
||||
}
|
||||
if c.HostFunc == nil {
|
||||
c.HostFunc = func(r *http.Request) string { return r.URL.Host }
|
||||
}
|
||||
}
|
||||
|
||||
type httpClientMetrics struct {
|
||||
@@ -50,6 +58,7 @@ type clientTransport struct {
|
||||
tracer trace.Tracer
|
||||
propagator propagation.TextMapPropagator
|
||||
metrics *httpClientMetrics
|
||||
hostFunc func(*http.Request) string
|
||||
}
|
||||
|
||||
// NewHTTPTransport wraps base (http.DefaultTransport when nil) with client
|
||||
@@ -65,6 +74,7 @@ func NewHTTPTransport(base http.RoundTripper, cfg HTTPClientConfig) http.RoundTr
|
||||
base: base,
|
||||
tracer: cfg.TracerProvider.Tracer(tracerName),
|
||||
propagator: cfg.Propagator,
|
||||
hostFunc: cfg.HostFunc,
|
||||
}
|
||||
if cfg.Metrics != nil {
|
||||
t.metrics = newHTTPClientMetrics(cfg.Metrics, cfg.Buckets)
|
||||
@@ -105,19 +115,18 @@ func (t *clientTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
}
|
||||
|
||||
if t.metrics != nil {
|
||||
host := req.URL.Host
|
||||
host := t.hostFunc(req)
|
||||
t.metrics.requests.WithLabelValues(method, host, code).Inc()
|
||||
observe(ctx, t.metrics.duration.WithLabelValues(method, host, code), time.Since(start).Seconds())
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// redactURL returns the request URL without user credentials.
|
||||
// redactURL returns the request URL without user credentials and without the
|
||||
// query string, which often carries tokens and signatures.
|
||||
func redactURL(req *http.Request) string {
|
||||
if req.URL.User == nil {
|
||||
return req.URL.String()
|
||||
}
|
||||
u := *req.URL
|
||||
u.User = nil
|
||||
u.RawQuery = ""
|
||||
return u.String()
|
||||
}
|
||||
+1
-1
@@ -97,7 +97,7 @@ func TestRedactURL(t *testing.T) {
|
||||
if strings.Contains(got, "secret") || strings.Contains(got, "user") {
|
||||
t.Errorf("credentials not redacted: %s", got)
|
||||
}
|
||||
if got != "https://example.com/path?q=1" {
|
||||
if got != "https://example.com/path" {
|
||||
t.Errorf("redactURL = %q", got)
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -25,10 +25,14 @@ const routeUnmatched = "unmatched"
|
||||
|
||||
// HTTPServerConfig configures the HTTP server middleware.
|
||||
type HTTPServerConfig struct {
|
||||
Metrics *Metrics // nil disables metrics
|
||||
Logger *slog.Logger // nil disables access logs
|
||||
TracerProvider trace.TracerProvider // nil: global provider
|
||||
Propagator propagation.TextMapPropagator // nil: global propagator
|
||||
Metrics *Metrics // nil disables metrics
|
||||
Logger *slog.Logger // nil disables access logs
|
||||
TracerProvider trace.TracerProvider // nil: global provider
|
||||
// Propagator extracts the incoming trace context; nil: global propagator.
|
||||
// Sampling follows the caller's decision, so on endpoints reachable by
|
||||
// untrusted clients set propagation.NewCompositeTextMapPropagator() to
|
||||
// ignore incoming trace headers.
|
||||
Propagator propagation.TextMapPropagator
|
||||
|
||||
// RouteFunc returns the low-cardinality route template of a request
|
||||
// (e.g. "/users/{id}"). It is called after the handler has run. The
|
||||
@@ -134,7 +138,7 @@ func NewHTTPMiddleware(cfg HTTPServerConfig) func(http.Handler) http.Handler {
|
||||
|
||||
status := rw.status
|
||||
switch {
|
||||
case rec != nil && !rw.wroteHeader:
|
||||
case rec != nil: // also after a partial response: the connection is aborted
|
||||
status = http.StatusInternalServerError
|
||||
case status == 0:
|
||||
status = http.StatusOK
|
||||
|
||||
+9
-6
@@ -90,9 +90,10 @@ func (m *Metrics) Gauge(name, help string, labels ...string) *prometheus.GaugeVe
|
||||
}
|
||||
|
||||
// GaugeFunc registers a gauge whose value is computed by fn on every scrape,
|
||||
// e.g. queue length or cache size.
|
||||
// e.g. queue length or cache size. Unlike Counter and friends it panics when
|
||||
// the name is already registered: a second fn would otherwise be ignored.
|
||||
func (m *Metrics) GaugeFunc(name, help string, fn func() float64) {
|
||||
register[prometheus.Collector](m.registry, prometheus.NewGaugeFunc(prometheus.GaugeOpts{
|
||||
m.registry.MustRegister(prometheus.NewGaugeFunc(prometheus.GaugeOpts{
|
||||
Namespace: m.cfg.Namespace,
|
||||
Subsystem: m.cfg.Subsystem,
|
||||
Name: name,
|
||||
@@ -101,9 +102,10 @@ func (m *Metrics) GaugeFunc(name, help string, fn func() float64) {
|
||||
}
|
||||
|
||||
// CounterFunc registers a counter whose value is computed by fn on every
|
||||
// scrape. fn must return monotonically increasing values.
|
||||
// scrape. fn must return monotonically increasing values. It panics when the
|
||||
// name is already registered.
|
||||
func (m *Metrics) CounterFunc(name, help string, fn func() float64) {
|
||||
register[prometheus.Collector](m.registry, prometheus.NewCounterFunc(prometheus.CounterOpts{
|
||||
m.registry.MustRegister(prometheus.NewCounterFunc(prometheus.CounterOpts{
|
||||
Namespace: m.cfg.Namespace,
|
||||
Subsystem: m.cfg.Subsystem,
|
||||
Name: name,
|
||||
@@ -112,9 +114,10 @@ func (m *Metrics) CounterFunc(name, help string, fn func() float64) {
|
||||
}
|
||||
|
||||
// RegisterDBStats exports database/sql connection pool statistics
|
||||
// (go_sql_* metrics) labeled with db_name=name.
|
||||
// (go_sql_* metrics) labeled with db_name=name. It panics when name is
|
||||
// already registered: stats of a second pool would otherwise be dropped.
|
||||
func (m *Metrics) RegisterDBStats(db *sql.DB, name string) {
|
||||
register(m.registry, collectors.NewDBStatsCollector(db, name))
|
||||
m.registry.MustRegister(collectors.NewDBStatsCollector(db, name))
|
||||
}
|
||||
|
||||
// Handler returns an http.Handler for the /metrics endpoint.
|
||||
|
||||
@@ -111,7 +111,6 @@ func TestMetrics_DBStats(t *testing.T) {
|
||||
db := sql.OpenDB(nopConnector{})
|
||||
defer db.Close()
|
||||
m.RegisterDBStats(db, "main")
|
||||
m.RegisterDBStats(db, "main") // idempotent
|
||||
|
||||
if !strings.Contains(scrape(t, m), `go_sql_max_open_connections{db_name="main"}`) {
|
||||
t.Error("db stats missing")
|
||||
|
||||
+41
-21
@@ -7,6 +7,7 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -200,25 +201,36 @@ func (o *Observer) accessLogger() *slog.Logger {
|
||||
}
|
||||
|
||||
// HTTPMiddleware instruments an HTTP handler with tracing, metrics and access
|
||||
// logs. It can wrap a handler directly or be used as router middleware:
|
||||
// logs, tuned by Config.HTTP. It can wrap a handler directly or be used as
|
||||
// router middleware:
|
||||
//
|
||||
// http.ListenAndServe(":8080", o.HTTPMiddleware(mux))
|
||||
// r.Use(o.HTTPMiddleware) // chi and similar routers
|
||||
// r.Use(o.HTTPMiddleware) // chi and similar routers: set Config.HTTP.RouteFunc
|
||||
func (o *Observer) HTTPMiddleware(next http.Handler) http.Handler {
|
||||
return NewHTTPMiddleware(HTTPServerConfig{
|
||||
Metrics: o.metrics,
|
||||
Logger: o.accessLogger(),
|
||||
TracerProvider: o.tp,
|
||||
})(next)
|
||||
cfg := o.cfg.HTTP
|
||||
if cfg.Metrics == nil {
|
||||
cfg.Metrics = o.metrics
|
||||
}
|
||||
if cfg.Logger == nil {
|
||||
cfg.Logger = o.accessLogger()
|
||||
}
|
||||
if cfg.TracerProvider == nil {
|
||||
cfg.TracerProvider = o.tp
|
||||
}
|
||||
return NewHTTPMiddleware(cfg)(next)
|
||||
}
|
||||
|
||||
// HTTPTransport wraps base (http.DefaultTransport when nil) with client
|
||||
// tracing, context propagation and metrics.
|
||||
// tracing, context propagation and metrics, tuned by Config.HTTPClient.
|
||||
func (o *Observer) HTTPTransport(base http.RoundTripper) http.RoundTripper {
|
||||
return NewHTTPTransport(base, HTTPClientConfig{
|
||||
Metrics: o.metrics,
|
||||
TracerProvider: o.tp,
|
||||
})
|
||||
cfg := o.cfg.HTTPClient
|
||||
if cfg.Metrics == nil {
|
||||
cfg.Metrics = o.metrics
|
||||
}
|
||||
if cfg.TracerProvider == nil {
|
||||
cfg.TracerProvider = o.tp
|
||||
}
|
||||
return NewHTTPTransport(base, cfg)
|
||||
}
|
||||
|
||||
// HTTPClient returns an *http.Client with an instrumented transport.
|
||||
@@ -226,16 +238,24 @@ func (o *Observer) HTTPClient() *http.Client {
|
||||
return &http.Client{Transport: o.HTTPTransport(nil)}
|
||||
}
|
||||
|
||||
// GRPCInterceptors returns instrumented gRPC interceptors bound to this Observer.
|
||||
// GRPCInterceptors returns instrumented gRPC interceptors bound to this
|
||||
// Observer, tuned by Config.GRPC. Health-check calls are never instrumented.
|
||||
func (o *Observer) GRPCInterceptors() *GRPCInterceptors {
|
||||
return NewGRPCInterceptors(GRPCConfig{
|
||||
Metrics: o.metrics,
|
||||
Logger: o.accessLogger(),
|
||||
TracerProvider: o.tp,
|
||||
Skip: func(fullMethod string) bool {
|
||||
return fullMethod == "/grpc.health.v1.Health/Check" || fullMethod == "/grpc.health.v1.Health/Watch"
|
||||
},
|
||||
})
|
||||
cfg := o.cfg.GRPC
|
||||
if cfg.Metrics == nil {
|
||||
cfg.Metrics = o.metrics
|
||||
}
|
||||
if cfg.Logger == nil {
|
||||
cfg.Logger = o.accessLogger()
|
||||
}
|
||||
if cfg.TracerProvider == nil {
|
||||
cfg.TracerProvider = o.tp
|
||||
}
|
||||
skip := cfg.Skip
|
||||
cfg.Skip = func(fullMethod string) bool {
|
||||
return strings.HasPrefix(fullMethod, "/grpc.health.v1.Health/") || skip != nil && skip(fullMethod)
|
||||
}
|
||||
return NewGRPCInterceptors(cfg)
|
||||
}
|
||||
|
||||
// GRPCServerOptions returns grpc.NewServer options with instrumentation.
|
||||
|
||||
+6
-4
@@ -182,7 +182,7 @@ func TestObserver_TrackError(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestObserver_AdminServer(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{Addr: "127.0.0.1:0"}})
|
||||
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{Addr: "127.0.0.1:0", EnablePprof: true}})
|
||||
base := "http://" + o.AdminAddr()
|
||||
|
||||
get := func(path string) (int, string) {
|
||||
@@ -249,8 +249,8 @@ func TestObserver_AdminServer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_AdminDisablePprof(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{DisablePprof: true}})
|
||||
func TestObserver_AdminPprofOffByDefault(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{}})
|
||||
w := httptest.NewRecorder()
|
||||
o.AdminHandler().ServeHTTP(w, httptest.NewRequest("GET", "/debug/pprof/", nil))
|
||||
if w.Code != http.StatusNotFound {
|
||||
@@ -294,6 +294,8 @@ func TestConfig_WithEnv(t *testing.T) {
|
||||
t.Setenv("OBSX_LOG_LEVEL", "debug")
|
||||
t.Setenv("OBSX_TRACING_SAMPLER", "0.25")
|
||||
t.Setenv("OBSX_TRACING_DISABLED", "true")
|
||||
t.Setenv("OBSX_TRACING_INSECURE", "true")
|
||||
t.Setenv("OBSX_ADMIN_ENABLE_PPROF", "true")
|
||||
t.Setenv("OBSX_HEALTH_TIMEOUT", "3s")
|
||||
t.Setenv("OBSX_ADMIN_ADDR", ":9999")
|
||||
t.Setenv("OBSX_DISABLE_ACCESS_LOG", "not-a-bool")
|
||||
@@ -306,7 +308,7 @@ func TestConfig_WithEnv(t *testing.T) {
|
||||
if cfg.Environment != "staging" || cfg.Logging.Level != "debug" || cfg.Logging.Format != "text" {
|
||||
t.Errorf("unexpected config: %+v", cfg)
|
||||
}
|
||||
if cfg.Tracing.Sampler != 0.25 || !cfg.Tracing.Disabled {
|
||||
if cfg.Tracing.Sampler != 0.25 || !cfg.Tracing.Disabled || !cfg.Tracing.Insecure || !cfg.Admin.EnablePprof {
|
||||
t.Errorf("unexpected tracing config: %+v", cfg.Tracing)
|
||||
}
|
||||
if cfg.Health.Timeout != 3*time.Second || cfg.Admin.Addr != ":9999" {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
@@ -31,7 +32,7 @@ const (
|
||||
type TracerConfig struct {
|
||||
ServiceName string
|
||||
ServiceVersion string
|
||||
// Environment is the deployment.environment resource attribute, e.g. "production".
|
||||
// Environment is the deployment.environment.name resource attribute, e.g. "production".
|
||||
Environment string
|
||||
// Endpoint is the OTLP collector endpoint: "host:port" or a URL
|
||||
// ("https://collector:4318"). When empty, the standard
|
||||
@@ -39,7 +40,9 @@ type TracerConfig struct {
|
||||
// variables are used; if those are unset too, spans are still created and
|
||||
// propagated (trace IDs appear in logs) but not exported.
|
||||
Endpoint string
|
||||
// Protocol is ProtocolGRPC (default) or ProtocolHTTP.
|
||||
// Protocol is ProtocolGRPC or ProtocolHTTP. When empty,
|
||||
// OTEL_EXPORTER_OTLP_TRACES_PROTOCOL / OTEL_EXPORTER_OTLP_PROTOCOL apply,
|
||||
// then ProtocolGRPC.
|
||||
Protocol string
|
||||
// Insecure disables TLS for the OTLP connection (local collectors, sidecars).
|
||||
Insecure bool
|
||||
@@ -65,7 +68,7 @@ func (c *TracerConfig) defaults() {
|
||||
c.Sampler = 1.0
|
||||
}
|
||||
if c.Protocol == "" {
|
||||
c.Protocol = ProtocolGRPC
|
||||
c.Protocol = cmp.Or(os.Getenv("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"), os.Getenv("OTEL_EXPORTER_OTLP_PROTOCOL"), ProtocolGRPC)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +191,7 @@ func newResource(ctx context.Context, cfg TracerConfig) (*resource.Resource, err
|
||||
attrs = append(attrs, semconv.ServiceVersion(cfg.ServiceVersion))
|
||||
}
|
||||
if cfg.Environment != "" {
|
||||
attrs = append(attrs, semconv.DeploymentEnvironment(cfg.Environment))
|
||||
attrs = append(attrs, attribute.String("deployment.environment.name", cfg.Environment))
|
||||
}
|
||||
if host, err := os.Hostname(); err == nil {
|
||||
attrs = append(attrs, semconv.ServiceInstanceID(host))
|
||||
|
||||
+4
-4
@@ -236,10 +236,10 @@ func TestNewResource_Attributes(t *testing.T) {
|
||||
got[string(kv.Key)] = kv.Value.Emit()
|
||||
}
|
||||
for k, v := range map[string]string{
|
||||
"service.name": "svc",
|
||||
"service.version": "v1",
|
||||
"deployment.environment": "prod",
|
||||
"team": "payments",
|
||||
"service.name": "svc",
|
||||
"service.version": "v1",
|
||||
"deployment.environment.name": "prod",
|
||||
"team": "payments",
|
||||
} {
|
||||
if got[k] != v {
|
||||
t.Errorf("resource %s = %q, want %q", k, got[k], v)
|
||||
|
||||
Reference in new issue
Block a user