aboutsummaryrefslogtreecommitdiff
path: root/weed/mq/kafka/protocol/metrics.go
blob: b4bcd98dd4ad7274d63a5830753359c04a7f0cdf (plain)
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package protocol

import (
	"sync"
	"sync/atomic"
	"time"
)

// Metrics tracks basic request/error/latency statistics for Kafka protocol operations
type Metrics struct {
	// Request counters by API key
	requestCounts map[uint16]*int64
	errorCounts   map[uint16]*int64

	// Latency tracking
	latencySum   map[uint16]*int64 // Total latency in microseconds
	latencyCount map[uint16]*int64 // Number of requests for average calculation

	// Connection metrics
	activeConnections int64
	totalConnections  int64

	// Mutex for map operations
	mu sync.RWMutex

	// Start time for uptime calculation
	startTime time.Time
}

// APIMetrics represents metrics for a specific API
type APIMetrics struct {
	APIKey       uint16  `json:"api_key"`
	APIName      string  `json:"api_name"`
	RequestCount int64   `json:"request_count"`
	ErrorCount   int64   `json:"error_count"`
	AvgLatencyMs float64 `json:"avg_latency_ms"`
}

// ConnectionMetrics represents connection-related metrics
type ConnectionMetrics struct {
	ActiveConnections int64     `json:"active_connections"`
	TotalConnections  int64     `json:"total_connections"`
	UptimeSeconds     int64     `json:"uptime_seconds"`
	StartTime         time.Time `json:"start_time"`
}

// MetricsSnapshot represents a complete metrics snapshot
type MetricsSnapshot struct {
	APIs        []APIMetrics      `json:"apis"`
	Connections ConnectionMetrics `json:"connections"`
	Timestamp   time.Time         `json:"timestamp"`
}

// NewMetrics creates a new metrics tracker
func NewMetrics() *Metrics {
	return &Metrics{
		requestCounts: make(map[uint16]*int64),
		errorCounts:   make(map[uint16]*int64),
		latencySum:    make(map[uint16]*int64),
		latencyCount:  make(map[uint16]*int64),
		startTime:     time.Now(),
	}
}

// RecordRequest records a successful request with latency
func (m *Metrics) RecordRequest(apiKey uint16, latency time.Duration) {
	m.ensureCounters(apiKey)

	atomic.AddInt64(m.requestCounts[apiKey], 1)
	atomic.AddInt64(m.latencySum[apiKey], latency.Microseconds())
	atomic.AddInt64(m.latencyCount[apiKey], 1)
}

// RecordError records an error for a specific API
func (m *Metrics) RecordError(apiKey uint16, latency time.Duration) {
	m.ensureCounters(apiKey)

	atomic.AddInt64(m.requestCounts[apiKey], 1)
	atomic.AddInt64(m.errorCounts[apiKey], 1)
	atomic.AddInt64(m.latencySum[apiKey], latency.Microseconds())
	atomic.AddInt64(m.latencyCount[apiKey], 1)
}

// RecordConnection records a new connection
func (m *Metrics) RecordConnection() {
	atomic.AddInt64(&m.activeConnections, 1)
	atomic.AddInt64(&m.totalConnections, 1)
}

// RecordDisconnection records a connection closure
func (m *Metrics) RecordDisconnection() {
	atomic.AddInt64(&m.activeConnections, -1)
}

// GetSnapshot returns a complete metrics snapshot
func (m *Metrics) GetSnapshot() MetricsSnapshot {
	m.mu.RLock()
	defer m.mu.RUnlock()

	apis := make([]APIMetrics, 0, len(m.requestCounts))

	for apiKey, requestCount := range m.requestCounts {
		requests := atomic.LoadInt64(requestCount)
		errors := atomic.LoadInt64(m.errorCounts[apiKey])
		latencySum := atomic.LoadInt64(m.latencySum[apiKey])
		latencyCount := atomic.LoadInt64(m.latencyCount[apiKey])

		var avgLatencyMs float64
		if latencyCount > 0 {
			avgLatencyMs = float64(latencySum) / float64(latencyCount) / 1000.0 // Convert to milliseconds
		}

		apis = append(apis, APIMetrics{
			APIKey:       apiKey,
			APIName:      getAPIName(APIKey(apiKey)),
			RequestCount: requests,
			ErrorCount:   errors,
			AvgLatencyMs: avgLatencyMs,
		})
	}

	return MetricsSnapshot{
		APIs: apis,
		Connections: ConnectionMetrics{
			ActiveConnections: atomic.LoadInt64(&m.activeConnections),
			TotalConnections:  atomic.LoadInt64(&m.totalConnections),
			UptimeSeconds:     int64(time.Since(m.startTime).Seconds()),
			StartTime:         m.startTime,
		},
		Timestamp: time.Now(),
	}
}

