模板功能用于发版本到gallery上面
需要在代码仓库配置webhook,需要maintianer权限
webhook配置可以参考Mr 触发的pre build
pipeline {
agent {
kubernetes {
label "${UUID.randomUUID().toString()}"
yaml """
metadata:
labels:
some-label: some-label-value
class: KubernetesDeclarativeAgentTest
namespace: scm
spec:
nodeSelector:
jenkins-ci: "true"
containers:
- name: prepare
image: hub.hobot.cc/builder/cicd-common-tool:v10
command:
- cat
tty: true
env:
- name: CONTAINER_ENV_VAR
value: prepare
- name: build
image: hub.hobot.cc/builder/hobot-adas-ltc:v4
command:
- cat
tty: true
env:
- name: CONTAINER_ENV_VAR
value: build
- name: gallery
image: hub.hobot.cc/ci/gallery-cli:0.1.9
command:
- cat
tty: true
env:
- name: CONTAINER_ENV_VAR
value: gallery
"""
}
}
stages{
stage('lanuch') {
steps {
container('prepare') {
script {
sh 'env'
println Jenkins.instance.getNode("${env.NODE_NAME}").toComputer().getLog()
if (!env.REVISION_ID) {
updateGitlabCommitStatus name: "Jenkins", state: 'running'
}
ssh_key_init()
get_code()
add_link()
}
}
}
}
stage('build') {
parallel {
stage('demo'){
steps {
container('build') {
script {
// 编译命令
build()
}
}
}
}
}
}
stage('upload') {
parallel {
stage('demo'){
environment {
// gallery上面的对应的GROUP和PROJECT 、
GALLERY_GROUP = "public"
GALLERY_PROJECT = "demo"
LANG = 'en_US.UTF-8'
}
steps {
container('gallery') {
script {
// 打包上传
exec_upload()
}
}
}
}
}
}
}
options {
gitLabConnection('Gitlab connector by hobot.ci')
}
triggers {
gitlab(
triggerOnPush: true,
triggerOnMergeRequest: true,
triggerOpenMergeRequestOnPush: "never",
triggerOnNoteRequest: true,
noteRegex: "Jenkins please retry a build",
skipWorkInProgressMergeRequest: true,
ciSkip: false,
setBuildDescription: true,
addNoteOnMergeRequest: true,
addCiMessage: true,
addVoteOnMergeRequest: true,
acceptMergeRequestOnSuccess: true,
pendingBuildName: "Jenkins",
cancelPendingBuildsOnUpdate: true,
// branchFilterType: "NameBasedFilter",
// includeBranchesSpec: "*",
branchFilterType: 'All',
// includeBranchesSpec: '',
// excludeBranchesSpec: '',
// branchFilterType: "NameBasedFilter",
// includeBranchesSpec: "refs/tags/*",
// excludeBranchesSpec: "",
)
}
parameters {
string defaultValue: '', description: 'Enter gitlabActionType', name: 'gitlabActionType_replay', trim: true
string defaultValue: '', description: 'Enter gitlabSourceBranch', name: 'gitlabSourceBranch_replay', trim: true
string defaultValue: '', description: 'Enter gitlabTargetBranch', name: 'gitlabTargetBranch_replay', trim: true
string defaultValue: '', description: 'Enter gitlabSourceRepoHomepage', name: 'gitlabSourceRepoHomepage_replay', trim: true
string defaultValue: '', description: 'Enter gitlabMergeRequestIid', name: 'gitlabMergeRequestIid_replay', trim: true
string defaultValue: '', description: 'Enter gitlabMergeRequestLastCommit', name: 'gitlabMergeRequestLastCommit_replay', trim: true
string defaultValue: '', description: 'Enter gitlabSourceRepoSshUrl', name: 'gitlabSourceRepoSshUrl_replay', trim: true
string defaultValue: '', description: 'Enter PH DIFF_ID', name: 'DIFF_ID', trim: true
string defaultValue: '', description: 'Enter PH PHID', name: 'PHID', trim: true
string defaultValue: '', description: 'Enter PH REVISION ID', name: 'REVISION_ID', trim: true
booleanParam defaultValue: false, description: 'flag daily testing', name: 'DAILY_TESTING'
booleanParam defaultValue: false, description: 'commit build upload to gallery', name: 'UPLOAD_GALLERY'
}
environment {
gitlabActionType = "${env.gitlabActionType ? "${env.gitlabActionType}" : "${env.gitlabActionType_replay}"}"
gitlabSourceBranch = "${env.gitlabSourceBranch ? "${env.gitlabSourceBranch}" : "${env.gitlabSourceBranch_replay}"}"
gitlabTargetBranch = "${env.gitlabTargetBranch ? "${env.gitlabTargetBranch}" : "${env.gitlabTargetBranch_replay}"}"
gitlabSourceRepoHomepage = "${env.gitlabSourceRepoHomepage ? "${env.gitlabSourceRepoHomepage}" : "${env.gitlabSourceRepoHomepage_replay}"}"
gitlabMergeRequestIid = "${env.gitlabMergeRequestIid ? "${env.gitlabMergeRequestIid}" : "${env.gitlabMergeRequestIid_replay}"}"
gitlabMergeRequestLastCommit = "${env.gitlabMergeRequestLastCommit ? "${env.gitlabMergeRequestLastCommit}" : "${env.gitlabMergeRequestLastCommit_replay}"}"
gitlabSourceRepoSshUrl = "${env.gitlabSourceRepoSshUrl ? "${env.gitlabSourceRepoSshUrl}" : "${env.gitlabSourceRepoSshUrl_replay}"}"
LANG = 'en_US.UTF-8'
SSH_KEY_FILE = credentials('725xxxx')
//这是配置编译时下载代码的密钥,密钥配置方法参考:CICD流程获取代码权限管理方案 中的 10. 如何在Jenkins内创建账号认证信息
}
post {
failure {
container('prepare') {
script {
if (!env.REVISION_ID) {
updateGitlabCommitStatus name: "Jenkins", state: 'failed'
}
}
}
}
success {
container('prepare') {
script {
if (!env.REVISION_ID) {
updateGitlabCommitStatus name: "Jenkins", state: 'success'
}
}
}
}
unstable {
container('prepare') {
script {
if (!env.REVISION_ID) {
updateGitlabCommitStatus name: "Jenkins", state: 'success'
}
}
}
}
aborted {
container('prepare') {
script {
if (!env.REVISION_ID) {
updateGitlabCommitStatus name: "Jenkins", state: 'canceled'
}
}
}
}
always {
container('prepare') {
script {
if (["MERGE", "NOTE"].contains(env.gitlabActionType)) {
addGitLabMRComment(comment: "Build Result: ${currentBuild.currentResult}\n\nJob Link: ${env.BUILD_URL}")
}
if (env.REVISION_ID) {
step([$class: 'PhabricatorNotifier', commentOnSuccess: true, commentWithConsoleLinkOnFailure: true])
}
}
}
}
}
}
def build() {
// 这里是编译命令 可以添加在下面
dir("../${STAGE_NAME}"){
sh 'cp -a ${WORKSPACE}/rsc/. .'
sh 'env'
sh 'pwd'
// sh 'sh -ex build.sh'
}
}
def get_version_status() {
if (["TAG_PUSH"].contains(env.gitlabActionType)) {
TAG_NAME = "${env.gitlabSourceBranch}".replace("refs/tags/", "")
tag_stage = sh (script: "git --no-pager show -s --format='%N' $TAG_NAME --",returnStdout: true).trim().replaceAll("[\\n\\r]", " ")
version_name = "${env.TAG_NAME}"
if (tag_stage ==~ /.*\[release\].*/) {
gallery_status = "release"
}
else {
gallery_status = "stage"
}
}
else {
if (env.DIFF_ID) {
version_name = "PH-D${env.REVISION_ID}" + "-" + "${env.BUILD_TIMESTAMP}".split()[0]
}
else {
def git_commit_id = sh (script: "git --no-pager log --pretty=format:%H -n 1",returnStdout: true).trim()
version_name = git_commit_id.trim()[0..8]
}
gallery_status = "snapshot"
}
echo version_name
echo gallery_status
return [version_name,gallery_status]
}
def exec_upload() {
dir("../${STAGE_NAME}"){
(version_name,gallery_status) = get_version_status()
echo version_name
echo gallery_status
// 以下是打包上传的命令,如果本地的生成物直接就是个压缩包则可以直接上传,如果是个目录就打成zip包上传
sh """
zip -r output.zip output
gallery-cli upload --filename output.zip \
--status $gallery_status \
--version $version_name
"""
}
}
def add_link() {
def git_commit_id = sh (script: "cd rsc;git --no-pager log --pretty=format:%H -n 1",returnStdout: true).trim()
switch("${env.gitlabActionType}") {
case "MERGE":
short_text = "ACTION: ${env.gitlabActionType} - FROM: ${env.gitlabSourceBranch} TO: ${env.gitlabTargetBranch} - REPO: ${env.gitlabSourceRepoSshUrl}"
short_link = "${env.gitlabSourceRepoHomepage}/merge_requests/${env.gitlabMergeRequestIid}"
break
case "NOTE":
short_text = "ACTION: ${env.gitlabActionType} - FROM: ${env.gitlabSourceBranch} TO: ${env.gitlabTargetBranch} - REPO: ${env.gitlabSourceRepoSshUrl}"
short_link = "${env.gitlabSourceRepoHomepage}/merge_requests/${env.gitlabMergeRequestIid}"
break
case "TAG_PUSH":
short_text = "ACTION: ${env.gitlabActionType} - TAG: ${env.gitlabSourceBranch} - REPO: ${env.gitlabSourceRepoSshUrl}"
short_link = "${env.gitlabSourceRepoHomepage}/" + "${env.gitlabSourceBranch}".replace("refs/", "/")
break
default:
short_text = "ACTION: ${env.gitlabActionType} - BRANCH: ${env.gitlabSourceBranch} - REPO: ${env.gitlabSourceRepoSshUrl}"
short_link = "${env.gitlabSourceRepoHomepage}/commit/${git_commit_id}"
break
}
if (env.REVISION_ID) {
sh '''
curl https://cr.hobot.cc/api/differential.revision.edit \
-d api.token= \
-d transactions[0][type]=comment \
-d transactions[0][value]="build job is running \n click this link then redirect to build job: \n ${BUILD_URL}" \
-d objectIdentifier=$REVISION_ID
'''
short_text = "Link to PH D${env.REVISION_ID}"
short_link = "https://cr.hobot.cc/D${env.REVISION_ID}"
}
addShortText(
text: "${short_text}",
padding: "1",
border: "0",
margin: "0px",
background: "transparent",
color: "blue",
link: "${short_link}"
)
}
def get_code() {
if (["MERGE", "NOTE"].contains(env.gitlabActionType)) {
echo "merge process"
checkout([
$class: 'GitSCM',
branches: [[name: "origin/${env.gitlabSourceBranch}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [
[$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false],
[$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', trackingSubmodules: true],
[$class: 'AuthorInChangelog'],
[$class: 'PreBuildMerge', options: [mergeRemote: 'origin', mergeTarget: "${env.gitlabTargetBranch}"]],
[$class: 'UserIdentity', email: 'xxx@horizon.ai', name: 'xxxx'],
[$class: 'RelativeTargetDirectory', relativeTargetDir: 'rsc']
],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'e4863685-67d4-499e-9b9b-417252cfa88b', url: "${env.gitlabSourceRepoSshUrl}"]]
])
}
else {
echo "push process"
checkout([
$class: 'GitSCM',
branches: [[name: "origin/${env.gitlabSourceBranch}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [
[$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false],
[$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', trackingSubmodules: true],
[$class: 'AuthorInChangelog'],
[$class: 'UserIdentity', email: 'hobot.ci@horizon.ai', name: 'hobot.ci'],
[$class: 'RelativeTargetDirectory', relativeTargetDir: 'rsc']
],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'e4863685-67d4-499e-9b9b-417252cfa88b', url: "${env.gitlabSourceRepoSshUrl}"]]
])
if (env.REVISION_ID) {
dir("rsc") {
echo "apply patch from ph"
PH_BRANCH_NAME = sh (script: 'curl -s https://cr.hobot.cc/api/differential.diff.search -d api.token= -d constraints[ids][0]=$DIFF_ID | python3 -c "import sys, json; print(json.load(sys.stdin)[\'result\'][\'data\'][0][\'fields\'][\'refs\'][1][\'name\'])"',returnStdout: true).trim().replaceAll("/", "%2F")
sh """
git config --global user.name hobot.ci
git config --global user.email hobot.ci@horizon.ai
git reset --hard origin/"${PH_BRANCH_NAME}"
git clean -fd -f
arc patch --diff "$DIFF_ID" --nobranch --force --conduit-uri=https://cr.hobot.cc/ --conduit-token=
"""
}
}
}
}
def ssh_key_init() {
sh '''
echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config
git config --global user.name hobot.ci
git config --global user.email hobot.ci@horizon.ai
git config --global color.ui false
rm -rf ~/.ssh
mkdir ~/.ssh
cp ${SSH_KEY_FILE} ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
ls -lsha ~/.ssh/
eval `ssh-agent`
ssh-add ~/.ssh/id_ed25519
ssh-add -l
'''
}