Repository navigation
Expand file tree
/
Copy pathdocker_analyzer.rs
More file actions
1634 lines (1454 loc) · 53.3 KB
/
Copy pathdocker_analyzer.rs
File metadata and controls
1634 lines (1454 loc) · 53.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Docker Analyzer Module
//!
//! This module provides Docker infrastructure analysis capabilities for detecting:
//! - Dockerfiles and their variants (dockerfile.dev, dockerfile.prod, etc.)
//! - Docker Compose files and their variants (docker-compose.dev.yaml, etc.)
//! - Port mappings and networking configuration
//! - Service discovery and inter-service communication
//! - Container orchestration patterns
use crate::error::Result;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
/// Represents a Docker infrastructure analysis
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DockerAnalysis {
/// All Dockerfiles found in the project
pub dockerfiles: Vec<DockerfileInfo>,
/// All Docker Compose files found in the project
pub compose_files: Vec<ComposeFileInfo>,
/// Analyzed services from compose files
pub services: Vec<DockerService>,
/// Network configuration and service discovery
pub networking: NetworkingConfig,
/// Overall container orchestration pattern
pub orchestration_pattern: OrchestrationPattern,
/// Environment-specific configurations
pub environments: Vec<DockerEnvironment>,
}
/// Information about a Dockerfile
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DockerfileInfo {
/// Path to the Dockerfile
pub path: PathBuf,
/// Environment this Dockerfile is for (dev, prod, staging, etc.)
pub environment: Option<String>,
/// Base image used
pub base_image: Option<String>,
/// Exposed ports from EXPOSE instructions
pub exposed_ports: Vec<u16>,
/// Working directory
pub workdir: Option<String>,
/// Entry point or CMD
pub entrypoint: Option<String>,
/// Environment variables defined
pub env_vars: Vec<String>,
/// Multi-stage build stages
pub build_stages: Vec<String>,
/// Whether it's a multi-stage build
pub is_multistage: bool,
/// Dockerfile instructions count (complexity indicator)
pub instruction_count: usize,
}
/// Dockerfile discovery result for deployment wizard
///
/// Provides deployment-focused metadata about a Dockerfile including
/// build context path, suggested service name, and port configuration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DiscoveredDockerfile {
/// Absolute path to the Dockerfile
pub path: PathBuf,
/// Relative path from project root to Dockerfile directory (build context)
pub build_context: String,
/// Suggested service name based on directory structure
pub suggested_service_name: String,
/// Suggested port for deployment (from EXPOSE or default)
pub suggested_port: Option<u16>,
/// Base image from Dockerfile
pub base_image: Option<String>,
/// Whether this is a multi-stage build
pub is_multistage: bool,
/// Environment type (dev, prod, staging) from filename
pub environment: Option<String>,
}
/// Information about a Docker Compose file
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ComposeFileInfo {
/// Path to the compose file
pub path: PathBuf,
/// Environment this compose file is for
pub environment: Option<String>,
/// Compose file version
pub version: Option<String>,
/// Services defined in the compose file
pub service_names: Vec<String>,
/// Networks defined
pub networks: Vec<String>,
/// Volumes defined
pub volumes: Vec<String>,
/// External dependencies (external networks, volumes)
pub external_dependencies: Vec<String>,
}
/// Container orchestration patterns
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum OrchestrationPattern {
/// Single container application
SingleContainer,
/// Multiple containers with docker-compose
DockerCompose,
/// Microservices architecture
Microservices,
/// Event-driven architecture
EventDriven,
/// Service mesh
ServiceMesh,
/// Mixed or complex pattern
Mixed,
}
/// Represents a Docker service from compose files
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DockerService {
/// Service name
pub name: String,
/// Which compose file this service is defined in
pub compose_file: PathBuf,
/// Docker image or build context
pub image_or_build: ImageOrBuild,
/// Port mappings
pub ports: Vec<PortMapping>,
/// Environment variables
pub environment: HashMap<String, String>,
/// Service dependencies
pub depends_on: Vec<String>,
/// Networks this service is connected to
pub networks: Vec<String>,
/// Volumes mounted
pub volumes: Vec<VolumeMount>,
/// Health check configuration
pub health_check: Option<HealthCheck>,
/// Restart policy
pub restart_policy: Option<String>,
/// Resource limits
pub resource_limits: Option<ResourceLimits>,
}
/// Image or build configuration for a service
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ImageOrBuild {
/// Uses a pre-built image
Image(String),
/// Builds from a Dockerfile
Build {
context: String,
dockerfile: Option<String>,
args: HashMap<String, String>,
},
}
/// Port mapping configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PortMapping {
/// Host port (external)
pub host_port: Option<u16>,
/// Container port (internal)
pub container_port: u16,
/// Protocol (tcp, udp)
pub protocol: String,
/// Whether this port is exposed to the host
pub exposed_to_host: bool,
}
/// Volume mount configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VolumeMount {
/// Source (host path or volume name)
pub source: String,
/// Target path in container
pub target: String,
/// Mount type (bind, volume, tmpfs)
pub mount_type: String,
/// Whether it's read-only
pub read_only: bool,
}
/// Health check configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct HealthCheck {
/// Test command
pub test: String,
/// Interval between checks
pub interval: Option<String>,
/// Timeout for each check
pub timeout: Option<String>,
/// Number of retries
pub retries: Option<u32>,
}
/// Resource limits configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResourceLimits {
/// CPU limit
pub cpu_limit: Option<String>,
/// Memory limit
pub memory_limit: Option<String>,
/// CPU reservation
pub cpu_reservation: Option<String>,
/// Memory reservation
pub memory_reservation: Option<String>,
}
/// Networking configuration analysis
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NetworkingConfig {
/// Custom networks defined
pub custom_networks: Vec<NetworkInfo>,
/// Service discovery patterns
pub service_discovery: ServiceDiscoveryConfig,
/// Load balancing configuration
pub load_balancing: Vec<LoadBalancerConfig>,
/// External connectivity patterns
pub external_connectivity: ExternalConnectivity,
}
/// Network information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NetworkInfo {
/// Network name
pub name: String,
/// Network driver
pub driver: Option<String>,
/// Whether it's external
pub external: bool,
/// Connected services
pub connected_services: Vec<String>,
}
/// Service discovery configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ServiceDiscoveryConfig {
/// Whether services can discover each other by name
pub internal_dns: bool,
/// External service discovery tools
pub external_tools: Vec<String>,
/// Service mesh indicators
pub service_mesh: bool,
}
/// Load balancer configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LoadBalancerConfig {
/// Service name
pub service: String,
/// Load balancer type (nginx, traefik, etc.)
pub lb_type: String,
/// Backend services
pub backends: Vec<String>,
}
/// External connectivity patterns
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ExternalConnectivity {
/// Services exposed to external traffic
pub exposed_services: Vec<ExposedService>,
/// Ingress patterns
pub ingress_patterns: Vec<String>,
/// API gateways
pub api_gateways: Vec<String>,
}
/// Service exposed to external traffic
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ExposedService {
/// Service name
pub service: String,
/// External ports
pub external_ports: Vec<u16>,
/// Protocols
pub protocols: Vec<String>,
/// Whether it has SSL/TLS
pub ssl_enabled: bool,
}
/// Environment-specific Docker configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DockerEnvironment {
/// Environment name (dev, prod, staging, etc.)
pub name: String,
/// Dockerfiles for this environment
pub dockerfiles: Vec<PathBuf>,
/// Compose files for this environment
pub compose_files: Vec<PathBuf>,
/// Environment-specific configurations
pub config_overrides: HashMap<String, String>,
}
/// Analyzes Docker infrastructure in a project
pub fn analyze_docker_infrastructure(project_root: &Path) -> Result<DockerAnalysis> {
log::info!(
"Starting Docker infrastructure analysis for: {}",
project_root.display()
);
// Find all Docker-related files
let dockerfiles = find_dockerfiles(project_root)?;
let compose_files = find_compose_files(project_root)?;
log::debug!(
"Found {} Dockerfiles and {} Compose files",
dockerfiles.len(),
compose_files.len()
);
// Parse Dockerfiles
let parsed_dockerfiles: Vec<DockerfileInfo> = dockerfiles
.into_iter()
.filter_map(|path| parse_dockerfile(&path).ok())
.collect();
// Parse Compose files
let parsed_compose_files: Vec<ComposeFileInfo> = compose_files
.into_iter()
.filter_map(|path| parse_compose_file(&path).ok())
.collect();
// Extract services from compose files
let services = extract_services_from_compose(&parsed_compose_files)?;
// Analyze networking
let networking = analyze_networking(&services, &parsed_compose_files)?;
// Determine orchestration pattern
let orchestration_pattern = determine_orchestration_pattern(&services, &networking);
// Analyze environments
let environments = analyze_environments(&parsed_dockerfiles, &parsed_compose_files);
Ok(DockerAnalysis {
dockerfiles: parsed_dockerfiles,
compose_files: parsed_compose_files,
services,
networking,
orchestration_pattern,
environments,
})
}
/// Finds all Dockerfiles in the project, including variants
fn find_dockerfiles(project_root: &Path) -> Result<Vec<PathBuf>> {
let mut dockerfiles = Vec::new();
fn collect_dockerfiles_recursive(dir: &Path, dockerfiles: &mut Vec<PathBuf>) -> Result<()> {
if dir.file_name().is_some_and(|name| {
name == "node_modules" || name == ".git" || name == "target" || name == ".next"
}) {
return Ok(());
}
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
collect_dockerfiles_recursive(&path, dockerfiles)?;
} else if let Some(filename) = path.file_name().and_then(|n| n.to_str())
&& is_dockerfile_name(filename)
{
dockerfiles.push(path);
}
}
Ok(())
}
collect_dockerfiles_recursive(project_root, &mut dockerfiles)?;
Ok(dockerfiles)
}
/// Checks if a filename matches Dockerfile patterns
fn is_dockerfile_name(filename: &str) -> bool {
let filename_lower = filename.to_lowercase();
// Exact matches
if filename_lower == "dockerfile" {
return true;
}
// Pattern matches
if filename_lower.starts_with("dockerfile.") {
return true;
}
if filename_lower.ends_with(".dockerfile") {
return true;
}
false
}
/// Finds all Docker Compose files in the project
fn find_compose_files(project_root: &Path) -> Result<Vec<PathBuf>> {
let mut compose_files = Vec::new();
fn collect_compose_files_recursive(dir: &Path, compose_files: &mut Vec<PathBuf>) -> Result<()> {
if dir.file_name().is_some_and(|name| {
name == "node_modules" || name == ".git" || name == "target" || name == ".next"
}) {
return Ok(());
}
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
collect_compose_files_recursive(&path, compose_files)?;
} else if let Some(filename) = path.file_name().and_then(|n| n.to_str())
&& is_compose_file_name(filename)
{
compose_files.push(path);
}
}
Ok(())
}
collect_compose_files_recursive(project_root, &mut compose_files)?;
Ok(compose_files)
}
/// Checks if a filename matches Docker Compose patterns
fn is_compose_file_name(filename: &str) -> bool {
let filename_lower = filename.to_lowercase();
// Common compose file patterns
let patterns = [
"docker-compose.yml",
"docker-compose.yaml",
"compose.yml",
"compose.yaml",
];
// Exact matches
for pattern in &patterns {
if filename_lower == *pattern {
return true;
}
}
// Environment-specific patterns
if filename_lower.starts_with("docker-compose.")
&& (filename_lower.ends_with(".yml") || filename_lower.ends_with(".yaml"))
{
return true;
}
if filename_lower.starts_with("compose.")
&& (filename_lower.ends_with(".yml") || filename_lower.ends_with(".yaml"))
{
return true;
}
false
}
/// Parses a Dockerfile and extracts information
fn parse_dockerfile(path: &PathBuf) -> Result<DockerfileInfo> {
let content = fs::read_to_string(path)?;
let lines: Vec<&str> = content.lines().collect();
let mut info = DockerfileInfo {
path: path.clone(),
environment: extract_environment_from_filename(path),
base_image: None,
exposed_ports: Vec::new(),
workdir: None,
entrypoint: None,
env_vars: Vec::new(),
build_stages: Vec::new(),
is_multistage: false,
instruction_count: 0,
};
// Regex patterns for Dockerfile instructions
let from_regex = Regex::new(r"(?i)^FROM\s+(.+?)(?:\s+AS\s+(.+))?$").unwrap();
let expose_regex = Regex::new(r"(?i)^EXPOSE\s+(.+)$").unwrap();
let workdir_regex = Regex::new(r"(?i)^WORKDIR\s+(.+)$").unwrap();
let cmd_regex = Regex::new(r"(?i)^CMD\s+(.+)$").unwrap();
let entrypoint_regex = Regex::new(r"(?i)^ENTRYPOINT\s+(.+)$").unwrap();
let env_regex = Regex::new(r"(?i)^ENV\s+(.+)$").unwrap();
for line in lines {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
info.instruction_count += 1;
// Parse FROM instructions
if let Some(captures) = from_regex.captures(line) {
if info.base_image.is_none() {
info.base_image = Some(captures.get(1).unwrap().as_str().trim().to_string());
}
if let Some(stage_name) = captures.get(2) {
info.build_stages
.push(stage_name.as_str().trim().to_string());
info.is_multistage = true;
}
}
// Parse EXPOSE instructions
if let Some(captures) = expose_regex.captures(line) {
let ports_str = captures.get(1).unwrap().as_str();
for port in ports_str.split_whitespace() {
if let Ok(port_num) = port.parse::<u16>() {
info.exposed_ports.push(port_num);
}
}
}
// Parse WORKDIR
if let Some(captures) = workdir_regex.captures(line) {
info.workdir = Some(captures.get(1).unwrap().as_str().trim().to_string());
}
// Parse CMD and ENTRYPOINT
if let Some(captures) = cmd_regex.captures(line)
&& info.entrypoint.is_none()
{
info.entrypoint = Some(captures.get(1).unwrap().as_str().trim().to_string());
}
if let Some(captures) = entrypoint_regex.captures(line) {
info.entrypoint = Some(captures.get(1).unwrap().as_str().trim().to_string());
}
// Parse ENV
if let Some(captures) = env_regex.captures(line) {
info.env_vars
.push(captures.get(1).unwrap().as_str().trim().to_string());
}
}
Ok(info)
}
/// Parses a Docker Compose file and extracts information
fn parse_compose_file(path: &PathBuf) -> Result<ComposeFileInfo> {
let content = fs::read_to_string(path)?;
// Parse YAML content
let yaml_value: serde_yaml::Value = serde_yaml::from_str(&content).map_err(|e| {
crate::error::AnalysisError::DependencyParsing {
file: path.display().to_string(),
reason: format!("YAML parsing error: {}", e),
}
})?;
let mut info = ComposeFileInfo {
path: path.clone(),
environment: extract_environment_from_filename(path),
version: None,
service_names: Vec::new(),
networks: Vec::new(),
volumes: Vec::new(),
external_dependencies: Vec::new(),
};
// Extract version
if let Some(version) = yaml_value.get("version").and_then(|v| v.as_str()) {
info.version = Some(version.to_string());
}
// Extract service names
if let Some(services) = yaml_value.get("services").and_then(|s| s.as_mapping()) {
for (service_name, _) in services {
if let Some(name) = service_name.as_str() {
info.service_names.push(name.to_string());
}
}
}
// Extract networks
if let Some(networks) = yaml_value.get("networks").and_then(|n| n.as_mapping()) {
for (network_name, network_config) in networks {
if let Some(name) = network_name.as_str() {
info.networks.push(name.to_string());
// Check if it's external
if let Some(config) = network_config.as_mapping()
&& config
.get("external")
.and_then(|e| e.as_bool())
.unwrap_or(false)
{
info.external_dependencies.push(format!("network:{}", name));
}
}
}
}
// Extract volumes
if let Some(volumes) = yaml_value.get("volumes").and_then(|v| v.as_mapping()) {
for (volume_name, volume_config) in volumes {
if let Some(name) = volume_name.as_str() {
info.volumes.push(name.to_string());
// Check if it's external
if let Some(config) = volume_config.as_mapping()
&& config
.get("external")
.and_then(|e| e.as_bool())
.unwrap_or(false)
{
info.external_dependencies.push(format!("volume:{}", name));
}
}
}
}
Ok(info)
}
/// Extracts environment from filename (e.g., "dev" from "dockerfile.dev")
fn extract_environment_from_filename(path: &Path) -> Option<String> {
if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
let filename_lower = filename.to_lowercase();
// Helper to map env shorthand to full name
let map_env = |env: &str| -> Option<String> {
match env {
"dev" | "development" | "local" => Some("development".to_string()),
"prod" | "production" => Some("production".to_string()),
"test" | "testing" => Some("test".to_string()),
"stage" | "staging" => Some("staging".to_string()),
_ if env.len() <= 10 && !env.is_empty() => Some(env.to_string()),
_ => None,
}
};
// Handle patterns like "docker-compose.prod.yml" (env between two dots)
if let Some(last_dot) = filename_lower.rfind('.')
&& let Some(env_dot_pos) = filename_lower[..last_dot].rfind('.')
{
let env = &filename_lower[env_dot_pos + 1..last_dot];
if let Some(result) = map_env(env) {
return Some(result);
}
}
// Handle patterns like "Dockerfile.dev" (env is the extension itself)
if let Some(dot_pos) = filename_lower.rfind('.') {
let ext = &filename_lower[dot_pos + 1..];
// Only if the base is dockerfile/docker-compose related
let base = &filename_lower[..dot_pos];
if (base.contains("dockerfile") || base.contains("docker-compose") || base == "compose")
&& let Some(result) = map_env(ext)
{
return Some(result);
}
}
}
None
}
/// Helper functions for parsing compose files
fn extract_services_from_compose(compose_files: &[ComposeFileInfo]) -> Result<Vec<DockerService>> {
let mut services = Vec::new();
for compose_file in compose_files {
let content = fs::read_to_string(&compose_file.path)?;
let yaml_value: serde_yaml::Value = serde_yaml::from_str(&content).map_err(|e| {
crate::error::AnalysisError::DependencyParsing {
file: compose_file.path.display().to_string(),
reason: format!("YAML parsing error: {}", e),
}
})?;
if let Some(services_yaml) = yaml_value.get("services").and_then(|s| s.as_mapping()) {
for (service_name, service_config) in services_yaml {
if let (Some(name), Some(config)) =
(service_name.as_str(), service_config.as_mapping())
{
let service = parse_docker_service(name, config, &compose_file.path)?;
services.push(service);
}
}
}
}
Ok(services)
}
/// Parses a Docker service from compose configuration
fn parse_docker_service(
name: &str,
config: &serde_yaml::Mapping,
compose_file: &Path,
) -> Result<DockerService> {
let mut service = DockerService {
name: name.to_string(),
compose_file: compose_file.to_path_buf(),
image_or_build: ImageOrBuild::Image("unknown".to_string()),
ports: Vec::new(),
environment: HashMap::new(),
depends_on: Vec::new(),
networks: Vec::new(),
volumes: Vec::new(),
health_check: None,
restart_policy: None,
resource_limits: None,
};
// Parse image or build
if let Some(image) = config.get("image").and_then(|i| i.as_str()) {
service.image_or_build = ImageOrBuild::Image(image.to_string());
} else if let Some(build_config) = config.get("build") {
if let Some(context) = build_config.as_str() {
service.image_or_build = ImageOrBuild::Build {
context: context.to_string(),
dockerfile: None,
args: HashMap::new(),
};
} else if let Some(build_mapping) = build_config.as_mapping() {
let context = build_mapping
.get("context")
.and_then(|c| c.as_str())
.unwrap_or(".")
.to_string();
let dockerfile = build_mapping
.get("dockerfile")
.and_then(|d| d.as_str())
.map(|s| s.to_string());
let mut args = HashMap::new();
if let Some(args_config) = build_mapping.get("args").and_then(|a| a.as_mapping()) {
for (key, value) in args_config {
if let (Some(k), Some(v)) = (key.as_str(), value.as_str()) {
args.insert(k.to_string(), v.to_string());
}
}
}
service.image_or_build = ImageOrBuild::Build {
context,
dockerfile,
args,
};
}
}
// Parse ports
if let Some(ports_config) = config.get("ports").and_then(|p| p.as_sequence()) {
for port_item in ports_config {
if let Some(port_mapping) = parse_port_mapping(port_item) {
service.ports.push(port_mapping);
}
}
}
// Parse environment variables
if let Some(env_config) = config.get("environment") {
parse_environment_variables(env_config, &mut service.environment);
}
// Parse depends_on
if let Some(depends_config) = config.get("depends_on") {
if let Some(depends_sequence) = depends_config.as_sequence() {
for dep in depends_sequence {
if let Some(dep_name) = dep.as_str() {
service.depends_on.push(dep_name.to_string());
}
}
} else if let Some(depends_mapping) = depends_config.as_mapping() {
for (dep_name, _) in depends_mapping {
if let Some(name) = dep_name.as_str() {
service.depends_on.push(name.to_string());
}
}
}
}
// Parse networks
if let Some(networks_config) = config.get("networks") {
if let Some(networks_sequence) = networks_config.as_sequence() {
for network in networks_sequence {
if let Some(network_name) = network.as_str() {
service.networks.push(network_name.to_string());
}
}
} else if let Some(networks_mapping) = networks_config.as_mapping() {
for (network_name, _) in networks_mapping {
if let Some(name) = network_name.as_str() {
service.networks.push(name.to_string());
}
}
}
}
// Parse volumes
if let Some(volumes_config) = config.get("volumes").and_then(|v| v.as_sequence()) {
for volume_item in volumes_config {
if let Some(volume_mount) = parse_volume_mount(volume_item) {
service.volumes.push(volume_mount);
}
}
}
// Parse restart policy
if let Some(restart) = config.get("restart").and_then(|r| r.as_str()) {
service.restart_policy = Some(restart.to_string());
}
// Parse health check
if let Some(healthcheck_config) = config.get("healthcheck").and_then(|h| h.as_mapping())
&& let Some(test) = healthcheck_config.get("test").and_then(|t| t.as_str())
{
service.health_check = Some(HealthCheck {
test: test.to_string(),
interval: healthcheck_config
.get("interval")
.and_then(|i| i.as_str())
.map(|s| s.to_string()),
timeout: healthcheck_config
.get("timeout")
.and_then(|t| t.as_str())
.map(|s| s.to_string()),
retries: healthcheck_config
.get("retries")
.and_then(|r| r.as_u64())
.map(|r| r as u32),
});
}
Ok(service)
}
/// Parses port mapping from YAML value
fn parse_port_mapping(port_value: &serde_yaml::Value) -> Option<PortMapping> {
if let Some(port_str) = port_value.as_str() {
// Handle string format like "8080:80" or "80"
if let Some(colon_pos) = port_str.find(':') {
let host_part = &port_str[..colon_pos];
let container_part = &port_str[colon_pos + 1..];
if let (Ok(host_port), Ok(container_port)) =
(host_part.parse::<u16>(), container_part.parse::<u16>())
{
return Some(PortMapping {
host_port: Some(host_port),
container_port,
protocol: "tcp".to_string(),
exposed_to_host: true,
});
}
} else if let Ok(container_port) = port_str.parse::<u16>() {
return Some(PortMapping {
host_port: None,
container_port,
protocol: "tcp".to_string(),
exposed_to_host: false,
});
}
} else if let Some(port_num) = port_value.as_u64() {
return Some(PortMapping {
host_port: None,
container_port: port_num as u16,
protocol: "tcp".to_string(),
exposed_to_host: false,
});
}
None
}
/// Parses volume mount from YAML value
fn parse_volume_mount(volume_value: &serde_yaml::Value) -> Option<VolumeMount> {
if let Some(volume_str) = volume_value.as_str() {
// Handle string format like "./data:/app/data:ro" or "./data:/app/data"
let parts: Vec<&str> = volume_str.split(':').collect();
if parts.len() >= 2 {
return Some(VolumeMount {
source: parts[0].to_string(),
target: parts[1].to_string(),
mount_type: if parts[0].starts_with('/') || parts[0].starts_with('.') {
"bind".to_string()
} else {
"volume".to_string()
},
read_only: parts.get(2).is_some_and(|&opt| opt == "ro"),
});
}
}
None
}
/// Parses environment variables from YAML
fn parse_environment_variables(
env_value: &serde_yaml::Value,
env_map: &mut HashMap<String, String>,
) {
if let Some(env_mapping) = env_value.as_mapping() {
for (key, value) in env_mapping {
if let Some(key_str) = key.as_str() {
let value_str = value.as_str().unwrap_or("").to_string();
env_map.insert(key_str.to_string(), value_str);
}
}
} else if let Some(env_sequence) = env_value.as_sequence() {
for env_item in env_sequence {
if let Some(env_str) = env_item.as_str() {
if let Some(eq_pos) = env_str.find('=') {
let key = env_str[..eq_pos].to_string();
let value = env_str[eq_pos + 1..].to_string();
env_map.insert(key, value);
} else {
env_map.insert(env_str.to_string(), String::new());
}
}
}
}
}
fn analyze_networking(
services: &[DockerService],
compose_files: &[ComposeFileInfo],
) -> Result<NetworkingConfig> {
let mut custom_networks = Vec::new();
let mut connected_services: HashMap<String, Vec<String>> = HashMap::new();
// Collect networks from compose files
for compose_file in compose_files {
for network_name in &compose_file.networks {
let network_info = NetworkInfo {
name: network_name.clone(),
driver: None, // TODO: Parse driver from compose file
external: compose_file
.external_dependencies
.contains(&format!("network:{}", network_name)),
connected_services: Vec::new(),
};
custom_networks.push(network_info);
}
}
// Map services to networks
for service in services {
for network in &service.networks {
connected_services
.entry(network.clone())
.or_default()
.push(service.name.clone());
}
}
// Update network info with connected services
for network in &mut custom_networks {
if let Some(services) = connected_services.get(&network.name) {
network.connected_services = services.clone();
}
}
// Analyze service discovery
let service_discovery = ServiceDiscoveryConfig {
internal_dns: !services.is_empty(), // Docker Compose provides internal DNS
external_tools: detect_service_discovery_tools(services),
service_mesh: detect_service_mesh(services),
};
// Analyze load balancing
let load_balancing = detect_load_balancers(services);
// Analyze external connectivity
let external_connectivity = analyze_external_connectivity(services);
Ok(NetworkingConfig {
custom_networks,
service_discovery,
load_balancing,
external_connectivity,
})
}
fn determine_orchestration_pattern(
services: &[DockerService],
networking: &NetworkingConfig,
) -> OrchestrationPattern {
if services.is_empty() {
return OrchestrationPattern::SingleContainer;
}
if services.len() == 1 {
return OrchestrationPattern::SingleContainer;
}
// Check for microservices patterns
let has_multiple_backends = services
.iter()
.filter(|s| match &s.image_or_build {
ImageOrBuild::Image(img) => {
!img.contains("nginx") && !img.contains("proxy") && !img.contains("traefik")