forked from ovn-org/libovsdb
-
Notifications
You must be signed in to change notification settings - Fork 15
/
client.go
374 lines (327 loc) · 9.71 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
package libovsdb
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/url"
"reflect"
"strings"
"sync"
"github.com/cenkalti/rpc2"
"github.com/cenkalti/rpc2/jsonrpc"
)
// OvsdbClient is an OVSDB client
type OvsdbClient struct {
rpcClient *rpc2.Client
Schema map[string]DatabaseSchema
Apis map[string]NativeAPI
handlers []NotificationHandler
handlersMutex *sync.Mutex
}
func newOvsdbClient(c *rpc2.Client) *OvsdbClient {
ovs := &OvsdbClient{
rpcClient: c,
Schema: make(map[string]DatabaseSchema),
handlersMutex: &sync.Mutex{},
}
return ovs
}
// Would rather replace this connection map with an OvsdbClient Receiver scoped method
// Unfortunately rpc2 package acts wierd with a receiver scoped method and needs some investigation.
var (
connections map[*rpc2.Client]*OvsdbClient
connectionsMutex = &sync.RWMutex{}
)
// Constants defined for libovsdb
const (
defaultTCPAddress = "127.0.0.1:6640"
defaultUnixAddress = "/var/run/openvswitch/ovnnb_db.sock"
SSL = "ssl"
TCP = "tcp"
UNIX = "unix"
)
// Connect to ovn, using endpoint in format ovsdb Connection Methods
// If address is empty, use default address for specified protocol
func Connect(endpoints string, tlsConfig *tls.Config) (*OvsdbClient, error) {
var c net.Conn
var err error
var u *url.URL
for _, endpoint := range strings.Split(endpoints, ",") {
if u, err = url.Parse(endpoint); err != nil {
return nil, err
}
// u.Opaque contains the original endPoint with the leading protocol stripped
// off. For example: endPoint is "tcp:127.0.0.1:6640" and u.Opaque is "127.0.0.1:6640"
host := u.Opaque
if len(host) == 0 {
host = defaultTCPAddress
}
switch u.Scheme {
case UNIX:
path := u.Path
if len(path) == 0 {
path = defaultUnixAddress
}
c, err = net.Dial(u.Scheme, path)
case TCP:
c, err = net.Dial(u.Scheme, host)
case SSL:
c, err = tls.Dial("tcp", host, tlsConfig)
default:
err = fmt.Errorf("unknown network protocol %s", u.Scheme)
}
if err == nil {
return newRPC2Client(c)
}
}
return nil, fmt.Errorf("failed to connect to endpoints %q: %v", endpoints, err)
}
func handleMonitorCancel(client *rpc2.Client, params []interface{}, reply *interface{}) error {
log.Println("monitor cancel received")
return client.Close()
}
func newRPC2Client(conn net.Conn) (*OvsdbClient, error) {
c := rpc2.NewClientWithCodec(jsonrpc.NewJSONCodec(conn))
c.SetBlocking(true)
c.Handle("echo", echo)
c.Handle("update", update)
c.Handle("monitor_cancel", handleMonitorCancel)
go c.Run()
go handleDisconnectNotification(c)
ovs := newOvsdbClient(c)
// Process Async Notifications
dbs, err := ovs.ListDbs()
if err != nil {
c.Close()
return nil, err
}
ovs.Apis = make(map[string]NativeAPI)
for _, db := range dbs {
schema, err := ovs.GetSchema(db)
if err == nil {
ovs.Schema[db] = *schema
ovs.Apis[db] = NewNativeAPI(schema)
} else {
c.Close()
return nil, err
}
}
connectionsMutex.Lock()
defer connectionsMutex.Unlock()
if connections == nil {
connections = make(map[*rpc2.Client]*OvsdbClient)
}
connections[c] = ovs
return ovs, nil
}
// Register registers the supplied NotificationHandler to recieve OVSDB Notifications
func (ovs *OvsdbClient) Register(handler NotificationHandler) {
ovs.handlersMutex.Lock()
defer ovs.handlersMutex.Unlock()
ovs.handlers = append(ovs.handlers, handler)
}
//Get Handler by index
func getHandlerIndex(handler NotificationHandler, handlers []NotificationHandler) (int, error) {
for i, h := range handlers {
if reflect.DeepEqual(h, handler) {
return i, nil
}
}
return -1, errors.New("Handler not found")
}
// Unregister the supplied NotificationHandler to not recieve OVSDB Notifications anymore
func (ovs *OvsdbClient) Unregister(handler NotificationHandler) error {
ovs.handlersMutex.Lock()
defer ovs.handlersMutex.Unlock()
i, err := getHandlerIndex(handler, ovs.handlers)
if err != nil {
return err
}
ovs.handlers = append(ovs.handlers[:i], ovs.handlers[i+1:]...)
return nil
}
// NotificationHandler is the interface that must be implemented to receive notifcations
type NotificationHandler interface {
// RFC 7047 section 4.1.6 Update Notification
Update(context interface{}, tableUpdates TableUpdates)
// RFC 7047 section 4.1.9 Locked Notification
Locked([]interface{})
// RFC 7047 section 4.1.10 Stolen Notification
Stolen([]interface{})
// RFC 7047 section 4.1.11 Echo Notification
Echo([]interface{})
Disconnected(*OvsdbClient)
}
// RFC 7047 : Section 4.1.6 : Echo
func echo(client *rpc2.Client, args []interface{}, reply *[]interface{}) error {
*reply = args
connectionsMutex.RLock()
defer connectionsMutex.RUnlock()
if _, ok := connections[client]; ok {
connections[client].handlersMutex.Lock()
defer connections[client].handlersMutex.Unlock()
for _, handler := range connections[client].handlers {
handler.Echo(nil)
}
}
return nil
}
// RFC 7047 : Update Notification Section 4.1.6
// Processing "params": [<json-value>, <table-updates>]
func update(client *rpc2.Client, params []interface{}, _ *interface{}) error {
if len(params) < 2 {
return errors.New("Invalid Update message")
}
// Ignore params[0] as we dont use the <json-value> currently for comparison
raw, ok := params[1].(map[string]interface{})
if !ok {
return errors.New("Invalid Update message")
}
var rowUpdates map[string]map[string]RowUpdate
b, err := json.Marshal(raw)
if err != nil {
return err
}
err = json.Unmarshal(b, &rowUpdates)
if err != nil {
return err
}
// Update the local DB cache with the tableUpdates
tableUpdates := getTableUpdatesFromRawUnmarshal(rowUpdates)
connectionsMutex.RLock()
defer connectionsMutex.RUnlock()
if _, ok := connections[client]; ok {
connections[client].handlersMutex.Lock()
defer connections[client].handlersMutex.Unlock()
for _, handler := range connections[client].handlers {
handler.Update(params[0], tableUpdates)
}
}
return nil
}
// GetSchema returns the schema in use for the provided database name
// RFC 7047 : get_schema
func (ovs OvsdbClient) GetSchema(dbName string) (*DatabaseSchema, error) {
args := NewGetSchemaArgs(dbName)
var reply DatabaseSchema
err := ovs.rpcClient.Call("get_schema", args, &reply)
if err != nil {
return nil, err
}
ovs.Schema[dbName] = reply
return &reply, err
}
// ListDbs returns the list of databases on the server
// RFC 7047 : list_dbs
func (ovs OvsdbClient) ListDbs() ([]string, error) {
var dbs []string
err := ovs.rpcClient.Call("list_dbs", nil, &dbs)
if err != nil {
return nil, fmt.Errorf("ListDbs failure - %v", err)
}
return dbs, err
}
// Transact performs the provided Operation's on the database
// RFC 7047 : transact
func (ovs OvsdbClient) Transact(database string, operation ...Operation) ([]OperationResult, error) {
var reply []OperationResult
db, ok := ovs.Schema[database]
if !ok {
return nil, fmt.Errorf("invalid Database %q Schema", database)
}
if ok := db.validateOperations(operation...); !ok {
return nil, errors.New("Validation failed for the operation")
}
args := NewTransactArgs(database, operation...)
err := ovs.rpcClient.Call("transact", args, &reply)
if err != nil {
return nil, err
}
return reply, nil
}
// MonitorAll is a convenience method to monitor every table/column
func (ovs OvsdbClient) MonitorAll(database string, jsonContext interface{}) (*TableUpdates, error) {
schema, ok := ovs.Schema[database]
if !ok {
return nil, fmt.Errorf("invalid Database %q Schema", database)
}
requests := make(map[string]MonitorRequest)
for table, tableSchema := range schema.Tables {
var columns []string
for column := range tableSchema.Columns {
columns = append(columns, column)
}
requests[table] = MonitorRequest{
Columns: columns,
Select: MonitorSelect{
Initial: true,
Insert: true,
Delete: true,
Modify: true,
}}
}
return ovs.Monitor(database, jsonContext, requests)
}
// MonitorCancel will request cancel a previously issued monitor request
// RFC 7047 : monitor_cancel
func (ovs OvsdbClient) MonitorCancel(jsonContext interface{}) error {
var reply OperationResult
args := NewMonitorCancelArgs(jsonContext)
err := ovs.rpcClient.Call("monitor_cancel", args, &reply)
if err != nil {
return err
}
if reply.Error != "" {
return fmt.Errorf("Error while executing transaction: %s", reply.Error)
}
return nil
}
// Monitor will provide updates for a given table/column
// RFC 7047 : monitor
func (ovs OvsdbClient) Monitor(database string, jsonContext interface{}, requests map[string]MonitorRequest) (*TableUpdates, error) {
var reply TableUpdates
args := NewMonitorArgs(database, jsonContext, requests)
// This totally sucks. Refer to golang JSON issue #6213
var response map[string]map[string]RowUpdate
err := ovs.rpcClient.Call("monitor", args, &response)
reply = getTableUpdatesFromRawUnmarshal(response)
if err != nil {
return nil, err
}
return &reply, err
}
func getTableUpdatesFromRawUnmarshal(raw map[string]map[string]RowUpdate) TableUpdates {
var tableUpdates TableUpdates
tableUpdates.Updates = make(map[string]TableUpdate)
for table, update := range raw {
tableUpdate := TableUpdate{update}
tableUpdates.Updates[table] = tableUpdate
}
return tableUpdates
}
func clearConnection(c *rpc2.Client) {
connectionsMutex.Lock()
defer connectionsMutex.Unlock()
if _, ok := connections[c]; ok {
for _, handler := range connections[c].handlers {
if handler != nil {
handler.Disconnected(connections[c])
}
}
}
delete(connections, c)
}
func handleDisconnectNotification(c *rpc2.Client) {
disconnected := c.DisconnectNotify()
select {
case <-disconnected:
clearConnection(c)
}
}
// Disconnect will close the OVSDB connection
func (ovs OvsdbClient) Disconnect() {
ovs.rpcClient.Close()
}