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