5ebae21cf003887f0f753d897b108d47a120a594
[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 "mkdir -p pool"
255                     for (component in [ "devops", "IM", "osmclient" ]) {
256                         sh "ls -al ${component}/pool/"
257                         sh "cp -r ${component}/pool/* pool/"
258                         sh "dpkg-sig --sign builder -k ${GPG_KEY_NAME} pool/${component}/*"
259                         sh "mkdir -p dists/${params.REPO_DISTRO}/${component}/binary-amd64/"
260                         sh "apt-ftparchive packages pool/${component} > dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
261                         sh "gzip -9fk dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
262                     }
263
264                     // create and sign the release file
265                     sh "apt-ftparchive release dists/${params.REPO_DISTRO} > dists/${params.REPO_DISTRO}/Release"
266                     sh "gpg --yes -abs -u ${GPG_KEY_NAME} -o dists/${params.REPO_DISTRO}/Release.gpg dists/${params.REPO_DISTRO}/Release"
267
268                     // copy the public key into the release folder
269                     // this pulls the key from the home dir of the current user (jenkins)
270                     sh "cp ~/${REPO_KEY_NAME} 'OSM ETSI Release Key.gpg'"
271                     sh "cp ~/${REPO_KEY_NAME} ."
272                 }
273
274                 // start an apache server to serve up the packages
275                 http_server_name = "${container_name}-apache"
276
277                 pwd = sh(returnStdout:true,  script: 'pwd').trim()
278                 repo_port = sh(script: 'echo $(python -c \'import socket; s=socket.socket(); s.bind(("", 0)); print(s.getsockname()[1]); s.close()\');', returnStdout: true).trim()
279                 repo_base_url = ci_helper.start_http_server(pwd,http_server_name,repo_port)
280                 NODE_IP_ADDRESS=sh(returnStdout: true, script:
281                     "echo ${SSH_CONNECTION} | awk '{print \$3}'").trim()
282             }
283
284             // Unpack devops package into temporary location so that we use it from upstream if it was part of a patch
285             osm_devops_dpkg = sh(returnStdout: true, script: "find ./repo/release/pool/ -name osm-devops*.deb").trim()
286             devopstempdir = sh(returnStdout: true, script: "mktemp -d").trim()
287             println("Extracting local devops package ${osm_devops_dpkg} into ${devopstempdir} for docker build step")
288             sh "dpkg -x ${osm_devops_dpkg} ${devopstempdir}"
289             OSM_DEVOPS="${devopstempdir}/usr/share/osm-devops"
290             // Convert URLs from stage 2 packages to arguments that can be passed to docker build
291             for (remotePath in packageList) {
292                 packageName=remotePath.substring(remotePath.lastIndexOf('/')+1)
293                 packageName=packageName.substring(0,packageName.indexOf('_'))
294                 builtModules[packageName]=remotePath
295             }
296         }
297
298 ///////////////////////////////////////////////////////////////////////////////////////
299 // Build docker containers
300 ///////////////////////////////////////////////////////////////////////////////////////
301         dir(OSM_DEVOPS) {
302             def remote = [:]
303             error = null
304             if ( params.DO_BUILD ) {
305                 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
306                                 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
307                     sh "docker login ${INTERNAL_DOCKER_REGISTRY} -u ${USERNAME} -p ${PASSWORD}"
308                 }
309                 moduleBuildArgs = ""
310                 for (packageName in builtModules.keySet()) {
311                     envName=packageName.replaceAll("-","_").toUpperCase()+"_URL"
312                     moduleBuildArgs += " --build-arg ${envName}=" + builtModules[packageName]
313                 }
314                 dir ("docker") {
315                     stage("Build") {
316                         containerList = sh(returnStdout: true, script:
317                             "find . -name Dockerfile -printf '%h\\n' | sed 's|\\./||'")
318                         containerList=Arrays.asList(containerList.split("\n"))
319                         print(containerList)
320                         parallelSteps = [:]
321                         for (buildStep in containerList) {
322                             def module = buildStep
323                             def moduleName = buildStep.toLowerCase()
324                             def moduleTag = container_name
325                             parallelSteps[module] = {
326                                 dir("$module") {
327                                     sh "docker build -t opensourcemano/${moduleName}:${moduleTag} ${moduleBuildArgs} ."
328                                     println("Tagging ${moduleName}:${moduleTag}")
329                                     sh "docker tag opensourcemano/${moduleName}:${moduleTag} ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}"
330                                     sh "docker push ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}"
331                                 }
332                             }
333                         }
334                         parallel parallelSteps
335                     }
336                 }
337             } // if ( params.DO_BUILD )
338
339             if ( params.DO_INSTALL ) {
340 ///////////////////////////////////////////////////////////////////////////////////////
341 // Launch VM
342 ///////////////////////////////////////////////////////////////////////////////////////
343                 stage("Spawn Remote VM") {
344                     println("Launching new VM")
345                     output=sh(returnStdout: true, script: """#!/bin/sh -e
346                         for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
347                         openstack server create --flavor osm.sanity \
348                                                 --image ubuntu18.04 \
349                                                 --key-name CICD \
350                                                 --property build_url="${BUILD_URL}" \
351                                                 --nic net-id=osm-ext \
352                                                 ${container_name}
353                     """).trim()
354
355                     server_id = get_value('id', output)
356
357                     if (server_id == null) {
358                         println("VM launch output: ")
359                         println(output)
360                         throw new Exception("VM Launch failed")
361                     }
362                     println("Target VM is ${server_id}, waiting for IP address to be assigned")
363
364                     IP_ADDRESS = ""
365
366                     while (IP_ADDRESS == "") {
367                         output=sh(returnStdout: true, script: """#!/bin/sh -e
368                             for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
369                             openstack server show ${server_id}
370                         """).trim()
371                         IP_ADDRESS = get_value('addresses', output)
372                     }
373                     IP_ADDRESS = IP_ADDRESS.split('=')[1]
374                     println("Waiting for VM at ${IP_ADDRESS} to be reachable")
375
376                     alive = false
377                     while (! alive) {
378                         output=sh(returnStdout: true, script: "sleep 1 ; nc -zv ${IP_ADDRESS} 22 2>&1 || true").trim()
379                         println("output is [$output]")
380                         alive = output.contains("succeeded")
381                     }
382                     println("VM is ready and accepting ssh connections")
383                 } // stage("Spawn Remote VM")
384
385 ///////////////////////////////////////////////////////////////////////////////////////
386 // Installation
387 ///////////////////////////////////////////////////////////////////////////////////////
388                 stage("Install") {
389                     commit_id = ''
390                     repo_distro = ''
391                     repo_key_name = ''
392                     release = ''
393
394                     if ( params.COMMIT_ID )
395                     {
396                         commit_id = "-b ${params.COMMIT_ID}"
397                     }
398
399                     if ( params.REPO_DISTRO )
400                     {
401                         repo_distro = "-r ${params.REPO_DISTRO}"
402                     }
403
404                     if ( params.REPO_KEY_NAME )
405                     {
406                         repo_key_name = "-k ${params.REPO_KEY_NAME}"
407                     }
408
409                     if ( params.RELEASE )
410                     {
411                         release = "-R ${params.RELEASE}"
412                     }
413
414                     if ( params.REPOSITORY_BASE )
415                     {
416                         repo_base_url = "-u ${params.REPOSITORY_BASE}"
417                     }
418                     else
419                     {
420                         repo_base_url = "-u http://${NODE_IP_ADDRESS}:${repo_port}"
421                     }
422
423                     remote.name = container_name
424                     remote.host = IP_ADDRESS
425                     remote.user = 'ubuntu'
426                     remote.identityFile = SSH_KEY
427                     remote.allowAnyHosts = true
428                     remote.logLevel = 'INFO'
429                     remote.pty = true
430
431                     sshCommand remote: remote, command: """
432                         wget https://osm-download.etsi.org/ftp/osm-9.0-nine/install_osm.sh
433                         chmod +x ./install_osm.sh
434                         sed -i '1 i\\export PATH=/snap/bin:\${PATH}' ~/.bashrc
435                     """
436
437                     if ( useCharmedInstaller ) {
438                         // Use local proxy for docker hub
439                         sshCommand remote: remote, command: '''
440                             sudo snap install microk8s --classic --channel=1.19/stable
441                             sudo sed -i "s|https://registry-1.docker.io|http://172.21.1.1:5000|" /var/snap/microk8s/current/args/containerd-template.toml
442                             sudo systemctl restart snap.microk8s.daemon-containerd.service
443                             sudo snap alias microk8s.kubectl kubectl
444                         '''
445
446                         withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
447                                         usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
448                             sshCommand remote: remote, command: """
449                                 ./install_osm.sh -y \
450                                     ${repo_base_url} \
451                                     ${repo_key_name} \
452                                     ${release} -r unstable \
453                                     --charmed  \
454                                     --registry ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
455                                     --tag ${container_name}
456                             """
457                         }
458                         prometheusHostname = "prometheus."+IP_ADDRESS+".xip.io"
459                         prometheusPort = 80
460                         osmHostname = "nbi."+IP_ADDRESS+".xip.io:443"
461                     } else {
462                         // Run -k8s installer here specifying internal docker registry and docker proxy
463                         withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
464                                         usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
465                             sshCommand remote: remote, command: """
466                                 ./install_osm.sh -y \
467                                     ${repo_base_url} \
468                                     ${repo_key_name} \
469                                     ${release} -r unstable \
470                                     -d ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
471                                     -p ${INTERNAL_DOCKER_PROXY} \
472                                     -t ${container_name} \
473                                     --nocachelxdimages
474                             """
475                         }
476                         prometheusHostname = IP_ADDRESS
477                         prometheusPort = 9091
478                         osmHostname = IP_ADDRESS
479                     }
480                 } // stage("Install")
481 ///////////////////////////////////////////////////////////////////////////////////////
482 // Health check of installed OSM in remote vm
483 ///////////////////////////////////////////////////////////////////////////////////////
484                 stage("OSM Health") {
485                     stackName = "osm"
486                     sshCommand remote: remote, command: """
487                         /usr/share/osm-devops/installers/osm_health.sh -k -s ${stackName}
488                     """
489                 } // stage("OSM Health")
490             } // if ( params.DO_INSTALL )
491
492
493 ///////////////////////////////////////////////////////////////////////////////////////
494 // Execute Robot tests
495 ///////////////////////////////////////////////////////////////////////////////////////
496             stage_archive = false
497             if ( params.DO_ROBOT ) {
498                 try {
499                     stage("System Integration Test") {
500                         if ( useCharmedInstaller ) {
501                             tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
502                             sh(script: "touch ${tempdir}/hosts")
503                             hostfile="${tempdir}/hosts"
504                             sh """cat << EOF > ${hostfile}
505 127.0.0.1           localhost
506 ${remote.host}      prometheus.${remote.host}.xip.io nbi.${remote.host}.xip.io
507 EOF"""
508                         } else {
509                             hostfile=null
510                         }
511
512                         jujuPassword=sshCommand remote: remote, command: """
513                             echo `juju gui 2>&1 | grep password | cut -d: -f2`
514                         """
515
516                         run_robot_systest(
517                             container_name,
518                             params.ROBOT_TAG_NAME,
519                             osmHostname,
520                             prometheusHostname,
521                             prometheusPort,
522                             params.ROBOT_VIM,
523                             params.KUBECONFIG,
524                             params.CLOUDS,
525                             hostfile,
526                             jujuPassword)
527                     } // stage("System Integration Test")
528                 } finally {
529                     stage("Archive Container Logs") {
530                         // Archive logs to containers_logs.txt
531                         archive_logs(remote)
532                         if ( ! currentBuild.result.equals('UNSTABLE') && ! currentBuild.result.equals('FAILURE')) {
533                             stage_archive = keep_artifacts
534                         } else {
535                             println ("Systest test failed, throwing error")
536                             error = new Exception("Systest test failed")
537                             currentBuild.result = 'FAILURE'
538                             throw error
539                         }
540                     }
541                 }
542             } // if ( params.DO_ROBOT )
543
544             if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive ) {
545                 stage("Archive") {
546                     sh "echo ${container_name} > build_version.txt"
547                     archiveArtifacts artifacts: "build_version.txt", fingerprint: true
548
549                     // Archive the tested repo
550                     dir("${RELEASE_DIR}") {
551                         ci_helper.archive(params.ARTIFACTORY_SERVER,RELEASE,GERRIT_BRANCH,'tested')
552                     }
553                     if ( params.DO_DOCKERPUSH ) {
554                         stage("Publish to Dockerhub") {
555                             parallelSteps = [:]
556                             for (buildStep in containerList) {
557                                 def module = buildStep
558                                 def moduleName = buildStep.toLowerCase()
559                                 def dockerTag = params.DOCKER_TAG
560                                 def moduleTag = container_name
561
562                                 parallelSteps[module] = {
563                                     dir("$module") {
564                                         sh "docker tag opensourcemano/${moduleName}:${moduleTag} opensourcemano/${moduleName}:${dockerTag}"
565                                         sh "docker push opensourcemano/${moduleName}:${dockerTag}"
566                                     }
567                                 }
568                             }
569                             parallel parallelSteps
570                         }
571
572                         stage("Snap promotion") {
573                             def snaps = ["osmclient"]
574                             sh "snapcraft login --with ~/.snapcraft/config"
575                             for (snap in snaps) {
576                                 channel="latest/"
577                                 if (BRANCH_NAME.startsWith("v")) {
578                                     channel=BRANCH_NAME.substring(1)+"/"
579                                 } else if (BRANCH_NAME!="master") {
580                                     channel+="/"+BRANCH_NAME.replaceAll('/','-')
581                                 }
582                                 track=channel+"edge\\*"
583                                 edge_rev=sh(returnStdout: true,
584                                     script: "snapcraft revisions $snap | " +
585                                     "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
586                                 print "edge rev is $edge_rev"
587                                 track=channel+"beta\\*"
588                                 beta_rev=sh(returnStdout: true,
589                                     script: "snapcraft revisions $snap | " +
590                                     "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
591                                 print "beta rev is $beta_rev"
592
593                                 if ( edge_rev != beta_rev ) {
594                                     print "Promoting $edge_rev to beta in place of $beta_rev"
595                                     beta_track=channel+"beta"
596                                     sh "snapcraft release $snap $edge_rev $beta_track"
597                                 }
598                             }
599                         } // stage("Snap promotion")
600                     } // if ( params.DO_DOCKERPUSH )
601                 } // stage("Archive")
602             } // if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive )
603         } // dir(OSM_DEVOPS)
604     } finally {
605         if ( params.DO_INSTALL && server_id != null) {
606             delete_vm = true
607             if (error && params.SAVE_CONTAINER_ON_FAIL ) {
608                 delete_vm = false
609             }
610             if (!error && params.SAVE_CONTAINER_ON_PASS ) {
611                 delete_vm = false
612             }
613
614             if ( delete_vm ) {
615                 if (server_id != null) {
616                     println("Deleting VM: $server_id")
617                     sh """#!/bin/sh -e
618                         for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
619                         openstack server delete ${server_id}
620                     """
621                 } else {
622                     println("Saved VM $server_id in ETSI VIM")
623                 }
624             }
625         }
626         if ( http_server_name != null ) {
627             sh "docker stop ${http_server_name} || true"
628             sh "docker rm ${http_server_name} || true"
629         }
630
631         if ( devopstempdir != null ) {
632             sh "rm -rf ${devopstempdir}"
633         }
634     }
635 }