1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 /* Simple Arvados Go SDK for communicating with API server. */
26 "git.arvados.org/arvados.git/sdk/go/arvados"
29 type StringMatcher func(string) bool
31 var UUIDMatch StringMatcher = arvados.UUIDMatch
32 var PDHMatch StringMatcher = arvados.PDHMatch
34 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
35 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
36 var ErrInvalidArgument = errors.New("Invalid argument")
38 // A common failure mode is to reuse a keepalive connection that has been
39 // terminated (in a way that we can't detect) for being idle too long.
40 // POST and DELETE are not safe to retry automatically, so we minimize
41 // such failures by always using a new or recently active socket.
42 var MaxIdleConnectionDuration = 30 * time.Second
44 var RetryDelay = 2 * time.Second
47 defaultInsecureHTTPClient *http.Client
48 defaultSecureHTTPClient *http.Client
49 defaultHTTPClientMtx sync.Mutex
52 // APIServerError contains an error that was returned by the API server.
53 type APIServerError struct {
54 // Address of server returning error, of the form "host:port".
57 // Components of server response.
59 HttpStatusMessage string
61 // Additional error details from response body.
65 func (e APIServerError) Error() string {
66 if len(e.ErrorDetails) > 0 {
67 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
68 strings.Join(e.ErrorDetails, "; "),
73 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
79 // StringBool tests whether s is suggestive of true. It returns true
80 // if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
81 func StringBool(s string) bool {
82 s = strings.ToLower(s)
83 return s == "1" || s == "yes" || s == "true"
86 // Dict is a helper type so we don't have to write out 'map[string]interface{}' every time.
87 type Dict map[string]interface{}
89 // ArvadosClient contains information about how to contact the Arvados server
90 type ArvadosClient struct {
94 // Arvados API server, form "host:port"
97 // Arvados API token for authentication
100 // Whether to require a valid SSL certificate or not
103 // Client object shared by client requests. Supports HTTP KeepAlive.
106 // If true, sets the X-External-Client header to indicate
107 // the client is outside the cluster.
110 // Base URIs of Keep services, e.g., {"https://host1:8443",
111 // "https://host2:8443"}. If this is nil, Keep clients will
112 // use the arvados.v1.keep_services.accessible API to discover
113 // available services.
114 KeepServiceURIs []string
116 // Discovery document
119 lastClosedIdlesAt time.Time
124 // X-Request-Id for outgoing requests
128 var CertFiles = []string{
129 "/etc/arvados/ca-certificates.crt",
130 "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
131 "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL
134 // MakeTLSConfig sets up TLS configuration for communicating with
135 // Arvados and Keep services.
136 func MakeTLSConfig(insecure bool) *tls.Config {
137 tlsconfig := tls.Config{InsecureSkipVerify: insecure}
140 // Use the first entry in CertFiles that we can read
141 // certificates from. If none of those work out, use
143 certs := x509.NewCertPool()
144 for _, file := range CertFiles {
145 data, err := ioutil.ReadFile(file)
147 if !os.IsNotExist(err) {
148 log.Printf("proceeding without loading cert file %q: %s", file, err)
152 if !certs.AppendCertsFromPEM(data) {
153 log.Printf("unable to load any certificates from %v", file)
156 tlsconfig.RootCAs = certs
164 // New returns an ArvadosClient using the given arvados.Client
165 // configuration. This is useful for callers who load arvados.Client
166 // fields from configuration files but still need to use the
167 // arvadosclient.ArvadosClient package.
168 func New(c *arvados.Client) (*ArvadosClient, error) {
169 ac := &ArvadosClient{
171 ApiServer: c.APIHost,
172 ApiToken: c.AuthToken,
173 ApiInsecure: c.Insecure,
174 Client: &http.Client{
175 Timeout: 5 * time.Minute,
176 Transport: &http.Transport{
177 TLSClientConfig: MakeTLSConfig(c.Insecure)},
181 KeepServiceURIs: c.KeepServiceURIs,
182 lastClosedIdlesAt: time.Now(),
188 // MakeArvadosClient creates a new ArvadosClient using the standard
189 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
190 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
191 // ARVADOS_KEEP_SERVICES.
192 func MakeArvadosClient() (ac *ArvadosClient, err error) {
193 ac, err = New(arvados.NewClientFromEnv())
197 ac.External = StringBool(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
201 // CallRaw is the same as Call() but returns a Reader that reads the
202 // response body, instead of taking an output object.
203 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
208 if c.ApiServer == "" {
209 return nil, fmt.Errorf("Arvados client is not configured (target API host is not set). Maybe env var ARVADOS_API_HOST should be set first?")
215 if resourceType != ApiDiscoveryResource {
216 u.Path = "/arvados/v1"
219 if resourceType != "" {
220 u.Path = u.Path + "/" + resourceType
223 u.Path = u.Path + "/" + uuid
226 u.Path = u.Path + "/" + action
229 if parameters == nil {
230 parameters = make(Dict)
233 vals := make(url.Values)
234 for k, v := range parameters {
235 if s, ok := v.(string); ok {
237 } else if m, err := json.Marshal(v); err == nil {
238 vals.Set(k, string(m))
244 case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
248 // Non-retryable methods such as POST are not safe to retry automatically,
249 // so we minimize such failures by always using a new or recently active socket
251 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
252 c.lastClosedIdlesAt = time.Now()
253 c.Client.Transport.(*http.Transport).CloseIdleConnections()
258 var req *http.Request
259 var resp *http.Response
261 for attempt := 0; attempt <= c.Retries; attempt++ {
262 if method == "GET" || method == "HEAD" {
263 u.RawQuery = vals.Encode()
264 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
268 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
271 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
274 // Add api token header
275 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
276 if c.RequestID != "" {
277 req.Header.Add("X-Request-Id", c.RequestID)
280 req.Header.Add("X-External-Client", "1")
283 resp, err = c.Client.Do(req)
286 time.Sleep(RetryDelay)
293 if resp.StatusCode == http.StatusOK {
294 return resp.Body, nil
297 defer resp.Body.Close()
299 switch resp.StatusCode {
300 case 408, 409, 422, 423, 500, 502, 503, 504:
301 time.Sleep(RetryDelay)
304 return nil, newAPIServerError(c.ApiServer, resp)
309 return nil, newAPIServerError(c.ApiServer, resp)
314 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
316 ase := APIServerError{
317 ServerAddress: ServerAddress,
318 HttpStatusCode: resp.StatusCode,
319 HttpStatusMessage: resp.Status}
321 // If the response body has {"errors":["reason1","reason2"]}
322 // then return those reasons.
324 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
325 if errorList, ok := errInfo["errors"]; ok {
326 if errArray, ok := errorList.([]interface{}); ok {
327 for _, errItem := range errArray {
328 // We expect an array of strings here.
329 // Non-strings will be passed along
331 if s, ok := errItem.(string); ok {
332 ase.ErrorDetails = append(ase.ErrorDetails, s)
333 } else if j, err := json.Marshal(errItem); err == nil {
334 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
343 // Call an API endpoint and parse the JSON response into an object.
345 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
346 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
347 // uuid - the uuid of the specific item to access. May be empty.
348 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
349 // parameters - method parameters.
350 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
352 // Returns a non-nil error if an error occurs making the API call, the
353 // API responds with a non-successful HTTP status, or an error occurs
354 // parsing the response body.
355 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
356 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
365 dec := json.NewDecoder(reader)
366 if err = dec.Decode(output); err != nil {
373 // Create a new resource. See Call for argument descriptions.
374 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
375 return c.Call("POST", resourceType, "", "", parameters, output)
378 // Delete a resource. See Call for argument descriptions.
379 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
380 return c.Call("DELETE", resource, uuid, "", parameters, output)
383 // Update attributes of a resource. See Call for argument descriptions.
384 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
385 return c.Call("PUT", resourceType, uuid, "", parameters, output)
388 // Get a resource. See Call for argument descriptions.
389 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
390 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
391 // No object has uuid == "": there is no need to make
392 // an API call. Furthermore, the HTTP request for such
393 // an API call would be "GET /arvados/v1/type/", which
394 // is liable to be misinterpreted as the List API.
395 return ErrInvalidArgument
397 return c.Call("GET", resourceType, uuid, "", parameters, output)
400 // List resources of a given type. See Call for argument descriptions.
401 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
402 return c.Call("GET", resource, "", "", parameters, output)
405 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
407 // Discovery returns the value of the given parameter in the discovery
408 // document. Returns a non-nil error if the discovery document cannot
409 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
410 // parameter is not found in the discovery document.
411 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
412 if len(c.DiscoveryDoc) == 0 {
413 c.DiscoveryDoc = make(Dict)
414 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
421 value, found = c.DiscoveryDoc[parameter]
425 return value, ErrInvalidArgument
428 // ClusterConfig returns the value of the given key in the current cluster's
429 // exported config. If key is an empty string, it'll return the entire config.
430 func (c *ArvadosClient) ClusterConfig(key string) (config interface{}, err error) {
431 var clusterConfig interface{}
432 err = c.Call("GET", "config", "", "", nil, &clusterConfig)
437 return clusterConfig, nil
439 configData, ok := clusterConfig.(map[string]interface{})[key]
441 return nil, ErrInvalidArgument
443 return configData, nil
446 func (c *ArvadosClient) httpClient() *http.Client {
450 cl := &defaultSecureHTTPClient
452 cl = &defaultInsecureHTTPClient
455 defaultHTTPClientMtx.Lock()
456 defer defaultHTTPClientMtx.Unlock()
457 *cl = &http.Client{Transport: &http.Transport{
458 TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}