-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
kibanaPipeline.groovy
467 lines (409 loc) · 12.7 KB
/
kibanaPipeline.groovy
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
def withPostBuildReporting(Map params, Closure closure) {
try {
closure()
} finally {
def parallelWorkspaces = []
try {
parallelWorkspaces = getParallelWorkspaces()
} catch(ex) {
print ex
}
if (params.runErrorReporter) {
catchErrors {
runErrorReporter([pwd()] + parallelWorkspaces)
}
}
catchErrors {
publishJunit()
}
catchErrors {
def parallelWorkspace = "${env.WORKSPACE}/parallel"
if (fileExists(parallelWorkspace)) {
dir(parallelWorkspace) {
def workspaceTasks = [:]
parallelWorkspaces.each { workspaceDir ->
workspaceTasks[workspaceDir] = {
dir(workspaceDir) {
catchErrors {
runbld.junit()
}
}
}
}
if (workspaceTasks) {
parallel(workspaceTasks)
}
}
}
}
}
}
def getParallelWorkspaces() {
def workspaces = []
def parallelWorkspace = "${env.WORKSPACE}/parallel"
if (fileExists(parallelWorkspace)) {
dir(parallelWorkspace) {
// findFiles only returns files if you use glob, so look for a file that should be in every valid workspace
workspaces = findFiles(glob: '*/kibana/package.json')
.collect {
// get the paths to the kibana directories for the parallel workspaces
return parallelWorkspace + '/' + it.path.tokenize('/').dropRight(1).join('/')
}
}
}
return workspaces
}
def notifyOnError(Closure closure) {
try {
closure()
} catch (ex) {
// If this is the first failed step, it's likely that the error hasn't propagated up far enough to mark the build as a failure
currentBuild.result = 'FAILURE'
catchErrors {
githubPr.sendComment(false)
}
catchErrors {
// an empty map is a valid config, but is falsey, so let's use .has()
if (buildState.has('SLACK_NOTIFICATION_CONFIG')) {
slackNotifications.sendFailedBuild(buildState.get('SLACK_NOTIFICATION_CONFIG'))
}
}
throw ex
}
}
def withFunctionalTestEnv(List additionalEnvs = [], Closure closure) {
// This can go away once everything that uses the deprecated workers.parallelProcesses() is moved to task queue
def parallelId = env.TASK_QUEUE_PROCESS_ID ?: env.CI_PARALLEL_PROCESS_NUMBER
def kibanaPort = "61${parallelId}1"
def esPort = "61${parallelId}2"
def esTransportPort = "61${parallelId}3"
def fleetPackageRegistryPort = "61${parallelId}4"
def alertingProxyPort = "61${parallelId}5"
def corsTestServerPort = "61${parallelId}6"
def apmActive = githubPr.isPr() ? "false" : "true"
withEnv([
"CI_GROUP=${parallelId}",
"REMOVE_KIBANA_INSTALL_DIR=1",
"CI_PARALLEL_PROCESS_NUMBER=${parallelId}",
"TEST_KIBANA_HOST=localhost",
"TEST_KIBANA_PORT=${kibanaPort}",
"TEST_KIBANA_URL=http://elastic:changeme@localhost:${kibanaPort}",
"TEST_ES_URL=http://elastic:changeme@localhost:${esPort}",
"TEST_ES_TRANSPORT_PORT=${esTransportPort}",
"TEST_CORS_SERVER_PORT=${corsTestServerPort}",
"KBN_NP_PLUGINS_BUILT=true",
"FLEET_PACKAGE_REGISTRY_PORT=${fleetPackageRegistryPort}",
"ALERTING_PROXY_PORT=${alertingProxyPort}",
"ELASTIC_APM_ACTIVE=${apmActive}",
"ELASTIC_APM_TRANSACTION_SAMPLE_RATE=0.1",
] + additionalEnvs) {
closure()
}
}
def functionalTestProcess(String name, Closure closure) {
return {
notifyOnError {
withFunctionalTestEnv(["JOB=${name}"], closure)
}
}
}
def functionalTestProcess(String name, String script) {
return functionalTestProcess(name) {
retryable(name) {
runbld(script, "Execute ${name}")
}
}
}
def ossCiGroupProcess(ciGroup) {
return functionalTestProcess("ciGroup" + ciGroup) {
withEnv([
"CI_GROUP=${ciGroup}",
"JOB=kibana-ciGroup${ciGroup}",
]) {
retryable("kibana-ciGroup${ciGroup}") {
runbld("./test/scripts/jenkins_ci_group.sh", "Execute kibana-ciGroup${ciGroup}")
}
}
}
}
def xpackCiGroupProcess(ciGroup) {
return functionalTestProcess("xpack-ciGroup" + ciGroup) {
withEnv([
"CI_GROUP=${ciGroup}",
"JOB=xpack-kibana-ciGroup${ciGroup}",
]) {
retryable("xpack-kibana-ciGroup${ciGroup}") {
runbld("./test/scripts/jenkins_xpack_ci_group.sh", "Execute xpack-kibana-ciGroup${ciGroup}")
}
}
}
}
def uploadGcsArtifact(uploadPrefix, pattern) {
googleStorageUpload(
credentialsId: 'kibana-ci-gcs-plugin',
bucket: "gs://${uploadPrefix}",
pattern: pattern,
sharedPublicly: true,
showInline: true,
)
}
def downloadCoverageArtifacts() {
def storageLocation = "gs://kibana-ci-artifacts/jobs/${env.JOB_NAME}/${BUILD_NUMBER}/coverage/"
def targetLocation = "/tmp/downloaded_coverage"
sh "mkdir -p '${targetLocation}' && gsutil -m cp -r '${storageLocation}' '${targetLocation}'"
}
def uploadCoverageArtifacts(prefix, pattern) {
def uploadPrefix = "kibana-ci-artifacts/jobs/${env.JOB_NAME}/${BUILD_NUMBER}/coverage/${prefix}"
uploadGcsArtifact(uploadPrefix, pattern)
}
def withGcsArtifactUpload(workerName, closure) {
def uploadPrefix = "kibana-ci-artifacts/jobs/${env.JOB_NAME}/${BUILD_NUMBER}/${workerName}"
def ARTIFACT_PATTERNS = [
'target/junit/**/*',
'target/kibana-*',
'target/kibana-coverage/jest/**/*',
'target/kibana-security-solution/**/*.png',
'target/test-metrics/*',
'target/test-suites-ci-plan.json',
'test/**/screenshots/diff/*.png',
'test/**/screenshots/failure/*.png',
'test/**/screenshots/session/*.png',
'test/functional/failure_debug/html/*.html',
'x-pack/test/**/screenshots/diff/*.png',
'x-pack/test/**/screenshots/failure/*.png',
'x-pack/test/**/screenshots/session/*.png',
'x-pack/test/functional/apps/reporting/reports/session/*.pdf',
'x-pack/test/functional/failure_debug/html/*.html',
]
withEnv([
"GCS_UPLOAD_PREFIX=${uploadPrefix}"
], {
try {
closure()
} finally {
catchErrors {
ARTIFACT_PATTERNS.each { pattern ->
uploadGcsArtifact(uploadPrefix, pattern)
}
dir(env.WORKSPACE) {
ARTIFACT_PATTERNS.each { pattern ->
uploadGcsArtifact(uploadPrefix, "parallel/*/kibana/${pattern}")
}
}
}
}
})
if (env.CODE_COVERAGE) {
sh 'tar -czf kibana-coverage.tar.gz target/kibana-coverage/**/*'
uploadGcsArtifact("kibana-ci-artifacts/jobs/${env.JOB_NAME}/${BUILD_NUMBER}/coverage/${workerName}", 'kibana-coverage.tar.gz')
}
}
def publishJunit() {
junit(testResults: 'target/junit/**/*.xml', allowEmptyResults: true, keepLongStdio: true)
dir(env.WORKSPACE) {
junit(testResults: 'parallel/*/kibana/target/junit/**/*.xml', allowEmptyResults: true, keepLongStdio: true)
}
}
def sendMail(Map params = [:]) {
// If the build doesn't have a result set by this point, there haven't been any errors and it can be marked as a success
// The e-mail plugin for the infra e-mail depends upon this being set
currentBuild.result = currentBuild.result ?: 'SUCCESS'
def buildStatus = buildUtils.getBuildStatus()
if (buildStatus != 'SUCCESS' && buildStatus != 'ABORTED') {
node('flyweight') {
sendInfraMail()
sendKibanaMail(params)
}
}
}
def sendInfraMail() {
catchErrors {
step([
$class: 'Mailer',
notifyEveryUnstableBuild: true,
recipients: '[email protected]',
sendToIndividuals: false
])
}
}
def sendKibanaMail(Map params = [:]) {
def config = [to: '[email protected]'] + params
catchErrors {
def buildStatus = buildUtils.getBuildStatus()
if(params.NOTIFY_ON_FAILURE && buildStatus != 'SUCCESS' && buildStatus != 'ABORTED') {
emailext(
config.to,
subject: "${env.JOB_NAME} - Build # ${env.BUILD_NUMBER} - ${buildStatus}",
body: '${SCRIPT,template="groovy-html.template"}',
mimeType: 'text/html',
)
}
}
}
def bash(script, label) {
sh(
script: "#!/bin/bash\n${script}",
label: label
)
}
def doSetup() {
notifyOnError {
retryWithDelay(2, 15) {
try {
runbld("./test/scripts/jenkins_setup.sh", "Setup Build Environment and Dependencies")
} catch (ex) {
try {
// Setup expects this directory to be missing, so we need to remove it before we do a retry
bash("rm -rf ../elasticsearch", "Remove elasticsearch sibling directory, if it exists")
} finally {
throw ex
}
}
}
}
}
def buildOss(maxWorkers = '') {
notifyOnError {
withEnv(["KBN_OPTIMIZER_MAX_WORKERS=${maxWorkers}"]) {
runbld("./test/scripts/jenkins_build_kibana.sh", "Build OSS/Default Kibana")
}
}
}
def buildXpack(maxWorkers = '') {
notifyOnError {
withEnv(["KBN_OPTIMIZER_MAX_WORKERS=${maxWorkers}"]) {
runbld("./test/scripts/jenkins_xpack_build_kibana.sh", "Build X-Pack Kibana")
}
}
}
def runErrorReporter() {
return runErrorReporter([pwd()])
}
def runErrorReporter(workspaces) {
def status = buildUtils.getBuildStatus()
def dryRun = status != "ABORTED" ? "" : "--no-github-update"
def globs = workspaces.collect { "'${it}/target/junit/**/*.xml'" }.join(" ")
bash(
"""
source src/dev/ci_setup/setup_env.sh
node scripts/report_failed_tests ${dryRun} ${globs}
""",
"Report failed tests, if necessary"
)
}
def call(Map params = [:], Closure closure) {
def config = [timeoutMinutes: 135, checkPrChanges: false, setCommitStatus: false] + params
stage("Kibana Pipeline") {
timeout(time: config.timeoutMinutes, unit: 'MINUTES') {
timestamps {
ansiColor('xterm') {
if (config.setCommitStatus) {
buildState.set('shouldSetCommitStatus', true)
}
if (config.checkPrChanges && githubPr.isPr()) {
pipelineLibraryTests()
print "Checking PR for changes to determine if CI needs to be run..."
if (prChanges.areChangesSkippable()) {
print "No changes requiring CI found in PR, skipping."
return
}
}
try {
closure()
} finally {
if (config.setCommitStatus) {
githubCommitStatus.onFinish()
}
}
}
}
}
}
}
// Creates a task queue using withTaskQueue, and copies the bootstrapped kibana repo into each process's workspace
// Note that node_modules are mostly symlinked to save time/space. See test/scripts/jenkins_setup_parallel_workspace.sh
def withCiTaskQueue(Map options = [:], Closure closure) {
def setupClosure = {
// This can't use runbld, because it expects the source to be there, which isn't yet
bash("${env.WORKSPACE}/kibana/test/scripts/jenkins_setup_parallel_workspace.sh", "Set up duplicate workspace for parallel process")
}
def config = [parallel: 24, setup: setupClosure] + options
withTaskQueue(config) {
closure.call()
}
}
def scriptTask(description, script) {
return {
withFunctionalTestEnv {
notifyOnError {
runbld(script, description)
}
}
}
}
def scriptTaskDocker(description, script) {
return {
withDocker(scriptTask(description, script))
}
}
def buildDocker() {
sh(
script: "./.ci/build_docker.sh",
label: 'Build CI Docker image'
)
}
def withDocker(Closure closure) {
docker
.image('kibana-ci')
.inside(
"-v /etc/runbld:/etc/runbld:ro -v '${env.JENKINS_HOME}:${env.JENKINS_HOME}' -v '/dev/shm/workspace:/dev/shm/workspace' --shm-size 2GB --cpus 4",
closure
)
}
def buildOssPlugins() {
runbld('./test/scripts/jenkins_build_plugins.sh', 'Build OSS Plugins')
}
def buildXpackPlugins() {
runbld('./test/scripts/jenkins_xpack_build_plugins.sh', 'Build X-Pack Plugins')
}
def withTasks(Map params = [worker: [:]], Closure closure) {
catchErrors {
def config = [name: 'ci-worker', size: 'xxl', ramDisk: true] + (params.worker ?: [:])
workers.ci(config) {
withCiTaskQueue(parallel: 24) {
parallel([
docker: {
retry(2) {
buildDocker()
}
},
// There are integration tests etc that require the plugins to be built first, so let's go ahead and build them before set up the parallel workspaces
ossPlugins: { buildOssPlugins() },
xpackPlugins: { buildXpackPlugins() },
])
catchErrors {
closure()
}
}
}
}
}
def allCiTasks() {
withTasks {
tasks.check()
tasks.lint()
tasks.test()
tasks.functionalOss()
tasks.functionalXpack()
}
}
def pipelineLibraryTests() {
whenChanged(['vars/', '.ci/pipeline-library/']) {
workers.base(size: 'flyweight', bootstrapped: false, ramDisk: false) {
dir('.ci/pipeline-library') {
sh './gradlew test'
}
}
}
}
return this