提升 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 的构建任务,减少因服务器重启带来的潜在问题。掌握这个自检服务的实现,有助于提升自动化测试和持续集成的效率。

相关推荐
克莱因3584 小时前
Linux CentOS7 进程基础知识
linux·运维·服务器
Skilce5 小时前
ZrLog 高可用部署
运维·服务器·数据库·阿里云·maven
papaofdoudou7 小时前
LINUX VFIO被IOMMUFD取代
linux·运维·服务器
sg_knight7 小时前
设计模式实战:模板方法模式(Template Method)
python·设计模式·模板方法模式
FreakStudio7 小时前
ESP32居然能当 DNS 服务器用?内含NCSI欺骗和DNS劫持实现
python·单片机·嵌入式·面向对象·并行计算·电子diy
乐观勇敢坚强的老彭8 小时前
2026全国青少年信息素养大赛考纲
python·数学建模
无忧智库8 小时前
智慧医院的“新基建”:从顶层设计到全栈式智能运维的深度解构(PPT)
大数据·运维
YMWM_9 小时前
【问题】thor上的cubLas
linux·python·thor
wefly20179 小时前
免安装!m3u8live.cn在线 M3U8 播放器,小白也能快速上手
java·开发语言·python·json·php·m3u8·m3u8在线转换