签入版本

This commit is contained in:
gitadmin 2025-09-23 21:22:17 +08:00
parent bdb883149e
commit 959b9325ad
6 changed files with 2266 additions and 0 deletions

View File

@ -0,0 +1,149 @@
package com.nexus
import com.nexus.stages.BuildService
import com.nexus.stages.DeployService
/**
* - CI/CD流水线核心协调器
* CI/CD阶段的业务逻辑Jenkins stage
* 线
*
*
* -
* -
* - 线
* -
* -
*
*
* 1.
* 2.
* 3.
* 4.
*
* @see Serializable Jenkins流水线的暂停和恢复
*/
class DeploymentService implements Serializable {
/**
* Jenkins pipeline脚本对象
* 访Jenkins DSL方法shechoerror等
* : Object (Jenkins pipeline的script对象)
*/
def script
/**
*
*
* : Map<String, Object>
*/
def envConfig
// ==========================================================================
//
// ==========================================================================
/**
*
* Maven项目的编译和打包操作
* : BuildService
*/
def buildService
/**
*
*
* : DeployService
*/
def deployService
/**
* -
*
*
* @param script Jenkins pipeline脚本对象
* - 访Jenkins DSL方法
* - Pipeline中通过`this`
*
* @param envConfig
* - Map<String, Object>
* - Map [:]
* -
* - [
* servers: [[serverIP: "192.168.1.1", serverPort: 22]],
* envVars: [JAVA_OPTS: "-Xms1g -Xmx1g"],
* deploymentStrategy: "rolling"
* ]
*/
DeploymentService(script, envConfig = [:]) {
//
this.script = script
this.envConfig = envConfig
//
//
this.buildService = new BuildService(script, envConfig)
this.deployService = new DeployService(script, envConfig)
script.echo "🔧 DeploymentService 初始化完成"
}
/**
*
* BuildService处理Maven项目的编译和打包
* CI/CD流水线的第一个阶段
*
* @param params Map
* - MAVEN_SET: String - Maven设置文件ID
* - PROFILES: String - Maven构建环境profiles
* - jarFilePath: String - JAR文件输出路径
* - jarFile: String - JAR文件名
* - skipTests: Boolean - true
* - goals: String - Maven执行目标"clean package"
* - pomFilePath: String - POM文件路径pom.xml
*
* @throws Exception Maven构建失败时抛出异常线
*
* @example 使
* def params = [
* MAVEN_SET: "nexus-maven-dev",
* PROFILES: "dev",
* jarFilePath: "target",
* jarFile: "app.jar"
* ]
* deploymentService.executeBuildStage(params)
*/
def executeBuildStage(params) {
// ...
buildService.executeBuildStage(params)
}
/**
*
* DeployService处理应用部署到目标服务器
* CI/CD流水线的第三个阶段
*
* @param params Map
* - servers: List -
* - deployServer: String -
* - projectName: String -
* - PROFILES: String -
*
* - deployScript: String -
* - deployPath: String -
* - envVars: Map -
* - deploymentStrategy: String -
*
* @throws Exception
*
* @note
* - deployServer = "servers[0]"
* - deployServer = "servers[0,1,2]"
* - deployServer = "auto"
*/
def executeDeployStage(params) {
// 🚀 ...
deployService.executeDeployStage(params)
}
}

View File

