-
Notifications
You must be signed in to change notification settings - Fork 582
/
jenkins.go
289 lines (252 loc) · 9.2 KB
/
jenkins.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
package orchestrator
import (
"encoding/json"
"io"
"strings"
"time"
"github.com/Jeffail/gabs/v2"
piperHttp "github.com/SAP/jenkins-library/pkg/http"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/pkg/errors"
)
type jenkinsConfigProvider struct {
client piperHttp.Client
apiInformation map[string]interface{}
}
func newJenkinsConfigProvider() *jenkinsConfigProvider {
return &jenkinsConfigProvider{}
}
// Configure initializes the Jenkins orchestrator with credentials
func (j *jenkinsConfigProvider) Configure(opts *Options) error {
j.client.SetOptions(piperHttp.ClientOptions{
Username: opts.JenkinsUser,
Password: opts.JenkinsToken,
MaxRetries: 3,
TransportTimeout: time.Second * 10,
})
log.Entry().Debug("Successfully initialized Jenkins config provider")
return nil
}
// OrchestratorVersion returns the orchestrator version currently running on
func (j *jenkinsConfigProvider) OrchestratorVersion() string {
return getEnv("JENKINS_VERSION", "n/a")
}
// OrchestratorType returns the orchestrator type Jenkins
func (j *jenkinsConfigProvider) OrchestratorType() string {
return "Jenkins"
}
func (j *jenkinsConfigProvider) fetchAPIInformation() {
if len(j.apiInformation) == 0 {
log.Entry().Debugf("apiInformation is empty, getting infos from API")
URL := j.BuildURL() + "api/json"
log.Entry().Debugf("API URL: %s", URL)
response, err := j.client.GetRequest(URL, nil, nil)
if err != nil {
log.Entry().WithError(err).Error("could not get API information from Jenkins")
j.apiInformation = map[string]interface{}{}
return
}
if response.StatusCode != 200 { //http.StatusNoContent
log.Entry().Errorf("Response-Code is %v, could not get timestamp from Jenkins. Setting timestamp to 1970.", response.StatusCode)
j.apiInformation = map[string]interface{}{}
return
}
err = piperHttp.ParseHTTPResponseBodyJSON(response, &j.apiInformation)
if err != nil {
log.Entry().WithError(err).Errorf("could not parse HTTP response body")
j.apiInformation = map[string]interface{}{}
return
}
log.Entry().Debugf("successfully retrieved apiInformation")
} else {
log.Entry().Debugf("apiInformation already set")
}
}
// BuildStatus returns build status of the current job
func (j *jenkinsConfigProvider) BuildStatus() string {
j.fetchAPIInformation()
if val, ok := j.apiInformation["result"]; ok {
// cases in ADO: succeeded, failed, canceled, none, partiallySucceeded
switch result := val; result {
case "SUCCESS":
return BuildStatusSuccess
case "ABORTED":
return BuildStatusAborted
default:
// FAILURE, NOT_BUILT
return BuildStatusFailure
}
}
return BuildStatusFailure
}
// ChangeSet returns the commitIds and timestamp of the changeSet of the current run
func (j *jenkinsConfigProvider) ChangeSets() []ChangeSet {
j.fetchAPIInformation()
marshal, err := json.Marshal(j.apiInformation)
if err != nil {
log.Entry().WithError(err).Debugf("could not marshal apiInformation")
return []ChangeSet{}
}
jsonParsed, err := gabs.ParseJSON(marshal)
if err != nil {
log.Entry().WithError(err).Debugf("could not parse apiInformation")
return []ChangeSet{}
}
var changeSetList []ChangeSet
for _, child := range jsonParsed.Path("changeSets").Children() {
if child.Path("kind").Data().(string) == "git" {
for _, item := range child.S("items").Children() {
tmpChangeSet := ChangeSet{
CommitId: item.Path("commitId").Data().(string),
Timestamp: item.Path("timestamp").String(),
}
changeSetList = append(changeSetList, tmpChangeSet)
}
}
}
return changeSetList
}
// FullLogs returns the logfile from the current job as byte object
func (j *jenkinsConfigProvider) FullLogs() ([]byte, error) {
URL := j.BuildURL() + "consoleText"
response, err := j.client.GetRequest(URL, nil, nil)
if err != nil {
return []byte{}, errors.Wrapf(err, "could not GET Jenkins log file %v", err)
} else if response.StatusCode != 200 {
log.Entry().Error("response code !=200 could not get log information from Jenkins, returning with empty log.")
return []byte{}, nil
}
logFile, err := io.ReadAll(response.Body)
if err != nil {
return []byte{}, errors.Wrapf(err, "could not read Jenkins log file from request %v", err)
}
defer response.Body.Close()
return logFile, nil
}
// PipelineStartTime returns the pipeline start time in UTC
func (j *jenkinsConfigProvider) PipelineStartTime() time.Time {
URL := j.BuildURL() + "api/json"
response, err := j.client.GetRequest(URL, nil, nil)
if err != nil {
log.Entry().WithError(err).Errorf("could not getRequest to URL %s", URL)
return time.Time{}.UTC()
}
if response.StatusCode != 200 { //http.StatusNoContent -> also empty log!
log.Entry().Errorf("response code is %v . \n Could not get timestamp from Jenkins. Setting timestamp to 1970.", response.StatusCode)
return time.Time{}.UTC()
}
var responseInterface map[string]interface{}
err = piperHttp.ParseHTTPResponseBodyJSON(response, &responseInterface)
if err != nil {
log.Entry().WithError(err).Infof("could not parse http response, returning 1970")
return time.Time{}.UTC()
}
rawTimeStamp := responseInterface["timestamp"].(float64)
timeStamp := time.Unix(int64(rawTimeStamp)/1000, 0)
log.Entry().Debugf("Pipeline start time: %v", timeStamp.String())
defer response.Body.Close()
return timeStamp.UTC()
}
// JobName returns the job name of the current job e.g. foo/bar/BRANCH
func (j *jenkinsConfigProvider) JobName() string {
return getEnv("JOB_NAME", "n/a")
}
// JobURL returns the current job URL e.g. https://jaas.url/job/foo/job/bar/job/main
func (j *jenkinsConfigProvider) JobURL() string {
return getEnv("JOB_URL", "n/a")
}
// getJenkinsHome returns the jenkins home e.g. /var/lib/jenkins
func (j *jenkinsConfigProvider) getJenkinsHome() string {
return getEnv("JENKINS_HOME", "n/a")
}
// BuildID returns the build ID of the current job, e.g. 1234
func (j *jenkinsConfigProvider) BuildID() string {
return getEnv("BUILD_ID", "n/a")
}
// StageName returns the stage name the job is currently in, e.g. Promote
func (j *jenkinsConfigProvider) StageName() string {
return getEnv("STAGE_NAME", "n/a")
}
// BuildReason returns the build reason of the current build
func (j *jenkinsConfigProvider) BuildReason() string {
// BuildReasons are unified with AzureDevOps build reasons,see
// https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#build-variables-devops-services
// ResourceTrigger, PullRequest, Manual, IndividualCI, Schedule
j.fetchAPIInformation()
marshal, err := json.Marshal(j.apiInformation)
if err != nil {
log.Entry().WithError(err).Debugf("could not marshal apiInformation")
return BuildReasonUnknown
}
jsonParsed, err := gabs.ParseJSON(marshal)
if err != nil {
log.Entry().WithError(err).Debugf("could not parse apiInformation")
return BuildReasonUnknown
}
for _, child := range jsonParsed.Path("actions").Children() {
class := child.S("_class")
if class == nil {
continue
}
if class.Data().(string) == "hudson.model.CauseAction" {
for _, val := range child.Path("causes").Children() {
subclass := val.S("_class")
if subclass.Data().(string) == "hudson.model.Cause$UserIdCause" {
return BuildReasonManual
} else if subclass.Data().(string) == "hudson.triggers.TimerTrigger$TimerTriggerCause" {
return BuildReasonSchedule
} else if subclass.Data().(string) == "jenkins.branch.BranchEventCause" {
return BuildReasonPullRequest
} else if subclass.Data().(string) == "org.jenkinsci.plugins.workflow.support.steps.build.BuildUpstreamCause" {
return BuildReasonResourceTrigger
} else {
return BuildReasonUnknown
}
}
}
}
return BuildReasonUnknown
}
// Branch returns the branch name, only works with the git plugin enabled
func (j *jenkinsConfigProvider) Branch() string {
return getEnv("BRANCH_NAME", "n/a")
}
// GitReference returns the git reference, only works with the git plugin enabled
func (j *jenkinsConfigProvider) GitReference() string {
ref := getEnv("BRANCH_NAME", "n/a")
if ref == "n/a" {
return ref
} else if strings.Contains(ref, "PR") {
return "refs/pull/" + strings.Split(ref, "-")[1] + "/head"
} else {
return "refs/heads/" + ref
}
}
// BuildURL returns the build url, e.g. https://jaas.url/job/foo/job/bar/job/main/1234/
func (j *jenkinsConfigProvider) BuildURL() string {
return getEnv("BUILD_URL", "n/a")
}
// CommitSHA returns the commit SHA from the current build, only works with the git plugin enabled
func (j *jenkinsConfigProvider) CommitSHA() string {
return getEnv("GIT_COMMIT", "n/a")
}
// RepoURL returns the repo URL of the current build, only works with the git plugin enabled
func (j *jenkinsConfigProvider) RepoURL() string {
return getEnv("GIT_URL", "n/a")
}
// PullRequestConfig returns the pull request config
func (j *jenkinsConfigProvider) PullRequestConfig() PullRequestConfig {
return PullRequestConfig{
Branch: getEnv("CHANGE_BRANCH", "n/a"),
Base: getEnv("CHANGE_TARGET", "n/a"),
Key: getEnv("CHANGE_ID", "n/a"),
}
}
// IsPullRequest returns boolean indicating if current job is a PR
func (j *jenkinsConfigProvider) IsPullRequest() bool {
return envVarIsTrue("CHANGE_ID")
}
func isJenkins() bool {
envVars := []string{"JENKINS_HOME", "JENKINS_URL"}
return envVarsAreSet(envVars)
}