提升 CI/CD 稳定性:Jenkins 开机自检与推送通知

简介:Jenkins 是一个广泛使用的开源自动化服务器,常用于持续集成和持续交付。在某些情况下,服务器重启可能导致 Jenkins 构建任务中断或失败。为了解决这个问题,可以使用一个自检服务,定期检查系统的启动时间,并在服务器重启时通过消息推送进行通知。本文将介绍如何实现这样的开机自检机制。

历史攻略:

定时任务:Jenkins

Jenkins:高效卸载和安装

Jenkins:控制台中文乱码问题处理

centos7:docker快速安装jenkins

python:消息推送 - 飞书机器人推送

python:消息推送 - 企业微信机器人推送

python:消息推送 - 发邮件(网易163邮箱为例)

python:消息推送 - 发送短信(以聚合数据为例)

python:消息推送 - 钉钉机器人推送(关键字模式)

python:消息推送 - 企业微信机器人推送

一、Jenkins 自检的基本特性

系统启动时间检测:实时获取系统的启动时间。

推送通知:在系统重启时向指定的 webhook 发送通知,提醒相关人员。

灵活的时间间隔:可设置自检的时间间隔,以便适应不同的监控需求。

二、安装与环境要求

在使用该自检服务之前,确保系统已安装 Python,并能够访问 Jenkins 服务器。还需要安装 requests 库,用于发送 HTTP 请求,可以通过以下命令安装

python 复制代码
pip install requests

三、示例代码

python 复制代码
# -*- coding: utf-8 -*-
# time: 2024/10/03 10:50
# file: jenkins_self_checking.py
# author: tom
# 微信公众号: 玩转测试开发
import json
import requests
import datetime
import subprocess


def get_system_boot_time():
    # 获取系统启动时间
    output = subprocess.check_output('uptime -s', shell=True, text=True).strip()

    # 将时间字符串转换为 datetime 对象
    boot_time = datetime.datetime.fromisoformat(output)

    return boot_time


def check_jenkins_push(webhook, now_time, boot_time):
    header = {
        "Content-Type": "application/json;charset=UTF-8"
    }

    message_body = {
        "msgtype": "markdown",
        "markdown": {
            "content": f"#### Jenkins自检服务告警 \n" +
                       f"开机时间:{boot_time}\n" +
                       f"当前时间:{now_time}\n" +
                       f'<font color="warning"> 服务器重启!!!请关注 Jenkins 构建任务是否需要重新运行。</font>\n'
        },
        "at": {
            "atMobiles": [],
            "isAtAll": False
        }
    }
    send_data = json.dumps(message_body)
    ChatBot = requests.post(url=webhook, data=send_data, headers=header)
    opener = ChatBot.json()
    if opener["errmsg"] == "ok":
        print(f"{opener} Notification message sent successfully!")
    else:
        print(f"Notification message sending failed, reason:{opener}")


def self_checking_push(hours, webhook):
    # 获取当前时间
    current_time = datetime.datetime.now()
    # 获取系统开机时间
    boot_time = get_system_boot_time()
    print(f"开机时间:{boot_time}")
    print(f"当前时间:{str(current_time)[:19]}")

    # 计算开机时间和当前时间的差值
    time_difference = current_time - boot_time

    # 判断差值是否小于 x 小时
    check_time_result = time_difference.total_seconds() < 60 * 60 * hours
    print(f"check_time_result:{check_time_result}")
    print(f"开机时间大于1小时,未出现机器重启现象。")

    if check_time_result:
        current_time = str(datetime.datetime.now())[:19]

        check_jenkins_push(webhook, current_time, boot_time)


if __name__ == "__main__":
    webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxx"
    self_checking_push(1, webhook)

四、运行结果参考

python 复制代码
(base) tom@tom:/mnt/$ python jenkins_self_checking.py
开机时间:2024-10-03 10:36:45
当前时间:2024-10-03 10:52:28
check_time_result:True
开机时间大于1小时,未出现机器重启现象。
{'errcode': 0, 'errmsg': 'ok'} Notification message sent successfully!

五、案例解析
1. 获取系统启动时间:get_system_boot_time 函数使用 uptime -s 命令获取系统的启动时间,并将其转换为 datetime 对象。

2. 推送通知:check_jenkins_push 函数构建了要发送的消息体,并使用 requests.post 发送到指定的 webhook。当服务器重启时,推送的信息将包括开机时间和当前时间,并提醒用户关注 Jenkins 的构建任务。

3. 自检逻辑:在 self_checking_push 函数中,程序首先获取当前时间和系统的开机时间。然后计算时间差,判断服务器是否在指定的时间间隔内重启。如果重启时间小于设定的小时数,程序将调用推送通知函数,提醒用户。

六、小结

通过实现 Jenkins 的开机自检机制,可以在服务器重启时及时得到通知,从而确保持续集成过程的稳定性。该方案能够帮助团队及时关注 Jenkins 的构建任务,减少因服务器重启带来的潜在问题。掌握这个自检服务的实现,有助于提升自动化测试和持续集成的效率。

相关推荐
汤姆yu5 分钟前
2026版基于python大数据的电影分析可视化系统
大数据·python·1024程序员节·电影分析可视化
Pa2sw0rd丶10 分钟前
Python 循环导入详解:为什么会导致生产环境崩溃及企业级解决方案
后端·python
qyhua18 分钟前
从零部署自维护版 Uptime Kuma:Node.js + PM2 + Nginx 全链路实战指南
运维·nginx·node.js
JZC_xiaozhong24 分钟前
OA 审批流与业务流程引擎区别:企业流程自动化进阶
运维·自动化·流程图·bpm·业务流程管理·流程设计可视化·流程监控
熟悉的新风景38 分钟前
window安装Elasticsearch(es)
大数据·elasticsearch·jenkins
梨轻巧39 分钟前
Maya Python入门:创建locator、getAttr() 获取属性、setAttr() 设置属性、定位xform()
python·maya
Xxxx. .Xxxx1 小时前
Classwork 5 - Check the HTML Tags
python
程序员大雄学编程1 小时前
「用Python来学微积分」11. 夹逼定理与单调有界收敛定理
python·数学·微积分·1024程序员节
deephub1 小时前
vLLM 性能优化实战:批处理、量化与缓存配置方案
人工智能·python·大语言模型·1024程序员节·vllm
云飞云共享云桌面1 小时前
苏州精密机械制造企业一台云服务器带8个SolidWorks研发
大数据·运维·服务器·自动化·制造