Spring_couplet_generation 自动化运维脚本:使用Python进行服务健康检查与日志清理
Spring_couplet_generation 自动化运维脚本使用Python进行服务健康检查与日志清理1. 引言想象一下这个场景你花了不少功夫终于把那个能自动生成对联的AI服务——Spring_couplet_generation部署到了服务器上。刚开始几天一切运行顺畅你甚至有点沾沾自喜。但没过多久问题就来了。某天早上你发现服务突然打不开了用户访问不了。手忙脚乱地登录服务器发现要么是服务进程自己“躺平”了要么是硬盘空间被日志文件塞得满满当当系统直接卡死。更头疼的是GPU显存不知道什么时候被占满了新的生成任务根本跑不起来。这种“救火”式的运维不仅耗费精力还严重影响服务的稳定性和用户体验。对于像Spring_couplet_generation这样需要长期稳定运行的AI应用来说手动维护显然不是长久之计。今天我们就来聊聊怎么用Python写一个“自动化管家”脚本。这个脚本能帮你定时检查服务是否活着监控GPU资源还能像清理电脑C盘一样自动扫除那些陈旧的日志和缓存文件让你的服务真正做到“高枕无忧”。2. 脚本核心功能设计我们的目标是打造一个全能型的自动化运维脚本。它不需要多么复杂的架构但必须实用、可靠。主要围绕三个核心功能来展开。2.1 服务进程健康检查这是脚本的“心跳”检测功能。Spring_couplet_generation服务通常以后台进程比如通过systemd或者nohup的方式运行。脚本需要能准确判断这个进程是否还在正常运行而不仅仅是存在。一个健壮的检查逻辑不应该只依赖简单的ps aux | grep。因为进程可能处于僵尸Zombie状态或者监听的端口已经崩溃。因此我们的检查会分为两步首先确认进程ID是否存在然后尝试向服务监听的端口例如7860发送一个HTTP请求如果能够收到正常的响应才认为服务是真正健康的。2.2 系统资源监控聚焦GPU对于依赖GPU进行推理的AI服务显存是比CPU和内存更关键的资源。脚本需要监控GPU的显存使用情况。我们使用nvidia-smi这个命令工具来获取信息并用Python解析其输出。监控的目的有两个一是预警当显存使用率超过某个阈值比如90%时及时发出告警提醒你可能需要优化模型或检查是否有内存泄漏二是记录将历史使用情况记录下来便于后续分析服务的资源消耗模式。2.3 智能日志与缓存清理这是解决“C盘爆满”问题的关键。AI服务在运行中会产生大量的日志文件如访问日志、错误日志、模型加载日志以及可能的临时缓存文件。如果不加管理它们会像滚雪球一样吞噬磁盘空间。我们的清理逻辑不是粗暴地删除所有旧文件而是模仿一个智能的“清理策略”定位目标明确需要清理的目录例如/logs/、/tmp/或服务自带的缓存目录。制定规则按时间如删除7天前的文件和按空间如当磁盘使用率超过85%时清理最旧的文件直到使用率低于70%进行清理。安全操作在删除前记录文件信息避免误删正在被使用的日志文件通过检查文件是否被打开并设置“安全期”绝不删除最近几分钟内产生的文件。3. Python脚本实现详解接下来我们一步步实现这个自动化脚本。你会看到用Python实现这些功能其实非常清晰。3.1 环境准备与依赖首先确保你的服务器Python环境在3.6以上。这个脚本主要用到Python的标准库唯一需要额外安装的是用于解析nvidia-smi输出的gpustat库当然你也可以选择直接用subprocess调用命令并解析文本。# 如果需要使用gpustat库更优雅 pip install gpustat # 或者使用更基础的psutil库来监控系统进程可选但功能强大 pip install psutil我们的脚本将主要使用以下内置模块import subprocess # 执行系统命令 import shutil # 磁盘空间信息 import os # 文件路径操作 import time # 时间、休眠 import logging # 记录脚本自身日志 import json # 可选用于保存监控历史 from datetime import datetime, timedelta # 处理时间3.2 服务健康检查实现我们来编写检查Spring_couplet_generation服务状态的函数。import requests import socket from http.client import HTTPConnection def check_service_health(service_name, port7860, timeout5): 检查指定服务是否健康。 参数: service_name: 服务进程名用于检查进程是否存在。 port: 服务监听的端口号。 timeout: 网络请求超时时间秒。 返回: dict: 包含检查状态和详细信息的字典。 result { service: service_name, port: port, is_process_alive: False, is_port_reachable: False, is_http_ok: False, details: } # 1. 检查进程是否存在 try: # 使用pgrep命令查找进程更精确 cmd fpgrep -f {service_name} proc subprocess.run(cmd, shellTrue, capture_outputTrue, textTrue) if proc.returncode 0 and proc.stdout.strip(): result[is_process_alive] True result[details] 进程存在。 else: result[details] 未找到相关进程。 return result # 进程都不在直接返回 except Exception as e: result[details] f进程检查出错{e}。 return result # 2. 检查端口是否可连接TCP层 try: sock socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) if sock.connect_ex((localhost, port)) 0: result[is_port_reachable] True result[details] 端口可连接。 else: result[details] 端口无法连接。 return result sock.close() except Exception as e: result[details] f端口检查出错{e}。 return result # 3. 检查HTTP服务是否正常响应应用层 try: # 尝试访问一个常见的健康检查端点或根路径 url fhttp://localhost:{port} response requests.get(url, timeouttimeout) if response.status_code 500: # 认为5xx错误是服务端问题4xx可能是客户端问题但服务在运行 result[is_http_ok] True result[details] fHTTP服务正常状态码{response.status_code}。 else: result[details] fHTTP服务返回错误状态码{response.status_code}。 except requests.exceptions.RequestException as e: result[details] fHTTP请求失败{e}。 return result # 使用示例 if __name__ __main__: health check_service_health(spring_couplet, port7860) print(health) # 如果进程和端口都正常但HTTP不正常可能需要重启服务 if health[is_process_alive] and health[is_port_reachable] and not health[is_http_ok]: print(警告服务进程在运行但Web界面无响应建议重启。)3.3 GPU显存监控实现这里展示两种方法使用subprocess解析nvidia-smi和使用第三方库gpustat。def get_gpu_info_by_nvidia_smi(): 通过解析nvidia-smi命令输出获取GPU信息。 返回: list of dicts, 每个dict包含一个GPU的信息。 try: cmd nvidia-smi --query-gpuindex,name,memory.total,memory.used,memory.free,utilization.gpu --formatcsv,noheader,nounits output subprocess.check_output(cmd, shellTrue, textTrue) gpu_list [] for line in output.strip().split(\n): if line: parts line.split(, ) if len(parts) 6: gpu_info { index: parts[0], name: parts[1], mem_total: int(parts[2]), mem_used: int(parts[3]), mem_free: int(parts[4]), gpu_util: int(parts[5]) } gpu_info[mem_usage_percent] round((gpu_info[mem_used] / gpu_info[mem_total]) * 100, 1) gpu_list.append(gpu_info) return gpu_list except subprocess.CalledProcessError as e: print(f执行nvidia-smi命令失败: {e}) return [] except FileNotFoundError: print(未找到nvidia-smi命令可能未安装NVIDIA驱动或不在PATH中。) return [] def get_gpu_info_by_gpustat(): 使用gpustat库获取GPU信息更简洁。 需要先安装: pip install gpustat try: import gpustat stats gpustat.GPUStatCollection.new_query() gpu_list [] for gpu in stats: gpu_list.append({ index: gpu.index, name: gpu.name, mem_total: gpu.memory_total, mem_used: gpu.memory_used, mem_free: gpu.memory_total - gpu.memory_used, gpu_util: gpu.utilization, mem_usage_percent: round((gpu.memory_used / gpu.memory_total) * 100, 1) }) return gpu_list except ImportError: print(请先安装gpustat库: pip install gpustat) return [] except Exception as e: print(f获取GPU信息失败: {e}) return [] def check_gpu_memory_warning(gpu_list, threshold_percent90): 检查GPU显存使用是否超过阈值并返回告警信息。 warnings [] for gpu in gpu_list: if gpu[mem_usage_percent] threshold_percent: warnings.append(fGPU {gpu[index]} ({gpu[name]}) 显存使用率过高: {gpu[mem_usage_percent]}%) return warnings # 使用示例 if __name__ __main__: gpus get_gpu_info_by_nvidia_smi() # 或使用 get_gpu_info_by_gpustat() for gpu in gpus: print(fGPU {gpu[index]}: {gpu[name]}, 显存使用率 {gpu[mem_usage_percent]}%) alerts check_gpu_memory_warning(gpus, threshold_percent85) if alerts: print(警告) for alert in alerts: print(f - {alert})3.4 智能日志与缓存清理实现这是实现“C盘清理”逻辑的核心。我们将实现一个按时间和按空间双重策略的清理器。import os import glob import shutil from pathlib import Path def clean_old_files_by_time(directory, pattern*.log, days_old7): 删除指定目录下匹配特定模式且超过一定天数的文件。 参数: directory: 要清理的目录路径。 pattern: 文件匹配模式例如 *.log, *.txt, cache_*。 days_old: 删除多少天之前的文件。 返回: list: 被删除的文件路径列表。 deleted_files [] if not os.path.isdir(directory): print(f目录不存在: {directory}) return deleted_files cutoff_time time.time() - (days_old * 24 * 60 * 60) search_path os.path.join(directory, pattern) for filepath in glob.glob(search_path): if os.path.isfile(filepath): file_mtime os.path.getmtime(filepath) if file_mtime cutoff_time: try: os.remove(filepath) deleted_files.append(filepath) print(f已删除旧文件: {filepath} (修改于 {time.ctime(file_mtime)})) except OSError as e: print(f删除文件失败 {filepath}: {e}) return deleted_files def clean_files_by_disk_usage(directory, pattern*, target_free_percent30): 当磁盘使用率过高时清理最旧的文件直到达到目标空闲比例。 这是一种更激进的清理策略用于紧急释放空间。 参数: directory: 要清理的目录所在的磁盘。 pattern: 文件匹配模式。 target_free_percent: 希望达到的磁盘空闲百分比。 返回: list: 被删除的文件路径列表。 deleted_files [] # 获取磁盘使用情况 total, used, free shutil.disk_usage(directory) free_percent (free / total) * 100 print(f当前磁盘空闲率: {free_percent:.1f}%) if free_percent target_free_percent: print(磁盘空间充足无需清理。) return deleted_files # 获取目录下所有匹配的文件并按修改时间排序从旧到新 search_path os.path.join(directory, **, pattern) if pattern ! * else os.path.join(directory, **, *) all_files [] for filepath in glob.glob(search_path, recursiveTrue): if os.path.isfile(filepath): all_files.append((filepath, os.path.getmtime(filepath))) all_files.sort(keylambda x: x[1]) # 按修改时间排序 # 开始删除最旧的文件直到满足空间要求 for filepath, mtime in all_files: if free_percent target_free_percent: break try: file_size os.path.getsize(filepath) os.remove(filepath) deleted_files.append(filepath) free file_size # 更新空闲空间估计值 free_percent (free / total) * 100 print(f为释放空间删除: {filepath} (大小: {file_size/1024/1024:.2f} MB)) except OSError as e: print(f删除文件失败 {filepath}: {e}) continue print(f清理后磁盘空闲率: {free_percent:.1f}%) return deleted_files # 使用示例组合策略 def smart_cleanup(log_dirs, cache_dirs, days_to_keep7, disk_clean_threshold85): 智能清理组合函数。 先按时间清理如果磁盘空间仍然紧张则触发按空间清理。 all_deleted [] # 1. 常规按时间清理 for dir_path in log_dirs: if os.path.exists(dir_path): deleted clean_old_files_by_time(dir_path, *.log, days_to_keep) all_deleted.extend(deleted) for dir_path in cache_dirs: if os.path.exists(dir_path): # 缓存文件可能没有固定后缀按文件名模式或全部清理 deleted clean_old_files_by_time(dir_path, *, days_to_keep) # 清理所有旧文件 all_deleted.extend(deleted) # 2. 检查磁盘使用率必要时触发紧急清理 # 假设我们监控服务所在的主要磁盘分区例如根目录 / disk_usage shutil.disk_usage(/) used_percent (disk_usage.used / disk_usage.total) * 100 if used_percent disk_clean_threshold: print(f磁盘使用率({used_percent:.1f}%)超过阈值({disk_clean_threshold}%)启动紧急空间清理。) # 通常选择一个特定的、可清理的目录进行深度清理比如日志目录 emergency_dir log_dirs[0] if log_dirs else /var/log deleted clean_files_by_disk_usage(emergency_dir, *.log, target_free_percent100-disk_clean_threshold10) all_deleted.extend(deleted) return all_deleted if __name__ __main__: # 假设的日志和缓存目录请根据实际部署修改 log_directories [/home/user/spring_couplet/logs, /var/log/spring_couplet] cache_directories [/home/user/spring_couplet/cache, /tmp/spring_couplet_cache] deleted_files smart_cleanup(log_directories, cache_directories, days_to_keep7, disk_clean_threshold85) print(f本轮清理共删除 {len(deleted_files)} 个文件。)4. 整合与自动化部署现在我们把以上所有功能模块整合到一个主脚本中并添加定时执行和告警通知的能力。4.1 主脚本整合与日志记录一个完整的运维脚本需要有清晰的日志记录方便事后追溯问题。import logging import schedule import time def setup_logging(): 配置日志记录 logging.basicConfig( levellogging.INFO, format%(asctime)s - %(name)s - %(levelname)s - %(message)s, handlers[ logging.FileHandler(service_monitor.log), logging.StreamHandler() # 同时输出到控制台 ] ) return logging.getLogger(__name__) def send_alert(message, alert_typewarning): 发送告警信息此处为示例需根据实际环境实现。 可以集成邮件、钉钉、企业微信、Slack等Webhook。 logger logging.getLogger(__name__) if alert_type error: logger.error(f[告警] {message}) # 此处添加发送邮件或Webhook的代码 # 例如: requests.post(webhook_url, json{text: message}) else: logger.warning(f[警告] {message}) # 简单示例打印到日志和控制台 print(f{alert_type.upper()}: {message}) def main_monitoring_cycle(): 执行一次完整的监控检查周期。 logger setup_logging() logger.info(开始执行监控周期...) # 1. 检查服务健康 service_health check_service_health(spring_couplet, port7860) logger.info(f服务健康检查结果: {service_health}) if not service_health[is_process_alive]: send_alert(f服务进程 spring_couplet 不存在详情{service_health[details]}, error) # 此处可以添加自动重启服务的逻辑例如 # subprocess.run([systemctl, restart, spring_couplet.service]) elif not service_health[is_http_ok]: send_alert(f服务进程存在但HTTP异常。详情{service_health[details]}, warning) # 2. 检查GPU状态 gpu_info_list get_gpu_info_by_nvidia_smi() for gpu in gpu_info_list: logger.info(fGPU {gpu[index]} 显存使用率: {gpu[mem_usage_percent]}%) gpu_alerts check_gpu_memory_warning(gpu_info_list, threshold_percent90) for alert in gpu_alerts: send_alert(alert, warning) # 3. 执行智能清理例如每天凌晨3点执行一次这里作为演示每次监控都检查磁盘 # 我们可以在主循环中判断是否到了清理时间或者用另一个定时任务。 # 这里简单演示如果磁盘使用率80%就触发清理检查。 disk_usage shutil.disk_usage(/) used_percent (disk_usage.used / disk_usage.total) * 100 if used_percent 80: logger.warning(f磁盘使用率较高({used_percent:.1f}%)触发清理检查。) log_dirs [/home/user/spring_couplet/logs] cache_dirs [/tmp] deleted smart_cleanup(log_dirs, cache_dirs, days_to_keep7, disk_clean_threshold85) if deleted: logger.info(f已自动清理 {len(deleted)} 个文件。) logger.info(监控周期执行完毕。\n) if __name__ __main__: # 设置定时任务示例每5分钟检查一次健康状态和GPU schedule.every(5).minutes.do(main_monitoring_cycle) # 设置定时清理任务示例每天凌晨3点执行 schedule.every().day.at(03:00).do(lambda: smart_cleanup([/home/user/spring_couplet/logs], [/tmp])) logger setup_logging() logger.info(Spring_couplet_generation 自动化运维监控脚本已启动。) # 保持脚本运行 while True: schedule.run_pending() time.sleep(60) # 每分钟检查一次是否有任务需要执行4.2 使用Systemd托管监控脚本为了让监控脚本本身也能在服务器上稳定、持久地运行我们可以将其配置为一个系统服务。创建服务文件/etc/systemd/system/spring-couplet-monitor.service[Unit] DescriptionSpring Couplet Generation Service Monitor Afternetwork.target [Service] Typesimple Useryour_username # 改为你的用户名 WorkingDirectory/path/to/your/script # 改为脚本所在目录 ExecStart/usr/bin/python3 /path/to/your/script/monitor.py Restarton-failure # 脚本异常退出时自动重启 RestartSec10 StandardOutputjournal StandardErrorjournal [Install] WantedBymulti-user.target启用并启动服务sudo systemctl daemon-reload sudo systemctl enable spring-couplet-monitor.service sudo systemctl start spring-couplet-monitor.service查看服务状态和日志sudo systemctl status spring-couplet-monitor.service sudo journalctl -u spring-couplet-monitor.service -f # 实时查看日志通过这种方式你的监控脚本就和Spring_couplet_generation服务一样成为了系统的一部分能够开机自启、自动重启并通过系统日志进行管理。5. 总结通过上面这一套组合拳我们为Spring_couplet_generation服务构建了一个从进程、资源到存储空间的立体化监控与维护体系。这个Python脚本的核心价值在于将重复、易出错的运维操作标准化和自动化。它就像一个不知疲倦的管家定时帮你检查服务的“心跳”进程、关注它的“体力消耗”GPU显存并及时清理掉积累的“代谢废物”日志缓存从而保障服务能够长期、稳定、高效地运行。实际部署时你还需要根据自己服务器的具体环境调整一些参数比如服务的进程名、端口号、日志文件的具体路径、清理策略的阈值等。告警部分也建议接入你们团队常用的通知渠道比如钉钉机器人或者邮件这样一旦出现问题你能第一时间获知。自动化运维的最终目的不是取代人而是把人从繁琐的重复劳动中解放出来让我们能更专注于业务逻辑和创新。希望这个脚本能成为一个不错的起点帮你打造一个更省心、更可靠的AI服务运行环境。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2446370.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!