gco_wrapper.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import threading
  2. import collections
  3. from enum import Enum, auto
  4. from typing import Callable, Type, Any, Dict
  5. from core_types import GroupConfig, GroupStatus
  6. from log_macros import VSC_INFO
  7. class State(Enum):
  8. CREATED = auto()
  9. LOADED = auto()
  10. RUNNING = auto()
  11. STOPPING = auto()
  12. STOPPED = auto()
  13. FAILED = auto()
  14. class GCOWrapper:
  15. def __init__(self, gco_class: Type[Any], gco_cfg: GroupConfig, redis_conf: Dict[str, Any]):
  16. """
  17. @param gco_class: Specific GCO class to wrap (SentinelGCO or BookerGCO)
  18. @param gco_cfg: Group configuration
  19. @param redis_conf: Redis connection configuration dictionary
  20. """
  21. self.gco_class = gco_class
  22. self.m_cfg = gco_cfg
  23. self.redis_conf = redis_conf
  24. self._gco = None
  25. self._state = State.CREATED
  26. self._log_queue = collections.deque(maxlen=1000)
  27. self._log_subscribers = set()
  28. self._lock = threading.Lock()
  29. self._push_callback: Callable = lambda t, d, s: None
  30. def set_push_callback(self, callback: Callable):
  31. self._push_callback = callback
  32. def _log(self, msg: str):
  33. gid = getattr(self.m_cfg, "identifier", "")
  34. with self._lock:
  35. VSC_INFO("-", msg, group_id=gid)
  36. self._log_queue.append(msg)
  37. for sub in self._log_subscribers:
  38. try:
  39. sub(msg)
  40. except Exception:
  41. pass
  42. # Legacy push callback
  43. self._push_callback("LOG", msg.encode(), self._state)
  44. def get_logs(self, last_n=50):
  45. with self._lock:
  46. return list(self._log_queue)[-last_n:]
  47. def subscribe_logs(self, callback: Callable):
  48. with self._lock:
  49. self._log_subscribers.add(callback)
  50. def unsubscribe_logs(self, callback: Callable):
  51. with self._lock:
  52. self._log_subscribers.discard(callback)
  53. def _transition(self, from_state, to_state):
  54. if self._state != from_state:
  55. raise Exception(f"invalid transition {self._state.name} -> {to_state.name}")
  56. self._state = to_state
  57. def load(self):
  58. self._transition(State.CREATED, State.LOADED)
  59. def start(self):
  60. self._transition(State.LOADED, State.RUNNING)
  61. try:
  62. # Dynamically instantiate class with Redis configuration
  63. self._gco = self.gco_class(self.m_cfg, self.redis_conf, logger=self._log)
  64. self._gco.start() # Call Sentinel or Booker start
  65. except Exception:
  66. self._state = State.FAILED
  67. raise
  68. def stop(self):
  69. if self._state != State.RUNNING:
  70. return
  71. self._transition(State.RUNNING, State.STOPPING)
  72. try:
  73. if self._gco:
  74. self._gco.stop() # Call Sentinel or Booker stop
  75. finally:
  76. self._transition(State.STOPPING, State.STOPPED)
  77. # ================= Hot Reloading Methods =================
  78. def update_config(self, new_cfg: GroupConfig):
  79. """
  80. Dynamically updates current Group configuration and propagates to underlying GCO instance.
  81. """
  82. with self._lock:
  83. self.m_cfg = new_cfg
  84. if self._gco:
  85. self._gco.update_config(new_cfg)
  86. def get_status(self) -> GroupStatus:
  87. """
  88. Returns aggregated status of current GCOWrapper and underlying GCO instance.
  89. """
  90. with self._lock:
  91. state_name = self._state.name
  92. if self._gco:
  93. status: GroupStatus = self._gco.get_status()
  94. status.wrapper_state = state_name
  95. return status
  96. return GroupStatus(
  97. group_id=self.m_cfg.identifier,
  98. enable=self.m_cfg.enable,
  99. plugin_name=self.m_cfg.plugin_config.plugin_name,
  100. wrapper_state=state_name,
  101. )