Files
RemoveWeeklyShapshot/config/settings.py
2026-02-20 16:55:53 +08:00

80 lines
3.7 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
from utils.logger import logger
def load_config():
"""加载 YAML 配置文件并解析其内容"""
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', []),
"SNAPSHOT_RETENTION_DAYS": int(global_config.get('snapshot_retention_days', 15)),
# "EXCEL_OUTPUT_PATH": global_config.get('excel_output_path', f'/logs/{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}-VMsSnapShots_report.xlsx'),
# "LOG_FILE_PATH": global_config.get('log_file_path', f'/logs/{datetime.now().strftime('%Y%m%d_%H%M%S')}-VMsSnapShots_cleanup.logs'), "EXCEL_OUTPUT_PATH": global_config.get('excel_output_path', f'/logs/{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}-VMsSnapShots_report.xlsx'),
"EXCEL_OUTPUT_PATH": global_config.get('excel_output_path', f'D:\\PycharmProjects\\RemoveWeeklyShapshot\\logs\\{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}-VMsSnapShots_report.xlsx'),
"DISABLE_SSL_VERIFY": global_config.get('disable_ssl_verify', True),
# 算出的过期时间点
}
# 验证配置
if not config["MANAGEMENT_NODES"]:
raise ValueError("未配置任何管理节点vCenter 或 ESXi只少要有一台 management_nodes 节点。")
# 检查每个节点的必填字段
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_PATH = os.path.join(os.path.dirname(__file__), 'config.yaml')
# 加载配置并导出全局变量
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"]
# 验证配置函数
def validate_config():
pass # 加载时已验证,此处留空
if __name__ == "__main__":
# 打印全局配置
print("\n【全局配置】")
print(f" 快照保留天数: {config['SNAPSHOT_RETENTION_DAYS']}")
print(f" Excel输出路径: {EXCEL_OUTPUT_PATH}")
#print(f" 日志文件路径: {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')}")