Files
gerrit/CI流水线部署方案.md

457 lines
10 KiB
Markdown
Raw Permalink Normal View History

2025-12-22 17:12:39 +08:00
# CI/CD 流水线部署方案
## 概述
当前项目已部署 Gerrit 代码审查系统(运行在 `http://101.43.95.130:8080`),本文档提供几种 CI/CD 流水线部署方案,可根据需求选择。
---
## 方案对比
| 方案 | 优点 | 缺点 | 适用场景 |
|------|------|------|----------|
| **Jenkins** | 功能强大、插件丰富、与 Gerrit 集成好 | 资源占用较大 | 企业级、复杂流水线 |
| **Drone CI** | 轻量级、现代化、Docker 原生 | 功能相对简单 | 中小型项目、容器化环境 |
| **GitLab Runner** | 独立运行、配置简单 | 需要单独配置 | 熟悉 GitLab CI 语法 |
| **Webhook + 脚本** | 最轻量、完全自定义 | 需要自己开发 | 简单自动化需求 |
---
## 方案一Jenkins推荐
### 特点
- ✅ 与 Gerrit 深度集成,支持事件触发
- ✅ 丰富的插件生态
- ✅ 成熟的流水线配置Pipeline as Code
- ✅ 支持分布式构建
### 安装步骤
#### 1. 快速安装(使用脚本)
```bash
# 运行 Jenkins 安装脚本
bash install_jenkins.sh
```
#### 2. 手动安装
```bash
# 1. 安装 JenkinsCentOS/RHEL
sudo wget -O /etc/yum.repos.d/jenkins.repo \
https://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key
sudo yum install -y jenkins
# 2. 启动 Jenkins
sudo systemctl start jenkins
sudo systemctl enable jenkins
# 3. 查看初始密码
sudo cat /var/lib/jenkins/secrets/initialAdminPassword
# 4. 访问 Jenkins
# http://101.43.95.130:8080如果端口冲突Jenkins 默认使用 8080需要修改
```
### Gerrit 集成配置
#### 1. 安装 Gerrit Trigger 插件
- Jenkins 管理界面 → 插件管理 → 搜索 "Gerrit Trigger" → 安装
#### 2. 配置 Gerrit 连接
- Jenkins 管理界面 → 系统配置 → Gerrit Trigger
- 添加 Gerrit Server
- **Name**: `Gerrit-Server`
- **Frontend URL**: `http://101.43.95.130:8080`
- **SSH Port**: `29418`
- **Username**: `admin`(或您的 Gerrit 用户名)
- **SSH Keyfile**: `/home/renjianbo/.ssh/id_rsa`Gerrit SSH 密钥路径)
#### 3. 创建流水线任务
- 新建任务 → 选择 "流水线" 类型
- 在 Pipeline 脚本中配置:
```groovy
pipeline {
agent any
triggers {
gerrit(
serverName: 'Gerrit-Server',
events: [
changeMerged(),
patchsetCreated()
],
project: 'plain:.*',
branch: 'plain:.*'
)
}
stages {
stage('构建') {
steps {
echo '开始构建...'
sh 'mvn clean package' // 或您的构建命令
}
}
stage('测试') {
steps {
echo '运行测试...'
sh 'mvn test'
}
}
stage('部署') {
steps {
echo '部署应用...'
// 您的部署脚本
}
}
}
post {
success {
echo '流水线执行成功'
}
failure {
echo '流水线执行失败'
}
}
}
```
---
## 方案二Drone CI轻量级
### 特点
- ✅ 轻量级,资源占用小
- ✅ 基于 Docker易于扩展
- ✅ 配置简单YAML 格式
- ✅ 支持 Gerrit Webhook
### 安装步骤
#### 1. 安装 Docker如果未安装
```bash
# CentOS/RHEL
sudo yum install -y docker
sudo systemctl start docker
sudo systemctl enable docker
```
#### 2. 安装 Drone Server
```bash
# 创建 Drone 配置目录
sudo mkdir -p /opt/drone
cd /opt/drone
# 运行 Drone Server使用 Docker
docker run \
--volume=/opt/drone:/data \
--env=DRONE_GERRIT_SERVER=http://101.43.95.130:8080 \
--env=DRONE_GERRIT_USERNAME=admin \
--env=DRONE_RPC_SECRET=$(openssl rand -hex 16) \
--env=DRONE_SERVER_HOST=101.43.95.130:3000 \
--env=DRONE_SERVER_PROTO=http \
--publish=3000:80 \
--publish=443:443 \
--restart=always \
--detach=true \
--name=drone \
drone/drone:latest
```
#### 3. 安装 Drone Runner
```bash
# 运行 Drone Runner
docker run -d \
-v /var/run/docker.sock:/var/run/docker.sock \
-e DRONE_RPC_PROTO=http \
-e DRONE_RPC_HOST=101.43.95.130:3000 \
-e DRONE_RPC_SECRET=<从上面获取的密钥> \
-e DRONE_RUNNER_CAPACITY=2 \
-e DRONE_RUNNER_NAME=runner-1 \
--restart always \
--name runner \
drone/drone-runner-docker:latest
```
### 配置 Gerrit Webhook
在 Gerrit 项目中创建 `.drone.yml` 文件:
```yaml
kind: pipeline
type: docker
name: default
steps:
- name: build
image: maven:3.8-openjdk-17
commands:
- mvn clean package
- name: test
image: maven:3.8-openjdk-17
commands:
- mvn test
- name: deploy
image: alpine
commands:
- echo "部署应用..."
```
在 Gerrit 项目设置中配置 Webhook
- URL: `http://101.43.95.130:3000/hook`
- 触发事件: `change-merged`, `patchset-created`
---
## 方案三GitLab Runner独立运行
### 特点
- ✅ 独立运行,不需要 GitLab
- ✅ 使用 GitLab CI 语法
- ✅ 支持多种执行器Docker、Shell 等)
### 安装步骤
```bash
# 1. 下载 GitLab Runner
curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh" | sudo bash
sudo yum install -y gitlab-runner
# 2. 注册 Runner需要 GitLab 实例,或使用本地配置)
sudo gitlab-runner register \
--non-interactive \
--url "http://localhost" \
--registration-token "your-token" \
--executor "shell" \
--description "Gerrit Runner"
# 3. 启动 Runner
sudo systemctl start gitlab-runner
sudo systemctl enable gitlab-runner
```
### 使用方式
在项目根目录创建 `.gitlab-ci.yml`
```yaml
stages:
- build
- test
- deploy
build:
stage: build
script:
- echo "构建项目..."
- mvn clean package
test:
stage: test
script:
- echo "运行测试..."
- mvn test
deploy:
stage: deploy
script:
- echo "部署应用..."
```
通过 Gerrit Webhook 触发 GitLab Runner 执行。
---
## 方案四Webhook + 自定义脚本(最简单)
### 特点
- ✅ 最轻量,无需额外服务
- ✅ 完全自定义
- ✅ 资源占用最小
### 实现步骤
#### 1. 创建 Webhook 接收脚本
```bash
# 创建目录
mkdir -p /opt/ci-scripts
cd /opt/ci-scripts
# 创建简单的 HTTP 服务器接收 Webhook
cat > webhook_receiver.py << 'EOF'
#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import subprocess
import os
class WebhookHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
try:
event = json.loads(post_data.decode('utf-8'))
# 处理 Gerrit 事件
if event.get('type') == 'patchset-created':
project = event.get('change', {}).get('project')
branch = event.get('change', {}).get('branch')
# 执行构建脚本
script_path = f'/opt/ci-scripts/build.sh'
if os.path.exists(script_path):
subprocess.Popen(['bash', script_path, project, branch])
self.send_response(200)
self.end_headers()
except Exception as e:
print(f"Error: {e}")
self.send_response(500)
self.end_headers()
if __name__ == '__main__':
server = HTTPServer(('0.0.0.0', 9000), WebhookHandler)
print("Webhook receiver started on port 9000")
server.serve_forever()
EOF
chmod +x webhook_receiver.py
```
#### 2. 创建构建脚本
```bash
cat > /opt/ci-scripts/build.sh << 'EOF'
#!/bin/bash
PROJECT=$1
BRANCH=$2
echo "构建项目: $PROJECT, 分支: $BRANCH"
# 克隆或更新代码
cd /tmp
if [ -d "$PROJECT" ]; then
cd $PROJECT
git pull
else
git clone ssh://admin@101.43.95.130:29418/$PROJECT
cd $PROJECT
fi
# 执行构建
# 根据项目类型执行不同的构建命令
if [ -f "pom.xml" ]; then
mvn clean package
elif [ -f "package.json" ]; then
npm install && npm run build
fi
echo "构建完成"
EOF
chmod +x /opt/ci-scripts/build.sh
```
#### 3. 启动 Webhook 服务
```bash
# 使用 systemd 管理
sudo tee /etc/systemd/system/webhook-ci.service > /dev/null << EOSERVICE
[Unit]
Description=CI Webhook Receiver
After=network.target
[Service]
Type=simple
User=renjianbo
WorkingDirectory=/opt/ci-scripts
ExecStart=/usr/bin/python3 /opt/ci-scripts/webhook_receiver.py
Restart=always
[Install]
WantedBy=multi-user.target
EOSERVICE
sudo systemctl daemon-reload
sudo systemctl start webhook-ci
sudo systemctl enable webhook-ci
```
#### 4. 配置 Gerrit Webhook
在 Gerrit 项目设置中添加 Webhook
- URL: `http://101.43.95.130:9000`
- 事件: `patchset-created`, `change-merged`
---
## 推荐方案选择
### 🎯 个人小团队推荐(首选)
**推荐:方案四 - Webhook + 自定义脚本**
-**最轻量**:资源占用最小,几乎零开销
-**最简单**:无需安装复杂服务,直接运行脚本
-**完全可控**:所有逻辑自己掌控,易于调试
-**快速部署**5分钟即可完成部署
- ⚠️ **适合场景**:个人开发者、小团队、简单构建需求
**备选:方案二 - Drone CI**
-**现代化**:轻量级 CI/CD 工具
-**Docker 原生**:适合容器化项目
-**配置简单**YAML 格式配置
- ⚠️ **需要 Docker**:服务器需要安装 Docker
### 场景 1企业级、复杂流水线
**推荐Jenkins**
- 需要多环境部署
- 需要复杂的构建流程
- 需要详细的构建报告和通知
### 场景 2中小型项目、容器化
**推荐Drone CI**
- 项目规模中等
- 使用 Docker 容器
- 需要快速部署
### 场景 3简单自动化
**推荐Webhook + 脚本**
- 只需要简单的构建和部署
- 资源有限
- 完全自定义需求
---
## 端口规划
| 服务 | 端口 | 说明 |
|------|------|------|
| Gerrit | 8080 | 已部署 |
| Jenkins | 8081 | 避免与 Gerrit 冲突 |
| Drone CI | 3000 | Web 界面 |
| Webhook Receiver | 9000 | 自定义脚本 |
---
## 下一步
1. 选择适合的方案
2. 运行对应的安装脚本
3. 配置 Gerrit 集成
4. 创建第一个流水线任务
如需帮助,请参考各方案的详细安装脚本。