Fix repositories.get_all_permissions, add tests. closes #3546
[arvados.git] / sdk / go / src / arvados.org / sdk / sdk.go
1 /* Simple Arvados Go SDK for communicating with API server. */
2
3 package sdk
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 )
16
17 // Errors
18 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
19 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
20 var ArvadosErrorForbidden = errors.New("Forbidden")
21 var ArvadosErrorNotFound = errors.New("Not found")
22 var ArvadosErrorBadRequest = errors.New("Bad request")
23 var ArvadosErrorServerError = errors.New("Server error")
24
25 // Helper type so we don't have to write out 'map[string]interface{}' every time.
26 type Dict map[string]interface{}
27
28 // Information about how to contact the Arvados server
29 type ArvadosClient struct {
30         // Arvados API server, form "host:port"
31         ApiServer string
32
33         // Arvados API token for authentication
34         ApiToken string
35
36         // Whether to require a valid SSL certificate or not
37         ApiInsecure bool
38
39         // Client object shared by client requests.  Supports HTTP KeepAlive.
40         Client *http.Client
41
42         // If true, sets the X-External-Client header to indicate
43         // the client is outside the cluster.
44         External bool
45 }
46
47 // Create a new KeepClient, initialized with standard Arvados environment
48 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
49 // ARVADOS_API_HOST_INSECURE.
50 func MakeArvadosClient() (kc ArvadosClient, err error) {
51         insecure := (os.Getenv("ARVADOS_API_HOST_INSECURE") == "true")
52         external := (os.Getenv("ARVADOS_EXTERNAL_CLIENT") == "true")
53
54         kc = ArvadosClient{
55                 ApiServer:   os.Getenv("ARVADOS_API_HOST"),
56                 ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
57                 ApiInsecure: insecure,
58                 Client: &http.Client{Transport: &http.Transport{
59                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
60                 External: external}
61
62         if os.Getenv("ARVADOS_API_HOST") == "" {
63                 return kc, MissingArvadosApiHost
64         }
65         if os.Getenv("ARVADOS_API_TOKEN") == "" {
66                 return kc, MissingArvadosApiToken
67         }
68
69         return kc, err
70 }
71
72 // Low-level access to a resource.
73 //
74 //   method - HTTP method, one of GET, HEAD, PUT, POST or DELETE
75 //   resource - the arvados resource to act on
76 //   uuid - the uuid of the specific item to access (may be empty)
77 //   action - sub-action to take on the resource or uuid (may be empty)
78 //   parameters - method parameters
79 //
80 // return
81 //   reader - the body reader, or nil if there was an error
82 //   err - error accessing the resource, or nil if no error
83 func (this ArvadosClient) CallRaw(method string, resource string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
84         var req *http.Request
85
86         u := url.URL{
87                 Scheme: "https",
88                 Host:   this.ApiServer}
89
90         u.Path = "/arvados/v1"
91
92         if resource != "" {
93                 u.Path = u.Path + "/" + resource
94         }
95         if uuid != "" {
96                 u.Path = u.Path + "/" + uuid
97         }
98         if action != "" {
99                 u.Path = u.Path + "/" + action
100         }
101
102         if parameters == nil {
103                 parameters = make(Dict)
104         }
105
106         parameters["format"] = "json"
107
108         vals := make(url.Values)
109         for k, v := range parameters {
110                 m, err := json.Marshal(v)
111                 if err == nil {
112                         vals.Set(k, string(m))
113                 }
114         }
115
116         if method == "GET" || method == "HEAD" {
117                 u.RawQuery = vals.Encode()
118                 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
119                         return nil, err
120                 }
121         } else {
122                 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
123                         return nil, err
124                 }
125                 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
126         }
127
128         // Add api token header
129         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.ApiToken))
130         if this.External {
131                 req.Header.Add("X-External-Client", "1")
132         }
133
134         // Make the request
135         var resp *http.Response
136         if resp, err = this.Client.Do(req); err != nil {
137                 return nil, err
138         }
139
140         switch resp.StatusCode {
141         case http.StatusOK:
142                 return resp.Body, nil
143         case http.StatusForbidden:
144                 resp.Body.Close()
145                 return nil, ArvadosErrorForbidden
146         case http.StatusNotFound:
147                 resp.Body.Close()
148                 return nil, ArvadosErrorNotFound
149         default:
150                 resp.Body.Close()
151                 if resp.StatusCode >= 400 && resp.StatusCode <= 499 {
152                         return nil, ArvadosErrorBadRequest
153                 } else {
154                         return nil, ArvadosErrorServerError
155                 }
156         }
157 }
158
159 // Access to a resource.
160 //
161 //   method - HTTP method, one of GET, HEAD, PUT, POST or DELETE
162 //   resource - the arvados resource to act on
163 //   uuid - the uuid of the specific item to access (may be empty)
164 //   action - sub-action to take on the resource or uuid (may be empty)
165 //   parameters - method parameters
166 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder
167 // return
168 //   err - error accessing the resource, or nil if no error
169 func (this ArvadosClient) Call(method string, resource string, uuid string, action string, parameters Dict, output interface{}) (err error) {
170         var reader io.ReadCloser
171         reader, err = this.CallRaw(method, resource, uuid, action, parameters)
172         if reader != nil {
173                 defer reader.Close()
174         }
175         if err != nil {
176                 return err
177         }
178
179         if output != nil {
180                 dec := json.NewDecoder(reader)
181                 if err = dec.Decode(output); err != nil {
182                         return err
183                 }
184         }
185         return nil
186 }
187
188 // Create a new instance of a resource.
189 //
190 //   resource - the arvados resource on which to create an item
191 //   parameters - method parameters
192 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder
193 // return
194 //   err - error accessing the resource, or nil if no error
195 func (this ArvadosClient) Create(resource string, parameters Dict, output interface{}) (err error) {
196         return this.Call("POST", resource, "", "", parameters, output)
197 }
198
199 // Delete an instance of a resource.
200 //
201 //   resource - the arvados resource on which to delete an item
202 //   uuid - the item to delete
203 //   parameters - method parameters
204 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder
205 // return
206 //   err - error accessing the resource, or nil if no error
207 func (this ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
208         return this.Call("DELETE", resource, uuid, "", parameters, output)
209 }
210
211 // Update fields of an instance of a resource.
212 //
213 //   resource - the arvados resource on which to update the item
214 //   uuid - the item to update
215 //   parameters - method parameters
216 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder
217 // return
218 //   err - error accessing the resource, or nil if no error
219 func (this ArvadosClient) Update(resource string, uuid string, parameters Dict, output interface{}) (err error) {
220         return this.Call("PUT", resource, uuid, "", parameters, output)
221 }
222
223 // List the instances of a resource
224 //
225 //   resource - the arvados resource on which to list
226 //   parameters - method parameters
227 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder
228 // return
229 //   err - error accessing the resource, or nil if no error
230 func (this ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
231         return this.Call("GET", resource, "", "", parameters, output)
232 }