-
Notifications
You must be signed in to change notification settings - Fork 17
/
ingress_client.go
407 lines (351 loc) · 10.3 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
package loggregator
import (
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"strconv"
"time"
"github.com/golang/protobuf/proto"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"code.cloudfoundry.org/go-loggregator/rpc/loggregator_v2"
)
// IngressOption is the type of a configurable client option.
type IngressOption func(*IngressClient)
// 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{})
}
// 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
}
}
// 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
logger Logger
closeErrors chan error
}
// 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: time.Second,
addr: "localhost:3458",
logger: log.New(ioutil.Discard, "", 0),
closeErrors: make(chan error),
}
for _, o := range opts {
o(c)
}
conn, err := grpc.Dial(
c.addr,
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
)
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 {
SetGaugeAppInfo(appID string, index int)
SetLogAppInfo(appID, sourceType, sourceInstance string)
SetLogToStdout()
SetGaugeValue(name string, value float64, unit string)
SetDelta(d 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
func WithAppInfo(appID, sourceType, sourceInstance string) EmitLogOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.SourceId = appID
e.InstanceId = sourceInstance
e.Tags["source_type"] = sourceType
case protoEditor:
e.SetLogAppInfo(appID, 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.
func WithGaugeAppInfo(appID string, index int) EmitGaugeOption {
return func(m proto.Message) {
switch e := m.(type) {
case *loggregator_v2.Envelope:
e.SourceId = appID
e.InstanceId = strconv.Itoa(index)
case protoEditor:
e.SetGaugeAppInfo(appID, index)
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))
}
}
}
// 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
}
// 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
}
func (c *IngressClient) startSender() {
t := time.NewTimer(c.batchFlushInterval)
var batch []*loggregator_v2.Envelope
for {
select {
case env, ok := <-c.envelopes:
if !ok {
if len(batch) > 0 {
c.closeErrors <- c.flush(batch, true)
}
return
}
batch = append(batch, env)
if len(batch) >= int(c.batchMaxSize) {
c.flush(batch, false)
batch = nil
if !t.Stop() {
<-t.C
}
t.Reset(c.batchFlushInterval)
}
case <-t.C:
if len(batch) > 0 {
c.flush(batch, false)
batch = nil
}
t.Reset(c.batchFlushInterval)
}
}
}
func (c *IngressClient) flush(batch []*loggregator_v2.Envelope, close bool) error {
err := c.emit(batch, close)
if err != nil {
c.logger.Printf("Error while flushing: %s", err)
}
return err
}
func (c *IngressClient) emit(batch []*loggregator_v2.Envelope, close bool) error {
if c.sender == nil {
var err error
// TODO Callers of emit should pass in a context. The code should not
// be hard-coding context.TODO here.
c.sender, err = c.client.BatchSender(context.TODO())
if err != nil {
return err
}
}
err := c.sender.Send(&loggregator_v2.EnvelopeBatch{Batch: batch})
if err != nil {
c.sender = nil
return err
}
if close {
return c.sender.CloseSend()
}
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))
}
}
}