Merge "Bug 873: Robot Automation Improvement 1. Create a separate test to delete...
[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: 'releasesix-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         booleanParam(defaultValue: false, description: '', name: 'DO_RBAC'),
54         string(defaultValue: 'sanity', description: 'smoke/vim/sanity/comprehensive are the options', name: 'TEST_NAME'),
55         string(defaultValue: '/home/jenkins/hive/robot-systest.cfg', description: '', name: 'ROBOT_VIM'),
56     ])
57 ])
58
59 def uninstall_osm(stackName) {
60     sh """
61          export OSM_USE_LOCAL_DEVOPS=true
62          export PATH=$PATH:/snap/bin
63          installers/full_install_osm.sh -y -w /tmp/osm -t ${stackName} -s ${stackName} --test --nolxd --nodocker --nojuju --nohostports --nohostclient --uninstall
64        """
65 }
66
67 def run_systest(stackName,tagName,testName,envfile=null) {
68     tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
69     if ( !envfile )
70     {
71         sh(script: "touch ${tempdir}/env")
72         envfile="${tempdir}/env"
73     }
74     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}"
75     sh "cp ${tempdir}/* ."
76     junit  '*.xml'
77 }
78
79 def run_robot_systest(stackName,tagName,testName,envfile=null) {
80     tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
81     if ( !envfile )
82     {
83         sh(script: "touch ${tempdir}/env")
84         envfile="${tempdir}/env"
85     }
86     sh "docker run --network net${stackName} --env-file ${envfile} -v ${tempdir}:/usr/share/osm-devops/robot-systest/reports opensourcemano/osmclient:${tagName} bash -C /usr/share/osm-devops/robot-systest/run_test.sh --do_install -t ${testName}"
87     sh "cp ${tempdir}/* ."
88     outputDirectory = sh(returnStdout: true, script: "pwd").trim()
89     println ("Present Directory is : ${outputDirectory}")
90     step([
91         $class : 'RobotPublisher',
92         outputPath : "${outputDirectory}",
93         outputFileName : "*.xml",
94         disableArchiveOutput : false,
95         reportFileName : "report.html",
96         logFileName : "log.html",
97         passThreshold : 0,
98         unstableThreshold: 0,
99         otherFiles : "*.png",
100     ])
101 }
102
103 node("${params.NODE}") {
104
105     sh 'env'
106
107     tag_or_branch = params.GERRIT_BRANCH.replaceAll(/\./,"")
108
109     stage("Checkout") {
110         checkout scm
111     }
112
113     ci_helper = load "jenkins/ci-pipelines/ci_helper.groovy"
114
115     def upstream_main_job = params.UPSTREAM_SUFFIX
116
117     // upstream jobs always use merged artifacts
118     upstream_main_job += '-merge'
119     container_name_prefix = "osm-${tag_or_branch}"
120     container_name = "${container_name_prefix}"
121
122     keep_artifacts = false
123     if ( JOB_NAME.contains('merge') ) {
124         container_name += "-merge"
125
126         // On a merge job, we keep artifacts on smoke success
127         keep_artifacts = params.SAVE_ARTIFACTS_ON_SMOKE_SUCCESS
128     }
129     container_name += "-${BUILD_NUMBER}"
130
131     // Copy the artifacts from the upstream jobs
132     stage("Copy Artifacts") {
133         // cleanup any previous repo
134         sh 'rm -rf repo'
135         dir("repo") {
136             // grab all stable upstream builds based on the
137
138             dir("${RELEASE}") {
139                 def list = ["RO", "openvim", "osmclient", "IM", "devops", "MON", "N2VC", "NBI", "common", "LCM", "POL", "LW-UI"]
140                 for (component in list) {
141                     step ([$class: 'CopyArtifact',
142                            projectName: "${component}${upstream_main_job}/${GERRIT_BRANCH}"])
143
144                     // grab the build name/number
145                     //options = get_env_from_build('build.env')
146                     build_num = ci_helper.get_env_value('build.env','BUILD_NUMBER')
147
148                     // grab the archives from the stage_2 builds (ie. this will be the artifacts stored based on a merge)
149                     ci_helper.get_archive(params.ARTIFACTORY_SERVER,component,GERRIT_BRANCH, "${component}${upstream_main_job} :: ${GERRIT_BRANCH}", build_num)
150
151                     // cleanup any prevously defined dists
152                     sh "rm -rf dists"
153                 }
154
155                 // check if an upstream artifact based on specific build number has been requested
156                 // This is the case of a merge build and the upstream merge build is not yet complete (it is not deemed
157                 // a successful build yet). The upstream job is calling this downstream job (with the its build artifiact)
158                 if ( params.UPSTREAM_JOB_NAME ) {
159                     step ([$class: 'CopyArtifact',
160                            projectName: "${params.UPSTREAM_JOB_NAME}",
161                            selector: [$class: 'SpecificBuildSelector', buildNumber: "${params.UPSTREAM_JOB_NUMBER}"]
162                           ])
163
164                     //options = get_env_from_build('build.env')
165                     // grab the build name/number
166                     //build_num = sh(returnStdout:true,  script: "cat build.env | awk -F= '/BUILD_NUMBER/{print \$2}'").trim()
167                     build_num = ci_helper.get_env_value('build.env','BUILD_NUMBER')
168                     component = ci_helper.get_mdg_from_project(ci_helper.get_env_value('build.env','GERRIT_PROJECT'))
169
170                     // the upstream job name contains suffix with the project. Need this stripped off
171                     def project_without_branch = params.UPSTREAM_JOB_NAME.split('/')[0]
172
173                     // Remove the previous artifact for this component. Use the new upstream artifact
174                     sh "rm -rf pool/${component}"
175
176                     ci_helper.get_archive(params.ARTIFACTORY_SERVER,component,GERRIT_BRANCH, "${project_without_branch} :: ${GERRIT_BRANCH}", build_num)
177
178                     sh "rm -rf dists"
179                 }
180                 
181                 // sign all the components
182                 for (component in list) {
183                     sh "dpkg-sig --sign builder -k ${GPG_KEY_NAME} pool/${component}/*"
184                 }
185
186                 // now create the distro
187                 for (component in list) {
188                     sh "mkdir -p dists/${params.REPO_DISTRO}/${component}/binary-amd64/"
189                     sh "apt-ftparchive packages pool/${component} > dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
190                     sh "gzip -9fk dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
191                 }
192
193                 // create and sign the release file
194                 sh "apt-ftparchive release dists/${params.REPO_DISTRO} > dists/${params.REPO_DISTRO}/Release"
195                 sh "gpg --yes -abs -u ${GPG_KEY_NAME} -o dists/${params.REPO_DISTRO}/Release.gpg dists/${params.REPO_DISTRO}/Release"
196
197                 // copy the public key into the release folder
198                 // this pulls the key from the home dir of the current user (jenkins)
199                 sh "cp ~/${REPO_KEY_NAME} ."
200
201                 // merge the change logs
202                 sh """
203                    rm -f changelog/changelog-osm.html
204                    [ ! -d changelog ] || for mdgchange in \$(ls changelog); do cat changelog/\$mdgchange >> changelog/changelog-osm.html; done
205                    """
206                 RELEASE_DIR = sh(returnStdout:true,  script: 'pwd').trim()
207             }
208             // start an apache server to serve up the images
209             http_server_name = "${container_name}-apache"
210
211             pwd = sh(returnStdout:true,  script: 'pwd').trim()
212             repo_base_url = ci_helper.start_http_server(pwd,http_server_name)
213         }
214
215         // now pull the devops package and install in temporary location
216         tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
217         osm_devops_dpkg = sh(returnStdout: true, script: "find . -name osm-devops*.deb").trim()
218         sh "dpkg -x ${osm_devops_dpkg} ${tempdir}"
219         OSM_DEVOPS="${tempdir}/usr/share/osm-devops"
220     }
221
222     dir(OSM_DEVOPS) {
223         error = null
224         if ( params.DO_BUILD ) {
225             stage("Build") {
226                 sh "make -C docker clean"
227                 sh "make -C docker 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}"
228             }
229         }
230
231         try {
232             if ( params.DO_INSTALL ) {
233                 stage("Install") {
234
235                     //will by default always delete containers on complete
236                     //sh "jenkins/system/delete_old_containers.sh ${container_name_prefix}"
237
238                     commit_id = ''
239                     repo_distro = ''
240                     repo_key_name = ''
241                     release = ''
242
243                     if ( params.COMMIT_ID )
244                     {
245                         commit_id = "-b ${params.COMMIT_ID}"
246                     }
247
248                     if ( params.REPO_DISTRO )
249                     {
250                         repo_distro = "-r ${params.REPO_DISTRO}"
251                     }
252
253                     if ( params.REPO_KEY_NAME )
254                     {
255                         repo_key_name = "-k ${params.REPO_KEY_NAME}"
256                     }
257
258                     if ( params.RELEASE )
259                     {
260                         release = "-R ${params.RELEASE}"
261                     }
262              
263                     if ( params.REPOSITORY_BASE )
264                     {
265                         repo_base_url = "-u ${params.REPOSITORY_BASE}"
266                     }
267                                         if ( params.DO_STAGE_4 ) {
268                                             try {
269                         sh "docker stack list |grep \"${container_name_prefix}\"|  awk '{ print \$1 }'| xargs docker stack rm"
270                                                 }
271                                                 catch (caughtError) {
272                                                   println("Caught error: docker stack rm failed!")
273                                                 }
274                                         }
275                     sh """
276                         export PATH=$PATH:/snap/bin
277                         installers/full_install_osm.sh -y -s ${container_name} --test --nolxd --nodocker --nojuju --nohostports --nohostclient \
278                                                         --nodockerbuild -t ${container_name} \
279                                                         -w /tmp/osm \
280                                                         ${commit_id} \
281                                                         ${repo_distro} \
282                                                         ${repo_base_url} \
283                                                         ${repo_key_name} \
284                                                         ${release} \
285                                                         ${params.BUILD_FROM_SOURCE}
286                        """
287                 }
288             }
289
290             stage_archive = false
291             if ( params.DO_SMOKE ) {
292                 stage("OSM Health") {
293                     sh "installers/osm_health.sh -s ${container_name}"
294                 }
295                 stage("Smoke") {
296                     run_systest(container_name,container_name,"smoke")
297                     // archive smoke success until stage_4 is ready
298
299                     if ( ! currentBuild.result.equals('UNSTABLE') ) {
300                         stage_archive = keep_artifacts
301                     } else {
302                                            error = new Exception("Smoke test failed")
303                                            currentBuild.result = 'FAILURE'
304                                         }
305                 }
306             }
307
308             if ( params.DO_STAGE_4 ) {
309                 // override stage_archive to only archive on stable
310                 stage_archive = false
311                 stage("System Integration Test") {
312                     if ( params.DO_ROBOT ) {
313                         if (params.DO_RBAC) {
314                             sh "docker service update ${container_name}_nbi --force --env-add OSMNBI_AUTHENTICATION_BACKEND=keystone --env-add OSMNBI_AUTHENTICATION_AUTH_URL=keystone --env-add OSMNBI_AUTHENTICATION_AUTH_PORT=5000 --env-add OSMNBI_AUTHENTICATION_USER_DOMAIN_NAME=default --env-add OSMNBI_AUTHENTICATION_PROJECT_DOMAIN_NAME=default --env-add OSMNBI_AUTHENTICATION_SERVICE_USERNAME=nbi --env-add OSMNBI_AUTHENTICATION_SERVICE_PROJECT=service"
315                             sh "installers/osm_health.sh -w 30 -s ${container_name}"
316                         }
317                         run_robot_systest(container_name,container_name,params.TEST_NAME,params.ROBOT_VIM)
318                     } //else {
319                     run_systest(container_name,container_name,"openstack_stage_4",params.HIVE_VIM_1)
320                     //}
321
322                     if ( ! currentBuild.result.equals('UNSTABLE') && ! currentBuild.result.equals('FAILURE')) {
323                         stage_archive = keep_artifacts
324                     } else {
325                        println ("Systest test failed, throwing error")
326                                            error = new Exception("Systest test failed")
327                                            currentBuild.result = 'FAILURE'
328                                            throw error
329                                         }
330                 }
331             }
332
333             // override to save the artifacts
334             if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive ) {
335                 stage("Archive") {
336                     sh "echo ${container_name} > build_version.txt"
337                     archiveArtifacts artifacts: "build_version.txt", fingerprint: true
338
339                     // Archive the tested repo
340                     dir("${RELEASE_DIR}") {
341                         ci_helper.archive(params.ARTIFACTORY_SERVER,RELEASE,GERRIT_BRANCH,'tested')
342                     }
343                     if ( params.DO_DOCKERPUSH ) {
344                         stage("Docker Push") {
345                             sh "make -C docker push INPUT_TAG=${container_name} TAG=${params.DOCKER_TAG}"
346                         }
347                     }
348                 }
349             }
350         }
351         catch(Exception ex) {
352             error = ex
353             currentBuild.result = 'FAILURE'
354             println("Caught error")
355             println(ex.getMessage())
356         }
357         finally {
358             if ( params.DO_INSTALL ) {
359                 if (error) {
360                     if ( !params.SAVE_CONTAINER_ON_FAIL ) {
361                         uninstall_osm container_name
362                         sh "docker stop ${http_server_name}"
363                         sh "docker rm ${http_server_name}"
364                     }
365                 }
366                 else {
367                     if ( !params.SAVE_CONTAINER_ON_PASS ) {
368                         uninstall_osm container_name
369                         sh "docker stop ${http_server_name}"
370                         sh "docker rm ${http_server_name}"
371                     }
372                 }
373             }
374         }
375     }
376 }