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
5 changes: 5 additions & 0 deletions changelog.d/1675.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Fixed

- `devops k8s deploy-stack --stack all` deploys every manifest and chart deployed by Argo CD Applications: added the pinned Traefik Helm chart (`kube-system/traefik`), GPU feature discovery DaemonSet (`Path("gpu-feature-discovery")`), the wildcard Cloudflare Ingress routes (`k8s/ingress/ingress-routes.yaml`), Portkey (`k8s/llm/portkey/*`), and the Valkey run index (`k8s/llm/valkey-runs.yaml`) ([#1675](https://github.com/dan-petty/devops-cli/issues/1675)).
- Helm conflict adoption (`_adopt_helm_resource_if_conflict`) refuses to adopt conflicting resources for the Traefik release and warns that stock k3s must be run with `--disable traefik` ([#1675](https://github.com/dan-petty/devops-cli/issues/1675)).
- Dropped NetworkPolicy undeployed exemptions (`UNDEPLOYED_NETWORK_POLICIES`) in `tests/test_k8s_network_policies.py` and replaced the hand-injected Traefik mapping in `tests/test_k8s_argocd_apps.py` with an exhaustive bidirectional counterpart mapping ([#1675](https://github.com/dan-petty/devops-cli/issues/1675)).
42 changes: 42 additions & 0 deletions docs/agent/tasks/task-1675-deploy-stack-parity-with-argocd.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Task: Deploy-stack parity with Argo CD Applications (#1675)

**Issue**: [#1675](https://github.com/dan-petty/devops-cli/issues/1675)
**Scope**: type/fix, scope/k8s
**Feasibility**: Verified against repository manifest definitions (`k8s/argocd/apps/`, `k8s/ingress/`, `k8s/llm/`, `k8s/gpu-feature-discovery/`) and the `stack_lifecycle.py` deployment pipeline. Confirmed via TDD that test assertions failed before the changes (RED) and passed cleanly after implementation (GREEN).

## Description

The `devops k8s deploy-stack --stack all` command and Argo CD Applications deployed different sets of Kubernetes manifests and charts, violating the invariant that `deploy-stack` comprehensively deploys all resources across stacks. Specifically, native `deploy-stack` omitted Traefik (`kube-system/traefik`), wildcard Ingress and IngressRoute definitions (`k8s/ingress/ingress-routes.yaml`), GPU feature discovery (`k8s/gpu-feature-discovery`), Portkey (`k8s/llm/portkey/*`), and the Valkey run index (`k8s/llm/valkey-runs.yaml`). Furthermore, tests masked these gaps via hand-injected map entries in `tests/test_k8s_argocd_apps.py` and undeployed policy exemptions in `tests/test_k8s_network_policies.py`.

This item closes all discrepancies and achieves full deployment parity:
- **Traefik Helm Release**: Added repository `traefik` (`https://traefik.github.io/charts`) to `_HELM_REPOS_BY_STACK["infra"]` and registered the pinned `traefik` Helm release (`traefik/traefik`, version 41.6.0, namespace `kube-system`, values `k8s/ingress/traefik-values.yaml`) in `_HELM_RELEASES_BY_STACK["infra"]`.
- **Traefik Conflict Guard**: In `_adopt_helm_resource_if_conflict`, guarded against adopting pre-existing conflicting resources for the `traefik` release, warning that stock k3s must be run with `--disable traefik` rather than adopting resources.
- **GPU Feature Discovery**: Added `Path("gpu-feature-discovery")` to `_KUSTOMIZATIONS_BY_STACK["infra"]`.
- **Ingress Routes Manifest**: Added `DEFAULT_K8S_DIR / "ingress" / "ingress-routes.yaml"` to `_MANIFESTS_BY_STACK["infra"]`, ensuring domain substitution applies during native deployment.
- **Portkey & Valkey Runs Manifests**: Added `k8s/llm/valkey-runs.yaml` and `k8s/llm/portkey/{configmap,deployment,service,networkpolicy}.yaml` to `_MANIFESTS_BY_STACK["llm"]`.
- **Tests & Invariant Enforcement**:
- Dropped `UNDEPLOYED_NETWORK_POLICIES` exemptions in `tests/test_k8s_network_policies.py`.
- Replaced the hand-injected Traefik release map in `test_helm_sources_pinned_versions` with an exhaustive `test_every_application_in_argocd_apps_maps_to_deploy_stack_counterpart` mapping every Application in `k8s/argocd/apps` (excluding `argocd-image-updater`) to its deploy-stack counterpart.
- Added unit test `test_adopt_helm_resource_warns_and_refuses_for_traefik` in `tests/test_k8s.py`.
- Updated expected dry-run kustomizations in `test_deploy_stack_dry_run_lists_the_kustomizations_its_stacks_apply` and `test_deploy_stack_applies_kustomizations`.
- **Documentation**: Updated `k8s/README.md` to document that `valkey-runs` and Ingress routes are deployed by `deploy-stack`, and noted that k3s must run with `--disable traefik`.

## Acceptance Criteria

- [x] `tests/test_k8s_network_policies.py` dropped all exemptions in `UNDEPLOYED_NETWORK_POLICIES` and passes.
- [x] `tests/test_k8s_argocd_apps.py` removed hand-injected Traefik mapping and verifies that every Application in `k8s/argocd/apps` maps to a deploy-stack counterpart.
- [x] `_adopt_helm_resource_if_conflict` warns and returns `False` when release name is `traefik`.
- [x] `_HELM_REPOS_BY_STACK`, `_HELM_RELEASES_BY_STACK`, `_KUSTOMIZATIONS_BY_STACK`, and `_MANIFESTS_BY_STACK` in `stack_lifecycle.py` include all missing counterparts.
- [x] `k8s/README.md` documents `valkey-runs` and Ingress route deployment by `deploy-stack` and k3s `--disable traefik`.
- [x] All test suites and quality gates pass locally (`uv run devops ci`).
- [x] `changelog.d/1675.md`.

## Deliverables

- [x] `src/devops_cli/commands/k8s/stack_lifecycle.py`
- [x] `tests/test_k8s_network_policies.py`
- [x] `tests/test_k8s_argocd_apps.py`
- [x] `tests/test_k8s.py`
- [x] `k8s/README.md`
- [x] `changelog.d/1675.md`
- [x] `docs/agent/tasks/task-1675-deploy-stack-parity-with-argocd.md`
11 changes: 5 additions & 6 deletions k8s/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ minikube service qdrant -n llm --url
# Valkey In-Memory Cache
kubectl -n llm exec -it svc/valkey -- valkey-cli ping

# Valkey Run Index (not deployed by deploy-stack; apply `k8s/llm/valkey-runs.yaml` yourself after creating its password):
# Valkey Run Index (deployed by deploy-stack; see Cluster Secrets for its password):
# benchmark and evaluation runs shared by workstations. Its password Secret comes from the keyring (see Cluster Secrets),
# then point devops-cli at it through its NodePort.
devops k8s push-secrets --only llm/valkey-runs-auth
Expand Down Expand Up @@ -567,11 +567,10 @@ Expose homelab Kubernetes services securely to the internet without public ports
```bash
kubectl apply -k k8s/cloudflared/
```
3. Set your Traefik ingress service type to `ClusterIP`:
```bash
kubectl patch svc traefik -n kube-system -p '{"spec": {"type": "ClusterIP"}}'
```
4. Deploy the core service Ingress definitions with template substitution (substitutes `k8s.domain` from `config.yaml`; set it to `homelab.<domain>` so the rendered hosts such as `chat.homelab.<domain>` fall under the `*.homelab.<domain>` tunnel hostname):
3. Ingress Controller (Traefik):
Stock k3s ships its own Traefik HelmChart; ensure k3s runs with `--disable traefik` so `devops k8s deploy-stack --stack infra` deploys the pinned Traefik release with `k8s/ingress/traefik-values.yaml` (configured with `service.type: ClusterIP`).
4. Core Ingress definitions:
`devops k8s deploy-stack --stack infra` deploys `k8s/ingress/ingress-routes.yaml` with template substitution automatically (substitutes `k8s.domain` from `config.yaml`). To apply or preview manually:
```bash
devops k8s apply k8s/ingress/ingress-routes.yaml --template
```
Expand Down
23 changes: 22 additions & 1 deletion src/devops_cli/commands/k8s/stack_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"grafana-community": "https://grafana-community.github.io/helm-charts",
"open-telemetry": "https://open-telemetry.github.io/opentelemetry-helm-charts",
"nvidia-dcgm": "https://nvidia.github.io/dcgm-exporter/helm-charts",
"traefik": "https://traefik.github.io/charts",
},
"llm": {
"open-webui": "https://open-webui.github.io/helm-charts",
Expand Down Expand Up @@ -143,6 +144,13 @@
"values": str(DEFAULT_K8S_DIR / "monitoring" / "pyroscope-values.yaml"),
"version": "2.3.1",
},
{
"name": "traefik",
"chart": "traefik/traefik",
"namespace": "kube-system",
"values": str(DEFAULT_K8S_DIR / "ingress" / "traefik-values.yaml"),
"version": "41.6.0",
},
],
"llm": [
{
Expand Down Expand Up @@ -177,16 +185,22 @@
"infra": [
DEFAULT_K8S_DIR / "argocd" / "networkpolicy.yaml",
DEFAULT_K8S_DIR / "otel" / "networkpolicy.yaml",
DEFAULT_K8S_DIR / "ingress" / "ingress-routes.yaml",
],
"llm": [
DEFAULT_K8S_DIR / "llm" / "networkpolicy.yaml",
DEFAULT_K8S_DIR / "llm" / "valkey.yaml",
DEFAULT_K8S_DIR / "llm" / "valkey-runs.yaml",
DEFAULT_K8S_DIR / "llm" / "profiles" / "services.yaml",
DEFAULT_K8S_DIR / "llm" / "profiles" / "ollama-profiles.yaml",
DEFAULT_K8S_DIR / "llm" / "gateway" / "configmap.yaml",
DEFAULT_K8S_DIR / "llm" / "gateway" / "networkpolicy.yaml",
DEFAULT_K8S_DIR / "llm" / "gateway" / "deployment.yaml",
DEFAULT_K8S_DIR / "llm" / "gateway" / "service.yaml",
DEFAULT_K8S_DIR / "llm" / "portkey" / "configmap.yaml",
DEFAULT_K8S_DIR / "llm" / "portkey" / "deployment.yaml",
DEFAULT_K8S_DIR / "llm" / "portkey" / "service.yaml",
DEFAULT_K8S_DIR / "llm" / "portkey" / "networkpolicy.yaml",
],
"logging": [
DEFAULT_K8S_DIR / "logging" / "networkpolicy.yaml",
Expand All @@ -210,7 +224,7 @@
# `monitoring` Application alone owns its objects (#1279); a cluster without Argo CD gets the same
# kustomization from here: the namespace's perimeter (#913) and the Grafana dashboards (#1297).
_KUSTOMIZATIONS_BY_STACK: dict[str, tuple[Path, ...]] = {
"infra": (Path("monitoring"),),
"infra": (Path("monitoring"), Path("gpu-feature-discovery")),
}

VALID_STACKS: tuple[str, ...] = ("infra", "llm", "logging", "devops", "all")
Expand Down Expand Up @@ -272,6 +286,13 @@ def _adopt_helm_resource_if_conflict(
):
return False

if release_name == "traefik":
print_warning(
"Traefik conflict detected: k3s must run with '--disable traefik' "
"rather than adopting pre-existing resources."
)
return False

matches = CONST_HELM_OWNERSHIP_CONFLICT_RE.findall(error_output)
if not matches:
return False
Expand Down
34 changes: 31 additions & 3 deletions tests/test_k8s.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,21 @@ def test_adopt_helm_resource_if_conflict(mock_run: MagicMock) -> None:
assert mock_run.call_count == 2


def test_adopt_helm_resource_warns_and_refuses_for_traefik() -> None:
"""_adopt_helm_resource_if_conflict warns and refuses to adopt for traefik release (#1675)."""
from devops_cli.commands.k8s.stack_lifecycle import _adopt_helm_resource_if_conflict

err = (
'Error: unable to continue with install: Service "traefik" in namespace "kube-system" exists '
"and cannot be imported into the current release: invalid ownership metadata; "
'label validation error: missing key "app.kubernetes.io/managed-by": must be set to "Helm"'
)
with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_run:
res = _adopt_helm_resource_if_conflict(err, "traefik", "kube-system", context="local-k3s")
assert res is False
assert mock_run.call_count == 0


_OPERATOR_CRDS = tuple(
f"{plural}.monitoring.coreos.com"
for plural in (
Expand Down Expand Up @@ -2141,14 +2156,27 @@ def test_native_deploy_stack_infra_applies_the_monitoring_kustomization() -> Non
for cmd in (call.args[0] for call in mock_cmd.call_args_list)
if cmd[:3] == ["kubectl", "apply", "-k"]
]
assert (res.exit_code, kustomize_targets) == (0, [Path("k8s"), Path("k8s", "monitoring")])
assert (res.exit_code, kustomize_targets) == (
0,
[
Path("k8s"),
Path("k8s", "monitoring"),
Path("k8s", "gpu-feature-discovery"),
],
)


@pytest.mark.parametrize(
("stack", "kustomizations"),
[
("infra", [str(Path("k8s", "monitoring"))]),
("all", [str(Path("k8s", "monitoring"))]),
(
"infra",
[str(Path("k8s", "monitoring")), str(Path("k8s", "gpu-feature-discovery"))],
),
(
"all",
[str(Path("k8s", "monitoring")), str(Path("k8s", "gpu-feature-discovery"))],
),
("llm", []),
],
)
Expand Down
129 changes: 97 additions & 32 deletions tests/test_k8s_argocd_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@

import yaml

from devops_cli.commands.k8s.stack_lifecycle import _HELM_RELEASES_BY_STACK
from devops_cli.commands.k8s.stack_lifecycle import (
_HELM_RELEASES_BY_STACK,
_KUSTOMIZATIONS_BY_STACK,
_MANIFESTS_BY_STACK,
)
from devops_cli.k8s.cluster_secrets import CLUSTER_SECRETS

REPO_ROOT = Path(__file__).resolve().parent.parent
Expand Down Expand Up @@ -101,44 +105,105 @@ def test_git_sources_and_revisions() -> None:
), f"{name} bad revision {git_s.get('targetRevision')}"


def test_helm_sources_pinned_versions() -> None:
apps = _all_applications()
def _assert_helm_app_matches_release(
app: dict[str, Any], release: dict[str, str], name: str
) -> None:
semver_re = re.compile(r"^\d+\.\d+\.\d+$")
sources = app.get("spec", {}).get("sources", [])
helm_sources = [s for s in sources if "chart" in s]
assert len(helm_sources) == 1, f"{name} expected 1 Helm source"
h = helm_sources[0]

target_rev = str(h["targetRevision"])
assert semver_re.match(target_rev), f"{name} helm version {target_rev} not pinned semver"
assert target_rev == release["version"]

expected_chart_name = release["chart"].split("/")[-1]
assert h["chart"] == expected_chart_name
assert app["spec"]["destination"]["namespace"] == release["namespace"]

value_files = h.get("helm", {}).get("valueFiles", [])
raw_val = Path(release["values"])
rel_val = raw_val.relative_to(REPO_ROOT) if raw_val.is_absolute() else raw_val
expected_rel_path = f"$values/{rel_val.as_posix()}"
assert value_files == [expected_rel_path]


def _kustomization_manifest_files(kust_dir: Path) -> list[Path]:
"""Find all concrete manifest files referenced by a kustomization recursively."""
kust_file = kust_dir / "kustomization.yaml"
if not kust_file.is_file():
return []
doc = yaml.safe_load(kust_file.read_text(encoding="utf-8")) or {}
files: list[Path] = []
for res in doc.get("resources", []):
res_path = (kust_dir / res).resolve()
if res_path.is_file():
files.append(res_path)
elif res_path.is_dir() and (res_path / "kustomization.yaml").is_file():
files.extend(_kustomization_manifest_files(res_path))
return files


helm_releases_map: dict[str, dict[str, str]] = {}
for releases in _HELM_RELEASES_BY_STACK.values():
for r in releases:
helm_releases_map[r["name"]] = r
helm_releases_map["traefik"] = {
"name": "traefik",
"chart": "traefik/traefik",
"namespace": "kube-system",
"values": "k8s/ingress/traefik-values.yaml",
"version": "41.6.0",
def test_helm_sources_pinned_versions() -> None:
apps = _all_applications()
helm_releases_map: dict[str, dict[str, str]] = {
r["name"]: r for releases in _HELM_RELEASES_BY_STACK.values() for r in releases
}

for name, expected in helm_releases_map.items():
assert name in apps, f"Missing Helm app {name}"
app = apps[name]
_assert_helm_app_matches_release(apps[name], expected, name)


def test_every_application_in_argocd_apps_maps_to_deploy_stack_counterpart() -> None:
"""Every Application in k8s/argocd/apps maps to a deploy-stack counterpart (#1675).

Each chart maps to a release with the same version and values file, and each path maps
to a deploy-stack manifest list or kustomization. argocd-image-updater is the only allowed
exception (k8s/README.md Service Image Updates; task-1485).
"""
helm_releases_map: dict[str, dict[str, str]] = {
r["name"]: r for releases in _HELM_RELEASES_BY_STACK.values() for r in releases
}
deploy_stack_kustomizations = {
(REPO_ROOT / "k8s").resolve(),
*(
(REPO_ROOT / "k8s" / k).resolve()
for ks in _KUSTOMIZATIONS_BY_STACK.values()
for k in ks
),
}
deploy_stack_manifests = {
(REPO_ROOT / p if not p.is_absolute() else p).resolve()
for ms in _MANIFESTS_BY_STACK.values()
for p in ms
}

for app_path_file in sorted(APPS_DIR.glob("*.yaml")):
if app_path_file.name == "projects.yaml":
continue
app = _load_yaml(app_path_file)
name = app["metadata"]["name"]
if name == "argocd-image-updater":
continue

spec = app["spec"]
sources = spec.get("sources", [])
helm_sources = [s for s in sources if "chart" in s]
assert len(helm_sources) == 1, f"{name} expected 1 Helm source"
h = helm_sources[0]

target_rev = str(h["targetRevision"])
assert semver_re.match(target_rev), f"{name} helm version {target_rev} not pinned semver"
assert target_rev == expected["version"]

expected_chart_name = expected["chart"].split("/")[-1]
assert h["chart"] == expected_chart_name
assert app["spec"]["destination"]["namespace"] == expected["namespace"]

value_files = h.get("helm", {}).get("valueFiles", [])
raw_val = Path(expected["values"])
rel_val = raw_val.relative_to(REPO_ROOT) if raw_val.is_absolute() else raw_val
expected_rel_path = f"$values/{rel_val.as_posix()}"
assert value_files == [expected_rel_path]
if "sources" in spec:
assert name in helm_releases_map, f"{name} has no deploy-stack release"
_assert_helm_app_matches_release(app, helm_releases_map[name], name)
elif "source" in spec and "path" in spec["source"]:
target_path = (REPO_ROOT / spec["source"]["path"]).resolve()
if target_path in deploy_stack_kustomizations:
continue
manifests = _kustomization_manifest_files(target_path)
assert manifests, f"{name} path {target_path} contains no manifests"
missing = [
m.relative_to(REPO_ROOT).as_posix()
for m in manifests
if m not in deploy_stack_manifests
]
assert not missing, f"{name} manifests missing from deploy-stack: {missing}"


def _assert_kustomization_resources(p: Path, name: str) -> None:
Expand Down
2 changes: 2 additions & 0 deletions tests/test_k8s_monitoring_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,9 @@ def test_otel_collector_remote_writes_to_the_path_alloy_serves() -> None:
# Each entry maps (namespace, name) to (manifest_path, owner).
EXEMPT_PLAIN_SERVICES: dict[tuple[str, str], tuple[str, str]] = {
("llm", "valkey"): ("k8s/llm/valkey.yaml", "llm stack valkey manifest"),
("llm", "valkey-runs"): ("k8s/llm/valkey-runs.yaml", "llm stack valkey-runs manifest"),
("llm", "llm-gateway"): ("k8s/llm/gateway/service.yaml", "llm stack gateway manifest"),
("llm", "portkey"): ("k8s/llm/portkey/service.yaml", "llm stack portkey manifest"),
**{
("llm", f"ollama-{name}"): ("k8s/llm/profiles/services.yaml", "llm stack ollama profile")
for name in (
Expand Down
11 changes: 1 addition & 10 deletions tests/test_k8s_network_policies.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,7 @@
# An Argo CD Application is such a path, never a deploy-stack one: a cluster without Argo CD gets
# only what deploy-stack applies (#913). Delete an entry once its policy gains a deploy-stack path
# or leaves its file; the guard below fails until then.
UNDEPLOYED_NETWORK_POLICIES: dict[tuple[str, str], tuple[str, str]] = {
("llm", "portkey-perimeter"): (
"k8s/llm/portkey/networkpolicy.yaml",
"Argo CD's llm Application; deploy-stack does not deploy Portkey",
),
("llm", "valkey-runs-perimeter"): (
"k8s/llm/valkey-runs.yaml",
"Argo CD's llm Application; a person applies the file for `devops ai runs` (k8s/README.md)",
),
}
UNDEPLOYED_NETWORK_POLICIES: dict[tuple[str, str], tuple[str, str]] = {}

TARGET_NAMESPACES = ("monitoring", "argocd", "llm", "otel", "devops")
METADATA_SSRF_IP = "169.254.169.254/32"
Expand Down
Loading