// GetAPIMetrics returns metrics for a specific API
func (m *Metrics) GetAPIMetrics(apiKey uint16) APIMetrics {
	m.ensureCounters(apiKey)

	requests := atomic.LoadInt64(m.requestCounts[apiKey])
	errors := atomic.LoadInt64(m.errorCounts[apiKey])
	latencySum := atomic.LoadInt64(m.latencySum[apiKey])
	latencyCount := atomic.LoadInt64(m.latencyCount[apiKey])

	var avgLatencyMs float64
	if latencyCount > 0 {
		avgLatencyMs = float64(latencySum) / float64(latencyCount) / 1000.0
	}

	return APIMetrics{
		APIKey:       apiKey,
		APIName:      getAPIName(APIKey(apiKey)),
		RequestCount: requests,
		ErrorCount:   errors,
		AvgLatencyMs: avgLatencyMs,
	}
}

// GetConnectionMetrics returns connection-related metrics
func (m *Metrics) GetConnectionMetrics() ConnectionMetrics {
	return ConnectionMetrics{
		ActiveConnections: atomic.LoadInt64(&m.activeConnections),
		TotalConnections:  atomic.LoadInt64(&m.totalConnections),
		UptimeSeconds:     int64(time.Since(m.startTime).Seconds()),
		StartTime:         m.startTime,
	}
}

// Reset resets all metrics (useful for testing)
func (m *Metrics) Reset() {
	m.mu.Lock()
	defer m.mu.Unlock()

	for apiKey := range m.requestCounts {
		atomic.StoreInt64(m.requestCounts[apiKey], 0)
		atomic.StoreInt64(m.errorCounts[apiKey], 0)
		atomic.StoreInt64(m.latencySum[apiKey], 0)
		atomic.StoreInt64(m.latencyCount[apiKey], 0)
	}

	atomic.StoreInt64(&m.activeConnections, 0)
	atomic.StoreInt64(&m.totalConnections, 0)
	m.startTime = time.Now()
}

// ensureCounters ensures that counters exist for the given API key
func (m *Metrics) ensureCounters(apiKey uint16) {
	m.mu.RLock()
	if _, exists := m.requestCounts[apiKey]; exists {
		m.mu.RUnlock()
		return
	}
	m.mu.RUnlock()

	m.mu.Lock()
	defer m.mu.Unlock()

	// Double-check after acquiring write lock
	if _, exists := m.requestCounts[apiKey]; exists {
		return
	}

	m.requestCounts[apiKey] = new(int64)
	m.errorCounts[apiKey] = new(int64)
	m.latencySum[apiKey] = new(int64)
	m.latencyCount[apiKey] = new(int64)
}

// Global metrics instance
var globalMetrics = NewMetrics()

// GetGlobalMetrics returns the global metrics instance
func GetGlobalMetrics() *Metrics {
	return globalMetrics
}

// RecordRequestMetrics is a convenience function to record request metrics globally
func RecordRequestMetrics(apiKey uint16, latency time.Duration) {
	globalMetrics.RecordRequest(apiKey, latency)
}

// RecordErrorMetrics is a convenience function to record error metrics globally
func RecordErrorMetrics(apiKey uint16, latency time.Duration) {
	globalMetrics.RecordError(apiKey, latency)
}

// RecordConnectionMetrics is a convenience function to record connection metrics globally
func RecordConnectionMetrics() {
	globalMetrics.RecordConnection()
}

// RecordDisconnectionMetrics is a convenience function to record disconnection metrics globally
func RecordDisconnectionMetrics() {
	globalMetrics.RecordDisconnection()
}