syncable_cli/analyzer/k8s_optimize/mod.rs
1//! Kubernetes Resource Optimization Analyzer
2//!
3//! A native Rust analyzer for detecting over-provisioned and under-provisioned
4//! Kubernetes workloads. Helps reduce cloud costs by right-sizing resource
5//! requests and limits.
6//!
7//! # Features
8//!
9//! ## Phase 1: Static Analysis
10//! - Static analysis of Kubernetes manifests (no cluster access required)
11//! - **Terraform HCL support** - Parse `kubernetes_*` provider resources
12//! - Pattern-based detection of over/under-provisioning
13//! - Workload type classification for smarter recommendations
14//! - Support for Deployments, StatefulSets, DaemonSets, Jobs, CronJobs
15//! - Helm chart and Kustomize directory support
16//! - Multiple output formats (table, JSON)
17//!
18//! ## Phase 2: Live Cluster Analysis
19//! - **Kubernetes API integration** - Connect to real clusters via kubeconfig
20//! - **metrics-server support** - Real-time CPU/memory usage data
21//! - **Prometheus integration** - Historical metrics (P50, P95, P99, max)
22//! - Data-driven recommendations based on actual usage
23//! - Waste percentage calculations with confidence levels
24//!
25//! # Example
26//!
27//! ```rust,ignore
28//! use syncable_cli::analyzer::k8s_optimize::{lint, K8sOptimizeConfig, OptimizationResult};
29//! use std::path::Path;
30//!
31//! // Static analysis (no cluster needed)
32//! let config = K8sOptimizeConfig::default();
33//! let result = lint(Path::new("./k8s/"), &config);
34//!
35//! // Or using the backward-compatible analyze() function:
36//! let result = analyze(Path::new("./k8s/"), &config);
37//!
38//! // Live cluster analysis (requires kubeconfig)
39//! use syncable_cli::analyzer::k8s_optimize::live_analyzer::{LiveAnalyzer, LiveAnalyzerConfig};
40//! let live_config = LiveAnalyzerConfig::default();
41//! let analyzer = LiveAnalyzer::new(live_config).await?;
42//! let live_result = analyzer.analyze().await?;
43//! ```
44//!
45//! # Optimization Rules
46//!
47//! The analyzer checks for these common issues (K8S-OPT-001 through K8S-OPT-010):
48//!
49//! ## Over-Provisioning Detection
50//! - K8S-OPT-005: CPU request > 1 core for non-batch workload
51//! - K8S-OPT-006: Memory request > 2Gi for non-database workload
52//! - K8S-OPT-007: Excessive CPU limit-to-request ratio (> 10x)
53//! - K8S-OPT-008: Excessive memory limit-to-request ratio (> 4x)
54//!
55//! ## Under-Provisioning Detection
56//! - K8S-OPT-001: No CPU request defined
57//! - K8S-OPT-002: No memory request defined
58//! - K8S-OPT-003: No CPU limit defined
59//! - K8S-OPT-004: No memory limit defined
60//!
61//! ## Best Practices
62//! - K8S-OPT-009: Requests equal to limits (no bursting allowed)
63//! - K8S-OPT-010: Unbalanced resource allocation for workload type
64
65// ============================================================================
66// Core modules (new structure)
67// ============================================================================
68
69/// Configuration for the optimizer.
70pub mod config;
71
72/// Core data types.
73pub mod types;
74
75/// Parsing utilities (YAML, Terraform, Helm).
76pub mod parser;
77
78/// Output formatting (table, JSON, YAML).
79pub mod formatter;
80
81/// Individual optimization rules (K8S-OPT-001 through K8S-OPT-010).
82pub mod rules;
83
84/// Annotation-based rule ignoring (pragma).
85pub mod pragma;
86
87// ============================================================================
88// Analysis modules
89// ============================================================================
90
91/// Static analysis of Kubernetes manifests.
92pub mod static_analyzer;
93
94/// Recommendation generation (now in rules/).
95pub mod recommender;
96
97/// Terraform parser (now in parser/terraform.rs, re-exported for compatibility).
98pub mod terraform_parser;
99
100// ============================================================================
101// Live cluster analysis modules
102// ============================================================================
103
104/// Live cluster analyzer.
105pub mod live_analyzer;
106
107/// Kubernetes metrics-server client.
108pub mod metrics_client;
109
110/// Prometheus client for historical metrics.
111pub mod prometheus_client;
112
113// ============================================================================
114// Cost and fix modules
115// ============================================================================
116
117/// Cost calculation and estimation.
118pub mod cost_calculator;
119
120/// Trend analysis.
121pub mod trend_analyzer;
122
123/// Fix application to manifest files.
124pub mod fix_applicator;
125
126// ============================================================================
127// Placeholder subfolders (for future organization)
128// ============================================================================
129
130/// Live analysis subfolder (future home for live_analyzer, metrics_client, prometheus_client).
131mod live;
132
133/// Cost analysis subfolder (future home for cost_calculator, trend_analyzer).
134mod cost;
135
136/// Fix application subfolder (future home for fix_applicator).
137mod fix;
138
139// ============================================================================
140// Re-exports: Configuration
141// ============================================================================
142
143pub use config::K8sOptimizeConfig;
144
145// ============================================================================
146// Re-exports: Core types
147// ============================================================================
148
149pub use types::{
150 // Core types
151 AnalysisMetadata,
152 AnalysisMode,
153 ChartValidation,
154 CloudProvider,
155 CostBreakdown,
156 // Cost estimation types
157 CostEstimation,
158 CostSavings,
159 FixApplicationResult,
160 FixImpact,
161 FixResourceValues,
162 FixRisk,
163 FixSource,
164 FixStatus,
165 HelmIssue,
166 HelmValidationReport,
167 HelmValidationSummary,
168 LiveClusterSummary,
169 LiveFix,
170 OptimizationIssue,
171 OptimizationResult,
172 OptimizationSummary,
173 // Precise fix types
174 PreciseFix,
175 ResourceOptimizationReport,
176 ResourceOptimizationSummary,
177 ResourceRecommendation,
178 ResourceSpec,
179 ResourceUsage,
180 ResourceWarning,
181 RuleCode,
182 SecurityFinding,
183 SecurityReport,
184 SecuritySummary,
185 Severity,
186 // Trend analysis types
187 TrendAnalysis,
188 TrendDirection,
189 UnifiedMetadata,
190 // Unified report types (for --full JSON output)
191 UnifiedReport,
192 UnifiedSummary,
193 WasteMetrics,
194 WorkloadCost,
195 WorkloadTrend,
196 WorkloadType,
197};
198
199// ============================================================================
200// Re-exports: Formatting
201// ============================================================================
202
203pub use formatter::{OutputFormat, format_result, format_result_to_string};
204
205// ============================================================================
206// Re-exports: Static analysis (primary API)
207// ============================================================================
208
209// Primary API - new lint() functions
210pub use static_analyzer::{
211 analyze as lint, analyze_content as lint_content, analyze_file as lint_file,
212};
213
214// Backward compatibility - keep analyze() functions
215pub use static_analyzer::{analyze, analyze_content, analyze_file};
216
217// ============================================================================
218// Re-exports: Parser utilities
219// ============================================================================
220
221pub use parser::{
222 TerraformContainer,
223 TerraformK8sResource,
224 TfResourceSpec,
225 bytes_to_memory_string,
226 cpu_limit_to_request_ratio,
227 detect_workload_type,
228 extract_container_image,
229 extract_container_name,
230 extract_resources,
231 memory_limit_to_request_ratio,
232 millicores_to_cpu_string,
233 // YAML parsing
234 parse_cpu_to_millicores,
235 parse_memory_to_bytes,
236 // Terraform parsing
237 parse_terraform_k8s_resources,
238};
239
240// ============================================================================
241// Re-exports: Rules
242// ============================================================================
243
244pub use rules::{
245 ContainerContext,
246 // Rule trait and context
247 OptimizationRule,
248 RuleContext,
249 // Rule registry
250 all_rules,
251 // Rule codes
252 codes as rule_codes,
253 generate_recommendations,
254 rule_description,
255};
256
257// ============================================================================
258// Re-exports: Pragma (annotation-based ignores)
259// ============================================================================
260
261pub use pragma::{
262 IGNORE_ANNOTATION_PREFIX, extract_annotations, get_ignore_reason, get_ignored_rules,
263 should_ignore_rule,
264};
265
266// ============================================================================
267// Re-exports: Live cluster analysis
268// ============================================================================
269
270pub use live_analyzer::{
271 DataSource, LiveAnalysisResult, LiveAnalyzer, LiveAnalyzerConfig, LiveRecommendation,
272};
273pub use metrics_client::{MetricsClient, PodMetrics, PodResources, ResourceComparison};
274pub use prometheus_client::{
275 ContainerHistory, HistoricalRecommendation, PrometheusAuth, PrometheusClient,
276};
277
278// ============================================================================
279// Re-exports: Cost estimation and trends
280// ============================================================================
281
282pub use cost_calculator::{calculate_from_live, calculate_from_static};
283pub use fix_applicator::{apply_fixes, locate_resources_from_static, locate_resources_in_file};
284pub use trend_analyzer::{analyze_trends_from_live, analyze_trends_static};