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