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