4e08254944aedb7efbf2c53de03b02d203ee156c
[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: 'OSMETSI', description: '', name: 'GPG_KEY_NAME'),
31         string(defaultValue: 'artifactory-osm', description: '', name: 'ARTIFACTORY_SERVER'),
32         string(defaultValue: 'osm-stage_4', description: '', name: 'DOWNSTREAM_STAGE_NAME'),
33         string(defaultValue: 'testing-daily', description: '', name: 'DOCKER_TAG'),
34         string(defaultValue: 'ubuntu20.04', description: '', name: 'OPENSTACK_BASE_IMAGE'),
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',
45                name: 'ROBOT_TAG_NAME'),
46         string(defaultValue: '/home/jenkins/hive/robot-systest.cfg', description: '', name: 'ROBOT_VIM'),
47         string(defaultValue: '/home/jenkins/hive/port-mapping-etsi-vim.yaml',
48                description: 'Port mapping file for SDN assist in ETSI VIM',
49                name: 'ROBOT_PORT_MAPPING_VIM'),
50         string(defaultValue: '/home/jenkins/hive/kubeconfig.yaml', description: '', name: 'KUBECONFIG'),
51         string(defaultValue: '/home/jenkins/hive/clouds.yaml', description: '', name: 'CLOUDS'),
52         string(defaultValue: 'Default', description: '', name: 'INSTALLER'),
53         string(defaultValue: '100.0', description: '% passed Robot tests to mark the build as passed',
54                name: 'ROBOT_PASS_THRESHOLD'),
55         string(defaultValue: '80.0', description: '% passed Robot tests to mark the build as unstable ' +
56                '(if lower, it will be failed)', name: 'ROBOT_UNSTABLE_THRESHOLD'),
57     ])
58 ])
59
60 ////////////////////////////////////////////////////////////////////////////////////////
61 // Helper Functions
62 ////////////////////////////////////////////////////////////////////////////////////////
63 void run_robot_systest(String tagName,
64                        String testName,
65                        String osmHostname,
66                        String prometheusHostname,
67                        Integer prometheusPort=null,
68                        String envfile=null,
69                        String portmappingfile=null,
70                        String kubeconfig=null,
71                        String clouds=null,
72                        String hostfile=null,
73                        String jujuPassword=null,
74                        String osmRSAfile=null,
75                        String passThreshold='0.0',
76                        String unstableThreshold='0.0') {
77     tempdir = sh(returnStdout: true, script: 'mktemp -d').trim()
78     String environmentFile = ''
79     if (envfile) {
80         environmentFile = envfile
81     } else {
82         sh(script: "touch ${tempdir}/env")
83         environmentFile = "${tempdir}/env"
84     }
85     PROMETHEUS_PORT_VAR = ''
86     if (prometheusPort != null) {
87         PROMETHEUS_PORT_VAR = "--env PROMETHEUS_PORT=${prometheusPort}"
88     }
89     hostfilemount = ''
90     if (hostfile) {
91         hostfilemount = "-v ${hostfile}:/etc/hosts"
92     }
93
94     JUJU_PASSWORD_VAR = ''
95     if (jujuPassword != null) {
96         JUJU_PASSWORD_VAR = "--env JUJU_PASSWORD=${jujuPassword}"
97     }
98
99     try {
100         sh("""docker run --env OSM_HOSTNAME=${osmHostname} --env PROMETHEUS_HOSTNAME=${prometheusHostname} \
101            ${PROMETHEUS_PORT_VAR} ${JUJU_PASSWORD_VAR} --env-file ${environmentFile} \
102            -v ${clouds}:/etc/openstack/clouds.yaml \
103            -v ${osmRSAfile}:/root/osm_id_rsa -v ${kubeconfig}:/root/.kube/config -v ${tempdir}:/robot-systest/reports \
104            -v ${portmappingfile}:/root/port-mapping.yaml ${hostfilemount} opensourcemano/tests:${tagName} \
105            -c -t ${testName}""")
106     } finally {
107         sh("cp ${tempdir}/* .")
108         outputDirectory = sh(returnStdout: true, script: 'pwd').trim()
109         println("Present Directory is : ${outputDirectory}")
110         step([
111             $class : 'RobotPublisher',
112             outputPath : "${outputDirectory}",
113             outputFileName : '*.xml',
114             disableArchiveOutput : false,
115             reportFileName : 'report.html',
116             logFileName : 'log.html',
117             passThreshold : passThreshold,
118             unstableThreshold: unstableThreshold,
119             otherFiles : '*.png',
120         ])
121     }
122 }
123
124 void archive_logs(Map remote) {
125
126     sshCommand remote: remote, command: '''mkdir -p logs'''
127     if (useCharmedInstaller) {
128         sshCommand remote: remote, command: '''
129             for container in `kubectl get pods -n osm | grep -v operator | grep -v NAME| awk '{print $1}'`; do
130                 logfile=`echo $container | cut -d- -f1`
131                 echo "Extracting log for $logfile"
132                 kubectl logs -n osm $container --timestamps=true 2>&1 > logs/$logfile.log
133             done
134         '''
135     } else {
136         sshCommand remote: remote, command: '''
137             for deployment in `kubectl -n osm get deployments | grep -v operator | grep -v NAME| awk '{print $1}'`; do
138                 echo "Extracting log for $deployment"
139                 kubectl -n osm logs deployments/$deployment --timestamps=true --all-containers 2>&1 \
140                 > logs/$deployment.log
141             done
142         '''
143         sshCommand remote: remote, command: '''
144             for statefulset in `kubectl -n osm get statefulsets | grep -v operator | grep -v NAME| awk '{print $1}'`; do
145                 echo "Extracting log for $statefulset"
146                 kubectl -n osm logs statefulsets/$statefulset --timestamps=true --all-containers 2>&1 \
147                 > logs/$statefulset.log
148             done
149         '''
150     }
151
152     sh 'rm -rf logs'
153     sshCommand remote: remote, command: '''ls -al logs'''
154     sshGet remote: remote, from: 'logs', into: '.', override: true
155     sh 'cp logs/* .'
156     archiveArtifacts artifacts: '*.log'
157 }
158
159 String get_value(String key, String output) {
160     for (String line : output.split( '\n' )) {
161         data = line.split( '\\|' )
162         if (data.length > 1) {
163             if ( data[1].trim() == key ) {
164                 return data[2].trim()
165             }
166         }
167     }
168 }
169
170 ////////////////////////////////////////////////////////////////////////////////////////
171 // Main Script
172 ////////////////////////////////////////////////////////////////////////////////////////
173 node("${params.NODE}") {
174
175     INTERNAL_DOCKER_REGISTRY = 'osm.etsi.org:5050/devops/cicd/'
176     INTERNAL_DOCKER_PROXY = 'http://172.21.1.1:5000'
177     APT_PROXY = 'http://172.21.1.1:3142'
178     SSH_KEY = '~/hive/cicd_rsa'
179     ARCHIVE_LOGS_FLAG = false
180     sh 'env'
181
182     tag_or_branch = params.GERRIT_BRANCH.replaceAll(/\./, '')
183
184     stage('Checkout') {
185         checkout scm
186     }
187
188     ci_helper = load 'jenkins/ci-pipelines/ci_helper.groovy'
189
190     def upstreamMainJob = params.UPSTREAM_SUFFIX
191
192     // upstream jobs always use merged artifacts
193     upstreamMainJob += '-merge'
194     containerNamePrefix = "osm-${tag_or_branch}"
195     containerName = "${containerNamePrefix}"
196
197     keep_artifacts = false
198     if ( JOB_NAME.contains('merge') ) {
199         containerName += '-merge'
200
201         // On a merge job, we keep artifacts on smoke success
202         keep_artifacts = params.SAVE_ARTIFACTS_ON_SMOKE_SUCCESS
203     }
204     containerName += "-${BUILD_NUMBER}"
205
206     server_id = null
207     http_server_name = null
208     devopstempdir = null
209     useCharmedInstaller = params.INSTALLER.equalsIgnoreCase('charmed')
210
211     try {
212         builtModules = [:]
213 ///////////////////////////////////////////////////////////////////////////////////////
214 // Fetch stage 2 .deb artifacts
215 ///////////////////////////////////////////////////////////////////////////////////////
216         stage('Copy Artifacts') {
217             // cleanup any previous repo
218             println("Logging system info before deleting repo.")
219             sh("pwd")
220             sh("tree -fD repo")
221             println("Trying to delete previous repo...")
222             sh("rm -rfv repo")
223             dir('repo') {
224                 packageList = []
225                 dir("${RELEASE}") {
226                     RELEASE_DIR = sh(returnStdout:true,  script: 'pwd').trim()
227
228                     // check if an upstream artifact based on specific build number has been requested
229                     // This is the case of a merge build and the upstream merge build is not yet complete
230                     // (it is not deemed a successful build yet). The upstream job is calling this downstream
231                     // job (with the its build artifact)
232                     def upstreamComponent = ''
233                     if (params.UPSTREAM_JOB_NAME) {
234                         println("Fetching upstream job artifact from ${params.UPSTREAM_JOB_NAME}")
235                         lock('Artifactory') {
236                             step ([$class: 'CopyArtifact',
237                                 projectName: "${params.UPSTREAM_JOB_NAME}",
238                                 selector: [$class: 'SpecificBuildSelector',
239                                 buildNumber: "${params.UPSTREAM_JOB_NUMBER}"]
240                                 ])
241
242                             upstreamComponent = ci_helper.get_mdg_from_project(
243                                 ci_helper.get_env_value('build.env','GERRIT_PROJECT'))
244                             def buildNumber = ci_helper.get_env_value('build.env','BUILD_NUMBER')
245                             dir("$upstreamComponent") {
246                                 // the upstream job name contains suffix with the project. Need this stripped off
247                                 project_without_branch = params.UPSTREAM_JOB_NAME.split('/')[0]
248                                 packages = ci_helper.get_archive(params.ARTIFACTORY_SERVER,
249                                     upstreamComponent,
250                                     GERRIT_BRANCH,
251                                     "${project_without_branch} :: ${GERRIT_BRANCH}",
252                                     buildNumber)
253
254                                 packageList.addAll(packages)
255                                 println("Fetched pre-merge ${params.UPSTREAM_JOB_NAME}: ${packages}")
256                             }
257                         } // lock artifactory
258                     }
259
260                     parallelSteps = [:]
261                     list = ['RO', 'osmclient', 'IM', 'devops', 'MON', 'N2VC', 'NBI',
262                             'common', 'LCM', 'POL', 'NG-UI', 'PLA', 'tests']
263                     if (upstreamComponent.length() > 0) {
264                         println("Skipping upstream fetch of ${upstreamComponent}")
265                         list.remove(upstreamComponent)
266                     }
267                     for (buildStep in list) {
268                         def component = buildStep
269                         parallelSteps[component] = {
270                             dir("$component") {
271                                 println("Fetching artifact for ${component}")
272                                 step([$class: 'CopyArtifact',
273                                        projectName: "${component}${upstreamMainJob}/${GERRIT_BRANCH}"])
274
275                                 // grab the archives from the stage_2 builds
276                                 // (ie. this will be the artifacts stored based on a merge)
277                                 packages = ci_helper.get_archive(params.ARTIFACTORY_SERVER,
278                                     component,
279                                     GERRIT_BRANCH,
280                                     "${component}${upstreamMainJob} :: ${GERRIT_BRANCH}",
281                                     ci_helper.get_env_value('build.env', 'BUILD_NUMBER'))
282                                 packageList.addAll(packages)
283                                 println("Fetched ${component}: ${packages}")
284                                 sh 'rm -rf dists'
285                             }
286                         }
287                     }
288                     lock('Artifactory') {
289                         parallel parallelSteps
290                     }
291
292 ///////////////////////////////////////////////////////////////////////////////////////
293 // Create Devops APT repository
294 ///////////////////////////////////////////////////////////////////////////////////////
295                     sh 'mkdir -p pool'
296                     for (component in [ 'devops', 'IM', 'osmclient' ]) {
297                         sh "ls -al ${component}/pool/"
298                         sh "cp -r ${component}/pool/* pool/"
299                         sh "dpkg-sig --sign builder -k ${GPG_KEY_NAME} pool/${component}/*"
300                         sh "mkdir -p dists/${params.REPO_DISTRO}/${component}/binary-amd64/"
301                         sh("""apt-ftparchive packages pool/${component} \
302                            > dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages""")
303                         sh "gzip -9fk dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
304                     }
305
306                     // create and sign the release file
307                     sh "apt-ftparchive release dists/${params.REPO_DISTRO} > dists/${params.REPO_DISTRO}/Release"
308                     sh("""gpg --yes -abs -u ${GPG_KEY_NAME} \
309                        -o dists/${params.REPO_DISTRO}/Release.gpg dists/${params.REPO_DISTRO}/Release""")
310
311                     // copy the public key into the release folder
312                     // this pulls the key from the home dir of the current user (jenkins)
313                     sh "cp ~/${REPO_KEY_NAME} 'OSM ETSI Release Key.gpg'"
314                     sh "cp ~/${REPO_KEY_NAME} ."
315                 }
316
317                 // start an apache server to serve up the packages
318                 http_server_name = "${containerName}-apache"
319
320                 pwd = sh(returnStdout:true,  script: 'pwd').trim()
321                 repo_port = sh(script: 'echo $(python -c \'import socket; s=socket.socket(); s.bind(("", 0));' +
322                                'print(s.getsockname()[1]); s.close()\');',
323                                returnStdout: true).trim()
324                 internal_docker_http_server_url = ci_helper.start_http_server(pwd, http_server_name, repo_port)
325                 NODE_IP_ADDRESS = sh(returnStdout: true, script:
326                     "echo ${SSH_CONNECTION} | awk '{print \$3}'").trim()
327                 ci_helper.check_status_http_server(NODE_IP_ADDRESS, repo_port)
328             }
329
330             // Unpack devops package into temporary location so that we use it from upstream if it was part of a patch
331             osm_devops_dpkg = sh(returnStdout: true, script: 'find ./repo/release/pool/ -name osm-devops*.deb').trim()
332             devopstempdir = sh(returnStdout: true, script: 'mktemp -d').trim()
333             println("Extracting local devops package ${osm_devops_dpkg} into ${devopstempdir} for docker build step")
334             sh "dpkg -x ${osm_devops_dpkg} ${devopstempdir}"
335             OSM_DEVOPS = "${devopstempdir}/usr/share/osm-devops"
336             // Convert URLs from stage 2 packages to arguments that can be passed to docker build
337             for (remotePath in packageList) {
338                 packageName = remotePath[remotePath.lastIndexOf('/') + 1 .. -1]
339                 packageName = packageName[0 .. packageName.indexOf('_') - 1]
340                 builtModules[packageName] = remotePath
341             }
342         }
343
344 ///////////////////////////////////////////////////////////////////////////////////////
345 // Build docker containers
346 ///////////////////////////////////////////////////////////////////////////////////////
347         dir(OSM_DEVOPS) {
348             Map remote = [:]
349             error = null
350             if ( params.DO_BUILD ) {
351                 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
352                                 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
353                     sh "docker login ${INTERNAL_DOCKER_REGISTRY} -u ${USERNAME} -p ${PASSWORD}"
354                 }
355                 datetime = sh(returnStdout: true, script: 'date +%Y-%m-%d:%H:%M:%S').trim()
356                 moduleBuildArgs = " --build-arg CACHE_DATE=${datetime}"
357                 for (packageName in builtModules.keySet()) {
358                     envName = packageName.replaceAll('-', '_').toUpperCase() + '_URL'
359                     moduleBuildArgs += " --build-arg ${envName}=" + builtModules[packageName]
360                 }
361                 dir('docker') {
362                     stage('Build') {
363                         containerList = sh(returnStdout: true, script:
364                             "find . -name Dockerfile -printf '%h\\n' | sed 's|\\./||'")
365                         containerList = Arrays.asList(containerList.split('\n'))
366                         print(containerList)
367                         parallelSteps = [:]
368                         for (buildStep in containerList) {
369                             def module = buildStep
370                             def moduleName = buildStep.toLowerCase()
371                             def moduleTag = containerName
372                             parallelSteps[module] = {
373                                 dir("$module") {
374                                     sh("""docker build --build-arg APT_PROXY=${APT_PROXY} \
375                                     -t opensourcemano/${moduleName}:${moduleTag} ${moduleBuildArgs} .""")
376                                     println("Tagging ${moduleName}:${moduleTag}")
377                                     sh("""docker tag opensourcemano/${moduleName}:${moduleTag} \
378                                     ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}""")
379                                     sh("""docker push \
380                                     ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}""")
381                                 }
382                             }
383                         }
384                         parallel parallelSteps
385                     }
386                 }
387             } // if (params.DO_BUILD)
388
389             if (params.DO_INSTALL) {
390 ///////////////////////////////////////////////////////////////////////////////////////
391 // Launch VM
392 ///////////////////////////////////////////////////////////////////////////////////////
393                 stage('Spawn Remote VM') {
394                     println('Launching new VM')
395                     output = sh(returnStdout: true, script: """#!/bin/sh -e
396                         for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
397                         openstack server create --flavor osm.sanity \
398                                                 --image ${OPENSTACK_BASE_IMAGE} \
399                                                 --key-name CICD \
400                                                 --property build_url="${BUILD_URL}" \
401                                                 --nic net-id=osm-ext \
402                                                 ${containerName}
403                     """).trim()
404
405                     server_id = get_value('id', output)
406
407                     if (server_id == null) {
408                         println('VM launch output: ')
409                         println(output)
410                         throw new Exception('VM Launch failed')
411                     }
412                     println("Target VM is ${server_id}, waiting for IP address to be assigned")
413
414                     IP_ADDRESS = ''
415
416                     while (IP_ADDRESS == '') {
417                         output = sh(returnStdout: true, script: """#!/bin/sh -e
418                             for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
419                             openstack server show ${server_id}
420                         """).trim()
421                         IP_ADDRESS = get_value('addresses', output)
422                     }
423                     IP_ADDRESS = IP_ADDRESS.split('=')[1]
424                     println("Waiting for VM at ${IP_ADDRESS} to be reachable")
425
426                     alive = false
427                     timeout(time: 1, unit: 'MINUTES') {
428                         while (!alive) {
429                             output = sh(
430                                 returnStatus: true,
431                                 script: "ssh -T -i ${SSH_KEY} " +
432                                     "-o StrictHostKeyChecking=no " +
433                                     "-o UserKnownHostsFile=/dev/null " +
434                                     "-o ConnectTimeout=5 ubuntu@${IP_ADDRESS} 'echo Alive'")
435                             alive = (output == 0)
436                         }
437                     }
438                     println('VM is ready and accepting ssh connections')
439                 } // stage("Spawn Remote VM")
440
441 ///////////////////////////////////////////////////////////////////////////////////////
442 // Checks before installation
443 ///////////////////////////////////////////////////////////////////////////////////////
444                 stage('Checks before installation') {
445                     remote = [
446                         name: containerName,
447                         host: IP_ADDRESS,
448                         user: 'ubuntu',
449                         identityFile: SSH_KEY,
450                         allowAnyHosts: true,
451                         logLevel: 'INFO',
452                         pty: true
453                     ]
454                     // Ensure the VM is ready
455                     sshCommand remote: remote, command: 'cloud-init status --wait'
456
457                     // Force time sync to avoid clock drift and invalid certificates
458                     sshCommand remote: remote, command: 'sudo apt-get update'
459                     sshCommand remote: remote, command: 'sudo apt-get install -y chrony'
460                     sshCommand remote: remote, command: 'sudo service chrony stop'
461                     sshCommand remote: remote, command: 'sudo chronyd -vq'
462                     sshCommand remote: remote, command: 'sudo service chrony start'
463
464                  } // stage("Checks before installation")
465 ///////////////////////////////////////////////////////////////////////////////////////
466 // Installation
467 ///////////////////////////////////////////////////////////////////////////////////////
468                 stage('Install') {
469                     commit_id = ''
470                     repo_distro = ''
471                     repo_key_name = ''
472                     release = ''
473
474                     if (params.COMMIT_ID) {
475                         commit_id = "-b ${params.COMMIT_ID}"
476                     }
477                     if (params.REPO_DISTRO) {
478                         repo_distro = "-r ${params.REPO_DISTRO}"
479                     }
480                     if (params.REPO_KEY_NAME) {
481                         repo_key_name = "-k ${params.REPO_KEY_NAME}"
482                     }
483                     if (params.RELEASE) {
484                         release = "-R ${params.RELEASE}"
485                     }
486                     if (params.REPOSITORY_BASE) {
487                         repo_base_url = "-u ${params.REPOSITORY_BASE}"
488                     } else {
489                         repo_base_url = "-u http://${NODE_IP_ADDRESS}:${repo_port}"
490                     }
491
492                     remote = [
493                         name: containerName,
494                         host: IP_ADDRESS,
495                         user: 'ubuntu',
496                         identityFile: SSH_KEY,
497                         allowAnyHosts: true,
498                         logLevel: 'INFO',
499                         pty: true
500                     ]
501
502                     sshCommand remote: remote, command: '''
503                         wget https://osm-download.etsi.org/ftp/osm-11.0-eleven/install_osm.sh
504                         chmod +x ./install_osm.sh
505                         sed -i '1 i\\export PATH=/snap/bin:\$PATH' ~/.bashrc
506                     '''
507
508                     Map gitlabCredentialsMap = [$class: 'UsernamePasswordMultiBinding',
509                                                 credentialsId: 'gitlab-registry',
510                                                 usernameVariable: 'USERNAME',
511                                                 passwordVariable: 'PASSWORD']
512                     if (useCharmedInstaller) {
513                         // Use local proxy for docker hub
514                         sshCommand remote: remote, command: '''
515                             sudo snap install microk8s --classic --channel=1.19/stable
516                             sudo sed -i "s|https://registry-1.docker.io|http://172.21.1.1:5000|" \
517                             /var/snap/microk8s/current/args/containerd-template.toml
518                             sudo systemctl restart snap.microk8s.daemon-containerd.service
519                             sudo snap alias microk8s.kubectl kubectl
520                         '''
521
522                         withCredentials([gitlabCredentialsMap]) {
523                             sshCommand remote: remote, command: """
524                                 ./install_osm.sh -y \
525                                     ${repo_base_url} \
526                                     ${repo_key_name} \
527                                     ${release} -r unstable \
528                                     --charmed  \
529                                     --registry ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
530                                     --tag ${containerName}
531                             """
532                         }
533                         prometheusHostname = "prometheus.${IP_ADDRESS}.nip.io"
534                         prometheusPort = 80
535                         osmHostname = "nbi.${IP_ADDRESS}.nip.io:443"
536                     } else {
537                         // Run -k8s installer here specifying internal docker registry and docker proxy
538                         withCredentials([gitlabCredentialsMap]) {
539                             sshCommand remote: remote, command: """
540                                 ./install_osm.sh -y \
541                                     ${repo_base_url} \
542                                     ${repo_key_name} \
543                                     ${release} -r unstable \
544                                     -d ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
545                                     -p ${INTERNAL_DOCKER_PROXY} \
546                                     -t ${containerName}
547                             """
548                         }
549                         prometheusHostname = IP_ADDRESS
550                         prometheusPort = 9091
551                         osmHostname = IP_ADDRESS
552                     }
553                 } // stage("Install")
554 ///////////////////////////////////////////////////////////////////////////////////////
555 // Health check of installed OSM in remote vm
556 ///////////////////////////////////////////////////////////////////////////////////////
557                 stage('OSM Health') {
558                     // if this point is reached, logs should be archived
559                     ARCHIVE_LOGS_FLAG = true
560                     stackName = 'osm'
561                     sshCommand remote: remote, command: """
562                         /usr/share/osm-devops/installers/osm_health.sh -k -s ${stackName}
563                     """
564                 } // stage("OSM Health")
565             } // if ( params.DO_INSTALL )
566
567
568 ///////////////////////////////////////////////////////////////////////////////////////
569 // Execute Robot tests
570 ///////////////////////////////////////////////////////////////////////////////////////
571             stage_archive = false
572             if ( params.DO_ROBOT ) {
573                 try {
574                     stage('System Integration Test') {
575                         if (useCharmedInstaller) {
576                             tempdir = sh(returnStdout: true, script: 'mktemp -d').trim()
577                             sh(script: "touch ${tempdir}/hosts")
578                             hostfile = "${tempdir}/hosts"
579                             sh """cat << EOF > ${hostfile}
580 127.0.0.1           localhost
581 ${remote.host}      prometheus.${remote.host}.nip.io nbi.${remote.host}.nip.io
582 EOF"""
583                         } else {
584                             hostfile = null
585                         }
586
587                         jujuPassword = sshCommand remote: remote, command: '''
588                             echo `juju gui 2>&1 | grep password | cut -d: -f2`
589                         '''
590
591                         run_robot_systest(
592                             containerName,
593                             params.ROBOT_TAG_NAME,
594                             osmHostname,
595                             prometheusHostname,
596                             prometheusPort,
597                             params.ROBOT_VIM,
598                             params.ROBOT_PORT_MAPPING_VIM,
599                             params.KUBECONFIG,
600                             params.CLOUDS,
601                             hostfile,
602                             jujuPassword,
603                             SSH_KEY,
604                             params.ROBOT_PASS_THRESHOLD,
605                             params.ROBOT_UNSTABLE_THRESHOLD
606                         )
607                     } // stage("System Integration Test")
608                 } finally {
609                     stage('After System Integration test') {
610                         if (currentBuild.result != 'FAILURE') {
611                             stage_archive = keep_artifacts
612                         } else {
613                             println('Systest test failed, throwing error')
614                             error = new Exception('Systest test failed')
615                             currentBuild.result = 'FAILURE'
616                             throw error
617                         }
618                     }
619                 }
620             } // if ( params.DO_ROBOT )
621
622             if (params.SAVE_ARTIFACTS_OVERRIDE || stage_archive) {
623                 stage('Archive') {
624                     // Archive the tested repo
625                     dir("${RELEASE_DIR}") {
626                         ci_helper.archive(params.ARTIFACTORY_SERVER, RELEASE, GERRIT_BRANCH, 'tested')
627                     }
628                     if (params.DO_DOCKERPUSH) {
629                         stage('Publish to Dockerhub') {
630                             parallelSteps = [:]
631                             for (buildStep in containerList) {
632                                 def module = buildStep
633                                 def moduleName = buildStep.toLowerCase()
634                                 def dockerTag = params.DOCKER_TAG
635                                 def moduleTag = containerName
636
637                                 parallelSteps[module] = {
638                                     dir("$module") {
639                                         sh("docker pull ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}")
640                                         sh("""docker tag opensourcemano/${moduleName}:${moduleTag} \
641                                            opensourcemano/${moduleName}:${dockerTag}""")
642                                         sh "docker push opensourcemano/${moduleName}:${dockerTag}"
643                                     }
644                                 }
645                             }
646                             parallel parallelSteps
647                         }
648                         stage('Snap promotion') {
649                             withCredentials([string(credentialsId: 'Snapstore', variable: 'SNAPCRAFT_STORE_CREDENTIALS')]) {
650                                 snaps = ['osmclient']
651                                 for (snap in snaps) {
652                                     channel = 'latest/'
653                                     if (BRANCH_NAME.startsWith('v')) {
654                                         channel = BRANCH_NAME.substring(1) + '/'
655                                     } else if (BRANCH_NAME != 'master') {
656                                         channel += '/' + BRANCH_NAME.replaceAll('/', '-')
657                                     }
658                                     track = channel + 'edge\\*'
659                                     edge_rev = sh(returnStdout: true,
660                                         script: "snapcraft revisions $snap | " +
661                                         "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
662                                     track = channel + 'beta\\*'
663                                     beta_rev = sh(returnStdout: true,
664                                         script: "snapcraft revisions $snap | " +
665                                         "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
666
667                                     print "Edge: $edge_rev, Beta: $beta_rev"
668
669                                     if (edge_rev != beta_rev) {
670                                         print "Promoting $edge_rev to beta in place of $beta_rev"
671                                         beta_track = channel + 'beta'
672                                         sh "snapcraft release $snap $edge_rev $beta_track"
673                                     }
674                                 }
675                             }
676                         } // stage('Snap promotion')
677                         stage('Charm promotion') {
678                             charms = [
679                                 'osm', // bundle
680                                 'osm-ha', // bundle
681                                 'osm-grafana',
682                                 'osm-mariadb',
683                                 'osm-lcm',
684                                 'osm-mon',
685                                 'osm-nbi',
686                                 'osm-ng-ui',
687                                 'osm-pol',
688                                 'osm-ro',
689                                 'osm-prometheus',
690                             ]
691                             for (charm in charms) {
692
693                                 channel = 'latest'
694                                 if (BRANCH_NAME.startsWith('v')) {
695                                     channel = BRANCH_NAME.substring(1)
696                                 } else if (BRANCH_NAME != 'master') {
697                                     channel += '/' + BRANCH_NAME.replaceAll('/', '-')
698                                 }
699
700                                 withCredentials([string(credentialsId: 'Charmstore', variable: 'CHARMCRAFT_AUTH')]) {
701                                     sh "charmcraft status $charm --format json > ${charm}.json"
702                                     isCharm = sh(returnStdout: true, script: "grep architecture ${charm}.json | wc -l").trim() as int
703                                     if (isCharm) {
704                                         jqScriptEdge = "cat ${charm}.json | jq -r '.[] | select(.track==\"$channel\") | .mappings[] | select(.base.architecture==\"amd64\" and .base.channel==\"20.04\") | .releases[] | select(.channel==\"$channel/edge/merged\")| .version'|head -1"
705                                         jqScriptBeta = "cat ${charm}.json | jq -r '.[] | select(.track==\"$channel\") | .mappings[] | select(.base.architecture==\"amd64\" and .base.channel==\"20.04\") | .releases[] | select(.channel==\"$channel/beta\")| .version'|head -1"
706                                     } else {
707                                         jqScriptEdge = "cat ${charm}.json | jq -r '.[] | select(.track==\"$channel\") | .mappings[].releases[] | select(.channel==\"$channel/edge/merged\")| .version'|head -1"
708                                         jqScriptBeta = "cat ${charm}.json | jq -r '.[] | select(.track==\"$channel\") | .mappings[].releases[] | select(.channel==\"$channel/beta\")| .version'|head -1"
709                                     }
710                                     // edge/merged is used in place of /edge as 10.1.0 LTS uses latest/edge
711                                     edge_rev = sh(returnStdout: true, script: jqScriptEdge).trim()
712                                     beta_rev = sh(returnStdout: true, script: jqScriptBeta).trim()
713                                     try { edge_rev = edge_rev as int } catch (NumberFormatException nfe) {edge_rev = 0}
714                                     try { beta_rev = beta_rev as int } catch (NumberFormatException nfe) {beta_rev = 0}
715
716                                     print "Edge: $edge_rev, Beta: $beta_rev"
717
718                                     if (edge_rev > beta_rev) {
719                                         print "Promoting $edge_rev to beta in place of $beta_rev"
720                                         beta_track = channel + 'beta'
721                                         sh "charmcraft release ${charm} --revision=${edge_rev} --channel=${channel}/beta"
722                                     }
723
724                                 }
725                             }
726                         } // stage('Charm promotion')
727                     } // if (params.DO_DOCKERPUSH)
728                 } // stage('Archive')
729             } // if (params.SAVE_ARTIFACTS_OVERRIDE || stage_archive)
730         } // dir(OSM_DEVOPS)
731     } finally {
732         stage('Archive Container Logs') {
733             if (ARCHIVE_LOGS_FLAG) {
734                 try {
735                     // Archive logs
736                     remote = [
737                         name: containerName,
738                         host: IP_ADDRESS,
739                         user: 'ubuntu',
740                         identityFile: SSH_KEY,
741                         allowAnyHosts: true,
742                         logLevel: 'INFO',
743                         pty: true
744                     ]
745                     println('Archiving container logs')
746                     archive_logs(remote)
747                 } catch (Exception e) {
748                     println('Error fetching logs: '+ e.getMessage())
749                 }
750             } // end if ( ARCHIVE_LOGS_FLAG )
751         }
752         stage('Cleanup') {
753             if (params.DO_INSTALL && server_id != null) {
754                 delete_vm = true
755                 if (error && params.SAVE_CONTAINER_ON_FAIL) {
756                     delete_vm = false
757                 }
758                 if (!error && params.SAVE_CONTAINER_ON_PASS) {
759                     delete_vm = false
760                 }
761
762                 if (delete_vm) {
763                     if (server_id != null) {
764                         println("Deleting VM: $server_id")
765                         sh """#!/bin/sh -e
766                             for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
767                             openstack server delete ${server_id}
768                         """
769                     } else {
770                         println("Saved VM $server_id in ETSI VIM")
771                     }
772                 }
773             }
774             if (http_server_name != null) {
775                 sh "docker stop ${http_server_name} || true"
776                 sh "docker rm ${http_server_name} || true"
777             }
778
779             if (devopstempdir != null) {
780                 sh "rm -rf ${devopstempdir}"
781             }
782         }
783     }
784 }