@ -0,0 +1,649 @@
package com.nexus
import com.utils.CommonUtils
import com.constants.ConfigConstants
/**
* JDK API - Nexus私库上传支持
*
* Nexus发布配置
*
*
* 1.
* 2.
* 3. Jenkins流水线参数
* 4.
* 5. Nexus私库上传配置解析
*
* @version 2.1.0
* @since 2025-09-09
*/
class ResolverService implements Serializable {
// Jenkins流水线脚本对象Jenkins相关操作
def script
// YAML数据
def config
//
def orgName
//
def envConfig
//
def jobConfigFile
/**
*
*
*
* @param script Jenkins流水线脚本对象echoerror等方法
* @param orgName
*/
ResolverService(script, orgName) {
this.script = script
this.orgName = orgName
this.config = [:]
this.envConfig = [:]
}
/**
*
*
*
* @throws Exception
*/
void loadConfigurations() {
script.echo "🚀 开始加载配置文件..."
// .env.yml
loadEnvConfig()
//
loadJobConfig()
script.echo "✅ 所有配置文件加载完成"
}
/**
*
* .jenkins/.env.yml读取环境配置
*
* @return
* @throws Exception
*/
def loadEnvConfig() {
try {
//
def envFilePath = '.jenkins/.env.yml'
script.echo "📁 环境配置文件路径: ${envFilePath}"
if (script.fileExists(envFilePath)) {
// YAML格式的环境配置文件
envConfig = script.readYaml(file: envFilePath)
//
jobConfigFile = ".pipeline-files/config-file/" + envConfig.jobConfigFile
script.echo "✅ 成功加载环境配置文件"
//
if (!envConfig.isEmpty()) {
script.echo "📋 环境配置内容:"
envConfig.each { key, value ->
script.echo " ${key}: ${value}"
}
}
} else {
script.echo "⚠️ 警告: 未找到环境配置文件 .env.yml使用默认配置"
}
} catch (Exception e) {
script.echo "⚠️ 警告: .env.yml 文件无效,使用默认配置: ${e.message}"
//
}
return this
}
/**
*
* commonbranchConfigserviceConfig等部分
*
* @return
* @throws Exception
*/
def loadJobConfig() {
try {
//
if (!script.fileExists(jobConfigFile)) {
script.error("❌ 错误: 配置文件不存在: ${jobConfigFile},请检查文件路径或创建配置文件")
}
// YAML格式的主配置文件
this.config = script.readYaml(file: jobConfigFile)
script.echo "✅ 成功加载主配置文件: ${jobConfigFile}"
//
printConfigSummary()
} catch (Exception e) {
script.error("❌ 错误: 加载配置文件失败: ${jobConfigFile}. 错误详情: ${e.message}")
}
return this
}
/**
*
* 便
*/
def printConfigSummary() {
script.echo "=" * 70
script.echo "📊 主配置文件详细内容"
script.echo "=" * 70
if (!this.config) {
script.echo "⚠️ 配置文件内容为空"
return
}
//
if (this.config.common) {
script.echo "🌐 通用配置:"
script.echo "-" * 50
// Nexus配置
if (this.config.common.nexus) {
script.echo "🔗 Nexus仓库配置:"
this.config.common.nexus.each { nexusName, nexusConfig ->
script.echo " ${nexusName}: ${nexusConfig.url}"
script.echo " 类型: ${nexusConfig.type}, 策略: ${nexusConfig.policy}"
}
}
//
if (this.config.common.buildStrategy) {
script.echo "⚡ 构建策略:"
script.echo " 重试次数: ${this.config.common.buildStrategy.retryCount}"
script.echo " 超时时间: ${this.config.common.buildStrategy.timeoutMinutes}分钟"
script.echo " 启用缓存: ${this.config.common.buildStrategy.enableCaching}"
}
//
if (this.config.common.publishStrategy) {
script.echo "🚀 发布策略:"
script.echo " 版本策略: ${this.config.common.publishStrategy.versionPolicy}"
script.echo " 自动发布: ${this.config.common.publishStrategy.autoPublish}"
script.echo " 签名构件: ${this.config.common.publishStrategy.signArtifacts}"
}
script.echo ""
}
//
if (this.config.common?.profiles) {
script.echo "🏭 环境配置 (共 ${this.config.common.profiles.size()} 个环境):"
script.echo "-" * 50
this.config.common.profiles.each { envName, envConfig ->
script.echo " ${envName.toUpperCase()} 环境:"
script.echo " Nexus配置: ${envConfig.nexus ?: 'default'}"
script.echo " 版本后缀: ${envConfig.versionSuffix ?: '无'}"
script.echo " 自动部署: ${envConfig.autoDeploy}"
script.echo " 仓库策略: ${envConfig.repositoryPolicy ?: 'releases'}"
script.echo ""
}
}
//
if (this.config.branchConfig) {
script.echo "🌿 分支构建配置 (共 ${this.config.branchConfig.size()} 个分支):"
script.echo "-" * 50
this.config.branchConfig.each { branchName, branchConfig ->
script.echo " ${branchName} 分支:"
script.echo " Jenkins代理: ${branchConfig.jenkinsAgent ?: '未设置'}"
script.echo " Maven配置集: ${branchConfig.maven?.mavenSet ?: '未设置'}"
script.echo " 跳过测试: ${branchConfig.maven?.skipTests ?: 'false'}"
script.echo " Maven目标: ${branchConfig.maven?.goals ?: '未设置'}"
script.echo " 部署操作: ${branchConfig.maven?.deploy ?: 'false'}"
}
}
//
if (this.config.serviceConfig) {
script.echo "🔧 服务配置 (共 ${this.config.serviceConfig.size()} 个服务):"
script.echo "-" * 50
this.config.serviceConfig.each { serviceName, serviceConfig ->
script.echo " ${serviceName} 服务:"
script.echo " 项目名称: ${serviceConfig.projectName ?: '未设置'}"
script.echo " 项目描述: ${serviceConfig.description ?: '未设置'}"
script.echo " 编程语言: ${serviceConfig.programLang ?: '未设置'}"
script.echo " 语言版本: ${serviceConfig.programLangVersion ?: '未设置'}"
script.echo " POM路径: ${serviceConfig.pomFilePath ?: '未设置'}"
script.echo " 服务路径: ${serviceConfig.servicePath ?: '未设置'}"
}
}
script.echo "=" * 70
}
/**
*
* Jenkins作业的分支名称查找对应的分支配置
*
* @return Map类型
* @throws Exception
*/
def getBranchConfig() {
// Jenkins作业的分支名称
def branchName = script.env.BRANCH_NAME
if (!branchName) {
script.error("❌ 错误: 无法获取分支名称env.BRANCH_NAME 为空。请检查流水线配置")
}
script.echo "🌿 正在查找分支配置: ${branchName}"
//
if (!config.branchConfig || config.branchConfig.isEmpty()) {
script.error("❌ 错误: 分支配置列表为空或未定义。请检查配置文件结构")
}
//
def branchConfig = config.branchConfig[branchName]
if (branchConfig) {
script.echo "✅ 成功匹配分支配置:"
script.echo " - Jenkins代理: ${branchConfig.jenkinsAgent ?: '未设置'}"
script.echo " - Maven配置集: ${branchConfig.maven?.mavenSet ?: '未设置'}"
script.echo " - Maven目标: ${branchConfig.maven?.goals ?: '未设置'}"
script.echo " - 跳过测试: ${branchConfig.maven?.skipTests ?: 'false'}"
script.echo " - 部署操作: ${branchConfig.maven?.deploy ?: 'false'}"
} else {
//
def availableBranches = config.branchConfig.keySet().join(', ')
script.error("❌ 错误: 找不到分支 '${branchName}' 的配置。可用分支: ${availableBranches}")
}
return branchConfig
}
/**
*
* serviceConfig中查找对应的服务配置
*
* @param serviceName serviceConfig的键匹配
* @return Map类型
* @throws Exception
*/
def getServiceConfig(serviceName) {
if (!serviceName) {
script.error("❌ 错误: 服务名称参数不能为空")
}
script.echo "🔧 正在查找服务配置: ${serviceName}"
//
if (!config.serviceConfig || config.serviceConfig.isEmpty()) {
script.error("❌ 错误: 服务配置列表为空或未定义,请检查配置文件结构")
}
//
def serviceConfig = config.serviceConfig[serviceName]
if (serviceConfig) {
script.echo "✅ 成功找到服务配置: ${serviceName}"
script.echo " - 项目名称: ${serviceConfig.projectName ?: '未设置'}"
script.echo " - 项目描述: ${serviceConfig.description ?: '未设置'}"
script.echo " - 编程语言: ${serviceConfig.programLang ?: '未设置'}"
script.echo " - 语言版本: ${serviceConfig.programLangVersion ?: '未设置'}"
script.echo " - POM路径: ${serviceConfig.pomFilePath ?: '未设置'}"
script.echo " - 服务路径: ${serviceConfig.servicePath ?: '未设置'}"
} else {
//
def availableServices = config.serviceConfig.keySet().join(', ')
script.error("❌ 错误: 找不到服务 '${serviceName}' 的配置。可用服务: ${availableServices}")
}
return serviceConfig
}
/**
*
* 线
* Nexus发布配置的支持
*
* @return
*/
def setupParameters() {
script.echo "⚙️ 开始设置管道参数..."
//
def branchConfig = getBranchConfig()
// Jenkins作业名称中提取服务名称
// : "组织名/服务名" "服务名"
def serviceName = script.env.JOB_NAME?.tokenize('/')?.get(0)
script.echo "📦 服务名称: ${serviceName}"
//
def serviceConfig = getServiceConfig(serviceName)
//
def profiles = getBranchProfiles(branchConfig)
script.echo "🌍 环境配置: ${profiles}"
//
def params = [
//
jenkinsAgent : branchConfig.jenkinsAgent,
MAVEN_SET : branchConfig.maven?.mavenSet,
skipTests : branchConfig.maven?.skipTests,
goals : branchConfig.maven?.goals,
mavenOptions : branchConfig.maven?.options,
//
projectName : serviceConfig.projectName ?: serviceConfig.containerName,
description : serviceConfig.description,
pomFilePath : serviceConfig.pomFilePath,
servicePath : serviceConfig.servicePath,
//
PROFILES : profiles.default_profile,
availableProfiles : profiles.available_profiles,
// Git配置
gitUrl : config.common?.git?.url,
gitCredentialsId : config.common?.git?.credentialsId,
gitBranch : script.env.BRANCH_NAME,
//
dingTalkCredentialsId: config.common?.dingtalk?.credentialsId,
//
envConfig : this.envConfig,
orgName : this.orgName,
branchConfig : branchConfig,
serviceConfig : serviceConfig
]
//
getEnvironmentConfig(params)
script.echo "基础参数:${params}"
// Jenkins参数线
setupJenkinsParameters(profiles.available_profiles as List<String>)
script.echo "✅ 管道参数设置完成"
//
return params
}
/**
*
* Nexus配置
*
* @param params
* @return Map
*/
def getEnvironmentConfig(params) {
try {
// 使"dev"
def envName = params.PROFILES ?: "dev"
def envKey = envName.toLowerCase()
script.echo "🔍 开始获取 ${envKey} 环境的全部配置参数..."
// ==========================================================================
// Nexus配置
// ==========================================================================
if (config.common?.nexus) {
params.nexusConfigs = config.common.nexus
script.echo "🔗 Nexus配置已加载共 ${config.common.nexus.size()} 个仓库"
// 使Nexus配置
def envConfig = config.common?.profiles?."${envKey}"
def nexusConfigName = envConfig?.nexus ?: "default"
params.currentNexusConfig = config.common.nexus[nexusConfigName]
script.echo "📦 当前环境使用Nexus配置: ${nexusConfigName}"
script.echo " - URL: ${params.currentNexusConfig?.url}"
script.echo " - 凭证ID: ${params.currentNexusConfig?.credentialsId}"
script.echo " - 策略: ${params.currentNexusConfig?.policy}"
}
// ==========================================================================
//
// ==========================================================================
if (config.common?.notification) {
params.notification = config.common.notification
script.echo "📧 通知配置已加载"
}
// ==========================================================================
//
// ==========================================================================
if (config.common?.buildStrategy) {
params.buildStrategy = config.common.buildStrategy
script.echo "⚡ 构建策略:"
script.echo " - 重试次数: ${params.buildStrategy.retryCount}"
script.echo " - 超时时间: ${params.buildStrategy.timeoutMinutes}分钟"
script.echo " - 启用缓存: ${params.buildStrategy.enableCaching}"
}
// ==========================================================================
//
// ==========================================================================
if (config.common?.publishStrategy) {
params.publishStrategy = config.common.publishStrategy
script.echo "🚀 发布策略:"
script.echo " - 版本策略: ${params.publishStrategy.versionPolicy}"
script.echo " - 自动发布: ${params.publishStrategy.autoPublish}"
script.echo " - 签名构件: ${params.publishStrategy.signArtifacts}"
}
script.echo "环境变量:${config.common?.profiles}"
//
def envConfig = config.common?.profiles?."${envKey}"
script.echo "环境变量:${envConfig}"
if (!envConfig) {
def availableProfiles = config?.common?.profiles?.keySet() ?: []
throw new Exception("未找到 ${envKey} 环境的配置,可用环境: ${availableProfiles.join(', ')}")
}
script.echo "✅ 找到 ${envKey} 环境配置,开始提取参数..."
// ==========================================================================
//
// ==========================================================================
if (envConfig?.versionSuffix) {
params.versionSuffix = envConfig.versionSuffix
script.echo "🏷️ 版本后缀: ${envConfig.versionSuffix}"
}
if (envConfig?.autoDeploy != null) {
params.autoDeploy = envConfig.autoDeploy
script.echo "🚀 自动部署: ${envConfig.autoDeploy}"
}
if (envConfig?.repositoryPolicy) {
params.repositoryPolicy = envConfig.repositoryPolicy
script.echo "📦 仓库策略: ${envConfig.repositoryPolicy}"
}
script.echo "✅ ${envKey} 环境全部参数获取完成"
return params
} catch (Exception e) {
script.echo "❌ 获取环境配置失败: ${e.message}"
throw e
}
}
/**
* Nexus配置信息
* Nexus仓库配置Nexus配置
*
* @param envName
* @param nexusConfigName Nexus配置名称使
* @return Nexus配置对象
*/
def getNexusConfig(String envName = null, String nexusConfigName = null) {
try {
def envKey = (envName ?: params.PROFILES ?: "dev").toLowerCase()
def configName = nexusConfigName ?: config.common?.profiles?."${envKey}"?.nexus ?: "default"
def nexusConfig = config.common?.nexus?."${configName}"
if (!nexusConfig) {
script.echo "⚠️ 警告: 未找到Nexus配置 '${configName}',使用默认配置"
nexusConfig = config.common?.nexus?.default ?: [:]
}
script.echo "🔗 Nexus配置 [${configName}] for ${envKey} 环境:"
script.echo " - URL: ${nexusConfig.url}"
script.echo " - Snapshots URL: ${nexusConfig.snapshotsUrl}"
script.echo " - 凭证ID: ${nexusConfig.credentialsId}"
return nexusConfig
} catch (Exception e) {
script.echo "❌ 获取Nexus配置失败: ${e.message}"
return [:]
}
}
/**
*
* @return
*/
def getBuildStrategy() {
return config.common?.buildStrategy ?: [:]
}
/**
*
* @return
*/
def getPublishStrategy() {
return config.common?.publishStrategy ?: [:]
}
/**
*
* @return
*/
def getNotificationConfig() {
return config.common?.notification ?: [:]
}
/**
* Jenkins
* 线
*
*
* @param availableProfiles
* - : List<String> ['dev', 'test', 'prod']
* - :
* - :
*
* @note 线
* @note 线
*
* @example :
* - PROFILES: dev/test/prod
* - SERVERS:
*/
private void setupJenkinsParameters(List<String> availableProfiles) {
//
if (!availableProfiles || availableProfiles.isEmpty()) {
script.echo "⚠️ 可用环境配置列表为空,跳过参数设置"
return
}
// 线
def branchName = script.env.BRANCH_NAME ?: ''
// 线: feature/xxx
boolean isMultibranchPipeline = branchName.contains('/')
if (isMultibranchPipeline) {
script.echo "🔧 检测到多分支流水线,跳过参数设置(分支: ${branchName}"
script.echo "💡 多分支流水线通常根据分支名称自动确定目标环境"
return
}
script.echo "🔧 标准流水线作业,设置部署环境参数"
script.echo "📋 可用环境选项: ${availableProfiles.join(', ')}"
try {
// ==========================================================================
//
// ==========================================================================
def profileParameter = script.choice(
choices: availableProfiles.join('\n'), //
description: '请选择要部署的目标环境', // Jenkins界面上
name: 'PROFILES' // params.PROFILES访问
)
// ==========================================================================
// Jenkins作业参数
// ==========================================================================
script.properties([
script.parameters([
profileParameter, //
])
])
script.echo "✅ 成功设置部署参数:"
script.echo " - PROFILES: 环境选择(${availableProfiles.size()} 个选项)"
} catch (Exception e) {
script.echo "⚠️ 设置 Jenkins 参数失败: ${e.message}"
script.echo "💡 这可能是因为没有权限修改作业配置,或者参数格式不正确"
//
}
}
/**
*
* @param branchConfig
* @return Map
*/
private def getBranchProfiles(branchConfig) {
//
def branchName = script.env.BRANCH_NAME ?: ''
// 1.
def availableProfiles = ConfigConstants.BRANCH_PROFILES[branchName]
// 2.
if (!availableProfiles) {
availableProfiles = (branchName == 'master') ?
envConfig.masterProfiles : // master分支使用特殊配置
envConfig.Profiles // 使
}
// availableProfiles不为nullnull则转为空列表
availableProfiles = availableProfiles ?: []
// 3.
def defaultProfile = ConfigConstants.DEFAULT_PROFILES[branchName]
// 4.
if (!defaultProfile) {
defaultProfile = availableProfiles.find { it } ? //
availableProfiles[0] : //
null // null
}
return [
available_profiles: availableProfiles,
default_profile : defaultProfile
]
}
}

