forked from scottdware/go-bigip
/
bigip.go
239 lines (205 loc) · 5.56 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
// 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"
)
// BigIP is a container for our session state.
type BigIP struct {
Host string
User string
Password string
Transport *http.Transport
}
// 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"`
}
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) *BigIP {
var url string
if !strings.HasPrefix(host, "http") {
url = fmt.Sprintf("https://%s", host)
} else {
url = host
}
return &BigIP{
Host: url,
User: user,
Password: passwd,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
}
// 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}
url := fmt.Sprintf("%s/mgmt/tm/%s", b.Host, options.URL)
body := bytes.NewReader([]byte(options.Body))
req, _ = http.NewRequest(strings.ToUpper(options.Method), url, body)
req.SetBasicAuth(b.User, b.Password)
//log.Println("REQ -- ", 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
}
//Generic delete
func (b *BigIP) delete(path ...string) error {
req := &APIRequest{
Method: "delete",
URL: strings.Join(path, "/"),
}
_, callErr := b.APICall(req)
return callErr
}
func (b *BigIP) post(body interface{}, path ...string) error {
marshalJSON, err := json.Marshal(body)
if err != nil {
return err
}
req := &APIRequest{
Method: "post",
URL: strings.Join(path, "/"),
Body: string(marshalJSON),
ContentType: "application/json",
}
_, callErr := b.APICall(req)
return callErr
}
func (b *BigIP) put(body interface{}, path ...string) error {
marshalJSON, err := json.Marshal(body)
if err != nil {
return err
}
req := &APIRequest{
Method: "put",
URL: strings.Join(path, "/"),
Body: string(marshalJSON),
ContentType: "application/json",
}
_, callErr := b.APICall(req)
return callErr
}
// 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
}
// Perform a GET request and treat 404's as nil objects instead of errors.
func (b *BigIP) SafeGet(url string) ([]byte, error) {
req := &APIRequest{
Method: "get",
URL: url,
ContentType: "application/json",
}
resp, err := b.APICall(req)
if err != nil {
var reqError RequestError
json.Unmarshal(resp, &reqError)
if reqError.Code == 404 {
return nil, nil
}
return nil, err
}
return resp, nil
}
// 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
}