|
| 1 | +import threading |
| 2 | +import logging |
| 3 | +import time |
| 4 | +from kubernetes import client, watch |
| 5 | +from typing import Callable, List |
| 6 | +import urllib3 |
| 7 | + |
| 8 | +logger = logging.getLogger(__name__) |
| 9 | + |
| 10 | +class ResourceWatcher: |
| 11 | + """ |
| 12 | + Watches Kubernetes pod events and notifies subscribers about relevant events. |
| 13 | +
|
| 14 | + Attributes |
| 15 | + ---------- |
| 16 | + namespace : str |
| 17 | + Kubernetes namespace to watch pods in. |
| 18 | + subscribers : List[Callable] |
| 19 | + List of subscriber callback functions to notify on events. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self, namespace, config): |
| 23 | + """ |
| 24 | + Initializes the ResourceWatcher. |
| 25 | +
|
| 26 | + Parameters |
| 27 | + ---------- |
| 28 | + namespace : str |
| 29 | + Kubernetes namespace to watch pods in. |
| 30 | + """ |
| 31 | + self.namespace = namespace |
| 32 | + self.reconnection_attempts = int(config.scrapyd().get('reconnection_attempts', 5)) |
| 33 | + self.backoff_time = int(config.scrapyd().get('backoff_time', 5)) |
| 34 | + self.backoff_coefficient = int(config.scrapyd().get('backoff_coefficient', 2)) |
| 35 | + self.subscribers: List[Callable] = [] |
| 36 | + self._stop_event = threading.Event() |
| 37 | + self.watcher_thread = threading.Thread(target=self.watch_pods, daemon=True) |
| 38 | + self.watcher_thread.start() |
| 39 | + logger.info(f"ResourceWatcher thread started for namespace '{self.namespace}'.") |
| 40 | + |
| 41 | + def subscribe(self, callback: Callable): |
| 42 | + """ |
| 43 | + Adds a subscriber callback to be notified on events. |
| 44 | +
|
| 45 | + Parameters |
| 46 | + ---------- |
| 47 | + callback : Callable |
| 48 | + A function to call when an event is received. |
| 49 | + """ |
| 50 | + if callback not in self.subscribers: |
| 51 | + self.subscribers.append(callback) |
| 52 | + logger.debug(f"Subscriber {callback.__name__} added.") |
| 53 | + |
| 54 | + def unsubscribe(self, callback: Callable): |
| 55 | + """ |
| 56 | + Removes a subscriber callback. |
| 57 | +
|
| 58 | + Parameters |
| 59 | + ---------- |
| 60 | + callback : Callable |
| 61 | + The subscriber function to remove. |
| 62 | + """ |
| 63 | + if callback in self.subscribers: |
| 64 | + self.subscribers.remove(callback) |
| 65 | + logger.debug(f"Subscriber {callback.__name__} removed.") |
| 66 | + |
| 67 | + def notify_subscribers(self, event: dict): |
| 68 | + """ |
| 69 | + Notifies all subscribers about an event. |
| 70 | +
|
| 71 | + Parameters |
| 72 | + ---------- |
| 73 | + event : dict |
| 74 | + The Kubernetes event data. |
| 75 | + """ |
| 76 | + for subscriber in self.subscribers: |
| 77 | + try: |
| 78 | + subscriber(event) |
| 79 | + except Exception as e: |
| 80 | + logger.exception(f"Error notifying subscriber {subscriber.__name__}: {e}") |
| 81 | + |
| 82 | + def watch_pods(self): |
| 83 | + """ |
| 84 | + Watches Kubernetes pod events and notifies subscribers. |
| 85 | + Runs in a separate thread. |
| 86 | + """ |
| 87 | + v1 = client.CoreV1Api() |
| 88 | + w = watch.Watch() |
| 89 | + resource_version = None |
| 90 | + |
| 91 | + logger.info(f"Started watching pods in namespace '{self.namespace}'.") |
| 92 | + backoff_time = self.backoff_time |
| 93 | + reconnection_attempts = self.reconnection_attempts |
| 94 | + while not self._stop_event.is_set() and reconnection_attempts > 0: |
| 95 | + try: |
| 96 | + kwargs = { |
| 97 | + 'namespace': self.namespace, |
| 98 | + 'timeout_seconds': 0, |
| 99 | + } |
| 100 | + if resource_version: |
| 101 | + kwargs['resource_version'] = resource_version |
| 102 | + first_event = True |
| 103 | + for event in w.stream(v1.list_namespaced_pod, **kwargs): |
| 104 | + if first_event: |
| 105 | + # Reset reconnection attempts and backoff time upon successful reconnection |
| 106 | + reconnection_attempts = self.reconnection_attempts |
| 107 | + backoff_time = self.backoff_time |
| 108 | + first_event = False # Ensure this only happens once per connection |
| 109 | + pod_name = event['object'].metadata.name |
| 110 | + resource_version = event['object'].metadata.resource_version |
| 111 | + event_type = event['type'] |
| 112 | + logger.debug(f"Received event: {event_type} for pod: {pod_name}") |
| 113 | + self.notify_subscribers(event) |
| 114 | + except (urllib3.exceptions.ProtocolError, |
| 115 | + urllib3.exceptions.ReadTimeoutError, |
| 116 | + urllib3.exceptions.ConnectionError) as e: |
| 117 | + reconnection_attempts -= 1 |
| 118 | + logger.exception(f"Encountered network error: {e}") |
| 119 | + logger.info(f"Retrying to watch pods after {backoff_time} seconds...") |
| 120 | + time.sleep(backoff_time) |
| 121 | + backoff_time *= self.backoff_coefficient |
| 122 | + except client.ApiException as e: |
| 123 | + # Resource version is too old and cannot be accessed anymore |
| 124 | + if e.status == 410: |
| 125 | + logger.error("Received 410 Gone error, resetting resource_version and restarting watch.") |
| 126 | + resource_version = None |
| 127 | + continue |
| 128 | + else: |
| 129 | + reconnection_attempts -= 1 |
| 130 | + logger.exception(f"Encountered ApiException: {e}") |
| 131 | + logger.info(f"Retrying to watch pods after {backoff_time} seconds...") |
| 132 | + time.sleep(backoff_time) |
| 133 | + backoff_time *= self.backoff_coefficient |
| 134 | + except StopIteration: |
| 135 | + logger.info("Watch stream ended, restarting watch.") |
| 136 | + continue |
| 137 | + except Exception as e: |
| 138 | + reconnection_attempts -= 1 |
| 139 | + logger.exception(f"Watcher encountered exception: {e}") |
| 140 | + logger.info(f"Retrying to watch pods after {backoff_time} seconds...") |
| 141 | + time.sleep(backoff_time) |
| 142 | + backoff_time *= self.backoff_coefficient |
| 143 | + |
| 144 | + |
| 145 | + def stop(self): |
| 146 | + """ |
| 147 | + Stops the watcher thread gracefully. |
| 148 | + """ |
| 149 | + self._stop_event.set() |
| 150 | + self.watcher_thread.join() |
| 151 | + logger.info(f"ResourceWatcher thread stopped for namespace '{self.namespace}'.") |
0 commit comments