|
1 | 1 | package main
|
2 | 2 |
|
3 | 3 | import (
|
4 |
| - "context" |
5 |
| - "crypto/tls" |
6 |
| - "encoding/json" |
7 |
| - "fmt" |
8 |
| - "github.com/avast/retry-go" |
9 |
| - "github.com/bndr/gojenkins" |
10 |
| - "github.com/spf13/cobra" |
11 |
| - "net/http" |
12 |
| - "os" |
13 |
| - "strings" |
14 |
| - "time" |
| 4 | + "context" |
| 5 | + "crypto/tls" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "github.com/avast/retry-go" |
| 9 | + "github.com/bndr/gojenkins" |
| 10 | + "github.com/spf13/cobra" |
| 11 | + "net/http" |
| 12 | + "os" |
| 13 | + "strings" |
| 14 | + "time" |
15 | 15 | )
|
16 | 16 |
|
17 | 17 | const (
|
18 |
| - defaultJenkinsUrl = "http://127.0.0.1:8080" |
19 |
| - defaultWait = false |
20 |
| - defaultWaitPollSecond = 10 |
21 |
| - defaultWaitMaxAttempts = 60 |
22 |
| - desc = `This command triggers Jenkins job. |
| 18 | + defaultJenkinsUrl = "http://127.0.0.1:8080" |
| 19 | + defaultWait = false |
| 20 | + defaultWaitPollSecond = 10 |
| 21 | + defaultWaitMaxAttempts = 60 |
| 22 | + desc = `This command triggers Jenkins job. |
23 | 23 |
|
24 | 24 | You can specify the '--job'/'-j' flag to determine the name of the Jenkins job to run.
|
25 | 25 | To specify jobs within folders, use the '-–job-folders'/'-f' flag to define the folder path using slashes (/) as separators (e.g., foo/bar).
|
@@ -49,179 +49,179 @@ Use '--max-attempts' flag to set the max count of polling for results.
|
49 | 49 | )
|
50 | 50 |
|
51 | 51 | func main() {
|
52 |
| - c := config{ |
53 |
| - Jenkins: jenkins{ |
54 |
| - Url: defaultJenkinsUrl, |
55 |
| - }, |
56 |
| - Job: job{}, |
57 |
| - Wait: wait{ |
58 |
| - Enabled: defaultWait, |
59 |
| - PollTime: defaultWaitPollSecond * time.Second, |
60 |
| - MaxAttempts: defaultWaitMaxAttempts, |
61 |
| - }, |
62 |
| - } |
63 |
| - |
64 |
| - params := params{} |
65 |
| - cmd := &cobra.Command{ |
66 |
| - Use: "jenkins-trigger", |
67 |
| - Short: "Trigger Jenkins job in Go", |
68 |
| - Long: desc, |
69 |
| - SilenceUsage: true, |
70 |
| - RunE: func(cmd *cobra.Command, args []string) (err error) { |
71 |
| - c.Job.Params, err = params.init() |
72 |
| - if err != nil { |
73 |
| - return |
74 |
| - } |
75 |
| - return triggerBuild(c) |
76 |
| - }, |
77 |
| - } |
78 |
| - |
79 |
| - flags := cmd.Flags() |
80 |
| - flags.StringVar(&c.Jenkins.Url, "jenkins-url", c.Jenkins.Url, "URL of the Jenkins server") |
81 |
| - flags.StringVar(&c.Jenkins.User, "jenkins-user", c.Jenkins.User, "User for accessing Jenkins") |
82 |
| - flags.StringVar(&c.Jenkins.Pat, "jenkins-pat", c.Jenkins.Pat, "Personal access token (PAT) for accessing Jenkins") |
83 |
| - flags.BoolVarP(&c.Jenkins.Insecure, "insecure", "k", c.Jenkins.Insecure, "Allow insecure Jenkins server connections when using SSL") |
84 |
| - flags.StringVarP(&c.Job.Name, "job", "j", c.Job.Name, "The name of the Jenkins job to run") |
85 |
| - flags.StringSliceVarP(&c.Job.Folders, "job-folders", "f", c.Job.Folders, "The folder paths of the job, can specify multiple or separate parameters with slashes, e.g., foo/bar") |
86 |
| - flags.StringSliceVarP(¶ms.slice, "params", "p", params.slice, "The parameters of the job in key=value format, can specify multiple or separate parameters with commas, e.g., foo=bar,baz=qux") |
87 |
| - flags.StringVarP(¶ms.json, "params-json", "P", params.json, "The parameters of the job in JSON format, e.g., {\"foo\":\"bar\",\"baz\":\"qux\"}") |
88 |
| - flags.BoolVar(&c.Wait.Enabled, "wait", c.Wait.Enabled, "Wait for the job to complete, and return the results") |
89 |
| - flags.DurationVar(&c.Wait.PollTime, "poll-time", c.Wait.PollTime, "How often (duration) to poll the Jenkins server for results") |
90 |
| - flags.UintVar(&c.Wait.MaxAttempts, "max-attempts", c.Wait.MaxAttempts, "Max count of polling for results") |
91 |
| - |
92 |
| - _ = cmd.MarkFlagRequired("job") |
93 |
| - |
94 |
| - if err := cmd.Execute(); err != nil { |
95 |
| - _, _ = fmt.Fprintln(os.Stderr, err) |
96 |
| - os.Exit(1) |
97 |
| - } |
| 52 | + c := config{ |
| 53 | + Jenkins: jenkins{ |
| 54 | + Url: defaultJenkinsUrl, |
| 55 | + }, |
| 56 | + Job: job{}, |
| 57 | + Wait: wait{ |
| 58 | + Enabled: defaultWait, |
| 59 | + PollTime: defaultWaitPollSecond * time.Second, |
| 60 | + MaxAttempts: defaultWaitMaxAttempts, |
| 61 | + }, |
| 62 | + } |
| 63 | + |
| 64 | + params := params{} |
| 65 | + cmd := &cobra.Command{ |
| 66 | + Use: "jenkins-trigger", |
| 67 | + Short: "Trigger Jenkins job in Go", |
| 68 | + Long: desc, |
| 69 | + SilenceUsage: true, |
| 70 | + RunE: func(cmd *cobra.Command, args []string) (err error) { |
| 71 | + c.Job.Params, err = params.init() |
| 72 | + if err != nil { |
| 73 | + return |
| 74 | + } |
| 75 | + return triggerBuild(c) |
| 76 | + }, |
| 77 | + } |
| 78 | + |
| 79 | + flags := cmd.Flags() |
| 80 | + flags.StringVar(&c.Jenkins.Url, "jenkins-url", c.Jenkins.Url, "URL of the Jenkins server") |
| 81 | + flags.StringVar(&c.Jenkins.User, "jenkins-user", c.Jenkins.User, "User for accessing Jenkins") |
| 82 | + flags.StringVar(&c.Jenkins.Pat, "jenkins-pat", c.Jenkins.Pat, "Personal access token (PAT) for accessing Jenkins") |
| 83 | + flags.BoolVarP(&c.Jenkins.Insecure, "insecure", "k", c.Jenkins.Insecure, "Allow insecure Jenkins server connections when using SSL") |
| 84 | + flags.StringVarP(&c.Job.Name, "job", "j", c.Job.Name, "The name of the Jenkins job to run") |
| 85 | + flags.StringSliceVarP(&c.Job.Folders, "job-folders", "f", c.Job.Folders, "The folder paths of the job, can specify multiple or separate parameters with slashes, e.g., foo/bar") |
| 86 | + flags.StringSliceVarP(¶ms.slice, "params", "p", params.slice, "The parameters of the job in key=value format, can specify multiple or separate parameters with commas, e.g., foo=bar,baz=qux") |
| 87 | + flags.StringVarP(¶ms.json, "params-json", "P", params.json, "The parameters of the job in JSON format, e.g., {\"foo\":\"bar\",\"baz\":\"qux\"}") |
| 88 | + flags.BoolVar(&c.Wait.Enabled, "wait", c.Wait.Enabled, "Wait for the job to complete, and return the results") |
| 89 | + flags.DurationVar(&c.Wait.PollTime, "poll-time", c.Wait.PollTime, "How often (duration) to poll the Jenkins server for results") |
| 90 | + flags.UintVar(&c.Wait.MaxAttempts, "max-attempts", c.Wait.MaxAttempts, "Max count of polling for results") |
| 91 | + |
| 92 | + _ = cmd.MarkFlagRequired("job") |
| 93 | + |
| 94 | + if err := cmd.Execute(); err != nil { |
| 95 | + _, _ = fmt.Fprintln(os.Stderr, err) |
| 96 | + os.Exit(1) |
| 97 | + } |
98 | 98 | }
|
99 | 99 |
|
100 | 100 | func triggerBuild(c config) error {
|
101 |
| - fmt.Printf("Triggering Jenkins build for job: %+v, wait: %+v\n", c.Job, c.Wait) |
102 |
| - |
103 |
| - jenkins, err := c.Jenkins.createClient() |
104 |
| - if err != nil { |
105 |
| - return err |
106 |
| - } |
107 |
| - |
108 |
| - queueId, err := buildJob(context.Background(), jenkins, &c.Job) |
109 |
| - if err != nil { |
110 |
| - return err |
111 |
| - } |
112 |
| - |
113 |
| - fmt.Printf("Job %s triggered successfully\n", c.Job.Name) |
114 |
| - |
115 |
| - if !c.Wait.Enabled { |
116 |
| - return nil |
117 |
| - } |
118 |
| - |
119 |
| - return retry.Do( |
120 |
| - pollBuildResult(c, jenkins, queueId), |
121 |
| - retry.DelayType(retry.FixedDelay), |
122 |
| - retry.Delay(c.Wait.PollTime), |
123 |
| - retry.Attempts(c.Wait.MaxAttempts), |
124 |
| - ) |
| 101 | + fmt.Printf("Triggering Jenkins build for job: %+v, wait: %+v\n", c.Job, c.Wait) |
| 102 | + |
| 103 | + jenkins, err := c.Jenkins.createClient() |
| 104 | + if err != nil { |
| 105 | + return err |
| 106 | + } |
| 107 | + |
| 108 | + queueId, err := buildJob(context.Background(), jenkins, &c.Job) |
| 109 | + if err != nil { |
| 110 | + return err |
| 111 | + } |
| 112 | + |
| 113 | + fmt.Printf("Job %s triggered successfully\n", c.Job.Name) |
| 114 | + |
| 115 | + if !c.Wait.Enabled { |
| 116 | + return nil |
| 117 | + } |
| 118 | + |
| 119 | + return retry.Do( |
| 120 | + pollBuildResult(c, jenkins, queueId), |
| 121 | + retry.DelayType(retry.FixedDelay), |
| 122 | + retry.Delay(c.Wait.PollTime), |
| 123 | + retry.Attempts(c.Wait.MaxAttempts), |
| 124 | + ) |
125 | 125 | }
|
126 | 126 |
|
127 | 127 | func buildJob(ctx context.Context, jenkins *gojenkins.Jenkins, job *job) (int64, error) {
|
128 |
| - var f []string |
129 |
| - for _, folder := range job.Folders { |
130 |
| - parts := strings.Split(folder, "/") |
131 |
| - for _, part := range parts { |
132 |
| - if trimmed := strings.TrimSpace(part); trimmed != "" { |
133 |
| - f = append(f, trimmed) |
134 |
| - } |
135 |
| - } |
136 |
| - } |
137 |
| - if len(f) == 0 { |
138 |
| - return jenkins.BuildJob(ctx, job.Name, job.Params) |
139 |
| - } |
140 |
| - j := gojenkins.Job{Jenkins: jenkins, Raw: new(gojenkins.JobResponse), Base: "/job/" + strings.Join(append(f, job.Name), "/job/")} |
141 |
| - return j.InvokeSimple(ctx, job.Params) |
| 128 | + var f []string |
| 129 | + for _, folder := range job.Folders { |
| 130 | + parts := strings.Split(folder, "/") |
| 131 | + for _, part := range parts { |
| 132 | + if trimmed := strings.TrimSpace(part); trimmed != "" { |
| 133 | + f = append(f, trimmed) |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + if len(f) == 0 { |
| 138 | + return jenkins.BuildJob(ctx, job.Name, job.Params) |
| 139 | + } |
| 140 | + j := gojenkins.Job{Jenkins: jenkins, Raw: new(gojenkins.JobResponse), Base: "/job/" + strings.Join(append(f, job.Name), "/job/")} |
| 141 | + return j.InvokeSimple(ctx, job.Params) |
142 | 142 | }
|
143 | 143 |
|
144 | 144 | func pollBuildResult(c config, jenkins *gojenkins.Jenkins, queueId int64) func() error {
|
145 |
| - return func() error { |
146 |
| - fmt.Printf("Polling build result for job %s\n", c.Job.Name) |
147 |
| - |
148 |
| - build, err := jenkins.GetBuildFromQueueID(context.Background(), queueId) |
149 |
| - if err != nil { |
150 |
| - return err |
151 |
| - } |
152 |
| - |
153 |
| - if build.IsGood(context.Background()) { |
154 |
| - fmt.Printf("Job %s, build number %d successfully\n", c.Job.Name, build.GetBuildNumber()) |
155 |
| - return nil |
156 |
| - } |
157 |
| - |
158 |
| - if build.IsRunning(context.Background()) { |
159 |
| - fmt.Printf("Job %s, build number %d is still running, retry after %s\n", c.Job.Name, build.GetBuildNumber(), c.Wait.PollTime) |
160 |
| - return &IsStillRunning{time.Now(), c.Job.Name, build.GetBuildNumber()} |
161 |
| - } |
162 |
| - |
163 |
| - return retry.Unrecoverable(fmt.Errorf("Job %s Build number %d did not complete successfully\n", c.Job.Name, build.GetBuildNumber())) |
164 |
| - } |
| 145 | + return func() error { |
| 146 | + fmt.Printf("Polling build result for job %s\n", c.Job.Name) |
| 147 | + |
| 148 | + build, err := jenkins.GetBuildFromQueueID(context.Background(), queueId) |
| 149 | + if err != nil { |
| 150 | + return err |
| 151 | + } |
| 152 | + |
| 153 | + if build.IsGood(context.Background()) { |
| 154 | + fmt.Printf("Job %s, build number %d successfully\n", c.Job.Name, build.GetBuildNumber()) |
| 155 | + return nil |
| 156 | + } |
| 157 | + |
| 158 | + if build.IsRunning(context.Background()) { |
| 159 | + fmt.Printf("Job %s, build number %d is still running, retry after %s\n", c.Job.Name, build.GetBuildNumber(), c.Wait.PollTime) |
| 160 | + return &IsStillRunning{time.Now(), c.Job.Name, build.GetBuildNumber()} |
| 161 | + } |
| 162 | + |
| 163 | + return retry.Unrecoverable(fmt.Errorf("Job %s Build number %d did not complete successfully\n", c.Job.Name, build.GetBuildNumber())) |
| 164 | + } |
165 | 165 | }
|
166 | 166 |
|
167 | 167 | // IsStillRunning indicate a Jenkins job is not done yet
|
168 | 168 | type IsStillRunning struct {
|
169 |
| - time time.Time |
170 |
| - jobName string |
171 |
| - buildNumber int64 |
| 169 | + time time.Time |
| 170 | + jobName string |
| 171 | + buildNumber int64 |
172 | 172 | }
|
173 | 173 |
|
174 | 174 | func (r *IsStillRunning) Error() string {
|
175 |
| - return fmt.Sprintf("job %s, build number %d is still running. (%s)\n", r.jobName, r.buildNumber, r.time.Format(time.Stamp)) |
| 175 | + return fmt.Sprintf("job %s, build number %d is still running. (%s)\n", r.jobName, r.buildNumber, r.time.Format(time.Stamp)) |
176 | 176 | }
|
177 | 177 |
|
178 | 178 | type config struct {
|
179 |
| - Jenkins jenkins |
180 |
| - Job job |
181 |
| - Wait wait |
| 179 | + Jenkins jenkins |
| 180 | + Job job |
| 181 | + Wait wait |
182 | 182 | }
|
183 | 183 |
|
184 | 184 | type wait struct {
|
185 |
| - Enabled bool |
186 |
| - PollTime time.Duration |
187 |
| - MaxAttempts uint |
| 185 | + Enabled bool |
| 186 | + PollTime time.Duration |
| 187 | + MaxAttempts uint |
188 | 188 | }
|
189 | 189 |
|
190 | 190 | type jenkins struct {
|
191 |
| - Url string |
192 |
| - User string |
193 |
| - Pat string |
194 |
| - Insecure bool |
| 191 | + Url string |
| 192 | + User string |
| 193 | + Pat string |
| 194 | + Insecure bool |
195 | 195 | }
|
196 | 196 |
|
197 | 197 | func (j *jenkins) createClient() (*gojenkins.Jenkins, error) {
|
198 |
| - client := &http.Client{Transport: &http.Transport{ |
199 |
| - TLSClientConfig: &tls.Config{InsecureSkipVerify: j.Insecure}, |
200 |
| - }} |
201 |
| - return gojenkins.CreateJenkins(client, j.Url, j.User, j.Pat).Init(context.Background()) |
| 198 | + client := &http.Client{Transport: &http.Transport{ |
| 199 | + TLSClientConfig: &tls.Config{InsecureSkipVerify: j.Insecure}, |
| 200 | + }} |
| 201 | + return gojenkins.CreateJenkins(client, j.Url, j.User, j.Pat).Init(context.Background()) |
202 | 202 | }
|
203 | 203 |
|
204 | 204 | type job struct {
|
205 |
| - Name string |
206 |
| - Folders []string |
207 |
| - Params map[string]string |
| 205 | + Name string |
| 206 | + Folders []string |
| 207 | + Params map[string]string |
208 | 208 | }
|
209 | 209 |
|
210 | 210 | type params struct {
|
211 |
| - slice []string |
212 |
| - json string |
| 211 | + slice []string |
| 212 | + json string |
213 | 213 | }
|
214 | 214 |
|
215 | 215 | func (p *params) init() (map[string]string, error) {
|
216 |
| - params := make(map[string]string) |
217 |
| - if p.json != "" { |
218 |
| - if err := json.Unmarshal([]byte(p.json), ¶ms); err != nil { |
219 |
| - return nil, err |
220 |
| - } |
221 |
| - } |
222 |
| - for _, v := range p.slice { |
223 |
| - split := strings.Split(v, "=") |
224 |
| - params[split[0]] = strings.Join(split[1:], "=") |
225 |
| - } |
226 |
| - return params, nil |
| 216 | + params := make(map[string]string) |
| 217 | + if p.json != "" { |
| 218 | + if err := json.Unmarshal([]byte(p.json), ¶ms); err != nil { |
| 219 | + return nil, err |
| 220 | + } |
| 221 | + } |
| 222 | + for _, v := range p.slice { |
| 223 | + split := strings.Split(v, "=") |
| 224 | + params[split[0]] = strings.Join(split[1:], "=") |
| 225 | + } |
| 226 | + return params, nil |
227 | 227 | }
|
0 commit comments