-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
scraper.go
218 lines (185 loc) · 5.35 KB
/
scraper.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package zookeeperreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/zookeeperreceiver"
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"regexp"
"strconv"
"time"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/receiver"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/zookeeperreceiver/internal/metadata"
)
var zookeeperFormatRE = regexp.MustCompile(`(^zk_\w+)\s+([\w\.\-]+)`)
const (
mntrCommand = "mntr"
ruokCommand = "ruok"
)
type zookeeperMetricsScraper struct {
logger *zap.Logger
config *Config
cancel context.CancelFunc
rb *metadata.ResourceBuilder
mb *metadata.MetricsBuilder
// For mocking.
closeConnection func(net.Conn) error
setConnectionDeadline func(net.Conn, time.Time) error
sendCmd func(net.Conn, string) (*bufio.Scanner, error)
}
func (z *zookeeperMetricsScraper) Name() string {
return metadata.Type.String()
}
func newZookeeperMetricsScraper(settings receiver.Settings, config *Config) (*zookeeperMetricsScraper, error) {
_, _, err := net.SplitHostPort(config.TCPAddrConfig.Endpoint)
if err != nil {
return nil, err
}
if config.Timeout <= 0 {
return nil, errors.New("timeout must be a positive duration")
}
z := &zookeeperMetricsScraper{
logger: settings.Logger,
config: config,
rb: metadata.NewResourceBuilder(config.ResourceAttributes),
mb: metadata.NewMetricsBuilder(config.MetricsBuilderConfig, settings),
closeConnection: closeConnection,
setConnectionDeadline: setConnectionDeadline,
sendCmd: sendCmd,
}
return z, nil
}
func (z *zookeeperMetricsScraper) shutdown(_ context.Context) error {
if z.cancel != nil {
z.cancel()
z.cancel = nil
}
return nil
}
func (z *zookeeperMetricsScraper) scrape(ctx context.Context) (pmetric.Metrics, error) {
responseMntr, err := z.runCommand(ctx, "mntr")
if err != nil {
return pmetric.NewMetrics(), err
}
responseRuok, err := z.runCommand(ctx, "ruok")
if err != nil {
return pmetric.NewMetrics(), err
}
z.processMntr(responseMntr)
z.processRuok(responseRuok)
return z.mb.Emit(metadata.WithResource(z.rb.Emit())), nil
}
func (z *zookeeperMetricsScraper) runCommand(ctx context.Context, command string) ([]string, error) {
conn, err := z.config.Dial(context.Background())
if err != nil {
z.logger.Error("failed to establish connection",
zap.String("endpoint", z.config.Endpoint),
zap.Error(err),
)
return nil, err
}
defer func() {
if closeErr := z.closeConnection(conn); closeErr != nil {
z.logger.Warn("failed to shutdown connection", zap.Error(closeErr))
}
}()
deadline, ok := ctx.Deadline()
if ok {
if err = z.setConnectionDeadline(conn, deadline); err != nil {
z.logger.Warn("failed to set deadline on connection", zap.Error(err))
}
}
scanner, err := z.sendCmd(conn, command)
if err != nil {
z.logger.Error("failed to send command",
zap.Error(err),
zap.String("command", command),
)
return nil, err
}
var response []string
for scanner.Scan() {
response = append(response, scanner.Text())
}
return response, nil
}
func (z *zookeeperMetricsScraper) processMntr(response []string) {
creator := newMetricCreator(z.mb)
now := pcommon.NewTimestampFromTime(time.Now())
for _, line := range response {
parts := zookeeperFormatRE.FindStringSubmatch(line)
if len(parts) != 3 {
z.logger.Warn("unexpected line in response",
zap.String("command", mntrCommand),
zap.String("line", line),
)
continue
}
metricKey := parts[1]
metricValue := parts[2]
switch metricKey {
case zkVersionKey:
z.rb.SetZkVersion(metricValue)
continue
case serverStateKey:
z.rb.SetServerState(metricValue)
continue
default:
// Skip metric if there is no descriptor associated with it.
recordDataPoints := creator.recordDataPointsFunc(metricKey)
if recordDataPoints == nil {
// Unexported metric, just move to the next line.
continue
}
int64Val, err := strconv.ParseInt(metricValue, 10, 64)
if err != nil {
z.logger.Debug(
fmt.Sprintf("non-integer value from %s", mntrCommand),
zap.String("value", metricValue),
)
continue
}
recordDataPoints(now, int64Val)
}
}
// Generate computed metrics
creator.generateComputedMetrics(z.logger, now)
}
func (z *zookeeperMetricsScraper) processRuok(response []string) {
creator := newMetricCreator(z.mb)
now := pcommon.NewTimestampFromTime(time.Now())
metricKey := "ruok"
metricValue := int64(0)
if len(response) > 0 {
if response[0] == "imok" {
metricValue = int64(1)
} else {
z.logger.Error("invalid response from ruok",
zap.String("command", ruokCommand),
)
return
}
}
recordDataPoints := creator.recordDataPointsFunc(metricKey)
recordDataPoints(now, metricValue)
}
func closeConnection(conn net.Conn) error {
return conn.Close()
}
func setConnectionDeadline(conn net.Conn, deadline time.Time) error {
return conn.SetDeadline(deadline)
}
func sendCmd(conn net.Conn, cmd string) (*bufio.Scanner, error) {
_, err := fmt.Fprintf(conn, "%s\n", cmd)
if err != nil {
return nil, err
}
reader := bufio.NewReader(conn)
scanner := bufio.NewScanner(reader)
return scanner, nil
}