Skip to content
Snippets Groups Projects
Forked from oai / cn5g / oai-cn5g-fed
791 commits behind the upstream repository.
Jenkinsfile-GitLab-Docker 17.50 KiB
#!/bin/groovy
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.1  (the "License"); you may not use this file
 * except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.openairinterface.org/?page_id=698
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

//-------------------------------------------------------------------------------
// Abstraction function to send social media messages:
// like on Slack or Mattermost
def sendSocialMediaMessage(pipeChannel, pipeColor, pipeMessage) {
  if (params.pipelineUsesSlack != null) {
    if (params.pipelineUsesSlack) {
      slackSend channel: pipeChannel, color: pipeColor, message: pipeMessage
    }
  }
}

// Location of the CN executor node
def cn_ci_host = params.Host_CN_CI_Server

// for lock
def cn_ci_resource = params.DockerContainers
def ds_tester_ci_resource = params.DsTester

// Location of the DsTester workspace
def dsTestFrameworkLocation = params.dsTestFrameworkLocation

// When triggered by upstream, specify which tag to use
def upstreamTagToUse = params.upstreamTagToUse

// Location of the 2nd CN executor
def new_host_flag = false
def new_host = ""
def new_host_user = ""

// Location of the CN tester
def dsT_host_flag = false
def dsT_host = ""
def dsT_host_user = ""
def dsT_host_ip_addr = ""

// Flags
def scmEvent = false
def upstreamEvent = false

// Default tags / branches  --> could be passed on by upstream job or by PR content
def nrfTag = 'dockerfile'
def nrfBranch = 'develop'
def amfTag = 'nrf-com'
def amfBranch = 'develop'
def smfTag = 'dockerfile'
def smfBranch = 'develop'
def spgwuTag = 'nrf-com'
def spgwuBranch = 'master'

