9514: update delete_old_job_logs task also to use the better performing sql.
[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         // Base URIs of Keep services, e.g., {"https://host1:8443",
90         // "https://host2:8443"}.  If this is nil, Keep clients will
91         // use the arvados.v1.keep_services.accessible API to discover
92         // available services.
93         KeepServiceURIs []string
94
95         // Discovery document
96         DiscoveryDoc Dict
97
98         lastClosedIdlesAt time.Time
99
100         // Number of retries
101         Retries int
102 }
103
104 // MakeArvadosClient creates a new ArvadosClient using the standard
105 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
106 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
107 // ARVADOS_KEEP_SERVICES.
108 func MakeArvadosClient() (ac ArvadosClient, err error) {
109         var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
110         insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
111         external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
112
113         ac = ArvadosClient{
114                 Scheme:      "https",
115                 ApiServer:   os.Getenv("ARVADOS_API_HOST"),
116                 ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
117                 ApiInsecure: insecure,
118                 Client: &http.Client{Transport: &http.Transport{
119                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
120                 External: external,
121                 Retries:  2}
122
123         for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
124                 if s == "" {
125                         continue
126                 }
127                 if u, err := url.Parse(s); err != nil {
128                         return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
129                 } else if !u.IsAbs() {
130                         return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
131                 }
132                 ac.KeepServiceURIs = append(ac.KeepServiceURIs, s)
133         }
134
135         if ac.ApiServer == "" {
136                 return ac, MissingArvadosApiHost
137         }
138         if ac.ApiToken == "" {
139                 return ac, MissingArvadosApiToken
140         }
141
142         ac.lastClosedIdlesAt = time.Now()
143
144         return ac, err
145 }
146
147 // CallRaw is the same as Call() but returns a Reader that reads the
148 // response body, instead of taking an output object.
149 func (c ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
150         scheme := c.Scheme
151         if scheme == "" {
152                 scheme = "https"
153         }
154         u := url.URL{
155                 Scheme: scheme,
156                 Host:   c.ApiServer}
157
158         if resourceType != API_DISCOVERY_RESOURCE {
159                 u.Path = "/arvados/v1"
160         }
161
162         if resourceType != "" {
163                 u.Path = u.Path + "/" + resourceType
164         }
165         if uuid != "" {
166                 u.Path = u.Path + "/" + uuid
167         }
168         if action != "" {
169                 u.Path = u.Path + "/" + action
170         }
171
172         if parameters == nil {
173                 parameters = make(Dict)
174         }
175
176         vals := make(url.Values)
177         for k, v := range parameters {
178                 if s, ok := v.(string); ok {
179                         vals.Set(k, s)
180                 } else if m, err := json.Marshal(v); err == nil {
181                         vals.Set(k, string(m))
182                 }
183         }
184
185         retryable := false
186         switch method {
187         case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
188                 retryable = true
189         }
190
191         // Non-retryable methods such as POST are not safe to retry automatically,
192         // so we minimize such failures by always using a new or recently active socket
193         if !retryable {
194                 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
195                         c.lastClosedIdlesAt = time.Now()
196                         c.Client.Transport.(*http.Transport).CloseIdleConnections()
197                 }
198         }
199
200         // Make the request
201         var req *http.Request
202         var resp *http.Response
203
204         for attempt := 0; attempt <= c.Retries; attempt++ {
205                 if method == "GET" || method == "HEAD" {
206                         u.RawQuery = vals.Encode()
207                         if req, err = http.NewRequest(method, u.String(), nil); err != nil {
208                                 return nil, err
209                         }
210                 } else {
211                         if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
212                                 return nil, err
213                         }
214                         req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
215                 }
216
217                 // Add api token header
218                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
219                 if c.External {
220                         req.Header.Add("X-External-Client", "1")
221                 }
222
223                 resp, err = c.Client.Do(req)
224                 if err != nil {
225                         if retryable {
226                                 time.Sleep(RetryDelay)
227                                 continue
228                         } else {
229                                 return nil, err
230                         }
231                 }
232
233                 if resp.StatusCode == http.StatusOK {
234                         return resp.Body, nil
235                 }
236
237                 defer resp.Body.Close()
238
239                 switch resp.StatusCode {
240                 case 408, 409, 422, 423, 500, 502, 503, 504:
241                         time.Sleep(RetryDelay)
242                         continue
243                 default:
244                         return nil, newAPIServerError(c.ApiServer, resp)
245                 }
246         }
247
248         if resp != nil {
249                 return nil, newAPIServerError(c.ApiServer, resp)
250         }
251         return nil, err
252 }
253
254 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
255
256         ase := APIServerError{
257                 ServerAddress:     ServerAddress,
258                 HttpStatusCode:    resp.StatusCode,
259                 HttpStatusMessage: resp.Status}
260
261         // If the response body has {"errors":["reason1","reason2"]}
262         // then return those reasons.
263         var errInfo = Dict{}
264         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
265                 if errorList, ok := errInfo["errors"]; ok {
266                         if errArray, ok := errorList.([]interface{}); ok {
267                                 for _, errItem := range errArray {
268                                         // We expect an array of strings here.
269                                         // Non-strings will be passed along
270                                         // JSON-encoded.
271                                         if s, ok := errItem.(string); ok {
272                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
273                                         } else if j, err := json.Marshal(errItem); err == nil {
274                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
275                                         }
276                                 }
277                         }
278                 }
279         }
280         return ase
281 }
282
283 // Call an API endpoint and parse the JSON response into an object.
284 //
285 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
286 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
287 //   uuid - the uuid of the specific item to access. May be empty.
288 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
289 //   parameters - method parameters.
290 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
291 //
292 // Returns a non-nil error if an error occurs making the API call, the
293 // API responds with a non-successful HTTP status, or an error occurs
294 // parsing the response body.
295 func (c ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
296         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
297         if reader != nil {
298                 defer reader.Close()
299         }
300         if err != nil {
301                 return err
302         }
303
304         if output != nil {
305                 dec := json.NewDecoder(reader)
306                 if err = dec.Decode(output); err != nil {
307                         return err
308                 }
309         }
310         return nil
311 }
312
313 // Create a new resource. See Call for argument descriptions.
314 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
315         return c.Call("POST", resourceType, "", "", parameters, output)
316 }
317
318 // Delete a resource. See Call for argument descriptions.
319 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
320         return c.Call("DELETE", resource, uuid, "", parameters, output)
321 }
322
323 // Modify attributes of a resource. See Call for argument descriptions.
324 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
325         return c.Call("PUT", resourceType, uuid, "", parameters, output)
326 }
327
328 // Get a resource. See Call for argument descriptions.
329 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
330         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
331                 // No object has uuid == "": there is no need to make
332                 // an API call. Furthermore, the HTTP request for such
333                 // an API call would be "GET /arvados/v1/type/", which
334                 // is liable to be misinterpreted as the List API.
335                 return ErrInvalidArgument
336         }
337         return c.Call("GET", resourceType, uuid, "", parameters, output)
338 }
339
340 // List resources of a given type. See Call for argument descriptions.
341 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
342         return c.Call("GET", resource, "", "", parameters, output)
343 }
344
345 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
346
347 // Discovery returns the value of the given parameter in the discovery
348 // document. Returns a non-nil error if the discovery document cannot
349 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
350 // parameter is not found in the discovery document.
351 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
352         if len(c.DiscoveryDoc) == 0 {
353                 c.DiscoveryDoc = make(Dict)
354                 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
355                 if err != nil {
356                         return nil, err
357                 }
358         }
359
360         var found bool
361         value, found = c.DiscoveryDoc[parameter]
362         if found {
363                 return value, nil
364         } else {
365                 return value, ErrInvalidArgument
366         }
367 }