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