14325: Merge branch 'master'
[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 // RequestAndDecode performs an API request and unmarshals the
197 // response (which must be JSON) into dst. Method and body arguments
198 // are the same as for http.NewRequest(). The given path is added to
199 // the server's scheme/host/port to form the request URL. The given
200 // params are passed via POST form or query string.
201 //
202 // path must not contain a query string.
203 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
204         if body, ok := body.(io.Closer); ok {
205                 // Ensure body is closed even if we error out early
206                 defer body.Close()
207         }
208         urlString := c.apiURL(path)
209         urlValues, err := anythingToValues(params)
210         if err != nil {
211                 return err
212         }
213         if urlValues == nil {
214                 // Nothing to send
215         } else if method == "GET" || method == "HEAD" || body != nil {
216                 // Must send params in query part of URL (FIXME: what
217                 // if resulting URL is too long?)
218                 u, err := url.Parse(urlString)
219                 if err != nil {
220                         return err
221                 }
222                 u.RawQuery = urlValues.Encode()
223                 urlString = u.String()
224         } else {
225                 body = strings.NewReader(urlValues.Encode())
226         }
227         req, err := http.NewRequest(method, urlString, body)
228         if err != nil {
229                 return err
230         }
231         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
232         return c.DoAndDecode(dst, req)
233 }
234
235 type resource interface {
236         resourceName() string
237 }
238
239 // UpdateBody returns an io.Reader suitable for use as an http.Request
240 // Body for a create or update API call.
241 func (c *Client) UpdateBody(rsc resource) io.Reader {
242         j, err := json.Marshal(rsc)
243         if err != nil {
244                 // Return a reader that returns errors.
245                 r, w := io.Pipe()
246                 w.CloseWithError(err)
247                 return r
248         }
249         v := url.Values{rsc.resourceName(): {string(j)}}
250         return bytes.NewBufferString(v.Encode())
251 }
252
253 type contextKey string
254
255 var contextKeyRequestID contextKey = "X-Request-Id"
256
257 func (c *Client) WithRequestID(reqid string) *Client {
258         cc := *c
259         cc.ctx = context.WithValue(cc.context(), contextKeyRequestID, reqid)
260         return &cc
261 }
262
263 func (c *Client) context() context.Context {
264         if c.ctx == nil {
265                 return context.Background()
266         }
267         return c.ctx
268 }
269
270 func (c *Client) httpClient() *http.Client {
271         switch {
272         case c.Client != nil:
273                 return c.Client
274         case c.Insecure:
275                 return InsecureHTTPClient
276         default:
277                 return DefaultSecureClient
278         }
279 }
280
281 func (c *Client) apiURL(path string) string {
282         return "https://" + c.APIHost + "/" + path
283 }
284
285 // DiscoveryDocument is the Arvados server's description of itself.
286 type DiscoveryDocument struct {
287         BasePath                     string              `json:"basePath"`
288         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
289         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
290         GitURL                       string              `json:"gitUrl"`
291         Schemas                      map[string]Schema   `json:"schemas"`
292         Resources                    map[string]Resource `json:"resources"`
293 }
294
295 type Resource struct {
296         Methods map[string]ResourceMethod `json:"methods"`
297 }
298
299 type ResourceMethod struct {
300         HTTPMethod string         `json:"httpMethod"`
301         Path       string         `json:"path"`
302         Response   MethodResponse `json:"response"`
303 }
304
305 type MethodResponse struct {
306         Ref string `json:"$ref"`
307 }
308
309 type Schema struct {
310         UUIDPrefix string `json:"uuidPrefix"`
311 }
312
313 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
314 // should not be modified: the same object may be returned by
315 // subsequent calls.
316 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
317         if c.dd != nil {
318                 return c.dd, nil
319         }
320         var dd DiscoveryDocument
321         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
322         if err != nil {
323                 return nil, err
324         }
325         c.dd = &dd
326         return c.dd, nil
327 }
328
329 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
330
331 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
332         if pdhRegexp.MatchString(uuid) {
333                 return "Collection", nil
334         }
335         if len(uuid) != 27 {
336                 return "", fmt.Errorf("invalid UUID: %q", uuid)
337         }
338         infix := uuid[6:11]
339         var model string
340         for m, s := range dd.Schemas {
341                 if s.UUIDPrefix == infix {
342                         model = m
343                         break
344                 }
345         }
346         if model == "" {
347                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
348         }
349         return model, nil
350 }
351
352 func (c *Client) KindForUUID(uuid string) (string, error) {
353         dd, err := c.DiscoveryDocument()
354         if err != nil {
355                 return "", err
356         }
357         model, err := c.modelForUUID(dd, uuid)
358         if err != nil {
359                 return "", err
360         }
361         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
362 }
363
364 func (c *Client) PathForUUID(method, uuid string) (string, error) {
365         dd, err := c.DiscoveryDocument()
366         if err != nil {
367                 return "", err
368         }
369         model, err := c.modelForUUID(dd, uuid)
370         if err != nil {
371                 return "", err
372         }
373         var resource string
374         for r, rsc := range dd.Resources {
375                 if rsc.Methods["get"].Response.Ref == model {
376                         resource = r
377                         break
378                 }
379         }
380         if resource == "" {
381                 return "", fmt.Errorf("no resource for model: %q", model)
382         }
383         m, ok := dd.Resources[resource].Methods[method]
384         if !ok {
385                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
386         }
387         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
388         if path[0] == '/' {
389                 path = path[1:]
390         }
391         return path, nil
392 }