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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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://<host>: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.<type>` 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.<type>` 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:
Expand Down
86 changes: 74 additions & 12 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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.
Expand Down Expand Up @@ -60,31 +76,77 @@ 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) {
req.NodeId = c.nodeID
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.
Expand Down
8 changes: 8 additions & 0 deletions client_diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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())
}
Expand Down
107 changes: 107 additions & 0 deletions client_observability_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
Loading
Loading