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.curoverse.com/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 // Indicates 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",
81 // StringBool tests whether s is suggestive of true. It returns true
82 // if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
83 func StringBool(s string) bool {
84 s = strings.ToLower(s)
85 return s == "1" || s == "yes" || s == "true"
88 // Helper type so we don't have to write out 'map[string]interface{}' every time.
89 type Dict map[string]interface{}
91 // Information about how to contact the Arvados server
92 type ArvadosClient struct {
96 // Arvados API server, form "host:port"
99 // Arvados API token for authentication
102 // Whether to require a valid SSL certificate or not
105 // Client object shared by client requests. Supports HTTP KeepAlive.
108 // If true, sets the X-External-Client header to indicate
109 // the client is outside the cluster.
112 // Base URIs of Keep services, e.g., {"https://host1:8443",
113 // "https://host2:8443"}. If this is nil, Keep clients will
114 // use the arvados.v1.keep_services.accessible API to discover
115 // available services.
116 KeepServiceURIs []string
118 // Discovery document
121 lastClosedIdlesAt time.Time
126 // X-Request-Id for outgoing requests
130 var CertFiles = []string{
131 "/etc/arvados/ca-certificates.crt",
132 "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
133 "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL
136 // MakeTLSConfig sets up TLS configuration for communicating with
137 // Arvados and Keep services.
138 func MakeTLSConfig(insecure bool) *tls.Config {
139 tlsconfig := tls.Config{InsecureSkipVerify: insecure}
142 // Use the first entry in CertFiles that we can read
143 // certificates from. If none of those work out, use
145 certs := x509.NewCertPool()
146 for _, file := range CertFiles {
147 data, err := ioutil.ReadFile(file)
149 if !os.IsNotExist(err) {
150 log.Printf("error reading %q: %s", file, err)
154 if !certs.AppendCertsFromPEM(data) {
155 log.Printf("unable to load any certificates from %v", file)
158 tlsconfig.RootCAs = certs
166 // New returns an ArvadosClient using the given arvados.Client
167 // configuration. This is useful for callers who load arvados.Client
168 // fields from configuration files but still need to use the
169 // arvadosclient.ArvadosClient package.
170 func New(c *arvados.Client) (*ArvadosClient, error) {
171 ac := &ArvadosClient{
173 ApiServer: c.APIHost,
174 ApiToken: c.AuthToken,
175 ApiInsecure: c.Insecure,
176 Client: &http.Client{Transport: &http.Transport{
177 TLSClientConfig: MakeTLSConfig(c.Insecure)}},
180 KeepServiceURIs: c.KeepServiceURIs,
181 lastClosedIdlesAt: time.Now(),
187 // MakeArvadosClient creates a new ArvadosClient using the standard
188 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
189 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
190 // ARVADOS_KEEP_SERVICES.
191 func MakeArvadosClient() (ac *ArvadosClient, err error) {
192 ac, err = New(arvados.NewClientFromEnv())
196 ac.External = StringBool(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
200 // CallRaw is the same as Call() but returns a Reader that reads the
201 // response body, instead of taking an output object.
202 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
211 if resourceType != API_DISCOVERY_RESOURCE {
212 u.Path = "/arvados/v1"
215 if resourceType != "" {
216 u.Path = u.Path + "/" + resourceType
219 u.Path = u.Path + "/" + uuid
222 u.Path = u.Path + "/" + action
225 if parameters == nil {
226 parameters = make(Dict)
229 vals := make(url.Values)
230 for k, v := range parameters {
231 if s, ok := v.(string); ok {
233 } else if m, err := json.Marshal(v); err == nil {
234 vals.Set(k, string(m))
240 case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
244 // Non-retryable methods such as POST are not safe to retry automatically,
245 // so we minimize such failures by always using a new or recently active socket
247 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
248 c.lastClosedIdlesAt = time.Now()
249 c.Client.Transport.(*http.Transport).CloseIdleConnections()
254 var req *http.Request
255 var resp *http.Response
257 for attempt := 0; attempt <= c.Retries; attempt++ {
258 if method == "GET" || method == "HEAD" {
259 u.RawQuery = vals.Encode()
260 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
264 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
267 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
270 // Add api token header
271 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
272 if c.RequestID != "" {
273 req.Header.Add("X-Request-Id", c.RequestID)
276 req.Header.Add("X-External-Client", "1")
279 resp, err = c.Client.Do(req)
282 time.Sleep(RetryDelay)
289 if resp.StatusCode == http.StatusOK {
290 return resp.Body, nil
293 defer resp.Body.Close()
295 switch resp.StatusCode {
296 case 408, 409, 422, 423, 500, 502, 503, 504:
297 time.Sleep(RetryDelay)
300 return nil, newAPIServerError(c.ApiServer, resp)
305 return nil, newAPIServerError(c.ApiServer, resp)
310 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
312 ase := APIServerError{
313 ServerAddress: ServerAddress,
314 HttpStatusCode: resp.StatusCode,
315 HttpStatusMessage: resp.Status}
317 // If the response body has {"errors":["reason1","reason2"]}
318 // then return those reasons.
320 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
321 if errorList, ok := errInfo["errors"]; ok {
322 if errArray, ok := errorList.([]interface{}); ok {
323 for _, errItem := range errArray {
324 // We expect an array of strings here.
325 // Non-strings will be passed along
327 if s, ok := errItem.(string); ok {
328 ase.ErrorDetails = append(ase.ErrorDetails, s)
329 } else if j, err := json.Marshal(errItem); err == nil {
330 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
339 // Call an API endpoint and parse the JSON response into an object.
341 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
342 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
343 // uuid - the uuid of the specific item to access. May be empty.
344 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
345 // parameters - method parameters.
346 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
348 // Returns a non-nil error if an error occurs making the API call, the
349 // API responds with a non-successful HTTP status, or an error occurs
350 // parsing the response body.
351 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
352 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
361 dec := json.NewDecoder(reader)
362 if err = dec.Decode(output); err != nil {
369 // Create a new resource. See Call for argument descriptions.
370 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
371 return c.Call("POST", resourceType, "", "", parameters, output)
374 // Delete a resource. See Call for argument descriptions.
375 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
376 return c.Call("DELETE", resource, uuid, "", parameters, output)
379 // Modify attributes of a resource. See Call for argument descriptions.
380 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
381 return c.Call("PUT", resourceType, uuid, "", parameters, output)
384 // Get a resource. See Call for argument descriptions.
385 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
386 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
387 // No object has uuid == "": there is no need to make
388 // an API call. Furthermore, the HTTP request for such
389 // an API call would be "GET /arvados/v1/type/", which
390 // is liable to be misinterpreted as the List API.
391 return ErrInvalidArgument
393 return c.Call("GET", resourceType, uuid, "", parameters, output)
396 // List resources of a given type. See Call for argument descriptions.
397 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
398 return c.Call("GET", resource, "", "", parameters, output)
401 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
403 // Discovery returns the value of the given parameter in the discovery
404 // document. Returns a non-nil error if the discovery document cannot
405 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
406 // parameter is not found in the discovery document.
407 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
408 if len(c.DiscoveryDoc) == 0 {
409 c.DiscoveryDoc = make(Dict)
410 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
417 value, found = c.DiscoveryDoc[parameter]
421 return value, ErrInvalidArgument
425 func (ac *ArvadosClient) httpClient() *http.Client {
426 if ac.Client != nil {
429 c := &defaultSecureHTTPClient
431 c = &defaultInsecureHTTPClient
434 defaultHTTPClientMtx.Lock()
435 defer defaultHTTPClientMtx.Unlock()
436 *c = &http.Client{Transport: &http.Transport{
437 TLSClientConfig: MakeTLSConfig(ac.ApiInsecure)}}