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

相关推荐
A-刘晨阳14 小时前
K8S 之 Taints(污点)与 Tolerations(容忍)
运维·云原生·容器·kubernetes·k8s污点·k8s容忍
likeGhee14 小时前
bridge 模式下docker容器无法访问,curl: (56) Recv failure: Connection reset by peer
运维·docker·容器
Kendra91914 小时前
服务器上架流程
运维·服务器·网络·ip·磁盘
Lsir10110_14 小时前
【Linux】线程初步——线程概念以及接口认识
linux·运维·服务器
edisao14 小时前
第三章 合规的自愿
jvm·数据仓库·python·神经网络·决策树·编辑器·动态规划
cuber膜拜14 小时前
Tenacity 原理与基本使用
服务器·网络·python·装饰器模式·tenacity
Myosotis51314 小时前
作业 第三次
开发语言·python
cuber膜拜14 小时前
PyBreaker 原理与基本使用
服务器·网络·python·pybreaker
学Linux的语莫14 小时前
模型转为RKNN格式
python·深度学习·机器学习
Albert Edison14 小时前
【Python】文件
android·服务器·python