Enable Robot Tests
[osm/devops.git] / jenkins / ci-pipelines / ci_stage_3.groovy
1 /* Copyright 2017 Sandvine
2  *
3  * All Rights Reserved.
4  *
5  *   Licensed under the Apache License, Version 2.0 (the "License"); you may
6  *   not use this file except in compliance with the License. You may obtain
7  *   a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *   Unless required by applicable law or agreed to in writing, software
12  *   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13  *   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14  *   License for the specific language governing permissions and limitations
15  *   under the License.
16  */
17
18 /* Change log:
19  * 1. Bug 745 : Jayant Madavi, Mrityunjay Yadav : JM00553988@techmahindra.com : 23-july-2019 : Improvement to the code, typically we have 2 *    or more branches whose build gets triggered, ex master & release branch, the previous code was removing any/all docker.
20  *        Now removing previous docker of the same branch, so that the other branch failed docker should not be removed. It also
21  *    acts as clean-up for previous docker remove failure.
22  * 2. Feature 7829 : Mrityunjay Yadav, Jayant Madavi: MY00514913@techmahindra.com : 19-Aug-2019 : Added a parameters & function to invoke Robot test.
23  */
24
25 properties([
26     parameters([
27         string(defaultValue: env.GERRIT_BRANCH, description: '', name: 'GERRIT_BRANCH'),
28         string(defaultValue: 'system', description: '', name: 'NODE'),
29         string(defaultValue: '', description: '', name: 'BUILD_FROM_SOURCE'),
30         string(defaultValue: 'unstable', description: '', name: 'REPO_DISTRO'),
31         string(defaultValue: '', description: '', name: 'COMMIT_ID'),
32         string(defaultValue: '-stage_2', description: '', name: 'UPSTREAM_SUFFIX'),
33         string(defaultValue: 'pubkey.asc', description: '', name: 'REPO_KEY_NAME'),
34         string(defaultValue: 'release', description: '', name: 'RELEASE'),
35         string(defaultValue: '', description: '', name: 'UPSTREAM_JOB_NAME'),
36         string(defaultValue: '', description: '', name: 'UPSTREAM_JOB_NUMBER'),
37         string(defaultValue: '', description: '', name: 'UPSTREAM_JOB_NUMBER'),
38         string(defaultValue: 'OSMETSI', description: '', name: 'GPG_KEY_NAME'),
39         string(defaultValue: 'artifactory-osm', description: '', name: 'ARTIFACTORY_SERVER'),
40         string(defaultValue: 'osm-stage_4', description: '', name: 'DOWNSTREAM_STAGE_NAME'),
41         string(defaultValue: 'testing-daily', description: '', name: 'DOCKER_TAG'),
42         booleanParam(defaultValue: true, description: '', name: 'SAVE_CONTAINER_ON_FAIL'),
43         booleanParam(defaultValue: false, description: '', name: 'SAVE_CONTAINER_ON_PASS'),
44         booleanParam(defaultValue: true, description: '', name: 'SAVE_ARTIFACTS_ON_SMOKE_SUCCESS'),
45         booleanParam(defaultValue: true, description: '', name: 'DO_STAGE_4'),
46         booleanParam(defaultValue: true, description: '',  name: 'DO_BUILD'),
47         booleanParam(defaultValue: true, description: '', name: 'DO_INSTALL'),
48         booleanParam(defaultValue: true, description: '', name: 'DO_SMOKE'),
49         booleanParam(defaultValue: true, description: '', name: 'DO_DOCKERPUSH'),
50         booleanParam(defaultValue: false, description: '', name: 'SAVE_ARTIFACTS_OVERRIDE'),
51         string(defaultValue: '/home/jenkins/hive/openstack-etsi.rc', description: '', name: 'HIVE_VIM_1'),
52         booleanParam(defaultValue: false, description: '', name: 'DO_ROBOT'),
53         string(defaultValue: 'sanity', description: 'sanity/regression are the options', name: 'TEST_NAME'),
54         string(defaultValue: '/home/jenkins/hive/robot-systest.cfg', description: '', name: 'ROBOT_VIM'),
55         string(defaultValue: '/home/jenkins/hive/kubeconfig.yaml', description: '', name: 'KUBECONFIG'),
56         string(defaultValue: '/home/jenkins/hive/clouds.yaml', description: '', name: 'CLOUDS'),
57     ])
58 ])
59
60 def uninstall_osm(stackName) {
61     sh """
62          export OSM_USE_LOCAL_DEVOPS=true
63          export PATH=$PATH:/snap/bin
64          installers/full_install_osm.sh -y -w /tmp/osm -t ${stackName} -s ${stackName} --test --nolxd --nodocker --nojuju --nohostports --nohostclient --uninstall
65        """
66 }
67
68 def run_systest(stackName,tagName,testName,envfile=null) {
69     tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
70     if ( !envfile )
71     {
72         sh(script: "touch ${tempdir}/env")
73         envfile="${tempdir}/env"
74     }
75     sh "docker run --network net${stackName} --env-file ${envfile} -v ${tempdir}:/usr/share/osm-devops/systest/reports opensourcemano/osmclient:${tagName} make -C /usr/share/osm-devops/systest ${testName}"
76     sh "cp ${tempdir}/* ."
77     junit  '*.xml'
78 }
79
80 def run_robot_systest(stackName,tagName,testName,envfile=null,kubeconfig=null,clouds=null) {
81     tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
82     if ( !envfile )
83     {
84         sh(script: "touch ${tempdir}/env")
85         envfile="${tempdir}/env"
86     }
87     sh "docker run --network net${stackName} --env OSM_HOSTNAME=${stackName}_nbi --env PROMETHEUS_HOSTNAME=${stackName}_prometheus --env-file ${envfile} -v ${clouds}:/etc/openstack/clouds.yaml -v ${kubeconfig}:/root/.kube/config -v ${tempdir}:/robot-systest/reports opensourcemano/tests:${tagName} -c -t ${testName}"
88     sh "cp ${tempdir}/* ."
89     outputDirectory = sh(returnStdout: true, script: "pwd").trim()
90     println ("Present Directory is : ${outputDirectory}")
91     step([
92         $class : 'RobotPublisher',
93         outputPath : "${outputDirectory}",
94         outputFileName : "*.xml",
95         disableArchiveOutput : false,
96         reportFileName : "report.html",
97         logFileName : "log.html",
98         passThreshold : 0,
99         unstableThreshold: 0,
100         otherFiles : "*.png",
101     ])
102 }
103
104 def archive_logs(stackName) {
105     sh "docker service ls |grep \"${stackName}\"| awk '{print \$2}'| xargs -iy docker service logs y --timestamps > containers_logs.txt 2>&1"
106     archiveArtifacts artifacts: 'containers_logs.txt'
107 }
108
109 node("${params.NODE}") {
110
111     sh 'env'
112
113     tag_or_branch = params.GERRIT_BRANCH.replaceAll(/\./,"")
114
115     stage("Checkout") {
116         checkout scm
117     }
118
119     ci_helper = load "jenkins/ci-pipelines/ci_helper.groovy"
120
121     def upstream_main_job = params.UPSTREAM_SUFFIX
122
123     // upstream jobs always use merged artifacts
124     upstream_main_job += '-merge'
125     container_name_prefix = "osm-${tag_or_branch}"
126     container_name = "${container_name_prefix}"
127
128     keep_artifacts = false
129     if ( JOB_NAME.contains('merge') ) {
130         container_name += "-merge"
131
132         // On a merge job, we keep artifacts on smoke success
133         keep_artifacts = params.SAVE_ARTIFACTS_ON_SMOKE_SUCCESS
134     }
135     container_name += "-${BUILD_NUMBER}"
136
137     // Copy the artifacts from the upstream jobs
138     stage("Copy Artifacts") {
139         // cleanup any previous repo
140         sh 'rm -rf repo'
141         dir("repo") {
142             // grab all stable upstream builds based on the
143
144             dir("${RELEASE}") {
145                 def list = ["RO", "openvim", "osmclient", "IM", "devops", "MON", "N2VC", "NBI", "common", "LCM", "POL", "LW-UI", "NG-UI", "PLA", "tests"]
146                 for (component in list) {
147                     step ([$class: 'CopyArtifact',
148                            projectName: "${component}${upstream_main_job}/${GERRIT_BRANCH}"])
149
150                     // grab the build name/number
151                     //options = get_env_from_build('build.env')
152                     build_num = ci_helper.get_env_value('build.env','BUILD_NUMBER')
153
154                     // grab the archives from the stage_2 builds (ie. this will be the artifacts stored based on a merge)
155                     ci_helper.get_archive(params.ARTIFACTORY_SERVER,component,GERRIT_BRANCH, "${component}${upstream_main_job} :: ${GERRIT_BRANCH}", build_num)
156
157                     // cleanup any prevously defined dists
158                     sh "rm -rf dists"
159                 }
160
161                 // check if an upstream artifact based on specific build number has been requested
162                 // This is the case of a merge build and the upstream merge build is not yet complete (it is not deemed
163                 // a successful build yet). The upstream job is calling this downstream job (with the its build artifiact)
164                 if ( params.UPSTREAM_JOB_NAME ) {
165                     step ([$class: 'CopyArtifact',
166                            projectName: "${params.UPSTREAM_JOB_NAME}",
167                            selector: [$class: 'SpecificBuildSelector', buildNumber: "${params.UPSTREAM_JOB_NUMBER}"]
168                           ])
169
170                     //options = get_env_from_build('build.env')
171                     // grab the build name/number
172                     //build_num = sh(returnStdout:true,  script: "cat build.env | awk -F= '/BUILD_NUMBER/{print \$2}'").trim()
173                     build_num = ci_helper.get_env_value('build.env','BUILD_NUMBER')
174                     component = ci_helper.get_mdg_from_project(ci_helper.get_env_value('build.env','GERRIT_PROJECT'))
175
176                     // the upstream job name contains suffix with the project. Need this stripped off
177                     def project_without_branch = params.UPSTREAM_JOB_NAME.split('/')[0]
178
179                     // Remove the previous artifact for this component. Use the new upstream artifact
180                     sh "rm -rf pool/${component}"
181
182                     ci_helper.get_archive(params.ARTIFACTORY_SERVER,component,GERRIT_BRANCH, "${project_without_branch} :: ${GERRIT_BRANCH}", build_num)
183
184                     sh "rm -rf dists"
185                 }
186
187                 // sign all the components
188                 for (component in list) {
189                     sh "dpkg-sig --sign builder -k ${GPG_KEY_NAME} pool/${component}/*"
190                 }
191
192                 // now create the distro
193                 for (component in list) {
194                     sh "mkdir -p dists/${params.REPO_DISTRO}/${component}/binary-amd64/"
195                     sh "apt-ftparchive packages pool/${component} > dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
196                     sh "gzip -9fk dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
197                 }
198
199                 // create and sign the release file
200                 sh "apt-ftparchive release dists/${params.REPO_DISTRO} > dists/${params.REPO_DISTRO}/Release"
201                 sh "gpg --yes -abs -u ${GPG_KEY_NAME} -o dists/${params.REPO_DISTRO}/Release.gpg dists/${params.REPO_DISTRO}/Release"
202
203                 // copy the public key into the release folder
204                 // this pulls the key from the home dir of the current user (jenkins)
205                 sh "cp ~/${REPO_KEY_NAME} ."
206
207                 // merge the change logs
208                 sh """
209                    rm -f changelog/changelog-osm.html
210                    [ ! -d changelog ] || for mdgchange in \$(ls changelog); do cat changelog/\$mdgchange >> changelog/changelog-osm.html; done
211                    """
212                 RELEASE_DIR = sh(returnStdout:true,  script: 'pwd').trim()
213             }
214             // start an apache server to serve up the images
215             http_server_name = "${container_name}-apache"
216
217             pwd = sh(returnStdout:true,  script: 'pwd').trim()
218             repo_base_url = ci_helper.start_http_server(pwd,http_server_name)
219         }
220
221         // now pull the devops package and install in temporary location
222         tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
223         osm_devops_dpkg = sh(returnStdout: true, script: "find . -name osm-devops*.deb").trim()
224         sh "dpkg -x ${osm_devops_dpkg} ${tempdir}"
225         OSM_DEVOPS="${tempdir}/usr/share/osm-devops"
226     }
227
228     dir(OSM_DEVOPS) {
229         error = null
230         if ( params.DO_BUILD ) {
231             stage("Build") {
232                 sh "make -C docker clean"
233                 sh "make -C docker -j `nproc` Q= CMD_DOCKER_ARGS= TAG=${container_name} RELEASE=${params.RELEASE} REPOSITORY_BASE=${repo_base_url} REPOSITORY_KEY=${params.REPO_KEY_NAME} REPOSITORY=${params.REPO_DISTRO}"
234             }
235         }
236
237         try {
238             if ( params.DO_INSTALL ) {
239                 stage("Install") {
240
241                     //will by default always delete containers on complete
242                     //sh "jenkins/system/delete_old_containers.sh ${container_name_prefix}"
243
244                     commit_id = ''
245                     repo_distro = ''
246                     repo_key_name = ''
247                     release = ''
248
249                     if ( params.COMMIT_ID )
250                     {
251                         commit_id = "-b ${params.COMMIT_ID}"
252                     }
253
254                     if ( params.REPO_DISTRO )
255                     {
256                         repo_distro = "-r ${params.REPO_DISTRO}"
257                     }
258
259                     if ( params.REPO_KEY_NAME )
260                     {
261                         repo_key_name = "-k ${params.REPO_KEY_NAME}"
262                     }
263
264                     if ( params.RELEASE )
265                     {
266                         release = "-R ${params.RELEASE}"
267                     }
268
269                     if ( params.REPOSITORY_BASE )
270                     {
271                         repo_base_url = "-u ${params.REPOSITORY_BASE}"
272                     }
273                                         if ( params.DO_STAGE_4 ) {
274                                             try {
275                         sh "docker stack list |grep \"${container_name_prefix}\"|  awk '{ print \$1 }'| xargs docker stack rm"
276                                                 }
277                                                 catch (caughtError) {
278                                                   println("Caught error: docker stack rm failed!")
279                                                 }
280                                         }
281                     sh """
282                         export PATH=$PATH:/snap/bin
283                         installers/full_install_osm.sh -y -s ${container_name} --test --nolxd --nodocker --nojuju --nohostports --nohostclient \
284                                                         --nodockerbuild -t ${container_name} \
285                                                         -w /tmp/osm \
286                                                         ${commit_id} \
287                                                         ${repo_distro} \
288                                                         ${repo_base_url} \
289                                                         ${repo_key_name} \
290                                                         ${release} \
291                                                         ${params.BUILD_FROM_SOURCE}
292                        """
293                 }
294             }
295
296             stage_archive = false
297             if ( params.DO_SMOKE ) {
298                 stage("OSM Health") {
299                     sh "installers/osm_health.sh -s ${container_name}"
300                 }
301                 stage("Smoke") {
302                     run_systest(container_name,container_name,"smoke")
303                     // archive smoke success until stage_4 is ready
304
305                     if ( ! currentBuild.result.equals('UNSTABLE') ) {
306                         stage_archive = keep_artifacts
307                     } else {
308                                            error = new Exception("Smoke test failed")
309                                            currentBuild.result = 'FAILURE'
310                                         }
311                 }
312             }
313
314             if ( params.DO_STAGE_4 ) {
315                 // override stage_archive to only archive on stable
316                 stage_archive = false
317                 stage("System Integration Test") {
318                     if ( params.DO_ROBOT ) {
319                         run_robot_systest(container_name,container_name,params.TEST_NAME,params.ROBOT_VIM,params.KUBECONFIG,params.CLOUDS)
320                     } //else {
321                     run_systest(container_name,container_name,"openstack_stage_4",params.HIVE_VIM_1)
322                     //}
323                     // Archive logs to containers_logs.txt
324                     archive_logs(container_name)
325                     if ( ! currentBuild.result.equals('UNSTABLE') && ! currentBuild.result.equals('FAILURE')) {
326                         stage_archive = keep_artifacts
327                     } else {
328                        println ("Systest test failed, throwing error")
329                                            error = new Exception("Systest test failed")
330                                            currentBuild.result = 'FAILURE'
331                                            throw error
332                                         }
333                 }
334             }
335
336             // override to save the artifacts
337             if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive ) {
338                 stage("Archive") {
339                     sh "echo ${container_name} > build_version.txt"
340                     archiveArtifacts artifacts: "build_version.txt", fingerprint: true
341
342                     // Archive the tested repo
343                     dir("${RELEASE_DIR}") {
344                         ci_helper.archive(params.ARTIFACTORY_SERVER,RELEASE,GERRIT_BRANCH,'tested')
345                     }
346                     if ( params.DO_DOCKERPUSH ) {
347                         stage("Docker Push") {
348                             sh "make -C docker push INPUT_TAG=${container_name} TAG=${params.DOCKER_TAG}"
349                         }
350                     }
351                 }
352             }
353         }
354         catch(Exception ex) {
355             error = ex
356             currentBuild.result = 'FAILURE'
357             println("Caught error")
358             println(ex.getMessage())
359         }
360         finally {
361             if ( params.DO_INSTALL ) {
362                 if (error) {
363                     if ( !params.SAVE_CONTAINER_ON_FAIL ) {
364                         uninstall_osm container_name
365                         sh "docker stop ${http_server_name}"
366                         sh "docker rm ${http_server_name}"
367                     }
368                 }
369                 else {
370                     if ( !params.SAVE_CONTAINER_ON_PASS ) {
371                         uninstall_osm container_name
372                         sh "docker stop ${http_server_name}"
373                         sh "docker rm ${http_server_name}"
374                     }
375                 }
376             }
377         }
378     }
379 }