-
Notifications
You must be signed in to change notification settings - Fork 169
/
update.js
269 lines (227 loc) · 9.8 KB
/
update.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
265
266
267
268
269
'use strict';
const boom = require('@hapi/boom');
const hoek = require('@hapi/hoek');
const schema = require('screwdriver-data-schema');
const joi = require('joi');
const idSchema = schema.models.job.base.extract('id');
const { getScmUri, getUserPermissions } = require('../helper');
/**
* Identify whether this build resulted in a previously failed job to become successful.
*
* @method isFixedBuild
* @param build Build Object
* @param jobFactory Job Factory instance
*/
async function isFixedBuild(build, jobFactory) {
if (build.status !== 'SUCCESS') {
return false;
}
const job = await jobFactory.get(build.jobId);
const failureBuild = await job.getLatestBuild({ status: 'FAILURE' });
const successBuild = await job.getLatestBuild({ status: 'SUCCESS' });
if ((failureBuild && !successBuild) || failureBuild.id > successBuild.id) {
return true;
}
return false;
}
/**
* Stops a frozen build from executing
* @method stopFrozenBuild
* @param {Object} build Build Object
* @param {String} previousStatus Prevous build status
*/
async function stopFrozenBuild(build, previousStatus) {
if (previousStatus !== 'FROZEN') {
return Promise.resolve();
}
return build.stopFrozen(previousStatus);
}
/**
* Updates execution details for init step
* @method stopFrozenBuild
* @param {Object} build Build Object
* @param {Object} app Hapi app Object
*/
async function updateInitStep(build, app) {
const step = await app.stepFactory.get({ buildId: build.id, name: 'sd-setup-init' });
// If there is no init step, do nothing
if (!step) {
return null;
}
step.endTime = build.startTime || new Date().toISOString();
step.code = 0;
return step.update();
}
/**
* Validate if build status can be updated
* @method validateBuildStatus
* @param {String} id Build Id
* @param {Object} buildFactory Build factory object to quey build store
*/
async function getBuildToUpdate(id, buildFactory) {
const build = await buildFactory.get(id);
if (!build) {
throw boom.notFound(`Build ${id} does not exist`);
}
// Check build status
if (!['RUNNING', 'QUEUED', 'BLOCKED', 'UNSTABLE', 'FROZEN'].includes(build.status)) {
throw boom.forbidden('Can only update RUNNING, QUEUED, BLOCKED, FROZEN, or UNSTABLE builds');
}
return build;
}
/**
*
* @param {Object} build Build object
* @param {Object} request hapi request object
* @throws boom.badRequest on validation error
*/
async function validateUserPermission(build, request) {
const { jobFactory, userFactory, bannerFactory, pipelineFactory } = request.server.app;
const { username, scmContext } = request.auth.credentials;
const { status: desiredStatus } = request.payload;
const scmDisplayName = bannerFactory.scm.getDisplayName({ scmContext });
// Check if Screwdriver admin
const adminDetails = request.server.plugins.banners.screwdriverAdminDetails(username, scmDisplayName);
// Check desired status
if (adminDetails.isAdmin) {
if (desiredStatus !== 'ABORTED' && desiredStatus !== 'FAILURE') {
throw boom.badRequest('Admin can only update builds to ABORTED or FAILURE');
}
} else if (desiredStatus !== 'ABORTED') {
throw boom.badRequest('User can only update builds to ABORTED');
}
// Check permission against the pipeline
// Fetch the job and user models
const [job, user] = await Promise.all([jobFactory.get(build.jobId), userFactory.get({ username, scmContext })]);
const pipeline = await job.pipeline;
// Use parent's scmUri if pipeline is child pipeline and using read-only SCM
const scmUri = await getScmUri({ pipeline, pipelineFactory });
// Check the user's permission
await getUserPermissions({ user, scmUri, level: 'push', isAdmin: adminDetails.isAdmin });
}
/**
*
* @param {Object} build Build Model
* @param {String} desiredStatus New Status
* @param {String} statusMessage User passed status message
* @param {String} username User initiating status build update
*/
function updateBuildStatus(build, desiredStatus, statusMessage, username) {
// UNSTABLE -> SUCCESS needs to update meta and endtime.
// However, the status itself cannot be updated to SUCCESS
const currentStatus = build.status;
if (currentStatus !== 'UNSTABLE') {
if (desiredStatus !== undefined) {
build.status = desiredStatus;
}
if (build.status === 'ABORTED') {
if (currentStatus === 'FROZEN') {
build.statusMessage = `Frozen build aborted by ${username}`;
} else {
build.statusMessage = `Aborted by ${username}`;
}
} else if (build.status === 'FAILURE' || build.status === 'SUCCESS') {
if (statusMessage) {
build.statusMessage = statusMessage;
}
} else {
build.statusMessage = statusMessage || null;
}
}
}
module.exports = () => ({
method: 'PUT',
path: '/builds/{id}',
options: {
description: 'Update a build',
notes: 'Update a specific build',
tags: ['api', 'builds'],
auth: {
strategies: ['token'],
scope: ['build', 'pipeline', 'user', '!guest', 'temporal']
},
handler: async (request, h) => {
const { buildFactory, eventFactory, jobFactory } = request.server.app;
const { id } = request.params;
const { statusMessage, stats, status: desiredStatus } = request.payload;
const { username, scmContext, scope } = request.auth.credentials;
const isBuild = scope.includes('build') || scope.includes('temporal');
const { triggerNextJobs, removeJoinBuilds } = request.server.plugins.builds;
if (isBuild && username !== id) {
return boom.forbidden(`Credential only valid for ${username}`);
}
const build = await getBuildToUpdate(id, buildFactory);
const currentStatus = build.status;
if (!isBuild) {
await validateUserPermission(build, request);
}
const event = await eventFactory.get(build.eventId);
if (stats) {
// need to do this so the field is dirty
build.stats = Object.assign(build.stats, stats);
}
// Short circuit for cases that don't need to update status
if (!desiredStatus) {
build.statusMessage = statusMessage || build.statusMessage;
} else if (['SUCCESS', 'FAILURE', 'ABORTED'].includes(desiredStatus)) {
build.meta = request.payload.meta || {};
event.meta = { ...event.meta, ...build.meta };
build.endTime = new Date().toISOString();
} else if (desiredStatus === 'RUNNING') {
build.startTime = new Date().toISOString();
} else if (desiredStatus === 'BLOCKED' && !hoek.reach(build, 'stats.blockedStartTime')) {
build.stats = Object.assign(build.stats, {
blockedStartTime: new Date().toISOString()
});
} else if (desiredStatus === 'QUEUED' && currentStatus !== 'QUEUED') {
throw boom.badRequest(`Cannot update builds to ${desiredStatus}`);
} else if (desiredStatus === 'BLOCKED' && currentStatus === 'BLOCKED') {
// Queue-Service can call BLOCKED status update multiple times
throw boom.badRequest(`Cannot update builds to ${desiredStatus}`);
}
let isFixed = Promise.resolve(false);
let stopFrozen = null;
updateBuildStatus(build, desiredStatus, statusMessage, username);
// If status got updated to RUNNING or COLLAPSED, update init endTime and code
if (['RUNNING', 'COLLAPSED', 'FROZEN'].includes(desiredStatus)) {
await updateInitStep(build, request.server.app);
} else {
stopFrozen = stopFrozenBuild(build, currentStatus);
isFixed = isFixedBuild(build, jobFactory);
}
const [newBuild, newEvent] = await Promise.all([build.update(), event.update(), stopFrozen]);
const job = await newBuild.job;
const pipeline = await job.pipeline;
if (desiredStatus) {
await request.server.events.emit('build_status', {
settings: job.permutations[0].settings,
status: newBuild.status,
event: newEvent.toJson(),
pipeline: pipeline.toJson(),
jobName: job.name,
build: newBuild.toJson(),
buildLink: `${buildFactory.uiUri}/pipelines/${pipeline.id}/builds/${id}`,
isFixed: await isFixed
});
}
const skipFurther = /\[(skip further)\]/.test(newEvent.causeMessage);
// Guard against triggering non-successful or unstable builds
// Don't further trigger pipeline if intented to skip further jobs
if (newBuild.status !== 'SUCCESS' || skipFurther) {
// Check for failed jobs and remove any child jobs in created state
if (newBuild.status === 'FAILURE') {
await removeJoinBuilds({ pipeline, job, build: newBuild }, request.server.app);
}
} else {
await triggerNextJobs({ pipeline, job, build: newBuild, username, scmContext }, request.server.app);
}
return h.response(await newBuild.toJsonWithSteps()).code(200);
},
validate: {
params: joi.object({
id: idSchema
}),
payload: schema.models.build.update
}
}
});