cloud_config.py 3.9 KB

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