-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
partition.go
324 lines (273 loc) · 6.54 KB
/
partition.go
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package partition
import (
"errors"
"fmt"
"io"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs"
"github.com/elastic/beats/metricbeat/mb"
"github.com/elastic/beats/metricbeat/mb/parse"
"github.com/Shopify/sarama"
)
// init registers the partition MetricSet with the central registry.
func init() {
if err := mb.Registry.AddMetricSet("kafka", "partition", New, parse.PassThruHostParser); err != nil {
panic(err)
}
}
// MetricSet type defines all fields of the partition MetricSet
type MetricSet struct {
mb.BaseMetricSet
broker *sarama.Broker
cfg *sarama.Config
id int32
topics []string
}
var noID int32 = -1
var errFailQueryOffset = errors.New("operation failed")
// New create a new instance of the partition MetricSet
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
config := defaultConfig
if err := base.Module().UnpackConfig(&config); err != nil {
return nil, err
}
tls, err := outputs.LoadTLSConfig(config.TLS)
if err != nil {
return nil, err
}
cfg := sarama.NewConfig()
cfg.Net.DialTimeout = base.Module().Config().Timeout
cfg.Net.ReadTimeout = base.Module().Config().Timeout
cfg.ClientID = config.ClientID
cfg.Metadata.Retry.Max = config.Retries
cfg.Metadata.Retry.Backoff = config.Backoff
if tls != nil {
cfg.Net.TLS.Enable = true
cfg.Net.TLS.Config = tls.BuildModuleConfig("")
}
if config.Username != "" {
cfg.Net.SASL.Enable = true
cfg.Net.SASL.User = config.Username
cfg.Net.SASL.Password = config.Password
}
broker := sarama.NewBroker(base.Host())
return &MetricSet{
BaseMetricSet: base,
broker: broker,
cfg: cfg,
id: noID,
topics: config.Topics,
}, nil
}
func (m *MetricSet) connect() (*sarama.Broker, error) {
b := m.broker
if err := b.Open(m.cfg); err != nil {
return nil, err
}
if m.id != noID {
return b, nil
}
// current broker is bootstrap only. Get metadata to find id:
meta, err := queryMetadataWithRetry(b, m.cfg, m.topics)
if err != nil {
closeBroker(b)
return nil, err
}
addr := b.Addr()
for _, other := range meta.Brokers {
if other.Addr() == addr {
m.id = other.ID()
break
}
}
if m.id == noID {
closeBroker(b)
err = fmt.Errorf("No advertised broker with address %v found", addr)
return nil, err
}
return b, nil
}
// Fetch partition stats list from kafka
func (m *MetricSet) Fetch() ([]common.MapStr, error) {
b, err := m.connect()
if err != nil {
return nil, err
}
defer closeBroker(b)
response, err := queryMetadataWithRetry(b, m.cfg, m.topics)
if err != nil {
return nil, err
}
events := []common.MapStr{}
evtBroker := common.MapStr{
"id": m.id,
"address": b.Addr(),
}
for _, topic := range response.Topics {
evtTopic := common.MapStr{
"name": topic.Name,
}
if topic.Err != 0 {
evtTopic["error"] = common.MapStr{
"code": topic.Err,
}
}
for _, partition := range topic.Partitions {
// partition offsets can be queried from leader only
if m.id != partition.Leader {
continue
}
// collect offsets for all replicas
for _, id := range partition.Replicas {
// Get oldest and newest available offsets
offOldest, offNewest, offOK, err := queryOffsetRange(b, id, topic.Name, partition.ID)
if !offOK {
if err == nil {
err = errFailQueryOffset
}
logp.Err("Failed to query kafka partition (%v:%v) offsets: %v",
topic.Name, partition.ID, err)
continue
}
partitionEvent := common.MapStr{
"id": partition.ID,
"leader": partition.Leader,
"replica": id,
"insync_replica": hasID(id, partition.Isr),
}
if partition.Err != 0 {
partitionEvent["error"] = common.MapStr{
"code": partition.Err,
}
}
// create event
event := common.MapStr{
"topic": evtTopic,
"broker": evtBroker,
"partition": partitionEvent,
"offset": common.MapStr{
"newest": offNewest,
"oldest": offOldest,
},
}
events = append(events, event)
}
}
}
return events, nil
}
func hasID(id int32, lst []int32) bool {
for _, other := range lst {
if id == other {
return true
}
}
return false
}
// queryOffsetRange queries the broker for the oldest and the newest offsets in
// a kafka topics partition for a given replica.
func queryOffsetRange(
b *sarama.Broker,
replicaID int32,
topic string,
partition int32,
) (int64, int64, bool, error) {
oldest, okOld, err := queryOffset(b, replicaID, topic, partition, sarama.OffsetOldest)
if err != nil {
return -1, -1, false, err
}
newest, okNew, err := queryOffset(b, replicaID, topic, partition, sarama.OffsetNewest)
if err != nil {
return -1, -1, false, err
}
return oldest, newest, okOld && okNew, nil
}
func queryOffset(
b *sarama.Broker,
replicaID int32,
topic string,
partition int32,
time int64,
) (int64, bool, error) {
req := &sarama.OffsetRequest{}
if replicaID != noID {
req.SetReplicaID(replicaID)
}
req.AddBlock(topic, partition, time, 1)
resp, err := b.GetAvailableOffsets(req)
if err != nil {
return -1, false, err
}
block := resp.GetBlock(topic, partition)
if len(block.Offsets) == 0 {
return -1, false, nil
}
return block.Offsets[0], true, nil
}
func closeBroker(b *sarama.Broker) {
if ok, _ := b.Connected(); ok {
b.Close()
}
}
func queryMetadataWithRetry(
b *sarama.Broker,
cfg *sarama.Config,
topics []string,
) (r *sarama.MetadataResponse, err error) {
err = withRetry(b, cfg, func() (e error) {
r, e = b.GetMetadata(&sarama.MetadataRequest{topics})
return
})
return
}
func withRetry(
b *sarama.Broker,
cfg *sarama.Config,
f func() error,
) error {
var err error
for max := 0; max < cfg.Metadata.Retry.Max; max++ {
if ok, _ := b.Connected(); !ok {
if err = b.Open(cfg); err == nil {
err = f()
}
} else {
err = f()
}
if err == nil {
return nil
}
retry, reconnect := checkRetryQuery(err)
if !retry {
return err
}
time.Sleep(cfg.Metadata.Retry.Backoff)
if reconnect {
closeBroker(b)
}
}
return err
}
func checkRetryQuery(err error) (retry, reconnect bool) {
if err == nil {
return false, false
}
if err == io.EOF {
return true, true
}
k, ok := err.(sarama.KError)
if !ok {
return false, false
}
switch k {
case sarama.ErrLeaderNotAvailable, sarama.ErrReplicaNotAvailable,
sarama.ErrOffsetsLoadInProgress, sarama.ErrRebalanceInProgress:
return true, false
case sarama.ErrRequestTimedOut, sarama.ErrBrokerNotAvailable,
sarama.ErrNetworkException:
return true, true
}
return false, false
}