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 // Discovery document
111 lastClosedIdlesAt time.Time
116 // X-Request-Id for outgoing requests
120 // MakeTLSConfig sets up TLS configuration for communicating with
121 // Arvados and Keep services.
122 func MakeTLSConfig(insecure bool) *tls.Config {
123 return &tls.Config{InsecureSkipVerify: insecure}
126 // New returns an ArvadosClient using the given arvados.Client
127 // configuration. This is useful for callers who load arvados.Client
128 // fields from configuration files but still need to use the
129 // arvadosclient.ArvadosClient package.
130 func New(c *arvados.Client) (*ArvadosClient, error) {
134 Timeout: 5 * time.Minute,
135 Transport: &http.Transport{
136 TLSClientConfig: MakeTLSConfig(c.Insecure)},
139 ac := &ArvadosClient{
141 ApiServer: c.APIHost,
142 ApiToken: c.AuthToken,
143 ApiInsecure: c.Insecure,
146 KeepServiceURIs: c.KeepServiceURIs,
147 lastClosedIdlesAt: time.Now(),
153 // MakeArvadosClient creates a new ArvadosClient using the standard
154 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
155 // ARVADOS_API_HOST_INSECURE, and ARVADOS_KEEP_SERVICES.
156 func MakeArvadosClient() (*ArvadosClient, error) {
157 return New(arvados.NewClientFromEnv())
160 // CallRaw is the same as Call() but returns a Reader that reads the
161 // response body, instead of taking an output object.
162 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
167 if c.ApiServer == "" {
168 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?")
174 if resourceType != ApiDiscoveryResource {
175 u.Path = "/arvados/v1"
178 if resourceType != "" {
179 u.Path = u.Path + "/" + resourceType
182 u.Path = u.Path + "/" + uuid
185 u.Path = u.Path + "/" + action
188 if parameters == nil {
189 parameters = make(Dict)
192 vals := make(url.Values)
193 for k, v := range parameters {
194 if s, ok := v.(string); ok {
196 } else if m, err := json.Marshal(v); err == nil {
197 vals.Set(k, string(m))
200 var req *http.Request
201 if method == "GET" || method == "HEAD" {
202 u.RawQuery = vals.Encode()
203 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
207 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
210 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
212 if c.RequestID != "" {
213 req.Header.Add("X-Request-Id", c.RequestID)
215 client := arvados.Client{
217 APIHost: c.ApiServer,
218 AuthToken: c.ApiToken,
219 Insecure: c.ApiInsecure,
220 Timeout: 30 * RetryDelay * time.Duration(c.Retries),
222 resp, err := client.Do(req)
226 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
227 defer resp.Body.Close()
228 return nil, newAPIServerError(c.ApiServer, resp)
230 return resp.Body, nil
233 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
235 ase := APIServerError{
236 ServerAddress: ServerAddress,
237 HttpStatusCode: resp.StatusCode,
238 HttpStatusMessage: resp.Status}
240 // If the response body has {"errors":["reason1","reason2"]}
241 // then return those reasons.
243 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
244 if errorList, ok := errInfo["errors"]; ok {
245 if errArray, ok := errorList.([]interface{}); ok {
246 for _, errItem := range errArray {
247 // We expect an array of strings here.
248 // Non-strings will be passed along
250 if s, ok := errItem.(string); ok {
251 ase.ErrorDetails = append(ase.ErrorDetails, s)
252 } else if j, err := json.Marshal(errItem); err == nil {
253 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
262 // Call an API endpoint and parse the JSON response into an object.
264 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
265 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
266 // uuid - the uuid of the specific item to access. May be empty.
267 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
268 // parameters - method parameters.
269 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
271 // Returns a non-nil error if an error occurs making the API call, the
272 // API responds with a non-successful HTTP status, or an error occurs
273 // parsing the response body.
274 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
275 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
284 dec := json.NewDecoder(reader)
285 if err = dec.Decode(output); err != nil {
292 // Create a new resource. See Call for argument descriptions.
293 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
294 return c.Call("POST", resourceType, "", "", parameters, output)
297 // Delete a resource. See Call for argument descriptions.
298 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
299 return c.Call("DELETE", resource, uuid, "", parameters, output)
302 // Update attributes of a resource. See Call for argument descriptions.
303 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
304 return c.Call("PUT", resourceType, uuid, "", parameters, output)
307 // Get a resource. See Call for argument descriptions.
308 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
309 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
310 // No object has uuid == "": there is no need to make
311 // an API call. Furthermore, the HTTP request for such
312 // an API call would be "GET /arvados/v1/type/", which
313 // is liable to be misinterpreted as the List API.
314 return ErrInvalidArgument
316 return c.Call("GET", resourceType, uuid, "", parameters, output)
319 // List resources of a given type. See Call for argument descriptions.
320 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
321 return c.Call("GET", resource, "", "", parameters, output)
324 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
326 // Discovery returns the value of the given parameter in the discovery
327 // document. Returns a non-nil error if the discovery document cannot
328 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
329 // parameter is not found in the discovery document.
330 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
331 if len(c.DiscoveryDoc) == 0 {
332 c.DiscoveryDoc = make(Dict)
333 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
340 value, found = c.DiscoveryDoc[parameter]
344 return value, ErrInvalidArgument
347 // ClusterConfig returns the value of the given key in the current cluster's
348 // exported config. If key is an empty string, it'll return the entire config.
349 func (c *ArvadosClient) ClusterConfig(key string) (config interface{}, err error) {
350 var clusterConfig interface{}
351 err = c.Call("GET", "config", "", "", nil, &clusterConfig)
356 return clusterConfig, nil
358 configData, ok := clusterConfig.(map[string]interface{})[key]
360 return nil, ErrInvalidArgument
362 return configData, nil
365 func (c *ArvadosClient) httpClient() *http.Client {
369 cl := &defaultSecureHTTPClient
371 cl = &defaultInsecureHTTPClient
374 defaultHTTPClientMtx.Lock()
375 defer defaultHTTPClientMtx.Unlock()
376 *cl = &http.Client{Transport: &http.Transport{
377 TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}