Jenkinsfile 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /**
  2. * UAT: Checkout -> Maven -> (optional) push images to Harbor -> deploy jar + docker restart.
  3. *
  4. * Jenkins Job: Pipeline script from SCM
  5. * Script Path: docs/jenkins/uat/Jenkinsfile
  6. *
  7. * Harbor (153.68): when PUSH_TO_HARBOR=true, push e.g.
  8. * 39.105.153.68/alien_cloud/gateway:uat-latest
  9. * Before push: existing uat-latest is archived as uat-build-<BUILD_NUMBER> (same digest).
  10. * New image is pushed only as uat-latest. Prod promote: SOURCE_TAG=uat-latest.
  11. */
  12. /** Normalize GIT_BRANCH: uat-20260202 (not origin/uat-20260202 or refs/heads/...) */
  13. def normalizeGitBranch(String raw) {
  14. def b = (raw ?: 'uat-20260202').trim()
  15. if (!b) {
  16. return 'uat-20260202'
  17. }
  18. b = b.replaceFirst('^refs/heads/', '')
  19. b = b.replaceFirst('^origin/', '')
  20. return b
  21. }
  22. /** HARBOR_PUSH_SCOPE: all-java-services | <repo>-only */
  23. def filterHarborPushScope(List allServices, String scope) {
  24. def s = (scope ?: 'all-java-services').trim()
  25. if (s == 'all-java-services') {
  26. return allServices
  27. }
  28. if (s.endsWith('-only')) {
  29. def repo = s.substring(0, s.length() - '-only'.length())
  30. def picked = allServices.findAll { it.repo == repo }
  31. if (picked.isEmpty()) {
  32. error("Unknown HARBOR_PUSH_SCOPE: ${scope}")
  33. }
  34. return picked
  35. }
  36. error("Unknown HARBOR_PUSH_SCOPE: ${scope}")
  37. }
  38. def pushOneHarborImage(def script, Map svc, String reg, String proj, String latestTag, String buildTag,
  39. String baseImage, String dockerfile, String workspace) {
  40. def jarName = "${svc.module}-1.0.0.jar"
  41. def imageLatest = "${reg}/${proj}/${svc.repo}:${latestTag}"
  42. def imageBuild = "${reg}/${proj}/${svc.repo}:${buildTag}"
  43. def withLibFlag = svc.withLib ? 'true' : 'false'
  44. script.sh """
  45. set -e
  46. export DOCKER_BUILDKIT=1
  47. test -f ${workspace}/${svc.module}/target/${jarName}
  48. cd ${workspace}/${svc.module}
  49. rm -rf .jenkins_docker_ctx && mkdir -p .jenkins_docker_ctx/lib
  50. cp -f target/${jarName} .jenkins_docker_ctx/${jarName}
  51. if [ "${withLibFlag}" = "true" ] && [ -d target/lib ]; then
  52. cp -rf target/lib/. .jenkins_docker_ctx/lib/
  53. else
  54. touch .jenkins_docker_ctx/lib/.keep
  55. fi
  56. cd .jenkins_docker_ctx
  57. if docker pull ${imageLatest} 2>/dev/null; then
  58. echo ">>> archive previous ${latestTag} -> ${buildTag}"
  59. docker tag ${imageLatest} ${imageBuild}
  60. docker push ${imageBuild}
  61. fi
  62. docker build -f ${workspace}/${dockerfile} \\
  63. --build-arg BASE_IMAGE=${baseImage} \\
  64. --build-arg JAR_FILE=${jarName} \\
  65. --build-arg SERVER_PORT=${svc.port} \\
  66. --build-arg WITH_LIB=${svc.withLib} \\
  67. -t ${imageLatest} .
  68. docker push ${imageLatest}
  69. echo ">>> pushed ${imageLatest} (archived prior latest as ${buildTag} if any)"
  70. docker rmi ${imageLatest} 2>/dev/null || true
  71. cd ${workspace}/${svc.module}
  72. rm -rf .jenkins_docker_ctx
  73. """
  74. }
  75. def deployOneUatService(def script, String moduleName, String dirName, String workspace) {
  76. def sourceJar = "${workspace}/${moduleName}/target/${moduleName}-1.0.0.jar"
  77. def sourceLib = "${workspace}/${moduleName}/target/lib"
  78. def targetDir = "/app_deploy_uat/${dirName}"
  79. script.sh """
  80. set -e
  81. echo ">>> Deploy module: ${moduleName}"
  82. if [ -f "${sourceJar}" ]; then
  83. mkdir -p "${targetDir}"
  84. if [ -d "${sourceLib}" ]; then
  85. rm -rf "${targetDir}/lib"
  86. cp -rf "${sourceLib}" "${targetDir}"
  87. fi
  88. cp -f "${sourceJar}" "${targetDir}/"
  89. if docker ps -a --format '{{.Names}}' | grep -wq "${dirName}"; then
  90. docker restart "${dirName}"
  91. echo ">>> [${dirName}] restarted"
  92. else
  93. echo ">>> [${dirName}] container missing, jar copied only"
  94. fi
  95. else
  96. echo ">>> [${dirName}] jar missing, skip"
  97. fi
  98. """
  99. }
  100. /** Delete oldest uat-build-* tags in Harbor, keep newest KEEP. Never deletes uat-latest or current build tag. */
  101. def pruneHarborUatTags(def script, String reg, String proj, List repoNames, int keepCount, String tagPrefix, String currentBuildTag, String latestTag) {
  102. if (repoNames == null || repoNames.isEmpty() || keepCount < 1) {
  103. return
  104. }
  105. def repos = repoNames.join(' ')
  106. // POSIX sh only (Jenkins sh step); no mapfile / process substitution
  107. script.sh """
  108. set -e
  109. REG='${reg}'
  110. PROJ='${proj}'
  111. KEEP=${keepCount}
  112. PREFIX='${tagPrefix}'
  113. CURRENT='${currentBuildTag}'
  114. LATEST='${latestTag}'
  115. if ! command -v jq >/dev/null 2>&1; then
  116. echo '>>> Harbor prune skipped: jq not installed on Jenkins agent'
  117. exit 0
  118. fi
  119. for repo in ${repos}; do
  120. enc_repo=\$(printf '%s' "\${repo}" | jq -sRr @uri)
  121. tags_file=\$(mktemp)
  122. curl -fsS -u "\${HARBOR_USER}:\${HARBOR_PASS}" \\
  123. "http://\${REG}/api/v2.0/projects/\${PROJ}/repositories/\${enc_repo}/artifacts?page_size=100" \\
  124. | jq -r '.[] | .tags[]? | .name' | grep "^\${PREFIX}" | sort -t- -k3 -n > "\${tags_file}" || true
  125. count=\$(wc -l < "\${tags_file}" | tr -d ' ')
  126. echo ">>> prune \${repo}: \${count} tag(s) matching \${PREFIX}*"
  127. if [ "\${count}" -le "\${KEEP}" ]; then
  128. rm -f "\${tags_file}"
  129. continue
  130. fi
  131. del_count=\$((count - KEEP))
  132. deleted=0
  133. while IFS= read -r t; do
  134. if [ -z "\${t}" ]; then
  135. continue
  136. fi
  137. if [ "\${t}" = "\${CURRENT}" ] || [ "\${t}" = "\${LATEST}" ]; then
  138. continue
  139. fi
  140. if [ "\${deleted}" -ge "\${del_count}" ]; then
  141. break
  142. fi
  143. echo ">>> DELETE Harbor tag \${repo}:\${t}"
  144. if ! curl -fsS -X DELETE -u "\${HARBOR_USER}:\${HARBOR_PASS}" \\
  145. "http://\${REG}/api/v2.0/projects/\${PROJ}/repositories/\${enc_repo}/artifacts/\${t}/tags/\${t}"; then
  146. echo ">>> WARN: delete failed \${repo}:\${t} (check robot delete permission)"
  147. fi
  148. deleted=\$((deleted + 1))
  149. done < "\${tags_file}"
  150. rm -f "\${tags_file}"
  151. done
  152. """
  153. }
  154. pipeline {
  155. agent any
  156. options {
  157. buildDiscarder(logRotator(numToKeepStr: '5'))
  158. disableConcurrentBuilds()
  159. timestamps()
  160. timeout(time: 90, unit: 'MINUTES')
  161. }
  162. parameters {
  163. string(
  164. name: 'GIT_BRANCH',
  165. defaultValue: 'uat-20260202',
  166. trim: true,
  167. description: 'Git branch, must match remote (e.g. uat-20260202)'
  168. )
  169. booleanParam(name: 'FORCE_UPDATE', defaultValue: false, description: 'mvn -U (routine builds leave unchecked for speed)')
  170. booleanParam(name: 'ALLOW_SNAPSHOTS', defaultValue: true, description: 'allow SNAPSHOT deps')
  171. booleanParam(
  172. name: 'PUSH_TO_HARBOR',
  173. defaultValue: true,
  174. description: 'After Maven: docker build + push to Harbor (tags uat-latest and uat-build-<N>). Uncheck for jar-only UAT deploy.'
  175. )
  176. choice(
  177. name: 'HARBOR_PUSH_SCOPE',
  178. choices: [
  179. 'all-java-services',
  180. 'gateway-only',
  181. 'store-only',
  182. 'second-only',
  183. 'store-platform-only',
  184. 'lawyer-only',
  185. 'job-only',
  186. 'dining-only',
  187. ],
  188. description: 'Only when PUSH_TO_HARBOR=true; default=all seven; *-only=one service'
  189. )
  190. string(name: 'HARBOR_REGISTRY', defaultValue: '39.105.153.68', trim: true)
  191. string(name: 'HARBOR_PROJECT', defaultValue: 'alien_cloud', trim: true)
  192. booleanParam(
  193. name: 'HARBOR_PRUNE_OLD_TAGS',
  194. defaultValue: true,
  195. description: 'After push: delete old uat-build-* tags in Harbor, keep last N per repo (never deletes uat-latest)'
  196. )
  197. string(name: 'HARBOR_KEEP_TAG_COUNT', defaultValue: '10', trim: true,
  198. description: 'How many uat-build-* tags to keep per repository')
  199. booleanParam(
  200. name: 'HARBOR_PUSH_PARALLEL',
  201. defaultValue: true,
  202. description: 'Parallel docker build/push per service (faster; needs enough CPU/disk on agent)'
  203. )
  204. }
  205. environment {
  206. MAVEN_HOME = tool '3.6.3'
  207. PATH = "${MAVEN_HOME}/bin:${env.PATH}"
  208. GIT_URL = 'http://8.152.195.41:3000/alien/alien_cloud'
  209. GIT_CREDENTIALS = 'zhanghaomimapingzheng'
  210. HARBOR_CREDENTIALS = 'harbor-robot-alien'
  211. UAT_HARBOR_LATEST_TAG = 'uat-latest'
  212. UAT_HARBOR_BUILD_TAG = "uat-build-${env.BUILD_NUMBER}"
  213. DOCKERFILE_JAVA = 'docs/jenkins/produ/docker/Dockerfile.java-service'
  214. MAVEN_LOCAL_REPO = '/var/jenkins_home/.m2/repository'
  215. }
  216. stages {
  217. stage('Checkout') {
  218. steps {
  219. script {
  220. def branch = normalizeGitBranch(params.GIT_BRANCH)
  221. if (!branch) {
  222. error('GIT_BRANCH is required')
  223. }
  224. env.GIT_BRANCH = branch
  225. echo ">>> Checkout branch: ${env.GIT_BRANCH} (use branch name only, e.g. uat-20260202)"
  226. git branch: "${env.GIT_BRANCH}",
  227. credentialsId: "${env.GIT_CREDENTIALS}",
  228. url: "${env.GIT_URL}"
  229. sh """
  230. set -e
  231. git fetch origin
  232. git reset --hard origin/${env.GIT_BRANCH}
  233. git log -1 --oneline
  234. """
  235. }
  236. }
  237. }
  238. stage('Prepare Maven Settings') {
  239. steps {
  240. script {
  241. writeFile file: 'settings.xml', text: """<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  242. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  243. xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
  244. <mirrors>
  245. <mirror>
  246. <id>aliyun-central</id>
  247. <mirrorOf>central</mirrorOf>
  248. <name>Aliyun Central</name>
  249. <url>https://maven.aliyun.com/repository/central</url>
  250. </mirror>
  251. </mirrors>
  252. <profiles>
  253. <profile>
  254. <id>repo-mix</id>
  255. <repositories>
  256. <repository>
  257. <id>aliyunmaven</id>
  258. <name>Aliyun Maven</name>
  259. <url>https://maven.aliyun.com/repository/public</url>
  260. <releases><enabled>true</enabled><updatePolicy>daily</updatePolicy></releases>
  261. <snapshots><enabled>false</enabled></snapshots>
  262. </repository>
  263. <repository>
  264. <id>central</id>
  265. <name>Maven Central</name>
  266. <url>https://repo.maven.apache.org/maven2</url>
  267. <releases><enabled>true</enabled><updatePolicy>daily</updatePolicy></releases>
  268. <snapshots><enabled>false</enabled></snapshots>
  269. </repository>
  270. <repository>
  271. <id>spring-milestones</id>
  272. <name>Spring Milestones</name>
  273. <url>https://repo.spring.io/milestone</url>
  274. <releases><enabled>true</enabled><updatePolicy>daily</updatePolicy></releases>
  275. <snapshots><enabled>false</enabled></snapshots>
  276. </repository>
  277. <repository>
  278. <id>spring-snapshots</id>
  279. <name>Spring Snapshots</name>
  280. <url>https://repo.spring.io/snapshot</url>
  281. <releases><enabled>false</enabled></releases>
  282. <snapshots><enabled>true</enabled><updatePolicy>daily</updatePolicy></snapshots>
  283. </repository>
  284. </repositories>
  285. <pluginRepositories>
  286. <pluginRepository>
  287. <id>aliyunmaven</id>
  288. <url>https://maven.aliyun.com/repository/public</url>
  289. <releases><enabled>true</enabled></releases>
  290. <snapshots><enabled>false</enabled></snapshots>
  291. </pluginRepository>
  292. <pluginRepository>
  293. <id>central</id>
  294. <url>https://repo.maven.apache.org/maven2</url>
  295. <releases><enabled>true</enabled></releases>
  296. <snapshots><enabled>false</enabled></snapshots>
  297. </pluginRepository>
  298. <pluginRepository>
  299. <id>spring-milestones</id>
  300. <url>https://repo.spring.io/milestone</url>
  301. <releases><enabled>true</enabled></releases>
  302. <snapshots><enabled>false</enabled></snapshots>
  303. </pluginRepository>
  304. </pluginRepositories>
  305. </profile>
  306. </profiles>
  307. <activeProfiles>
  308. <activeProfile>repo-mix</activeProfile>
  309. </activeProfiles>
  310. </settings>
  311. """
  312. }
  313. }
  314. }
  315. stage('Maven Build') {
  316. steps {
  317. script {
  318. def updateFlag = params.FORCE_UPDATE ? '-U' : ''
  319. retry(2) {
  320. sh """
  321. set -e
  322. mvn -version
  323. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy no_proxy NO_PROXY || true
  324. export MAVEN_OPTS="-Xms512m -Xmx2048m -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"
  325. mkdir -p ${MAVEN_LOCAL_REPO}
  326. mvn clean package -DskipTests -s settings.xml ${updateFlag} -e \\
  327. -T 1C -Dmaven.artifact.threads=8 \\
  328. -Dmaven.repo.local=${MAVEN_LOCAL_REPO}
  329. """
  330. }
  331. }
  332. }
  333. }
  334. stage('Push images to Harbor') {
  335. when {
  336. expression { return params.PUSH_TO_HARBOR == true }
  337. }
  338. steps {
  339. script {
  340. def reg = params.HARBOR_REGISTRY.trim()
  341. def proj = params.HARBOR_PROJECT.trim()
  342. def latestTag = env.UAT_HARBOR_LATEST_TAG
  343. def buildTag = env.UAT_HARBOR_BUILD_TAG
  344. def baseImage = "${reg}/${proj}/base/openjdk8-ffmpeg:v1"
  345. def dockerfile = env.DOCKERFILE_JAVA
  346. def allHarborServices = [
  347. [module: 'alien-gateway', repo: 'gateway', port: '8000', withLib: false],
  348. [module: 'alien-store', repo: 'store', port: '50014', withLib: true],
  349. [module: 'alien-second', repo: 'second', port: '50015', withLib: false],
  350. [module: 'alien-store-platform', repo: 'store-platform', port: '50016', withLib: false],
  351. [module: 'alien-lawyer', repo: 'lawyer', port: '50017', withLib: true],
  352. [module: 'alien-job', repo: 'job', port: '50108', withLib: false],
  353. [module: 'alien-dining', repo: 'dining', port: '50019', withLib: false],
  354. ]
  355. def harborServices = filterHarborPushScope(allHarborServices, params.HARBOR_PUSH_SCOPE)
  356. echo ">>> HARBOR_PUSH_SCOPE=${params.HARBOR_PUSH_SCOPE} repos=${harborServices*.repo.join(',')}"
  357. withCredentials([usernamePassword(
  358. credentialsId: env.HARBOR_CREDENTIALS,
  359. usernameVariable: 'HARBOR_USER',
  360. passwordVariable: 'HARBOR_PASS',
  361. )]) {
  362. sh """
  363. set -e
  364. echo "\${HARBOR_PASS}" | docker login ${reg} -u "\${HARBOR_USER}" --password-stdin
  365. echo ">>> docker disk before Harbor push:"
  366. df -h /var/lib/docker 2>/dev/null || df -h / || true
  367. docker system prune -f --filter until=48h 2>/dev/null || true
  368. """
  369. if (params.HARBOR_PUSH_PARALLEL) {
  370. def pushBranches = [:]
  371. harborServices.each { svc ->
  372. def s = svc
  373. pushBranches[s.repo] = {
  374. pushOneHarborImage(
  375. this, s, reg, proj, latestTag, buildTag,
  376. baseImage, dockerfile, env.WORKSPACE,
  377. )
  378. }
  379. }
  380. parallel pushBranches
  381. } else {
  382. harborServices.each { svc ->
  383. pushOneHarborImage(
  384. this, svc, reg, proj, latestTag, buildTag,
  385. baseImage, dockerfile, env.WORKSPACE,
  386. )
  387. }
  388. }
  389. if (params.HARBOR_PRUNE_OLD_TAGS == true) {
  390. def keepN = (params.HARBOR_KEEP_TAG_COUNT ?: '10').trim() as int
  391. catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
  392. pruneHarborUatTags(
  393. this, reg, proj, harborServices*.repo,
  394. keepN, 'uat-build-', buildTag, latestTag,
  395. )
  396. }
  397. }
  398. }
  399. echo ">>> Harbor latest: ${env.UAT_HARBOR_LATEST_TAG}; archived tag this run: ${env.UAT_HARBOR_BUILD_TAG}"
  400. echo ">>> Prod promote: SOURCE_TAG=${env.UAT_HARBOR_LATEST_TAG}"
  401. }
  402. }
  403. }
  404. stage('Deploy Services') {
  405. steps {
  406. script {
  407. def services = [
  408. 'alien-gateway:gateway-uat',
  409. 'alien-job:job-uat',
  410. 'alien-lawyer:lawyer-uat',
  411. 'alien-second:second-uat',
  412. 'alien-store:store-uat',
  413. 'alien-dining:dining-uat',
  414. 'alien-store-platform:store-platform-uat',
  415. ]
  416. def deployBranches = [:]
  417. services.each { item ->
  418. def parts = item.split(':')
  419. def moduleName = parts[0]
  420. def dirName = parts[1]
  421. deployBranches[dirName] = {
  422. deployOneUatService(this, moduleName, dirName, env.WORKSPACE)
  423. }
  424. }
  425. parallel deployBranches
  426. }
  427. }
  428. }
  429. }
  430. post {
  431. always {
  432. sh 'rm -f settings.xml || true'
  433. script {
  434. if (!params.PUSH_TO_HARBOR) {
  435. echo '>>> Harbor push SKIPPED: PUSH_TO_HARBOR is false. On "Build with Parameters" check PUSH_TO_HARBOR.'
  436. }
  437. }
  438. }
  439. success {
  440. script {
  441. if (params.PUSH_TO_HARBOR) {
  442. echo ">>> Harbor latest: ${env.UAT_HARBOR_LATEST_TAG}"
  443. echo ">>> Prod promote: SOURCE_TAG=${env.UAT_HARBOR_LATEST_TAG}"
  444. }
  445. }
  446. }
  447. }
  448. }