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