使用 Golang 执行 Kafka 的监控任务

Kafka 是一个高吞吐量、可扩展的分布式消息系统,广泛应用于实时数据流处理场景。监控 Kafka 是确保其平稳运行和及时处理问题的关键。本文将介绍如何使用 Golang 来执行 Kafka 的监控任务。

前置准备

安装依赖库:

1
2
3
4
5
6
7

# 安装 Sarama,用于 Kafka 的操作
$ go get github.com/Shopify/sarama

# 安装 Kafka 管理扩展
$ go get github.com/twmb/franz-go

功能实现

在 Kafka 监控中,以下核心指标是需要重点关注的:

1
2
3
4
5
6
7
8
9

1.集群健康状态:包括 Broker 的数量和可用性。

2.消费延迟:每个主题分区的最新和最早偏移量的差值。

3.消费者组状态:确保消费者组处于稳定状态,成员无频繁变动。

4.消息积压:某些分区可能因为消费者问题导致消息堆积。

1. 核心监控指标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 监控指标结构体
type KafkaMetrics struct {
// 消费者组指标
ConsumerGroupLag int64 // 消费延迟
ConsumerGroupMembers int // 消费者组成员数
LastConsumeTimestamp int64 // 最后消费时间

// 主题分区指标
PartitionSize int64 // 分区大小
MessageCount int64 // 消息数量
FirstOffset int64 // 起始偏移量
LastOffset int64 // 最新偏移量

// Broker 指标
BrokerStatus bool // Broker 存活状态
UnderReplicatedPartitions int // 未同步的副本数

// 性能指标
ProduceRequestsPerSec float64 // 生产请求QPS
ConsumeRequestsPerSec float64 // 消费请求QPS
NetworkProcessorAvgIdlePercent float64 // 网络处理器空闲比例
}

2.实现完整的监控系统

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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package main

import (
"context"
"encoding/json"
"fmt"
"log"
"sync"
"time"

"github.com/Shopify/sarama"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)

// 监控配置
type MonitorConfig struct {
BrokerList []string
Topics []string
ConsumerGroup string
Interval time.Duration
}

// Kafka 监控器
type KafkaMonitor struct {
config *MonitorConfig
client sarama.Client
admin sarama.ClusterAdmin
metrics *KafkaMetrics
prometheus *PrometheusMetrics
mu sync.RWMutex
}

// Prometheus 指标
type PrometheusMetrics struct {
consumerLag *prometheus.GaugeVec
consumerThroughput *prometheus.GaugeVec
topicSize *prometheus.GaugeVec
errorCount *prometheus.CounterVec
}

// 初始化 Prometheus 指标
func initPrometheusMetrics() *PrometheusMetrics {
return &PrometheusMetrics{
consumerLag: promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "kafka_consumer_lag",
Help: "Kafka consumer lag in messages",
},
[]string{"topic", "partition", "consumer_group"},
),
consumerThroughput: promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "kafka_consumer_throughput",
Help: "Kafka consumer throughput in messages/sec",
},
[]string{"topic", "consumer_group"},
),
topicSize: promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "kafka_topic_size",
Help: "Kafka topic size in bytes",
},
[]string{"topic"},
),
errorCount: promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "kafka_monitor_errors_total",
Help: "Total number of monitoring errors",
},
[]string{"type"},
),
}
}

// 创建新的监控器
func NewKafkaMonitor(config *MonitorConfig) (*KafkaMonitor, error) {
// 创建 Kafka 客户端配置
conf := sarama.NewConfig()
conf.Version = sarama.V2_4_0_0

// 创建 Kafka 客户端
client, err := sarama.NewClient(config.BrokerList, conf)
if err != nil {
return nil, fmt.Errorf("failed to create client: %v", err)
return nil, fmt.Errorf("failed to create admin client: %v", err)
}

// 创建 Kafka 管理客户端
admin, err := sarama.NewClusterAdmin(config.BrokerList, conf)
if err != nil {
return nil, fmt.Errorf("failed to create admin client: %v", err)
}

return &KafkaMonitor{
config: config,
client: client,
admin: admin,
metrics: &KafkaMetrics{},
prometheus: initPrometheusMetrics(),
}, nil
}

