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

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

历史攻略:

定时任务:Jenkins

Jenkins:高效卸载和安装

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

centos7:docker快速安装jenkins

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

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

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

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

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

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

一、Jenkins 自检的基本特性

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

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

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

二、安装与环境要求

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

pip install requests

三、示例代码

# -*- 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)

四、运行结果参考

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值