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: 2 additions & 0 deletions k8s/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ Register each manifest, Helm release and post-Helm step that runs in the cluster
- kubectl and helm on PATH (installed by devcontainer features)
- standard Kubernetes context configuration (the CLI uses `$KUBECONFIG` or defaults to `~/.kube/config`)

Kubernetes supports `kubectl` within one minor version of the API server. The `tools.lock` file tracks a current `kubectl` release. The homelab cluster runs Kubernetes 1.31 (`v1.31.4+k3s1`), which stays outside the supported skew range until dan-petty/homelab#3 lands. We do not pin `kubectl` to 1.31 or 1.32, because both versions are end of life and the devcontainer minikube runs a current release.

## Quick Start

```bash
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-26
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Design: Kubernetes Version Skew Verification

## Context
See `proposal.md` for motivation and system constraints.

## Goals / Non-Goals

**Goals:**
- Include `server_version` in `Snapshot` via `VersionApi.get_code`.
- Add `get_code` to `plan_doctor_requests` so `--dry-run` shows the call.
- Provide pure helper functions to parse versions and determine skew according to Kubernetes skew policy.
- Emit warning findings in `devops k8s doctor` for kubectl skew (> 1 minor) and kubelet skew (> 3 minors older or newer).
- Emit a console warning in `devops k8s deploy-stack` when kubectl skew is detected, without aborting execution.
- Document skew policy and homelab status in `k8s/README.md`.

**Non-Goals:**
- Upgrading k3s or kubelet binaries in the homelab cluster (tracked in dan-petty/homelab#3).
- Downgrading or pinning older `kubectl` versions in `tools.lock`.
- Halting or aborting `deploy-stack` execution on version skew.

## Decisions

### Decision 1: Version parsing with `packaging.version.Version`
- **Choice**: Use `packaging.version.Version` to parse Kubernetes semantic versions including build metadata (e.g. `v1.31.4+k3s1`).
- **Alternative Considered**: Custom regex parsing.
- **Evidence / Rationale**: Regex parsing is brittle and fails on complex build tags or pre-release metadata. `packaging` is an existing dependency and handles PEP 440 versions reliably.

### Decision 2: Cache `server_version` in `KubernetesService`
- **Choice**: In `KubernetesService.is_cluster_reachable()`, retain `git_version` from `VersionApi.get_code()` in cache and expose `server_version(context)` method.
- **Alternative Considered**: Spawning `kubectl version -o json` or making redundant API calls.
- **Evidence / Rationale**: `is_cluster_reachable()` already probes `VersionApi.get_code()` during reachability checks. Capturing this result incurs zero additional network overhead.

### Decision 3: Pure version-skew diagnostic functions
- **Choice**: Implement `check_kubectl_version_skew(server_ver, kubectl_ver)` and `diagnose_version_skew(snapshot, kubectl_ver)` as pure helper functions that accept version strings or snapshots and return findings or formatted warnings.
- **Alternative Considered**: Direct inline logic within CLI commands.
- **Evidence / Rationale**: Pure functions enable complete unit test coverage with fake data without needing active cluster connections or monkeypatching subprocesses.

## Risks / Trade-offs

- **[Risk] Unconventional or unparseable version string returned by custom Kubernetes builds.**
→ *Mitigation*: Wrap version parsing in error handling; if parsing fails, omit the skew finding rather than raising an unhandled exception.
- **[Risk] Minor discrepancy in kubectl vs server releases during upgrade transitions.**
→ *Mitigation*: Emit findings and logs as `warning` severity rather than `critical`, ensuring workflows are alerted without being blocked.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Proposal: Kubernetes Version Skew Verification

## Why
devops-cli pins `kubectl` at version 1.37.1 in `tools.lock`, while the target homelab cluster runs Kubernetes 1.31 (`v1.31.4+k3s1`), leaving client and server six minor versions apart (#1640). Upstream Kubernetes supports `kubectl` only within one minor version of the API server and kubelets within three minor versions, yet `devops k8s doctor` and `devops k8s deploy-stack` execute without warning about this skew.

## What Changes
- Add `server_version` to `Snapshot` in `src/devops_cli/k8s/doctor.py`, populated via `VersionApi.get_code` during snapshot collection.
- Register `get_code` in `plan_doctor_requests` so `devops k8s doctor --dry-run` reports the planned call.
- Add pure helper functions to parse versions using `packaging.version.Version` and evaluate skew for both `kubectl` and node kubelets.
- Add a `version-skew` diagnostic rule to `devops k8s doctor` that warns if `kubectl` minor skew exceeds 1 or if any node kubelet is older than the API server by more than 3 minor versions.
- Emit a warning in `devops k8s deploy-stack` before applying manifests or Helm releases when `kubectl` version skew is detected, without aborting execution.
- Update `k8s/README.md` Prerequisites to document the version skew policy, current `tools.lock` pin, and homelab status.

This change fits in one pull request.

## Capabilities

### New Capabilities
- `k8s-doctor`: Cluster diagnosis, node and workload rule evaluation, request planning, and version-skew reporting.

### Modified Capabilities
- `k8s-helm-deploy`: Add kubectl version skew detection and warning to stack deployment workflow before applying resources.

## Impact
- Affected code: `src/devops_cli/k8s/doctor.py`, `src/devops_cli/k8s/service.py`, `src/devops_cli/commands/k8s/diagnostics.py`, `src/devops_cli/commands/k8s/stack_lifecycle.py`, `src/devops_cli/config/constants.py`, `k8s/README.md`.
- No breaking API changes or dependency changes; `packaging` is already a project dependency.

## Feasibility
- Upstream Kubernetes version skew documentation confirms `kubectl` is supported within $\pm 1$ minor version of `kube-apiserver`, and kubelet is supported up to 3 minor versions older and no newer than `kube-apiserver`.
- `packaging.version.Version` successfully parses semantic versions and build tags such as `v1.31.4+k3s1` and `1.37.1`.
- `VersionApi.get_code()` in the official Kubernetes Python client returns `VersionInfo` with attribute `git_version`.
- `devops_cli.tools_lock.load_tools_lock().binary["kubectl"].version` returns the pinned `1.37.1` version string.

## Existing Tool Considered
We evaluated using `kubectl version --client -o json` as an external subprocess. Spawning a subprocess adds unnecessary latency and requires a functioning `kubectl` binary on the host PATH. We instead utilize the in-process `VersionApi.get_code` call already performed by `KubernetesService` and parse versions with standard `packaging.version.Version`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Spec Delta

## Purpose

Diagnose Kubernetes cluster deployment health, collect API snapshots, verify component version skew, and recommend remediations.

## ADDED Requirements

### Requirement: Snapshot collection and dry run
The doctor SHALL collect API objects from the Kubernetes cluster into a diagnostic snapshot, including server version, nodes, pods, and events. When executed with `--dry-run`, doctor SHALL render the planned requests without contacting the cluster.

#### Scenario: Dry run lists version and cluster requests
- **WHEN** `devops k8s doctor --dry-run` is invoked
- **THEN** the request plan includes `get_code cluster`, `list_node cluster`, and workload listings without executing them

#### Scenario: Server version is captured in snapshot
- **WHEN** doctor collects cluster state from an active cluster
- **THEN** `Snapshot.server_version` contains the Kubernetes API server gitVersion string

### Requirement: Version skew diagnostic rule
The doctor SHALL evaluate version skew between the pinned `kubectl` binary, the API server, and node kubelets according to the Kubernetes version skew policy. Skew exceeding supported limits SHALL produce warning findings.

#### Scenario: Kubectl version skew exceeds one minor version
- **WHEN** the locked `kubectl` minor version differs from the API server minor version by more than one
- **THEN** doctor generates a cluster warning finding naming both versions and the supported server version range

#### Scenario: Kubectl version matches supported skew
- **WHEN** the locked `kubectl` minor version is within one minor of the API server minor version
- **THEN** doctor generates no version skew finding for `kubectl`

#### Scenario: Node kubelet is older than API server by more than three minor versions
- **WHEN** a node reports a `kubeletVersion` more than three minor versions older than the API server
- **THEN** doctor generates a cluster warning finding for that node identifying the kubelet version and the supported range

#### Scenario: Server version is empty or unavailable
- **WHEN** the cluster snapshot contains no server version
- **THEN** doctor skips version skew evaluation without raising an unhandled exception
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Spec Delta

## ADDED Requirements

### Requirement: Kubectl version skew notification
Before deploying stack resources or applying Helm releases, the deployment process SHALL check whether the locked `kubectl` version is outside the supported minor version skew of the Kubernetes API server. If a skew is detected, the deployment SHALL print a warning message naming both versions and the supported range, and continue deployment.

#### Scenario: Skew detected before deployment
- **WHEN** `devops k8s deploy-stack` runs against a cluster whose API server minor differs from the locked `kubectl` minor by more than one
- **THEN** a warning message naming both versions and the supported range is emitted and the deployment continues

#### Scenario: No skew detected
- **WHEN** `devops k8s deploy-stack` runs against a cluster whose API server is within one minor version of the locked `kubectl`
- **THEN** no version skew warning is printed
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Tasks

## 1. Version Skew Detection and Diagnostics

- [x] 1.1 Write failing tests for version skew diagnostics and deploy-stack skew warnings, verifying failure with `uv run devops ci test tests/test_k8s_doctor.py`
- [x] 1.2 Implement `Snapshot.server_version`, `get_code` in `plan_doctor_requests`, and the version skew diagnostic rule in `src/devops_cli/k8s/doctor.py` and `src/devops_cli/k8s/service.py`, verifying with `uv run devops ci test tests/test_k8s_doctor.py`
- [x] 1.3 Add kubectl version skew warning to `src/devops_cli/commands/k8s/stack_lifecycle.py` before applying stack resources, verifying with `uv run devops ci test tests/test_k8s_stack_lifecycle.py`
- [x] 1.4 Document the kubectl version skew policy and homelab cluster status in `k8s/README.md`, and synchronize documentation with `uv run devops docs generate --sync-readme`

## Workflow follow-up

- Pending a person: review the diff in tuicr (`tuicr -r origin/main..HEAD`).
36 changes: 36 additions & 0 deletions openspec/specs/k8s-doctor/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# k8s-doctor Specification

## Purpose
Diagnose Kubernetes cluster deployment health, collect API snapshots, verify component version skew, and recommend remediations.

## Requirements

### Requirement: Snapshot collection and dry run
The doctor SHALL collect API objects from the Kubernetes cluster into a diagnostic snapshot, including server version, nodes, pods, and events. When executed with `--dry-run`, doctor SHALL render the planned requests without contacting the cluster.

#### Scenario: Dry run lists version and cluster requests
- **WHEN** `devops k8s doctor --dry-run` is invoked
- **THEN** the request plan includes `get_code cluster`, `list_node cluster`, and workload listings without executing them

#### Scenario: Server version is captured in snapshot
- **WHEN** doctor collects cluster state from an active cluster
- **THEN** `Snapshot.server_version` contains the Kubernetes API server gitVersion string

### Requirement: Version skew diagnostic rule
The doctor SHALL evaluate version skew between the pinned `kubectl` binary, the API server, and node kubelets according to the Kubernetes version skew policy. Skew exceeding supported limits SHALL produce warning findings.

#### Scenario: Kubectl version skew exceeds one minor version
- **WHEN** the locked `kubectl` minor version differs from the API server minor version by more than one
- **THEN** doctor generates a cluster warning finding naming both versions and the supported server version range

#### Scenario: Kubectl version matches supported skew
- **WHEN** the locked `kubectl` minor version is within one minor of the API server minor version
- **THEN** doctor generates no version skew finding for `kubectl`

#### Scenario: Node kubelet is older than API server by more than three minor versions
- **WHEN** a node reports a `kubeletVersion` more than three minor versions older than the API server
- **THEN** doctor generates a cluster warning finding for that node identifying the kubelet version and the supported range

#### Scenario: Server version is empty or unavailable
- **WHEN** the cluster snapshot contains no server version
- **THEN** doctor skips version skew evaluation without raising an unhandled exception
11 changes: 11 additions & 0 deletions openspec/specs/k8s-helm-deploy/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,14 @@ Every `helm upgrade --install` invocation SHALL include `--take-ownership` to ad
#### Scenario: Upgrade command includes take-ownership
- **WHEN** `devops k8s deploy-stack` executes a Helm release install or upgrade
- **THEN** the constructed `helm upgrade --install` command arguments include `--take-ownership`

### Requirement: Kubectl version skew notification
Before deploying stack resources or applying Helm releases, the deployment process SHALL check whether the locked `kubectl` version is outside the supported minor version skew of the Kubernetes API server. If a skew is detected, the deployment SHALL print a warning message naming both versions and the supported range, and continue deployment.

#### Scenario: Skew detected before deployment
- **WHEN** `devops k8s deploy-stack` runs against a cluster whose API server minor differs from the locked `kubectl` minor by more than one
- **THEN** a warning message naming both versions and the supported range is emitted and the deployment continues

#### Scenario: No skew detected
- **WHEN** `devops k8s deploy-stack` runs against a cluster whose API server is within one minor version of the locked `kubectl`
- **THEN** no version skew warning is printed
14 changes: 14 additions & 0 deletions src/devops_cli/commands/k8s/stack_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -978,6 +978,19 @@ def _warn_about_gpu_placement(k8s_dir: Path, context: str | None) -> None:
print_warning(warning)


def _warn_about_version_skew(context: str | None) -> None:
"""Warn when kubectl version skew exceeds the Kubernetes version skew policy."""
from devops_cli.k8s.doctor import check_kubectl_version_skew
from devops_cli.k8s.service import KubernetesService

server_ver = KubernetesService.get_instance().server_version(context=context)
if not server_ver:
return
warning = check_kubectl_version_skew(server_ver)
if warning:
print_warning(warning)


def _apply_post_helm_paths(
paths: Sequence[Path],
kubectl_ctx: list[str],
Expand Down Expand Up @@ -1234,6 +1247,7 @@ def deploy_stack(
# 3. Verify cluster reachability, then warn about GPU nodes no Ollama tier accepts. The read
# comes before the Argo CD early return, so the warning prints on either kind of cluster.
_verify_cluster_ready(effective_context)
_warn_about_version_skew(effective_context)
if "llm" in selected_stacks:
_warn_about_gpu_placement(k8s_dir, effective_context)

Expand Down
1 change: 1 addition & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -2993,6 +2993,7 @@ class WebhookExposure(StrEnum):
CONST_K8S_DOCTOR_RULE_POD_UNSCHEDULABLE: Final[str] = "pod-unschedulable"
CONST_K8S_DOCTOR_RULE_POD_NOT_READY: Final[str] = "pod-not-ready"
CONST_K8S_DOCTOR_RULE_WARNING_EVENTS: Final[str] = "warning-events"
CONST_K8S_DOCTOR_RULE_VERSION_SKEW: Final[str] = "version-skew"

# ── Kubernetes Doctor: the Gitea stack (#2187) ───────────────────────────────
CONST_K8S_DOCTOR_STACK_GITEA: Final[str] = "gitea"
Expand Down
Loading
Loading