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 // Base URIs of Keep services, e.g., {"https://host1:8443",
107 // "https://host2:8443"}. If this is nil, Keep clients will
108 // use the arvados.v1.keep_services.accessible API to discover
109 // available services.
110 KeepServiceURIs []string
112 // Discovery document
115 lastClosedIdlesAt time.Time
120 // X-Request-Id for outgoing requests
124 var CertFiles = []string{
125 "/etc/arvados/ca-certificates.crt",
126 "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
127 "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL
130 // MakeTLSConfig sets up TLS configuration for communicating with
131 // Arvados and Keep services.
132 func MakeTLSConfig(insecure bool) *tls.Config {
133 tlsconfig := tls.Config{InsecureSkipVerify: insecure}
136 // Use the first entry in CertFiles that we can read
137 // certificates from. If none of those work out, use
139 certs := x509.NewCertPool()
140 for _, file := range CertFiles {
141 data, err := ioutil.ReadFile(file)
143 if !os.IsNotExist(err) {
144 log.Printf("proceeding without loading cert file %q: %s", file, err)
148 if !certs.AppendCertsFromPEM(data) {
149 log.Printf("unable to load any certificates from %v", file)
152 tlsconfig.RootCAs = certs
160 // New returns an ArvadosClient using the given arvados.Client
161 // configuration. This is useful for callers who load arvados.Client
162 // fields from configuration files but still need to use the
163 // arvadosclient.ArvadosClient package.
164 func New(c *arvados.Client) (*ArvadosClient, error) {
168 Timeout: 5 * time.Minute,
169 Transport: &http.Transport{
170 TLSClientConfig: MakeTLSConfig(c.Insecure)},
173 ac := &ArvadosClient{
175 ApiServer: c.APIHost,
176 ApiToken: c.AuthToken,
177 ApiInsecure: 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, and ARVADOS_KEEP_SERVICES.
190 func MakeArvadosClient() (*ArvadosClient, error) {
191 return New(arvados.NewClientFromEnv())
194 // CallRaw is the same as Call() but returns a Reader that reads the
195 // response body, instead of taking an output object.
196 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
201 if c.ApiServer == "" {
202 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?")
208 if resourceType != ApiDiscoveryResource {
209 u.Path = "/arvados/v1"
212 if resourceType != "" {
213 u.Path = u.Path + "/" + resourceType
216 u.Path = u.Path + "/" + uuid
219 u.Path = u.Path + "/" + action
222 if parameters == nil {
223 parameters = make(Dict)
226 vals := make(url.Values)
227 for k, v := range parameters {
228 if s, ok := v.(string); ok {
230 } else if m, err := json.Marshal(v); err == nil {
231 vals.Set(k, string(m))
234 var req *http.Request
235 if method == "GET" || method == "HEAD" {
236 u.RawQuery = vals.Encode()
237 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
241 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
244 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
246 if c.RequestID != "" {
247 req.Header.Add("X-Request-Id", c.RequestID)
249 client := arvados.Client{
251 APIHost: c.ApiServer,
252 AuthToken: c.ApiToken,
253 Insecure: c.ApiInsecure,
254 Timeout: 30 * RetryDelay * time.Duration(c.Retries),
256 resp, err := client.Do(req)
260 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
261 defer resp.Body.Close()
262 return nil, newAPIServerError(c.ApiServer, resp)
264 return resp.Body, nil
267 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
269 ase := APIServerError{
270 ServerAddress: ServerAddress,
271 HttpStatusCode: resp.StatusCode,
272 HttpStatusMessage: resp.Status}
274 // If the response body has {"errors":["reason1","reason2"]}
275 // then return those reasons.
277 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
278 if errorList, ok := errInfo["errors"]; ok {
279 if errArray, ok := errorList.([]interface{}); ok {
280 for _, errItem := range errArray {
281 // We expect an array of strings here.
282 // Non-strings will be passed along
284 if s, ok := errItem.(string); ok {
285 ase.ErrorDetails = append(ase.ErrorDetails, s)
286 } else if j, err := json.Marshal(errItem); err == nil {
287 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
296 // Call an API endpoint and parse the JSON response into an object.
298 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
299 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
300 // uuid - the uuid of the specific item to access. May be empty.
301 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
302 // parameters - method parameters.
303 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
305 // Returns a non-nil error if an error occurs making the API call, the
306 // API responds with a non-successful HTTP status, or an error occurs
307 // parsing the response body.
308 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
309 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
318 dec := json.NewDecoder(reader)
319 if err = dec.Decode(output); err != nil {
326 // Create a new resource. See Call for argument descriptions.
327 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
328 return c.Call("POST", resourceType, "", "", parameters, output)
331 // Delete a resource. See Call for argument descriptions.
332 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
333 return c.Call("DELETE", resource, uuid, "", parameters, output)
336 // Update attributes of a resource. See Call for argument descriptions.
337 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
338 return c.Call("PUT", resourceType, uuid, "", parameters, output)
341 // Get a resource. See Call for argument descriptions.
342 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
343 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
344 // No object has uuid == "": there is no need to make
345 // an API call. Furthermore, the HTTP request for such
346 // an API call would be "GET /arvados/v1/type/", which
347 // is liable to be misinterpreted as the List API.
348 return ErrInvalidArgument
350 return c.Call("GET", resourceType, uuid, "", parameters, output)
353 // List resources of a given type. See Call for argument descriptions.
354 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
355 return c.Call("GET", resource, "", "", parameters, output)
358 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
360 // Discovery returns the value of the given parameter in the discovery
361 // document. Returns a non-nil error if the discovery document cannot
362 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
363 // parameter is not found in the discovery document.
364 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
365 if len(c.DiscoveryDoc) == 0 {
366 c.DiscoveryDoc = make(Dict)
367 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
374 value, found = c.DiscoveryDoc[parameter]
378 return value, ErrInvalidArgument
381 // ClusterConfig returns the value of the given key in the current cluster's
382 // exported config. If key is an empty string, it'll return the entire config.
383 func (c *ArvadosClient) ClusterConfig(key string) (config interface{}, err error) {
384 var clusterConfig interface{}
385 err = c.Call("GET", "config", "", "", nil, &clusterConfig)
390 return clusterConfig, nil
392 configData, ok := clusterConfig.(map[string]interface{})[key]
394 return nil, ErrInvalidArgument
396 return configData, nil
399 func (c *ArvadosClient) httpClient() *http.Client {
403 cl := &defaultSecureHTTPClient
405 cl = &defaultInsecureHTTPClient
408 defaultHTTPClientMtx.Lock()
409 defer defaultHTTPClientMtx.Unlock()
410 *cl = &http.Client{Transport: &http.Transport{
411 TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}