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