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 {
68 // Arvados API server, form "host:port"
71 // Arvados API token for authentication
74 // Whether to require a valid SSL certificate or not
77 // Client object shared by client requests. Supports HTTP KeepAlive.
80 // If true, sets the X-External-Client header to indicate
81 // the client is outside the cluster.
87 lastClosedIdlesAt time.Time
90 // Create a new ArvadosClient, initialized with standard Arvados environment
91 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
92 // ARVADOS_API_HOST_INSECURE.
93 func MakeArvadosClient() (ac ArvadosClient, err error) {
94 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
95 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
96 external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
99 ApiServer: os.Getenv("ARVADOS_API_HOST"),
100 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
101 ApiInsecure: insecure,
102 Client: &http.Client{Transport: &http.Transport{
103 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
106 if ac.ApiServer == "" {
107 return ac, MissingArvadosApiHost
109 if ac.ApiToken == "" {
110 return ac, MissingArvadosApiToken
113 ac.lastClosedIdlesAt = time.Now()
118 // CallRaw is the same as Call() but returns a Reader that reads the
119 // response body, instead of taking an output object.
120 func (c ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
121 var req *http.Request
127 if resourceType != API_DISCOVERY_RESOURCE {
128 u.Path = "/arvados/v1"
131 if resourceType != "" {
132 u.Path = u.Path + "/" + resourceType
135 u.Path = u.Path + "/" + uuid
138 u.Path = u.Path + "/" + action
141 if parameters == nil {
142 parameters = make(Dict)
145 vals := make(url.Values)
146 for k, v := range parameters {
147 if s, ok := v.(string); ok {
149 } else if m, err := json.Marshal(v); err == nil {
150 vals.Set(k, string(m))
154 if method == "GET" || method == "HEAD" {
155 u.RawQuery = vals.Encode()
156 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
160 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
163 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
166 // Add api token header
167 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
169 req.Header.Add("X-External-Client", "1")
172 // POST and DELETE are not safe to retry automatically, so we minimize
173 // such failures by always using a new or recently active socket
174 if method == "POST" || method == "DELETE" {
175 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
176 c.lastClosedIdlesAt = time.Now()
177 c.Client.Transport.(*http.Transport).CloseIdleConnections()
182 var resp *http.Response
183 if resp, err = c.Client.Do(req); err != nil {
187 if resp.StatusCode == http.StatusOK {
188 return resp.Body, nil
191 defer resp.Body.Close()
192 return nil, newAPIServerError(c.ApiServer, resp)
195 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
197 ase := APIServerError{
198 ServerAddress: ServerAddress,
199 HttpStatusCode: resp.StatusCode,
200 HttpStatusMessage: resp.Status}
202 // If the response body has {"errors":["reason1","reason2"]}
203 // then return those reasons.
205 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
206 if errorList, ok := errInfo["errors"]; ok {
207 if errArray, ok := errorList.([]interface{}); ok {
208 for _, errItem := range errArray {
209 // We expect an array of strings here.
210 // Non-strings will be passed along
212 if s, ok := errItem.(string); ok {
213 ase.ErrorDetails = append(ase.ErrorDetails, s)
214 } else if j, err := json.Marshal(errItem); err == nil {
215 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
224 // Call an API endpoint and parse the JSON response into an object.
226 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
227 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
228 // uuid - the uuid of the specific item to access. May be empty.
229 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
230 // parameters - method parameters.
231 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
233 // Returns a non-nil error if an error occurs making the API call, the
234 // API responds with a non-successful HTTP status, or an error occurs
235 // parsing the response body.
236 func (c ArvadosClient) Call(method string, resourceType string, uuid string, action string, parameters Dict, output interface{}) error {
237 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
246 dec := json.NewDecoder(reader)
247 if err = dec.Decode(output); err != nil {
254 // Create a new resource. See Call for argument descriptions.
255 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
256 return c.Call("POST", resourceType, "", "", parameters, output)
259 // Delete a resource. See Call for argument descriptions.
260 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
261 return c.Call("DELETE", resource, uuid, "", parameters, output)
264 // Modify attributes of a resource. See Call for argument descriptions.
265 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
266 return c.Call("PUT", resourceType, uuid, "", parameters, output)
269 // Get a resource. See Call for argument descriptions.
270 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
271 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
272 // No object has uuid == "": there is no need to make
273 // an API call. Furthermore, the HTTP request for such
274 // an API call would be "GET /arvados/v1/type/", which
275 // is liable to be misinterpreted as the List API.
276 return ErrInvalidArgument
278 return c.Call("GET", resourceType, uuid, "", parameters, output)
281 // List resources of a given type. See Call for argument descriptions.
282 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
283 return c.Call("GET", resource, "", "", parameters, output)
286 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
288 // Discovery returns the value of the given parameter in the discovery
289 // document. Returns a non-nil error if the discovery document cannot
290 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
291 // parameter is not found in the discovery document.
292 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
293 if len(c.DiscoveryDoc) == 0 {
294 c.DiscoveryDoc = make(Dict)
295 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
302 value, found = c.DiscoveryDoc[parameter]
306 return value, ErrInvalidArgument