diff --git a/ROADMAP.md b/ROADMAP.md index ad3655d..876eec9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -41,6 +41,53 @@ O que **NÃO funciona / NÃO existe**: --- +## 🔍 Análise Profunda de Arquitetura e Anti-Patterns (Junho/2026) + +Foi realizada uma varredura completa no projeto e identificamos **gambiarras críticas** e desvios de boas práticas em Python/Flet que devem ser corrigidos na [STORY-14.05](#story-1405-refatoração-de-arquitetura-anti-patterns--gambiarras) antes da adição de novas funcionalidades: + +1. **Supressão Silenciosa de Erros (Error Swallowing)** + - *Onde*: `kubeidea/kube/resources.py` + - *Problema*: Todas as listagens (ex: `list_pods`) e CRUDs possuem um bloco `except Exception: return []` ou `return False` genérico. Isso mascara falhas de conectividade, timeouts e falta de permissão RBAC. O usuário vê uma tela vazia em vez de saber por que falhou. + - *Solução*: Remover os try/except genéricos nos adapters, lançar exceções específicas e tratá-las na camada de UI exibindo *SnackBars* ou painéis de erro. +2. **Quebra do Open/Closed Principle (Switch-Cases Gigantes)** + - *Onde*: `kubeidea/kube/resources.py`, `ui/views/_explorer_detail.py` e `ui/views/_explorer_rows.py`. + - *Problema*: Uso de mega-dicionários globais (como `_KIND_API_MAP`, `_INFO_BUILDERS`, `_ROW_BUILDERS`) mapeando strings literais para funções hardcoded. O arquivo `resources.py` já passa de 1000 linhas. + - *Solução*: Implementar o padrão **Strategy** ou herança polimórfica (ex: uma classe base abstrata `ResourceAdapter` onde cada recurso implementa seus próprios métodos `load()`, `build_ui_row()`, e `build_ui_detail()`). +3. **Monolitismo de Testes** + - *Onde*: `tests/test_resources.py` + - *Problema*: Arquivo gigante (mais de 65KB e 1500 linhas) contendo repetição excessiva de código de setup de Mocks manuais, o que torna a manutenção insustentável. + - *Solução*: Utilizar intensamente `pytest.mark.parametrize` e extrair a lógica repetitiva de Mocks para *fixtures* genéricas no `conftest.py`. +4. **Problemas Práticos com Flet (Bloqueio de UI)** + - *Onde*: `ui/views/explorer.py` (`_render_all_categories`) e módulos de view. + - *Problema*: Loops imensos (`for resource in items: lv.controls.append(...)`) executados de forma imperativa. Falta encapsulamento de estado em componentes granulares. + - *Solução*: Criar controles independentes extraindo a lógica visual para classes dedicadas, e utilizar de forma correta as capacidades assíncronas e features otimizadas (`first_item_prototype=True`) de `ListViews` do Flet para grandes datasets. + +### Plano de Ação Detalhado de Correções + +Para resolver as gambiarras arquiteturais e o débito técnico com segurança (sem quebrar as funcionalidades existentes), a refatoração deve seguir a seguinte ordem de execução estrita (representada nas TASKS da STORY-14.05): + +**Passo 1: Foundation & Tratamento de Erros (TASK-14.05.02)** +- Criar o módulo genérico `kubeidea.core.exceptions` com exceções padronizadas do domínio (`KubeAPIError`, `ResourceNotFoundError`, `RBACAccessError`). +- Atualizar o `kube/client.py` para levantar essas exceções. +- Remover os blocos silenciosos `except Exception: return []` de `kube/resources.py`. Atualizar o `ExplorerView` para capturar as falhas e engatilhar *SnackBars* visuais e estados de "Erro" na UI, garantindo transparência para o usuário final. + +**Passo 2: Injeção de Dependência e Pattern Strategy (TASK-14.05.01)** +- Criar uma interface base `BaseResourceAdapter` (ex: em `kubeidea/kube/adapters/base.py`). +- Extrair a lógica do imenso `kubeidea/kube/resources.py` dividindo-a em pequenas classes adaptadoras específicas (ex: `PodAdapter`, `DeploymentAdapter`). +- Substituir o *switch-case* e os mega-dicionários globais (`_KIND_API_MAP`, etc) por um Registro dinâmico de instâncias instanciadas sob demanda para facilitar escalabilidade e manutenibilidade (Open/Closed Principle). + +**Passo 3: Modernização de UI Flet e Desacoplamento (TASK-14.05.03)** +- Migrar a arquitetura baseada em funções procedurais em `_explorer_rows.py` e `_explorer_detail.py` para Componentes isolados instanciados via classes, implementando a construção via herança de instâncias Flet (ex: isolar ciclos de vida em `did_mount` e `will_unmount`). +- Habilitar propriedades otimizadas do Flet em grandes ListViews como `first_item_prototype=True`. +- Retirar o bloqueio explícito da Thread UI delegando iterações pesadas e renderizações longas com paginação lazy (lotes) suportado via assincronismo real e chamadas ao `page.run_task()`. + +**Passo 4: Saneamento e Modularização de Testes (TASK-14.05.04)** +- Criar um `conftest.py` para registrar Mocks centrais globais do Client Kubernetes (reduzindo centenas de repetições). +- Retalhar o gigantesco arquivo `test_resources.py` (65KB) em test suites orientadas a contexto: `test_pods.py`, `test_deployments.py`, `test_services.py`, etc. +- Empregar maciçamente `@pytest.mark.parametrize` para varrer cenários de teste na nova arquitetura baseada nos Adaptadores, unificando as asserções. + +--- + ## EPIC-01: Resource Explorer Completo > **Objetivo**: Transformar o explorer de uma lista simplificada em um painel completo de visualização, inspeção e gestão de recursos Kubernetes. @@ -613,6 +660,17 @@ O que **NÃO funciona / NÃO existe**: | TASK-14.04.02 | Task | Atualizar `docs/architecture.md` refletindo estado real | ⬚ | | TASK-14.04.03 | Task | Atualizar `README.md` — separar "Features implementadas" de "Planejadas" | ⬚ | +### STORY-14.05: Refatoração de Arquitetura (Anti-patterns & Gambiarras) + +> Identificado após análise profunda: O código sofre de problemas estruturais que dificultarão a manutenção, como supressão de erros globais, funções gigantes baseadas em switch-case de strings e testes excessivamente repetitivos. + +| ID | Tipo | Descrição | Status | +|---|---|---|---| +| TASK-14.05.01 | Task | **Strategy Pattern em Resources**: Eliminar dicionários globais (`_KIND_API_MAP`, `_INFO_BUILDERS`) e implementar um padrão OOP (ex: `ResourceAdapter`) para lidar com listagem/detalhes de recursos sem ferir o princípio Open/Closed. | ⬚ | +| TASK-14.05.02 | Task | **Tratamento de Erros Eficaz**: Remover os `except Exception:` genéricos em `kube/resources.py` que retornam listas vazias silenciosamente. Propagar os erros da API do K8s (ex: 403 Forbidden) para a UI exibir de forma visível ao usuário. | ⬚ | +| TASK-14.05.03 | Task | **Componentização Flet**: Refatorar `_explorer_rows.py` e `_explorer_detail.py` transformando o excesso de funções "builder" procedurais em classes orientadas a componentes, isolando estado interno. | ⬚ | +| TASK-14.05.04 | Task | **Otimização de Testes Monolíticos**: Refatorar `test_resources.py` (atualmente com +65KB e extrema repetição) utilizando `pytest.mark.parametrize` e fixtures dinâmicas para reduzir o boilerplate de mocks. | ⬚ | + --- ## Resumo por EPIC @@ -632,8 +690,8 @@ O que **NÃO funciona / NÃO existe**: | EPIC-11 | CLI Interface | 1 | 7 | 🟢 Baixa | | EPIC-12 | DevSecOps & Quality | 4 | 16 | 🟠 Alta | | EPIC-13 | UX & Polish | 9 | 33 | 🟢 Baixa | -| EPIC-14 | Limpeza Técnica & Debt | 4 | 14 | 🟡 Média | -| **TOTAL** | | **46** | **191** | | +| EPIC-14 | Limpeza Técnica & Debt | 5 | 18 | 🟡 Média | +| **TOTAL** | | **47** | **195** | | --- diff --git a/src/kubeidea/core/exceptions.py b/src/kubeidea/core/exceptions.py new file mode 100644 index 0000000..32c3022 --- /dev/null +++ b/src/kubeidea/core/exceptions.py @@ -0,0 +1,17 @@ +"""Core exception classes for the Kube-IDEA application.""" + +class KubeIdeaError(Exception): + """Base exception for all custom Kube-IDEA errors.""" + pass + +class KubeAPIError(KubeIdeaError): + """Raised when a Kubernetes API call fails.""" + pass + +class ResourceNotFoundError(KubeAPIError): + """Raised when a requested Kubernetes resource is not found (HTTP 404).""" + pass + +class RBACAccessError(KubeAPIError): + """Raised when the user lacks permissions to perform an action (HTTP 403).""" + pass diff --git a/src/kubeidea/kube/adapters/__init__.py b/src/kubeidea/kube/adapters/__init__.py new file mode 100644 index 0000000..b2fa99d --- /dev/null +++ b/src/kubeidea/kube/adapters/__init__.py @@ -0,0 +1,46 @@ +"""Adapters package for Kubernetes resources.""" + +from kubeidea.kube.adapters.registry import AdapterRegistry +from kubeidea.kube.adapters.workloads import PodAdapter, DeploymentAdapter +from kubeidea.kube.adapters.legacy import LegacyAdapter + +from kubeidea.kube.resources import ( + list_configmaps, + list_cronjobs, + list_daemonsets, + list_events, + list_hpa, + list_ingresses, + list_jobs, + list_networkpolicies, + list_nodes, + list_persistentvolumeclaims, + list_persistentvolumes, + list_secrets, + list_serviceaccounts, + list_services, + list_statefulsets, +) + +def init_registry(): + AdapterRegistry.register(PodAdapter()) + AdapterRegistry.register(DeploymentAdapter()) + + # Legacy adapters + AdapterRegistry.register(LegacyAdapter("StatefulSet", list_statefulsets)) + AdapterRegistry.register(LegacyAdapter("DaemonSet", list_daemonsets)) + AdapterRegistry.register(LegacyAdapter("Job", list_jobs)) + AdapterRegistry.register(LegacyAdapter("CronJob", list_cronjobs)) + AdapterRegistry.register(LegacyAdapter("Service", list_services)) + AdapterRegistry.register(LegacyAdapter("Ingress", list_ingresses)) + AdapterRegistry.register(LegacyAdapter("NetworkPolicy", list_networkpolicies)) + AdapterRegistry.register(LegacyAdapter("ConfigMap", list_configmaps)) + AdapterRegistry.register(LegacyAdapter("Secret", list_secrets)) + AdapterRegistry.register(LegacyAdapter("ServiceAccount", list_serviceaccounts)) + AdapterRegistry.register(LegacyAdapter("PersistentVolume", list_persistentvolumes, True)) + AdapterRegistry.register(LegacyAdapter("PersistentVolumeClaim", list_persistentvolumeclaims)) + AdapterRegistry.register(LegacyAdapter("Node", list_nodes, True)) + AdapterRegistry.register(LegacyAdapter("HorizontalPodAutoscaler", list_hpa)) + AdapterRegistry.register(LegacyAdapter("Event", list_events)) + +init_registry() diff --git a/src/kubeidea/kube/adapters/base.py b/src/kubeidea/kube/adapters/base.py new file mode 100644 index 0000000..fb1e10f --- /dev/null +++ b/src/kubeidea/kube/adapters/base.py @@ -0,0 +1,49 @@ +"""Base interfaces for Kubernetes resource adapters.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Any + +import flet as ft + +class ResourceAdapter(ABC): + """Base class for all Kubernetes resource adapters.""" + + @property + @abstractmethod + def kind(self) -> str: + """The Kubernetes API Kind (e.g. 'Pod', 'Deployment').""" + pass + + @property + @abstractmethod + def plural(self) -> str: + """The plural display name (e.g. 'Pods', 'Deployments').""" + pass + + @abstractmethod + def list_items(self, api_client: Any, namespace: str = "default") -> list[Any]: + """Fetch all resources of this kind in the given namespace. + + Must raise kubeidea.core.exceptions.KubeAPIError on failure, + instead of returning empty lists silently. + """ + pass + + def delete_item(self, api_client: Any, name: str, namespace: str) -> bool: + """Delete a resource of this kind by name and namespace. + + Raises: + NotImplementedError: If deletion is not supported. + KubeAPIError: On API failure. + """ + raise NotImplementedError(f"Delete not supported for {self.kind}") + + def build_row(self, resource: Any, on_click: Any) -> ft.Control: + """Build the UI row for the explorer list.""" + raise NotImplementedError(f"UI row building not supported for {self.kind}") + + def build_detail(self, resource: Any, rows: list[ft.Control]) -> None: + """Append UI detail rows to the given list for the explorer detail panel.""" + raise NotImplementedError(f"UI detail building not supported for {self.kind}") diff --git a/src/kubeidea/kube/adapters/legacy.py b/src/kubeidea/kube/adapters/legacy.py new file mode 100644 index 0000000..b27c7aa --- /dev/null +++ b/src/kubeidea/kube/adapters/legacy.py @@ -0,0 +1,25 @@ +"""Legacy adapter to bridge unmigrated functions.""" + +from typing import Any, Callable +from kubeidea.kube.adapters.base import ResourceAdapter + +class LegacyAdapter(ResourceAdapter): + """Wrapper for legacy list functions in resources.py.""" + + def __init__(self, kind: str, list_func: Callable[..., list[Any]], is_cluster_scoped: bool = False): + self._kind = kind + self._list_func = list_func + self._is_cluster_scoped = is_cluster_scoped + + @property + def kind(self) -> str: + return self._kind + + @property + def plural(self) -> str: + return self._kind + "s" + + def list_items(self, api_client: Any, namespace: str = "default") -> list[Any]: + if self._is_cluster_scoped: + return self._list_func(api_client) + return self._list_func(api_client, namespace=namespace) diff --git a/src/kubeidea/kube/adapters/registry.py b/src/kubeidea/kube/adapters/registry.py new file mode 100644 index 0000000..5517852 --- /dev/null +++ b/src/kubeidea/kube/adapters/registry.py @@ -0,0 +1,30 @@ +"""Registry for Kubernetes resource adapters.""" + +from __future__ import annotations + +from kubeidea.kube.adapters.base import ResourceAdapter + +class AdapterRegistry: + """Central registry for ResourceAdapters.""" + + _adapters: dict[str, ResourceAdapter] = {} + + @classmethod + def register(cls, adapter: ResourceAdapter) -> None: + """Register a resource adapter.""" + cls._adapters[adapter.kind] = adapter + + @classmethod + def get(cls, kind: str) -> ResourceAdapter: + """Get an adapter by kind. + + Raises ValueError if not found. + """ + if kind not in cls._adapters: + raise ValueError(f"No adapter registered for kind: {kind}") + return cls._adapters[kind] + + @classmethod + def get_all(cls) -> list[ResourceAdapter]: + """Get all registered adapters.""" + return list(cls._adapters.values()) diff --git a/src/kubeidea/kube/adapters/workloads.py b/src/kubeidea/kube/adapters/workloads.py new file mode 100644 index 0000000..a64004c --- /dev/null +++ b/src/kubeidea/kube/adapters/workloads.py @@ -0,0 +1,110 @@ +"""Adapters for workload resources (Pods, Deployments, etc.).""" + +from typing import Any +import flet as ft +from kubeidea.kube.adapters.base import ResourceAdapter +from kubeidea.kube.models import PodInfo, ContainerInfo, DeploymentInfo + +class PodAdapter(ResourceAdapter): + @property + def kind(self) -> str: + return "Pod" + + @property + def plural(self) -> str: + return "Pods" + + def list_items(self, api_client: Any, namespace: str = "default") -> list[PodInfo]: + from kubernetes.client import CoreV1Api + from kubeidea.core.exceptions import KubeAPIError + try: + v1 = CoreV1Api(api_client=api_client) + pod_list = v1.list_namespaced_pod(namespace=namespace) + except Exception as exc: + raise KubeAPIError(f"API request failed: {exc}") from exc + + results = [] + for pod in pod_list.items: + if not pod.metadata: + continue + containers = [] + total_restarts = 0 + ready_count = 0 + total_count = 0 + if pod.status and pod.status.container_statuses: + for cs in pod.status.container_statuses: + total_count += 1 + total_restarts += cs.restart_count or 0 + if cs.ready: + ready_count += 1 + + state_dict = cs.state.to_dict() if cs.state else {} + state_keys = [k for k, v in state_dict.items() if v is not None] + state = state_keys[0] if state_keys else "Unknown" + + containers.append( + ContainerInfo( + name=cs.name, + image=cs.image, + ready=cs.ready, + restarts=cs.restart_count or 0, + state=state, + ) + ) + + status = pod.status.phase if pod.status else "Unknown" + + from kubeidea.kube.resources import _resource_age + results.append( + PodInfo( + name=pod.metadata.name, + namespace=pod.metadata.namespace or namespace, + status=status, + age=_resource_age(pod.metadata.creation_timestamp), + ready=f"{ready_count}/{total_count}", + restarts=total_restarts, + node=pod.spec.node_name if pod.spec else None, + ip=pod.status.pod_ip if pod.status else None, + containers=containers, + ) + ) + return results + +class DeploymentAdapter(ResourceAdapter): + @property + def kind(self) -> str: + return "Deployment" + + @property + def plural(self) -> str: + return "Deployments" + + def list_items(self, api_client: Any, namespace: str = "default") -> list[DeploymentInfo]: + from kubernetes.client import AppsV1Api + from kubeidea.core.exceptions import KubeAPIError + try: + apps_v1 = AppsV1Api(api_client=api_client) + dep_list = apps_v1.list_namespaced_deployment(namespace=namespace) + except Exception as exc: + raise KubeAPIError(f"API request failed: {exc}") from exc + + results = [] + for dep in dep_list.items: + if not dep.metadata: + continue + status = dep.status + spec = dep.spec + + from kubeidea.kube.resources import _resource_age + results.append( + DeploymentInfo( + name=dep.metadata.name, + namespace=dep.metadata.namespace or namespace, + age=_resource_age(dep.metadata.creation_timestamp), + replicas=spec.replicas if spec else 0, + ready_replicas=status.ready_replicas if status and status.ready_replicas else 0, + available_replicas=status.available_replicas if status and status.available_replicas else 0, + strategy=spec.strategy.type if spec and spec.strategy else "Unknown", + ) + ) + return results diff --git a/src/kubeidea/kube/client.py b/src/kubeidea/kube/client.py index ddafc69..989b3a8 100644 --- a/src/kubeidea/kube/client.py +++ b/src/kubeidea/kube/client.py @@ -46,8 +46,12 @@ def list_contexts(self) -> list[KubeContext]: ) for ctx in contexts ] - except Exception: - return [] + except FileNotFoundError as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"Kubeconfig file not found: {self.kubeconfig_path}") from exc + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"Failed to list contexts: {exc}") from exc def load_context(self, context_name: str) -> Any: """Load a specific kubeconfig context and return an API client. @@ -59,6 +63,11 @@ def load_context(self, context_name: str) -> Any: A configured ``kubernetes.client.ApiClient`` for the given context. """ from kubernetes import client, config + from kubeidea.core.exceptions import KubeAPIError + + try: + config.load_kube_config(config_file=self.kubeconfig_path, context=context_name) + return client.ApiClient() + except Exception as exc: + raise KubeAPIError(f"Failed to load context {context_name}: {exc}") from exc - config.load_kube_config(config_file=self.kubeconfig_path, context=context_name) - return client.ApiClient() diff --git a/src/kubeidea/kube/resources.py b/src/kubeidea/kube/resources.py index 9cb5e08..8b6e538 100644 --- a/src/kubeidea/kube/resources.py +++ b/src/kubeidea/kube/resources.py @@ -82,9 +82,9 @@ def list_pods(api_client: Any, namespace: str = "default") -> list[PodInfo]: try: v1 = CoreV1Api(api_client=api_client) pod_list = v1.list_namespaced_pod(namespace=namespace) - except Exception: - logger.exception("Failed to list pods in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc results: list[PodInfo] = [] for pod in pod_list.items: @@ -146,9 +146,9 @@ def list_deployments(api_client: Any, namespace: str = "default") -> list[Deploy try: apps = AppsV1Api(api_client=api_client) dep_list = apps.list_namespaced_deployment(namespace=namespace) - except Exception: - logger.exception("Failed to list deployments in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ DeploymentInfo( @@ -178,9 +178,9 @@ def list_services(api_client: Any, namespace: str = "default") -> list[ServiceIn try: v1 = CoreV1Api(api_client=api_client) svc_list = v1.list_namespaced_service(namespace=namespace) - except Exception: - logger.exception("Failed to list services in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc results: list[ServiceInfo] = [] for svc in svc_list.items: @@ -216,9 +216,9 @@ def list_nodes(api_client: Any) -> list[NodeInfo]: try: v1 = CoreV1Api(api_client=api_client) node_list = v1.list_node() - except Exception: - logger.exception("Failed to list nodes") - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc results: list[NodeInfo] = [] for node in node_list.items: @@ -264,9 +264,9 @@ def list_configmaps(api_client: Any, namespace: str = "default") -> list[ConfigM try: v1 = CoreV1Api(api_client=api_client) cm_list = v1.list_namespaced_config_map(namespace=namespace) - except Exception: - logger.exception("Failed to list configmaps in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ ConfigMapInfo( @@ -292,9 +292,9 @@ def list_secrets(api_client: Any, namespace: str = "default") -> list[SecretInfo try: v1 = CoreV1Api(api_client=api_client) sec_list = v1.list_namespaced_secret(namespace=namespace) - except Exception: - logger.exception("Failed to list secrets in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ SecretInfo( @@ -321,9 +321,9 @@ def list_ingresses(api_client: Any, namespace: str = "default") -> list[IngressI try: net = NetworkingV1Api(api_client=api_client) ing_list = net.list_namespaced_ingress(namespace=namespace) - except Exception: - logger.exception("Failed to list ingresses in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc results: list[IngressInfo] = [] for ing in ing_list.items: @@ -364,9 +364,9 @@ def list_jobs(api_client: Any, namespace: str = "default") -> list[JobInfo]: try: batch = BatchV1Api(api_client=api_client) job_list = batch.list_namespaced_job(namespace=namespace) - except Exception: - logger.exception("Failed to list jobs in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc results: list[JobInfo] = [] for job in job_list.items: @@ -412,9 +412,9 @@ def list_cronjobs(api_client: Any, namespace: str = "default") -> list[CronJobIn try: batch = BatchV1Api(api_client=api_client) cj_list = batch.list_namespaced_cron_job(namespace=namespace) - except Exception: - logger.exception("Failed to list cronjobs in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ CronJobInfo( @@ -443,9 +443,9 @@ def list_statefulsets(api_client: Any, namespace: str = "default") -> list[State try: apps = AppsV1Api(api_client=api_client) ss_list = apps.list_namespaced_stateful_set(namespace=namespace) - except Exception: - logger.exception("Failed to list statefulsets in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ StatefulSetInfo( @@ -472,9 +472,9 @@ def list_daemonsets(api_client: Any, namespace: str = "default") -> list[DaemonS try: apps = AppsV1Api(api_client=api_client) ds_list = apps.list_namespaced_daemon_set(namespace=namespace) - except Exception: - logger.exception("Failed to list daemonsets in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ DaemonSetInfo( @@ -502,9 +502,9 @@ def list_persistentvolumes(api_client: Any) -> list[PersistentVolumeInfo]: try: v1 = CoreV1Api(api_client=api_client) pv_list = v1.list_persistent_volume() - except Exception: - logger.exception("Failed to list persistent volumes") - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc results: list[PersistentVolumeInfo] = [] for pv in pv_list.items: @@ -540,9 +540,9 @@ def list_persistentvolumeclaims(api_client: Any, namespace: str = "default") -> try: v1 = CoreV1Api(api_client=api_client) pvc_list = v1.list_namespaced_persistent_volume_claim(namespace=namespace) - except Exception: - logger.exception("Failed to list PVCs in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc results: list[PersistentVolumeClaimInfo] = [] for pvc in pvc_list.items: @@ -576,9 +576,9 @@ def list_hpa(api_client: Any, namespace: str = "default") -> list[HPAInfo]: try: auto = AutoscalingV2Api(api_client=api_client) hpa_list = auto.list_namespaced_horizontal_pod_autoscaler(namespace=namespace) - except Exception: - logger.exception("Failed to list HPAs in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ HPAInfo( @@ -611,9 +611,9 @@ def list_networkpolicies(api_client: Any, namespace: str = "default") -> list[Ne try: net = NetworkingV1Api(api_client=api_client) np_list = net.list_namespaced_network_policy(namespace=namespace) - except Exception: - logger.exception("Failed to list network policies in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ NetworkPolicyInfo( @@ -640,9 +640,9 @@ def list_serviceaccounts(api_client: Any, namespace: str = "default") -> list[Se try: v1 = CoreV1Api(api_client=api_client) sa_list = v1.list_namespaced_service_account(namespace=namespace) - except Exception: - logger.exception("Failed to list service accounts in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc return [ ServiceAccountInfo( @@ -678,9 +678,9 @@ def list_events( ) else: ev_list = v1.list_namespaced_event(namespace=namespace) - except Exception: - logger.exception("Failed to list events in namespace %s", namespace) - return [] + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"API request failed: {exc}") from exc results: list[EventInfo] = [] for ev in ev_list.items: @@ -820,9 +820,9 @@ def delete_resource(api_client: Any, kind: str, name: str, namespace: str = "def logger.warning("delete_resource: unsupported kind %s", kind) return False return True - except Exception: - logger.exception("Failed to delete %s/%s in %s", kind, name, namespace) - return False + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"Action failed: {exc}") from exc def scale_resource( @@ -853,9 +853,9 @@ def scale_resource( logger.warning("scale_resource: unsupported kind %s", kind) return False return True - except Exception: - logger.exception("Failed to scale %s/%s in %s", kind, name, namespace) - return False + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"Action failed: {exc}") from exc def restart_resource(api_client: Any, kind: str, name: str, namespace: str) -> bool: @@ -892,9 +892,9 @@ def restart_resource(api_client: Any, kind: str, name: str, namespace: str) -> b logger.warning("restart_resource: unsupported kind %s", kind) return False return True - except Exception: - logger.exception("Failed to restart %s/%s in %s", kind, name, namespace) - return False + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"Action failed: {exc}") from exc # --------------------------------------------------------------------------- @@ -1020,6 +1020,6 @@ def apply_resource(api_client: Any, manifest_yaml: str) -> bool: else: getattr(api, replace_method)(name=name, body=doc) return True - except Exception: - logger.exception("Failed to replace %s/%s in %s", kind, name, namespace) - return False + except Exception as exc: + from kubeidea.core.exceptions import KubeAPIError + raise KubeAPIError(f"Action failed: {exc}") from exc diff --git a/src/kubeidea/ui/components/rows/base.py b/src/kubeidea/ui/components/rows/base.py new file mode 100644 index 0000000..eb5be50 --- /dev/null +++ b/src/kubeidea/ui/components/rows/base.py @@ -0,0 +1,44 @@ +"""Base classes for resource rows.""" + +from typing import Any, Callable +import flet as ft + +ClickHandler = Callable[[str, Any], None] + +class ResourceRow(ft.Container): + """Base component for resource rows. Inherits from ft.Container since UserControl is deprecated.""" + + def __init__(self, resource: Any, on_click: ClickHandler, kind: str): + super().__init__() + self.resource = resource + self.on_click_handler = on_click + self.kind = kind + + self.padding = ft.Padding.symmetric(horizontal=12, vertical=5) + self.border_radius = 4 + self.on_click = self._handle_click + + self.content = ft.Row( + controls=self.build_controls(), + vertical_alignment=ft.CrossAxisAlignment.CENTER, + spacing=8, + ) + + def _handle_click(self, _e: Any) -> None: + self.on_click_handler(self.kind, self.resource) + + def build_controls(self) -> list[ft.Control]: + """Override to provide row-specific controls.""" + return [ft.Text(getattr(self.resource, "name", "Unknown"))] + + # Utility methods for subclasses + def _pill(self, text: str, color: str) -> ft.Container: + return ft.Container( + content=ft.Text(text, size=11, color=color), + bgcolor=ft.Colors.with_opacity(0.12, color), + padding=ft.Padding.symmetric(horizontal=6, vertical=1), + border_radius=4, + ) + + def _dim(self, text: str) -> ft.Text: + return ft.Text(text, size=11, color=ft.Colors.GREY_400) diff --git a/src/kubeidea/ui/components/rows/workloads.py b/src/kubeidea/ui/components/rows/workloads.py new file mode 100644 index 0000000..defce97 --- /dev/null +++ b/src/kubeidea/ui/components/rows/workloads.py @@ -0,0 +1,29 @@ +"""Workload rows for Explorer.""" + +import flet as ft +from kubeidea.kube.models import PodInfo, DeploymentInfo +from kubeidea.ui.components.rows.base import ResourceRow +from kubeidea.ui.views._explorer_rows import STATUS_COLORS + +class PodRow(ResourceRow): + def build_controls(self) -> list[ft.Control]: + pod: PodInfo = self.resource + color = STATUS_COLORS.get(pod.status, ft.Colors.GREY_500) + return [ + ft.Icon(ft.Icons.CIRCLE, size=10, color=color), + ft.Text(pod.name, size=12, expand=True), + self._dim(pod.ready), + self._dim(f"↻{pod.restarts}"), + self._dim(pod.age), + ] + +class DeploymentRow(ResourceRow): + def build_controls(self) -> list[ft.Control]: + dep: DeploymentInfo = self.resource + color = ft.Colors.GREEN_400 if dep.ready_replicas == dep.replicas else ft.Colors.ORANGE_400 + return [ + ft.Icon(ft.Icons.LAYERS, size=14, color=color), + ft.Text(dep.name, size=12, expand=True), + self._dim(f"{dep.ready_replicas}/{dep.replicas}"), + self._dim(dep.age), + ] diff --git a/src/kubeidea/ui/views/clusters.py b/src/kubeidea/ui/views/clusters.py index 507d052..bc44d6f 100644 --- a/src/kubeidea/ui/views/clusters.py +++ b/src/kubeidea/ui/views/clusters.py @@ -80,8 +80,37 @@ def __init__( # ── data ────────────────────────────────────────────────────────── def _load_contexts(self) -> None: - self._contexts = self._manager.list_contexts() self._context_list.controls.clear() + + try: + self._contexts = self._manager.list_contexts() + except Exception as exc: + self._contexts = [] + self._status_text.value = f"Error: {exc}" + self._status_text.color = ft.Colors.RED_400 + self._context_list.controls.append( + ft.Container( + content=ft.Column( + controls=[ + ft.Icon(ft.Icons.ERROR_OUTLINE, size=40, color=ft.Colors.RED_400), + ft.Text("Failed to load kubeconfig", size=14), + ft.Text( + str(exc), + size=11, + color=ft.Colors.GREY_500, + ), + ], + horizontal_alignment=ft.CrossAxisAlignment.CENTER, + spacing=8, + ), + alignment=ft.Alignment(0, 0), + expand=True, + padding=40, + ) + ) + if self._page.controls: + self._page.update() + return if not self._contexts: self._status_text.value = f"No contexts found in {self._manager.kubeconfig_path}" diff --git a/src/kubeidea/ui/views/explorer.py b/src/kubeidea/ui/views/explorer.py index aa957da..9e94745 100644 --- a/src/kubeidea/ui/views/explorer.py +++ b/src/kubeidea/ui/views/explorer.py @@ -17,25 +17,7 @@ import flet as ft from kubeidea.core.context import AppContext -from kubeidea.kube.resources import ( - list_configmaps, - list_cronjobs, - list_daemonsets, - list_deployments, - list_events, - list_hpa, - list_ingresses, - list_jobs, - list_networkpolicies, - list_nodes, - list_persistentvolumeclaims, - list_persistentvolumes, - list_pods, - list_secrets, - list_serviceaccounts, - list_services, - list_statefulsets, -) +from kubeidea.kube.adapters import AdapterRegistry from kubeidea.ui.views._explorer_detail import DetailPanel from kubeidea.ui.views._explorer_rows import ( CATEGORIES, @@ -45,27 +27,6 @@ logger = logging.getLogger(__name__) -# ── Loader registry (kind → callable) ──────────────────────────── -_LOADERS: dict[str, Any] = { - "Pod": list_pods, - "Deployment": list_deployments, - "StatefulSet": list_statefulsets, - "DaemonSet": list_daemonsets, - "Job": list_jobs, - "CronJob": list_cronjobs, - "Service": list_services, - "Ingress": list_ingresses, - "NetworkPolicy": list_networkpolicies, - "ConfigMap": list_configmaps, - "Secret": list_secrets, - "ServiceAccount": list_serviceaccounts, - "PersistentVolume": list_persistentvolumes, - "PersistentVolumeClaim": list_persistentvolumeclaims, - "Node": list_nodes, - "HorizontalPodAutoscaler": list_hpa, - "Event": list_events, -} - # Resources whose loader does NOT accept a namespace argument _CLUSTER_SCOPED: set[str] = {"Node", "PersistentVolume"} @@ -301,27 +262,44 @@ async def refresh(self) -> None: self._ns_dropdown.options = [ft.DropdownOption(key=ns) for ns in self._ctx.namespaces] self._ns_dropdown.value = self._ctx.current_namespace - await asyncio.to_thread(self._load_all_resources) + errors = await asyncio.to_thread(self._load_all_resources) self._render_all_categories() + + if errors: + self._page.snack_bar = ft.SnackBar( + content=ft.Text(f"Errors loading some resources:\n" + "\n".join(errors)), + bgcolor=ft.Colors.RED_800, + ) + self._page.snack_bar.open = True + self._page.update() # ── data loading ────────────────────────────────────────────── - def _load_all_resources(self) -> None: + def _load_all_resources(self) -> list[str]: """Fetch every resource kind from the cluster.""" client = self._ctx.api_client + errors = [] if not client: - return + return errors ns = self._ctx.current_namespace - for kind, loader in _LOADERS.items(): + + from kubeidea.core.exceptions import KubeAPIError + + for adapter in AdapterRegistry.get_all(): + kind = adapter.kind try: - if kind in _CLUSTER_SCOPED: - self._data[kind] = loader(client) - else: - self._data[kind] = loader(client, ns) + self._data[kind] = adapter.list_items(client, namespace=ns) + except KubeAPIError as exc: + logger.warning("API Error loading %s: %s", kind, exc) + self._data[kind] = [] + errors.append(f"{kind}: {exc}") except Exception as exc: logger.warning("Failed to load %s: %s", kind, exc) self._data[kind] = [] + errors.append(f"{kind}: Unexpected error") + + return errors # ── rendering ───────────────────────────────────────────────── diff --git a/tests/test_kube_client.py b/tests/test_kube_client.py index e34c5e5..1461be0 100644 --- a/tests/test_kube_client.py +++ b/tests/test_kube_client.py @@ -24,6 +24,8 @@ def test_kube_config_manager_default_path() -> None: def test_list_contexts_graceful_on_missing_file() -> None: """list_contexts should return empty list when kubeconfig is missing.""" + import pytest + from kubeidea.core.exceptions import KubeAPIError mgr = KubeConfigManager(kubeconfig_path="/tmp/nonexistent-kubeconfig") - contexts = mgr.list_contexts() - assert contexts == [] + with pytest.raises(KubeAPIError, match="Kubeconfig file not found"): + mgr.list_contexts()