forked from f5devcentral/go-bigip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbigip.go
375 lines (323 loc) · 8.94 KB
/
bigip.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
// Package bigip interacts with F5 BIG-IP systems using the REST API.
package bigip
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"strings"
"time"
)
var defaultConfigOptions = &ConfigOptions{
APICallTimeout: 60 * time.Second,
}
type ConfigOptions struct {
APICallTimeout time.Duration
}
// BigIP is a container for our session state.
type BigIP struct {
Host string
User string
Password string
Token string // if set, will be used instead of User/Password
Transport *http.Transport
ConfigOptions *ConfigOptions
}
// APIRequest builds our request before sending it to the server.
type APIRequest struct {
Method string
URL string
Body string
ContentType string
}
// RequestError contains information about any error we get from a request.
type RequestError struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
ErrorStack []string `json:"errorStack,omitempty"`
}
// Error returns the error message.
func (r *RequestError) Error() error {
if r.Message != "" {
return errors.New(r.Message)
}
return nil
}
// NewSession sets up our connection to the BIG-IP system.
func NewSession(host, user, passwd string, configOptions *ConfigOptions) *BigIP {
var url string
if !strings.HasPrefix(host, "http") {
url = fmt.Sprintf("https://%s", host)
} else {
url = host
}
if configOptions == nil {
configOptions = defaultConfigOptions
}
return &BigIP{
Host: url,
User: user,
Password: passwd,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
ConfigOptions: configOptions,
}
}
// NewTokenSession sets up our connection to the BIG-IP system, and
// instructs the session to use token authentication instead of Basic
// Auth. This is required when using an external authentication
// provider, such as Radius or Active Directory. loginProviderName is
// probably "tmos" but your environment may vary.
func NewTokenSession(host, user, passwd, loginProviderName string, configOptions *ConfigOptions) (b *BigIP, err error) {
type authReq struct {
Username string `json:"username"`
Password string `json:"password"`
LoginProviderName string `json:"loginProviderName"`
}
type authResp struct {
Token struct {
Token string
}
}
auth := authReq{
user,
passwd,
loginProviderName,
}
marshalJSON, err := json.Marshal(auth)
if err != nil {
return
}
req := &APIRequest{
Method: "post",
URL: "mgmt/shared/authn/login",
Body: string(marshalJSON),
ContentType: "application/json",
}
b = NewSession(host, user, passwd, configOptions)
resp, err := b.APICall(req)
if err != nil {
return
}
if resp == nil {
err = fmt.Errorf("unable to acquire authentication token")
return
}
var aresp authResp
err = json.Unmarshal(resp, &aresp)
if err != nil {
return
}
if aresp.Token.Token == "" {
err = fmt.Errorf("unable to acquire authentication token")
return
}
b.Token = aresp.Token.Token
return
}
// APICall is used to query the BIG-IP web API.
func (b *BigIP) APICall(options *APIRequest) ([]byte, error) {
var req *http.Request
client := &http.Client{
Transport: b.Transport,
Timeout: b.ConfigOptions.APICallTimeout,
}
var format string
if strings.Contains(options.URL, "mgmt/") {
format = "%s/%s"
} else {
format = "%s/mgmt/tm/%s"
}
url := fmt.Sprintf(format, b.Host, options.URL)
body := bytes.NewReader([]byte(options.Body))
req, _ = http.NewRequest(strings.ToUpper(options.Method), url, body)
if b.Token != "" {
req.Header.Set("X-F5-Auth-Token", b.Token)
} else {
req.SetBasicAuth(b.User, b.Password)
}
//fmt.Println("REQ -- ", options.Method, " ", url," -- ",options.Body)
if len(options.ContentType) > 0 {
req.Header.Set("Content-Type", options.ContentType)
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
data, _ := ioutil.ReadAll(res.Body)
if res.StatusCode >= 400 {
if res.Header["Content-Type"][0] == "application/json" {
return data, b.checkError(data)
}
return data, errors.New(fmt.Sprintf("HTTP %d :: %s", res.StatusCode, string(data[:])))
}
return data, nil
}
func (b *BigIP) iControlPath(parts []string) string {
var buffer bytes.Buffer
for i, p := range parts {
buffer.WriteString(strings.Replace(p, "/", "~", -1))
if i < len(parts)-1 {
buffer.WriteString("/")
}
}
return buffer.String()
}
//Generic delete
func (b *BigIP) delete(path ...string) error {
req := &APIRequest{
Method: "delete",
URL: b.iControlPath(path),
}
_, callErr := b.APICall(req)
return callErr
}
func (b *BigIP) post(body interface{}, path ...string) error {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return err
}
req := &APIRequest{
Method: "post",
URL: b.iControlPath(path),
Body: strings.TrimRight(string(marshalJSON), "\n"),
ContentType: "application/json",
}
_, callErr := b.APICall(req)
return callErr
}
func (b *BigIP) put(body interface{}, path ...string) error {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return err
}
req := &APIRequest{
Method: "put",
URL: b.iControlPath(path),
Body: strings.TrimRight(string(marshalJSON), "\n"),
ContentType: "application/json",
}
_, callErr := b.APICall(req)
return callErr
}
func (b *BigIP) patch(body interface{}, path ...string) error {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return err
}
req := &APIRequest{
Method: "patch",
URL: b.iControlPath(path),
Body: string(marshalJSON),
ContentType: "application/json",
}
_, callErr := b.APICall(req)
return callErr
}
//Get a url and populate an entity. If the entity does not exist (404) then the
//passed entity will be untouched and false will be returned as the second parameter.
//You can use this to distinguish between a missing entity or an actual error.
func (b *BigIP) getForEntity(e interface{}, path ...string) (error, bool) {
req := &APIRequest{
Method: "get",
URL: b.iControlPath(path),
ContentType: "application/json",
}
resp, err := b.APICall(req)
if err != nil {
var reqError RequestError
json.Unmarshal(resp, &reqError)
if reqError.Code == 404 {
return nil, false
}
return err, false
}
err = json.Unmarshal(resp, e)
if err != nil {
return err, false
}
return nil, true
}
// checkError handles any errors we get from our API requests. It returns either the
// message of the error, if any, or nil.
func (b *BigIP) checkError(resp []byte) error {
if len(resp) == 0 {
return nil
}
var reqError RequestError
err := json.Unmarshal(resp, &reqError)
if err != nil {
return errors.New(fmt.Sprintf("%s\n%s", err.Error(), string(resp[:])))
}
err = reqError.Error()
if err != nil {
return err
}
return nil
}
// jsonMarshal specifies an encoder with 'SetEscapeHTML' set to 'false' so that <, >, and & are not escaped. https://golang.org/pkg/encoding/json/#Marshal
// https://stackoverflow.com/questions/28595664/how-to-stop-json-marshal-from-escaping-and
func jsonMarshal(t interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
return buffer.Bytes(), err
}
// Helper to copy between transfer objects and model objects to hide the myriad of boolean representations
// in the iControlREST api. DTO fields can be tagged with bool:"yes|enabled|true" to set what true and false
// marshal to.
func marshal(to, from interface{}) error {
toVal := reflect.ValueOf(to).Elem()
fromVal := reflect.ValueOf(from).Elem()
toType := toVal.Type()
for i := 0; i < toVal.NumField(); i++ {
toField := toVal.Field(i)
toFieldType := toType.Field(i)
fromField := fromVal.FieldByName(toFieldType.Name)
if fromField.Interface() != nil && fromField.Kind() == toField.Kind() {
toField.Set(fromField)
} else if toField.Kind() == reflect.Bool && fromField.Kind() == reflect.String {
switch fromField.Interface() {
case "yes", "enabled", "true":
toField.SetBool(true)
break
case "no", "disabled", "false", "":
toField.SetBool(false)
break
default:
return fmt.Errorf("Unknown boolean conversion for %s: %s", toFieldType.Name, fromField.Interface())
}
} else if fromField.Kind() == reflect.Bool && toField.Kind() == reflect.String {
tag := toFieldType.Tag.Get("bool")
switch tag {
case "yes":
toField.SetString(toBoolString(fromField.Interface().(bool), "yes", "no"))
break
case "enabled":
toField.SetString(toBoolString(fromField.Interface().(bool), "enabled", "disabled"))
break
case "true":
toField.SetString(toBoolString(fromField.Interface().(bool), "true", "false"))
break
}
} else {
return fmt.Errorf("Unknown type conversion %s -> %s", fromField.Kind(), toField.Kind())
}
}
return nil
}
func toBoolString(b bool, trueStr, falseStr string) string {
if b {
return trueStr
}
return falseStr
}