Skip to content

Instantly share code, notes, and snippets.

@jouyouyun
Created April 21, 2019 13:11
Show Gist options
  • Save jouyouyun/ba2aad5c318889406aca7f7e2a2d7208 to your computer and use it in GitHub Desktop.
Save jouyouyun/ba2aad5c318889406aca7f7e2a2d7208 to your computer and use it in GitHub Desktop.
Trigger jenkins job build
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
)
// QueueInfo jenkins return's info by queue json api
type QueueInfo struct {
Executable struct {
Number int `json:"number"`
URL string `json:"url"`
} `json:"Executable"`
}
var (
jenkinsURL = flag.String("url", "https://ci.deepin.io", "Jenkins site url")
jenkinsView = flag.String("view", "", "Jenkins job view")
jenkinsJob = flag.String("job", "", "Jenkins job name")
jenkinsToken = flag.String("token", "", "Jenkins job token")
)
func main() {
flag.Parse()
if len(os.Args) == 1 || (len(os.Args) == 2 &&
(os.Args[1] == "-h" || os.Args[1] == "--help")) {
flag.Usage()
return
}
if len(*jenkinsURL) == 0 || len(*jenkinsJob) == 0 {
fmt.Println("No url or job found")
return
}
var params = make(map[string]string)
if len(*jenkinsToken) != 0 {
params["token"] = *jenkinsToken
}
id, err := BuildJob(params)
if err != nil {
return
}
fmt.Println("Trigger job build success, id:", id)
}
// BuildJob trigger a job build
func BuildJob(params map[string]string) (int, error) {
var api = *jenkinsURL
if len(*jenkinsView) != 0 {
api += fmt.Sprintf("/view/%s", *jenkinsView)
}
if len(*jenkinsJob) != 0 {
api += fmt.Sprintf("/job/%s", *jenkinsJob)
}
api += "/build"
fmt.Println("Request URL:", api)
// params must encode by url
var values = make(url.Values)
for k, v := range params {
values.Set(k, v)
}
fmt.Println("Request data:", values.Encode())
req, err := http.NewRequest(http.MethodPost, api,
bytes.NewBufferString(values.Encode()))
if err != nil {
return -1, err
}
// must set 'Content-Type' to 'application/x-www-form-urlencoded'
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return -1, err
}
if resp.Body != nil {
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read response content:", err)
} else {
fmt.Println("Response content:", string(data))
}
}
fmt.Println("Status:", resp.Status)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
fmt.Println("Failed to build job")
return -1, fmt.Errorf("build job failure")
}
fmt.Println("Response headers:", resp.Header)
queueAPI := resp.Header.Get("Location")
queue, err := GetQueue(queueAPI)
if err != nil {
return -1, err
}
return queue.Executable.Number, nil
}
func GetQueue(api string) (*QueueInfo, error) {
resp, err := http.Get(api + "/api/json")
if err != nil {
fmt.Println("Failed to get queue:", err)
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read response content:", err)
}
fmt.Println("Queue response content:", string(data))
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
fmt.Println("Failed to get queue info")
return nil, fmt.Errorf("get queue info failure")
}
var info QueueInfo
err = json.Unmarshal(data, &info)
if err != nil {
return nil, err
}
return &info, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment