1 /* Simple Arvados Go SDK for communicating with API server. */
19 type StringMatcher func(string) bool
21 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
22 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
24 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
25 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
26 var ErrInvalidArgument = errors.New("Invalid argument")
28 // Indicates an error that was returned by the API server.
29 type APIServerError struct {
30 // Address of server returning error, of the form "host:port".
33 // Components of server response.
35 HttpStatusMessage string
37 // Additional error details from response body.
41 func (e APIServerError) Error() string {
42 if len(e.ErrorDetails) > 0 {
43 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
44 strings.Join(e.ErrorDetails, "; "),
49 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
56 // Helper type so we don't have to write out 'map[string]interface{}' every time.
57 type Dict map[string]interface{}
59 // Information about how to contact the Arvados server
60 type ArvadosClient struct {
64 // Arvados API server, form "host:port"
67 // Arvados API token for authentication
70 // Whether to require a valid SSL certificate or not
73 // Client object shared by client requests. Supports HTTP KeepAlive.
76 // If true, sets the X-External-Client header to indicate
77 // the client is outside the cluster.
87 // Create a new ArvadosClient, initialized with standard Arvados environment
88 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
89 // ARVADOS_API_HOST_INSECURE.
90 func MakeArvadosClient() (ac ArvadosClient, err error) {
91 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
92 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
93 external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
97 ApiServer: os.Getenv("ARVADOS_API_HOST"),
98 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
99 ApiInsecure: insecure,
100 Client: &http.Client{Transport: &http.Transport{
101 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
105 if ac.ApiServer == "" {
106 return ac, MissingArvadosApiHost
108 if ac.ApiToken == "" {
109 return ac, MissingArvadosApiToken
115 // CallRaw is the same as Call() but returns a Reader that reads the
116 // response body, instead of taking an output object.
117 func (c ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
126 if resourceType != API_DISCOVERY_RESOURCE {
127 u.Path = "/arvados/v1"
130 if resourceType != "" {
131 u.Path = u.Path + "/" + resourceType
134 u.Path = u.Path + "/" + uuid
137 u.Path = u.Path + "/" + action
140 if parameters == nil {
141 parameters = make(Dict)
144 vals := make(url.Values)
145 for k, v := range parameters {
146 if s, ok := v.(string); ok {
148 } else if m, err := json.Marshal(v); err == nil {
149 vals.Set(k, string(m))
154 remainingTries := 1 + c.Retries
155 var req *http.Request
156 var resp *http.Response
160 for remainingTries > 0 {
161 if method == "GET" || method == "HEAD" {
162 u.RawQuery = vals.Encode()
163 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
167 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
170 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
173 // Add api token header
174 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
176 req.Header.Add("X-External-Client", "1")
179 resp, err = c.Client.Do(req)
181 if method == "GET" || method == "HEAD" || method == "PUT" {
182 errs = append(errs, err.Error())
191 if resp.StatusCode == http.StatusOK {
192 return resp.Body, nil
195 defer resp.Body.Close()
197 if resp.StatusCode == 408 ||
198 resp.StatusCode == 409 ||
199 resp.StatusCode == 422 ||
200 resp.StatusCode == 423 ||
201 resp.StatusCode == 500 ||
202 resp.StatusCode == 502 ||
203 resp.StatusCode == 503 ||
204 resp.StatusCode == 504 {
209 return nil, newAPIServerError(c.ApiServer, resp)
214 return nil, newAPIServerError(c.ApiServer, resp)
216 return nil, fmt.Errorf("%v", errs)
220 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
222 ase := APIServerError{
223 ServerAddress: ServerAddress,
224 HttpStatusCode: resp.StatusCode,
225 HttpStatusMessage: resp.Status}
227 // If the response body has {"errors":["reason1","reason2"]}
228 // then return those reasons.
230 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
231 if errorList, ok := errInfo["errors"]; ok {
232 if errArray, ok := errorList.([]interface{}); ok {
233 for _, errItem := range errArray {
234 // We expect an array of strings here.
235 // Non-strings will be passed along
237 if s, ok := errItem.(string); ok {
238 ase.ErrorDetails = append(ase.ErrorDetails, s)
239 } else if j, err := json.Marshal(errItem); err == nil {
240 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
249 // Call an API endpoint and parse the JSON response into an object.
251 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
252 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
253 // uuid - the uuid of the specific item to access. May be empty.
254 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
255 // parameters - method parameters.
256 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
258 // Returns a non-nil error if an error occurs making the API call, the
259 // API responds with a non-successful HTTP status, or an error occurs
260 // parsing the response body.
261 func (c ArvadosClient) Call(method string, resourceType string, uuid string, action string, parameters Dict, output interface{}) error {
262 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
271 dec := json.NewDecoder(reader)
272 if err = dec.Decode(output); err != nil {
279 // Create a new resource. See Call for argument descriptions.
280 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
281 return c.Call("POST", resourceType, "", "", parameters, output)
284 // Delete a resource. See Call for argument descriptions.
285 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
286 return c.Call("DELETE", resource, uuid, "", parameters, output)
289 // Modify attributes of a resource. See Call for argument descriptions.
290 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
291 return c.Call("PUT", resourceType, uuid, "", parameters, output)
294 // Get a resource. See Call for argument descriptions.
295 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
296 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
297 // No object has uuid == "": there is no need to make
298 // an API call. Furthermore, the HTTP request for such
299 // an API call would be "GET /arvados/v1/type/", which
300 // is liable to be misinterpreted as the List API.
301 return ErrInvalidArgument
303 return c.Call("GET", resourceType, uuid, "", parameters, output)
306 // List resources of a given type. See Call for argument descriptions.
307 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
308 return c.Call("GET", resource, "", "", parameters, output)
311 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
313 // Discovery returns the value of the given parameter in the discovery
314 // document. Returns a non-nil error if the discovery document cannot
315 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
316 // parameter is not found in the discovery document.
317 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
318 if len(c.DiscoveryDoc) == 0 {
319 c.DiscoveryDoc = make(Dict)
320 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
327 value, found = c.DiscoveryDoc[parameter]
331 return value, ErrInvalidArgument