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