1 /* Simple Arvados Go SDK for communicating with API server. */
20 type StringMatcher func(string) bool
22 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
23 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
25 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
26 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
27 var ErrInvalidArgument = errors.New("Invalid argument")
29 // A common failure mode is to reuse a keepalive connection that has been
30 // terminated (in a way that we can't detect) for being idle too long.
31 // POST and DELETE are not safe to retry automatically, so we minimize
32 // such failures by always using a new or recently active socket.
33 var MaxIdleConnectionDuration = 30 * time.Second
35 // Indicates an error that was returned by the API server.
36 type APIServerError struct {
37 // Address of server returning error, of the form "host:port".
40 // Components of server response.
42 HttpStatusMessage string
44 // Additional error details from response body.
48 func (e APIServerError) Error() string {
49 if len(e.ErrorDetails) > 0 {
50 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
51 strings.Join(e.ErrorDetails, "; "),
56 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
63 // Helper type so we don't have to write out 'map[string]interface{}' every time.
64 type Dict map[string]interface{}
66 // Information about how to contact the Arvados server
67 type ArvadosClient struct {
71 // Arvados API server, form "host:port"
74 // Arvados API token for authentication
77 // Whether to require a valid SSL certificate or not
80 // Client object shared by client requests. Supports HTTP KeepAlive.
83 // If true, sets the X-External-Client header to indicate
84 // the client is outside the cluster.
90 lastClosedIdlesAt time.Time
96 // Create a new ArvadosClient, initialized with standard Arvados environment
97 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
98 // ARVADOS_API_HOST_INSECURE.
99 func MakeArvadosClient() (ac ArvadosClient, err error) {
100 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
101 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
102 external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
106 ApiServer: os.Getenv("ARVADOS_API_HOST"),
107 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
108 ApiInsecure: insecure,
109 Client: &http.Client{Transport: &http.Transport{
110 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
114 if ac.ApiServer == "" {
115 return ac, MissingArvadosApiHost
117 if ac.ApiToken == "" {
118 return ac, MissingArvadosApiToken
121 ac.lastClosedIdlesAt = time.Now()
126 // CallRaw is the same as Call() but returns a Reader that reads the
127 // response body, instead of taking an output object.
128 func (c ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
137 if resourceType != API_DISCOVERY_RESOURCE {
138 u.Path = "/arvados/v1"
141 if resourceType != "" {
142 u.Path = u.Path + "/" + resourceType
145 u.Path = u.Path + "/" + uuid
148 u.Path = u.Path + "/" + action
151 if parameters == nil {
152 parameters = make(Dict)
155 vals := make(url.Values)
156 for k, v := range parameters {
157 if s, ok := v.(string); ok {
159 } else if m, err := json.Marshal(v); err == nil {
160 vals.Set(k, string(m))
165 remainingTries := 1 + c.Retries
166 var req *http.Request
167 var resp *http.Response
171 for remainingTries > 0 {
172 if method == "GET" || method == "HEAD" {
173 u.RawQuery = vals.Encode()
174 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
178 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
181 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
184 // Add api token header
185 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
187 req.Header.Add("X-External-Client", "1")
190 // POST and DELETE are not safe to retry automatically, so we minimize
191 // such failures by always using a new or recently active socket
192 if method == "POST" || method == "DELETE" {
193 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
194 c.lastClosedIdlesAt = time.Now()
195 c.Client.Transport.(*http.Transport).CloseIdleConnections()
199 resp, err = c.Client.Do(req)
201 if method == "GET" || method == "HEAD" || method == "PUT" {
202 errs = append(errs, err.Error())
211 if resp.StatusCode == http.StatusOK {
212 return resp.Body, nil
215 defer resp.Body.Close()
217 if resp.StatusCode == 408 ||
218 resp.StatusCode == 409 ||
219 resp.StatusCode == 422 ||
220 resp.StatusCode == 423 ||
221 resp.StatusCode == 500 ||
222 resp.StatusCode == 502 ||
223 resp.StatusCode == 503 ||
224 resp.StatusCode == 504 {
229 return nil, newAPIServerError(c.ApiServer, resp)
234 return nil, newAPIServerError(c.ApiServer, resp)
236 return nil, fmt.Errorf("%v", errs)
240 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
242 ase := APIServerError{
243 ServerAddress: ServerAddress,
244 HttpStatusCode: resp.StatusCode,
245 HttpStatusMessage: resp.Status}
247 // If the response body has {"errors":["reason1","reason2"]}
248 // then return those reasons.
250 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
251 if errorList, ok := errInfo["errors"]; ok {
252 if errArray, ok := errorList.([]interface{}); ok {
253 for _, errItem := range errArray {
254 // We expect an array of strings here.
255 // Non-strings will be passed along
257 if s, ok := errItem.(string); ok {
258 ase.ErrorDetails = append(ase.ErrorDetails, s)
259 } else if j, err := json.Marshal(errItem); err == nil {
260 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
269 // Call an API endpoint and parse the JSON response into an object.
271 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
272 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
273 // uuid - the uuid of the specific item to access. May be empty.
274 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
275 // parameters - method parameters.
276 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
278 // Returns a non-nil error if an error occurs making the API call, the
279 // API responds with a non-successful HTTP status, or an error occurs
280 // parsing the response body.
281 func (c ArvadosClient) Call(method string, resourceType string, uuid string, action string, parameters Dict, output interface{}) error {
282 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
291 dec := json.NewDecoder(reader)
292 if err = dec.Decode(output); err != nil {
299 // Create a new resource. See Call for argument descriptions.
300 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
301 return c.Call("POST", resourceType, "", "", parameters, output)
304 // Delete a resource. See Call for argument descriptions.
305 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
306 return c.Call("DELETE", resource, uuid, "", parameters, output)
309 // Modify attributes of a resource. See Call for argument descriptions.
310 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
311 return c.Call("PUT", resourceType, uuid, "", parameters, output)
314 // Get a resource. See Call for argument descriptions.
315 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
316 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
317 // No object has uuid == "": there is no need to make
318 // an API call. Furthermore, the HTTP request for such
319 // an API call would be "GET /arvados/v1/type/", which
320 // is liable to be misinterpreted as the List API.
321 return ErrInvalidArgument
323 return c.Call("GET", resourceType, uuid, "", parameters, output)
326 // List resources of a given type. See Call for argument descriptions.
327 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
328 return c.Call("GET", resource, "", "", parameters, output)
331 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
333 // Discovery returns the value of the given parameter in the discovery
334 // document. Returns a non-nil error if the discovery document cannot
335 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
336 // parameter is not found in the discovery document.
337 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
338 if len(c.DiscoveryDoc) == 0 {
339 c.DiscoveryDoc = make(Dict)
340 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
347 value, found = c.DiscoveryDoc[parameter]
351 return value, ErrInvalidArgument