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"
23 "github.com/sirupsen/logrus"
26 type StringMatcher func(string) bool
28 var UUIDMatch StringMatcher = arvados.UUIDMatch
29 var PDHMatch StringMatcher = arvados.PDHMatch
31 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
32 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
33 var ErrInvalidArgument = errors.New("Invalid argument")
35 // A common failure mode is to reuse a keepalive connection that has been
36 // terminated (in a way that we can't detect) for being idle too long.
37 // POST and DELETE are not safe to retry automatically, so we minimize
38 // such failures by always using a new or recently active socket.
39 var MaxIdleConnectionDuration = 30 * time.Second
41 var RetryDelay = 2 * time.Second
44 defaultInsecureHTTPClient *http.Client
45 defaultSecureHTTPClient *http.Client
46 defaultHTTPClientMtx sync.Mutex
49 // APIServerError contains an error that was returned by the API server.
50 type APIServerError struct {
51 // Address of server returning error, of the form "host:port".
54 // Components of server response.
56 HttpStatusMessage string
58 // Additional error details from response body.
62 func (e APIServerError) Error() string {
63 if len(e.ErrorDetails) > 0 {
64 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
65 strings.Join(e.ErrorDetails, "; "),
70 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
76 // StringBool tests whether s is suggestive of true. It returns true
77 // if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
78 func StringBool(s string) bool {
79 s = strings.ToLower(s)
80 return s == "1" || s == "yes" || s == "true"
83 // Dict is a helper type so we don't have to write out 'map[string]interface{}' every time.
84 type Dict map[string]interface{}
86 // ArvadosClient contains information about how to contact the Arvados server
87 type ArvadosClient struct {
91 // Arvados API server, form "host:port"
94 // Arvados API token for authentication
97 // Whether to require a valid SSL certificate or not
100 // Client object shared by client requests. Supports HTTP KeepAlive.
103 // Base URIs of Keep services, e.g., {"https://host1:8443",
104 // "https://host2:8443"}. If this is nil, Keep clients will
105 // use the arvados.v1.keep_services.accessible API to discover
106 // available services.
107 KeepServiceURIs []string
109 // Maximum disk cache size in bytes or percent of total
110 // filesystem size. If zero, use default, currently 10% of
112 DiskCacheSize arvados.ByteSizeOrPercent
114 // Where to write debug logs. May be nil.
115 Logger logrus.FieldLogger
117 // Discovery document
120 lastClosedIdlesAt time.Time
125 // X-Request-Id for outgoing requests
128 // Cluster config from the arvados.Client passed to New(), if
129 // any. If non-nil, its keep services configuration is used
130 // instead of requesting a server list from controller. Note
131 // this is disabled by default in test suites via
132 // ARVADOS_FORCE_KEEP_SERVICES_TABLE environment variable.
133 Cluster *arvados.Cluster
136 // MakeTLSConfig sets up TLS configuration for communicating with
137 // Arvados and Keep services.
138 func MakeTLSConfig(insecure bool) *tls.Config {
139 return &tls.Config{InsecureSkipVerify: insecure}
142 // New returns an ArvadosClient using the given arvados.Client
143 // configuration. This is useful for callers who load arvados.Client
144 // fields from configuration files but still need to use the
145 // arvadosclient.ArvadosClient package.
146 func New(c *arvados.Client) (*ArvadosClient, error) {
150 Timeout: 5 * time.Minute,
151 Transport: &http.Transport{
152 TLSClientConfig: MakeTLSConfig(c.Insecure)},
155 ac := &ArvadosClient{
157 ApiServer: c.APIHost,
158 ApiToken: c.AuthToken,
159 ApiInsecure: c.Insecure,
162 KeepServiceURIs: c.KeepServiceURIs,
163 DiskCacheSize: c.DiskCacheSize,
165 lastClosedIdlesAt: time.Now(),
172 // MakeArvadosClient creates a new ArvadosClient using the standard
173 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
174 // ARVADOS_API_HOST_INSECURE, and ARVADOS_KEEP_SERVICES.
175 func MakeArvadosClient() (*ArvadosClient, error) {
176 return New(arvados.NewClientFromEnv())
179 // CallRaw is the same as Call() but returns a Reader that reads the
180 // response body, instead of taking an output object.
181 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
186 if c.ApiServer == "" {
187 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?")
193 if resourceType != ApiDiscoveryResource {
194 u.Path = "/arvados/v1"
197 if resourceType != "" {
198 u.Path = u.Path + "/" + resourceType
201 u.Path = u.Path + "/" + uuid
204 u.Path = u.Path + "/" + action
207 if parameters == nil {
208 parameters = make(Dict)
211 vals := make(url.Values)
212 for k, v := range parameters {
213 if s, ok := v.(string); ok {
215 } else if m, err := json.Marshal(v); err == nil {
216 vals.Set(k, string(m))
219 var req *http.Request
220 if method == "GET" || method == "HEAD" {
221 u.RawQuery = vals.Encode()
222 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
226 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
229 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
231 if c.RequestID != "" {
232 req.Header.Add("X-Request-Id", c.RequestID)
234 client := arvados.Client{
236 APIHost: c.ApiServer,
237 AuthToken: c.ApiToken,
238 Insecure: c.ApiInsecure,
239 Timeout: 30 * RetryDelay * time.Duration(c.Retries),
241 resp, err := client.Do(req)
245 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
246 defer resp.Body.Close()
247 return nil, newAPIServerError(c.ApiServer, resp)
249 return resp.Body, nil
252 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
254 ase := APIServerError{
255 ServerAddress: ServerAddress,
256 HttpStatusCode: resp.StatusCode,
257 HttpStatusMessage: resp.Status}
259 // If the response body has {"errors":["reason1","reason2"]}
260 // then return those reasons.
262 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
263 if errorList, ok := errInfo["errors"]; ok {
264 if errArray, ok := errorList.([]interface{}); ok {
265 for _, errItem := range errArray {
266 // We expect an array of strings here.
267 // Non-strings will be passed along
269 if s, ok := errItem.(string); ok {
270 ase.ErrorDetails = append(ase.ErrorDetails, s)
271 } else if j, err := json.Marshal(errItem); err == nil {
272 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
281 // Call an API endpoint and parse the JSON response into an object.
283 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
284 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
285 // uuid - the uuid of the specific item to access. May be empty.
286 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
287 // parameters - method parameters.
288 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
290 // Returns a non-nil error if an error occurs making the API call, the
291 // API responds with a non-successful HTTP status, or an error occurs
292 // parsing the response body.
293 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
294 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
303 dec := json.NewDecoder(reader)
304 if err = dec.Decode(output); err != nil {
311 // Create a new resource. See Call for argument descriptions.
312 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
313 return c.Call("POST", resourceType, "", "", parameters, output)
316 // Delete a resource. See Call for argument descriptions.
317 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
318 return c.Call("DELETE", resource, uuid, "", parameters, output)
321 // Update attributes of a resource. See Call for argument descriptions.
322 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
323 return c.Call("PUT", resourceType, uuid, "", parameters, output)
326 // Get a resource. See Call for argument descriptions.
327 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
328 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
329 // No object has uuid == "": there is no need to make
330 // an API call. Furthermore, the HTTP request for such
331 // an API call would be "GET /arvados/v1/type/", which
332 // is liable to be misinterpreted as the List API.
333 return ErrInvalidArgument
335 return c.Call("GET", resourceType, uuid, "", parameters, output)
338 // List resources of a given type. See Call for argument descriptions.
339 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
340 return c.Call("GET", resource, "", "", parameters, output)
343 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
345 // Discovery returns the value of the given parameter in the discovery
346 // document. Returns a non-nil error if the discovery document cannot
347 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
348 // parameter is not found in the discovery document.
349 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
350 if len(c.DiscoveryDoc) == 0 {
351 c.DiscoveryDoc = make(Dict)
352 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
359 value, found = c.DiscoveryDoc[parameter]
363 return value, ErrInvalidArgument
366 // ClusterConfig returns the value of the given key in the current cluster's
367 // exported config. If key is an empty string, it'll return the entire config.
368 func (c *ArvadosClient) ClusterConfig(key string) (config interface{}, err error) {
369 var clusterConfig interface{}
370 err = c.Call("GET", "config", "", "", nil, &clusterConfig)
375 return clusterConfig, nil
377 configData, ok := clusterConfig.(map[string]interface{})[key]
379 return nil, ErrInvalidArgument
381 return configData, nil
384 func (c *ArvadosClient) httpClient() *http.Client {
388 cl := &defaultSecureHTTPClient
390 cl = &defaultInsecureHTTPClient
393 defaultHTTPClientMtx.Lock()
394 defer defaultHTTPClientMtx.Unlock()
395 *cl = &http.Client{Transport: &http.Transport{
396 TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}