-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathrlp_gateway_client.go
327 lines (286 loc) · 8.29 KB
/
rlp_gateway_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
package loggregator
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"
"time"
"code.cloudfoundry.org/go-loggregator/v10/rpc/loggregator_v2"
"golang.org/x/net/context"
"google.golang.org/protobuf/encoding/protojson"
)
type RLPGatewayClient struct {
addr string
log Logger
doer Doer
maxRetries int
errChan chan error
}
type GatewayLogger interface {
Printf(format string, v ...interface{})
Panicf(format string, v ...interface{})
}
func NewRLPGatewayClient(addr string, opts ...RLPGatewayClientOption) *RLPGatewayClient {
c := &RLPGatewayClient{
addr: addr,
log: log.New(io.Discard, "", 0),
doer: http.DefaultClient,
maxRetries: 10,
}
for _, o := range opts {
o(c)
}
return c
}
// RLPGatewayClientOption is the type of a configurable client option.
type RLPGatewayClientOption func(*RLPGatewayClient)
// WithRLPGatewayClientLogger returns a RLPGatewayClientOption to configure
// the logger of the RLPGatewayClient. It defaults to a silent logger.
func WithRLPGatewayClientLogger(log GatewayLogger) RLPGatewayClientOption {
return func(c *RLPGatewayClient) {
c.log = log
}
}
// WithRLPGatewayClientLogger returns a RLPGatewayClientOption to configure
// the HTTP client. It defaults to the http.DefaultClient.
func WithRLPGatewayHTTPClient(d Doer) RLPGatewayClientOption {
return func(c *RLPGatewayClient) {
c.doer = d
}
}
// WithRLPGatewayMaxRetries returns a RLPGatewayClientOption to configure
// how many times the client will attempt to connect to the RLP gateway
// before giving up.
func WithRLPGatewayMaxRetries(r int) RLPGatewayClientOption {
return func(c *RLPGatewayClient) {
c.maxRetries = r
}
}
// WithRLPGatewayErrChan returns a RLPGatewayClientOption to configure
// an error channel to communicate errors when the client exceeds max retries
func WithRLPGatewayErrChan(errChan chan error) RLPGatewayClientOption {
return func(c *RLPGatewayClient) {
c.errChan = errChan
}
}
// Doer is used to make HTTP requests to the RLP Gateway.
type Doer interface {
// Do is a implementation of the http.Client's Do method.
Do(*http.Request) (*http.Response, error)
}
// Stream returns a new EnvelopeStream for the given context and request. The
// lifecycle of the EnvelopeStream is managed by the given context. If the
// underlying SSE stream dies, it attempts to reconnect until the context
// is done. Any errors are logged via the client's logger.
func (c *RLPGatewayClient) Stream(ctx context.Context, req *loggregator_v2.EgressBatchRequest) EnvelopeStream {
es := make(chan []*loggregator_v2.Envelope, 100)
go c.connectToStream(es, ctx, req)()
return streamEnvelopes(ctx, es)
}
func (c *RLPGatewayClient) connectToStream(es chan []*loggregator_v2.Envelope, ctx context.Context, req *loggregator_v2.EgressBatchRequest) func() {
var numRetries int
return func() {
defer close(es)
for ctx.Err() == nil && numRetries <= c.maxRetries {
connectionSucceeded := c.connect(ctx, es, req)
if connectionSucceeded {
numRetries = 0
continue
}
numRetries++
}
if numRetries > c.maxRetries {
select {
case c.errChan <- errors.New("client connection attempts exceeded max retries -- giving up"):
default:
log.Printf("unable to write error to err chan -- givin up")
}
}
}
}
func streamEnvelopes(ctx context.Context, es chan []*loggregator_v2.Envelope) func() []*loggregator_v2.Envelope {
return func() []*loggregator_v2.Envelope {
for {
select {
case <-ctx.Done():
return nil
case e, ok := <-es:
if !ok {
return nil
}
return e
default:
time.Sleep(50 * time.Millisecond)
}
}
}
}
func (c *RLPGatewayClient) connect(
ctx context.Context,
es chan<- []*loggregator_v2.Envelope,
logReq *loggregator_v2.EgressBatchRequest,
) bool {
readAddr := fmt.Sprintf("%s/v2/read%s", c.addr, c.buildQuery(logReq))
req, err := http.NewRequest(http.MethodGet, readAddr, nil)
if err != nil {
c.log.Panicf("failed to build request %s", err)
}
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("Cache-Control", "no-cache")
resp, err := c.doer.Do(req.WithContext(ctx))
if err != nil {
c.log.Printf("error making request: %s", err)
return false
}
defer func() {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
c.log.Printf("failed to read body: %s", err)
return false
}
c.log.Printf("unexpected status code %d: %s", resp.StatusCode, body)
return false
}
rawBatches := make(chan string, 100)
defer close(rawBatches)
c.initWorkerPool(rawBatches, es)
return c.readStream(resp.Body, rawBatches)
}
func (c *RLPGatewayClient) readStream(r io.Reader, rawBatches chan string) bool {
buf := bytes.NewBuffer(nil)
reader := bufio.NewReader(r)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
c.log.Printf("failed while reading stream: %s", err)
return true
}
switch {
case bytes.HasPrefix(line, []byte("heartbeat: ")):
// TODO: Remove this old case
continue
case bytes.HasPrefix(line, []byte("event: closing")):
return true
case bytes.HasPrefix(line, []byte("event: heartbeat")):
// Throw away the data of the heartbeat event and the next
// newline.
_, _ = reader.ReadBytes('\n')
_, _ = reader.ReadBytes('\n')
continue
case bytes.HasPrefix(line, []byte("data: ")):
buf.Write(line[len("data: "):])
case bytes.Equal(line, []byte("\n")):
if buf.Len() == 0 {
continue
}
rawBatches <- buf.String()
buf.Reset()
}
}
}
func (c *RLPGatewayClient) initWorkerPool(rawBatches chan string, batches chan<- []*loggregator_v2.Envelope) {
workerCount := 1000
for i := 0; i < workerCount; i++ {
go func(rawBatches chan string, es chan<- []*loggregator_v2.Envelope) {
for batch := range rawBatches {
var eb loggregator_v2.EnvelopeBatch
if err := protojson.Unmarshal([]byte(batch), &eb); err != nil {
c.log.Printf("failed to unmarshal envelope: %s", err)
return
}
es <- eb.Batch
}
}(rawBatches, batches)
}
}
func (c *RLPGatewayClient) buildQuery(req *loggregator_v2.EgressBatchRequest) string {
var query []string
if req.GetShardId() != "" {
query = append(query, "shard_id="+req.GetShardId())
}
if req.GetDeterministicName() != "" {
query = append(query, "deterministic_name="+req.GetDeterministicName())
}
for _, selector := range req.GetSelectors() {
if selector.GetSourceId() != "" {
query = append(query, "source_id="+selector.GetSourceId())
}
switch selector.Message.(type) {
case *loggregator_v2.Selector_Log:
query = append(query, "log")
case *loggregator_v2.Selector_Counter:
if selector.GetCounter().GetName() != "" {
query = append(query, "counter.name="+selector.GetCounter().GetName())
continue
}
query = append(query, "counter")
case *loggregator_v2.Selector_Gauge:
if len(selector.GetGauge().GetNames()) > 1 {
// TODO: This is a mistake in the gateway.
panic("This is not yet supported")
}
if len(selector.GetGauge().GetNames()) != 0 {
query = append(query, "gauge.name="+selector.GetGauge().GetNames()[0])
continue
}
query = append(query, "gauge")
case *loggregator_v2.Selector_Timer:
query = append(query, "timer")
case *loggregator_v2.Selector_Event:
query = append(query, "event")
}
}
namedCounter := containsPrefix(query, "counter.name")
namedGauge := containsPrefix(query, "gauge.name")
if namedCounter {
query = filter(query, "counter")
}
if namedGauge {
query = filter(query, "gauge")
}
query = removeDuplicateSourceIDs(query)
if len(query) == 0 {
return ""
}
return "?" + strings.Join(query, "&")
}
func removeDuplicateSourceIDs(query []string) []string {
sids := map[string]bool{}
duplicates := 0
for i, j := 0, 0; i < len(query); i++ {
if strings.HasPrefix(query[i], "source_id=") && sids[query[i]] {
// Duplicate source ID
duplicates++
continue
}
sids[query[i]] = true
query[j] = query[i]
j++
}
return query[:len(query)-duplicates]
}
func containsPrefix(arr []string, prefix string) bool {
for _, i := range arr {
if strings.HasPrefix(i, prefix) {
return true
}
}
return false
}
func filter(arr []string, target string) []string {
var filtered []string
for _, i := range arr {
if i != target {
filtered = append(filtered, i)
}
}
return filtered
}