Files
RemoveWeeklyShapshot/config/settings.py
2026-02-19 15:35:27 +08:00

88 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import yaml
import os
from datetime import datetime, timedelta
# from utils.logger import logger
# 配置文件路径
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'config.yaml')
def load_config():
"""加载YAML配置区分vCenter和ESXi"""
try:
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
raw_config = yaml.safe_load(f)
# 全局配置
global_config = raw_config.get('global', {})
config = {
# vCenter/ESXi节点列表
"MANAGEMENT_NODES": raw_config.get('management_nodes', []),
# vCenter/ESXi节点列表
"SNAPSHOT_RETENTION_DAYS": int(global_config.get('snapshot_retention_days', 15)),
"EXCEL_OUTPUT_PATH": global_config.get('excel_output_path', '/tmp/vm_snapshots_report.xlsx'),
"LOG_FILE_PATH": global_config.get('log_file_path', '/var/log/vm_snapshot_cleanup.log'),
"DISABLE_SSL_VERIFY": global_config.get('disable_ssl_verify', True),
# 算出的过期时间点
"EXPIRE_DATE": datetime.now() - timedelta(days=int(global_config.get('snapshot_retention_days', 15)))
}
# 验证配置
if not config["MANAGEMENT_NODES"]:
raise ValueError("未配置任何管理节点vCenter/ESXi")
# 检查每个节点的必填字段
required_fields = ['type', 'name', 'host', 'user', 'password', 'max_delete_concurrent']
for node in config["MANAGEMENT_NODES"]:
missing = [f for f in required_fields if f not in node]
if missing:
raise ValueError(f"节点 {node.get('name', '未知')} 缺少配置字段: {missing}")
# 验证类型合法性
if node['type'] not in ['vcenter', 'esxi']:
raise ValueError(f"节点 {node['name']} 类型错误仅支持vcenter/esxi")
#logger.info(f"✅ 成功加载配置,共 {len(config['MANAGEMENT_NODES'])} 个管理节点")
return config
except Exception as e:
#logger.error(f"❌ 加载配置失败: {str(e)}")
raise
# 加载配置并导出全局变量
config = load_config() # 模块导入时立即执行
MANAGEMENT_NODES = config["MANAGEMENT_NODES"]
SNAPSHOT_RETENTION_DAYS = config["SNAPSHOT_RETENTION_DAYS"]
EXCEL_OUTPUT_PATH = config["EXCEL_OUTPUT_PATH"]
LOG_FILE_PATH = config["LOG_FILE_PATH"]
DISABLE_SSL_VERIFY = config["DISABLE_SSL_VERIFY"]
EXPIRE_DATE = config["EXPIRE_DATE"]
# 验证配置函数
def validate_config():
pass # 加载时已验证,此处留空
if __name__ == "__main__":
# 打印全局配置
print("\n【全局配置】")
print(f" 快照保留天数: {config['SNAPSHOT_RETENTION_DAYS']}")
print(f" 过期日期: {config['EXPIRE_DATE']}")
print(f" Excel输出路径: {config['EXCEL_OUTPUT_PATH']}")
print(f" 日志文件路径: {config['LOG_FILE_PATH']}")
print(f" 禁用SSL验证: {config['DISABLE_SSL_VERIFY']}")
# 打印管理节点
nodes = config['MANAGEMENT_NODES']
print(f"\n【管理节点】共 {len(nodes)}")
for i, node in enumerate(nodes, 1):
print(f"\n 节点[{i}]:")
print(f" 类型: {node.get('type')}")
print(f" 名称: {node.get('name')}")
print(f" 地址: {node.get('host')}")
print(f" 用户: {node.get('user')}")
print(f" 密码: {'*' * len(node.get('password', ''))}")
# print(f" 密码: {node.get('password', '')}") # 直接打印出密码
print(f" 最大并发删除: {node.get('max_delete_concurrent')}")