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

相关推荐
java1234_小锋1 分钟前
基于Python的旅游推荐协同过滤算法系统(去哪儿网数据分析及可视化(Django+echarts))
python·数据分析·旅游
蓝婷儿2 分钟前
Python 机器学习核心入门与实战进阶 Day 4 - 支持向量机(SVM)原理与分类实战
python·机器学习·支持向量机
杰夫贾维斯5 分钟前
CentOS Linux 8 的系统部署 Qwen2.5-7B -Instruct-AWQ
linux·运维·人工智能·机器学习·centos
%d%d227 分钟前
python 在运行时没有加载修改后的版本
java·服务器·python
CodeWithMe1 小时前
【Note】Linux Kernel 实时技术深入:详解 PREEMPT_RT 与 Xenomai
linux·运维·服务器
muyun28001 小时前
安全访问云端内部应用:用frp的stcp功能解决SSH转发的痛点
运维·安全·ssh·frp
amazinging1 小时前
北京-4年功能测试2年空窗-报培训班学测开-第四十七天
python·学习·selenium
AI迅剑2 小时前
模块三:现代C++工程实践(4篇)第三篇《C++与系统编程:Linux内核模块开发入门》
linux·运维·服务器
Freak嵌入式2 小时前
一文速通 Python 并行计算:13 Python 异步编程-基本概念与事件循环和回调机制
开发语言·python·嵌入式·协程·硬件·异步编程
专一的咸鱼哥2 小时前
Linux驱动开发(platform 设备驱动)
linux·运维·驱动开发