Debian Codegraph @

rundeck/client.go

raw symbols SCIP
1 // Package rundeck provides a client for interacting with a Rundeck instance
2 // via its HTTP API.
3 //
4 // Instantiate a Client with the NewClient function to get started.
5 //
6 // At present this package uses Rundeck API version 13.
7 package rundeck
8
9 import (
10 "bytes"
11 "crypto/tls"
12 "encoding/xml"
13 "fmt"
14 "io/ioutil"
15 "net/http"
16 "net/url"
17 "mime/multipart"
18 "strings"
19 )
20
21 // ClientConfig is used with NewClient to specify initialization settings.
22 type ClientConfig struct {
23 // The base URL of the Rundeck instance.
24 BaseURL string
25
26 // The API auth token generated from user settings in the Rundeck UI.
27 AuthToken string
28
29 // Don't fail if the server uses SSL with an un-verifiable certificate.
30 // This is not recommended except during development/debugging.
31 AllowUnverifiedSSL bool
32 }
33
34 // Client is a Rundeck API client interface.
35 type Client struct {
36 httpClient *http.Client
37 apiURL *url.URL
38 authToken string
39 }
40
41 type request struct {
42 Method string
43 PathParts []string
44 QueryArgs map[string]string
45 Headers map[string]string
46 BodyBytes []byte
47 }
48
49 // NewClient returns a configured Rundeck client.
50 func NewClient(config *ClientConfig) (*Client, error) {
51 t := &http.Transport{
52 TLSClientConfig: &tls.Config{
53 InsecureSkipVerify: config.AllowUnverifiedSSL,
54 },
55 }
56 httpClient := &http.Client{
57 Transport: t,
58 }
59
60 apiPath, _ := url.Parse("api/13/")
61 baseURL, err := url.Parse(config.BaseURL)
62 if err != nil {
63 return nil, fmt.Errorf("invalid base URL: %s", err.Error())
64 }
65 apiURL := baseURL.ResolveReference(apiPath)
66
67 return &Client{
68 httpClient: httpClient,
69 apiURL: apiURL,
70 authToken: config.AuthToken,
71 }, nil
72 }
73
74 func (c *Client) rawRequest(req *request) ([]byte, error) {
75 res, err := c.httpClient.Do(req.MakeHTTPRequest(c))
76 if err != nil {
77 return nil, err
78 }
79
80 resBodyBytes, err := ioutil.ReadAll(res.Body)
81 if err != nil {
82 return nil, err
83 }
84
85 if res.StatusCode == 404 {
86 return nil, &NotFoundError{}
87 }
88
89 if res.StatusCode < 200 || res.StatusCode >= 300 {
90 if strings.HasPrefix(res.Header.Get("Content-Type"), "text/xml") {
91 var richErr Error
92 err = xml.Unmarshal(resBodyBytes, &richErr)
93 if err != nil {
94 return nil, fmt.Errorf("HTTP Error %i with error decoding XML body: %s", res.StatusCode, err.Error())
95 }
96 return nil, richErr
97 }
98
99 return nil, fmt.Errorf("HTTP Error %i", res.StatusCode)
100 }
101
102 if res.StatusCode != 200 && res.StatusCode != 201 {
103 return nil, nil
104 }
105
106 return resBodyBytes, nil
107 }
108
109 func (c *Client) xmlRequest(method string, pathParts []string, query map[string]string, reqBody interface{}, result interface{}) error {
110
111 var err error
112 var reqBodyBytes []byte
113 reqBodyBytes = nil
114 if reqBody != nil {
115 reqBodyBytes, err = xml.Marshal(reqBody)
116 if err != nil {
117 return err
118 }
119 }
120
121 req := &request{
122 Method: method,
123 PathParts: pathParts,
124 QueryArgs: query,
125 BodyBytes: reqBodyBytes,
126 Headers: map[string]string{
127 "Accept": "application/xml",
128 },
129 }
130
131 if reqBody != nil {
132 req.Headers["Content-Type"] = "application/xml"
133 }
134
135 resBodyBytes, err := c.rawRequest(req)
136 if err != nil {
137 return err
138 }
139
140 if result != nil {
141 if resBodyBytes == nil {
142 return fmt.Errorf("server did not return an XML payload")
143 }
144 err = xml.Unmarshal(resBodyBytes, result)
145 if err != nil {
146 return fmt.Errorf("error decoding response XML payload: %s", err.Error())
147 }
148 }
149
150 return nil
151 }
152
153 func (c *Client) get(pathParts []string, query map[string]string, result interface{}) error {
154 return c.xmlRequest("GET", pathParts, query, nil, result)
155 }
156
157 func (c *Client) rawGet(pathParts []string, query map[string]string, accept string) (string, error) {
158 req := &request{
159 Method: "GET",
160 PathParts: pathParts,
161 QueryArgs: query,
162 Headers: map[string]string{
163 "Accept": accept,
164 },
165 }
166
167 resBodyBytes, err := c.rawRequest(req)
168 if err != nil {
169 return "", err
170 }
171
172 return string(resBodyBytes), nil
173 }
174
175 func (c *Client) post(pathParts []string, query map[string]string, reqBody interface{}, result interface{}) error {
176 return c.xmlRequest("POST", pathParts, query, reqBody, result)
177 }
178
179 func (c *Client) put(pathParts []string, reqBody interface{}, result interface{}) error {
180 return c.xmlRequest("PUT", pathParts, nil, reqBody, result)
181 }
182
183 func (c *Client) delete(pathParts []string) error {
184 return c.xmlRequest("DELETE", pathParts, nil, nil, nil)
185 }
186
187 func (c *Client) postXMLBatch(pathParts []string, args map[string]string, xmlBatch interface{}, result interface{}) error {
188 req := &http.Request{
189 Method: "POST",
190 Header: http.Header{},
191 }
192 req.Header.Add("User-Agent", "Go-Rundeck-API")
193 req.Header.Add("X-Rundeck-Auth-Token", c.authToken)
194
195 urlPath := &url.URL{
196 Path: strings.Join(pathParts, "/"),
197 }
198 reqURL := c.apiURL.ResolveReference(urlPath)
199 req.URL = reqURL
200
201 buf := bytes.Buffer{}
202 writer := multipart.NewWriter(&buf)
203 for k, v := range args {
204 err := writer.WriteField(k, v)
205 if err != nil {
206 return err
207 }
208 }
209 partWriter, err := writer.CreateFormFile("xmlBatch", "batch.xml")
210 if err != nil {
211 return err
212 }
213
214 reqBodyBytes, err := xml.Marshal(xmlBatch)
215 if err != nil {
216 return err
217 }
218
219 _, err = partWriter.Write(reqBodyBytes)
220 if err != nil {
221 return err
222 }
223
224 writer.Close()
225
226 reqBodyReader := bytes.NewReader(buf.Bytes())
227 req.Body = ioutil.NopCloser(reqBodyReader)
228 req.ContentLength = int64(buf.Len())
229 req.Header.Add("Content-Type", writer.FormDataContentType())
230
231 res, err := c.httpClient.Do(req)
232
233 if err != nil {
234 return err
235 }
236
237 resBodyBytes, err := ioutil.ReadAll(res.Body)
238 if err != nil {
239 return err
240 }
241
242 if res.StatusCode < 200 || res.StatusCode >= 300 {
243 if strings.HasPrefix(res.Header.Get("Content-Type"), "text/xml") {
244 var richErr Error
245 err = xml.Unmarshal(resBodyBytes, &richErr)
246 if err != nil {
247 return fmt.Errorf("HTTP Error %i with error decoding XML body: %s", res.StatusCode, err.Error())
248 }
249 return richErr
250 }
251
252 return fmt.Errorf("HTTP Error %i", res.StatusCode)
253 }
254
255 if result != nil {
256 if res.StatusCode != 200 && res.StatusCode != 201 {
257 return fmt.Errorf("server did not return an XML payload")
258 }
259 err = xml.Unmarshal(resBodyBytes, result)
260 if err != nil {
261 return fmt.Errorf("error decoding response XML payload: %s", err.Error())
262 }
263 }
264
265 return nil
266 }
267
268 func (r *request) MakeHTTPRequest(client *Client) *http.Request {
269 req := &http.Request{
270 Method: r.Method,
271 Header: http.Header{},
272 }
273
274 // Automatic/mandatory HTTP headers first
275 req.Header.Add("User-Agent", "Go-Rundeck-API")
276 req.Header.Add("X-Rundeck-Auth-Token", client.authToken)
277
278 for k, v := range r.Headers {
279 req.Header.Add(k, v)
280 }
281
282 urlPath := &url.URL{
283 Path: strings.Join(r.PathParts, "/"),
284 }
285 reqURL := client.apiURL.ResolveReference(urlPath)
286 req.URL = reqURL
287
288 if len(r.QueryArgs) > 0 {
289 urlQuery := url.Values{}
290 for k, v := range r.QueryArgs {
291 urlQuery.Add(k, v)
292 }
293 reqURL.RawQuery = urlQuery.Encode()
294 }
295
296 if r.BodyBytes != nil {
297 req.Body = ioutil.NopCloser(bytes.NewReader(r.BodyBytes))
298 req.ContentLength = int64(len(r.BodyBytes))
299 }
300
301 return req
302 }