Skip to content
Open
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
62 changes: 60 additions & 2 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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** | |

---

Expand Down
17 changes: 17 additions & 0 deletions src/kubeidea/core/exceptions.py
Original file line number Diff line number Diff line change
@@ -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
46 changes: 46 additions & 0 deletions src/kubeidea/kube/adapters/__init__.py
Original file line number Diff line number Diff line change
@@ -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()
49 changes: 49 additions & 0 deletions src/kubeidea/kube/adapters/base.py
Original file line number Diff line number Diff line change
@@ -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}")
25 changes: 25 additions & 0 deletions src/kubeidea/kube/adapters/legacy.py
Original file line number Diff line number Diff line change
@@ -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)
30 changes: 30 additions & 0 deletions src/kubeidea/kube/adapters/registry.py
Original file line number Diff line number Diff line change
@@ -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())
110 changes: 110 additions & 0 deletions src/kubeidea/kube/adapters/workloads.py
Original file line number Diff line number Diff line change
@@ -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
17 changes: 13 additions & 4 deletions src/kubeidea/kube/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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()
Loading
Loading