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