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