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 {
61 // Arvados API server, form "host:port"
64 // Arvados API token for authentication
67 // Whether to require a valid SSL certificate or not
70 // Client object shared by client requests. Supports HTTP KeepAlive.
73 // If true, sets the X-External-Client header to indicate
74 // the client is outside the cluster.
81 // Create a new ArvadosClient, initialized with standard Arvados environment
82 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
83 // ARVADOS_API_HOST_INSECURE.
84 func MakeArvadosClient() (ac ArvadosClient, err error) {
85 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
86 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
87 external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
90 ApiServer: os.Getenv("ARVADOS_API_HOST"),
91 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
92 ApiInsecure: insecure,
93 Client: &http.Client{Transport: &http.Transport{
94 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
97 if ac.ApiServer == "" {
98 return ac, MissingArvadosApiHost
100 if ac.ApiToken == "" {
101 return ac, MissingArvadosApiToken
107 // CallRaw is the same as Call() but returns a Reader that reads the
108 // response body, instead of taking an output object.
109 func (c ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
110 var req *http.Request
116 if resourceType != API_DISCOVERY_RESOURCE {
117 u.Path = "/arvados/v1"
120 if resourceType != "" {
121 u.Path = u.Path + "/" + resourceType
124 u.Path = u.Path + "/" + uuid
127 u.Path = u.Path + "/" + action
130 if parameters == nil {
131 parameters = make(Dict)
134 vals := make(url.Values)
135 for k, v := range parameters {
136 if s, ok := v.(string); ok {
138 } else if m, err := json.Marshal(v); err == nil {
139 vals.Set(k, string(m))
143 if method == "GET" || method == "HEAD" {
144 u.RawQuery = vals.Encode()
145 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
149 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
152 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
155 // Add api token header
156 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
158 req.Header.Add("X-External-Client", "1")
162 var resp *http.Response
163 if resp, err = c.Client.Do(req); err != nil {
167 if resp.StatusCode == http.StatusOK {
168 return resp.Body, nil
171 defer resp.Body.Close()
172 return nil, newAPIServerError(c.ApiServer, resp)
175 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
177 ase := APIServerError{
178 ServerAddress: ServerAddress,
179 HttpStatusCode: resp.StatusCode,
180 HttpStatusMessage: resp.Status}
182 // If the response body has {"errors":["reason1","reason2"]}
183 // then return those reasons.
185 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
186 if errorList, ok := errInfo["errors"]; ok {
187 if errArray, ok := errorList.([]interface{}); ok {
188 for _, errItem := range errArray {
189 // We expect an array of strings here.
190 // Non-strings will be passed along
192 if s, ok := errItem.(string); ok {
193 ase.ErrorDetails = append(ase.ErrorDetails, s)
194 } else if j, err := json.Marshal(errItem); err == nil {
195 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
204 // Call an API endpoint and parse the JSON response into an object.
206 // method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
207 // resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
208 // uuid - the uuid of the specific item to access. May be empty.
209 // action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
210 // parameters - method parameters.
211 // output - a map or annotated struct which is a legal target for encoding/json/Decoder.
213 // Returns a non-nil error if an error occurs making the API call, the
214 // API responds with a non-successful HTTP status, or an error occurs
215 // parsing the response body.
216 func (c ArvadosClient) Call(method string, resourceType string, uuid string, action string, parameters Dict, output interface{}) error {
217 reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
226 dec := json.NewDecoder(reader)
227 if err = dec.Decode(output); err != nil {
234 // Create a new resource. See Call for argument descriptions.
235 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
236 return c.Call("POST", resourceType, "", "", parameters, output)
239 // Delete a resource. See Call for argument descriptions.
240 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
241 return c.Call("DELETE", resource, uuid, "", parameters, output)
244 // Modify attributes of a resource. See Call for argument descriptions.
245 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
246 return c.Call("PUT", resourceType, uuid, "", parameters, output)
249 // Get a resource. See Call for argument descriptions.
250 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
251 if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
252 // No object has uuid == "": there is no need to make
253 // an API call. Furthermore, the HTTP request for such
254 // an API call would be "GET /arvados/v1/type/", which
255 // is liable to be misinterpreted as the List API.
256 return ErrInvalidArgument
258 return c.Call("GET", resourceType, uuid, "", parameters, output)
261 // List resources of a given type. See Call for argument descriptions.
262 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
263 return c.Call("GET", resource, "", "", parameters, output)
266 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
268 // Discovery returns the value of the given parameter in the discovery
269 // document. Returns a non-nil error if the discovery document cannot
270 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
271 // parameter is not found in the discovery document.
272 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
273 if len(c.DiscoveryDoc) == 0 {
274 c.DiscoveryDoc = make(Dict)
275 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
282 value, found = c.DiscoveryDoc[parameter]
286 return value, ErrInvalidArgument