/
PipelineValidator.js
384 lines (357 loc) · 13.4 KB
/
PipelineValidator.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
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
// @flow
import fetch from './fetchClassic';
import pipelineStore from './PipelineStore';
import pipelineMetadataService from './PipelineMetadataService';
import type { PipelineInfo, StageInfo, StepInfo } from './PipelineStore';
import { convertInternalModelToJson } from './PipelineSyntaxConverter';
import { isObservableArray } from 'mobx';
import debounce from 'lodash.debounce';
const validationTimeout = 500;
export function isValidEnvironmentKey(key: string): boolean {
if (!key) {
return false;
}
if (/^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/.test(key)) {
return true;
}
return false;
}
function _isArray(o) {
return o instanceof Array || typeof o === 'array' || isObservableArray(o);
}
function _hasValidationErrors(node) {
return node && node.validationErrors && node.validationErrors.length;
}
function _appendValidationError(node, message) {
if (_hasValidationErrors(node)) {
node.validationErrors.push(message);
} else {
node.validationErrors = [message];
}
}
function _validateAgentEntries(metadata, agent) {
if (!agent || agent.type === 'none' || agent.type === 'any') {
return;
}
let meta;
for (const m of metadata.agentMetadata) {
if (agent.type === m.symbol) {
meta = m;
break;
}
}
if (!meta) {
_appendValidationError(meta, 'Unknown agent type: ' + agent.type);
return;
}
meta.parameters.map(param => {
const arg = agent.arguments.filter(arg => arg.key === param.name)[0];
if (param.isRequired && (!arg || !arg.value || !arg.value.value)) {
_appendValidationError(agent, param.name + ' is required');
}
});
}
function _validateEnvironmentEntries(metadata, entries) {
for (const entry of entries) {
if (!_hasValidationErrors(entry) && !isValidEnvironmentKey(entry.key)) {
_appendValidationError(entry, 'Environment Name is not valid. Please ensure it is a valid Pipeline identifier.');
}
}
}
function _validateStepValues(metadata, steps) {
for (const step of steps) {
const meta = metadata.stepMetadata.find(step);
if (meta && meta.isRequired && !step.validationErrors && !step.value.value) {
_appendValidationError(entry, 'Required step value');
}
if (step.children) {
_validateStepValues(metadata, step.children);
}
}
}
function _addClientSideErrors(metadata, node) {
const parent = pipelineStore.findParentStage(node);
if (node.agent) {
_validateAgentEntries(metadata, node.agent);
}
if (node.environment) {
_validateEnvironmentEntries(metadata, node.environment);
}
if (node.steps) {
_validateStepValues(metadata, node.steps);
}
if (!node.children || !node.children.length) {
if (parent && (!node.steps || !node.steps.length)) {
// For this one particular error, just replace it
//node.validationErrors = [];
//node.steps.validationErrors = [ 'At least one step is required' ];
node.validationErrors = ['At least one step is required'];
}
if (node === pipelineStore.pipeline) {
// override default message
node.validationErrors = ['A stage is required'];
}
} else {
node.children.map(child => _addClientSideErrors(metadata, child));
}
}
export class PipelineValidator {
lastPipelineValidated: string;
validatePipeline(pipeline: PipelineInfo, handler: ValidationResult) {
const json = convertInternalModelToJson(pipeline);
fetch(
'/pipeline-model-converter/validateJson',
'json=' + encodeURIComponent(JSON.stringify(json)),
data => {
if (!data.result && data.errors) {
if (window.isDevelopmentMode) console.error(data);
}
handler(data);
},
{ disableLoadingIndicator: true }
);
}
/**
* Indicates this node or any child node has a validation error
*/
hasValidationErrors(node: Object, visited: any[] = []): boolean {
if (visited.indexOf(node) >= 0) {
return false;
}
visited.push(node);
if (_hasValidationErrors(node)) {
return true;
}
// if this is a parallel, check the parent stage for errors
const parent = pipelineStore.findParentStage(node);
if (parent && pipelineStore.pipeline !== parent && parent.validationErrors) {
return true;
}
for (const key of Object.keys(node)) {
const val = node[key];
if (val instanceof Object) {
if (this.hasValidationErrors(val, visited)) {
return true;
}
}
}
return false;
}
/**
* Gets the validation errors for the specific node
*/
getNodeValidationErrors(node: Object, visited: any[] = []): Object[] {
const validationErrors = node.validationErrors ? [...node.validationErrors] : [];
// if this is a parallel, check the parent stage for errors
const parent = pipelineStore.findParentStage(node);
if (parent && pipelineStore.pipeline !== parent && parent.validationErrors) {
validationErrors.push.apply(validationErrors, parent.validationErrors);
}
return validationErrors.length ? validationErrors : null;
}
/**
* Gets all validation errors for the node and all child nodes
*/
getAllValidationErrors(node: Object, visited: any[] = []): Object[] {
if (visited.indexOf(node) >= 0) {
return null;
}
visited.push(node);
const validationErrors = [];
if (_hasValidationErrors(node)) {
validationErrors.push.apply(validationErrors, node.validationErrors);
}
if (node instanceof Array || typeof node === 'array') {
for (const v of node) {
const childErrors = this.getAllValidationErrors(v, visited);
if (childErrors) {
validationErrors.push.apply(validationErrors, childErrors);
}
}
} else if (node instanceof Object) {
for (const key of Object.keys(node)) {
const childErrors = this.getAllValidationErrors(node[key], visited);
if (childErrors) {
validationErrors.push.apply(validationErrors, childErrors);
}
}
}
return validationErrors.length ? validationErrors : null;
}
findNodeFromPath(pipeline: PipelineInfo, path: string[]): any {
// like: "pipeline"/"stages"/"0"/"branches"/"0"/"steps"
let node = pipeline;
for (let i = 0; i < path.length; i++) {
const part = path[i];
switch (part) {
case 'pipeline': {
break;
}
case 'stages': {
const idx = parseInt(path[++i]);
if (parseInt(idx) === idx) {
node = node.children[idx];
}
break;
}
case 'branches': {
const idx = parseInt(path[++i]);
// check if the 'default' single node path vs. parallel
if (!node.children || node.children.length == 0) {
// This probably in a parallel block, and is referencing the default branch, which is this node
} else {
node = node.children[idx];
}
break;
}
case 'parallel': {
const idx = parseInt(path[++i]);
if (!isNaN(idx)) {
node = node.children[idx];
}
break;
}
case 'steps': {
const idx = parseInt(path[++i]);
if (!isNaN(idx)) {
// it is actually the steps array, so just target the node
node = node.steps[idx];
}
break;
}
case 'arguments': {
const idx = parseInt(path[++i]);
if (!isNaN(idx)) {
// it is actually the arguments array, so just target the node
// FIXME ehh, arguments are stored in 'data'
node = node.data;
}
break;
}
default: {
// if we have reached a key/value, just apply the error here
if (node && 'key' in node && 'value' in node) {
return node;
}
// some error with some unknown section, try to find it
// so we can at least display the error
node = node[part];
break;
}
}
}
if (!node) {
if (window.isDevelopmentMode) console.error('unable to find node for', path, 'in', pipeline);
return pipeline;
}
return node;
}
applyValidationMarkers(metadata, pipeline: PipelineInfo, validation: Object): void {
// just make sure nothing is hanging around
this.clearValidationMarkers(pipeline);
if (validation.result == 'failure') {
for (const error of validation.errors) {
if (error.location) {
const node = this.findNodeFromPath(pipeline, error.location);
if (node) {
// ignore errors for nodes that are 'pristine'
if (!node.pristine) {
_appendValidationError(node, error.error);
}
error.applied = true;
}
} else if (error.jenkinsfileErrors) {
for (const globalError of error.jenkinsfileErrors.errors) {
if (_isArray(globalError.error)) {
for (const errorText of globalError.error) {
_appendValidationError(pipeline, errorText);
error.applied = true;
}
} else {
_appendValidationError(pipeline, globalError.error);
error.applied = true;
}
}
}
}
for (const error of validation.errors) {
if (!error.applied) {
if (window.developmentMode) console.error(error);
// surface in the UI
_appendValidationError(pipeline, error.error);
}
}
}
_addClientSideErrors(metadata, pipeline);
}
clearValidationMarkers(node: Object, visited: any[] = []): void {
if (visited.indexOf(node) >= 0) {
return;
}
visited.push(node);
if (node.validationErrors) {
delete node.validationErrors;
}
if (_isArray(node)) {
for (const v of node) {
this.clearValidationMarkers(v, visited);
}
} else if (node instanceof Object) {
for (const key of Object.keys(node)) {
const val = node[key];
if (val instanceof Object) {
this.clearValidationMarkers(val, visited);
}
}
}
}
hasPristineEdits(node: Object, visited: any[] = []) {
if (visited.indexOf(node) >= 0) {
return false;
}
visited.push(node);
if (node.pristine) {
return true;
}
for (const key of Object.keys(node)) {
const val = node[key];
if (val instanceof Object) {
if (this.hasPristineEdits(val, visited)) {
return true;
}
}
}
return false;
}
validateNow(onComplete) {
const pipeline = pipelineStore.pipeline;
const json = JSON.stringify(convertInternalModelToJson(pipeline));
this.lastPipelineValidated = json + (this.hasPristineEdits(pipeline) ? '.' : '');
pipelineMetadataService.getStepListing(stepMetadata => {
pipelineMetadataService.getAgentListing(agentMetadata => {
this.validatePipeline(pipeline, validationResult => {
this.applyValidationMarkers({ stepMetadata, agentMetadata }, pipeline, validationResult);
pipelineStore.setPipeline(pipeline); // notify listeners to re-render
if (onComplete) onComplete();
});
});
});
}
delayedValidate = debounce(() => {
this.validateNow();
}, validationTimeout);
validate(onComplete) {
const json = JSON.stringify(convertInternalModelToJson(pipelineStore.pipeline));
if (this.lastPipelineValidated === json) {
if (onComplete) onComplete();
return;
}
if (!this.lastPipelineValidate) {
this.validateNow(onComplete);
} else {
this.delayedValidate();
}
}
}
const pipelineValidator = new PipelineValidator();
export default pipelineValidator;