14262: Add createAPIToken, with test
[arvados.git] / sdk / go / arvados / client.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bytes"
9         "context"
10         "crypto/tls"
11         "encoding/json"
12         "fmt"
13         "io"
14         "io/ioutil"
15         "log"
16         "math"
17         "net/http"
18         "net/url"
19         "os"
20         "regexp"
21         "strings"
22         "time"
23
24         "git.curoverse.com/arvados.git/sdk/go/httpserver"
25 )
26
27 // A Client is an HTTP client with an API endpoint and a set of
28 // Arvados credentials.
29 //
30 // It offers methods for accessing individual Arvados APIs, and
31 // methods that implement common patterns like fetching multiple pages
32 // of results using List APIs.
33 type Client struct {
34         // HTTP client used to make requests. If nil,
35         // DefaultSecureClient or InsecureHTTPClient will be used.
36         Client *http.Client `json:"-"`
37
38         // Hostname (or host:port) of Arvados API server.
39         APIHost string
40
41         // User authentication token.
42         AuthToken string
43
44         // Accept unverified certificates. This works only if the
45         // Client field is nil: otherwise, it has no effect.
46         Insecure bool
47
48         // Override keep service discovery with a list of base
49         // URIs. (Currently there are no Client methods for
50         // discovering keep services so this is just a convenience for
51         // callers who use a Client to initialize an
52         // arvadosclient.ArvadosClient.)
53         KeepServiceURIs []string `json:",omitempty"`
54
55         dd *DiscoveryDocument
56
57         ctx context.Context
58 }
59
60 // The default http.Client used by a Client with Insecure==true and
61 // Client==nil.
62 var InsecureHTTPClient = &http.Client{
63         Transport: &http.Transport{
64                 TLSClientConfig: &tls.Config{
65                         InsecureSkipVerify: true}},
66         Timeout: 5 * time.Minute}
67
68 // The default http.Client used by a Client otherwise.
69 var DefaultSecureClient = &http.Client{
70         Timeout: 5 * time.Minute}
71
72 // NewClientFromEnv creates a new Client that uses the default HTTP
73 // client with the API endpoint and credentials given by the
74 // ARVADOS_API_* environment variables.
75 func NewClientFromEnv() *Client {
76         var svcs []string
77         for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
78                 if s == "" {
79                         continue
80                 } else if u, err := url.Parse(s); err != nil {
81                         log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
82                 } else if !u.IsAbs() {
83                         log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
84                 } else {
85                         svcs = append(svcs, s)
86                 }
87         }
88         var insecure bool
89         if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
90                 insecure = true
91         }
92         return &Client{
93                 APIHost:         os.Getenv("ARVADOS_API_HOST"),
94                 AuthToken:       os.Getenv("ARVADOS_API_TOKEN"),
95                 Insecure:        insecure,
96                 KeepServiceURIs: svcs,
97         }
98 }
99
100 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
101
102 // Do adds Authorization and X-Request-Id headers and then calls
103 // (*http.Client)Do().
104 func (c *Client) Do(req *http.Request) (*http.Response, error) {
105         if c.AuthToken != "" {
106                 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
107         }
108
109         if req.Header.Get("X-Request-Id") == "" {
110                 reqid, _ := c.context().Value(contextKeyRequestID).(string)
111                 if reqid == "" {
112                         reqid = reqIDGen.Next()
113                 }
114                 if req.Header == nil {
115                         req.Header = http.Header{"X-Request-Id": {reqid}}
116                 } else {
117                         req.Header.Set("X-Request-Id", reqid)
118                 }
119         }
120         return c.httpClient().Do(req)
121 }
122
123 // DoAndDecode performs req and unmarshals the response (which must be
124 // JSON) into dst. Use this instead of RequestAndDecode if you need
125 // more control of the http.Request object.
126 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
127         resp, err := c.Do(req)
128         if err != nil {
129                 return err
130         }
131         defer resp.Body.Close()
132         buf, err := ioutil.ReadAll(resp.Body)
133         if err != nil {
134                 return err
135         }
136         if resp.StatusCode != 200 {
137                 return newTransactionError(req, resp, buf)
138         }
139         if dst == nil {
140                 return nil
141         }
142         return json.Unmarshal(buf, dst)
143 }
144
145 // Convert an arbitrary struct to url.Values. For example,
146 //
147 //     Foo{Bar: []int{1,2,3}, Baz: "waz"}
148 //
149 // becomes
150 //
151 //     url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
152 //
153 // params itself is returned if it is already an url.Values.
154 func anythingToValues(params interface{}) (url.Values, error) {
155         if v, ok := params.(url.Values); ok {
156                 return v, nil
157         }
158         // TODO: Do this more efficiently, possibly using
159         // json.Decode/Encode, so the whole thing doesn't have to get
160         // encoded, decoded, and re-encoded.
161         j, err := json.Marshal(params)
162         if err != nil {
163                 return nil, err
164         }
165         var generic map[string]interface{}
166         err = json.Unmarshal(j, &generic)
167         if err != nil {
168                 return nil, err
169         }
170         urlValues := url.Values{}
171         for k, v := range generic {
172                 if v, ok := v.(string); ok {
173                         urlValues.Set(k, v)
174                         continue
175                 }
176                 if v, ok := v.(float64); ok {
177                         // Unmarshal decodes all numbers as float64,
178                         // which can be written as 1.2345e4 in JSON,
179                         // but this form is not accepted for ints in
180                         // url params. If a number fits in an int64,
181                         // encode it as int64 rather than float64.
182                         if v, frac := math.Modf(v); frac == 0 && v <= math.MaxInt64 && v >= math.MinInt64 {
183                                 urlValues.Set(k, fmt.Sprintf("%d", int64(v)))
184                                 continue
185                         }
186                 }
187                 j, err := json.Marshal(v)
188                 if err != nil {
189                         return nil, err
190                 }
191                 urlValues.Set(k, string(j))
192         }
193         return urlValues, nil
194 }
195
196 func (c *Client) MakeRequest(method, path string, body io.Reader, params interface{}) (*http.Request, error) {
197         urlString := c.apiURL(path)
198         urlValues, err := anythingToValues(params)
199         if err != nil {
200                 return nil, err
201         }
202         if (method == "GET" || body != nil) && urlValues != nil {
203                 // FIXME: what if params don't fit in URL
204                 u, err := url.Parse(urlString)
205                 if err != nil {
206                         return nil, err
207                 }
208                 u.RawQuery = urlValues.Encode()
209                 urlString = u.String()
210         }
211         req, err := http.NewRequest(method, urlString, body)
212         if err != nil {
213                 return nil, err
214         }
215         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
216
217         if c.AuthToken != "" {
218                 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
219         }
220
221         if req.Header.Get("X-Request-Id") == "" {
222                 reqid, _ := c.context().Value(contextKeyRequestID).(string)
223                 if reqid == "" {
224                         reqid = reqIDGen.Next()
225                 }
226                 if req.Header == nil {
227                         req.Header = http.Header{"X-Request-Id": {reqid}}
228                 } else {
229                         req.Header.Set("X-Request-Id", reqid)
230                 }
231         }
232
233         return req, nil
234 }
235
236 // RequestAndDecode performs an API request and unmarshals the
237 // response (which must be JSON) into dst. Method and body arguments
238 // are the same as for http.NewRequest(). The given path is added to
239 // the server's scheme/host/port to form the request URL. The given
240 // params are passed via POST form or query string.
241 //
242 // path must not contain a query string.
243 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
244         if body, ok := body.(io.Closer); ok {
245                 // Ensure body is closed even if we error out early
246                 defer body.Close()
247         }
248         req, err := c.MakeRequest(method, path, body, params)
249         if err != nil {
250                 return err
251         }
252         return c.DoAndDecode(dst, req)
253 }
254
255 type resource interface {
256         resourceName() string
257 }
258
259 // UpdateBody returns an io.Reader suitable for use as an http.Request
260 // Body for a create or update API call.
261 func (c *Client) UpdateBody(rsc resource) io.Reader {
262         j, err := json.Marshal(rsc)
263         if err != nil {
264                 // Return a reader that returns errors.
265                 r, w := io.Pipe()
266                 w.CloseWithError(err)
267                 return r
268         }
269         v := url.Values{rsc.resourceName(): {string(j)}}
270         return bytes.NewBufferString(v.Encode())
271 }
272
273 type contextKey string
274
275 var contextKeyRequestID contextKey = "X-Request-Id"
276
277 func (c *Client) WithRequestID(reqid string) *Client {
278         cc := *c
279         cc.ctx = context.WithValue(cc.context(), contextKeyRequestID, reqid)
280         return &cc
281 }
282
283 func (c *Client) context() context.Context {
284         if c.ctx == nil {
285                 return context.Background()
286         }
287         return c.ctx
288 }
289
290 func (c *Client) httpClient() *http.Client {
291         switch {
292         case c.Client != nil:
293                 return c.Client
294         case c.Insecure:
295                 return InsecureHTTPClient
296         default:
297                 return DefaultSecureClient
298         }
299 }
300
301 func (c *Client) apiURL(path string) string {
302         return "https://" + c.APIHost + "/" + path
303 }
304
305 // DiscoveryDocument is the Arvados server's description of itself.
306 type DiscoveryDocument struct {
307         BasePath                     string              `json:"basePath"`
308         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
309         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
310         GitURL                       string              `json:"gitUrl"`
311         Schemas                      map[string]Schema   `json:"schemas"`
312         Resources                    map[string]Resource `json:"resources"`
313 }
314
315 type Resource struct {
316         Methods map[string]ResourceMethod `json:"methods"`
317 }
318
319 type ResourceMethod struct {
320         HTTPMethod string         `json:"httpMethod"`
321         Path       string         `json:"path"`
322         Response   MethodResponse `json:"response"`
323 }
324
325 type MethodResponse struct {
326         Ref string `json:"$ref"`
327 }
328
329 type Schema struct {
330         UUIDPrefix string `json:"uuidPrefix"`
331 }
332
333 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
334 // should not be modified: the same object may be returned by
335 // subsequent calls.
336 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
337         if c.dd != nil {
338                 return c.dd, nil
339         }
340         var dd DiscoveryDocument
341         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
342         if err != nil {
343                 return nil, err
344         }
345         c.dd = &dd
346         return c.dd, nil
347 }
348
349 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
350
351 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
352         if pdhRegexp.MatchString(uuid) {
353                 return "Collection", nil
354         }
355         if len(uuid) != 27 {
356                 return "", fmt.Errorf("invalid UUID: %q", uuid)
357         }
358         infix := uuid[6:11]
359         var model string
360         for m, s := range dd.Schemas {
361                 if s.UUIDPrefix == infix {
362                         model = m
363                         break
364                 }
365         }
366         if model == "" {
367                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
368         }
369         return model, nil
370 }
371
372 func (c *Client) KindForUUID(uuid string) (string, error) {
373         dd, err := c.DiscoveryDocument()
374         if err != nil {
375                 return "", err
376         }
377         model, err := c.modelForUUID(dd, uuid)
378         if err != nil {
379                 return "", err
380         }
381         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
382 }
383
384 func (c *Client) PathForUUID(method, uuid string) (string, error) {
385         dd, err := c.DiscoveryDocument()
386         if err != nil {
387                 return "", err
388         }
389         model, err := c.modelForUUID(dd, uuid)
390         if err != nil {
391                 return "", err
392         }
393         var resource string
394         for r, rsc := range dd.Resources {
395                 if rsc.Methods["get"].Response.Ref == model {
396                         resource = r
397                         break
398                 }
399         }
400         if resource == "" {
401                 return "", fmt.Errorf("no resource for model: %q", model)
402         }
403         m, ok := dd.Resources[resource].Methods[method]
404         if !ok {
405                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
406         }
407         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
408         if path[0] == '/' {
409                 path = path[1:]
410         }
411         return path, nil
412 }