Repository navigation
feat(k8s): centralized kubernetes logging stack and LogQL integration - #96
Conversation
- Add declarative Loki and Fluent Bit manifests under k8s/logging with PSA labels and network isolation - Register logging stack in deploy-stack and teardown-stack lifecycle - Implement native LogQL query parser, line filter evaluator, and stream engine in k8s.logql - Add OpenTelemetry trace_id extraction and trace correlation in LogQL entries and Grafana Loki datasource - Support live follow and transparent fallback to kubectl logs in devops k8s logs - Register FastMCP tools k8s_logs_query and k8s_logs_tail - Author unit tests and verify 10-gate CI suite Closes #89
There was a problem hiding this comment.
🟡 Changes recommended
Critical and moderate findings remain unresolved across network exposure, endpoint validation, query correctness, and CLI/MCP behavior.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds centralized Kubernetes logging with Loki/Fluent Bit, LogQL querying, trace correlation, CLI/MCP integration, and lifecycle support.
Changes:
- Adds logging manifests, network policy, and stack lifecycle management.
- Implements LogQL parsing, Loki queries, filtering, trace extraction, and kubectl fallback.
- Updates CLI, MCP tools, Grafana configuration, tests, and documentation.
File summaries
| File | Reviewed change |
|---|---|
tests/test_k8s_logql.py |
LogQL parser and query tests |
tests/test_k8s_logging_stack.py |
Logging lifecycle and CLI tests |
src/devops_cli/k8s/logql.py |
LogQL engine, Loki integration, and fallback |
src/devops_cli/commands/k8s/stack_lifecycle.py |
Logging stack deployment and teardown |
src/devops_cli/commands/k8s/networking.py |
Logging stack networking support |
src/devops_cli/commands/k8s/cluster_context.py |
Kubernetes log CLI integration |
src/devops_cli/ai/mcp/server.py |
MCP logging tools and resource |
README.md |
CLI documentation updates |
k8s/namespaces.yaml |
Logging namespace configuration |
k8s/monitoring/prometheus-values.yaml |
Loki and trace-correlation configuration |
k8s/logging/networkpolicy.yaml |
Logging network policy |
k8s/logging/loki-values.yaml |
Loki configuration |
k8s/logging/fluent-bit-values.yaml |
Fluent Bit configuration |
docs/ROADMAP.md |
Logging roadmap status |
docs/MCP_TOOLS.md |
MCP tool documentation |
docs/commands/k8s.md |
Kubernetes command documentation |
docs/CLI_REFERENCE.md |
CLI reference updates |
docs/agent/task.md |
Task status updates |
Review details
Suppressed comments (14)
docs/ROADMAP.md:252
- This PR marks the logging work complete in
docs/agent/task.md, but the corresponding active-release roadmap item remains unchecked immediately after this hunk. The roadmap and task tracker now disagree about whether the deliverable is complete; synchronize the status before merging.
- *Acceptance Criteria*: 100% scanner registration in `ScannerRegistry`; zero ad-hoc subprocess calls; cyclomatic complexity $\le 10$ and nesting depth $\le 5$ across all scanner adapters. Passed all 10 `devops ci` quality gates.
k8s/monitoring/prometheus-values.yaml:66
- Grafana's Jaeger trace-to-log provisioning uses
filterByTraceIDandfilterBySpanID; thesefilterByTrace/filterBySpankeys are ignored. The datasource may show logs without applying the selected trace/span filters, so the advertised trace correlation does not work.
datasourceUid: loki
tags: ['job', 'instance', 'pod', 'namespace']
filterByTrace: true
filterBySpan: true
k8s/monitoring/prometheus-values.yaml:78
- The derived field points at
datasourceUid: Jaeger, but the Jaeger datasource above has no explicituid; Grafana may generate a different UID, so Loki-to-Jaeger trace links will not resolve reliably. Assign a stable Jaeger UID and reference that value here.
- datasourceUid: Jaeger
src/devops_cli/ai/mcp/server.py:304
- The MCP helper
_validate_mcp_int_boundis used by other numeric tools butlinesis forwarded unchecked here. Values of 0 or less can produce invalid--limitbehavior; reject them before spawning the CLI.
_validate_mcp_arg("query", query)
src/devops_cli/ai/mcp/server.py:283
- Passing the query as the first positional argument collides with the CLI's
query/tail/streamsentinels. An MCP call whose valid query text is exactly one of those values is interpreted as a subcommand with an empty query. Use the explicit--queryoption for this tool.
"logs",
query,
src/devops_cli/ai/mcp/server.py:311
- Passing the query as the first positional argument collides with the CLI's
query/tail/streamsentinels. A valid selector/query equal to one of those values is interpreted as a subcommand with an empty query. Use the explicit--queryoption for this tool.
"logs",
query,
src/devops_cli/ai/mcp/server.py:926
- This resource promises logs across active namespaces, but when Loki is unavailable the command enters the fallback with
{}andexecute_logql_querydefaults the namespace todefault. The fallback therefore only discovers default-namespace pods, producing an incomplete resource without indicating the loss of coverage; enumerate namespaces or narrow the contract.
["uv", "run", "devops", "k8s", "logs", "{}", "--limit", "30", "--format", "json"],
src/devops_cli/commands/k8s/cluster_context.py:173
entry.lineis inserted directly into a Rich-formatted string. A log line containing Rich markup can alter rendering or trigger a markup parse error, and this path also bypasses the sanitizer used bywrite_stream. Escape untrusted log text before composing the styled badge/output.
print(f"{ns_pod}{entry.line}{trace_badge}")
src/devops_cli/commands/k8s/cluster_context.py:139
- When
logs query,logs tail, orlogs streamis invoked without a query, this returns an empty string; the next call sends an empty Loki expression and the kubectl fallback has no filters, so it can return arbitrary logs. Reject a missing query before executing.
return extra_arg or ""
src/devops_cli/commands/k8s/stack_lifecycle.py:651
_resolve_stacksaccepts case-insensitive stack names, but teardown compares the original string.--stack LOGGINGcan therefore uninstall releases while skipping this namespace-cleanup branch; normalize the value before the cleanup dispatch.
elif stack == "logging":
src/devops_cli/k8s/logql.py:287
query_rangedoes not use the LogCLI-stylesinceparameter; Loki expects an explicitstart/endrange. As written,--sinceis ignored or rejected for every Loki request, so the query is not constrained to the requested window and may immediately fall back. Translate the duration before issuing the request and test the generated parameters.
params: dict[str, Any] = {
"query": query.raw_query,
"limit": limit,
"since": since,
"direction": "BACKWARD",
src/devops_cli/k8s/logql.py:361
- The fallback call drops
since;execute_kubectl_logqlonly receivesnamespaceandlimitand therefore uses--tailregardless of the requested time range. When Loki is unavailable,devops k8s logs --since 30mcan return older entries, violating the CLI contract. Pass the time bound through and implement it with kubectl or report that the fallback cannot honor it.
return execute_loki_query(parsed, loki_url=url, limit=limit, since=since)
except Exception as exc:
logger.info("Loki unreachable (%s); falling back to kubectl logs stream", exc)
return execute_kubectl_logql(parsed, namespace=target_ns, limit=limit)
src/devops_cli/k8s/logql.py:20
- This default is a cluster-internal DNS name, but the CLI and MCP tools run from the workstation.
deploy-stackdoes not port-forward Loki or configure a host-reachable endpoint, so the default request fails DNS and silently falls back tokubectl; centralized Loki storage is never queried unless callers supply--loki-url. Add Loki endpoint discovery/port-forwarding or an in-cluster execution path before advertising this as the default.
DEFAULT_LOKI_URL = "http://loki.logging.svc.cluster.local:3100"
src/devops_cli/k8s/logql.py:358
--namespaceis applied only to the kubectl fallback: the Loki branch sendsparsed.raw_queryunchanged. Thusdevops k8s logs '{app="web"}' --namespace prodqueries every namespace whenever Loki is available, despite the documented namespace option. Merge the explicit namespace into the Loki selector (or reject conflicting selectors) before issuing the request.
return execute_loki_query(parsed, loki_url=url, limit=limit, since=since)
- Files reviewed: 18/18 changed files
- Comments generated: 11
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
… and logql integration
…stack # Conflicts: # docs/agent/task.md
…nd logql integration
…e qdrant clusterip security perimeter
* fix(review): remediate security findings and enhance review feedback loop - Remediate all 11 verified findings across security, sandbox isolation, and resource bounds: - CodeMode: Remove reflection primitives (getattr, hasattr, type) and sys module from safe_builtins to prevent sandbox escape - K8s: Remove hardcoded default password for Open-WebUI admin account, generating a cryptographically secure random token when omitted - SSH: Mask secrets in key rotation error messages and provide actionable connectivity guidance - Harness Memory: Enforce bounded LIMIT clause and cursor iteration on SQLite search queries - Pydantic AI Tools: Enforce unconditional path traversal validation across all tool parameters regardless of schema presence - Harness Compaction: Enforce bounded capacity and FIFO eviction for overflow fallback memory using OrderedDict - Pipeline Protocol: Sanitize stage exception messages using mask_secrets in StageExecutionRecord - Ollama Models: Add URL scheme validation and block link-local cloud metadata (169.254.169.254) in base_url - Ollama Client: Sanitize HTTP status and streaming error messages using mask_secrets - Valkey: Centralize and sanitize error messages across all Valkey CLI commands using mask_secrets - Update DevSecOps review prompts, verification falsification rules, and task manuals for the closed-loop feedback loop - Export verified findings into the continuous learning feedback dataset - Bump version to 0.2.15 in pyproject.toml and package init - Synchronize CLI documentation and README Closes #87 * fix(review): address copilot feedback on sandbox isolation, credential masking, and query bounds * feat(security): complete security scanner migration to BaseSecurityScanner and ScannerRegistry (#93) * feat(security): complete security scanner migration to BaseSecurityScanner and ScannerRegistry * fix(security): address review feedback on security scanner base migration * refactor(core): eliminate obsolete shims, aliases, proxy wrappers, and backwards compatibility remnants (#95) * refactor(core): eliminate obsolete shims, aliases, proxy wrappers, and backwards compatibility remnants - Strip unicode icons and emojis from README bullets and markdown files - Remove numeric counts, timestamps, and arbitrary identifiers from test names, variables, and documentation - Remove legacy __getattr__ proxies, wrapper functions, and private aliases across commands and AI modules - Replace private re-exports with canonical functions in security.sanitizer - Extract clean GhCliClient and eliminate inner class shims in GitHub commands - Clean up stopwatch timers and semantic schema variable identifiers - Update all impacted tests and verify complete 10-gate CI suite Closes #94 * fix(review): address copilot feedback on paginated json, adapter tests, and git boundary - Add parse_paginated_json to handle concatenated multi-page JSON arrays from gh api --paginate in GhCliClient and gh commands - Implement edit_milestone method on GhCliClient for full synchronizer compatibility - Author focused unit tests for GhCliClient and parse_paginated_json in test_github_client.py - Exercise real git repository boundary and gitignore filtering in test_review_runner.py * refactor(pages,review): eliminate legacy config paths and harden secret redaction * fix(review,security): decouple secret redaction and resolve CodeQL clear-text false positives * feat(k8s): centralized kubernetes logging stack and LogQL integration (#96) * feat(k8s): centralized kubernetes logging stack and LogQL integration - Add declarative Loki and Fluent Bit manifests under k8s/logging with PSA labels and network isolation - Register logging stack in deploy-stack and teardown-stack lifecycle - Implement native LogQL query parser, line filter evaluator, and stream engine in k8s.logql - Add OpenTelemetry trace_id extraction and trace correlation in LogQL entries and Grafana Loki datasource - Support live follow and transparent fallback to kubectl logs in devops k8s logs - Register FastMCP tools k8s_logs_query and k8s_logs_tail - Author unit tests and verify 10-gate CI suite Closes #89 * fix(k8s): remediate code review findings on centralized logging stack and logql integration * feat(k8s): configure qdrant service with nodePort 31744 for direct host RAG access * fix(k8s): resolve code review feedback on centralized logging stack and logql integration * fix(k8s): confine rich markup escaping to output submodule and restore qdrant clusterip security perimeter * feat(tf): infracost finops cloud cost estimation and reporting (#97) * feat(tf): infracost finops cloud cost estimation and reporting * fix(tf): address code review feedback on Infracost FinOps cost engine - Enforce DependencyError when Infracost binary is missing in non-mock execution - Raise typed SubprocessError on non-zero Infracost breakdown/diff subprocess exit - Add ToolExecutionError error boundaries around breakdown and diff JSON deserialization - Add --compare-to baseline option to run_infracost_diff and CLI command - Validate budget thresholds before rendering and serializing JSON output - Register dynamic MCP resource resource://tf/cost/latest - Add comprehensive unit tests covering parsing, baseline diffs, and budget serialization * feat(argo): multi-cluster argocd fleet synchronization and rollouts (#98) * feat(argo): multi-cluster argocd fleet synchronization and rollouts - Implement multi-cluster fleet coordination engine with bounded concurrency under devops argo fleet sync - Add progressive delivery rollout controls (promote, abort, restart) wrapping kubectl argo rollouts - Introduce automated metric-driven rollback gates evaluating Prometheus/LogQL error rates with auto-abort capability - Add format_argo_fleet_sync_table and format_argo_rollout_analysis_table formatters - Register argo_fleet_sync, argo_rollout_analyze FastMCP tools and resource://argo/fleet/status resource - Add comprehensive test suite with 98%+ code coverage adhering to strict architectural invariants * fix(argo): address review feedback on fleet sync and rollouts * perf(ci): optimize caching configuration across all github workflows (#100) * perf(ci): optimize caching configuration across all github workflows * fix(ci): bound tooling cache key and enforce exact devcontainer cacheFrom assertion * refactor(agent): modularize task tracking to eliminate merge conflicts - Decompose monolithic docs/agent/task.md into isolated per-task tracking files under docs/agent/tasks/ (task-<issue>-<slug>.md) - Update GitHub Projects v2 parser (src/devops_cli/github/projects.py) to recursively scan and parse docs/agent/tasks/ by default while excluding archives and READMEs - Decompose parser functions to enforce cyclomatic complexity <= 10 and nesting depth <= 5 - Archive historical phases 1-50 in docs/agent/archive/historical-phases-1-to-50.md - Replace docs/agent/task.md with a lean index table pointing to modular task files - Update AGENTS.md, ROUTINE_TASKS.md, and Knowledge Base Task Manual 13 with the modular task architecture and commit context mandate - Author comprehensive unit tests in tests/test_github_projects.py Closes #101 * feat(ai): strengthen target-agnostic review prompts and feedback dataset synchronization * feat(ai): generalize devops ai review for target-agnostic evaluation and multi-convention discovery * fix(telemetry): optimize jaeger memory sizing, exception span hygiene, and embedding fast failover - Update k8s/otel/jaeger.yaml to configure MEMORY_MAX_TRACES to 10000 and scale memory limits to 1024Mi to eliminate OOMKills - Refactor telemetry tracer span exception handling to avoid attaching stack traces to handled CLI exits (typer.Exit) - Add DEFAULT_RAG_EMBEDDING_TIMEOUT (15.0s) and rapid 2.0s connect timeouts for fast Ollama multi-node failover - Author comprehensive unit tests in tests/test_telemetry.py and tests/test_rag_embeddings.py - Ground and deliver GitHub task 104 in docs/agent/tasks/task-104-telemetry-trace-optimizations.md (Closes #104)
Problem Statement
Cluster logs in Minikube and remote Kubernetes currently lack unified centralized storage, OpenTelemetry trace correlation, and native CLI log inspection.
Summary of Changes
k8s/logging/manifests (loki-values.yaml,fluent-bit-values.yaml,networkpolicy.yaml) with PSA labels and network isolation.loggingstack indeploy-stackandteardown-stacklifecycle commands.src/devops_cli/k8s/logql.py.trace_idextraction from JSON and logfmt streams, linking traces with Loki logs.devops k8s logs [query|tail|stream]with live follow and transparent fallback tokubectl logs.k8s_logs_queryandk8s_logs_tailtools with 119 schemas exported.test_k8s_logging_stack.pyandtest_k8s_logql.py; full 10-gate CI suite green.Closes #89