Update stage1 and stage3 to run robot tests with tag
[osm/devops.git] / jenkins / ci-pipelines / ci_stage_3.groovy
1 /* Copyright ETSI Contributors and Others
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: 'OSMETSI', 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         string(defaultValue: 'testing-daily', description: '', name: 'DOCKER_TAG'),
35         booleanParam(defaultValue: false, description: '', name: 'SAVE_CONTAINER_ON_FAIL'),
36         booleanParam(defaultValue: false, description: '', name: 'SAVE_CONTAINER_ON_PASS'),
37         booleanParam(defaultValue: true, description: '', name: 'SAVE_ARTIFACTS_ON_SMOKE_SUCCESS'),
38         booleanParam(defaultValue: true, description: '',  name: 'DO_BUILD'),
39         booleanParam(defaultValue: true, description: '', name: 'DO_INSTALL'),
40         booleanParam(defaultValue: true, description: '', name: 'DO_DOCKERPUSH'),
41         booleanParam(defaultValue: false, description: '', name: 'SAVE_ARTIFACTS_OVERRIDE'),
42         string(defaultValue: '/home/jenkins/hive/openstack-etsi.rc', description: '', name: 'HIVE_VIM_1'),
43         booleanParam(defaultValue: true, description: '', name: 'DO_ROBOT'),
44         string(defaultValue: 'sanity', description: 'sanity/regression/daily are the common options', name: 'ROBOT_TAG_NAME'),
45         string(defaultValue: '/home/jenkins/hive/robot-systest.cfg', description: '', name: 'ROBOT_VIM'),
46         string(defaultValue: '/home/jenkins/hive/kubeconfig.yaml', description: '', name: 'KUBECONFIG'),
47         string(defaultValue: '/home/jenkins/hive/clouds.yaml', description: '', name: 'CLOUDS'),
48         string(defaultValue: 'Default', description: '', name: 'INSTALLER'),
49     ])
50 ])
51
52
53 ////////////////////////////////////////////////////////////////////////////////////////
54 // Helper Functions
55 ////////////////////////////////////////////////////////////////////////////////////////
56 def run_robot_systest(tagName,testName,osmHostname,prometheusHostname,prometheus_port=null,envfile=null,kubeconfig=null,clouds=null,hostfile=null,jujuPassword=null) {
57     tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
58     if ( !envfile )
59     {
60         sh(script: "touch ${tempdir}/env")
61         envfile="${tempdir}/env"
62     }
63     PROMETHEUS_PORT_VAR = ""
64     if ( prometheusPort != null) {
65         PROMETHEUS_PORT_VAR = "--env PROMETHEUS_PORT="+prometheusPort
66     }
67     hostfilemount=""
68     if ( hostfile ) {
69         hostfilemount="-v "+hostfile+":/etc/hosts"
70     }
71
72     JUJU_PASSWORD_VAR = ""
73     if ( jujuPassword != null) {
74         JUJU_PASSWORD_VAR = "--env JUJU_PASSWORD="+jujuPassword
75     }
76
77     try {
78         sh "docker run --env OSM_HOSTNAME=${osmHostname} --env PROMETHEUS_HOSTNAME=${prometheusHostname} ${PROMETHEUS_PORT_VAR} ${JUJU_PASSWORD_VAR} --env-file ${envfile} -v ${clouds}:/etc/openstack/clouds.yaml -v ${kubeconfig}:/root/.kube/config -v ${tempdir}:/robot-systest/reports ${hostfilemount} opensourcemano/tests:${tagName} -c -t ${testName}"
79     } finally {
80         sh "cp ${tempdir}/* ."
81         outputDirectory = sh(returnStdout: true, script: "pwd").trim()
82         println ("Present Directory is : ${outputDirectory}")
83         step([
84             $class : 'RobotPublisher',
85             outputPath : "${outputDirectory}",
86             outputFileName : "*.xml",
87             disableArchiveOutput : false,
88             reportFileName : "report.html",
89             logFileName : "log.html",
90             passThreshold : 0,
91             unstableThreshold: 0,
92             otherFiles : "*.png",
93         ])
94     }
95 }
96
97 def archive_logs(remote) {
98
99     sshCommand remote: remote, command: '''mkdir -p logs'''
100     if (useCharmedInstaller) {
101         sshCommand remote: remote, command: '''
102             for container in `kubectl get pods -n osm | grep -v operator | grep -v NAME| awk '{print $1}'`; do
103                 logfile=`echo $container | cut -d- -f1`
104                 echo "Extracting log for $logfile"
105                 kubectl logs -n osm $container --timestamps=true 2>&1 > logs/$logfile.log
106             done
107         '''
108     } else {
109         sshCommand remote: remote, command: '''
110             for deployment in `kubectl -n osm get deployments | grep -v operator | grep -v NAME| awk '{print $1}'`; do
111                 echo "Extracting log for $deployment"
112                 kubectl -n osm logs deployments/$deployment --timestamps=true --all-containers 2>&1 > logs/$deployment.log
113             done
114         '''
115         sshCommand remote: remote, command: '''
116             for statefulset in `kubectl -n osm get statefulsets | grep -v operator | grep -v NAME| awk '{print $1}'`; do
117                 echo "Extracting log for $statefulset"
118                 kubectl -n osm logs statefulsets/$statefulset --timestamps=true --all-containers 2>&1 > logs/$statefulset.log
119             done
120         '''
121     }
122
123     sh "rm -rf logs"
124     sshCommand remote: remote, command: '''ls -al logs'''
125     sshGet remote: remote, from: 'logs', into: '.', override: true
126     sh "cp logs/* ."
127     archiveArtifacts artifacts: '*.log'
128 }
129
130 def get_value(key, output) {
131     for (String line : output.split( '\n' )) {
132         data = line.split( '\\|' )
133         if (data.length > 1) {
134             if ( data[1].trim() == key ) {
135                 return data[2].trim()
136             }
137         }
138     }
139 }
140
141 ////////////////////////////////////////////////////////////////////////////////////////
142 // Main Script
143 ////////////////////////////////////////////////////////////////////////////////////////
144 node("${params.NODE}") {
145
146     INTERNAL_DOCKER_REGISTRY = 'osm.etsi.org:5050/devops/cicd/'
147     INTERNAL_DOCKER_PROXY = 'http://172.21.1.1:5000'
148     SSH_KEY = '~/hive/cicd_rsa'
149     sh 'env'
150
151     tag_or_branch = params.GERRIT_BRANCH.replaceAll(/\./,"")
152
153     stage("Checkout") {
154         checkout scm
155     }
156
157     ci_helper = load "jenkins/ci-pipelines/ci_helper.groovy"
158
159     def upstream_main_job = params.UPSTREAM_SUFFIX
160
161     // upstream jobs always use merged artifacts
162     upstream_main_job += '-merge'
163     container_name_prefix = "osm-${tag_or_branch}"
164     container_name = "${container_name_prefix}"
165
166     keep_artifacts = false
167     if ( JOB_NAME.contains('merge') ) {
168         container_name += "-merge"
169
170         // On a merge job, we keep artifacts on smoke success
171         keep_artifacts = params.SAVE_ARTIFACTS_ON_SMOKE_SUCCESS
172     }
173     container_name += "-${BUILD_NUMBER}"
174
175     server_id = null
176     http_server_name = null
177     devopstempdir = null
178     useCharmedInstaller = params.INSTALLER.equalsIgnoreCase("charmed")
179
180     try {
181         builtModules = [:]
182 ///////////////////////////////////////////////////////////////////////////////////////
183 // Fetch stage 2 .deb artifacts
184 ///////////////////////////////////////////////////////////////////////////////////////
185         stage("Copy Artifacts") {
186             // cleanup any previous repo
187             sh 'rm -rf repo'
188             dir("repo") {
189                 packageList = []
190                 dir("${RELEASE}") {
191                     RELEASE_DIR = sh(returnStdout:true,  script: 'pwd').trim()
192
193                     // check if an upstream artifact based on specific build number has been requested
194                     // This is the case of a merge build and the upstream merge build is not yet complete (it is not deemed
195                     // a successful build yet). The upstream job is calling this downstream job (with the its build artifiact)
196                     def upstreamComponent=""
197                     if ( params.UPSTREAM_JOB_NAME ) {
198                         println("Fetching upstream job artifact from ${params.UPSTREAM_JOB_NAME}")
199
200                         step ([$class: 'CopyArtifact',
201                                projectName: "${params.UPSTREAM_JOB_NAME}",
202                                selector: [$class: 'SpecificBuildSelector',
203                                buildNumber: "${params.UPSTREAM_JOB_NUMBER}"]
204                               ])
205
206                         upstreamComponent = ci_helper.get_mdg_from_project(
207                             ci_helper.get_env_value('build.env','GERRIT_PROJECT'))
208                         def buildNumber = ci_helper.get_env_value('build.env','BUILD_NUMBER')
209                         dir("$upstreamComponent") {
210                             // the upstream job name contains suffix with the project. Need this stripped off
211                             def project_without_branch = params.UPSTREAM_JOB_NAME.split('/')[0]
212                             def packages = ci_helper.get_archive(params.ARTIFACTORY_SERVER,
213                                 upstreamComponent,
214                                 GERRIT_BRANCH,
215                                 "${project_without_branch} :: ${GERRIT_BRANCH}",
216                                 buildNumber)
217
218                             packageList.addAll(packages)
219                             println("Fetched pre-merge ${params.UPSTREAM_JOB_NAME}: ${packages}")
220                         }
221                     }
222
223                     parallelSteps = [:]
224                     def list = ["RO", "openvim", "osmclient", "IM", "devops", "MON", "N2VC", "NBI", "common", "LCM", "POL", "LW-UI", "NG-UI", "PLA", "tests"]
225                     if (upstreamComponent.length()>0) {
226                         println("Skipping upstream fetch of "+upstreamComponent)
227                         list.remove(upstreamComponent)
228                     }
229                     for (buildStep in list) {
230                         def component = buildStep
231                         parallelSteps[component] = {
232                             dir("$component") {
233                                 println("Fetching artifact for ${component}")
234                                 step ([$class: 'CopyArtifact',
235                                        projectName: "${component}${upstream_main_job}/${GERRIT_BRANCH}"])
236
237                                 // grab the archives from the stage_2 builds (ie. this will be the artifacts stored based on a merge)
238                                 def packages = ci_helper.get_archive(params.ARTIFACTORY_SERVER,
239                                     component,
240                                     GERRIT_BRANCH,
241                                     "${component}${upstream_main_job} :: ${GERRIT_BRANCH}",
242                                     ci_helper.get_env_value('build.env','BUILD_NUMBER'))
243                                 packageList.addAll(packages)
244                                 println("Fetched ${component}: ${packages}")
245                                 sh "rm -rf dists"
246                             }
247                         }
248                     }
249                     parallel parallelSteps
250
251 ///////////////////////////////////////////////////////////////////////////////////////
252 // Create Devops APT repository
253 ///////////////////////////////////////////////////////////////////////////////////////
254                     sh "mv devops/pool/ pool"
255                     sh "dpkg-sig --sign builder -k ${GPG_KEY_NAME} pool/devops/*"
256                     sh "mkdir -p dists/${params.REPO_DISTRO}/devops/binary-amd64/"
257                     sh "apt-ftparchive packages pool/devops > dists/${params.REPO_DISTRO}/devops/binary-amd64/Packages"
258                     sh "gzip -9fk dists/${params.REPO_DISTRO}/devops/binary-amd64/Packages"
259
260                     // create and sign the release file
261                     sh "apt-ftparchive release dists/${params.REPO_DISTRO} > dists/${params.REPO_DISTRO}/Release"
262                     sh "gpg --yes -abs -u ${GPG_KEY_NAME} -o dists/${params.REPO_DISTRO}/Release.gpg dists/${params.REPO_DISTRO}/Release"
263
264                     // copy the public key into the release folder
265                     // this pulls the key from the home dir of the current user (jenkins)
266                     sh "cp ~/${REPO_KEY_NAME} 'OSM ETSI Release Key.gpg'"
267                     sh "cp ~/${REPO_KEY_NAME} ."
268                 }
269
270                 // start an apache server to serve up the packages
271                 http_server_name = "${container_name}-apache"
272
273                 pwd = sh(returnStdout:true,  script: 'pwd').trim()
274                 repo_port = sh(script: 'echo $(python -c \'import socket; s=socket.socket(); s.bind(("", 0)); print(s.getsockname()[1]); s.close()\');', returnStdout: true).trim()
275                 repo_base_url = ci_helper.start_http_server(pwd,http_server_name,repo_port)
276                 NODE_IP_ADDRESS=sh(returnStdout: true, script:
277                     "echo ${SSH_CONNECTION} | awk '{print \$3}'").trim()
278             }
279
280             // Unpack devops package into temporary location so that we use it from upstream if it was part of a patch
281             osm_devops_dpkg = sh(returnStdout: true, script: "find ./repo/release/pool/ -name osm-devops*.deb").trim()
282             devopstempdir = sh(returnStdout: true, script: "mktemp -d").trim()
283             println("Extracting local devops package ${osm_devops_dpkg} into ${devopstempdir} for docker build step")
284             sh "dpkg -x ${osm_devops_dpkg} ${devopstempdir}"
285             OSM_DEVOPS="${devopstempdir}/usr/share/osm-devops"
286             // Convert URLs from stage 2 packages to arguments that can be passed to docker build
287             for (remotePath in packageList) {
288                 packageName=remotePath.substring(remotePath.lastIndexOf('/')+1)
289                 packageName=packageName.substring(0,packageName.indexOf('_'))
290                 builtModules[packageName]=remotePath
291             }
292         }
293
294 ///////////////////////////////////////////////////////////////////////////////////////
295 // Build docker containers
296 ///////////////////////////////////////////////////////////////////////////////////////
297         dir(OSM_DEVOPS) {
298             def remote = [:]
299             error = null
300             if ( params.DO_BUILD ) {
301                 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
302                                 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
303                     sh "docker login ${INTERNAL_DOCKER_REGISTRY} -u ${USERNAME} -p ${PASSWORD}"
304                 }
305                 moduleBuildArgs = ""
306                 for (packageName in builtModules.keySet()) {
307                     envName=packageName.replaceAll("-","_").toUpperCase()+"_URL"
308                     moduleBuildArgs += " --build-arg ${envName}=" + builtModules[packageName]
309                 }
310                 dir ("docker") {
311                     stage("Build") {
312                         containerList = sh(returnStdout: true, script:
313                             "find . -name Dockerfile -printf '%h\\n' | sed 's|\\./||'")
314                         containerList=Arrays.asList(containerList.split("\n"))
315                         print(containerList)
316                         parallelSteps = [:]
317                         for (buildStep in containerList) {
318                             def module = buildStep
319                             def moduleName = buildStep.toLowerCase()
320                             def moduleTag = container_name
321                             parallelSteps[module] = {
322                                 dir("$module") {
323                                     sh "docker build -t opensourcemano/${moduleName}:${moduleTag} ${moduleBuildArgs} ."
324                                     println("Tagging ${moduleName}:${moduleTag}")
325                                     sh "docker tag opensourcemano/${moduleName}:${moduleTag} ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}"
326                                     sh "docker push ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}"
327                                 }
328                             }
329                         }
330                         parallel parallelSteps
331                     }
332                 }
333             } // if ( params.DO_BUILD )
334
335             if ( params.DO_INSTALL ) {
336 ///////////////////////////////////////////////////////////////////////////////////////
337 // Launch VM
338 ///////////////////////////////////////////////////////////////////////////////////////
339                 stage("Spawn Remote VM") {
340                     println("Launching new VM")
341                     output=sh(returnStdout: true, script: """#!/bin/sh -e
342                         for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
343                         openstack server create --flavor osm.sanity \
344                                                 --image ubuntu18.04 \
345                                                 --key-name CICD \
346                                                 --property build_url="${BUILD_URL}" \
347                                                 --nic net-id=osm-ext \
348                                                 ${container_name}
349                     """).trim()
350
351                     server_id = get_value('id', output)
352
353                     if (server_id == null) {
354                         println("VM launch output: ")
355                         println(output)
356                         throw new Exception("VM Launch failed")
357                     }
358                     println("Target VM is ${server_id}, waiting for IP address to be assigned")
359
360                     IP_ADDRESS = ""
361
362                     while (IP_ADDRESS == "") {
363                         output=sh(returnStdout: true, script: """#!/bin/sh -e
364                             for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
365                             openstack server show ${server_id}
366                         """).trim()
367                         IP_ADDRESS = get_value('addresses', output)
368                     }
369                     IP_ADDRESS = IP_ADDRESS.split('=')[1]
370                     println("Waiting for VM at ${IP_ADDRESS} to be reachable")
371
372                     alive = false
373                     while (! alive) {
374                         output=sh(returnStdout: true, script: "sleep 1 ; nc -zv ${IP_ADDRESS} 22 2>&1 || true").trim()
375                         println("output is [$output]")
376                         alive = output.contains("succeeded")
377                     }
378                     println("VM is ready and accepting ssh connections")
379                 } // stage("Spawn Remote VM")
380
381 ///////////////////////////////////////////////////////////////////////////////////////
382 // Installation
383 ///////////////////////////////////////////////////////////////////////////////////////
384                 stage("Install") {
385                     commit_id = ''
386                     repo_distro = ''
387                     repo_key_name = ''
388                     release = ''
389
390                     if ( params.COMMIT_ID )
391                     {
392                         commit_id = "-b ${params.COMMIT_ID}"
393                     }
394
395                     if ( params.REPO_DISTRO )
396                     {
397                         repo_distro = "-r ${params.REPO_DISTRO}"
398                     }
399
400                     if ( params.REPO_KEY_NAME )
401                     {
402                         repo_key_name = "-k ${params.REPO_KEY_NAME}"
403                     }
404
405                     if ( params.RELEASE )
406                     {
407                         release = "-R ${params.RELEASE}"
408                     }
409
410                     if ( params.REPOSITORY_BASE )
411                     {
412                         repo_base_url = "-u ${params.REPOSITORY_BASE}"
413                     }
414                     else
415                     {
416                         repo_base_url = "-u http://${NODE_IP_ADDRESS}:${repo_port}"
417                     }
418
419                     remote.name = container_name
420                     remote.host = IP_ADDRESS
421                     remote.user = 'ubuntu'
422                     remote.identityFile = SSH_KEY
423                     remote.allowAnyHosts = true
424                     remote.logLevel = 'INFO'
425                     remote.pty = true
426
427                     sshCommand remote: remote, command: """
428                         wget https://osm-download.etsi.org/ftp/osm-9.0-nine/install_osm.sh
429                         chmod +x ./install_osm.sh
430                         sed -i '1 i\\export PATH=/snap/bin:\${PATH}' ~/.bashrc
431                     """
432
433                     if ( useCharmedInstaller ) {
434                         // Use local proxy for docker hub
435                         sshCommand remote: remote, command: '''
436                             sudo snap install microk8s --classic --channel=1.19/stable
437                             sudo sed -i "s|https://registry-1.docker.io|http://172.21.1.1:5000|" /var/snap/microk8s/current/args/containerd-template.toml
438                             sudo systemctl restart snap.microk8s.daemon-containerd.service
439                             sudo snap alias microk8s.kubectl kubectl
440                         '''
441
442                         withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
443                                         usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
444                             sshCommand remote: remote, command: """
445                                 ./install_osm.sh -y \
446                                     ${repo_base_url} \
447                                     ${repo_key_name} \
448                                     ${release} -r unstable \
449                                     --charmed  \
450                                     --registry ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
451                                     --tag ${container_name}
452                             """
453                         }
454                         prometheusHostname = "prometheus."+IP_ADDRESS+".xip.io"
455                         prometheusPort = 80
456                         osmHostname = "nbi."+IP_ADDRESS+".xip.io:443"
457                     } else {
458                         // Run -k8s installer here specifying internal docker registry and docker proxy
459                         withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
460                                         usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
461                             sshCommand remote: remote, command: """
462                                 ./install_osm.sh -y \
463                                     ${repo_base_url} \
464                                     ${repo_key_name} \
465                                     ${release} -r unstable \
466                                     -d ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
467                                     -p ${INTERNAL_DOCKER_PROXY} \
468                                     -t ${container_name}
469                             """
470                         }
471                         prometheusHostname = IP_ADDRESS
472                         prometheusPort = 9091
473                         osmHostname = IP_ADDRESS
474                     }
475                 } // stage("Install")
476 ///////////////////////////////////////////////////////////////////////////////////////
477 // Health check of installed OSM in remote vm
478 ///////////////////////////////////////////////////////////////////////////////////////
479                 stage("OSM Health") {
480                     stackName = "osm"
481                     sshCommand remote: remote, command: """
482                         /usr/share/osm-devops/installers/osm_health.sh -k -s ${stackName}
483                     """
484                 } // stage("OSM Health")
485             } // if ( params.DO_INSTALL )
486
487
488 ///////////////////////////////////////////////////////////////////////////////////////
489 // Execute Robot tests
490 ///////////////////////////////////////////////////////////////////////////////////////
491             stage_archive = false
492             if ( params.DO_ROBOT ) {
493                 try {
494                     stage("System Integration Test") {
495                         if ( useCharmedInstaller ) {
496                             tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
497                             sh(script: "touch ${tempdir}/hosts")
498                             hostfile="${tempdir}/hosts"
499                             sh """cat << EOF > ${hostfile}
500 127.0.0.1           localhost
501 ${remote.host}      prometheus.${remote.host}.xip.io nbi.${remote.host}.xip.io
502 EOF"""
503                         } else {
504                             hostfile=null
505                         }
506
507                         jujuPassword=sshCommand remote: remote, command: """
508                             echo `juju gui 2>&1 | grep password | cut -d: -f2`
509                         """
510
511                         run_robot_systest(
512                             container_name,
513                             params.ROBOT_TAG_NAME,
514                             osmHostname,
515                             prometheusHostname,
516                             prometheusPort,
517                             params.ROBOT_VIM,
518                             params.KUBECONFIG,
519                             params.CLOUDS,
520                             hostfile,
521                             jujuPassword)
522                     } // stage("System Integration Test")
523                 } finally {
524                     stage("Archive Container Logs") {
525                         // Archive logs to containers_logs.txt
526                         archive_logs(remote)
527                         if ( ! currentBuild.result.equals('UNSTABLE') && ! currentBuild.result.equals('FAILURE')) {
528                             stage_archive = keep_artifacts
529                         } else {
530                             println ("Systest test failed, throwing error")
531                             error = new Exception("Systest test failed")
532                             currentBuild.result = 'FAILURE'
533                             throw error
534                         }
535                     }
536                 }
537             } // if ( params.DO_ROBOT )
538
539             if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive ) {
540                 stage("Archive") {
541                     sh "echo ${container_name} > build_version.txt"
542                     archiveArtifacts artifacts: "build_version.txt", fingerprint: true
543
544                     // Archive the tested repo
545                     dir("${RELEASE_DIR}") {
546                         ci_helper.archive(params.ARTIFACTORY_SERVER,RELEASE,GERRIT_BRANCH,'tested')
547                     }
548                     if ( params.DO_DOCKERPUSH ) {
549                         stage("Publish to Dockerhub") {
550                             parallelSteps = [:]
551                             for (buildStep in containerList) {
552                                 def module = buildStep
553                                 def moduleName = buildStep.toLowerCase()
554                                 def dockerTag = params.DOCKER_TAG
555                                 def moduleTag = container_name
556
557                                 parallelSteps[module] = {
558                                     dir("$module") {
559                                         sh "docker tag opensourcemano/${moduleName}:${moduleTag} opensourcemano/${moduleName}:${dockerTag}"
560                                         sh "docker push opensourcemano/${moduleName}:${dockerTag}"
561                                     }
562                                 }
563                             }
564                             parallel parallelSteps
565                         }
566
567                         stage("Snap promotion") {
568                             def snaps = ["osmclient"]
569                             sh "snapcraft login --with ~/.snapcraft/config"
570                             for (snap in snaps) {
571                                 channel="latest/"
572                                 if (BRANCH_NAME.startsWith("v")) {
573                                     channel=BRANCH_NAME.substring(1)+"/"
574                                 } else if (BRANCH_NAME!="master") {
575                                     channel+="/"+BRANCH_NAME.replaceAll('/','-')
576                                 }
577                                 track=channel+"edge\\*"
578                                 edge_rev=sh(returnStdout: true,
579                                     script: "snapcraft revisions $snap | " +
580                                     "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
581                                 print "edge rev is $edge_rev"
582                                 track=channel+"beta\\*"
583                                 beta_rev=sh(returnStdout: true,
584                                     script: "snapcraft revisions $snap | " +
585                                     "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
586                                 print "beta rev is $beta_rev"
587
588                                 if ( edge_rev != beta_rev ) {
589                                     print "Promoting $edge_rev to beta in place of $beta_rev"
590                                     beta_track=channel+"beta"
591                                     sh "snapcraft release $snap $edge_rev $beta_track"
592                                 }
593                             }
594                         } // stage("Snap promotion")
595                     } // if ( params.DO_DOCKERPUSH )
596                 } // stage("Archive")
597             } // if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive )
598         } // dir(OSM_DEVOPS)
599     } finally {
600         if ( params.DO_INSTALL && server_id != null) {
601             delete_vm = true
602             if (error && params.SAVE_CONTAINER_ON_FAIL ) {
603                 delete_vm = false
604             }
605             if (!error && params.SAVE_CONTAINER_ON_PASS ) {
606                 delete_vm = false
607             }
608
609             if ( delete_vm ) {
610                 if (server_id != null) {
611                     println("Deleting VM: $server_id")
612                     sh """#!/bin/sh -e
613                         for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
614                         openstack server delete ${server_id}
615                     """
616                 } else {
617                     println("Saved VM $server_id in ETSI VIM")
618                 }
619             }
620         }
621         if ( http_server_name != null ) {
622             sh "docker stop ${http_server_name} || true"
623             sh "docker rm ${http_server_name} || true"
624         }
625
626         if ( devopstempdir != null ) {
627             sh "rm -rf ${devopstempdir}"
628         }
629     }
630 }