File: client.go

package info (click to toggle)
golang-github-apparentlymart-go-rundeck-api 0.0.1%2Bgit20170705.2c962ac-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 120 kB
  • sloc: makefile: 2
file content (302 lines) | stat: -rw-r--r-- 6,989 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// Package rundeck provides a client for interacting with a Rundeck instance
// via its HTTP API.
//
// Instantiate a Client with the NewClient function to get started.
//
// At present this package uses Rundeck API version 13.
package rundeck

import (
	"bytes"
	"crypto/tls"
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"mime/multipart"
	"strings"
)

// ClientConfig is used with NewClient to specify initialization settings.
type ClientConfig struct {
	// The base URL of the Rundeck instance.
	BaseURL string

	// The API auth token generated from user settings in the Rundeck UI.
	AuthToken string

	// Don't fail if the server uses SSL with an un-verifiable certificate.
	// This is not recommended except during development/debugging.
	AllowUnverifiedSSL bool
}

// Client is a Rundeck API client interface.
type Client struct {
	httpClient *http.Client
	apiURL     *url.URL
	authToken  string
}

type request struct {
	Method string
	PathParts []string
	QueryArgs map[string]string
	Headers map[string]string
	BodyBytes []byte
}

// NewClient returns a configured Rundeck client.
func NewClient(config *ClientConfig) (*Client, error) {
	t := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: config.AllowUnverifiedSSL,
		},
	}
	httpClient := &http.Client{
		Transport: t,
	}

	apiPath, _ := url.Parse("api/13/")
	baseURL, err := url.Parse(config.BaseURL)
	if err != nil {
		return nil, fmt.Errorf("invalid base URL: %s", err.Error())
	}
	apiURL := baseURL.ResolveReference(apiPath)

	return &Client{
		httpClient: httpClient,
		apiURL:     apiURL,
		authToken:  config.AuthToken,
	}, nil
}

func (c *Client) rawRequest(req *request) ([]byte, error) {
	res, err := c.httpClient.Do(req.MakeHTTPRequest(c))
	if err != nil {
		return nil, err
	}

	resBodyBytes, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	if res.StatusCode == 404 {
		return nil, &NotFoundError{}
	}

	if res.StatusCode < 200 || res.StatusCode >= 300 {
		if strings.HasPrefix(res.Header.Get("Content-Type"), "text/xml") {
			var richErr Error
			err = xml.Unmarshal(resBodyBytes, &richErr)
			if err != nil {
				return nil, fmt.Errorf("HTTP Error %i with error decoding XML body: %s", res.StatusCode, err.Error())
			}
			return nil, richErr
		}

		return nil, fmt.Errorf("HTTP Error %i", res.StatusCode)
	}

	if res.StatusCode != 200 && res.StatusCode != 201 {
		return nil, nil
	}

	return resBodyBytes, nil
}

func (c *Client) xmlRequest(method string, pathParts []string, query map[string]string, reqBody interface{}, result interface{}) error {

	var err error
	var reqBodyBytes []byte
	reqBodyBytes = nil
	if reqBody != nil {
		reqBodyBytes, err = xml.Marshal(reqBody)
		if err != nil {
			return err
		}
	}

	req := &request{
		Method: method,
		PathParts: pathParts,
		QueryArgs: query,
		BodyBytes: reqBodyBytes,
		Headers: map[string]string{
			"Accept": "application/xml",
		},
	}

	if reqBody != nil {
		req.Headers["Content-Type"] = "application/xml"
	}

	resBodyBytes, err := c.rawRequest(req)
	if err != nil {
		return err
	}

	if result != nil {
		if resBodyBytes == nil {
			return fmt.Errorf("server did not return an XML payload")
		}
		err = xml.Unmarshal(resBodyBytes, result)
		if err != nil {
			return fmt.Errorf("error decoding response XML payload: %s", err.Error())
		}
	}

	return nil
}

func (c *Client) get(pathParts []string, query map[string]string, result interface{}) error {
	return c.xmlRequest("GET", pathParts, query, nil, result)
}

