-
Notifications
You must be signed in to change notification settings - Fork 29
/
client.go
322 lines (271 loc) · 7.58 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
package client
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/ciscoecosystem/aci-go-client/container"
)
const authPayload = `{
"aaaUser" : {
"attributes" : {
"name" : "%s",
"pwd" : "%s"
}
}
}`
const DefaultMOURL = "/api/node/mo"
// Client is the main entry point
type Client struct {
BaseURL *url.URL
MOURL string
httpClient *http.Client
AuthToken *Auth
username string
password string
privatekey string
adminCert string
insecure bool
proxyUrl string
skipLoggingPayload bool
*ServiceManager
}
// singleton implementation of a client
var clientImpl *Client
type Option func(*Client)
func Insecure(insecure bool) Option {
return func(client *Client) {
client.insecure = insecure
}
}
func MoURL(moURL string) Option {
return func(sm *Client) {
sm.MOURL = moURL
}
}
func Password(password string) Option {
return func(client *Client) {
client.password = password
}
}
func PrivateKey(privatekey string) Option {
return func(client *Client) {
client.privatekey = privatekey
}
}
func AdminCert(adminCert string) Option {
return func(client *Client) {
client.adminCert = adminCert
}
}
func ProxyUrl(pUrl string) Option {
return func(client *Client) {
client.proxyUrl = pUrl
}
}
func SkipLoggingPayload(skipLoggingPayload bool) Option {
return func(client *Client) {
client.skipLoggingPayload = skipLoggingPayload
}
}
func initClient(clientUrl, username string, options ...Option) *Client {
var transport *http.Transport
bUrl, err := url.Parse(clientUrl)
if err != nil {
// cannot move forward if url is undefined
log.Fatal(err)
}
client := &Client{
BaseURL: bUrl,
username: username,
httpClient: http.DefaultClient,
MOURL: DefaultMOURL,
}
for _, option := range options {
option(client)
}
transport = client.useInsecureHTTPClient(client.insecure)
if client.proxyUrl != "" {
transport = client.configProxy(transport)
}
client.httpClient = &http.Client{
Transport: transport,
}
client.ServiceManager = NewServiceManager(client.MOURL, client)
return client
}
// GetClient returns a singleton
func GetClient(clientUrl, username string, options ...Option) *Client {
if clientImpl == nil {
clientImpl = initClient(clientUrl, username, options...)
} else {
// making sure it is the same client
bUrl, err := url.Parse(clientUrl)
if err != nil {
// cannot move forward if url is undefined
log.Fatal(err)
}
if bUrl != clientImpl.BaseURL {
clientImpl = initClient(clientUrl, username, options...)
}
}
return clientImpl
}
// NewClient returns a new Instance of the client - allowing for simultaneous connections to the same APIC
func NewClient(clientUrl, username string, options ...Option) *Client {
// making sure it is the same client
_, err := url.Parse(clientUrl)
if err != nil {
// cannot move forward if url is undefined
log.Fatal(err)
}
// initClient always returns a new struct, so always create a new pointer to allow for
// multiple object instances
newClientImpl := initClient(clientUrl, username, options...)
return newClientImpl
}
func (c *Client) configProxy(transport *http.Transport) *http.Transport {
pUrl, err := url.Parse(c.proxyUrl)
if err != nil {
log.Fatal(err)
}
transport.Proxy = http.ProxyURL(pUrl)
return transport
}
func (c *Client) useInsecureHTTPClient(insecure bool) *http.Transport {
// proxyUrl, _ := url.Parse("http://10.0.1.167:3128")
transport := &http.Transport{
TLSClientConfig: &tls.Config{
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
},
PreferServerCipherSuites: true,
InsecureSkipVerify: insecure,
MinVersion: tls.VersionTLS11,
MaxVersion: tls.VersionTLS12,
},
}
return transport
}
func (c *Client) MakeRestRequest(method string, path string, body *container.Container, authenticated bool) (*http.Request, error) {
url, err := url.Parse(path)
if err != nil {
return nil, err
}
fURL := c.BaseURL.ResolveReference(url)
var req *http.Request
if method == "GET" {
req, err = http.NewRequest(method, fURL.String(), nil)
} else {
req, err = http.NewRequest(method, fURL.String(), bytes.NewBuffer((body.Bytes())))
}
if err != nil {
return nil, err
}
if c.skipLoggingPayload {
log.Printf("HTTP request %s %s", method, path)
} else {
log.Printf("HTTP request %s %s %v", method, path, req)
}
if authenticated {
req, err = c.InjectAuthenticationHeader(req, path)
if err != nil {
return req, err
}
}
if !c.skipLoggingPayload {
log.Printf("HTTP request after injection %s %s %v", method, path, req)
}
return req, nil
}
// Authenticate is used to
func (c *Client) Authenticate() error {
method := "POST"
path := "/api/aaaLogin.json"
body, err := container.ParseJSON([]byte(fmt.Sprintf(authPayload, c.username, c.password)))
if err != nil {
return err
}
req, err := c.MakeRestRequest(method, path, body, false)
obj, _, err := c.Do(req)
if err != nil {
return err
}
if obj == nil {
return errors.New("Empty response")
}
token := obj.S("imdata").Index(0).S("aaaLogin", "attributes", "token").String()
creationTimeStr := stripQuotes(obj.S("imdata").Index(0).S("aaaLogin", "attributes", "creationTime").String())
refreshTimeStr := stripQuotes(obj.S("imdata").Index(0).S("aaaLogin", "attributes", "refreshTimeoutSeconds").String())
creationTimeInt, err := StrtoInt(creationTimeStr, 10, 64)
if err != nil {
return err
}
refreshTimeInt, err := StrtoInt(refreshTimeStr, 10, 64)
if err != nil {
return err
}
if token == "" {
return errors.New("Invalid Username or Password")
}
if c.AuthToken == nil {
c.AuthToken = &Auth{}
}
c.AuthToken.Token = stripQuotes(token)
c.AuthToken.apicCreatedAt = time.Unix(creationTimeInt, 0)
c.AuthToken.realCreatedAt = time.Now()
c.AuthToken.CalculateExpiry(refreshTimeInt)
c.AuthToken.CaclulateOffset()
return nil
}
func StrtoInt(s string, startIndex int, bitSize int) (int64, error) {
return strconv.ParseInt(s, startIndex, bitSize)
}
func (c *Client) Do(req *http.Request) (*container.Container, *http.Response, error) {
log.Printf("[DEBUG] Begining DO method %s", req.URL.String())
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, nil, err
}
log.Printf("\n\n\n HTTP request: %v", req.Body)
log.Printf("\nHTTP Request: %s %s", req.Method, req.URL.String())
log.Printf("nHTTP Response: %d %s %v", resp.StatusCode, resp.Status, resp)
bodyBytes, err := ioutil.ReadAll(resp.Body)
bodyStr := string(bodyBytes)
resp.Body.Close()
log.Printf("\n HTTP response unique string %s %s %s", req.Method, req.URL.String(), bodyStr)
obj, err := container.ParseJSON(bodyBytes)
if err != nil {
log.Printf("Error occured while json parsing %+v", err)
return nil, resp, err
}
log.Printf("[DEBUG] Exit from do method")
return obj, resp, err
}
func (c *Client) DoRaw(req *http.Request) (*http.Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
log.Printf("\n\n\n HTTP request: %v", req.Body)
log.Printf("\nHTTP Request: %s %s", req.Method, req.URL.String())
log.Printf("nHTTP Response: %d %s %v", resp.StatusCode, resp.Status, resp)
return resp, err
}
func stripQuotes(word string) string {
if strings.HasPrefix(word, "\"") && strings.HasSuffix(word, "\"") {
return strings.TrimSuffix(strings.TrimPrefix(word, "\""), "\"")
}
return word
}