Skip to content

Commit 139d3ff

Browse files
committed
新增jenkins-api项目
0 parents  commit 139d3ff

File tree

9 files changed

+970
-0
lines changed

9 files changed

+970
-0
lines changed

api/computer.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package api
2+
3+
type ComputerObject struct {
4+
BusyExecutors int `json:"busyExecutors"`
5+
Computers []Computer `json:"computer"`
6+
DisplayName string `json:"displayName"`
7+
TotalExecutors int `json:"totalExecutors"`
8+
}
9+
10+
type Computer struct {
11+
Actions []struct{} `json:"actions"`
12+
DisplayName string `json:"displayName"`
13+
Executors []struct{} `json:"executors"`
14+
Idle bool `json:"idle"`
15+
JnlpAgent bool `json:"jnlpAgent"`
16+
LaunchSupported bool `json:"launchSupported"`
17+
ManualLaunchAllowed bool `json:"manualLaunchAllowed"`
18+
MonitorData struct {
19+
SwapSpaceMonitor struct {
20+
AvailablePhysicalMemory int64 `json:"availablePhysicalMemory"`
21+
AvailableSwapSpace int64 `json:"availableSwapSpace"`
22+
TotalPhysicalMemory int64 `json:"totalPhysicalMemory"`
23+
TotalSwapSpace int64 `json:"totalSwapSpace"`
24+
} `json:"hudson.node_monitors.SwapSpaceMonitor"`
25+
TemporarySpaceMonitor struct {
26+
Timestamp int64 `json:"timestamp"`
27+
Path string `json:"path"`
28+
Size int64 `json:"size"`
29+
} `json:"hudson.node_monitors.TemporarySpaceMonitor"`
30+
DiskSpaceMonitor struct {
31+
Timestamp int64 `json:"timestamp"`
32+
Path string `json:"path"`
33+
Size int64 `json:"size"`
34+
} `json:"hudson.node_monitors.DiskSpaceMonitor"`
35+
ArchitectureMonitor string `json:"hudson.node_monitors.ArchitectureMonitor"`
36+
ResponseTimeMonitor struct {
37+
Timestamp int64 `json:"timestamp"`
38+
Average int64 `json:"average"`
39+
} `json:"hudson.node_monitors.ResponseTimeMonitor"`
40+
ClockMonitor struct {
41+
Diff int64 `json:"diff"`
42+
} `json:"hudson.node_monitors.ClockMonitor"`
43+
} `json:"monitorData"`
44+
NumExecutors int `json:"numExecutors"`
45+
Offline bool `json:"offline"`
46+
OfflineCauseReason string `json:"offlineCauseReason"`
47+
TemporarilyOffline bool `json:"temporarilyOffline"`
48+
}

api/jenkins.go

