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