Jenkins入门教程(十九):Jenkins性能优化与监控

随着使用规模增长,Jenkins可能出现性能问题。本文将详细介绍Jenkins的性能优化和监控方法,包括完整的配置示例和诊断命令。

JVM调优

查看当前JVM配置

# 查看Jenkins进程的JVM参数
ps aux | grep jenkins | grep java

# 输出示例
jenkins  12345  5.0 15.0 4096000 1536000 ?  Ssl  12:00  10:30 /usr/bin/java \
    -Djava.awt.headless=true \
    -Xmx1g \
    -jar /usr/share/java/jenkins.war

# 查看更详细的JVM信息
jinfo -flags 12345

优化JVM参数

# 编辑Jenkins配置文件
sudo vim /etc/default/jenkins  # Debian/Ubuntu
# 或
sudo vim /etc/sysconfig/jenkins  # CentOS/RHEL

# 推荐的JVM配置(根据服务器内存调整)
JAVA_ARGS="\
    -Xms2g \
    -Xmx4g \
    -XX:+UseG1GC \
    -XX:MaxGCPauseMillis=200 \
    -XX:+ParallelRefProcEnabled \
    -XX:+DisableExplicitGC \
    -XX:+HeapDumpOnOutOfMemoryError \
    -XX:HeapDumpPath=/var/lib/jenkins/heapdump.hprof \
    -Djava.awt.headless=true \
    -Djenkins.install.runSetupWizard=false"

# 配置说明
# -Xms2g            : 初始堆内存2GB
# -Xmx4g            : 最大堆内存4GB(建议为物理内存的50-70%)
# -XX:+UseG1GC      : 使用G1垃圾收集器(推荐)
# -XX:MaxGCPauseMillis=200 : GC暂停时间目标200ms

# 重启Jenkins
sudo systemctl restart jenkins

# 验证配置
ps aux | grep jenkins

Docker部署的JVM配置

# docker-compose.yml
version: '3.8'
services:
  jenkins:
    image: jenkins/jenkins:lts
    environment:
      - JAVA_OPTS=-Xms2g -Xmx4g -XX:+UseG1GC -XX:MaxGCPauseMillis=200
    deploy:
      resources:
        limits:
          memory: 6G
        reservations:
          memory: 4G
    volumes:
      - jenkins_home:/var/jenkins_home
    ports:
      - "8080:8080"
      - "50000:50000"

减少Master负载

# 将Master执行器数量设为0
# 系统管理 > 节点管理 > 配置主节点
# 执行器数量: 0

# 所有构建任务在Agent上执行
pipeline {
    agent {
        label 'build-agent'  // 不使用master
    }
    stages {
        stage('Build') {
            steps {
                sh 'make build'
            }
        }
    }
}

清理策略

构建历史清理

# Pipeline中配置构建保留策略
pipeline {
    agent any
    
    options {
        buildDiscarder(logRotator(
            numToKeepStr: '10',          // 保留最近10个构建
            artifactNumToKeepStr: '5',   // 保留5个构建的产物
            daysToKeepStr: '30'          // 保留30天
        ))
    }
    
    stages {
        stage('Build') {
            steps {
                sh 'make build'
            }
        }
    }
}

# 批量清理旧构建(Groovy脚本)
# 系统管理 > 脚本命令行
jenkins.model.Jenkins.instance.allItems(Job.class).each { job ->
    println "Processing: ${job.fullName}"
    def builds = job.builds
    def toDelete = builds.drop(10)  // 保留最近10个
    toDelete.each { build ->
        println "  Deleting: ${build.displayName}"
        build.delete()
    }
}

工作空间清理

# Pipeline中自动清理工作空间
pipeline {
    agent any
    
    options {
        skipDefaultCheckout()  // 跳过默认checkout
    }
    
    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        stage('Build') {
            steps {
                sh 'make build'
            }
        }
    }
    
    post {
        always {
            cleanWs()  // 清理工作空间
        }
    }
}

# 定时清理工作空间脚本
#!/bin/bash
WORKSPACE_DIR="/var/lib/jenkins/workspace"
DAYS_OLD=7

echo "Cleaning workspaces older than ${DAYS_OLD} days..."

find ${WORKSPACE_DIR} -maxdepth 1 -type d -mtime +${DAYS_OLD} | while read dir; do
    echo "Removing: $dir"
    rm -rf "$dir"
done

# 显示清理后的空间
echo "Workspace size after cleanup:"
du -sh ${WORKSPACE_DIR}

# 添加到crontab
# 0 2 * * * /opt/scripts/cleanup-workspace.sh >> /var/log/jenkins-cleanup.log 2>&1

插件管理

# 查看已安装插件数量
curl -s -u admin:token "http://localhost:8080/pluginManager/api/json?depth=1" | \
    jq '.plugins | length'
# 输出: 87

# 查看占用内存最多的插件(需要安装Metrics插件)
# 系统管理 > 系统信息 > 插件

# 禁用不需要的插件
# 系统管理 > 插件管理 > 已安装 > 选择插件 > 禁用

# 卸载未使用的插件
java -jar jenkins-cli.jar -s http://localhost:8080/ -auth admin:token \
    disable-plugin plugin-name

java -jar jenkins-cli.jar -s http://localhost:8080/ -auth admin:token \
    uninstall-plugin plugin-name

