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. */
22 "git.arvados.org/arvados.git/sdk/go/arvados"
25 type StringMatcher func(string) bool
27 var UUIDMatch StringMatcher = arvados.UUIDMatch
28 var PDHMatch StringMatcher = arvados.PDHMatch
30 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
31 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
32 var ErrInvalidArgument = errors.New("Invalid argument")
34 // A common failure mode is to reuse a keepalive connection that has been
35 // terminated (in a way that we can't detect) for being idle too long.
36 // POST and DELETE are not safe to retry automatically, so we minimize
37 // such failures by always using a new or recently active socket.
38 var MaxIdleConnectionDuration = 30 * time.Second
40 var RetryDelay = 2 * time.Second
43 defaultInsecureHTTPClient *http.Client
44 defaultSecureHTTPClient *http.Client
45 defaultHTTPClientMtx sync.Mutex
48 // APIServerError contains an error that was returned by the API server.
49 type APIServerError struct {
50 // Address of server returning error, of the form "host:port".
53 // Components of server response.
55 HttpStatusMessage string
57 // Additional error details from response body.
61 func (e APIServerError) Error() string {
62 if len(e.ErrorDetails) > 0 {
63 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
64 strings.Join(e.ErrorDetails, "; "),
69 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
75 // StringBool tests whether s is suggestive of true. It returns true
76 // if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
77 func StringBool(s string) bool {
78 s = strings.ToLower(s)
79 return s == "1" || s == "yes" || s == "true"
82 // Dict is a helper type so we don't have to write out 'map[string]interface{}' every time.
83 type Dict map[string]interface{}
85 // ArvadosClient contains information about how to contact the Arvados server
86 type ArvadosClient struct {
90 // Arvados API server, form "host:port"
93 // Arvados API token for authentication
96 // Whether to require a valid SSL certificate or not
99 // Client object shared by client requests. Supports HTTP KeepAlive.
102 // Base URIs of Keep services, e.g., {"https://host1:8443",
103 // "https://host2:8443"}. If this is nil, Keep clients will
104 // use the arvados.v1.keep_services.accessible API to discover
105 // available services.
106 KeepServiceURIs []string
108 // Maximum disk cache size in bytes or percent of total
109 // filesystem size. If zero, use default, currently 10% of
111 DiskCacheSize arvados.ByteSizeOrPercent
113 // Discovery document
116 lastClosedIdlesAt time.Time
121 // X-Request-Id for outgoing requests
125 // MakeTLSConfig sets up TLS configuration for communicating with
126 // Arvados and Keep services.
127 func MakeTLSConfig(insecure bool) *tls.Config {
128 return &tls.Config{InsecureSkipVerify: insecure}
131 // New returns an ArvadosClient using the given arvados.Client
132 // configuration. This is useful for callers who load arvados.Client
133 // fields from configuration files but still need to use the
134 // arvadosclient.ArvadosClient package.
135 func New(c *arvados.Client) (*ArvadosClient, error) {
139 Timeout: 5 * time.Minute,
140 Transport: &http.Transport{
141 TLSClientConfig: MakeTLSConfig(c.Insecure)},
144 ac := &ArvadosClient{
146 ApiServer: c.APIHost,
147 ApiToken: c.AuthToken,
148 ApiInsecure: c.Insecure,
151 KeepServiceURIs: c.KeepServiceURIs,
152 DiskCacheSize: c.DiskCacheSize,
153 lastClosedIdlesAt: time.Now(),
159 // MakeArvadosClient creates a new ArvadosClient using the standard
160 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
161 // ARVADOS_API_HOST_INSECURE, and ARVADOS_KEEP_SERVICES.
162 func MakeArvadosClient() (*ArvadosClient, error) {
163 return New(arvados.NewClientFromEnv())
166 // CallRaw is the same as Call() but returns a Reader that reads the
167 // response body, instead of taking an output object.
168 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
173 if c.ApiServer == "" {
174 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?")
180 if resourceType != ApiDiscoveryResource {
181 u.Path = "/arvados/v1"
184 if resourceType != "" {
185 u.Path = u.Path + "/" + resourceType
188 u.Path = u.Path + "/" + uuid
191 u.Path = u.Path + "/" + action
194 if parameters == nil {
195 parameters = make(Dict)
198 vals := make(url.Values)
199 for k, v := range parameters {
200 if s, ok := v.(string); ok {
202 } else if m, err := json.Marshal(v); err == nil {
203 vals.Set(k, string(m))
206 var req *http.Request
207 if method == "GET" || method == "HEAD" {
208 u.RawQuery = vals.Encode()
209 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
213 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
216 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
218 if c.RequestID != "" {
219 req.Header.Add("X-Request-Id", c.RequestID)
221 client := arvados.Client{
223 APIHost: c.ApiServer,
224 AuthToken: c.ApiToken,
225 Insecure: c.ApiInsecure,
226 Timeout: 30 * RetryDelay * time.Duration(c.Retries),
228 resp, err := client.Do(req)
232 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
233 defer resp.Body.Close()
234 return nil, newAPIServerError(c.ApiServer, resp)
236 return resp.Body, nil
239 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
241 ase := APIServerError{
242 ServerAddress: ServerAddress,
243 HttpStatusCode: resp.StatusCode,
244 HttpStatusMessage: resp.Status}
246 // If the response body has {"errors":["reason1","reason2"]}
247 // then return those reasons.
249 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
250 if errorList, ok := errInfo["errors"]; ok {
251 if errArray, ok := errorList.([]interface{}); ok {
252 for _, errItem := range errArray {
253 // We expect an array of strings here.
254 // Non-strings will be passed along
256 if s, ok := errItem.(string); ok {
257 ase.ErrorDetails = append(ase.ErrorDetails, s)
258 } else if j, err := json.Marshal(errItem); err == nil {
259 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
268 // Call an API endpoint and parse the JSON response into an object.
270 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
271 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
272 // uuid - the uuid of the specific item to access. May be empty.
273 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
274 // parameters - method parameters.
275 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
277 // Returns a non-nil error if an error occurs making the API call, the
278 // API responds with a non-successful HTTP status, or an error occurs
279 // parsing the response body.
280 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
281 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
290 dec := json.NewDecoder(reader)
291 if err = dec.Decode(output); err != nil {
298 // Create a new resource. See Call for argument descriptions.
299 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
300 return c.Call("POST", resourceType, "", "", parameters, output)
303 // Delete a resource. See Call for argument descriptions.
304 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
305 return c.Call("DELETE", resource, uuid, "", parameters, output)
308 // Update attributes of a resource. See Call for argument descriptions.
309 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
310 return c.Call("PUT", resourceType, uuid, "", parameters, output)
313 // Get a resource. See Call for argument descriptions.
314 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
315 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
316 // No object has uuid == "": there is no need to make
317 // an API call. Furthermore, the HTTP request for such
318 // an API call would be "GET /arvados/v1/type/", which
319 // is liable to be misinterpreted as the List API.
320 return ErrInvalidArgument
322 return c.Call("GET", resourceType, uuid, "", parameters, output)
325 // List resources of a given type. See Call for argument descriptions.
326 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
327 return c.Call("GET", resource, "", "", parameters, output)
330 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
332 // Discovery returns the value of the given parameter in the discovery
333 // document. Returns a non-nil error if the discovery document cannot
334 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
335 // parameter is not found in the discovery document.
336 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
337 if len(c.DiscoveryDoc) == 0 {
338 c.DiscoveryDoc = make(Dict)
339 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
346 value, found = c.DiscoveryDoc[parameter]
350 return value, ErrInvalidArgument
353 // ClusterConfig returns the value of the given key in the current cluster's
354 // exported config. If key is an empty string, it'll return the entire config.
355 func (c *ArvadosClient) ClusterConfig(key string) (config interface{}, err error) {
356 var clusterConfig interface{}
357 err = c.Call("GET", "config", "", "", nil, &clusterConfig)
362 return clusterConfig, nil
364 configData, ok := clusterConfig.(map[string]interface{})[key]
366 return nil, ErrInvalidArgument
368 return configData, nil
371 func (c *ArvadosClient) httpClient() *http.Client {
375 cl := &defaultSecureHTTPClient
377 cl = &defaultInsecureHTTPClient
380 defaultHTTPClientMtx.Lock()
381 defer defaultHTTPClientMtx.Unlock()
382 *cl = &http.Client{Transport: &http.Transport{
383 TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}