19 // A Client is an HTTP client with an API endpoint and a set of
20 // Arvados credentials.
22 // It offers methods for accessing individual Arvados APIs, and
23 // methods that implement common patterns like fetching multiple pages
24 // of results using List APIs.
26 // HTTP client used to make requests. If nil,
27 // DefaultSecureClient or InsecureHTTPClient will be used.
28 Client *http.Client `json:"-"`
30 // Hostname (or host:port) of Arvados API server.
33 // User authentication token.
36 // Accept unverified certificates. This works only if the
37 // Client field is nil: otherwise, it has no effect.
40 // Override keep service discovery with a list of base
41 // URIs. (Currently there are no Client methods for
42 // discovering keep services so this is just a convenience for
43 // callers who use a Client to initialize an
44 // arvadosclient.ArvadosClient.)
45 KeepServiceURIs []string `json:",omitempty"`
50 // The default http.Client used by a Client with Insecure==true and
52 var InsecureHTTPClient = &http.Client{
53 Transport: &http.Transport{
54 TLSClientConfig: &tls.Config{
55 InsecureSkipVerify: true}},
56 Timeout: 5 * time.Minute}
58 // The default http.Client used by a Client otherwise.
59 var DefaultSecureClient = &http.Client{
60 Timeout: 5 * time.Minute}
62 // NewClientFromEnv creates a new Client that uses the default HTTP
63 // client with the API endpoint and credentials given by the
64 // ARVADOS_API_* environment variables.
65 func NewClientFromEnv() *Client {
67 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
70 } else if u, err := url.Parse(s); err != nil {
71 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
72 } else if !u.IsAbs() {
73 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
75 svcs = append(svcs, s)
79 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
83 APIHost: os.Getenv("ARVADOS_API_HOST"),
84 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
86 KeepServiceURIs: svcs,
90 // Do adds authentication headers and then calls (*http.Client)Do().
91 func (c *Client) Do(req *http.Request) (*http.Response, error) {
92 if c.AuthToken != "" {
93 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
95 return c.httpClient().Do(req)
98 // DoAndDecode performs req and unmarshals the response (which must be
99 // JSON) into dst. Use this instead of RequestAndDecode if you need
100 // more control of the http.Request object.
101 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
102 resp, err := c.Do(req)
106 defer resp.Body.Close()
107 buf, err := ioutil.ReadAll(resp.Body)
111 if resp.StatusCode != 200 {
112 return newTransactionError(req, resp, buf)
117 return json.Unmarshal(buf, dst)
120 // Convert an arbitrary struct to url.Values. For example,
122 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
126 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
128 // params itself is returned if it is already an url.Values.
129 func anythingToValues(params interface{}) (url.Values, error) {
130 if v, ok := params.(url.Values); ok {
133 // TODO: Do this more efficiently, possibly using
134 // json.Decode/Encode, so the whole thing doesn't have to get
135 // encoded, decoded, and re-encoded.
136 j, err := json.Marshal(params)
140 var generic map[string]interface{}
141 err = json.Unmarshal(j, &generic)
145 urlValues := url.Values{}
146 for k, v := range generic {
147 if v, ok := v.(string); ok {
151 if v, ok := v.(float64); ok {
152 // Unmarshal decodes all numbers as float64,
153 // which can be written as 1.2345e4 in JSON,
154 // but this form is not accepted for ints in
155 // url params. If a number fits in an int64,
156 // encode it as int64 rather than float64.
157 if v, frac := math.Modf(v); frac == 0 && v <= math.MaxInt64 && v >= math.MinInt64 {
158 urlValues.Set(k, fmt.Sprintf("%d", int64(v)))
162 j, err := json.Marshal(v)
166 urlValues.Set(k, string(j))
168 return urlValues, nil
171 // RequestAndDecode performs an API request and unmarshals the
172 // response (which must be JSON) into dst. Method and body arguments
173 // are the same as for http.NewRequest(). The given path is added to
174 // the server's scheme/host/port to form the request URL. The given
175 // params are passed via POST form or query string.
177 // path must not contain a query string.
178 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
179 urlString := c.apiURL(path)
180 urlValues, err := anythingToValues(params)
184 if (method == "GET" || body != nil) && urlValues != nil {
185 // FIXME: what if params don't fit in URL
186 u, err := url.Parse(urlString)
190 u.RawQuery = urlValues.Encode()
191 urlString = u.String()
193 req, err := http.NewRequest(method, urlString, body)
197 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
198 return c.DoAndDecode(dst, req)
201 func (c *Client) httpClient() *http.Client {
203 case c.Client != nil:
206 return InsecureHTTPClient
208 return DefaultSecureClient
212 func (c *Client) apiURL(path string) string {
213 return "https://" + c.APIHost + "/" + path
216 // DiscoveryDocument is the Arvados server's description of itself.
217 type DiscoveryDocument struct {
218 BasePath string `json:"basePath"`
219 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
220 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
221 Schemas map[string]Schema `json:"schemas"`
222 Resources map[string]Resource `json:"resources"`
225 type Resource struct {
226 Methods map[string]ResourceMethod `json:"methods"`
229 type ResourceMethod struct {
230 HTTPMethod string `json:"httpMethod"`
231 Path string `json:"path"`
232 Response MethodResponse `json:"response"`
235 type MethodResponse struct {
236 Ref string `json:"$ref"`
240 UUIDPrefix string `json:"uuidPrefix"`
243 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
244 // should not be modified: the same object may be returned by
246 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
250 var dd DiscoveryDocument
251 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
259 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
261 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
262 if pdhRegexp.MatchString(uuid) {
263 return "Collection", nil
266 return "", fmt.Errorf("invalid UUID: %q", uuid)
270 for m, s := range dd.Schemas {
271 if s.UUIDPrefix == infix {
277 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
282 func (c *Client) KindForUUID(uuid string) (string, error) {
283 dd, err := c.DiscoveryDocument()
287 model, err := c.modelForUUID(dd, uuid)
291 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
294 func (c *Client) PathForUUID(method, uuid string) (string, error) {
295 dd, err := c.DiscoveryDocument()
299 model, err := c.modelForUUID(dd, uuid)
304 for r, rsc := range dd.Resources {
305 if rsc.Methods["get"].Response.Ref == model {
311 return "", fmt.Errorf("no resource for model: %q", model)
313 m, ok := dd.Resources[resource].Methods[method]
315 return "", fmt.Errorf("no method %q for resource %q", method, resource)
317 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)