Jenkinsfile 20 KB

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