-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathjenkins.js
264 lines (224 loc) · 7.82 KB
/
jenkins.js
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
var cron = require('cron');
var jenkins = require('./api/jenkins');
var job = require('./api/job');
var Swaggy = require('swaggy-jenkins');
var text = require('bagoftext');
var _url = require('url');
var util = require('./cli/util');
var view = require('./api/view');
var fs = require('fs');
text.initLocales(__dirname);
/**
* class Jenkins
*
* @param {String} url: Jenkins URL, fallback to JENKINS_URL environment variable, otherwise default to http://localhost:8080
*/
function Jenkins(url) {
function _authFail(result, cb) {
cb(new Error(text.__('Authentication failed - incorrect username and/or password')));
}
function _authRequire(result, cb) {
cb(new Error(text.__('Jenkins requires authentication - please set username and password')));
}
this.url = url || process.env.JENKINS_URL || 'http://localhost:8080';
// base URL is needed for functionalities that operate against base Jenkins path
// this is needed for retrieving Jenkins crumb where the URL might contain paths to folders,
// but the the Jenkins crumb retrieval still needs to be executed against the base Jenkins path
let parsedUrl = _url.parse(this.url);
this.baseUrl = this.url.replace(parsedUrl.path, '');
var cert = process.env.JENKINS_CERT;
var ca = process.env.JENKINS_CA;
var key = process.env.JENKINS_KEY;
this.opts = {
handlers: {
401: _authFail,
403: _authRequire
}
};
this.remoteAccessApi = new Swaggy.RemoteAccessApi();
this.remoteAccessApi.apiClient.basePath = this.url;
// a new Swaggy.ApiClient must be created here in order
// to force baseApi to not share the same ApiClient as
// remoteAccessApi
// this is necessary because baseApi uses a URL that could be
// different to remoteAccessApi
this.baseApi = new Swaggy.BaseApi(new Swaggy.ApiClient());
this.baseApi.apiClient.basePath = this.baseUrl;
if (cert) {
var key_path = key.split(':')[0];
var passphrase = key.split(':')[1];
this.opts.agentOptions = {
passphrase: passphrase,
secureProtocol: 'TLSv1_method'
};
if(cert && fs.statSync(cert)){
this.opts.agentOptions.cert = fs.readFileSync(cert);
}
if(key_path && fs.statSync(key_path)){
this.opts.agentOptions.key = fs.readFileSync(key_path);
}
if(ca && fs.statSync(ca)){
this.opts.agentOptions.ca = fs.readFileSync(ca);
}
}
}
/**
* Add Jenkins crumb header to instance.
* This is needed for Jenkins installations that have CSRF protection enabled.
* New installations of Jenkins starting version 2.x enables CSRF protection by default.
* https://wiki.jenkins-ci.org/display/JENKINS/CSRF+Protection
*
* @param {Function} cb: standard cb(err, result) callback
*/
function csrf(cb) {
var self = this;
this.opts.headers = this.opts.headers || {};
function resultCb(err, data, response) {
if (!err) {
self.opts.headers[data.crumbRequestField] = data.crumb;
self.opts.headers.jenkinsCrumb = data.crumb;
}
cb(err, data);
}
this.crumb(resultCb);
}
/**
* Summarise executor information from computers array.
*
* @param {Array} computers: computers array, part of Jenkins#computer result
* @return executor summary object
*/
function executorSummary(computers) {
var data = {};
computers.forEach(function (computer) {
var idleCount = 0;
var activeCount = 0;
data[computer.displayName] = { executors: [] };
computer.executors.forEach(function (executor) {
data[computer.displayName].executors.push({
idle: executor.idle,
stuck: executor.likelyStuck,
progress: executor.progress,
name: (!executor.idle && executor.currentExecutable.url) ?
executor.currentExecutable.url.replace(/.*\/job\//, '').replace(/\/.*/, '') :
undefined
});
if (executor.idle) {
idleCount += 1;
} else {
activeCount += 1;
}
});
var summary = [];
if (activeCount > 0) {
summary.push(text.__('%d active', activeCount));
}
if (idleCount > 0) {
summary.push(text.__('%d idle', idleCount));
}
data[computer.displayName].summary = summary.join(', ');
});
return data;
}
/**
* Monitor Jenkins latest build status on a set interval.
*
* @param {Object} opts: optional
* - job: Jenkins job name
* - view: Jenkins view name
* - schedule: cron scheduling definition in standard * * * * * * format, default: 0 * * * * * (every minute)
* @param {Function} cb: standard cb(err, result) callback
*/
function monitor(opts, cb) {
var self = this;
function singleJobResultCb(err, result) {
if (!err) {
result = util.statusByColor(result.color);
}
cb(err, result);
}
// when there are multiple jobs, status is derived following these rules:
// - fail if any job has Jenkins color red
// - warn if any job has Jenkins color yellow but no red
// - non-success (e.g. notbuilt) if any job has Jenkins color status but no red and yellow
// - success only if all jobs are either blue or green
function multiJobsResultCb(err, result) {
if (!err) {
var hasRed = false;
var hasYellow = false;
var hasNonSuccess = false;
var hasSuccess = false;
var successColor;
var nonSuccessColor;
result.jobs.forEach(function (job) {
if (job.color === 'red') {
hasRed = true;
}
if (job.color === 'yellow') {
hasYellow = true;
}
if (['red', 'yellow', 'blue', 'green'].indexOf(job.color) === -1) {
hasNonSuccess = true;
nonSuccessColor = job.color;
}
if (job.color === 'blue' || job.color === 'green') {
hasSuccess = true;
successColor = job.color;
}
});
var resultColor;
if (hasRed) {
resultColor = 'red';
} else if (hasYellow) {
resultColor = 'yellow';
} else if (hasNonSuccess) {
resultColor = nonSuccessColor;
} else {
resultColor = successColor;
}
result = util.statusByColor(resultColor);
}
cb(err, result);
}
function _notify() {
if (opts.job) {
self.readJob(opts.job, singleJobResultCb);
} else if (opts.view) {
self.readView(opts.view, multiJobsResultCb);
} else {
self.info(multiJobsResultCb);
}
}
_notify();
new cron.CronJob(opts.schedule || '0 * * * * *', _notify).start();
}
Jenkins.prototype.csrf = csrf;
Jenkins.prototype.discover = jenkins.discover;
Jenkins.prototype.computer = jenkins.computer;
Jenkins.prototype.crumb = jenkins.crumb;
Jenkins.prototype.info = jenkins.info;
Jenkins.prototype.monitor = monitor;
Jenkins.prototype.parseFeed = jenkins.parseFeed;
Jenkins.prototype.queue = jenkins.queue;
Jenkins.prototype.version = jenkins.version;
Jenkins.prototype.createJob = job.create;
Jenkins.prototype.readJob = job.read;
Jenkins.prototype.readLatestJob = job.readLatest;
Jenkins.prototype.updateJob = job.update;
Jenkins.prototype.deleteJob = job.delete;
Jenkins.prototype.buildJob = job.build;
Jenkins.prototype.checkBuildStarted = job.checkStarted;
Jenkins.prototype.stopJob = job.stop;
Jenkins.prototype.streamJobConsole = job.streamConsole;
Jenkins.prototype.enableJob = job.enable;
Jenkins.prototype.disableJob = job.disable;
Jenkins.prototype.copyJob = job.copy;
Jenkins.prototype.fetchJobConfig = job.fetchConfig;
Jenkins.prototype.parseJobFeed = job.parseFeed;
Jenkins.prototype.createView = view.create;
Jenkins.prototype.readView = view.read;
Jenkins.prototype.updateView = view.update;
Jenkins.prototype.fetchViewConfig = view.fetchConfig;
Jenkins.prototype.parseViewFeed = view.parseFeed;
Jenkins.executorSummary = executorSummary;
module.exports = Jenkins;