7167: loadConfig setupKeepclient do only one set at a time.
[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 type StringMatcher func(string) bool
20
21 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
22 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
23
24 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
25 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
26 var ErrInvalidArgument = errors.New("Invalid argument")
27
28 // Indicates an error that was returned by the API server.
29 type APIServerError struct {
30         // Address of server returning error, of the form "host:port".
31         ServerAddress string
32
33         // Components of server response.
34         HttpStatusCode    int
35         HttpStatusMessage string
36
37         // Additional error details from response body.
38         ErrorDetails []string
39 }
40
41 func (e APIServerError) Error() string {
42         if len(e.ErrorDetails) > 0 {
43                 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
44                         strings.Join(e.ErrorDetails, "; "),
45                         e.HttpStatusCode,
46                         e.HttpStatusMessage,
47                         e.ServerAddress)
48         } else {
49                 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
50                         e.HttpStatusCode,
51                         e.HttpStatusMessage,
52                         e.ServerAddress)
53         }
54 }
55
56 // Helper type so we don't have to write out 'map[string]interface{}' every time.
57 type Dict map[string]interface{}
58
59 // Information about how to contact the Arvados server
60 type ArvadosClient struct {
61         // Arvados API server, form "host:port"
62         ApiServer string
63
64         // Arvados API token for authentication
65         ApiToken string
66
67         // Whether to require a valid SSL certificate or not
68         ApiInsecure bool
69
70         // Client object shared by client requests.  Supports HTTP KeepAlive.
71         Client *http.Client
72
73         // If true, sets the X-External-Client header to indicate
74         // the client is outside the cluster.
75         External bool
76
77         // Discovery document
78         DiscoveryDoc Dict
79 }
80
81 // Create a new ArvadosClient, initialized with standard Arvados environment
82 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
83 // ARVADOS_API_HOST_INSECURE.
84 func MakeArvadosClient() (ac ArvadosClient, err error) {
85         var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
86         insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
87         external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
88
89         ac = ArvadosClient{
90                 ApiServer:   os.Getenv("ARVADOS_API_HOST"),
91                 ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
92                 ApiInsecure: insecure,
93                 Client: &http.Client{Transport: &http.Transport{
94                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
95                 External: external}
96
97         if ac.ApiServer == "" {
98                 return ac, MissingArvadosApiHost
99         }
100         if ac.ApiToken == "" {
101                 return ac, MissingArvadosApiToken
102         }
103
104         return ac, err
105 }
106
107 // CallRaw is the same as Call() but returns a Reader that reads the
108 // response body, instead of taking an output object.
109 func (c ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
110         var req *http.Request
111
112         u := url.URL{
113                 Scheme: "https",
114                 Host:   c.ApiServer}
115
116         if resourceType != API_DISCOVERY_RESOURCE {
117                 u.Path = "/arvados/v1"
118         }
119
120         if resourceType != "" {
121                 u.Path = u.Path + "/" + resourceType
122         }
123         if uuid != "" {
124                 u.Path = u.Path + "/" + uuid
125         }
126         if action != "" {
127                 u.Path = u.Path + "/" + action
128         }
129
130         if parameters == nil {
131                 parameters = make(Dict)
132         }
133
134         vals := make(url.Values)
135         for k, v := range parameters {
136                 if s, ok := v.(string); ok {
137                         vals.Set(k, s)
138                 } else if m, err := json.Marshal(v); 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", c.ApiToken))
157         if c.External {
158                 req.Header.Add("X-External-Client", "1")
159         }
160
161         // Make the request
162         var resp *http.Response
163         if resp, err = c.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(c.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 // Call an API endpoint and parse the JSON response into an object.
205 //
206 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
207 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
208 //   uuid - the uuid of the specific item to access. May be empty.
209 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
210 //   parameters - method parameters.
211 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
212 //
213 // Returns a non-nil error if an error occurs making the API call, the
214 // API responds with a non-successful HTTP status, or an error occurs
215 // parsing the response body.
216 func (c ArvadosClient) Call(method string, resourceType string, uuid string, action string, parameters Dict, output interface{}) error {
217         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
218         if reader != nil {
219                 defer reader.Close()
220         }
221         if err != nil {
222                 return err
223         }
224
225         if output != nil {
226                 dec := json.NewDecoder(reader)
227                 if err = dec.Decode(output); err != nil {
228                         return err
229                 }
230         }
231         return nil
232 }
233
234 // Create a new resource. See Call for argument descriptions.
235 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
236         return c.Call("POST", resourceType, "", "", parameters, output)
237 }
238
239 // Delete a resource. See Call for argument descriptions.
240 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
241         return c.Call("DELETE", resource, uuid, "", parameters, output)
242 }
243
244 // Modify attributes of a resource. See Call for argument descriptions.
245 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
246         return c.Call("PUT", resourceType, uuid, "", parameters, output)
247 }
248
249 // Get a resource. See Call for argument descriptions.
250 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
251         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
252                 // No object has uuid == "": there is no need to make
253                 // an API call. Furthermore, the HTTP request for such
254                 // an API call would be "GET /arvados/v1/type/", which
255                 // is liable to be misinterpreted as the List API.
256                 return ErrInvalidArgument
257         }
258         return c.Call("GET", resourceType, uuid, "", parameters, output)
259 }
260
261 // List resources of a given type. See Call for argument descriptions.
262 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
263         return c.Call("GET", resource, "", "", parameters, output)
264 }
265
266 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
267
268 // Discovery returns the value of the given parameter in the discovery
269 // document. Returns a non-nil error if the discovery document cannot
270 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
271 // parameter is not found in the discovery document.
272 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
273         if len(c.DiscoveryDoc) == 0 {
274                 c.DiscoveryDoc = make(Dict)
275                 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
276                 if err != nil {
277                         return nil, err
278                 }
279         }
280
281         var found bool
282         value, found = c.DiscoveryDoc[parameter]
283         if found {
284                 return value, nil
285         } else {
286                 return value, ErrInvalidArgument
287         }
288 }