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