forked from shabesoglu/pipeline-generator
/
jenkins-server.go
269 lines (219 loc) · 6.36 KB
/
jenkins-server.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
package pipeline
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"regexp"
"strconv"
)
// JenkinsServer provides interaction with a jenkins server
type JenkinsServer string
type jenkinsPlugin struct {
ShortName string `json:"shortName"`
Version string `json:"version"`
}
type jenkinsPlugins struct {
List []jenkinsPlugin `json:"plugins"`
}
type jenkinsServerJob map[string]string
type jenkinsJobList struct {
Jobs []jenkinsServerJob
}
func checkResponse(resp *http.Response) error {
if resp.StatusCode >= 400 {
f, err := ioutil.TempFile("", "errormsg.html")
if err != nil {
fmt.Fprintf(os.Stderr, "error creating dump of error response: %s\n", err.Error())
os.Exit(1)
}
defer f.Close()
contentInBytes, err := ioutil.ReadAll(resp.Body)
_, err = f.Write(contentInBytes)
if err != nil {
fmt.Fprintf(os.Stderr, "error dumping error response: %s\n", err.Error())
os.Exit(2)
}
debug("an error occured while speaking with jenkins, the error html messag was dumped to: %s\n", f.Name())
return fmt.Errorf("an error occured while speaking with jenkins, the error html messag was dumped to: %s\n", f.Name())
}
return nil
}
func (js JenkinsServer) createJob(jobName string, content io.Reader) error {
resp, err := http.Post(string(js)+"/createItem?name="+jobName, "application/xml", content)
if err != nil {
return err
}
return checkResponse(resp)
}
func (js JenkinsServer) updateJob(url string, content io.Reader) error {
resp, err := http.Post(url+"config.xml", "application/xml", content)
if err != nil {
return err
}
return checkResponse(resp)
}
func (js JenkinsServer) createView(viewName string, content io.Reader) error {
resp, err := http.Post(string(js)+"/createView?name="+viewName, "application/xml", content)
if err != nil {
return err
}
return checkResponse(resp)
}
func (js JenkinsServer) jobURL(jobName string) string {
return string(js) + "/job/" + jobName
}
func (js JenkinsServer) viewURL(viewName string) string {
return string(js) + "/view/" + viewName
}
func (js JenkinsServer) jobList() (jenkinsJobList, error) {
var jobList jenkinsJobList
debug("getting job list: %v/api/json\n", js)
resp, err := http.Get(string(js) + "/api/json")
if err != nil {
return jobList, err
}
debug("done\n")
err = json.NewDecoder(resp.Body).Decode(&jobList)
if err != nil {
return jobList, fmt.Errorf("error decoding %#v: %s\n", resp.Body, err.Error())
}
return jobList, nil
}
// removes a job from the list and returns the new list keeping the order and the removed job
func (jl jenkinsJobList) remove(name string) (jenkinsJobList, jenkinsServerJob, error) {
jobs := jl.Jobs
for i, job := range jobs {
if job["name"] == name {
if i == len(jobs)-1 {
return jenkinsJobList{jobs[:i]}, job, nil
}
return jenkinsJobList{append(jobs[:i], jobs[i+1:]...)}, job, nil
}
}
return jl, jenkinsServerJob{}, fmt.Errorf("no job named '%s' found", name)
}
func (js JenkinsServer) pipelineJobs(name string) (jenkinsJobList, error) {
l, err := js.jobList()
if err != nil {
return jenkinsJobList{}, err
}
jobs := []jenkinsServerJob{}
subJobRegexp := regexp.MustCompile(`~` + name + `\.[0-9][0-9]\.`)
for _, job := range l.Jobs {
if job["name"] == name || subJobRegexp.MatchString(job["name"]) {
jobs = append(jobs, job)
}
}
debug("Jobs that match on jenkins server: %#v\n", jobs)
return jenkinsJobList{jobs}, nil
}
func backup(name, url string) error {
f, err := ioutil.TempFile("", "__"+name+".xml__")
if err != nil {
fmt.Fprintf(os.Stderr, "Error backing up %s -- chickening out", url)
os.Exit(1)
}
defer f.Close()
info("backup\t%s\t%s\n", url, f.Name())
resp, err := http.Get(url + "config.xml")
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Fprintf(f, "%s", body)
return nil
}
func (jps jenkinsPlugins) installed(plugins []string) error {
for _, plugin := range plugins {
found := false
for _, installedPlugin := range jps.List {
if installedPlugin.ShortName == plugin {
found = true
break
}
}
if found == false {
return fmt.Errorf("jenkins server not setup correctly: required plugin '%s' not installed", plugin)
}
}
return nil
}
// Check returns nil when all necessary plugins are installed, an error otherwise
func (js JenkinsServer) Check() error {
resp, err := http.Get(string(js) + "/pluginManager/api/json?pretty=true&depth=1")
if err != nil {
return fmt.Errorf("error checking jenkins server: %s", err.Error())
}
var plugins jenkinsPlugins
err = json.NewDecoder(resp.Body).Decode(&plugins)
if err != nil {
return err
}
return plugins.installed([]string{
"ansicolor",
"build-pipeline-plugin",
"copyartifact",
"delivery-pipeline-plugin",
"git",
"jenkins-multijob-plugin",
"junit",
"next-build-number",
"parameterized-trigger",
"timestamper",
})
}
// DeletePipeline deletes all jobs and views of the named pipeline
func (js JenkinsServer) DeletePipeline(name string) (int, error) {
l, err := js.pipelineJobs(name)
if err != nil {
return 0, err
}
buildNum, err := js.BuildNumber(name)
if err != nil {
return 0, err
}
for _, jenkinsJob := range l.Jobs {
err := backup(jenkinsJob["name"], jenkinsJob["url"])
if err != nil {
return 0, err
}
debug("post\t%s\n", jenkinsJob["url"]+"/doDelete")
if _, err = http.Post(jenkinsJob["url"]+"/doDelete", "application/xml", nil); err != nil {
return 0, err
}
}
err = backup("pipeline-view-"+name, string(js)+"/view/"+name+"/")
if err != nil {
return buildNum, err
}
_, err = http.Post(string(js)+"/view/"+name+"/doDelete", "application/xml", nil)
fmt.Printf("lastbuildnum\t%d\n", buildNum)
return buildNum, err
}
// BuildNumber returns the latest build number for a named job
func (js JenkinsServer) BuildNumber(job string) (int, error) {
url := string(js) + "/job/" + job + "/lastBuild/buildNumber"
resp, err := http.Get(url)
if err != nil {
return 0, err
}
if resp.StatusCode == 404 {
return 0, nil
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
return strconv.Atoi(string(body))
}
// SetBuildNumber sets the next build number for named job to given build number
func (js JenkinsServer) SetBuildNumber(job string, buildNumber int) error {
_, err := http.Post(string(js)+"/job/"+job+"/nextbuildnumber/submit?nextBuildNumber="+strconv.Itoa(buildNumber), "application/xml", nil)
return err
}