优化Pipeline

# 1. 使用并行执行
stage('Test') {
    parallel {
        stage('Unit') { steps { sh 'make test-unit' } }
        stage('Integration') { steps { sh 'make test-integration' } }
        stage('E2E') { steps { sh 'make test-e2e' } }
    }
}

# 2. 使用缓存
agent {
    docker {
        image 'maven:3.8-openjdk-17'
        args '-v $HOME/.m2:/root/.m2'  // Maven缓存
    }
}

# 3. 浅克隆大型仓库
checkout([
    $class: 'GitSCM',
    extensions: [
        [$class: 'CloneOption', depth: 1, shallow: true, noTags: true]
    ],
    ...
])

# 4. 避免在Pipeline中执行复杂Groovy
// 不推荐
script {
    def result = []
    for (int i = 0; i < 1000; i++) {
        result << someExpensiveOperation(i)
    }
}

// 推荐:将复杂逻辑放在shell脚本中
sh './scripts/complex-operation.sh'

监控配置

安装Metrics插件

# 安装Prometheus Metrics插件
# 系统管理 > 插件管理 > 搜索 "Prometheus metrics"

# 访问指标端点
curl http://localhost:8080/prometheus/

# 输出示例
# HELP jenkins_builds_total Total builds
# TYPE jenkins_builds_total counter
jenkins_builds_total{result="SUCCESS"} 1234
jenkins_builds_total{result="FAILURE"} 56
jenkins_builds_total{result="UNSTABLE"} 12

# HELP jenkins_job_duration_seconds Job duration
# TYPE jenkins_job_duration_seconds histogram
jenkins_job_duration_seconds_bucket{job="my-job",le="60"} 100
jenkins_job_duration_seconds_bucket{job="my-job",le="300"} 150

# HELP jenkins_queue_size Current queue size
# TYPE jenkins_queue_size gauge
jenkins_queue_size 5

# HELP jenkins_executors_available Available executors
# TYPE jenkins_executors_available gauge
jenkins_executors_available 10

Prometheus配置

# prometheus.yml
scrape_configs:
  - job_name: 'jenkins'
    metrics_path: '/prometheus'
    static_configs:
      - targets: ['jenkins:8080']
    basic_auth:
      username: 'prometheus'
      password: 'your-api-token'

Grafana仪表盘

# 导入Jenkins仪表盘模板
# https://grafana.com/grafana/dashboards/9964-jenkins-performance-and-health-overview/

# 关键监控指标
- jenkins_queue_size              # 队列长度
- jenkins_executors_available     # 可用执行器
- jenkins_executors_busy          # 繁忙执行器
- jenkins_node_online             # 节点在线状态
- jenkins_builds_total            # 构建总数
- jenkins_builds_duration_seconds # 构建时长
- jvm_memory_used_bytes           # JVM内存使用
- jvm_gc_collection_seconds_sum   # GC时间

性能诊断

# 查看系统资源使用
echo "=== CPU Usage ==="
top -bn1 | head -20

echo "\n=== Memory Usage ==="
free -h

echo "\n=== Disk Usage ==="
df -h /var/lib/jenkins

echo "\n=== Jenkins Workspace Size ==="
du -sh /var/lib/jenkins/workspace

echo "\n=== Jenkins Builds Size ==="
du -sh /var/lib/jenkins/jobs/*/builds | sort -h | tail -10

# 查看Jenkins线程
jstack $(pgrep -f jenkins) > /tmp/jenkins-threads.txt
grep -c "java.lang.Thread.State" /tmp/jenkins-threads.txt
# 输出: 156 (线程数)

# 查看GC日志
tail -f /var/log/jenkins/gc.log

# 生成堆转储(内存分析)
jmap -dump:format=b,file=/tmp/jenkins-heap.hprof $(pgrep -f jenkins)

性能告警

# Prometheus告警规则
groups:
  - name: jenkins
    rules:
      - alert: JenkinsQueueTooLong
        expr: jenkins_queue_size > 10
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Jenkins队列过长"
          description: "队列中有 {{ $value }} 个任务等待"
      
      - alert: JenkinsNoExecutors
        expr: jenkins_executors_available == 0
        for: 10m
        labels:
          severity: critical
        annotations:
          summary: "Jenkins没有可用执行器"
          description: "所有执行器都在繁忙状态"
      
      - alert: JenkinsHighMemory
        expr: jvm_memory_used_bytes / jvm_memory_max_bytes > 0.9
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Jenkins内存使用过高"
          description: "内存使用率: {{ $value | humanizePercentage }}"

优化检查清单

# Jenkins性能优化检查清单

[ ] JVM堆内存配置合理(物理内存的50-70%)
[ ] 使用G1垃圾收集器
[ ] Master执行器数量设为0
[ ] 构建保留策略已配置
[ ] 定期清理工作空间
[ ] 禁用不需要的插件
[ ] Pipeline使用并行执行
[ ] 使用浅克隆大型仓库
[ ] 配置了监控和告警
[ ] 定期检查磁盘空间

总结

本文详细介绍了Jenkins的性能优化方法,包括JVM调优、清理策略、Pipeline优化和监控配置。良好的运维可以保证Jenkins稳定高效运行。

下一篇我们将总结Jenkins的最佳实践。

发表回复

后才能评论