1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
23 "git.curoverse.com/arvados.git/sdk/go/httpserver"
26 // A Client is an HTTP client with an API endpoint and a set of
27 // Arvados credentials.
29 // It offers methods for accessing individual Arvados APIs, and
30 // methods that implement common patterns like fetching multiple pages
31 // of results using List APIs.
33 // HTTP client used to make requests. If nil,
34 // DefaultSecureClient or InsecureHTTPClient will be used.
35 Client *http.Client `json:"-"`
37 // Protocol scheme: "http", "https", or "" (https)
40 // Hostname (or host:port) of Arvados API server.
43 // User authentication token.
46 // Accept unverified certificates. This works only if the
47 // Client field is nil: otherwise, it has no effect.
50 // Override keep service discovery with a list of base
51 // URIs. (Currently there are no Client methods for
52 // discovering keep services so this is just a convenience for
53 // callers who use a Client to initialize an
54 // arvadosclient.ArvadosClient.)
55 KeepServiceURIs []string `json:",omitempty"`
62 // The default http.Client used by a Client with Insecure==true and
64 var InsecureHTTPClient = &http.Client{
65 Transport: &http.Transport{
66 TLSClientConfig: &tls.Config{
67 InsecureSkipVerify: true}},
68 Timeout: 5 * time.Minute}
70 // The default http.Client used by a Client otherwise.
71 var DefaultSecureClient = &http.Client{
72 Timeout: 5 * time.Minute}
74 // NewClientFromConfig creates a new Client that uses the endpoints in
77 // AuthToken is left empty for the caller to populate.
78 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
79 ctrlURL := cluster.Services.Controller.ExternalURL
80 if ctrlURL.Host == "" {
81 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
84 Scheme: ctrlURL.Scheme,
85 APIHost: ctrlURL.Host,
86 Insecure: cluster.TLS.Insecure,
90 // NewClientFromEnv creates a new Client that uses the default HTTP
91 // client with the API endpoint and credentials given by the
92 // ARVADOS_API_* environment variables.
93 func NewClientFromEnv() *Client {
95 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
98 } else if u, err := url.Parse(s); err != nil {
99 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
100 } else if !u.IsAbs() {
101 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
103 svcs = append(svcs, s)
107 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
112 APIHost: os.Getenv("ARVADOS_API_HOST"),
113 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
115 KeepServiceURIs: svcs,
119 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
121 // Do adds Authorization and X-Request-Id headers and then calls
122 // (*http.Client)Do().
123 func (c *Client) Do(req *http.Request) (*http.Response, error) {
124 if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
125 req.Header.Add("Authorization", auth)
126 } else if c.AuthToken != "" {
127 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
130 if req.Header.Get("X-Request-Id") == "" {
131 reqid, _ := req.Context().Value(contextKeyRequestID{}).(string)
133 reqid, _ = c.context().Value(contextKeyRequestID{}).(string)
136 reqid = reqIDGen.Next()
138 if req.Header == nil {
139 req.Header = http.Header{"X-Request-Id": {reqid}}
141 req.Header.Set("X-Request-Id", reqid)
144 return c.httpClient().Do(req)
147 // DoAndDecode performs req and unmarshals the response (which must be
148 // JSON) into dst. Use this instead of RequestAndDecode if you need
149 // more control of the http.Request object.
150 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
151 resp, err := c.Do(req)
155 defer resp.Body.Close()
156 buf, err := ioutil.ReadAll(resp.Body)
160 if resp.StatusCode != 200 {
161 return newTransactionError(req, resp, buf)
166 return json.Unmarshal(buf, dst)
169 // Convert an arbitrary struct to url.Values. For example,
171 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
175 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
177 // params itself is returned if it is already an url.Values.
178 func anythingToValues(params interface{}) (url.Values, error) {
179 if v, ok := params.(url.Values); ok {
182 // TODO: Do this more efficiently, possibly using
183 // json.Decode/Encode, so the whole thing doesn't have to get
184 // encoded, decoded, and re-encoded.
185 j, err := json.Marshal(params)
189 var generic map[string]interface{}
190 dec := json.NewDecoder(bytes.NewBuffer(j))
192 err = dec.Decode(&generic)
196 urlValues := url.Values{}
197 for k, v := range generic {
198 if v, ok := v.(string); ok {
202 if v, ok := v.(json.Number); ok {
203 urlValues.Set(k, v.String())
206 if v, ok := v.(bool); ok {
208 urlValues.Set(k, "true")
210 // "foo=false", "foo=0", and "foo="
211 // are all taken as true strings, so
212 // don't send false values at all --
213 // rely on the default being false.
217 j, err := json.Marshal(v)
221 if bytes.Equal(j, []byte("null")) {
222 // don't add it to urlValues at all
225 urlValues.Set(k, string(j))
227 return urlValues, nil
230 // RequestAndDecode performs an API request and unmarshals the
231 // response (which must be JSON) into dst. Method and body arguments
232 // are the same as for http.NewRequest(). The given path is added to
233 // the server's scheme/host/port to form the request URL. The given
234 // params are passed via POST form or query string.
236 // path must not contain a query string.
237 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
238 return c.RequestAndDecodeContext(c.context(), dst, method, path, body, params)
241 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
242 if body, ok := body.(io.Closer); ok {
243 // Ensure body is closed even if we error out early
246 urlString := c.apiURL(path)
247 urlValues, err := anythingToValues(params)
251 if urlValues == nil {
253 } else if method == "GET" || method == "HEAD" || body != nil {
254 // Must send params in query part of URL (FIXME: what
255 // if resulting URL is too long?)
256 u, err := url.Parse(urlString)
260 u.RawQuery = urlValues.Encode()
261 urlString = u.String()
263 body = strings.NewReader(urlValues.Encode())
265 req, err := http.NewRequest(method, urlString, body)
269 req = req.WithContext(ctx)
270 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
271 return c.DoAndDecode(dst, req)
274 type resource interface {
275 resourceName() string
278 // UpdateBody returns an io.Reader suitable for use as an http.Request
279 // Body for a create or update API call.
280 func (c *Client) UpdateBody(rsc resource) io.Reader {
281 j, err := json.Marshal(rsc)
283 // Return a reader that returns errors.
285 w.CloseWithError(err)
288 v := url.Values{rsc.resourceName(): {string(j)}}
289 return bytes.NewBufferString(v.Encode())
292 // WithRequestID returns a new shallow copy of c that sends the given
293 // X-Request-Id value (instead of a new randomly generated one) with
294 // each subsequent request that doesn't provide its own via context or
296 func (c *Client) WithRequestID(reqid string) *Client {
298 cc.ctx = ContextWithRequestID(cc.context(), reqid)
302 func (c *Client) context() context.Context {
304 return context.Background()
309 func (c *Client) httpClient() *http.Client {
311 case c.Client != nil:
314 return InsecureHTTPClient
316 return DefaultSecureClient
320 func (c *Client) apiURL(path string) string {
325 return scheme + "://" + c.APIHost + "/" + path
328 // DiscoveryDocument is the Arvados server's description of itself.
329 type DiscoveryDocument struct {
330 BasePath string `json:"basePath"`
331 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
332 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
333 GitURL string `json:"gitUrl"`
334 Schemas map[string]Schema `json:"schemas"`
335 Resources map[string]Resource `json:"resources"`
338 type Resource struct {
339 Methods map[string]ResourceMethod `json:"methods"`
342 type ResourceMethod struct {
343 HTTPMethod string `json:"httpMethod"`
344 Path string `json:"path"`
345 Response MethodResponse `json:"response"`
348 type MethodResponse struct {
349 Ref string `json:"$ref"`
353 UUIDPrefix string `json:"uuidPrefix"`
356 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
357 // should not be modified: the same object may be returned by
359 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
363 var dd DiscoveryDocument
364 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
372 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
374 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
375 if pdhRegexp.MatchString(uuid) {
376 return "Collection", nil
379 return "", fmt.Errorf("invalid UUID: %q", uuid)
383 for m, s := range dd.Schemas {
384 if s.UUIDPrefix == infix {
390 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
395 func (c *Client) KindForUUID(uuid string) (string, error) {
396 dd, err := c.DiscoveryDocument()
400 model, err := c.modelForUUID(dd, uuid)
404 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
407 func (c *Client) PathForUUID(method, uuid string) (string, error) {
408 dd, err := c.DiscoveryDocument()
412 model, err := c.modelForUUID(dd, uuid)
417 for r, rsc := range dd.Resources {
418 if rsc.Methods["get"].Response.Ref == model {
424 return "", fmt.Errorf("no resource for model: %q", model)
426 m, ok := dd.Resources[resource].Methods[method]
428 return "", fmt.Errorf("no method %q for resource %q", method, resource)
430 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)