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) {
172 Timeout: 5 * time.Minute,
173 Transport: &http.Transport{
174 TLSClientConfig: MakeTLSConfig(c.Insecure)},
177 ac := &ArvadosClient{
179 ApiServer: c.APIHost,
180 ApiToken: c.AuthToken,
181 ApiInsecure: c.Insecure,
185 KeepServiceURIs: c.KeepServiceURIs,
186 lastClosedIdlesAt: time.Now(),
192 // MakeArvadosClient creates a new ArvadosClient using the standard
193 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
194 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
195 // ARVADOS_KEEP_SERVICES.
196 func MakeArvadosClient() (ac *ArvadosClient, err error) {
197 ac, err = New(arvados.NewClientFromEnv())
201 ac.External = StringBool(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
205 // CallRaw is the same as Call() but returns a Reader that reads the
206 // response body, instead of taking an output object.
207 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
212 if c.ApiServer == "" {
213 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?")
219 if resourceType != ApiDiscoveryResource {
220 u.Path = "/arvados/v1"
223 if resourceType != "" {
224 u.Path = u.Path + "/" + resourceType
227 u.Path = u.Path + "/" + uuid
230 u.Path = u.Path + "/" + action
233 if parameters == nil {
234 parameters = make(Dict)
237 vals := make(url.Values)
238 for k, v := range parameters {
239 if s, ok := v.(string); ok {
241 } else if m, err := json.Marshal(v); err == nil {
242 vals.Set(k, string(m))
248 case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
252 // Non-retryable methods such as POST are not safe to retry automatically,
253 // so we minimize such failures by always using a new or recently active socket
255 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
256 c.lastClosedIdlesAt = time.Now()
257 c.Client.Transport.(*http.Transport).CloseIdleConnections()
262 var req *http.Request
263 var resp *http.Response
265 for attempt := 0; attempt <= c.Retries; attempt++ {
266 if method == "GET" || method == "HEAD" {
267 u.RawQuery = vals.Encode()
268 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
272 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
275 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
278 // Add api token header
279 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
280 if c.RequestID != "" {
281 req.Header.Add("X-Request-Id", c.RequestID)
284 req.Header.Add("X-External-Client", "1")
287 resp, err = c.Client.Do(req)
290 time.Sleep(RetryDelay)
297 if resp.StatusCode == http.StatusOK {
298 return resp.Body, nil
301 defer resp.Body.Close()
303 switch resp.StatusCode {
304 case 408, 409, 422, 423, 500, 502, 503, 504:
305 time.Sleep(RetryDelay)
308 return nil, newAPIServerError(c.ApiServer, resp)
313 return nil, newAPIServerError(c.ApiServer, resp)
318 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
320 ase := APIServerError{
321 ServerAddress: ServerAddress,
322 HttpStatusCode: resp.StatusCode,
323 HttpStatusMessage: resp.Status}
325 // If the response body has {"errors":["reason1","reason2"]}
326 // then return those reasons.
328 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
329 if errorList, ok := errInfo["errors"]; ok {
330 if errArray, ok := errorList.([]interface{}); ok {
331 for _, errItem := range errArray {
332 // We expect an array of strings here.
333 // Non-strings will be passed along
335 if s, ok := errItem.(string); ok {
336 ase.ErrorDetails = append(ase.ErrorDetails, s)
337 } else if j, err := json.Marshal(errItem); err == nil {
338 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
347 // Call an API endpoint and parse the JSON response into an object.
349 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
350 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
351 // uuid - the uuid of the specific item to access. May be empty.
352 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
353 // parameters - method parameters.
354 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
356 // Returns a non-nil error if an error occurs making the API call, the
357 // API responds with a non-successful HTTP status, or an error occurs
358 // parsing the response body.
359 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
360 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
369 dec := json.NewDecoder(reader)
370 if err = dec.Decode(output); err != nil {
377 // Create a new resource. See Call for argument descriptions.
378 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
379 return c.Call("POST", resourceType, "", "", parameters, output)
382 // Delete a resource. See Call for argument descriptions.
383 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
384 return c.Call("DELETE", resource, uuid, "", parameters, output)
387 // Update attributes of a resource. See Call for argument descriptions.
388 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
389 return c.Call("PUT", resourceType, uuid, "", parameters, output)
392 // Get a resource. See Call for argument descriptions.
393 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
394 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
395 // No object has uuid == "": there is no need to make
396 // an API call. Furthermore, the HTTP request for such
397 // an API call would be "GET /arvados/v1/type/", which
398 // is liable to be misinterpreted as the List API.
399 return ErrInvalidArgument
401 return c.Call("GET", resourceType, uuid, "", parameters, output)
404 // List resources of a given type. See Call for argument descriptions.
405 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
406 return c.Call("GET", resource, "", "", parameters, output)
409 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
411 // Discovery returns the value of the given parameter in the discovery
412 // document. Returns a non-nil error if the discovery document cannot
413 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
414 // parameter is not found in the discovery document.
415 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
416 if len(c.DiscoveryDoc) == 0 {
417 c.DiscoveryDoc = make(Dict)
418 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
425 value, found = c.DiscoveryDoc[parameter]
429 return value, ErrInvalidArgument
432 // ClusterConfig returns the value of the given key in the current cluster's
433 // exported config. If key is an empty string, it'll return the entire config.
434 func (c *ArvadosClient) ClusterConfig(key string) (config interface{}, err error) {
435 var clusterConfig interface{}
436 err = c.Call("GET", "config", "", "", nil, &clusterConfig)
441 return clusterConfig, nil
443 configData, ok := clusterConfig.(map[string]interface{})[key]
445 return nil, ErrInvalidArgument
447 return configData, nil
450 func (c *ArvadosClient) httpClient() *http.Client {
454 cl := &defaultSecureHTTPClient
456 cl = &defaultInsecureHTTPClient
459 defaultHTTPClientMtx.Lock()
460 defer defaultHTTPClientMtx.Unlock()
461 *cl = &http.Client{Transport: &http.Transport{
462 TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}