forked from projectcalico/calico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_client.go
579 lines (527 loc) · 18.3 KB
/
sync_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
// Copyright (c) 2017-2019 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package syncclient
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/gob"
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/golang/snappy"
calicotls "github.com/dtest11/calico/crypto/pkg/tls"
"github.com/dtest11/calico/libcalico-go/lib/backend/api"
"github.com/dtest11/calico/libcalico-go/lib/readlogger"
"github.com/dtest11/calico/typha/pkg/discovery"
"github.com/dtest11/calico/typha/pkg/syncproto"
"github.com/dtest11/calico/typha/pkg/tlsutils"
)
var nextID uint64 = 1 // Non-zero so we can tell whether it's set at all.
const (
defaultReadtimeout = 30 * time.Second
defaultWriteTimeout = 10 * time.Second
)
type Options struct {
ReadTimeout time.Duration
ReadBufferSize int
WriteTimeout time.Duration
KeyFile string
CertFile string
CAFile string
ServerCN string
ServerURISAN string
SyncerType syncproto.SyncerType
// DisableDecoderRestart disables decoder restart and the features that depend on
// it (such as compression). Useful for simulating an older client in UT.
DisableDecoderRestart bool
// DebugLogReads tells the client to wrap each connection with a Reader that
// logs every read. Intended only for use in tests!
DebugLogReads bool
// DebugDiscardKVUpdates discards all KV updates from typha without decoding them.
// Useful for load testing Typha without having to run a "full" client.
DebugDiscardKVUpdates bool
// FIPSModeEnabled Enables FIPS 140-2 verified crypto mode.
FIPSModeEnabled bool
}
func (o *Options) readTimeout() time.Duration {
if o == nil || o.ReadTimeout <= 0 {
return defaultReadtimeout
}
return o.ReadTimeout
}
func (o *Options) writeTimeout() time.Duration {
if o == nil || o.WriteTimeout <= 0 {
return defaultWriteTimeout
}
return o.WriteTimeout
}
func (o *Options) requiringTLS() bool {
// True if any of the TLS parameters are set.
requiringTLS := o != nil && o.KeyFile+o.CertFile+o.CAFile+o.ServerCN+o.ServerURISAN != ""
log.WithField("requiringTLS", requiringTLS).Info("")
return requiringTLS
}
func (o *Options) validate() (err error) {
// If any client-side TLS options are specified, they _all_ must be - except that either
// ServerCN or ServerURISAN may be left unset.
if o.requiringTLS() {
// Some TLS options specified.
if o.KeyFile == "" ||
o.CertFile == "" ||
o.CAFile == "" ||
(o.ServerCN == "" && o.ServerURISAN == "") {
err = errors.New("If any Felix-Typha TLS options are specified," +
" they _all_ must be" +
" - except that either ServerCN or ServerURISAN may be left unset.")
}
}
return
}
func New(
discoverer *discovery.Discoverer,
myVersion, myHostname, myInfo string,
cbs api.SyncerCallbacks,
options *Options,
) *SyncerClient {
if err := options.validate(); err != nil {
log.WithField("options", options).WithError(err).Fatal("Invalid options")
}
id := nextID
nextID++
if options == nil {
options = &Options{}
}
return &SyncerClient{
ID: id,
logCxt: log.WithFields(log.Fields{
"myID": id,
"type": options.SyncerType,
}),
callbacks: cbs,
discoverer: discoverer,
myVersion: myVersion,
myHostname: myHostname,
myInfo: myInfo,
options: options,
handshakeStatus: &handshakeStatus{
helloReceivedChan: make(chan struct{}, 1),
},
}
}
type SyncerClient struct {
ID uint64
logCxt *log.Entry
discoverer *discovery.Discoverer
connInfo *discovery.Typha
myHostname, myVersion, myInfo string
options *Options
connection net.Conn
connR io.Reader
encoder *gob.Encoder
decoder *gob.Decoder
handshakeStatus *handshakeStatus
supportsNodeResourceUpdates bool
callbacks api.SyncerCallbacks
Finished sync.WaitGroup
}
type handshakeStatus struct {
helloReceivedChan chan struct{}
complete bool
}
func (s *SyncerClient) Start(cxt context.Context) error {
// Connect synchronously so that we can return an error early if we can't connect at all.
s.logCxt.Info("Starting Typha client...")
// Defensive: in case there's a bug in NextAddr() and it never stops returning values,
// set a sanity limit on the number of tries.
maxTries := s.calculateConnectionAttemptLimit(len(s.discoverer.CachedTyphaAddrs()))
remainingTries := maxTries
cat := discovery.NewConnAttemptTracker(s.discoverer)
for {
remainingTries--
if remainingTries < 0 {
return fmt.Errorf("failed to connect to Typha after %d tries", maxTries)
}
addr, err := cat.NextAddr()
if err != nil {
return fmt.Errorf("failed to load next Typha address to try: %w", err)
}
s.logCxt.Infof("Connecting to typha endpoint %s.", addr.Addr)
err = s.connect(cxt, addr)
if err != nil {
s.logCxt.WithError(err).Warnf("Failed to connect to typha endpoint %s. Will try another if available...", addr.Addr)
time.Sleep(100 * time.Millisecond) // Avoid tight loop.
} else {
s.logCxt.Infof("Successfully connected to Typha at %s.", addr.Addr)
break
}
}
// Then start our background goroutines. We start the main loop and a second goroutine to
// manage shutdown.
cxt, cancelFn := context.WithCancel(cxt)
s.Finished.Add(1)
go s.loop(cxt, cancelFn)
s.Finished.Add(1)
go func() {
// Broadcast that we're finished.
defer s.Finished.Done()
// Wait for the context to finish, either due to external cancel or our own loop
// exiting.
<-cxt.Done()
s.logCxt.Info("Typha client Context asked us to exit, closing connection...")
// Close the connection. This will trigger the main loop to exit if it hasn't
// already.
err := s.connection.Close()
if err != nil {
log.WithError(err).Warn("Ignoring error from Close during shut-down of client.")
}
}()
return nil
}
func (s *SyncerClient) calculateConnectionAttemptLimit(numDiscoveredTyphas int) int {
expectedNumTyphas := numDiscoveredTyphas
if expectedNumTyphas < 3 {
// Most clusters have at least 3 Typha instances so, if we discovered fewer instances,
// assume that there may be more starting up.
expectedNumTyphas = 3
}
// During upgrade, we expect all Typha instances to be replaced one by one so, for a safe
// upper bound on the number of potential connection attempts, assume that we try to connect
// to double the number of instances that we detected.
maxTries := expectedNumTyphas * 2
return maxTries
}
// SupportsNodeResourceUpdates waits for the Typha server to send a hello and returns true if
// the server supports node resource updates. If the given timeout is reached, an error is returned.
func (s *SyncerClient) SupportsNodeResourceUpdates(timeout time.Duration) (bool, error) {
// If a previous call has already marked the handshake as complete, then just return the value.
if s.handshakeStatus.complete {
return s.supportsNodeResourceUpdates, nil
}
select {
case <-s.handshakeStatus.helloReceivedChan:
s.logCxt.Debug("Received MsgServerHello from server")
s.handshakeStatus.complete = true
return s.supportsNodeResourceUpdates, nil
case <-time.After(timeout):
// fallthrough
}
return false, fmt.Errorf("Timed out waiting for handshake to complete")
}
func (s *SyncerClient) connect(cxt context.Context, typhaAddr discovery.Typha) error {
log.Info("Starting Typha client")
var err error
logCxt := s.logCxt.WithField("address", typhaAddr)
var connFunc func(string) (net.Conn, error)
if s.options.requiringTLS() {
cert, err := tls.LoadX509KeyPair(s.options.CertFile, s.options.KeyFile)
if err != nil {
log.WithError(err).Error("Failed to load certificate and key")
return err
}
tlsConfig := calicotls.NewTLSConfig(s.options.FIPSModeEnabled)
tlsConfig.Certificates = []tls.Certificate{cert}
// Typha API is a private binary API so we can enforce a recent TLS variant without
// worrying about back-compatibility with old browsers (for example).
tlsConfig.MinVersion = tls.VersionTLS12
// Set InsecureSkipVerify true, because when it's false crypto/tls insists on
// verifying the server's hostname or IP address against tlsConfig.ServerName, and
// we don't always want that. We will do certificate chain verification ourselves
// inside CertificateVerifier.
tlsConfig.InsecureSkipVerify = true
caPEMBlock, err := os.ReadFile(s.options.CAFile)
if err != nil {
log.WithError(err).Error("Failed to read CA data")
return err
}
tlsConfig.RootCAs = x509.NewCertPool()
ok := tlsConfig.RootCAs.AppendCertsFromPEM(caPEMBlock)
if !ok {
log.Error("Failed to add CA data to pool")
return errors.New("Failed to add CA data to pool")
}
tlsConfig.VerifyPeerCertificate = tlsutils.CertificateVerifier(
logCxt,
tlsConfig.RootCAs,
s.options.ServerCN,
s.options.ServerURISAN,
)
connFunc = func(addr string) (net.Conn, error) {
return tls.DialWithDialer(
&net.Dialer{Timeout: 10 * time.Second},
"tcp",
addr,
tlsConfig)
}
} else {
connFunc = func(addr string) (net.Conn, error) {
return net.DialTimeout("tcp", addr, 10*time.Second)
}
}
if cxt.Err() == nil {
logCxt.Info("Connecting to Typha.")
s.connection, err = connFunc(typhaAddr.Addr)
if err != nil {
return err
}
s.connR = s.connection
if s.options.DebugLogReads {
s.connR = readlogger.New(s.connection)
}
}
if cxt.Err() != nil {
if s.connection != nil {
err := s.connection.Close()
if err != nil {
log.WithError(err).Warn("Ignoring error from Close during shut-down of client.")
}
}
return cxt.Err()
}
if s.options.ReadBufferSize != 0 {
tcpConn := extractTCPConn(s.connection)
if tcpConn == nil {
log.Warn("Cannot set read buffer size, not a TCP connection?")
} else {
err := tcpConn.SetReadBuffer(s.options.ReadBufferSize)
if err != nil {
log.WithError(err).Warn("Failed to set read buffer size, ignoring")
} else {
log.WithField("size", s.options.ReadBufferSize).Warn("Set read buffer size")
}
}
}
logCxt.Info("Connected to Typha.")
s.connInfo = &typhaAddr
// Log TLS connection details.
tlsConn, ok := s.connection.(*tls.Conn)
log.WithField("ok", ok).Debug("TLS conn?")
if ok {
state := tlsConn.ConnectionState()
for _, v := range state.PeerCertificates {
bytes, _ := x509.MarshalPKIXPublicKey(v.PublicKey)
logCxt.Debugf("%#v", bytes)
logCxt.Debugf("%#v", v.Subject)
logCxt.Debugf("%#v", v.URIs)
}
logCxt.WithFields(log.Fields{
"handshake": state.HandshakeComplete,
}).Debug("TLS negotiation")
}
return nil
}
func extractTCPConn(c net.Conn) *net.TCPConn {
if wrapper, ok := c.(interface{ NetConn() net.Conn }); ok {
// TLS conn provides an interface to get the underlying net.Conn
c = wrapper.NetConn()
}
switch c := c.(type) {
case *net.TCPConn:
return c
default:
return nil
}
}
func (s *SyncerClient) logConnectionFailure(cxt context.Context, logCxt *log.Entry, err error, operation string) {
if cxt.Err() != nil {
logCxt.WithError(err).Warn("Connection failed while being shut down by context.")
return
}
logCxt.WithError(err).Errorf("Failed to %s", operation)
}
func (s *SyncerClient) loop(cxt context.Context, cancelFn context.CancelFunc) {
defer s.Finished.Done()
defer cancelFn()
logCxt := s.logCxt.WithField("connection", s.connInfo)
logCxt.Info("Started Typha client main loop")
// Always start with basic gob encoding for the handshake. We may upgrade to a compressed version below.
s.encoder = gob.NewEncoder(s.connection)
s.decoder = gob.NewDecoder(s.connR)
ourSyncerType := s.options.SyncerType
if ourSyncerType == "" {
ourSyncerType = syncproto.SyncerTypeFelix
}
compAlgs := []syncproto.CompressionAlgorithm{syncproto.CompressionSnappy}
if s.options.DisableDecoderRestart {
// Compression requires decoder restart.
compAlgs = nil
}
err := s.sendMessageToServer(cxt, logCxt, "send hello to server",
syncproto.MsgClientHello{
Hostname: s.myHostname,
Version: s.myVersion,
Info: s.myInfo,
SyncerType: ourSyncerType,
SupportsDecoderRestart: !s.options.DisableDecoderRestart,
SupportedCompressionAlgorithms: compAlgs,
ClientConnID: s.ID,
},
)
if err != nil {
return // (Failure already logged.)
}
// Read the handshake response. It must be the first message.
msg, err := s.readMessageFromServer(cxt, logCxt)
if err != nil {
return
}
serverHello, ok := msg.(syncproto.MsgServerHello)
if !ok {
logCxt.WithField("msg", msg).Error("Unexpected first message from server.")
return
}
if serverHello.ServerConnID != 0 {
logCxt = logCxt.WithField("serverConnID", serverHello.ServerConnID)
}
logCxt.WithField("serverMsg", serverHello).Info("ServerHello message received")
// Check whether Typha supports node resource updates.
if !serverHello.SupportsNodeResourceUpdates {
logCxt.Info("Server responded without support for node resource updates, assuming older Typha")
}
s.supportsNodeResourceUpdates = serverHello.SupportsNodeResourceUpdates
s.handshakeStatus.helloReceivedChan <- struct{}{}
// Check the SyncerType reported by the server. If the server is too old to support SyncerType then
// the message will have an empty string in place of the SyncerType. In that case we only proceed if
// the client wants the felix syncer.
serverSyncerType := serverHello.SyncerType
if serverSyncerType == "" {
logCxt.Info("Server responded without SyncerType, assuming an old Typha version that only " +
"supports SyncerTypeFelix.")
serverSyncerType = syncproto.SyncerTypeFelix
}
if ourSyncerType != serverSyncerType {
logCxt.Errorf("We require SyncerType %s but Typha server doesn't support it.", ourSyncerType)
return
}
// Handshake done, start processing messages from the server.
for cxt.Err() == nil {
msg, err := s.readMessageFromServer(cxt, logCxt)
if err != nil {
return
}
debug := log.IsLevelEnabled(log.DebugLevel)
switch msg := msg.(type) {
case syncproto.MsgSyncStatus:
logCxt.WithField("newStatus", msg.SyncStatus).Info("Status update from Typha.")
s.callbacks.OnStatusUpdated(msg.SyncStatus)
case syncproto.MsgPing:
logCxt.Debug("Ping received from Typha")
err := s.sendMessageToServer(cxt, logCxt, "write pong to server",
syncproto.MsgPong{
PingTimestamp: msg.Timestamp,
},
)
if err != nil {
return // (Failure already logged.)
}
logCxt.Debug("Pong sent to Typha")
case syncproto.MsgKVs:
updates := make([]api.Update, 0, len(msg.KVs))
if s.options.DebugDiscardKVUpdates {
// For simulating lots of clients in tests, just throw away the data.
continue
}
for _, kv := range msg.KVs {
update, err := kv.ToUpdate()
if err != nil {
logCxt.WithError(err).Error("Failed to deserialize update, skipping.")
continue
}
if debug {
logCxt.WithFields(log.Fields{
"serialized": kv,
"deserialized": update,
}).Debug("Decoded update from Typha")
}
updates = append(updates, update)
}
s.callbacks.OnUpdates(updates)
case syncproto.MsgDecoderRestart:
if s.options.DisableDecoderRestart {
log.Error("Server sent MsgDecoderRestart but we signalled no support.")
return
}
err = s.restartDecoder(cxt, logCxt, msg)
if err != nil {
log.WithError(err).Error("Failed to restart decoder")
return
}
case syncproto.MsgServerHello:
logCxt.WithField("serverVersion", msg.Version).Error("Unexpected extra server hello message received")
return
}
}
}
func (s *SyncerClient) restartDecoder(cxt context.Context, logCxt *log.Entry, msg syncproto.MsgDecoderRestart) error {
logCxt.WithField("msg", msg).Info("Server asked us to restart our decoder")
// Check if we should enable compression.
switch msg.CompressionAlgorithm {
case syncproto.CompressionSnappy:
logCxt.Info("Server selected snappy compression.")
r := snappy.NewReader(s.connR)
s.decoder = gob.NewDecoder(r)
case "":
logCxt.Info("Server selected no compression.")
s.decoder = gob.NewDecoder(s.connR)
}
// Server requires an ack of the MsgDecoderRestart before it can send data in the new format.
err := s.sendMessageToServer(cxt, logCxt, "send ACK to server",
syncproto.MsgACK{},
)
return err
}
// sendMessageToServer sends a single value-type MsgXYZ object to the server. It updates the connection's
// write deadline to ensure we don't block forever. Logs errors via logConnectionFailure.
func (s *SyncerClient) sendMessageToServer(cxt context.Context, logCxt *log.Entry, op string, message interface{}) error {
err := s.connection.SetWriteDeadline(time.Now().Add(s.options.writeTimeout()))
if err != nil {
s.logConnectionFailure(cxt, logCxt, err, "set timeout before "+op)
return err
}
err = s.encoder.Encode(syncproto.Envelope{
Message: message,
})
if err != nil {
s.logConnectionFailure(cxt, logCxt, err, op)
return err
}
return nil
}
// readMessageFromServer reads a single value-type MsgXYZ object from the server. It updates the connection's
// read deadline to ensure we don't block forever. Logs errors via logConnectionFailure.
func (s *SyncerClient) readMessageFromServer(cxt context.Context, logCxt *log.Entry) (interface{}, error) {
var envelope syncproto.Envelope
// Update the read deadline before we try to read, otherwise we could block for a very long time if the
// TCP connection was severed without being cleanly shut down. Typha sends regular pings so we should receive
// something even if there are no datamodel updates.
err := s.connection.SetReadDeadline(time.Now().Add(s.options.readTimeout()))
if err != nil {
s.logConnectionFailure(cxt, logCxt, err, "set read timeout")
return nil, err
}
err = s.decoder.Decode(&envelope)
if err != nil {
s.logConnectionFailure(cxt, logCxt, err, "read from server")
return nil, err
}
if log.IsLevelEnabled(log.DebugLevel) {
logCxt.WithField("envelope", envelope).Debug("New message from Typha.")
}
return envelope.Message, nil
}