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