Debian Codegraph @

dynect/client.go

raw symbols SCIP
1 package dynect
2
3 import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io/ioutil"
9 "log"
10 "net/http"
11 "strings"
12 "time"
13 )
14
15 const (
16 DynAPIPrefix = "https://api.dynect.net/REST"
17 )
18
19 var (
20 PollingInterval = 1 * time.Second
21 ErrPromotedToJob = errors.New("promoted to job")
22 ErrRateLimited = errors.New("too many requests")
23 )
24
25 // handleJobRedirect overrides the net/http.DefaultClient's redirection policy
26 // function.
27 //
28 // This function will set the Content-Type, and Auth-Token headers, so that we
29 // don't get an error back from the API.
30 func handleJobRedirect(req *http.Request, via []*http.Request) error {
31 // Set the Content-Type header.
32 req.Header.Set("Content-Type", "application/json")
33
34 // Now, try and divine the Auth-Token header's value from previous
35 // requests.
36 for _, r := range via {
37 if authHdr := r.Header.Get("Auth-Token"); authHdr != "" {
38 req.Header.Set("Auth-Token", authHdr)
39 return nil
40 }
41 }
42 return fmt.Errorf("failed to set Auth-Token header from previous requests")
43 }
44
45 // A client for use with DynECT's REST API.
46 type Client struct {
47 Token string
48 CustomerName string
49 Transport http.RoundTripper
50 verbose bool
51 }
52
53 // Creates a new Httpclient.
54 func NewClient(customerName string) *Client {
55 return &Client{
56 CustomerName: customerName,
57 Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
58 }
59 }
60
61 // Sets the transport for the client.
62 func (c *Client) SetTransport(t http.RoundTripper) {
63 c.Transport = t
64 }
65
66 // Enable, or disable verbose output from the client.
67 //
68 // This will enable (or disable) logging messages that explain what the client
69 // is about to do, like the endpoint it is about to make a request to. If the
70 // request fails with an unexpected HTTP response code, then the response body
71 // will be logged out, as well.
72 func (c *Client) Verbose(p bool) {
73 c.verbose = p
74 }
75
76 // Establishes a new session with the DynECT API.
77 func (c *Client) Login(username, password string) error {
78 var req = LoginBlock{
79 Username: username,
80 Password: password,
81 CustomerName: c.CustomerName}
82
83 var resp LoginResponse
84
85 err := c.Do("POST", "Session", req, &resp)
86 if err != nil {
87 return err
88 }
89
90 c.Token = resp.Data.Token
91 return nil
92 }
93
94 func (c *Client) LoggedIn() bool {
95 return len(c.Token) > 0
96 }
97
98 func (c *Client) Logout() error {
99 return c.Do("DELETE", "Session", nil, nil)
100 }
101
102 // newRequest creates a new *http.Request, and sets the following headers:
103 // <ul>
104 // <li>Auth-Token</li>
105 // <li>Content-Type</li>
106 // </ul>
107 func (c *Client) newRequest(method, urlStr string, data []byte) (*http.Request, error) {
108 var r *http.Request
109 var err error
110
111 if data != nil {
112 r, err = http.NewRequest(method, urlStr, bytes.NewReader(data))
113 } else {
114 r, err = http.NewRequest(method, urlStr, nil)
115 }
116
117 r.Header.Set("Auth-Token", c.Token)
118 r.Header.Set("Content-Type", "application/json")
119
120 return r, err
121 }
122
123 func (c *Client) Do(method, endpoint string, requestData, responseData interface{}) error {
124 // Throw an error if the user tries to make a request if the client is
125 // logged out/unauthenticated, but make an exemption for when the
126 // caller is trying to log in.
127 if !c.LoggedIn() && method != "POST" && endpoint != "Session" {
128 return errors.New("Will not perform request; client is closed")
129 }
130
131 var err error
132
133 // Marshal the request data into a byte slice.
134 if c.verbose {
135 log.Println("dynect: marshaling request data")
136 }
137 var js []byte
138 if requestData != nil {
139 js, err = json.Marshal(requestData)
140 } else {
141 js = []byte("")
142 }
143 if err != nil {
144 return err
145 }
146
147 urlStr := fmt.Sprintf("%s/%s", DynAPIPrefix, endpoint)
148
149 // Create a new http.Request.
150 req, err := c.newRequest(method, urlStr, js)
151 if err != nil {
152 return err
153 }
154
155 if c.verbose {
156 log.Printf("Making %s request to %q", method, urlStr)
157 }
158
159 var resp *http.Response
160 resp, err = c.Transport.RoundTrip(req)
161
162 if err != nil {
163 if c.verbose {
164 respBody, err := ioutil.ReadAll(resp.Body)
165 if err != nil {
166 return err
167 }
168 log.Printf("%s", string(respBody))
169 }
170 return err
171 }
172 defer resp.Body.Close()
173
174 switch resp.StatusCode {
175 case 200:
176 if resp.ContentLength == 0 {
177 // Zero-length content body?
178 log.Println("dynect: warning: zero-length response body; skipping decoding of response")
179 return nil
180 }
181
182 //dec := json.NewDecoder(resp.Body)
183 text, err := ioutil.ReadAll(resp.Body)
184 if err != nil {
185 return fmt.Errorf("Could not read response body")
186 }
187 if err := json.Unmarshal(text, &responseData); err != nil {
188 return fmt.Errorf("Error unmarshalling response:", err)
189 }
190
191 return nil
192
193 case 307:
194 // Handle the temporary redirect, which should point to a
195 // /REST/Jobs endpoint.
196 loc := resp.Header.Get("Location")
197 log.Println("dynect: request is taking too long to complete: redirecting to", loc)
198
199 // Going in to this blind, the documentation says that it will
200 // return a URI when promoting a long-running request to a
201 // job.
202 //
203 // Since a URL is technically a URI, we should do some checks
204 // on the returned URI to sanitize it, and make sure that it is
205 // in the format we would like it to be.
206 if strings.HasPrefix(loc, "/REST/") {
207 loc = strings.TrimLeft(loc, "/REST/")
208 }
209 if !strings.HasPrefix(loc, DynAPIPrefix) {
210 loc = fmt.Sprintf("%s/%s", DynAPIPrefix, loc)
211 }
212
213 log.Println("Fetching location:", loc)
214
215 // Generate a new request.
216 req, err := c.newRequest("GET", loc, nil)
217 if err != nil {
218 return err
219 }
220
221 var jobData JobData
222
223 // Poll the API endpoint, until we get a response back.
224 for {
225 select {
226 case <-time.After(PollingInterval):
227 resp, err := c.Transport.RoundTrip(req)
228 if err != nil {
229 return err
230 }
231 defer resp.Body.Close()
232
233 text, err := ioutil.ReadAll(resp.Body)
234 //log.Println(string(text))
235 if err != nil {
236 return fmt.Errorf("Could not read response body:", err)
237 }
238 if err := json.Unmarshal(text, &jobData); err != nil {
239 return fmt.Errorf("failed to decode job response body:", err)
240 }
241
242 // Check to see the status of the job.
243 //
244 // If it is "incomplete", loop around again.
245 //
246 // Should the job's status be "success", then
247 // return the data, business-as-usual.
248 //
249 // TODO(nesv): Figure out what to do in the
250 // event of a "failure" job status.
251
252 switch jobData.Status {
253 case "incomplete":
254 continue
255 case "success":
256 if err := json.Unmarshal(text, &responseData); err != nil {
257 return fmt.Errorf("failed to decode response body:", err)
258 }
259 return nil
260 case "failure":
261 return fmt.Errorf("request failed: %v", jobData.Messages)
262 }
263 }
264 }
265
266 return nil
267
268 case 429:
269 return ErrRateLimited
270 }
271
272 // If we got here, this means that the client does not know how to
273 // interpret the response, and it should just error out.
274 reason, err := ioutil.ReadAll(resp.Body)
275 if err != nil {
276 return fmt.Errorf("failed to read in response body")
277 }
278 return fmt.Errorf("server responded with %v: %v",
279 resp.Status,
280 string(reason))
281 }