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