~bigbes/shroud

ref: 321879085cefec9f799abe941b2b76b17ad4a1db shroud/internal/metrics/collector.go -rw-r--r-- 5.0 KiB
32187908 — Eugene Blikh refactor: rename Go module to go.bigb.es/shroud a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package metrics

import (
	"log/slog"
	"net"
	"sync"
	"time"

	"golang.getoutline.org/tunnel-server/ipinfo"
	outline_prometheus "golang.getoutline.org/tunnel-server/prometheus"
	"golang.getoutline.org/tunnel-server/service"
	svcmetrics "golang.getoutline.org/tunnel-server/service/metrics"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
)

// ServerMetrics tracks server-level Prometheus metrics.
type ServerMetrics struct {
	buildInfo         *prometheus.GaugeVec
	accessKeys        prometheus.Gauge
	ports             prometheus.Gauge
	addedNatEntries   prometheus.Counter
	removedNatEntries prometheus.Counter
}

var _ prometheus.Collector = (*ServerMetrics)(nil)
var _ service.NATMetrics = (*ServerMetrics)(nil)

func NewServerMetrics() *ServerMetrics {
	return &ServerMetrics{
		buildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Name: "build_info",
			Help: "Information on the shroud build",
		}, []string{"version"}),
		accessKeys: prometheus.NewGauge(prometheus.GaugeOpts{
			Name: "keys",
			Help: "Count of access keys",
		}),
		ports: prometheus.NewGauge(prometheus.GaugeOpts{
			Name: "ports",
			Help: "Count of open ports",
		}),
		addedNatEntries: prometheus.NewCounter(prometheus.CounterOpts{
			Subsystem: "udp",
			Name:      "nat_entries_added",
			Help:      "Entries added to the UDP NAT table",
		}),
		removedNatEntries: prometheus.NewCounter(prometheus.CounterOpts{
			Subsystem: "udp",
			Name:      "nat_entries_removed",
			Help:      "Entries removed from the UDP NAT table",
		}),
	}
}

func (m *ServerMetrics) Describe(ch chan<- *prometheus.Desc) {
	m.buildInfo.Describe(ch)
	m.accessKeys.Describe(ch)
	m.ports.Describe(ch)
	m.addedNatEntries.Describe(ch)
	m.removedNatEntries.Describe(ch)
}

func (m *ServerMetrics) Collect(ch chan<- prometheus.Metric) {
	m.buildInfo.Collect(ch)
	m.accessKeys.Collect(ch)
	m.ports.Collect(ch)
	m.addedNatEntries.Collect(ch)
	m.removedNatEntries.Collect(ch)
}

func (m *ServerMetrics) SetVersion(version string) {
	m.buildInfo.WithLabelValues(version).Set(1)
}

func (m *ServerMetrics) SetNumAccessKeys(numKeys int, ports int) {
	m.accessKeys.Set(float64(numKeys))
	m.ports.Set(float64(ports))
}

func (m *ServerMetrics) AddNATEntry()    { m.addedNatEntries.Inc() }
func (m *ServerMetrics) RemoveNATEntry() { m.removedNatEntries.Inc() }

// TransferTracker wraps ServiceMetrics to also track per-key byte transfer
// for the REST API's /metrics/transfer endpoint.
type TransferTracker struct {
	service.ServiceMetrics
	mu       sync.Mutex
	transfer map[string]int64 // key ID -> cumulative outbound bytes
}

func NewTransferTracker(inner service.ServiceMetrics) *TransferTracker {
	return &TransferTracker{
		ServiceMetrics: inner,
		transfer:       make(map[string]int64),
	}
}

func (t *TransferTracker) AddOpenTCPConnection(conn net.Conn) service.TCPConnMetrics {
	inner := t.ServiceMetrics.AddOpenTCPConnection(conn)
	return &trackingTCPConnMetrics{TCPConnMetrics: inner, tracker: t}
}

// GetTransferByKey returns cumulative byte transfer per key and resets counters.
func (t *TransferTracker) GetTransferByKey() map[string]int64 {
	t.mu.Lock()
	defer t.mu.Unlock()
	result := t.transfer
	t.transfer = make(map[string]int64)
	return result
}

func (t *TransferTracker) addBytes(keyID string, bytes int64) {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.transfer[keyID] += bytes
}

type trackingTCPConnMetrics struct {
	service.TCPConnMetrics
	tracker   *TransferTracker
	accessKey string
}

func (m *trackingTCPConnMetrics) AddAuthentication(accessKey string) {
	m.accessKey = accessKey
	m.TCPConnMetrics.AddAuthentication(accessKey)
}

func (m *trackingTCPConnMetrics) AddClose(status string, data svcmetrics.ProxyMetrics, duration time.Duration) {
	if m.accessKey != "" {
		m.tracker.addBytes(m.accessKey, data.ProxyTarget+data.TargetProxy)
	}
	m.TCPConnMetrics.AddClose(status, data, duration)
}

// SetupRegistry creates a Prometheus registry with all metric collectors.
func SetupRegistry(
	ip2info ipinfo.IPInfoMap,
	serverMetrics *ServerMetrics,
	version string,
	nodeCollectors []string,
	logger *slog.Logger,
) (*prometheus.Registry, *TransferTracker, *ServerMetrics, error) {
	registry := prometheus.NewRegistry()

	// Go runtime metrics.
	registry.MustRegister(collectors.NewGoCollector())
	registry.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))

	// Shadowsocks service metrics.
	serviceMetrics, err := outline_prometheus.NewServiceMetrics(ip2info)
	if err != nil {
		return nil, nil, nil, err
	}

	serverMetrics.SetVersion(version)

	r := prometheus.WrapRegistererWithPrefix("shadowsocks_", registry)
	r.MustRegister(serverMetrics, serviceMetrics)

	transferTracker := NewTransferTracker(serviceMetrics)

	// Node exporter collectors.
	if len(nodeCollectors) > 0 {
		if err := registerNodeCollectors(registry, logger, nodeCollectors); err != nil {
			logger.Warn("Failed to register node_exporter collectors, continuing without them.", "err", err)
		}
	}

	return registry, transferTracker, serverMetrics, nil
}