View File

@ -0,0 +1,396 @@
package com.nexus.stages
/**
* - Maven项目的编译和打包Nexus私库发布
*
*
* - Maven项目的清理
* -
* -
* -
* - Nexus私库发布和依赖管理
*
*
* - Maven构建相关的逻辑
* - 线
* -
* - Map接收所有配置信息
*
* @see Serializable Jenkins流水线的暂停和恢复
*/
class BuildService implements Serializable {
/**
* Jenkins pipeline脚本对象
* 访Jenkins DSL方法shechoerror等
* : Object (Jenkins pipeline的script对象)
*/
def script
/**
*
*
* : Map<String, Object>
*/
def envConfig
/**
* -
*
* @param script Jenkins pipeline脚本对象
* - 访Jenkins DSL方法
* - Pipeline中通过`this`
*
* @param envConfig
* - Map<String, Object>
* - Map [:]
* -
*/
BuildService(script, envConfig = [:]) {
this.script = script
this.envConfig = envConfig
script.echo "🔧 BuildService 初始化完成"
}
/**
* - Nexus私库发布
* Maven项目的完整构建生命周期
*
*
* 1.
* 2.
* 3. Maven构建命令Nexus部署
* 4.
* 5.
*
* @param params Map
* - MAVEN_SET: String - Maven设置文件IDJenkins Config File ID
* - PROFILES: String - Maven构建环境profilesdev, test, prod
*
* - jarFilePath: String - JAR文件输出路径target
* - jarFile: String - JAR文件名
* - skipTests: Boolean - true
* - goals: String - Maven执行目标
* - pomFilePath: String - POM文件路径pom.xml
* - orgName: String - JDK服务验证
* - availableProfiles: List - profile列表
* - branchConfig: Map -
* - currentNexusConfig: Map - Nexus配置
* - repositoryPolicy: String -
* - publishStrategy: Map -
*
* @throws Exception Maven构建失败时抛出异常线
*
*
* @example 使
* def buildParams = [
* MAVEN_SET: "nexus-maven-dev",
* PROFILES: "dev",
* jarFilePath: "target",
* jarFile: "xiaomayi-common.jar",
* skipTests: true,
* orgName: "xiaomayi",
* availableProfiles: ["dev", "test", "prod"],
* branchConfig: [maven: [deploy: true]],
* currentNexusConfig: [url: "http://nexus/repository/maven-snapshots/"],
* repositoryPolicy: "snapshots"
* ]
* buildService.executeBuildStage(buildParams)
*/
def executeBuildStage(params) {
try {
//
script.echo "🏗️ 开始构建阶段..."
printBuildConfiguration(params)
// profile的有效性
validateProfile(params)
// Maven构建命令
executeMavenBuild(params)
//
generateBuildReport(params)
} catch (Exception e) {
//
handleBuildFailure(e, params)
// 线
throw e
}
}
/**
*
* 便
*
* @param params Map
*/
private def printBuildConfiguration(params) {
script.echo "📋 构建配置详情:"
script.echo " 🔧 Maven配置: ${params.MAVEN_SET}"
script.echo " 🌍 构建Profile: ${params.PROFILES}"
script.echo " 📦 输出路径: ${params.jarFilePath ?: 'target'}"
script.echo " 🏷️ JAR文件: ${params.jarFile ?: '未指定'}"
script.echo " ⚡ 跳过测试: ${params.skipTests ?: true}"
script.echo " 📄 POM文件: ${params.pomFilePath ?: 'pom.xml'}"
// Nexus相关配置
if (params.currentNexusConfig) {
script.echo " 🔗 Nexus仓库: ${params.currentNexusConfig.url}"
script.echo " 🎯 仓库策略: ${params.repositoryPolicy ?: 'releases'}"
}
//
if (params.publishStrategy) {
script.echo " 🚀 自动发布: ${params.publishStrategy.autoPublish ?: 'false'}"
script.echo " 🔏 GPG签名: ${params.publishStrategy.signArtifacts ?: 'false'}"
}
}
/**
* Maven构建命令
* 使Config File Provider动态加载Maven配置
*
* @param params Map
*/
private def executeMavenBuild(params) {
script.echo "🔨 执行Maven构建命令..."
// 使Config File Provider加载Maven settings.xml
script.configFileProvider([script.configFile(fileId: params.MAVEN_SET, variable: 'MAVEN_SETTINGS_XML')]) {
// Maven命令参数
def mavenGoals = buildMavenGoals(params)
def mavenOptions = buildMavenOptions(params)
script.sh """
# ================================================
# Maven构建脚本
# : ${params.PROFILES}
# : \$(date)
# ================================================
echo "🚀 开始执行Maven构建..."
# Maven版本信息
/usr/local/maven/bin/mvn --version
# POM文件
echo "📁 工作目录: \$(pwd)"
echo "📄 POM文件: ${params.pomFilePath ?: 'pom.xml'}"
echo "🔧 Settings文件: \${MAVEN_SETTINGS_XML}"
# Maven构建命令
echo "🔨 执行命令: /usr/local/maven/bin/mvn --settings \${MAVEN_SETTINGS_XML} ${mavenGoals} ${mavenOptions}"
/usr/local/maven/bin/mvn \\
--settings \${MAVEN_SETTINGS_XML} \\
-f ${params.pomFilePath ?: 'pom.xml'} \\
${mavenGoals} ${mavenOptions}
#
BUILD_RESULT=\$?
if [ \$BUILD_RESULT -eq 0 ]; then
echo "✅ Maven构建成功完成!"
else
echo "❌ Maven构建失败退出码: \$BUILD_RESULT"
exit \$BUILD_RESULT
fi
"""
}
}
/**
* Maven执行目标
* Maven goals
*
* @param params Map
* @return Maven goals字符串
*/
private def buildMavenGoals(params) {
def goals = []
//
goals.add("dependency:purge-local-repository -Dinclude=com.xiaomayi")
//
goals.add("clean")
//
if (params.branchConfig?.maven?.deploy) {
goals.add("deploy")
script.echo " 🚀 启用部署到Nexus仓库"
} else {
goals.add("install")
script.echo " 💾 仅安装到本地仓库"
}
goals.add("package")
return goals.join(" ")
}
/**
* Maven选项参数
* Maven命令行选项
*
* @param params Map
* @return Maven选项字符串
*/
private def buildMavenOptions(params) {
def options = []
//
options.add("-U")
//
if (params.skipTests ?: true) {
options.add("-Dmaven.test.skip=true")
script.echo " ⚡ 跳过单元测试"
} else {
script.echo " ✅ 执行单元测试"
}
// Maven profile
if (params.PROFILES) {
options.add("-P${params.PROFILES}")
}
//
if (params.branchConfig?.maven?.options) {
options.add(params.branchConfig.maven.options)
}
return options.join(" ")
}
/**
*
*
*
* @param params Map
*/
private def generateBuildReport(params) {
script.echo "📊 构建阶段完成报告:"
script.echo " - ✅ 依赖清理完成com.xiaomayi"
script.echo " - ✅ 代码编译完成"
script.echo " - ${params.skipTests ? '⚡ 单元测试跳过' : '✅ 单元测试通过'}"
script.echo " - ✅ 打包完成"
//
def deployStatus = params.branchConfig?.maven?.deploy ? "已部署到Nexus" : "未部署"
script.echo " - 📦 部署状态: ${deployStatus}"
if (params.branchConfig?.maven?.deploy) {
script.echo " 🎯 目标仓库: ${params.currentNexusConfig?.url ?: '默认仓库'}"
script.echo " 📋 仓库策略: ${params.repositoryPolicy ?: 'releases'}"
}
// GPG签名状态
if (params.publishStrategy?.signArtifacts) {
script.echo " - 🔏 GPG签名: 已启用(密钥: ${params.publishStrategy.gpgKeyId ?: '默认密钥'}"
}
//
script.echo "🎉 构建产物已生成到: ${params.jarFilePath ?: 'target'} 目录"
// JAR文件
try {
def jarFiles = script.findFiles(glob: "${params.jarFilePath ?: 'target'}/*.jar")
if (jarFiles) {
script.echo "📦 生成的构件:"
jarFiles.each { file ->
script.echo " - ${file.name} (${file.length()} bytes)"
}
}
} catch (Exception e) {
script.echo " 无法列出构件文件: ${e.message}"
}
}
/**
*
*
*
* @param e
* @param params Map
*/
private def handleBuildFailure(Exception e, params) {
script.echo "❌ 构建阶段失败: ${e.message}"
script.echo "💡 建议检查:"
script.echo " - Maven settings.xml 配置是否正确"
script.echo " - Nexus仓库连接是否正常地址: ${params.currentNexusConfig?.url ?: '未配置'}"
script.echo " - 网络连接是否正常(依赖下载)"
script.echo " - 代码编译是否有语法错误"
script.echo " - 单元测试是否通过"
script.echo " - 版本号冲突或依赖问题"
//
script.echo "🔍 调试信息:"
script.echo " - 环境: ${params.PROFILES}"
script.echo " - Maven配置: ${params.MAVEN_SET}"
script.echo " - POM文件: ${params.pomFilePath ?: 'pom.xml'}"
}
/**
* profile有效性
*
*
*
* -
* -
* -
*
* @param params Map
* - PROFILES: String - profile名称
* - availableProfiles: List<String> - profile列表
* - orgName: String -
*
* @throws IllegalArgumentException
* @throws Exception
*/
private def validateProfile(params) {
script.echo "🔍 开始验证环境profile有效性..."
//
if (!params.PROFILES) {
def errorMsg = "缺少必要的PROFILES参数请指定要部署的环境"
script.echo "❌ ${errorMsg}"
throw new IllegalArgumentException(errorMsg)
}
if (!params.availableProfiles || params.availableProfiles.isEmpty()) {
def errorMsg = "缺少可用的环境profile列表请检查配置文件中环境配置"
script.echo "❌ ${errorMsg}"
throw new IllegalArgumentException(errorMsg)
}
if (!params.orgName) {
script.echo "⚠️ 缺少组织名称参数orgName使用默认标识"
}
//
try {
def selectedProfile = params.PROFILES.trim()
def availableProfiles = params.availableProfiles.collect { it.toString().trim() }
script.echo "📋 验证详情:"
script.echo " 🎯 选择的环境: ${selectedProfile}"
script.echo " 📊 可用环境: ${availableProfiles.join(', ')}"
if (!availableProfiles.contains(selectedProfile)) {
def errorMsg = "无效的部署环境: '${selectedProfile}'。可用环境: ${availableProfiles.join(', ')}"
script.error("环境验证失败: ${errorMsg}")
}
script.echo "✅ 环境profile验证通过: ${selectedProfile}"
} catch (Exception e) {
script.echo "❌ 环境profile验证过程中发生错误: ${e.message}"
script.echo "📋 可用环境列表: ${params.availableProfiles.join(', ')}"
throw e
}
}
}