Lines changed: 328 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
1+
package api
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"encoding/xml"
7+
"errors"
8+
"fmt"
9+
"io"
10+
"io/ioutil"
11+
"net/http"
12+
"net/url"
13+
"strings"
14+
)
15+
16+
type Auth struct {
17+
Username string
18+
ApiToken string
19+
}
20+
type Crumb struct {
21+
CrumbRequestField string `json:"crumbRequestField"`
22+
Crumb string `json:"crumb"`
23+
}
24+
25+
type Jenkins struct {
26+
auth *Auth
27+
baseUrl string
28+
}
29+
30+
func NewJenkins(auth *Auth, baseUrl string) *Jenkins {
31+
return &Jenkins{
32+
auth: auth,
33+
baseUrl: baseUrl,
34+
}
35+
}
36+
37+
func (jenkins *Jenkins) buildUrl(path string, params url.Values) (requestUrl string) {
38+
requestUrl = jenkins.baseUrl + path + "/api/json"
39+
if params != nil {
40+
queryString := params.Encode()
41+
if queryString != "" {
42+
requestUrl = requestUrl + "?" + queryString
43+
fmt.Println(requestUrl)
44+
}
45+
}
46+
47+
return
48+
}
49+
50+
func (jenkins *Jenkins) sendRequest(req *http.Request, crumbFlag bool) (*http.Response, error) {
51+
if crumbFlag {
52+
crumbUrl := jenkins.buildUrl("/crumbIssuer", nil)
53+
reqCrumb, _ := http.NewRequest("GET", crumbUrl, nil)
54+
if jenkins.auth != nil {
55+
reqCrumb.SetBasicAuth(jenkins.auth.Username, jenkins.auth.ApiToken)
56+
}
57+
resp, _ := http.DefaultClient.Do(reqCrumb)
58+
var crumb Crumb
59+
jenkins.parseResponse(resp, &crumb)
60+
req.Header.Add(crumb.CrumbRequestField, crumb.Crumb)
61+
}
62+
if jenkins.auth != nil {
63+
req.SetBasicAuth(jenkins.auth.Username, jenkins.auth.ApiToken)
64+
}
65+
return http.DefaultClient.Do(req)
66+
}
67+
68+
func (jenkins *Jenkins) parseXmlResponse(resp *http.Response, body interface{}) (err error) {
69+
defer resp.Body.Close()
70+
71+
if body == nil {
72+
return
73+
}
74+
75+
data, err := ioutil.ReadAll(resp.Body)
76+
if err != nil {
77+
return
78+
}
79+
80+
return xml.Unmarshal(data, body)
81+
}
82+
83+
func (jenkins *Jenkins) parseResponse(resp *http.Response, body interface{}) (err error) {
84+
defer resp.Body.Close()
85+
86+
if body == nil {
87+
return
88+
}
89+
90+
data, err := ioutil.ReadAll(resp.Body)
91+
if err != nil {
92+
return
93+
}
94+
return json.Unmarshal(data, body)
95+
}
96+
97+
func (jenkins *Jenkins) get(path string, params url.Values, crumbFlag bool, body interface{}) (err error) {
98+
requestUrl := jenkins.buildUrl(path, params)
99+
req, err := http.NewRequest("GET", requestUrl, nil)
100+
if err != nil {
101+
return
102+
}
103+
resp, err := jenkins.sendRequest(req, crumbFlag)
104+
if err != nil {
105+
return
106+
}
107+
return jenkins.parseResponse(resp, body)
108+
}
109+
110+
func (jenkins *Jenkins) getXml(path string, params url.Values, crumbFlag bool, body interface{}) (err error) {
111+
requestUrl := jenkins.buildUrl(path, params)
112+
req, err := http.NewRequest("GET", requestUrl, nil)
113+
if err != nil {
114+
return
115+
}
116+
117+
resp, err := jenkins.sendRequest(req, crumbFlag)
118+
if err != nil {
119+
return
120+
}
121+
return jenkins.parseXmlResponse(resp, body)
122+
}
123+
124+
func (jenkins *Jenkins) post(path string, params url.Values, crumbFlag bool, body interface{}) (err error) {
125+
requestUrl := jenkins.buildUrl(path, params)
126+
req, err := http.NewRequest("POST", requestUrl, nil)
127+
if err != nil {
128+
return
129+
}
130+
resp, err := jenkins.sendRequest(req, crumbFlag)
131+
if err != nil {
132+
return
133+
}
134+
return jenkins.parseResponse(resp, body)
135+
}
136+
func (jenkins *Jenkins) postXml(path string, params url.Values, xmlBody io.Reader, crumbFlag bool, body interface{}) (err error) {
137+
requestUrl := jenkins.baseUrl + path
138+
if params != nil {
139+
queryString := params.Encode()
140+
if queryString != "" {
141+
requestUrl = requestUrl + "?" + queryString
142+
}
143+
}
144+
145+
req, err := http.NewRequest("POST", requestUrl, xmlBody)
146+
if err != nil {
147+
return
148+
}
149+
150+
req.Header.Add("Content-Type", "application/xml")
151+
resp, err := jenkins.sendRequest(req, crumbFlag)
152+
if err != nil {
153+
return
154+
}
155+
if resp.StatusCode != 200 {
156+
return errors.New(fmt.Sprintf("error: HTTP POST returned status code returned: %d", resp.StatusCode))
157+
}
158+
159+
return jenkins.parseXmlResponse(resp, body)
160+
}
161+
162+
// GetJobs returns all jobs you can read.
163+
func (jenkins *Jenkins) GetJobs(crumbFlag bool) ([]Job, error) {
164+
var payload = struct {
165+
Jobs []Job `json:"jobs"`
166+
}{}
167+
err := jenkins.get("", nil, crumbFlag, &payload)
168+
return payload.Jobs, err
169+
}
170+
171+
// GetJob returns a job which has specified name.
172+
func (jenkins *Jenkins) GetJob(name string, crumbFlag bool) (job Job, err error) {
173+
err = jenkins.get(fmt.Sprintf("/job/%s", name), nil, crumbFlag, &job)
174+
return
175+
}
176+
177+
//GetJobConfig returns a maven job, has the one used to create Maven job
178+
func (jenkins *Jenkins) GetJobConfig(name string, crumbFlag bool) (job MavenJobItem, err error) {
179+
err = jenkins.getXml(fmt.Sprintf("/job/%s/config.xml", name), nil, crumbFlag, &job)
180+
return
181+
}
182+
183+
// GetBuild returns a number-th build result of specified job.
184+
func (jenkins *Jenkins) GetBuild(job Job, number int, crumbFlag bool) (build Build, err error) {
185+
err = jenkins.get(fmt.Sprintf("/job/%s/%d", job.Name, number), nil, crumbFlag, &build)
186+
return
187+
}
188+
189+
// GetLastBuild returns the last build of specified job.
190+
func (jenkins *Jenkins) GetLastBuild(job Job, crumbFlag bool) (build Build, err error) {
191+
err = jenkins.get(fmt.Sprintf("/job/%s/lastBuild", job.Name), nil, crumbFlag, &build)
192+
return
193+
}
194+
195+
// Create a new job
196+
func (jenkins *Jenkins) CreateJob(mavenJobItem MavenJobItem, jobName string, crumbFlag bool) error {
197+
mavenJobItemXml, _ := xml.Marshal(mavenJobItem)
198+
fmt.Println(string(mavenJobItemXml))
199+
reader := bytes.NewReader(mavenJobItemXml)
200+
params := url.Values{"name": []string{jobName}}
201+
202+
return jenkins.postXml("/createItem", params, reader, crumbFlag, nil)
203+
}
204+
205+
// Create a new job
206+
func (jenkins *Jenkins) CreateJobByCfgXml(cfgXml string, jobName string, crumbFlag bool) error {
207+
reader := strings.NewReader(cfgXml)
208+
params := url.Values{"name": []string{jobName}}
209+
210+
return jenkins.postXml("/createItem", params, reader, crumbFlag, nil)
211+
}
212+
213+
// Add job to view
214+
func (jenkins *Jenkins) AddJobToView(viewName string, job Job, crumbFlag bool) error {
215+
params := url.Values{"name": []string{job.Name}}
216+
return jenkins.post(fmt.Sprintf("/view/%s/addJobToView", viewName), params, crumbFlag, nil)
217+
}
218+
219+
// Create a new view
220+
func (jenkins *Jenkins) CreateView(listView ListView, crumbFlag bool) error {
221+
xmlListView, _ := xml.Marshal(listView)
222+
reader := bytes.NewReader(xmlListView)
223+
params := url.Values{"name": []string{listView.Name}}
224+
225+
return jenkins.postXml("/createView", params, reader, crumbFlag, nil)
226+
}
227+
228+
// Create a new build for this job.
229+
// Params can be nil.
230+
func (jenkins *Jenkins) Build(job Job, params url.Values, crumbFlag bool) error {
231+
if hasParams(job) {
232+
return jenkins.post(fmt.Sprintf("/job/%s/buildWithParameters", job.Name), params, crumbFlag, nil)
233+
} else {
234+
return jenkins.post(fmt.Sprintf("/job/%s/build", job.Name), params, crumbFlag, nil)
235+
}
236+
}
237+
238+
// Get the console output from a build.
239+
func (jenkins *Jenkins) GetBuildConsoleOutput(build Build, crumbFlag bool) ([]byte, error) {
240+
requestUrl := fmt.Sprintf("%s/consoleText", build.Url)
241+
req, err := http.NewRequest("GET", requestUrl, nil)
242+
if err != nil {
243+
return nil, err
244+
}
245+
246+
res, err := jenkins.sendRequest(req, crumbFlag)
247+
if err != nil {
248+
return nil, err
249+
}
250+
251+
defer res.Body.Close()
252+
return ioutil.ReadAll(res.Body)
253+
}
254+
255+
// GetQueue returns the current build queue from Jenkins
256+
func (jenkins *Jenkins) GetQueue(crumbFlag bool) (queue Queue, err error) {
257+
err = jenkins.get(fmt.Sprintf("/queue"), nil, crumbFlag, &queue)
258+
return
259+
}
260+
261+
// GetArtifact return the content of a build artifact
262+
func (jenkins *Jenkins) GetArtifact(build Build, artifact Artifact, crumbFlag bool) ([]byte, error) {
263+
requestUrl := fmt.Sprintf("%s/artifact/%s", build.Url, artifact.RelativePath)
264+
req, err := http.NewRequest("GET", requestUrl, nil)
265+
if err != nil {
266+
return nil, err
267+
}
268+
269+
res, err := jenkins.sendRequest(req, crumbFlag)
270+
if err != nil {
271+
return nil, err
272+
}
273+
274+
defer res.Body.Close()
275+
return ioutil.ReadAll(res.Body)
276+
}
277+
278+
// SetBuildDescription sets the description of a build
279+
func (jenkins *Jenkins) SetBuildDescription(build Build, description string, crumbFlag bool) error {
280+
requestUrl := fmt.Sprintf("%ssubmitDescription?description=%s", build.Url, url.QueryEscape(description))
281+
req, err := http.NewRequest("GET", requestUrl, nil)
282+
if err != nil {
283+
return err
284+
}
285+
286+
res, err := jenkins.sendRequest(req, crumbFlag)
287+
if err != nil {
288+
return err
289+
}
290+
defer res.Body.Close()
291+
292+
if res.StatusCode != 200 {
293+
return fmt.Errorf("Unexpected response: expected '200' but received '%d'", res.StatusCode)
294+
}
295+
296+
return nil
297+
}
298+
299+
// GetComputerObject returns the main ComputerObject
300+
func (jenkins *Jenkins) GetComputerObject(crumbFlag bool) (co ComputerObject, err error) {
301+
err = jenkins.get(fmt.Sprintf("/computer"), nil, crumbFlag, &co)
302+
return
303+
}
304+
305+
// GetComputers returns the list of all Computer objects
306+
func (jenkins *Jenkins) GetComputers(crumbFlag bool) ([]Computer, error) {
307+
var payload = struct {
308+
Computers []Computer `json:"computer"`
309+
}{}
310+
err := jenkins.get("/computer", nil, crumbFlag, &payload)
311+
return payload.Computers, err
312+
}
313+
314+
// GetComputer returns a Computer object with a specified name.
315+
func (jenkins *Jenkins) GetComputer(name string, crumbFlag bool) (computer Computer, err error) {
316+
err = jenkins.get(fmt.Sprintf("/computer/%s", name), nil, crumbFlag, &computer)
317+
return
318+
}
319+
320+
// hasParams returns a boolean value indicating if the job is parameterized
321+
func hasParams(job Job) bool {
322+
for _, action := range job.Actions {
323+
if len(action.ParameterDefinitions) > 0 {
324+
return true
325+
}
326+
}
327+
return false
328+
}

0 commit comments

Comments
 (0)