1 /* Simple Arvados Go SDK for communicating with API server. */
20 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
21 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
23 // Indicates an error that was returned by the API server.
24 type APIServerError struct {
25 // Address of server returning error, of the form "host:port".
28 // Components of server response.
30 HttpStatusMessage string
32 // Additional error details from response body.
36 func (e APIServerError) Error() string {
37 if len(e.ErrorDetails) > 0 {
38 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
39 strings.Join(e.ErrorDetails, "; "),
44 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
51 // Helper type so we don't have to write out 'map[string]interface{}' every time.
52 type Dict map[string]interface{}
54 // Information about how to contact the Arvados server
55 type ArvadosClient struct {
56 // Arvados API server, form "host:port"
59 // Arvados API token for authentication
62 // Whether to require a valid SSL certificate or not
65 // Client object shared by client requests. Supports HTTP KeepAlive.
68 // If true, sets the X-External-Client header to indicate
69 // the client is outside the cluster.
73 // Create a new ArvadosClient, initialized with standard Arvados environment
74 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
75 // ARVADOS_API_HOST_INSECURE.
76 func MakeArvadosClient() (ac ArvadosClient, err error) {
77 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
78 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
79 external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
82 ApiServer: os.Getenv("ARVADOS_API_HOST"),
83 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
84 ApiInsecure: insecure,
85 Client: &http.Client{Transport: &http.Transport{
86 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
89 if ac.ApiServer == "" {
90 return ac, MissingArvadosApiHost
92 if ac.ApiToken == "" {
93 return ac, MissingArvadosApiToken
99 // Low-level access to a resource.
101 // method - HTTP method, one of GET, HEAD, PUT, POST or DELETE
102 // resource - the arvados resource to act on
103 // uuid - the uuid of the specific item to access (may be empty)
104 // action - sub-action to take on the resource or uuid (may be empty)
105 // parameters - method parameters
108 // reader - the body reader, or nil if there was an error
109 // err - error accessing the resource, or nil if no error
110 func (this ArvadosClient) CallRaw(method string, resource string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
111 var req *http.Request
115 Host: this.ApiServer}
117 u.Path = "/arvados/v1"
120 u.Path = u.Path + "/" + resource
123 u.Path = u.Path + "/" + uuid
126 u.Path = u.Path + "/" + action
129 if parameters == nil {
130 parameters = make(Dict)
133 parameters["format"] = "json"
135 vals := make(url.Values)
136 for k, v := range parameters {
137 m, err := json.Marshal(v)
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", this.ApiToken))
158 req.Header.Add("X-External-Client", "1")
162 var resp *http.Response
163 if resp, err = this.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(this.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 // Access to a resource.
206 // method - HTTP method, one of GET, HEAD, PUT, POST or DELETE
207 // resource - the arvados resource to act on
208 // uuid - the uuid of the specific item to access (may be empty)
209 // action - sub-action to take on the resource or uuid (may be empty)
210 // parameters - method parameters
211 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
213 // err - error accessing the resource, or nil if no error
214 func (this ArvadosClient) Call(method string, resource string, uuid string, action string, parameters Dict, output interface{}) (err error) {
215 var reader io.ReadCloser
216 reader, err = this.CallRaw(method, resource, uuid, action, parameters)
225 dec := json.NewDecoder(reader)
226 if err = dec.Decode(output); err != nil {
233 // Create a new instance of a resource.
235 // resource - the arvados resource on which to create an item
236 // parameters - method parameters
237 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
239 // err - error accessing the resource, or nil if no error
240 func (this ArvadosClient) Create(resource string, parameters Dict, output interface{}) (err error) {
241 return this.Call("POST", resource, "", "", parameters, output)
244 // Delete an instance of a resource.
246 // resource - the arvados resource on which to delete an item
247 // uuid - the item to delete
248 // parameters - method parameters
249 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
251 // err - error accessing the resource, or nil if no error
252 func (this ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
253 return this.Call("DELETE", resource, uuid, "", parameters, output)
256 // Update fields of an instance of a resource.
258 // resource - the arvados resource on which to update the item
259 // uuid - the item to update
260 // parameters - method parameters
261 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
263 // err - error accessing the resource, or nil if no error
264 func (this ArvadosClient) Update(resource string, uuid string, parameters Dict, output interface{}) (err error) {
265 return this.Call("PUT", resource, uuid, "", parameters, output)
268 // List the instances of a resource
270 // resource - the arvados resource on which to list
271 // parameters - method parameters
272 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
274 // err - error accessing the resource, or nil if no error
275 func (this ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
276 return this.Call("GET", resource, "", "", parameters, output)