View File

@ -0,0 +1,375 @@
package com.nexus.stages
/**
* - Maven项目的编译
*
*
*
* - Maven项目的清理
* - Maven仓库
* -
* -
* -
*
*
* -
* - 线
* -
* - Map接收所有配置信息
*
* @see Serializable Jenkins流水线的暂停和恢复
*/
class BuildService implements Serializable {
/**
* Jenkins pipeline脚本对象
*/
def script
/**
*
*/
def envConfig
/**
* -
*
* @param script Jenkins pipeline脚本对象
* @param envConfig
*/
BuildService(script, envConfig = [:]) {
this.script = script
this.envConfig = envConfig
script.echo "🔧 BuildService 初始化完成(纯构建版本)"
}
/**
*
* Maven项目的编译
*
*
* 1.
* 2.
* 3. Maven install步骤
* 4.
* 5.
*
* @param params Map
* @return
* @throws Exception Maven构建失败时抛出异常线
*/
def executeBuildStage(params) {
def buildResult = [:]
try {
//
script.echo "🏗️ 开始构建阶段..."
printBuildConfiguration(params)
// profile的有效性
validateProfile(params)
// Maven install
buildResult = executeMavenInstall(params)
//
generateBuildReport(params, buildResult)
return buildResult
} catch (Exception e) {
//
handleBuildFailure(e, params)
// 线
throw e
}
}
/**
* Maven install步骤
*
*
* @param params Map
* @return
*/
private def executeMavenInstall(params) {
script.echo "📦 开始执行Maven install步骤..."
def buildResult = [
success: false,
artifacts: [],
installTime: new Date().format('yyyy-MM-dd HH:mm:ss'),
profile: params.PROFILES
]
// 使Config File Provider加载Maven settings.xml
script.configFileProvider([script.configFile(fileId: params.MAVEN_SET, variable: 'MAVEN_SETTINGS_XML')]) {
def installGoals = buildInstallGoals(params)
def installOptions = buildInstallOptions(params)
def installOutput = script.sh(
script: """
# ================================================
# Maven Install -
# : ${params.PROFILES}
# : \$(date)
# ================================================
echo "🚀 开始Maven install操作..."
#
echo "📁 工作目录: \$(pwd)"
echo "📄 POM文件: ${params.pomFilePath ?: 'pom.xml'}"
echo "🔧 Settings文件: \${MAVEN_SETTINGS_XML}"
echo "🎯 操作目标: 本地安装 (install)"
# install命令
echo "🔨 执行命令: /usr/local/maven/bin/mvn --settings \${MAVEN_SETTINGS_XML} ${installGoals} ${installOptions}"
/usr/local/maven/bin/mvn \\
--settings \${MAVEN_SETTINGS_XML} \\
-f ${params.pomFilePath ?: 'pom.xml'} \\
${installGoals} ${installOptions}
""",
returnStatus: true
)
//
buildResult.success = (installOutput == 0)
buildResult.exitCode = installOutput
if (buildResult.success) {
script.echo "✅ Maven install 成功完成!"
//
buildResult.artifacts = collectArtifacts(params)
buildResult.localRepositoryPath = getLocalRepositoryPath()
} else {
script.echo "❌ Maven install 失败,退出码: ${installOutput}"
throw new Exception("Maven构建失败退出码: ${installOutput}")
}
}
return buildResult
}
/**
* install步骤的Maven目标
*
* @param params Map
* @return Maven goals字符串
*/
private def buildInstallGoals(params) {
def goals = []
//
goals.add("dependency:purge-local-repository -Dinclude=com.xiaomayi")
//
goals.add("clean")
goals.add("install") // package阶段
script.echo " 🔧 Install步骤Goals: ${goals.join(' ')}"
return goals.join(" ")
}
/**
* install步骤的Maven选项
*
* @param params Map
* @return Maven选项字符串
*/
private def buildInstallOptions(params) {
def options = []
//
options.add("-U")
//
if (params.skipTests ?: true) {
options.add("-Dmaven.test.skip=true")
}
// Maven profile
if (params.PROFILES) {
options.add("-P${params.PROFILES}")
}
//
if (params.branchConfig?.maven?.options) {
options.add(params.branchConfig.maven.options)
}
script.echo " ⚙️ Install步骤Options: ${options.join(' ')}"
return options.join(" ")
}
/**
*
*
* @param params Map
* @return
*/
private def collectArtifacts(params) {
def artifacts = []
try {
def jarFiles = script.findFiles(glob: "${params.jarFilePath ?: 'target'}/*.jar")
jarFiles.each { file ->
artifacts.add([
name: file.name,
path: file.path,
size: file.length(),
type: file.name.endsWith('-sources.jar') ? 'sources' :
file.name.endsWith('-javadoc.jar') ? 'javadoc' : 'main'
])
}
} catch (Exception e) {
script.echo "⚠️ 无法收集构件信息: ${e.message}"
}
return artifacts
}
/**
*
*
* @return
*/
private def getLocalRepositoryPath() {
return "~/.m2/repository/com/xiaomayi/"
}
/**
*
*
* @param params Map
*/
private def printBuildConfiguration(params) {
script.echo "📋 构建配置详情:"
script.echo " 🔧 Maven配置: ${params.MAVEN_SET}"
script.echo " 🌍 构建Profile: ${params.PROFILES}"
script.echo " 📦 输出路径: ${params.jarFilePath ?: 'target'}"
script.echo " 🏷️ JAR文件: ${params.jarFile ?: '未指定'}"
script.echo " ⚡ 跳过测试: ${params.skipTests ?: true}"
script.echo " 📄 POM文件: ${params.pomFilePath ?: 'pom.xml'}"
script.echo " 🔄 构建模式: 纯构建 (install only)"
}
/**
*
*
* @param params Map
* @param buildResult
*/
private def generateBuildReport(params, buildResult) {
script.echo "📊 构建阶段完成报告:"
script.echo " - ✅ 依赖清理完成com.xiaomayi"
script.echo " - ✅ 代码编译完成"
script.echo " - ${params.skipTests ? '⚡ 单元测试跳过' : '✅ 单元测试通过'}"
script.echo " - ✅ 打包完成"
script.echo " - ✅ 本地安装完成"
//
script.echo "🎉 构建产物信息:"
script.echo " - 本地路径: ${params.jarFilePath ?: 'target'} 目录"
script.echo " - 本地仓库: ${buildResult.localRepositoryPath}"
if (buildResult.artifacts) {
script.echo "📦 生成的构件:"
buildResult.artifacts.each { artifact ->
script.echo " - ${artifact.name} (${artifact.size} bytes) [${artifact.type}]"
}
}
script.echo "⏱️ 构建时间: ${buildResult.installTime}"
}
/**
*
*
* @param e
* @param params Map
*/
private def handleBuildFailure(Exception e, params) {
script.echo "❌ 构建阶段失败: ${e.message}"
script.echo "💡 建议检查:"
script.echo " - Maven settings.xml 配置是否正确"
script.echo " - 网络连接是否正常(依赖下载)"
script.echo " - 代码编译是否有语法错误"
script.echo " - 单元测试是否通过"
script.echo " - 版本号冲突或依赖问题"
//
script.echo "🔍 调试信息:"
script.echo " - 环境: ${params.PROFILES}"
script.echo " - Maven配置: ${params.MAVEN_SET}"
script.echo " - POM文件: ${params.pomFilePath ?: 'pom.xml'}"
}
/**
* profile有效性
*
* @param params Map
*/
private def validateProfile(params) {
script.echo "🔍 开始验证环境profile有效性..."
//
if (!params.PROFILES) {
def errorMsg = "缺少必要的PROFILES参数请指定要部署的环境"
script.echo "❌ ${errorMsg}"
throw new IllegalArgumentException(errorMsg)
}
if (!params.availableProfiles || params.availableProfiles.isEmpty()) {
def errorMsg = "缺少可用的环境profile列表请检查配置文件中环境配置"
script.echo "❌ ${errorMsg}"
throw new IllegalArgumentException(errorMsg)
}
//
try {
def selectedProfile = params.PROFILES.trim()
def availableProfiles = params.availableProfiles.collect { it.toString().trim() }
script.echo "📋 验证详情:"
script.echo " 🎯 选择的环境: ${selectedProfile}"
script.echo " 📊 可用环境: ${availableProfiles.join(', ')}"
if (!availableProfiles.contains(selectedProfile)) {
def errorMsg = "无效的部署环境: '${selectedProfile}'。可用环境: ${availableProfiles.join(', ')}"
script.error("环境验证失败: ${errorMsg}")
}
script.echo "✅ 环境profile验证通过: ${selectedProfile}"
} catch (Exception e) {
script.echo "❌ 环境profile验证过程中发生错误: ${e.message}"
script.echo "📋 可用环境列表: ${params.availableProfiles.join(', ')}"
throw e
}
}
/**
*
*
* @param buildResult
* @return boolean
*/
def isBuildSuccessful(buildResult) {
return buildResult?.success ?: false
}
/**
*
*
* @param buildResult
* @return
*/
def getBuildArtifacts(buildResult) {
return buildResult?.artifacts ?: []
}
}

