From a4d3ac96954c4fc94734fcdc5dc0f7216843eedc Mon Sep 17 00:00:00 2001 From: Boris Shestov Date: Mon, 3 Feb 2025 20:41:01 +0300 Subject: [PATCH] [DO-1497] pipeline: Changed release activity flow (!71) [DO-1497] pipeline: Changed release activity flow Co-authored-by: Boris Shestov Reviewed-on: https://git.avroid.tech/DevOps/jenkins-pipelines/pulls/71 --- pipelines/Release-activity/platformng.groovy | 265 ++++++++++++++----- 1 file changed, 204 insertions(+), 61 deletions(-) diff --git a/pipelines/Release-activity/platformng.groovy b/pipelines/Release-activity/platformng.groovy index 30062d5..507d1ec 100644 --- a/pipelines/Release-activity/platformng.groovy +++ b/pipelines/Release-activity/platformng.groovy @@ -1,11 +1,32 @@ @Library('shared-lib') _ +import tech.avroid.scm.Git import tech.avroid.api.Gitea +import tech.avroid.kube.PodTemplates -String branch String apiRepoURL = "${env.JENKINS_GIT_REPOSITORY_URL}/api/v1/repos" -List parentJobs = ['jobs-dsl'] +Git git = new Git(this, env.JENKINS_GIT_CREDENTIALS_SSH) +String branchName = 'master' +String gitRepoUrl = 'BBL/platformng' +String gitUser = 'svc_jenkins' +String gitUserMail = gitUser + '@avroid.tech' + +String uuidDir = UUID.randomUUID().toString() + +Boolean specVersionUpdate = false +String specVersion = '' +String latestTag = '' +String newTag = '' +String appRpmSpecPath = 'ru.avroid.avroid_platform.spec' +String jobName = 'BBL Team/platformng' + +Integer major = 0 +Integer minor = 0 +Integer patch = 0 + +PodTemplates slaveTemplates = + new PodTemplates(this, env.JENKINS_DOCKER_REGISTRY, ["${env.JENKINS_K8S_HARBOR_SECRET}"]) withCredentials([usernamePassword(credentialsId: "${JENKINS_GIT_CREDENTIALS_HTTP}", usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_USER_PASSWORD')]) { @@ -18,9 +39,14 @@ properties([ numToKeepStr: '10')), disableConcurrentBuilds(), parameters([ + choice( + name: 'ACTION', + choices: ['', 'Up minor', 'Up major', 'Build'], + description: 'Select one feature action' + ), choice( name: 'BRANCH_TYPE', - choices: ['Release', 'RC'], + choices: ['release', 'rc'], description: 'Select one of branch types' ), [$class: 'ChoiceParameter', @@ -30,72 +56,189 @@ properties([ name: 'SOURCE_BRANCH_NAME', script: [$class: 'GroovyScript', script: [sandbox: false, script: """import groovy.json.JsonSlurperClassic -def sout = new StringBuffer(), serr = new StringBuffer() -def proc = 'curl --connect-timeout 15 -u ${gitLogin}:${gitPass} ${apiRepoURL}/BBL/platformng/branches'.execute() -proc.consumeProcessOutput(sout, serr) -proc.waitForOrKill(5000) -JSONInfo = new JsonSlurperClassic().parseText(sout.toString()) -List branches = [] -JSONInfo.each{ branch -> -branches.add(branch.name) -} -return branches.sort() -"""]], - ], - string(name: 'VERSION', defaultValue: '', description: 'Release and RC version eg. 1.4'), + def soutB = new StringBuffer(), serrB = new StringBuffer() + def procB = 'curl --connect-timeout 15 -u ${gitLogin}:${gitPass} ${apiRepoURL}/BBL/platformng/branches'.execute() + procB.consumeProcessOutput(soutB, serrB) + procB.waitForOrKill(5000) + JSONInfoB = new JsonSlurperClassic().parseText(soutB.toString()) + List branches = [] + JSONInfoB.each{ branch -> + branches.add(branch.name) + } + + def soutT = new StringBuffer(), serrT = new StringBuffer() + def procT = 'curl --connect-timeout 15 -u ${gitLogin}:${gitPass} ${apiRepoURL}/BBL/platformng/tags'.execute() + procT.consumeProcessOutput(soutT, serrT) + procT.waitForOrKill(5000) + JSONInfoT = new JsonSlurperClassic().parseText(soutT.toString()) + + JSONInfoT.each{ tag -> + branches.add(tag.name) + } + + return branches.sort() + """]], + ] ]) ]) -// Check if job triggered by parent job -Boolean isContainsParentJob = parentJobs.any {job -> currentBuild.upstreamBuilds.projectName.contains(job) } +List gitCreds = [ + [path: 'team-devops/accounts/ldap/service_accounts/svc_jenkins', engineVersion: 2, + secretValues: + [ + [envVar: 'avroidKey', vaultKey: 'openssh.private.key'], + ] + ] +] -if (isContainsParentJob) { - currentBuild.result = 'SUCCESS' - println("This job was triggered by one or more of following upstream jobs ${parentJobs}, so it will be exited without running the steps.") - return -} +Map configuration = [ + vaultUrl: env.JENKINS_VAULT_URL, + vaultCredentialId: 'vault-role', + engineVersion: 2 +] -podTemplate(workspaceVolume: emptyDirWorkspaceVolume(memory: false), yaml: getPodTemplate('alpine')) { - node(POD_LABEL) { - try { - stage('Create branch') { - currentBuild.description = "Build from ${params.SOURCE_BRANCH_NAME}" - String versionPattern = /^\d+\.\d+.*/ - Gitea platformngRepo = new Gitea(this, "${apiRepoURL}/BBL/platformng", "${env.JENKINS_GIT_CREDENTIALS_HTTP}") - branch = params.BRANCH_TYPE.toLowerCase() + params.VERSION - println "Branch name: ${branch}" - - if (!params.VERSION.matches(versionPattern)) { - println('You must specify correct version, see description!') - error() - } - - Boolean result = platformngRepo.createBranch(params.SOURCE_BRANCH_NAME, branch) +slaveTemplates.jnlp { + slaveTemplates.git(imageVersion = 'v2.45.2') { + withVault([configuration: configuration, vaultSecrets: gitCreds]) { + node(POD_LABEL) { + container(name: 'git') { + stage('Prepare ssh config'){ + if (params.ACTION == '') { + error('Необходимо выбрать действие (ACTION).') + } - if (!result) { - println("Branch doesn't create, maybe ${branch} already exists") - error() + sh """#!/bin/sh + mkdir -p ~/.ssh + echo " + Host git.avroid.tech + Hostname git.avroid.tech + IdentityFile ~/.ssh/avroidKey + User git + StrictHostKeyChecking no + UserKnownHostsFile=/dev/null + " > ~/.ssh/config + + echo "${avroidKey}" > ~/.ssh/avroidKey + chmod 600 ~/.ssh/avroidKey + + """ + } + + stage('GitSCM') { + git.clone([urlRepo: "${env.JENKINS_GIT_REPOSITORY_SSH_URL}/${gitRepoUrl}", + path: "${env.WORKSPACE}/${uuidDir}", + disableSubmodules: true, + branch: branchName]) + } + + stage('Set build parameters') { + dir("${env.WORKSPACE}/${uuidDir}") { + git.checkout(origin: 'origin', branch: 'master') + git.config(gitUser, gitUserMail) + + latestTag = sh(script: 'git describe --tags --abbrev=0', returnStdout: true).trim() + echo "latestTag: ${latestTag}" + + String tagPrefix = '' + String tagSuffix = '' + + if (latestTag.startsWith("v")) { + tagPrefix = "v" + tagSuffix = latestTag.substring(1) + } else { + error "Tag does not start with 'v'" + } + + // Разбиваем тег на части + List versionParts = tagSuffix.tokenize('.') + major = versionParts[0].toInteger() + minor = versionParts[1].toInteger() + patch = versionParts[2].toInteger() + + // Инкрементируем указанную часть версии + switch (params.ACTION) { + case 'Up major': + println('up Major') + major += 1 + minor = 0 + patch = 0 + echo "Major тег: ${major}" + specVersionUpdate = true + specVersion = "${major}.0.0" + break + case 'Up minor': + println('up Minor') + minor += 1 + patch = 0 + echo "Minor тег: ${minor}" + specVersionUpdate = true + specVersion = "${major}.${minor}.0" + break + case 'patch': + patch += 1 + echo "Patch тег: ${patch}" + break + } + newTag = "${tagPrefix}${major}.${minor}.${patch}" + echo "newTag: ${newTag}" + } + } + + stage('Update spec file') { + if (specVersionUpdate) { + dir("${env.WORKSPACE}/${uuidDir}") { + sh """#!/bin/bash + sed -i "s/^Version: .*/Version: ${specVersion}/" rpm/${appRpmSpecPath} + cat rpm/${appRpmSpecPath} + """ + } + } + } + + stage('Push to remote repo') { + if (specVersionUpdate) { + dir("${env.WORKSPACE}/${uuidDir}") { + git.config(gitUser, gitUserMail) + git.add() + git.commit("Update version from ${latestTag} to ${newTag}") + git.push(origin: 'origin', branch: branchName) + git.tag([tagName: newTag]) + git.push("origin ${newTag}") + } + } + } + + stage('Run build') { + if (params.ACTION == 'Build') { + dir("${env.WORKSPACE}/${uuidDir}") { + String branchType = params.BRANCH_TYPE + String sourceRef = params.SOURCE_BRANCH_NAME + git.checkout(sourceRef) + latestTag = sh(script: 'git describe --tags --abbrev=0', returnStdout: true).trim() + echo "latestTag: ${latestTag}" + + String newBranch = "${branchType}_${latestTag}" + + echo "sourceRef: ${sourceRef}, newBranch: ${newBranch}" + + Gitea platformngTestRepo = new Gitea(this, + "${apiRepoURL}/${gitRepoUrl}", + "${env.JENKINS_GIT_CREDENTIALS_HTTP}") + try { + Boolean result = platformngTestRepo.createBranch(sourceRef, newBranch) + println(result) + } catch (err) { + println("Branch doesn't create: ${err.getMessage()}") + currentBuild.result = 'UNSTABLE' + } + build(job: jobName, wait: false) + sleep(20) + build(job: "${jobName}/${newBranch}") + } + } + } } } - - if (params.BRANCH_TYPE == 'Release') { - stage('Create SharedLib tag') { - Gitea sharedLibRepo = new Gitea(this, - "${apiRepoURL}/DevOps/jenkins-shared-lib", - "${env.JENKINS_GIT_CREDENTIALS_HTTP}") - - sharedLibRepo.createTag('master', "platformng_${branch}") - } - } - - stage('Run build') { - sleep(5) - build(job: "BBL Team/platformng/${branch}") - } - } - catch(err) { - echo 'ERROR: ' + err.getMessage() - currentBuild.result = 'FAILURE' } } }