//-------------------------------------------------------------------------------
// Pipeline start
pipeline {
  agent {
    label cn_ci_host
  }
  options {
    disableConcurrentBuilds()
    timestamps()
    ansiColor('xterm')
    lock(cn_ci_resource)
  }
  stages {
    stage ('Verify Parameters') {
      steps {
        script {
          echo '\u2705 \u001B[32mVerify Parameters\u001B[0m'

          JOB_TIMESTAMP = sh returnStdout: true, script: 'date --utc --rfc-3339=seconds | sed -e "s#+00:00##"'
          JOB_TIMESTAMP = JOB_TIMESTAMP.trim()

          if (params.Host_CN_CI_2nd_Server_Flag != null) {
            new_host_flag = params.Host_CN_CI_2nd_Server_Flag
            if (new_host_flag) {
              new_host = params.Host_CN_CI_2nd_Server
              new_host_user = params.Host_CN_CI_2nd_Server_Login
              echo "1st Node   is ${NODE_NAME}"
              echo "2nd Node   is ${new_host}"
            } else {
              echo "Node       is ${NODE_NAME}"
            }
          } else {
            echo "Node       is ${NODE_NAME}"
          }
          if (params.DS_Tester_Server_Flag != null) {
            dsT_host_flag = params.DS_Tester_Server_Flag
            if (dsT_host_flag) {
              def allParametersPresent = true
              if (params.DS_Tester_Server_Name == null) {
                allParametersPresent = false
              } else {
                dsT_host = params.DS_Tester_Server_Name
              }
              if (params.DS_Tester_Server_Login == null) {
                allParametersPresent = false
              } else {
                dsT_host_user = params.DS_Tester_Server_Login
              }
              if (params.DS_Tester_Server_IP_Addr == null) {
                allParametersPresent = false
              } else {
                dsT_host_ip_addr = params.DS_Tester_Server_IP_Addr
              }
              if (allParametersPresent) {
                echo "DS Tester  is on ${dsT_host}"
              } else {
                echo "Some DS Tester parameters are missing!"
                sh "./ci-scripts/fail.sh"
              }
            }
          }

          // Find out the cause of the trigger
          for (cause in currentBuild.getBuildCauses()) {
            if (cause.toString() ==~ /.*UpstreamCause.*/) {
              upstreamEvent = true
            //} else {
            //  scmEvent = true
            }
          }

          if (upstreamEvent) {
            if (params.NRF_TAG != null) {
              nrfTag = params.NRF_TAG
              echo "Upstream Job passed NRF_TAG to use: ${nrfTag}"
            }
            if (params.NRF_BRANCH != null) {
              nrfBranch = params.NRF_BRANCH
              echo "Upstream Job passed NRF_BRANCH to use: ${nrfBranch}"
            }
            if (params.AMF_TAG != null) {
              amfTag = params.AMF_TAG
              echo "Upstream Job passed AMF_TAG to use: ${amfTag}"
            }
            if (params.AMF_BRANCH != null) {
              amfBranch = params.AMF_BRANCH
              echo "Upstream Job passed AMF_BRANCH to use: ${amfBranch}"
            }
            if (params.SMF_TAG != null) {
              smfTag = params.SMF_TAG
              echo "Upstream Job passed SMF_TAG to use: ${smfTag}"
            }
            if (params.SMF_BRANCH != null) {
              smfBranch = params.SMF_BRANCH
              echo "Upstream Job passed SMF_BRANCH to use: ${smfBranch}"
            }
            sh "git clean -x -d -f > /dev/null 2>&1"
            sh "git fetch --prune > /dev/null 2>&1"
            sh 'git checkout -f ' + upstreamTagToUse
            sh "zip -r -qq oai-cn5g-fed.zip .git"
            sh "mkdir -p archives DS-TEST-RESULTS"
            sh './scripts/syncComponents.sh --nrf-branch ' + nrfBranch + ' --amf-branch ' + amfBranch + ' --smf-branch ' + smfBranch + ' --spgwu-tiny-branch ' + spgwuBranch
            if (new_host_flag) {
              // Prepare the workspace in remote server
              copyTo2ndServer('oai-cn5g-fed.zip', new_host_flag, new_host_user, new_host)
              myShCmd('git clean -x -d -f > /dev/null 2>&1', new_host_flag, new_host_user, new_host)
              myShCmd('mkdir -p archives DS-TEST-RESULTS', new_host_flag, new_host_user, new_host)
              myShCmd('./scripts/syncComponents.sh --nrf-branch ' + nrfBranch + ' --amf-branch ' + amfBranch + ' --smf-branch ' + smfBranch, new_host_flag, new_host_user, new_host)
            }
          }
          if (scmEvent) {
            sh "git clean -x -d -f > /dev/null 2>&1"
            if ("MERGE".equals(env.gitlabActionType)) {
              sh "./ci-scripts/doGitLabMerge.sh --src-branch ${env.gitlabSourceBranch} --src-commit ${env.gitlabMergeRequestLastCommit} --target-branch ${env.gitlabTargetBranch} --target-commit ${GIT_COMMIT}"
            }
            sh "zip -r -qq oai-cn5g-fed.zip .git"
            sh "mkdir -p archives DS-TEST-RESULTS"
            sh './scripts/syncComponents.sh'
            if (new_host_flag) {
              // Prepare the workspace in remote server
              copyTo2ndServer('oai-cn5g-fed.zip', new_host_flag, new_host_user, new_host)
              myShCmd('git clean -x -d -f > /dev/null 2>&1', new_host_flag, new_host_user, new_host)
              if ("MERGE".equals(env.gitlabActionType)) {
                myShCmd("./ci-scripts/doGitLabMerge.sh --src-branch ${env.gitlabSourceBranch} --src-commit ${env.gitlabMergeRequestLastCommit} --target-branch ${env.gitlabTargetBranch} --target-commit ${GIT_COMMIT}", new_host_flag, new_host_user, new_host)
              }
              myShCmd('mkdir -p archives DS-TEST-RESULTS', new_host_flag, new_host_user, new_host)
              myShCmd('./scripts/syncComponents.sh', new_host_flag, new_host_user, new_host)
            }
          }
          if ((!upstreamEvent) && (!scmEvent)) {
            sh "git clean -x -d -f > /dev/null 2>&1"
            sh './scripts/syncComponents.sh --nrf-branch ' + nrfBranch + ' --amf-branch ' + amfBranch + ' --smf-branch ' + smfBranch + ' --spgwu-tiny-branch ' + spgwuBranch
            sh "mkdir -p archives DS-TEST-RESULTS"
          }
          // Verify that the images are available
          try {
            sh 'echo "OAI_NRF_TAG: oai-nrf:' + nrfTag +'" > archives/oai_nrf_image_info.log'
            sh 'docker image inspect --format=\'Size = {{.Size}} bytes\' oai-nrf:' + nrfTag + ' >> archives/oai_nrf_image_info.log'
            sh 'docker image inspect --format=\'Date = {{.Created}}\' oai-nrf:' + nrfTag + ' >> archives/oai_nrf_image_info.log'
          } catch (Exception e) {
            error "OAI NRF Image tag to test does not exist!"
          }
          try {
            sh 'echo "OAI_AMF_TAG: oai-amf:' + amfTag +'" > archives/oai_amf_image_info.log'
            sh 'docker image inspect --format=\'Size = {{.Size}} bytes\' oai-amf:' + amfTag + ' >> archives/oai_amf_image_info.log'
            sh 'docker image inspect --format=\'Date = {{.Created}}\' oai-amf:' + amfTag + ' >> archives/oai_amf_image_info.log'
          } catch (Exception e) {
            error "OAI AMF Image tag to test does not exist!"
          }
          try {
            sh 'echo "OAI_SMF_TAG: oai-smf:' + smfTag +'" > archives/oai_smf_image_info.log'
            sh 'docker image inspect --format=\'Size = {{.Size}} bytes\' oai-smf:' + smfTag + ' >> archives/oai_smf_image_info.log'
            sh 'docker image inspect --format=\'Date = {{.Created}}\' oai-smf:' + smfTag + ' >> archives/oai_smf_image_info.log'
          } catch (Exception e) {
            error "OAI SMF Image tag to test does not exist!"
          }
          try {
            sh 'echo "OAI_SPGWU_TAG: oai-spgwu-tiny:' + spgwuTag +'" > archives/oai_spgwu_image_info.log'
            sh 'docker image inspect --format=\'Size = {{.Size}} bytes\' oai-spgwu-tiny:' + spgwuTag + ' >> archives/oai_spgwu_image_info.log'
            sh 'docker image inspect --format=\'Date = {{.Created}}\' oai-spgwu-tiny:' + spgwuTag + ' >> archives/oai_spgwu_image_info.log'
          } catch (Exception e) {
            error "OAI SPGW-U-Tiny Image tag to test does not exist!"
          }
        }
      }
    }
    stage ('Deploy Whole 5G Core Network') {
      steps {
        script {
          echo '\u2705 \u001B[32mDeploy CN5G in idle mode\u001B[0m'
          // Prepare all needed files for docker-compose
          // First put all correct tags to test
          sh 'sed -e "s#NRF_IMAGE_TAG#' + nrfTag + '#" -e "s#AMF_IMAGE_TAG#' + amfTag + '#" -e "s#SMF_IMAGE_TAG#' + smfTag + '#" ci-scripts/dsTesterDockerCompose/docker-compose.tplt > ci-scripts/dsTesterDockerCompose/docker-compose.yml'
          // Entrypoints are modified to be inactive for dsTester framework
          sh 'sed -e "s@exec.*@sleep infinity@" component/oai-nrf/scripts/entrypoint.sh > ci-scripts/dsTesterDockerCompose/nrf-entrypoint-sleep.sh'
          sh 'sed -e "s@exec.*@sleep infinity@" component/oai-amf/scripts/entrypoint.sh > ci-scripts/dsTesterDockerCompose/amf-entrypoint-sleep.sh'
          sh 'sed -e "s@exec.*@sleep infinity@" component/oai-smf/scripts/entrypoint.sh > ci-scripts/dsTesterDockerCompose/smf-entrypoint-sleep.sh'
          sh 'sed -e "s@exec.*@sleep infinity@" component/oai-upf-equivalent/scripts/entrypoint.sh > ci-scripts/dsTesterDockerCompose/upf-entrypoint-sleep.sh'
          sh 'chmod 775 ci-scripts/dsTesterDockerCompose/*entrypoint-sleep.sh'
          dir('ci-scripts/dsTesterDockerCompose') {
            sh 'docker-compose up -d  > ../../archives/compose_5gcn_up.log 2>&1'
            sh 'sleep 100'
            // Do a check on number of healthy containers
            // 5 == mysql + nrf + amf + smf + upf(spgwu-tiny)
            ret = sh returnStdout: true, script: 'docker-compose ps -a | grep -v unhealthy | grep -c healthy || true'
            ret = ret.trim()
            if (ret != '5') {
              error "Deployment went wrong!"
            }          
          }
        }
      }
      post {
        always {
          script {
            // Check status on mysql.
            try {
              sh 'docker exec cicd-mysql-svr /bin/bash -c "mysqladmin -u root --password=linux ping" > archives/mysql_status.log 2>&1'
              sh 'docker inspect --format=\'STATUS: {{.State.Health.Status}}\' cicd-mysql-svr >> archives/mysql_status.log'
            } catch (Exception e) {
              sh 'echo "STATUS: KO" >> archives/mysql_status.log'
            }
            // Do docker logs to recover the configuration results
            try {
              sh 'docker logs cicd-oai-nrf > archives/nrf_config.log 2>&1'
              sh 'docker inspect --format=\'STATUS: {{.State.Health.Status}}\' cicd-oai-nrf >> archives/nrf_config.log'
            } catch (Exception e) {
              sh 'echo "STATUS: KO" >> archives/nrf_config.log'
            }
            try {
              sh 'docker logs cicd-oai-amf > archives/amf_config.log 2>&1'
              sh 'docker inspect --format=\'STATUS: {{.State.Health.Status}}\' cicd-oai-amf >> archives/amf_config.log'
            } catch (Exception e) {
              sh 'echo "STATUS: KO" >> archives/amf_config.log'
            }
            try {
              sh 'docker logs cicd-oai-smf > archives/smf_config.log 2>&1'
              sh 'docker inspect --format=\'STATUS: {{.State.Health.Status}}\' cicd-oai-smf >> archives/smf_config.log'
            } catch (Exception e) {
              sh 'echo "STATUS: OK" >> archives/smf_config.log'
            }
            try {
              sh 'docker logs cicd-oai-upf > archives/spgwu_config.log 2>&1'
              sh 'docker inspect --format=\'STATUS: {{.State.Health.Status}}\' cicd-oai-upf >> archives/spgwu_config.log'
            } catch (Exception e) {
              sh 'echo "STATUS: KO" >> archives/spgwu_config.log'
            }
          }
        }
        success {
          script {
            sh 'echo "DEPLOYMENT: OK" > archives/deployment_status.log'
          }
        }
        unsuccessful {
          script {
            sh 'echo "DEPLOYMENT: KO" > archives/deployment_status.log'
          }
        }
      }
    }
    stage ('Check with DS Tester') {
      when { expression {dsT_host_flag} }
      steps {
        lock (ds_tester_ci_resource) {
          script {
            sh 'cd ' + dsTestFrameworkLocation + ' && git clean -x -d -f > /dev/null'
            sh 'cd ' + dsTestFrameworkLocation + '/scripts && export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:.:/usr/local/devsol/bin && CI_ENV=True SRC_BASE_DIR=' + WORKSPACE + ' ./run-5gc.bash -pt --shark --detach --get-results --5g > ' + WORKSPACE + '/archives/run-5g-dstester.log 2>&1'
            sh 'cd ' + dsTestFrameworkLocation + ' && git stash > /dev/null'
            sh 'cd ' + dsTestFrameworkLocation + ' && git stash clear > /dev/null'
          }
        }
      }
    }
    stage ('Undeploy 5G-CN') {
      steps {
        script {
          echo '\u2705 \u001B[32mUn-Deploy CN5G\u001B[0m'
          dir('ci-scripts/dsTesterDockerCompose') {
            sh 'docker-compose down > ../../archives/compose_normal_down.log 2>&1'
          }
        }
      }
    }
  }
  post {
    always {
      script { 
        // Remove any leftover containers/networks
        dir('ci-scripts/dsTesterDockerCompose') {
          sh 'docker-compose down > ../../archives/compose_l_down.log 2>&1'
        }
        // Generating the HTML report
        sh 'python3 ./ci-scripts/dsTestGenerateHTMLReport.py --job_name=' + JOB_NAME + ' --job_id=' + BUILD_ID + ' --job_url=' + BUILD_URL

        // Zipping all archived log files
        sh "zip -r -qq cn5g_fed_docker_logs.zip archives DS-TEST-RESULTS/*.tar DS-TEST-RESULTS/status.txt"
        if (fileExists('cn5g_fed_docker_logs.zip')) {
          archiveArtifacts artifacts: 'cn5g_fed_docker_logs.zip'
        }
        if (fileExists('test_results_oai_cn5g.html')) {
          archiveArtifacts artifacts: 'test_results_oai_cn5g.html'
        }
      }
    }
  }
}

