-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathingress_client.go
593 lines (509 loc) · 15.1 KB
/
ingress_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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
package loggregator
import (
"crypto/tls"
"fmt"
"io"
"log"
"strconv"
"time"
"google.golang.org/protobuf/proto"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"code.cloudfoundry.org/go-loggregator/v10/rpc/loggregator_v2"
)
// IngressOption is the type of a configurable client option.
type IngressOption func(*IngressClient)
func WithDialOptions(opts ...grpc.DialOption) IngressOption {
return func(c *IngressClient) {
c.dialOpts = append(c.dialOpts, opts...)
}
}
// WithTag allows for the configuration of arbitrary string value
// metadata which will be included in all data sent to Loggregator
func WithTag(name, value string) IngressOption {
return func(c *IngressClient) {
c.tags[name] = value
}
}
// WithBatchMaxSize allows for the configuration of the number of messages to
// collect before emitting them into loggregator. By default, its value is 100
// messages.
//
// Note that aside from batch size, messages will be flushed from
// the client into loggregator at a fixed interval to ensure messages are not
// held for an undue amount of time before being sent. In other words, even if
// the client has not yet achieved the maximum batch size, the batch interval
// may trigger the messages to be sent.
func WithBatchMaxSize(maxSize uint) IngressOption {
return func(c *IngressClient) {
c.batchMaxSize = maxSize
}
}
// WithBatchFlushInterval allows for the configuration of the maximum time to
// wait before sending a batch of messages. Note that the batch interval
// may be triggered prior to the batch reaching the configured maximum size.
func WithBatchFlushInterval(d time.Duration) IngressOption {
return func(c *IngressClient) {
c.batchFlushInterval = d
}
}
// WithAddr allows for the configuration of the loggregator v2 address.
// The value to defaults to localhost:3458, which happens to be the default
// address in the loggregator server.
func WithAddr(addr string) IngressOption {
return func(c *IngressClient) {
c.addr = addr
}
}
// Logger declares the minimal logging interface used within the v2 client
type Logger interface {
Printf(string, ...interface{})
Panicf(string, ...interface{})
}
// WithLogger allows for the configuration of a logger.
// By default, the logger is disabled.
func WithLogger(l Logger) IngressOption {
return func(c *IngressClient) {
c.logger = l
}
}
// WithContext configures the context that manages the lifecycle for the gRPC
// connection. It defaults to a context.Background().
func WithContext(ctx context.Context) IngressOption {
return func(c *IngressClient) {
c.ctx = ctx
}
}
// IngressClient represents an emitter into loggregator. It should be created with the
// NewIngressClient constructor.
type IngressClient struct {
client loggregator_v2.IngressClient
sender loggregator_v2.Ingress_BatchSenderClient
envelopes chan *loggregator_v2.Envelope
tags map[string]string
batchMaxSize uint
batchFlushInterval time.Duration
addr string
dialOpts []grpc.DialOption
logger Logger
closeErrors chan error
ctx context.Context
cancel func()
}
// NewIngressClient creates a v2 loggregator client. Its TLS configuration
// must share a CA with the loggregator server.
func NewIngressClient(tlsConfig *tls.Config, opts ...IngressOption) (*IngressClient, error) {
c := &IngressClient{
envelopes: make(chan *loggregator_v2.Envelope, 100),
tags: make(map[string]string),
batchMaxSize: 100,
batchFlushInterval: 100 * time.Millisecond,
addr: "localhost:3458",
logger: log.New(io.Discard, "", 0),
closeErrors: make(chan error),
ctx: context.Background(),
}
for _, o := range opts {
o(c)
}
c.ctx, c.cancel = context.WithCancel(c.ctx)
c.dialOpts = append(c.dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
conn, err := grpc.NewClient(
c.addr,
c.dialOpts...,
)
if err != nil {
return nil, err
}
c.client = loggregator_v2.NewIngressClient(conn)
go c.startSender()
return c, nil
}
// protoEditor is required for v1 envelopes. It should be removed once v1
// is removed. It is necessary to prevent any v1 dependency in the v2 path.
type protoEditor interface {
SetLogAppInfo(appID, sourceType, sourceInstance string)
SetGaugeAppInfo(appID string, index int)
SetCounterAppInfo(appID string, index int)
SetSourceInfo(sourceID, instanceID string)
SetLogToStdout()
SetGaugeValue(name string, value float64, unit string)
SetDelta(d uint64)
SetTotal(t uint64)
SetTag(name, value string)
}
// EmitLogOption is the option type passed into EmitLog
type EmitLogOption func(proto.Message)
// WithAppInfo configures the meta data associated with emitted data. Exists
// for backward compatability. If possible, use WithSourceInfo instead.
func WithAppInfo(appID, sourceType, sourceInstance string) EmitLogOption {
return WithSourceInfo(appID, sourceType, sourceInstance)
}
// WithSourceInfo configures the meta data associated with emitted data
func WithSourceInfo(sourceID, sourceType, sourceInstance string) EmitLogOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.SourceId = sourceID
e.InstanceId = sourceInstance
e.Tags["source_type"] = sourceType
case protoEditor:
e.SetLogAppInfo(sourceID, sourceType, sourceInstance)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// WithStdout sets the output type to stdout. Without using this option,
// all data is assumed to be stderr output.
func WithStdout() EmitLogOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.GetLog().Type = loggregator_v2.Log_OUT
case protoEditor:
e.SetLogToStdout()
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// EmitLog sends a message to loggregator.
func (c *IngressClient) EmitLog(message string, opts ...EmitLogOption) {
e := &loggregator_v2.Envelope{
Timestamp: time.Now().UnixNano(),
Message: &loggregator_v2.Envelope_Log{
Log: &loggregator_v2.Log{
Payload: []byte(message),
Type: loggregator_v2.Log_ERR,
},
},
Tags: make(map[string]string),
}
for k, v := range c.tags {
e.Tags[k] = v
}
for _, o := range opts {
o(e)
}
c.envelopes <- e
}
// EmitGaugeOption is the option type passed into EmitGauge.
type EmitGaugeOption func(proto.Message)
// WithGaugeAppInfo configures an envelope with both the app ID and index.
// Exists for backward compatability. If possible, use WithGaugeSourceInfo
// instead.
func WithGaugeAppInfo(appID string, index int) EmitGaugeOption {
return WithGaugeSourceInfo(appID, strconv.Itoa(index))
}
// WithGaugeSourceInfo configures an envelope with both the source ID and
// instance ID.
func WithGaugeSourceInfo(sourceID, instanceID string) EmitGaugeOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.SourceId = sourceID
e.InstanceId = instanceID
case protoEditor:
e.SetSourceInfo(sourceID, instanceID)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// WithGaugeValue adds a gauge information. For example,
// to send information about current CPU usage, one might use:
//
// WithGaugeValue("cpu", 3.0, "percent")
//
// An number of calls to WithGaugeValue may be passed into EmitGauge.
// If there are duplicate names in any of the options, i.e., "cpu" and "cpu",
// then the last EmitGaugeOption will take precedence.
func WithGaugeValue(name string, value float64, unit string) EmitGaugeOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.GetGauge().Metrics[name] = &loggregator_v2.GaugeValue{Value: value, Unit: unit}
case protoEditor:
e.SetGaugeValue(name, value, unit)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// EmitGauge sends the configured gauge values to loggregator.
// If no EmitGaugeOption values are present, the client will emit
// an empty gauge.
func (c *IngressClient) EmitGauge(opts ...EmitGaugeOption) {
e := &loggregator_v2.Envelope{
Timestamp: time.Now().UnixNano(),
Message: &loggregator_v2.Envelope_Gauge{
Gauge: &loggregator_v2.Gauge{
Metrics: make(map[string]*loggregator_v2.GaugeValue),
},
},
Tags: make(map[string]string),
}
for k, v := range c.tags {
e.Tags[k] = v
}
for _, o := range opts {
o(e)
}
c.envelopes <- e
}
// EmitCounterOption is the option type passed into EmitCounter.
type EmitCounterOption func(proto.Message)
// WithDelta is an option that sets the delta for a counter.
func WithDelta(d uint64) EmitCounterOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.GetCounter().Delta = d
case protoEditor:
e.SetDelta(d)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// WithTotal is an option that sets the total for a counter.
func WithTotal(t uint64) EmitCounterOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.GetCounter().Total = t
e.GetCounter().Delta = 0
case protoEditor:
e.SetTotal(t)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// WithCounterAppInfo configures an envelope with both the app ID and index.
// Exists for backward compatability. If possible, use WithCounterSourceInfo
// instead.
func WithCounterAppInfo(appID string, index int) EmitCounterOption {
return WithCounterSourceInfo(appID, strconv.Itoa(index))
}
// WithCounterSourceInfo configures an envelope with both the app ID and
// source ID.
func WithCounterSourceInfo(sourceID, instanceID string) EmitCounterOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.SourceId = sourceID
e.InstanceId = instanceID
case protoEditor:
e.SetSourceInfo(sourceID, instanceID)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// EmitCounter sends a counter envelope with a delta of 1.
func (c *IngressClient) EmitCounter(name string, opts ...EmitCounterOption) {
e := &loggregator_v2.Envelope{
Timestamp: time.Now().UnixNano(),
Message: &loggregator_v2.Envelope_Counter{
Counter: &loggregator_v2.Counter{
Name: name,
Delta: uint64(1),
},
},
Tags: make(map[string]string),
}
for k, v := range c.tags {
e.Tags[k] = v
}
for _, o := range opts {
o(e)
}
c.envelopes <- e
}
// EmitTimerOption is the option type passed into EmitTimer.
type EmitTimerOption func(proto.Message)
// WithTimerSourceInfo configures an envelope with both the source and instance
// IDs.
func WithTimerSourceInfo(sourceID, instanceID string) EmitTimerOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.SourceId = sourceID
e.InstanceId = instanceID
case protoEditor:
e.SetSourceInfo(sourceID, instanceID)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// EmitTimer sends a timer envelope with the given name, start time and stop time.
func (c *IngressClient) EmitTimer(name string, start, stop time.Time, opts ...EmitTimerOption) {
e := &loggregator_v2.Envelope{
Timestamp: time.Now().UnixNano(),
Message: &loggregator_v2.Envelope_Timer{
Timer: &loggregator_v2.Timer{
Name: name,
Start: start.UnixNano(),
Stop: stop.UnixNano(),
},
},
Tags: make(map[string]string),
}
for k, v := range c.tags {
e.Tags[k] = v
}
for _, o := range opts {
o(e)
}
c.envelopes <- e
}
// EmitEventOption is the option type passed into EmitEvent.
type EmitEventOption func(proto.Message)
// WithEventSourceInfo configures an envelope with both the source and instance
// IDs.
func WithEventSourceInfo(sourceID, instanceID string) EmitEventOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.SourceId = sourceID
e.InstanceId = instanceID
case protoEditor:
e.SetSourceInfo(sourceID, instanceID)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// EmitEvent sends an Event envelope.
func (c *IngressClient) EmitEvent(ctx context.Context, title, body string, opts ...EmitEventOption) error {
e := &loggregator_v2.Envelope{
Timestamp: time.Now().UnixNano(),
Message: &loggregator_v2.Envelope_Event{
Event: &loggregator_v2.Event{
Title: title,
Body: body,
},
},
Tags: make(map[string]string),
}
for k, v := range c.tags {
e.Tags[k] = v
}
for _, o := range opts {
o(e)
}
_, err := c.client.Send(ctx, &loggregator_v2.EnvelopeBatch{
Batch: []*loggregator_v2.Envelope{e},
})
return err
}
// Emit sends an envelope. It will sent within a batch.
func (c *IngressClient) Emit(e *loggregator_v2.Envelope) {
c.envelopes <- e
}
// CloseSend will flush the envelope buffers and close the stream to the
// ingress server. This method will block until the buffers are flushed.
func (c *IngressClient) CloseSend() error {
close(c.envelopes)
return <-c.closeErrors
}
func (c *IngressClient) startSender() {
defer c.cancel()
t := time.NewTimer(c.batchFlushInterval)
var batch []*loggregator_v2.Envelope
for {
select {
case env, ok := <-c.envelopes:
if !ok {
if len(batch) > 0 {
err := c.flush(batch)
c.closeAndRecv()
c.closeErrors <- err
return
}
c.closeAndRecv()
c.closeErrors <- nil
return
}
batch = append(batch, env)
if len(batch) >= int(c.batchMaxSize) {
c.flush(batch)
batch = nil
if !t.Stop() {
<-t.C
}
t.Reset(c.batchFlushInterval)
}
case <-t.C:
if len(batch) > 0 {
c.flush(batch)
batch = nil
}
t.Reset(c.batchFlushInterval)
}
}
}
func (c *IngressClient) closeAndRecv() {
if c.sender == nil {
return
}
_, _ = c.sender.CloseAndRecv()
}
func (c *IngressClient) flush(batch []*loggregator_v2.Envelope) error {
err := c.emit(batch)
if err != nil {
c.logger.Printf("Error while flushing: %s", err)
}
return err
}
func (c *IngressClient) emit(batch []*loggregator_v2.Envelope) error {
if c.sender == nil {
var err error
c.sender, err = c.client.BatchSender(c.ctx)
if err != nil {
return err
}
}
err := c.sender.Send(&loggregator_v2.EnvelopeBatch{Batch: batch})
if err != nil {
c.sender = nil
return err
}
return nil
}
// WithEnvelopeTag adds a tag to the envelope.
func WithEnvelopeTag(name, value string) func(proto.Message) {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.Tags[name] = value
case protoEditor:
e.SetTag(name, value)
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}
// WithEnvelopeTags adds tag information that can be text, integer, or decimal to
// the envelope. WithEnvelopeTags expects a single call with a complete map
// and will overwrite if called a second time.
func WithEnvelopeTags(tags map[string]string) func(proto.Message) {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
for name, value := range tags {
e.Tags[name] = value
}
case protoEditor:
for name, value := range tags {
e.SetTag(name, value)
}
default:
panic(fmt.Sprintf("unsupported Message type: %T", m))
}
}
}