Merge branch 'master' into 5538-arvadosclient-retry
[arvados.git] / sdk / go / arvadosclient / arvadosclient.go
1 /* Simple Arvados Go SDK for communicating with API server. */
2
3 package arvadosclient
4
5 import (
6         "bytes"
7         "crypto/tls"
8         "encoding/json"
9         "errors"
10         "fmt"
11         "io"
12         "net/http"
13         "net/url"
14         "os"
15         "regexp"
16         "strings"
17         "time"
18 )
19
20 type StringMatcher func(string) bool
21
22 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
23 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
24
25 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
26 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
27 var ErrInvalidArgument = errors.New("Invalid argument")
28
29 // A common failure mode is to reuse a keepalive connection that has been
30 // terminated (in a way that we can't detect) for being idle too long.
31 // POST and DELETE are not safe to retry automatically, so we minimize
32 // such failures by always using a new or recently active socket.
33 var MaxIdleConnectionDuration = 30 * time.Second
34
35 var RetryDelay = 2 * time.Second
36
37 // Indicates an error that was returned by the API server.
38 type APIServerError struct {
39         // Address of server returning error, of the form "host:port".
40         ServerAddress string
41
42         // Components of server response.
43         HttpStatusCode    int
44         HttpStatusMessage string
45
46         // Additional error details from response body.
47         ErrorDetails []string
48 }
49
50 func (e APIServerError) Error() string {
51         if len(e.ErrorDetails) > 0 {
52                 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
53                         strings.Join(e.ErrorDetails, "; "),
54                         e.HttpStatusCode,
55                         e.HttpStatusMessage,
56                         e.ServerAddress)
57         } else {
58                 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
59                         e.HttpStatusCode,
60                         e.HttpStatusMessage,
61                         e.ServerAddress)
62         }
63 }
64
65 // Helper type so we don't have to write out 'map[string]interface{}' every time.
66 type Dict map[string]interface{}
67
68 // Information about how to contact the Arvados server
69 type ArvadosClient struct {
70         // https
71         Scheme string
72
73         // Arvados API server, form "host:port"
74         ApiServer string
75
76         // Arvados API token for authentication
77         ApiToken string
78
79         // Whether to require a valid SSL certificate or not
80         ApiInsecure bool
81
82         // Client object shared by client requests.  Supports HTTP KeepAlive.
83         Client *http.Client
84
85         // If true, sets the X-External-Client header to indicate
86         // the client is outside the cluster.
87         External bool
88
89         // Discovery document
90         DiscoveryDoc Dict
91
92         lastClosedIdlesAt time.Time
93
94         // Number of retries
95         Retries int
96 }
97
98 // Create a new ArvadosClient, initialized with standard Arvados environment
99 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
100 // ARVADOS_API_HOST_INSECURE.
101 func MakeArvadosClient() (ac ArvadosClient, err error) {
102         var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
103         insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
104         external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
105
106         ac = ArvadosClient{
107                 Scheme:      "https",
108                 ApiServer:   os.Getenv("ARVADOS_API_HOST"),
109                 ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
110                 ApiInsecure: insecure,
111                 Client: &http.Client{Transport: &http.Transport{
112                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
113                 External: external,
114                 Retries:  2}
115
116         if ac.ApiServer == "" {
117                 return ac, MissingArvadosApiHost
118         }
119         if ac.ApiToken == "" {
120                 return ac, MissingArvadosApiToken
121         }
122
123         ac.lastClosedIdlesAt = time.Now()
124
125         return ac, err
126 }
127
128 // CallRaw is the same as Call() but returns a Reader that reads the
129 // response body, instead of taking an output object.
130 func (c ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
131         scheme := c.Scheme
132         if scheme == "" {
133                 scheme = "https"
134         }
135         u := url.URL{
136                 Scheme: scheme,
137                 Host:   c.ApiServer}
138
139         if resourceType != API_DISCOVERY_RESOURCE {
140                 u.Path = "/arvados/v1"
141         }
142
143         if resourceType != "" {
144                 u.Path = u.Path + "/" + resourceType
145         }
146         if uuid != "" {
147                 u.Path = u.Path + "/" + uuid
148         }
149         if action != "" {
150                 u.Path = u.Path + "/" + action
151         }
152
153         if parameters == nil {
154                 parameters = make(Dict)
155         }
156
157         vals := make(url.Values)
158         for k, v := range parameters {
159                 if s, ok := v.(string); ok {
160                         vals.Set(k, s)
161                 } else if m, err := json.Marshal(v); err == nil {
162                         vals.Set(k, string(m))
163                 }
164         }
165
166         retryable := false
167         switch method {
168         case "GET", "HEAD", "PUT", "OPTIONS", "POST", "DELETE":
169                 retryable = true
170         }
171
172         // POST and DELETE are not safe to retry automatically, so we minimize
173         // such failures by always using a new or recently active socket
174         if method == "POST" || method == "DELETE" {
175                 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
176                         c.lastClosedIdlesAt = time.Now()
177                         c.Client.Transport.(*http.Transport).CloseIdleConnections()
178                 }
179         }
180
181         // Make the request
182         var req *http.Request
183         var resp *http.Response
184
185         for attempt := 0; attempt <= c.Retries; attempt++ {
186                 if method == "GET" || method == "HEAD" {
187                         u.RawQuery = vals.Encode()
188                         if req, err = http.NewRequest(method, u.String(), nil); err != nil {
189                                 return nil, err
190                         }
191                 } else {
192                         if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
193                                 return nil, err
194                         }
195                         req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
196                 }
197
198                 // Add api token header
199                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
200                 if c.External {
201                         req.Header.Add("X-External-Client", "1")
202                 }
203
204                 resp, err = c.Client.Do(req)
205                 if err != nil {
206                         if retryable {
207                                 time.Sleep(RetryDelay)
208                                 continue
209                         } else {
210                                 return nil, err
211                         }
212                 }
213
214                 if resp.StatusCode == http.StatusOK {
215                         return resp.Body, nil
216                 }
217
218                 defer resp.Body.Close()
219
220                 switch resp.StatusCode {
221                 case 408, 409, 422, 423, 500, 502, 503, 504:
222                         time.Sleep(RetryDelay)
223                         continue
224                 default:
225                         return nil, newAPIServerError(c.ApiServer, resp)
226                 }
227         }
228
229         if resp != nil {
230                 return nil, newAPIServerError(c.ApiServer, resp)
231         } else {
232                 return nil, err
233         }
234 }
235
236 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
237
238         ase := APIServerError{
239                 ServerAddress:     ServerAddress,
240                 HttpStatusCode:    resp.StatusCode,
241                 HttpStatusMessage: resp.Status}
242
243         // If the response body has {"errors":["reason1","reason2"]}
244         // then return those reasons.
245         var errInfo = Dict{}
246         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
247                 if errorList, ok := errInfo["errors"]; ok {
248                         if errArray, ok := errorList.([]interface{}); ok {
249                                 for _, errItem := range errArray {
250                                         // We expect an array of strings here.
251                                         // Non-strings will be passed along
252                                         // JSON-encoded.
253                                         if s, ok := errItem.(string); ok {
254                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
255                                         } else if j, err := json.Marshal(errItem); err == nil {
256                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
257                                         }
258                                 }
259                         }
260                 }
261         }
262         return ase
263 }
264
265 // Call an API endpoint and parse the JSON response into an object.
266 //
267 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
268 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
269 //   uuid - the uuid of the specific item to access. May be empty.
270 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
271 //   parameters - method parameters.
272 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
273 //
274 // Returns a non-nil error if an error occurs making the API call, the
275 // API responds with a non-successful HTTP status, or an error occurs
276 // parsing the response body.
277 func (c ArvadosClient) Call(method string, resourceType string, uuid string, action string, parameters Dict, output interface{}) error {
278         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
279         if reader != nil {
280                 defer reader.Close()
281         }
282         if err != nil {
283                 return err
284         }
285
286         if output != nil {
287                 dec := json.NewDecoder(reader)
288                 if err = dec.Decode(output); err != nil {
289                         return err
290                 }
291         }
292         return nil
293 }
294
295 // Create a new resource. See Call for argument descriptions.
296 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
297         return c.Call("POST", resourceType, "", "", parameters, output)
298 }
299
300 // Delete a resource. See Call for argument descriptions.
301 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
302         return c.Call("DELETE", resource, uuid, "", parameters, output)
303 }
304
305 // Modify attributes of a resource. See Call for argument descriptions.
306 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
307         return c.Call("PUT", resourceType, uuid, "", parameters, output)
308 }
309
310 // Get a resource. See Call for argument descriptions.
311 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
312         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
313                 // No object has uuid == "": there is no need to make
314                 // an API call. Furthermore, the HTTP request for such
315                 // an API call would be "GET /arvados/v1/type/", which
316                 // is liable to be misinterpreted as the List API.
317                 return ErrInvalidArgument
318         }
319         return c.Call("GET", resourceType, uuid, "", parameters, output)
320 }
321
322 // List resources of a given type. See Call for argument descriptions.
323 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
324         return c.Call("GET", resource, "", "", parameters, output)
325 }
326
327 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
328
329 // Discovery returns the value of the given parameter in the discovery
330 // document. Returns a non-nil error if the discovery document cannot
331 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
332 // parameter is not found in the discovery document.
333 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
334         if len(c.DiscoveryDoc) == 0 {
335                 c.DiscoveryDoc = make(Dict)
336                 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
337                 if err != nil {
338                         return nil, err
339                 }
340         }
341
342         var found bool
343         value, found = c.DiscoveryDoc[parameter]
344         if found {
345                 return value, nil
346         } else {
347                 return value, ErrInvalidArgument
348         }
349 }