[2025-03-03] 添加Jenkins结合Jacoco实现覆盖率报告
All checks were successful
Publish to Confluence / confluence (push) Successful in 2h25m31s

This commit is contained in:
liuxiaohua 2025-03-03 14:41:50 +08:00
parent 9528778051
commit c749442ac8
6 changed files with 463 additions and 0 deletions

View File

@ -1,3 +1,9 @@
## 20250224-20250228
- [ ] 试用期规划
- [ ] JeecgBoot搭建及初步使用
- [ ] KubeSphere API: https://kubesphere.io/api/kubesphere/
- [ ] KubeSphere DevOps
## 20250120-20250123
- [X] 梳理南北流量网关,重构具有歧义调用方法

View File

@ -0,0 +1,192 @@
<!-- Space: qifu -->
<!-- Parent: 后端技术&知识&规范 -->
<!-- Parent: 技术方案 -->
<!-- Parent: 基建 -->
<!-- Parent: 04-使用教程 -->
<!-- Title: 20250303-Jenkins整合Jacoco实现覆盖率报告 -->
<!-- Macro: :anchor\((.*)\):
Template: ac:anchor
Anchor: ${1} -->
<!-- Macro: \!\[.*\]\((.+)\)\<\!\-\- width=(.*) \-\-\>
Template: ac:image
Url: ${1}
Width: ${2} -->
<!-- Macro: \<\!\-\- :toc: \-\-\>
Template: ac:toc
Printable: 'false'
MinLevel: 2
MaxLevel: 4 -->
<!-- Include: 杂项/声明文件.md -->
<!-- :toc: -->
# Jenkins整合Jacoco实现覆盖率报告
## 前置说明
- [Jenkins 安装](https://plugins.jenkins.io/maven-plugin)
- Jenkins 插件安装
- [Git plugin][Git plugin]
- [Git Forensics Plugin][Git Forensics Plugin]
- [Git Parameter Plug-In][Git Parameter Plug-In]
- [Coverage Plugin][Coverage Plugin]
- [Maven Integration plugin][Maven Integration plugin]
- [Maven](https://plugins.jenkins.io/maven-plugin)
- [Jacoco](https://www.jacoco.org/)
## Maven添加Jacoco插件
### 方法一、更新parent版本
- 项目中父依赖为:`qifu-saas-parent`
- 更新 `qifu-saas-parent` 版本 `<version>[1.0.14,)</version>`。开发测试 `<version>[1.0.14-SNAPSHOT,)</version>`
### 方法二、直接添加插件
- pom.xml 中添加插件
- ```xml
<!-- 以下是需要复制的内容,以上是方便查找复制的位置-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
<configuration>
<argLine>${argLine} </argLine>
<forkCount>4</forkCount>
<reuseForks>true</reuseForks>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.12</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
```
## 集成覆盖率报告
### Jenkins安装插件
- [Git plugin][Git plugin]
- [Git Forensics Plugin][Git Forensics Plugin]
- [Git Parameter Plug-In][Git Parameter Plug-In]
- [Coverage Plugin][Coverage Plugin]
- [Maven Integration plugin][Maven Integration plugin]
### Jenkins流水线配置
- 可以参考https://github.com/jenkinsci/coverage-plugin?tab=readme-ov-file#usage
#### 自由风格项目Freestyle Project
- 添加构建后操作Post Step
- 增量对比:
- ![](https://picture.texous.cn/blog/20250303104613312.png)
- 报告采集展示
- ![](https://picture.texous.cn/blog/20250303104707049.png)
#### 流水线Pipeline
- 编写Jenkinsfile
- ```groovy
pipeline {
agent any
tools {
maven "MavenInner"
}
parameters {
gitParameter(branch: '', branchFilter: '.*', defaultValue: 'master', name: 'buildBranch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'GitParameterDefinition')
}
environment {
GIT_URL='ssh://git@git.keyfil.com:9922/qifu-gateway/keycloak-justauth.git'
}
stages {
stage('Checkout') {
steps {
echo "正在从 GitLab 拉取分支的代码..."
git branch: "main", credentialsId: "1", url: "${GIT_URL}"
}
}
stage('Maven Build') {
steps {
echo "开始执行 Maven 构建..."
sh 'mvn clean test jacoco:report -Daliyun=*'
}
}
stage('Generate Coverage Report') {
steps {
echo "使用 Git Forensics 统计代码变更..."
discoverGitReferenceBuild referenceJob: 'Jacoco测试', targetBranch: '$referenceJob'
recordCoverage qualityGates: [[criticality: 'NOTE', metric: 'MODULE'], [baseline: 'MODIFIED_FILES', criticality: 'NOTE', metric: 'FILE'], [baseline: 'MODIFIED_LINES', criticality: 'NOTE', metric: 'LINE']], tools: [[parser: 'JACOCO']]
}
}
}
post {
success {
echo "构建成功!"
}
failure {
echo "构建失败,请检查日志。"
}
}
}
```
### 构建测试
## 编写单元测试
### 添加pom依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
```
### 编写单元测试
```java
package io.github.yanfeiwuji.justauth.social;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class WeworkIdentityProviderFactoryTest {
private WeworkIdentityProviderFactory weworkIdentityProviderFactoryUnderTest;
@BeforeEach
void setUp() {
weworkIdentityProviderFactoryUnderTest = new WeworkIdentityProviderFactory();
}
@Test
void testGetName() throws Exception {
assertEquals("企业微信", weworkIdentityProviderFactoryUnderTest.getName());
}
}
```
## 高级使用
### Squaretest插件
- 安装 Squaretest 插件并破解
- [直接下载](http://confluence.qifu.com/download/attachments/38510668/Squaretest.zip?api=v2)
- [破解教程参考](https://blog.csdn.net/binbushi/article/details/135942290)
- 右键 > Generate > Generate test
## 参考
[Git plugin]: https://plugins.jenkins.io/git
[Git Forensics Plugin]: https://plugins.jenkins.io/git-forensics
[Git Parameter Plug-In]: https://plugins.jenkins.io/git-parameter
[Coverage Plugin]: https://plugins.jenkins.io/coverage
[Maven Integration plugin]: https://plugins.jenkins.io/maven-plugin

View File

@ -0,0 +1,55 @@
# 基础镜像地址记录
## Jenkins插件镜像
- 配置路径:`Dashboard > Manage Jenkins > Plugins > Advanced settings > Update Site > URL`
- 镜像地址:`https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json`
- 点击 `submit` 使其生效
## Maven镜像仓库
### 阿里云Maven镜像仓库
- 配置路径 `settings.xml`
- ```xml
<mirror>
<id>aliyun-central</id>
<name>aliyun-central</name>
<url>https://maven.aliyun.com/repository/central</url>
<mirrorOf>central</mirrorOf>
</mirror>
<mirror>
<id>aliyun-public</id>
<name>aliyun-public</name>
<url>https://maven.aliyun.com/repository/public</url>
<mirrorOf>public</mirrorOf>
</mirror>
```
## NPM镜像仓库
- 使用方式
- ```shell
npm config set registry https://registry.npmmirror.com
#- 或者
npm install xxx --registry https://registry.npmmirror.com
```
## Docker镜像仓库
- 为了加速镜像拉取,你可以使用以下命令设置 registry mirror:
- ```shell
sudo tee /etc/docker/daemon.json <<EOF
{
"registry-mirrors": ["https://docker.zhai.cm"]
}
EOF
```
- 用法:
- 原拉取镜像命令: `docker pull library/alpine:latest`
- 加速拉取镜像命令: `docker pull docker.zhai.cm/library/alpine:latest`
- 其余备选列表:
- https://fast360.xyz 正常
- https://docker.m.daocloud.io 正常
- https://1ms.run 正常
- https://docker.zhai.cm 正常
- https://docker.gbfeng.com 正常
- https://hub.haod.eu.org 正常
- https://xdark.top 正常

View File

@ -0,0 +1,22 @@
## Gitflow
```mermaid
%%{init: { 'gitGraph': {'mainBranchName': 'master'}} }%%
gitGraph
commit
commit
branch developer
checkout developer
commit
branch feat/0001
checkout feat/0001
commit
checkout developer
commit
branch feat/0002
checkout feat/0002
commit
commit
checkout feat/0001
commit
```

View File

@ -0,0 +1,140 @@
以下是将 **Nightingale****Grafana OnCall** 整合,构建完整 **监控告警 + OnCall 值班管理** 系统的分步方案:
---
### **一、整合架构**
```mermaid
graph LR
A[Nightingale] -->|Webhook 告警推送| B[Grafana OnCall]
B -->|通知值班人员| C[钉钉/企业微信/短信]
B -->|告警状态同步| A
```
---
### **二、核心步骤**
#### **步骤 1配置 Grafana OnCall 告警接收通道**
1. **创建 OnCall Webhook 集成**
- 进入 Grafana OnCall → **Integrations****New Integration** → 选择 **Webhook**
- 记录生成的 **Webhook URL**(如 `https://oncall-api.example.com/integrations/webhook/abc123/`)。
2. **配置 Payload 模板**(适配 Nightingale 告警格式):
```json
{
"title": "{{ .CommonLabels.alertname }}",
"message": "{{ .CommonAnnotations.summary }}",
"status": "{{ .Status }}",
"severity": "{{ .CommonLabels.severity }}",
"fingerprint": "{{ .Fingerprint }}",
"source": "nightingale"
}
```
---
#### **步骤 2配置 Nightingale 告警转发到 Grafana OnCall**
1. **在 Nightingale 中创建通知模板**
- 进入 Nightingale → **告警管理****通知模板****新建模板**
- 类型选择 **Webhook**URL 填写 Grafana OnCall 的 Webhook URL。
2. **设置告警规则关联 Webhook**
- 编辑告警规则 → **通知配置** → 选择刚创建的 Webhook 模板。
- 自定义告警参数映射(确保 `alertname``summary` 等字段正确传递)。
---
#### **步骤 3配置 OnCall 排班与通知策略**
1. **创建值班表**
- 进入 Grafana OnCall → **Schedules****New Schedule**
- 设置轮班规则(如 24x7 轮班、工作日/节假日)、时区、交接提醒。
2. **配置通知渠道**
- **Channels** → 添加钉钉机器人、企业微信应用、短信网关等。
- 测试通知是否可达。
3. **设置告警路由规则**
- **Routes** → 根据标签(如 `severity=critical`)将告警路由到不同值班组。
- 示例:`severity=critical → 电话通知severity=warning → 企业微信群通知`
---
#### **步骤 4告警状态回传同步可选**
若需在 Nightingale 中同步 OnCall 处理状态,需开发回调接口:
```python
# 示例Grafana OnCall → Nightingale 状态同步
@app.route("/oncall-callback", methods=["POST"])
def handle_oncall_callback():
data = request.json
alert_id = data.get("fingerprint")
status = "resolved" if data.get("status") == "ok" else "firing"
# 调用 Nightingale API 更新告警状态
requests.patch(
f"{NIGHTINGALE_URL}/api/v1/alerts/{alert_id}",
json={"status": status},
headers={"Authorization": "Bearer {API_KEY}"}
)
return jsonify({"status": "success"})
```
---
### **三、关键配置说明**
| 组件 | 配置项 | 作用 |
|--------------------|------------|-------------------------------|
| **Nightingale** | Webhook 模板 | 将告警格式转换为 OnCall 兼容的 JSON 结构 |
| **Grafana OnCall** | Payload 模板 | 解析 Nightingale 告警字段(标题、描述、状态) |
| **Grafana OnCall** | 告警路由规则 | 根据标签(如 `severity`)定向通知值班人员 |
| **Nightingale** | 回调接口(可选) | 同步 OnCall 处理状态,保持告警状态一致性 |
---
### **四、验证与调试**
1. **触发测试告警**
```bash
# 使用 Nightingale 的测试告警功能
curl -X POST http://nightingale:17000/api/v1/alerts \
-H "Content-Type: application/json" \
-d '{"labels":{"alertname":"TestAlert","severity":"critical"},"annotations":{"summary":"Integration test"}}'
```
2. **检查 OnCall 告警流水**
- 进入 Grafana OnCall → **Alert Groups**,确认测试告警已接收并分配。
3. **验证通知渠道**
- 确保值班人员收到钉钉/短信通知,且内容包含告警详情。
---
### **五、性能优化建议**
1. **告警聚合**
在 Nightingale 中设置合理的告警分组规则,避免 OnCall 被高频告警淹没。
2. **分级通知**
- 使用 OnCall 的 **Escalation Policies**,配置多级通知(如 5 分钟未响应则通知上级)。
3. **去重与静默**
- 利用 OnCall 的 **Alert Manager** 功能,对重复告警自动合并或静默。
---
### **六、故障排查**
| 现象 | 可能原因 | 解决方案 |
|--------------|------------------|-----------------------------------|
| OnCall 未收到告警 | Webhook URL 配置错误 | 检查 Nightingale 的 Webhook 地址和网络连通性 |
| 告警字段缺失 | Payload 模板不匹配 | 调整 OnCall 的 Payload 模板匹配字段 |
| 通知延迟 | 渠道限速或网络问题 | 检查钉钉/企业微信的 API 调用频率限制 |
---
通过以上方案,可实现 **Nightingale 告警生成 → Grafana OnCall 值班管理** 的全链路自动化,显著提升运维响应效率。

48
草稿/Jenkinsfile vendored Normal file
View File

@ -0,0 +1,48 @@
pipeline {
agent any
// options {
// ansiColor('xterm')
// }
// properties([parameters([gitParameter(branch: '', branchFilter: '.*', defaultValue: '*/master', name: 'buildBranch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'GitParameterDefinition')])])
tools {
maven: 'MavenInner'
}
parameters {
// string(name: 'BRANCH_NAME', defaultValue: 'main', description: '请输入要构建的分支名称')
gitParameter(branch: '', branchFilter: '.*', defaultValue: '*/master', name: 'buildBranch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'GitParameterDefinition')
}
environment {
GIT_CREDENTIALS = credentials('your-gitlab-credentials-id')
GIT_URL='ssh://git@git.keyfil.com:9922/qifu-gateway/keycloak-justauth.git'
}
stages {
stage('Checkout') {
steps {
echo "正在从 GitLab 拉取 ${params.BRANCH_NAME} 分支的代码..."
// git credentialsId: "${GIT_CREDENTIALS}", url: 'https://gitlab.com/your-repo.git', branch: "${params.BRANCH_NAME}"
git branch: "${params.buildBranch}", credentialsId: '1', url: "${GIT_URL}"
}
}
stage('Maven Build') {
steps {
echo "开始执行 Maven 构建..."
sh 'mvn clean test jacoco:report -Daliyun=*'
}
}
stage('Generate Coverage Report') {
steps {
echo "使用 Git Forensics 统计代码变更..."
discoverGitReferenceBuild referenceJob: 'Jacoco测试', targetBranch: '$referenceJob'
recordCoverage qualityGates: [[criticality: 'NOTE', metric: 'MODULE'], [baseline: 'MODIFIED_FILES', criticality: 'NOTE', metric: 'FILE'], [baseline: 'MODIFIED_LINES', criticality: 'NOTE', metric: 'LINE']], tools: [[parser: 'JACOCO']]
}
}
}
post {
success {
echo "构建成功!"
}
failure {
echo "构建失败,请检查日志。"
}
}
}