1 /* Copyright ETSI Contributors and Others
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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
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: '', description: '', name: 'UPSTREAM_JOB_NUMBER'),
31 string(defaultValue: 'OSMETSI', description: '', name: 'GPG_KEY_NAME'),
32 string(defaultValue: 'artifactory-osm', description: '', name: 'ARTIFACTORY_SERVER'),
33 string(defaultValue: 'osm-stage_4', description: '', name: 'DOWNSTREAM_STAGE_NAME'),
34 string(defaultValue: 'testing-daily', description: '', name: 'DOCKER_TAG'),
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', name: 'ROBOT_TAG'),
45 string(defaultValue: '/home/jenkins/hive/robot-systest.cfg', description: '', name: 'ROBOT_VIM'),
46 string(defaultValue: '/home/jenkins/hive/kubeconfig.yaml', description: '', name: 'KUBECONFIG'),
47 string(defaultValue: '/home/jenkins/hive/clouds.yaml', description: '', name: 'CLOUDS'),
48 string(defaultValue: 'Default', description: '', name: 'INSTALLER'),
53 ////////////////////////////////////////////////////////////////////////////////////////
55 ////////////////////////////////////////////////////////////////////////////////////////
56 def run_robot_systest(tagName,testName,osmHostname,prometheusHostname,prometheus_port=null,envfile=null,kubeconfig=null,clouds=null,hostfile=null,jujuPassword=null) {
57 tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
60 sh(script: "touch ${tempdir}/env")
61 envfile="${tempdir}/env"
63 PROMETHEUS_PORT_VAR = ""
64 if ( prometheusPort != null) {
65 PROMETHEUS_PORT_VAR = "--env PROMETHEUS_PORT="+prometheusPort
69 hostfilemount="-v "+hostfile+":/etc/hosts"
72 JUJU_PASSWORD_VAR = ""
73 if ( jujuPassword != null) {
74 JUJU_PASSWORD_VAR = "--env JUJU_PASSWORD="+jujuPassword
78 sh "docker run --env OSM_HOSTNAME=${osmHostname} --env PROMETHEUS_HOSTNAME=${prometheusHostname} ${PROMETHEUS_PORT_VAR} ${JUJU_PASSWORD_VAR} --env-file ${envfile} -v ${clouds}:/etc/openstack/clouds.yaml -v ${kubeconfig}:/root/.kube/config -v ${tempdir}:/robot-systest/reports ${hostfilemount} opensourcemano/tests:${tagName} -c -t ${testName}"
80 sh "cp ${tempdir}/* ."
81 outputDirectory = sh(returnStdout: true, script: "pwd").trim()
82 println ("Present Directory is : ${outputDirectory}")
84 $class : 'RobotPublisher',
85 outputPath : "${outputDirectory}",
86 outputFileName : "*.xml",
87 disableArchiveOutput : false,
88 reportFileName : "report.html",
89 logFileName : "log.html",
97 def archive_logs(remote) {
99 sshCommand remote: remote, command: '''mkdir -p logs'''
100 if (useCharmedInstaller) {
101 sshCommand remote: remote, command: '''
102 for container in `kubectl get pods -n osm | grep -v operator | grep -v NAME| awk '{print $1}'`; do
103 logfile=`echo $container | cut -d- -f1`
104 echo "Extracting log for $logfile"
105 kubectl logs -n osm $container --timestamps=true 2>&1 > logs/$logfile.log
109 sshCommand remote: remote, command: '''
110 for deployment in `kubectl -n osm get deployments | grep -v operator | grep -v NAME| awk '{print $1}'`; do
111 echo "Extracting log for $deployment"
112 kubectl -n osm logs deployments/$deployment --timestamps=true --all-containers 2>&1 > logs/$deployment.log
115 sshCommand remote: remote, command: '''
116 for statefulset in `kubectl -n osm get statefulsets | grep -v operator | grep -v NAME| awk '{print $1}'`; do
117 echo "Extracting log for $statefulset"
118 kubectl -n osm logs statefulsets/$statefulset --timestamps=true --all-containers 2>&1 > logs/$statefulset.log
124 sshCommand remote: remote, command: '''ls -al logs'''
125 sshGet remote: remote, from: 'logs', into: '.', override: true
127 archiveArtifacts artifacts: '*.log'
130 def get_value(key, output) {
131 for (String line : output.split( '\n' )) {
132 data = line.split( '\\|' )
133 if (data.length > 1) {
134 if ( data[1].trim() == key ) {
135 return data[2].trim()
141 ////////////////////////////////////////////////////////////////////////////////////////
143 ////////////////////////////////////////////////////////////////////////////////////////
144 node("${params.NODE}") {
146 INTERNAL_DOCKER_REGISTRY = 'osm.etsi.org:5050/devops/cicd/'
147 INTERNAL_DOCKER_PROXY = 'http://172.21.1.1:5000'
148 SSH_KEY = '~/hive/cicd_rsa'
151 tag_or_branch = params.GERRIT_BRANCH.replaceAll(/\./,"")
157 ci_helper = load "jenkins/ci-pipelines/ci_helper.groovy"
159 def upstream_main_job = params.UPSTREAM_SUFFIX
161 // upstream jobs always use merged artifacts
162 upstream_main_job += '-merge'
163 container_name_prefix = "osm-${tag_or_branch}"
164 container_name = "${container_name_prefix}"
166 keep_artifacts = false
167 if ( JOB_NAME.contains('merge') ) {
168 container_name += "-merge"
170 // On a merge job, we keep artifacts on smoke success
171 keep_artifacts = params.SAVE_ARTIFACTS_ON_SMOKE_SUCCESS
173 container_name += "-${BUILD_NUMBER}"
176 http_server_name = null
178 useCharmedInstaller = params.INSTALLER.equalsIgnoreCase("charmed")
182 ///////////////////////////////////////////////////////////////////////////////////////
183 // Fetch stage 2 .deb artifacts
184 ///////////////////////////////////////////////////////////////////////////////////////
185 stage("Copy Artifacts") {
186 // cleanup any previous repo
191 RELEASE_DIR = sh(returnStdout:true, script: 'pwd').trim()
193 // check if an upstream artifact based on specific build number has been requested
194 // This is the case of a merge build and the upstream merge build is not yet complete (it is not deemed
195 // a successful build yet). The upstream job is calling this downstream job (with the its build artifiact)
196 def upstreamComponent=""
197 if ( params.UPSTREAM_JOB_NAME ) {
198 println("Fetching upstream job artifact from ${params.UPSTREAM_JOB_NAME}")
200 step ([$class: 'CopyArtifact',
201 projectName: "${params.UPSTREAM_JOB_NAME}",
202 selector: [$class: 'SpecificBuildSelector',
203 buildNumber: "${params.UPSTREAM_JOB_NUMBER}"]
206 upstreamComponent = ci_helper.get_mdg_from_project(
207 ci_helper.get_env_value('build.env','GERRIT_PROJECT'))
208 def buildNumber = ci_helper.get_env_value('build.env','BUILD_NUMBER')
209 dir("$upstreamComponent") {
210 // the upstream job name contains suffix with the project. Need this stripped off
211 def project_without_branch = params.UPSTREAM_JOB_NAME.split('/')[0]
212 def packages = ci_helper.get_archive(params.ARTIFACTORY_SERVER,
215 "${project_without_branch} :: ${GERRIT_BRANCH}",
218 packageList.addAll(packages)
219 println("Fetched pre-merge ${params.UPSTREAM_JOB_NAME}: ${packages}")
224 def list = ["RO", "openvim", "osmclient", "IM", "devops", "MON", "N2VC", "NBI", "common", "LCM", "POL", "LW-UI", "NG-UI", "PLA", "tests"]
225 if (upstreamComponent.length()>0) {
226 println("Skipping upstream fetch of "+upstreamComponent)
227 list.remove(upstreamComponent)
229 for (buildStep in list) {
230 def component = buildStep
231 parallelSteps[component] = {
233 println("Fetching artifact for ${component}")
234 step ([$class: 'CopyArtifact',
235 projectName: "${component}${upstream_main_job}/${GERRIT_BRANCH}"])
237 // grab the archives from the stage_2 builds (ie. this will be the artifacts stored based on a merge)
238 def packages = ci_helper.get_archive(params.ARTIFACTORY_SERVER,
241 "${component}${upstream_main_job} :: ${GERRIT_BRANCH}",
242 ci_helper.get_env_value('build.env','BUILD_NUMBER'))
243 packageList.addAll(packages)
244 println("Fetched ${component}: ${packages}")
249 parallel parallelSteps
251 ///////////////////////////////////////////////////////////////////////////////////////
252 // Create Devops APT repository
253 ///////////////////////////////////////////////////////////////////////////////////////
254 sh "mv devops/pool/ pool"
255 sh "dpkg-sig --sign builder -k ${GPG_KEY_NAME} pool/devops/*"
256 sh "mkdir -p dists/${params.REPO_DISTRO}/devops/binary-amd64/"
257 sh "apt-ftparchive packages pool/devops > dists/${params.REPO_DISTRO}/devops/binary-amd64/Packages"
258 sh "gzip -9fk dists/${params.REPO_DISTRO}/devops/binary-amd64/Packages"
260 // create and sign the release file
261 sh "apt-ftparchive release dists/${params.REPO_DISTRO} > dists/${params.REPO_DISTRO}/Release"
262 sh "gpg --yes -abs -u ${GPG_KEY_NAME} -o dists/${params.REPO_DISTRO}/Release.gpg dists/${params.REPO_DISTRO}/Release"
264 // copy the public key into the release folder
265 // this pulls the key from the home dir of the current user (jenkins)
266 sh "cp ~/${REPO_KEY_NAME} 'OSM ETSI Release Key.gpg'"
267 sh "cp ~/${REPO_KEY_NAME} ."
270 // start an apache server to serve up the packages
271 http_server_name = "${container_name}-apache"
273 pwd = sh(returnStdout:true, script: 'pwd').trim()
274 repo_port = sh(script: 'echo $(python -c \'import socket; s=socket.socket(); s.bind(("", 0)); print(s.getsockname()[1]); s.close()\');', returnStdout: true).trim()
275 repo_base_url = ci_helper.start_http_server(pwd,http_server_name,repo_port)
276 NODE_IP_ADDRESS=sh(returnStdout: true, script:
277 "echo ${SSH_CONNECTION} | awk '{print \$3}'").trim()
280 // Unpack devops package into temporary location so that we use it from upstream if it was part of a patch
281 osm_devops_dpkg = sh(returnStdout: true, script: "find ./repo/release/pool/ -name osm-devops*.deb").trim()
282 devopstempdir = sh(returnStdout: true, script: "mktemp -d").trim()
283 println("Extracting local devops package ${osm_devops_dpkg} into ${devopstempdir} for docker build step")
284 sh "dpkg -x ${osm_devops_dpkg} ${devopstempdir}"
285 OSM_DEVOPS="${devopstempdir}/usr/share/osm-devops"
286 // Convert URLs from stage 2 packages to arguments that can be passed to docker build
287 for (remotePath in packageList) {
288 packageName=remotePath.substring(remotePath.lastIndexOf('/')+1)
289 packageName=packageName.substring(0,packageName.indexOf('_'))
290 builtModules[packageName]=remotePath
294 ///////////////////////////////////////////////////////////////////////////////////////
295 // Build docker containers
296 ///////////////////////////////////////////////////////////////////////////////////////
300 if ( params.DO_BUILD ) {
301 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
302 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
303 sh "docker login ${INTERNAL_DOCKER_REGISTRY} -u ${USERNAME} -p ${PASSWORD}"
306 for (packageName in builtModules.keySet()) {
307 envName=packageName.replaceAll("-","_").toUpperCase()+"_URL"
308 moduleBuildArgs += " --build-arg ${envName}=" + builtModules[packageName]
312 containerList = sh(returnStdout: true, script:
313 "find . -name Dockerfile -printf '%h\\n' | sed 's|\\./||'")
314 containerList=Arrays.asList(containerList.split("\n"))
317 for (buildStep in containerList) {
318 def module = buildStep
319 def moduleName = buildStep.toLowerCase()
320 def moduleTag = container_name
321 parallelSteps[module] = {
323 sh "docker build -t opensourcemano/${moduleName}:${moduleTag} ${moduleBuildArgs} ."
324 println("Tagging ${moduleName}:${moduleTag}")
325 sh "docker tag opensourcemano/${moduleName}:${moduleTag} ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}"
326 sh "docker push ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}"
330 parallel parallelSteps
333 } // if ( params.DO_BUILD )
335 if ( params.DO_INSTALL ) {
336 ///////////////////////////////////////////////////////////////////////////////////////
338 ///////////////////////////////////////////////////////////////////////////////////////
339 stage("Spawn Remote VM") {
340 println("Launching new VM")
341 output=sh(returnStdout: true, script: """#!/bin/sh -e
342 for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
343 openstack server create --flavor osm.sanity \
344 --image ubuntu18.04 \
346 --property build_url="${BUILD_URL}" \
347 --nic net-id=osm-ext \
351 server_id = get_value('id', output)
353 if (server_id == null) {
354 println("VM launch output: ")
356 throw new Exception("VM Launch failed")
358 println("Target VM is ${server_id}, waiting for IP address to be assigned")
362 while (IP_ADDRESS == "") {
363 output=sh(returnStdout: true, script: """#!/bin/sh -e
364 for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
365 openstack server show ${server_id}
367 IP_ADDRESS = get_value('addresses', output)
369 IP_ADDRESS = IP_ADDRESS.split('=')[1]
370 println("Waiting for VM at ${IP_ADDRESS} to be reachable")
374 output=sh(returnStdout: true, script: "sleep 1 ; nc -zv ${IP_ADDRESS} 22 2>&1 || true").trim()
375 println("output is [$output]")
376 alive = output.contains("succeeded")
378 println("VM is ready and accepting ssh connections")
379 } // stage("Spawn Remote VM")
381 ///////////////////////////////////////////////////////////////////////////////////////
383 ///////////////////////////////////////////////////////////////////////////////////////
390 if ( params.COMMIT_ID )
392 commit_id = "-b ${params.COMMIT_ID}"
395 if ( params.REPO_DISTRO )
397 repo_distro = "-r ${params.REPO_DISTRO}"
400 if ( params.REPO_KEY_NAME )
402 repo_key_name = "-k ${params.REPO_KEY_NAME}"
405 if ( params.RELEASE )
407 release = "-R ${params.RELEASE}"
410 if ( params.REPOSITORY_BASE )
412 repo_base_url = "-u ${params.REPOSITORY_BASE}"
416 repo_base_url = "-u http://${NODE_IP_ADDRESS}:${repo_port}"
419 remote.name = container_name
420 remote.host = IP_ADDRESS
421 remote.user = 'ubuntu'
422 remote.identityFile = SSH_KEY
423 remote.allowAnyHosts = true
424 remote.logLevel = 'INFO'
427 sshCommand remote: remote, command: """
428 wget https://osm-download.etsi.org/ftp/osm-9.0-nine/install_osm.sh
429 chmod +x ./install_osm.sh
430 sed -i '1 i\\export PATH=/snap/bin:\${PATH}' ~/.bashrc
433 if ( useCharmedInstaller ) {
434 // Use local proxy for docker hub
435 sshCommand remote: remote, command: '''
436 sudo snap install microk8s --classic --channel=1.19/stable
437 sudo sed -i "s|https://registry-1.docker.io|http://172.21.1.1:5000|" /var/snap/microk8s/current/args/containerd-template.toml
438 sudo systemctl restart snap.microk8s.daemon-containerd.service
439 sudo snap alias microk8s.kubectl kubectl
442 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
443 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
444 sshCommand remote: remote, command: """
445 ./install_osm.sh -y \
448 ${release} -r unstable \
450 --registry ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
451 --tag ${container_name}
454 prometheusHostname = "prometheus."+IP_ADDRESS+".xip.io"
456 osmHostname = "nbi."+IP_ADDRESS+".xip.io:443"
458 // Run -k8s installer here specifying internal docker registry and docker proxy
459 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
460 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
461 sshCommand remote: remote, command: """
462 ./install_osm.sh -y \
465 ${release} -r unstable \
466 -d ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
467 -p ${INTERNAL_DOCKER_PROXY} \
471 prometheusHostname = IP_ADDRESS
472 prometheusPort = 9091
473 osmHostname = IP_ADDRESS
475 } // stage("Install")
476 ///////////////////////////////////////////////////////////////////////////////////////
477 // Health check of installed OSM in remote vm
478 ///////////////////////////////////////////////////////////////////////////////////////
479 stage("OSM Health") {
481 sshCommand remote: remote, command: """
482 /usr/share/osm-devops/installers/osm_health.sh -k -s ${stackName}
484 } // stage("OSM Health")
486 } // if ( params.DO_INSTALL )
489 ///////////////////////////////////////////////////////////////////////////////////////
490 // Execute Robot tests
491 ///////////////////////////////////////////////////////////////////////////////////////
492 stage_archive = false
493 if ( params.DO_ROBOT ) {
495 stage("System Integration Test") {
496 if ( useCharmedInstaller ) {
497 tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
498 sh(script: "touch ${tempdir}/hosts")
499 hostfile="${tempdir}/hosts"
500 sh """cat << EOF > ${hostfile}
502 ${remote.host} prometheus.${remote.host}.xip.io nbi.${remote.host}.xip.io
508 jujuPassword=sshCommand remote: remote, command: """
509 echo `juju gui 2>&1 | grep password | cut -d: -f2`
523 } // stage("System Integration Test")
525 stage("Archive Container Logs") {
526 // Archive logs to containers_logs.txt
528 if ( ! currentBuild.result.equals('UNSTABLE') && ! currentBuild.result.equals('FAILURE')) {
529 stage_archive = keep_artifacts
531 println ("Systest test failed, throwing error")
532 error = new Exception("Systest test failed")
533 currentBuild.result = 'FAILURE'
538 } // if ( params.DO_ROBOT )
540 if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive ) {
542 sh "echo ${container_name} > build_version.txt"
543 archiveArtifacts artifacts: "build_version.txt", fingerprint: true
545 // Archive the tested repo
546 dir("${RELEASE_DIR}") {
547 ci_helper.archive(params.ARTIFACTORY_SERVER,RELEASE,GERRIT_BRANCH,'tested')
549 if ( params.DO_DOCKERPUSH ) {
550 stage("Publish to Dockerhub") {
552 for (buildStep in containerList) {
553 def module = buildStep
554 def moduleName = buildStep.toLowerCase()
555 def dockerTag = params.DOCKER_TAG
556 def moduleTag = container_name
558 parallelSteps[module] = {
560 sh "docker tag opensourcemano/${moduleName}:${moduleTag} opensourcemano/${moduleName}:${dockerTag}"
561 sh "docker push opensourcemano/${moduleName}:${dockerTag}"
565 parallel parallelSteps
568 stage("Snap promotion") {
569 def snaps = ["osmclient"]
570 sh "snapcraft login --with ~/.snapcraft/config"
571 for (snap in snaps) {
573 if (BRANCH_NAME.startsWith("v")) {
574 channel=BRANCH_NAME.substring(1)+"/"
575 } else if (BRANCH_NAME!="master") {
576 channel+="/"+BRANCH_NAME.replaceAll('/','-')
578 track=channel+"edge\\*"
579 edge_rev=sh(returnStdout: true,
580 script: "snapcraft revisions $snap | " +
581 "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
582 print "edge rev is $edge_rev"
583 track=channel+"beta\\*"
584 beta_rev=sh(returnStdout: true,
585 script: "snapcraft revisions $snap | " +
586 "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
587 print "beta rev is $beta_rev"
589 if ( edge_rev != beta_rev ) {
590 print "Promoting $edge_rev to beta in place of $beta_rev"
591 beta_track=channel+"beta"
592 sh "snapcraft release $snap $edge_rev $beta_track"
595 } // stage("Snap promotion")
596 } // if ( params.DO_DOCKERPUSH )
597 } // stage("Archive")
598 } // if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive )
601 if ( params.DO_INSTALL && server_id != null) {
603 if (error && params.SAVE_CONTAINER_ON_FAIL ) {
606 if (!error && params.SAVE_CONTAINER_ON_PASS ) {
611 if (server_id != null) {
612 println("Deleting VM: $server_id")
614 for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
615 openstack server delete ${server_id}
618 println("Saved VM $server_id in ETSI VIM")
622 if ( http_server_name != null ) {
623 sh "docker stop ${http_server_name} || true"
624 sh "docker rm ${http_server_name} || true"
627 if ( devopstempdir != null ) {
628 sh "rm -rf ${devopstempdir}"