1 /* Simple Arvados Go SDK for communicating with API server. */
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
26 type StringMatcher func(string) bool
28 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
29 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
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 // Indicates 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",
77 // StringBool tests whether s is suggestive of true. It returns true
78 // if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
79 func StringBool(s string) bool {
80 s = strings.ToLower(s)
81 return s == "1" || s == "yes" || s == "true"
84 // Helper type so we don't have to write out 'map[string]interface{}' every time.
85 type Dict map[string]interface{}
87 // Information about how to contact the Arvados server
88 type ArvadosClient struct {
92 // Arvados API server, form "host:port"
95 // Arvados API token for authentication
98 // Whether to require a valid SSL certificate or not
101 // Client object shared by client requests. Supports HTTP KeepAlive.
104 // If true, sets the X-External-Client header to indicate
105 // the client is outside the cluster.
108 // Base URIs of Keep services, e.g., {"https://host1:8443",
109 // "https://host2:8443"}. If this is nil, Keep clients will
110 // use the arvados.v1.keep_services.accessible API to discover
111 // available services.
112 KeepServiceURIs []string
114 // Discovery document
117 lastClosedIdlesAt time.Time
123 var CertFiles = []string{
124 "/etc/arvados/ca-certificates.crt",
125 "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
126 "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL
129 // MakeTLSConfig sets up TLS configuration for communicating with
130 // Arvados and Keep services.
131 func MakeTLSConfig(insecure bool) *tls.Config {
132 tlsconfig := tls.Config{InsecureSkipVerify: insecure}
135 // Use the first entry in CertFiles that we can read
136 // certificates from. If none of those work out, use
138 certs := x509.NewCertPool()
139 for _, file := range CertFiles {
140 data, err := ioutil.ReadFile(file)
142 if !os.IsNotExist(err) {
143 log.Printf("error reading %q: %s", file, err)
147 if !certs.AppendCertsFromPEM(data) {
148 log.Printf("unable to load any certificates from %v", file)
151 tlsconfig.RootCAs = certs
159 // New returns an ArvadosClient using the given arvados.Client
160 // configuration. This is useful for callers who load arvados.Client
161 // fields from configuration files but still need to use the
162 // arvadosclient.ArvadosClient package.
163 func New(c *arvados.Client) (*ArvadosClient, error) {
164 ac := &ArvadosClient{
166 ApiServer: c.APIHost,
167 ApiToken: c.AuthToken,
168 ApiInsecure: c.Insecure,
169 Client: &http.Client{Transport: &http.Transport{
170 TLSClientConfig: MakeTLSConfig(c.Insecure)}},
173 KeepServiceURIs: c.KeepServiceURIs,
174 lastClosedIdlesAt: time.Now(),
180 // MakeArvadosClient creates a new ArvadosClient using the standard
181 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
182 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
183 // ARVADOS_KEEP_SERVICES.
184 func MakeArvadosClient() (ac *ArvadosClient, err error) {
185 ac, err = New(arvados.NewClientFromEnv())
189 ac.External = StringBool(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
193 // CallRaw is the same as Call() but returns a Reader that reads the
194 // response body, instead of taking an output object.
195 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
204 if resourceType != API_DISCOVERY_RESOURCE {
205 u.Path = "/arvados/v1"
208 if resourceType != "" {
209 u.Path = u.Path + "/" + resourceType
212 u.Path = u.Path + "/" + uuid
215 u.Path = u.Path + "/" + action
218 if parameters == nil {
219 parameters = make(Dict)
222 vals := make(url.Values)
223 for k, v := range parameters {
224 if s, ok := v.(string); ok {
226 } else if m, err := json.Marshal(v); err == nil {
227 vals.Set(k, string(m))
233 case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
237 // Non-retryable methods such as POST are not safe to retry automatically,
238 // so we minimize such failures by always using a new or recently active socket
240 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
241 c.lastClosedIdlesAt = time.Now()
242 c.Client.Transport.(*http.Transport).CloseIdleConnections()
247 var req *http.Request
248 var resp *http.Response
250 for attempt := 0; attempt <= c.Retries; attempt++ {
251 if method == "GET" || method == "HEAD" {
252 u.RawQuery = vals.Encode()
253 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
257 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
260 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
263 // Add api token header
264 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
266 req.Header.Add("X-External-Client", "1")
269 resp, err = c.Client.Do(req)
272 time.Sleep(RetryDelay)
279 if resp.StatusCode == http.StatusOK {
280 return resp.Body, nil
283 defer resp.Body.Close()
285 switch resp.StatusCode {
286 case 408, 409, 422, 423, 500, 502, 503, 504:
287 time.Sleep(RetryDelay)
290 return nil, newAPIServerError(c.ApiServer, resp)
295 return nil, newAPIServerError(c.ApiServer, resp)
300 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
302 ase := APIServerError{
303 ServerAddress: ServerAddress,
304 HttpStatusCode: resp.StatusCode,
305 HttpStatusMessage: resp.Status}
307 // If the response body has {"errors":["reason1","reason2"]}
308 // then return those reasons.
310 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
311 if errorList, ok := errInfo["errors"]; ok {
312 if errArray, ok := errorList.([]interface{}); ok {
313 for _, errItem := range errArray {
314 // We expect an array of strings here.
315 // Non-strings will be passed along
317 if s, ok := errItem.(string); ok {
318 ase.ErrorDetails = append(ase.ErrorDetails, s)
319 } else if j, err := json.Marshal(errItem); err == nil {
320 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
329 // Call an API endpoint and parse the JSON response into an object.
331 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
332 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
333 // uuid - the uuid of the specific item to access. May be empty.
334 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
335 // parameters - method parameters.
336 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
338 // Returns a non-nil error if an error occurs making the API call, the
339 // API responds with a non-successful HTTP status, or an error occurs
340 // parsing the response body.
341 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
342 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
351 dec := json.NewDecoder(reader)
352 if err = dec.Decode(output); err != nil {
359 // Create a new resource. See Call for argument descriptions.
360 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
361 return c.Call("POST", resourceType, "", "", parameters, output)
364 // Delete a resource. See Call for argument descriptions.
365 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
366 return c.Call("DELETE", resource, uuid, "", parameters, output)
369 // Modify attributes of a resource. See Call for argument descriptions.
370 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
371 return c.Call("PUT", resourceType, uuid, "", parameters, output)
374 // Get a resource. See Call for argument descriptions.
375 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
376 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
377 // No object has uuid == "": there is no need to make
378 // an API call. Furthermore, the HTTP request for such
379 // an API call would be "GET /arvados/v1/type/", which
380 // is liable to be misinterpreted as the List API.
381 return ErrInvalidArgument
383 return c.Call("GET", resourceType, uuid, "", parameters, output)
386 // List resources of a given type. See Call for argument descriptions.
387 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
388 return c.Call("GET", resource, "", "", parameters, output)
391 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
393 // Discovery returns the value of the given parameter in the discovery
394 // document. Returns a non-nil error if the discovery document cannot
395 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
396 // parameter is not found in the discovery document.
397 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
398 if len(c.DiscoveryDoc) == 0 {
399 c.DiscoveryDoc = make(Dict)
400 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
407 value, found = c.DiscoveryDoc[parameter]
411 return value, ErrInvalidArgument
415 func (ac *ArvadosClient) httpClient() *http.Client {
416 if ac.Client != nil {
419 c := &defaultSecureHTTPClient
421 c = &defaultInsecureHTTPClient
424 defaultHTTPClientMtx.Lock()
425 defer defaultHTTPClientMtx.Unlock()
426 *c = &http.Client{Transport: &http.Transport{
427 TLSClientConfig: MakeTLSConfig(ac.ApiInsecure)}}