cloud_config.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import os
  2. import json
  3. import yaml
  4. import hashlib
  5. import time
  6. from typing import Any, Tuple, Optional, Callable
  7. from toolkit.cloud_api import CloudApi
  8. def compute_config_hash(config_data: Any) -> str:
  9. """计算配置数据的 MD5 哈希,用于快速对比判断配置是否发生变更"""
  10. if config_data is None:
  11. return ""
  12. serialized = json.dumps(config_data, sort_keys=True, ensure_ascii=False)
  13. return hashlib.md5(serialized.encode('utf-8')).hexdigest()
  14. def fetch_cloud_config(role: str, node_id: str) -> Optional[Any]:
  15. """
  16. 使用内置 CloudApi 从云端读取指定 role (entry_type) 及 node_id 的节点配置列表。
  17. 接口: GET /api/node-configurations/{entry_type}?node_id={node_id}&pageSize=100
  18. 返回 items 数组。
  19. """
  20. try:
  21. data = CloudApi.Instance().get_node_configurations(entry_type=role, node_id=node_id, page_size=100)
  22. if data and "items" in data:
  23. return data["items"]
  24. except Exception:
  25. pass
  26. return None
  27. def save_local_cache(path: str, data: Any) -> bool:
  28. """将从云端获取到的最新配置保存到本地 YAML 缓存文件路径"""
  29. try:
  30. dir_name = os.path.dirname(path)
  31. if dir_name and not os.path.exists(dir_name):
  32. os.makedirs(dir_name, exist_ok=True)
  33. tmp_path = path + ".tmp"
  34. with open(tmp_path, "w", encoding="utf-8") as f:
  35. yaml.safe_dump(data, f, allow_unicode=True, sort_keys=False)
  36. os.replace(tmp_path, path)
  37. return True
  38. except Exception as e:
  39. print(f"[CloudConfig] Failed to save local cache to {path}: {e}")
  40. return False
  41. def load_local_config(path: str) -> Any:
  42. """从本地 YAML 文件读取配置"""
  43. if not os.path.exists(path):
  44. return None
  45. with open(path, "r", encoding="utf-8") as f:
  46. return yaml.safe_load(f)
  47. def load_remote_or_cache(
  48. role: str,
  49. node_id: str,
  50. local_cache_path: str,
  51. use_cloud: bool = True,
  52. logger: Optional[Callable[[str], None]] = None
  53. ) -> Tuple[Any, str, bool]:
  54. """
  55. 核心拉取与 Fallback 逻辑:
  56. - 若开启了 use_cloud(默认):尝试调用 CloudApi 获取指定 role + node_id 的配置列表,成功则写入本地缓存文件;失败则 Fallback 读取本地缓存。
  57. - 若未开启 use_cloud(显式传了 -c/--config):直接读取本地配置文件。
  58. """
  59. def log_info(msg: str):
  60. if logger:
  61. logger(f"[CloudConfig] {msg}")
  62. else:
  63. print(f"[CloudConfig] {msg}")
  64. def log_warn(msg: str):
  65. if logger:
  66. logger(f"[CloudConfig][WARNING] {msg}")
  67. else:
  68. print(f"[CloudConfig][WARNING] {msg}")
  69. if use_cloud:
  70. try:
  71. log_info(f"Fetching cloud configuration for role '{role}' (node_id: '{node_id}') via CloudApi...")
  72. data = fetch_cloud_config(role=role, node_id=node_id)
  73. if data is not None:
  74. config_hash = compute_config_hash(data)
  75. log_info(f"Successfully fetched cloud config for role '{role}' (hash: {config_hash[:8]}, count: {len(data)})")
  76. save_local_cache(local_cache_path, data)
  77. return data, config_hash, True
  78. else:
  79. log_warn(f"Cloud config for role '{role}' (node_id: '{node_id}') returned empty/null data.")
  80. except Exception as e:
  81. log_warn(f"Failed to fetch cloud config for role '{role}' (node_id: '{node_id}') via CloudApi: {e}")
  82. log_warn(f"Fallback to local cache file: {local_cache_path}")
  83. local_data = load_local_config(local_cache_path)
  84. if local_data is None:
  85. log_warn(f"Local config file {local_cache_path} does not exist or is empty.")
  86. local_data = [] if "booker" in local_cache_path or "sentinel" in local_cache_path else {}
  87. config_hash = compute_config_hash(local_data)
  88. return local_data, config_hash, False