View File

@ -0,0 +1,431 @@
package com.nexus.stages
/**
* - Maven构件部署到Nexus私库
*
*
*
* - Maven deploy步骤
* -
* - GPG签名等安全相关操作
* -
* -
*
*
* -
* - BuildService的输出结果
* -
* -
*
* @see Serializable Jenkins流水线的暂停和恢复
*/
class DeployService implements Serializable {
/**
* Jenkins pipeline脚本对象
*/
def script
/**
*
*/
def envConfig
/**
* -
*
* @param script Jenkins pipeline脚本对象
* @param envConfig
*/
DeployService(script, envConfig = [:]) {
this.script = script
this.envConfig = envConfig
script.echo "🚀 DeployService 初始化完成"
}
/**
*
* Nexus仓库
*
*
* 1.
* 2. Maven deploy步骤
* 3.
* 4.
*
* @param params Map
* @param buildResult
* @return
* @throws Exception
*/
def executeDeployStage(params, buildResult = null) {
def deployResult = [:]
try {
//
if (!shouldExecuteDeploy(params)) {
script.echo "⏭️ 跳过部署阶段(部署功能未启用)"
return [success: true, skipped: true, reason: "部署功能未启用"]
}
//
script.echo "🚀 开始部署阶段..."
printDeployConfiguration(params)
//
validateDeployEnvironment(params)
// Maven deploy步骤
deployResult = executeMavenDeploy(params)
//
generateDeployReport(params, deployResult, buildResult)
return deployResult
} catch (Exception e) {
//
handleDeployFailure(e, params)
// 线
throw e
}
}
/**
* Maven deploy步骤
* Nexus仓库
*
* @param params Map
* @return
*/
private def executeMavenDeploy(params) {
script.echo "📤 开始执行Maven deploy步骤..."
def deployResult = [
success: false,
deployedArtifacts: [],
deployTime: new Date().format('yyyy-MM-dd HH:mm:ss'),
repositoryUrl: params.currentNexusConfig?.url,
repositoryPolicy: params.repositoryPolicy
]
// 使Config File Provider加载Maven settings.xml
script.configFileProvider([script.configFile(fileId: params.MAVEN_SET, variable: 'MAVEN_SETTINGS_XML')]) {
def deployGoals = buildDeployGoals(params)
def deployOptions = buildDeployOptions(params)
def deployOutput = script.sh(
script: """
# ================================================
# Maven Deploy - Nexus仓库
# : ${params.PROFILES}
# : \$(date)
# ================================================
echo "🚀 开始部署到Nexus仓库..."
#
echo "🎯 目标仓库: ${params.currentNexusConfig?.url ?: '默认仓库'}"
echo "📋 仓库策略: ${params.repositoryPolicy ?: 'releases'}"
echo "🔧 Settings文件: \${MAVEN_SETTINGS_XML}"
echo "🏷️ 版本后缀: ${params.versionSuffix ?: '无'}"
# deploy命令
echo "🔨 执行命令: /usr/local/maven/bin/mvn --settings \${MAVEN_SETTINGS_XML} ${deployGoals} ${deployOptions}"
/usr/local/maven/bin/mvn \\
--settings \${MAVEN_SETTINGS_XML} \\
-f ${params.pomFilePath ?: 'pom.xml'} \\
${deployGoals} ${deployOptions}
""",
returnStatus: true
)
//
deployResult.success = (deployOutput == 0)
deployResult.exitCode = deployOutput
if (deployResult.success) {
script.echo "✅ Maven deploy 成功完成!"
deployResult.deployedArtifacts = estimateDeployedArtifacts(params)
} else {
script.echo "❌ Maven deploy 失败,退出码: ${deployOutput}"
throw new Exception("Maven部署失败退出码: ${deployOutput}")
}
}
return deployResult
}
/**
* deploy步骤的Maven目标
*
* @param params Map
* @return Maven goals字符串
*/
private def buildDeployGoals(params) {
def goals = ["deploy"]
script.echo " 🚀 Deploy步骤Goals: ${goals.join(' ')}"
return goals.join(" ")
}
/**
* deploy步骤的Maven选项
*
* @param params Map
* @return Maven选项字符串
*/
private def buildDeployOptions(params) {
def options = buildCommonMavenOptions(params)
// deploy特有的选项
if (params.publishStrategy?.signArtifacts) {
options.add("-Dgpg.sign=true")
if (params.publishStrategy.gpgKeyId) {
options.add("-Dgpg.keyname=${params.publishStrategy.gpgKeyId}")
}
script.echo " 🔏 启用GPG签名"
}
script.echo " ⚙️ Deploy步骤Options: ${options.join(' ')}"
return options.join(" ")
}
/**
* Maven选项
*
* @param params Map
* @return Maven选项列表
*/
private def buildCommonMavenOptions(params) {
def options = []
//
options.add("-U")
//
if (params.skipTests ?: true) {
options.add("-Dmaven.test.skip=true")
}
// Maven profile
if (params.PROFILES) {
options.add("-P${params.PROFILES}")
}
//
if (params.branchConfig?.maven?.options) {
options.add(params.branchConfig.maven.options)
}
return options
}
/**
* deploy步骤
*
* @param params Map
* @return boolean deploy
*/
private def shouldExecuteDeploy(params) {
// deploy设置
def branchDeployEnabled = params.branchConfig?.maven?.deploy ?: false
// autoDeploy设置
def envAutoDeploy = params.autoDeploy ?: true
// autoPublish设置
def publishAutoPublish = params.publishStrategy?.autoPublish ?: true
//
def finalDecision = branchDeployEnabled && envAutoDeploy && publishAutoPublish
script.echo "📋 部署决策分析:"
script.echo " - 分支部署配置: ${branchDeployEnabled}"
script.echo " - 环境自动部署: ${envAutoDeploy}"
script.echo " - 发布策略自动发布: ${publishAutoPublish}"
script.echo " - 最终决策: ${finalDecision ? '执行部署' : '跳过部署'}"
return finalDecision
}
/**
*
*
* @param params Map
* @return
*/
private def estimateDeployedArtifacts(params) {
def artifacts = []
// Maven项目结构估计部署的构件
def baseArtifacts = [
[name: "${params.artifactName ?: 'project'}.jar", type: "main"],
[name: "${params.artifactName ?: 'project'}-sources.jar", type: "sources"],
[name: "${params.artifactName ?: 'project'}-javadoc.jar", type: "javadoc"],
[name: "${params.artifactName ?: 'project'}.pom", type: "pom"]
]
baseArtifacts.each { artifact ->
artifacts.add([
name: artifact.name,
type: artifact.type,
repository: params.currentNexusConfig?.url,
policy: params.repositoryPolicy
])
}
return artifacts
}
/**
*
*
* @param params Map
*/
private def validateDeployEnvironment(params) {
script.echo "🔍 验证部署环境配置..."
// Nexus配置
if (!params.currentNexusConfig) {
throw new IllegalArgumentException("缺少Nexus仓库配置")
}
if (!params.currentNexusConfig.url) {
throw new IllegalArgumentException("Nexus仓库URL未配置")
}
if (!params.currentNexusConfig.credentialsId) {
script.echo "⚠️ Nexus仓库凭证未配置可能使用匿名访问"
}
//
if (!params.repositoryPolicy) {
script.echo "⚠️ 仓库策略未指定,使用默认策略"
}
script.echo "✅ 部署环境验证通过"
}
/**
*
*
* @param params Map
*/
private def printDeployConfiguration(params) {
script.echo "📋 部署配置详情:"
script.echo " 🔧 Maven配置: ${params.MAVEN_SET}"
script.echo " 🌍 部署Profile: ${params.PROFILES}"
script.echo " 🔗 Nexus仓库: ${params.currentNexusConfig?.url}"
script.echo " 🎯 仓库策略: ${params.repositoryPolicy ?: 'releases'}"
script.echo " 🔑 凭证ID: ${params.currentNexusConfig?.credentialsId ?: '未设置'}"
//
if (params.publishStrategy) {
script.echo " 🚀 自动发布: ${params.publishStrategy.autoPublish ?: 'false'}"
script.echo " 🔏 GPG签名: ${params.publishStrategy.signArtifacts ?: 'false'}"
if (params.publishStrategy.signArtifacts) {
script.echo " 🔑 GPG密钥: ${params.publishStrategy.gpgKeyId ?: '默认密钥'}"
}
script.echo " 📋 版本策略: ${params.publishStrategy.versionPolicy ?: 'semantic'}"
}
script.echo " 🏷️ 版本后缀: ${params.versionSuffix ?: '无'}"
}
/**
*
*
* @param params Map
* @param deployResult
* @param buildResult
*/
private def generateDeployReport(params, deployResult, buildResult) {
script.echo "📊 部署阶段完成报告:"
script.echo " - ✅ 构件验证完成"
script.echo " - ✅ 仓库连接建立"
script.echo " - ✅ 构件上传完成"
if (params.publishStrategy?.signArtifacts) {
script.echo " - 🔏 GPG签名验证完成"
}
script.echo "🎯 部署目标信息:"
script.echo " - 🌐 仓库地址: ${deployResult.repositoryUrl}"
script.echo " - 📋 仓库策略: ${deployResult.repositoryPolicy}"
script.echo " - 🏷️ 版本类型: ${params.versionSuffix ? '快照版本' : '正式版本'}"
if (deployResult.deployedArtifacts) {
script.echo "📦 部署的构件:"
deployResult.deployedArtifacts.each { artifact ->
script.echo " - ${artifact.name} [${artifact.type}]"
}
}
script.echo "⏱️ 部署时间: ${deployResult.deployTime}"
//
if (buildResult) {
script.echo "🔗 构建-部署关联:"
script.echo " - 构建时间: ${buildResult.installTime}"
script.echo " - 部署时间: ${deployResult.deployTime}"
script.echo " - 总耗时: 计算中..."
}
}
/**
*
*
* @param e
* @param params Map
*/
private def handleDeployFailure(Exception e, params) {
script.echo "❌ 部署阶段失败: ${e.message}"
script.echo "💡 建议检查:"
script.echo " - Nexus仓库地址是否正确"
script.echo " - 仓库访问权限是否足够"
script.echo " - 网络连接是否正常"
script.echo " - 版本号是否冲突(重复部署)"
script.echo " - GPG签名配置是否正确"
//
script.echo "🔍 调试信息:"
script.echo " - 环境: ${params.PROFILES}"
script.echo " - Nexus仓库: ${params.currentNexusConfig?.url}"
script.echo " - 仓库策略: ${params.repositoryPolicy}"
script.echo " - 部署配置: ${params.branchConfig?.maven?.deploy ? '启用' : '禁用'}"
}
/**
*
*
* @param deployResult
* @return boolean
*/
def isDeploySuccessful(deployResult) {
return deployResult?.success ?: false
}
/**
*
*
* @param deployResult
* @return boolean
*/
def isDeploySkipped(deployResult) {
return deployResult?.skipped ?: false
}
/**
*
*
* @param deployResult
* @return
*/
def getDeployedArtifacts(deployResult) {
return deployResult?.deployedArtifacts ?: []
}
}

