-
Notifications
You must be signed in to change notification settings - Fork 0
/
health_checker.go
65 lines (57 loc) · 1.34 KB
/
health_checker.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
package kafka
import (
"context"
"github.com/segmentio/kafka-go"
"time"
)
type HealthChecker struct {
Brokers []string
Service string
Timeout int64
}
func NewHealthChecker(brokers []string, options ...string) *HealthChecker {
var name string
if len(options) > 0 && len(options[0]) > 0 {
name = options[0]
} else {
name = "kafka"
}
return NewKafkaHealthChecker(brokers, name, 4)
}
func NewKafkaHealthChecker(brokers []string, name string, timeouts ...int64) *HealthChecker {
var timeout int64
if len(timeouts) >= 1 {
timeout = timeouts[0]
} else {
timeout = 4
}
return &HealthChecker{Brokers: brokers, Service: name, Timeout: timeout}
}
func (s *HealthChecker) Name() string {
return s.Service
}
func (s *HealthChecker) Check(ctx context.Context) (map[string]interface{}, error) {
res := make(map[string]interface{})
dialer := &kafka.Dialer{
Timeout: time.Duration(s.Timeout) * time.Second,
DualStack: true,
}
for _, broker := range s.Brokers {
conn, err := dialer.DialContext(ctx, "tcp", broker)
if err != nil {
return res, err
}
conn.Close()
}
return res, nil
}
func (s *HealthChecker) Build(ctx context.Context, data map[string]interface{}, err error) map[string]interface{} {
if err == nil {
return data
}
if data == nil {
data = make(map[string]interface{}, 0)
}
data["error"] = err.Error()
return data
}