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 // 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",
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 // Helper type so we don't have to write out 'map[string]interface{}' every time.
88 type Dict map[string]interface{}
90 // 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) {
213 if resourceType != API_DISCOVERY_RESOURCE {
214 u.Path = "/arvados/v1"
217 if resourceType != "" {
218 u.Path = u.Path + "/" + resourceType
221 u.Path = u.Path + "/" + uuid
224 u.Path = u.Path + "/" + action
227 if parameters == nil {
228 parameters = make(Dict)
231 vals := make(url.Values)
232 for k, v := range parameters {
233 if s, ok := v.(string); ok {
235 } else if m, err := json.Marshal(v); err == nil {
236 vals.Set(k, string(m))
242 case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
246 // Non-retryable methods such as POST are not safe to retry automatically,
247 // so we minimize such failures by always using a new or recently active socket
249 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
250 c.lastClosedIdlesAt = time.Now()
251 c.Client.Transport.(*http.Transport).CloseIdleConnections()
256 var req *http.Request
257 var resp *http.Response
259 for attempt := 0; attempt <= c.Retries; attempt++ {
260 if method == "GET" || method == "HEAD" {
261 u.RawQuery = vals.Encode()
262 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
266 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
269 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
272 // Add api token header
273 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
274 if c.RequestID != "" {
275 req.Header.Add("X-Request-Id", c.RequestID)
278 req.Header.Add("X-External-Client", "1")
281 resp, err = c.Client.Do(req)
284 time.Sleep(RetryDelay)
291 if resp.StatusCode == http.StatusOK {
292 return resp.Body, nil
295 defer resp.Body.Close()
297 switch resp.StatusCode {
298 case 408, 409, 422, 423, 500, 502, 503, 504:
299 time.Sleep(RetryDelay)
302 return nil, newAPIServerError(c.ApiServer, resp)
307 return nil, newAPIServerError(c.ApiServer, resp)
312 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
314 ase := APIServerError{
315 ServerAddress: ServerAddress,
316 HttpStatusCode: resp.StatusCode,
317 HttpStatusMessage: resp.Status}
319 // If the response body has {"errors":["reason1","reason2"]}
320 // then return those reasons.
322 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
323 if errorList, ok := errInfo["errors"]; ok {
324 if errArray, ok := errorList.([]interface{}); ok {
325 for _, errItem := range errArray {
326 // We expect an array of strings here.
327 // Non-strings will be passed along
329 if s, ok := errItem.(string); ok {
330 ase.ErrorDetails = append(ase.ErrorDetails, s)
331 } else if j, err := json.Marshal(errItem); err == nil {
332 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
341 // Call an API endpoint and parse the JSON response into an object.
343 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
344 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
345 // uuid - the uuid of the specific item to access. May be empty.
346 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
347 // parameters - method parameters.
348 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
350 // Returns a non-nil error if an error occurs making the API call, the
351 // API responds with a non-successful HTTP status, or an error occurs
352 // parsing the response body.
353 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
354 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
363 dec := json.NewDecoder(reader)
364 if err = dec.Decode(output); err != nil {
371 // Create a new resource. See Call for argument descriptions.
372 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
373 return c.Call("POST", resourceType, "", "", parameters, output)
376 // Delete a resource. See Call for argument descriptions.
377 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
378 return c.Call("DELETE", resource, uuid, "", parameters, output)
381 // Modify attributes of a resource. See Call for argument descriptions.
382 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
383 return c.Call("PUT", resourceType, uuid, "", parameters, output)
386 // Get a resource. See Call for argument descriptions.
387 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
388 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
389 // No object has uuid == "": there is no need to make
390 // an API call. Furthermore, the HTTP request for such
391 // an API call would be "GET /arvados/v1/type/", which
392 // is liable to be misinterpreted as the List API.
393 return ErrInvalidArgument
395 return c.Call("GET", resourceType, uuid, "", parameters, output)
398 // List resources of a given type. See Call for argument descriptions.
399 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
400 return c.Call("GET", resource, "", "", parameters, output)
403 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
405 // Discovery returns the value of the given parameter in the discovery
406 // document. Returns a non-nil error if the discovery document cannot
407 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
408 // parameter is not found in the discovery document.
409 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
410 if len(c.DiscoveryDoc) == 0 {
411 c.DiscoveryDoc = make(Dict)
412 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
419 value, found = c.DiscoveryDoc[parameter]
423 return value, ErrInvalidArgument
426 func (ac *ArvadosClient) httpClient() *http.Client {
427 if ac.Client != nil {
430 c := &defaultSecureHTTPClient
432 c = &defaultInsecureHTTPClient
435 defaultHTTPClientMtx.Lock()
436 defer defaultHTTPClientMtx.Unlock()
437 *c = &http.Client{Transport: &http.Transport{
438 TLSClientConfig: MakeTLSConfig(ac.ApiInsecure)}}