1 /* Simple Arvados Go SDK for communicating with API server. */
19 "git.curoverse.com/arvados.git/sdk/go/arvados"
22 type StringMatcher func(string) bool
24 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
25 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
27 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
28 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
29 var ErrInvalidArgument = errors.New("Invalid argument")
31 // A common failure mode is to reuse a keepalive connection that has been
32 // terminated (in a way that we can't detect) for being idle too long.
33 // POST and DELETE are not safe to retry automatically, so we minimize
34 // such failures by always using a new or recently active socket.
35 var MaxIdleConnectionDuration = 30 * time.Second
37 var RetryDelay = 2 * time.Second
39 // Indicates an error that was returned by the API server.
40 type APIServerError struct {
41 // Address of server returning error, of the form "host:port".
44 // Components of server response.
46 HttpStatusMessage string
48 // Additional error details from response body.
52 func (e APIServerError) Error() string {
53 if len(e.ErrorDetails) > 0 {
54 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
55 strings.Join(e.ErrorDetails, "; "),
60 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
67 // Helper type so we don't have to write out 'map[string]interface{}' every time.
68 type Dict map[string]interface{}
70 // Information about how to contact the Arvados server
71 type ArvadosClient struct {
75 // Arvados API server, form "host:port"
78 // Arvados API token for authentication
81 // Whether to require a valid SSL certificate or not
84 // Client object shared by client requests. Supports HTTP KeepAlive.
87 // If true, sets the X-External-Client header to indicate
88 // the client is outside the cluster.
91 // Base URIs of Keep services, e.g., {"https://host1:8443",
92 // "https://host2:8443"}. If this is nil, Keep clients will
93 // use the arvados.v1.keep_services.accessible API to discover
94 // available services.
95 KeepServiceURIs []string
100 lastClosedIdlesAt time.Time
106 // New returns an ArvadosClient using the given arvados.Client
107 // configuration. This is useful for callers who load arvados.Client
108 // fields from configuration files but still need to use the
109 // arvadosclient.ArvadosClient package.
110 func New(c *arvados.Client) (*ArvadosClient, error) {
111 return &ArvadosClient{
113 ApiServer: c.APIHost,
114 ApiToken: c.AuthToken,
115 ApiInsecure: c.Insecure,
116 Client: &http.Client{Transport: &http.Transport{
117 TLSClientConfig: &tls.Config{InsecureSkipVerify: c.Insecure}}},
120 lastClosedIdlesAt: time.Now(),
124 // MakeArvadosClient creates a new ArvadosClient using the standard
125 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
126 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
127 // ARVADOS_KEEP_SERVICES.
128 func MakeArvadosClient() (ac *ArvadosClient, err error) {
129 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
130 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
131 external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
135 ApiServer: os.Getenv("ARVADOS_API_HOST"),
136 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
137 ApiInsecure: insecure,
138 Client: &http.Client{Transport: &http.Transport{
139 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
143 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
147 if u, err := url.Parse(s); err != nil {
148 return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
149 } else if !u.IsAbs() {
150 return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
152 ac.KeepServiceURIs = append(ac.KeepServiceURIs, s)
155 if ac.ApiServer == "" {
156 return ac, MissingArvadosApiHost
158 if ac.ApiToken == "" {
159 return ac, MissingArvadosApiToken
162 ac.lastClosedIdlesAt = time.Now()
167 // CallRaw is the same as Call() but returns a Reader that reads the
168 // response body, instead of taking an output object.
169 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
178 if resourceType != API_DISCOVERY_RESOURCE {
179 u.Path = "/arvados/v1"
182 if resourceType != "" {
183 u.Path = u.Path + "/" + resourceType
186 u.Path = u.Path + "/" + uuid
189 u.Path = u.Path + "/" + action
192 if parameters == nil {
193 parameters = make(Dict)
196 vals := make(url.Values)
197 for k, v := range parameters {
198 if s, ok := v.(string); ok {
200 } else if m, err := json.Marshal(v); err == nil {
201 vals.Set(k, string(m))
207 case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
211 // Non-retryable methods such as POST are not safe to retry automatically,
212 // so we minimize such failures by always using a new or recently active socket
214 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
215 c.lastClosedIdlesAt = time.Now()
216 c.Client.Transport.(*http.Transport).CloseIdleConnections()
221 var req *http.Request
222 var resp *http.Response
224 for attempt := 0; attempt <= c.Retries; attempt++ {
225 if method == "GET" || method == "HEAD" {
226 u.RawQuery = vals.Encode()
227 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
231 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
234 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
237 // Add api token header
238 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
240 req.Header.Add("X-External-Client", "1")
243 resp, err = c.Client.Do(req)
246 time.Sleep(RetryDelay)
253 if resp.StatusCode == http.StatusOK {
254 return resp.Body, nil
257 defer resp.Body.Close()
259 switch resp.StatusCode {
260 case 408, 409, 422, 423, 500, 502, 503, 504:
261 time.Sleep(RetryDelay)
264 return nil, newAPIServerError(c.ApiServer, resp)
269 return nil, newAPIServerError(c.ApiServer, resp)
274 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
276 ase := APIServerError{
277 ServerAddress: ServerAddress,
278 HttpStatusCode: resp.StatusCode,
279 HttpStatusMessage: resp.Status}
281 // If the response body has {"errors":["reason1","reason2"]}
282 // then return those reasons.
284 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
285 if errorList, ok := errInfo["errors"]; ok {
286 if errArray, ok := errorList.([]interface{}); ok {
287 for _, errItem := range errArray {
288 // We expect an array of strings here.
289 // Non-strings will be passed along
291 if s, ok := errItem.(string); ok {
292 ase.ErrorDetails = append(ase.ErrorDetails, s)
293 } else if j, err := json.Marshal(errItem); err == nil {
294 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
303 // Call an API endpoint and parse the JSON response into an object.
305 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
306 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
307 // uuid - the uuid of the specific item to access. May be empty.
308 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
309 // parameters - method parameters.
310 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
312 // Returns a non-nil error if an error occurs making the API call, the
313 // API responds with a non-successful HTTP status, or an error occurs
314 // parsing the response body.
315 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
316 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
325 dec := json.NewDecoder(reader)
326 if err = dec.Decode(output); err != nil {
333 // Create a new resource. See Call for argument descriptions.
334 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
335 return c.Call("POST", resourceType, "", "", parameters, output)
338 // Delete a resource. See Call for argument descriptions.
339 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
340 return c.Call("DELETE", resource, uuid, "", parameters, output)
343 // Modify attributes of a resource. See Call for argument descriptions.
344 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
345 return c.Call("PUT", resourceType, uuid, "", parameters, output)
348 // Get a resource. See Call for argument descriptions.
349 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
350 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
351 // No object has uuid == "": there is no need to make
352 // an API call. Furthermore, the HTTP request for such
353 // an API call would be "GET /arvados/v1/type/", which
354 // is liable to be misinterpreted as the List API.
355 return ErrInvalidArgument
357 return c.Call("GET", resourceType, uuid, "", parameters, output)
360 // List resources of a given type. See Call for argument descriptions.
361 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
362 return c.Call("GET", resource, "", "", parameters, output)
365 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
367 // Discovery returns the value of the given parameter in the discovery
368 // document. Returns a non-nil error if the discovery document cannot
369 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
370 // parameter is not found in the discovery document.
371 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
372 if len(c.DiscoveryDoc) == 0 {
373 c.DiscoveryDoc = make(Dict)
374 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
381 value, found = c.DiscoveryDoc[parameter]
385 return value, ErrInvalidArgument