system_analysis/
types.rs

1//! Core types for system analysis.
2
3use crate::resources::{ResourceRequirement, ResourceType};
4use crate::workloads::Workload;
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9/// Represents a complete system profile with all capability scores
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct SystemProfile {
12    /// CPU performance score (0-10)
13    pub cpu_score: f64,
14    /// GPU performance score (0-10)
15    pub gpu_score: f64,
16    /// Memory performance score (0-10)
17    pub memory_score: f64,
18    /// Storage performance score (0-10)
19    pub storage_score: f64,
20    /// Network performance score (0-10)
21    pub network_score: f64,
22    /// Overall system score (0-10)
23    pub overall_score: f64,
24    /// Detailed system information
25    pub system_info: SystemInfo,
26    /// Timestamp when profile was created
27    pub created_at: DateTime<Utc>,
28}
29
30impl SystemProfile {
31    /// Create a new system profile
32    pub fn new(
33        cpu_score: f64,
34        gpu_score: f64,
35        memory_score: f64,
36        storage_score: f64,
37        network_score: f64,
38        system_info: SystemInfo,
39    ) -> Self {
40        let overall_score = (cpu_score + gpu_score + memory_score + storage_score + network_score) / 5.0;
41        
42        Self {
43            cpu_score,
44            gpu_score,
45            memory_score,
46            storage_score,
47            network_score,
48            overall_score,
49            system_info,
50            created_at: Utc::now(),
51        }
52    }
53
54    /// Get the CPU score
55    pub fn cpu_score(&self) -> f64 {
56        self.cpu_score
57    }
58
59    /// Get the GPU score
60    pub fn gpu_score(&self) -> f64 {
61        self.gpu_score
62    }
63
64    /// Get the memory score
65    pub fn memory_score(&self) -> f64 {
66        self.memory_score
67    }
68
69    /// Get the storage score
70    pub fn storage_score(&self) -> f64 {
71        self.storage_score
72    }
73
74    /// Get the network score
75    pub fn network_score(&self) -> f64 {
76        self.network_score
77    }
78
79    /// Get the overall score
80    pub fn overall_score(&self) -> f64 {
81        self.overall_score
82    }
83
84    /// Get AI capabilities assessment
85    pub fn ai_capabilities(&self) -> AICapabilities {
86        AICapabilities::from_profile(self)
87    }
88}
89
90/// Detailed system information
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct SystemInfo {
93    /// Operating system name
94    pub os_name: String,
95    /// OS version
96    pub os_version: String,
97    /// CPU information
98    pub cpu_info: CpuInfo,
99    /// GPU information
100    pub gpu_info: Vec<GpuInfo>,
101    /// Memory information
102    pub memory_info: MemoryInfo,
103    /// Storage information
104    pub storage_info: Vec<StorageInfo>,
105    /// Network information
106    pub network_info: NetworkInfo,
107}
108
109/// CPU information
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct CpuInfo {
112    /// CPU brand/model
113    pub brand: String,
114    /// Number of physical cores
115    pub physical_cores: usize,
116    /// Number of logical cores
117    pub logical_cores: usize,
118    /// Base frequency in MHz
119    pub base_frequency: u64,
120    /// Maximum frequency in MHz
121    pub max_frequency: Option<u64>,
122    /// Cache size in MB
123    pub cache_size: Option<u64>,
124    /// Architecture (x86_64, arm64, etc.)
125    pub architecture: String,
126}
127
128/// GPU information
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct GpuInfo {
131    /// GPU name/model
132    pub name: String,
133    /// GPU vendor (NVIDIA, AMD, Intel, etc.)
134    pub vendor: String,
135    /// VRAM size in MB
136    pub vram_size: Option<u64>,
137    /// Compute capability (for CUDA)
138    pub compute_capability: Option<String>,
139    /// OpenCL support
140    pub opencl_support: bool,
141    /// CUDA support
142    pub cuda_support: bool,
143}
144
145/// Memory information
146#[derive(Debug, Clone, Serialize, Deserialize)]
147pub struct MemoryInfo {
148    /// Total RAM in MB
149    pub total_ram: u64,
150    /// Available RAM in MB
151    pub available_ram: u64,
152    /// Memory type (DDR4, DDR5, etc.)
153    pub memory_type: Option<String>,
154    /// Memory speed in MHz
155    pub memory_speed: Option<u64>,
156}
157
158/// Storage information
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct StorageInfo {
161    /// Storage device name
162    pub name: String,
163    /// Storage type (SSD, HDD, NVMe, etc.)
164    pub storage_type: String,
165    /// Total capacity in GB
166    pub total_capacity: u64,
167    /// Available capacity in GB
168    pub available_capacity: u64,
169    /// Read speed in MB/s
170    pub read_speed: Option<u64>,
171    /// Write speed in MB/s
172    pub write_speed: Option<u64>,
173}
174
175/// Network information
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct NetworkInfo {
178    /// Network interfaces
179    pub interfaces: Vec<NetworkInterface>,
180    /// Internet connectivity
181    pub internet_connected: bool,
182    /// Estimated bandwidth in Mbps
183    pub estimated_bandwidth: Option<u64>,
184}
185
186/// Network interface information
187#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct NetworkInterface {
189    /// Interface name
190    pub name: String,
191    /// Interface type (Ethernet, WiFi, etc.)
192    pub interface_type: String,
193    /// MAC address
194    pub mac_address: String,
195    /// IP addresses
196    pub ip_addresses: Vec<String>,
197    /// Connection speed in Mbps
198    pub speed: Option<u64>,
199}
200
201/// AI capabilities assessment
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct AICapabilities {
204    /// AI inference capability level
205    pub inference_level: String,
206    /// AI training capability level
207    pub training_level: String,
208    /// Recommended model sizes
209    pub recommended_models: Vec<String>,
210    /// Hardware acceleration support
211    pub hardware_acceleration: Vec<String>,
212}
213
214impl AICapabilities {
215    /// Create AI capabilities from system profile
216    pub fn from_profile(profile: &SystemProfile) -> Self {
217        let inference_level = match profile.overall_score {
218            score if score >= 8.0 => "High - Can run large models efficiently",
219            score if score >= 6.0 => "Medium - Can run medium models",
220            score if score >= 4.0 => "Low - Can run small models",
221            _ => "Very Low - Limited AI capabilities",
222        };
223
224        let training_level = match profile.gpu_score {
225            score if score >= 8.0 => "High - Can train large models",
226            score if score >= 6.0 => "Medium - Can train medium models",
227            score if score >= 4.0 => "Low - Can train small models",
228            _ => "Very Low - Training not recommended",
229        };
230
231        let recommended_models = match profile.overall_score {
232            score if score >= 8.0 => vec![
233                "GPT-4 class models".to_string(),
234                "Large language models (70B+)".to_string(),
235                "Multimodal models".to_string(),
236            ],
237            score if score >= 6.0 => vec![
238                "Medium language models (7B-13B)".to_string(),
239                "Image generation models".to_string(),
240                "Code generation models".to_string(),
241            ],
242            score if score >= 4.0 => vec![
243                "Small language models (1B-3B)".to_string(),
244                "Lightweight models".to_string(),
245            ],
246            _ => vec!["Quantized models only".to_string()],
247        };
248
249        let mut hardware_acceleration = Vec::new();
250        if profile.gpu_score >= 6.0 {
251            hardware_acceleration.push("GPU acceleration".to_string());
252        }
253        if profile.cpu_score >= 7.0 {
254            hardware_acceleration.push("CPU optimization".to_string());
255        }
256
257        Self {
258            inference_level: inference_level.to_string(),
259            training_level: training_level.to_string(),
260            recommended_models,
261            hardware_acceleration,
262        }
263    }
264
265    /// Get the inference level
266    pub fn inference_level(&self) -> &str {
267        &self.inference_level
268    }
269
270    /// Get the training level
271    pub fn training_level(&self) -> &str {
272        &self.training_level
273    }
274}
275
276/// Workload requirements specification
277#[derive(Debug)]
278pub struct WorkloadRequirements {
279    /// Workload name/identifier
280    pub name: String,
281    /// Resource requirements
282    pub resource_requirements: Vec<ResourceRequirement>,
283    /// Specific workload details
284    pub workload: Option<Box<dyn Workload>>,
285    /// Priority level
286    pub priority: WorkloadPriority,
287    /// Performance targets
288    pub performance_targets: PerformanceTargets,
289    /// Created timestamp
290    pub created_at: DateTime<Utc>,
291}
292
293impl Clone for WorkloadRequirements {
294    fn clone(&self) -> Self {
295        Self {
296            name: self.name.clone(),
297            resource_requirements: self.resource_requirements.clone(),
298            workload: self.workload.as_ref().map(|w| w.clone_workload()),
299            priority: self.priority,
300            performance_targets: self.performance_targets.clone(),
301            created_at: self.created_at,
302        }
303    }
304}
305impl WorkloadRequirements {
306    /// Create new workload requirements
307    pub fn new(name: impl Into<String>) -> Self {
308        Self {
309            name: name.into(),
310            resource_requirements: Vec::new(),
311            workload: None,
312            priority: WorkloadPriority::Medium,
313            performance_targets: PerformanceTargets::default(),
314            created_at: Utc::now(),
315        }
316    }
317
318    /// Add a resource requirement
319    pub fn add_resource_requirement(&mut self, requirement: ResourceRequirement) {
320        self.resource_requirements.push(requirement);
321    }
322
323    /// Set the workload
324    pub fn set_workload(&mut self, workload: Box<dyn Workload>) {
325        self.workload = Some(workload);
326    }
327
328    /// Set the priority
329    pub fn set_priority(&mut self, priority: WorkloadPriority) {
330        self.priority = priority;
331    }
332
333    /// Set performance targets
334    pub fn set_performance_targets(&mut self, targets: PerformanceTargets) {
335        self.performance_targets = targets;
336    }
337
338    /// Get resource requirement by type
339    pub fn get_resource_requirement(&self, resource_type: &ResourceType) -> Option<&ResourceRequirement> {
340        self.resource_requirements
341            .iter()
342            .find(|req| &req.resource_type == resource_type)
343    }
344}
345
346/// Workload priority levels
347#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
348pub enum WorkloadPriority {
349    /// Low priority workload
350    Low,
351    /// Medium priority workload
352    Medium,
353    /// High priority workload
354    High,
355    /// Critical priority workload
356    Critical,
357}
358
359/// Performance targets for workloads
360#[derive(Debug, Clone, Serialize, Deserialize)]
361pub struct PerformanceTargets {
362    /// Target latency in milliseconds
363    pub target_latency_ms: Option<f64>,
364    /// Target throughput (operations per second)
365    pub target_throughput: Option<f64>,
366    /// Maximum resource utilization percentage
367    pub max_resource_utilization: Option<f64>,
368    /// Energy efficiency requirements
369    pub energy_efficiency: Option<f64>,
370}
371
372impl Default for PerformanceTargets {
373    fn default() -> Self {
374        Self {
375            target_latency_ms: None,
376            target_throughput: None,
377            max_resource_utilization: Some(80.0),
378            energy_efficiency: None,
379        }
380    }
381}
382
383/// Result of compatibility analysis
384#[derive(Debug, Clone, Serialize, Deserialize)]
385pub struct CompatibilityResult {
386    /// Whether the system is compatible
387    pub is_compatible: bool,
388    /// Overall compatibility score (0-10)
389    pub score: f64,
390    /// Performance estimate
391    pub performance_estimate: PerformanceEstimate,
392    /// Missing requirements
393    pub missing_requirements: Vec<MissingRequirement>,
394    /// Bottlenecks identified
395    pub bottlenecks: Vec<Bottleneck>,
396    /// Recommendations
397    pub recommendations: Vec<String>,
398}
399
400impl CompatibilityResult {
401    /// Check if system is compatible
402    pub fn is_compatible(&self) -> bool {
403        self.is_compatible
404    }
405
406    /// Get compatibility score
407    pub fn score(&self) -> f64 {
408        self.score
409    }
410
411    /// Get performance estimate
412    pub fn performance_estimate(&self) -> &PerformanceEstimate {
413        &self.performance_estimate
414    }
415
416    /// Get missing requirements
417    pub fn missing_requirements(&self) -> &[MissingRequirement] {
418        &self.missing_requirements
419    }
420}
421
422/// Performance estimate for a workload
423#[derive(Debug, Clone, Serialize, Deserialize)]
424pub struct PerformanceEstimate {
425    /// Estimated latency in milliseconds
426    pub estimated_latency_ms: f64,
427    /// Estimated throughput (operations per second)
428    pub estimated_throughput: f64,
429    /// Confidence level (0-1)
430    pub confidence: f64,
431    /// Performance tier
432    pub performance_tier: PerformanceTier,
433}
434
435impl std::fmt::Display for PerformanceEstimate {
436    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
437        write!(
438            f,
439            "{} (latency: {:.2}ms, throughput: {:.2} ops/s, confidence: {:.1}%)",
440            self.performance_tier,
441            self.estimated_latency_ms,
442            self.estimated_throughput,
443            self.confidence * 100.0
444        )
445    }
446}
447
448/// Performance tier classification
449#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
450pub enum PerformanceTier {
451    /// Excellent performance
452    Excellent,
453    /// Good performance
454    Good,
455    /// Fair performance
456    Fair,
457    /// Poor performance
458    Poor,
459}
460
461impl std::fmt::Display for PerformanceTier {
462    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
463        match self {
464            PerformanceTier::Excellent => write!(f, "Excellent"),
465            PerformanceTier::Good => write!(f, "Good"),
466            PerformanceTier::Fair => write!(f, "Fair"),
467            PerformanceTier::Poor => write!(f, "Poor"),
468        }
469    }
470}
471
472/// Missing requirement information
473#[derive(Debug, Clone, Serialize, Deserialize)]
474pub struct MissingRequirement {
475    /// Resource type that's missing
476    pub resource_type: ResourceType,
477    /// Required amount/level
478    pub required: String,
479    /// Currently available amount/level
480    pub available: String,
481    /// Severity of the missing requirement
482    pub severity: RequirementSeverity,
483}
484
485impl MissingRequirement {
486    /// Get the resource type
487    pub fn resource_type(&self) -> &ResourceType {
488        &self.resource_type
489    }
490
491    /// Get the required amount
492    pub fn required(&self) -> &str {
493        &self.required
494    }
495
496    /// Get the available amount
497    pub fn available(&self) -> &str {
498        &self.available
499    }
500}
501
502/// Severity of missing requirements
503#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
504pub enum RequirementSeverity {
505    /// Critical - workload cannot run
506    Critical,
507    /// High - significant performance impact
508    High,
509    /// Medium - moderate performance impact
510    Medium,
511    /// Low - minor performance impact
512    Low,
513}
514
515/// System bottleneck information
516#[derive(Debug, Clone, Serialize, Deserialize)]
517pub struct Bottleneck {
518    /// Resource type that's bottlenecked
519    pub resource_type: ResourceType,
520    /// Bottleneck description
521    pub description: String,
522    /// Impact level
523    pub impact: BottleneckImpact,
524    /// Suggestions to resolve
525    pub suggestions: Vec<String>,
526}
527
528/// Impact level of bottlenecks
529#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
530pub enum BottleneckImpact {
531    /// Severe impact
532    Severe,
533    /// Moderate impact
534    Moderate,
535    /// Minor impact
536    Minor,
537}
538
539/// Resource utilization prediction
540#[derive(Debug, Clone, Serialize, Deserialize)]
541pub struct ResourceUtilization {
542    /// CPU utilization percentage
543    pub cpu_percent: f64,
544    /// GPU utilization percentage
545    pub gpu_percent: f64,
546    /// Memory utilization percentage
547    pub memory_percent: f64,
548    /// Storage utilization percentage
549    pub storage_percent: f64,
550    /// Network utilization percentage
551    pub network_percent: f64,
552    /// Peak utilization values
553    pub peak_utilization: HashMap<ResourceType, f64>,
554}
555
556impl ResourceUtilization {
557    /// Get CPU utilization percentage
558    pub fn cpu_percent(&self) -> f64 {
559        self.cpu_percent
560    }
561
562    /// Get GPU utilization percentage
563    pub fn gpu_percent(&self) -> f64 {
564        self.gpu_percent
565    }
566
567    /// Get memory utilization percentage
568    pub fn memory_percent(&self) -> f64 {
569        self.memory_percent
570    }
571
572    /// Get storage utilization percentage
573    pub fn storage_percent(&self) -> f64 {
574        self.storage_percent
575    }
576
577    /// Get network utilization percentage
578    pub fn network_percent(&self) -> f64 {
579        self.network_percent
580    }
581}
582
583/// Upgrade recommendation
584#[derive(Debug, Clone, Serialize, Deserialize)]
585pub struct UpgradeRecommendation {
586    /// Resource type to upgrade
587    pub resource_type: ResourceType,
588    /// Upgrade recommendation
589    pub recommendation: String,
590    /// Estimated improvement
591    pub estimated_improvement: String,
592    /// Cost estimate
593    pub cost_estimate: Option<CostEstimate>,
594    /// Priority level
595    pub priority: UpgradePriority,
596}
597
598impl UpgradeRecommendation {
599    /// Get the resource type
600    pub fn resource_type(&self) -> &ResourceType {
601        &self.resource_type
602    }
603
604    /// Get the recommendation
605    pub fn recommendation(&self) -> &str {
606        &self.recommendation
607    }
608
609    /// Get the estimated improvement
610    pub fn estimated_improvement(&self) -> &str {
611        &self.estimated_improvement
612    }
613}
614
615/// Cost estimate for upgrades
616#[derive(Debug, Clone, Serialize, Deserialize)]
617pub struct CostEstimate {
618    /// Minimum cost
619    pub min_cost: f64,
620    /// Maximum cost
621    pub max_cost: f64,
622    /// Currency
623    pub currency: String,
624    /// Time frame
625    pub time_frame: String,
626}
627
628/// Upgrade priority levels
629#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
630pub enum UpgradePriority {
631    /// Low priority upgrade
632    Low,
633    /// Medium priority upgrade
634    Medium,
635    /// High priority upgrade
636    High,
637    /// Critical priority upgrade
638    Critical,
639}
640
641/// Optimal configuration recommendation
642#[derive(Debug, Clone, Serialize, Deserialize)]
643pub struct OptimalConfiguration {
644    /// CPU recommendation
645    pub cpu_recommendation: String,
646    /// GPU recommendation
647    pub gpu_recommendation: String,
648    /// Memory recommendation
649    pub memory_recommendation: String,
650    /// Storage recommendation
651    pub storage_recommendation: String,
652    /// Network recommendation
653    pub network_recommendation: String,
654    /// Total estimated cost
655    pub total_cost: Option<CostEstimate>,
656    /// Performance projection
657    pub performance_projection: PerformanceEstimate,
658}
659
660impl OptimalConfiguration {
661    /// Get CPU recommendation
662    pub fn cpu_recommendation(&self) -> &str {
663        &self.cpu_recommendation
664    }
665
666    /// Get GPU recommendation
667    pub fn gpu_recommendation(&self) -> &str {
668        &self.gpu_recommendation
669    }
670
671    /// Get memory recommendation
672    pub fn memory_recommendation(&self) -> &str {
673        &self.memory_recommendation
674    }
675
676    /// Get storage recommendation
677    pub fn storage_recommendation(&self) -> &str {
678        &self.storage_recommendation
679    }
680
681    /// Get network recommendation
682    pub fn network_recommendation(&self) -> &str {
683        &self.network_recommendation
684    }
685}