Skip to main content

all_smi/device/
memory_linux.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 chrono::Local;
16use once_cell::sync::Lazy;
17use std::fs;
18
19use crate::device::container_info::ContainerInfo;
20use crate::device::{MemoryInfo, MemoryReader};
21use crate::utils::get_hostname;
22
23// Cache container detection result globally to avoid repeated filesystem operations
24static CONTAINER_INFO: Lazy<Option<ContainerInfo>> = Lazy::new(|| {
25    let info = ContainerInfo::detect();
26    if info.is_container { Some(info) } else { None }
27});
28
29pub struct LinuxMemoryReader {
30    // Reference to the global container info
31    container_info: &'static Option<ContainerInfo>,
32}
33
34impl Default for LinuxMemoryReader {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40impl LinuxMemoryReader {
41    pub fn new() -> Self {
42        LinuxMemoryReader {
43            container_info: &CONTAINER_INFO,
44        }
45    }
46}
47
48impl MemoryReader for LinuxMemoryReader {
49    fn get_memory_info(&self) -> Vec<MemoryInfo> {
50        let mut memory_info = Vec::new();
51
52        // Check if we're in a container and have memory limits
53        if let Some(container_info) = self.container_info
54            && let Some((total, used, utilization)) = container_info.get_memory_stats()
55        {
56            // Use container memory limits
57            let hostname = get_hostname();
58            let now = Local::now();
59
60            // For containers, we primarily care about the limit and usage
61            // Other values like buffers/cached are from /proc/meminfo but less relevant
62            memory_info.push(MemoryInfo {
63                index: 0, // Overwritten by AllSmi::get_memory_info when flattening readers
64                host_id: hostname.clone(),
65                hostname: hostname.clone(),
66                instance: hostname,
67                total_bytes: total,
68                used_bytes: used,
69                available_bytes: total.saturating_sub(used),
70                free_bytes: total.saturating_sub(used),
71                buffers_bytes: 0,    // Not easily available in container context
72                cached_bytes: 0,     // Not easily available in container context
73                swap_total_bytes: 0, // Container swap is complex
74                swap_used_bytes: 0,
75                swap_free_bytes: 0,
76                utilization,
77                time: now.format("%Y-%m-%d %H:%M:%S").to_string(),
78            });
79
80            return memory_info;
81        }
82
83        // Fall back to reading /proc/meminfo for non-container or when container info is not available
84        if let Ok(meminfo_content) = fs::read_to_string("/proc/meminfo") {
85            let mut total_bytes = 0;
86            let mut available_bytes = 0;
87            let mut free_bytes = 0;
88            let mut buffers_bytes = 0;
89            let mut cached_bytes = 0;
90            let mut swap_total_bytes = 0;
91            let mut swap_free_bytes = 0;
92
93            for line in meminfo_content.lines() {
94                let parts: Vec<&str> = line.split_whitespace().collect();
95                if parts.len() >= 2 {
96                    let key = parts[0].trim_end_matches(':');
97                    if let Ok(value) = parts[1].parse::<u64>() {
98                        let value_bytes = value * 1024; // Convert from kB to bytes
99
100                        match key {
101                            "MemTotal" => total_bytes = value_bytes,
102                            "MemAvailable" => available_bytes = value_bytes,
103                            "MemFree" => free_bytes = value_bytes,
104                            "Buffers" => buffers_bytes = value_bytes,
105                            "Cached" => cached_bytes = value_bytes,
106                            "SwapTotal" => swap_total_bytes = value_bytes,
107                            "SwapFree" => swap_free_bytes = value_bytes,
108                            _ => {}
109                        }
110                    }
111                }
112            }
113
114            // Calculate used memory
115            let used_bytes = total_bytes - available_bytes;
116            let swap_used_bytes = swap_total_bytes - swap_free_bytes;
117
118            // Calculate utilization percentage
119            let utilization = if total_bytes > 0 {
120                (used_bytes as f64 / total_bytes as f64) * 100.0
121            } else {
122                0.0
123            };
124
125            let hostname = get_hostname();
126            let now = Local::now();
127
128            memory_info.push(MemoryInfo {
129                index: 0,                  // Overwritten by AllSmi::get_memory_info when flattening readers
130                host_id: hostname.clone(), // For local mode, host_id is just the hostname
131                hostname: hostname.clone(),
132                instance: hostname,
133                total_bytes,
134                used_bytes,
135                available_bytes,
136                free_bytes,
137                buffers_bytes,
138                cached_bytes,
139                swap_total_bytes,
140                swap_used_bytes,
141                swap_free_bytes,
142                utilization,
143                time: now.format("%Y-%m-%d %H:%M:%S").to_string(),
144            });
145        }
146
147        memory_info
148    }
149}
150
151#[cfg(test)]
152#[path = "memory_linux/tests.rs"]
153mod tests;