// 监控消费者延迟
func (km *KafkaMonitor) monitorConsumerLag(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
for _, topic := range km.config.Topics {
partitions, err := km.client.Partitions(topic)
if err != nil {
km.prometheus.errorCount.WithLabelValues("consumer_lag").Inc()
continue
}

for _, partition := range partitions {
// 获取最新偏移量
latestOffset, err := km.client.GetOffset(topic, partition, sarama.OffsetNewest)
if err != nil {
continue
}

// 获取消费者偏移量
offset, err := km.admin.ListConsumerGroupOffsets(km.config.ConsumerGroup, map[string][]int32{
topic: {partition},
})
if err != nil {
continue
}

// 计算延迟
block := offset.Blocks[topic][partition]
lag := latestOffset - block.Offset

// 更新 Prometheus 指标
km.prometheus.consumerLag.WithLabelValues(
topic,
fmt.Sprintf("%d", partition),
km.config.ConsumerGroup,
).Set(float64(lag))

// 更新内部指标
km.mu.Lock()
km.metrics.ConsumerLag = lag
km.mu.Unlock()
}
}
time.Sleep(km.config.Interval)
}
}
}

// 监控主题大小和消息数量
func (km *KafkaMonitor) monitorTopicMetrics(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
for _, topic := range km.config.Topics {
// 获取主题详情
topicDetails, err := km.admin.DescribeTopics([]string{topic})
if err != nil {
km.prometheus.errorCount.WithLabelValues("topic_metrics").Inc()
continue
}

var totalSize int64
var messageCount int64

// 计算主题大小和消息数量
for _, detail := range topicDetails {
for _, partition := range detail.Partitions {
newest, err := km.client.GetOffset(topic, partition.ID, sarama.OffsetNewest)
if err != nil {
continue
}
oldest, err := km.client.GetOffset(topic, partition.ID, sarama.OffsetOldest)
if err != nil {
continue
}
messageCount += newest - oldest
}
}

// 更新 Prometheus 指标
km.prometheus.topicSize.WithLabelValues(topic).Set(float64(totalSize))

// 更新内部指标
km.mu.Lock()
km.metrics.TopicSize = totalSize
km.metrics.MessageCount = messageCount
km.metrics.LastUpdateTime = time.Now()
km.mu.Unlock()
}
time.Sleep(km.config.Interval)
}
}
}

