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