Skip to main content

all_smi/utils/
runtime_environment.rs

1// Copyright 2025 Lablup Inc. and Jeongkyu Shin
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::common::config::AppConfig;
16use crate::utils::command::new_command;
17#[cfg(feature = "cli")]
18use crossterm::style::Color;
19use std::env;
20use std::fs;
21use std::path::Path;
22
23#[derive(Debug, Clone, PartialEq)]
24pub enum ContainerRuntime {
25    Docker,
26    Kubernetes,
27    Podman,
28    Containerd,
29    Lxc,
30    CriO,
31    BackendAI,
32    None,
33}
34
35impl ContainerRuntime {
36    pub fn as_str(&self) -> &'static str {
37        match self {
38            ContainerRuntime::Docker => "Docker",
39            ContainerRuntime::Kubernetes => "Kubernetes",
40            ContainerRuntime::Podman => "Podman",
41            ContainerRuntime::Containerd => "containerd",
42            ContainerRuntime::Lxc => "LXC/LXD",
43            ContainerRuntime::CriO => "CRI-O",
44            ContainerRuntime::BackendAI => "Backend.AI",
45            ContainerRuntime::None => "None",
46        }
47    }
48
49    #[cfg(feature = "cli")]
50    pub fn brand_color(&self) -> Color {
51        match self {
52            ContainerRuntime::Docker => Color::Rgb {
53                r: 36,
54                g: 150,
55                b: 237,
56            }, // #2496ED
57            ContainerRuntime::Kubernetes => Color::Rgb {
58                r: 50,
59                g: 108,
60                b: 229,
61            }, // #326CE5
62            ContainerRuntime::Podman => Color::Rgb {
63                r: 137,
64                g: 44,
65                b: 160,
66            }, // #892CA0
67            ContainerRuntime::BackendAI => Color::Rgb {
68                r: 0,
69                g: 212,
70                b: 170,
71            }, // #00D4AA
72            ContainerRuntime::Containerd => Color::Rgb {
73                r: 87,
74                g: 89,
75                b: 90,
76            }, // #57595A
77            ContainerRuntime::Lxc => Color::Rgb {
78                r: 255,
79                g: 102,
80                b: 0,
81            }, // #FF6600
82            ContainerRuntime::CriO => Color::Rgb {
83                r: 41,
84                g: 66,
85                b: 77,
86            }, // #29424D
87            ContainerRuntime::None => Color::DarkGrey,
88        }
89    }
90}
91
92#[derive(Debug, Clone)]
93pub struct ContainerInfo {
94    pub runtime: ContainerRuntime,
95    pub container_id: Option<String>,
96    pub pod_name: Option<String>,
97    pub namespace: Option<String>,
98}
99
100impl ContainerInfo {
101    pub fn is_containerized(&self) -> bool {
102        self.runtime != ContainerRuntime::None
103    }
104}
105
106/// Detects if the current process is running inside a container and identifies the runtime
107pub fn detect_container_environment() -> ContainerInfo {
108    // Check for Backend.AI
109    if Path::new("/opt/kernel/libbaihook.so").exists() {
110        return ContainerInfo {
111            runtime: ContainerRuntime::BackendAI,
112            container_id: env::var("BACKENDAI_KERNEL_ID")
113                .or_else(|_| env::var("BACKEND_AI_KERNEL_ID"))
114                .ok()
115                .map(|id| id.chars().take(12).collect()),
116            pod_name: None,
117            namespace: None,
118        };
119    }
120
121    // Check for Docker
122    if Path::new("/.dockerenv").exists() {
123        return ContainerInfo {
124            runtime: ContainerRuntime::Docker,
125            container_id: extract_container_id_from_cgroup("/docker/"),
126            pod_name: None,
127            namespace: None,
128        };
129    }
130
131    // Check for Podman
132    if Path::new("/run/.containerenv").exists()
133        || env::var("container").unwrap_or_default() == "podman"
134    {
135        return ContainerInfo {
136            runtime: ContainerRuntime::Podman,
137            container_id: extract_container_id_from_cgroup("/machine.slice/"),
138            pod_name: None,
139            namespace: None,
140        };
141    }
142
143    // Check for Kubernetes
144    if env::var("KUBERNETES_SERVICE_HOST").is_ok()
145        || Path::new("/var/run/secrets/kubernetes.io").exists()
146    {
147        let pod_name = env::var("HOSTNAME").ok();
148        let namespace = read_k8s_namespace();
149
150        return ContainerInfo {
151            runtime: ContainerRuntime::Kubernetes,
152            container_id: extract_container_id_from_cgroup("/kubepods/"),
153            pod_name,
154            namespace,
155        };
156    }
157
158    // Check cgroup for other container runtimes
159    if let Ok(cgroup_content) = fs::read_to_string("/proc/self/cgroup") {
160        if cgroup_content.contains("/docker/") {
161            return ContainerInfo {
162                runtime: ContainerRuntime::Docker,
163                container_id: extract_container_id_from_cgroup("/docker/"),
164                pod_name: None,
165                namespace: None,
166            };
167        } else if cgroup_content.contains("/kubepods/") {
168            let pod_name = env::var("HOSTNAME").ok();
169            let namespace = read_k8s_namespace();
170
171            return ContainerInfo {
172                runtime: ContainerRuntime::Kubernetes,
173                container_id: extract_container_id_from_cgroup("/kubepods/"),
174                pod_name,
175                namespace,
176            };
177        } else if cgroup_content.contains("/containerd/") {
178            return ContainerInfo {
179                runtime: ContainerRuntime::Containerd,
180                container_id: extract_container_id_from_cgroup("/containerd/"),
181                pod_name: None,
182                namespace: None,
183            };
184        } else if cgroup_content.contains("/lxc/") {
185            return ContainerInfo {
186                runtime: ContainerRuntime::Lxc,
187                container_id: extract_container_id_from_cgroup("/lxc/"),
188                pod_name: None,
189                namespace: None,
190            };
191        } else if cgroup_content.contains("/crio-") {
192            return ContainerInfo {
193                runtime: ContainerRuntime::CriO,
194                container_id: extract_container_id_from_cgroup("/crio-"),
195                pod_name: None,
196                namespace: None,
197            };
198        }
199    }
200
201    // Check for LXC environment variable
202    if let Ok(environ) = fs::read_to_string("/proc/1/environ")
203        && environ.contains("container=lxc")
204    {
205        return ContainerInfo {
206            runtime: ContainerRuntime::Lxc,
207            container_id: None,
208            pod_name: None,
209            namespace: None,
210        };
211    }
212
213    // Not in a container
214    ContainerInfo {
215        runtime: ContainerRuntime::None,
216        container_id: None,
217        pod_name: None,
218        namespace: None,
219    }
220}
221
222/// Extract container ID from cgroup file
223fn extract_container_id_from_cgroup(pattern: &str) -> Option<String> {
224    if let Ok(cgroup_content) = fs::read_to_string("/proc/self/cgroup") {
225        for line in cgroup_content.lines() {
226            if let Some(pos) = line.find(pattern) {
227                let id_start = pos + pattern.len();
228                let remaining = &line[id_start..];
229
230                // Extract the container ID (usually the next path component)
231                let id = remaining
232                    .split('/')
233                    .next()
234                    .unwrap_or("")
235                    .split('.')
236                    .next()
237                    .unwrap_or("");
238
239                if !id.is_empty() && id.len() >= 12 {
240                    // Return first 12 characters of container ID
241                    return Some(id.chars().take(12).collect());
242                }
243            }
244        }
245    }
246    None
247}
248
249/// Read Kubernetes namespace from mounted secret
250fn read_k8s_namespace() -> Option<String> {
251    fs::read_to_string("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
252        .ok()
253        .map(|s| s.trim().to_string())
254}
255
256#[derive(Debug, Clone, PartialEq)]
257#[allow(dead_code)]
258pub enum VirtualizationType {
259    VMware,
260    VirtualBox,
261    Kvm,
262    Qemu,
263    HyperV,
264    Xen,
265    Aws,
266    Gcp,
267    Azure,
268    DigitalOcean,
269    Oracle,
270    Parallels,
271    None,
272}
273
274impl VirtualizationType {
275    pub fn as_str(&self) -> &'static str {
276        match self {
277            VirtualizationType::VMware => "VMware",
278            VirtualizationType::VirtualBox => "VirtualBox",
279            VirtualizationType::Kvm => "KVM",
280            VirtualizationType::Qemu => "QEMU",
281            VirtualizationType::HyperV => "Hyper-V",
282            VirtualizationType::Xen => "Xen",
283            VirtualizationType::Aws => "AWS EC2",
284            VirtualizationType::Gcp => "Google Cloud",
285            VirtualizationType::Azure => "Microsoft Azure",
286            VirtualizationType::DigitalOcean => "DigitalOcean",
287            VirtualizationType::Oracle => "Oracle Cloud",
288            VirtualizationType::Parallels => "Parallels",
289            VirtualizationType::None => "None",
290        }
291    }
292
293    #[cfg(feature = "cli")]
294    pub fn brand_color(&self) -> Color {
295        match self {
296            VirtualizationType::VMware => Color::Rgb {
297                r: 113,
298                g: 112,
299                b: 116,
300            }, // #717074
301            VirtualizationType::VirtualBox => Color::Rgb {
302                r: 24,
303                g: 58,
304                b: 92,
305            }, // #183A5C
306            VirtualizationType::Kvm => Color::Rgb {
307                r: 255,
308                g: 68,
309                b: 68,
310            }, // #FF4444 (Red Hat)
311            VirtualizationType::Qemu => Color::Rgb {
312                r: 255,
313                g: 106,
314                b: 0,
315            }, // #FF6A00
316            VirtualizationType::HyperV => Color::Rgb {
317                r: 0,
318                g: 188,
319                b: 242,
320            }, // #00BCF2
321            VirtualizationType::Xen => Color::Rgb {
322                r: 255,
323                g: 143,
324                b: 0,
325            }, // #FF8F00
326            VirtualizationType::Aws => Color::Rgb {
327                r: 255,
328                g: 153,
329                b: 0,
330            }, // #FF9900
331            VirtualizationType::Gcp => Color::Rgb {
332                r: 66,
333                g: 133,
334                b: 244,
335            }, // #4285F4
336            VirtualizationType::Azure => Color::Rgb {
337                r: 0,
338                g: 120,
339                b: 212,
340            }, // #0078D4
341            VirtualizationType::DigitalOcean => Color::Rgb {
342                r: 0,
343                g: 105,
344                b: 255,
345            }, // #0069FF
346            VirtualizationType::Oracle => Color::Rgb { r: 248, g: 0, b: 0 }, // #F80000
347            VirtualizationType::Parallels => Color::Rgb {
348                r: 223,
349                g: 0,
350                b: 56,
351            }, // #DF0038
352            VirtualizationType::None => Color::DarkGrey,
353        }
354    }
355}
356
357#[derive(Debug, Clone)]
358pub struct VirtualizationInfo {
359    pub vm_type: VirtualizationType,
360    pub hypervisor: Option<String>,
361    pub is_virtual: bool,
362}
363
364/// Detects if the current process is running inside a virtual machine
365pub fn detect_virtualization() -> VirtualizationInfo {
366    // Try systemd-detect-virt first (most reliable if available)
367    if let Ok(output) = new_command("systemd-detect-virt").output()
368        && output.status.success()
369    {
370        let virt_type = String::from_utf8_lossy(&output.stdout).trim().to_string();
371        match virt_type.as_str() {
372            "kvm" => {
373                return VirtualizationInfo {
374                    vm_type: VirtualizationType::Kvm,
375                    hypervisor: Some("KVM".to_string()),
376                    is_virtual: true,
377                };
378            }
379            "vmware" => {
380                return VirtualizationInfo {
381                    vm_type: VirtualizationType::VMware,
382                    hypervisor: Some("VMware".to_string()),
383                    is_virtual: true,
384                };
385            }
386            "oracle" | "virtualbox" => {
387                return VirtualizationInfo {
388                    vm_type: VirtualizationType::VirtualBox,
389                    hypervisor: Some("VirtualBox".to_string()),
390                    is_virtual: true,
391                };
392            }
393            "microsoft" | "hyperv" => {
394                return VirtualizationInfo {
395                    vm_type: VirtualizationType::HyperV,
396                    hypervisor: Some("Hyper-V".to_string()),
397                    is_virtual: true,
398                };
399            }
400            "xen" => {
401                return VirtualizationInfo {
402                    vm_type: VirtualizationType::Xen,
403                    hypervisor: Some("Xen".to_string()),
404                    is_virtual: true,
405                };
406            }
407            "qemu" => {
408                return VirtualizationInfo {
409                    vm_type: VirtualizationType::Qemu,
410                    hypervisor: Some("QEMU".to_string()),
411                    is_virtual: true,
412                };
413            }
414            "parallels" => {
415                return VirtualizationInfo {
416                    vm_type: VirtualizationType::Parallels,
417                    hypervisor: Some("Parallels".to_string()),
418                    is_virtual: true,
419                };
420            }
421            "none" => {
422                // Continue with other detection methods
423            }
424            _ if !virt_type.is_empty() => {
425                // Unknown virtualization detected
426                return VirtualizationInfo {
427                    vm_type: VirtualizationType::None,
428                    hypervisor: Some(virt_type),
429                    is_virtual: true,
430                };
431            }
432            _ => {}
433        }
434    }
435
436    // Check DMI/SMBIOS information
437    if let Ok(vendor) = fs::read_to_string("/sys/class/dmi/id/sys_vendor") {
438        let vendor = vendor.trim().to_lowercase();
439        if vendor.contains("vmware") {
440            return VirtualizationInfo {
441                vm_type: VirtualizationType::VMware,
442                hypervisor: Some("VMware".to_string()),
443                is_virtual: true,
444            };
445        } else if vendor.contains("innotek") || vendor.contains("virtualbox") {
446            return VirtualizationInfo {
447                vm_type: VirtualizationType::VirtualBox,
448                hypervisor: Some("VirtualBox".to_string()),
449                is_virtual: true,
450            };
451        } else if vendor.contains("microsoft") {
452            return VirtualizationInfo {
453                vm_type: VirtualizationType::HyperV,
454                hypervisor: Some("Hyper-V".to_string()),
455                is_virtual: true,
456            };
457        } else if vendor.contains("xen") {
458            return VirtualizationInfo {
459                vm_type: VirtualizationType::Xen,
460                hypervisor: Some("Xen".to_string()),
461                is_virtual: true,
462            };
463        } else if vendor.contains("qemu") {
464            return VirtualizationInfo {
465                vm_type: VirtualizationType::Qemu,
466                hypervisor: Some("QEMU".to_string()),
467                is_virtual: true,
468            };
469        } else if vendor.contains("parallels") {
470            return VirtualizationInfo {
471                vm_type: VirtualizationType::Parallels,
472                hypervisor: Some("Parallels".to_string()),
473                is_virtual: true,
474            };
475        }
476    }
477
478    // Check product name
479    if let Ok(product) = fs::read_to_string("/sys/class/dmi/id/product_name") {
480        let product = product.trim().to_lowercase();
481        if product.contains("vmware") {
482            return VirtualizationInfo {
483                vm_type: VirtualizationType::VMware,
484                hypervisor: Some("VMware".to_string()),
485                is_virtual: true,
486            };
487        } else if product.contains("virtualbox") {
488            return VirtualizationInfo {
489                vm_type: VirtualizationType::VirtualBox,
490                hypervisor: Some("VirtualBox".to_string()),
491                is_virtual: true,
492            };
493        } else if product.contains("virtual machine") {
494            return VirtualizationInfo {
495                vm_type: VirtualizationType::HyperV,
496                hypervisor: Some("Hyper-V".to_string()),
497                is_virtual: true,
498            };
499        }
500    }
501
502    // Check for cloud providers
503    if Path::new("/sys/hypervisor/uuid").exists()
504        || env::var("AWS_EXECUTION_ENV").is_ok()
505        || check_aws_metadata()
506    {
507        return VirtualizationInfo {
508            vm_type: VirtualizationType::Aws,
509            hypervisor: Some("AWS EC2".to_string()),
510            is_virtual: true,
511        };
512    }
513
514    // Check for GCP
515    if let Ok(bios_vendor) = fs::read_to_string("/sys/class/dmi/id/bios_vendor")
516        && bios_vendor.trim().to_lowercase().contains("google")
517    {
518        return VirtualizationInfo {
519            vm_type: VirtualizationType::Gcp,
520            hypervisor: Some("Google Cloud".to_string()),
521            is_virtual: true,
522        };
523    }
524
525    // Check for Azure
526    if let Ok(chassis_asset_tag) = fs::read_to_string("/sys/class/dmi/id/chassis_asset_tag")
527        && chassis_asset_tag.trim() == "7783-7084-3265-9085-8269-3286-77"
528    {
529        return VirtualizationInfo {
530            vm_type: VirtualizationType::Azure,
531            hypervisor: Some("Microsoft Azure".to_string()),
532            is_virtual: true,
533        };
534    }
535
536    // Check for DigitalOcean
537    if let Ok(vendor) = fs::read_to_string("/sys/class/dmi/id/sys_vendor")
538        && vendor.trim().to_lowercase().contains("digitalocean")
539    {
540        return VirtualizationInfo {
541            vm_type: VirtualizationType::DigitalOcean,
542            hypervisor: Some("DigitalOcean".to_string()),
543            is_virtual: true,
544        };
545    }
546
547    // Check CPU flags for hypervisor
548    if let Ok(cpuinfo) = fs::read_to_string("/proc/cpuinfo")
549        && cpuinfo.contains("hypervisor")
550    {
551        return VirtualizationInfo {
552            vm_type: VirtualizationType::None,
553            hypervisor: Some("Unknown".to_string()),
554            is_virtual: true,
555        };
556    }
557
558    // Check for specific kernel modules
559    if let Ok(modules) = fs::read_to_string("/proc/modules") {
560        if modules.contains("vboxguest") || modules.contains("vboxsf") {
561            return VirtualizationInfo {
562                vm_type: VirtualizationType::VirtualBox,
563                hypervisor: Some("VirtualBox".to_string()),
564                is_virtual: true,
565            };
566        } else if modules.contains("vmw_balloon") || modules.contains("vmwgfx") {
567            return VirtualizationInfo {
568                vm_type: VirtualizationType::VMware,
569                hypervisor: Some("VMware".to_string()),
570                is_virtual: true,
571            };
572        } else if modules.contains("hv_vmbus") || modules.contains("hv_storvsc") {
573            return VirtualizationInfo {
574                vm_type: VirtualizationType::HyperV,
575                hypervisor: Some("Hyper-V".to_string()),
576                is_virtual: true,
577            };
578        } else if modules.contains("virtio") {
579            return VirtualizationInfo {
580                vm_type: VirtualizationType::Kvm,
581                hypervisor: Some("KVM/QEMU".to_string()),
582                is_virtual: true,
583            };
584        }
585    }
586
587    // Not in a VM
588    VirtualizationInfo {
589        vm_type: VirtualizationType::None,
590        hypervisor: None,
591        is_virtual: false,
592    }
593}
594
595/// Check if AWS metadata service is accessible
596fn check_aws_metadata() -> bool {
597    // Make the AWS metadata check optional via environment variable
598    if let Ok(val) = env::var("AWS_METADATA_CHECK_ENABLED")
599        && (val == "0" || val.to_lowercase() == "false")
600    {
601        return false;
602    }
603
604    // Try to access AWS metadata service with very short timeout
605    match new_command("curl")
606        .args([
607            "-s",
608            "--max-time",
609            "1",
610            "--connect-timeout",
611            "1",
612            "http://169.254.169.254/latest/meta-data/instance-id",
613        ])
614        .output()
615    {
616        Ok(output) => output.status.success() && !output.stdout.is_empty(),
617        _ => false,
618    }
619}
620
621#[derive(Debug, Clone)]
622pub struct RuntimeEnvironment {
623    pub container: ContainerInfo,
624    pub virtualization: VirtualizationInfo,
625}
626
627impl Default for RuntimeEnvironment {
628    fn default() -> Self {
629        Self {
630            container: ContainerInfo {
631                runtime: ContainerRuntime::None,
632                container_id: None,
633                pod_name: None,
634                namespace: None,
635            },
636            virtualization: VirtualizationInfo {
637                vm_type: VirtualizationType::None,
638                hypervisor: None,
639                is_virtual: false,
640            },
641        }
642    }
643}
644
645impl RuntimeEnvironment {
646    /// Detect both container and virtualization environments
647    pub fn detect() -> Self {
648        Self {
649            container: detect_container_environment(),
650            virtualization: detect_virtualization(),
651        }
652    }
653
654    /// Get the display name and color for the runtime environment
655    /// Prioritizes container environment over VM if both are detected
656    #[cfg(feature = "cli")]
657    pub fn display_info(&self) -> Option<(&str, Color)> {
658        if self.container.is_containerized() {
659            match self.container.runtime {
660                ContainerRuntime::None => None,
661                _ => Some((
662                    self.container.runtime.as_str(),
663                    self.container.runtime.brand_color(),
664                )),
665            }
666        } else if self.virtualization.is_virtual {
667            match self.virtualization.vm_type {
668                VirtualizationType::None => None,
669                _ => Some((
670                    self.virtualization.vm_type.as_str(),
671                    self.virtualization.vm_type.brand_color(),
672                )),
673            }
674        } else {
675            None
676        }
677    }
678
679    /// Check if running in Backend.AI environment
680    pub fn is_backend_ai(&self) -> bool {
681        self.container.runtime == ContainerRuntime::BackendAI
682    }
683
684    /// Get Backend.AI cluster hosts from environment variable
685    /// Returns a list of host URLs constructed from BACKENDAI_CLUSTER_HOSTS
686    pub fn get_backend_ai_hosts(&self) -> Option<Vec<String>> {
687        if !self.is_backend_ai() {
688            return None;
689        }
690
691        // Try to get hosts from environment variable
692        if let Ok(hosts_str) = env::var("BACKENDAI_CLUSTER_HOSTS") {
693            let hosts: Vec<String> = hosts_str
694                .split(',')
695                .map(|host| {
696                    let host = host.trim();
697                    // If host doesn't have a scheme, prepend http://
698                    if !host.starts_with("http://") && !host.starts_with("https://") {
699                        format!("http://{host}:{}", AppConfig::BACKEND_AI_DEFAULT_PORT)
700                    } else {
701                        host.to_string()
702                    }
703                })
704                .filter(|host| !host.is_empty())
705                .collect();
706
707            if !hosts.is_empty() {
708                return Some(hosts);
709            }
710        }
711
712        None
713    }
714}
715
716#[cfg(test)]
717mod tests {
718    use super::*;
719
720    #[test]
721    fn test_container_runtime_as_str() {
722        assert_eq!(ContainerRuntime::Docker.as_str(), "Docker");
723        assert_eq!(ContainerRuntime::Kubernetes.as_str(), "Kubernetes");
724        assert_eq!(ContainerRuntime::Podman.as_str(), "Podman");
725        assert_eq!(ContainerRuntime::None.as_str(), "None");
726    }
727
728    #[test]
729    fn test_container_info_is_containerized() {
730        let info = ContainerInfo {
731            runtime: ContainerRuntime::Docker,
732            container_id: Some("abc123".to_string()),
733            pod_name: None,
734            namespace: None,
735        };
736        assert!(info.is_containerized());
737
738        let info = ContainerInfo {
739            runtime: ContainerRuntime::None,
740            container_id: None,
741            pod_name: None,
742            namespace: None,
743        };
744        assert!(!info.is_containerized());
745    }
746}