1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
24 "git.curoverse.com/arvados.git/sdk/go/httpserver"
27 // A Client is an HTTP client with an API endpoint and a set of
28 // Arvados credentials.
30 // It offers methods for accessing individual Arvados APIs, and
31 // methods that implement common patterns like fetching multiple pages
32 // of results using List APIs.
34 // HTTP client used to make requests. If nil,
35 // DefaultSecureClient or InsecureHTTPClient will be used.
36 Client *http.Client `json:"-"`
38 // Hostname (or host:port) of Arvados API server.
41 // User authentication token.
44 // Accept unverified certificates. This works only if the
45 // Client field is nil: otherwise, it has no effect.
48 // Override keep service discovery with a list of base
49 // URIs. (Currently there are no Client methods for
50 // discovering keep services so this is just a convenience for
51 // callers who use a Client to initialize an
52 // arvadosclient.ArvadosClient.)
53 KeepServiceURIs []string `json:",omitempty"`
60 // The default http.Client used by a Client with Insecure==true and
62 var InsecureHTTPClient = &http.Client{
63 Transport: &http.Transport{
64 TLSClientConfig: &tls.Config{
65 InsecureSkipVerify: true}},
66 Timeout: 5 * time.Minute}
68 // The default http.Client used by a Client otherwise.
69 var DefaultSecureClient = &http.Client{
70 Timeout: 5 * time.Minute}
72 // NewClientFromConfig creates a new Client that uses the endpoints in
75 // AuthToken is left empty for the caller to populate.
76 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
77 ctrlURL := cluster.Services.Controller.ExternalURL
78 if ctrlURL.Host == "" {
79 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
82 APIHost: ctrlURL.Host,
83 Insecure: cluster.TLS.Insecure,
87 // NewClientFromEnv creates a new Client that uses the default HTTP
88 // client with the API endpoint and credentials given by the
89 // ARVADOS_API_* environment variables.
90 func NewClientFromEnv() *Client {
92 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
95 } else if u, err := url.Parse(s); err != nil {
96 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
97 } else if !u.IsAbs() {
98 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
100 svcs = append(svcs, s)
104 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
108 APIHost: os.Getenv("ARVADOS_API_HOST"),
109 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
111 KeepServiceURIs: svcs,
115 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
117 // Do adds Authorization and X-Request-Id headers and then calls
118 // (*http.Client)Do().
119 func (c *Client) Do(req *http.Request) (*http.Response, error) {
120 if c.AuthToken != "" {
121 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
124 if req.Header.Get("X-Request-Id") == "" {
125 reqid, _ := c.context().Value(contextKeyRequestID).(string)
127 reqid = reqIDGen.Next()
129 if req.Header == nil {
130 req.Header = http.Header{"X-Request-Id": {reqid}}
132 req.Header.Set("X-Request-Id", reqid)
135 return c.httpClient().Do(req)
138 // DoAndDecode performs req and unmarshals the response (which must be
139 // JSON) into dst. Use this instead of RequestAndDecode if you need
140 // more control of the http.Request object.
141 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
142 resp, err := c.Do(req)
146 defer resp.Body.Close()
147 buf, err := ioutil.ReadAll(resp.Body)
151 if resp.StatusCode != 200 {
152 return newTransactionError(req, resp, buf)
157 return json.Unmarshal(buf, dst)
160 // Convert an arbitrary struct to url.Values. For example,
162 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
166 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
168 // params itself is returned if it is already an url.Values.
169 func anythingToValues(params interface{}) (url.Values, error) {
170 if v, ok := params.(url.Values); ok {
173 // TODO: Do this more efficiently, possibly using
174 // json.Decode/Encode, so the whole thing doesn't have to get
175 // encoded, decoded, and re-encoded.
176 j, err := json.Marshal(params)
180 var generic map[string]interface{}
181 err = json.Unmarshal(j, &generic)
185 urlValues := url.Values{}
186 for k, v := range generic {
187 if v, ok := v.(string); ok {
191 if v, ok := v.(float64); ok {
192 // Unmarshal decodes all numbers as float64,
193 // which can be written as 1.2345e4 in JSON,
194 // but this form is not accepted for ints in
195 // url params. If a number fits in an int64,
196 // encode it as int64 rather than float64.
197 if v, frac := math.Modf(v); frac == 0 && v <= math.MaxInt64 && v >= math.MinInt64 {
198 urlValues.Set(k, fmt.Sprintf("%d", int64(v)))
202 j, err := json.Marshal(v)
206 urlValues.Set(k, string(j))
208 return urlValues, nil
211 // RequestAndDecode performs an API request and unmarshals the
212 // response (which must be JSON) into dst. Method and body arguments
213 // are the same as for http.NewRequest(). The given path is added to
214 // the server's scheme/host/port to form the request URL. The given
215 // params are passed via POST form or query string.
217 // path must not contain a query string.
218 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
219 if body, ok := body.(io.Closer); ok {
220 // Ensure body is closed even if we error out early
223 urlString := c.apiURL(path)
224 urlValues, err := anythingToValues(params)
228 if urlValues == nil {
230 } else if method == "GET" || method == "HEAD" || body != nil {
231 // Must send params in query part of URL (FIXME: what
232 // if resulting URL is too long?)
233 u, err := url.Parse(urlString)
237 u.RawQuery = urlValues.Encode()
238 urlString = u.String()
240 body = strings.NewReader(urlValues.Encode())
242 req, err := http.NewRequest(method, urlString, body)
246 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
247 return c.DoAndDecode(dst, req)
250 type resource interface {
251 resourceName() string
254 // UpdateBody returns an io.Reader suitable for use as an http.Request
255 // Body for a create or update API call.
256 func (c *Client) UpdateBody(rsc resource) io.Reader {
257 j, err := json.Marshal(rsc)
259 // Return a reader that returns errors.
261 w.CloseWithError(err)
264 v := url.Values{rsc.resourceName(): {string(j)}}
265 return bytes.NewBufferString(v.Encode())
268 type contextKey string
270 var contextKeyRequestID contextKey = "X-Request-Id"
272 func (c *Client) WithRequestID(reqid string) *Client {
274 cc.ctx = context.WithValue(cc.context(), contextKeyRequestID, reqid)
278 func (c *Client) context() context.Context {
280 return context.Background()
285 func (c *Client) httpClient() *http.Client {
287 case c.Client != nil:
290 return InsecureHTTPClient
292 return DefaultSecureClient
296 func (c *Client) apiURL(path string) string {
297 return "https://" + c.APIHost + "/" + path
300 // DiscoveryDocument is the Arvados server's description of itself.
301 type DiscoveryDocument struct {
302 BasePath string `json:"basePath"`
303 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
304 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
305 GitURL string `json:"gitUrl"`
306 Schemas map[string]Schema `json:"schemas"`
307 Resources map[string]Resource `json:"resources"`
310 type Resource struct {
311 Methods map[string]ResourceMethod `json:"methods"`
314 type ResourceMethod struct {
315 HTTPMethod string `json:"httpMethod"`
316 Path string `json:"path"`
317 Response MethodResponse `json:"response"`
320 type MethodResponse struct {
321 Ref string `json:"$ref"`
325 UUIDPrefix string `json:"uuidPrefix"`
328 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
329 // should not be modified: the same object may be returned by
331 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
335 var dd DiscoveryDocument
336 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
344 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
346 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
347 if pdhRegexp.MatchString(uuid) {
348 return "Collection", nil
351 return "", fmt.Errorf("invalid UUID: %q", uuid)
355 for m, s := range dd.Schemas {
356 if s.UUIDPrefix == infix {
362 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
367 func (c *Client) KindForUUID(uuid string) (string, error) {
368 dd, err := c.DiscoveryDocument()
372 model, err := c.modelForUUID(dd, uuid)
376 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
379 func (c *Client) PathForUUID(method, uuid string) (string, error) {
380 dd, err := c.DiscoveryDocument()
384 model, err := c.modelForUUID(dd, uuid)
389 for r, rsc := range dd.Resources {
390 if rsc.Methods["get"].Response.Ref == model {
396 return "", fmt.Errorf("no resource for model: %q", model)
398 m, ok := dd.Resources[resource].Methods[method]
400 return "", fmt.Errorf("no method %q for resource %q", method, resource)
402 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)