🔐 系统安全运维与监控告警手册
基于 OpenClaw + Claude Code 的端到端研发自动化系统任务拆解
从需求 → PRD 设计 → 技术方案设计 → API 接口开发 → AI Coding → 测试 → CI/CD → 自动部署 → UI 自动化验收全流程
版本: v1.0 | 发布日期: 2026 年 3 月 14 日 | 适用环境: Jenkins + Docker + K8S (KubeSphere)
中间研发节点支持人机协同
第 1 章:系统架构概述
1.1 OpenClaw + Claude Code 核心架构
OpenClaw(原名 Clawdbot,过渡名 Moltbot)是 2026 年 1 月爆火的开源个人 AI 助手项目,由 Peter Steinberger(PSPDFKit 创始人)开发。它是一个可执行任务的智能体,不仅能回答问题,还能主动操作系统、访问网页、处理邮件、整理文件、发起提醒甚至自动编写代码。
核心能力:
- 将自然语言目标拆解为可执行步骤
- 自动调用终端命令执行操作
- 创建与修改项目文件
- 运行代码并检测结果
- 根据报错自动修复
- 本地优先 + 长期记忆机制
- 支持几乎所有大模型(Claude、Gemini、OpenAI、Ollama 等)
1.2 端到端研发自动化系统架构图
需求分析 Agent
PRD 设计 Agent
后端方案设计 Agent
前端方案设计 Agent
API 接口设计 Agent
AI Coding Agent
Unit Test Agent
集成测试 Agent
CI/Jenkins Agent
Docker + K8S 部署 Agent
UI 自动化验收 Agent
1.3 技术栈组成
| 层级 |
技术组件 |
用途 |
| AI 智能体层 |
OpenClaw, Claude Code, OpenSkills |
任务规划、代码生成、自动化执行 |
| 协作平台层 |
飞书/Slack/Discord |
人机交互、任务分发、状态通知 |
| 代码管理层 |
GitLab/GitHub |
版本控制、Code Review、MR/PR 管理 |
| CI/CD 层 |
Jenkins, GitLab CI |
持续集成、自动化构建、流水线编排 |
| 容器化层 |
Docker, Docker Compose |
应用容器化、环境一致性保障 |
| 编排调度层 |
Kubernetes, KubeSphere |
容器编排、服务发现、弹性伸缩 |
| 监控告警层 |
Prometheus, Grafana, ELK |
指标采集、可视化、日志分析、告警通知 |
| 安全防护层 |
WAF, IDS/IPS, Vault |
网络安全、入侵检测、密钥管理 |
1.4 Supervisor-Worker 多智能体协同架构
采用Supervisor-Worker 架构实现多智能体团队化作战,通过分工协作解决单一 AI Agent 的能力瓶颈问题。
- 调度层(Supervisor):负责任务分解、资源分配、进度跟踪、质量把控
- 执行层(Worker):负责具体任务执行,如代码生成、测试编写、部署操作等
- 通信机制:采用 JSON-RPC 和事件总线实现高效通信
- 隔离机制:身份隔离、会话隔离、工具权限三层隔离
安全注意事项:
- 所有 Agent 操作必须经过权限验证
- 敏感操作(如生产环境部署)需要人工审批
- 所有操作日志必须完整记录并审计
- API Key 和凭证必须使用 Vault 等工具加密存储
第 2 章:各研发角色 Agents 岗位设计
2.1 产品经理 Agent(Product Manager Agent)
| 属性 |
描述 |
| 职责 |
需求收集、市场分析、竞品调研、PRD 文档撰写 |
| 技能包 |
需求分析、用户故事编写、优先级排序、原型设计 |
| 工具 |
飞书文档、Jira、Figma、Miro |
| 输出物 |
需求文档、PRD、用户故事地图、产品路线图 |
工作流程示例:
# 产品经理 Agent 工作流
1. 接收业务方需求输入(自然语言/文档)
2. 进行需求澄清和问题追问
3. 市场调研和竞品分析(调用搜索工具)
4. 编写用户故事和验收标准
5. 生成 PRD 文档(Markdown 格式)
6. 组织需求评审会议(邀请相关方)
7. 根据反馈迭代 PRD
8. 提交至需求管理系统
2.2 架构师 Agent(Solution Architect Agent)
| 属性 |
描述 |
| 职责 |
技术方案设计、架构选型、技术风险评估、性能容量规划 |
| 技能包 |
系统设计、微服务架构、数据库设计、API 设计 |
| 工具 |
Draw.io、PlantUML、Archimate、Swagger |
| 输出物 |
技术方案文档、架构图、API 规范、数据模型 |
2.3 后端开发工程师 Agent(Backend Developer Agent)
| 属性 |
描述 |
| 职责 |
后端代码开发、数据库设计、API 实现、性能优化 |
| 技能包 |
Java/Python/Go、Spring Boot、MySQL/PostgreSQL、Redis、消息队列 |
| 工具 |
IDEA、VS Code、Postman、Docker |
| 输出物 |
后端代码、单元测试、API 文档、部署脚本 |
2.4 前端开发工程师 Agent(Frontend Developer Agent)
| 属性 |
描述 |
| 职责 |
前端界面开发、交互实现、性能优化、跨浏览器兼容 |
| 技能包 |
React/Vue、TypeScript、CSS/Sass、Webpack、响应式设计 |
| 工具 |
VS Code、Chrome DevTools、Figma、Storybook |
| 输出物 |
前端代码、组件库、样式指南、构建配置 |
2.5 测试工程师 Agent(QA Engineer Agent)
| 属性 |
描述 |
| 职责 |
测试用例设计、自动化测试、性能测试、质量报告 |
| 技能包 |
JUnit/Pytest、Selenium、JMeter、TestNG、Mock 技术 |
| 工具 |
Jenkins、SonarQube、Allure、Playwright |
| 输出物 |
测试用例、测试报告、缺陷报告、质量度量 |
2.6 DevOps 工程师 Agent(DevOps Engineer Agent)
| 属性 |
描述 |
| 职责 |
CI/CD 流水线设计、容器化部署、监控告警、基础设施即代码 |
| 技能包 |
Jenkins Pipeline、Docker、K8S、Terraform、Ansible |
| 工具 |
KubeSphere、Prometheus、Grafana、ELK、Vault |
| 输出物 |
流水线脚本、Dockerfile、Helm Chart、监控大盘 |
2.7 安全工程师 Agent(Security Engineer Agent)
| 属性 |
描述 |
| 职责 |
安全审计、漏洞扫描、渗透测试、安全策略制定 |
| 技能包 |
OWASP Top 10、SAST/DAST、加密技术、身份认证 |
| 工具 |
SonarQube、Fortify、Burp Suite、Metasploit |
| 输出物 |
安全报告、漏洞清单、修复建议、合规文档 |
多 Agent 协同优势:
- 专业分工:每个 Agent 专注于特定领域,提升专业度
- 并行执行:多个任务可以同时进行,提高效率
- 知识沉淀:每个 Agent 积累领域知识,持续优化
- 质量保障:多层审核机制,降低错误率
第 3 章:全流程自动化研发流程
3.1 需求阶段
3.1.1 需求收集与分析
# 需求收集流程
1. 业务方通过飞书/Slack 提交需求(自然语言描述)
2. 产品经理 Agent 进行需求澄清对话
- 询问业务背景和目标
- 确认用户群体和使用场景
- 明确功能边界和约束条件
3. Agent 自动生成需求摘要和待确认问题列表
4. 召开需求澄清会议(人机协同)
5. 形成最终需求文档
3.1.2 PRD 文档自动生成
# PRD 文档结构模板
# 1. 文档概述
- 产品背景
- 目标用户
- 核心价值
# 2. 功能需求
- 功能列表
- 功能详细描述
- 用户故事(As a... I want... So that...)
- 验收标准(Given-When-Then)
# 3. 非功能需求
- 性能要求(QPS、响应时间)
- 可用性要求(SLA)
- 安全性要求
- 兼容性要求
# 4. 数据需求
- 数据模型
- 数据统计需求
- 数据迁移方案
# 5. 接口需求
- 内部接口
- 外部接口
# 6. 上线计划
- 里程碑
- 发布策略
- 回滚方案
3.2 设计阶段
3.2.1 后端技术方案设计
# 后端设计方案内容
1. 系统架构设计
- 微服务划分
- 服务间通信方式(REST/gRPC/消息队列)
- 数据一致性方案
2. 数据库设计
- ER 图
- 表结构设计
- 索引设计
- 分库分表策略
3. API 设计
- RESTful API 规范
- 接口文档(OpenAPI/Swagger)
- 接口版本管理
4. 技术选型
- 编程语言和框架
- 中间件(缓存、消息队列)
- 第三方服务依赖
5. 性能设计
- 缓存策略
- 异步处理
- 限流降级方案
6. 安全设计
- 认证授权机制
- 数据加密
- 防攻击措施
3.2.2 前端技术方案设计
# 前端设计方案内容
1. 技术栈选型
- 框架(React/Vue/Angular)
- 状态管理(Redux/Vuex)
- UI 组件库(Ant Design/Material UI)
2. 页面架构
- 路由设计
- 页面组件拆分
- 复用组件设计
3. 状态管理
- 全局状态设计
- 本地状态设计
- 数据流设计
4. 接口对接
- API 调用封装
- 错误处理
- 加载状态管理
5. 性能优化
- 代码分割
- 懒加载
- 缓存策略
- 打包优化
6. 兼容性方案
- 浏览器兼容
- 响应式布局
- 移动端适配
3.3 API 接口开发协议设计
# API 接口设计规范(OpenAPI 3.0)
openapi: 3.0.0
info:
title: 用户管理 API
version: 1.0.0
description: 用户管理相关接口
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: 获取用户列表
operationId: listUsers
tags: [用户管理]
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: pageSize
in: query
schema:
type: integer
default: 20
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/UserList'
'401':
description: 未授权
'500':
description: 服务器错误
post:
summary: 创建用户
operationId: createUser
tags: [用户管理]
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
'201':
description: 创建成功
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: string
format: uuid
username:
type: string
email:
type: string
format: email
createdAt:
type: string
format: date-time
CreateUserRequest:
type: object
required:
- username
- email
- password
properties:
username:
type: string
minLength: 3
maxLength: 50
email:
type: string
format: email
password:
type: string
minLength: 8
UserList:
type: object
properties:
items:
type: array
items:
$ref: '#/components/schemas/User'
total:
type: integer
page:
type: integer
pageSize:
type: integer
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
security:
- bearerAuth: []
3.4 AI Coding 阶段
3.4.1 代码生成流程
# AI Coding 工作流(基于 Claude Code + OpenSkills)
1. 接收设计文档和 API 规范
2. 分析项目结构和现有代码
3. 生成代码实现计划(Coding Plan)
4. 分模块生成代码
- Controller 层
- Service 层
- Repository 层
- Model/Entity 层
- DTO/VO 层
5. 代码自检和优化
- 代码规范检查
- 潜在 Bug 检测
- 性能优化建议
6. 生成单元测试代码
7. 提交代码到 Git 仓库
8. 创建 Merge Request
3.4.2 使用 OpenSkills 技能包
# 安装 OpenSkills
npm install -g openskills
# 常用技能包
- test-driven-development: 测试驱动开发
- code-review: 代码审查
- debugging: 调试辅助
- refactoring: 重构建议
- documentation: 文档生成
- security-audit: 安全审计
- performance-optimization: 性能优化
# 在 Cursor/Claude Code 中加载技能
openskills load test-driven-development
openskills load code-review
3.5 单元测试阶段
3.5.1 单元测试规范
# 单元测试覆盖率要求
- 行覆盖率:≥ 80%
- 分支覆盖率:≥ 75%
- 方法覆盖率:≥ 90%
# 测试代码结构(JUnit 5 示例)
@SpringBootTest
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
@DisplayName("应该成功创建用户")
void shouldCreateUserSuccessfully() {
// Given
CreateUserRequest request = new CreateUserRequest();
request.setUsername("testuser");
request.setEmail("test@example.com");
User savedUser = new User();
savedUser.setId("uuid-123");
savedUser.setUsername("testuser");
when(userRepository.save(any())).thenReturn(savedUser);
// When
User result = userService.createUser(request);
// Then
assertNotNull(result.getId());
assertEquals("testuser", result.getUsername());
verify(userRepository, times(1)).save(any());
}
@Test
@DisplayName("用户名已存在时应抛出异常")
void shouldThrowExceptionWhenUsernameExists() {
// Given
CreateUserRequest request = new CreateUserRequest();
request.setUsername("existinguser");
when(userRepository.existsByUsername("existinguser"))
.thenReturn(true);
// When & Then
assertThrows(UsernameAlreadyExistsException.class, () -> {
userService.createUser(request);
});
}
}
3.6 集成测试阶段
3.6.1 集成测试策略
# 集成测试范围
1. API 接口集成测试
- 单接口功能验证
- 多接口串联测试
- 边界条件测试
- 异常场景测试
2. 服务间集成测试
- 微服务间调用
- 消息队列消费
- 缓存一致性
- 分布式事务
3. 数据库集成测试
- CRUD 操作验证
- 事务回滚测试
- 并发访问测试
- 数据迁移测试
4. 第三方服务集成测试
- 支付接口
- 短信服务
- 邮件服务
- OSS 存储
# 使用 Testcontainers 进行集成测试
@Testcontainers
class OrderServiceIntegrationTest {
@Container
static PostgreSQLContainer> postgres =
PostgreSQLContainerBuilder.build("postgres:15");
@Container
static RedisContainer> redis =
new RedisContainer("redis:7");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.redis.host", redis::getHost);
registry.add("spring.redis.port", redis::getFirstMappedPort);
}
@Test
void shouldProcessOrderSuccessfully() {
// 完整的订单处理流程测试
}
}
3.7 UI 自动化测试验收
3.7.1 UI 自动化测试框架
# 使用 Playwright 进行 UI 自动化测试
import { test, expect } from '@playwright/test';
test.describe('用户登录流程', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:3000');
});
test('应该成功登录', async ({ page }) => {
// 填写登录表单
await page.fill('#username', 'testuser');
await page.fill('#password', 'password123');
// 提交表单
await page.click('button[type="submit"]');
// 验证跳转
await expect(page).toHaveURL('/dashboard');
// 验证欢迎信息
await expect(page.locator('.welcome-message'))
.toContainText('Welcome, testuser');
});
test('密码错误时应显示错误提示', async ({ page }) => {
await page.fill('#username', 'testuser');
await page.fill('#password', 'wrongpassword');
await page.click('button[type="submit"]');
await expect(page.locator('.error-message'))
.toContainText('Invalid credentials');
});
test('表单验证', async ({ page }) => {
await page.click('button[type="submit"]');
await expect(page.locator('#username'))
.toHaveAttribute('aria-invalid', 'true');
await expect(page.locator('#password'))
.toHaveAttribute('aria-invalid', 'true');
});
});
# E2E 测试场景
test.describe('完整购物流程', () => {
test('从浏览商品到完成支付', async ({ page }) => {
// 1. 浏览商品列表
// 2. 搜索商品
// 3. 查看商品详情
// 4. 添加到购物车
// 5. 结算
// 6. 填写收货地址
// 7. 选择支付方式
// 8. 完成支付
// 9. 查看订单详情
});
});
测试金字塔原则:
- 单元测试(70%):快速、稳定、覆盖核心逻辑
- 集成测试(20%):验证模块间协作
- E2E 测试(10%):模拟真实用户场景
第 4 章:CI/CD + Docker + K8S 自动部署
4.1 Jenkins 流水线设计
4.1.1 Jenkins Pipeline 脚本
// Jenkinsfile - 声明式流水线
pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: maven
image: maven:3.9-openjdk-17
command:
- cat
tty: true
- name: docker
image: docker:24-dind
securityContext:
privileged: true
'''
}
}
environment {
REGISTRY = 'registry.example.com'
IMAGE_NAME = 'myapp/backend'
KUBECONFIG_CREDENTIALS_ID = 'kubeconfig-prod'
SONAR_TOKEN_CREDENTIALS_ID = 'sonar-token'
}
triggers {
pollSCM('*/5 * * * *') // 每 5 分钟轮询
cron('0 2 * * *') // 每天凌晨 2 点执行
}
options {
timeout(time: 60, unit: 'MINUTES')
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '10'))
timestamps()
}
stages {
stage('Checkout') {
steps {
checkout scm
script {
env.GIT_COMMIT_SHORT = sh(
script: 'git rev-parse --short HEAD',
returnStdout: true
).trim()
env.BUILD_VERSION = "${env.BUILD_NUMBER}-${env.GIT_COMMIT_SHORT}"
}
}
}
stage('Code Quality') {
parallel {
stage('SonarQube Analysis') {
steps {
withCredentials([string(credentialsId: SONAR_TOKEN_CREDENTIALS_ID, variable: 'SONAR_TOKEN')]) {
sh '''
mvn sonar:sonar \
-Dsonar.projectKey=myapp-backend \
-Dsonar.host.url=${SONAR_HOST_URL} \
-Dsonar.token=${SONAR_TOKEN} \
-Dsonar.qualitygate.wait=true
'''
}
}
}
stage('Security Scan') {
steps {
sh 'mvn dependency-check:check'
dependencyCheck additionalArguments: '--scan ./ --format HTML', odcInstallation: 'ODC'
dependencyCheckPublisher pattern: '**/dependency-check-report.*'
}
}
}
}
stage('Unit Test') {
steps {
sh 'mvn test'
}
post {
always {
junit 'target/surefire-reports/*.xml'
publishHTML(target: [
allowMissingReport: false,
alwaysLinkToLastBuild: true,
keepAllHistory: true,
reportDir: 'target/site/jacoco',
reportFiles: 'index.html',
reportName: 'Jacoco Coverage Report'
])
}
}
}
stage('Build Docker Image') {
steps {
script {
docker.withRegistry("https://${REGISTRY}", 'docker-registry-credentials') {
def customImage = docker.build("${IMAGE_NAME}:${BUILD_VERSION}")
customImage.push()
customImage.push('latest')
}
}
}
}
stage('Deploy to Dev') {
when {
branch 'develop'
}
steps {
script {
kubeconfigWithAuth(credentialsId: KUBECONFIG_CREDENTIALS_ID, serverUrl: '') {
sh """
kubectl set image deployment/myapp-backend \
backend=${REGISTRY}/${IMAGE_NAME}:${BUILD_VERSION} \
-n development
kubectl rollout status deployment/myapp-backend -n development --timeout=300s
"""
}
}
}
}
stage('Deploy to Staging') {
when {
branch 'release/*'
}
steps {
input message: 'Deploy to staging?', ok: 'Yes, deploy'
script {
kubeconfigWithAuth(credentialsId: KUBECONFIG_CREDENTIALS_ID, serverUrl: '') {
sh """
kubectl set image deployment/myapp-backend \
backend=${REGISTRY}/${IMAGE_NAME}:${BUILD_VERSION} \
-n staging
kubectl rollout status deployment/myapp-backend -n staging --timeout=300s
"""
}
}
}
}
stage('Deploy to Production') {
when {
branch 'main'
}
steps {
input message: 'Deploy to production?', ok: 'Yes, deploy to PROD'
script {
kubeconfigWithAuth(credentialsId: KUBECONFIG_CREDENTIALS_ID, serverUrl: '') {
sh """
# 蓝绿部署
kubectl apply -f k8s/production/green-deployment.yaml \
-l version=${BUILD_VERSION}
# 等待就绪
kubectl rollout status deployment/myapp-backend-green -n production --timeout=300s
# 切换流量
kubectl patch service myapp-backend -n production \
-p '{"spec":{"selector":{"version":"${BUILD_VERSION}"}}}'
# 删除旧版本
kubectl delete deployment myapp-backend-blue -n production || true
"""
}
}
}
}
stage('Smoke Test') {
steps {
script {
def healthCheck = sh(
script: 'curl -s -o /dev/null -w "%{http_code}" http://myapp.example.com/health',
returnStdout: true
).trim()
if (healthCheck != '200') {
error('Health check failed!')
}
}
}
}
}
post {
always {
cleanWs()
archiveArtifacts artifacts: 'target/*.jar', allowEmptyArchive: true
}
success {
script {
// 发送成功通知
slackSend(color: 'good', message: "Build ${env.BUILD_NUMBER} succeeded!")
}
}
failure {
script {
// 发送失败通知
slackSend(color: 'danger', message: "Build ${env.BUILD_NUMBER} failed!")
// 创建 Jira 问题
jiraNewIssue(
site: 'JIRA',
issue: [
project: [key: 'PROJ'],
summary: "Build ${env.BUILD_NUMBER} failed",
description: "Build failed: ${env.BUILD_URL}",
issuetype: [name: 'Bug'],
priority: [name: 'High']
]
)
}
}
}
}
4.2 Docker 容器化
4.2.1 Dockerfile 最佳实践
# 多阶段构建 Dockerfile
# Stage 1: Build
FROM maven:3.9-eclipse-temurin-17 AS builder
WORKDIR /app
# 复制 pom.xml 以利用 Docker 缓存层
COPY pom.xml .
RUN mvn dependency:go-offline -B
# 复制源代码并构建
COPY src ./src
RUN mvn package -DskipTests -B
# Stage 2: Runtime
FROM eclipse-temurin:17-jre-alpine
# 创建非 root 用户
RUN addgroup -g 1001 appgroup && \
adduser -u 1001 -G appgroup -D appuser
WORKDIR /app
# 复制构建产物
COPY --from=builder --chown=appuser:appgroup /app/target/*.jar app.jar
# JVM 优化参数
ENV JAVA_OPTS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp"
# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/actuator/health || exit 1
USER appuser
EXPOSE 8080
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]
4.2.2 Docker Compose 配置
version: '3.8'
services:
backend:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=docker
- DB_HOST=postgres
- REDIS_HOST=redis
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
networks:
- app-network
volumes:
- logs:/app/logs
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/actuator/health"]
interval: 30s
timeout: 3s
retries: 3
start_period: 40s
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "80:80"
depends_on:
- backend
networks:
- app-network
postgres:
image: postgres:15-alpine
environment:
POSTGRES_DB: myapp
POSTGRES_USER: admin
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- postgres-data:/var/lib/postgresql/data
- ./init-scripts:/docker-entrypoint-initdb.d
networks:
- app-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U admin -d myapp"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
command: redis-server --appendonly yes
volumes:
- redis-data:/data
networks:
- app-network
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
prometheus:
image: prom/prometheus:v2.45.0
ports:
- "9090:9090"
volumes:
- ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus-data:/prometheus
networks:
- app-network
grafana:
image: grafana/grafana:10.0.0
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
volumes:
- grafana-data:/var/lib/grafana
- ./monitoring/grafana/dashboards:/etc/grafana/provisioning/dashboards
- ./monitoring/grafana/datasources:/etc/grafana/provisioning/datasources
networks:
- app-network
depends_on:
- prometheus
networks:
app-network:
driver: bridge
volumes:
postgres-data:
redis-data:
prometheus-data:
grafana-data:
logs:
4.3 Kubernetes 部署
4.3.1 K8S Deployment 配置
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-backend
namespace: production
labels:
app: myapp-backend
version: v1.0.0
spec:
replicas: 3
selector:
matchLabels:
app: myapp-backend
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
labels:
app: myapp-backend
version: v1.0.0
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/actuator/prometheus"
spec:
serviceAccountName: myapp-sa
securityContext:
runAsNonRoot: true
fsGroup: 1001
initContainers:
- name: wait-for-db
image: busybox:1.36
command: ['sh', '-c', 'until nc -z postgres-service 5432; do echo waiting for postgres; sleep 2; done']
containers:
- name: backend
image: registry.example.com/myapp/backend:v1.0.0
imagePullPolicy: Always
ports:
- name: http
containerPort: 8080
protocol: TCP
env:
- name: SPRING_PROFILES_ACTIVE
value: "production"
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: myapp-config
key: db.host
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: myapp-secret
key: db.password
resources:
requests:
memory: "512Mi"
cpu: "250m"
limits:
memory: "1Gi"
cpu: "500m"
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 60
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 30
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
securityContext:
runAsUser: 1001
runAsGroup: 1001
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp-volume
mountPath: /tmp
- name: logs-volume
mountPath: /app/logs
volumes:
- name: tmp-volume
emptyDir: {}
- name: logs-volume
emptyDir: {}
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- myapp-backend
topologyKey: kubernetes.io/hostname
---
apiVersion: v1
kind: Service
metadata:
name: myapp-backend-service
namespace: production
spec:
selector:
app: myapp-backend
ports:
- name: http
port: 80
targetPort: 8080
type: ClusterIP
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: myapp-backend-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: myapp-backend
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 10
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
- type: Pods
value: 4
periodSeconds: 15
selectPolicy: Max
4.3.2 KubeSphere 集成
# KubeSphere DevOps 流水线配置
apiVersion: devops.kubesphere.io/v1alpha3
kind: Pipeline
metadata:
name: myapp-pipeline
namespace: myproject
spec:
pipelineConfig:
type: Jenkinsfile
jenkinsfile: |
pipeline {
agent {
label 'maven'
}
stages {
stage('Build') {
steps {
container('maven') {
sh 'mvn clean package -DskipTests'
}
}
}
stage('Build Image') {
steps {
container('docker') {
script {
docker.build("registry.example.com/myapp/backend:${BUILD_ID}")
}
}
}
}
stage('Deploy') {
steps {
container('kubectl') {
sh '''
kubectl set image deployment/myapp-backend \
backend=registry.example.com/myapp/backend:${BUILD_ID}
'''
}
}
}
}
}
scheduler:
cron: '0 2 * * *'
triggerType: CRON
部署最佳实践:
- 使用蓝绿部署或金丝雀发布减少风险
- 配置健康检查和自动恢复
- 实施资源限制和请求
- 使用 HPA 实现自动扩缩容
- 配置 Pod 反亲和性提高可用性
- 使用 ConfigMap 和 Secret 管理配置
第 5 章:安全运维体系
5.1 安全架构设计
5.1.1 纵深防御策略
# 多层安全防护体系
1. 网络层安全
- WAF(Web 应用防火墙)
- DDoS 防护
- 网络隔离(VPC、子网划分)
- 安全组规则
2. 主机层安全
- 操作系统加固
- 最小权限原则
- 定期补丁更新
- 入侵检测系统(IDS)
3. 应用层安全
- 身份认证(OAuth2.0、JWT)
- 授权控制(RBAC、ABAC)
- 输入验证
- SQL 注入防护
- XSS 防护
- CSRF 防护
4. 数据层安全
- 传输加密(TLS 1.3)
- 存储加密(AES-256)
- 数据脱敏
- 备份与恢复
5. 运维层安全
- 堡垒机
- 操作审计
- 密钥管理(Vault)
- 零信任网络
5.2 身份认证与授权
5.2.1 OAuth2.0 + JWT 实现
# Spring Security OAuth2 配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private DataSource dataSource;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource)
.withClient("myapp-client")
.secret(passwordEncoder().encode("client-secret"))
.authorizedGrantTypes("authorization_code", "refresh_token", "password")
.redirectUris("http://localhost:8080/callback")
.scopes("read", "write")
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(86400);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.authenticationManager(authenticationManager)
.tokenStore(jwtTokenStore())
.accessTokenConverter(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("your-secret-key");
return converter;
}
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
}
# Resource Server 配置
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.csrf().disable();
}
}
5.3 密钥管理
5.3.1 HashiCorp Vault 集成
# Vault 部署配置(Kubernetes)
apiVersion: v1
kind: Namespace
metadata:
name: vault
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: vault
namespace: vault
spec:
serviceName: vault
replicas: 3
selector:
matchLabels:
app: vault
template:
metadata:
labels:
app: vault
spec:
serviceAccountName: vault
containers:
- name: vault
image: hashicorp/vault:1.14
args:
- server
- -config=/vault/config/config.hcl
ports:
- name: http
containerPort: 8200
- name: rpc
containerPort: 8201
env:
- name: VAULT_ADDR
value: "http://localhost:8200"
volumeMounts:
- name: config
mountPath: /vault/config
- name: data
mountPath: /vault/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi
---
# 应用通过 Vault Agent Sidecar 获取密钥
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-backend
spec:
template:
spec:
containers:
- name: vault-agent
image: hashicorp/vault:1.14
args:
- agent
- -config=/vault/config/agent-config.hcl
env:
- name: VAULT_ADDR
value: "http://vault.vault.svc:8200"
volumeMounts:
- name: vault-secrets
mountPath: /vault/secrets
- name: vault-config
mountPath: /vault/config
- name: backend
image: myapp/backend:latest
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: vault-secret
key: db-password
volumeMounts:
- name: vault-secrets
mountPath: /etc/secrets
readOnly: true
volumes:
- name: vault-secrets
emptyDir:
medium: Memory
- name: vault-config
configMap:
name: vault-agent-config
5.4 安全扫描与审计
5.4.1 SAST/DAST 集成
# Jenkins 流水线中的安全扫描
stage('Security Scanning') {
parallel {
stage('SAST - SonarQube') {
steps {
withCredentials([string(credentialsId: 'sonar-token', variable: 'SONAR_TOKEN')]) {
sh '''
mvn sonar:sonar \
-Dsonar.security.hotspots.inheritedRules=true \
-Dsonar.auth.github.enabled=true
'''
}
}
}
stage('Dependency Check') {
steps {
sh 'mvn dependency-check:check -DdependencyCheck.failBuild=NONE'
dependencyCheckPublisher pattern: '**/dependency-check-report.xml'
}
}
stage('Container Scan') {
steps {
sh 'trivy image --severity HIGH,CRITICAL myapp/backend:latest'
}
}
stage('DAST - OWASP ZAP') {
steps {
zapScan(
baseline: 'false',
failOnAlert: 'true',
targetUrl: 'http://staging.myapp.com',
reportDir: 'zap-reports'
)
}
}
}
}
# 安全门禁配置
qualityGate {
timeout: 300
conditions: [
[metric: 'security_rating', operator: 'LT', value: '1'],
[metric: 'vulnerabilities', operator: 'LT', value: '0'],
[metric: 'security_hotspots_reviewed', operator: 'GT', value: '80']
]
}
5.5 合规与审计
5.5.1 操作审计日志
# Kubernetes 审计配置
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
# 记录所有写操作
- level: RequestResponse
verbs: ["create", "update", "patch", "delete"]
resources:
- group: ""
resources: ["pods", "services", "configmaps", "secrets"]
# 记录所有对 Secrets 的访问
- level: Metadata
resources:
- group: ""
resources: ["secrets"]
# 不记录某些读操作的日志
- level: None
verbs: ["get", "watch", "list"]
resources:
- group: ""
resources: ["configmaps", "endpoints"]
# 默认级别
- level: Metadata
omitStages:
- "RequestReceived"
# 审计日志收集
apiVersion: v1
kind: ConfigMap
metadata:
name: audit-policy
namespace: kube-system
data:
policy.yaml: |
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: RequestResponse
resources:
- group: ""
resources: ["secrets", "configmaps"]
安全红线:
- 禁止硬编码密码和密钥
- 禁止使用 HTTP 明文传输敏感数据
- 禁止关闭安全日志
- 禁止绕过身份认证和授权
- 禁止在生产环境使用默认凭证
- 所有变更必须经过安全评审
第 6 章:监控告警体系(Prometheus + Grafana + ELK)
6.1 Prometheus 监控
6.1.1 Prometheus 配置
# prometheus.yml 配置文件
global:
scrape_interval: 15s
evaluation_interval: 15s
external_labels:
monitor: 'myapp-monitor'
environment: 'production'
alerting:
alertmanagers:
- static_configs:
- targets:
- alertmanager:9093
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
# Prometheus 自监控
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
# Spring Boot 应用监控
- job_name: 'spring-boot-apps'
metrics_path: '/actuator/prometheus'
kubernetes_sd_configs:
- role: pod
namespaces:
names:
- production
- staging
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
- action: labelmap
regex: __meta_kubernetes_pod_label_(.+)
- source_labels: [__meta_kubernetes_namespace]
action: replace
target_label: kubernetes_namespace
- source_labels: [__meta_kubernetes_pod_name]
action: replace
target_label: kubernetes_pod_name
# Node Exporter
- job_name: 'node-exporter'
kubernetes_sd_configs:
- role: node
relabel_configs:
- action: labelmap
regex: __meta_kubernetes_node_label_(.+)
- target_label: __address__
replacement: kubernetes.default.svc:443
- source_labels: [__meta_kubernetes_node_name]
regex: (.+)
target_label: __metrics_path__
replacement: /api/v1/nodes/${1}/proxy/metrics
# cAdvisor 容器监控
- job_name: 'cadvisor'
kubernetes_sd_configs:
- role: node
relabel_configs:
- action: labelmap
regex: __meta_kubernetes_node_label_(.+)
- target_label: __address__
replacement: kubernetes.default.svc:443
- source_labels: [__meta_kubernetes_node_name]
regex: (.+)
target_label: __metrics_path__
replacement: /api/v1/nodes/${1}/proxy/metrics/cadvisor
# MySQL Exporter
- job_name: 'mysql'
static_configs:
- targets: ['mysql-exporter:9104']
# Redis Exporter
- job_name: 'redis'
static_configs:
- targets: ['redis-exporter:9121']
6.1.2 告警规则配置
# alerts.yml 告警规则
groups:
- name: application-alerts
interval: 30s
rules:
# 应用宕机告警
- alert: ApplicationDown
expr: up{job="spring-boot-apps"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "应用 {{ $labels.job }} 宕机"
description: "实例 {{ $labels.instance }} 已经宕机超过 1 分钟"
# HTTP 错误率过高
- alert: HighHTTPErrorRate
expr: sum(rate(http_server_requests_seconds_count{status=~"5.."}[5m])) / sum(rate(http_server_requests_seconds_count[5m])) > 0.05
for: 5m
labels:
severity: warning
annotations:
summary: "HTTP 5xx 错误率过高"
description: "当前 HTTP 5xx 错误率为 {{ $value | humanizePercentage }}"
# 响应时间过长
- alert: HighResponseTime
expr: histogram_quantile(0.95, sum(rate(http_server_requests_seconds_bucket[5m])) by (le)) > 2
for: 5m
labels:
severity: warning
annotations:
summary: "P95 响应时间过长"
description: "P95 响应时间为 {{ $value }} 秒"
# JVM 内存使用率过高
- alert: HighJVMMemoryUsage
expr: jvm_memory_used_bytes{area="heap"} / jvm_memory_max_bytes{area="heap"} > 0.85
for: 5m
labels:
severity: warning
annotations:
summary: "JVM 堆内存使用率过高"
description: "当前堆内存使用率为 {{ $value | humanizePercentage }}"
# GC 时间过长
- alert: HighGCTime
expr: rate(jvm_gc_pause_seconds_sum[5m]) / rate(jvm_gc_pause_seconds_count[5m]) > 0.5
for: 5m
labels:
severity: warning
annotations:
summary: "GC 暂停时间过长"
description: "平均 GC 暂停时间为 {{ $value }} 秒"
# 数据库连接池耗尽
- alert: DatabaseConnectionPoolExhausted
expr: hikaricp_connections_active / hikaricp_connections_max > 0.9
for: 5m
labels:
severity: critical
annotations:
summary: "数据库连接池即将耗尽"
description: "当前连接池使用率为 {{ $value | humanizePercentage }}"
- name: infrastructure-alerts
rules:
# CPU 使用率过高
- alert: HighCPUUsage
expr: 100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 5m
labels:
severity: warning
annotations:
summary: "CPU 使用率过高"
description: "实例 {{ $labels.instance }} CPU 使用率为 {{ $value }}%"
# 内存使用率过高
- alert: HighMemoryUsage
expr: (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100 > 85
for: 5m
labels:
severity: warning
annotations:
summary: "内存使用率过高"
description: "实例 {{ $labels.instance }} 内存使用率为 {{ $value }}%"
# 磁盘使用率过高
- alert: HighDiskUsage
expr: (1 - (node_filesystem_avail_bytes / node_filesystem_size_bytes)) * 100 > 85
for: 5m
labels:
severity: warning
annotations:
summary: "磁盘使用率过高"
description: "实例 {{ $labels.instance }} 磁盘使用率为 {{ $value }}%"
# Pod 重启频繁
- alert: PodCrashLooping
expr: increase(kube_pod_container_status_restarts_total[1h]) > 3
for: 5m
labels:
severity: warning
annotations:
summary: "Pod {{ $labels.pod }} 频繁重启"
description: "过去 1 小时内重启了 {{ $value }} 次"
6.2 Grafana 可视化
6.2.1 Dashboard 配置
# Grafana Dashboard JSON 示例
{
"dashboard": {
"title": "应用监控大盘",
"tags": ["spring-boot", "application"],
"timezone": "browser",
"panels": [
{
"id": 1,
"title": "QPS",
"type": "graph",
"targets": [
{
"expr": "sum(rate(http_server_requests_seconds_count[1m]))",
"legendFormat": "QPS"
}
],
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}
},
{
"id": 2,
"title": "响应时间 (P95/P99)",
"type": "graph",
"targets": [
{
"expr": "histogram_quantile(0.95, sum(rate(http_server_requests_seconds_bucket[5m])) by (le))",
"legendFormat": "P95"
},
{
"expr": "histogram_quantile(0.99, sum(rate(http_server_requests_seconds_bucket[5m])) by (le))",
"legendFormat": "P99"
}
],
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}
},
{
"id": 3,
"title": "错误率",
"type": "singlestat",
"targets": [
{
"expr": "sum(rate(http_server_requests_seconds_count{status=~\"5..\"}[5m])) / sum(rate(http_server_requests_seconds_count[5m])) * 100",
"legendFormat": "Error Rate %"
}
],
"gridPos": {"h": 4, "w": 6, "x": 0, "y": 8},
"thresholds": "1,5",
"colorValue": true
},
{
"id": 4,
"title": "JVM 内存使用",
"type": "graph",
"targets": [
{
"expr": "jvm_memory_used_bytes{area=\"heap\"}",
"legendFormat": "Used"
},
{
"expr": "jvm_memory_max_bytes{area=\"heap\"}",
"legendFormat": "Max"
}
],
"gridPos": {"h": 8, "w": 12, "x": 6, "y": 8}
},
{
"id": 5,
"title": "线程池状态",
"type": "graph",
"targets": [
{
"expr": "tomcat_threads_busy",
"legendFormat": "Busy Threads"
},
{
"expr": "tomcat_threads_current",
"legendFormat": "Current Threads"
},
{
"expr": "tomcat_threads_max",
"legendFormat": "Max Threads"
}
],
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 12}
}
],
"refresh": "30s",
"time": {
"from": "now-1h",
"to": "now"
}
}
}
6.3 ELK 日志系统
6.3.1 Elasticsearch 配置
# elasticsearch.yml
cluster.name: myapp-logs
node.name: es-node-1
path.data: /usr/share/elasticsearch/data
path.logs: /usr/share/elasticsearch/logs
network.host: 0.0.0.0
http.port: 9200
discovery.type: single-node
xpack.security.enabled: true
xpack.security.enrollment.enabled: false
# 索引生命周期管理(ILM)
PUT _ilm/policy/app-logs-policy
{
"policy": {
"phases": {
"hot": {
"min_age": "0ms",
"actions": {
"rollover": {
"max_size": "50gb",
"max_age": "1d"
},
"set_priority": {
"priority": 100
}
}
},
"warm": {
"min_age": "2d",
"actions": {
"set_priority": {
"priority": 50
},
"shrink": {
"number_of_shards": 1
}
}
},
"cold": {
"min_age": "7d",
"actions": {
"set_priority": {
"priority": 0
},
"freeze": {}
}
},
"delete": {
"min_age": "30d",
"actions": {
"delete": {}
}
}
}
}
}
# 索引模板
PUT _index_template/app-logs-template
{
"index_patterns": ["app-logs-*"],
"template": {
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"index.lifecycle.name": "app-logs-policy",
"index.lifecycle.rollover_alias": "app-logs"
},
"mappings": {
"properties": {
"@timestamp": {"type": "date"},
"level": {"type": "keyword"},
"service": {"type": "keyword"},
"trace_id": {"type": "keyword"},
"span_id": {"type": "keyword"},
"message": {"type": "text"},
"logger": {"type": "keyword"},
"thread": {"type": "keyword"},
"exception": {"type": "text"}
}
}
}
}
6.3.2 Logstash 配置
# logstash.conf
input {
beats {
port => 5044
}
kafka {
bootstrap_servers => "kafka:9092"
topics => ["app-logs"]
group_id => "logstash"
codec => json
}
}
filter {
# 解析 JSON 日志
json {
source => "message"
target => "json_data"
}
# 添加字段
mutate {
add_field => {
"environment" => "production"
"application" => "myapp-backend"
}
rename => {
"json_data" => "log"
}
}
# 解析时间
date {
match => ["[log][timestamp]", "ISO8601", "yyyy-MM-dd HH:mm:ss.SSS"]
target => "@timestamp"
}
# 删除临时字段
mutate {
remove_field => ["message", "host"]
}
# GeoIP 解析
geoip {
source => "[log][client_ip]"
target => "geoip"
}
}
output {
elasticsearch {
hosts => ["elasticsearch:9200"]
index => "app-logs-%{+YYYY.MM.dd}"
user => "elastic"
password => "${ES_PASSWORD}"
}
# 同时输出到 Kafka(用于其他系统消费)
kafka {
bootstrap_servers => "kafka:9092"
topic_id => "processed-logs"
codec => json
}
}
6.3.3 Filebeat 配置
# filebeat.yml
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/myapp/*.log
json.keys_under_root: true
json.add_error_key: true
json.message_key: message
fields:
service: myapp-backend
environment: production
field_under_root: true
- type: container
paths:
- /var/lib/docker/containers/*/*.log
processors:
- add_kubernetes_metadata:
host: ${NODE_NAME}
matchers:
- logs_path:
logs_path: "/var/lib/docker/containers/"
processors:
- add_host_metadata: ~
- add_cloud_metadata: ~
- add_docker_metadata: ~
- add_kubernetes_metadata: ~
output.logstash:
hosts: ["logstash:5044"]
logging.level: info
logging.to_files: true
logging.files:
path: /var/log/filebeat
name: filebeat.log
keepfiles: 7
permissions: 0644
6.4 告警通知集成
6.4.1 Alertmanager 配置
# alertmanager.yml
global:
resolve_timeout: 5m
smtp_smarthost: 'smtp.example.com:587'
smtp_from: 'alertmanager@example.com'
smtp_auth_username: 'alertmanager@example.com'
smtp_auth_password: '${SMTP_PASSWORD}'
slack_api_url: '${SLACK_WEBHOOK_URL}'
route:
group_by: ['alertname', 'severity', 'service']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
receiver: 'default-receiver'
routes:
- match:
severity: critical
receiver: 'critical-alerts'
continue: true
- match:
severity: warning
receiver: 'warning-alerts'
- match:
service: database
receiver: 'dba-team'
receivers:
- name: 'default-receiver'
email_configs:
- to: 'dev-team@example.com'
send_resolved: true
headers:
Subject: '[{{ .Status | toUpper }}] {{ .GroupLabels.alertname }}'
- name: 'critical-alerts'
email_configs:
- to: 'oncall@example.com'
send_resolved: true
html: '{{ template "email.default.html" . }}'
slack_configs:
- channel: '#alerts-critical'
send_resolved: true
title: '{{ template "slack.default.title" . }}'
text: '{{ template "slack.default.text" . }}'
pagerduty_configs:
- service_key: '${PAGERDUTY_SERVICE_KEY}'
send_resolved: true
- name: 'warning-alerts'
email_configs:
- to: 'dev-team@example.com'
send_resolved: true
slack_configs:
- channel: '#alerts-warning'
send_resolved: true
- name: 'dba-team'
email_configs:
- to: 'dba-team@example.com'
send_resolved: true
webhook_configs:
- url: 'http://webhook-service/dba-alerts'
inhibit_rules:
- source_match:
severity: 'critical'
target_match:
severity: 'warning'
equal: ['alertname', 'service']
templates:
- '/etc/alertmanager/templates/*.tmpl'
监控黄金指标(Four Golden Signals):
- 延迟(Latency):处理请求所需的时间
- 流量(Traffic):系统的需求量(QPS、并发连接数)
- 错误(Errors):请求失败的比率
- 饱和度(Saturation):系统资源的利用率(CPU、内存、磁盘)
第 7 章:人机协同机制
7.1 人机协同模式
7.1.1 AI 自主程度分级
| 等级 |
描述 |
适用场景 |
审批要求 |
| L1 - 辅助模式 |
AI 提供建议,人类决策和执行 |
高风险操作、架构设计 |
所有操作需人工确认 |
| L2 - 半自动模式 |
AI 执行常规任务,人类监督 |
代码生成、单元测试 |
关键节点人工确认 |
| L3 - 条件自动模式 |
AI 自主执行,异常时请求人类 |
CI/CD 流水线、监控告警 |
异常情况人工介入 |
| L4 - 高度自动模式 |
AI 完全自主,事后通知人类 |
日志分析、性能优化 |
定期审计报告 |
| L5 - 全自动模式 |
AI 完全自主,无需人类参与 |
简单重复任务 |
无需人工干预 |
7.2 人工介入点设计
7.2.1 必须人工审批的场景
# 需要人工审批的操作清单
1. 生产环境部署
- 新版本上线
- 配置变更
- 数据库迁移
2. 敏感操作
- 删除生产数据
- 修改权限配置
- 访问敏感信息
3. 高风险变更
- 核心服务重启
- 网络配置变更
- 安全策略调整
4. 异常处理
- 严重告警响应
- 系统故障恢复
- 安全事件处置
5. 质量门禁
- Code Review
- 架构评审
- 安全审计
7.2.2 人机交互接口设计
# 飞书机器人集成示例
# 审批请求消息
{
"msg_type": "interactive",
"card": {
"config": {
"wide_screen_mode": true
},
"header": {
"template": "blue",
"title": {
"content": "🔔 部署审批请求",
"tag": "plain_text"
}
},
"elements": [
{
"tag": "div",
"text": {
"tag": "lark_md",
"content": "**应用**: myapp-backend\n**版本**: v1.2.3\n**环境**: 生产环境\n**变更内容**: 新增用户管理功能\n**影响范围**: 用户服务模块"
}
},
{
"tag": "div",
"text": {
"tag": "lark_md",
"content": "**风险提示**: \n- 数据库 schema 变更\n- API 接口不兼容旧版本"
}
},
{
"tag": "action",
"actions": [
{
"tag": "button",
"text": {
"tag": "plain_text",
"content": "✅ 批准部署"
},
"type": "primary",
"value": {
"action": "approve_deployment",
"build_id": "12345",
"approver": "${user_id}"
}
},
{
"tag": "button",
"text": {
"tag": "plain_text",
"content": "❌ 拒绝部署"
},
"type": "danger",
"value": {
"action": "reject_deployment",
"build_id": "12345",
"approver": "${user_id}"
}
},
{
"tag": "button",
"text": {
"tag": "plain_text",
"content": "📝 查看详情"
},
"type": "default",
"url": "http://jenkins.example.com/job/myapp/12345"
}
]
}
]
}
}
# 告警通知消息
{
"msg_type": "interactive",
"card": {
"header": {
"template": "red",
"title": {
"content": "🚨 严重告警",
"tag": "plain_text"
}
},
"elements": [
{
"tag": "div",
"text": {
"tag": "lark_md",
"content": "**告警名称**: ApplicationDown\n**告警级别**: Critical\n**发生时间**: 2026-03-14 09:15:00\n**影响服务**: myapp-backend\n**实例**: 192.168.1.100:8080"
}
},
{
"tag": "action",
"actions": [
{
"tag": "button",
"text": {
"tag": "plain_text",
"content": "📊 查看监控"
},
"url": "http://grafana.example.com/d/app-monitor"
},
{
"tag": "button",
"text": {
"tag": "plain_text",
"content": "📝 查看日志"
},
"url": "http://kibana.example.com"
},
{
"tag": "button",
"text": {
"tag": "plain_text",
"content": "🔧 执行预案"
},
"value": {
"action": "execute_runbook",
"runbook_id": "app-down-001"
}
}
]
}
]
}
}
7.3 上下文管理
7.3.1 长期记忆机制
# OpenClaw 工作区记忆文件结构
~/.openclaw/workspace/
├── AGENTS.md # 指令说明
├── USER.md # 用户偏好设置
├── MEMORY.md # 长期记忆
├── HEARTBEAT.md # 检查清单
├── SOUL.md # 人格/语气
├── IDENTITY.md # 名称/主题
└── BOOT.md # 启动配置
# MEMORY.md 示例
## 项目上下文
- 项目名称:myapp
- 技术栈:Spring Boot + React + PostgreSQL
- 团队规模:5 人
- 开发周期:2026.01 - 2026.06
## 架构决策记录(ADR)
### ADR-001: 选择 PostgreSQL 作为主数据库
- 日期:2026-01-15
- 状态:已接受
- 决策者:张三
- 原因:支持 JSON 类型、优秀的并发性能
### ADR-002: 采用微服务架构
- 日期:2026-01-20
- 状态:已接受
- 决策者:李四
- 原因:业务复杂度高、需要独立扩展
## 技术债务
- TODO: 重构用户服务的认证逻辑
- TODO: 优化订单查询的 N+1 问题
- FIXME: 支付回调的幂等性处理不完善
## 重要约定
- API 版本前缀:/api/v1/
- 代码规范:遵循阿里巴巴 Java 开发手册
- Git 分支策略:Git Flow
7.4 反馈学习机制
7.4.1 人类反馈强化学习(RLHF)
# 反馈收集机制
1. 代码审查反馈
- 接受/拒绝 AI 生成的代码
- 修改意见记录
- 质量评分(1-5 星)
2. 决策反馈
- 审批通过/拒绝
- 替代方案记录
- 决策理由说明
3. 结果反馈
- 部署成功/失败
- 性能指标对比
- 用户满意度调查
4. 主动学习
- 不确定性采样
- 多样性采样
- 基于错误的学习
# 反馈数据存储
{
"feedback_id": "fb-12345",
"timestamp": "2026-03-14T09:25:00Z",
"agent_id": "backend-dev-agent",
"task_type": "code_generation",
"input": {
"requirement": "实现用户注册接口",
"context": {...}
},
"output": {
"code": "...",
"tests": "..."
},
"feedback": {
"rating": 4,
"accepted": true,
"modifications": ["添加了参数校验", "优化了异常处理"],
"comments": "整体质量不错,需要加强输入验证",
"reviewer": "zhangsan"
},
"outcome": {
"deployed": true,
"bugs_found": 0,
"performance_impact": "none"
}
}
人机协同最佳实践:
- 明确界定 AI 和人类的职责边界
- 建立透明的决策机制和可解释性
- 保持人类对关键决策的最终控制权
- 持续收集反馈优化 AI 行为
- 定期审查 AI 的表现和安全性
- 培养团队的 AI 协作能力(AI Coding Fluency)
第 8 章:应急响应与故障处理
8.1 应急响应流程
8.1.1 事件分级
| 级别 |
定义 |
响应时间 |
升级路径 |
| P0 - 灾难级 |
核心服务完全不可用,大面积用户受影响 |
立即响应(< 5 分钟) |
CTO + 全体技术团队 |
| P1 - 严重级 |
核心功能严重受损,部分用户受影响 |
15 分钟内 |
技术总监 + 相关团队 |
| P2 - 高级 |
非核心功能故障,用户体验下降 |
1 小时内 |
团队负责人 |
| P3 - 中级 |
轻微问题,不影响主要功能 |
4 小时内 |
值班工程师 |
| P4 - 低级 |
cosmetic 问题,建议性改进 |
24 小时内 |
普通工程师 |
8.1.2 应急响应流程
# 标准应急响应流程(Incident Response)
## Phase 1: 检测与识别(Detection)
1. 监控系统触发告警
2. 值班工程师确认告警真实性
3. 初步评估影响范围和严重程度
4. 确定事件级别(P0-P4)
## Phase 2: 响应与通报(Response)
1. 启动应急预案(Runbook)
2. 召集应急响应团队(ERT)
3. 指定事件指挥官(Incident Commander)
4. 建立沟通渠道(战时会议室)
5. 通知相关干系人
## Phase 3: 诊断与定位(Diagnosis)
1. 收集故障现象和日志
2. 分析监控指标和链路追踪
3. 复现问题(如果可能)
4. 定位根本原因
5. 评估修复方案
## Phase 4: 修复与恢复(Recovery)
1. 执行修复方案
- 回滚到上一个稳定版本
- 热修复(Hotfix)
- 切换备用系统
- 限流降级
2. 验证修复效果
3. 逐步恢复服务
4. 持续监控稳定性
## Phase 5: 复盘与改进(Post-Mortem)
1. 召开事后复盘会议(24-48 小时内)
2. 编写事故报告(Post-Mortem Report)
3. 制定改进行动计划(Action Items)
4. 跟踪落实改进措施
5. 更新应急预案和监控
8.2 常见故障应急预案
8.2.1 应用宕机应急预案
# Runbook: APP-DOWN-001 - 应用实例宕机
## 症状
- Prometheus 告警:ApplicationDown
- Grafana 显示实例离线
- 用户报告服务不可用
## 自动检测
```bash
# 检查 Pod 状态
kubectl get pods -n production -l app=myapp-backend
# 查看 Pod 事件
kubectl describe pod myapp-backend-xxx -n production
# 查看最后日志
kubectl logs myapp-backend-xxx -n production --tail=100
```
## 手动诊断
```bash
# 检查节点状态
kubectl get nodes
# 检查资源使用
kubectl top pods -n production
# 检查 Events
kubectl get events -n production --sort-by='.lastTimestamp'
```
## 恢复步骤
### 方案 A: 重启 Pod(适用于临时故障)
```bash
kubectl delete pod myapp-backend-xxx -n production
# Deployment 会自动创建新 Pod
```
### 方案 B: 回滚版本(适用于新版本 Bug)
```bash
kubectl rollout undo deployment/myapp-backend -n production
# 或回滚到特定版本
kubectl rollout undo deployment/myapp-backend --to-revision=2 -n production
```
### 方案 C: 扩容(适用于资源不足)
```bash
kubectl scale deployment myapp-backend --replicas=5 -n production
```
### 方案 D: 切换流量(适用于严重故障)
```bash
# 如果有蓝绿部署
kubectl patch service myapp-backend -n production \
-p '{"spec":{"selector":{"version":"green"}}}'
```
## 验证
```bash
# 检查 Pod 就绪状态
kubectl rollout status deployment/myapp-backend -n production
# 健康检查
curl http://myapp-backend-service/actuator/health
# 查看监控指标
# 访问 Grafana Dashboard
```
## 升级条件
- 5 分钟内无法恢复 → 升级为 P1 事件
- 影响核心功能 → 立即通知技术总监
- 数据丢失风险 → 立即通知 CTO
8.2.2 数据库故障应急预案
# Runbook: DB-DOWN-001 - 数据库不可用
## 症状
- 应用日志出现大量数据库连接错误
- Prometheus 告警:DatabaseConnectionPoolExhausted
- 用户报告数据相关功能失败
## 快速诊断
```bash
# 检查数据库 Pod
kubectl get pods -n production -l app=postgres
# 检查数据库连接
psql -h postgres-service -U admin -d myapp -c "SELECT 1"
# 查看慢查询
psql -h postgres-service -U admin -d myapp \
-c "SELECT * FROM pg_stat_activity WHERE state != 'idle'"
# 检查锁等待
psql -h postgres-service -U admin -d myapp \
-c "SELECT * FROM pg_locks WHERE NOT granted"
```
## 恢复步骤
### 方案 A: 重启数据库(谨慎使用)
```bash
kubectl rollout restart statefulset/postgres -n production
```
### 方案 B: 切换到只读副本
```bash
# 修改应用配置指向只读副本
kubectl set env deployment/myapp-backend \
DB_HOST=postgres-read-replica -n production
kubectl rollout restart deployment/myapp-backend -n production
```
### 方案 C: 从备份恢复(最后手段)
```bash
# 找到最近的备份
ls -lt /backups/postgres/
# 恢复数据
pg_restore -h postgres-service -U admin -d myapp \
/backups/postgres/latest.dump
# 注意:这会导致数据丢失到备份时间点
```
## 数据一致性检查
```bash
# 检查表完整性
psql -h postgres-service -U admin -d myapp \
-c "SELECT schemaname, tablename FROM pg_tables"
# 检查外键约束
psql -h postgres-service -U admin -d myapp \
-c "SELECT * FROM information_schema.table_constraints WHERE constraint_type = 'FOREIGN KEY'"
```
## 预防措施
- 配置主从复制和高可用
- 定期备份验证
- 监控连接池和慢查询
- 设置合理的超时和重试机制
8.2.3 安全事件应急预案
# Runbook: SEC-BREACH-001 - 安全漏洞/入侵事件
## 症状
- 异常流量模式
- 未经授权的访问尝试
- 数据泄露告警
- 安全扫描发现漏洞
## 立即行动(Containment)
### 1. 隔离受影响系统
```bash
# 切断外部访问
kubectl patch svc myapp-backend -n production \
-p '{"spec":{"type":"ClusterIP"}}'
# 或者使用 NetworkPolicy
kubectl apply -f emergency-network-policy.yaml
```
### 2. 保存证据
```bash
# 导出日志
kubectl logs myapp-backend-xxx -n production > incident-logs.txt
# 保存容器快照
docker export $(docker ps -q | grep myapp) > container-snapshot.tar
# 导出数据库审计日志
pg_dump -h postgres-service -U admin myapp_audit > audit_backup.sql
```
### 3. 重置凭证
```bash
# 轮换所有密钥
kubectl create secret generic myapp-secret \
--from-literal=db-password=$(openssl rand -base64 32) \
--dry-run=client -o yaml | kubectl apply -f -
# 通知 Vault 撤销旧凭证
vault token revoke -self
```
## 调查与根因分析
1. 分析访问日志和审计日志
2. 追踪攻击路径
3. 确定受影响范围
4. 识别漏洞类型(SQL 注入、XSS、未授权访问等)
## 修复与加固
1. 修补安全漏洞
2. 更新 WAF 规则
3. 加强访问控制
4. 部署额外监控
## 通知与合规
1. 通知法务和合规团队
2. 评估是否需要监管报告
3. 准备用户通知(如果需要)
4. 联系网络安全保险公司
## 事后改进
1. 全面安全审计
2. 渗透测试
3. 安全培训
4. 更新安全策略
8.3 灾备与业务连续性
8.3.1 备份策略
# 数据库备份配置(PostgreSQL)
# 使用 pgBackRest 进行备份
apiVersion: v1
kind: ConfigMap
metadata:
name: pgbackrest-config
namespace: production
data:
pgbackrest.conf: |
[global]
repo1-path=/var/lib/pgbackrest
repo1-retention-full=2
repo1-retention-diff=7
compress-type=gzip
[myapp]
process-max=4
label-system-info=y
backup-standby=y
# 全量备份:每周日凌晨 2 点
# 差异备份:每天凌晨 2 点
# WAL 归档:实时
# 备份 CronJob
apiVersion: batch/v1
kind: CronJob
metadata:
name: postgres-backup
namespace: production
spec:
schedule: "0 2 * * *" # 每天凌晨 2 点
jobTemplate:
spec:
template:
spec:
containers:
- name: pgbackrest
image: pgbackrest/pgbackrest:latest
command:
- pgbackrest
- --stanza=myapp
- backup
- --type=full
env:
- name: PGBACKREST_REPO1_PATH
value: /backup
volumeMounts:
- name: backup-storage
mountPath: /backup
- name: pgbackrest-config
mountPath: /etc/pgbackrest
restartPolicy: OnFailure
volumes:
- name: backup-storage
persistentVolumeClaim:
claimName: backup-pvc
- name: pgbackrest-config
configMap:
name: pgbackrest-config
# 备份验证 Job
apiVersion: batch/v1
kind: CronJob
metadata:
name: backup-verification
namespace: production
spec:
schedule: "0 6 * * 0" # 每周日早上 6 点
jobTemplate:
spec:
template:
spec:
containers:
- name: verify-backup
image: postgres:15
command:
- /bin/sh
- -c
- |
pg_restore --list /backup/latest.dump > /dev/null && \
echo "Backup verification successful" || \
echo "Backup verification failed"
restartPolicy: Never
8.3.2 灾难恢复计划(DRP)
# 灾难恢复计划大纲
## 1. 恢复目标
- RTO(恢复时间目标): 4 小时
- RPO(恢复点目标): 15 分钟
## 2. 灾难场景
### 场景 A: 单数据中心故障
- 影响:部分服务中断
- 响应:自动故障转移到备用数据中心
### 场景 B: 区域级灾难
- 影响:整个区域不可用
- 响应:启用异地灾备中心
### 场景 C: 数据损坏/丢失
- 影响:数据不一致或丢失
- 响应:从备份恢复
## 3. 恢复步骤
### Phase 1: 评估与决策(0-30 分钟)
1. 确认灾难范围和影响
2. 评估恢复选项
3. 决策是否启动 DRP
4. 通知应急团队
### Phase 2: 启动灾备中心(30-120 分钟)
1. 激活备用基础设施
2. 恢复最新备份
3. 验证数据完整性
4. 启动应用服务
### Phase 3: 流量切换(120-180 分钟)
1. 更新 DNS 记录
2. 切换负载均衡器
3. 验证服务可用性
4. 监控稳定性
### Phase 4: 恢复正常运营(180-240 分钟)
1. 确认服务稳定
2. 通知用户和业务方
3. 开始主数据中心修复
4. 计划回切流程
## 4. 演练计划
- 每季度进行一次桌面演练
- 每半年进行一次技术演练
- 每年进行一次全链路演练
## 5. 联系人清单
| 角色 | 姓名 | 电话 | 邮箱 |
|------|------|------|------|
| 事件指挥官 | 张三 | 138-xxxx | zhangsan@example.com |
| 技术负责人 | 李四 | 139-xxxx | lisi@example.com |
| DBA | 王五 | 137-xxxx | wangwu@example.com |
| 安全负责人 | 赵六 | 136-xxxx | zhaoliu@example.com |
应急响应黄金法则:
- 先恢复,后诊断:优先恢复服务,再分析根因
- 沟通优先:保持信息透明,及时通报进展
- 记录一切:详细记录所有操作和时间线
- 不要单打独斗:召集团队,分工协作
- 避免二次伤害:谨慎操作,避免雪上加霜
- 事后必复盘:每次事件都要有改进措施
第 9 章:最佳实践与案例
9.1 AI Coding 最佳实践
9.1.1 提示词工程(Prompt Engineering)
# 高质量代码生成提示词模板
## 模板 1: 功能实现
"""
你是一位资深 Java 后端开发工程师。请根据以下需求实现代码:
【需求描述】
实现一个用户注册接口,包含以下功能:
1. 接收用户名、邮箱、密码参数
2. 参数校验(用户名 3-50 字符,邮箱格式,密码至少 8 位)
3. 检查用户名和邮箱是否已存在
4. 密码加密存储(BCrypt)
5. 发送欢迎邮件
6. 返回用户 ID
【技术要求】
- 使用 Spring Boot 3.x
- 遵循 RESTful API 规范
- 使用 DTO 接收参数
- 全局异常处理
- 添加完整的单元测试
- 代码符合阿里巴巴 Java 开发手册
【项目上下文】
- 包路径:com.example.myapp.user
- 已有实体:User, CreateUserRequest
- 已有服务:UserService, EmailService
- 已有仓库:UserRepository
请生成完整的 Controller、Service 实现和测试代码。
"""
## 模板 2: 代码审查
"""
你是一位资深代码审查专家。请审查以下代码:
【审查要点】
1. 代码规范和可读性
2. 潜在 Bug 和空指针风险
3. 性能问题和优化建议
4. 安全漏洞(SQL 注入、XSS 等)
5. 异常处理是否完善
6. 测试覆盖率
【代码】
[Paste code here]
请以结构化格式输出审查结果:
- ✅ 优点
- ⚠️ 需要改进
- ❌ 严重问题
- 💡 优化建议
"""
## 模板 3: Bug 修复
"""
你是一位调试专家。请帮助修复以下 Bug:
【问题描述】
用户在高并发场景下偶尔收到 500 错误
【错误日志】
org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections
【当前配置】
- HikariCP 最大连接数:20
- PostgreSQL max_connections: 100
- 应用实例数:5
【分析要求】
1. 分析根本原因
2. 提供短期和长期解决方案
3. 给出具体配置参数
4. 说明权衡取舍
请提供详细的分析和修复方案。
"""
9.2 性能优化案例
9.2.1 数据库性能优化
# 案例:订单查询性能优化
## 问题
订单列表接口 P95 响应时间 3 秒,用户投诉严重
## 分析过程
1. 使用 APM 工具定位慢查询
2. EXPLAIN 分析 SQL 执行计划
3. 发现 N+1 查询问题
4. 缺少合适索引
## 原始代码(有问题)
```java
// N+1 查询问题
List orders = orderRepository.findAllByUserId(userId);
for (Order order : orders) {
// 每次循环都查询数据库
User buyer = userRepository.findById(order.getBuyerId());
List items = orderItemRepository.findByOrderId(order.getId());
order.setBuyer(buyer);
order.setItems(items);
}
```
## 优化方案
```java
// 使用 JOIN FETCH 一次性加载
@Query("SELECT o FROM Order o " +
"JOIN FETCH o.buyer b " +
"JOIN FETCH o.items i " +
"WHERE o.userId = :userId")
List findAllWithDetails(@Param("userId") String userId);
// 添加复合索引
CREATE INDEX idx_orders_user_created
ON orders(user_id, created_at DESC);
// 添加覆盖索引
CREATE INDEX idx_order_items_order_id
ON order_items(order_id) INCLUDE (product_id, quantity, price);
```
## 优化效果
- P95 响应时间:3000ms → 150ms
- 数据库查询次数:N+1 → 1
- 吞吐量提升:20 倍
9.3 监控告警优化案例
9.3.1 告警疲劳治理
# 问题:每天收到 500+ 告警,团队产生告警疲劳
## 治理措施
### 1. 告警分级
- Critical: 立即响应(电话通知)
- Warning: 工作时间处理(IM 通知)
- Info: 记录即可(无需通知)
### 2. 告警聚合
```yaml
# Alertmanager 分组配置
route:
group_by: ['alertname', 'severity', 'service']
group_wait: 30s # 等待 30 秒收集同组告警
group_interval: 5m # 5 分钟内的同组告警合并
repeat_interval: 4h # 4 小时内不重复通知
```
### 3. 抑制规则
```yaml
# 避免告警风暴
inhibit_rules:
# 如果服务宕机,抑制该服务的所有其他告警
- source_match:
alertname: ApplicationDown
target_match_re:
alertname: ".*"
equal: ['service']
# 如果机房网络故障,抑制该机房所有告警
- source_match:
alertname: DatacenterNetworkDown
target_match_re:
alertname: ".*"
equal: ['datacenter']
```
### 4. 动态阈值
```promql
# 使用预测算法代替固定阈值
# 预测未来 1 小时磁盘使用率
predict_linear(node_filesystem_avail_bytes[6h], 3600) < 0
# 使用同比环比检测异常
# 当前 QPS 相比上周同期下降超过 50%
sum(rate(http_requests_total[5m])) <
sum(rate(http_requests_total[5m] offset 1w)) * 0.5
```
## 效果
- 日均告警数量:500+ → 20-
- 告警准确率:60% → 95%
- 平均响应时间:30 分钟 → 5 分钟
9.4 安全加固案例
9.4.1 零信任架构实施
# 案例:从零开始构建零信任安全架构
## 背景
传统边界防护无法应对内部威胁和横向移动攻击
## 实施步骤
### Phase 1: 身份为中心
1. 实施强身份认证(MFA)
2. 基于角色的访问控制(RBAC)
3. 最小权限原则
4. 会话管理和超时
### Phase 2: 设备可信
1. 设备注册和认证
2. 设备健康检查
3. 合规性验证
4. 不安全设备隔离
### Phase 3: 网络微隔离
```yaml
# Kubernetes NetworkPolicy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-isolation
namespace: production
spec:
podSelector:
matchLabels:
app: myapp-backend
policyTypes:
- Ingress
- Egress
ingress:
# 只允许前端访问
- from:
- podSelector:
matchLabels:
app: myapp-frontend
ports:
- protocol: TCP
port: 8080
egress:
# 只允许访问数据库和缓存
- to:
- podSelector:
matchLabels:
app: postgres
ports:
- protocol: TCP
port: 5432
- to:
- podSelector:
matchLabels:
app: redis
ports:
- protocol: TCP
port: 6379
```
### Phase 4: 持续验证
1. 实时风险评估
2. 行为分析
3. 异常检测
4. 自适应访问控制
## 效果
- 安全事件减少:80%
- 横向移动攻击阻断:100%
- 合规审计通过率:100%
9.5 成本优化案例
9.5.1 云资源成本优化
# 案例:月度云资源成本从 10 万降至 6 万
## 优化措施
### 1. 资源右尺寸(Right Sizing)
```bash
# 分析实际资源使用
kubectl top pods --all-namespaces
# 根据实际使用调整资源配置
resources:
requests:
memory: "256Mi" # 从 512Mi 降低
cpu: "100m" # 从 250m 降低
limits:
memory: "512Mi"
cpu: "200m"
```
### 2. 自动扩缩容
```yaml
# 配置 HPA
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: myapp-hpa
spec:
minReplicas: 2 # 从 3 降低
maxReplicas: 10 # 从 20 降低
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # 避免频繁伸缩
```
### 3. 使用 Spot 实例
```yaml
# 混合使用按需和 Spot 实例
# 核心服务:按需实例(保证稳定性)
# 无状态服务:Spot 实例(节省成本)
# 配置节点池
- name: spot-pool
preemptible: true
maxPrice: 0.05
minNodes: 0
maxNodes: 10
```
### 4. 存储优化
- 冷热数据分层
- 启用生命周期管理
- 清理无用镜像和快照
### 5. 预留实例
- 对稳定负载购买 RI
- 1 年期 vs 3 年期对比
- 可转换 RI 增加灵活性
## 成本对比
| 项目 | 优化前 | 优化后 | 节省 |
|------|--------|--------|------|
| 计算资源 | ¥60,000 | ¥35,000 | 42% |
| 存储 | ¥25,000 | ¥15,000 | 40% |
| 网络 | ¥15,000 | ¥10,000 | 33% |
| **总计** | **¥100,000** | **¥60,000** | **40%** |
## 注意事项
- 成本优化不能以牺牲稳定性为代价
- 持续监控性能和成本指标
- 建立成本责任制(FinOps)
持续改进文化:
- 每周技术分享会
- 每月复盘会议
- 季度架构评审
- 年度技术规划
- 鼓励试错和创新
- 知识沉淀和文档化
📚 附录
附录 A:常用命令速查
# Kubernetes 常用命令
kubectl get pods -n
kubectl describe pod -n
kubectl logs -n [-f] [--tail=100]
kubectl exec -it -n -- /bin/bash
kubectl apply -f
kubectl delete -f
kubectl rollout status deployment/
kubectl rollout undo deployment/
kubectl scale deployment/ --replicas=
kubectl top pods/nodes
# Docker 常用命令
docker ps [-a]
docker images
docker build -t .
docker run -d -p :
docker logs [-f]
docker exec -it /bin/bash
docker-compose up -d
docker-compose down
# Jenkins 常用操作
# 重启 Jenkins
systemctl restart jenkins
# 查看日志
tail -f /var/log/jenkins/jenkins.log
# 备份配置
cp -r /var/lib/jenkins /backup/jenkins-$(date +%Y%m%d)
# Prometheus 查询示例
# QPS
sum(rate(http_requests_total[1m]))
# P95 响应时间
histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
# 错误率
sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))
# 内存使用率
jvm_memory_used_bytes{area="heap"} / jvm_memory_max_bytes{area="heap"}
# OpenClaw 常用命令
openclaw status
openclaw gateway start/stop/restart
openclaw onboard
openclaw doctor
openclaw dashboard
clawhub search/install/update
附录 B:参考资源
附录 C:术语表
| 术语 |
英文全称 |
解释 |
| AI Agent |
Artificial Intelligence Agent |
人工智能代理,能够感知环境并采取行动的自主系统 |
| CI/CD |
Continuous Integration/Continuous Deployment |
持续集成/持续部署 |
| RTO |
Recovery Time Objective |
恢复时间目标,业务中断后允许的最大停机时间 |
| RPO |
Recovery Point Objective |
恢复点目标,业务中断后允许的最大数据丢失量 |
| SLA |
Service Level Agreement |
服务级别协议,定义服务提供商和客户之间的服务质量承诺 |
| SLO |
Service Level Objective |
服务级别目标,具体的、可衡量的服务质量指标 |
| MTTR |
Mean Time To Recovery |
平均恢复时间,从故障发生到恢复服务的平均时间 |
| MTBF |
Mean Time Between Failures |
平均故障间隔时间,系统两次故障之间的平均时间 |