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