-
Notifications
You must be signed in to change notification settings - Fork 31
/
eapilib.go
606 lines (552 loc) · 20 KB
/
eapilib.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
//
// Copyright (c) 2015-2016, Arista Networks, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Arista Networks nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
package goeapi
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// EapiConnectionEntity is an interface representing the ability to execute a
// single json transaction, obtaining the Response for a given Request.
type EapiConnectionEntity interface {
Execute(commands []interface{}, encoding string) (*JSONRPCResponse, error)
SetTimeout(to uint32)
SetDisableKeepAlive(disableKeepAlive bool)
Error() error
}
// EapiConnection represents the base object for implementing an EapiConnection
// type. This clase should not be instantiated directly
type EapiConnection struct {
transport string
err error
url string
host string
port int
path string
auth *url.Userinfo
timeOut uint32
disableKeepAlive bool
}
// Execute the list of commands on the destination node. In the case of
// EapiConnection, this serves as a base model and is not fully implemented.
//
// Args:
// commands ([]interface): list of commands to execute on remote node
// encoding (string): The encoding to send along with the request
// message to the destination node. Valid values include
// 'json' or 'text'. This argument will influence the
// response encoding
// Returns:
// pointer to JSONRPCResponse or error on failure
func (conn *EapiConnection) Execute(commands []interface{},
encoding string) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No connection")
}
return &JSONRPCResponse{}, fmt.Errorf("Not Currently Implemented")
}
// Authentication Configures the user authentication for eAPI. This method
// configures the username and password combination to use for authenticating
// to eAPI.
//
// Args:
// username (string): The username to use to authenticate the eAPI
// connection with
// password (string): The password in clear text to use to authenticate
// the eAPI connection with
func (conn *EapiConnection) Authentication(username string, passwd string) {
username = strings.Replace(username, "\n", "", -1)
passwd = strings.Replace(passwd, "\n", "", -1)
conn.auth = url.UserPassword(username, passwd)
}
// getURL helper method to prebuild url for http/s
func (conn *EapiConnection) getURL() string {
if conn == nil {
return ""
}
url := url.URL{
Scheme: conn.transport,
User: conn.auth,
Host: conn.host + ":" + strconv.Itoa(conn.port),
Path: "/command-api",
}
return url.String()
}
// Error returns the current error for Connection
func (conn *EapiConnection) Error() error {
if conn == nil {
return nil
}
return conn.err
}
// SetError sets error for Connection
func (conn *EapiConnection) SetError(e error) {
if conn == nil {
return
}
conn.err = e
}
// ClearError clears any error for Connection
func (conn *EapiConnection) ClearError() {
if conn == nil {
return
}
conn.err = nil
}
// SetTimeout sets timeout value for Connection
func (conn *EapiConnection) SetTimeout(timeOut uint32) {
var val uint32
if conn == nil {
return
}
if timeOut > 65535 {
val = 60
} else {
val = timeOut
}
conn.timeOut = val
}
// SetDisableKeepAlive sets disablekeepalive value for Connection
func (conn *EapiConnection) SetDisableKeepAlive(disableKeepAlive bool) {
conn.disableKeepAlive = disableKeepAlive
}
// buildJSONRequest builds a JSON request given a list of commands, encoding
// type of either json or text, and request id. The command list input is made
// up of a list of interface{} types. This is so associative entries and list
// entries both can be used. Returns []byte of the built JSON request.
// Successful call returns err == nil.
func buildJSONRequest(commands []interface{},
encoding string, reqid string) ([]byte, error) {
p := Parameters{1, commands, encoding}
req := Request{"2.0", "runCmds", p, reqid}
data, err := json.Marshal(req)
//debugJSON(data)
return data, err
}
// SocketEapiConnection represents the EapiConnection for handling Socket
// level transactions
type SocketEapiConnection struct {
EapiConnection
}
//
const defaultUnixSocket = "/var/run/command-api.sock"
// NewSocketEapiConnection initializes a SocketEapiConnection.
//
// Args:
// transport (string): The transport to use to create the instance.
// host (string): The IP addres or DNS host name of the connection device.
// username(string): The username to pass to the device to authenticate
// the eAPI connection.
// password(string): The password to pass to the device to authenticate
// the eAPI connection. The default value is ''
// port(int): The TCP port of the endpoint for the eAPI connection.
//
// Returns:
// Newly created SocketEapiConnection
func NewSocketEapiConnection(transport string, host string, username string,
password string, port int) EapiConnectionEntity {
conn := EapiConnection{transport: transport, host: host, port: port, timeOut: 60}
return &SocketEapiConnection{conn}
}
// send the eAPI request to the destination node
//
// This method is responsible for sending an eAPI request to the
// destination node and returning a response based on the JSONRPCResponse
// object. eAPI responds to request messages with either a success
// message or failure message. On successful decode of the Response,
// a JSONRPCResponse type is returned. Otherwise err is returned.
func (conn *SocketEapiConnection) send(data []byte) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No Connection")
}
timeOut := time.Duration(time.Duration(conn.timeOut) * time.Second)
// We create our fake URL. Post() will be checking the format, but it ignores
// the fqhn. Also we replace the Dial func with our own fakeDial() to create
// the socket connection. By doing this, we can leverage the
// client.Post/Get methods to compose our headers, etc..
//
fakeURL := "http://localhost/command-api"
var fakeDial = func(proto, addr string) (conn net.Conn, err error) {
return net.Dial("unix", defaultUnixSocket)
}
client := &http.Client{
Timeout: timeOut,
Transport: &http.Transport{
Dial: fakeDial,
},
}
resp, err := client.Post(fakeURL, "application/json", bytes.NewReader(data))
if err != nil {
conn.SetError(err)
return &JSONRPCResponse{}, err
}
defer func() {
if cerr := resp.Body.Close(); cerr != nil {
err = cerr
conn.SetError(err)
}
}()
jsonRsp, err := decodeEapiResponse(resp)
if err != nil {
conn.SetError(err)
return jsonRsp, err
}
return jsonRsp, nil
}
// Execute the list of commands on the destination node
//
// This method takes a list of commands and sends them to the
// destination node, returning the results. It is assumed that the
// list of commands (type []interface{}) has been properly built and
// enable mode passwd is set if needed. On success, a reference
// to JSONRPCResponse is returned...otherwise err is set.
//
// Args:
// commands ([]interface): list of commands to execute on remote node
// encoding (string): The encoding to send along with the request
// message to the destination node. Valid values include
// 'json' or 'text'. This argument will influence the
// response encoding
// Returns:
// pointer to JSONRPCResponse or error on failure
func (conn *SocketEapiConnection) Execute(commands []interface{},
encoding string) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No connection")
}
conn.ClearError()
data, err := buildJSONRequest(commands, encoding, strconv.Itoa(os.Getpid()))
if err != nil {
conn.SetError(err)
return &JSONRPCResponse{}, err
}
return conn.send(data)
}
// HTTPLocalEapiConnection is an EapiConnection suited for local HTTP connection
type HTTPLocalEapiConnection struct {
EapiConnection
}
// UseDefaultPortNum recommends the underlying api to use default value for
// Port Number.
const UseDefaultPortNum = -1
// DefaultHTTPLocalPort uses 8080
const DefaultHTTPLocalPort = 8080
// NewHTTPLocalEapiConnection initializes a HTTPLocalEapiConnection.
//
// Args:
// transport (string): The transport to use to create the instance.
// host (string): The IP addres or DNS host name of the connection device.
// username(string): The username to pass to the device to authenticate
// the eAPI connection.
// password(string): The password to pass to the device to authenticate
// the eAPI connection. The default value is ''
// port(int): The TCP port of the endpoint for the eAPI connection.
//
// Returns:
// Newly created SocketEapiConnection
func NewHTTPLocalEapiConnection(transport string, host string, username string,
password string, port int) EapiConnectionEntity {
if port == UseDefaultPortNum {
port = DefaultHTTPLocalPort
}
conn := EapiConnection{transport: transport, host: host, port: port, timeOut: 60}
return &HTTPLocalEapiConnection{conn}
}
// send the eAPI request to the destination node
//
// This method is responsible for sending an eAPI request to the
// destination node and returning a response based on the JSONRPCResponse
// object. eAPI responds to request messages with either a success
// message or failure message. On successful decode of the Response,
// a JSONRPCResponse type is returned. Otherwise err is returned.
//
// Args:
// data ([]byte): data to be sent
// Returns:
// ptr to JSONRPCResponse on success. Otherwise error will be returned.
func (conn *HTTPLocalEapiConnection) send(data []byte) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No Connection")
}
return &JSONRPCResponse{}, fmt.Errorf("Not Currently Implemented")
}
// Execute the list of commands
//
// This method takes a list of commands and sends them to the
// destination node, returning the results. It is assumed that the
// list of commands (type []interface{}) has been properly built and
// enable mode passwd is set if needed. On success, a reference
// to JSONRPCResponse is returned...otherwise err is set.
//
// Args:
// commands ([]interface): list of commands to execute on remote node
// encoding (string): The encoding to send along with the request
// message to the destination node. Valid values include
// 'json' or 'text'. This argument will influence the
// response encoding
// Returns:
// pointer to JSONRPCResponse or error on failure
func (conn *HTTPLocalEapiConnection) Execute(commands []interface{},
encoding string) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No connection")
}
conn.ClearError()
data, err := buildJSONRequest(commands, encoding, strconv.Itoa(os.Getpid()))
if err != nil {
conn.SetError(err)
return &JSONRPCResponse{}, err
}
return conn.send(data)
}
// HTTPEapiConnection is an EapiConnection suited for HTTP connection
type HTTPEapiConnection struct {
EapiConnection
}
// DefaultHTTPPort uses 80
const DefaultHTTPPort = 80
// NewHTTPEapiConnection initializes a HttpEapiConnection.
//
// Args:
// transport (string): The transport to use to create the instance.
// host (string): The IP addres or DNS host name of the connection device.
// username(string): The username to pass to the device to authenticate
// the eAPI connection.
// password(string): The password to pass to the device to authenticate
// the eAPI connection. The default value is ''
// port(int): The TCP port of the endpoint for the eAPI connection.
//
// Returns:
// Newly created HTTPEapiConnection
func NewHTTPEapiConnection(transport string, host string, username string,
password string, port int) EapiConnectionEntity {
if port == UseDefaultPortNum {
port = DefaultHTTPPort
}
conn := EapiConnection{transport: transport, host: host, port: port, timeOut: 60, disableKeepAlive: false}
conn.Authentication(username, password)
return &HTTPEapiConnection{conn}
}
// send the eAPI request to the destination node
//
// This method is responsible for sending an eAPI request to the
// destination node and returning a response based on the JSONRPCResponse
// object. eAPI responds to request messages with either a success
// message or failure message. On successful decode of the Response,
// a JSONRPCResponse type is returned. Otherwise err is returned.
//
// Args:
// data ([]byte): data to be sent
// Returns:
// ptr to JSONRPCResponse on success. Otherwise error will be returned.
func (conn *HTTPEapiConnection) send(data []byte) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No Connection")
}
tr := &http.Transport{
DisableKeepAlives: conn.disableKeepAlive,
}
timeOut := time.Duration(time.Duration(conn.timeOut) * time.Second)
client := &http.Client{
Timeout: timeOut,
Transport: tr,
}
url := conn.getURL()
resp, err := client.Post(url, "application/json", bytes.NewReader(data))
if err != nil {
conn.SetError(err)
return &JSONRPCResponse{}, err
}
defer func() {
if cerr := resp.Body.Close(); cerr != nil {
err = cerr
conn.SetError(err)
}
}()
jsonRsp, err := decodeEapiResponse(resp)
if err != nil {
conn.SetError(err)
return jsonRsp, err
}
return jsonRsp, nil
}
// Execute the list of commands on the destination node
//
// This method takes a list of commands and sends them to the
// destination node, returning the results. It is assumed that the
// list of commands (type []interface{}) has been properly built and
// enable mode passwd is set if needed. On success, a reference
// to JSONRPCResponse is returned...otherwise err is set.
//
// Args:
// commands ([]interface): list of commands to execute on remote node
// encoding (string): The encoding to send along with the request
// message to the destination node. Valid values include
// 'json' or 'text'. This argument will influence the
// response encoding
// Returns:
// pointer to JSONRPCResponse or error on failure
func (conn *HTTPEapiConnection) Execute(commands []interface{},
encoding string) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No connection")
}
conn.ClearError()
data, err := buildJSONRequest(commands, encoding, strconv.Itoa(os.Getpid()))
if err != nil {
conn.SetError(err)
return &JSONRPCResponse{}, err
}
return conn.send(data)
}
// HTTPSEapiConnection is an EapiConnection suited for HTTP connection
type HTTPSEapiConnection struct {
EapiConnection
path string
enforceVerification bool
}
// DefaultHTTPSPort default port used by https
const DefaultHTTPSPort = 443
// DefaultHTTPSPath command path
const DefaultHTTPSPath = "/command-api"
// NewHTTPSEapiConnection initializes an HttpsEapiConnection.
//
// Args:
// transport (string): The transport to use to create the instance.
// host (string): The IP addres or DNS host name of the connection device.
// username(string): The username to pass to the device to authenticate
// the eAPI connection.
// password(string): The password to pass to the device to authenticate
// the eAPI connection. The default value is ''
// port(int): The TCP port of the endpoint for the eAPI connection.
//
// Returns:
// Newly created HTTPSEapiConnection
func NewHTTPSEapiConnection(transport string, host string, username string,
password string, port int) EapiConnectionEntity {
if port == UseDefaultPortNum {
port = DefaultHTTPSPort
}
path := DefaultHTTPSPath
conn := EapiConnection{transport: transport, host: host, port: port, timeOut: 60, disableKeepAlive: false}
conn.Authentication(username, password)
return &HTTPSEapiConnection{path: path, EapiConnection: conn}
}
// send the eAPI request to the destination node
//
// This method is responsible for sending an eAPI request to the
// destination node and returning a response based on the JSONRPCResponse
// object. eAPI responds to request messages with either a success
// message or failure message. On successful decode of the Response,
// a JSONRPCResponse type is returned. Otherwise err is returned.
//
// Args:
// data ([]byte): data to be sent
// Returns:
// ptr to JSONRPCResponse on success. Otherwise error will be returned.
func (conn *HTTPSEapiConnection) send(data []byte) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No Connection")
}
timeOut := time.Duration(time.Duration(conn.timeOut) * time.Second)
url := conn.getURL()
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: conn.disableKeepAlive,
}
client := &http.Client{
Timeout: timeOut,
Transport: tr,
}
resp, err := client.Post(url, "application/json", bytes.NewReader(data))
if err != nil {
conn.SetError(err)
return &JSONRPCResponse{}, err
}
defer func() {
if cerr := resp.Body.Close(); cerr != nil {
err = cerr
conn.SetError(err)
}
}()
jsonRsp, err := decodeEapiResponse(resp)
if err != nil {
conn.SetError(err)
return jsonRsp, err
}
return jsonRsp, nil
}
// Execute the list of commands on the destination node
//
// This method takes a list of commands and sends them to the
// destination node, returning the results. It is assumed that the
// list of commands (type []interface{}) has been properly built and
// enable mode passwd is set if needed. On success, a reference
// to JSONRPCResponse is returned...otherwise err is set.
//
// Args:
// commands ([]interface): list of commands to execute on remote node
// encoding (string): The encoding to send along with the request
// message to the destination node. Valid values include
// 'json' or 'text'. This argument will influence the
// response encoding
// Returns:
// pointer to JSONRPCResponse or error on failure
func (conn *HTTPSEapiConnection) Execute(commands []interface{},
encoding string) (*JSONRPCResponse, error) {
if conn == nil {
return &JSONRPCResponse{}, fmt.Errorf("No connection")
}
conn.ClearError()
data, err := buildJSONRequest(commands, encoding, strconv.Itoa(os.Getpid()))
if err != nil {
conn.SetError(err)
return &JSONRPCResponse{}, err
}
return conn.send(data)
}
// disableCertificateVerification disables https verification
func (conn *HTTPSEapiConnection) disableCertificateVerification() {
conn.enforceVerification = false
}
// enableCertificateVerification enables https verification
func (conn *HTTPSEapiConnection) enableCertificateVerification() {
conn.enforceVerification = true
}