func (c *Client) rawGet(pathParts []string, query map[string]string, accept string) (string, error) {
	req := &request{
		Method: "GET",
		PathParts: pathParts,
		QueryArgs: query,
		Headers: map[string]string{
			"Accept": accept,
		},
	}

	resBodyBytes, err := c.rawRequest(req)
	if err != nil {
		return "", err
	}

	return string(resBodyBytes), nil
}

func (c *Client) post(pathParts []string, query map[string]string, reqBody interface{}, result interface{}) error {
	return c.xmlRequest("POST", pathParts, query, reqBody, result)
}

func (c *Client) put(pathParts []string, reqBody interface{}, result interface{}) error {
	return c.xmlRequest("PUT", pathParts, nil, reqBody, result)
}

func (c *Client) delete(pathParts []string) error {
	return c.xmlRequest("DELETE", pathParts, nil, nil, nil)
}

func (c *Client) postXMLBatch(pathParts []string, args map[string]string, xmlBatch interface{}, result interface{}) error {
	req := &http.Request{
		Method: "POST",
		Header: http.Header{},
	}
	req.Header.Add("User-Agent", "Go-Rundeck-API")
	req.Header.Add("X-Rundeck-Auth-Token", c.authToken)

	urlPath := &url.URL{
		Path: strings.Join(pathParts, "/"),
	}
	reqURL := c.apiURL.ResolveReference(urlPath)
	req.URL = reqURL

	buf := bytes.Buffer{}
	writer := multipart.NewWriter(&buf)
	for k, v := range args {
		err := writer.WriteField(k, v)
		if err != nil {
			return err
		}
	}
	partWriter, err := writer.CreateFormFile("xmlBatch", "batch.xml")
	if err != nil {
		return err
	}

	reqBodyBytes, err := xml.Marshal(xmlBatch)
	if err != nil {
		return err
	}

	_, err = partWriter.Write(reqBodyBytes)
	if err != nil {
		return err
	}

	writer.Close()

	reqBodyReader := bytes.NewReader(buf.Bytes())
	req.Body = ioutil.NopCloser(reqBodyReader)
	req.ContentLength = int64(buf.Len())
	req.Header.Add("Content-Type", writer.FormDataContentType())

	res, err := c.httpClient.Do(req)

	if err != nil {
		return err
	}

	resBodyBytes, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return err
	}

	if res.StatusCode < 200 || res.StatusCode >= 300 {
		if strings.HasPrefix(res.Header.Get("Content-Type"), "text/xml") {
			var richErr Error
			err = xml.Unmarshal(resBodyBytes, &richErr)
			if err != nil {
				return fmt.Errorf("HTTP Error %i with error decoding XML body: %s", res.StatusCode, err.Error())
			}
			return richErr
		}

		return fmt.Errorf("HTTP Error %i", res.StatusCode)
	}

	if result != nil {
		if res.StatusCode != 200 && res.StatusCode != 201 {
			return fmt.Errorf("server did not return an XML payload")
		}
		err = xml.Unmarshal(resBodyBytes, result)
		if err != nil {
			return fmt.Errorf("error decoding response XML payload: %s", err.Error())
		}
	}

	return nil
}

func (r *request) MakeHTTPRequest(client *Client) *http.Request {
	req := &http.Request{
		Method: r.Method,
		Header: http.Header{},
	}

	// Automatic/mandatory HTTP headers first
	req.Header.Add("User-Agent", "Go-Rundeck-API")
	req.Header.Add("X-Rundeck-Auth-Token", client.authToken)

	for k, v := range r.Headers {
		req.Header.Add(k, v)
	}

	urlPath := &url.URL{
		Path: strings.Join(r.PathParts, "/"),
	}
	reqURL := client.apiURL.ResolveReference(urlPath)
	req.URL = reqURL

	if len(r.QueryArgs) > 0 {
		urlQuery := url.Values{}
		for k, v := range r.QueryArgs {
			urlQuery.Add(k, v)
		}
		reqURL.RawQuery = urlQuery.Encode()
	}

	if r.BodyBytes != nil {
		req.Body = ioutil.NopCloser(bytes.NewReader(r.BodyBytes))
		req.ContentLength = int64(len(r.BodyBytes))
	}

	return req
}