diff --git a/README.md b/README.md index d65ac5c..130a26e 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,14 @@ Configuration is done via environment variables. The following environment varia | `MU_V2FLY_ADDRS` | Comma-separated list of V2Fly server addresses (VMess inbound, tag `proxy`) | `v2fly1.example.com,v2fly2.example.com` | | `MU_VLESS_ADDRS` | Comma-separated list of V2Fly server addresses with a VLESS inbound | `vless1.example.com,vless2.example.com` | | `MU_VLESS_INBOUND_TAG` | Tag of the VLESS inbound on those servers (default `vless`) | `vless` | +| `MU_METRICS_ENABLED` | Serve Prometheus metrics at `/metrics` (default `true`) | `true` | +| `MU_METRICS_PORT` | Metrics listen port, all interfaces (default `9090`) | `9090` | +| `MU_TRACING_ENABLED` | Enable OpenTelemetry tracing (default `false`) | `true` | +| `MU_TRACING_EXPORTER` | `otlp` (OTLP/gRPC, default) or `stdout` (JSON spans on stderr) | `otlp` | +| `MU_TRACING_ENDPOINT` | OTLP collector `host:port` or URL; empty defers to `OTEL_EXPORTER_OTLP_*`, then `localhost:4317` | `otel-collector:4317` | +| `MU_TRACING_INSECURE` | Plaintext gRPC for `host:port` endpoints (default `true`); URLs use their scheme | `false` | +| `MU_TRACING_SERVICE_NAME` | `service.name` resource attribute (default `mu-service`) | `mu-node-1` | +| `MU_TRACING_SAMPLE_RATE` | Parent-based trace ID ratio, `0`–`1` (default `1`) | `0.1` | ### API failure diagnostics @@ -76,6 +84,94 @@ export MU_VLESS_ADDRS="vless1.example.com" export MU_VLESS_INBOUND_TAG="vless" ``` +## Observability + +mu exposes Prometheus metrics and, optionally, OpenTelemetry traces. Metrics are always on unless +`MU_METRICS_ENABLED=false`; tracing is off by default and costs nothing while disabled. The metrics +endpoint is unauthenticated and listens on all interfaces: keep it on a trusted network. + +### Metrics + +Scrape `http://:9090/metrics`. With an OpenTelemetry Collector, use the `prometheus` receiver +(see below) to forward them over OTLP. + +| Metric | Type | Labels | Use | +|--------|------|--------|-----| +| `mu_build_info` | gauge | `version`, `go_version` | Which build is running | +| `mu_api_requests_total` | counter | `rpc`, `status`, `code` | MU API outcomes per RPC; `code` is the Twirp error code (transport failures appear as `internal`) | +| `mu_api_request_duration_seconds` | histogram | `rpc` | MU API latency per RPC | +| `mu_ping_total`, `mu_ping_duration_seconds` | counter, histogram | `status` | Ping job | +| `mu_user_sync_total`, `mu_user_sync_duration_seconds` | counter, histogram | `status`, `sync_type` | Per-protocol user sync (`trojan`, `v2fly`, `vless`) | +| `mu_traffic_sync_total`, `mu_traffic_sync_duration_seconds` | counter, histogram | `status` | Traffic collection + upload cycle | +| `mu_job_last_success_timestamp_seconds` | gauge | `job` (`ping`, `sync_user`, `sync_traffic`) | Staleness alerts | +| `mu_traffic_outbox_batches`, `mu_traffic_outbox_logs` | gauge | – | Durable upload queue size; keeps growing while the API is unreachable | +| `mu_backend_user_operations_total` | counter | `sync_type`, `operation` (`add`, `remove`), `status` | Add/remove calls against backends (V2Ray adds are idempotent and repeat every sync) | +| `mu_traffic_logs_collected`, `mu_traffic_logs_uploaded` | gauge | `sync_type` / – | Records in the last cycle | +| `mu_total_upload_bytes`, `mu_total_download_bytes` | counter | `sync_type` | Reported traffic (VLESS is counted under `v2fly`) | +| `mu_users_count` | gauge | `node_id` | Users in the last snapshot | +| `mu_errors_total` | counter | `operation`, `error_type` | Failures by stage | + +Example alerts: `time() - mu_job_last_success_timestamp_seconds{job="sync_traffic"} > 300` and +`mu_traffic_outbox_logs > 0` for longer than a few cycles. + +### Traces + +Every 60-second cycle produces three traces (`App.ping`, `App.syncTraffic`, `App.syncUser`): + +- `App.ping` → `MU.Ping` +- `App.syncTraffic` → `App.flushTraffic` (attributes `traffic.batches_uploaded`, `traffic.logs_uploaded`) → + `MU.UploadTrafficLog`, then `MU.GetUsers` and one `App.syncTraffic.` span per backend + (`traffic.logs_collected`); the root span carries `traffic.outbox_batches` / `traffic.outbox_logs`. +- `App.syncUser` (`mu.users`) → `MU.GetUsers` and one `App.syncUser.` span per backend with + `sync.users_desired`, `sync.users_enabled`, `sync.users_removed`, `sync.users_applied` + (V2Fly/VLESS also `sync.users_observed` and `sync.stats_available`). + +`MU.*` spans are client spans with `rpc.system=twirp`, `rpc.method`, `mu.node_id`, +`http.response.status_code`, `rpc.twirp.error_code`, `mu.request_id` and `mu.cf_ray` when available. +Failures set the span status to error; only the sanitized error category is recorded, never remote +messages or the API token. The W3C `traceparent` header is sent to the MU API, so API-side traces can +join mu's. Resource attributes: `service.name`, `service.version`, `mu.node_id`, host and process +information; `OTEL_RESOURCE_ATTRIBUTES` and `OTEL_EXPORTER_OTLP_*` (headers, TLS, timeout, ...) are honored. +`MU API request failed` logs include `trace_id` and `span_id` when tracing is on. + +Debug without a collector (no Docker needed): + +```bash +MU_TRACING_ENABLED=true MU_TRACING_EXPORTER=stdout ./bin/mu 2> mu.log +``` + +Send traces to a collector: + +```bash +export MU_TRACING_ENABLED=true +export MU_TRACING_ENDPOINT=otel-collector:4317 # or https://collector.example.com:4317 +export MU_TRACING_SAMPLE_RATE=0.25 +``` + +Minimal Collector configuration receiving OTLP traces and scraping mu's metrics: + +```yaml +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + prometheus: + config: + scrape_configs: + - job_name: mu + scrape_interval: 30s + static_configs: + - targets: ["mu:9090"] +exporters: + debug: + verbosity: detailed +service: + pipelines: + traces: { receivers: [otlp], exporters: [debug] } + metrics: { receivers: [prometheus], exporters: [debug] } +``` + ## Docker Compose You can use Docker Compose to run mu in a containerized environment. Here's an example `docker-compose.yml` file: diff --git a/client.go b/client.go index 7c92952..d42e7a4 100644 --- a/client.go +++ b/client.go @@ -9,6 +9,10 @@ import ( pb "github.com/icebase/mu/proto/v1" "github.com/twitchtv/twirp" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" ) const ( @@ -24,6 +28,18 @@ type Client struct { nodeID string client pb.MUService apiDebug bool + observer RequestObserver +} + +const instrumentationName = "github.com/icebase/mu" + +// RequestObserver is called after every MU API request. code is the Twirp error code when the +// server returned one; err is the sanitized error (nil on success). +type RequestObserver func(rpc string, elapsed time.Duration, code string, err error) + +// WithRequestObserver registers a callback used for metrics. +func WithRequestObserver(observer RequestObserver) ClientOption { + return func(c *Client) { c.observer = observer } } // ClientOption configures MU client diagnostics. @@ -60,11 +76,12 @@ func (c *Client) newContext(ctx context.Context) context.Context { func (c *Client) GetUsers(ctx context.Context, req *pb.GetUsersRequest) (*pb.GetUsersResponse, error) { req.NodeId = c.nodeID - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) - defer cancel() - ctx, diagnostics := newRequestDiagnostics(ctx) - response, err := c.client.GetUsers(c.newContext(ctx), req) - return response, c.requestError(ctx, "GetUsers", "get MU users", diagnostics, err) + var response *pb.GetUsersResponse + err := c.call(ctx, "GetUsers", "get MU users", func(ctx context.Context) (err error) { + response, err = c.client.GetUsers(ctx, req) + return err + }) + return response, err } func (c *Client) UploadTrafficLog(ctx context.Context, req *pb.UploadTrafficLogRequest) (*pb.UploadTrafficLogResponse, error) { @@ -72,19 +89,64 @@ func (c *Client) UploadTrafficLog(ctx context.Context, req *pb.UploadTrafficLogR if req.UploadAt == 0 { req.UploadAt = time.Now().Unix() } - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) - defer cancel() - ctx, diagnostics := newRequestDiagnostics(ctx) - response, err := c.client.UploadTrafficLog(c.newContext(ctx), req) - return response, c.requestError(ctx, "UploadTrafficLog", "upload MU traffic", diagnostics, err) + var response *pb.UploadTrafficLogResponse + err := c.call(ctx, "UploadTrafficLog", "upload MU traffic", func(ctx context.Context) (err error) { + response, err = c.client.UploadTrafficLog(ctx, req) + return err + }) + return response, err } func (c *Client) Ping(ctx context.Context, req *pb.PingRequest) (*pb.PingResponse, error) { + var response *pb.PingResponse + err := c.call(ctx, "Ping", "ping MU", func(ctx context.Context) (err error) { + response, err = c.client.Ping(ctx, req) + return err + }) + return response, err +} + +// call runs one MU API request with a deadline, a client span, diagnostics and the optional observer. +// Only sanitized error details reach spans, logs and the observer; see apiError. +func (c *Client) call(ctx context.Context, rpc, operation string, invoke func(context.Context) error) error { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() + ctx, span := otel.Tracer(instrumentationName).Start(ctx, "MU."+rpc, trace.WithSpanKind(trace.SpanKindClient), + trace.WithAttributes( + attribute.String("rpc.system", "twirp"), + attribute.String("rpc.method", rpc), + attribute.String("mu.node_id", c.nodeID), + )) + defer span.End() ctx, diagnostics := newRequestDiagnostics(ctx) - response, err := c.client.Ping(c.newContext(ctx), req) - return response, c.requestError(ctx, "Ping", "ping MU", diagnostics, err) + rawErr := invoke(c.newContext(ctx)) + err := c.requestError(ctx, rpc, operation, diagnostics, rawErr) + elapsed := time.Since(diagnostics.started) + code := "" + var remote twirp.Error + if errors.As(rawErr, &remote) { + code = string(remote.Code()) + } + if diagnostics.status != 0 { + span.SetAttributes(attribute.Int("http.response.status_code", diagnostics.status)) + } + if diagnostics.requestID != "" { + span.SetAttributes(attribute.String("mu.request_id", c.diagnosticText(diagnostics.requestID))) + } + if diagnostics.cfRay != "" { + span.SetAttributes(attribute.String("mu.cf_ray", c.diagnosticText(diagnostics.cfRay))) + } + if err != nil { + if code != "" { + span.SetAttributes(attribute.String("rpc.twirp.error_code", code)) + } + span.RecordError(err) + span.SetStatus(codes.Error, err.Error()) + } + if c.observer != nil { + c.observer(rpc, elapsed, code, err) + } + return err } // Remote messages can contain authentication material. Expose only the error category. diff --git a/client_diagnostics.go b/client_diagnostics.go index f445760..459d038 100644 --- a/client_diagnostics.go +++ b/client_diagnostics.go @@ -9,6 +9,9 @@ import ( "time" "github.com/twitchtv/twirp" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" ) const maxDiagnosticLength = 2048 @@ -32,6 +35,8 @@ func newRequestDiagnostics(ctx context.Context) (context.Context, *requestDiagno type diagnosticHTTPClient struct{ client *http.Client } func (c *diagnosticHTTPClient) Do(req *http.Request) (*http.Response, error) { + // Propagate the trace context (traceparent/tracestate/baggage) so API-side traces can be joined. + otel.GetTextMapPropagator().Inject(req.Context(), propagation.HeaderCarrier(req.Header)) response, err := c.client.Do(req) if details, ok := req.Context().Value(diagnosticsKey{}).(*requestDiagnostics); ok { details.transportErr = err @@ -58,6 +63,9 @@ func (c *Client) requestError(ctx context.Context, rpc, operation string, detail if details.cfRay != "" { attrs = append(attrs, "cf_ray", c.diagnosticText(details.cfRay)) } + if sc := trace.SpanContextFromContext(ctx); sc.IsValid() { + attrs = append(attrs, "trace_id", sc.TraceID().String(), "span_id", sc.SpanID().String()) + } if ctx.Err() != nil { attrs = append(attrs, "context_error", ctx.Err().Error()) } diff --git a/client_observability_test.go b/client_observability_test.go new file mode 100644 index 0000000..d0357ca --- /dev/null +++ b/client_observability_test.go @@ -0,0 +1,107 @@ +package mu + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + pb "github.com/icebase/mu/proto/v1" + "github.com/twitchtv/twirp" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/propagation" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + "go.opentelemetry.io/otel/trace/noop" +) + +type observed struct { + rpc string + code string + err error + elapsed time.Duration +} + +func TestClientEmitsSpanPropagatesTraceAndNotifiesObserver(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder))) + otel.SetTextMapPropagator(propagation.TraceContext{}) + t.Cleanup(func() { + otel.SetTracerProvider(noop.NewTracerProvider()) + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator()) + }) + + var mu sync.Mutex + var traceparents []string + service := &clientTestService{} + handler := pb.NewMUServiceServer(service, twirp.WithServerPathPrefix("")) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + traceparents = append(traceparents, r.Header.Get("traceparent")) + mu.Unlock() + w.Header().Set("X-Request-ID", "req-1") + handler.ServeHTTP(w, r) + })) + t.Cleanup(server.Close) + + var calls []observed + client := NewClient(server.URL, "fixture-token", "node", WithRequestObserver(func(rpc string, elapsed time.Duration, code string, err error) { + calls = append(calls, observed{rpc, code, err, elapsed}) + })) + + if _, err := client.Ping(context.Background(), &pb.PingRequest{}); err != nil { + t.Fatal(err) + } + // The fixture fails the first upload with a Twirp "internal" error. + _, uploadErr := client.UploadTrafficLog(context.Background(), &pb.UploadTrafficLogRequest{}) + if uploadErr == nil { + t.Fatal("expected upload failure") + } + + if len(calls) != 2 || calls[0].rpc != "Ping" || calls[0].err != nil || calls[0].code != "" || calls[0].elapsed <= 0 { + t.Fatalf("unexpected success observation: %+v", calls) + } + if calls[1].rpc != "UploadTrafficLog" || calls[1].code != string(twirp.Internal) || calls[1].err == nil || + strings.Contains(calls[1].err.Error(), "fixture-credential") { + t.Fatalf("unexpected failure observation (must be sanitized): %+v", calls[1]) + } + + spans := recorder.Ended() + if len(spans) != 2 { + t.Fatalf("expected 2 client spans, got %d", len(spans)) + } + for _, span := range spans { + if !strings.HasPrefix(span.Name(), "MU.") { + t.Errorf("unexpected span name %q", span.Name()) + } + } + failed := spans[1] + if failed.Status().Code.String() != "Error" || strings.Contains(failed.Status().Description, "fixture-credential") { + t.Errorf("failed span status = %+v", failed.Status()) + } + attrs := map[attribute.Key]attribute.Value{} + for _, kv := range failed.Attributes() { + attrs[kv.Key] = kv.Value + } + if attrs["rpc.method"].AsString() != "UploadTrafficLog" || attrs["mu.node_id"].AsString() != "node" || + attrs["http.response.status_code"].AsInt64() != http.StatusInternalServerError || + attrs["rpc.twirp.error_code"].AsString() != "internal" || attrs["mu.request_id"].AsString() != "req-1" { + t.Errorf("missing span attributes: %v", attrs) + } + + mu.Lock() + defer mu.Unlock() + if len(traceparents) != 2 { + t.Fatalf("expected 2 requests, got %d", len(traceparents)) + } + for i, header := range traceparents { + want := "00-" + spans[i].SpanContext().TraceID().String() + "-" + spans[i].SpanContext().SpanID().String() + "-01" + if header != want { + t.Errorf("request %d traceparent = %q, want %q", i, header, want) + } + } +} diff --git a/go.mod b/go.mod index 8e5cc74..decc1a7 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( go.opentelemetry.io/otel v1.47.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 + go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.47.0 go.opentelemetry.io/otel/sdk v1.47.0 go.opentelemetry.io/otel/trace v1.47.0 golang.org/x/sys v0.49.0 diff --git a/go.sum b/go.sum index a13ff9f..7ffbf7e 100644 --- a/go.sum +++ b/go.sum @@ -207,6 +207,8 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSd go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 h1:UFpxOpYPmMNUtOWhdb+nC1WELIgVf8z9higURrbzYU4= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0/go.mod h1:YBGjxe3lt0jtXoEXxGrGhv/jM7oUBUDVK7zhAvNyEjc= +go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.47.0 h1:N3YQCxjxQ/bMjyc3heladfRm9t9RTksGQH8z4w6yU/0= +go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.47.0/go.mod h1:Mp8HOFqcaUyypCuGv9IhDdTHnJ56lSudSHMd+pVSCEA= go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= diff --git a/internal/mu/app/app.go b/internal/mu/app/app.go index 92f3b8b..f06c2cc 100644 --- a/internal/mu/app/app.go +++ b/internal/mu/app/app.go @@ -9,6 +9,7 @@ import ( "net/http" "os" "os/signal" + "runtime" "syscall" "time" @@ -18,7 +19,6 @@ import ( pb "github.com/icebase/mu/proto/v1" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/trace" @@ -60,13 +60,15 @@ func (a *App) Init() (err error) { if err != nil { return fmt.Errorf("open synchronization state: %w", err) } + metrics.SetOutbox(a.state.pendingStats()) if err := a.initTracing(); err != nil { return fmt.Errorf("init tracing: %w", err) } if err := a.initMetrics(); err != nil { return fmt.Errorf("init metrics: %w", err) } - a.muClient = mu.NewClient(a.config.MuAPIBaseURL, a.config.MuAPIToken, a.config.MuNodeID, mu.WithAPIDebug(a.config.MuAPIDebug)) + a.muClient = mu.NewClient(a.config.MuAPIBaseURL, a.config.MuAPIToken, a.config.MuNodeID, + mu.WithAPIDebug(a.config.MuAPIDebug), mu.WithRequestObserver(metrics.ObserveAPIRequest)) for _, addr := range a.config.TrojanAddrs { syncer, err := newTrojanSync(addr, a.state) if err != nil { @@ -91,15 +93,22 @@ func (a *App) Init() (err error) { return nil } func (a *App) initTracing() error { - provider, err := tracing.InitTracer(a.ctx, a.config.Tracing) + cfg := a.config.Tracing + cfg.ServiceVersion = version + cfg.NodeID = a.config.MuNodeID + provider, err := tracing.InitTracer(a.ctx, cfg) if err != nil { return err } a.tracerProvider = provider - a.tracer = otel.Tracer("mu-app") + a.tracer = tracing.Tracer() + if cfg.Enabled { + slog.Info("tracing enabled", "exporter", cfg.Exporter, "sample_rate", cfg.SampleRate) + } return nil } func (a *App) initMetrics() error { + metrics.BuildInfo.WithLabelValues(version, runtime.Version()).Set(1) if !a.config.MetricsEnabled { return nil } @@ -108,7 +117,7 @@ func (a *App) initMetrics() error { a.metricsServer = &http.Server{Addr: ":" + a.config.MetricsPort, Handler: mux, ReadHeaderTimeout: 5 * time.Second} go func() { if err := a.metricsServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { - slog.Error("metrics server failed") + slog.Error("metrics server failed", "addr", a.metricsServer.Addr, "error", err) } }() return nil @@ -166,9 +175,10 @@ func (a *App) jobs() { } } } -func (a *App) ping() error { +func (a *App) ping() (resultErr error) { ctx, span := a.tracer.Start(a.ctx, "App.ping") defer span.End() + defer func() { finishSpan(ctx, resultErr, "ping failed") }() timer := prometheus.NewTimer(metrics.PingDuration) defer timer.ObserveDuration() _, err := a.muClient.Ping(ctx, &pb.PingRequest{NodeId: a.config.MuNodeID, Version: version}) @@ -176,9 +186,11 @@ func (a *App) ping() error { if err != nil { result = syncFailure metrics.ErrorsTotal.WithLabelValues("ping", "api_error").Inc() - tracing.RecordError(ctx, err, "ping failed") } metrics.PingCounter.WithLabelValues(result).Inc() + if err == nil { + metrics.MarkJobSuccess(metrics.JobPing) + } return err } func (a *App) fetchUsers(ctx context.Context) ([]*pb.User, error) { @@ -194,14 +206,21 @@ func (a *App) fetchUsers(ctx context.Context) ([]*pb.User, error) { } return response.Users, nil } -func (a *App) syncUser() error { +func (a *App) syncUser() (resultErr error) { ctx, span := a.tracer.Start(a.ctx, "App.syncUser") defer span.End() + defer func() { + finishSpan(ctx, resultErr, "user sync failed") + if resultErr == nil { + metrics.MarkJobSuccess(metrics.JobSyncUser) + } + }() users, err := a.fetchUsers(ctx) if err != nil { metrics.ErrorsTotal.WithLabelValues("sync_user", "api_error").Inc() return err } + span.SetAttributes(attribute.Int("mu.users", len(users)), attribute.Int("sync.backends", len(a.userSync))) metrics.UsersCount.WithLabelValues(a.config.MuNodeID).Set(float64(len(users))) var errs []error for index, syncer := range a.userSync { @@ -221,6 +240,7 @@ func (a *App) syncUser() error { metrics.ErrorsTotal.WithLabelValues("sync_user", syncType+"_error").Inc() tracing.RecordError(child, err, "backend user sync failed") } + childSpan.SetAttributes(attribute.String("sync.result", result)) metrics.UserSyncCounter.WithLabelValues(result, syncType).Inc() childSpan.End() } @@ -235,11 +255,12 @@ func (a *App) syncTraffic() (resultErr error) { timer := prometheus.NewTimer(metrics.TrafficSyncDuration) defer timer.ObserveDuration() defer func() { - result := syncSuccess - if resultErr != nil { - result = syncFailure + finishSpan(ctx, resultErr, "traffic sync failed") + metrics.TrafficSyncCounter.WithLabelValues(metrics.Result(resultErr)).Inc() + a.publishOutbox(span) + if resultErr == nil { + metrics.MarkJobSuccess(metrics.JobSyncTraffic) } - metrics.TrafficSyncCounter.WithLabelValues(result).Inc() }() var errs []error metrics.TrafficLogsUploaded.Set(0) @@ -257,11 +278,12 @@ func (a *App) syncTraffic() (resultErr error) { for index, syncer := range a.userSync { syncType := syncer.Name() child, childSpan := a.tracer.Start(ctx, "App.syncTraffic."+syncType, - trace.WithAttributes(attribute.Int("sync.backend_index", index)), + trace.WithAttributes(attribute.String("sync.type", syncType), attribute.Int("sync.backend_index", index)), ) child, cancel := context.WithTimeout(child, backendTimeout) logs, err := syncer.GetTraffic(child, users) cancel() + childSpan.SetAttributes(attribute.Int("traffic.logs_collected", len(logs))) collected[syncType] += len(logs) metrics.TrafficLogsCollected.WithLabelValues(syncType).Set(float64(collected[syncType])) if err != nil { @@ -279,9 +301,16 @@ func (a *App) syncTraffic() (resultErr error) { } return errors.Join(errs...) } -func (a *App) flushTraffic(ctx context.Context) error { +func (a *App) flushTraffic(ctx context.Context) (resultErr error) { + ctx, span := a.tracer.Start(ctx, "App.flushTraffic") + defer span.End() + defer func() { finishSpan(ctx, resultErr, "traffic upload failed") }() ctx, cancel := context.WithTimeout(ctx, backendTimeout) defer cancel() + uploadedBatches, uploadedLogs := 0, 0 + defer func() { + span.SetAttributes(attribute.Int("traffic.batches_uploaded", uploadedBatches), attribute.Int("traffic.logs_uploaded", uploadedLogs)) + }() for { snapshot := a.state.snapshot() if len(snapshot.Pending) == 0 { @@ -296,6 +325,8 @@ func (a *App) flushTraffic(ctx context.Context) error { if err := a.state.acknowledge(); err != nil { return err } + uploadedBatches++ + uploadedLogs += len(batch.Logs) metrics.TrafficLogsUploaded.Add(float64(len(batch.Logs))) for _, log := range batch.Logs { kind := protocolTrojan @@ -307,3 +338,15 @@ func (a *App) flushTraffic(ctx context.Context) error { } } } + +// finishSpan marks the span in ctx as failed when err is non-nil. +func finishSpan(ctx context.Context, err error, description string) { + tracing.RecordError(ctx, err, description) +} + +// publishOutbox exports the size of the durable upload queue as metrics and span attributes. +func (a *App) publishOutbox(span trace.Span) { + batches, logs := a.state.pendingStats() + metrics.SetOutbox(batches, logs) + span.SetAttributes(attribute.Int("traffic.outbox_batches", batches), attribute.Int("traffic.outbox_logs", logs)) +} diff --git a/internal/mu/app/config.go b/internal/mu/app/config.go index bcc2a8b..3e77ca8 100644 --- a/internal/mu/app/config.go +++ b/internal/mu/app/config.go @@ -30,13 +30,16 @@ type Config struct { // ConfigFromEnv initializes and returns a Config object with values from environment variables. // Environment variable names: -// - MU_API_BASE_URL: API base URL -// - MU_API_TOKEN: API token -// - MU_NODE_ID: Node identifier -// - MU_TROJAN_ADDRS: Comma-separated list of Trojan addresses -// - MU_V2FLY_ADDRS: Comma-separated list of V2Fly addresses -// - MU_VLESS_ADDRS: Comma-separated list of V2Fly addresses hosting a VLESS inbound -// - MU_VLESS_INBOUND_TAG: Tag of the VLESS inbound (default "vless") +// - MU_API_BASE_URL: API base URL +// - MU_API_TOKEN: API token +// - MU_NODE_ID: Node identifier +// - MU_TROJAN_ADDRS: Comma-separated list of Trojan addresses +// - MU_V2FLY_ADDRS: Comma-separated list of V2Fly addresses +// - MU_VLESS_ADDRS: Comma-separated list of V2Fly addresses hosting a VLESS inbound +// - MU_VLESS_INBOUND_TAG: Tag of the VLESS inbound (default "vless") +// - MU_METRICS_ENABLED / MU_METRICS_PORT: Prometheus endpoint (default true / 9090) +// - MU_TRACING_ENABLED, MU_TRACING_EXPORTER, MU_TRACING_ENDPOINT, MU_TRACING_INSECURE, +// MU_TRACING_SERVICE_NAME, MU_TRACING_SAMPLE_RATE: OpenTelemetry tracing (disabled by default) func ConfigFromEnv() *Config { v := viper.New() @@ -58,7 +61,8 @@ func ConfigFromEnv() *Config { // Tracing defaults v.SetDefault("TRACING_ENABLED", false) v.SetDefault("TRACING_SERVICE_NAME", "mu-service") - v.SetDefault("TRACING_ENDPOINT", "localhost:4317") + v.SetDefault("TRACING_EXPORTER", tracing.ExporterOTLP) + v.SetDefault("TRACING_ENDPOINT", "") v.SetDefault("TRACING_INSECURE", true) v.SetDefault("TRACING_SAMPLE_RATE", 1.0) @@ -84,6 +88,7 @@ func ConfigFromEnv() *Config { Tracing: tracing.Config{ Enabled: v.GetBool("TRACING_ENABLED"), ServiceName: v.GetString("TRACING_SERVICE_NAME"), + Exporter: v.GetString("TRACING_EXPORTER"), Endpoint: v.GetString("TRACING_ENDPOINT"), Insecure: v.GetBool("TRACING_INSECURE"), SampleRate: v.GetFloat64("TRACING_SAMPLE_RATE"), diff --git a/internal/mu/app/config_test.go b/internal/mu/app/config_test.go index 2431ca1..90c5536 100644 --- a/internal/mu/app/config_test.go +++ b/internal/mu/app/config_test.go @@ -13,7 +13,7 @@ func defaultTracing() tracing.Config { return tracing.Config{ Enabled: false, ServiceName: "mu-service", - Endpoint: "localhost:4317", + Exporter: "otlp", Insecure: true, SampleRate: 1.0, } diff --git a/internal/mu/app/metrics/metrics.go b/internal/mu/app/metrics/metrics.go index 5016b3a..72b407b 100644 --- a/internal/mu/app/metrics/metrics.go +++ b/internal/mu/app/metrics/metrics.go @@ -1,6 +1,8 @@ package metrics import ( + "time" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" ) @@ -112,4 +114,101 @@ var ( }, []string{labelSyncType}, ) + + // BuildInfo exposes the running version, useful to correlate behavior changes with deployments. + BuildInfo = promauto.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "mu_build_info", + Help: "Build information; the value is always 1", + }, + []string{"version", "go_version"}, + ) + + // MU API 请求指标(每个 RPC 一次 HTTP 调用) + APIRequests = promauto.NewCounterVec( + prometheus.CounterOpts{ + Name: "mu_api_requests_total", + Help: "Total number of MU API requests by rpc, outcome and Twirp error code (empty on success; transport failures are reported by Twirp as internal)", + }, + []string{"rpc", labelStatus, "code"}, + ) + + APIRequestDuration = promauto.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "mu_api_request_duration_seconds", + Help: "Duration of MU API requests in seconds", + Buckets: prometheus.DefBuckets, + }, + []string{"rpc"}, + ) + + // 任务最近一次成功时间,用于告警(time() - mu_job_last_success_timestamp_seconds) + JobLastSuccess = promauto.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "mu_job_last_success_timestamp_seconds", + Help: "Unix time of the last fully successful run of a job (ping, sync_user, sync_traffic)", + }, + []string{"job"}, + ) + + // 待上传流量队列(持久化 outbox) + OutboxBatches = promauto.NewGauge( + prometheus.GaugeOpts{ + Name: "mu_traffic_outbox_batches", + Help: "Number of queued traffic batches waiting for upload", + }, + ) + + OutboxLogs = promauto.NewGauge( + prometheus.GaugeOpts{ + Name: "mu_traffic_outbox_logs", + Help: "Number of queued traffic log records waiting for upload", + }, + ) + + // 后端(Trojan/V2Fly/VLESS)用户增删操作 + BackendUserOperations = promauto.NewCounterVec( + prometheus.CounterOpts{ + Name: "mu_backend_user_operations_total", + Help: "Total number of user add/remove calls made to proxy backends", + }, + []string{labelSyncType, "operation", labelStatus}, + ) ) + +// Job names used by JobLastSuccess. +const ( + JobPing = "ping" + JobSyncUser = "sync_user" + JobSyncTraffic = "sync_traffic" +) + +// Result returns the status label value for err. +func Result(err error) string { + if err != nil { + return "failure" + } + return "success" +} + +// MarkJobSuccess records that job completed without errors just now. +func MarkJobSuccess(job string) { + JobLastSuccess.WithLabelValues(job).SetToCurrentTime() +} + +// ObserveAPIRequest records one MU API request. +func ObserveAPIRequest(rpc string, elapsed time.Duration, code string, err error) { + APIRequests.WithLabelValues(rpc, Result(err), code).Inc() + APIRequestDuration.WithLabelValues(rpc).Observe(elapsed.Seconds()) +} + +// SetOutbox publishes the size of the pending traffic queue. +func SetOutbox(batches, logs int) { + OutboxBatches.Set(float64(batches)) + OutboxLogs.Set(float64(logs)) +} + +// ObserveBackendUserOperation records one add/remove call against a proxy backend. +func ObserveBackendUserOperation(syncType, operation string, err error) { + BackendUserOperations.WithLabelValues(syncType, operation, Result(err)).Inc() +} diff --git a/internal/mu/app/observability_test.go b/internal/mu/app/observability_test.go new file mode 100644 index 0000000..f043337 --- /dev/null +++ b/internal/mu/app/observability_test.go @@ -0,0 +1,130 @@ +package app + +import ( + "context" + "testing" + + "github.com/icebase/mu/internal/mu/app/metrics" + pb "github.com/icebase/mu/proto/v1" + "github.com/p4gefau1t/trojan-go/common" + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" + "go.opentelemetry.io/otel/attribute" + codes "go.opentelemetry.io/otel/codes" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" +) + +func metricValue(t *testing.T, collector prometheus.Collector) float64 { + t.Helper() + metric, ok := collector.(prometheus.Metric) + if !ok { + t.Fatalf("%T is not a single metric", collector) + } + out := &dto.Metric{} + if err := metric.Write(out); err != nil { + t.Fatal(err) + } + if out.Counter != nil { + return out.Counter.GetValue() + } + return out.Gauge.GetValue() +} + +func spanAttrs(span sdktrace.ReadOnlySpan) map[attribute.Key]attribute.Value { + attrs := map[attribute.Key]attribute.Value{} + for _, kv := range span.Attributes() { + attrs[kv.Key] = kv.Value + } + return attrs +} + +func TestSyncTrafficEmitsSpansAndOutboxMetrics(t *testing.T) { + syncer, auth := realTrojanForReview(t, "active") + users := []*pb.User{{Id: 1, Enable: 1, V2RayUser: &pb.VUser{Uuid: "active"}}} + if _, err := syncer.GetTraffic(context.Background(), users); err != nil { + t.Fatal(err) + } + _, meter := auth.AuthUser(common.SHA224String("active")) + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + app := reviewApp(t, &reviewMUService{users: users, failUpload: true}, syncer) + app.tracer = provider.Tracer("test") + + meter.AddTraffic(100, 200) + if err := app.syncTraffic(); err == nil { + t.Fatal("expected upload failure") + } + if got := metricValue(t, metrics.OutboxBatches); got != 1 { + t.Errorf("outbox batches after failed upload = %v, want 1", got) + } + if got := metricValue(t, metrics.OutboxLogs); got != 1 { + t.Errorf("outbox logs after failed upload = %v, want 1", got) + } + failed := recorder.Ended() + byName := map[string]sdktrace.ReadOnlySpan{} + for _, span := range failed { + byName[span.Name()] = span + } + if span := byName["App.flushTraffic"]; span == nil || span.Status().Code != codes.Error { + t.Errorf("failed flush span missing or not marked as error: %v", span) + } + if span := byName["App.syncTraffic"]; span == nil || span.Status().Code != codes.Error || + spanAttrs(span)["traffic.outbox_batches"].AsInt64() != 1 { + t.Errorf("syncTraffic span missing error status/outbox attributes: %v", span) + } + + if err := app.syncTraffic(); err != nil { + t.Fatal(err) + } + if got := metricValue(t, metrics.OutboxBatches); got != 0 { + t.Errorf("outbox batches after successful upload = %v, want 0", got) + } + if got := metricValue(t, metrics.JobLastSuccess.WithLabelValues(metrics.JobSyncTraffic)); got <= 0 { + t.Error("job success timestamp was not recorded") + } + var uploaded sdktrace.ReadOnlySpan + for _, span := range recorder.Ended() { + if span.Name() == "App.flushTraffic" && span.Status().Code != codes.Error && spanAttrs(span)["traffic.logs_uploaded"].AsInt64() == 1 { + uploaded = span + } + } + if uploaded == nil { + t.Error("no successful flush span with uploaded log count") + } +} + +func TestSyncUserRecordsBackendOperationsAndSpanAttributes(t *testing.T) { + syncer, _ := realTrojanForReview(t, "removed") + users := []*pb.User{{Id: 1, Enable: 1, V2RayUser: &pb.VUser{Uuid: "active"}}} + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + app := reviewApp(t, &reviewMUService{users: users}, syncer) + app.tracer = provider.Tracer("test") + + adds := metrics.BackendUserOperations.WithLabelValues(protocolTrojan, operationAdd, syncSuccess) + removes := metrics.BackendUserOperations.WithLabelValues(protocolTrojan, operationRemove, syncSuccess) + addsBefore, removesBefore := metricValue(t, adds), metricValue(t, removes) + if err := app.syncUser(); err != nil { + t.Fatal(err) + } + if metricValue(t, adds) != addsBefore+1 || metricValue(t, removes) != removesBefore+1 { + t.Error("backend add/remove operations were not counted") + } + var found bool + for _, span := range recorder.Ended() { + if span.Name() == "App.syncUser.trojan" { + found = true + attrs := spanAttrs(span) + if attrs["sync.users_desired"].AsInt64() != 1 || attrs["sync.users_removed"].AsInt64() != 1 || attrs["sync.users_applied"].AsInt64() != 1 { + t.Errorf("unexpected backend span attributes: %v", attrs) + } + } + } + if !found { + t.Error("backend sync span was not recorded") + } + if got := metricValue(t, metrics.JobLastSuccess.WithLabelValues(metrics.JobSyncUser)); got <= 0 { + t.Error("sync_user success timestamp was not recorded") + } +} diff --git a/internal/mu/app/state.go b/internal/mu/app/state.go index 49493b2..5d76f10 100644 --- a/internal/mu/app/state.go +++ b/internal/mu/app/state.go @@ -190,6 +190,16 @@ func (s *syncState) snapshot() stateData { _ = json.Unmarshal(encoded, &data) return data } + +// pendingStats returns the queued batch and log counts without cloning the whole state. +func (s *syncState) pendingStats() (batches, logs int) { + s.mu.Lock() + defer s.mu.Unlock() + for _, batch := range s.data.Pending { + logs += len(batch.Logs) + } + return len(s.data.Pending), logs +} func (s *syncState) prepare(key string, users map[string]managedUser, reset map[string]bool) error { cursors := make(map[string]trafficCursor, len(reset)) for id, shouldReset := range reset { diff --git a/internal/mu/app/sync.go b/internal/mu/app/sync.go index a5d4a89..306d157 100644 --- a/internal/mu/app/sync.go +++ b/internal/mu/app/sync.go @@ -15,6 +15,12 @@ const protocolTrojan = "trojan" const protocolV2Fly = "v2fly" const protocolVLESS = "vless" +// Backend user operation labels for mu_backend_user_operations_total. +const ( + operationAdd = "add" + operationRemove = "remove" +) + // GetTraffic durably queues deltas in the shared state before returning them for metrics. // Sync also takes a final snapshot before changing authorization. Neither operation resets counters. type UserSync interface { diff --git a/internal/mu/app/sync_trojan.go b/internal/mu/app/sync_trojan.go index b65593e..6844f91 100644 --- a/internal/mu/app/sync_trojan.go +++ b/internal/mu/app/sync_trojan.go @@ -6,9 +6,12 @@ import ( "fmt" "math" + "github.com/icebase/mu/internal/mu/app/metrics" + "github.com/icebase/mu/internal/mu/app/tracing" "github.com/icebase/mu/pkg/trojan" pb "github.com/icebase/mu/proto/v1" "github.com/p4gefau1t/trojan-go/api/service" + "go.opentelemetry.io/otel/attribute" ) type trojanSync struct { @@ -75,7 +78,9 @@ func (t *trojanSync) Sync(ctx context.Context, users []*pb.User) error { if _, keep := enabled[id]; keep { continue } - if err := t.tjManager.RemoveUser(ctx, "", id); err != nil { + err := t.tjManager.RemoveUser(ctx, "", id) + metrics.ObserveBackendUserOperation(t.Name(), operationRemove, err) + if err != nil { errs = append(errs, err) continue } @@ -84,13 +89,20 @@ func (t *trojanSync) Sync(ctx context.Context, users []*pb.User) error { applied := make(map[string]managedUser) for id, user := range enabled { if !present[id] { - if err := t.tjManager.AddUser(ctx, user.UUID); err != nil { + err := t.tjManager.AddUser(ctx, user.UUID) + metrics.ObserveBackendUserOperation(t.Name(), operationAdd, err) + if err != nil { errs = append(errs, fmt.Errorf("add Trojan user ID %d: %w", user.ID, err)) continue } } applied[id] = user } + tracing.SetAttributes(ctx, + attribute.Int("sync.users_desired", len(all)), attribute.Int("sync.users_enabled", len(enabled)), + attribute.Int("sync.users_present", len(present)), attribute.Int("sync.users_removed", len(removed)), + attribute.Int("sync.users_applied", len(applied)), + ) if err := t.state.complete(t.key, applied, removed); err != nil { errs = append(errs, err) } diff --git a/internal/mu/app/tracing/tracing.go b/internal/mu/app/tracing/tracing.go index 958dfd7..2a8d2b6 100644 --- a/internal/mu/app/tracing/tracing.go +++ b/internal/mu/app/tracing/tracing.go @@ -1,8 +1,17 @@ +// Package tracing configures OpenTelemetry tracing for mu. +// +// Tracing is disabled by default. When disabled the global OpenTelemetry tracer provider stays the +// no-op default, so instrumented code costs (almost) nothing. package tracing import ( "context" "fmt" + "io" + "log/slog" + "math" + "os" + "strings" "time" "go.opentelemetry.io/otel" @@ -10,133 +19,192 @@ import ( "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" + "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" "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.24.0" "go.opentelemetry.io/otel/trace" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" ) -// Config 定义 tracing 配置 +const ( + // InstrumentationName is the tracer name used for mu spans. + InstrumentationName = "github.com/icebase/mu" + + // ExporterOTLP exports spans to an OTLP/gRPC collector (default). + ExporterOTLP = "otlp" + // ExporterStdout prints finished spans as JSON to stderr; useful for debugging without a collector. + ExporterStdout = "stdout" + + defaultEndpoint = "localhost:4317" +) + +// stdoutWriter is replaced in tests. +var stdoutWriter io.Writer = os.Stderr + +// Config defines the tracing configuration. type Config struct { Enabled bool `json:"enabled" yaml:"enabled"` ServiceName string `json:"service_name" yaml:"service_name"` - Endpoint string `json:"endpoint" yaml:"endpoint"` // OTLP endpoint, e.g., "localhost:4317" - Insecure bool `json:"insecure" yaml:"insecure"` // 是否使用不安全连接 - SampleRate float64 `json:"sample_rate" yaml:"sample_rate"` // 采样率 0.0-1.0 + Exporter string `json:"exporter" yaml:"exporter"` // "otlp" (default) or "stdout" + Endpoint string `json:"endpoint" yaml:"endpoint"` // host:port or URL; empty defers to OTEL_EXPORTER_OTLP_* variables + Insecure bool `json:"insecure" yaml:"insecure"` // plaintext gRPC for host:port endpoints + SampleRate float64 `json:"sample_rate" yaml:"sample_rate"` // 0.0-1.0, parent-based + + // ServiceVersion and NodeID are exported as resource attributes (service.version, mu.node_id). + ServiceVersion string `json:"service_version" yaml:"service_version"` + NodeID string `json:"node_id" yaml:"node_id"` } -// InitTracer 初始化 OpenTelemetry tracer -func InitTracer(ctx context.Context, config Config) (*sdktrace.TracerProvider, error) { - if !config.Enabled { - // 如果未启用,返回一个 noop tracer provider - tp := sdktrace.NewTracerProvider() - otel.SetTracerProvider(tp) - return tp, nil - } - - // 创建 resource - res, err := resource.Merge( - resource.Default(), - resource.NewWithAttributes( - semconv.SchemaURL, - semconv.ServiceName(config.ServiceName), - semconv.ServiceVersion("v0.0.1"), - attribute.String("environment", "production"), - ), - ) - if err != nil { - return nil, fmt.Errorf("failed to create resource: %w", err) +// Validate reports configuration errors that would otherwise surface as confusing runtime behavior. +func (c Config) Validate() error { + if !c.Enabled { + return nil } - - // 创建 OTLP exporter - var opts []otlptracegrpc.Option - - if config.Endpoint != "" { - opts = append(opts, otlptracegrpc.WithEndpoint(config.Endpoint)) + if math.IsNaN(c.SampleRate) || c.SampleRate < 0 || c.SampleRate > 1 { + return fmt.Errorf("tracing sample rate %v must be between 0 and 1", c.SampleRate) + } + switch c.exporter() { + case ExporterOTLP, ExporterStdout: + default: + return fmt.Errorf("unsupported tracing exporter %q (use %q or %q)", c.Exporter, ExporterOTLP, ExporterStdout) } + return nil +} - if config.Insecure { - opts = append(opts, otlptracegrpc.WithDialOption( - grpc.WithTransportCredentials(insecure.NewCredentials()), - )) - opts = append(opts, otlptracegrpc.WithInsecure()) +func (c Config) exporter() string { + if exporter := strings.ToLower(strings.TrimSpace(c.Exporter)); exporter != "" { + return exporter } + return ExporterOTLP +} - client := otlptracegrpc.NewClient(opts...) - exporter, err := otlptrace.New(ctx, client) +// InitTracer configures the global tracer provider and propagators. +// It returns a nil provider when tracing is disabled. +func InitTracer(ctx context.Context, config Config) (*sdktrace.TracerProvider, error) { + if !config.Enabled { + return nil, nil + } + if err := config.Validate(); err != nil { + return nil, err + } + res, err := newResource(ctx, config) if err != nil { - return nil, fmt.Errorf("failed to create trace exporter: %w", err) + return nil, fmt.Errorf("create resource: %w", err) } - - // 创建 sampler - sampler := sdktrace.TraceIDRatioBased(config.SampleRate) - - // 创建 TracerProvider - tp := sdktrace.NewTracerProvider( - sdktrace.WithBatcher(exporter), + options := []sdktrace.TracerProviderOption{ sdktrace.WithResource(res), - sdktrace.WithSampler(sampler), - ) - - // 设置全局 TracerProvider + sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(config.SampleRate))), + } + switch config.exporter() { + case ExporterStdout: + exporter, err := stdouttrace.New(stdouttrace.WithWriter(stdoutWriter)) + if err != nil { + return nil, fmt.Errorf("create stdout trace exporter: %w", err) + } + // Synchronous export so spans appear immediately while debugging. + options = append(options, sdktrace.WithSyncer(exporter)) + default: + exporter, err := otlptrace.New(ctx, otlptracegrpc.NewClient(otlpOptions(config)...)) + if err != nil { + return nil, fmt.Errorf("create OTLP trace exporter: %w", err) + } + options = append(options, sdktrace.WithBatcher(exporter)) + } + tp := sdktrace.NewTracerProvider(options...) otel.SetTracerProvider(tp) + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})) + otel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) { + slog.Warn("OpenTelemetry error", "error", err) + })) + return tp, nil +} - // 设置全局 Propagator - otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( - propagation.TraceContext{}, - propagation.Baggage{}, - )) +// newResource intentionally avoids resource.Default(): it carries a different semconv schema URL +// than any pinned semconv package and Merge would fail. OTEL_RESOURCE_ATTRIBUTES and +// OTEL_SERVICE_NAME are still honored through WithFromEnv; explicit config wins for service.name. +func newResource(ctx context.Context, config Config) (*resource.Resource, error) { + var attrs []attribute.KeyValue + if config.ServiceName != "" { + attrs = append(attrs, attribute.String("service.name", config.ServiceName)) + } + if config.ServiceVersion != "" { + attrs = append(attrs, attribute.String("service.version", config.ServiceVersion)) + } + if config.NodeID != "" { + attrs = append(attrs, attribute.String("mu.node_id", config.NodeID)) + } + return resource.New(ctx, + resource.WithFromEnv(), + resource.WithTelemetrySDK(), + resource.WithHost(), + resource.WithProcessPID(), + resource.WithAttributes(attrs...), + ) +} - return tp, nil +func otlpOptions(config Config) []otlptracegrpc.Option { + endpoint := strings.TrimSpace(config.Endpoint) + switch { + case strings.Contains(endpoint, "://"): + // The URL scheme (http/https) selects plaintext or TLS. + return []otlptracegrpc.Option{otlptracegrpc.WithEndpointURL(endpoint)} + case endpoint == "" && (os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "" || os.Getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") != ""): + // Let the SDK read the standard OTEL_EXPORTER_OTLP_* variables (endpoint, headers, TLS, ...). + return nil + } + if endpoint == "" { + endpoint = defaultEndpoint + } + opts := []otlptracegrpc.Option{otlptracegrpc.WithEndpoint(endpoint)} + if config.Insecure { + opts = append(opts, otlptracegrpc.WithInsecure()) + } + return opts } -// Shutdown 关闭 tracer provider +// Shutdown flushes and stops the tracer provider. A nil provider is a no-op. func Shutdown(ctx context.Context, tp *sdktrace.TracerProvider) error { - // 给予 10 秒的时间来完成导出 + if tp == nil { + return nil + } + // Bound the final export so a dead collector cannot block process exit. ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() - if err := tp.Shutdown(ctx); err != nil { - return fmt.Errorf("failed to shutdown tracer provider: %w", err) + return fmt.Errorf("shutdown tracer provider: %w", err) } - return nil } -// StartSpan 创建一个新的 span,这是一个便利函数 +// Tracer returns the mu tracer from the global provider. +func Tracer() trace.Tracer { return otel.Tracer(InstrumentationName) } + +// StartSpan starts a span with the mu tracer. func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) { - tracer := otel.Tracer("mu-app") - return tracer.Start(ctx, name, opts...) + return Tracer().Start(ctx, name, opts...) } -// RecordError 记录错误到当前 span +// RecordError records err on the span in ctx and marks the span as failed. func RecordError(ctx context.Context, err error, description string) { - span := trace.SpanFromContext(ctx) - if span != nil && err != nil { - span.RecordError(err, trace.WithAttributes( - attribute.String("error.description", description), - )) - span.SetStatus(codes.Error, description) + if err == nil { + return } + span := trace.SpanFromContext(ctx) + span.RecordError(err, trace.WithAttributes(attribute.String("error.description", description))) + span.SetStatus(codes.Error, description) } -// SetAttributes 设置 span 属性 +// SetAttributes sets attributes on the span in ctx. func SetAttributes(ctx context.Context, attrs ...attribute.KeyValue) { - span := trace.SpanFromContext(ctx) - if span != nil { - span.SetAttributes(attrs...) - } + trace.SpanFromContext(ctx).SetAttributes(attrs...) } -// DefaultConfig 返回默认配置 +// DefaultConfig returns the default (disabled) configuration. func DefaultConfig() Config { return Config{ Enabled: false, ServiceName: "mu-service", - Endpoint: "localhost:4317", + Exporter: ExporterOTLP, Insecure: true, SampleRate: 1.0, } diff --git a/internal/mu/app/tracing/tracing_test.go b/internal/mu/app/tracing/tracing_test.go new file mode 100644 index 0000000..8da18d9 --- /dev/null +++ b/internal/mu/app/tracing/tracing_test.go @@ -0,0 +1,119 @@ +package tracing + +import ( + "bytes" + "context" + "os" + "strings" + "testing" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" + "go.opentelemetry.io/otel/trace/noop" +) + +func restoreGlobals(t *testing.T) { + t.Helper() + t.Cleanup(func() { + otel.SetTracerProvider(noop.NewTracerProvider()) + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator()) + }) +} + +func TestDisabledTracingKeepsNoopProvider(t *testing.T) { + restoreGlobals(t) + otel.SetTracerProvider(noop.NewTracerProvider()) + before := otel.GetTracerProvider() + tp, err := InitTracer(context.Background(), DefaultConfig()) + if err != nil || tp != nil { + t.Fatalf("disabled tracing must be a no-op, got provider=%v err=%v", tp, err) + } + if otel.GetTracerProvider() != before { + t.Fatal("disabled tracing replaced the global provider") + } + if err := Shutdown(context.Background(), nil); err != nil { + t.Fatal(err) + } +} + +func TestValidate(t *testing.T) { + for name, tc := range map[string]struct { + config Config + wantErr bool + }{ + "disabled ignores bad values": {Config{SampleRate: 7, Exporter: "bogus"}, false}, + "valid": {Config{Enabled: true, SampleRate: 0.5}, false}, + "stdout": {Config{Enabled: true, SampleRate: 1, Exporter: "STDOUT"}, false}, + "rate above one": {Config{Enabled: true, SampleRate: 1.5}, true}, + "negative rate": {Config{Enabled: true, SampleRate: -0.1}, true}, + "unknown exporter": {Config{Enabled: true, SampleRate: 1, Exporter: "jaeger"}, true}, + } { + t.Run(name, func(t *testing.T) { + if err := tc.config.Validate(); (err != nil) != tc.wantErr { + t.Fatalf("Validate() = %v, wantErr=%v", err, tc.wantErr) + } + }) + } +} + +// Regression: enabling tracing used to fail at startup with "conflicting Schema URL". +func TestStdoutExporterEmitsSpansWithResource(t *testing.T) { + restoreGlobals(t) + var out bytes.Buffer + stdoutWriter = &out + t.Cleanup(func() { stdoutWriter = os.Stderr }) + config := DefaultConfig() + config.Enabled, config.Exporter = true, ExporterStdout + config.ServiceVersion, config.NodeID = "v1.2.3", "node-7" + tp, err := InitTracer(context.Background(), config) + if err != nil { + t.Fatal(err) + } + ctx, span := StartSpan(context.Background(), "unit.test", trace.WithAttributes(attribute.Int("n", 1))) + RecordError(ctx, context.DeadlineExceeded, "boom") + span.End() + if err := Shutdown(context.Background(), tp); err != nil { + t.Fatal(err) + } + text := out.String() + for _, want := range []string{`"Name":"unit.test"`, "mu-service", "v1.2.3", "node-7", "boom"} { + if !strings.Contains(text, want) { + t.Errorf("exported span is missing %q:\n%s", want, text) + } + } +} + +func TestOTLPInitDoesNotBlockWithoutCollector(t *testing.T) { + restoreGlobals(t) + config := DefaultConfig() + config.Enabled = true + tp, err := InitTracer(context.Background(), config) + if err != nil { + t.Fatal(err) + } + if err := Shutdown(context.Background(), tp); err != nil { + t.Fatal(err) + } +} + +func TestPropagatorIsConfigured(t *testing.T) { + restoreGlobals(t) + config := DefaultConfig() + config.Enabled, config.Exporter = true, ExporterStdout + stdoutWriter = &bytes.Buffer{} + t.Cleanup(func() { stdoutWriter = os.Stderr }) + tp, err := InitTracer(context.Background(), config) + if err != nil { + t.Fatal(err) + } + defer func() { _ = Shutdown(context.Background(), tp) }() + ctx, span := StartSpan(context.Background(), "parent") + defer span.End() + carrier := propagation.MapCarrier{} + otel.GetTextMapPropagator().Inject(ctx, carrier) + if carrier.Get("traceparent") == "" { + t.Fatal("traceparent header was not injected") + } +} diff --git a/internal/mu/app/v2fly_sync.go b/internal/mu/app/v2fly_sync.go index 557f3bc..c1abd83 100644 --- a/internal/mu/app/v2fly_sync.go +++ b/internal/mu/app/v2fly_sync.go @@ -8,8 +8,11 @@ import ( "maps" "strings" + "github.com/icebase/mu/internal/mu/app/metrics" + "github.com/icebase/mu/internal/mu/app/tracing" "github.com/icebase/mu/pkg/v2fly" pb "github.com/icebase/mu/proto/v1" + "go.opentelemetry.io/otel/attribute" ) const tag = "proxy" @@ -148,7 +151,9 @@ func (v *v2flySync) Sync(ctx context.Context, users []*pb.User) error { if _, keep := enabled[id]; keep { continue } - if err := v.manager.RemoveUser(ctx, user.v2User()); err != nil { + err := v.manager.RemoveUser(ctx, user.v2User()) + metrics.ObserveBackendUserOperation(v.Name(), operationRemove, err) + if err != nil { errs = append(errs, err) continue } @@ -159,19 +164,28 @@ func (v *v2flySync) Sync(ctx context.Context, users []*pb.User) error { old, exists := previous.Applied[id] // Add is not an update. Replace unknown/changed configurations once; persist the applied identity. if !exists || !sameV2Account(old, user) { - if err := v.manager.RemoveUser(ctx, user.v2User()); err != nil { + err := v.manager.RemoveUser(ctx, user.v2User()) + metrics.ObserveBackendUserOperation(v.Name(), operationRemove, err) + if err != nil { errs = append(errs, err) continue } removed = append(removed, id) } // Idempotent Add also restores users after a backend restart, regardless of traffic-counter existence. - if _, err := v.manager.AddUser(ctx, user.v2User()); err != nil { + _, err := v.manager.AddUser(ctx, user.v2User()) + metrics.ObserveBackendUserOperation(v.Name(), operationAdd, err) + if err != nil { errs = append(errs, fmt.Errorf("add V2Ray user ID %d: %w", user.ID, err)) continue } applied[id] = user } + tracing.SetAttributes(ctx, + attribute.Int("sync.users_desired", len(all)), attribute.Int("sync.users_enabled", len(enabled)), + attribute.Int("sync.users_observed", len(snapshot)), attribute.Int("sync.users_removed", len(removed)), + attribute.Int("sync.users_applied", len(applied)), attribute.Bool("sync.stats_available", statsErr == nil), + ) if err := v.state.complete(v.key, applied, removed); err != nil { errs = append(errs, err) }