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 // Before a POST or DELERE request, close any connections that were idle for this long
30 var MaxIdleConnectionDuration = 30 * time.Second
32 // Indicates an error that was returned by the API server.
33 type APIServerError struct {
34 // Address of server returning error, of the form "host:port".
37 // Components of server response.
39 HttpStatusMessage string
41 // Additional error details from response body.
45 func (e APIServerError) Error() string {
46 if len(e.ErrorDetails) > 0 {
47 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
48 strings.Join(e.ErrorDetails, "; "),
53 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
60 // Helper type so we don't have to write out 'map[string]interface{}' every time.
61 type Dict map[string]interface{}
63 // Information about how to contact the Arvados server
64 type ArvadosClient struct {
65 // Arvados API server, form "host:port"
68 // Arvados API token for authentication
71 // Whether to require a valid SSL certificate or not
74 // Client object shared by client requests. Supports HTTP KeepAlive.
77 // If true, sets the X-External-Client header to indicate
78 // the client is outside the cluster.
84 lastClosedIdlesAt time.Time
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"))
96 ApiServer: os.Getenv("ARVADOS_API_HOST"),
97 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
98 ApiInsecure: insecure,
99 Client: &http.Client{Transport: &http.Transport{
100 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
103 if ac.ApiServer == "" {
104 return ac, MissingArvadosApiHost
106 if ac.ApiToken == "" {
107 return ac, MissingArvadosApiToken
110 ac.lastClosedIdlesAt = time.Now()
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) {
118 var req *http.Request
124 if resourceType != API_DISCOVERY_RESOURCE {
125 u.Path = "/arvados/v1"
128 if resourceType != "" {
129 u.Path = u.Path + "/" + resourceType
132 u.Path = u.Path + "/" + uuid
135 u.Path = u.Path + "/" + action
138 if parameters == nil {
139 parameters = make(Dict)
142 vals := make(url.Values)
143 for k, v := range parameters {
144 if s, ok := v.(string); ok {
146 } else if m, err := json.Marshal(v); err == nil {
147 vals.Set(k, string(m))
151 if method == "GET" || method == "HEAD" {
152 u.RawQuery = vals.Encode()
153 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
157 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
160 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
163 // Add api token header
164 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
166 req.Header.Add("X-External-Client", "1")
169 // Before a POST or DELETE, close any idle connections
170 if method == "POST" || method == "DELETE" {
171 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
172 c.lastClosedIdlesAt = time.Now()
173 c.Client.Transport.(*http.Transport).CloseIdleConnections()
178 var resp *http.Response
179 if resp, err = c.Client.Do(req); err != nil {
183 if resp.StatusCode == http.StatusOK {
184 return resp.Body, nil
187 defer resp.Body.Close()
188 return nil, newAPIServerError(c.ApiServer, resp)
191 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
193 ase := APIServerError{
194 ServerAddress: ServerAddress,
195 HttpStatusCode: resp.StatusCode,
196 HttpStatusMessage: resp.Status}
198 // If the response body has {"errors":["reason1","reason2"]}
199 // then return those reasons.
201 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
202 if errorList, ok := errInfo["errors"]; ok {
203 if errArray, ok := errorList.([]interface{}); ok {
204 for _, errItem := range errArray {
205 // We expect an array of strings here.
206 // Non-strings will be passed along
208 if s, ok := errItem.(string); ok {
209 ase.ErrorDetails = append(ase.ErrorDetails, s)
210 } else if j, err := json.Marshal(errItem); err == nil {
211 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
220 // Call an API endpoint and parse the JSON response into an object.
222 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
223 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
224 // uuid - the uuid of the specific item to access. May be empty.
225 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
226 // parameters - method parameters.
227 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
229 // Returns a non-nil error if an error occurs making the API call, the
230 // API responds with a non-successful HTTP status, or an error occurs
231 // parsing the response body.
232 func (c ArvadosClient) Call(method string, resourceType string, uuid string, action string, parameters Dict, output interface{}) error {
233 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
242 dec := json.NewDecoder(reader)
243 if err = dec.Decode(output); err != nil {
250 // Create a new resource. See Call for argument descriptions.
251 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
252 return c.Call("POST", resourceType, "", "", parameters, output)
255 // Delete a resource. See Call for argument descriptions.
256 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
257 return c.Call("DELETE", resource, uuid, "", parameters, output)
260 // Modify attributes of a resource. See Call for argument descriptions.
261 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
262 return c.Call("PUT", resourceType, uuid, "", parameters, output)
265 // Get a resource. See Call for argument descriptions.
266 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
267 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
268 // No object has uuid == "": there is no need to make
269 // an API call. Furthermore, the HTTP request for such
270 // an API call would be "GET /arvados/v1/type/", which
271 // is liable to be misinterpreted as the List API.
272 return ErrInvalidArgument
274 return c.Call("GET", resourceType, uuid, "", parameters, output)
277 // List resources of a given type. See Call for argument descriptions.
278 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
279 return c.Call("GET", resource, "", "", parameters, output)
282 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
284 // Discovery returns the value of the given parameter in the discovery
285 // document. Returns a non-nil error if the discovery document cannot
286 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
287 // parameter is not found in the discovery document.
288 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
289 if len(c.DiscoveryDoc) == 0 {
290 c.DiscoveryDoc = make(Dict)
291 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
298 value, found = c.DiscoveryDoc[parameter]
302 return value, ErrInvalidArgument