Merge branch '3145-close-early' closes #3145
[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 APIServerError 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 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, "; "),
40                         e.HttpStatusCode,
41                         e.HttpStatusMessage,
42                         e.ServerAddress)
43         } else {
44                 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
45                         e.HttpStatusCode,
46                         e.HttpStatusMessage,
47                         e.ServerAddress)
48         }
49 }
50
51 // Helper type so we don't have to write out 'map[string]interface{}' every time.
52 type Dict map[string]interface{}
53
54 // Information about how to contact the Arvados server
55 type ArvadosClient struct {
56         // Arvados API server, form "host:port"
57         ApiServer string
58
59         // Arvados API token for authentication
60         ApiToken string
61
62         // Whether to require a valid SSL certificate or not
63         ApiInsecure bool
64
65         // Client object shared by client requests.  Supports HTTP KeepAlive.
66         Client *http.Client
67
68         // If true, sets the X-External-Client header to indicate
69         // the client is outside the cluster.
70         External bool
71 }
72
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"))
80
81         ac = ArvadosClient{
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}}},
87                 External: external}
88
89         if ac.ApiServer == "" {
90                 return ac, MissingArvadosApiHost
91         }
92         if ac.ApiToken == "" {
93                 return ac, MissingArvadosApiToken
94         }
95
96         return ac, err
97 }
98
99 // Low-level access to a resource.
100 //
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
106 //
107 // return
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
112
113         u := url.URL{
114                 Scheme: "https",
115                 Host:   this.ApiServer}
116
117         u.Path = "/arvados/v1"
118
119         if resource != "" {
120                 u.Path = u.Path + "/" + resource
121         }
122         if uuid != "" {
123                 u.Path = u.Path + "/" + uuid
124         }
125         if action != "" {
126                 u.Path = u.Path + "/" + action
127         }
128
129         if parameters == nil {
130                 parameters = make(Dict)
131         }
132
133         parameters["format"] = "json"
134
135         vals := make(url.Values)
136         for k, v := range parameters {
137                 m, err := json.Marshal(v)
138                 if err == nil {
139                         vals.Set(k, string(m))
140                 }
141         }
142
143         if method == "GET" || method == "HEAD" {
144                 u.RawQuery = vals.Encode()
145                 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
146                         return nil, err
147                 }
148         } else {
149                 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
150                         return nil, err
151                 }
152                 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
153         }
154
155         // Add api token header
156         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.ApiToken))
157         if this.External {
158                 req.Header.Add("X-External-Client", "1")
159         }
160
161         // Make the request
162         var resp *http.Response
163         if resp, err = this.Client.Do(req); err != nil {
164                 return nil, err
165         }
166
167         if resp.StatusCode == http.StatusOK {
168                 return resp.Body, nil
169         }
170
171         defer resp.Body.Close()
172         return nil, newAPIServerError(this.ApiServer, resp)
173 }
174
175 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
176
177         ase := APIServerError{
178                 ServerAddress:     ServerAddress,
179                 HttpStatusCode:    resp.StatusCode,
180                 HttpStatusMessage: resp.Status}
181
182         // If the response body has {"errors":["reason1","reason2"]}
183         // then return those reasons.
184         var errInfo = Dict{}
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
191                                         // JSON-encoded.
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))
196                                         }
197                                 }
198                         }
199                 }
200         }
201         return ase
202 }
203
204 // Access to a resource.
205 //
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
212 // return
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)
217         if reader != nil {
218                 defer reader.Close()
219         }
220         if err != nil {
221                 return err
222         }
223
224         if output != nil {
225                 dec := json.NewDecoder(reader)
226                 if err = dec.Decode(output); err != nil {
227                         return err
228                 }
229         }
230         return nil
231 }
232
233 // Create a new instance of a resource.
234 //
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
238 // return
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)
242 }
243
244 // Delete an instance of a resource.
245 //
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
250 // return
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)
254 }
255
256 // Update fields of an instance of a resource.
257 //
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
262 // return
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)
266 }
267
268 // List the instances of a resource
269 //
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
273 // return
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)
277 }