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_NAME'),
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 ///////////////////////////////////////////////////////////////////////////////////////
255 for (component in [ "devops", "IM", "osmclient" ]) {
256 sh "ls -al ${component}/pool/"
257 sh "cp -r ${component}/pool/* pool/"
258 sh "dpkg-sig --sign builder -k ${GPG_KEY_NAME} pool/${component}/*"
259 sh "mkdir -p dists/${params.REPO_DISTRO}/${component}/binary-amd64/"
260 sh "apt-ftparchive packages pool/${component} > dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
261 sh "gzip -9fk dists/${params.REPO_DISTRO}/${component}/binary-amd64/Packages"
264 // create and sign the release file
265 sh "apt-ftparchive release dists/${params.REPO_DISTRO} > dists/${params.REPO_DISTRO}/Release"
266 sh "gpg --yes -abs -u ${GPG_KEY_NAME} -o dists/${params.REPO_DISTRO}/Release.gpg dists/${params.REPO_DISTRO}/Release"
268 // copy the public key into the release folder
269 // this pulls the key from the home dir of the current user (jenkins)
270 sh "cp ~/${REPO_KEY_NAME} 'OSM ETSI Release Key.gpg'"
271 sh "cp ~/${REPO_KEY_NAME} ."
274 // start an apache server to serve up the packages
275 http_server_name = "${container_name}-apache"
277 pwd = sh(returnStdout:true, script: 'pwd').trim()
278 repo_port = sh(script: 'echo $(python -c \'import socket; s=socket.socket(); s.bind(("", 0)); print(s.getsockname()[1]); s.close()\');', returnStdout: true).trim()
279 repo_base_url = ci_helper.start_http_server(pwd,http_server_name,repo_port)
280 NODE_IP_ADDRESS=sh(returnStdout: true, script:
281 "echo ${SSH_CONNECTION} | awk '{print \$3}'").trim()
284 // Unpack devops package into temporary location so that we use it from upstream if it was part of a patch
285 osm_devops_dpkg = sh(returnStdout: true, script: "find ./repo/release/pool/ -name osm-devops*.deb").trim()
286 devopstempdir = sh(returnStdout: true, script: "mktemp -d").trim()
287 println("Extracting local devops package ${osm_devops_dpkg} into ${devopstempdir} for docker build step")
288 sh "dpkg -x ${osm_devops_dpkg} ${devopstempdir}"
289 OSM_DEVOPS="${devopstempdir}/usr/share/osm-devops"
290 // Convert URLs from stage 2 packages to arguments that can be passed to docker build
291 for (remotePath in packageList) {
292 packageName=remotePath.substring(remotePath.lastIndexOf('/')+1)
293 packageName=packageName.substring(0,packageName.indexOf('_'))
294 builtModules[packageName]=remotePath
298 ///////////////////////////////////////////////////////////////////////////////////////
299 // Build docker containers
300 ///////////////////////////////////////////////////////////////////////////////////////
304 if ( params.DO_BUILD ) {
305 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
306 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
307 sh "docker login ${INTERNAL_DOCKER_REGISTRY} -u ${USERNAME} -p ${PASSWORD}"
310 for (packageName in builtModules.keySet()) {
311 envName=packageName.replaceAll("-","_").toUpperCase()+"_URL"
312 moduleBuildArgs += " --build-arg ${envName}=" + builtModules[packageName]
316 containerList = sh(returnStdout: true, script:
317 "find . -name Dockerfile -printf '%h\\n' | sed 's|\\./||'")
318 containerList=Arrays.asList(containerList.split("\n"))
321 for (buildStep in containerList) {
322 def module = buildStep
323 def moduleName = buildStep.toLowerCase()
324 def moduleTag = container_name
325 parallelSteps[module] = {
327 sh "docker build -t opensourcemano/${moduleName}:${moduleTag} ${moduleBuildArgs} ."
328 println("Tagging ${moduleName}:${moduleTag}")
329 sh "docker tag opensourcemano/${moduleName}:${moduleTag} ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}"
330 sh "docker push ${INTERNAL_DOCKER_REGISTRY}opensourcemano/${moduleName}:${moduleTag}"
334 parallel parallelSteps
337 } // if ( params.DO_BUILD )
339 if ( params.DO_INSTALL ) {
340 ///////////////////////////////////////////////////////////////////////////////////////
342 ///////////////////////////////////////////////////////////////////////////////////////
343 stage("Spawn Remote VM") {
344 println("Launching new VM")
345 output=sh(returnStdout: true, script: """#!/bin/sh -e
346 for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
347 openstack server create --flavor osm.sanity \
348 --image ubuntu18.04 \
350 --property build_url="${BUILD_URL}" \
351 --nic net-id=osm-ext \
355 server_id = get_value('id', output)
357 if (server_id == null) {
358 println("VM launch output: ")
360 throw new Exception("VM Launch failed")
362 println("Target VM is ${server_id}, waiting for IP address to be assigned")
366 while (IP_ADDRESS == "") {
367 output=sh(returnStdout: true, script: """#!/bin/sh -e
368 for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
369 openstack server show ${server_id}
371 IP_ADDRESS = get_value('addresses', output)
373 IP_ADDRESS = IP_ADDRESS.split('=')[1]
374 println("Waiting for VM at ${IP_ADDRESS} to be reachable")
378 output=sh(returnStdout: true, script: "sleep 1 ; nc -zv ${IP_ADDRESS} 22 2>&1 || true").trim()
379 println("output is [$output]")
380 alive = output.contains("succeeded")
382 println("VM is ready and accepting ssh connections")
383 } // stage("Spawn Remote VM")
385 ///////////////////////////////////////////////////////////////////////////////////////
387 ///////////////////////////////////////////////////////////////////////////////////////
394 if ( params.COMMIT_ID )
396 commit_id = "-b ${params.COMMIT_ID}"
399 if ( params.REPO_DISTRO )
401 repo_distro = "-r ${params.REPO_DISTRO}"
404 if ( params.REPO_KEY_NAME )
406 repo_key_name = "-k ${params.REPO_KEY_NAME}"
409 if ( params.RELEASE )
411 release = "-R ${params.RELEASE}"
414 if ( params.REPOSITORY_BASE )
416 repo_base_url = "-u ${params.REPOSITORY_BASE}"
420 repo_base_url = "-u http://${NODE_IP_ADDRESS}:${repo_port}"
423 remote.name = container_name
424 remote.host = IP_ADDRESS
425 remote.user = 'ubuntu'
426 remote.identityFile = SSH_KEY
427 remote.allowAnyHosts = true
428 remote.logLevel = 'INFO'
431 sshCommand remote: remote, command: """
432 wget https://osm-download.etsi.org/ftp/osm-9.0-nine/install_osm.sh
433 chmod +x ./install_osm.sh
434 sed -i '1 i\\export PATH=/snap/bin:\${PATH}' ~/.bashrc
437 if ( useCharmedInstaller ) {
438 // Use local proxy for docker hub
439 sshCommand remote: remote, command: '''
440 sudo snap install microk8s --classic --channel=1.19/stable
441 sudo sed -i "s|https://registry-1.docker.io|http://172.21.1.1:5000|" /var/snap/microk8s/current/args/containerd-template.toml
442 sudo systemctl restart snap.microk8s.daemon-containerd.service
443 sudo snap alias microk8s.kubectl kubectl
446 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
447 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
448 sshCommand remote: remote, command: """
449 ./install_osm.sh -y \
452 ${release} -r unstable \
454 --registry ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
455 --tag ${container_name}
458 prometheusHostname = "prometheus."+IP_ADDRESS+".xip.io"
460 osmHostname = "nbi."+IP_ADDRESS+".xip.io:443"
462 // Run -k8s installer here specifying internal docker registry and docker proxy
463 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'gitlab-registry',
464 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
465 sshCommand remote: remote, command: """
466 ./install_osm.sh -y \
469 ${release} -r unstable \
470 -d ${USERNAME}:${PASSWORD}@${INTERNAL_DOCKER_REGISTRY} \
471 -p ${INTERNAL_DOCKER_PROXY} \
472 -t ${container_name} \
476 prometheusHostname = IP_ADDRESS
477 prometheusPort = 9091
478 osmHostname = IP_ADDRESS
480 } // stage("Install")
481 ///////////////////////////////////////////////////////////////////////////////////////
482 // Health check of installed OSM in remote vm
483 ///////////////////////////////////////////////////////////////////////////////////////
484 stage("OSM Health") {
486 sshCommand remote: remote, command: """
487 /usr/share/osm-devops/installers/osm_health.sh -k -s ${stackName}
489 } // stage("OSM Health")
490 } // if ( params.DO_INSTALL )
493 ///////////////////////////////////////////////////////////////////////////////////////
494 // Execute Robot tests
495 ///////////////////////////////////////////////////////////////////////////////////////
496 stage_archive = false
497 if ( params.DO_ROBOT ) {
499 stage("System Integration Test") {
500 if ( useCharmedInstaller ) {
501 tempdir = sh(returnStdout: true, script: "mktemp -d").trim()
502 sh(script: "touch ${tempdir}/hosts")
503 hostfile="${tempdir}/hosts"
504 sh """cat << EOF > ${hostfile}
506 ${remote.host} prometheus.${remote.host}.xip.io nbi.${remote.host}.xip.io
512 jujuPassword=sshCommand remote: remote, command: """
513 echo `juju gui 2>&1 | grep password | cut -d: -f2`
518 params.ROBOT_TAG_NAME,
527 } // stage("System Integration Test")
529 stage("Archive Container Logs") {
530 // Archive logs to containers_logs.txt
532 if ( ! currentBuild.result.equals('UNSTABLE') && ! currentBuild.result.equals('FAILURE')) {
533 stage_archive = keep_artifacts
535 println ("Systest test failed, throwing error")
536 error = new Exception("Systest test failed")
537 currentBuild.result = 'FAILURE'
542 } // if ( params.DO_ROBOT )
544 if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive ) {
546 sh "echo ${container_name} > build_version.txt"
547 archiveArtifacts artifacts: "build_version.txt", fingerprint: true
549 // Archive the tested repo
550 dir("${RELEASE_DIR}") {
551 ci_helper.archive(params.ARTIFACTORY_SERVER,RELEASE,GERRIT_BRANCH,'tested')
553 if ( params.DO_DOCKERPUSH ) {
554 stage("Publish to Dockerhub") {
556 for (buildStep in containerList) {
557 def module = buildStep
558 def moduleName = buildStep.toLowerCase()
559 def dockerTag = params.DOCKER_TAG
560 def moduleTag = container_name
562 parallelSteps[module] = {
564 sh "docker tag opensourcemano/${moduleName}:${moduleTag} opensourcemano/${moduleName}:${dockerTag}"
565 sh "docker push opensourcemano/${moduleName}:${dockerTag}"
569 parallel parallelSteps
572 stage("Snap promotion") {
573 def snaps = ["osmclient"]
574 sh "snapcraft login --with ~/.snapcraft/config"
575 for (snap in snaps) {
577 if (BRANCH_NAME.startsWith("v")) {
578 channel=BRANCH_NAME.substring(1)+"/"
579 } else if (BRANCH_NAME!="master") {
580 channel+="/"+BRANCH_NAME.replaceAll('/','-')
582 track=channel+"edge\\*"
583 edge_rev=sh(returnStdout: true,
584 script: "snapcraft revisions $snap | " +
585 "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
586 print "edge rev is $edge_rev"
587 track=channel+"beta\\*"
588 beta_rev=sh(returnStdout: true,
589 script: "snapcraft revisions $snap | " +
590 "grep \"$track\" | tail -1 | awk '{print \$1}'").trim()
591 print "beta rev is $beta_rev"
593 if ( edge_rev != beta_rev ) {
594 print "Promoting $edge_rev to beta in place of $beta_rev"
595 beta_track=channel+"beta"
596 sh "snapcraft release $snap $edge_rev $beta_track"
599 } // stage("Snap promotion")
600 } // if ( params.DO_DOCKERPUSH )
601 } // stage("Archive")
602 } // if ( params.SAVE_ARTIFACTS_OVERRIDE || stage_archive )
605 if ( params.DO_INSTALL && server_id != null) {
607 if (error && params.SAVE_CONTAINER_ON_FAIL ) {
610 if (!error && params.SAVE_CONTAINER_ON_PASS ) {
615 if (server_id != null) {
616 println("Deleting VM: $server_id")
618 for line in `grep OS ~/hive/robot-systest.cfg | grep -v OS_CLOUD` ; do export \$line ; done
619 openstack server delete ${server_id}
622 println("Saved VM $server_id in ETSI VIM")
626 if ( http_server_name != null ) {
627 sh "docker stop ${http_server_name} || true"
628 sh "docker rm ${http_server_name} || true"
631 if ( devopstempdir != null ) {
632 sh "rm -rf ${devopstempdir}"