-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathjenkins.go
385 lines (320 loc) · 9.48 KB
/
jenkins.go
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package gojenkins
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
)
type HTTPStatusError struct {
URL string
Code int
Status string
}
func (e *HTTPStatusError) Error() string {
return fmt.Sprintf("bad http status: %d: %s", e.Code, e.Status)
}
type Auth struct {
Username string
ApiToken string
}
type Jenkins struct {
auth *Auth
baseUrl string
client *http.Client
}
func NewJenkins(auth *Auth, baseUrl string) *Jenkins {
return &Jenkins{
auth: auth,
baseUrl: baseUrl,
client: http.DefaultClient,
}
}
// SetHTTPClient with timeouts or insecure transport, etc.
func (jenkins *Jenkins) SetHTTPClient(client *http.Client) {
jenkins.client = client
}
func (jenkins *Jenkins) buildUrl(path string, params url.Values) (requestUrl string) {
requestUrl = jenkins.baseUrl + path + "/api/json"
if params != nil {
queryString := params.Encode()
if queryString != "" {
requestUrl = requestUrl + "?" + queryString
}
}
return
}
// checkCrumb - checks if `useCrumb` is enabled and if so, retrieves crumb field and value and updates request header
func (jenkins *Jenkins) checkCrumb(req *http.Request) (*http.Request, error) {
// api - store jenkins api useCrumbs response
api := struct {
UseCrumbs bool `json:"useCrumbs"`
}{}
err := jenkins.get("/api/json", url.Values{"tree": []string{"useCrumbs"}}, &api)
if err != nil {
return req, err
}
if !api.UseCrumbs {
// CSRF Protection is not enabled
return req, nil
}
// get crumb field and value
crumb := struct {
Crumb string `json:"crumb"`
CrumbRequestField string `json:"crumbRequestField"`
}{}
err = jenkins.get("/crumbIssuer", nil, &crumb)
if err != nil {
return req, err
}
// update header
req.Header.Set(crumb.CrumbRequestField, crumb.Crumb)
return req, nil
}
func (jenkins *Jenkins) sendRequest(req *http.Request) (*http.Response, error) {
if jenkins.auth != nil {
req.SetBasicAuth(jenkins.auth.Username, jenkins.auth.ApiToken)
}
res, err := jenkins.client.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, &HTTPStatusError{
URL: req.URL.String(),
Code: res.StatusCode,
Status: res.Status,
}
}
return res, nil
}
func (jenkins *Jenkins) parseXmlResponse(resp *http.Response, body interface{}) (err error) {
defer resp.Body.Close()
if body == nil {
return
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return xml.Unmarshal(data, body)
}
func (jenkins *Jenkins) parseResponse(resp *http.Response, body interface{}) (err error) {
defer resp.Body.Close()
if body == nil {
return
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return json.Unmarshal(data, body)
}
func (jenkins *Jenkins) get(path string, params url.Values, body interface{}) (err error) {
requestUrl := jenkins.buildUrl(path, params)
req, err := http.NewRequest("GET", requestUrl, nil)
if err != nil {
return
}
resp, err := jenkins.sendRequest(req)
if err != nil {
return
}
return jenkins.parseResponse(resp, body)
}
func (jenkins *Jenkins) getXml(path string, params url.Values, body interface{}) (err error) {
requestUrl := jenkins.buildUrl(path, params)
req, err := http.NewRequest("GET", requestUrl, nil)
if err != nil {
return
}
resp, err := jenkins.sendRequest(req)
if err != nil {
return
}
return jenkins.parseXmlResponse(resp, body)
}
func (jenkins *Jenkins) post(path string, params url.Values, body interface{}) (err error) {
requestUrl := jenkins.buildUrl(path, params)
req, err := http.NewRequest("POST", requestUrl, nil)
if err != nil {
return
}
if _, err := jenkins.checkCrumb(req); err != nil {
return err
}
resp, err := jenkins.sendRequest(req)
if err != nil {
return
}
if !(200 <= resp.StatusCode && resp.StatusCode <= 299) {
return errors.New(fmt.Sprintf("error: HTTP POST returned status code %d (expected 2xx)", resp.StatusCode))
}
return jenkins.parseResponse(resp, body)
}
func (jenkins *Jenkins) postXml(path string, params url.Values, xmlBody io.Reader, body interface{}) (err error) {
requestUrl := jenkins.baseUrl + path
if params != nil {
queryString := params.Encode()
if queryString != "" {
requestUrl = requestUrl + "?" + queryString
}
}
req, err := http.NewRequest("POST", requestUrl, xmlBody)
if err != nil {
return
}
if _, err := jenkins.checkCrumb(req); err != nil {
return err
}
req.Header.Add("Content-Type", "application/xml")
resp, err := jenkins.sendRequest(req)
if err != nil {
return
}
if resp.StatusCode != 200 {
return errors.New(fmt.Sprintf("error: HTTP POST returned status code returned: %d", resp.StatusCode))
}
return jenkins.parseXmlResponse(resp, body)
}
// GetJobs returns all jobs you can read.
func (jenkins *Jenkins) GetJobs() ([]Job, error) {
var payload = struct {
Jobs []Job `json:"jobs"`
}{}
err := jenkins.get("", nil, &payload)
return payload.Jobs, err
}
// GetJob returns a job which has specified name.
func (jenkins *Jenkins) GetJob(name string) (job Job, err error) {
err = jenkins.get(fmt.Sprintf("/job/%s", name), nil, &job)
return
}
//GetJobConfig returns a maven job, has the one used to create Maven job
func (jenkins *Jenkins) GetJobConfig(name string) (job MavenJobItem, err error) {
err = jenkins.getXml(fmt.Sprintf("/job/%s/config.xml", name), nil, &job)
return
}
// GetBuild returns a number-th build result of specified job.
func (jenkins *Jenkins) GetBuild(job Job, number int) (build Build, err error) {
err = jenkins.get(fmt.Sprintf("/job/%s/%d", job.Name, number), nil, &build)
return
}
// GetLastBuild returns the last build of specified job.
func (jenkins *Jenkins) GetLastBuild(job Job) (build Build, err error) {
err = jenkins.get(fmt.Sprintf("/job/%s/lastBuild", job.Name), nil, &build)
return
}
// Create a new job
func (jenkins *Jenkins) CreateJob(mavenJobItem MavenJobItem, jobName string) error {
mavenJobItemXml, _ := xml.Marshal(mavenJobItem)
reader := bytes.NewReader(mavenJobItemXml)
params := url.Values{"name": []string{jobName}}
return jenkins.postXml("/createItem", params, reader, nil)
}
// Delete a job
func (jenkins *Jenkins) DeleteJob(job Job) error {
return jenkins.post(fmt.Sprintf("/job/%s/doDelete", job.Name), nil, nil)
}
// Add job to view
func (jenkins *Jenkins) AddJobToView(viewName string, job Job) error {
params := url.Values{"name": []string{job.Name}}
return jenkins.post(fmt.Sprintf("/view/%s/addJobToView", viewName), params, nil)
}
// Create a new view
func (jenkins *Jenkins) CreateView(listView ListView) error {
xmlListView, _ := xml.Marshal(listView)
reader := bytes.NewReader(xmlListView)
params := url.Values{"name": []string{listView.Name}}
return jenkins.postXml("/createView", params, reader, nil)
}
// Create a new build for this job.
// Params can be nil.
func (jenkins *Jenkins) Build(job Job, params url.Values) error {
if hasParams(job) {
return jenkins.post(fmt.Sprintf("/job/%s/buildWithParameters", job.Name), params, nil)
} else {
return jenkins.post(fmt.Sprintf("/job/%s/build", job.Name), params, nil)
}
}
// Get the console output from a build.
func (jenkins *Jenkins) GetBuildConsoleOutput(build Build) ([]byte, error) {
requestUrl := fmt.Sprintf("%s/consoleText", build.Url)
req, err := http.NewRequest("GET", requestUrl, nil)
if err != nil {
return nil, err
}
res, err := jenkins.sendRequest(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
return ioutil.ReadAll(res.Body)
}
// GetQueue returns the current build queue from Jenkins
func (jenkins *Jenkins) GetQueue() (queue Queue, err error) {
err = jenkins.get(fmt.Sprintf("/queue"), nil, &queue)
return
}
// GetArtifact return the content of a build artifact
func (jenkins *Jenkins) GetArtifact(build Build, artifact Artifact) ([]byte, error) {
requestUrl := fmt.Sprintf("%s/artifact/%s", build.Url, artifact.RelativePath)
req, err := http.NewRequest("GET", requestUrl, nil)
if err != nil {
return nil, err
}
res, err := jenkins.sendRequest(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
return ioutil.ReadAll(res.Body)
}
// SetBuildDescription sets the description of a build
func (jenkins *Jenkins) SetBuildDescription(build Build, description string) error {
requestUrl := fmt.Sprintf("%ssubmitDescription?description=%s", build.Url, url.QueryEscape(description))
req, err := http.NewRequest("GET", requestUrl, nil)
if err != nil {
return err
}
res, err := jenkins.sendRequest(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("Unexpected response: expected '200' but received '%d'", res.StatusCode)
}
return nil
}
// GetComputerObject returns the main ComputerObject
func (jenkins *Jenkins) GetComputerObject() (co ComputerObject, err error) {
err = jenkins.get(fmt.Sprintf("/computer"), nil, &co)
return
}
// GetComputers returns the list of all Computer objects
func (jenkins *Jenkins) GetComputers() ([]Computer, error) {
var payload = struct {
Computers []Computer `json:"computer"`
}{}
err := jenkins.get("/computer", nil, &payload)
return payload.Computers, err
}
// GetComputer returns a Computer object with a specified name.
func (jenkins *Jenkins) GetComputer(name string) (computer Computer, err error) {
err = jenkins.get(fmt.Sprintf("/computer/%s", name), nil, &computer)
return
}
// hasParams returns a boolean value indicating if the job is parameterized
func hasParams(job Job) bool {
for _, action := range job.Actions {
if len(action.ParameterDefinitions) > 0 {
return true
}
}
return false
}