-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathclient.go
More file actions
704 lines (612 loc) · 16.7 KB
/
client.go
File metadata and controls
704 lines (612 loc) · 16.7 KB
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
//
// Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
//
package contrail
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strings"
"unicode"
)
// TypeMap is used to inject the auto-generated types library.
//
// Types are generated from the OpenContrail schema and allow the library
// to operate in terms of go structs that contain fields that represent
// IF-MAP properties (metadata associated with a single Identifier) and
// arrays of references to other Identifiers (with optional metadata).
// Each auto-generated type implements the IObject interface.
type TypeMap map[string]reflect.Type
// objectInterface defines the interface used internally between
// ObjectBase and Client implmementation
type objectInterface interface {
GetField(IObject, string) error
UpdateReference(*ReferenceUpdateMsg) error
}
// The Authenticator interface is used to add an autentication token on a per
// request basis. This is used by the Keystone authentication class to decorate
// the requests with a token.
type Authenticator interface {
AddAuthentication(*http.Request) error
}
// NopAuthenticator is an authentication that doesn't modify the request.
type NopAuthenticator struct {
}
// AddAuthentication implements the Authenticator interface for NopAuthenticator.
func (*NopAuthenticator) AddAuthentication(*http.Request) error {
return nil
}
// The Encryptor interface is used to add an encryption to the REST call
type Encryptor interface {
AddEncryption(caFile string, keyFile string, certFile string, insecure bool) error
}
// NopEncryptor doesn't add encryption
type NopEncryptor struct {
}
// AddEncryption implements the Encryptor interface for NopEncryptor.
func (*NopEncryptor) AddEncryption(caFile string, keyFile string, certFile string, insecure bool) error {
return nil
}
// AddEncryption implements the Encryptor interface for Client.
func (c *Client) AddEncryption(caFile string, keyFile string, certFile string, insecure bool) error {
c.scheme = "https"
tlsConfig := &tls.Config{}
if insecure {
tlsConfig.InsecureSkipVerify = true
} else if caFile != "" {
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
return nil
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
if certFile != "" && keyFile != "" {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil
}
tlsConfig.Certificates = []tls.Certificate{cert}
} else {
tlsConfig.InsecureSkipVerify = true
}
}
transport := &http.Transport{
TLSClientConfig: tlsConfig,
}
c.httpClient.Transport = transport
return nil
}
// ApiClient interface
type ApiClient interface {
Create(ptr IObject) error
Update(ptr IObject) error
DeleteByUuid(typename, uuid string) error
Delete(ptr IObject) error
FindByUuid(typename string, uuid string) (IObject, error)
UuidByName(typename string, fqn string) (string, error)
FQNameByUuid(uuid string) ([]string, error)
FindByName(typename string, fqn string) (IObject, error)
List(typename string) ([]ListResult, error)
ListByParent(typename string, parentID string) ([]ListResult, error)
ListDetail(typename string, fields []string) ([]IObject, error)
ListDetailByParent(typename string, parentID string, fields []string) ([]IObject, error)
}
// A Client of the OpenContrail API server.
type Client struct {
server string
scheme string
port int
httpClient *http.Client
auth Authenticator
encrypt Encryptor
}
type TlsConfig struct {
ca string
key string
cert string
}
// ListResult is the return type of the {List, ListByParent} API calls.
type ListResult struct {
Fq_name []string
Href string
Uuid string
}
var (
typeMap TypeMap
)
// NewClient allocates and initializes a Contrail API client.
//
func NewClient(server string, port int) *Client {
client := new(Client)
client.server = server
client.port = port
client.scheme = "http"
client.httpClient = &http.Client{}
client.auth = new(NopAuthenticator)
client.encrypt = new(NopEncryptor)
return client
}
// GetServer retrieves the name or address of the Contrail API server.
func (c *Client) GetServer() string {
return c.server
}
// SetAuthenticator enables the user to configure an Authenticator (e.g. Keystone)
// to be used by Contrail API requests.
func (c *Client) SetAuthenticator(auth Authenticator) {
c.auth = auth
}
// SetEncryptor enables the user to encrypt the API traffic
func (c *Client) SetEncryptor(encrypt Encryptor) {
c.encrypt = encrypt
}
func typename(ptr IObject) string {
name := reflect.TypeOf(ptr).Elem().Name()
var buf []rune
for i, c := range name {
if unicode.IsUpper(c) {
if i > 0 {
buf = append(buf, '-')
}
buf = append(buf, unicode.ToLower(c))
} else {
buf = append(buf, c)
}
}
return string(buf)
}
func (c *Client) httpPost(url string, bodyType string, body io.Reader) (
*http.Response, error) {
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", bodyType)
err = c.auth.AddAuthentication(req)
if err != nil {
return nil, err
}
return c.httpClient.Do(req)
}
func (c *Client) httpPut(url string, bodyType string, body io.Reader) (
*http.Response, error) {
req, err := http.NewRequest("PUT", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", bodyType)
err = c.auth.AddAuthentication(req)
if err != nil {
return nil, err
}
return c.httpClient.Do(req)
}
func (c *Client) httpGet(url string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
err = c.auth.AddAuthentication(req)
if err != nil {
return nil, err
}
return c.httpClient.Do(req)
}
func (c *Client) httpDelete(url string) (*http.Response, error) {
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
err = c.auth.AddAuthentication(req)
if err != nil {
return nil, err
}
return c.httpClient.Do(req)
}
// Create an object in the OpenContrail API server.
//
// The object must have been initialized with a name.
func (c *Client) Create(ptr IObject) error {
xtype := typename(ptr)
url := fmt.Sprintf("%s://%s:%d/%ss", c.scheme, c.server, c.port, xtype)
objJson, err := json.Marshal(ptr)
if err != nil {
return err
}
var rawJson json.RawMessage = objJson
msg := map[string]*json.RawMessage{
xtype: &rawJson,
}
data, err := json.Marshal(msg)
resp, err := c.httpPost(url, "application/json", bytes.NewReader(data))
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s: %s", resp.Status, body)
}
ptr.SetClient(c)
var m map[string]json.RawMessage
err = json.Unmarshal(body, &m)
if err != nil {
return err
}
return json.Unmarshal(m[xtype], ptr)
}
// Read an object from the API server.
//
// This method retrieves the object properties but not its references to
// other objects.
func (c *Client) readObject(typename string, href string) (IObject, error) {
url := fmt.Sprintf("%s?exclude_back_refs=true&exclude_children=true",
href)
resp, err := c.httpGet(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, body)
}
var m map[string]*json.RawMessage
err = json.Unmarshal(body, &m)
if err != nil {
return nil, err
}
content, ok := m[typename]
if !ok {
return nil, fmt.Errorf("No %s in Response", typename)
}
var xtype reflect.Type = typeMap[typename]
valueT := reflect.New(xtype)
obj := valueT.Interface().(IObject)
err = json.Unmarshal(*content, obj)
if err != nil {
return nil, err
}
obj.SetClient(c)
return obj, err
}
// Given a ListResult, retrieve an object from the API server.
func (c *Client) ReadListResult(
typename string, result *ListResult) (IObject, error) {
return c.readObject(typename, result.Href)
}
// Given a link reference, retrieve an object from the API server.
func (c *Client) ReadReference(
typename string, ref *Reference) (IObject, error) {
return c.readObject(typename, ref.Href)
}
// Update the API server with the changes made in the local representation
// of the object.
//
// There is currently no mechanism to guarantee that the object as not
// been concurrently modified in the API server.
// Updates modify properties that have been marked as modified in the local
// representation.
func (c *Client) Update(ptr IObject) error {
objJson, err := ptr.UpdateObject()
if err != nil {
return err
}
var rawJson json.RawMessage = objJson
msg := map[string]*json.RawMessage{
ptr.GetType(): &rawJson,
}
data, err := json.Marshal(msg)
if err != nil {
return err
}
resp, err := c.httpPut(ptr.GetHref(), "application/json",
bytes.NewReader(data))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("%s: %s", resp.Status, body)
}
err = ptr.UpdateReferences()
if err != nil {
return err
}
ptr.UpdateDone()
return nil
}
// DeleteByUuid deletes the specified object.
func (c *Client) DeleteByUuid(typename, uuid string) error {
url := fmt.Sprintf("%s://%s:%d/%s/%s", c.scheme, c.server, c.port, typename, uuid)
resp, err := c.httpDelete(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("%s: %s", resp.Status, body)
}
return nil
}
// Delete an object from the API server.
func (c *Client) Delete(ptr IObject) error {
resp, err := c.httpDelete(ptr.GetHref())
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("%s: %s", resp.Status, body)
}
return nil
}
// FindByUuid reads an object identified by UUID.
func (c *Client) FindByUuid(typename string, uuid string) (IObject, error) {
url := fmt.Sprintf("%s://%s:%d/%s/%s", c.scheme, c.server, c.port,
typename, uuid)
return c.readObject(typename, url)
}
// UuidByName returns the UUID of an object as identified by its fully qualified name.
func (c *Client) UuidByName(typename string, fqn string) (string, error) {
url := fmt.Sprintf("%s://%s:%d/fqname-to-id", c.scheme, c.server, c.port)
request := struct {
Typename string `json:"type"`
Fq_name []string `json:"fq_name"`
}{
typename,
strings.Split(fqn, ":"),
}
data, err := json.Marshal(request)
if err != nil {
return "", err
}
resp, err := c.httpPost(url, "application/json", bytes.NewReader(data))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("%s: %s", resp.Status, body)
}
m := struct {
Uuid string
}{}
err = json.Unmarshal(body, &m)
if err != nil {
return "", err
}
return m.Uuid, nil
}
// FQNameByUuid returns the fully-qualified name of an object as identified by a UUID.
func (c *Client) FQNameByUuid(uuid string) ([]string, error) {
request := struct {
Uuid string `json:"uuid"`
}{
uuid,
}
data, err := json.Marshal(request)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s://%s:%d/id-to-fqname", c.scheme, c.server, c.port)
resp, err := c.httpPost(url, "application/json", bytes.NewReader(data))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, body)
}
var response struct {
Type string
Fq_name []string
}
err = json.Unmarshal(body, &response)
return response.Fq_name, err
}
// FindByName reads an object identified by fully-qualified name represented as a
// string.
func (c *Client) FindByName(typename string, fqn string) (IObject, error) {
uuid, err := c.UuidByName(typename, fqn)
if err != nil {
return nil, err
}
href := fmt.Sprintf(
"%s://%s:%d/%s/%s", c.scheme, c.server, c.port, typename, uuid)
return c.readObject(typename, href)
}
// ListByParent retrieves the identifiers of the objects of a specific type that are
// descendents of a specific object.
func (c *Client) ListByParent(
typename string, parentID string) ([]ListResult, error) {
var values url.Values
values = make(url.Values, 0)
if len(parentID) > 0 {
values.Add("parent_id", parentID)
}
url := fmt.Sprintf("%s://%s:%d/%ss", c.scheme, c.server, c.port, typename)
if len(values) > 0 {
url += fmt.Sprintf("?%s", values.Encode())
}
resp, err := c.httpGet(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, body)
}
var m map[string]*json.RawMessage
err = json.Unmarshal(body, &m)
if err != nil {
return nil, err
}
content, ok := m[typename+"s"]
if !ok {
return nil, fmt.Errorf("No %ss in Response", typename)
}
var rlist []ListResult
err = json.Unmarshal(*content, &rlist)
return rlist, err
}
// List retrieves the identifiers of all objects of a given type.
func (c *Client) List(typename string) ([]ListResult, error) {
return c.ListByParent(typename, "")
}
// ListDetailByParent reads all the objects of a given type that are descendents of the
// specified parent object.
func (c *Client) ListDetailByParent(
typename string, parentID string, fields []string) (
[]IObject, error) {
var values url.Values
values = make(url.Values, 0)
if len(parentID) > 0 {
values.Add("parent_id", parentID)
}
for _, field := range fields {
values.Add("fields", field)
}
values.Add("detail", "true")
url := fmt.Sprintf("%s://%s:%d/%ss?%s", c.scheme, c.server, c.port, typename, values.Encode())
resp, err := c.httpGet(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, body)
}
var m map[string]*json.RawMessage
err = json.Unmarshal(body, &m)
if err != nil {
return nil, err
}
content, ok := m[typename+"s"]
if !ok {
return nil, fmt.Errorf("No %ss in Response", typename)
}
var elements []*json.RawMessage
err = json.Unmarshal(*content, &elements)
if err != nil {
return nil, err
}
var result []IObject
var xtype reflect.Type = typeMap[typename]
for _, element := range elements {
var item map[string]*json.RawMessage
err = json.Unmarshal(*element, &item)
if err != nil {
return nil, err
}
content, ok := item[typename]
if !ok {
return nil, fmt.Errorf("No %s in element", typename)
}
valueT := reflect.New(xtype)
obj := valueT.Interface().(IObject)
err = json.Unmarshal(*content, obj)
if err != nil {
return nil, err
}
obj.SetClient(c)
result = append(result, obj)
}
return result, nil
}
// ListDetail reads all the objects of a specific type.
func (c *Client) ListDetail(typename string, fields []string) (
[]IObject, error) {
return c.ListDetailByParent(typename, "", fields)
}
// GetField retrieves a specified field of an object from the API server.
// This API is used by the generated types library to retrieve reference lists.
func (c *Client) GetField(obj IObject, field string) error {
url := fmt.Sprintf("%s?fields=%s", obj.GetHref(), field)
resp, err := c.httpGet(url)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s: %s", resp.Status, body)
}
var m map[string]json.RawMessage
err = json.Unmarshal(body, &m)
if err != nil {
return err
}
return json.Unmarshal(m[obj.GetType()], obj)
}
// UpdateReference sends a reference update message to the API server.
// Used by the generated types library.
func (c *Client) UpdateReference(msg *ReferenceUpdateMsg) error {
data, err := json.Marshal(msg)
if err != nil {
return err
}
url := fmt.Sprintf("%s://%s:%d/ref-update", c.scheme, c.server, c.port)
resp, err := c.httpPost(url, "application/json", bytes.NewReader(data))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("%s: %s", resp.Status, body)
}
return nil
}
// RegisterTypeMap is used by the generated types library to register the list of known
// object types.
func RegisterTypeMap(m TypeMap) {
typeMap = m
}