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