From 2c9df21f7031dcab11b740fbeca37c85cb5cdac4 Mon Sep 17 00:00:00 2001 From: orvice Date: Sat, 21 Nov 2026 22:40:44 +0800 Subject: [PATCH 1/2] feat: expose V2Fly v5 backend metrics --- README.md | 17 +++++++ internal/mu/app/app.go | 23 ++++++--- internal/mu/app/config.go | 24 ++++++---- internal/mu/app/metrics/v2fly.go | 68 +++++++++++++++++++++++++++ internal/mu/app/v2fly_metrics_test.go | 54 +++++++++++++++++++++ pkg/v2fly/node_stats.go | 51 ++++++++++++++++++++ 6 files changed, 221 insertions(+), 16 deletions(-) create mode 100644 internal/mu/app/metrics/v2fly.go create mode 100644 internal/mu/app/v2fly_metrics_test.go create mode 100644 pkg/v2fly/node_stats.go diff --git a/README.md b/README.md index 130a26e..c814522 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,23 @@ Scrape `http://: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. + ### Traces Every 60-second cycle produces three traces (`App.ping`, `App.syncTraffic`, `App.syncUser`): diff --git a/internal/mu/app/app.go b/internal/mu/app/app.go index f06c2cc..1d45dd2 100644 --- a/internal/mu/app/app.go +++ b/internal/mu/app/app.go @@ -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" @@ -64,9 +65,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 { @@ -76,12 +74,14 @@ 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) @@ -89,8 +89,9 @@ func (a *App) Init() (err error) { return err } a.userSync = append(a.userSync, syncer) + v2flyBackends[addr] = syncer.manager } - return nil + return a.initMetrics(v2flyBackends) } func (a *App) initTracing() error { cfg := a.config.Tracing @@ -107,13 +108,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) { diff --git a/internal/mu/app/config.go b/internal/mu/app/config.go index 3e77ca8..a045ff9 100644 --- a/internal/mu/app/config.go +++ b/internal/mu/app/config.go @@ -21,8 +21,9 @@ type Config struct { VlessInboundTag string // Metrics 配置 - MetricsEnabled bool - MetricsPort string + V2FlyMetricsEnabled bool + MetricsEnabled bool + MetricsPort string // Tracing 配置 Tracing tracing.Config @@ -37,6 +38,7 @@ 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_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) @@ -55,6 +57,7 @@ func ConfigFromEnv() *Config { v.SetDefault("STATE_FILE", "data/mu-state.json") // Metrics defaults + v.SetDefault("V2FLY_METRICS_ENABLED", false) v.SetDefault("METRICS_ENABLED", true) v.SetDefault("METRICS_PORT", "9090") @@ -77,14 +80,15 @@ 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"), + V2FlyMetricsEnabled: v.GetBool("V2FLY_METRICS_ENABLED"), Tracing: tracing.Config{ Enabled: v.GetBool("TRACING_ENABLED"), ServiceName: v.GetString("TRACING_SERVICE_NAME"), diff --git a/internal/mu/app/metrics/v2fly.go b/internal/mu/app/metrics/v2fly.go new file mode 100644 index 0000000..45a6b6b --- /dev/null +++ b/internal/mu/app/metrics/v2fly.go @@ -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) + } +} diff --git a/internal/mu/app/v2fly_metrics_test.go b/internal/mu/app/v2fly_metrics_test.go new file mode 100644 index 0000000..cca993c --- /dev/null +++ b/internal/mu/app/v2fly_metrics_test.go @@ -0,0 +1,54 @@ +package app + +import ( + "net/http/httptest" + "path/filepath" + "strings" + "testing" +) + +func TestV2FlyMetricsEndpoint(t *testing.T) { + healthy, _, stats := reviewRealVMess(t) + failing, _, _ := reviewRealVMess(t, true) + for _, name := range []string{"inbound>>>proxy>>>traffic>>>uplink", "user>>>private@example.test>>>traffic>>>downlink", "outbound>>>invalid"} { + counter, err := stats.RegisterCounter(name) + if err != nil { + t.Fatal(err) + } + counter.Set(123) + } + address := func(s *v2flySync) string { return strings.TrimSuffix(strings.TrimPrefix(s.key, "v2fly:"), ":"+tag) } + t.Setenv("MU_V2FLY_METRICS_ENABLED", "true") + cfg := ConfigFromEnv() + cfg.MetricsPort = "0" + cfg.MuNodeID = "metrics-test" + cfg.StateFile = filepath.Join(t.TempDir(), "state.json") + cfg.MetricsEnabled = true + cfg.V2flyAddrs = []string{address(healthy)} + cfg.VlessAddrs = []string{address(healthy), address(failing)} + cfg.VlessInboundTag = "vless" + a := New(cfg) + if err := a.Init(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = a.Close() }) + for range 2 { + rec := httptest.NewRecorder() + a.metricsServer.Handler.ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil)) + body := rec.Body.String() + for _, expected := range []string{ + "mu_build_info", + "mu_traffic_sync_duration_seconds", + "v2ray_up{backend=\"" + address(healthy) + "\"} 1", + "v2ray_up{backend=\"" + address(failing) + "\"} 0", + "v2ray_traffic_uplink_bytes_total{backend=\"" + address(healthy) + "\",dimension=\"inbound\",target=\"proxy\"} 123", + } { + if rec.Code != 200 || !strings.Contains(body, expected) { + t.Fatalf("HTTP %d, missing %s", rec.Code, expected) + } + } + if strings.Contains(body, "private@example.test") { + t.Fatal("exported user identity") + } + } +} diff --git a/pkg/v2fly/node_stats.go b/pkg/v2fly/node_stats.go new file mode 100644 index 0000000..cf4d3db --- /dev/null +++ b/pkg/v2fly/node_stats.go @@ -0,0 +1,51 @@ +package v2fly + +import ( + "context" + "errors" + "strings" + + stats "github.com/v2fly/v2ray-core/v5/app/stats/command" +) + +type NodeStats struct { + Runtime *stats.SysStatsResponse + Traffic []TagTraffic +} + +type TagTraffic struct { + Dimension, Tag, Direction string + Bytes int64 +} + +// ReadNodeStats samples a backend without modifying its accounting state. +func (m *Manager) ReadNodeStats(ctx context.Context) (NodeStats, error) { + ctx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() + runtime, err := m.statsClient.GetSysStats(ctx, &stats.SysStatsRequest{}) + if err != nil { + return NodeStats{}, rpcError("read backend runtime", err) + } + resp, err := m.statsClient.QueryStats(ctx, &stats.QueryStatsRequest{Patterns: []string{"inbound>>>", "outbound>>>"}}) + if err != nil { + return NodeStats{}, rpcError("read backend traffic", err) + } + if runtime == nil || resp == nil { + return NodeStats{}, errors.New("missing backend statistics") + } + result := NodeStats{Runtime: runtime} + for _, stat := range resp.Stat { + parts := strings.Split(stat.GetName(), ">>>") + if len(parts) != 4 || parts[1] == "" || parts[2] != "traffic" { + continue + } + if (parts[0] != "inbound" && parts[0] != "outbound") || (parts[3] != uplinkDirection && parts[3] != downlinkDirection) { + continue + } + if stat.Value < 0 { + return NodeStats{}, errors.New("negative backend traffic counter") + } + result.Traffic = append(result.Traffic, TagTraffic{Dimension: parts[0], Tag: parts[1], Direction: parts[3], Bytes: stat.Value}) + } + return result, nil +} From 46a669a9c8e33ddf15c316b42a9adc8432b983bd Mon Sep 17 00:00:00 2001 From: orvice Date: Sun, 22 Nov 2026 00:10:09 +0800 Subject: [PATCH 2/2] feat: report V2Fly metrics directly to MU Server --- README.md | 17 + client.go | 7 +- client_node_metrics.go | 51 ++ go.mod | 2 +- internal/mu/app/app.go | 13 + internal/mu/app/config.go | 28 +- internal/mu/app/node_metrics.go | 70 +++ internal/mu/app/node_metrics_test.go | 99 ++++ proto/v1/mu.pb.go | 201 ++++---- proto/v1/mu.twirp.go | 577 +++++++++++++++++++++-- proto/v1/mu_grpc.pb.go | 116 ++++- proto/v1/node_metrics.pb.go | 570 ++++++++++++++++++++++ proto/v1/node_metrics.pb.validate.go | 679 +++++++++++++++++++++++++++ proto/v1/v1connect/mu.connect.go | 79 ++++ v1/mu.proto | 7 + v1/node_metrics.proto | 44 ++ 16 files changed, 2407 insertions(+), 153 deletions(-) create mode 100644 client_node_metrics.go create mode 100644 internal/mu/app/node_metrics.go create mode 100644 internal/mu/app/node_metrics_test.go create mode 100644 proto/v1/node_metrics.pb.go create mode 100644 proto/v1/node_metrics.pb.validate.go create mode 100644 v1/node_metrics.proto diff --git a/README.md b/README.md index c814522..1cbaa5e 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,23 @@ traffic. User-level series are excluded. These counters reflect the backend proc 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`): diff --git a/client.go b/client.go index d42e7a4..9c15dad 100644 --- a/client.go +++ b/client.go @@ -27,6 +27,7 @@ type Client struct { addr, token string nodeID string client pb.MUService + nodeMetrics pb.NodeMetricsService apiDebug bool observer RequestObserver } @@ -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 } diff --git a/client_node_metrics.go b/client_node_metrics.go new file mode 100644 index 0000000..9f2b126 --- /dev/null +++ b/client_node_metrics.go @@ -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 + } +} diff --git a/go.mod b/go.mod index decc1a7..fbdda9a 100644 --- a/go.mod +++ b/go.mod @@ -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 @@ -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 diff --git a/internal/mu/app/app.go b/internal/mu/app/app.go index 1d45dd2..93a10fa 100644 --- a/internal/mu/app/app.go +++ b/internal/mu/app/app.go @@ -40,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} } @@ -91,6 +92,7 @@ func (a *App) Init() (err error) { a.userSync = append(a.userSync, syncer) v2flyBackends[addr] = syncer.manager } + a.v2flyBackends = v2flyBackends return a.initMetrics(v2flyBackends) } func (a *App) initTracing() error { @@ -137,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) } diff --git a/internal/mu/app/config.go b/internal/mu/app/config.go index a045ff9..310842f 100644 --- a/internal/mu/app/config.go +++ b/internal/mu/app/config.go @@ -21,9 +21,10 @@ type Config struct { VlessInboundTag string // Metrics 配置 - V2FlyMetricsEnabled bool - MetricsEnabled bool - MetricsPort string + NodeMetricsReportingEnabled bool + V2FlyMetricsEnabled bool + MetricsEnabled bool + MetricsPort string // Tracing 配置 Tracing tracing.Config @@ -38,6 +39,7 @@ 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, @@ -57,6 +59,7 @@ 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") @@ -80,15 +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"), - V2FlyMetricsEnabled: v.GetBool("V2FLY_METRICS_ENABLED"), + 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"), diff --git a/internal/mu/app/node_metrics.go b/internal/mu/app/node_metrics.go new file mode 100644 index 0000000..fc5ca1f --- /dev/null +++ b/internal/mu/app/node_metrics.go @@ -0,0 +1,70 @@ +package app + +import ( + "context" + "log/slog" + "time" + + "github.com/google/uuid" + pb "github.com/icebase/mu/proto/v1" +) + +const nodeMetricsInterval = time.Minute + +func (a *App) reportNodeMetrics(ctx context.Context) { + ticker := time.NewTicker(nodeMetricsInterval) + defer ticker.Stop() + for ctx.Err() == nil { + if err := a.reportNodeMetricsOnce(ctx); err != nil && ctx.Err() == nil { + slog.Warn("node metrics report failed", "error", err) + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +func (a *App) reportNodeMetricsOnce(ctx context.Context) error { + batch := &pb.ReportNodeMetricsRequest{ + BatchId: uuid.NewString(), + Backends: make([]*pb.V2FlyBackendSnapshot, 0, len(a.v2flyBackends)), + } + for address, backend := range a.v2flyBackends { + if err := ctx.Err(); err != nil { + return err + } + sample := &pb.V2FlyBackendSnapshot{Backend: address, SampledAtUnixMillis: time.Now().UnixMilli()} + stats, err := backend.ReadNodeStats(ctx) + if err == nil { + sample.Up = true + sample.Runtime = &pb.V2FlyRuntimeStats{ + UptimeSeconds: stats.Runtime.GetUptime(), + Goroutines: stats.Runtime.GetNumGoroutine(), + HeapAllocBytes: stats.Runtime.GetAlloc(), + TotalAllocBytes: stats.Runtime.GetTotalAlloc(), + RuntimeSysBytes: stats.Runtime.GetSys(), + Mallocs: stats.Runtime.GetMallocs(), + Frees: stats.Runtime.GetFrees(), + GcCycles: stats.Runtime.GetNumGC(), + GcPauseTotalNanoseconds: stats.Runtime.GetPauseTotalNs(), + } + sample.Traffic = make([]*pb.V2FlyTrafficCounter, 0, len(stats.Traffic)) + for _, counter := range stats.Traffic { + sample.Traffic = append(sample.Traffic, &pb.V2FlyTrafficCounter{ + Dimension: counter.Dimension, + Tag: counter.Tag, + Direction: counter.Direction, + Bytes: uint64(counter.Bytes), + }) + } + } + batch.Backends = append(batch.Backends, sample) + } + if err := ctx.Err(); err != nil { + return err + } + _, err := a.muClient.ReportNodeMetrics(ctx, batch) + return err +} diff --git a/internal/mu/app/node_metrics_test.go b/internal/mu/app/node_metrics_test.go new file mode 100644 index 0000000..7d3bb39 --- /dev/null +++ b/internal/mu/app/node_metrics_test.go @@ -0,0 +1,99 @@ +package app + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/icebase/mu" + pb "github.com/icebase/mu/proto/v1" + "github.com/twitchtv/twirp" + "google.golang.org/protobuf/proto" +) + +type nodeMetricsReceiver struct { + attempts atomic.Int32 + reports chan *pb.ReportNodeMetricsRequest +} + +func (r *nodeMetricsReceiver) ReportNodeMetrics(_ context.Context, req *pb.ReportNodeMetricsRequest) (*pb.ReportNodeMetricsResponse, error) { + r.reports <- req + if r.attempts.Add(1) == 1 { + return nil, twirp.NewError(twirp.Unavailable, "test retry") + } + return &pb.ReportNodeMetricsResponse{}, nil +} + +func TestReportNodeMetricsWithoutPrometheus(t *testing.T) { + healthy, _, stats := reviewRealVMess(t) + failing, _, _ := reviewRealVMess(t, true) + counter, err := stats.RegisterCounter("inbound>>>proxy>>>traffic>>>uplink") + if err != nil { + t.Fatal(err) + } + counter.Set(123) + if _, err := stats.RegisterCounter("user>>>private@example.test>>>traffic>>>uplink"); err != nil { + t.Fatal(err) + } + receiver := &nodeMetricsReceiver{reports: make(chan *pb.ReportNodeMetricsRequest, 2)} + handler := pb.NewNodeMetricsServiceServer(receiver, twirp.WithServerPathPrefix("")) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(mu.TokenHeader) != "fixture-token" { + http.Error(w, "missing token", http.StatusUnauthorized) + return + } + handler.ServeHTTP(w, r) + })) + defer server.Close() + + address := func(s *v2flySync) string { return strings.TrimSuffix(strings.TrimPrefix(s.key, "v2fly:"), ":"+tag) } + t.Setenv("MU_NODE_METRICS_REPORTING_ENABLED", "true") + t.Setenv("MU_METRICS_ENABLED", "false") + cfg := ConfigFromEnv() + cfg.MuNodeID = "metrics-test" + cfg.MuAPIBaseURL = server.URL + cfg.MuAPIToken = "fixture-token" + cfg.StateFile = filepath.Join(t.TempDir(), "state.json") + cfg.V2flyAddrs = []string{address(healthy)} + cfg.VlessAddrs = []string{address(healthy), address(failing)} + a := New(cfg) + if err := a.Init(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = a.Close() }) + if !cfg.NodeMetricsReportingEnabled || a.metricsServer != nil { + t.Fatal("expected reporting enabled and the scrape server disabled") + } + if err := a.reportNodeMetricsOnce(t.Context()); err != nil { + t.Fatal(err) + } + first, retry := <-receiver.reports, <-receiver.reports + if first.NodeId != cfg.MuNodeID || first.BatchId == "" || !proto.Equal(first, retry) { + t.Fatal("report did not preserve node identity and the same payload across retries") + } + if len(first.Backends) != 2 || counter.Value() != 123 { + t.Fatal("backends were not deduplicated or the counter changed") + } + for _, sample := range first.Backends { + if sample.SampledAtUnixMillis <= 0 { + t.Fatal("missing sample timestamp") + } + switch sample.Backend { + case address(healthy): + expected := &pb.V2FlyTrafficCounter{Dimension: "inbound", Tag: "proxy", Direction: "uplink", Bytes: 123} + if !sample.Up || sample.Runtime == nil || len(sample.Traffic) != 1 || !proto.Equal(sample.Traffic[0], expected) { + t.Fatalf("unexpected healthy backend sample: %v", sample) + } + case address(failing): + if sample.Up || sample.Runtime != nil || len(sample.Traffic) != 0 { + t.Fatalf("unexpected failed backend sample: %v", sample) + } + default: + t.Fatalf("unexpected backend: %s", sample.Backend) + } + } +} diff --git a/proto/v1/mu.pb.go b/proto/v1/mu.pb.go index aab1208..8570377 100644 --- a/proto/v1/mu.pb.go +++ b/proto/v1/mu.pb.go @@ -622,76 +622,84 @@ var File_v1_mu_proto protoreflect.FileDescriptor var file_v1_mu_proto_rawDesc = []byte{ 0x0a, 0x0b, 0x76, 0x31, 0x2f, 0x6d, 0x75, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x02, 0x76, - 0x31, 0x22, 0x2a, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x22, 0x32, 0x0a, - 0x10, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x12, 0x1e, 0x0a, 0x05, 0x75, 0x73, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x08, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x05, 0x75, 0x73, 0x65, 0x72, - 0x73, 0x22, 0x77, 0x0a, 0x17, 0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x72, 0x61, 0x66, 0x66, - 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, - 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6e, - 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x26, 0x0a, 0x04, 0x6c, 0x6f, 0x67, 0x73, 0x18, 0x02, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x54, 0x72, 0x61, - 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x04, 0x6c, 0x6f, 0x67, 0x73, 0x12, 0x1b, 0x0a, - 0x09, 0x75, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, - 0x52, 0x08, 0x75, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x41, 0x74, 0x22, 0x1a, 0x0a, 0x18, 0x55, 0x70, - 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x62, 0x0a, 0x05, 0x56, 0x55, 0x73, 0x65, 0x72, 0x12, - 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, - 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x12, 0x0a, 0x04, 0x75, 0x75, 0x69, 0x64, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x04, 0x75, 0x75, 0x69, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x61, 0x6c, 0x74, - 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x61, 0x6c, 0x74, - 0x65, 0x72, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x22, 0xe1, 0x01, 0x0a, 0x04, 0x55, - 0x73, 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, - 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x05, 0x52, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x61, 0x73, 0x73, 0x77, - 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x61, 0x73, 0x73, 0x77, 0x64, 0x12, - 0x16, 0x0a, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x65, 0x6e, 0x61, 0x62, 0x6c, - 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x12, - 0x27, 0x0a, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x5f, 0x65, 0x6e, 0x61, 0x62, - 0x6c, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, - 0x65, 0x72, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x0c, 0x0a, 0x01, 0x75, 0x18, 0x07, 0x20, - 0x01, 0x28, 0x03, 0x52, 0x01, 0x75, 0x12, 0x0c, 0x0a, 0x01, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, - 0x03, 0x52, 0x01, 0x64, 0x12, 0x28, 0x0a, 0x0a, 0x76, 0x32, 0x72, 0x61, 0x79, 0x5f, 0x75, 0x73, - 0x65, 0x72, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x09, 0x2e, 0x76, 0x31, 0x2e, 0x56, 0x55, - 0x73, 0x65, 0x72, 0x52, 0x09, 0x76, 0x32, 0x72, 0x61, 0x79, 0x55, 0x73, 0x65, 0x72, 0x22, 0x7c, - 0x0a, 0x0e, 0x55, 0x73, 0x65, 0x72, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, - 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x03, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x75, 0x75, 0x69, - 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x75, 0x75, 0x69, 0x64, 0x12, 0x0c, 0x0a, - 0x01, 0x75, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x75, 0x12, 0x0c, 0x0a, 0x01, 0x64, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x74, 0x72, 0x61, - 0x66, 0x66, 0x69, 0x63, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, - 0x0b, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x54, 0x79, 0x70, 0x65, 0x22, 0x40, 0x0a, 0x0b, - 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, + 0x31, 0x1a, 0x15, 0x76, 0x31, 0x2f, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6d, 0x65, 0x74, 0x72, 0x69, + 0x63, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2a, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x55, + 0x73, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6e, 0x6f, - 0x64, 0x65, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x0e, - 0x0a, 0x0c, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2a, 0x5c, - 0x0a, 0x0b, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, - 0x18, 0x54, 0x52, 0x41, 0x46, 0x46, 0x49, 0x43, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, - 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x16, 0x0a, 0x12, 0x54, - 0x52, 0x41, 0x46, 0x46, 0x49, 0x43, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x56, 0x32, 0x46, 0x4c, - 0x59, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x54, 0x52, 0x41, 0x46, 0x46, 0x49, 0x43, 0x5f, 0x54, - 0x59, 0x50, 0x45, 0x5f, 0x54, 0x52, 0x4f, 0x4a, 0x41, 0x4e, 0x10, 0x02, 0x32, 0xc2, 0x01, 0x0a, - 0x09, 0x4d, 0x55, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x2b, 0x0a, 0x04, 0x50, 0x69, - 0x6e, 0x67, 0x12, 0x0f, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x10, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x37, 0x0a, 0x08, 0x47, 0x65, 0x74, 0x55, 0x73, - 0x65, 0x72, 0x73, 0x12, 0x13, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, - 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, - 0x74, 0x55, 0x73, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, - 0x12, 0x4f, 0x0a, 0x10, 0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, - 0x63, 0x4c, 0x6f, 0x67, 0x12, 0x1b, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, - 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x1a, 0x1c, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x72, 0x61, - 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, - 0x00, 0x42, 0x20, 0x5a, 0x1e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x69, 0x63, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x6d, 0x75, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x64, 0x65, 0x49, 0x64, 0x22, 0x32, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x73, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1e, 0x0a, 0x05, 0x75, 0x73, 0x65, 0x72, + 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x08, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x73, 0x65, + 0x72, 0x52, 0x05, 0x75, 0x73, 0x65, 0x72, 0x73, 0x22, 0x77, 0x0a, 0x17, 0x55, 0x70, 0x6c, 0x6f, + 0x61, 0x64, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x26, 0x0a, 0x04, + 0x6c, 0x6f, 0x67, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x76, 0x31, 0x2e, + 0x55, 0x73, 0x65, 0x72, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x04, + 0x6c, 0x6f, 0x67, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x75, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x61, + 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x75, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x41, + 0x74, 0x22, 0x1a, 0x0a, 0x18, 0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x72, 0x61, 0x66, 0x66, + 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x62, 0x0a, + 0x05, 0x56, 0x55, 0x73, 0x65, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x12, 0x0a, 0x04, + 0x75, 0x75, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x75, 0x75, 0x69, 0x64, + 0x12, 0x19, 0x0a, 0x08, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x0d, 0x52, 0x07, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x6c, + 0x65, 0x76, 0x65, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6c, 0x65, 0x76, 0x65, + 0x6c, 0x22, 0xe1, 0x01, 0x0a, 0x04, 0x55, 0x73, 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x6f, + 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x16, + 0x0a, 0x06, 0x70, 0x61, 0x73, 0x73, 0x77, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, + 0x70, 0x61, 0x73, 0x73, 0x77, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, + 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x12, 0x16, + 0x0a, 0x06, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, + 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, + 0x65, 0x72, 0x5f, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x12, + 0x0c, 0x0a, 0x01, 0x75, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x75, 0x12, 0x0c, 0x0a, + 0x01, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x64, 0x12, 0x28, 0x0a, 0x0a, 0x76, + 0x32, 0x72, 0x61, 0x79, 0x5f, 0x75, 0x73, 0x65, 0x72, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x09, 0x2e, 0x76, 0x31, 0x2e, 0x56, 0x55, 0x73, 0x65, 0x72, 0x52, 0x09, 0x76, 0x32, 0x72, 0x61, + 0x79, 0x55, 0x73, 0x65, 0x72, 0x22, 0x7c, 0x0a, 0x0e, 0x55, 0x73, 0x65, 0x72, 0x54, 0x72, 0x61, + 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, + 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, + 0x12, 0x12, 0x0a, 0x04, 0x75, 0x75, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, + 0x75, 0x75, 0x69, 0x64, 0x12, 0x0c, 0x0a, 0x01, 0x75, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x01, 0x75, 0x12, 0x0c, 0x0a, 0x01, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x64, + 0x12, 0x21, 0x0a, 0x0c, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x5f, 0x74, 0x79, 0x70, 0x65, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0b, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x54, + 0x79, 0x70, 0x65, 0x22, 0x40, 0x0a, 0x0b, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x0e, 0x0a, 0x0c, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2a, 0x5c, 0x0a, 0x0b, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, + 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x18, 0x54, 0x52, 0x41, 0x46, 0x46, 0x49, 0x43, 0x5f, + 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, + 0x10, 0x00, 0x12, 0x16, 0x0a, 0x12, 0x54, 0x52, 0x41, 0x46, 0x46, 0x49, 0x43, 0x5f, 0x54, 0x59, + 0x50, 0x45, 0x5f, 0x56, 0x32, 0x46, 0x4c, 0x59, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x54, 0x52, + 0x41, 0x46, 0x46, 0x49, 0x43, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x54, 0x52, 0x4f, 0x4a, 0x41, + 0x4e, 0x10, 0x02, 0x32, 0xc2, 0x01, 0x0a, 0x09, 0x4d, 0x55, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x12, 0x2b, 0x0a, 0x04, 0x50, 0x69, 0x6e, 0x67, 0x12, 0x0f, 0x2e, 0x76, 0x31, 0x2e, 0x50, + 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x10, 0x2e, 0x76, 0x31, 0x2e, + 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x37, + 0x0a, 0x08, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x73, 0x12, 0x13, 0x2e, 0x76, 0x31, 0x2e, + 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x14, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x4f, 0x0a, 0x10, 0x55, 0x70, 0x6c, 0x6f, 0x61, + 0x64, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x12, 0x1b, 0x2e, 0x76, 0x31, + 0x2e, 0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, + 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1c, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, + 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x4c, 0x6f, 0x67, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x32, 0x68, 0x0a, 0x12, 0x4e, 0x6f, 0x64, 0x65, + 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x52, + 0x0a, 0x11, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x4e, 0x6f, 0x64, 0x65, 0x4d, 0x65, 0x74, 0x72, + 0x69, 0x63, 0x73, 0x12, 0x1c, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x4e, + 0x6f, 0x64, 0x65, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x1d, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x4e, 0x6f, 0x64, + 0x65, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x22, 0x00, 0x42, 0x20, 0x5a, 0x1e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, + 0x2f, 0x69, 0x63, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x6d, 0x75, 0x2f, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -709,32 +717,36 @@ func file_v1_mu_proto_rawDescGZIP() []byte { var file_v1_mu_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_v1_mu_proto_msgTypes = make([]protoimpl.MessageInfo, 9) var file_v1_mu_proto_goTypes = []interface{}{ - (TrafficType)(0), // 0: v1.TrafficType - (*GetUsersRequest)(nil), // 1: v1.GetUsersRequest - (*GetUsersResponse)(nil), // 2: v1.GetUsersResponse - (*UploadTrafficLogRequest)(nil), // 3: v1.UploadTrafficLogRequest - (*UploadTrafficLogResponse)(nil), // 4: v1.UploadTrafficLogResponse - (*VUser)(nil), // 5: v1.VUser - (*User)(nil), // 6: v1.User - (*UserTrafficLog)(nil), // 7: v1.UserTrafficLog - (*PingRequest)(nil), // 8: v1.PingRequest - (*PingResponse)(nil), // 9: v1.PingResponse + (TrafficType)(0), // 0: v1.TrafficType + (*GetUsersRequest)(nil), // 1: v1.GetUsersRequest + (*GetUsersResponse)(nil), // 2: v1.GetUsersResponse + (*UploadTrafficLogRequest)(nil), // 3: v1.UploadTrafficLogRequest + (*UploadTrafficLogResponse)(nil), // 4: v1.UploadTrafficLogResponse + (*VUser)(nil), // 5: v1.VUser + (*User)(nil), // 6: v1.User + (*UserTrafficLog)(nil), // 7: v1.UserTrafficLog + (*PingRequest)(nil), // 8: v1.PingRequest + (*PingResponse)(nil), // 9: v1.PingResponse + (*ReportNodeMetricsRequest)(nil), // 10: v1.ReportNodeMetricsRequest + (*ReportNodeMetricsResponse)(nil), // 11: v1.ReportNodeMetricsResponse } var file_v1_mu_proto_depIdxs = []int32{ - 6, // 0: v1.GetUsersResponse.users:type_name -> v1.User - 7, // 1: v1.UploadTrafficLogRequest.logs:type_name -> v1.UserTrafficLog - 5, // 2: v1.User.v2ray_user:type_name -> v1.VUser - 8, // 3: v1.MUService.Ping:input_type -> v1.PingRequest - 1, // 4: v1.MUService.GetUsers:input_type -> v1.GetUsersRequest - 3, // 5: v1.MUService.UploadTrafficLog:input_type -> v1.UploadTrafficLogRequest - 9, // 6: v1.MUService.Ping:output_type -> v1.PingResponse - 2, // 7: v1.MUService.GetUsers:output_type -> v1.GetUsersResponse - 4, // 8: v1.MUService.UploadTrafficLog:output_type -> v1.UploadTrafficLogResponse - 6, // [6:9] is the sub-list for method output_type - 3, // [3:6] is the sub-list for method input_type - 3, // [3:3] is the sub-list for extension type_name - 3, // [3:3] is the sub-list for extension extendee - 0, // [0:3] is the sub-list for field type_name + 6, // 0: v1.GetUsersResponse.users:type_name -> v1.User + 7, // 1: v1.UploadTrafficLogRequest.logs:type_name -> v1.UserTrafficLog + 5, // 2: v1.User.v2ray_user:type_name -> v1.VUser + 8, // 3: v1.MUService.Ping:input_type -> v1.PingRequest + 1, // 4: v1.MUService.GetUsers:input_type -> v1.GetUsersRequest + 3, // 5: v1.MUService.UploadTrafficLog:input_type -> v1.UploadTrafficLogRequest + 10, // 6: v1.NodeMetricsService.ReportNodeMetrics:input_type -> v1.ReportNodeMetricsRequest + 9, // 7: v1.MUService.Ping:output_type -> v1.PingResponse + 2, // 8: v1.MUService.GetUsers:output_type -> v1.GetUsersResponse + 4, // 9: v1.MUService.UploadTrafficLog:output_type -> v1.UploadTrafficLogResponse + 11, // 10: v1.NodeMetricsService.ReportNodeMetrics:output_type -> v1.ReportNodeMetricsResponse + 7, // [7:11] is the sub-list for method output_type + 3, // [3:7] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name } func init() { file_v1_mu_proto_init() } @@ -742,6 +754,7 @@ func file_v1_mu_proto_init() { if File_v1_mu_proto != nil { return } + file_v1_node_metrics_proto_init() if !protoimpl.UnsafeEnabled { file_v1_mu_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetUsersRequest); i { @@ -860,7 +873,7 @@ func file_v1_mu_proto_init() { NumEnums: 1, NumMessages: 9, NumExtensions: 0, - NumServices: 1, + NumServices: 2, }, GoTypes: file_v1_mu_proto_goTypes, DependencyIndexes: file_v1_mu_proto_depIdxs, diff --git a/proto/v1/mu.twirp.go b/proto/v1/mu.twirp.go index a3a1dba..39af91c 100644 --- a/proto/v1/mu.twirp.go +++ b/proto/v1/mu.twirp.go @@ -1079,6 +1079,502 @@ func (s *mUServiceServer) PathPrefix() string { return baseServicePath(s.pathPrefix, "v1", "MUService") } +// ============================ +// NodeMetricsService Interface +// ============================ + +type NodeMetricsService interface { + // Authenticate the node and durably accept a batch before acknowledging it. + // Repeated submissions of the same (node_id, batch_id) succeed without inserting duplicates. + ReportNodeMetrics(context.Context, *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) +} + +// ================================== +// NodeMetricsService Protobuf Client +// ================================== + +type nodeMetricsServiceProtobufClient struct { + client HTTPClient + urls [1]string + interceptor twirp.Interceptor + opts twirp.ClientOptions +} + +// NewNodeMetricsServiceProtobufClient creates a Protobuf client that implements the NodeMetricsService interface. +// It communicates using Protobuf and can be configured with a custom HTTPClient. +func NewNodeMetricsServiceProtobufClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) NodeMetricsService { + if c, ok := client.(*http.Client); ok { + client = withoutRedirects(c) + } + + clientOpts := twirp.ClientOptions{} + for _, o := range opts { + o(&clientOpts) + } + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + literalURLs := false + _ = clientOpts.ReadOpt("literalURLs", &literalURLs) + var pathPrefix string + if ok := clientOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + // Build method URLs: []/./ + serviceURL := sanitizeBaseURL(baseURL) + serviceURL += baseServicePath(pathPrefix, "v1", "NodeMetricsService") + urls := [1]string{ + serviceURL + "ReportNodeMetrics", + } + + return &nodeMetricsServiceProtobufClient{ + client: client, + urls: urls, + interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...), + opts: clientOpts, + } +} + +func (c *nodeMetricsServiceProtobufClient) ReportNodeMetrics(ctx context.Context, in *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "v1") + ctx = ctxsetters.WithServiceName(ctx, "NodeMetricsService") + ctx = ctxsetters.WithMethodName(ctx, "ReportNodeMetrics") + caller := c.callReportNodeMetrics + if c.interceptor != nil { + caller = func(ctx context.Context, req *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*ReportNodeMetricsRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*ReportNodeMetricsRequest) when calling interceptor") + } + return c.callReportNodeMetrics(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*ReportNodeMetricsResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*ReportNodeMetricsResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *nodeMetricsServiceProtobufClient) callReportNodeMetrics(ctx context.Context, in *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + out := new(ReportNodeMetricsResponse) + ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[0], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +// ============================== +// NodeMetricsService JSON Client +// ============================== + +type nodeMetricsServiceJSONClient struct { + client HTTPClient + urls [1]string + interceptor twirp.Interceptor + opts twirp.ClientOptions +} + +// NewNodeMetricsServiceJSONClient creates a JSON client that implements the NodeMetricsService interface. +// It communicates using JSON and can be configured with a custom HTTPClient. +func NewNodeMetricsServiceJSONClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) NodeMetricsService { + if c, ok := client.(*http.Client); ok { + client = withoutRedirects(c) + } + + clientOpts := twirp.ClientOptions{} + for _, o := range opts { + o(&clientOpts) + } + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + literalURLs := false + _ = clientOpts.ReadOpt("literalURLs", &literalURLs) + var pathPrefix string + if ok := clientOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + // Build method URLs: []/./ + serviceURL := sanitizeBaseURL(baseURL) + serviceURL += baseServicePath(pathPrefix, "v1", "NodeMetricsService") + urls := [1]string{ + serviceURL + "ReportNodeMetrics", + } + + return &nodeMetricsServiceJSONClient{ + client: client, + urls: urls, + interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...), + opts: clientOpts, + } +} + +func (c *nodeMetricsServiceJSONClient) ReportNodeMetrics(ctx context.Context, in *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "v1") + ctx = ctxsetters.WithServiceName(ctx, "NodeMetricsService") + ctx = ctxsetters.WithMethodName(ctx, "ReportNodeMetrics") + caller := c.callReportNodeMetrics + if c.interceptor != nil { + caller = func(ctx context.Context, req *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*ReportNodeMetricsRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*ReportNodeMetricsRequest) when calling interceptor") + } + return c.callReportNodeMetrics(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*ReportNodeMetricsResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*ReportNodeMetricsResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *nodeMetricsServiceJSONClient) callReportNodeMetrics(ctx context.Context, in *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + out := new(ReportNodeMetricsResponse) + ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[0], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +// ================================= +// NodeMetricsService Server Handler +// ================================= + +type nodeMetricsServiceServer struct { + NodeMetricsService + interceptor twirp.Interceptor + hooks *twirp.ServerHooks + pathPrefix string // prefix for routing + jsonSkipDefaults bool // do not include unpopulated fields (default values) in the response + jsonCamelCase bool // JSON fields are serialized as lowerCamelCase rather than keeping the original proto names +} + +// NewNodeMetricsServiceServer builds a TwirpServer that can be used as an http.Handler to handle +// HTTP requests that are routed to the right method in the provided svc implementation. +// The opts are twirp.ServerOption modifiers, for example twirp.WithServerHooks(hooks). +func NewNodeMetricsServiceServer(svc NodeMetricsService, opts ...interface{}) TwirpServer { + serverOpts := newServerOpts(opts) + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + jsonSkipDefaults := false + _ = serverOpts.ReadOpt("jsonSkipDefaults", &jsonSkipDefaults) + jsonCamelCase := false + _ = serverOpts.ReadOpt("jsonCamelCase", &jsonCamelCase) + var pathPrefix string + if ok := serverOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + return &nodeMetricsServiceServer{ + NodeMetricsService: svc, + hooks: serverOpts.Hooks, + interceptor: twirp.ChainInterceptors(serverOpts.Interceptors...), + pathPrefix: pathPrefix, + jsonSkipDefaults: jsonSkipDefaults, + jsonCamelCase: jsonCamelCase, + } +} + +// writeError writes an HTTP response with a valid Twirp error format, and triggers hooks. +// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err) +func (s *nodeMetricsServiceServer) writeError(ctx context.Context, resp http.ResponseWriter, err error) { + writeError(ctx, resp, err, s.hooks) +} + +// handleRequestBodyError is used to handle error when the twirp server cannot read request +func (s *nodeMetricsServiceServer) handleRequestBodyError(ctx context.Context, resp http.ResponseWriter, msg string, err error) { + if context.Canceled == ctx.Err() { + s.writeError(ctx, resp, twirp.NewError(twirp.Canceled, "failed to read request: context canceled")) + return + } + if context.DeadlineExceeded == ctx.Err() { + s.writeError(ctx, resp, twirp.NewError(twirp.DeadlineExceeded, "failed to read request: deadline exceeded")) + return + } + s.writeError(ctx, resp, twirp.WrapError(malformedRequestError(msg), err)) +} + +// NodeMetricsServicePathPrefix is a convenience constant that may identify URL paths. +// Should be used with caution, it only matches routes generated by Twirp Go clients, +// with the default "/twirp" prefix and default CamelCase service and method names. +// More info: https://twitchtv.github.io/twirp/docs/routing.html +const NodeMetricsServicePathPrefix = "/twirp/v1.NodeMetricsService/" + +func (s *nodeMetricsServiceServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) { + ctx := req.Context() + ctx = ctxsetters.WithPackageName(ctx, "v1") + ctx = ctxsetters.WithServiceName(ctx, "NodeMetricsService") + ctx = ctxsetters.WithResponseWriter(ctx, resp) + + var err error + ctx, err = callRequestReceived(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + if req.Method != "POST" { + msg := fmt.Sprintf("unsupported method %q (only POST is allowed)", req.Method) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + + // Verify path format: []/./ + prefix, pkgService, method := parseTwirpPath(req.URL.Path) + if pkgService != "v1.NodeMetricsService" { + msg := fmt.Sprintf("no handler for path %q", req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + if prefix != s.pathPrefix { + msg := fmt.Sprintf("invalid path prefix %q, expected %q, on path %q", prefix, s.pathPrefix, req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + + switch method { + case "ReportNodeMetrics": + s.serveReportNodeMetrics(ctx, resp, req) + return + default: + msg := fmt.Sprintf("no handler for path %q", req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } +} + +func (s *nodeMetricsServiceServer) serveReportNodeMetrics(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + header := req.Header.Get("Content-Type") + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + switch strings.TrimSpace(strings.ToLower(header[:i])) { + case "application/json": + s.serveReportNodeMetricsJSON(ctx, resp, req) + case "application/protobuf": + s.serveReportNodeMetricsProtobuf(ctx, resp, req) + default: + msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) + twerr := badRouteError(msg, req.Method, req.URL.Path) + s.writeError(ctx, resp, twerr) + } +} + +func (s *nodeMetricsServiceServer) serveReportNodeMetricsJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "ReportNodeMetrics") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + d := json.NewDecoder(req.Body) + rawReqBody := json.RawMessage{} + if err := d.Decode(&rawReqBody); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + reqContent := new(ReportNodeMetricsRequest) + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + + handler := s.NodeMetricsService.ReportNodeMetrics + if s.interceptor != nil { + handler = func(ctx context.Context, req *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*ReportNodeMetricsRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*ReportNodeMetricsRequest) when calling interceptor") + } + return s.NodeMetricsService.ReportNodeMetrics(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*ReportNodeMetricsResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*ReportNodeMetricsResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *ReportNodeMetricsResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *ReportNodeMetricsResponse and nil error while calling ReportNodeMetrics. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} + respBytes, err := marshaler.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/json") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *nodeMetricsServiceServer) serveReportNodeMetricsProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "ReportNodeMetrics") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + s.handleRequestBodyError(ctx, resp, "failed to read request body", err) + return + } + reqContent := new(ReportNodeMetricsRequest) + if err = proto.Unmarshal(buf, reqContent); err != nil { + s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) + return + } + + handler := s.NodeMetricsService.ReportNodeMetrics + if s.interceptor != nil { + handler = func(ctx context.Context, req *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*ReportNodeMetricsRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*ReportNodeMetricsRequest) when calling interceptor") + } + return s.NodeMetricsService.ReportNodeMetrics(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*ReportNodeMetricsResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*ReportNodeMetricsResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *ReportNodeMetricsResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *ReportNodeMetricsResponse and nil error while calling ReportNodeMetrics. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + respBytes, err := proto.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/protobuf") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *nodeMetricsServiceServer) ServiceDescriptor() ([]byte, int) { + return twirpFileDescriptor0, 1 +} + +func (s *nodeMetricsServiceServer) ProtocGenTwirpVersion() string { + return "v8.1.3" +} + +// PathPrefix returns the base service path, in the form: "//./" +// that is everything in a Twirp route except for the . This can be used for routing, +// for example to identify the requests that are targeted to this service in a mux. +func (s *nodeMetricsServiceServer) PathPrefix() string { + return baseServicePath(s.pathPrefix, "v1", "NodeMetricsService") +} + // ===== // Utils // ===== @@ -1645,43 +2141,46 @@ func callClientError(ctx context.Context, h *twirp.ClientHooks, err twirp.Error) } var twirpFileDescriptor0 = []byte{ - // 600 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x54, 0x4d, 0x4f, 0xdb, 0x40, - 0x10, 0xc5, 0x8e, 0xf3, 0xe1, 0x31, 0x0d, 0xd6, 0x82, 0x60, 0x1b, 0x10, 0x4a, 0x7d, 0x68, 0x23, - 0x2a, 0x25, 0x8a, 0x7b, 0xe8, 0xb5, 0x94, 0x26, 0x95, 0x2b, 0x0a, 0x68, 0x71, 0x90, 0xa8, 0x2a, - 0x59, 0x4e, 0xbc, 0x04, 0x4b, 0x8e, 0xed, 0xda, 0x6b, 0xa3, 0x48, 0xfd, 0x75, 0xfd, 0x27, 0xfd, - 0x27, 0xd5, 0xae, 0x6d, 0x42, 0x68, 0x24, 0x6e, 0xfb, 0xde, 0x8c, 0xdf, 0x9b, 0xd9, 0xd9, 0x31, - 0x68, 0xf9, 0x70, 0xb0, 0xc8, 0xfa, 0x71, 0x12, 0xb1, 0x08, 0xc9, 0xf9, 0xd0, 0x38, 0x81, 0x9d, - 0xaf, 0x94, 0x4d, 0x52, 0x9a, 0xa4, 0x84, 0xfe, 0xca, 0x68, 0xca, 0xd0, 0x01, 0x34, 0xc3, 0xc8, - 0xa3, 0x8e, 0xef, 0x61, 0xa9, 0x2b, 0xf5, 0x54, 0xd2, 0xe0, 0xd0, 0xf2, 0x0c, 0x13, 0xf4, 0x55, - 0x6e, 0x1a, 0x47, 0x61, 0x4a, 0xd1, 0x31, 0xd4, 0x33, 0x4e, 0x60, 0xa9, 0x5b, 0xeb, 0x69, 0x66, - 0xab, 0x9f, 0x0f, 0xfb, 0x3c, 0x83, 0x14, 0xb4, 0xf1, 0x00, 0x07, 0x93, 0x38, 0x88, 0x5c, 0xcf, - 0x4e, 0xdc, 0xbb, 0x3b, 0x7f, 0x76, 0x1e, 0xcd, 0x5f, 0xf2, 0x41, 0x6f, 0x41, 0x09, 0xa2, 0x79, - 0x8a, 0x65, 0x21, 0x89, 0x2a, 0xc9, 0x27, 0x0a, 0x22, 0x8e, 0x0e, 0x41, 0xcd, 0x84, 0xb6, 0xe3, - 0x32, 0x5c, 0xeb, 0x4a, 0xbd, 0x1a, 0x69, 0x15, 0xc4, 0x29, 0x33, 0x3a, 0x80, 0xff, 0x37, 0x2e, - 0x8a, 0x36, 0xa6, 0x50, 0xbf, 0xe1, 0x8a, 0x68, 0x0f, 0xea, 0x74, 0xe1, 0xfa, 0x41, 0x59, 0x40, - 0x01, 0x10, 0x02, 0x25, 0xcb, 0x7c, 0x0f, 0xcb, 0x82, 0x14, 0x67, 0xf4, 0x1a, 0x5a, 0x6e, 0xc0, - 0x68, 0xc2, 0xab, 0xe5, 0x56, 0xaf, 0x48, 0x53, 0x60, 0xcb, 0xe3, 0x22, 0x01, 0xcd, 0x69, 0x80, - 0x15, 0xc1, 0x17, 0xc0, 0xf8, 0x2b, 0x81, 0x22, 0x3c, 0xda, 0x20, 0x97, 0x1d, 0xd6, 0x88, 0xec, - 0x7b, 0x5c, 0x3d, 0x8e, 0x12, 0x26, 0xd4, 0xeb, 0x44, 0x9c, 0xd1, 0x3e, 0x34, 0x62, 0x37, 0x4d, - 0x1f, 0x0a, 0x6d, 0x95, 0x94, 0x88, 0xf3, 0x0b, 0xca, 0xee, 0x23, 0x4f, 0x68, 0xab, 0xa4, 0x44, - 0x9c, 0xa7, 0xa1, 0x3b, 0x0d, 0x28, 0xae, 0x0b, 0x95, 0x12, 0xa1, 0x77, 0xb0, 0xc3, 0x12, 0x37, - 0x4c, 0xef, 0x68, 0xe2, 0x94, 0x09, 0x0d, 0x61, 0xdc, 0xae, 0xe8, 0x51, 0x91, 0xb8, 0x0d, 0x52, - 0x86, 0x9b, 0x22, 0x24, 0x65, 0x1c, 0x79, 0xb8, 0x55, 0x20, 0x0f, 0xf5, 0x00, 0x72, 0x33, 0x71, - 0x97, 0x0e, 0x9f, 0x20, 0x56, 0xbb, 0x52, 0x4f, 0x33, 0x55, 0x3e, 0x04, 0x71, 0x67, 0x44, 0x15, - 0x41, 0x7e, 0x34, 0x7e, 0x43, 0x7b, 0x7d, 0x30, 0x7c, 0xa6, 0xfc, 0x2b, 0xe7, 0xb1, 0xe3, 0x06, - 0x87, 0x96, 0xb7, 0xf1, 0x4e, 0x45, 0x11, 0xb5, 0xb5, 0x22, 0x94, 0xaa, 0x88, 0x37, 0xb0, 0xcd, - 0x0a, 0x59, 0x87, 0x2d, 0xe3, 0xaa, 0x4f, 0xad, 0xe4, 0xec, 0x65, 0x4c, 0x8d, 0x4f, 0xa0, 0x5d, - 0xf9, 0xe1, 0xcb, 0xcf, 0x09, 0x43, 0x33, 0xa7, 0x49, 0xea, 0x47, 0x61, 0xe9, 0x5e, 0x41, 0xa3, - 0x0d, 0xdb, 0x85, 0x42, 0xf1, 0x2e, 0x4e, 0x7e, 0x82, 0x66, 0xaf, 0x0c, 0xd0, 0x11, 0x60, 0x9b, - 0x9c, 0x8e, 0xc7, 0xd6, 0x99, 0x63, 0xdf, 0x5e, 0x8d, 0x9c, 0xc9, 0xc5, 0xf5, 0xd5, 0xe8, 0xcc, - 0x1a, 0x5b, 0xa3, 0x2f, 0xfa, 0x16, 0xda, 0x07, 0xb4, 0x16, 0xbd, 0x31, 0xc7, 0xe7, 0xb7, 0xba, - 0x84, 0x0e, 0x60, 0x77, 0x8d, 0xb7, 0xc9, 0xe5, 0xb7, 0xd3, 0x0b, 0x5d, 0x36, 0xff, 0x48, 0xa0, - 0x7e, 0x9f, 0x5c, 0xd3, 0x24, 0xf7, 0x67, 0x14, 0xbd, 0x07, 0x85, 0x7b, 0xa3, 0x1d, 0x7e, 0xb3, - 0x4f, 0xfa, 0xe8, 0xe8, 0x2b, 0xa2, 0x7c, 0xae, 0x5b, 0xe8, 0x23, 0xb4, 0xaa, 0xcd, 0x43, 0xbb, - 0x3c, 0xfe, 0x6c, 0x67, 0x3b, 0x7b, 0xeb, 0xe4, 0xe3, 0x87, 0x97, 0xa0, 0x3f, 0xdf, 0x02, 0x74, - 0x28, 0x16, 0x6a, 0xf3, 0x52, 0x76, 0x8e, 0x36, 0x07, 0x2b, 0xc1, 0xcf, 0xdd, 0x1f, 0xc7, 0x73, - 0x9f, 0xdd, 0x67, 0xd3, 0xfe, 0x2c, 0x5a, 0x0c, 0xfc, 0x19, 0x9d, 0xba, 0x29, 0x1d, 0x2c, 0xb2, - 0x81, 0xf8, 0xa5, 0x0c, 0xf2, 0xe1, 0xb4, 0x21, 0x4e, 0x1f, 0xfe, 0x05, 0x00, 0x00, 0xff, 0xff, - 0xde, 0x19, 0x97, 0x9a, 0x6b, 0x04, 0x00, 0x00, + // 642 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x54, 0x5d, 0x4f, 0xdb, 0x30, + 0x14, 0x25, 0xfd, 0xce, 0x2d, 0x2b, 0xdd, 0x85, 0x81, 0x57, 0x18, 0xea, 0xf2, 0xb0, 0x55, 0x4c, + 0x6a, 0xd5, 0xec, 0x61, 0xaf, 0x63, 0xac, 0x9d, 0x3a, 0xf1, 0x25, 0xd3, 0x22, 0x31, 0x4d, 0x8a, + 0xd2, 0xc6, 0x40, 0xa4, 0x34, 0xc9, 0x12, 0x27, 0x08, 0x69, 0xbf, 0x6e, 0xff, 0x64, 0xff, 0x64, + 0xb2, 0x9d, 0x00, 0x85, 0x4e, 0xbc, 0xf9, 0x9c, 0xe3, 0x9c, 0x73, 0xaf, 0xed, 0x1b, 0xa8, 0xa7, + 0xfd, 0xde, 0x3c, 0xe9, 0x86, 0x51, 0xc0, 0x03, 0x2c, 0xa4, 0xfd, 0xd6, 0xab, 0xb4, 0xdf, 0xf3, + 0x03, 0x87, 0x59, 0x73, 0xc6, 0x23, 0x77, 0x16, 0x2b, 0xc9, 0xd8, 0x83, 0xb5, 0x6f, 0x8c, 0x4f, + 0x62, 0x16, 0xc5, 0x94, 0xfd, 0x4a, 0x58, 0xcc, 0x71, 0x0b, 0xaa, 0x72, 0xa3, 0xeb, 0x10, 0xad, + 0xad, 0x75, 0x74, 0x5a, 0x11, 0x70, 0xe4, 0x18, 0x26, 0x34, 0xef, 0xf7, 0xc6, 0x61, 0xe0, 0xc7, + 0x0c, 0x77, 0xa1, 0x9c, 0x08, 0x82, 0x68, 0xed, 0x62, 0xa7, 0x6e, 0xd6, 0xba, 0x69, 0xbf, 0x2b, + 0x76, 0x50, 0x45, 0x1b, 0x37, 0xb0, 0x35, 0x09, 0xbd, 0xc0, 0x76, 0xc6, 0x91, 0x7d, 0x79, 0xe9, + 0xce, 0x0e, 0x83, 0xab, 0xe7, 0x72, 0xf0, 0x1d, 0x94, 0xbc, 0xe0, 0x2a, 0x26, 0x05, 0x69, 0x89, + 0xb9, 0xe5, 0x03, 0x07, 0xa9, 0xe3, 0x36, 0xe8, 0x89, 0xf4, 0xb6, 0x6c, 0x4e, 0x8a, 0x6d, 0xad, + 0x53, 0xa4, 0x35, 0x45, 0xec, 0x73, 0xa3, 0x05, 0xe4, 0x69, 0xb0, 0x2a, 0xda, 0x98, 0x42, 0xf9, + 0x5c, 0x38, 0xe2, 0x06, 0x94, 0xd9, 0xdc, 0x76, 0xbd, 0xac, 0x00, 0x05, 0x10, 0xa1, 0x94, 0x24, + 0xae, 0x43, 0x0a, 0x92, 0x94, 0x6b, 0x7c, 0x0d, 0x35, 0xdb, 0xe3, 0x2c, 0x12, 0xd5, 0x8a, 0xa8, + 0x17, 0xb4, 0x2a, 0xf1, 0xc8, 0x11, 0x26, 0x1e, 0x4b, 0x99, 0x47, 0x4a, 0x92, 0x57, 0xc0, 0xf8, + 0xab, 0x41, 0x49, 0x66, 0x34, 0xa0, 0x90, 0x75, 0x58, 0xa4, 0x05, 0xd7, 0x11, 0xee, 0x61, 0x10, + 0x71, 0xe9, 0x5e, 0xa6, 0x72, 0x8d, 0x9b, 0x50, 0x09, 0xed, 0x38, 0xbe, 0x51, 0xde, 0x3a, 0xcd, + 0x90, 0xe0, 0xe7, 0x8c, 0x5f, 0x07, 0x8e, 0xf4, 0xd6, 0x69, 0x86, 0x04, 0xcf, 0x7c, 0x7b, 0xea, + 0x31, 0x52, 0x96, 0x2e, 0x19, 0xc2, 0xf7, 0xb0, 0xc6, 0x23, 0xdb, 0x8f, 0x2f, 0x59, 0x64, 0x65, + 0x1b, 0x2a, 0x32, 0xb8, 0x91, 0xd3, 0x03, 0xb5, 0x71, 0x15, 0xb4, 0x84, 0x54, 0xa5, 0xa4, 0x25, + 0x02, 0x39, 0xa4, 0xa6, 0x90, 0x83, 0x1d, 0x80, 0xd4, 0x8c, 0xec, 0x5b, 0x4b, 0xdc, 0x20, 0xd1, + 0xdb, 0x5a, 0xa7, 0x6e, 0xea, 0xe2, 0x12, 0xe4, 0x99, 0x51, 0x5d, 0x8a, 0x62, 0x69, 0xfc, 0x86, + 0xc6, 0xe2, 0xc5, 0x88, 0x3b, 0x15, 0x5f, 0x59, 0x77, 0x1d, 0x57, 0x04, 0x1c, 0x39, 0x4b, 0xcf, + 0x54, 0x16, 0x51, 0x5c, 0x28, 0xa2, 0x94, 0x17, 0xf1, 0x16, 0x56, 0xb9, 0xb2, 0xb5, 0xf8, 0x6d, + 0x98, 0xf7, 0x59, 0xcf, 0xb8, 0xf1, 0x6d, 0xc8, 0x8c, 0xcf, 0x50, 0x3f, 0x75, 0xfd, 0xe7, 0x9f, + 0x13, 0x81, 0x6a, 0xca, 0xa2, 0xd8, 0x0d, 0xfc, 0x2c, 0x3d, 0x87, 0x46, 0x03, 0x56, 0x95, 0x83, + 0x7a, 0x17, 0x7b, 0x3f, 0xa1, 0x3e, 0xbe, 0x0f, 0xc0, 0x1d, 0x20, 0x63, 0xba, 0x3f, 0x1c, 0x8e, + 0x0e, 0xac, 0xf1, 0xc5, 0xe9, 0xc0, 0x9a, 0x1c, 0x9f, 0x9d, 0x0e, 0x0e, 0x46, 0xc3, 0xd1, 0xe0, + 0x6b, 0x73, 0x05, 0x37, 0x01, 0x17, 0xd4, 0x73, 0x73, 0x78, 0x78, 0xd1, 0xd4, 0x70, 0x0b, 0xd6, + 0x17, 0xf8, 0x31, 0x3d, 0xf9, 0xbe, 0x7f, 0xdc, 0x2c, 0x98, 0x7f, 0x34, 0xd0, 0x8f, 0x26, 0x67, + 0x2c, 0x4a, 0xdd, 0x19, 0xc3, 0x0f, 0x50, 0x12, 0xd9, 0xb8, 0x26, 0x4e, 0xf6, 0x41, 0x1f, 0xad, + 0xe6, 0x3d, 0x91, 0x3d, 0xd7, 0x15, 0xfc, 0x04, 0xb5, 0x7c, 0xf2, 0x70, 0x5d, 0xe8, 0x8f, 0x66, + 0xb6, 0xb5, 0xb1, 0x48, 0xde, 0x7d, 0x78, 0x02, 0xcd, 0xc7, 0x53, 0x80, 0xdb, 0x72, 0xa0, 0x96, + 0x0f, 0x65, 0x6b, 0x67, 0xb9, 0x98, 0x1b, 0x9a, 0xd7, 0x80, 0xc7, 0x81, 0xc3, 0x8e, 0xd4, 0x4f, + 0x24, 0x6f, 0x86, 0xc2, 0x4b, 0xca, 0xc4, 0x4b, 0x7e, 0xa0, 0xa1, 0xb4, 0x7a, 0x42, 0xe7, 0x41, + 0x6f, 0xfe, 0xa3, 0xe6, 0x49, 0x5f, 0xda, 0x3f, 0x76, 0xaf, 0x5c, 0x7e, 0x9d, 0x4c, 0xbb, 0xb3, + 0x60, 0xde, 0x73, 0x67, 0x6c, 0x6a, 0xc7, 0xac, 0x37, 0x4f, 0x7a, 0xf2, 0xc7, 0xd5, 0x4b, 0xfb, + 0xd3, 0x8a, 0x5c, 0x7d, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0x84, 0x63, 0x0a, 0x27, 0xec, 0x04, + 0x00, 0x00, } diff --git a/proto/v1/mu_grpc.pb.go b/proto/v1/mu_grpc.pb.go index 9eb077b..19a2e23 100644 --- a/proto/v1/mu_grpc.pb.go +++ b/proto/v1/mu_grpc.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.5.1 +// - protoc-gen-go-grpc v1.6.2 // - protoc (unknown) // source: v1/mu.proto @@ -89,13 +89,13 @@ type MUServiceServer interface { type UnimplementedMUServiceServer struct{} func (UnimplementedMUServiceServer) Ping(context.Context, *PingRequest) (*PingResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented") + return nil, status.Error(codes.Unimplemented, "method Ping not implemented") } func (UnimplementedMUServiceServer) GetUsers(context.Context, *GetUsersRequest) (*GetUsersResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUsers not implemented") + return nil, status.Error(codes.Unimplemented, "method GetUsers not implemented") } func (UnimplementedMUServiceServer) UploadTrafficLog(context.Context, *UploadTrafficLogRequest) (*UploadTrafficLogResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UploadTrafficLog not implemented") + return nil, status.Error(codes.Unimplemented, "method UploadTrafficLog not implemented") } func (UnimplementedMUServiceServer) mustEmbedUnimplementedMUServiceServer() {} func (UnimplementedMUServiceServer) testEmbeddedByValue() {} @@ -108,7 +108,7 @@ type UnsafeMUServiceServer interface { } func RegisterMUServiceServer(s grpc.ServiceRegistrar, srv MUServiceServer) { - // If the following call pancis, it indicates UnimplementedMUServiceServer was + // If the following call panics, it indicates UnimplementedMUServiceServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. @@ -195,3 +195,109 @@ var MUService_ServiceDesc = grpc.ServiceDesc{ Streams: []grpc.StreamDesc{}, Metadata: "v1/mu.proto", } + +const ( + NodeMetricsService_ReportNodeMetrics_FullMethodName = "/v1.NodeMetricsService/ReportNodeMetrics" +) + +// NodeMetricsServiceClient is the client API for NodeMetricsService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type NodeMetricsServiceClient interface { + // Authenticate the node and durably accept a batch before acknowledging it. + // Repeated submissions of the same (node_id, batch_id) succeed without inserting duplicates. + ReportNodeMetrics(ctx context.Context, in *ReportNodeMetricsRequest, opts ...grpc.CallOption) (*ReportNodeMetricsResponse, error) +} + +type nodeMetricsServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewNodeMetricsServiceClient(cc grpc.ClientConnInterface) NodeMetricsServiceClient { + return &nodeMetricsServiceClient{cc} +} + +func (c *nodeMetricsServiceClient) ReportNodeMetrics(ctx context.Context, in *ReportNodeMetricsRequest, opts ...grpc.CallOption) (*ReportNodeMetricsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ReportNodeMetricsResponse) + err := c.cc.Invoke(ctx, NodeMetricsService_ReportNodeMetrics_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// NodeMetricsServiceServer is the server API for NodeMetricsService service. +// All implementations must embed UnimplementedNodeMetricsServiceServer +// for forward compatibility. +type NodeMetricsServiceServer interface { + // Authenticate the node and durably accept a batch before acknowledging it. + // Repeated submissions of the same (node_id, batch_id) succeed without inserting duplicates. + ReportNodeMetrics(context.Context, *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) + mustEmbedUnimplementedNodeMetricsServiceServer() +} + +// UnimplementedNodeMetricsServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedNodeMetricsServiceServer struct{} + +func (UnimplementedNodeMetricsServiceServer) ReportNodeMetrics(context.Context, *ReportNodeMetricsRequest) (*ReportNodeMetricsResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ReportNodeMetrics not implemented") +} +func (UnimplementedNodeMetricsServiceServer) mustEmbedUnimplementedNodeMetricsServiceServer() {} +func (UnimplementedNodeMetricsServiceServer) testEmbeddedByValue() {} + +// UnsafeNodeMetricsServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to NodeMetricsServiceServer will +// result in compilation errors. +type UnsafeNodeMetricsServiceServer interface { + mustEmbedUnimplementedNodeMetricsServiceServer() +} + +func RegisterNodeMetricsServiceServer(s grpc.ServiceRegistrar, srv NodeMetricsServiceServer) { + // If the following call panics, it indicates UnimplementedNodeMetricsServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&NodeMetricsService_ServiceDesc, srv) +} + +func _NodeMetricsService_ReportNodeMetrics_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ReportNodeMetricsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(NodeMetricsServiceServer).ReportNodeMetrics(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: NodeMetricsService_ReportNodeMetrics_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(NodeMetricsServiceServer).ReportNodeMetrics(ctx, req.(*ReportNodeMetricsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// NodeMetricsService_ServiceDesc is the grpc.ServiceDesc for NodeMetricsService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var NodeMetricsService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "v1.NodeMetricsService", + HandlerType: (*NodeMetricsServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ReportNodeMetrics", + Handler: _NodeMetricsService_ReportNodeMetrics_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "v1/mu.proto", +} diff --git a/proto/v1/node_metrics.pb.go b/proto/v1/node_metrics.pb.go new file mode 100644 index 0000000..4219b67 --- /dev/null +++ b/proto/v1/node_metrics.pb.go @@ -0,0 +1,570 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.34.1 +// protoc (unknown) +// source: v1/node_metrics.proto + +package v1 + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type ReportNodeMetricsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + NodeId string `protobuf:"bytes,1,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"` + BatchId string `protobuf:"bytes,2,opt,name=batch_id,json=batchId,proto3" json:"batch_id,omitempty"` + Backends []*V2FlyBackendSnapshot `protobuf:"bytes,3,rep,name=backends,proto3" json:"backends,omitempty"` +} + +func (x *ReportNodeMetricsRequest) Reset() { + *x = ReportNodeMetricsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_v1_node_metrics_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ReportNodeMetricsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReportNodeMetricsRequest) ProtoMessage() {} + +func (x *ReportNodeMetricsRequest) ProtoReflect() protoreflect.Message { + mi := &file_v1_node_metrics_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReportNodeMetricsRequest.ProtoReflect.Descriptor instead. +func (*ReportNodeMetricsRequest) Descriptor() ([]byte, []int) { + return file_v1_node_metrics_proto_rawDescGZIP(), []int{0} +} + +func (x *ReportNodeMetricsRequest) GetNodeId() string { + if x != nil { + return x.NodeId + } + return "" +} + +func (x *ReportNodeMetricsRequest) GetBatchId() string { + if x != nil { + return x.BatchId + } + return "" +} + +func (x *ReportNodeMetricsRequest) GetBackends() []*V2FlyBackendSnapshot { + if x != nil { + return x.Backends + } + return nil +} + +type ReportNodeMetricsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *ReportNodeMetricsResponse) Reset() { + *x = ReportNodeMetricsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_v1_node_metrics_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ReportNodeMetricsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReportNodeMetricsResponse) ProtoMessage() {} + +func (x *ReportNodeMetricsResponse) ProtoReflect() protoreflect.Message { + mi := &file_v1_node_metrics_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReportNodeMetricsResponse.ProtoReflect.Descriptor instead. +func (*ReportNodeMetricsResponse) Descriptor() ([]byte, []int) { + return file_v1_node_metrics_proto_rawDescGZIP(), []int{1} +} + +type V2FlyBackendSnapshot struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The configured gRPC address, scoped to this node. + Backend string `protobuf:"bytes,1,opt,name=backend,proto3" json:"backend,omitempty"` + SampledAtUnixMillis int64 `protobuf:"varint,2,opt,name=sampled_at_unix_millis,json=sampledAtUnixMillis,proto3" json:"sampled_at_unix_millis,omitempty"` + // False means collection failed. Runtime and traffic are then absent. + Up bool `protobuf:"varint,3,opt,name=up,proto3" json:"up,omitempty"` + Runtime *V2FlyRuntimeStats `protobuf:"bytes,4,opt,name=runtime,proto3" json:"runtime,omitempty"` + Traffic []*V2FlyTrafficCounter `protobuf:"bytes,5,rep,name=traffic,proto3" json:"traffic,omitempty"` +} + +func (x *V2FlyBackendSnapshot) Reset() { + *x = V2FlyBackendSnapshot{} + if protoimpl.UnsafeEnabled { + mi := &file_v1_node_metrics_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *V2FlyBackendSnapshot) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*V2FlyBackendSnapshot) ProtoMessage() {} + +func (x *V2FlyBackendSnapshot) ProtoReflect() protoreflect.Message { + mi := &file_v1_node_metrics_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use V2FlyBackendSnapshot.ProtoReflect.Descriptor instead. +func (*V2FlyBackendSnapshot) Descriptor() ([]byte, []int) { + return file_v1_node_metrics_proto_rawDescGZIP(), []int{2} +} + +func (x *V2FlyBackendSnapshot) GetBackend() string { + if x != nil { + return x.Backend + } + return "" +} + +func (x *V2FlyBackendSnapshot) GetSampledAtUnixMillis() int64 { + if x != nil { + return x.SampledAtUnixMillis + } + return 0 +} + +func (x *V2FlyBackendSnapshot) GetUp() bool { + if x != nil { + return x.Up + } + return false +} + +func (x *V2FlyBackendSnapshot) GetRuntime() *V2FlyRuntimeStats { + if x != nil { + return x.Runtime + } + return nil +} + +func (x *V2FlyBackendSnapshot) GetTraffic() []*V2FlyTrafficCounter { + if x != nil { + return x.Traffic + } + return nil +} + +type V2FlyRuntimeStats struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + UptimeSeconds uint32 `protobuf:"varint,1,opt,name=uptime_seconds,json=uptimeSeconds,proto3" json:"uptime_seconds,omitempty"` + Goroutines uint32 `protobuf:"varint,2,opt,name=goroutines,proto3" json:"goroutines,omitempty"` + HeapAllocBytes uint64 `protobuf:"varint,3,opt,name=heap_alloc_bytes,json=heapAllocBytes,proto3" json:"heap_alloc_bytes,omitempty"` + TotalAllocBytes uint64 `protobuf:"varint,4,opt,name=total_alloc_bytes,json=totalAllocBytes,proto3" json:"total_alloc_bytes,omitempty"` + RuntimeSysBytes uint64 `protobuf:"varint,5,opt,name=runtime_sys_bytes,json=runtimeSysBytes,proto3" json:"runtime_sys_bytes,omitempty"` + Mallocs uint64 `protobuf:"varint,6,opt,name=mallocs,proto3" json:"mallocs,omitempty"` + Frees uint64 `protobuf:"varint,7,opt,name=frees,proto3" json:"frees,omitempty"` + GcCycles uint32 `protobuf:"varint,8,opt,name=gc_cycles,json=gcCycles,proto3" json:"gc_cycles,omitempty"` + GcPauseTotalNanoseconds uint64 `protobuf:"varint,9,opt,name=gc_pause_total_nanoseconds,json=gcPauseTotalNanoseconds,proto3" json:"gc_pause_total_nanoseconds,omitempty"` +} + +func (x *V2FlyRuntimeStats) Reset() { + *x = V2FlyRuntimeStats{} + if protoimpl.UnsafeEnabled { + mi := &file_v1_node_metrics_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *V2FlyRuntimeStats) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*V2FlyRuntimeStats) ProtoMessage() {} + +func (x *V2FlyRuntimeStats) ProtoReflect() protoreflect.Message { + mi := &file_v1_node_metrics_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use V2FlyRuntimeStats.ProtoReflect.Descriptor instead. +func (*V2FlyRuntimeStats) Descriptor() ([]byte, []int) { + return file_v1_node_metrics_proto_rawDescGZIP(), []int{3} +} + +func (x *V2FlyRuntimeStats) GetUptimeSeconds() uint32 { + if x != nil { + return x.UptimeSeconds + } + return 0 +} + +func (x *V2FlyRuntimeStats) GetGoroutines() uint32 { + if x != nil { + return x.Goroutines + } + return 0 +} + +func (x *V2FlyRuntimeStats) GetHeapAllocBytes() uint64 { + if x != nil { + return x.HeapAllocBytes + } + return 0 +} + +func (x *V2FlyRuntimeStats) GetTotalAllocBytes() uint64 { + if x != nil { + return x.TotalAllocBytes + } + return 0 +} + +func (x *V2FlyRuntimeStats) GetRuntimeSysBytes() uint64 { + if x != nil { + return x.RuntimeSysBytes + } + return 0 +} + +func (x *V2FlyRuntimeStats) GetMallocs() uint64 { + if x != nil { + return x.Mallocs + } + return 0 +} + +func (x *V2FlyRuntimeStats) GetFrees() uint64 { + if x != nil { + return x.Frees + } + return 0 +} + +func (x *V2FlyRuntimeStats) GetGcCycles() uint32 { + if x != nil { + return x.GcCycles + } + return 0 +} + +func (x *V2FlyRuntimeStats) GetGcPauseTotalNanoseconds() uint64 { + if x != nil { + return x.GcPauseTotalNanoseconds + } + return 0 +} + +type V2FlyTrafficCounter struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // inbound or outbound + Dimension string `protobuf:"bytes,1,opt,name=dimension,proto3" json:"dimension,omitempty"` + Tag string `protobuf:"bytes,2,opt,name=tag,proto3" json:"tag,omitempty"` + // uplink or downlink + Direction string `protobuf:"bytes,3,opt,name=direction,proto3" json:"direction,omitempty"` + // Cumulative bytes from this backend process. May reset on restart. + Bytes uint64 `protobuf:"varint,4,opt,name=bytes,proto3" json:"bytes,omitempty"` +} + +func (x *V2FlyTrafficCounter) Reset() { + *x = V2FlyTrafficCounter{} + if protoimpl.UnsafeEnabled { + mi := &file_v1_node_metrics_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *V2FlyTrafficCounter) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*V2FlyTrafficCounter) ProtoMessage() {} + +func (x *V2FlyTrafficCounter) ProtoReflect() protoreflect.Message { + mi := &file_v1_node_metrics_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use V2FlyTrafficCounter.ProtoReflect.Descriptor instead. +func (*V2FlyTrafficCounter) Descriptor() ([]byte, []int) { + return file_v1_node_metrics_proto_rawDescGZIP(), []int{4} +} + +func (x *V2FlyTrafficCounter) GetDimension() string { + if x != nil { + return x.Dimension + } + return "" +} + +func (x *V2FlyTrafficCounter) GetTag() string { + if x != nil { + return x.Tag + } + return "" +} + +func (x *V2FlyTrafficCounter) GetDirection() string { + if x != nil { + return x.Direction + } + return "" +} + +func (x *V2FlyTrafficCounter) GetBytes() uint64 { + if x != nil { + return x.Bytes + } + return 0 +} + +var File_v1_node_metrics_proto protoreflect.FileDescriptor + +var file_v1_node_metrics_proto_rawDesc = []byte{ + 0x0a, 0x15, 0x76, 0x31, 0x2f, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, + 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x02, 0x76, 0x31, 0x22, 0x84, 0x01, 0x0a, 0x18, + 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x4e, 0x6f, 0x64, 0x65, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, + 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, + 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, + 0x64, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x12, 0x34, 0x0a, 0x08, + 0x62, 0x61, 0x63, 0x6b, 0x65, 0x6e, 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, + 0x2e, 0x76, 0x31, 0x2e, 0x56, 0x32, 0x46, 0x6c, 0x79, 0x42, 0x61, 0x63, 0x6b, 0x65, 0x6e, 0x64, + 0x53, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, 0x74, 0x52, 0x08, 0x62, 0x61, 0x63, 0x6b, 0x65, 0x6e, + 0x64, 0x73, 0x22, 0x1b, 0x0a, 0x19, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x4e, 0x6f, 0x64, 0x65, + 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, + 0xd9, 0x01, 0x0a, 0x14, 0x56, 0x32, 0x46, 0x6c, 0x79, 0x42, 0x61, 0x63, 0x6b, 0x65, 0x6e, 0x64, + 0x53, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x62, 0x61, 0x63, 0x6b, + 0x65, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x61, 0x63, 0x6b, 0x65, + 0x6e, 0x64, 0x12, 0x33, 0x0a, 0x16, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x64, 0x5f, 0x61, 0x74, + 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6d, 0x69, 0x6c, 0x6c, 0x69, 0x73, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x03, 0x52, 0x13, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x64, 0x41, 0x74, 0x55, 0x6e, 0x69, + 0x78, 0x4d, 0x69, 0x6c, 0x6c, 0x69, 0x73, 0x12, 0x0e, 0x0a, 0x02, 0x75, 0x70, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x08, 0x52, 0x02, 0x75, 0x70, 0x12, 0x2f, 0x0a, 0x07, 0x72, 0x75, 0x6e, 0x74, 0x69, + 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x76, 0x31, 0x2e, 0x56, 0x32, + 0x46, 0x6c, 0x79, 0x52, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x73, 0x52, + 0x07, 0x72, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x12, 0x31, 0x0a, 0x07, 0x74, 0x72, 0x61, 0x66, + 0x66, 0x69, 0x63, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x76, 0x31, 0x2e, 0x56, + 0x32, 0x46, 0x6c, 0x79, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x43, 0x6f, 0x75, 0x6e, 0x74, + 0x65, 0x72, 0x52, 0x07, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x22, 0xe6, 0x02, 0x0a, 0x11, + 0x56, 0x32, 0x46, 0x6c, 0x79, 0x52, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, + 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x75, 0x70, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x73, 0x65, 0x63, 0x6f, + 0x6e, 0x64, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0d, 0x75, 0x70, 0x74, 0x69, 0x6d, + 0x65, 0x53, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x67, 0x6f, 0x72, 0x6f, + 0x75, 0x74, 0x69, 0x6e, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x67, 0x6f, + 0x72, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x65, 0x73, 0x12, 0x28, 0x0a, 0x10, 0x68, 0x65, 0x61, 0x70, + 0x5f, 0x61, 0x6c, 0x6c, 0x6f, 0x63, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x04, 0x52, 0x0e, 0x68, 0x65, 0x61, 0x70, 0x41, 0x6c, 0x6c, 0x6f, 0x63, 0x42, 0x79, 0x74, + 0x65, 0x73, 0x12, 0x2a, 0x0a, 0x11, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x61, 0x6c, 0x6c, 0x6f, + 0x63, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x74, + 0x6f, 0x74, 0x61, 0x6c, 0x41, 0x6c, 0x6c, 0x6f, 0x63, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x2a, + 0x0a, 0x11, 0x72, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x73, 0x79, 0x73, 0x5f, 0x62, 0x79, + 0x74, 0x65, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x72, 0x75, 0x6e, 0x74, 0x69, + 0x6d, 0x65, 0x53, 0x79, 0x73, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x61, + 0x6c, 0x6c, 0x6f, 0x63, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x6d, 0x61, 0x6c, + 0x6c, 0x6f, 0x63, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x72, 0x65, 0x65, 0x73, 0x18, 0x07, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x05, 0x66, 0x72, 0x65, 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x67, 0x63, + 0x5f, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x67, + 0x63, 0x43, 0x79, 0x63, 0x6c, 0x65, 0x73, 0x12, 0x3b, 0x0a, 0x1a, 0x67, 0x63, 0x5f, 0x70, 0x61, + 0x75, 0x73, 0x65, 0x5f, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x73, 0x65, + 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x18, 0x09, 0x20, 0x01, 0x28, 0x04, 0x52, 0x17, 0x67, 0x63, 0x50, + 0x61, 0x75, 0x73, 0x65, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x4e, 0x61, 0x6e, 0x6f, 0x73, 0x65, 0x63, + 0x6f, 0x6e, 0x64, 0x73, 0x22, 0x79, 0x0a, 0x13, 0x56, 0x32, 0x46, 0x6c, 0x79, 0x54, 0x72, 0x61, + 0x66, 0x66, 0x69, 0x63, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x12, 0x1c, 0x0a, 0x09, 0x64, + 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, + 0x64, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x61, 0x67, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x74, 0x61, 0x67, 0x12, 0x1c, 0x0a, 0x09, 0x64, + 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, + 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, + 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x42, + 0x20, 0x5a, 0x1e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x63, + 0x65, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x6d, 0x75, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x76, + 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_v1_node_metrics_proto_rawDescOnce sync.Once + file_v1_node_metrics_proto_rawDescData = file_v1_node_metrics_proto_rawDesc +) + +func file_v1_node_metrics_proto_rawDescGZIP() []byte { + file_v1_node_metrics_proto_rawDescOnce.Do(func() { + file_v1_node_metrics_proto_rawDescData = protoimpl.X.CompressGZIP(file_v1_node_metrics_proto_rawDescData) + }) + return file_v1_node_metrics_proto_rawDescData +} + +var file_v1_node_metrics_proto_msgTypes = make([]protoimpl.MessageInfo, 5) +var file_v1_node_metrics_proto_goTypes = []interface{}{ + (*ReportNodeMetricsRequest)(nil), // 0: v1.ReportNodeMetricsRequest + (*ReportNodeMetricsResponse)(nil), // 1: v1.ReportNodeMetricsResponse + (*V2FlyBackendSnapshot)(nil), // 2: v1.V2FlyBackendSnapshot + (*V2FlyRuntimeStats)(nil), // 3: v1.V2FlyRuntimeStats + (*V2FlyTrafficCounter)(nil), // 4: v1.V2FlyTrafficCounter +} +var file_v1_node_metrics_proto_depIdxs = []int32{ + 2, // 0: v1.ReportNodeMetricsRequest.backends:type_name -> v1.V2FlyBackendSnapshot + 3, // 1: v1.V2FlyBackendSnapshot.runtime:type_name -> v1.V2FlyRuntimeStats + 4, // 2: v1.V2FlyBackendSnapshot.traffic:type_name -> v1.V2FlyTrafficCounter + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_v1_node_metrics_proto_init() } +func file_v1_node_metrics_proto_init() { + if File_v1_node_metrics_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_v1_node_metrics_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ReportNodeMetricsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_v1_node_metrics_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ReportNodeMetricsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_v1_node_metrics_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*V2FlyBackendSnapshot); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_v1_node_metrics_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*V2FlyRuntimeStats); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_v1_node_metrics_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*V2FlyTrafficCounter); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_v1_node_metrics_proto_rawDesc, + NumEnums: 0, + NumMessages: 5, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_v1_node_metrics_proto_goTypes, + DependencyIndexes: file_v1_node_metrics_proto_depIdxs, + MessageInfos: file_v1_node_metrics_proto_msgTypes, + }.Build() + File_v1_node_metrics_proto = out.File + file_v1_node_metrics_proto_rawDesc = nil + file_v1_node_metrics_proto_goTypes = nil + file_v1_node_metrics_proto_depIdxs = nil +} diff --git a/proto/v1/node_metrics.pb.validate.go b/proto/v1/node_metrics.pb.validate.go new file mode 100644 index 0000000..c60755c --- /dev/null +++ b/proto/v1/node_metrics.pb.validate.go @@ -0,0 +1,679 @@ +// Code generated by protoc-gen-validate. DO NOT EDIT. +// source: v1/node_metrics.proto + +package v1 + +import ( + "bytes" + "errors" + "fmt" + "net" + "net/mail" + "net/url" + "regexp" + "sort" + "strings" + "time" + "unicode/utf8" + + "google.golang.org/protobuf/types/known/anypb" +) + +// ensure the imports are used +var ( + _ = bytes.MinRead + _ = errors.New("") + _ = fmt.Print + _ = utf8.UTFMax + _ = (*regexp.Regexp)(nil) + _ = (*strings.Reader)(nil) + _ = net.IPv4len + _ = time.Duration(0) + _ = (*url.URL)(nil) + _ = (*mail.Address)(nil) + _ = anypb.Any{} + _ = sort.Sort +) + +// Validate checks the field values on ReportNodeMetricsRequest with the rules +// defined in the proto definition for this message. If any rules are +// violated, the first error encountered is returned, or nil if there are no violations. +func (m *ReportNodeMetricsRequest) Validate() error { + return m.validate(false) +} + +// ValidateAll checks the field values on ReportNodeMetricsRequest with the +// rules defined in the proto definition for this message. If any rules are +// violated, the result is a list of violation errors wrapped in +// ReportNodeMetricsRequestMultiError, or nil if none found. +func (m *ReportNodeMetricsRequest) ValidateAll() error { + return m.validate(true) +} + +func (m *ReportNodeMetricsRequest) validate(all bool) error { + if m == nil { + return nil + } + + var errors []error + + // no validation rules for NodeId + + // no validation rules for BatchId + + for idx, item := range m.GetBackends() { + _, _ = idx, item + + if all { + switch v := interface{}(item).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, ReportNodeMetricsRequestValidationError{ + field: fmt.Sprintf("Backends[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, ReportNodeMetricsRequestValidationError{ + field: fmt.Sprintf("Backends[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return ReportNodeMetricsRequestValidationError{ + field: fmt.Sprintf("Backends[%v]", idx), + reason: "embedded message failed validation", + cause: err, + } + } + } + + } + + if len(errors) > 0 { + return ReportNodeMetricsRequestMultiError(errors) + } + + return nil +} + +// ReportNodeMetricsRequestMultiError is an error wrapping multiple validation +// errors returned by ReportNodeMetricsRequest.ValidateAll() if the designated +// constraints aren't met. +type ReportNodeMetricsRequestMultiError []error + +// Error returns a concatenation of all the error messages it wraps. +func (m ReportNodeMetricsRequestMultiError) Error() string { + msgs := make([]string, 0, len(m)) + for _, err := range m { + msgs = append(msgs, err.Error()) + } + return strings.Join(msgs, "; ") +} + +// AllErrors returns a list of validation violation errors. +func (m ReportNodeMetricsRequestMultiError) AllErrors() []error { return m } + +// ReportNodeMetricsRequestValidationError is the validation error returned by +// ReportNodeMetricsRequest.Validate if the designated constraints aren't met. +type ReportNodeMetricsRequestValidationError struct { + field string + reason string + cause error + key bool +} + +// Field function returns field value. +func (e ReportNodeMetricsRequestValidationError) Field() string { return e.field } + +// Reason function returns reason value. +func (e ReportNodeMetricsRequestValidationError) Reason() string { return e.reason } + +// Cause function returns cause value. +func (e ReportNodeMetricsRequestValidationError) Cause() error { return e.cause } + +// Key function returns key value. +func (e ReportNodeMetricsRequestValidationError) Key() bool { return e.key } + +// ErrorName returns error name. +func (e ReportNodeMetricsRequestValidationError) ErrorName() string { + return "ReportNodeMetricsRequestValidationError" +} + +// Error satisfies the builtin error interface +func (e ReportNodeMetricsRequestValidationError) Error() string { + cause := "" + if e.cause != nil { + cause = fmt.Sprintf(" | caused by: %v", e.cause) + } + + key := "" + if e.key { + key = "key for " + } + + return fmt.Sprintf( + "invalid %sReportNodeMetricsRequest.%s: %s%s", + key, + e.field, + e.reason, + cause) +} + +var _ error = ReportNodeMetricsRequestValidationError{} + +var _ interface { + Field() string + Reason() string + Key() bool + Cause() error + ErrorName() string +} = ReportNodeMetricsRequestValidationError{} + +// Validate checks the field values on ReportNodeMetricsResponse with the rules +// defined in the proto definition for this message. If any rules are +// violated, the first error encountered is returned, or nil if there are no violations. +func (m *ReportNodeMetricsResponse) Validate() error { + return m.validate(false) +} + +// ValidateAll checks the field values on ReportNodeMetricsResponse with the +// rules defined in the proto definition for this message. If any rules are +// violated, the result is a list of violation errors wrapped in +// ReportNodeMetricsResponseMultiError, or nil if none found. +func (m *ReportNodeMetricsResponse) ValidateAll() error { + return m.validate(true) +} + +func (m *ReportNodeMetricsResponse) validate(all bool) error { + if m == nil { + return nil + } + + var errors []error + + if len(errors) > 0 { + return ReportNodeMetricsResponseMultiError(errors) + } + + return nil +} + +// ReportNodeMetricsResponseMultiError is an error wrapping multiple validation +// errors returned by ReportNodeMetricsResponse.ValidateAll() if the +// designated constraints aren't met. +type ReportNodeMetricsResponseMultiError []error + +// Error returns a concatenation of all the error messages it wraps. +func (m ReportNodeMetricsResponseMultiError) Error() string { + msgs := make([]string, 0, len(m)) + for _, err := range m { + msgs = append(msgs, err.Error()) + } + return strings.Join(msgs, "; ") +} + +// AllErrors returns a list of validation violation errors. +func (m ReportNodeMetricsResponseMultiError) AllErrors() []error { return m } + +// ReportNodeMetricsResponseValidationError is the validation error returned by +// ReportNodeMetricsResponse.Validate if the designated constraints aren't met. +type ReportNodeMetricsResponseValidationError struct { + field string + reason string + cause error + key bool +} + +// Field function returns field value. +func (e ReportNodeMetricsResponseValidationError) Field() string { return e.field } + +// Reason function returns reason value. +func (e ReportNodeMetricsResponseValidationError) Reason() string { return e.reason } + +// Cause function returns cause value. +func (e ReportNodeMetricsResponseValidationError) Cause() error { return e.cause } + +// Key function returns key value. +func (e ReportNodeMetricsResponseValidationError) Key() bool { return e.key } + +// ErrorName returns error name. +func (e ReportNodeMetricsResponseValidationError) ErrorName() string { + return "ReportNodeMetricsResponseValidationError" +} + +// Error satisfies the builtin error interface +func (e ReportNodeMetricsResponseValidationError) Error() string { + cause := "" + if e.cause != nil { + cause = fmt.Sprintf(" | caused by: %v", e.cause) + } + + key := "" + if e.key { + key = "key for " + } + + return fmt.Sprintf( + "invalid %sReportNodeMetricsResponse.%s: %s%s", + key, + e.field, + e.reason, + cause) +} + +var _ error = ReportNodeMetricsResponseValidationError{} + +var _ interface { + Field() string + Reason() string + Key() bool + Cause() error + ErrorName() string +} = ReportNodeMetricsResponseValidationError{} + +// Validate checks the field values on V2FlyBackendSnapshot with the rules +// defined in the proto definition for this message. If any rules are +// violated, the first error encountered is returned, or nil if there are no violations. +func (m *V2FlyBackendSnapshot) Validate() error { + return m.validate(false) +} + +// ValidateAll checks the field values on V2FlyBackendSnapshot with the rules +// defined in the proto definition for this message. If any rules are +// violated, the result is a list of violation errors wrapped in +// V2FlyBackendSnapshotMultiError, or nil if none found. +func (m *V2FlyBackendSnapshot) ValidateAll() error { + return m.validate(true) +} + +func (m *V2FlyBackendSnapshot) validate(all bool) error { + if m == nil { + return nil + } + + var errors []error + + // no validation rules for Backend + + // no validation rules for SampledAtUnixMillis + + // no validation rules for Up + + if all { + switch v := interface{}(m.GetRuntime()).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, V2FlyBackendSnapshotValidationError{ + field: "Runtime", + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, V2FlyBackendSnapshotValidationError{ + field: "Runtime", + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(m.GetRuntime()).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return V2FlyBackendSnapshotValidationError{ + field: "Runtime", + reason: "embedded message failed validation", + cause: err, + } + } + } + + for idx, item := range m.GetTraffic() { + _, _ = idx, item + + if all { + switch v := interface{}(item).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, V2FlyBackendSnapshotValidationError{ + field: fmt.Sprintf("Traffic[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, V2FlyBackendSnapshotValidationError{ + field: fmt.Sprintf("Traffic[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return V2FlyBackendSnapshotValidationError{ + field: fmt.Sprintf("Traffic[%v]", idx), + reason: "embedded message failed validation", + cause: err, + } + } + } + + } + + if len(errors) > 0 { + return V2FlyBackendSnapshotMultiError(errors) + } + + return nil +} + +// V2FlyBackendSnapshotMultiError is an error wrapping multiple validation +// errors returned by V2FlyBackendSnapshot.ValidateAll() if the designated +// constraints aren't met. +type V2FlyBackendSnapshotMultiError []error + +// Error returns a concatenation of all the error messages it wraps. +func (m V2FlyBackendSnapshotMultiError) Error() string { + msgs := make([]string, 0, len(m)) + for _, err := range m { + msgs = append(msgs, err.Error()) + } + return strings.Join(msgs, "; ") +} + +// AllErrors returns a list of validation violation errors. +func (m V2FlyBackendSnapshotMultiError) AllErrors() []error { return m } + +// V2FlyBackendSnapshotValidationError is the validation error returned by +// V2FlyBackendSnapshot.Validate if the designated constraints aren't met. +type V2FlyBackendSnapshotValidationError struct { + field string + reason string + cause error + key bool +} + +// Field function returns field value. +func (e V2FlyBackendSnapshotValidationError) Field() string { return e.field } + +// Reason function returns reason value. +func (e V2FlyBackendSnapshotValidationError) Reason() string { return e.reason } + +// Cause function returns cause value. +func (e V2FlyBackendSnapshotValidationError) Cause() error { return e.cause } + +// Key function returns key value. +func (e V2FlyBackendSnapshotValidationError) Key() bool { return e.key } + +// ErrorName returns error name. +func (e V2FlyBackendSnapshotValidationError) ErrorName() string { + return "V2FlyBackendSnapshotValidationError" +} + +// Error satisfies the builtin error interface +func (e V2FlyBackendSnapshotValidationError) Error() string { + cause := "" + if e.cause != nil { + cause = fmt.Sprintf(" | caused by: %v", e.cause) + } + + key := "" + if e.key { + key = "key for " + } + + return fmt.Sprintf( + "invalid %sV2FlyBackendSnapshot.%s: %s%s", + key, + e.field, + e.reason, + cause) +} + +var _ error = V2FlyBackendSnapshotValidationError{} + +var _ interface { + Field() string + Reason() string + Key() bool + Cause() error + ErrorName() string +} = V2FlyBackendSnapshotValidationError{} + +// Validate checks the field values on V2FlyRuntimeStats with the rules defined +// in the proto definition for this message. If any rules are violated, the +// first error encountered is returned, or nil if there are no violations. +func (m *V2FlyRuntimeStats) Validate() error { + return m.validate(false) +} + +// ValidateAll checks the field values on V2FlyRuntimeStats with the rules +// defined in the proto definition for this message. If any rules are +// violated, the result is a list of violation errors wrapped in +// V2FlyRuntimeStatsMultiError, or nil if none found. +func (m *V2FlyRuntimeStats) ValidateAll() error { + return m.validate(true) +} + +func (m *V2FlyRuntimeStats) validate(all bool) error { + if m == nil { + return nil + } + + var errors []error + + // no validation rules for UptimeSeconds + + // no validation rules for Goroutines + + // no validation rules for HeapAllocBytes + + // no validation rules for TotalAllocBytes + + // no validation rules for RuntimeSysBytes + + // no validation rules for Mallocs + + // no validation rules for Frees + + // no validation rules for GcCycles + + // no validation rules for GcPauseTotalNanoseconds + + if len(errors) > 0 { + return V2FlyRuntimeStatsMultiError(errors) + } + + return nil +} + +// V2FlyRuntimeStatsMultiError is an error wrapping multiple validation errors +// returned by V2FlyRuntimeStats.ValidateAll() if the designated constraints +// aren't met. +type V2FlyRuntimeStatsMultiError []error + +// Error returns a concatenation of all the error messages it wraps. +func (m V2FlyRuntimeStatsMultiError) Error() string { + msgs := make([]string, 0, len(m)) + for _, err := range m { + msgs = append(msgs, err.Error()) + } + return strings.Join(msgs, "; ") +} + +// AllErrors returns a list of validation violation errors. +func (m V2FlyRuntimeStatsMultiError) AllErrors() []error { return m } + +// V2FlyRuntimeStatsValidationError is the validation error returned by +// V2FlyRuntimeStats.Validate if the designated constraints aren't met. +type V2FlyRuntimeStatsValidationError struct { + field string + reason string + cause error + key bool +} + +// Field function returns field value. +func (e V2FlyRuntimeStatsValidationError) Field() string { return e.field } + +// Reason function returns reason value. +func (e V2FlyRuntimeStatsValidationError) Reason() string { return e.reason } + +// Cause function returns cause value. +func (e V2FlyRuntimeStatsValidationError) Cause() error { return e.cause } + +// Key function returns key value. +func (e V2FlyRuntimeStatsValidationError) Key() bool { return e.key } + +// ErrorName returns error name. +func (e V2FlyRuntimeStatsValidationError) ErrorName() string { + return "V2FlyRuntimeStatsValidationError" +} + +// Error satisfies the builtin error interface +func (e V2FlyRuntimeStatsValidationError) Error() string { + cause := "" + if e.cause != nil { + cause = fmt.Sprintf(" | caused by: %v", e.cause) + } + + key := "" + if e.key { + key = "key for " + } + + return fmt.Sprintf( + "invalid %sV2FlyRuntimeStats.%s: %s%s", + key, + e.field, + e.reason, + cause) +} + +var _ error = V2FlyRuntimeStatsValidationError{} + +var _ interface { + Field() string + Reason() string + Key() bool + Cause() error + ErrorName() string +} = V2FlyRuntimeStatsValidationError{} + +// Validate checks the field values on V2FlyTrafficCounter with the rules +// defined in the proto definition for this message. If any rules are +// violated, the first error encountered is returned, or nil if there are no violations. +func (m *V2FlyTrafficCounter) Validate() error { + return m.validate(false) +} + +// ValidateAll checks the field values on V2FlyTrafficCounter with the rules +// defined in the proto definition for this message. If any rules are +// violated, the result is a list of violation errors wrapped in +// V2FlyTrafficCounterMultiError, or nil if none found. +func (m *V2FlyTrafficCounter) ValidateAll() error { + return m.validate(true) +} + +func (m *V2FlyTrafficCounter) validate(all bool) error { + if m == nil { + return nil + } + + var errors []error + + // no validation rules for Dimension + + // no validation rules for Tag + + // no validation rules for Direction + + // no validation rules for Bytes + + if len(errors) > 0 { + return V2FlyTrafficCounterMultiError(errors) + } + + return nil +} + +// V2FlyTrafficCounterMultiError is an error wrapping multiple validation +// errors returned by V2FlyTrafficCounter.ValidateAll() if the designated +// constraints aren't met. +type V2FlyTrafficCounterMultiError []error + +// Error returns a concatenation of all the error messages it wraps. +func (m V2FlyTrafficCounterMultiError) Error() string { + msgs := make([]string, 0, len(m)) + for _, err := range m { + msgs = append(msgs, err.Error()) + } + return strings.Join(msgs, "; ") +} + +// AllErrors returns a list of validation violation errors. +func (m V2FlyTrafficCounterMultiError) AllErrors() []error { return m } + +// V2FlyTrafficCounterValidationError is the validation error returned by +// V2FlyTrafficCounter.Validate if the designated constraints aren't met. +type V2FlyTrafficCounterValidationError struct { + field string + reason string + cause error + key bool +} + +// Field function returns field value. +func (e V2FlyTrafficCounterValidationError) Field() string { return e.field } + +// Reason function returns reason value. +func (e V2FlyTrafficCounterValidationError) Reason() string { return e.reason } + +// Cause function returns cause value. +func (e V2FlyTrafficCounterValidationError) Cause() error { return e.cause } + +// Key function returns key value. +func (e V2FlyTrafficCounterValidationError) Key() bool { return e.key } + +// ErrorName returns error name. +func (e V2FlyTrafficCounterValidationError) ErrorName() string { + return "V2FlyTrafficCounterValidationError" +} + +// Error satisfies the builtin error interface +func (e V2FlyTrafficCounterValidationError) Error() string { + cause := "" + if e.cause != nil { + cause = fmt.Sprintf(" | caused by: %v", e.cause) + } + + key := "" + if e.key { + key = "key for " + } + + return fmt.Sprintf( + "invalid %sV2FlyTrafficCounter.%s: %s%s", + key, + e.field, + e.reason, + cause) +} + +var _ error = V2FlyTrafficCounterValidationError{} + +var _ interface { + Field() string + Reason() string + Key() bool + Cause() error + ErrorName() string +} = V2FlyTrafficCounterValidationError{} diff --git a/proto/v1/v1connect/mu.connect.go b/proto/v1/v1connect/mu.connect.go index 05e9d9b..3638e5e 100644 --- a/proto/v1/v1connect/mu.connect.go +++ b/proto/v1/v1connect/mu.connect.go @@ -23,6 +23,8 @@ const _ = connect.IsAtLeastVersion1_13_0 const ( // MUServiceName is the fully-qualified name of the MUService service. MUServiceName = "v1.MUService" + // NodeMetricsServiceName is the fully-qualified name of the NodeMetricsService service. + NodeMetricsServiceName = "v1.NodeMetricsService" ) // These constants are the fully-qualified names of the RPCs defined in this package. They're @@ -40,6 +42,9 @@ const ( // MUServiceUploadTrafficLogProcedure is the fully-qualified name of the MUService's // UploadTrafficLog RPC. MUServiceUploadTrafficLogProcedure = "/v1.MUService/UploadTrafficLog" + // NodeMetricsServiceReportNodeMetricsProcedure is the fully-qualified name of the + // NodeMetricsService's ReportNodeMetrics RPC. + NodeMetricsServiceReportNodeMetricsProcedure = "/v1.NodeMetricsService/ReportNodeMetrics" ) // MUServiceClient is a client for the v1.MUService service. @@ -163,3 +168,77 @@ func (UnimplementedMUServiceHandler) GetUsers(context.Context, *connect.Request[ func (UnimplementedMUServiceHandler) UploadTrafficLog(context.Context, *connect.Request[v1.UploadTrafficLogRequest]) (*connect.Response[v1.UploadTrafficLogResponse], error) { return nil, connect.NewError(connect.CodeUnimplemented, errors.New("v1.MUService.UploadTrafficLog is not implemented")) } + +// NodeMetricsServiceClient is a client for the v1.NodeMetricsService service. +type NodeMetricsServiceClient interface { + // Authenticate the node and durably accept a batch before acknowledging it. + // Repeated submissions of the same (node_id, batch_id) succeed without inserting duplicates. + ReportNodeMetrics(context.Context, *connect.Request[v1.ReportNodeMetricsRequest]) (*connect.Response[v1.ReportNodeMetricsResponse], error) +} + +// NewNodeMetricsServiceClient constructs a client for the v1.NodeMetricsService service. By +// default, it uses the Connect protocol with the binary Protobuf Codec, asks for gzipped responses, +// and sends uncompressed requests. To use the gRPC or gRPC-Web protocols, supply the +// connect.WithGRPC() or connect.WithGRPCWeb() options. +// +// The URL supplied here should be the base URL for the Connect or gRPC server (for example, +// http://api.acme.com or https://acme.com/grpc). +func NewNodeMetricsServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) NodeMetricsServiceClient { + baseURL = strings.TrimRight(baseURL, "/") + nodeMetricsServiceMethods := v1.File_v1_mu_proto.Services().ByName("NodeMetricsService").Methods() + return &nodeMetricsServiceClient{ + reportNodeMetrics: connect.NewClient[v1.ReportNodeMetricsRequest, v1.ReportNodeMetricsResponse]( + httpClient, + baseURL+NodeMetricsServiceReportNodeMetricsProcedure, + connect.WithSchema(nodeMetricsServiceMethods.ByName("ReportNodeMetrics")), + connect.WithClientOptions(opts...), + ), + } +} + +// nodeMetricsServiceClient implements NodeMetricsServiceClient. +type nodeMetricsServiceClient struct { + reportNodeMetrics *connect.Client[v1.ReportNodeMetricsRequest, v1.ReportNodeMetricsResponse] +} + +// ReportNodeMetrics calls v1.NodeMetricsService.ReportNodeMetrics. +func (c *nodeMetricsServiceClient) ReportNodeMetrics(ctx context.Context, req *connect.Request[v1.ReportNodeMetricsRequest]) (*connect.Response[v1.ReportNodeMetricsResponse], error) { + return c.reportNodeMetrics.CallUnary(ctx, req) +} + +// NodeMetricsServiceHandler is an implementation of the v1.NodeMetricsService service. +type NodeMetricsServiceHandler interface { + // Authenticate the node and durably accept a batch before acknowledging it. + // Repeated submissions of the same (node_id, batch_id) succeed without inserting duplicates. + ReportNodeMetrics(context.Context, *connect.Request[v1.ReportNodeMetricsRequest]) (*connect.Response[v1.ReportNodeMetricsResponse], error) +} + +// NewNodeMetricsServiceHandler builds an HTTP handler from the service implementation. It returns +// the path on which to mount the handler and the handler itself. +// +// By default, handlers support the Connect, gRPC, and gRPC-Web protocols with the binary Protobuf +// and JSON codecs. They also support gzip compression. +func NewNodeMetricsServiceHandler(svc NodeMetricsServiceHandler, opts ...connect.HandlerOption) (string, http.Handler) { + nodeMetricsServiceMethods := v1.File_v1_mu_proto.Services().ByName("NodeMetricsService").Methods() + nodeMetricsServiceReportNodeMetricsHandler := connect.NewUnaryHandler( + NodeMetricsServiceReportNodeMetricsProcedure, + svc.ReportNodeMetrics, + connect.WithSchema(nodeMetricsServiceMethods.ByName("ReportNodeMetrics")), + connect.WithHandlerOptions(opts...), + ) + return "/v1.NodeMetricsService/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case NodeMetricsServiceReportNodeMetricsProcedure: + nodeMetricsServiceReportNodeMetricsHandler.ServeHTTP(w, r) + default: + http.NotFound(w, r) + } + }) +} + +// UnimplementedNodeMetricsServiceHandler returns CodeUnimplemented from all methods. +type UnimplementedNodeMetricsServiceHandler struct{} + +func (UnimplementedNodeMetricsServiceHandler) ReportNodeMetrics(context.Context, *connect.Request[v1.ReportNodeMetricsRequest]) (*connect.Response[v1.ReportNodeMetricsResponse], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("v1.NodeMetricsService.ReportNodeMetrics is not implemented")) +} diff --git a/v1/mu.proto b/v1/mu.proto index 8a12c58..3b1e144 100644 --- a/v1/mu.proto +++ b/v1/mu.proto @@ -2,6 +2,7 @@ syntax = "proto3"; package v1; // import "validate/validate.proto"; +import "v1/node_metrics.proto"; option go_package = "github.com/icebase/mu/proto/v1"; @@ -11,6 +12,12 @@ service MUService { rpc UploadTrafficLog(UploadTrafficLogRequest) returns (UploadTrafficLogResponse) {} } +service NodeMetricsService { + // Authenticate the node and durably accept a batch before acknowledging it. + // Repeated submissions of the same (node_id, batch_id) succeed without inserting duplicates. + rpc ReportNodeMetrics(ReportNodeMetricsRequest) returns (ReportNodeMetricsResponse) {} +} + message GetUsersRequest { string node_id = 1; } diff --git a/v1/node_metrics.proto b/v1/node_metrics.proto new file mode 100644 index 0000000..e00dc7d --- /dev/null +++ b/v1/node_metrics.proto @@ -0,0 +1,44 @@ +syntax = "proto3"; +package v1; + +option go_package = "github.com/icebase/mu/proto/v1"; + +message ReportNodeMetricsRequest { + string node_id = 1; + string batch_id = 2; + repeated V2FlyBackendSnapshot backends = 3; +} + +message ReportNodeMetricsResponse {} + +message V2FlyBackendSnapshot { + // The configured gRPC address, scoped to this node. + string backend = 1; + int64 sampled_at_unix_millis = 2; + // False means collection failed. Runtime and traffic are then absent. + bool up = 3; + V2FlyRuntimeStats runtime = 4; + repeated V2FlyTrafficCounter traffic = 5; +} + +message V2FlyRuntimeStats { + uint32 uptime_seconds = 1; + uint32 goroutines = 2; + uint64 heap_alloc_bytes = 3; + uint64 total_alloc_bytes = 4; + uint64 runtime_sys_bytes = 5; + uint64 mallocs = 6; + uint64 frees = 7; + uint32 gc_cycles = 8; + uint64 gc_pause_total_nanoseconds = 9; +} + +message V2FlyTrafficCounter { + // inbound or outbound + string dimension = 1; + string tag = 2; + // uplink or downlink + string direction = 3; + // Cumulative bytes from this backend process. May reset on restart. + uint64 bytes = 4; +}