From d4d1730b6bf3c5b1949e4d2034284858f61fc69f Mon Sep 17 00:00:00 2001 From: Per Johansson Date: Thu, 18 Jan 2024 09:16:13 +0100 Subject: [PATCH] Fix sonarlint reports. Incorrect type hint. Computing complexity for the watch function. --- k8s/base.py | 3 ++- k8s/watcher.py | 21 +++++++++++++-------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/k8s/base.py b/k8s/base.py index 5a3a6fa..f3583ac 100644 --- a/k8s/base.py +++ b/k8s/base.py @@ -21,6 +21,7 @@ import json import logging from collections import namedtuple +from typing import Optional import requests import requests.packages.urllib3 as urllib3 @@ -180,7 +181,7 @@ def _watch_list_url(cls, namespace): return url @classmethod - def _parse_watch_event(cls, line) -> WatchBaseEvent: + def _parse_watch_event(cls, line) -> Optional[WatchBaseEvent]: """ Parse a line from the watch stream into a WatchEvent or WatchBookmark. Raises APIServerError if the line is an error event. diff --git a/k8s/watcher.py b/k8s/watcher.py index f00517e..e81c3b5 100644 --- a/k8s/watcher.py +++ b/k8s/watcher.py @@ -59,17 +59,22 @@ def watch(self, namespace=None): namespace=namespace, resource_version=last_seen_resource_version, allow_bookmarks=True ): last_seen_resource_version = event.resource_version - if not event.has_object(): - continue - o = event.object - key = (o.metadata.name, o.metadata.namespace) - if self._seen.get(key) == o.metadata.resourceVersion and event.type != WatchEvent.DELETED: - continue - self._seen[key] = o.metadata.resourceVersion - yield event + if self._should_yield(event): + yield event except APIServerError as e: # A 410 response indicates our resourceVersion is too old, and we need to do a new quorum read. if e.api_error["code"] == 410: last_seen_resource_version = None else: raise + + def _should_yield(self, event) -> bool: + """Check if this is a new event, and if so, mark it as seen""" + if not event.has_object(): + return False + o = event.object + key = (o.metadata.name, o.metadata.namespace) + if self._seen.get(key) == o.metadata.resourceVersion and event.type != WatchEvent.DELETED: + return False + self._seen[key] = o.metadata.resourceVersion + return True