-
Notifications
You must be signed in to change notification settings - Fork 73
feat: add Event.list() for listing existing events #2686
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
threcc
wants to merge
1
commit into
RedHatQE:main
Choose a base branch
from
threcc:feat/event-list
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+76
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| import warnings | ||
| from collections.abc import Generator | ||
| from datetime import datetime, timedelta, timezone | ||
| from typing import Any | ||
|
|
||
| from kubernetes.dynamic import DynamicClient | ||
|
|
@@ -90,6 +91,81 @@ def get( | |
| timeout=timeout, | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _parse_timestamp(event: Any) -> datetime | None: | ||
| """Parse event timestamp, preferring lastTimestamp over creationTimestamp.""" | ||
| timestamp = event.get("lastTimestamp") or event.get("metadata", {}).get("creationTimestamp") | ||
| if not timestamp: | ||
| return None | ||
| try: | ||
| return datetime.fromisoformat(timestamp.replace("Z", "+00:00")) | ||
| except (ValueError, TypeError): | ||
| LOGGER.debug(f"Failed to parse event timestamp: {timestamp}") | ||
| return None | ||
|
|
||
| @classmethod | ||
| def list( | ||
| cls, | ||
| client: DynamicClient, | ||
| namespace: str | None = None, | ||
| field_selector: str | None = None, | ||
| label_selector: str | None = None, | ||
| since_seconds: int = 300, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Validate Negative values currently produce a future cutoff and unintuitive filtering. Add a guard to fail fast. 💡 Proposed fix def list(
cls,
client: DynamicClient,
namespace: str | None = None,
field_selector: str | None = None,
label_selector: str | None = None,
since_seconds: int = 300,
) -> list[Any]:
+ if since_seconds < 0:
+ raise ValueError("since_seconds must be >= 0")Also applies to: 159-159 🤖 Prompt for AI Agents |
||
| ) -> list[Any]: | ||
| """ | ||
| List existing K8s events using a standard API list call (not watch). | ||
| Unlike ``Event.get()`` which uses watch and streams events in real-time, | ||
| this method returns already-existing events immediately. | ||
| Args: | ||
| client: K8s dynamic client. | ||
| namespace: Filter events to this namespace. | ||
| field_selector: Filter events by fields (e.g. ``"type==Warning"``). | ||
| label_selector: Filter events by labels. | ||
| since_seconds: Only return events from the last N seconds (default: 300 = 5 minutes). | ||
| Returns: | ||
| List of event resource objects, sorted by ``lastTimestamp`` descending (most recent first). | ||
| Example: | ||
| List Warning events from the last 5 minutes in a namespace:: | ||
| events = Event.list( | ||
| client=client, | ||
| namespace="my-namespace", | ||
| field_selector="type==Warning", | ||
| ) | ||
| """ | ||
| LOGGER.info("Listing events") | ||
| LOGGER.debug( | ||
| f"list events parameters: namespace={namespace}," | ||
| f" field_selector='{field_selector}', label_selector='{label_selector}'," | ||
| f" since_seconds={since_seconds}" | ||
| ) | ||
|
|
||
| resource = client.resources.get(api_version=cls.api_version, kind=cls.__name__) | ||
| kwargs: dict[str, Any] = {} | ||
| if namespace: | ||
| kwargs["namespace"] = namespace | ||
| if field_selector: | ||
| kwargs["field_selector"] = field_selector | ||
| if label_selector: | ||
| kwargs["label_selector"] = label_selector | ||
|
|
||
| response = resource.get(**kwargs) | ||
| events = response.items or [] | ||
|
|
||
| cutoff = datetime.now(tz=timezone.utc) - timedelta(seconds=since_seconds) | ||
| timed_events: list[tuple[datetime, Any]] = [] | ||
| for event in events: | ||
| event_time = cls._parse_timestamp(event) | ||
| if event_time and event_time >= cutoff: | ||
| timed_events.append((event_time, event)) | ||
|
|
||
| timed_events.sort(key=lambda pair: pair[0], reverse=True) | ||
| return [event for _, event in timed_events] | ||
|
|
||
| @classmethod | ||
| def delete_events( | ||
| cls, | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: RedHatQE/openshift-python-wrapper
Length of output: 249
🏁 Script executed:
Repository: RedHatQE/openshift-python-wrapper
Length of output: 99
🏁 Script executed:
Repository: RedHatQE/openshift-python-wrapper
Length of output: 10161
🏁 Script executed:
Repository: RedHatQE/openshift-python-wrapper
Length of output: 59
Normalize parsed timestamps to timezone-aware UTC to prevent comparison error at runtime.
When a timestamp lacks a timezone indicator (e.g.,
"2026-04-03T12:00:00"),datetime.fromisoformat()returns a naive datetime. Comparing this naive datetime to the timezone-awarecutoffat line 163 raisesTypeError: can't compare offset-naive and offset-aware datetimes, silently bypassing the try-except block at line 102 and crashing thelist()method.Proposed fix
Also applies to: line 163
🤖 Prompt for AI Agents