gco_wrapper.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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 logger_setup 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. if self._gco:
  68. try:
  69. self._gco.stop()
  70. except Exception as cleanup_err:
  71. self._log(f'Startup rollback incomplete: {cleanup_err}')
  72. raise
  73. def stop(self):
  74. if self._state not in (State.RUNNING, State.FAILED, State.STOPPED):
  75. return
  76. self._state = State.STOPPING
  77. try:
  78. if self._gco:
  79. self._gco.stop() # Call Sentinel or Booker stop
  80. except Exception:
  81. self._state = State.FAILED
  82. raise
  83. else:
  84. self._state = State.STOPPED
  85. # ================= Hot Reloading Methods =================
  86. def update_config(self, new_cfg: GroupConfig):
  87. """
  88. Dynamically updates current Group configuration and propagates to underlying GCO instance.
  89. """
  90. with self._lock:
  91. self.m_cfg = new_cfg
  92. if self._gco:
  93. self._gco.update_config(new_cfg)
  94. def get_status(self) -> GroupStatus:
  95. """
  96. Returns aggregated status of current GCOWrapper and underlying GCO instance.
  97. """
  98. with self._lock:
  99. state_name = self._state.name
  100. if self._gco:
  101. status: GroupStatus = self._gco.get_status()
  102. status.wrapper_state = state_name
  103. return status
  104. return GroupStatus(
  105. group_id=self.m_cfg.identifier,
  106. enable=self.m_cfg.enable,
  107. plugin_name=self.m_cfg.plugin_config.plugin_name,
  108. wrapper_state=state_name,
  109. )