17 // A Client is an HTTP client with an API endpoint and a set of
18 // Arvados credentials.
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.
24 // HTTP client used to make requests. If nil,
25 // DefaultSecureClient or InsecureHTTPClient will be used.
26 Client *http.Client `json:"-"`
28 // Hostname (or host:port) of Arvados API server.
31 // User authentication token.
34 // Accept unverified certificates. This works only if the
35 // Client field is nil: otherwise, it has no effect.
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"`
48 // The default http.Client used by a Client with Insecure==true and
50 var InsecureHTTPClient = &http.Client{
51 Transport: &http.Transport{
52 TLSClientConfig: &tls.Config{
53 InsecureSkipVerify: true}},
54 Timeout: 5 * time.Minute}
56 // The default http.Client used by a Client otherwise.
57 var DefaultSecureClient = &http.Client{
58 Timeout: 5 * time.Minute}
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 {
65 if s := os.Getenv("ARVADOS_KEEP_SERVICES"); s != "" {
66 svcs = strings.Split(s, " ")
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,
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)
81 return c.httpClient().Do(req)
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)
92 defer resp.Body.Close()
93 buf, err := ioutil.ReadAll(resp.Body)
97 if resp.StatusCode != 200 {
98 return newTransactionError(req, resp, buf)
103 return json.Unmarshal(buf, dst)
106 // Convert an arbitrary struct to url.Values. For example,
108 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
112 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
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 {
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)
126 var generic map[string]interface{}
127 err = json.Unmarshal(j, &generic)
131 urlValues := url.Values{}
132 for k, v := range generic {
133 if v, ok := v.(string); ok {
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)))
148 j, err := json.Marshal(v)
152 urlValues.Set(k, string(j))
154 return urlValues, nil
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.
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)
170 if (method == "GET" || body != nil) && urlValues != nil {
171 // FIXME: what if params don't fit in URL
172 u, err := url.Parse(urlString)
176 u.RawQuery = urlValues.Encode()
177 urlString = u.String()
179 req, err := http.NewRequest(method, urlString, body)
183 return c.DoAndDecode(dst, req)
186 func (c *Client) httpClient() *http.Client {
188 case c.Client != nil:
191 return InsecureHTTPClient
193 return DefaultSecureClient
197 func (c *Client) apiURL(path string) string {
198 return "https://" + c.APIHost + "/" + path
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"`
210 type Resource struct {
211 Methods map[string]ResourceMethod `json:"methods"`
214 type ResourceMethod struct {
215 HTTPMethod string `json:"httpMethod"`
216 Path string `json:"path"`
217 Response MethodResponse `json:"response"`
220 type MethodResponse struct {
221 Ref string `json:"$ref"`
225 UUIDPrefix string `json:"uuidPrefix"`
228 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
229 // should not be modified: the same object may be returned by
231 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
235 var dd DiscoveryDocument
236 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
244 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
246 return "", fmt.Errorf("invalid UUID: %q", uuid)
250 for m, s := range dd.Schemas {
251 if s.UUIDPrefix == infix {
257 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
262 func (c *Client) KindForUUID(uuid string) (string, error) {
263 dd, err := c.DiscoveryDocument()
267 model, err := c.modelForUUID(dd, uuid)
271 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
274 func (c *Client) PathForUUID(method, uuid string) (string, error) {
275 dd, err := c.DiscoveryDocument()
279 model, err := c.modelForUUID(dd, uuid)
284 for r, rsc := range dd.Resources {
285 if rsc.Methods["get"].Response.Ref == model {
291 return "", fmt.Errorf("no resource for model: %q", model)
293 m, ok := dd.Resources[resource].Methods[method]
295 return "", fmt.Errorf("no method %q for resource %q", method, resource)
297 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)