// HTTP 处理器 - 返回监控指标
func (km *KafkaMonitor) metricsHandler(w http.ResponseWriter, r *http.Request) {
km.mu.RLock()
defer km.mu.RUnlock()

response, err := json.Marshal(km.metrics)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
type MonitorWorkerPool struct {
workers int
tasks chan MonitorTask
}

func NewMonitorWorkerPool(workers int) *MonitorWorkerPool {
return &MonitorWorkerPool{
workers: workers,
tasks: make(chan MonitorTask, workers*2),
}
}

func (p *MonitorWorkerPool) Start() {
for i := 0; i < p.workers; i++ {
go p.worker()
}
}

func (p *MonitorWorkerPool) worker() {
for task := range p.tasks {
task.Execute()
}
}

type AutoScaler struct {
metrics *KafkaMetrics
scaleThreshold float64
cooldownPeriod time.Duration
lastScaleTime time.Time
}

func (as *AutoScaler) CheckAndScale() {
if time.Since(as.lastScaleTime) < as.cooldownPeriod {
return
}

w.Header().Set("Content-Type", "application/json")
w.Write(response)
if as.metrics.ConsumerLag > int64(as.scaleThreshold) {
as.scaleOut()
} else if as.metrics.ConsumerLag < int64(as.scaleThreshold/2) {
as.scaleIn()
}
}

// 启动监控服务
type SmartAlert struct {
history []Alert
threshold map[string]float64
correlation map[string][]string
func NewMonitorWorkerPool(workers int) *MonitorWorkerPool {
return &MonitorWorkerPool{
workers: workers,
tasks: make(chan MonitorTask, workers*2),
}
sa.adjustThresholds()
func (as *AutoScaler) CheckAndScale() {
if time.Since(as.lastScaleTime) < as.cooldownPeriod {
return
}
Topics: []string{"important-topic"},
ConsumerGroup: "monitor-group",
Interval: time.Second * 30,
}

monitor, err := NewKafkaMonitor(config)
if err != nil {
log.Fatalf("Failed to create Kafka monitor: %v", err)
}

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// 启动监控 goroutines
go monitor.monitorConsumerLag(ctx)
go monitor.monitorTopicMetrics(ctx)

// 设置 HTTP 处理器
http.HandleFunc("/metrics/kafka", monitor.metricsHandler)
http.Handle("/metrics", promhttp.Handler()) // Prometheus metrics endpoint
http.Handle("/metrics", promhttp.Handler())

// 启动 HTTP 服务
log.Fatal(http.ListenAndServe(":8080", nil))
}

3.告警集成

在监控系统中,告警集成是一个重要的组成部分,它可以帮助我们及时发现和解决问题。在 Kafka 监控中,告警集成可以通过多种方式实现,例如:

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
// 告警配置
type AlertConfig struct {
EnableEmail bool
EnableSlack bool
EnableWebhook bool
AlertThreshold struct {
ConsumerLag int64
ErrorCount int64
ResponseTime float64
}
}

// 告警管理器
type AlertManager struct {
config AlertConfig
clients map[string]AlertClient
}

// 告警客户端接口
type AlertClient interface {
Send(alert Alert) error
}

// 告警信息
type Alert struct {
Level string
Title string
Description string
Timestamp time.Time
MetricName string
Value float64
}

// 实现邮件告警
type EmailAlert struct {
smtpConfig smtp.Config
}

func (ea *EmailAlert) Send(alert Alert) error {
// 实现邮件发送逻辑
return nil
}

// 实现 Slack 告警
type SlackAlert struct {
webhookURL string
}

func (sa *SlackAlert) Send(alert Alert) error {
// 实现 Slack 通知逻辑
return nil
}

// 检查和发送告警
func (km *KafkaMonitor) checkAndSendAlerts() {
km.mu.RLock()
metrics := *km.metrics
km.mu.RUnlock()

// 检查消费延迟告警
if metrics.ConsumerLag > km.alertConfig.AlertThreshold.ConsumerLag {
alert := Alert{
Level: "WARNING",
Title: "High Consumer Lag Detected",
Description: fmt.Sprintf("Consumer lag is %d messages", metrics.ConsumerLag),
Timestamp: time.Now(),
MetricName: "consumer_lag",
Value: float64(metrics.ConsumerLag),
}

km.alertManager.SendAlert(alert)
}

// 检查错误数量告警
if metrics.ErrorCount > km.alertConfig.AlertThreshold.ErrorCount {
alert := Alert{
Level: "ERROR",
Title: "High Error Count Detected",
Description: fmt.Sprintf("Error count is %d", metrics.ErrorCount),
Timestamp: time.Now(),
MetricName: "error_count",
Value: float64(metrics.ErrorCount),
}

km.alertManager.SendAlert(alert)
}

// 检查响应时间告警
if metrics.ResponseTime > km.alertConfig.AlertThreshold.ResponseTime {
alert := Alert{
Level: "WARNING",
Title: "High Response Time Detected",
Description: fmt.Sprintf("Response time is %.2f seconds", metrics.ResponseTime),
Timestamp: time.Now(),
MetricName: "response_time",
Value: metrics.ResponseTime,
}

km.alertManager.SendAlert(alert)
}
}

版权声明

  • 本文作者: PFinal南丞
  • 本文链接:
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

相关阅读