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