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