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