// Functions

def copyTo2ndServer(filename, flag, user, host) {
  if (flag) {
    if ("oai-cn5g-fed.zip".equals(filename)) {
      sh "ssh ${user}@${host} 'rm -rf /tmp/CI-CN5G-FED'"
      sh "ssh ${user}@${host} 'mkdir -p /tmp/CI-CN5G-FED'"
    }
    sh "scp ${filename} ${user}@${host}:/tmp/CI-CN5G-FED"
    if ("oai-cn5g-fed.zip".equals(filename)) {
      sh "ssh ${user}@${host} 'cd /tmp/CI-CN5G-FED && unzip -qq oai-cn5g-fed.zip && rm oai-cn5g-fed.zip'"
      sh "ssh ${user}@${host} 'cd /tmp/CI-CN5G-FED && git checkout -f ${GIT_COMMIT}'"
      sh "ssh ${user}@${host} 'cd /tmp/CI-CN5G-FED && git log -n1'"
    }
  }
}

def copyFrom2ndServer(filename, target, flag, user, host) {
  if (flag) {
    sh "scp ${user}@${host}:/tmp/CI-CN5G-FED/${filename} ${target}"
  }
}

def myShCmd(cmd, flag, user, host) {
  if (flag) {
    sh "ssh -t -t ${user}@${host} 'cd /tmp/CI-CN5G-FED && ${cmd}'"
  } else {
    sh "${cmd}"
  }
}

def myShCmdWithLog(cmd, logFile, flag, user, host) {
  if (flag) {
    sh "ssh -t -t ${user}@${host} 'export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:.:/usr/local/devsol/bin && ${cmd}' > ${logFile} 2>&1"
  } else {
    sh "${cmd} > ${logFile} 2>&1"
  }
}

def myShRetCmd(cmd, flag, user, host) {
  if (flag) {
    ret = sh returnStdout: true, script: "ssh -t -t ${user}@${host} 'cd /tmp/CI-CN5G-FED && ${cmd}'"
  } else {
    ret = sh returnStdout: true, script: "${cmd}"
  }
  ret = ret.trim()
  return ret
}