forked from bndr/gojenkins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.go
520 lines (467 loc) · 13.5 KB
/
build.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// Copyright 2015 Vadim Kravcenko
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package gojenkins
import (
"bytes"
"context"
"errors"
"net/url"
"regexp"
"strconv"
"time"
)
type Build struct {
Raw *BuildResponse
Job *Job
Jenkins *Jenkins
Base string
Depth int
}
type parameter struct {
Name string
Value interface{}
}
type branch struct {
SHA1 string
Name string
}
type BuildRevision struct {
SHA1 string `json:"SHA1"`
Branch []branch `json:"branch"`
}
type Builds struct {
BuildNumber int64 `json:"buildNumber"`
BuildResult interface{} `json:"buildResult"`
Marked BuildRevision `json:"marked"`
Revision BuildRevision `json:"revision"`
}
type Culprit struct {
AbsoluteUrl string
FullName string
}
type generalObj struct {
Parameters []parameter `json:"parameters"`
Causes []map[string]interface{} `json:"causes"`
BuildsByBranchName map[string]Builds `json:"buildsByBranchName"`
LastBuiltRevision BuildRevision `json:"lastBuiltRevision"`
RemoteUrls []string `json:"remoteUrls"`
ScmName string `json:"scmName"`
MercurialNodeName string `json:"mercurialNodeName"`
MercurialRevisionNumber string `json:"mercurialRevisionNumber"`
Subdir interface{} `json:"subdir"`
TotalCount int64
UrlName string
}
type TestResult struct {
Duration float64 `json:"duration"`
Empty bool `json:"empty"`
FailCount int64 `json:"failCount"`
PassCount int64 `json:"passCount"`
SkipCount int64 `json:"skipCount"`
Suites []struct {
Cases []struct {
Age int64 `json:"age"`
ClassName string `json:"className"`
Duration float64 `json:"duration"`
ErrorDetails interface{} `json:"errorDetails"`
ErrorStackTrace interface{} `json:"errorStackTrace"`
FailedSince int64 `json:"failedSince"`
Name string `json:"name"`
Skipped bool `json:"skipped"`
SkippedMessage interface{} `json:"skippedMessage"`
Status string `json:"status"`
Stderr interface{} `json:"stderr"`
Stdout interface{} `json:"stdout"`
} `json:"cases"`
Duration float64 `json:"duration"`
ID interface{} `json:"id"`
Name string `json:"name"`
Stderr interface{} `json:"stderr"`
Stdout interface{} `json:"stdout"`
Timestamp interface{} `json:"timestamp"`
} `json:"suites"`
}
type BuildResponse struct {
Actions []generalObj
Artifacts []struct {
DisplayPath string `json:"displayPath"`
FileName string `json:"fileName"`
RelativePath string `json:"relativePath"`
} `json:"artifacts"`
Building bool `json:"building"`
BuiltOn string `json:"builtOn"`
ChangeSet struct {
Items []struct {
AffectedPaths []string `json:"affectedPaths"`
Author struct {
AbsoluteUrl string `json:"absoluteUrl"`
FullName string `json:"fullName"`
} `json:"author"`
Comment string `json:"comment"`
CommitID string `json:"commitId"`
Date string `json:"date"`
ID string `json:"id"`
Msg string `json:"msg"`
Paths []struct {
EditType string `json:"editType"`
File string `json:"file"`
} `json:"paths"`
Timestamp int64 `json:"timestamp"`
} `json:"items"`
Kind string `json:"kind"`
Revisions []struct {
Module string
Revision int
} `json:"revision"`
} `json:"changeSet"`
ChangeSets []struct {
Items []struct {
AffectedPaths []string `json:"affectedPaths"`
Author struct {
AbsoluteUrl string `json:"absoluteUrl"`
FullName string `json:"fullName"`
} `json:"author"`
Comment string `json:"comment"`
CommitID string `json:"commitId"`
Date string `json:"date"`
ID string `json:"id"`
Msg string `json:"msg"`
Paths []struct {
EditType string `json:"editType"`
File string `json:"file"`
} `json:"paths"`
Timestamp int64 `json:"timestamp"`
} `json:"items"`
Kind string `json:"kind"`
Revisions []struct {
Module string
Revision int
} `json:"revision"`
} `json:"changeSets"`
Culprits []Culprit `json:"culprits"`
Description interface{} `json:"description"`
Duration float64 `json:"duration"`
EstimatedDuration float64 `json:"estimatedDuration"`
Executor interface{} `json:"executor"`
DisplayName string `json:"displayName"`
FullDisplayName string `json:"fullDisplayName"`
ID string `json:"id"`
KeepLog bool `json:"keepLog"`
Number int64 `json:"number"`
QueueID int64 `json:"queueId"`
Result string `json:"result"`
Timestamp int64 `json:"timestamp"`
URL string `json:"url"`
MavenArtifacts interface{} `json:"mavenArtifacts"`
MavenVersionUsed string `json:"mavenVersionUsed"`
FingerPrint []FingerPrintResponse
Runs []struct {
Number int64
URL string
} `json:"runs"`
}
type consoleResponse struct {
Content string
Offset int64
HasMoreText bool
}
// Builds
func (b *Build) Info() *BuildResponse {
return b.Raw
}
func (b *Build) GetActions() []generalObj {
return b.Raw.Actions
}
func (b *Build) GetUrl() string {
return b.Raw.URL
}
func (b *Build) GetBuildNumber() int64 {
return b.Raw.Number
}
func (b *Build) GetResult() string {
return b.Raw.Result
}
func (b *Build) GetArtifacts() []Artifact {
artifacts := make([]Artifact, len(b.Raw.Artifacts))
for i, artifact := range b.Raw.Artifacts {
artifacts[i] = Artifact{
Jenkins: b.Jenkins,
Build: b,
FileName: artifact.FileName,
Path: b.Base + "/artifact/" + artifact.RelativePath,
}
}
return artifacts
}
func (b *Build) GetCulprits() []Culprit {
return b.Raw.Culprits
}
func (b *Build) Stop(ctx context.Context) (bool, error) {
if b.IsRunning(ctx) {
response, err := b.Jenkins.Requester.Post(ctx, b.Base+"/stop", nil, nil, nil)
if err != nil {
return false, err
}
return response.StatusCode == 200, nil
}
return true, nil
}
func (b *Build) GetConsoleOutput(ctx context.Context) string {
url := b.Base + "/consoleText"
var content string
b.Jenkins.Requester.GetXML(ctx, url, &content, nil)
return content
}
func (b *Build) GetConsoleOutputFromIndex(ctx context.Context, startID int64) (consoleResponse, error) {
strstart := strconv.FormatInt(startID, 10)
url := b.Base + "/logText/progressiveText"
var console consoleResponse
querymap := make(map[string]string)
querymap["start"] = strstart
rsp, err := b.Jenkins.Requester.Get(ctx, url, &console.Content, querymap)
if err != nil {
return console, err
}
textSize := rsp.Header.Get("X-Text-Size")
console.HasMoreText = len(rsp.Header.Get("X-More-Data")) != 0
console.Offset, err = strconv.ParseInt(textSize, 10, 64)
if err != nil {
return console, err
}
return console, err
}
func (b *Build) GetCauses(ctx context.Context) ([]map[string]interface{}, error) {
_, err := b.Poll(ctx)
if err != nil {
return nil, err
}
for _, a := range b.Raw.Actions {
if a.Causes != nil {
return a.Causes, nil
}
}
return nil, errors.New("No Causes")
}
func (b *Build) GetParameters() []parameter {
for _, a := range b.Raw.Actions {
if a.Parameters != nil {
return a.Parameters
}
}
return nil
}
func (b *Build) GetInjectedEnvVars(ctx context.Context) (map[string]string, error) {
var envVars struct {
EnvMap map[string]string `json:"envMap"`
}
endpoint := b.Base + "/injectedEnvVars"
_, err := b.Jenkins.Requester.GetJSON(ctx, endpoint, &envVars, nil)
if err != nil {
return envVars.EnvMap, err
}
return envVars.EnvMap, nil
}
func (b *Build) GetDownstreamBuilds(ctx context.Context) ([]*Build, error) {
result := make([]*Build, 0)
downstreamJobs, err := b.Job.GetDownstreamJobs(ctx)
if err != nil {
return nil, err
}
for _, job := range downstreamJobs {
allBuildIDs, err := job.GetAllBuildIds(ctx)
if err != nil {
return nil, err
}
for _, buildID := range allBuildIDs {
build, err := job.GetBuild(ctx, buildID.Number)
if err != nil {
return nil, err
}
upstreamBuild, err := build.GetUpstreamBuild(ctx)
// older build may no longer exist, so simply ignore these
// cannot compare only id, it can be from different job
if err == nil && b.GetUrl() == upstreamBuild.GetUrl() {
result = append(result, build)
break
}
}
}
return result, nil
}
func (b *Build) GetDownstreamJobNames(ctx context.Context) []string {
result := make([]string, 0)
downstreamJobs := b.Job.GetDownstreamJobsMetadata()
fingerprints := b.GetAllFingerPrints(ctx)
for _, fingerprint := range fingerprints {
for _, usage := range fingerprint.Raw.Usage {
for _, job := range downstreamJobs {
if job.Name == usage.Name {
result = append(result, job.Name)
}
}
}
}
return result
}
func (b *Build) GetAllFingerPrints(ctx context.Context) []*FingerPrint {
b.Poll(ctx)
result := make([]*FingerPrint, len(b.Raw.FingerPrint))
for i, f := range b.Raw.FingerPrint {
result[i] = &FingerPrint{Jenkins: b.Jenkins, Base: "/fingerprint/", Id: f.Hash, Raw: &f}
}
return result
}
func (b *Build) GetUpstreamJob(ctx context.Context) (*Job, error) {
causes, err := b.GetCauses(ctx)
if err != nil {
return nil, err
}
for _, cause := range causes {
if job, ok := cause["upstreamProject"]; ok {
return b.Jenkins.GetJob(ctx, job.(string))
}
}
return nil, errors.New("Unable to get Upstream Job")
}
func (b *Build) GetUpstreamBuildNumber(ctx context.Context) (int64, error) {
causes, err := b.GetCauses(ctx)
if err != nil {
return 0, err
}
for _, cause := range causes {
if build, ok := cause["upstreamBuild"]; ok {
switch t := build.(type) {
default:
return t.(int64), nil
case float64:
return int64(t), nil
}
}
}
return 0, nil
}
func (b *Build) GetUpstreamBuild(ctx context.Context) (*Build, error) {
job, err := b.GetUpstreamJob(ctx)
if err != nil {
return nil, err
}
if job != nil {
buildNumber, err := b.GetUpstreamBuildNumber(ctx)
if err == nil && buildNumber != 0 {
return job.GetBuild(ctx, buildNumber)
}
}
return nil, errors.New("Build not found")
}
func (b *Build) GetMatrixRuns(ctx context.Context) ([]*Build, error) {
_, err := b.Poll(ctx, 0)
if err != nil {
return nil, err
}
runs := b.Raw.Runs
result := make([]*Build, len(b.Raw.Runs))
r, _ := regexp.Compile(`job/(.*?)/(.*?)/(\d+)/`)
for i, run := range runs {
result[i] = &Build{Jenkins: b.Jenkins, Job: b.Job, Raw: new(BuildResponse), Depth: 1, Base: "/" + r.FindString(run.URL)}
result[i].Poll(ctx)
}
return result, nil
}
func (b *Build) GetResultSet(ctx context.Context) (*TestResult, error) {
url := b.Base + "/testReport"
var report TestResult
_, err := b.Jenkins.Requester.GetJSON(ctx, url, &report, nil)
if err != nil {
return nil, err
}
return &report, nil
}
func (b *Build) GetTimestamp() time.Time {
msInt := int64(b.Raw.Timestamp)
return time.Unix(0, msInt*int64(time.Millisecond))
}
func (b *Build) GetDuration() float64 {
return b.Raw.Duration
}
func (b *Build) GetRevision() string {
vcs := b.Raw.ChangeSet.Kind
if vcs == "git" || vcs == "hg" {
for _, a := range b.Raw.Actions {
if a.LastBuiltRevision.SHA1 != "" {
return a.LastBuiltRevision.SHA1
}
if a.MercurialRevisionNumber != "" {
return a.MercurialRevisionNumber
}
}
} else if vcs == "svn" {
return strconv.Itoa(b.Raw.ChangeSet.Revisions[0].Revision)
}
return ""
}
func (b *Build) GetRevisionBranch() string {
vcs := b.Raw.ChangeSet.Kind
if vcs == "git" {
for _, a := range b.Raw.Actions {
if len(a.LastBuiltRevision.Branch) > 0 && a.LastBuiltRevision.Branch[0].SHA1 != "" {
return a.LastBuiltRevision.Branch[0].SHA1
}
}
} else {
panic("Not implemented")
}
return ""
}
func (b *Build) IsGood(ctx context.Context) bool {
return (!b.IsRunning(ctx) && b.Raw.Result == STATUS_SUCCESS)
}
func (b *Build) IsRunning(ctx context.Context) bool {
_, err := b.Poll(ctx)
if err != nil {
return false
}
return b.Raw.Building
}
func (b *Build) SetDescription(ctx context.Context, description string) error {
data := url.Values{}
data.Set("description", description)
_, err := b.Jenkins.Requester.Post(ctx, b.Base+"/submitDescription", bytes.NewBufferString(data.Encode()), nil, nil)
return err
}
// Poll for current data. Optional parameter - depth.
// More about depth here: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API
func (b *Build) Poll(ctx context.Context, options ...interface{}) (int, error) {
depth := "-1"
for _, o := range options {
switch v := o.(type) {
case string:
depth = v
case int:
depth = strconv.Itoa(v)
case int64:
depth = strconv.FormatInt(v, 10)
}
}
if depth == "-1" {
depth = strconv.Itoa(b.Depth)
}
qr := map[string]string{
"depth": depth,
}
response, err := b.Jenkins.Requester.GetJSON(ctx, b.Base, b.Raw, qr)
if err != nil {
return 0, err
}
return response.StatusCode, nil
}