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 // Helper type so we don't have to write out 'map[string]interface{}' every time.
78 type Dict map[string]interface{}
80 // Information about how to contact the Arvados server
81 type ArvadosClient struct {
85 // Arvados API server, form "host:port"
88 // Arvados API token for authentication
91 // Whether to require a valid SSL certificate or not
94 // Client object shared by client requests. Supports HTTP KeepAlive.
97 // If true, sets the X-External-Client header to indicate
98 // the client is outside the cluster.
101 // Base URIs of Keep services, e.g., {"https://host1:8443",
102 // "https://host2:8443"}. If this is nil, Keep clients will
103 // use the arvados.v1.keep_services.accessible API to discover
104 // available services.
105 KeepServiceURIs []string
107 // Discovery document
110 lastClosedIdlesAt time.Time
116 var CertFiles = []string{
117 "/etc/arvados/ca-certificates.crt",
118 "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
119 "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL
122 // MakeTLSConfig sets up TLS configuration for communicating with
123 // Arvados and Keep services.
124 func MakeTLSConfig(insecure bool) *tls.Config {
125 tlsconfig := tls.Config{InsecureSkipVerify: insecure}
128 // Use the first entry in CertFiles that we can read
129 // certificates from. If none of those work out, use
131 certs := x509.NewCertPool()
132 for _, file := range CertFiles {
133 data, err := ioutil.ReadFile(file)
135 if !os.IsNotExist(err) {
136 log.Printf("error reading %q: %s", file, err)
140 if !certs.AppendCertsFromPEM(data) {
141 log.Printf("unable to load any certificates from %v", file)
144 tlsconfig.RootCAs = certs
152 // New returns an ArvadosClient using the given arvados.Client
153 // configuration. This is useful for callers who load arvados.Client
154 // fields from configuration files but still need to use the
155 // arvadosclient.ArvadosClient package.
156 func New(c *arvados.Client) (*ArvadosClient, error) {
157 ac := &ArvadosClient{
159 ApiServer: c.APIHost,
160 ApiToken: c.AuthToken,
161 ApiInsecure: c.Insecure,
162 Client: &http.Client{Transport: &http.Transport{
163 TLSClientConfig: MakeTLSConfig(c.Insecure)}},
166 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, ARVADOS_EXTERNAL_CLIENT, and
175 // ARVADOS_KEEP_SERVICES.
176 func MakeArvadosClient() (ac *ArvadosClient, err error) {
177 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
178 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
179 external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
183 ApiServer: os.Getenv("ARVADOS_API_HOST"),
184 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
185 ApiInsecure: insecure,
186 Client: &http.Client{Transport: &http.Transport{
187 TLSClientConfig: MakeTLSConfig(insecure)}},
191 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
195 if u, err := url.Parse(s); err != nil {
196 return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
197 } else if !u.IsAbs() {
198 return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
200 ac.KeepServiceURIs = append(ac.KeepServiceURIs, s)
203 if ac.ApiServer == "" {
204 return ac, MissingArvadosApiHost
206 if ac.ApiToken == "" {
207 return ac, MissingArvadosApiToken
210 ac.lastClosedIdlesAt = time.Now()
215 // CallRaw is the same as Call() but returns a Reader that reads the
216 // response body, instead of taking an output object.
217 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
226 if resourceType != API_DISCOVERY_RESOURCE {
227 u.Path = "/arvados/v1"
230 if resourceType != "" {
231 u.Path = u.Path + "/" + resourceType
234 u.Path = u.Path + "/" + uuid
237 u.Path = u.Path + "/" + action
240 if parameters == nil {
241 parameters = make(Dict)
244 vals := make(url.Values)
245 for k, v := range parameters {
246 if s, ok := v.(string); ok {
248 } else if m, err := json.Marshal(v); err == nil {
249 vals.Set(k, string(m))
255 case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
259 // Non-retryable methods such as POST are not safe to retry automatically,
260 // so we minimize such failures by always using a new or recently active socket
262 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
263 c.lastClosedIdlesAt = time.Now()
264 c.Client.Transport.(*http.Transport).CloseIdleConnections()
269 var req *http.Request
270 var resp *http.Response
272 for attempt := 0; attempt <= c.Retries; attempt++ {
273 if method == "GET" || method == "HEAD" {
274 u.RawQuery = vals.Encode()
275 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
279 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
282 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
285 // Add api token header
286 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
288 req.Header.Add("X-External-Client", "1")
291 resp, err = c.Client.Do(req)
294 time.Sleep(RetryDelay)
301 if resp.StatusCode == http.StatusOK {
302 return resp.Body, nil
305 defer resp.Body.Close()
307 switch resp.StatusCode {
308 case 408, 409, 422, 423, 500, 502, 503, 504:
309 time.Sleep(RetryDelay)
312 return nil, newAPIServerError(c.ApiServer, resp)
317 return nil, newAPIServerError(c.ApiServer, resp)
322 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
324 ase := APIServerError{
325 ServerAddress: ServerAddress,
326 HttpStatusCode: resp.StatusCode,
327 HttpStatusMessage: resp.Status}
329 // If the response body has {"errors":["reason1","reason2"]}
330 // then return those reasons.
332 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
333 if errorList, ok := errInfo["errors"]; ok {
334 if errArray, ok := errorList.([]interface{}); ok {
335 for _, errItem := range errArray {
336 // We expect an array of strings here.
337 // Non-strings will be passed along
339 if s, ok := errItem.(string); ok {
340 ase.ErrorDetails = append(ase.ErrorDetails, s)
341 } else if j, err := json.Marshal(errItem); err == nil {
342 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
351 // Call an API endpoint and parse the JSON response into an object.
353 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
354 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
355 // uuid - the uuid of the specific item to access. May be empty.
356 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
357 // parameters - method parameters.
358 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
360 // Returns a non-nil error if an error occurs making the API call, the
361 // API responds with a non-successful HTTP status, or an error occurs
362 // parsing the response body.
363 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
364 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
373 dec := json.NewDecoder(reader)
374 if err = dec.Decode(output); err != nil {
381 // Create a new resource. See Call for argument descriptions.
382 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
383 return c.Call("POST", resourceType, "", "", parameters, output)
386 // Delete a resource. See Call for argument descriptions.
387 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
388 return c.Call("DELETE", resource, uuid, "", parameters, output)
391 // Modify attributes of a resource. See Call for argument descriptions.
392 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
393 return c.Call("PUT", resourceType, uuid, "", parameters, output)
396 // Get a resource. See Call for argument descriptions.
397 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
398 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
399 // No object has uuid == "": there is no need to make
400 // an API call. Furthermore, the HTTP request for such
401 // an API call would be "GET /arvados/v1/type/", which
402 // is liable to be misinterpreted as the List API.
403 return ErrInvalidArgument
405 return c.Call("GET", resourceType, uuid, "", parameters, output)
408 // List resources of a given type. See Call for argument descriptions.
409 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
410 return c.Call("GET", resource, "", "", parameters, output)
413 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
415 // Discovery returns the value of the given parameter in the discovery
416 // document. Returns a non-nil error if the discovery document cannot
417 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
418 // parameter is not found in the discovery document.
419 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
420 if len(c.DiscoveryDoc) == 0 {
421 c.DiscoveryDoc = make(Dict)
422 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
429 value, found = c.DiscoveryDoc[parameter]
433 return value, ErrInvalidArgument
437 func (ac *ArvadosClient) httpClient() *http.Client {
438 if ac.Client != nil {
441 c := &defaultSecureHTTPClient
443 c = &defaultInsecureHTTPClient
446 defaultHTTPClientMtx.Lock()
447 defer defaultHTTPClientMtx.Unlock()
448 *c = &http.Client{Transport: &http.Transport{
449 TLSClientConfig: MakeTLSConfig(ac.ApiInsecure)}}