-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
499 lines (447 loc) · 12.1 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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package statshouse
import (
"log"
"sync"
"sync/atomic"
"time"
)
type Client struct {
// logging
logMu sync.Mutex
logF LoggerFunc
logT time.Time // last write time, to reduce # of errors reported
// transport
transportMu sync.RWMutex
app string
env string // if set, will be put into key0/env
network string
addr string
conn netConn
packet
// data
mu sync.RWMutex // taken after [bucket.mu]
w map[metricKey]*bucket
r []*bucket
wn map[metricKeyNamed]*bucket
rn []*bucket
tsUnixSec uint32
maxBucketSize int
// external callbacks
regularFuncsMu sync.Mutex
regularFuncs map[int]func(*Client)
nextRegularID int
// shutdown
closeOnce sync.Once
closeErr error
close chan chan struct{}
// debug
bucketCount *atomic.Int32
}
// NewClient creates a new [Client] to send metrics. Use NewClient only if you are
// sending metrics to two or more StatsHouse clusters. Otherwise, simply [Configure]
// the default global [Client].
//
// Specifying empty StatsHouse address will make the client silently discard all metrics.
// if you get compiler error after updating to recent version of library, pass statshouse.DefaultNetwork to network parameter
func NewClient(logf LoggerFunc, network string, statsHouseAddr string, defaultEnv string) *Client {
return NewClientEx(ConfigureArgs{
Logger: logf,
Network: network,
StatsHouseAddr: statsHouseAddr,
DefaultEnv: defaultEnv,
})
}
func NewClientEx(args ConfigureArgs) *Client {
c := &Client{
close: make(chan chan struct{}),
w: map[metricKey]*bucket{},
wn: map[metricKeyNamed]*bucket{},
regularFuncs: map[int]func(*Client){},
tsUnixSec: uint32(time.Now().Unix()),
}
c.ConfigureEx(args)
go c.run()
return c
}
func (c *Client) ConfigureEx(args ConfigureArgs) {
if args.Logger == nil {
args.Logger = log.Printf
}
if args.Network == "" {
args.Network = DefaultNetwork
}
if args.StatsHouseAddr == "" {
args.StatsHouseAddr = DefaultAddr
}
if args.MaxBucketSize <= 0 {
args.MaxBucketSize = defaultMaxBucketSize
}
// update logger
c.logMu.Lock()
c.logF = args.Logger
c.logMu.Unlock()
// update max bucket size
c.mu.Lock()
c.maxBucketSize = args.MaxBucketSize
c.mu.Unlock()
// update transport
c.transportMu.Lock()
defer c.transportMu.Unlock()
c.app = args.AppName
c.env = args.DefaultEnv
c.network = args.Network
c.addr = args.StatsHouseAddr
if c.conn != nil {
err := c.conn.Close()
if err != nil {
args.Logger("[statshouse] failed to close connection: %v", err)
}
c.conn = nil
}
// update packet size
if maxSize := maxPacketSize(args.Network); maxSize != c.packet.maxSize {
c.packet = packet{
buf: make([]byte, batchHeaderLen, maxSize),
maxSize: maxSize,
}
}
if c.addr == "" {
args.Logger("[statshouse] configured with empty address, all statistics will be silently dropped")
}
}
// Close the [Client] and flush unsent metrics to the StatsHouse agent.
// No data will be sent after Close has returned.
func (c *Client) Close() error {
c.closeOnce.Do(func() {
ch := make(chan struct{})
c.close <- ch
<-ch
c.transportMu.Lock()
defer c.transportMu.Unlock()
if c.conn != nil {
c.closeErr = c.conn.Close()
}
})
return c.closeErr
}
// SetEnv changes the default environment associated with [Client].
func (c *Client) SetEnv(env string) {
c.transportMu.Lock()
c.env = env
c.transportMu.Unlock()
}
// For debug purposes. If necessary then it should be first method called on [Client].
func (c *Client) TrackBucketCount() {
c.bucketCount = &atomic.Int32{}
}
// For debug purposes. Panics if [Client.TrackBucketCount] wasn't called.
func (c *Client) BucketCount() int32 {
return c.bucketCount.Load()
}
// StartRegularMeasurement will call f once per collection interval with no gaps or drift,
// until StopRegularMeasurement is called with the same ID.
func (c *Client) StartRegularMeasurement(f func(*Client)) (id int) {
c.regularFuncsMu.Lock()
defer c.regularFuncsMu.Unlock()
c.nextRegularID++
c.regularFuncs[c.nextRegularID] = f
return c.nextRegularID
}
// StopRegularMeasurement cancels StartRegularMeasurement with the specified ID.
func (c *Client) StopRegularMeasurement(id int) {
c.regularFuncsMu.Lock()
defer c.regularFuncsMu.Unlock()
delete(c.regularFuncs, id)
}
func (c *Client) Count(name string, tags Tags, n float64) {
m := c.MetricRef(name, tags)
m.Count(n)
}
func (c *Client) CountHistoric(name string, tags Tags, n float64, tsUnixSec uint32) {
m := c.MetricRef(name, tags)
m.CountHistoric(n, tsUnixSec)
}
func (c *Client) NamedCount(name string, tags NamedTags, n float64) {
m := c.MetricNamedRef(name, tags)
m.Count(n)
}
func (c *Client) NamedCountHistoric(name string, tags NamedTags, n float64, tsUnixSec uint32) {
m := c.MetricNamedRef(name, tags)
m.CountHistoric(n, tsUnixSec)
}
func (c *Client) Value(name string, tags Tags, value float64) {
m := c.MetricRef(name, tags)
m.Value(value)
}
func (c *Client) ValueHistoric(name string, tags Tags, value float64, tsUnixSec uint32) {
m := c.MetricRef(name, tags)
m.ValueHistoric(value, tsUnixSec)
}
func (c *Client) NamedValue(name string, tags NamedTags, value float64) {
m := c.MetricNamedRef(name, tags)
m.Value(value)
}
func (c *Client) NamedValueHistoric(name string, tags NamedTags, value float64, tsUnixSec uint32) {
m := c.MetricNamedRef(name, tags)
m.ValueHistoric(value, tsUnixSec)
}
func (c *Client) Values(name string, tags Tags, values []float64) {
m := c.MetricRef(name, tags)
m.Values(values)
}
func (c *Client) ValuesHistoric(name string, tags Tags, values []float64, tsUnixSec uint32) {
m := c.MetricRef(name, tags)
m.ValuesHistoric(values, tsUnixSec)
}
func (c *Client) NamedValues(name string, tags NamedTags, values []float64) {
m := c.MetricNamedRef(name, tags)
m.Values(values)
}
func (c *Client) NamedValuesHistoric(name string, tags NamedTags, values []float64, tsUnixSec uint32) {
m := c.MetricNamedRef(name, tags)
m.ValuesHistoric(values, tsUnixSec)
}
func (c *Client) Unique(name string, tags Tags, value int64) {
m := c.MetricRef(name, tags)
m.Unique(value)
}
func (c *Client) UniqueHistoric(name string, tags Tags, value int64, tsUnixSec uint32) {
m := c.MetricRef(name, tags)
m.UniqueHistoric(value, tsUnixSec)
}
func (c *Client) NamedUnique(name string, tags NamedTags, value int64) {
m := c.MetricNamedRef(name, tags)
m.Unique(value)
}
func (c *Client) NamedUniqueHistoric(name string, tags NamedTags, value int64, tsUnixSec uint32) {
m := c.MetricNamedRef(name, tags)
m.UniqueHistoric(value, tsUnixSec)
}
func (c *Client) Uniques(name string, tags Tags, values []int64) {
m := c.MetricRef(name, tags)
m.Uniques(values)
}
func (c *Client) UniquesHistoric(name string, tags Tags, values []int64, tsUnixSec uint32) {
m := c.MetricRef(name, tags)
m.UniquesHistoric(values, tsUnixSec)
}
func (c *Client) NamedUniques(name string, tags NamedTags, values []int64) {
m := c.MetricNamedRef(name, tags)
m.Uniques(values)
}
func (c *Client) NamedUniquesHistoric(name string, tags NamedTags, values []int64, tsUnixSec uint32) {
m := c.MetricNamedRef(name, tags)
m.UniquesHistoric(values, tsUnixSec)
}
func (c *Client) StringTop(name string, tags Tags, value string) {
m := c.MetricRef(name, tags)
m.StringTop(value)
}
func (c *Client) StringTopHistoric(name string, tags Tags, value string, tsUnixSec uint32) {
m := c.MetricRef(name, tags)
m.StringTopHistoric(value, tsUnixSec)
}
func (c *Client) NamedStringTop(name string, tags NamedTags, value string) {
m := c.MetricNamedRef(name, tags)
m.StringTop(value)
}
func (c *Client) NamedStringTopHistoric(name string, tags NamedTags, value string, tsUnixSec uint32) {
m := c.MetricNamedRef(name, tags)
m.StringTopHistoric(value, tsUnixSec)
}
func (c *Client) StringsTop(name string, tags Tags, values []string) {
m := c.MetricRef(name, tags)
m.StringsTop(values)
}
func (c *Client) StringsTopHistoric(name string, tags Tags, values []string, tsUnixSec uint32) {
m := c.MetricRef(name, tags)
m.StringsTopHistoric(values, tsUnixSec)
}
func (c *Client) NamedStringsTop(name string, tags NamedTags, values []string) {
m := c.MetricNamedRef(name, tags)
m.StringsTop(values)
}
func (c *Client) NamedStringsTopHistoric(name string, tags NamedTags, values []string, tsUnixSec uint32) {
m := c.MetricNamedRef(name, tags)
m.StringsTopHistoric(values, tsUnixSec)
}
func (c *Client) run() {
var regularCache []func(*Client)
// get a resettable timer
timer := time.NewTimer(time.Hour)
if !timer.Stop() {
<-timer.C
}
c.mu.Lock()
now := time.Unix(int64(c.tsUnixSec), 0)
c.mu.Unlock()
// loop
for {
timer.Reset(now.Truncate(defaultSendPeriod).Add(defaultSendPeriod).Sub(now))
select {
case now = <-timer.C:
regularCache = c.callRegularFuncs(regularCache[:0])
c.send(uint32(now.Unix()))
case ch := <-c.close:
c.send(0) // last send: we will lose all metrics produced "after"
close(ch)
return
}
now = time.Now()
}
}
func (c *Client) send(nowUnixSec uint32) {
// load & switch second
c.mu.Lock()
ss, ssn := c.r, c.rn
sendUnixSec := c.tsUnixSec
c.tsUnixSec = nowUnixSec
c.mu.Unlock()
// swap
for i := 0; i < len(ss); i++ {
ss[i].swapToSend(nowUnixSec)
}
for i := 0; i < len(ssn); i++ {
ssn[i].swapToSend(nowUnixSec)
}
// send
c.transportMu.Lock()
for i := 0; i < len(ss); i++ {
if ss[i].emptySend() {
continue
}
ss[i].send(c, sendUnixSec)
}
for i := 0; i < len(ssn); i++ {
if ssn[i].emptySend() {
continue
}
ssn[i].send(c, sendUnixSec)
}
c.flush()
c.transportMu.Unlock()
// remove unused & compact
i, n := 0, len(ss)
for i < n {
b := ss[i]
if !b.emptySend() {
i++
b.emptySendCount = 0
continue
}
if b.emptySendCount < maxEmptySendCount {
i++
b.emptySendCount++
continue
} else {
b.emptySendCount = 0
}
// remove
b.mu.Lock()
c.mu.Lock()
c.w[b.k] = nil // release bucket reference
delete(c.w, b.k)
n--
c.r[i] = c.r[n]
c.r[n] = nil // release bucket reference
b.attached = false
c.mu.Unlock()
b.mu.Unlock()
}
if d := len(ss) - n; d != 0 {
c.mu.Lock()
for i := len(ss); i < len(c.r); i++ {
c.r[i-d] = c.r[i]
c.r[i] = nil // release bucket reference
}
c.r = c.r[:len(c.r)-d]
c.mu.Unlock()
}
// remove unused & compact (named)
i, n = 0, len(ssn)
for i < n {
b := ssn[i]
if !b.emptySend() {
i++
b.emptySendCount = 0
continue
}
if b.emptySendCount < maxEmptySendCount {
i++
b.emptySendCount++
continue
} else {
b.emptySendCount = 0
}
// remove
b.mu.Lock()
c.mu.Lock()
c.wn[b.kn] = nil // release bucket reference
delete(c.wn, b.kn)
n--
c.rn[i] = c.rn[n]
c.rn[n] = nil // release bucket reference
b.attached = false
c.mu.Unlock()
b.mu.Unlock()
}
if d := len(ssn) - n; d != 0 {
c.mu.Lock()
for i := len(ssn); i < len(c.rn); i++ {
c.rn[i-d] = c.rn[i]
c.rn[i] = nil // release bucket reference
}
c.rn = c.rn[:len(c.rn)-d]
c.mu.Unlock()
}
}
func (c *Client) callRegularFuncs(regularCache []func(*Client)) []func(*Client) {
c.regularFuncsMu.Lock()
for _, f := range c.regularFuncs { // TODO - call in order of registration. Use RB-tree when available
regularCache = append(regularCache, f)
}
c.regularFuncsMu.Unlock()
defer func() {
if p := recover(); p != nil {
c.rareLog("[statshouse] panic inside regular measurement function, ignoring: %v", p)
}
}()
for _, f := range regularCache { // called without locking to prevent deadlock
f(c)
}
return regularCache
}
func (c *Client) flush() {
if c.batchCount <= 0 {
return
}
c.writeBatchHeader()
if c.conn == nil && c.addr != "" {
conn, err := c.netDial()
if err != nil {
c.rareLog("[statshouse] failed to dial statshouse: %v", err)
} else {
c.conn = conn
}
}
if c.conn != nil && c.addr != "" {
var err error
c.buf, err = c.conn.Write(c.buf)
if err != nil {
c.rareLog("[statshouse] failed to send data to statshouse: %v", err)
}
}
c.buf = c.buf[:batchHeaderLen]
c.batchCount = 0
}
func (c *Client) rareLog(format string, args ...interface{}) {
c.logMu.Lock()
if time.Since(c.logT) < errorReportingPeriod {
c.logMu.Unlock()
return
}
logf := c.logF
c.logT = time.Now()
c.logMu.Unlock()
logf(format, args...)
}