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