This repository has been archived by the owner on Oct 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
grpc_connector.go
338 lines (284 loc) · 7.67 KB
/
grpc_connector.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
package plumbing
import (
"fmt"
"log"
"sync"
"sync/atomic"
"time"
"unsafe"
"code.cloudfoundry.org/loggregator/metricemitter"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"golang.org/x/net/context"
)
const (
maxConnections = 2000
)
// DopplerPool creates a pool of doppler gRPC connections
type DopplerPool interface {
RegisterDoppler(addr string)
Subscribe(dopplerAddr string, ctx context.Context, req *SubscriptionRequest) (Doppler_BatchSubscribeClient, error)
Close(dopplerAddr string)
}
type Event struct {
GRPCDopplers []string
}
// Finder yields events that tell us what dopplers are available.
type Finder interface {
Next() Event
}
// GRPCConnector establishes GRPC connections to dopplers and allows calls to
// Firehose, Stream, etc to be reduced down to a single Receiver.
type GRPCConnector struct {
mu sync.RWMutex
clients []*dopplerClientInfo
pool DopplerPool
finder Finder
consumerStates []unsafe.Pointer
bufferSize int
ingressMetric *metricemitter.Counter
recentLogsError *metricemitter.Counter
}
// MetricClient creates new CounterMetrics to be emitted periodically.
type MetricClient interface {
NewCounter(name string, opts ...metricemitter.MetricOption) *metricemitter.Counter
}
// NewGRPCConnector creates a new GRPCConnector.
func NewGRPCConnector(
bufferSize int,
pool DopplerPool,
f Finder,
m MetricClient,
) *GRPCConnector {
ingressMetric := m.NewCounter("ingress",
metricemitter.WithTags(map[string]string{
"protocol": "grpc",
}),
metricemitter.WithVersion(2, 0),
)
recentLogsError := m.NewCounter("query_error",
metricemitter.WithTags(map[string]string{
"query": "recent_logs",
}),
metricemitter.WithVersion(2, 0),
)
c := &GRPCConnector{
bufferSize: bufferSize,
pool: pool,
finder: f,
consumerStates: make([]unsafe.Pointer, maxConnections),
ingressMetric: ingressMetric,
recentLogsError: recentLogsError,
}
go c.readFinder()
return c
}
// Subscribe returns a Receiver that yields all corresponding messages from Doppler
func (c *GRPCConnector) Subscribe(ctx context.Context, req *SubscriptionRequest) (recv func() ([]byte, error), err error) {
cs := &consumerState{
data: make(chan []byte, c.bufferSize),
errs: make(chan error, 1),
ctx: ctx,
req: req,
dopplers: make(map[string]bool),
}
go func() {
<-cs.ctx.Done()
atomic.StoreInt64(&cs.dead, 1)
}()
err = c.addConsumerState(cs)
if err != nil {
return nil, err
}
c.mu.RLock()
defer c.mu.RUnlock()
log.Printf("Connecting to %d dopplers", len(c.clients))
for _, client := range c.clients {
go c.consumeSubscription(cs, client)
}
return cs.Recv, nil
}
func (c *GRPCConnector) readFinder() {
for {
e := c.finder.Next()
log.Printf("Event from finder: %+v", e)
c.handleFinderEvent(e.GRPCDopplers)
}
}
func (c *GRPCConnector) handleFinderEvent(uris []string) {
c.mu.Lock()
defer c.mu.Unlock()
newURIs, deadClients := c.delta(uris)
for _, addr := range newURIs {
c.pool.RegisterDoppler(addr)
client := &dopplerClientInfo{
uri: addr,
}
c.clients = append(c.clients, client)
for i := range c.consumerStates {
cs := atomic.LoadPointer(&c.consumerStates[i])
if cs != nil &&
(*consumerState)(cs) != nil &&
atomic.LoadInt64(&(*consumerState)(cs).dead) == 0 {
go c.consumeSubscription((*consumerState)(cs), client)
}
}
}
for _, deadClient := range deadClients {
log.Printf("Disabling reconnects for doppler %s", deadClient.uri)
deadClient.disconnect = true
if atomic.LoadInt64(&deadClient.refCount) == 0 {
log.Printf("closing doppler connection %s...", deadClient.uri)
c.pool.Close(deadClient.uri)
c.close(deadClient)
}
}
}
func (c *GRPCConnector) delta(uris []string) (add []string, dead []*dopplerClientInfo) {
dead = make([]*dopplerClientInfo, len(c.clients))
copy(dead, c.clients)
for _, newURI := range uris {
var contained bool
dead, contained = c.subtractClient(dead, newURI)
if !contained {
add = append(add, newURI)
}
}
return add, dead
}
func (c *GRPCConnector) subtractClient(remaining []*dopplerClientInfo, uri string) ([]*dopplerClientInfo, bool) {
for i, client := range remaining {
if uri == client.uri {
client.disconnect = false
return append(remaining[:i], remaining[i+1:]...), true
}
}
return remaining, false
}
func (c *GRPCConnector) close(client *dopplerClientInfo) {
for i, clt := range c.clients {
if clt == client {
c.clients = append(c.clients[:i], c.clients[i+1:]...)
}
}
}
func (c *GRPCConnector) consumeSubscription(cs *consumerState, dopplerClient *dopplerClientInfo) {
if !cs.tryAddDoppler(dopplerClient.uri) {
return
}
atomic.AddInt64(&dopplerClient.refCount, 1)
defer func() {
c.mu.Lock()
defer c.mu.Unlock()
if atomic.AddInt64(&dopplerClient.refCount, -1) <= 0 &&
dopplerClient.disconnect {
log.Printf("closing doppler connection %s...", dopplerClient.uri)
c.pool.Close(dopplerClient.uri)
c.close(dopplerClient)
}
cs.forgetDoppler(dopplerClient.uri)
}()
delay := time.Millisecond
tried := false
for {
ctxDisconnect := atomic.LoadInt64(&cs.dead)
c.mu.RLock()
dopplerDisconnect := dopplerClient.disconnect
c.mu.RUnlock()
if tried && dopplerDisconnect || ctxDisconnect != 0 {
log.Printf("Disconnecting from stream (%s) (doppler.disconnect=%v) (ctx.disconnect=%d)", dopplerClient.uri, dopplerDisconnect, ctxDisconnect)
return
}
tried = true
dopplerStream, err := c.pool.Subscribe(dopplerClient.uri, cs.ctx, cs.req)
if err != nil {
log.Printf("Unable to connect to doppler (%s): %s", dopplerClient.uri, err)
time.Sleep(delay)
if delay < time.Minute {
delay *= 10
}
continue
}
delay = time.Millisecond
if err := c.readStream(dopplerStream, cs); err != nil {
status, ok := status.FromError(err)
if ok && status.Code() != codes.Canceled {
log.Printf("error getting logs from provider: %s", err)
}
continue
}
}
}
func (c *GRPCConnector) readStream(s Doppler_BatchSubscribeClient, cs *consumerState) error {
for {
// Recv() will return an error if the context has been cancelled.
resp, err := s.Recv()
if err != nil {
return err
}
for _, p := range resp.Payload {
select {
case <-cs.ctx.Done():
return nil
case cs.data <- p:
}
}
// metric-documentation-v2: (ingress) Number of v1 envelopes received over
// gRPC from Dopplers.
c.ingressMetric.Increment(uint64(len(resp.Payload)))
}
}
func (c *GRPCConnector) addConsumerState(cs *consumerState) error {
for i := range c.consumerStates {
state := atomic.LoadPointer(&c.consumerStates[i])
if state == nil ||
(*consumerState)(state) == nil ||
atomic.LoadInt64(&(*consumerState)(state).dead) != 0 {
if atomic.CompareAndSwapPointer(&c.consumerStates[i], state, unsafe.Pointer(cs)) {
return nil
}
}
}
return fmt.Errorf("at connection limit: %d", maxConnections)
}
type dopplerClientInfo struct {
uri string
disconnect bool
refCount int64
}
type consumerState struct {
ctx context.Context
req *SubscriptionRequest
data chan []byte
errs chan error
missed int
maxMissed int
dead int64
mu sync.Mutex
dopplers map[string]bool
}
func (cs *consumerState) Recv() ([]byte, error) {
select {
case err := <-cs.errs:
return nil, err
case data := <-cs.data:
return data, nil
case <-cs.ctx.Done():
return nil, cs.ctx.Err()
}
}
func (cs *consumerState) tryAddDoppler(doppler string) bool {
cs.mu.Lock()
defer cs.mu.Unlock()
ok, _ := cs.dopplers[doppler]
if ok {
return false
}
cs.dopplers[doppler] = true
return true
}
func (cs *consumerState) forgetDoppler(doppler string) {
cs.mu.Lock()
defer cs.mu.Unlock()
delete(cs.dopplers, doppler)
}