-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathclient.go
1216 lines (1101 loc) · 34.1 KB
/
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package client
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/url"
"os"
"reflect"
"strings"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/cenkalti/rpc2"
"github.com/cenkalti/rpc2/jsonrpc"
"github.com/go-logr/logr"
"github.com/go-logr/stdr"
"github.com/ovn-org/libovsdb/cache"
"github.com/ovn-org/libovsdb/model"
"github.com/ovn-org/libovsdb/ovsdb"
"github.com/ovn-org/libovsdb/ovsdb/serverdb"
)
// Constants defined for libovsdb
const (
SSL = "ssl"
TCP = "tcp"
UNIX = "unix"
)
const serverDB = "_Server"
// ErrNotConnected is an error returned when the client is not connected
var ErrNotConnected = errors.New("not connected")
// ErrAlreadyConnected is an error returned when the client is already connected
var ErrAlreadyConnected = errors.New("already connected")
// ErrUnsupportedRPC is an error returned when an unsupported RPC method is called
var ErrUnsupportedRPC = errors.New("unsupported rpc")
// Client represents an OVSDB Client Connection
// It provides all the necessary functionality to Connect to a server,
// perform transactions, and build your own replica of the database with
// Monitor or MonitorAll. It also provides a Cache that is populated from OVSDB
// update notifications.
type Client interface {
Connect(context.Context) error
Disconnect()
Close()
Schema() ovsdb.DatabaseSchema
Cache() *cache.TableCache
SetOption(Option) error
Connected() bool
DisconnectNotify() chan struct{}
Echo(context.Context) error
Transact(context.Context, ...ovsdb.Operation) ([]ovsdb.OperationResult, error)
Monitor(context.Context, *Monitor) (MonitorCookie, error)
MonitorAll(context.Context) (MonitorCookie, error)
MonitorCancel(ctx context.Context, cookie MonitorCookie) error
NewMonitor(...MonitorOption) *Monitor
CurrentEndpoint() string
API
}
type bufferedUpdate struct {
updates *ovsdb.TableUpdates
updates2 *ovsdb.TableUpdates2
lastTxnID string
}
// ovsdbClient is an OVSDB client
type ovsdbClient struct {
options *options
metrics metrics
connected bool
rpcClient *rpc2.Client
rpcMutex sync.RWMutex
activeEndpoint string
// The name of the "primary" database - that is to say, the DB
// that the user expects to interact with.
primaryDBName string
databases map[string]*database
stopCh chan struct{}
disconnect chan struct{}
shutdown bool
shutdownMutex sync.Mutex
logger *logr.Logger
}
// database is everything needed to map between go types and an ovsdb Database
type database struct {
// model encapsulates the database schema and model of the database we're connecting to
model model.DatabaseModel
// modelMutex protects model from being replaced (via reconnect) while in use
modelMutex sync.RWMutex
// cache is used to store the updates for monitored tables
cache *cache.TableCache
// cacheMutex protects cache from being replaced (via reconnect) while in use
cacheMutex sync.RWMutex
api API
// any ongoing monitors, so we can re-create them if we disconnect
monitors map[string]*Monitor
monitorsMutex sync.Mutex
// tracks any outstanding updates while waiting for a monitor response
deferUpdates bool
deferredUpdates []*bufferedUpdate
}
// NewOVSDBClient creates a new OVSDB Client with the provided
// database model. The client can be configured using one or more Option(s),
// like WithTLSConfig. If no WithEndpoint option is supplied, the default of
// unix:/var/run/openvswitch/ovsdb.sock is used
func NewOVSDBClient(clientDBModel model.ClientDBModel, opts ...Option) (Client, error) {
return newOVSDBClient(clientDBModel, opts...)
}
// newOVSDBClient creates a new ovsdbClient
func newOVSDBClient(clientDBModel model.ClientDBModel, opts ...Option) (*ovsdbClient, error) {
ovs := &ovsdbClient{
primaryDBName: clientDBModel.Name(),
databases: map[string]*database{
clientDBModel.Name(): {
model: model.NewPartialDatabaseModel(clientDBModel),
monitors: make(map[string]*Monitor),
deferUpdates: true,
deferredUpdates: make([]*bufferedUpdate, 0),
},
},
disconnect: make(chan struct{}),
}
var err error
ovs.options, err = newOptions(opts...)
if err != nil {
return nil, err
}
if ovs.options.logger == nil {
// create a new logger to log to stdout
l := stdr.NewWithOptions(log.New(os.Stderr, "", log.LstdFlags), stdr.Options{LogCaller: stdr.All}).WithName("libovsdb").WithValues(
"database", ovs.primaryDBName,
)
stdr.SetVerbosity(5)
ovs.logger = &l
} else {
// add the "database" value to the structured logger
// to make it easier to tell between different DBs (e.g. ovn nbdb vs. sbdb)
l := ovs.options.logger.WithValues(
"database", ovs.primaryDBName,
)
ovs.logger = &l
}
ovs.registerMetrics()
// if we should only connect to the leader, then add the special "_Server" database as well
if ovs.options.leaderOnly {
sm, err := serverdb.FullDatabaseModel()
if err != nil {
return nil, fmt.Errorf("could not initialize model _Server: %w", err)
}
ovs.databases[serverDB] = &database{
model: model.NewPartialDatabaseModel(sm),
monitors: make(map[string]*Monitor),
}
}
ovs.metrics.init(clientDBModel.Name())
return ovs, nil
}
// Connect opens a connection to an OVSDB Server using the
// endpoint provided when the Client was created.
// The connection can be configured using one or more Option(s), like WithTLSConfig
// If no WithEndpoint option is supplied, the default of unix:/var/run/openvswitch/ovsdb.sock is used
func (o *ovsdbClient) Connect(ctx context.Context) error {
if err := o.connect(ctx, false); err != nil {
if err == ErrAlreadyConnected {
return nil
}
return err
}
if o.options.leaderOnly {
if err := o.watchForLeaderChange(); err != nil {
return err
}
}
return nil
}
func (o *ovsdbClient) connect(ctx context.Context, reconnect bool) error {
o.rpcMutex.Lock()
defer o.rpcMutex.Unlock()
if o.rpcClient != nil {
return ErrAlreadyConnected
}
connected := false
connectErrors := []error{}
for _, endpoint := range o.options.endpoints {
u, err := url.Parse(endpoint)
if err != nil {
return err
}
if err := o.tryEndpoint(ctx, u); err != nil {
connectErrors = append(connectErrors,
fmt.Errorf("failed to connect to %s: %w", endpoint, err))
continue
} else {
o.logger.V(3).Info("successfully connected", "endpoint", endpoint)
o.activeEndpoint = endpoint
connected = true
break
}
}
if !connected {
if len(connectErrors) == 1 {
return connectErrors[0]
}
var combined []string
for _, e := range connectErrors {
combined = append(combined, e.Error())
}
return fmt.Errorf("unable to connect to any endpoints: %s", strings.Join(combined, ". "))
}
// if we're reconnecting, re-start all the monitors
if reconnect {
o.logger.V(3).Info("reconnected - restarting monitors")
for dbName, db := range o.databases {
db.monitorsMutex.Lock()
defer db.monitorsMutex.Unlock()
for id, request := range db.monitors {
err := o.monitor(ctx, MonitorCookie{DatabaseName: dbName, ID: id}, true, request)
if err != nil {
o.rpcClient.Close()
o.rpcClient = nil
return err
}
}
}
}
go o.handleDisconnectNotification()
for _, db := range o.databases {
go o.handleCacheErrors(o.stopCh, db.cache.Errors())
go db.cache.Run(o.stopCh)
}
o.connected = true
return nil
}
func (o *ovsdbClient) tryEndpoint(ctx context.Context, u *url.URL) error {
o.logger.V(5).Info("trying to connect", "endpoint", fmt.Sprintf("%v", u))
var dialer net.Dialer
var err error
var c net.Conn
switch u.Scheme {
case UNIX:
c, err = dialer.DialContext(ctx, u.Scheme, u.Path)
case TCP:
c, err = dialer.DialContext(ctx, u.Scheme, u.Opaque)
case SSL:
dialer := tls.Dialer{
Config: o.options.tlsConfig,
}
c, err = dialer.DialContext(ctx, "tcp", u.Opaque)
default:
err = fmt.Errorf("unknown network protocol %s", u.Scheme)
}
if err != nil {
return fmt.Errorf("failed to open connection: %w", err)
}
o.createRPC2Client(c)
serverDBNames, err := o.listDbs(ctx)
if err != nil {
o.rpcClient.Close()
o.rpcClient = nil
return err
}
// for every requested database, ensure the DB exists in the server and
// that the schema matches what we expect.
for dbName, db := range o.databases {
// check the server has what we want
found := false
for _, name := range serverDBNames {
if name == dbName {
found = true
break
}
}
if !found {
err = fmt.Errorf("target database %s not found", dbName)
o.rpcClient.Close()
o.rpcClient = nil
return err
}
// load and validate the schema
schema, err := o.getSchema(ctx, dbName)
if err != nil {
o.rpcClient.Close()
o.rpcClient = nil
return err
}
db.modelMutex.Lock()
var errors []error
db.model, errors = model.NewDatabaseModel(schema, db.model.Client())
db.modelMutex.Unlock()
if len(errors) > 0 {
var combined []string
for _, err := range errors {
combined = append(combined, err.Error())
}
err = fmt.Errorf("database %s validation error (%d): %s", dbName, len(errors),
strings.Join(combined, ". "))
o.rpcClient.Close()
o.rpcClient = nil
return err
}
db.cacheMutex.Lock()
if db.cache == nil {
db.cache, err = cache.NewTableCache(db.model, nil, o.logger)
if err != nil {
db.cacheMutex.Unlock()
o.rpcClient.Close()
o.rpcClient = nil
return err
}
db.api = newAPI(db.cache, o.logger)
} else {
db.cache.Purge(db.model)
}
db.cacheMutex.Unlock()
}
// check that this is the leader
if o.options.leaderOnly {
var leader bool
leader, err = o.isEndpointLeader(ctx)
if err != nil {
o.rpcClient.Close()
o.rpcClient = nil
return err
}
if !leader {
err = fmt.Errorf("endpoint is not leader")
o.rpcClient.Close()
o.rpcClient = nil
return err
}
}
return nil
}
// createRPC2Client creates an rpcClient using the provided connection
// It is also responsible for setting up go routines for client-side event handling
// Should only be called when the mutex is held
func (o *ovsdbClient) createRPC2Client(conn net.Conn) {
o.stopCh = make(chan struct{})
o.rpcClient = rpc2.NewClientWithCodec(jsonrpc.NewJSONCodec(conn))
o.rpcClient.SetBlocking(true)
o.rpcClient.Handle("echo", func(_ *rpc2.Client, args []interface{}, reply *[]interface{}) error {
return o.echo(args, reply)
})
o.rpcClient.Handle("update", func(_ *rpc2.Client, args []json.RawMessage, reply *[]interface{}) error {
return o.update(args, reply)
})
o.rpcClient.Handle("update2", func(_ *rpc2.Client, args []json.RawMessage, reply *[]interface{}) error {
return o.update2(args, reply)
})
o.rpcClient.Handle("update3", func(_ *rpc2.Client, args []json.RawMessage, reply *[]interface{}) error {
return o.update3(args, reply)
})
go o.rpcClient.Run()
}
// isEndpointLeader returns true if the currently connected endpoint is leader.
// assumes rpcMutex is held
func (o *ovsdbClient) isEndpointLeader(ctx context.Context) (bool, error) {
op := ovsdb.Operation{
Op: ovsdb.OperationSelect,
Table: "Database",
Columns: []string{"name", "model", "leader"},
}
results, err := o.transact(ctx, serverDB, op)
if err != nil {
return false, fmt.Errorf("could not check if server was leader: %w", err)
}
// for now, if no rows are returned, just accept this server
if len(results) != 1 {
return true, nil
}
result := results[0]
if len(result.Rows) == 0 {
return true, nil
}
for _, row := range result.Rows {
dbName, ok := row["name"].(string)
if !ok {
return false, fmt.Errorf("could not parse name")
}
if dbName != o.primaryDBName {
continue
}
model, ok := row["model"].(string)
if !ok {
return false, fmt.Errorf("could not parse model")
}
// the database reports whether or not it is part of a cluster via the
// "model" column. If it's not clustered, it is by definition leader.
if model != serverdb.DatabaseModelClustered {
return true, nil
}
leader, ok := row["leader"].(bool)
if !ok {
return false, fmt.Errorf("could not parse leader")
}
return leader, nil
}
// Extremely unlikely: there is no _Server row for the desired DB (which we made sure existed)
// for now, just continue
o.logger.V(3).Info("Couldn't find a row in _Server for our database. Continuing without leader detection", "database", o.primaryDBName)
return true, nil
}
func (o *ovsdbClient) primaryDB() *database {
return o.databases[o.primaryDBName]
}
// Schema returns the DatabaseSchema that is being used by the client
// it will be nil until a connection has been established
func (o *ovsdbClient) Schema() ovsdb.DatabaseSchema {
db := o.primaryDB()
db.modelMutex.RLock()
defer db.modelMutex.RUnlock()
return db.model.Schema
}
// Cache returns the TableCache that is populated from
// ovsdb update notifications. It will be nil until a connection
// has been established, and empty unless you call Monitor
func (o *ovsdbClient) Cache() *cache.TableCache {
db := o.primaryDB()
db.cacheMutex.RLock()
defer db.cacheMutex.RUnlock()
return db.cache
}
// SetOption sets a new value for an option.
// It may only be called when the client is not connected
func (o *ovsdbClient) SetOption(opt Option) error {
o.rpcMutex.RLock()
defer o.rpcMutex.RUnlock()
if o.rpcClient != nil {
return fmt.Errorf("cannot set option when client is connected")
}
return opt(o.options)
}
// Connected returns whether or not the client is currently connected to the server
func (o *ovsdbClient) Connected() bool {
o.rpcMutex.RLock()
defer o.rpcMutex.RUnlock()
return o.connected
}
func (o *ovsdbClient) CurrentEndpoint() string {
o.rpcMutex.RLock()
defer o.rpcMutex.RUnlock()
if o.rpcClient == nil {
return ""
}
return o.activeEndpoint
}
// DisconnectNotify returns a channel which will notify the caller when the
// server has disconnected
func (o *ovsdbClient) DisconnectNotify() chan struct{} {
return o.disconnect
}
// RFC 7047 : Section 4.1.6 : Echo
func (o *ovsdbClient) echo(args []interface{}, reply *[]interface{}) error {
*reply = args
return nil
}
// RFC 7047 : Update Notification Section 4.1.6
// params is an array of length 2: [json-value, table-updates]
// - json-value: the arbitrary json-value passed when creating the Monitor, i.e. the "cookie"
// - table-updates: map of table name to table-update. Table-update is a map of uuid to (old, new) row paris
func (o *ovsdbClient) update(params []json.RawMessage, reply *[]interface{}) error {
cookie := MonitorCookie{}
*reply = []interface{}{}
if len(params) > 2 {
return fmt.Errorf("update requires exactly 2 args")
}
err := json.Unmarshal(params[0], &cookie)
if err != nil {
return err
}
var updates ovsdb.TableUpdates
err = json.Unmarshal(params[1], &updates)
if err != nil {
return err
}
db := o.databases[cookie.DatabaseName]
if db == nil {
return fmt.Errorf("update: invalid database name: %s unknown", cookie.DatabaseName)
}
o.metrics.numUpdates.WithLabelValues(cookie.DatabaseName).Inc()
for tableName := range updates {
o.metrics.numTableUpdates.WithLabelValues(cookie.DatabaseName, tableName).Inc()
}
db.cacheMutex.Lock()
if db.deferUpdates {
db.deferredUpdates = append(db.deferredUpdates, &bufferedUpdate{&updates, nil, ""})
db.cacheMutex.Unlock()
return nil
}
db.cacheMutex.Unlock()
// Update the local DB cache with the tableUpdates
db.cacheMutex.RLock()
err = db.cache.Update(cookie.ID, updates)
db.cacheMutex.RUnlock()
return err
}
// update2 handling from ovsdb-server.7
func (o *ovsdbClient) update2(params []json.RawMessage, reply *[]interface{}) error {
cookie := MonitorCookie{}
*reply = []interface{}{}
if len(params) > 2 {
return fmt.Errorf("update2 requires exactly 2 args")
}
err := json.Unmarshal(params[0], &cookie)
if err != nil {
return err
}
var updates ovsdb.TableUpdates2
err = json.Unmarshal(params[1], &updates)
if err != nil {
return err
}
db := o.databases[cookie.DatabaseName]
if db == nil {
return fmt.Errorf("update: invalid database name: %s unknown", cookie.DatabaseName)
}
db.cacheMutex.Lock()
if db.deferUpdates {
db.deferredUpdates = append(db.deferredUpdates, &bufferedUpdate{nil, &updates, ""})
db.cacheMutex.Unlock()
return nil
}
db.cacheMutex.Unlock()
// Update the local DB cache with the tableUpdates
db.cacheMutex.RLock()
err = db.cache.Update2(cookie, updates)
db.cacheMutex.RUnlock()
return err
}
// update3 handling from ovsdb-server.7
func (o *ovsdbClient) update3(params []json.RawMessage, reply *[]interface{}) error {
cookie := MonitorCookie{}
*reply = []interface{}{}
if len(params) > 3 {
return fmt.Errorf("update requires exactly 3 args")
}
err := json.Unmarshal(params[0], &cookie)
if err != nil {
return err
}
var lastTransactionID string
err = json.Unmarshal(params[1], &lastTransactionID)
if err != nil {
return err
}
var updates ovsdb.TableUpdates2
err = json.Unmarshal(params[2], &updates)
if err != nil {
return err
}
db := o.databases[cookie.DatabaseName]
if db == nil {
return fmt.Errorf("update: invalid database name: %s unknown", cookie.DatabaseName)
}
db.cacheMutex.Lock()
if db.deferUpdates {
db.deferredUpdates = append(db.deferredUpdates, &bufferedUpdate{nil, &updates, lastTransactionID})
db.cacheMutex.Unlock()
return nil
}
db.cacheMutex.Unlock()
// Update the local DB cache with the tableUpdates
db.cacheMutex.RLock()
err = db.cache.Update2(cookie, updates)
db.cacheMutex.RUnlock()
if err == nil {
db.monitorsMutex.Lock()
mon := db.monitors[cookie.ID]
mon.LastTransactionID = lastTransactionID
db.monitorsMutex.Unlock()
}
return err
}
// getSchema returns the schema in use for the provided database name
// RFC 7047 : get_schema
// Should only be called when mutex is held
func (o *ovsdbClient) getSchema(ctx context.Context, dbName string) (ovsdb.DatabaseSchema, error) {
args := ovsdb.NewGetSchemaArgs(dbName)
var reply ovsdb.DatabaseSchema
err := o.rpcClient.CallWithContext(ctx, "get_schema", args, &reply)
if err != nil {
if err == rpc2.ErrShutdown {
return ovsdb.DatabaseSchema{}, ErrNotConnected
}
return ovsdb.DatabaseSchema{}, err
}
return reply, err
}
// listDbs returns the list of databases on the server
// RFC 7047 : list_dbs
// Should only be called when mutex is held
func (o *ovsdbClient) listDbs(ctx context.Context) ([]string, error) {
var dbs []string
err := o.rpcClient.CallWithContext(ctx, "list_dbs", nil, &dbs)
if err != nil {
if err == rpc2.ErrShutdown {
return nil, ErrNotConnected
}
return nil, fmt.Errorf("listdbs failure - %v", err)
}
return dbs, err
}
// Transact performs the provided Operations on the database
// RFC 7047 : transact
func (o *ovsdbClient) Transact(ctx context.Context, operation ...ovsdb.Operation) ([]ovsdb.OperationResult, error) {
o.rpcMutex.RLock()
if o.rpcClient == nil || !o.connected {
o.rpcMutex.RUnlock()
if o.options.reconnect {
o.logger.V(5).Info("blocking transaction until reconnected", "operations",
fmt.Sprintf("%+v", operation))
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
ReconnectWaitLoop:
for {
select {
case <-ctx.Done():
return nil, fmt.Errorf("%w: while awaiting reconnection", ctx.Err())
case <-ticker.C:
o.rpcMutex.RLock()
if o.rpcClient != nil && o.connected {
break ReconnectWaitLoop
}
o.rpcMutex.RUnlock()
}
}
} else {
return nil, ErrNotConnected
}
}
defer o.rpcMutex.RUnlock()
return o.transact(ctx, o.primaryDBName, operation...)
}
func (o *ovsdbClient) transact(ctx context.Context, dbName string, operation ...ovsdb.Operation) ([]ovsdb.OperationResult, error) {
var reply []ovsdb.OperationResult
db := o.databases[dbName]
db.modelMutex.RLock()
schema := o.databases[dbName].model.Schema
db.modelMutex.RUnlock()
if reflect.DeepEqual(schema, ovsdb.DatabaseSchema{}) {
return nil, fmt.Errorf("cannot transact to database %s: schema unknown", dbName)
}
if ok := schema.ValidateOperations(operation...); !ok {
return nil, fmt.Errorf("validation failed for the operation")
}
args := ovsdb.NewTransactArgs(dbName, operation...)
if o.rpcClient == nil {
return nil, ErrNotConnected
}
o.logger.V(5).Info("transacting operations", "database", dbName, "operations", fmt.Sprintf("%+v", operation))
err := o.rpcClient.CallWithContext(ctx, "transact", args, &reply)
if err != nil {
if err == rpc2.ErrShutdown {
return nil, ErrNotConnected
}
return nil, err
}
return reply, nil
}
// MonitorAll is a convenience method to monitor every table/column
func (o *ovsdbClient) MonitorAll(ctx context.Context) (MonitorCookie, error) {
m := newMonitor()
for name := range o.primaryDB().model.Types() {
m.Tables = append(m.Tables, TableMonitor{Table: name})
}
return o.Monitor(ctx, m)
}
// MonitorCancel will request cancel a previously issued monitor request
// RFC 7047 : monitor_cancel
func (o *ovsdbClient) MonitorCancel(ctx context.Context, cookie MonitorCookie) error {
var reply ovsdb.OperationResult
args := ovsdb.NewMonitorCancelArgs(cookie)
o.rpcMutex.Lock()
defer o.rpcMutex.Unlock()
if o.rpcClient == nil {
return ErrNotConnected
}
err := o.rpcClient.CallWithContext(ctx, "monitor_cancel", args, &reply)
if err != nil {
if err == rpc2.ErrShutdown {
return ErrNotConnected
}
return err
}
if reply.Error != "" {
return fmt.Errorf("error while executing transaction: %s", reply.Error)
}
o.primaryDB().monitorsMutex.Lock()
defer o.primaryDB().monitorsMutex.Unlock()
delete(o.primaryDB().monitors, cookie.ID)
o.metrics.numMonitors.Dec()
return nil
}
// Monitor will provide updates for a given table/column
// and populate the cache with them. Subsequent updates will be processed
// by the Update Notifications
// RFC 7047 : monitor
func (o *ovsdbClient) Monitor(ctx context.Context, monitor *Monitor) (MonitorCookie, error) {
cookie := newMonitorCookie(o.primaryDBName)
db := o.databases[o.primaryDBName]
db.monitorsMutex.Lock()
defer db.monitorsMutex.Unlock()
return cookie, o.monitor(ctx, cookie, false, monitor)
}
//gocyclo:ignore
// monitor must only be called with a lock on monitorsMutex
func (o *ovsdbClient) monitor(ctx context.Context, cookie MonitorCookie, reconnecting bool, monitor *Monitor) error {
// if we're reconnecting, we already hold the rpcMutex
if !reconnecting {
o.rpcMutex.RLock()
defer o.rpcMutex.RUnlock()
}
if o.rpcClient == nil {
return ErrNotConnected
}
if len(monitor.Tables) == 0 {
return fmt.Errorf("at least one table should be monitored")
}
if len(monitor.Errors) != 0 {
var errString []string
for _, err := range monitor.Errors {
errString = append(errString, err.Error())
}
return fmt.Errorf(strings.Join(errString, ". "))
}
dbName := cookie.DatabaseName
db := o.databases[dbName]
db.modelMutex.RLock()
mmapper := db.model.Mapper
typeMap := db.model.Types()
requests := make(map[string]ovsdb.MonitorRequest)
for _, o := range monitor.Tables {
_, ok := typeMap[o.Table]
if !ok {
return fmt.Errorf("type for table %s does not exist in model", o.Table)
}
model, err := db.model.NewModel(o.Table)
if err != nil {
return err
}
info, err := db.model.NewModelInfo(model)
if err != nil {
return err
}
request, err := mmapper.NewMonitorRequest(info, o.Fields)
if err != nil {
return err
}
requests[o.Table] = *request
}
db.modelMutex.RUnlock()
var args []interface{}
if monitor.Method == ovsdb.ConditionalMonitorSinceRPC {
// FIXME: We should pass the monitor.LastTransactionID here
// But that would require delaying clearing the cache until
// after the monitors have been re-established - the logic
// would also need to be different for monitor and monitor_cond
// as we must always clear the cache in that instance
args = ovsdb.NewMonitorCondSinceArgs(dbName, cookie, requests, emptyUUID)
} else {
args = ovsdb.NewMonitorArgs(dbName, cookie, requests)
}
var err error
var tableUpdates interface{}
switch monitor.Method {
case ovsdb.MonitorRPC:
var reply ovsdb.TableUpdates
err = o.rpcClient.CallWithContext(ctx, monitor.Method, args, &reply)
tableUpdates = reply
case ovsdb.ConditionalMonitorRPC:
var reply ovsdb.TableUpdates2
err = o.rpcClient.CallWithContext(ctx, monitor.Method, args, &reply)
tableUpdates = reply
case ovsdb.ConditionalMonitorSinceRPC:
var reply ovsdb.MonitorCondSinceReply
err = o.rpcClient.CallWithContext(ctx, monitor.Method, args, &reply)
if err == nil && reply.Found {
monitor.LastTransactionID = reply.LastTransactionID
}
tableUpdates = reply.Updates
default:
return fmt.Errorf("unsupported monitor method: %v", monitor.Method)
}
if err != nil {
if err == rpc2.ErrShutdown {
return ErrNotConnected
}
if err.Error() == "unknown method" {
if monitor.Method == ovsdb.ConditionalMonitorSinceRPC {
o.logger.V(3).Error(err, "method monitor_cond_since not supported, falling back to monitor_cond")
monitor.Method = ovsdb.ConditionalMonitorRPC
return o.monitor(ctx, cookie, reconnecting, monitor)
}
if monitor.Method == ovsdb.ConditionalMonitorRPC {
o.logger.V(3).Error(err, "method monitor_cond not supported, falling back to monitor")
monitor.Method = ovsdb.MonitorRPC
return o.monitor(ctx, cookie, reconnecting, monitor)
}
}
return err
}
if !reconnecting {
db.monitors[cookie.ID] = monitor
o.metrics.numMonitors.Inc()
}
db.cacheMutex.Lock()
defer db.cacheMutex.Unlock()
if monitor.Method == ovsdb.MonitorRPC {
u := tableUpdates.(ovsdb.TableUpdates)
err = db.cache.Populate(u)
} else {
u := tableUpdates.(ovsdb.TableUpdates2)
err = db.cache.Populate2(u)
}
if err != nil {
return err
}
// populate any deferred updates
db.deferUpdates = false
for _, update := range db.deferredUpdates {
if update.updates != nil {
if err = db.cache.Populate(*update.updates); err != nil {
return err
}
}
if update.updates2 != nil {
if err = db.cache.Populate2(*update.updates2); err != nil {
return err
}
}
if len(update.lastTxnID) > 0 {
db.monitors[cookie.ID].LastTransactionID = update.lastTxnID
}
}
// clear deferred updates for next time
db.deferredUpdates = make([]*bufferedUpdate, 0)
return err
}
// Echo tests the liveness of the OVSDB connetion
func (o *ovsdbClient) Echo(ctx context.Context) error {
args := ovsdb.NewEchoArgs()
var reply []interface{}
o.rpcMutex.RLock()
defer o.rpcMutex.RUnlock()
if o.rpcClient == nil {
return ErrNotConnected
}
err := o.rpcClient.CallWithContext(ctx, "echo", args, &reply)
if err != nil {
if err == rpc2.ErrShutdown {
return ErrNotConnected
}
}
if !reflect.DeepEqual(args, reply) {
return fmt.Errorf("incorrect server response: %v, %v", args, reply)
}
return nil
}
// watchForLeaderChange will trigger a reconnect if the connected endpoint
// ever loses leadership
func (o *ovsdbClient) watchForLeaderChange() error {
updates := make(chan model.Model)
o.databases[serverDB].cache.AddEventHandler(&cache.EventHandlerFuncs{
UpdateFunc: func(table string, _, new model.Model) {
if table == "Database" {
updates <- new
}
},
})
m := newMonitor()
// NOTE: _Server does not support monitor_cond_since
m.Method = ovsdb.ConditionalMonitorRPC
m.Tables = []TableMonitor{{Table: "Database"}}
db := o.databases[serverDB]
db.monitorsMutex.Lock()
defer db.monitorsMutex.Unlock()
err := o.monitor(context.Background(), newMonitorCookie(serverDB), false, m)
if err != nil {
return err
}
go func() {
for m := range updates {
dbInfo, ok := m.(*serverdb.Database)
if !ok {
continue
}
// Ignore the dbInfo for _Server
if dbInfo.Name != o.primaryDBName {
continue
}
if dbInfo.Model == serverdb.DatabaseModelClustered && !dbInfo.Leader && o.Connected() {
o.logger.V(3).Info("endpoint lost leader, reconnecting", "endpoint", o.activeEndpoint)
o.Disconnect()
}
}
}()
return nil
}
func (o *ovsdbClient) handleCacheErrors(stopCh <-chan struct{}, errorChan <-chan error) {
for {
select {
case <-stopCh:
return
case err := <-errorChan: