-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
213 lines (195 loc) · 5.64 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
// Package goaci is a a Cisco ACI client library for Go.
package goaci
import (
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"strings"
"time"
"github.com/tidwall/gjson"
)
// Client is an HTTP ACI API client.
// Use goaci.NewClient to initiate a client.
// This will ensure proper cookie handling and processing of modifiers.
type Client struct {
// HttpClient is the *http.Client used for API requests.
HttpClient *http.Client
// Url is the APIC IP or hostname, e.g. 10.0.0.1:80 (port is optional).
Url string
// Usr is the APIC username.
Usr string
// Pwd is the APIC password.
Pwd string
// LastRefresh is the timestamp of the last token refresh interval.
LastRefresh time.Time
// Token is the current authentication token
Token string
}
// NewClient creates a new ACI HTTP client.
// Pass modifiers in to modify the behavior of the client, e.g.
// client, _ := NewClient("apic", "user", "password", RequestTimeout(120))
func NewClient(url, usr, pwd string, mods ...func(*Client)) (Client, error) {
// Normalize the URL
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
url = "https://" + url
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
cookieJar, _ := cookiejar.New(nil)
httpClient := http.Client{
Timeout: 60 * time.Second,
Transport: tr,
Jar: cookieJar,
}
client := Client{
HttpClient: &httpClient,
Url: url,
Usr: usr,
Pwd: pwd,
}
for _, mod := range mods {
mod(&client)
}
return client, nil
}
// NewReq creates a new Req request for this client.
func (client Client) NewReq(method, uri string, body io.Reader, mods ...func(*Req)) Req {
httpReq, _ := http.NewRequest(method, client.Url+uri+".json", body)
req := Req{
HttpReq: httpReq,
Refresh: true,
}
for _, mod := range mods {
mod(&req)
}
return req
}
// RequestTimeout modifies the HTTP request timeout from the default of 60 seconds.
func RequestTimeout(x time.Duration) func(*Client) {
return func(client *Client) {
client.HttpClient.Timeout = x * time.Second
}
}
// Do makes a request.
// Requests for Do are built ouside of the client, e.g.
//
// req := client.NewReq("GET", "/api/class/fvBD", nil)
// res := client.Do(req)
func (client *Client) Do(req Req) (Res, error) {
if req.Refresh && time.Now().Sub(client.LastRefresh) > 480*time.Second {
if err := client.Refresh(); err != nil {
return Res{}, err
}
}
httpRes, err := client.HttpClient.Do(req.HttpReq)
if err != nil {
return Res{}, err
}
defer httpRes.Body.Close()
if httpRes.StatusCode != http.StatusOK {
return Res{}, fmt.Errorf("received HTTP status %d", httpRes.StatusCode)
}
body, err := ioutil.ReadAll(httpRes.Body)
if err != nil {
return Res{}, errors.New("cannot decode response body")
}
return Res(gjson.ParseBytes(body)), nil
}
// Get makes a GET request and returns a GJSON result.
// Results will be the raw data structure as returned by the APIC, wrapped in imdata, e.g.
//
// {
// "imdata": [
// {
// "fvTenant": {
// "attributes": {
// "dn": "uni/tn-mytenant",
// "name": "mytenant",
// }
// }
// }
// ],
// "totalCount": "1"
// }
func (client *Client) Get(path string, mods ...func(*Req)) (Res, error) {
req := client.NewReq("GET", path, nil, mods...)
return client.Do(req)
}
// GetClass makes a GET request by class and unwraps the results.
// Result is removed from imdata, but still wrapped in Class.attributes, e.g.
// [
// {
// "fvTenant": {
// "attributes": {
// "dn": "uni/tn-mytenant",
// "name": "mytenant",
// }
// }
// }
// ]
func (client *Client) GetClass(class string, mods ...func(*Req)) (Res, error) {
res, err := client.Get(fmt.Sprintf("/api/class/%s", class), mods...)
if err != nil {
return res, err
}
return res.Get("imdata"), nil
}
// GetDn makes a GET request by DN.
// Result is removed from imdata and first result is removed from the list, e.g.
// {
// "fvTenant": {
// "attributes": {
// "dn": "uni/tn-mytenant",
// "name": "mytenant",
// }
// }
// }
func (client *Client) GetDn(dn string, mods ...func(*Req)) (Res, error) {
res, err := client.Get(fmt.Sprintf("/api/mo/%s", dn), mods...)
if err != nil {
return res, err
}
return res.Get("imdata.0"), nil
}
// Post makes a POST request and returns a GJSON result.
// Hint: Use the Body struct to easily create POST body data.
func (client *Client) Post(path, data string, mods ...func(*Req)) (Res, error) {
req := client.NewReq("POST", path, strings.NewReader(data), mods...)
return client.Do(req)
}
// Login authenticates to the APIC.
func (client *Client) Login() error {
data := fmt.Sprintf(`{"aaaUser":{"attributes":{"name":"%s","pwd":"%s"}}}`,
client.Usr,
client.Pwd,
)
res, err := client.Post("/api/aaaLogin", data, NoRefresh)
if err != nil {
return err
}
errText := res.Get("imdata.0.error.attributes.text").Str
if errText != "" {
return errors.New("authentication error")
}
client.Token = res.Get("imdata.0.aaaLogin.attributes.token").Str
client.LastRefresh = time.Now()
return nil
}
// Refresh refreshes the authentication token.
// Note that this will be handled automatically be default.
// Refresh will be checked every request and the token will be refreshed after 8 minutes.
// Pass goaci.NoRefresh to prevent automatic refresh handling and handle it directly instead.
func (client *Client) Refresh() error {
res, err := client.Get("/api/aaaRefresh", NoRefresh)
if err != nil {
return err
}
client.Token = res.Get("imdata.0.aaaRefresh.attributes.token").Str
client.LastRefresh = time.Now()
return nil
}