3198: Fix Operation(inode_cache) init. Break up tests into a few smaller
[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 type ArvadosApiError struct {
24         error
25         HttpStatusCode int
26         HttpStatus string
27 }
28
29 func (e ArvadosApiError) Error() string { return e.error.Error() }
30
31 // Helper type so we don't have to write out 'map[string]interface{}' every time.
32 type Dict map[string]interface{}
33
34 // Information about how to contact the Arvados server
35 type ArvadosClient struct {
36         // Arvados API server, form "host:port"
37         ApiServer string
38
39         // Arvados API token for authentication
40         ApiToken string
41
42         // Whether to require a valid SSL certificate or not
43         ApiInsecure bool
44
45         // Client object shared by client requests.  Supports HTTP KeepAlive.
46         Client *http.Client
47
48         // If true, sets the X-External-Client header to indicate
49         // the client is outside the cluster.
50         External bool
51 }
52
53 // Create a new KeepClient, initialized with standard Arvados environment
54 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
55 // ARVADOS_API_HOST_INSECURE.
56 func MakeArvadosClient() (kc ArvadosClient, err error) {
57         var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
58         insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
59         external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
60
61         kc = ArvadosClient{
62                 ApiServer:   os.Getenv("ARVADOS_API_HOST"),
63                 ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
64                 ApiInsecure: insecure,
65                 Client: &http.Client{Transport: &http.Transport{
66                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
67                 External: external}
68
69         if kc.ApiServer == "" {
70                 return kc, MissingArvadosApiHost
71         }
72         if kc.ApiToken == "" {
73                 return kc, MissingArvadosApiToken
74         }
75
76         return kc, err
77 }
78
79 // Low-level access to a resource.
80 //
81 //   method - HTTP method, one of GET, HEAD, PUT, POST or DELETE
82 //   resource - the arvados resource to act on
83 //   uuid - the uuid of the specific item to access (may be empty)
84 //   action - sub-action to take on the resource or uuid (may be empty)
85 //   parameters - method parameters
86 //
87 // return
88 //   reader - the body reader, or nil if there was an error
89 //   err - error accessing the resource, or nil if no error
90 func (this ArvadosClient) CallRaw(method string, resource string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
91         var req *http.Request
92
93         u := url.URL{
94                 Scheme: "https",
95                 Host:   this.ApiServer}
96
97         u.Path = "/arvados/v1"
98
99         if resource != "" {
100                 u.Path = u.Path + "/" + resource
101         }
102         if uuid != "" {
103                 u.Path = u.Path + "/" + uuid
104         }
105         if action != "" {
106                 u.Path = u.Path + "/" + action
107         }
108
109         if parameters == nil {
110                 parameters = make(Dict)
111         }
112
113         parameters["format"] = "json"
114
115         vals := make(url.Values)
116         for k, v := range parameters {
117                 m, err := json.Marshal(v)
118                 if err == nil {
119                         vals.Set(k, string(m))
120                 }
121         }
122
123         if method == "GET" || method == "HEAD" {
124                 u.RawQuery = vals.Encode()
125                 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
126                         return nil, err
127                 }
128         } else {
129                 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
130                         return nil, err
131                 }
132                 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
133         }
134
135         // Add api token header
136         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.ApiToken))
137         if this.External {
138                 req.Header.Add("X-External-Client", "1")
139         }
140
141         // Make the request
142         var resp *http.Response
143         if resp, err = this.Client.Do(req); err != nil {
144                 return nil, err
145         }
146
147         if resp.StatusCode == http.StatusOK {
148                 return resp.Body, nil
149         }
150
151         defer resp.Body.Close()
152         errorText := fmt.Sprintf("API response: %s", resp.Status)
153
154         // If the response body has {"errors":["reason1","reason2"]}
155         // then return those reasons.
156         var errInfo = Dict{}
157         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
158                 if errorList, ok := errInfo["errors"]; ok {
159                         var errorStrings []string
160                         if errArray, ok := errorList.([]interface{}); ok {
161                                 for _, errItem := range errArray {
162                                         // We expect an array of strings here.
163                                         // Non-strings will be passed along
164                                         // JSON-encoded.
165                                         if s, ok := errItem.(string); ok {
166                                                 errorStrings = append(errorStrings, s)
167                                         } else if j, err := json.Marshal(errItem); err == nil {
168                                                 errorStrings = append(errorStrings, string(j))
169                                         }
170                                 }
171                                 errorText = strings.Join(errorStrings, "; ")
172                         }
173                 }
174         }
175         return nil, ArvadosApiError{errors.New(errorText), resp.StatusCode, resp.Status}
176 }
177
178 // Access to a resource.
179 //
180 //   method - HTTP method, one of GET, HEAD, PUT, POST or DELETE
181 //   resource - the arvados resource to act on
182 //   uuid - the uuid of the specific item to access (may be empty)
183 //   action - sub-action to take on the resource or uuid (may be empty)
184 //   parameters - method parameters
185 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder
186 // return
187 //   err - error accessing the resource, or nil if no error
188 func (this ArvadosClient) Call(method string, resource string, uuid string, action string, parameters Dict, output interface{}) (err error) {
189         var reader io.ReadCloser
190         reader, err = this.CallRaw(method, resource, uuid, action, parameters)
191         if reader != nil {
192                 defer reader.Close()
193         }
194         if err != nil {
195                 return err
196         }
197
198         if output != nil {
199                 dec := json.NewDecoder(reader)
200                 if err = dec.Decode(output); err != nil {
201                         return err
202                 }
203         }
204         return nil
205 }
206
207 // Create a new instance of a resource.
208 //
209 //   resource - the arvados resource on which to create an item
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) Create(resource string, parameters Dict, output interface{}) (err error) {
215         return this.Call("POST", resource, "", "", parameters, output)
216 }
217
218 // Delete an instance of a resource.
219 //
220 //   resource - the arvados resource on which to delete an item
221 //   uuid - the item to delete
222 //   parameters - method parameters
223 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder
224 // return
225 //   err - error accessing the resource, or nil if no error
226 func (this ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
227         return this.Call("DELETE", resource, uuid, "", parameters, output)
228 }
229
230 // Update fields of an instance of a resource.
231 //
232 //   resource - the arvados resource on which to update the item
233 //   uuid - the item to update
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) Update(resource string, uuid string, parameters Dict, output interface{}) (err error) {
239         return this.Call("PUT", resource, uuid, "", parameters, output)
240 }
241
242 // List the instances of a resource
243 //
244 //   resource - the arvados resource on which to list
245 //   parameters - method parameters
246 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder
247 // return
248 //   err - error accessing the resource, or nil if no error
249 func (this ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
250         return this.Call("GET", resource, "", "", parameters, output)
251 }