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
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,40 @@ Scrape `http://<host>:9090/metrics`. With an OpenTelemetry Collector, use the `p
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.

### V2Fly metrics

Set `MU_V2FLY_METRICS_ENABLED=true` to collect V2Fly v5 statistics on the existing
`/metrics` endpoint (default port 9090, requires `MU_METRICS_ENABLED=true`, the default).
Each scrape reads each unique address in `MU_V2FLY_ADDRS` and `MU_VLESS_ADDRS` over its
existing gRPC connection with a five-second deadline. Enable StatsService, statistics and the inbound/outbound traffic
policy flags for the directions you want to monitor.

`v2ray_up{backend}` reports success of the backend scrape. On failure, only health and
scrape duration are emitted for that backend. Runtime metrics include uptime, goroutines,
heap and GC statistics. The counters `v2ray_traffic_uplink_bytes_total` and
`v2ray_traffic_downlink_bytes_total` use `backend` (configured address), `dimension`
(inbound or outbound) and `target` (proxy tag). Select one dimension when totaling
traffic. User-level series are excluded. These counters reflect the backend process
and can reset on restart. The existing `mu_total_*_bytes` metrics track acknowledged
traffic reports.

### Report V2Fly metrics to MU Server

Set `MU_NODE_METRICS_REPORTING_ENABLED=true` to send V2Fly backend metrics to
`MU_API_BASE_URL` starting at launch and then every minute. This option is disabled by default.
Use `MU_METRICS_ENABLED=false` to run without a Prometheus endpoint. Reporting uses the
same V2Fly stats and policy settings as the scrape endpoint, plus the existing MU API token.

The MU Server must mount the generated Twirp handler for `NodeMetricsService` at
`/v1.NodeMetricsService/` (empty Twirp path prefix). It should authorize the token for the
submitted `node_id`, validate the batch and enforce uniqueness of `(node_id, batch_id)`.
A duplicate of an already accepted batch should return success. Acknowledge after persisting the
batch. Each backend sample contains a timestamp and collection status. Successful samples
also carry runtime statistics and cumulative byte counters by proxy tag.

The agent retries transient upload failures once using the same batch ID. Batches are kept
in memory for the attempt and retry, so an outage can leave gaps in the metric history.

### Traces

Every 60-second cycle produces three traces (`App.ping`, `App.syncTraffic`, `App.syncUser`):
Expand Down
7 changes: 5 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type Client struct {
addr, token string
nodeID string
client pb.MUService
nodeMetrics pb.NodeMetricsService
apiDebug bool
observer RequestObserver
}
Expand Down Expand Up @@ -55,12 +56,14 @@ func NewClient(addr string, token string, nodeID string, options ...ClientOption
for _, option := range options {
option(c)
}
c.client = pb.NewMUServiceJSONClient(addr, &diagnosticHTTPClient{
httpClient := &diagnosticHTTPClient{
client: &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse },
},
}, twirp.WithClientPathPrefix(""))
}
c.client = pb.NewMUServiceJSONClient(addr, httpClient, twirp.WithClientPathPrefix(""))
c.nodeMetrics = pb.NewNodeMetricsServiceJSONClient(addr, httpClient, twirp.WithClientPathPrefix(""))
return c
}

Expand Down
51 changes: 51 additions & 0 deletions client_node_metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package mu

import (
"context"
"errors"
"time"

pb "github.com/icebase/mu/proto/v1"
"github.com/twitchtv/twirp"
)

var _ pb.NodeMetricsService = (*Client)(nil)

// ReportNodeMetrics retries a transient failure once with the same batch ID.
func (c *Client) ReportNodeMetrics(ctx context.Context, req *pb.ReportNodeMetricsRequest) (*pb.ReportNodeMetricsResponse, error) {
req.NodeId = c.nodeID
var response *pb.ReportNodeMetricsResponse
var rawErr error
send := func() error {
return c.call(ctx, "ReportNodeMetrics", "report MU node metrics", func(ctx context.Context) error {
response, rawErr = c.nodeMetrics.ReportNodeMetrics(ctx, req)
return rawErr
})
}
err := send()
if err == nil || req.BatchId == "" || !retryableNodeMetricsError(rawErr) {
return response, err
}
timer := time.NewTimer(time.Second)
defer timer.Stop()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-timer.C:
err = send()
return response, err
}
}

func retryableNodeMetricsError(err error) bool {
var remote twirp.Error
if !errors.As(err, &remote) {
return true
}
switch remote.Code() {
case twirp.Unavailable, twirp.DeadlineExceeded, twirp.Internal, twirp.ResourceExhausted:
return true
default:
return false
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ toolchain go1.27.2

require (
connectrpc.com/connect v1.21.1
github.com/google/uuid v1.6.0
github.com/google/wire v0.7.0
github.com/p4gefau1t/trojan-go v0.10.6
github.com/prometheus/client_golang v1.25.0
Expand Down Expand Up @@ -37,7 +38,6 @@ require (
github.com/go-sql-driver/mysql v1.10.1 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.32.0 // indirect
github.com/miekg/dns v1.1.73 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
Expand Down
36 changes: 30 additions & 6 deletions internal/mu/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/icebase/mu"
"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"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
Expand All @@ -39,6 +40,7 @@ type App struct {
tracer trace.Tracer
tracerProvider *sdktrace.TracerProvider
metricsServer *http.Server
v2flyBackends map[string]*v2fly.Manager
}

func New(config *Config) *App { return &App{config: config} }
Expand All @@ -64,9 +66,6 @@ func (a *App) Init() (err error) {
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), mu.WithRequestObserver(metrics.ObserveAPIRequest))
for _, addr := range a.config.TrojanAddrs {
Expand All @@ -76,21 +75,25 @@ func (a *App) Init() (err error) {
}
a.userSync = append(a.userSync, syncer)
}
v2flyBackends := make(map[string]*v2fly.Manager)
for _, addr := range a.config.V2flyAddrs {
syncer, err := newV2flySync(addr, a.state)
if err != nil {
return err
}
a.userSync = append(a.userSync, syncer)
v2flyBackends[addr] = syncer.manager
}
for _, addr := range a.config.VlessAddrs {
syncer, err := newVlessSync(addr, a.config.VlessInboundTag, a.state)
if err != nil {
return err
}
a.userSync = append(a.userSync, syncer)
v2flyBackends[addr] = syncer.manager
}
return nil
a.v2flyBackends = v2flyBackends
return a.initMetrics(v2flyBackends)
}
func (a *App) initTracing() error {
cfg := a.config.Tracing
Expand All @@ -107,13 +110,23 @@ func (a *App) initTracing() error {
}
return nil
}
func (a *App) initMetrics() error {
func (a *App) initMetrics(backends map[string]*v2fly.Manager) error {
metrics.BuildInfo.WithLabelValues(version, runtime.Version()).Set(1)
if !a.config.MetricsEnabled {
return nil
}
registry := prometheus.NewRegistry()
if a.config.V2FlyMetricsEnabled {
for addr, manager := range backends {
registerer := prometheus.WrapRegistererWith(prometheus.Labels{"backend": addr}, registry)
if err := registerer.Register(metrics.NewV2FlyCollector(a.ctx, manager.ReadNodeStats)); err != nil {
return fmt.Errorf("register V2Fly metrics: %w", err)
}
}
}
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
handler := promhttp.HandlerFor(prometheus.Gatherers{prometheus.DefaultGatherer, registry}, promhttp.HandlerOpts{})
mux.Handle("/metrics", promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, handler))
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) {
Expand All @@ -126,7 +139,18 @@ func (a *App) Run() {
ctx, stop := signal.NotifyContext(a.ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
a.ctx = ctx
var reportingDone chan struct{}
if a.config.NodeMetricsReportingEnabled && len(a.v2flyBackends) > 0 {
reportingDone = make(chan struct{})
go func() {
defer close(reportingDone)
a.reportNodeMetrics(ctx)
}()
}
a.jobs()
if reportingDone != nil {
<-reportingDone
}
if err := a.Close(); err != nil {
slog.Error("shutdown failed", "error", err)
}
Expand Down
28 changes: 18 additions & 10 deletions internal/mu/app/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ type Config struct {
VlessInboundTag string

// Metrics 配置
MetricsEnabled bool
MetricsPort string
NodeMetricsReportingEnabled bool
V2FlyMetricsEnabled bool
MetricsEnabled bool
MetricsPort string

// Tracing 配置
Tracing tracing.Config
Expand All @@ -37,6 +39,8 @@ type Config struct {
// - 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_NODE_METRICS_REPORTING_ENABLED: Push node metrics to MU Server (disabled by default)
// - MU_V2FLY_METRICS_ENABLED: Enable V2Fly backend statistics (disabled by default)
// - 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)
Expand All @@ -55,6 +59,8 @@ func ConfigFromEnv() *Config {
v.SetDefault("STATE_FILE", "data/mu-state.json")

// Metrics defaults
v.SetDefault("NODE_METRICS_REPORTING_ENABLED", false)
v.SetDefault("V2FLY_METRICS_ENABLED", false)
v.SetDefault("METRICS_ENABLED", true)
v.SetDefault("METRICS_PORT", "9090")

Expand All @@ -77,14 +83,16 @@ func ConfigFromEnv() *Config {

// Create a config struct with values from environment variables
config := &Config{
MuAPIBaseURL: v.GetString("API_BASE_URL"),
MuAPIToken: v.GetString("API_TOKEN"),
MuAPIDebug: v.GetBool("API_DEBUG"),
MuNodeID: v.GetString("NODE_ID"),
StateFile: v.GetString("STATE_FILE"),
VlessInboundTag: v.GetString("VLESS_INBOUND_TAG"),
MetricsEnabled: v.GetBool("METRICS_ENABLED"),
MetricsPort: v.GetString("METRICS_PORT"),
MuAPIBaseURL: v.GetString("API_BASE_URL"),
MuAPIToken: v.GetString("API_TOKEN"),
MuAPIDebug: v.GetBool("API_DEBUG"),
MuNodeID: v.GetString("NODE_ID"),
StateFile: v.GetString("STATE_FILE"),
VlessInboundTag: v.GetString("VLESS_INBOUND_TAG"),
MetricsEnabled: v.GetBool("METRICS_ENABLED"),
MetricsPort: v.GetString("METRICS_PORT"),
NodeMetricsReportingEnabled: v.GetBool("NODE_METRICS_REPORTING_ENABLED"),
V2FlyMetricsEnabled: v.GetBool("V2FLY_METRICS_ENABLED"),
Tracing: tracing.Config{
Enabled: v.GetBool("TRACING_ENABLED"),
ServiceName: v.GetString("TRACING_SERVICE_NAME"),
Expand Down
68 changes: 68 additions & 0 deletions internal/mu/app/metrics/v2fly.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package metrics

import (
"context"
"time"

"github.com/icebase/mu/pkg/v2fly"
"github.com/prometheus/client_golang/prometheus"
)

type nodeCollector struct {
ctx context.Context
read func(context.Context) (v2fly.NodeStats, error)
}

func NewV2FlyCollector(ctx context.Context, read func(context.Context) (v2fly.NodeStats, error)) prometheus.Collector {
return &nodeCollector{ctx: ctx, read: read}
}

var nodeMetrics = map[string]*prometheus.Desc{
"up": prometheus.NewDesc("v2ray_up", "Whether the backend statistics request succeeded.", nil, nil),
"scrape_duration_seconds": prometheus.NewDesc("v2ray_scrape_duration_seconds", "Time spent reading this backend.", nil, nil),
"uptime_seconds": prometheus.NewDesc("v2ray_uptime_seconds", "Backend uptime in seconds.", nil, nil),
"goroutines": prometheus.NewDesc("v2ray_goroutines", "Current backend goroutine count.", nil, nil),
"memstats_alloc_bytes": prometheus.NewDesc("v2ray_memstats_alloc_bytes", "Bytes currently allocated on the backend heap.", nil, nil),
"memstats_alloc_bytes_total": prometheus.NewDesc("v2ray_memstats_alloc_bytes_total", "Total bytes allocated on the backend heap.", nil, nil),
"memstats_sys_bytes": prometheus.NewDesc("v2ray_memstats_sys_bytes", "Bytes obtained by the backend runtime from the OS.", nil, nil),
"memstats_mallocs_total": prometheus.NewDesc("v2ray_memstats_mallocs_total", "Total heap allocations.", nil, nil),
"memstats_frees_total": prometheus.NewDesc("v2ray_memstats_frees_total", "Total freed heap objects.", nil, nil),
"memstats_num_gc": prometheus.NewDesc("v2ray_memstats_num_gc", "Completed garbage collections.", nil, nil),
"memstats_pause_total_ns": prometheus.NewDesc("v2ray_memstats_pause_total_ns", "Cumulative garbage collection pause time in nanoseconds.", nil, nil),
"uplink": prometheus.NewDesc("v2ray_traffic_uplink_bytes_total",
"Cumulative uplink bytes by proxy tag.", []string{"dimension", "target"}, nil),
"downlink": prometheus.NewDesc("v2ray_traffic_downlink_bytes_total",
"Cumulative downlink bytes by proxy tag.", []string{"dimension", "target"}, nil),
}

func (c *nodeCollector) Describe(ch chan<- *prometheus.Desc) {
for _, desc := range nodeMetrics {
ch <- desc
}
}

func (c *nodeCollector) Collect(ch chan<- prometheus.Metric) {
start := time.Now()
snapshot, err := c.read(c.ctx)
emit := func(name string, kind prometheus.ValueType, value float64, labels ...string) {
ch <- prometheus.MustNewConstMetric(nodeMetrics[name], kind, value, labels...)
}
emit("scrape_duration_seconds", prometheus.GaugeValue, time.Since(start).Seconds())
if err != nil {
emit("up", prometheus.GaugeValue, 0)
return
}
emit("up", prometheus.GaugeValue, 1)
emit("uptime_seconds", prometheus.GaugeValue, float64(snapshot.Runtime.GetUptime()))
emit("goroutines", prometheus.GaugeValue, float64(snapshot.Runtime.GetNumGoroutine()))
emit("memstats_alloc_bytes", prometheus.GaugeValue, float64(snapshot.Runtime.GetAlloc()))
emit("memstats_alloc_bytes_total", prometheus.CounterValue, float64(snapshot.Runtime.GetTotalAlloc()))
emit("memstats_sys_bytes", prometheus.GaugeValue, float64(snapshot.Runtime.GetSys()))
emit("memstats_mallocs_total", prometheus.CounterValue, float64(snapshot.Runtime.GetMallocs()))
emit("memstats_frees_total", prometheus.CounterValue, float64(snapshot.Runtime.GetFrees()))
emit("memstats_num_gc", prometheus.CounterValue, float64(snapshot.Runtime.GetNumGC()))
emit("memstats_pause_total_ns", prometheus.CounterValue, float64(snapshot.Runtime.GetPauseTotalNs()))
for _, traffic := range snapshot.Traffic {
emit(traffic.Direction, prometheus.CounterValue, float64(traffic.Bytes), traffic.Dimension, traffic.Tag)
}
}
Loading
Loading