-
Notifications
You must be signed in to change notification settings - Fork 11
/
udnssdk.go
304 lines (263 loc) · 8.18 KB
/
udnssdk.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
package udnssdk
// udnssdk - a golang sdk for the ultradns REST service.
// 2015-07-03 - jmasseo@gmail.com
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/oauth2"
oauthPassword "github.com/terra-farm/udnssdk/password"
)
const (
libraryVersion = "0.1"
// DefaultTestBaseURL returns the URL for UltraDNS's test restapi endpoint
DefaultTestBaseURL = "https://test-restapi.ultradns.com/"
// DefaultLiveBaseURL returns the URL for UltraDNS's production restapi endpoint
DefaultLiveBaseURL = "https://restapi.ultradns.com/"
userAgent = "udnssdk-go/" + libraryVersion
apiVersion = "v1"
)
// QueryInfo wraps a query request
type QueryInfo struct {
Q string `json:"q"`
Sort string `json:"sort"`
Reverse bool `json:"reverse"`
Limit int `json:"limit"`
}
// ResultInfo wraps the list metadata for an index response
type ResultInfo struct {
TotalCount int `json:"totalCount"`
Offset int `json:"offset"`
ReturnedCount int `json:"returnedCount"`
}
// Client wraps our general-purpose Service Client
type Client struct {
// This is our client structure.
HTTPClient *http.Client
Config *oauthPassword.Config
BaseURL *url.URL
UserAgent string
// Accounts API
Accounts *AccountsService
// Probe Alerts API
Alerts *AlertsService
// Directional Pools API
DirectionalPools *DirectionalPoolsService
// Events API
Events *EventsService
// Notifications API
Notifications *NotificationsService
// Probes API
Probes *ProbesService
// Resource Record Sets API
RRSets *RRSetsService
// Tasks API
Tasks *TasksService
}
// NewClient returns a new ultradns API client.
func NewClient(username, password, baseURL string) (*Client, error) {
ctx := oauth2.NoContext
conf := NewConfig(username, password, baseURL)
u, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
c := &Client{
HTTPClient: conf.Client(ctx),
BaseURL: u,
UserAgent: userAgent,
Config: conf,
}
c.Accounts = &AccountsService{client: c}
c.Alerts = &AlertsService{client: c}
c.DirectionalPools = &DirectionalPoolsService{client: c}
c.Events = &EventsService{client: c}
c.Notifications = &NotificationsService{client: c}
c.Probes = &ProbesService{client: c}
c.RRSets = &RRSetsService{client: c}
c.Tasks = &TasksService{client: c}
return c, nil
}
// newStubClient returns a new ultradns API client.
func newStubClient(username, password, baseURL, clientID, clientSecret string) (*Client, error) {
u, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
c := &Client{
HTTPClient: &http.Client{},
BaseURL: u,
UserAgent: userAgent,
}
c.Accounts = &AccountsService{client: c}
c.Alerts = &AlertsService{client: c}
c.DirectionalPools = &DirectionalPoolsService{client: c}
c.Events = &EventsService{client: c}
c.Notifications = &NotificationsService{client: c}
c.Probes = &ProbesService{client: c}
c.RRSets = &RRSetsService{client: c}
c.Tasks = &TasksService{client: c}
return c, nil
}
// NewRequest creates an API request.
// The path is expected to be a relative path and will be resolved
// according to the BaseURL of the Client. Paths should always be specified without a preceding slash.
func (c *Client) NewRequest(method, pathquery string, payload interface{}) (*http.Request, error) {
url := *c.BaseURL
pq := strings.SplitN(pathquery, "?", 2)
url.Path = url.Path + fmt.Sprintf("%s/%s", apiVersion, pq[0])
if len(pq) == 2 {
url.RawQuery = pq[1]
}
body := new(bytes.Buffer)
if payload != nil {
err := json.NewEncoder(body).Encode(payload)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", c.UserAgent)
return req, nil
}
func (c *Client) get(path string, v interface{}) (*http.Response, error) {
return c.Do("GET", path, nil, v)
}
func (c *Client) post(path string, payload, v interface{}) (*http.Response, error) {
return c.Do("POST", path, payload, v)
}
func (c *Client) put(path string, payload, v interface{}) (*http.Response, error) {
return c.Do("PUT", path, payload, v)
}
func (c *Client) delete(path string, payload interface{}) (*http.Response, error) {
return c.Do("DELETE", path, payload, nil)
}
// Do sends an API request and returns the API response.
// The API response is JSON decoded and stored in the value pointed by v,
// or returned as an error if an API error has occurred.
// If v implements the io.Writer interface, the raw response body will be written to v,
// without attempting to decode it.
func (c *Client) Do(method, path string, payload, v interface{}) (*http.Response, error) {
hc := c.HTTPClient
req, err := c.NewRequest(method, path, payload)
if err != nil {
return nil, err
}
log.Printf("[DEBUG] HTTP Request: %+v\n", req)
r, err := hc.Do(req)
log.Printf("[DEBUG] HTTP Response: %+v\n", r)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode == 202 {
// This is a deferred task.
tid := TaskID(r.Header.Get("X-Task-Id"))
log.Printf("[DEBUG] Received Async Task %+v.. will retry...\n", tid)
// TODO: Sane Configuration for timeouts / retries
timeout := 5
waittime := 5 * time.Second
i := 0
breakmeout := false
for i < timeout || breakmeout {
t, _, err := c.Tasks.Find(tid)
if err != nil {
return nil, err
}
log.Printf("[DEBUG] Task ID: %+v Retry: %d Status Code: %s\n", tid, i, t.TaskStatusCode)
switch t.TaskStatusCode {
case "COMPLETE":
// Yay
resp, err := c.Tasks.FindResultByTask(t)
if err != nil {
return nil, err
}
r = resp
breakmeout = true
case "PENDING", "IN_PROCESS":
i = i + 1
time.Sleep(waittime)
continue
case "ERROR":
return nil, err
}
}
}
err = CheckResponse(r)
if err != nil {
return r, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
io.Copy(w, r.Body)
} else {
err = json.NewDecoder(r.Body).Decode(v)
// err = json.Unmarshal(r.Body, v)
}
}
return r, err
}
// ErrorResponse represents an error caused by an API request.
// Example:
// {"errorCode":60001,"errorMessage":"invalid_grant:Invalid username & password combination.","error":"invalid_grant","error_description":"60001: invalid_grant:Invalid username & password combination."}
type ErrorResponse struct {
Response *http.Response // HTTP response that caused this error
ErrorCode int `json:"errorCode"` // error code
ErrorMessage string `json:"errorMessage"` // human-readable message
ErrorStr string `json:"error"`
ErrorDescription string `json:"error_description"`
}
// ErrorResponseList wraps an HTTP response that has a list of errors
type ErrorResponseList struct {
Response *http.Response // HTTP response that caused this error
Responses []ErrorResponse
}
// Error implements the error interface.
func (r ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %d %v",
r.Response.Request.Method, r.Response.Request.URL,
r.Response.StatusCode, r.ErrorCode, r.ErrorMessage)
}
func (r ErrorResponseList) Error() string {
return fmt.Sprintf("%v %v: %d %d %v",
r.Response.Request.Method, r.Response.Request.URL,
r.Response.StatusCode, r.Responses[0].ErrorCode, r.Responses[0].ErrorMessage)
}
// CheckResponse checks the API response for errors, and returns them if present.
// A response is considered an error if the status code is different than 2xx. Specific requests
// may have additional requirements, but this is sufficient in most of the cases.
func CheckResponse(r *http.Response) error {
if code := r.StatusCode; 200 <= code && code <= 299 {
return nil
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
// Attempt marshaling to ErrorResponse
var er ErrorResponse
err = json.Unmarshal(body, &er)
if err == nil {
er.Response = r
return er
}
// Attempt marshaling to ErrorResponseList
var ers []ErrorResponse
err = json.Unmarshal(body, &ers)
if err == nil {
return &ErrorResponseList{Response: r, Responses: ers}
}
return fmt.Errorf("Response had non-successful Status: %#v, but could not extract any errors from Body: %#v", r.Status, string(body))
}