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