This repository has been archived by the owner on Mar 14, 2022. It is now read-only.
forked from cloudfoundry/go-loggregator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
envelope_stream_connector_test.go
337 lines (288 loc) · 7.42 KB
/
envelope_stream_connector_test.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
package loggregator_test
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"code.cloudfoundry.org/go-loggregator"
"code.cloudfoundry.org/go-loggregator/rpc/loggregator_v2"
"github.com/gogo/protobuf/proto"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Connector", func() {
It("initiates a connection to receive envelopes", func() {
producer, err := newFakeEventProducer()
Expect(err).NotTo(HaveOccurred())
producer.start()
defer producer.stop()
tlsConf, err := NewClientMutualTLSConfig(
fixture("server.crt"),
fixture("server.key"),
fixture("CA.crt"),
"metron",
)
Expect(err).NotTo(HaveOccurred())
addr := producer.addr
req := &loggregator_v2.EgressBatchRequest{ShardId: "some-id"}
c := loggregator.NewEnvelopeStreamConnector(
addr,
tlsConf,
)
rx := c.Stream(context.Background(), req)
Expect(len(rx())).NotTo(BeZero())
Expect(proto.Equal(producer.actualReq(), req)).To(BeTrue())
})
It("reconnects if the stream fails", func() {
producer, err := newFakeEventProducer()
Expect(err).NotTo(HaveOccurred())
// Producer will grab a port on start. When the producer is restarted,
// it will grab the same port.
producer.start()
tlsConf, err := NewClientMutualTLSConfig(
fixture("server.crt"),
fixture("server.key"),
fixture("CA.crt"),
"metron",
)
Expect(err).NotTo(HaveOccurred())
addr := producer.addr
c := loggregator.NewEnvelopeStreamConnector(
addr,
tlsConf,
)
go func() {
rx := c.Stream(context.Background(), &loggregator_v2.EgressBatchRequest{})
for {
rx()
}
}()
Eventually(producer.connectionAttempts).Should(Equal(1))
producer.stop()
producer.start()
defer producer.stop()
// Reconnect after killing the server.
Eventually(producer.connectionAttempts, 5).Should(Equal(2))
// Ensure we don't create new connections when we don't need to.
Consistently(producer.connectionAttempts).Should(Equal(2))
})
It("enables buffering", func() {
producer, err := newFakeEventProducer()
Expect(err).NotTo(HaveOccurred())
// Producer will grab a port on start. When the producer is restarted,
// it will grab the same port.
producer.start()
defer producer.stop()
tlsConf, err := NewClientMutualTLSConfig(
fixture("server.crt"),
fixture("server.key"),
fixture("CA.crt"),
"metron",
)
Expect(err).NotTo(HaveOccurred())
var (
mu sync.Mutex
missed int
)
addr := producer.addr
c := loggregator.NewEnvelopeStreamConnector(
addr,
tlsConf,
loggregator.WithEnvelopeStreamBuffer(5, func(m int) {
mu.Lock()
defer mu.Unlock()
missed += m
}),
)
rx := c.Stream(context.Background(), &loggregator_v2.EgressBatchRequest{})
var count int
// Read to allow the diode to notice it dropped data
go func() {
for range time.Tick(500 * time.Millisecond) {
// Do not invoke rx while mu is locked
l := len(rx())
mu.Lock()
count += l
mu.Unlock()
}
}()
Eventually(func() int {
mu.Lock()
defer mu.Unlock()
return missed
}).ShouldNot(BeZero())
mu.Lock()
l := count
mu.Unlock()
Expect(l).ToNot(BeZero())
})
})
type fakeEventProducer struct {
server *grpc.Server
addr string
mu sync.Mutex
connectionAttempts_ int
actualReq_ *loggregator_v2.EgressBatchRequest
}
func newFakeEventProducer() (*fakeEventProducer, error) {
f := &fakeEventProducer{}
return f, nil
}
func (f *fakeEventProducer) Receiver(
*loggregator_v2.EgressRequest,
loggregator_v2.Egress_ReceiverServer,
) error {
return grpc.Errorf(codes.Unimplemented, "use BatchedReceiver instead")
}
func (f *fakeEventProducer) BatchedReceiver(
req *loggregator_v2.EgressBatchRequest,
srv loggregator_v2.Egress_BatchedReceiverServer,
) error {
f.mu.Lock()
f.connectionAttempts_++
f.actualReq_ = req
f.mu.Unlock()
var i int
for range time.Tick(10 * time.Millisecond) {
srv.Send(&loggregator_v2.EnvelopeBatch{
Batch: []*loggregator_v2.Envelope{
{
SourceId: fmt.Sprintf("envelope-%d", i),
Message: &loggregator_v2.Envelope_Event{
Event: &loggregator_v2.Event{
Title: "event-name",
Body: "event-body",
},
},
},
},
})
i++
}
return nil
}
func (f *fakeEventProducer) start() {
addr := f.addr
if addr == "" {
addr = "127.0.0.1:0"
}
var lis net.Listener
for i := 0; ; i++ {
var err error
lis, err = net.Listen("tcp", addr)
if err != nil {
// This can happen if the port is already in use...
if i < 50 {
log.Printf("failed to bind for fake producer. Trying again (%d/50)...: %s", i+1, err)
time.Sleep(100 * time.Millisecond)
continue
}
panic(err)
}
break
}
f.addr = lis.Addr().String()
c, err := newServerMutualTLSConfig()
if err != nil {
panic(err)
}
opt := grpc.Creds(credentials.NewTLS(c))
f.server = grpc.NewServer(opt)
loggregator_v2.RegisterEgressServer(f.server, f)
go f.listen(lis)
}
func (f *fakeEventProducer) listen(lis net.Listener) {
_ = f.server.Serve(lis)
}
func (f *fakeEventProducer) stop() bool {
if f.server == nil {
return false
}
f.server.Stop()
f.server = nil
return true
}
func (f *fakeEventProducer) actualReq() *loggregator_v2.EgressBatchRequest {
f.mu.Lock()
defer f.mu.Unlock()
return f.actualReq_
}
func (f *fakeEventProducer) connectionAttempts() int {
f.mu.Lock()
defer f.mu.Unlock()
return f.connectionAttempts_
}
func newServerMutualTLSConfig() (*tls.Config, error) {
certFile := fixture("server.crt")
keyFile := fixture("server.key")
caCertFile := fixture("CA.crt")
tlsCert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("failed to load keypair: %s", err)
}
certBytes, err := ioutil.ReadFile(caCertFile)
if err != nil {
return nil, fmt.Errorf("failed to read ca cert file: %s", err)
}
caCertPool := x509.NewCertPool()
if ok := caCertPool.AppendCertsFromPEM(certBytes); !ok {
return nil, errors.New("unable to load ca cert file")
}
tlsConfig := &tls.Config{
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{tlsCert},
ClientCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
}
return tlsConfig, nil
}
func NewClientMutualTLSConfig(
certFile string,
keyFile string,
caCertFile string,
serverName string,
) (*tls.Config, error) {
tlsCert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("failed to load keypair: %s", err)
}
certBytes, err := ioutil.ReadFile(caCertFile)
if err != nil {
return nil, fmt.Errorf("failed to read ca cert file: %s", err)
}
caCertPool := x509.NewCertPool()
if ok := caCertPool.AppendCertsFromPEM(certBytes); !ok {
return nil, errors.New("unable to load ca cert file")
}
certificate, err := x509.ParseCertificate(tlsCert.Certificate[0])
if err != nil {
return nil, err
}
verifyOptions := x509.VerifyOptions{
Roots: caCertPool,
KeyUsages: []x509.ExtKeyUsage{
x509.ExtKeyUsageAny,
},
}
if _, err := certificate.Verify(verifyOptions); err != nil {
return nil, fmt.Errorf("failed to verify certificate: %s", err)
}
tlsConfig := &tls.Config{
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{tlsCert},
ServerName: serverName,
RootCAs: caCertPool,
}
return tlsConfig, err
}