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 RemoteApiServerError 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 RemoteApiServerError) Error() string {
37 s := fmt.Sprintf("API server (%s) returned %d: %s.",
41 if len(e.ErrorDetails) > 0 {
42 s = fmt.Sprintf("%s Additional details: %s",
44 strings.Join(e.ErrorDetails, "; "))
49 // Helper type so we don't have to write out 'map[string]interface{}' every time.
50 type Dict map[string]interface{}
52 // Information about how to contact the Arvados server
53 type ArvadosClient struct {
54 // Arvados API server, form "host:port"
57 // Arvados API token for authentication
60 // Whether to require a valid SSL certificate or not
63 // Client object shared by client requests. Supports HTTP KeepAlive.
66 // If true, sets the X-External-Client header to indicate
67 // the client is outside the cluster.
71 // Create a new ArvadosClient, initialized with standard Arvados environment
72 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
73 // ARVADOS_API_HOST_INSECURE.
74 func MakeArvadosClient() (ac ArvadosClient, err error) {
75 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
76 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
77 external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
80 ApiServer: os.Getenv("ARVADOS_API_HOST"),
81 ApiToken: os.Getenv("ARVADOS_API_TOKEN"),
82 ApiInsecure: insecure,
83 Client: &http.Client{Transport: &http.Transport{
84 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
87 if ac.ApiServer == "" {
88 return ac, MissingArvadosApiHost
90 if ac.ApiToken == "" {
91 return ac, MissingArvadosApiToken
97 // Low-level access to a resource.
99 // method - HTTP method, one of GET, HEAD, PUT, POST or DELETE
100 // resource - the arvados resource to act on
101 // uuid - the uuid of the specific item to access (may be empty)
102 // action - sub-action to take on the resource or uuid (may be empty)
103 // parameters - method parameters
106 // reader - the body reader, or nil if there was an error
107 // err - error accessing the resource, or nil if no error
108 func (this ArvadosClient) CallRaw(method string, resource string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
109 var req *http.Request
113 Host: this.ApiServer}
115 u.Path = "/arvados/v1"
118 u.Path = u.Path + "/" + resource
121 u.Path = u.Path + "/" + uuid
124 u.Path = u.Path + "/" + action
127 if parameters == nil {
128 parameters = make(Dict)
131 parameters["format"] = "json"
133 vals := make(url.Values)
134 for k, v := range parameters {
135 m, err := json.Marshal(v)
137 vals.Set(k, string(m))
141 if method == "GET" || method == "HEAD" {
142 u.RawQuery = vals.Encode()
143 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
147 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
150 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
153 // Add api token header
154 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.ApiToken))
156 req.Header.Add("X-External-Client", "1")
160 var resp *http.Response
161 if resp, err = this.Client.Do(req); err != nil {
165 if resp.StatusCode == http.StatusOK {
166 return resp.Body, nil
169 defer resp.Body.Close()
170 return nil, NewRemoteApiServerError(this.ApiServer, resp)
173 func NewRemoteApiServerError(ServerAddress string, resp *http.Response) RemoteApiServerError {
175 rase := RemoteApiServerError{
176 ServerAddress: ServerAddress,
177 HttpStatusCode: resp.StatusCode,
178 HttpStatusMessage: resp.Status}
180 // If the response body has {"errors":["reason1","reason2"]}
181 // then return those reasons.
183 if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
184 if errorList, ok := errInfo["errors"]; ok {
185 if errArray, ok := errorList.([]interface{}); ok {
186 for _, errItem := range errArray {
187 // We expect an array of strings here.
188 // Non-strings will be passed along
190 if s, ok := errItem.(string); ok {
191 rase.ErrorDetails = append(rase.ErrorDetails, s)
192 } else if j, err := json.Marshal(errItem); err == nil {
193 rase.ErrorDetails = append(rase.ErrorDetails, string(j))
202 // Access to a resource.
204 // method - HTTP method, one of GET, HEAD, PUT, POST or DELETE
205 // resource - the arvados resource to act on
206 // uuid - the uuid of the specific item to access (may be empty)
207 // action - sub-action to take on the resource or uuid (may be empty)
208 // parameters - method parameters
209 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
211 // err - error accessing the resource, or nil if no error
212 func (this ArvadosClient) Call(method string, resource string, uuid string, action string, parameters Dict, output interface{}) (err error) {
213 var reader io.ReadCloser
214 reader, err = this.CallRaw(method, resource, uuid, action, parameters)
223 dec := json.NewDecoder(reader)
224 if err = dec.Decode(output); err != nil {
231 // Create a new instance of a resource.
233 // resource - the arvados resource on which to create an item
234 // parameters - method parameters
235 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
237 // err - error accessing the resource, or nil if no error
238 func (this ArvadosClient) Create(resource string, parameters Dict, output interface{}) (err error) {
239 return this.Call("POST", resource, "", "", parameters, output)
242 // Delete an instance of a resource.
244 // resource - the arvados resource on which to delete an item
245 // uuid - the item to delete
246 // parameters - method parameters
247 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
249 // err - error accessing the resource, or nil if no error
250 func (this ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
251 return this.Call("DELETE", resource, uuid, "", parameters, output)
254 // Update fields of an instance of a resource.
256 // resource - the arvados resource on which to update the item
257 // uuid - the item to update
258 // parameters - method parameters
259 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
261 // err - error accessing the resource, or nil if no error
262 func (this ArvadosClient) Update(resource string, uuid string, parameters Dict, output interface{}) (err error) {
263 return this.Call("PUT", resource, uuid, "", parameters, output)
266 // List the instances of a resource
268 // resource - the arvados resource on which to list
269 // parameters - method parameters
270 // output - a map or annotated struct which is a legal target for encoding/json/Decoder
272 // err - error accessing the resource, or nil if no error
273 func (this ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
274 return this.Call("GET", resource, "", "", parameters, output)