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