Skip to content
Snippets Groups Projects
Jenkinsfile 12.5 KiB
Newer Older
  • Learn to ignore specific revisions
  •         node {
                label 'jenkins-quarkus-build-agent'
    
    OZGCloud's avatar
    OZGCloud committed
            BLUE_OCEAN_URL = "https://jenkins.infra.ozg-cloud.systems/job/user-manager/job/${env.BRANCH_NAME}/${env.BUILD_NUMBER}/"
    
            RELEASE_REGEX = /\d+.\d+.\d+/
            SNAPSHOT_REGEX = /\d+.\d+.\d+-SNAPSHOT/
            FAILED_STAGE = ""
    
    OZGCloud's avatar
    OZGCloud committed
            SH_SUCCESS_STATUS_CODE = 0
    
    
    OZGCloud's avatar
    OZGCloud committed
            //The container runtime (e.g. docker) that is used to do an image based build. If this is set then a container build is always done.
    
            QUARKUS_NATIVE_CONTAINER_RUNTIME = "docker"
    
    OZGCloud's avatar
    OZGCloud committed
            QUARKUS_CONTAINER_IMAGE_NAME = "user-manager"
    
            QUARKUS_CONTAINER_IMAGE_TAG = "build-latest"
    
        }
    
        options {
            timeout(time: 1, unit: 'HOURS')
            disableConcurrentBuilds()
            buildDiscarder(logRotator(numToKeepStr: '5'))
        }
    
    
    OZGCloud's avatar
    OZGCloud committed
        stages {
            stage('Check Version') {
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
                        def rootVersion = getPomVersion('pom.xml')
                        def userManagerVersion = getPomVersion('user-manager-server/pom.xml')
                        def interfaceVersion = getPomVersion('user-manager-interface/pom.xml')
    
                        if(env.BRANCH_NAME == 'release'){
                            if ( !(rootVersion ==~ RELEASE_REGEX) || !(userManagerVersion ==~ RELEASE_REGEX) || !(interfaceVersion ==~ RELEASE_REGEX)) {
                                error("Keine Release Version für Branch ${env.BRANCH_NAME}.")
                            }
                        } else {
                            if ( !(rootVersion ==~ SNAPSHOT_REGEX) || !(userManagerVersion ==~ SNAPSHOT_REGEX) || !(interfaceVersion ==~ SNAPSHOT_REGEX)) {
                                error("Keine Snapshot Version für Branch ${env.BRANCH_NAME}.")
                            }
                        }
    
                        if( !(rootVersion == userManagerVersion && rootVersion == interfaceVersion )){
                            error("Versionen sind nicht identisch")
                        }
                    }
                }
            }
    
            stage('Build UserManager GRPC') {
    
                steps {
                    script {
                        FAILED_STAGE=env.STAGE_NAME
                    }
    
                    configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                        sh './mvnw -pl user-manager-interface -s $MAVEN_SETTINGS clean deploy -Dmaven.wagon.http.retryHandler.count=3'
                    }
                }
            }
    
            stage('Build UserManager') {
                steps {
                    script {
                        FAILED_STAGE=env.STAGE_NAME
    
                        configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                            sh './mvnw -pl user-manager-server -s $MAVEN_SETTINGS clean deploy -Dmaven.wagon.http.retryHandler.count=3'
                            junit testResults: '**/target/surefire-reports/*.xml', skipPublishingChecks: true
                        }
                    }
                }
            }
    
            stage('Build native container image') {
    
    OZGCloud's avatar
    OZGCloud committed
                steps {
    
    OZGCloud's avatar
    OZGCloud committed
                    script {
                        FAILED_STAGE=env.STAGE_NAME
    
    
                        withCredentials([usernamePassword(credentialsId: 'jenkins-nexus-login', usernameVariable: 'USER', passwordVariable: 'PASSWORD')]) {
                            configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                                sh './mvnw -pl user-manager-server -s $MAVEN_SETTINGS clean verify -Pnative -Dquarkus.container-image.registry=docker.ozg-sh.de -Dquarkus.container-image.username=${USER} -Dquarkus.container-image.password=${PASSWORD} -Dquarkus.container-image.push=true -Dquarkus.container-image.build=true -Dquarkus.native.remote-container-build=true -Dmaven.wagon.http.retryHandler.count=3'
                            }
                        }
    
    OZGCloud's avatar
    OZGCloud committed
                    }
    
            stage ('OWASP Dependency-Check Vulnerabilities') {
    
                when {
                    branch 'master'
                }
    
                steps {
                    dependencyCheck additionalArguments: '''
                            -o "./"
                            -s "./"
                            -f "ALL"
                            -d /dependency-check-data
                            --suppression dependency-check-supressions.xml
                            --disableKnownExploited
                            --disableArchive
                            --prettyPrint''', odcInstallation: 'dependency-check-owasp'
    
                    dependencyCheckPublisher pattern: 'dependency-check-report.xml'
    
    OZGCloud's avatar
    OZGCloud committed
                }
            }
    
            stage('Sonar Checks') {
                when {
                    branch 'master'
                }
    
                steps {
                    script {
    
    OZGCloud's avatar
    OZGCloud committed
                        FAILED_STAGE=env.STAGE_NAME
    
    
                        configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                            dir('user-manager-server') {
                                try {
                                    withSonarQubeEnv('sonarqube-ozg-sh'){
                                        sh "./mvnw -s $MAVEN_SETTINGS package sonar:sonar -Dsonar.coverage.jacoco.xmlReportPaths=${env.WORKSPACE}/user-manager-server/target/jacoco-report/jacoco.xml"
                                    }
                                } catch (Exception e) {
                                    unstable("SonarQube failed")
                                }
                            }
                        }
    
    OZGCloud's avatar
    OZGCloud committed
                    }
    
            stage('Tag and Push Docker image') {
    
    OZGCloud's avatar
    OZGCloud committed
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
    
                        IMAGE_TAG = generateImageTag()
    
                        tagAndPushDockerImage(IMAGE_TAG)
    
                        if (env.BRANCH_NAME == 'master') {
                            tagAndPushDockerImage('snapshot-latest')
                        }
                        else if (env.BRANCH_NAME == 'release') {
                            tagAndPushDockerImage('latest')
                        }
    
    OZGCloud's avatar
    OZGCloud committed
                    }
                }
            }
    
            stage('Test, build and deploy Helm Chart') {
                steps {
                    script {
                        FAILED_STAGE=env.STAGE_NAME
                        HELM_CHART_VERSION = generateHelmChartVersion()
    
                        dir('src/main/helm') {
                            sh "helm lint -f ../../test/unit-values.yaml"
    
    
    OZGCloud's avatar
    OZGCloud committed
                            sh "helm unittest --helm3 -f '../../test/helm/*.yaml' -v '../../test/unit-values.yaml' ."
    
    OZGCloud's avatar
    OZGCloud committed
    
                            sh "helm package --version=${HELM_CHART_VERSION} ."
    
    
                            deployHelmChart(HELM_CHART_VERSION)
    
    OZGCloud's avatar
    OZGCloud committed
                        }
                    }
                }
            }
    
            stage('Rollout Dev UserManager') {
                when {
                    branch 'master'
                }
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
    
                        cloneGitopsRepo()
    
                        setNewDevUserManagerVersion()
    
                        pushDevGitopsRepo()
                    }
                }
            }
    
            stage('Trigger Test rollout') {
                when {
    
                    branch 'release'
    
    OZGCloud's avatar
    OZGCloud committed
                }
    
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
    
    
                        cloneGitopsRepo()
    
                        setNewTestUserManagerVersion()
    
                        pushTestGitopsRepo()
    
    OZGCloud's avatar
    OZGCloud committed
        post {
            failure {
                script {
                    if (env.BRANCH_NAME == 'master' || env.BRANCH_NAME == 'release') {
                        sendFailureMessage()
                    }
                }
            }
        }
    
    Void deployHelmChart(String helmChartVersion) {
    
        withCredentials([usernamePassword(credentialsId: 'jenkins-nexus-login', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
            if (env.BRANCH_NAME == 'release') {
    
                result = sh script: '''curl -u $USERNAME:$PASSWORD https://nexus.ozg-sh.de/service/rest/v1/components?repository=ozg-base-apps -F file=@user-manager-'''+helmChartVersion+'''.tgz''', returnStdout: true
    
                result = sh script: '''curl -u $USERNAME:$PASSWORD https://nexus.ozg-sh.de/service/rest/v1/components?repository=ozg-base-apps-snapshot -F file=@user-manager-'''+helmChartVersion+'''.tgz''', returnStdout: true
    
            }
    
            if (result != '') {
                error(result)
            }
        }
    }
    
    String generateHelmChartVersion() {
        def chartVersion = getPomVersion('pom.xml')
    
        if (env.BRANCH_NAME == 'master') {
            chartVersion += "-${env.GIT_COMMIT.take(7)}"
        }
        else if (env.BRANCH_NAME != 'release') {
            chartVersion += "-${env.BRANCH_NAME}"
        }
    
    
        return chartVersion.replaceAll("_", "-")
    
    Void sendFailureMessage() {
        def room = ''
        def data = """{"msgtype":"m.text", \
    
                        "body":"UserManager: Build Failed. Stage: ${FAILED_STAGE} Build-ID: ${env.BUILD_NUMBER} Link: ${BLUE_OCEAN_URL}", \
    
                        "format": "org.matrix.custom.html", \
    
                        "formatted_body":"UserManager: Build Failed. Stage: ${FAILED_STAGE} Build-ID: <a href='${BLUE_OCEAN_URL}'>${env.BUILD_NUMBER}</a>"}"""
    
        if (env.BRANCH_NAME == 'master') {
            room = "!iQPAvQIiRwRpNOszjw:matrix.ozg-sh.de"
        }
        else if (env.BRANCH_NAME == 'release') {
            room = "!oWZpUGTFsxkJIYNfYg:matrix.ozg-sh.de"
        }
    
        sh "curl -XPOST -H 'authorization: Bearer ${getElementAccessToken()}' -d '${data}' https://matrix.ozg-sh.de/_matrix/client/v3/rooms/$room/send/m.room.message"
    }
    
    String getElementAccessToken() {
        withCredentials([string(credentialsId: 'element-login-json', variable: 'LOGIN_JSON')]) {
            return readJSON ( text: sh (script: '''curl -XPOST -d \"$LOGIN_JSON\" https://matrix.ozg-sh.de/_matrix/client/v3/login''', returnStdout: true)).access_token
        }
    
    OZGCloud's avatar
    OZGCloud committed
    }
    
    OZGCloud's avatar
    OZGCloud committed
    Void setNewDevUserManagerVersion() {
        setNewGitopsVersion('dev')
    }
    
    Void setNewTestUserManagerVersion() {
        setNewGitopsVersion('test')
    }
    
    
    OZGCloud's avatar
    OZGCloud committed
    Void setNewGitopsVersion(String environment) {
        dir("gitops") {
            def envFile = "${environment}/application/values/user-manager-values.yaml"
    
    OZGCloud's avatar
    OZGCloud committed
            def envVersions = readYaml file: envFile
    
    
    OZGCloud's avatar
    OZGCloud committed
            envVersions.user_manager.image.tag = IMAGE_TAG
            envVersions.user_manager.helm.version = HELM_CHART_VERSION
    
    OZGCloud's avatar
    OZGCloud committed
    
            writeYaml file: envFile, data: envVersions, overwrite: true
        }
    }
    
    
    Void configureGit() {
    
    OZGCloud's avatar
    OZGCloud committed
        final email = "jenkins@ozg-sh.de"
        final name = "jenkins"
    
        dir("gitops") {
            sh "git config user.email '${email}'"
            sh "git config user.name '${name}'"
        }
    }
    
    
    Void cloneGitopsRepo() {
    
        withCredentials([usernamePassword(credentialsId: 'jenkins-gitea-access-token', passwordVariable: 'TOKEN', usernameVariable: 'USER')]) {
    
    OZGCloud's avatar
    OZGCloud committed
            sh 'git clone https://${USER}:${TOKEN}@git.ozg-sh.de/mgm/gitops.git'
    
        configureGit()
    
    OZGCloud's avatar
    OZGCloud committed
    }
    
    Void pushDevGitopsRepo(){
        pushNewGitopsVersion('dev')
    }
    
    Void pushTestGitopsRepo(){
        pushNewGitopsVersion('test')
    
    OZGCloud's avatar
    OZGCloud committed
    Void pushNewGitopsVersion(String environment) {
        dir('gitops') {
    
    OZGCloud's avatar
    OZGCloud committed
            if (!hasUserManagerValuesFileChanged(environment)) {
    
            withCredentials([usernamePassword(credentialsId: 'jenkins-gitea-access-token', passwordVariable: 'TOKEN', usernameVariable: 'USER')]) {
    
    OZGCloud's avatar
    OZGCloud committed
                sh "git add ${environment}/application/values/user-manager-values.yaml"
    
                sh "git commit -m 'jenkins rollout ${environment} user-manager version ${IMAGE_TAG}'"
    
    OZGCloud's avatar
    OZGCloud committed
                sh 'git push https://${USER}:${TOKEN}@git.ozg-sh.de/mgm/gitops.git'
    
    OZGCloud's avatar
    OZGCloud committed
    Boolean hasUserManagerValuesFileChanged(String environment) {
        return sh (script: "git status | grep '${environment}/application/values/user-manager-values.yaml'", returnStatus: true) == env.SH_SUCCESS_STATUS_CODE as Integer
    }
    
    
    String getPomVersion(String pomFile){
        def pom = readMavenPom file: pomFile
    
        return pom.version
    }
    
    String generateImageTag() {
        def imageTag = "${env.BRANCH_NAME}-${getPomVersion('pom.xml')}"
    
        if (env.BRANCH_NAME == 'master') {
            imageTag += "-${env.GIT_COMMIT.take(7)}"
        }
    
        return imageTag
    }
    
    Void tagAndPushDockerImage(String newTag) {
    
    OZGCloud's avatar
    OZGCloud committed
        withCredentials([usernamePassword(credentialsId: 'jenkins-nexus-login', usernameVariable: 'USER', passwordVariable: 'PASSWORD')]) {
    
            sh 'docker login docker.ozg-sh.de -u ${USER} -p ${PASSWORD}'
            sh "docker pull docker.ozg-sh.de/root/user-manager:build-latest"
    
            sh "docker tag docker.ozg-sh.de/root/user-manager:build-latest docker.ozg-sh.de/user-manager:${newTag}"
            sh "docker push docker.ozg-sh.de/user-manager:${newTag}"