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. */
27 "git.arvados.org/arvados.git/sdk/go/arvados"
30 type StringMatcher func(string) bool
32 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
33 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
35 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
36 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
37 var ErrInvalidArgument = errors.New("Invalid argument")
39 // A common failure mode is to reuse a keepalive connection that has been
40 // terminated (in a way that we can't detect) for being idle too long.
41 // POST and DELETE are not safe to retry automatically, so we minimize
42 // such failures by always using a new or recently active socket.
43 var MaxIdleConnectionDuration = 30 * time.Second
45 var RetryDelay = 2 * time.Second
48 defaultInsecureHTTPClient *http.Client
49 defaultSecureHTTPClient *http.Client
50 defaultHTTPClientMtx sync.Mutex
53 // APIServerError contains an error that was returned by the API server.
54 type APIServerError struct {
55 // Address of server returning error, of the form "host:port".
58 // Components of server response.
60 HttpStatusMessage string
62 // Additional error details from response body.
66 func (e APIServerError) Error() string {
67 if len(e.ErrorDetails) > 0 {
68 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
69 strings.Join(e.ErrorDetails, "; "),
74 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
80 // StringBool tests whether s is suggestive of true. It returns true
81 // if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
82 func StringBool(s string) bool {
83 s = strings.ToLower(s)
84 return s == "1" || s == "yes" || s == "true"
87 // Dict is a helper type so we don't have to write out 'map[string]interface{}' every time.
88 type Dict map[string]interface{}
90 // ArvadosClient contains information about how to contact the Arvados server
91 type ArvadosClient struct {
95 // Arvados API server, form "host:port"
98 // Arvados API token for authentication
101 // Whether to require a valid SSL certificate or not
104 // Client object shared by client requests. Supports HTTP KeepAlive.
107 // If true, sets the X-External-Client header to indicate
108 // the client is outside the cluster.
111 // Base URIs of Keep services, e.g., {"https://host1:8443",
112 // "https://host2:8443"}. If this is nil, Keep clients will
113 // use the arvados.v1.keep_services.accessible API to discover
114 // available services.
115 KeepServiceURIs []string
117 // Discovery document
120 lastClosedIdlesAt time.Time
125 // X-Request-Id for outgoing requests
129 var CertFiles = []string{
130 "/etc/arvados/ca-certificates.crt",
131 "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
132 "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL
135 // MakeTLSConfig sets up TLS configuration for communicating with
136 // Arvados and Keep services.
137 func MakeTLSConfig(insecure bool) *tls.Config {
138 tlsconfig := tls.Config{InsecureSkipVerify: insecure}
141 // Use the first entry in CertFiles that we can read
142 // certificates from. If none of those work out, use
144 certs := x509.NewCertPool()
145 for _, file := range CertFiles {
146 data, err := ioutil.ReadFile(file)
148 if !os.IsNotExist(err) {
149 log.Printf("error reading %q: %s", file, err)
153 if !certs.AppendCertsFromPEM(data) {
154 log.Printf("unable to load any certificates from %v", file)
157 tlsconfig.RootCAs = certs
165 // New returns an ArvadosClient using the given arvados.Client
166 // configuration. This is useful for callers who load arvados.Client
167 // fields from configuration files but still need to use the
168 // arvadosclient.ArvadosClient package.
169 func New(c *arvados.Client) (*ArvadosClient, error) {
170 ac := &ArvadosClient{
172 ApiServer: c.APIHost,
173 ApiToken: c.AuthToken,
174 ApiInsecure: c.Insecure,
175 Client: &http.Client{
176 Timeout: 5 * time.Minute,
177 Transport: &http.Transport{
178 TLSClientConfig: MakeTLSConfig(c.Insecure)},
182 KeepServiceURIs: c.KeepServiceURIs,
183 lastClosedIdlesAt: time.Now(),
189 // MakeArvadosClient creates a new ArvadosClient using the standard
190 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
191 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
192 // ARVADOS_KEEP_SERVICES.
193 func MakeArvadosClient() (ac *ArvadosClient, err error) {
194 ac, err = New(arvados.NewClientFromEnv())
198 ac.External = StringBool(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
202 // CallRaw is the same as Call() but returns a Reader that reads the
203 // response body, instead of taking an output object.
204 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
209 if c.ApiServer == "" {
210 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?")
216 if resourceType != ApiDiscoveryResource {
217 u.Path = "/arvados/v1"
220 if resourceType != "" {
221 u.Path = u.Path + "/" + resourceType
224 u.Path = u.Path + "/" + uuid
227 u.Path = u.Path + "/" + action
230 if parameters == nil {
231 parameters = make(Dict)
234 vals := make(url.Values)
235 for k, v := range parameters {
236 if s, ok := v.(string); ok {
238 } else if m, err := json.Marshal(v); err == nil {
239 vals.Set(k, string(m))
245 case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
249 // Non-retryable methods such as POST are not safe to retry automatically,
250 // so we minimize such failures by always using a new or recently active socket
252 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
253 c.lastClosedIdlesAt = time.Now()
254 c.Client.Transport.(*http.Transport).CloseIdleConnections()
259 var req *http.Request
260 var resp *http.Response
262 for attempt := 0; attempt <= c.Retries; attempt++ {
263 if method == "GET" || method == "HEAD" {
264 u.RawQuery = vals.Encode()
265 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
269 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
272 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
275 // Add api token header
276 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
277 if c.RequestID != "" {
278 req.Header.Add("X-Request-Id", c.RequestID)
281 req.Header.Add("X-External-Client", "1")
284 resp, err = c.Client.Do(req)
287 time.Sleep(RetryDelay)
294 if resp.StatusCode == http.StatusOK {
295 return resp.Body, nil
298 defer resp.Body.Close()
300 switch resp.StatusCode {
301 case 408, 409, 422, 423, 500, 502, 503, 504:
302 time.Sleep(RetryDelay)
305 return nil, newAPIServerError(c.ApiServer, resp)
310 return nil, newAPIServerError(c.ApiServer, resp)
315 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
317 ase := APIServerError{
318 ServerAddress: ServerAddress,
319 HttpStatusCode: resp.StatusCode,
320 HttpStatusMessage: resp.Status}
322 // If the response body has {"errors":["reason1","reason2"]}
323 // then return those reasons.
325 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
326 if errorList, ok := errInfo["errors"]; ok {
327 if errArray, ok := errorList.([]interface{}); ok {
328 for _, errItem := range errArray {
329 // We expect an array of strings here.
330 // Non-strings will be passed along
332 if s, ok := errItem.(string); ok {
333 ase.ErrorDetails = append(ase.ErrorDetails, s)
334 } else if j, err := json.Marshal(errItem); err == nil {
335 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
344 // Call an API endpoint and parse the JSON response into an object.
346 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
347 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
348 // uuid - the uuid of the specific item to access. May be empty.
349 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
350 // parameters - method parameters.
351 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
353 // Returns a non-nil error if an error occurs making the API call, the
354 // API responds with a non-successful HTTP status, or an error occurs
355 // parsing the response body.
356 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
357 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
366 dec := json.NewDecoder(reader)
367 if err = dec.Decode(output); err != nil {
374 // Create a new resource. See Call for argument descriptions.
375 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
376 return c.Call("POST", resourceType, "", "", parameters, output)
379 // Delete a resource. See Call for argument descriptions.
380 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
381 return c.Call("DELETE", resource, uuid, "", parameters, output)
384 // Update attributes of a resource. See Call for argument descriptions.
385 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
386 return c.Call("PUT", resourceType, uuid, "", parameters, output)
389 // Get a resource. See Call for argument descriptions.
390 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
391 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
392 // No object has uuid == "": there is no need to make
393 // an API call. Furthermore, the HTTP request for such
394 // an API call would be "GET /arvados/v1/type/", which
395 // is liable to be misinterpreted as the List API.
396 return ErrInvalidArgument
398 return c.Call("GET", resourceType, uuid, "", parameters, output)
401 // List resources of a given type. See Call for argument descriptions.
402 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
403 return c.Call("GET", resource, "", "", parameters, output)
406 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
408 // Discovery returns the value of the given parameter in the discovery
409 // document. Returns a non-nil error if the discovery document cannot
410 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
411 // parameter is not found in the discovery document.
412 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
413 if len(c.DiscoveryDoc) == 0 {
414 c.DiscoveryDoc = make(Dict)
415 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
422 value, found = c.DiscoveryDoc[parameter]
426 return value, ErrInvalidArgument
429 func (c *ArvadosClient) httpClient() *http.Client {
433 cl := &defaultSecureHTTPClient
435 cl = &defaultInsecureHTTPClient
438 defaultHTTPClientMtx.Lock()
439 defer defaultHTTPClientMtx.Unlock()
440 *cl = &http.Client{Transport: &http.Transport{
441 TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}