Merge branch '9005-keep-http-client'
[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         "crypto/x509"
9         "encoding/json"
10         "errors"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "log"
15         "net/http"
16         "net/url"
17         "os"
18         "regexp"
19         "strings"
20         "sync"
21         "time"
22
23         "git.curoverse.com/arvados.git/sdk/go/arvados"
24 )
25
26 type StringMatcher func(string) bool
27
28 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
29 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
30
31 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
32 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
33 var ErrInvalidArgument = errors.New("Invalid argument")
34
35 // A common failure mode is to reuse a keepalive connection that has been
36 // terminated (in a way that we can't detect) for being idle too long.
37 // POST and DELETE are not safe to retry automatically, so we minimize
38 // such failures by always using a new or recently active socket.
39 var MaxIdleConnectionDuration = 30 * time.Second
40
41 var RetryDelay = 2 * time.Second
42
43 var (
44         defaultInsecureHTTPClient *http.Client
45         defaultSecureHTTPClient   *http.Client
46         defaultHTTPClientMtx      sync.Mutex
47 )
48
49 // Indicates an error that was returned by the API server.
50 type APIServerError struct {
51         // Address of server returning error, of the form "host:port".
52         ServerAddress string
53
54         // Components of server response.
55         HttpStatusCode    int
56         HttpStatusMessage string
57
58         // Additional error details from response body.
59         ErrorDetails []string
60 }
61
62 func (e APIServerError) Error() string {
63         if len(e.ErrorDetails) > 0 {
64                 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
65                         strings.Join(e.ErrorDetails, "; "),
66                         e.HttpStatusCode,
67                         e.HttpStatusMessage,
68                         e.ServerAddress)
69         } else {
70                 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
71                         e.HttpStatusCode,
72                         e.HttpStatusMessage,
73                         e.ServerAddress)
74         }
75 }
76
77 // Helper type so we don't have to write out 'map[string]interface{}' every time.
78 type Dict map[string]interface{}
79
80 // Information about how to contact the Arvados server
81 type ArvadosClient struct {
82         // https
83         Scheme string
84
85         // Arvados API server, form "host:port"
86         ApiServer string
87
88         // Arvados API token for authentication
89         ApiToken string
90
91         // Whether to require a valid SSL certificate or not
92         ApiInsecure bool
93
94         // Client object shared by client requests.  Supports HTTP KeepAlive.
95         Client *http.Client
96
97         // If true, sets the X-External-Client header to indicate
98         // the client is outside the cluster.
99         External bool
100
101         // Base URIs of Keep services, e.g., {"https://host1:8443",
102         // "https://host2:8443"}.  If this is nil, Keep clients will
103         // use the arvados.v1.keep_services.accessible API to discover
104         // available services.
105         KeepServiceURIs []string
106
107         // Discovery document
108         DiscoveryDoc Dict
109
110         lastClosedIdlesAt time.Time
111
112         // Number of retries
113         Retries int
114 }
115
116 var CertFiles = []string{
117         "/etc/arvados/ca-certificates.crt",
118         "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
119         "/etc/pki/tls/certs/ca-bundle.crt",   // Fedora/RHEL
120 }
121
122 // MakeTLSConfig sets up TLS configuration for communicating with
123 // Arvados and Keep services.
124 func MakeTLSConfig(insecure bool) *tls.Config {
125         tlsconfig := tls.Config{InsecureSkipVerify: insecure}
126
127         if !insecure {
128                 // Use the first entry in CertFiles that we can read
129                 // certificates from. If none of those work out, use
130                 // the Go defaults.
131                 certs := x509.NewCertPool()
132                 for _, file := range CertFiles {
133                         data, err := ioutil.ReadFile(file)
134                         if err != nil {
135                                 if !os.IsNotExist(err) {
136                                         log.Printf("error reading %q: %s", file, err)
137                                 }
138                                 continue
139                         }
140                         if !certs.AppendCertsFromPEM(data) {
141                                 log.Printf("unable to load any certificates from %v", file)
142                                 continue
143                         }
144                         tlsconfig.RootCAs = certs
145                         break
146                 }
147         }
148
149         return &tlsconfig
150 }
151
152 // New returns an ArvadosClient using the given arvados.Client
153 // configuration. This is useful for callers who load arvados.Client
154 // fields from configuration files but still need to use the
155 // arvadosclient.ArvadosClient package.
156 func New(c *arvados.Client) (*ArvadosClient, error) {
157         ac := &ArvadosClient{
158                 Scheme:      "https",
159                 ApiServer:   c.APIHost,
160                 ApiToken:    c.AuthToken,
161                 ApiInsecure: c.Insecure,
162                 Client: &http.Client{Transport: &http.Transport{
163                         TLSClientConfig: MakeTLSConfig(c.Insecure)}},
164                 External:          false,
165                 Retries:           2,
166                 lastClosedIdlesAt: time.Now(),
167         }
168
169         return ac, nil
170 }
171
172 // MakeArvadosClient creates a new ArvadosClient using the standard
173 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
174 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
175 // ARVADOS_KEEP_SERVICES.
176 func MakeArvadosClient() (ac *ArvadosClient, err error) {
177         var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
178         insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
179         external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
180
181         ac = &ArvadosClient{
182                 Scheme:      "https",
183                 ApiServer:   os.Getenv("ARVADOS_API_HOST"),
184                 ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
185                 ApiInsecure: insecure,
186                 Client: &http.Client{Transport: &http.Transport{
187                         TLSClientConfig: MakeTLSConfig(insecure)}},
188                 External: external,
189                 Retries:  2}
190
191         for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
192                 if s == "" {
193                         continue
194                 }
195                 if u, err := url.Parse(s); err != nil {
196                         return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
197                 } else if !u.IsAbs() {
198                         return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
199                 }
200                 ac.KeepServiceURIs = append(ac.KeepServiceURIs, s)
201         }
202
203         if ac.ApiServer == "" {
204                 return ac, MissingArvadosApiHost
205         }
206         if ac.ApiToken == "" {
207                 return ac, MissingArvadosApiToken
208         }
209
210         ac.lastClosedIdlesAt = time.Now()
211
212         return ac, err
213 }
214
215 // CallRaw is the same as Call() but returns a Reader that reads the
216 // response body, instead of taking an output object.
217 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
218         scheme := c.Scheme
219         if scheme == "" {
220                 scheme = "https"
221         }
222         u := url.URL{
223                 Scheme: scheme,
224                 Host:   c.ApiServer}
225
226         if resourceType != API_DISCOVERY_RESOURCE {
227                 u.Path = "/arvados/v1"
228         }
229
230         if resourceType != "" {
231                 u.Path = u.Path + "/" + resourceType
232         }
233         if uuid != "" {
234                 u.Path = u.Path + "/" + uuid
235         }
236         if action != "" {
237                 u.Path = u.Path + "/" + action
238         }
239
240         if parameters == nil {
241                 parameters = make(Dict)
242         }
243
244         vals := make(url.Values)
245         for k, v := range parameters {
246                 if s, ok := v.(string); ok {
247                         vals.Set(k, s)
248                 } else if m, err := json.Marshal(v); err == nil {
249                         vals.Set(k, string(m))
250                 }
251         }
252
253         retryable := false
254         switch method {
255         case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
256                 retryable = true
257         }
258
259         // Non-retryable methods such as POST are not safe to retry automatically,
260         // so we minimize such failures by always using a new or recently active socket
261         if !retryable {
262                 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
263                         c.lastClosedIdlesAt = time.Now()
264                         c.Client.Transport.(*http.Transport).CloseIdleConnections()
265                 }
266         }
267
268         // Make the request
269         var req *http.Request
270         var resp *http.Response
271
272         for attempt := 0; attempt <= c.Retries; attempt++ {
273                 if method == "GET" || method == "HEAD" {
274                         u.RawQuery = vals.Encode()
275                         if req, err = http.NewRequest(method, u.String(), nil); err != nil {
276                                 return nil, err
277                         }
278                 } else {
279                         if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
280                                 return nil, err
281                         }
282                         req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
283                 }
284
285                 // Add api token header
286                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
287                 if c.External {
288                         req.Header.Add("X-External-Client", "1")
289                 }
290
291                 resp, err = c.Client.Do(req)
292                 if err != nil {
293                         if retryable {
294                                 time.Sleep(RetryDelay)
295                                 continue
296                         } else {
297                                 return nil, err
298                         }
299                 }
300
301                 if resp.StatusCode == http.StatusOK {
302                         return resp.Body, nil
303                 }
304
305                 defer resp.Body.Close()
306
307                 switch resp.StatusCode {
308                 case 408, 409, 422, 423, 500, 502, 503, 504:
309                         time.Sleep(RetryDelay)
310                         continue
311                 default:
312                         return nil, newAPIServerError(c.ApiServer, resp)
313                 }
314         }
315
316         if resp != nil {
317                 return nil, newAPIServerError(c.ApiServer, resp)
318         }
319         return nil, err
320 }
321
322 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
323
324         ase := APIServerError{
325                 ServerAddress:     ServerAddress,
326                 HttpStatusCode:    resp.StatusCode,
327                 HttpStatusMessage: resp.Status}
328
329         // If the response body has {"errors":["reason1","reason2"]}
330         // then return those reasons.
331         var errInfo = Dict{}
332         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
333                 if errorList, ok := errInfo["errors"]; ok {
334                         if errArray, ok := errorList.([]interface{}); ok {
335                                 for _, errItem := range errArray {
336                                         // We expect an array of strings here.
337                                         // Non-strings will be passed along
338                                         // JSON-encoded.
339                                         if s, ok := errItem.(string); ok {
340                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
341                                         } else if j, err := json.Marshal(errItem); err == nil {
342                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
343                                         }
344                                 }
345                         }
346                 }
347         }
348         return ase
349 }
350
351 // Call an API endpoint and parse the JSON response into an object.
352 //
353 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
354 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
355 //   uuid - the uuid of the specific item to access. May be empty.
356 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
357 //   parameters - method parameters.
358 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
359 //
360 // Returns a non-nil error if an error occurs making the API call, the
361 // API responds with a non-successful HTTP status, or an error occurs
362 // parsing the response body.
363 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
364         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
365         if reader != nil {
366                 defer reader.Close()
367         }
368         if err != nil {
369                 return err
370         }
371
372         if output != nil {
373                 dec := json.NewDecoder(reader)
374                 if err = dec.Decode(output); err != nil {
375                         return err
376                 }
377         }
378         return nil
379 }
380
381 // Create a new resource. See Call for argument descriptions.
382 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
383         return c.Call("POST", resourceType, "", "", parameters, output)
384 }
385
386 // Delete a resource. See Call for argument descriptions.
387 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
388         return c.Call("DELETE", resource, uuid, "", parameters, output)
389 }
390
391 // Modify attributes of a resource. See Call for argument descriptions.
392 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
393         return c.Call("PUT", resourceType, uuid, "", parameters, output)
394 }
395
396 // Get a resource. See Call for argument descriptions.
397 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
398         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
399                 // No object has uuid == "": there is no need to make
400                 // an API call. Furthermore, the HTTP request for such
401                 // an API call would be "GET /arvados/v1/type/", which
402                 // is liable to be misinterpreted as the List API.
403                 return ErrInvalidArgument
404         }
405         return c.Call("GET", resourceType, uuid, "", parameters, output)
406 }
407
408 // List resources of a given type. See Call for argument descriptions.
409 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
410         return c.Call("GET", resource, "", "", parameters, output)
411 }
412
413 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
414
415 // Discovery returns the value of the given parameter in the discovery
416 // document. Returns a non-nil error if the discovery document cannot
417 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
418 // parameter is not found in the discovery document.
419 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
420         if len(c.DiscoveryDoc) == 0 {
421                 c.DiscoveryDoc = make(Dict)
422                 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
423                 if err != nil {
424                         return nil, err
425                 }
426         }
427
428         var found bool
429         value, found = c.DiscoveryDoc[parameter]
430         if found {
431                 return value, nil
432         } else {
433                 return value, ErrInvalidArgument
434         }
435 }
436
437 func (ac *ArvadosClient) httpClient() *http.Client {
438         if ac.Client != nil {
439                 return ac.Client
440         }
441         c := &defaultSecureHTTPClient
442         if ac.ApiInsecure {
443                 c = &defaultInsecureHTTPClient
444         }
445         if *c == nil {
446                 defaultHTTPClientMtx.Lock()
447                 defer defaultHTTPClientMtx.Unlock()
448                 *c = &http.Client{Transport: &http.Transport{
449                         TLSClientConfig: MakeTLSConfig(ac.ApiInsecure)}}
450         }
451         return *c
452 }