Rewrote ArvadosApiError as RemoteApiServerError:
[arvados.git] / sdk / go / arvadosclient / arvadosclient.go
1 /* Simple Arvados Go SDK for communicating with API server. */
2
3 package arvadosclient
4
5 import (
6         "bytes"
7         "crypto/tls"
8         "encoding/json"
9         "errors"
10         "fmt"
11         "io"
12         "net/http"
13         "net/url"
14         "os"
15         "regexp"
16         "strings"
17 )
18
19 // Errors
20 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
21 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
22
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".
26         ServerAddress string
27
28         // Components of server response.
29         HttpStatusCode    int
30         HttpStatusMessage string
31
32         // Additional error details from response body
33         ErrorDetails []string
34 }
35
36 func (e RemoteApiServerError) Error() string {
37         s := fmt.Sprintf("API server (%s) returned %d: %s.",
38                 e.ServerAddress,
39                 e.HttpStatusCode,
40                 e.HttpStatusMessage)
41         if len(e.ErrorDetails) > 0 {
42                 s = fmt.Sprintf("%s Additional details: %s",
43                         s,
44                         strings.Join(e.ErrorDetails, "; "))
45         }
46         return s
47 }
48
49 // Helper type so we don't have to write out 'map[string]interface{}' every time.
50 type Dict map[string]interface{}
51
52 // Information about how to contact the Arvados server
53 type ArvadosClient struct {
54         // Arvados API server, form "host:port"
55         ApiServer string
56
57         // Arvados API token for authentication
58         ApiToken string
59
60         // Whether to require a valid SSL certificate or not
61         ApiInsecure bool
62
63         // Client object shared by client requests.  Supports HTTP KeepAlive.
64         Client *http.Client
65
66         // If true, sets the X-External-Client header to indicate
67         // the client is outside the cluster.
68         External bool
69 }
70
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"))
78
79         ac = ArvadosClient{
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}}},
85                 External: external}
86
87         if ac.ApiServer == "" {
88                 return ac, MissingArvadosApiHost
89         }
90         if ac.ApiToken == "" {
91                 return ac, MissingArvadosApiToken
92         }
93
94         return ac, err
95 }
96
97 // Low-level access to a resource.
98 //
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
104 //
105 // return
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
110
111         u := url.URL{
112                 Scheme: "https",
113                 Host:   this.ApiServer}
114
115         u.Path = "/arvados/v1"
116
117         if resource != "" {
118                 u.Path = u.Path + "/" + resource
119         }
120         if uuid != "" {
121                 u.Path = u.Path + "/" + uuid
122         }
123         if action != "" {
124                 u.Path = u.Path + "/" + action
125         }
126
127         if parameters == nil {
128                 parameters = make(Dict)
129         }
130
131         parameters["format"] = "json"
132
133         vals := make(url.Values)
134         for k, v := range parameters {
135                 m, err := json.Marshal(v)
136                 if err == nil {
137                         vals.Set(k, string(m))
138                 }
139         }
140
141         if method == "GET" || method == "HEAD" {
142                 u.RawQuery = vals.Encode()
143                 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
144                         return nil, err
145                 }
146         } else {
147                 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
148                         return nil, err
149                 }
150                 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
151         }
152
153         // Add api token header
154         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.ApiToken))
155         if this.External {
156                 req.Header.Add("X-External-Client", "1")
157         }
158
159         // Make the request
160         var resp *http.Response
161         if resp, err = this.Client.Do(req); err != nil {
162                 return nil, err
163         }
164
165         if resp.StatusCode == http.StatusOK {
166                 return resp.Body, nil
167         }
168
169         defer resp.Body.Close()
170         return nil, NewRemoteApiServerError(this.ApiServer, resp)
171 }
172
173 func NewRemoteApiServerError(ServerAddress string, resp *http.Response) RemoteApiServerError {
174
175         rase := RemoteApiServerError{
176                 ServerAddress:     ServerAddress,
177                 HttpStatusCode:    resp.StatusCode,
178                 HttpStatusMessage: resp.Status}
179
180         // If the response body has {"errors":["reason1","reason2"]}
181         // then return those reasons.
182         var errInfo = Dict{}
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
189                                         // JSON-encoded.
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))
194                                         }
195                                 }
196                         }
197                 }
198         }
199         return rase
200 }
201
202 // Access to a resource.
203 //
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
210 // return
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)
215         if reader != nil {
216                 defer reader.Close()
217         }
218         if err != nil {
219                 return err
220         }
221
222         if output != nil {
223                 dec := json.NewDecoder(reader)
224                 if err = dec.Decode(output); err != nil {
225                         return err
226                 }
227         }
228         return nil
229 }
230
231 // Create a new instance of a resource.
232 //
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
236 // return
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)
240 }
241
242 // Delete an instance of a resource.
243 //
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
248 // return
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)
252 }
253
254 // Update fields of an instance of a resource.
255 //
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
260 // return
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)
264 }
265
266 // List the instances of a resource
267 //
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
271 // return
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)
275 }