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