Jenkinsfile 20 KB

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