Debian Codegraph @

tests/CI/universal-asterisk-nongerrit.jenkinsfile

raw
1 /*
2 * This is a generic jenkinsfile to build Asterisk and optionally
3 * perform one or more of the following:
4 * * Publish the API docs to the wiki
5 * * Run the Unit tests
6 * * Run Testsuite Tests
7 *
8 * This job can be triggered manually from Jenkins or be triggered
9 * automatically on a schedule based on a cron string.
10 *
11 * To use this jenkinsfile, create a new "Multi-Branch Pipeline" job
12 * in Jenkins. For easier configuration, the job name should contain
13 * only letters, numbers, or the "-", "_" and "." special characters.
14 * Use the "by Jenkinsfile" "Build Configuration" mode and specify
15 * the path to this jenkinsfile.
16 *
17 * When you save this job definition, Jenkins will scan the git
18 * repository and find any branches with this Jenkinsfile and then try
19 * run the job. It's expected that the jobs will fail because you
20 * haven't create the config file yet.
21 *
22 * The job is configured from a Jenkins managed config file named
23 * "jobConfig". These files are created using the "Config Files"
24 * option of the base job and are unique to a job so you can create
25 * multiple jobs based on this Jenkinsfile without conflicts.
26 *
27 * Create the file as a "Json file" remembering to change the ID
28 * from the auto-generated UUID to "jobConfig".
29 *
30 * Example contents:
31 * {
32 * cronString: 'H H(0-4) * * *',
33 * jobTimeout: {
34 * timeout: 2,
35 * units: 'HOURS',
36 * },
37 * jobCleanup: {
38 * keepBuilds: 5,
39 * artifactKeepBuilds: 2
40 * },
41 * throttleCategories: [
42 * 'default'
43 * ],
44 * docker: [
45 * images: [
46 * 'asterisk/jenkins-agent-centos7'
47 * ]
48 * ],
49 * buildAsterisk: [
50 * build: true,
51 * env: [
52 * REF_DEBUG: true
53 * ]
54 * ],
55 * unitTests: [
56 * run: true,
57 * testCommand: 'test execute all'
58 * ]
59 * }
60 *
61 * NOTE: The JSON file can actually reference variables from the
62 * environment using string interpolation. For example, if you
63 * need to substitute the current branch in a value for some reason,
64 * you could use:
65 * mybranch: "${BRANCH}"
66 */
67
68 /*
69 * All jobConfig parameters have defaults BUT if left that way,
70 * only an Asterisk build will be done.
71 *
72 * NOTE: Groovy syntax uses brackets "[]" for both arrays and
73 * maps/dictionaries where JSON uses brackets "[]" for arrays but
74 * braces "{}" for maps/dictionaries. Your jobConfig file is JSON
75 * but the defaults below are Groovy.
76 */
77 def jobConfig = [
78 /* Must match a label assigned to agents. */
79 agentLabel: 'swdev-docker',
80 /*
81 * https://jenkins.io/doc/book/pipeline/syntax/#cron-syntax
82 * If empty, job will not be scheduled and must be triggered manually.
83 */
84 cronString: '',
85 /*
86 * An array of strings that name categories defined in Jenkins
87 * Global Settings under "Throttle Concurrent Builds". If you
88 * specify one or more categories, they MUST have been defined
89 * or the job will fail.
90 */
91 throttleCategories: [
92 ],
93 jobTimeout: [
94 /* How long should the job be allowed to run? */
95 timeout: 120,
96 /* Common valid units are "MINUTES", "HOURS", "DAYS". */
97 units: 'MINUTES'
98 ],
99 jobCleanup: [
100 /* The total number of past jobs to keep. */
101 keepBuilds: 14,
102 /* But only this number will have their artifacts saved. */
103 artifactKeepBuilds: 7,
104 /* Clean up the workspace on the agent when the job completes. */
105 cleanupWorkspace: true
106 ],
107 docker: [
108 /* The host and port of our Docker image registry. */
109 registry: 'swdev-docker0:5000',
110 /*
111 * An array of images that can be used for this job.
112 * One will be chosen from the list at random.
113 */
114 images: [
115 'asterisk/jenkins-agent-centos7'
116 ],
117 ],
118 buildAsterisk: [
119 /* Build Asterisk */
120 build: true,
121 /* Additional envuronment variables to pass to buildAsterisk.sh */
122 env: [
123 ]
124 ],
125 unitTests: [
126 /* Run the Asterisk Unit Tests. */
127 run: false,
128 /* The Asterisk CLI command to run the tests. */
129 testCommand: 'test execute all'
130 ],
131 wikiDocs: [
132 /* Build and publish the wiki documentation? */
133 publish: false,
134 /* The URL to the "publish-docs" repository */
135 gitURL: "https://gerrit.asterisk.org/publish-docs",
136 /*
137 * Only for branches that match the regex.
138 * I.E. Only the base branches excluding master.
139 */
140 branchRegex: '^([0-9]+)$'
141 ],
142 testsuite: [
143 /* Run the Testsuite? */
144 run: false,
145 /* The URL to the "testsuite" repository */
146 gitURL: "https://gerrit.asterisk.org/testsuite",
147 /*
148 * The name of the testsuite config file.
149 * See the "Testsuite" stage below for more info.
150 */
151 configFile: 'testsuiteConfig',
152 ]
153 ]
154
155 /*
156 * The easiest way to process the above defaults is to merge the
157 * values from the jobConfig file over the defaults map. Groovy
158 * provides a standard way to do this but it's not a deep operation
159 * so we provide our own deep merge function.
160 */
161 Map merge(Map onto, Map... overrides) {
162 if (!overrides)
163 return onto
164 else if (overrides.length == 1) {
165 overrides[0]?.each { k, v ->
166 if (v instanceof Map && onto[k] instanceof Map)
167 merge((Map) onto[k], (Map) v)
168 else
169 onto[k] = v
170 }
171 return onto
172 }
173 return overrides.inject(onto, { acc, override -> merge(acc, override ?: [:]) })
174 }
175
176 /*
177 * The job setup steps such as reading the config file and merging the
178 * defaults can be done on the "built-in" node before we send the job off
179 * to an agent.
180 */
181 node('built-in') {
182 def tempJobConfig
183 configFileProvider([configFile(fileId: 'jobConfig',
184 replaceTokens: true, variable: 'JOB_CONFIG_FILE')]) {
185 echo "Retrieved jobConfig file from ${env.JOB_CONFIG_FILE}"
186 tempJobConfig = readJSON file: env.JOB_CONFIG_FILE
187 }
188 script {
189 merge(jobConfig, tempJobConfig)
190 echo jobConfig.toString()
191 causeClasses = currentBuild.getBuildCauses()
192 causeClass = causeClasses[0]
193 echo "Build Cause: ${causeClass.toString()}"
194 }
195 }
196
197 pipeline {
198 triggers {
199 /* If jobConfig.cronString is empty (the default), the trigger will be ignored */
200 cron jobConfig.cronString
201 }
202
203 options {
204 throttle(jobConfig.throttleCategories)
205 timeout(time: jobConfig.jobTimeout.timeout, unit: jobConfig.jobTimeout.units)
206 buildDiscarder(
207 logRotator(numToKeepStr: "${jobConfig.jobCleanup.keepBuilds}",
208 artifactNumToKeepStr: "${jobConfig.jobCleanup.artifactKeepBuilds}"))
209 }
210
211 agent {
212 label jobConfig.agentLabel
213 }
214
215 stages {
216 stage ("Setup") {
217 when {
218 /*
219 * When you make changes to the base job or a new branch is discovered
220 * Jenkins tries to run it the job. We probably don't want this to happen
221 * so if "BranchIndexing" was teh cause, don't run any of the steps.
222 */
223 not {
224 triggeredBy 'BranchIndexingCause'
225 }
226 }
227
228 steps { script {
229 createSummary(icon: "/plugin/workflow-job/images/48x48/pipelinejob.png", text: "Docker Host: ${NODE_NAME}")
230 sh "sudo chown -R jenkins:users ."
231 sh "printenv -0 | sort -z | tr '\\0' '\\n'"
232 sh "sudo tests/CI/setupJenkinsEnvironment.sh"
233
234 /* Find a docker image, setup parameters and pull image */
235 def r = currentBuild.startTimeInMillis % jobConfig.docker.images.size()
236 def ri = jobConfig.docker.images[(int)r]
237 echo "Docker Image: ${ri}"
238 def randomImage = jobConfig.docker.registry + "/" + ri
239 echo "Docker Path: ${randomImage}"
240 dockerOptions = "--privileged --ulimit core=0 --ulimit nofile=10240 " +
241 " --tmpfs /tmp:exec,size=1G -v /srv/jenkins:/srv/jenkins:rw -v /srv/cache:/srv/cache:rw " +
242 " --entrypoint=''"
243 buildTag = env.BUILD_TAG.replaceAll(/[^a-zA-Z0-9_.-]/, '-')
244 dockerImage = docker.image(randomImage)
245 dockerImage.pull()
246 }}
247 }
248
249 stage ("Build") {
250 when {
251 expression { jobConfig.buildAsterisk.build }
252 not {
253 triggeredBy 'BranchIndexingCause'
254 }
255 }
256 steps { script {
257 dockerImage.inside(dockerOptions + " --name ${buildTag}-build") {
258 echo 'Building..'
259
260 withEnv(jobConfig.buildAsterisk.env) {
261 sh "./tests/CI/buildAsterisk.sh --branch-name=${BRANCH_NAME} --output-dir=tests/CI/output/Build --cache-dir=/srv/cache"
262 }
263
264 archiveArtifacts allowEmptyArchive: true, defaultExcludes: false, fingerprint: false,
265 artifacts: "tests/CI/output/Build/*"
266 }
267 }}
268 }
269
270 stage ("WikiDocs") {
271 when {
272 expression { jobConfig.wikiDocs.publish }
273 not {
274 triggeredBy 'BranchIndexingCause'
275 }
276 }
277 steps { script {
278 dockerImage.inside(dockerOptions + " --name ${buildTag}-wikidocs") {
279 sh "sudo ./tests/CI/installAsterisk.sh --branch-name=${BRANCH_NAME} --user-group=jenkins:users"
280
281 checkout scm: [$class: 'GitSCM',
282 branches: [[name: "master"]],
283 extensions: [
284 [$class: 'RelativeTargetDirectory', relativeTargetDir: "tests/CI/output/publish-docs"],
285 [$class: 'CloneOption',
286 noTags: true,
287 honorRefspec: true,
288 shallow: false
289 ],
290 ],
291 userRemoteConfigs: [[url: jobConfig.wikiDocs.gitURL]]
292 ]
293 sh "./tests/CI/publishAsteriskDocs.sh --user-group=jenkins:users --branch-name=${BRANCH_NAME} --wiki-doc-branch-regex=\"${jobConfig.wikiDocs.branchRegex}\""
294 }
295 }}
296 }
297
298 stage ("UnitTests") {
299 when {
300 expression { jobConfig.unitTests.run }
301 not {
302 triggeredBy 'BranchIndexingCause'
303 }
304 }
305 steps { script {
306 dockerImage.inside(dockerOptions + " --name ${buildTag}-unittests") {
307 def outputdir = "tests/CI/output/UnitTests"
308 def outputfile = "${outputdir}/unittests-results.xml"
309
310 sh "sudo ./tests/CI/installAsterisk.sh --uninstall-all --branch-name=${BRANCH_NAME} --user-group=jenkins:users"
311 sh "tests/CI/runUnittests.sh --user-group=jenkins:users --output-dir='${outputdir}' --output-xml='${outputfile}' --unittest-command='${jobConfig.unitTests.testCommand}'"
312
313 archiveArtifacts allowEmptyArchive: true, defaultExcludes: false, fingerprint: true,
314 artifacts: "${outputdir}/**"
315 junit testResults: outputfile,
316 healthScaleFactor: 1.0,
317 keepLongStdio: true
318 }
319 }}
320 }
321
322 /* Testsuite Tests
323 *
324 * When jobConfig.testsuite.run is true, load the JSON file specified by
325 * jobConfig.testsuite.configFile (default "testsuiteConfig") and spin off a
326 * separate docker container for each testGroup contained therein that also
327 * has its "enabled" property set to true.
328 *
329 * If a testGroup has a customTests child, the specified custom tests repo
330 * will be cloned into "<groupDir>/tests/custom" and can be referenced as
331 * any other testsuite test.
332 *
333 * Example testsuiteConfig file:
334 *
335 * {
336 * testGroups: [
337 * {
338 * name: "ari1-mwi",
339 * enabled: false,
340 * dir: "tests/CI/output/ari1",
341 * runTestsuiteOptions: "--test-timeout=180",
342 * testcmd: "--test-regex=tests/rest_api --test-regex=tests/channels/pjsip/.*mwi"
343 * },
344 * {
345 * name: "custom1",
346 * enabled: false,
347 * dir: "tests/CI/output/custom1",
348 * runTestsuiteOptions: "--test-timeout=180",
349 * testcmd: "--test-regex=tests/custom/tests/stress",
350 * customTests: {
351 * branch: "master",
352 * gitURL: "http://somehost/private-tests"
353 * }
354 * }
355 * ]
356 * }
357 *
358 */
359 stage("Testsuite") {
360 when {
361 expression { jobConfig.testsuite.run }
362 }
363 steps { script {
364 testConfig = [
365 testGroups: [],
366 ]
367 def tempTestConfig
368 configFileProvider([configFile(fileId: jobConfig.testsuite.configFile, variable: 'TESTSUITE_CONFIG_FILE')]) {
369 echo "Retrieved test config file from ${env.TESTSUITE_CONFIG_FILE}"
370 tempTestConfig = readJSON file: env.TESTSUITE_CONFIG_FILE
371 }
372 merge(testConfig, tempTestConfig)
373
374 tasks = [ : ]
375
376 testConfig.testGroups.each {
377 def testGroup = it
378 tasks[testGroup.name] = {
379 dockerImage.inside("${dockerOptions} --name ${buildTag}-${testGroup.name}") {
380
381 lock("${JOB_NAME}.${NODE_NAME}.installer") {
382 sh "sudo ./tests/CI/installAsterisk.sh --uninstall-all --branch-name=${BRANCH_NAME} --user-group=jenkins:users"
383 }
384
385 sh "sudo rm -rf ${testGroup.dir} || : "
386
387 checkout scm: [$class: 'GitSCM',
388 branches: [[name: "${BRANCH_NAME}"]],
389 extensions: [
390 [$class: 'RelativeTargetDirectory', relativeTargetDir: testGroup.dir],
391 [$class: 'CloneOption',
392 noTags: true,
393 depth: 100,
394 honorRefspec: true,
395 shallow: true
396 ],
397 ],
398 userRemoteConfigs: [[url: jobConfig.testsuite.gitURL]]
399 ]
400 echo "Test Custom Config: ${testGroup.customTests.toString()}"
401
402 if (testGroup.customTests && testGroup.customTests?.branch && testGroup.customTests?.gitURL) {
403 checkout scm: [$class: 'GitSCM',
404 branches: [[name: testGroup.customTests.branch]],
405 extensions: [
406 [$class: 'RelativeTargetDirectory', relativeTargetDir: "${testGroup.dir}/tests/custom"],
407 [$class: 'CloneOption',
408 noTags: true,
409 depth: 100,
410 honorRefspec: true,
411 shallow: true
412 ],
413 ],
414 userRemoteConfigs: [[url: testGroup.customTests.gitURL]]
415 ]
416 }
417 sh "sudo tests/CI/runTestsuite.sh ${testGroup.runTestsuiteOptions} --testsuite-dir='${testGroup.dir}' --testsuite-command='${testGroup.testcmd}'"
418
419 echo "Group result d: ${currentBuild.currentResult}"
420
421 archiveArtifacts allowEmptyArchive: true, defaultExcludes: false, fingerprint: true,
422 artifacts: "${testGroup.dir}/asterisk-test-suite-report.xml, ${testGroup.dir}/logs/**, ${testGroup.dir}/core*.txt"
423
424 junit testResults: "${testGroup.dir}/asterisk-test-suite-report.xml",
425 healthScaleFactor: 1.0,
426 keepLongStdio: true
427 }
428 }
429 }
430 parallel tasks
431 }}
432 }
433 }
434 post {
435 cleanup {
436 script {
437 if (jobConfig.jobCleanup.cleanupWorkspace) {
438 cleanWs deleteDirs: true, notFailBuild: false
439 }
440 }
441 }
442 success {
443 echo "Reporting ${currentBuild.currentResult} Passed"
444 }
445 failure {
446 echo "Reporting ${currentBuild.currentResult}: Failed: Fatal Error"
447 }
448 unstable {
449 echo "Reporting ${currentBuild.currentResult}: Failed: Tests Failed"
450 }
451 }
452 }