1use std::fmt::Write;
11
12#[derive(Debug, Clone)]
14pub enum Language {
15 Rust,
16 Go,
17 Elixir,
18 TypeScript,
19 Python,
20 Java,
21}
22
23impl Language {
24 pub fn builder_image(&self) -> &'static str {
25 match self {
26 Language::Rust => "rust:latest",
27 Language::Go => "golang:1.24-alpine",
28 Language::Elixir => "elixir:latest",
29 Language::TypeScript => "node:20-alpine",
30 Language::Python => "python:3.12-slim",
31 Language::Java => "openjdk:21-jdk-slim",
32 }
33 }
34
35 pub fn runtime_image(&self) -> &'static str {
36 match self {
37 Language::Rust => "debian:bookworm-slim",
38 Language::Go => "alpine:latest",
39 Language::Elixir => "erlang:27-slim",
40 Language::TypeScript => "node:20-alpine",
41 Language::Python => "python:3.12-slim",
42 Language::Java => "openjdk:21-jre-slim",
43 }
44 }
45
46 pub fn build_command(&self) -> &'static str {
47 match self {
48 Language::Rust => "cargo build --release",
49 Language::Go => "CGO_ENABLED=0 GOOS=linux go build -o app .",
50 Language::Elixir => "MIX_ENV=prod mix deps.get && mix compile && mix release",
51 Language::TypeScript => "npm ci && npm run build",
52 Language::Python => "pip install --no-cache-dir -r requirements.txt",
53 Language::Java => "mvnd clean package -DskipTests",
54 }
55 }
56
57 pub fn binary_path(&self) -> &'static str {
58 match self {
59 Language::Rust => "/app/target/release/myapp",
60 Language::Go => "/app/app",
61 Language::Elixir => "/app/_build/prod/rel/app/bin/app",
62 Language::TypeScript => "/app/dist/index.js",
63 Language::Python => "/app",
64 Language::Java => "/app/target/*.jar",
65 }
66 }
67}
68
69#[derive(Debug, Clone)]
71pub struct ServiceSpec {
72 pub name: String,
73 pub service_type: String, pub replicas: u32,
75 pub port: u32,
76 pub target_port: u32,
77 pub image: String,
78 pub registry: String, pub tag: String,
80 pub env_vars: Vec<(String, String)>, }
82
83impl Default for ServiceSpec {
84 fn default() -> Self {
85 Self {
86 name: "default-service".to_string(),
87 service_type: "ClusterIP".to_string(),
88 replicas: 3,
89 port: 8001,
90 target_port: 8001,
91 image: "default-app".to_string(),
92 registry: "myregistry.azurecr.io".to_string(),
93 tag: "latest".to_string(),
94 env_vars: vec![],
95 }
96 }
97}
98
99pub struct DockerKubernetesGenerator;
101
102impl DockerKubernetesGenerator {
103 pub fn generate_dockerfile(language: &Language, service_name: &str) -> Result<String, String> {
105 let mut output = String::new();
106
107 writeln!(output, "# Multi-stage Dockerfile for {}", service_name)
108 .map_err(|e| e.to_string())?;
109 writeln!(output, "# Generated: production-ready container").map_err(|e| e.to_string())?;
110
111 writeln!(output, "\nFROM {} as builder", language.builder_image())
113 .map_err(|e| e.to_string())?;
114 writeln!(output, "WORKDIR /app").map_err(|e| e.to_string())?;
115 writeln!(output, "COPY . .").map_err(|e| e.to_string())?;
116
117 match language {
119 Language::Rust => {
120 writeln!(output, "RUN {} && cargo clean", language.build_command())
121 .map_err(|e| e.to_string())?;
122 }
123 Language::Go => {
124 writeln!(output, "RUN {}", language.build_command()).map_err(|e| e.to_string())?;
125 }
126 Language::Elixir => {
127 writeln!(output, "RUN {}", language.build_command()).map_err(|e| e.to_string())?;
128 }
129 Language::TypeScript => {
130 writeln!(output, "RUN npm ci").map_err(|e| e.to_string())?;
131 writeln!(output, "RUN {}", language.build_command()).map_err(|e| e.to_string())?;
132 }
133 Language::Python => {
134 writeln!(output, "COPY requirements.txt .").map_err(|e| e.to_string())?;
135 writeln!(output, "RUN {}", language.build_command()).map_err(|e| e.to_string())?;
136 }
137 Language::Java => {
138 writeln!(output, "RUN {}", language.build_command()).map_err(|e| e.to_string())?;
139 }
140 }
141
142 writeln!(output, "\nFROM {}", language.runtime_image()).map_err(|e| e.to_string())?;
144 writeln!(output, "WORKDIR /app").map_err(|e| e.to_string())?;
145 writeln!(output, "RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/* || true")
146 .map_err(|e| e.to_string())?;
147
148 match language {
150 Language::Rust => {
151 writeln!(
152 output,
153 "COPY --from=builder /app/target/release/{} /app/{}",
154 service_name, service_name
155 )
156 .map_err(|e| e.to_string())?;
157 writeln!(output, "ENTRYPOINT [\"/app/{}\"]", service_name)
158 .map_err(|e| e.to_string())?;
159 }
160 Language::Go => {
161 writeln!(output, "COPY --from=builder /app/app /app/app")
162 .map_err(|e| e.to_string())?;
163 writeln!(output, "ENTRYPOINT [\"/app/app\"]").map_err(|e| e.to_string())?;
164 }
165 Language::Elixir => {
166 writeln!(output, "COPY --from=builder /app/_build/prod/rel /app/rel")
167 .map_err(|e| e.to_string())?;
168 writeln!(output, "ENTRYPOINT [\"/app/rel/app/bin/app\"]")
169 .map_err(|e| e.to_string())?;
170 }
171 Language::TypeScript => {
172 writeln!(
173 output,
174 "COPY --from=builder /app/node_modules /app/node_modules"
175 )
176 .map_err(|e| e.to_string())?;
177 writeln!(output, "COPY --from=builder /app/dist /app/dist")
178 .map_err(|e| e.to_string())?;
179 writeln!(output, "CMD [\"node\", \"dist/index.js\"]").map_err(|e| e.to_string())?;
180 }
181 Language::Python => {
182 writeln!(output, "COPY --from=builder /usr/local/lib /usr/local/lib")
183 .map_err(|e| e.to_string())?;
184 writeln!(output, "COPY . /app").map_err(|e| e.to_string())?;
185 writeln!(output, "CMD [\"python\", \"app.py\"]").map_err(|e| e.to_string())?;
186 }
187 Language::Java => {
188 writeln!(output, "COPY --from=builder /app/target/*.jar /app/app.jar")
189 .map_err(|e| e.to_string())?;
190 writeln!(output, "ENTRYPOINT [\"java\", \"-jar\", \"/app/app.jar\"]")
191 .map_err(|e| e.to_string())?;
192 }
193 }
194
195 writeln!(
197 output,
198 "\nHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\"
199 )
200 .map_err(|e| e.to_string())?;
201 writeln!(
202 output,
203 " CMD curl -f http://localhost:8080/health || exit 1"
204 )
205 .map_err(|e| e.to_string())?;
206
207 Ok(output)
208 }
209
210 pub fn generate_k8s_deployment(spec: &ServiceSpec) -> Result<String, String> {
212 let mut output = String::new();
213
214 writeln!(output, "apiVersion: apps/v1").map_err(|e| e.to_string())?;
215 writeln!(output, "kind: Deployment").map_err(|e| e.to_string())?;
216 writeln!(output, "metadata:").map_err(|e| e.to_string())?;
217 writeln!(output, " name: {}", spec.name).map_err(|e| e.to_string())?;
218 writeln!(output, " labels:").map_err(|e| e.to_string())?;
219 writeln!(output, " app: {}", spec.name).map_err(|e| e.to_string())?;
220 writeln!(output, " version: v1").map_err(|e| e.to_string())?;
221
222 writeln!(output, "spec:").map_err(|e| e.to_string())?;
223 writeln!(output, " replicas: {}", spec.replicas).map_err(|e| e.to_string())?;
224 writeln!(output, " selector:").map_err(|e| e.to_string())?;
225 writeln!(output, " matchLabels:").map_err(|e| e.to_string())?;
226 writeln!(output, " app: {}", spec.name).map_err(|e| e.to_string())?;
227
228 writeln!(output, " template:").map_err(|e| e.to_string())?;
229 writeln!(output, " metadata:").map_err(|e| e.to_string())?;
230 writeln!(output, " labels:").map_err(|e| e.to_string())?;
231 writeln!(output, " app: {}", spec.name).map_err(|e| e.to_string())?;
232 writeln!(output, " spec:").map_err(|e| e.to_string())?;
233
234 writeln!(output, " containers:").map_err(|e| e.to_string())?;
235 writeln!(output, " - name: {}", spec.name).map_err(|e| e.to_string())?;
236 writeln!(
237 output,
238 " image: {}/{}:{}",
239 spec.registry, spec.image, spec.tag
240 )
241 .map_err(|e| e.to_string())?;
242 writeln!(output, " imagePullPolicy: Always").map_err(|e| e.to_string())?;
243
244 writeln!(output, " ports:").map_err(|e| e.to_string())?;
245 writeln!(output, " - name: http").map_err(|e| e.to_string())?;
246 writeln!(output, " containerPort: {}", spec.target_port)
247 .map_err(|e| e.to_string())?;
248 writeln!(output, " protocol: TCP").map_err(|e| e.to_string())?;
249
250 if !spec.env_vars.is_empty() {
252 writeln!(output, " env:").map_err(|e| e.to_string())?;
253 for (key, value) in &spec.env_vars {
254 writeln!(output, " - name: {}", key).map_err(|e| e.to_string())?;
255 writeln!(output, " value: \"{}\"", value).map_err(|e| e.to_string())?;
256 }
257 }
258
259 writeln!(output, " livenessProbe:").map_err(|e| e.to_string())?;
261 writeln!(output, " httpGet:").map_err(|e| e.to_string())?;
262 writeln!(output, " path: /health").map_err(|e| e.to_string())?;
263 writeln!(output, " port: {}", spec.target_port).map_err(|e| e.to_string())?;
264 writeln!(output, " initialDelaySeconds: 10").map_err(|e| e.to_string())?;
265 writeln!(output, " periodSeconds: 10").map_err(|e| e.to_string())?;
266 writeln!(output, " timeoutSeconds: 5").map_err(|e| e.to_string())?;
267 writeln!(output, " failureThreshold: 3").map_err(|e| e.to_string())?;
268
269 writeln!(output, " readinessProbe:").map_err(|e| e.to_string())?;
270 writeln!(output, " httpGet:").map_err(|e| e.to_string())?;
271 writeln!(output, " path: /ready").map_err(|e| e.to_string())?;
272 writeln!(output, " port: {}", spec.target_port).map_err(|e| e.to_string())?;
273 writeln!(output, " initialDelaySeconds: 5").map_err(|e| e.to_string())?;
274 writeln!(output, " periodSeconds: 5").map_err(|e| e.to_string())?;
275
276 writeln!(output, " resources:").map_err(|e| e.to_string())?;
278 writeln!(output, " requests:").map_err(|e| e.to_string())?;
279 writeln!(output, " cpu: 100m").map_err(|e| e.to_string())?;
280 writeln!(output, " memory: 128Mi").map_err(|e| e.to_string())?;
281 writeln!(output, " limits:").map_err(|e| e.to_string())?;
282 writeln!(output, " cpu: 500m").map_err(|e| e.to_string())?;
283 writeln!(output, " memory: 512Mi").map_err(|e| e.to_string())?;
284
285 Ok(output)
286 }
287
288 pub fn generate_k8s_service(spec: &ServiceSpec) -> Result<String, String> {
290 let mut output = String::new();
291
292 writeln!(output, "apiVersion: v1").map_err(|e| e.to_string())?;
293 writeln!(output, "kind: Service").map_err(|e| e.to_string())?;
294 writeln!(output, "metadata:").map_err(|e| e.to_string())?;
295 writeln!(output, " name: {}", spec.name).map_err(|e| e.to_string())?;
296 writeln!(output, " labels:").map_err(|e| e.to_string())?;
297 writeln!(output, " app: {}", spec.name).map_err(|e| e.to_string())?;
298
299 writeln!(output, "spec:").map_err(|e| e.to_string())?;
300 writeln!(output, " type: {}", spec.service_type).map_err(|e| e.to_string())?;
301 writeln!(output, " selector:").map_err(|e| e.to_string())?;
302 writeln!(output, " app: {}", spec.name).map_err(|e| e.to_string())?;
303
304 writeln!(output, " ports:").map_err(|e| e.to_string())?;
305 writeln!(output, " - name: http").map_err(|e| e.to_string())?;
306 writeln!(output, " port: {}", spec.port).map_err(|e| e.to_string())?;
307 writeln!(output, " targetPort: {}", spec.target_port).map_err(|e| e.to_string())?;
308 writeln!(output, " protocol: TCP").map_err(|e| e.to_string())?;
309
310 if spec.service_type == "LoadBalancer" {
312 writeln!(output, " sessionAffinity: ClientIP").map_err(|e| e.to_string())?;
313 writeln!(output, " sessionAffinityConfig:").map_err(|e| e.to_string())?;
314 writeln!(output, " clientIP:").map_err(|e| e.to_string())?;
315 writeln!(output, " timeoutSeconds: 10800").map_err(|e| e.to_string())?;
316 }
317
318 Ok(output)
319 }
320
321 pub fn generate_configmap(
323 name: &str, config_pairs: &[(String, String)],
324 ) -> Result<String, String> {
325 let mut output = String::new();
326
327 writeln!(output, "apiVersion: v1").map_err(|e| e.to_string())?;
328 writeln!(output, "kind: ConfigMap").map_err(|e| e.to_string())?;
329 writeln!(output, "metadata:").map_err(|e| e.to_string())?;
330 writeln!(output, " name: {}-config", name).map_err(|e| e.to_string())?;
331 writeln!(output, " namespace: default").map_err(|e| e.to_string())?;
332
333 writeln!(output, "data:").map_err(|e| e.to_string())?;
334 for (key, value) in config_pairs {
335 writeln!(output, " {}: |", key).map_err(|e| e.to_string())?;
336 for line in value.lines() {
338 writeln!(output, " {}", line).map_err(|e| e.to_string())?;
339 }
340 }
341
342 Ok(output)
343 }
344
345 pub fn generate_helm_values(services: &[ServiceSpec]) -> Result<String, String> {
347 let mut output = String::new();
348
349 writeln!(
350 output,
351 "# Helm values template for multi-service deployment"
352 )
353 .map_err(|e| e.to_string())?;
354 writeln!(output, "# Auto-generated from service specifications")
355 .map_err(|e| e.to_string())?;
356 writeln!(output).map_err(|e| e.to_string())?;
357
358 writeln!(output, "# Global configuration").map_err(|e| e.to_string())?;
359 writeln!(output, "global:").map_err(|e| e.to_string())?;
360 writeln!(output, " namespace: default").map_err(|e| e.to_string())?;
361 writeln!(output, " registry: myregistry.azurecr.io").map_err(|e| e.to_string())?;
362 writeln!(output, " imagePullPolicy: Always").map_err(|e| e.to_string())?;
363 writeln!(output).map_err(|e| e.to_string())?;
364
365 writeln!(output, "# Per-service overrides").map_err(|e| e.to_string())?;
366 writeln!(output, "services:").map_err(|e| e.to_string())?;
367
368 for service in services {
369 writeln!(output, " {}:", service.name).map_err(|e| e.to_string())?;
370 writeln!(output, " enabled: true").map_err(|e| e.to_string())?;
371 writeln!(output, " replicas: {}", service.replicas).map_err(|e| e.to_string())?;
372 writeln!(output, " image:").map_err(|e| e.to_string())?;
373 writeln!(
374 output,
375 " repository: {}/{}",
376 service.registry, service.image
377 )
378 .map_err(|e| e.to_string())?;
379 writeln!(output, " tag: \"{}\"", service.tag).map_err(|e| e.to_string())?;
380 writeln!(output, " service:").map_err(|e| e.to_string())?;
381 writeln!(output, " type: {}", service.service_type).map_err(|e| e.to_string())?;
382 writeln!(output, " port: {}", service.port).map_err(|e| e.to_string())?;
383 writeln!(output, " targetPort: {}", service.target_port)
384 .map_err(|e| e.to_string())?;
385 writeln!(output, " resources:").map_err(|e| e.to_string())?;
386 writeln!(output, " requests:").map_err(|e| e.to_string())?;
387 writeln!(output, " cpu: 100m").map_err(|e| e.to_string())?;
388 writeln!(output, " memory: 128Mi").map_err(|e| e.to_string())?;
389 writeln!(output, " limits:").map_err(|e| e.to_string())?;
390 writeln!(output, " cpu: 500m").map_err(|e| e.to_string())?;
391 writeln!(output, " memory: 512Mi").map_err(|e| e.to_string())?;
392
393 if !service.env_vars.is_empty() {
394 writeln!(output, " env:").map_err(|e| e.to_string())?;
395 for (key, value) in &service.env_vars {
396 writeln!(output, " {}: \"{}\"", key, value).map_err(|e| e.to_string())?;
397 }
398 }
399 writeln!(output).map_err(|e| e.to_string())?;
400 }
401
402 writeln!(output, "# Common overrides").map_err(|e| e.to_string())?;
404 writeln!(output, "autoscaling:").map_err(|e| e.to_string())?;
405 writeln!(output, " enabled: true").map_err(|e| e.to_string())?;
406 writeln!(output, " minReplicas: 2").map_err(|e| e.to_string())?;
407 writeln!(output, " maxReplicas: 10").map_err(|e| e.to_string())?;
408 writeln!(output, " targetCPUUtilizationPercentage: 80").map_err(|e| e.to_string())?;
409
410 Ok(output)
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417
418 #[test]
419 fn test_dockerfile_generation_rust() {
420 let result = DockerKubernetesGenerator::generate_dockerfile(&Language::Rust, "myapp");
421 assert!(result.is_ok());
422 let docker = result.unwrap();
423 assert!(docker.contains("FROM rust:latest as builder"));
424 assert!(docker.contains("FROM debian:bookworm-slim"));
425 assert!(docker.contains("cargo build --release"));
426 }
427
428 #[test]
429 fn test_dockerfile_generation_go() {
430 let result = DockerKubernetesGenerator::generate_dockerfile(&Language::Go, "myapp");
431 assert!(result.is_ok());
432 let docker = result.unwrap();
433 assert!(docker.contains("FROM golang:1.24-alpine as builder"));
434 assert!(docker.contains("FROM alpine:latest"));
435 assert!(docker.contains("CGO_ENABLED=0"));
436 }
437
438 #[test]
439 fn test_k8s_deployment_generation() {
440 let spec = ServiceSpec {
441 name: "order-api".to_string(),
442 replicas: 3,
443 port: 8001,
444 target_port: 8001,
445 image: "order-api".to_string(),
446 ..Default::default()
447 };
448
449 let result = DockerKubernetesGenerator::generate_k8s_deployment(&spec);
450 assert!(result.is_ok());
451 let manifest = result.unwrap();
452 assert!(manifest.contains("kind: Deployment"));
453 assert!(manifest.contains("name: order-api"));
454 assert!(manifest.contains("replicas: 3"));
455 assert!(manifest.contains("containerPort: 8001"));
456 }
457
458 #[test]
459 fn test_k8s_service_generation() {
460 let spec = ServiceSpec {
461 name: "order-api".to_string(),
462 service_type: "LoadBalancer".to_string(),
463 port: 8001,
464 target_port: 8001,
465 ..Default::default()
466 };
467
468 let result = DockerKubernetesGenerator::generate_k8s_service(&spec);
469 assert!(result.is_ok());
470 let manifest = result.unwrap();
471 assert!(manifest.contains("kind: Service"));
472 assert!(manifest.contains("type: LoadBalancer"));
473 assert!(manifest.contains("port: 8001"));
474 }
475
476 #[test]
477 fn test_configmap_generation() {
478 let config = vec![
479 (
480 "DATABASE_URL".to_string(),
481 "postgres://localhost".to_string(),
482 ),
483 ("API_KEY".to_string(), "secret123".to_string()),
484 ];
485
486 let result = DockerKubernetesGenerator::generate_configmap("myapp", &config);
487 assert!(result.is_ok());
488 let cm = result.unwrap();
489 assert!(cm.contains("kind: ConfigMap"));
490 assert!(cm.contains("name: myapp-config"));
491 assert!(cm.contains("DATABASE_URL"));
492 }
493
494 #[test]
495 fn test_helm_values_generation() {
496 let specs = vec![
497 ServiceSpec {
498 name: "api".to_string(),
499 replicas: 3,
500 port: 8001,
501 image: "api".to_string(),
502 ..Default::default()
503 },
504 ServiceSpec {
505 name: "worker".to_string(),
506 replicas: 2,
507 port: 8002,
508 image: "worker".to_string(),
509 ..Default::default()
510 },
511 ];
512
513 let result = DockerKubernetesGenerator::generate_helm_values(&specs);
514 assert!(result.is_ok());
515 let values = result.unwrap();
516 assert!(values.contains("services:"));
517 assert!(values.contains("api:"));
518 assert!(values.contains("worker:"));
519 assert!(values.contains("autoscaling:"));
520 }
521
522 #[test]
523 fn test_service_spec_defaults() {
524 let spec = ServiceSpec::default();
525 assert_eq!(spec.name, "default-service");
526 assert_eq!(spec.replicas, 3);
527 assert_eq!(spec.port, 8001);
528 }
529
530 #[test]
531 fn test_language_builder_images() {
532 assert_eq!(Language::Rust.builder_image(), "rust:latest");
533 assert_eq!(Language::Go.builder_image(), "golang:1.24-alpine");
534 assert_eq!(Language::Elixir.builder_image(), "elixir:latest");
535 assert_eq!(Language::TypeScript.builder_image(), "node:20-alpine");
536 }
537
538 #[test]
539 fn test_language_build_commands() {
540 assert!(Language::Rust.build_command().contains("cargo build"));
541 assert!(Language::Go.build_command().contains("go build"));
542 assert!(Language::Elixir.build_command().contains("mix"));
543 }
544}