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