10684: Add Arvados-specific search path to Go SDK TLSClientConfig.
[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",   // Arvados specific
110         "/etc/ssl/certs/ca-certificates.crt", // Debian
111         "/etc/pki/tls/certs/ca-bundle.crt",   // Red Hat
112 }
113
114 // SetupRootCAs loads a set of root certificates into TLSClientConfig by
115 // searching a default list of locations.
116 func SetupRootCAs(tlsClientConfig *tls.Config) error {
117         // Container may not have certificates installed, so need to look for
118         // /etc/arvados/ca-certificates.crt in addition to normal system certs.
119
120         certs := x509.NewCertPool()
121         for _, file := range CertFiles {
122                 data, err := ioutil.ReadFile(file)
123                 if err == nil {
124                         certs.AppendCertsFromPEM(data)
125                         tlsClientConfig.RootCAs = certs
126                         return nil
127                 }
128         }
129
130         return fmt.Errorf("Unable to find TLS root certificates to use, tried %v", CertFiles)
131 }
132
133 // New returns an ArvadosClient using the given arvados.Client
134 // configuration. This is useful for callers who load arvados.Client
135 // fields from configuration files but still need to use the
136 // arvadosclient.ArvadosClient package.
137 func New(c *arvados.Client) (*ArvadosClient, error) {
138         tlsconfig := &tls.Config{InsecureSkipVerify: c.Insecure}
139         SetupRootCAs(tlsconfig)
140         ac := &ArvadosClient{
141                 Scheme:      "https",
142                 ApiServer:   c.APIHost,
143                 ApiToken:    c.AuthToken,
144                 ApiInsecure: c.Insecure,
145                 Client: &http.Client{Transport: &http.Transport{
146                         TLSClientConfig: tlsconfig}},
147                 External:          false,
148                 Retries:           2,
149                 lastClosedIdlesAt: time.Now(),
150         }
151
152         return ac, nil
153 }
154
155 // MakeArvadosClient creates a new ArvadosClient using the standard
156 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
157 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
158 // ARVADOS_KEEP_SERVICES.
159 func MakeArvadosClient() (ac *ArvadosClient, err error) {
160         var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
161         insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
162         external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
163
164         tlsconfig := &tls.Config{InsecureSkipVerify: insecure}
165         SetupRootCAs(tlsconfig)
166
167         ac = &ArvadosClient{
168                 Scheme:      "https",
169                 ApiServer:   os.Getenv("ARVADOS_API_HOST"),
170                 ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
171                 ApiInsecure: insecure,
172                 Client: &http.Client{Transport: &http.Transport{
173                         TLSClientConfig: tlsconfig}},
174                 External: external,
175                 Retries:  2}
176
177         for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
178                 if s == "" {
179                         continue
180                 }
181                 if u, err := url.Parse(s); err != nil {
182                         return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
183                 } else if !u.IsAbs() {
184                         return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
185                 }
186                 ac.KeepServiceURIs = append(ac.KeepServiceURIs, s)
187         }
188
189         if ac.ApiServer == "" {
190                 return ac, MissingArvadosApiHost
191         }
192         if ac.ApiToken == "" {
193                 return ac, MissingArvadosApiToken
194         }
195
196         ac.lastClosedIdlesAt = time.Now()
197
198         return ac, err
199 }
200
201 // CallRaw is the same as Call() but returns a Reader that reads the
202 // response body, instead of taking an output object.
203 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
204         scheme := c.Scheme
205         if scheme == "" {
206                 scheme = "https"
207         }
208         u := url.URL{
209                 Scheme: scheme,
210                 Host:   c.ApiServer}
211
212         if resourceType != API_DISCOVERY_RESOURCE {
213                 u.Path = "/arvados/v1"
214         }
215
216         if resourceType != "" {
217                 u.Path = u.Path + "/" + resourceType
218         }
219         if uuid != "" {
220                 u.Path = u.Path + "/" + uuid
221         }
222         if action != "" {
223                 u.Path = u.Path + "/" + action
224         }
225
226         if parameters == nil {
227                 parameters = make(Dict)
228         }
229
230         vals := make(url.Values)
231         for k, v := range parameters {
232                 if s, ok := v.(string); ok {
233                         vals.Set(k, s)
234                 } else if m, err := json.Marshal(v); err == nil {
235                         vals.Set(k, string(m))
236                 }
237         }
238
239         retryable := false
240         switch method {
241         case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
242                 retryable = true
243         }
244
245         // Non-retryable methods such as POST are not safe to retry automatically,
246         // so we minimize such failures by always using a new or recently active socket
247         if !retryable {
248                 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
249                         c.lastClosedIdlesAt = time.Now()
250                         c.Client.Transport.(*http.Transport).CloseIdleConnections()
251                 }
252         }
253
254         // Make the request
255         var req *http.Request
256         var resp *http.Response
257
258         for attempt := 0; attempt <= c.Retries; attempt++ {
259                 if method == "GET" || method == "HEAD" {
260                         u.RawQuery = vals.Encode()
261                         if req, err = http.NewRequest(method, u.String(), nil); err != nil {
262                                 return nil, err
263                         }
264                 } else {
265                         if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
266                                 return nil, err
267                         }
268                         req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
269                 }
270
271                 // Add api token header
272                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
273                 if c.External {
274                         req.Header.Add("X-External-Client", "1")
275                 }
276
277                 resp, err = c.Client.Do(req)
278                 if err != nil {
279                         if retryable {
280                                 time.Sleep(RetryDelay)
281                                 continue
282                         } else {
283                                 return nil, err
284                         }
285                 }
286
287                 if resp.StatusCode == http.StatusOK {
288                         return resp.Body, nil
289                 }
290
291                 defer resp.Body.Close()
292
293                 switch resp.StatusCode {
294                 case 408, 409, 422, 423, 500, 502, 503, 504:
295                         time.Sleep(RetryDelay)
296                         continue
297                 default:
298                         return nil, newAPIServerError(c.ApiServer, resp)
299                 }
300         }
301
302         if resp != nil {
303                 return nil, newAPIServerError(c.ApiServer, resp)
304         }
305         return nil, err
306 }
307
308 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
309
310         ase := APIServerError{
311                 ServerAddress:     ServerAddress,
312                 HttpStatusCode:    resp.StatusCode,
313                 HttpStatusMessage: resp.Status}
314
315         // If the response body has {"errors":["reason1","reason2"]}
316         // then return those reasons.
317         var errInfo = Dict{}
318         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
319                 if errorList, ok := errInfo["errors"]; ok {
320                         if errArray, ok := errorList.([]interface{}); ok {
321                                 for _, errItem := range errArray {
322                                         // We expect an array of strings here.
323                                         // Non-strings will be passed along
324                                         // JSON-encoded.
325                                         if s, ok := errItem.(string); ok {
326                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
327                                         } else if j, err := json.Marshal(errItem); err == nil {
328                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
329                                         }
330                                 }
331                         }
332                 }
333         }
334         return ase
335 }
336
337 // Call an API endpoint and parse the JSON response into an object.
338 //
339 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
340 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
341 //   uuid - the uuid of the specific item to access. May be empty.
342 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
343 //   parameters - method parameters.
344 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
345 //
346 // Returns a non-nil error if an error occurs making the API call, the
347 // API responds with a non-successful HTTP status, or an error occurs
348 // parsing the response body.
349 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
350         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
351         if reader != nil {
352                 defer reader.Close()
353         }
354         if err != nil {
355                 return err
356         }
357
358         if output != nil {
359                 dec := json.NewDecoder(reader)
360                 if err = dec.Decode(output); err != nil {
361                         return err
362                 }
363         }
364         return nil
365 }
366
367 // Create a new resource. See Call for argument descriptions.
368 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
369         return c.Call("POST", resourceType, "", "", parameters, output)
370 }
371
372 // Delete a resource. See Call for argument descriptions.
373 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
374         return c.Call("DELETE", resource, uuid, "", parameters, output)
375 }
376
377 // Modify attributes of a resource. See Call for argument descriptions.
378 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
379         return c.Call("PUT", resourceType, uuid, "", parameters, output)
380 }
381
382 // Get a resource. See Call for argument descriptions.
383 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
384         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
385                 // No object has uuid == "": there is no need to make
386                 // an API call. Furthermore, the HTTP request for such
387                 // an API call would be "GET /arvados/v1/type/", which
388                 // is liable to be misinterpreted as the List API.
389                 return ErrInvalidArgument
390         }
391         return c.Call("GET", resourceType, uuid, "", parameters, output)
392 }
393
394 // List resources of a given type. See Call for argument descriptions.
395 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
396         return c.Call("GET", resource, "", "", parameters, output)
397 }
398
399 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
400
401 // Discovery returns the value of the given parameter in the discovery
402 // document. Returns a non-nil error if the discovery document cannot
403 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
404 // parameter is not found in the discovery document.
405 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
406         if len(c.DiscoveryDoc) == 0 {
407                 c.DiscoveryDoc = make(Dict)
408                 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
409                 if err != nil {
410                         return nil, err
411                 }
412         }
413
414         var found bool
415         value, found = c.DiscoveryDoc[parameter]
416         if found {
417                 return value, nil
418         } else {
419                 return value, ErrInvalidArgument
420         }
421 }