View File

@ -0,0 +1,266 @@
// Pipeline 使
// Jenkins (Shared Libraries)
import com.nexus.ResolverService
import com.nexus.DeploymentService
import com.common.StageService
import com.common.NotificationService
/**
*
* CI/CD流水线功能
* Jenkins (Shared Library) (Global Variable) Pipeline
*
* @param orgName 线
*
*
* - orgName
* - 线
* - ()
* -
* -
*
*
* @Library ('share-library@master')_
* orgName = 'xiaomayi'
* pipelineJDKService(orgName)
*/
def call(String orgName) { // Jenkins Pipeline call
// null
def pipelineParams = null
//
def resolverService = null //
def deploymentService = null //
def stageService = null //
def notificationService = null //
// Jenkins代理标签线
def jenkinsAgent = ''
// 线 Declarative Pipeline
pipeline {
// 线any表示可在任何可用代理上运行
// agent stage agent
agent any
// 线
options {
// Jenkins
buildDiscarder(logRotator(
artifactDaysToKeepStr: '', // 使
artifactNumToKeepStr: '2', // 2jar包docker镜像等
daysToKeepStr: '7', // 7
numToKeepStr: '3' // 3
))
// 线2
timeout(time: 2, unit: 'HOURS')
// : disableConcurrentBuilds()
}
// 线 (stages)
stages {
/**
*
*
* pipeline agent any
*/
stage('Setup Parameters & ENV') {
steps {
// Git检出操作 (checkout SCM)线
checkout scmGit([ // scmGit checkout
// master
branches: [[name: '*/master']],
// URL
userRemoteConfigs: [[
credentialsId: 'c9b5eae2-5df5-485f-bebd-9cd5393b03e1', // Jenkins Git ID
url: 'http://192.168.10.102:3000/cicd/jenkins-pipeline-files.git' // URL地址
]],
//
extensions: [[
$class: 'RelativeTargetDirectory', // Jenkins checkout
relativeTargetDir: '.pipeline-files' // .pipeline-files
]],
])
script {
echo "=== 开始初始化配置 ==="
echo "组织名称: ${orgName}" //
try { // 使 try-catch
// this 线访 Jenkins
stageService = new StageService(this)
// '初始化配置'
stageService.recordStageStart('初始化配置')
//
resolverService = new ResolverService(this, orgName)
//
resolverService.loadConfigurations()
//
// pipelineParams Maven
pipelineParams = resolverService.setupParameters()
// profile
// params.PROFILES Jenkins parameters {}
// profile使使 profile (pipelineParams.PROFILES)
def selectedProfile = params.PROFILES ?: pipelineParams.PROFILES
pipelineParams.PROFILES = selectedProfile // profile Map中
// 使 Jenkins
// 使使 'master' Jenkins Controller
jenkinsAgent = pipelineParams?.jenkinsAgent ?: 'master'
echo "本次使用代理节点: ${jenkinsAgent}"
//
deploymentService = new DeploymentService(this, pipelineParams.envConfig)
//
notificationService = new NotificationService(this, pipelineParams, stageService)
// '初始化配置'
stageService.recordStageEnd('初始化配置', 'SUCCESS')
} catch (Exception e) { //
// 线
echo "配置初始化失败: ${e.message}"
// '初始化配置'
stageService.recordStageEnd('初始化配置', 'FAILURE')
// 线 FAILURE
error("管道初始化失败: " + e.getMessage())
}
echo "=== 结束初始化配置 ==="
}
}
}
/**
*
* Maven构建JAR包和Docker镜像
* Jenkins (jenkinsAgent) 使
*/
stage('Build') {
// 使 Jenkins
agent {
label jenkinsAgent // 使
}
steps {
script {
echo "=== 🔨 开始代码构建 ==="
// '构建镜像'
stageService.recordStageStart('构建镜像')
//
// mvn clean compile/test/packagedocker build/push
deploymentService.executeBuildStage(pipelineParams)
// '构建镜像'
stageService.recordStageEnd('构建镜像', 'SUCCESS')
echo "=== 🔨 完成代码构建 ==="
}
}
}
// /**
// *
// * Docker镜像部署到目标服务器
// * Jenkins (jenkinsAgent)
// */
// stage('Deploy') {
// // 使 Jenkins
// agent {
// label jenkinsAgent
// }
// steps {
// script {
// echo "=== 🚀 开始应用部署 ==="
// // '应用部署'
// stageService.recordStageStart('应用部署')
// //
// // SSH docker compose/k8s
// deploymentService.executeDeployStage(pipelineParams)
// // '应用部署'
// stageService.recordStageEnd('应用部署', 'SUCCESS')
// echo "=== 🚀 完成应用部署 ==="
// }
// }
// }
//
}
/**
* 线 (post section)
* 线
* pipeline agent any
*/
post {
/**
* always
*
*/
always {
echo "=== 管道执行完成 ==="
echo "完成时间: ${new Date()}" // 线
// 线
cleanWs()
script {
echo "构建完成,状态: ${currentBuild.currentResult}" //
//
stageService.collectAllStagesInfo()
}
}
/**
* success线 SUCCESS
*
*/
success {
echo "✅ 部署成功!"
script {
// Slack等
notificationService.sendBuildSuccess()
}
}
/**
* failure线 FAILURE
*
*/
failure {
echo "❌ 部署失败!"
script {
//
// errorMsg extraInfo
notificationService.sendBuildFailure(
errorMsg: "单元测试失败", //
extraInfo: [stage: "test", errorDetails: "具体错误信息"] //
)
}
}
/**
* aborted线 ABORTED
*
*/
aborted {
echo "❌ 构建中止!"
script {
//
notificationService.sendBuildAborted(
//
extraInfo: [: '手动中止', : env.USER_ID]
)
}
}
/**
* unstable线 UNSTABLE
*
*/
unstable {
echo "⚠️ 管道执行不稳定"
script {
//
notificationService.sendBuildUnstable(
extraInfo: ["不稳定原因": "测试未通过或存在警告"] //
)
}
}
}
}
}