-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
270 lines (226 loc) · 6 KB
/
client.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
package graphite
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/url"
"os"
"strings"
"time"
)
const (
// DefaultMaxBufferSize is the default maximum number of metrics to buffer
// before sending them to the Graphite server.
DefaultMaxBufferSize = 1000
// DefaultMaxMetricsPerMessage is the default maximum number of metrics to
// send to the Graphite server in a single request.
DefaultMaxMetricsPerMessage = 1
// DefaultMaxTries is the default maximum number of times to try sending
// metrics to the Graphite server.
DefaultMaxTries = 3
)
var (
// ErrNoAddress is returned when no server address is specified for the
// Graphite client.
ErrNoAddress = errors.New(
"graphite: no address specified for Graphite server",
)
)
// Client is the interface defining a Graphite client.
type Client interface {
// SendMetric sends a metric to the Graphite server.
SendMetric(ctx context.Context,
metric MetricMetadata,
value string,
timestamp time.Time,
) error
// Submit submits the queued metrics to the Graphite server.
Submit(ctx context.Context) error
}
type clientOptions struct {
// The maximum number of metrics to buffer before sending them to the
// Graphite server.
MaxBufferSize int
// The maximum number of metrics to send to the Graphite server in a single
// request.
MaxMetricsPerMessage int
// The maximum number of times to retry sending metrics to the Graphite
// server.
MaxTries int
// The connection to use when sending metrics to the Graphite server.
Conn net.Conn
// The address of the Graphite server. This is used if [Conn] is not set.
Addr url.URL
}
// ClientOption represents an option that can be set on the Graphite client.
type ClientOption func(c *clientOptions)
// WithMaxBufferSize sets the maximum number of metrics to buffer before
// sending them to the Graphite server.
func WithMaxBufferSize(maxBufferSize int) ClientOption {
return func(c *clientOptions) {
c.MaxBufferSize = maxBufferSize
}
}
// WithMaxMetricsPerMessage sets the maximum number of metrics to send to the
// Graphite server in a single request.
func WithMaxMetricsPerMessage(maxMetricsPerMessage int) ClientOption {
return func(c *clientOptions) {
c.MaxMetricsPerMessage = maxMetricsPerMessage
}
}
// WithMaxTries sets the maximum number of times to retry sending metrics to
// the Graphite server.
func WithMaxTries(maxTries int) ClientOption {
return func(c *clientOptions) {
c.MaxTries = maxTries
}
}
// WithConnection sets the connection to use when sending metrics to the
// Graphite server.
func WithConnection(conn net.Conn) ClientOption {
return func(c *clientOptions) {
c.Conn = conn
}
}
// WithAddress sets the address of the Graphite server. This is used if
// [Conn] is not set.
func WithAddress(addr url.URL) ClientOption {
return func(c *clientOptions) {
c.Addr = addr
}
}
func (c *clientOptions) setDefaults(ctx context.Context) error {
if c.MaxBufferSize == 0 {
c.MaxBufferSize = DefaultMaxBufferSize
}
if c.MaxMetricsPerMessage == 0 {
c.MaxMetricsPerMessage = DefaultMaxMetricsPerMessage
}
if c.MaxTries == 0 {
c.MaxTries = DefaultMaxTries
}
if c.Conn == nil {
if c.Addr.Host == "" {
return ErrNoAddress
}
var err error
switch c.Addr.Scheme {
case "tls":
c.Conn, err = tls.Dial("tcp", c.Addr.Host, nil)
if err != nil {
return fmt.Errorf(
"graphite: failed to connect to TLS endpoint: %w",
err,
)
}
default:
// Assume TCP endpoint.
fallthrough
case "tcp":
c.Conn, err = net.Dial("tcp", c.Addr.Host)
if err != nil {
return fmt.Errorf(
"graphite: failed to connect to TCP endpoint: %w",
err,
)
}
}
}
return nil
}
type client struct {
clientOptions
queuedMetrics chan Metric
}
var _ Client = &client{}
// NewClient creates a new Graphite client.
func NewClient(ctx context.Context, opts ...ClientOption) (Client, error) {
clientOptions := clientOptions{}
for _, opt := range opts {
opt(&clientOptions)
}
if err := clientOptions.setDefaults(ctx); err != nil {
return nil, err
}
return &client{
clientOptions: clientOptions,
queuedMetrics: make(chan Metric, clientOptions.MaxBufferSize),
}, nil
}
// Submit submits the queued metrics to the Graphite server.
func (c *client) Submit(ctx context.Context) error {
go func() {
io.Copy(os.Stderr, c.Conn)
}()
for {
metricStrings := make([]string, 0, c.MaxMetricsPerMessage)
select {
case metric := <-c.queuedMetrics:
metricStrings = append(metricStrings, metric.String())
case <-ctx.Done():
return fmt.Errorf(
"graphite: context cancelled while submitting: %w",
ctx.Err(),
)
}
furtherMetrics := true
for i := 1; furtherMetrics && i < c.MaxMetricsPerMessage; i++ {
select {
case metric := <-c.queuedMetrics:
metricStrings = append(metricStrings, metric.String())
case <-ctx.Done():
return fmt.Errorf(
"graphite: context cancelled while submitting: %w",
ctx.Err(),
)
default:
furtherMetrics = false
}
}
if err := c.SubmitMetricsString(
ctx,
strings.Join(metricStrings, "\n"),
); err != nil {
return fmt.Errorf("graphite: failed to submit metrics: %w", err)
}
}
}
// SubmitMetricsString submits the given metrics string to the Graphite server, retrying for [c.MaxTries] times.
func (c *client) SubmitMetricsString(ctx context.Context, str string) (err error) {
// Ensure line termination.
if !strings.HasSuffix(str, "\n") {
str += "\n"
}
for i := 0; i < c.MaxTries; i++ {
if _, err = c.Conn.Write([]byte(str)); err == nil {
return nil
}
}
return fmt.Errorf(
"graphite: failed to send metrics after %d tries: %w",
c.MaxTries,
err,
)
}
// SendMetric sends a metric to the configured metric server.
func (c *client) SendMetric(
ctx context.Context,
metric MetricMetadata,
value string,
timestamp time.Time,
) error {
queuedMetric := Metric{
MetricMetadata: metric,
Value: value,
Timestamp: timestamp,
}
select {
case c.queuedMetrics <- queuedMetric:
return nil
case <-ctx.Done():
return ctx.Err()
}
}