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