-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
1647 lines (1472 loc) · 57.1 KB
/
lib.rs
File metadata and controls
1647 lines (1472 loc) · 57.1 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
/*
Copyright 2024 San Francisco Compute Company
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This Rust program collects various hardware and network information from the local server
and serializes it into a TOML configuration file.
It gathers information such as:
- Hostname
- IP addresses of network interfaces
- BMC (Baseboard Management Controller) IP and MAC addresses
- CPU, memory, storage, and GPU details
- Network interface details, including Infiniband if present
The collected data is written to `server_config.toml`.
*/
use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::process::Command;
pub mod posting;
pub mod netbox;
lazy_static! {
static ref STORAGE_SIZE_RE: Regex = Regex::new(r"(\d+(?:\.\d+)?)(B|K|M|G|T)").unwrap();
static ref NETWORK_SPEED_RE: Regex = Regex::new(r"Speed:\s+(\S+)").unwrap();
}
/// CPU topology information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuTopology {
pub total_cores: u32,
pub total_threads: u32,
pub sockets: u32,
pub cores_per_socket: u32,
pub threads_per_core: u32,
pub numa_nodes: u32,
pub cpu_model: String,
}
/// Motherboard information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MotherboardInfo {
pub manufacturer: String,
pub product_name: String,
pub version: String,
pub serial: String,
pub features: String,
pub location: String,
pub type_: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfo {
pub uuid: String,
pub serial: String,
pub product_name: String,
pub product_manufacturer: String,
}
/// Summary of key system components
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemSummary {
/// System information
pub system_info: SystemInfo,
/// Total system memory capacity
pub total_memory: String,
/// Memory speed and type
pub memory_config: String,
/// Total storage capacity
pub total_storage: String,
/// Total storage capacity in TB
pub total_storage_tb: f64,
/// Available filesystems
pub filesystems: Vec<String>,
/// BIOS information
pub bios: BiosInfo,
/// System chassis information
pub chassis: ChassisInfo,
/// Motherboard information
pub motherboard: MotherboardInfo,
/// Total number of GPUs
pub total_gpus: usize,
/// Total number of network interfaces
pub total_nics: usize,
/// NUMA topology information
pub numa_topology: HashMap<String, NumaNode>,
/// CPU topology information
pub cpu_topology: CpuTopology,
/// CPU configuration summary
pub cpu_summary: String,
}
/// BIOS information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BiosInfo {
pub vendor: String,
pub version: String,
pub release_date: String,
pub firmware_version: String,
}
/// Chassis information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChassisInfo {
pub manufacturer: String,
pub type_: String,
pub serial: String,
}
/// Represents the overall server information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerInfo {
/// System summary
pub summary: SystemSummary,
/// Other fields remain the same
pub hostname: String,
pub fqdn: String,
pub os_ip: Vec<InterfaceIPs>,
pub bmc_ip: Option<String>,
pub bmc_mac: Option<String>,
pub hardware: HardwareInfo,
pub network: NetworkInfo,
}
/// Contains detailed hardware information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareInfo {
/// CPU information.
pub cpu: CpuInfo,
/// Memory information.
pub memory: MemoryInfo,
/// Storage information.
pub storage: StorageInfo,
/// GPU information.
pub gpus: GpuInfo,
}
/// Represents CPU information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuInfo {
/// CPU model name.
pub model: String,
/// Number of cores per socket.
pub cores: u32,
/// Number of threads per core.
pub threads: u32,
/// Number of sockets.
pub sockets: u32,
/// CPU speed in MHz.
pub speed: String,
}
/// Represents memory information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryInfo {
/// Total memory size.
pub total: String,
/// Memory type (e.g., DDR4).
pub type_: String,
/// Memory speed.
pub speed: String,
/// Individual memory modules.
pub modules: Vec<MemoryModule>,
}
/// Represents a memory module.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryModule {
/// Size of the memory module.
pub size: String,
/// Type of the memory module.
pub type_: String,
/// Speed of the memory module.
pub speed: String,
/// Physical location of the memory module.
pub location: String,
/// Manufacturer of the memory module.
pub manufacturer: String,
/// Serial number of the memory module.
pub serial: String,
}
/// Represents storage information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageInfo {
/// List of storage devices.
pub devices: Vec<StorageDevice>,
}
/// Represents a storage device.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageDevice {
/// Device name.
pub name: String,
/// Device type (e.g., disk).
pub type_: String,
/// Device size.
pub size: String,
/// Device model.
pub model: String,
}
/// Represents GPU information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuInfo {
/// List of GPU devices.
pub devices: Vec<GpuDevice>,
}
/// Represents a GPU device.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuDevice {
/// GPU index
pub index: u32,
/// GPU name
pub name: String,
/// GPU UUID
pub uuid: String,
/// Total GPU memory
pub memory: String,
/// PCI ID (vendor:device)
pub pci_id: String,
/// Vendor name
pub vendor: String,
/// NUMA node
pub numa_node: Option<i32>,
}
/// Represents a NUMA node
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NumaNode {
/// Node ID
pub id: i32,
/// CPU list
pub cpus: Vec<u32>,
/// Memory size
pub memory: String,
/// Devices attached to this node
pub devices: Vec<NumaDevice>,
/// distances to other nodse (node_id _> distance)
pub distances: HashMap<String, u32>,
}
/// Represents a device attached to a NUMA node
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NumaDevice {
/// Device type (GPU, NIC, etc.)
pub type_: String,
/// PCI ID
pub pci_id: String,
/// Device name
pub name: String,
}
/// Represents network information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkInfo {
/// List of network interfaces.
pub interfaces: Vec<NetworkInterface>,
/// Infiniband information, if available.
pub infiniband: Option<InfinibandInfo>,
}
/// Represents a network interface.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkInterface {
/// Interface name.
pub name: String,
/// MAC address.
pub mac: String,
/// IP address.
pub ip: String,
/// Interface speed.
pub speed: Option<String>,
/// Interface type.
pub type_: String,
pub vendor: String,
pub model: String,
pub pci_id: String,
pub numa_node: Option<i32>,
}
/// Represents Infiniband information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InfinibandInfo {
/// List of Infiniband interfaces.
pub interfaces: Vec<IbInterface>,
}
/// Represents an Infiniband interface.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IbInterface {
/// Interface name.
pub name: String,
/// Port number.
pub port: u32,
/// Interface state.
pub state: String,
/// Interface rate.
pub rate: String,
}
#[allow(dead_code)]
pub struct NumaInfo {
pub nodes: Vec<NumaNode>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InterfaceIPs {
pub interface: String,
pub ip_addresses: Vec<String>,
}
#[allow(unused_variables)]
#[allow(unused_assignments)]
#[allow(clippy::useless_format)]
#[allow(clippy::manual_map)]
#[allow(clippy::format_in_format_args)]
#[allow(clippy::needless_borrows_for_generic_args)]
impl ServerInfo {
/// Checks for required system dependencies and returns any missing ones
fn check_dependencies() -> Result<Vec<&'static str>, Box<dyn Error>> {
let required_packages = vec![
("numactl", "NUMA topology information"),
("lspci", "PCI device information"),
("ethtool", "Network interface information"),
("dmidecode", "System hardware information"),
("lscpu", "CPU information"),
("ip", "Network interface details"),
("lsblk", "Storage device information"),
("hostname", "System hostname"),
("free", "Memory usage information"),
("df", "Filesystem information"),
];
let mut missing_packages = Vec::new();
let mut missing_info = Vec::new();
// Check which packages are missing
for (package, purpose) in &required_packages {
let status = Command::new("which").arg(package).output()?;
if !status.status.success() {
missing_packages.push(*package);
missing_info.push(format!(" - {}: {}", package, purpose));
}
}
if !missing_packages.is_empty() {
eprintln!("\nWarning: Some system utilities are not installed.");
eprintln!("Missing utilities:");
for info in &missing_info {
eprintln!("{}", info);
}
eprintln!("\nSome hardware information may be incomplete or unavailable.");
// Separate packages that are typically pre-installed vs specialized tools
let core_utils = ["hostname", "ip", "lscpu", "free", "df", "lsblk"];
let specialized_tools = ["numactl", "lspci", "ethtool", "dmidecode"];
let missing_core: Vec<&str> = missing_packages
.iter()
.filter(|&&pkg| core_utils.contains(&pkg))
.copied()
.collect();
let missing_specialized: Vec<&str> = missing_packages
.iter()
.filter(|&&pkg| specialized_tools.contains(&pkg))
.copied()
.collect();
if !missing_core.is_empty() {
eprintln!("\nCore utilities missing (usually pre-installed):");
eprintln!(
" Ubuntu/Debian: sudo apt install {}",
missing_core
.iter()
.map(|&pkg| match pkg {
"ip" => "iproute2",
"lscpu" | "lsblk" => "util-linux",
"free" | "hostname" => "procps",
"df" => "coreutils",
_ => pkg,
})
.collect::<Vec<_>>()
.join(" ")
);
eprintln!(
" RHEL/Fedora: sudo dnf install {}",
missing_core
.iter()
.map(|&pkg| match pkg {
"ip" => "iproute",
"lscpu" | "lsblk" => "util-linux",
"free" => "procps-ng",
"hostname" | "df" => "coreutils",
_ => pkg,
})
.collect::<Vec<_>>()
.join(" ")
);
}
if !missing_specialized.is_empty() {
eprintln!("\nSpecialized tools missing:");
eprintln!(
" Ubuntu/Debian: sudo apt install {}",
missing_specialized.join(" ")
);
eprintln!(
" RHEL/Fedora: sudo dnf install {}",
missing_specialized.join(" ")
);
}
eprintln!();
}
Ok(missing_packages)
}
/// Gets motherboard information using dmidecode
fn get_motherboard_info() -> Result<MotherboardInfo, Box<dyn Error>> {
let output = match Command::new("dmidecode").args(&["-t", "2"]).output() {
Ok(out) => {
if !out.status.success() {
Command::new("sudo")
.args(&["dmidecode", "-t", "2"])
.output()?
} else {
out
}
}
Err(_) => Command::new("sudo")
.args(&["dmidecode", "-t", "2"])
.output()?,
};
let stdout = String::from_utf8_lossy(&output.stdout);
if !output.status.success() || stdout.trim().is_empty() {
return Ok(MotherboardInfo {
manufacturer: "Unknown Manufacturer".to_string(),
product_name: "Unknown Product".to_string(),
version: "Unknown Version".to_string(),
serial: "Unknown S/N".to_string(),
features: "Unknown".to_string(),
location: "Unknown".to_string(),
type_: "Unknown".to_string(),
});
}
Ok(MotherboardInfo {
manufacturer: Self::extract_dmidecode_value(&stdout, "Manufacturer")
.unwrap_or_else(|_| "Unknown Manufacturer".to_string()),
product_name: Self::extract_dmidecode_value(&stdout, "Product Name")
.unwrap_or_else(|_| "Unknown Product".to_string()),
version: Self::extract_dmidecode_value(&stdout, "Version")
.unwrap_or_else(|_| "Unknown Version".to_string()),
serial: Self::extract_dmidecode_value(&stdout, "Serial Number")
.unwrap_or_else(|_| "Unknown S/N".to_string()),
features: Self::extract_dmidecode_value(&stdout, "Features")
.unwrap_or_else(|_| "Unknown".to_string()),
location: Self::extract_dmidecode_value(&stdout, "Location In Chassis")
.unwrap_or_else(|_| "Unknown".to_string()),
type_: Self::extract_dmidecode_value(&stdout, "Type")
.unwrap_or_else(|_| "Unknown".to_string()),
})
}
/// Converts storage size string to bytes
fn parse_storage_size(size: &str) -> Result<u64, Box<dyn Error>> {
let size_str = size.replace(" ", "");
let re = Regex::new(r"(\d+(?:\.\d+)?)(B|K|M|G|T)")?;
if let Some(caps) = re.captures(&size_str) {
let value: f64 = caps[1].parse()?;
let unit = &caps[2];
let multiplier = match unit {
"B" => 1_u64,
"K" => 1024_u64,
"M" => 1024_u64 * 1024,
"G" => 1024_u64 * 1024 * 1024,
"T" => 1024_u64 * 1024 * 1024 * 1024,
_ => 0_u64,
};
Ok((value * multiplier as f64) as u64)
} else {
Err("Invalid storage size format".into())
}
}
/// Automatically installs numactl if not present
fn auto_install_numactl() -> Result<bool, Box<dyn Error>> {
// Check if we have sudo/root privileges
let euid = unsafe { libc::geteuid() };
let use_sudo = euid != 0;
// Detect the package manager
let pkg_managers = vec![
("apt-get", vec!["update"], vec!["install", "-y", "numactl"]),
("apt", vec!["update"], vec!["install", "-y", "numactl"]),
("dnf", vec![], vec!["install", "-y", "numactl"]),
("yum", vec![], vec!["install", "-y", "numactl"]),
("zypper", vec!["refresh"], vec!["install", "-y", "numactl"]),
];
for (manager, update_args, install_args) in pkg_managers {
// Check if the package manager exists
if Command::new("which")
.arg(manager)
.output()?
.status
.success()
{
// Run update command if needed
if !update_args.is_empty() {
let mut update_cmd = if use_sudo {
let mut cmd = Command::new("sudo");
cmd.arg(manager);
cmd
} else {
Command::new(manager)
};
update_cmd.args(&update_args);
let _ = update_cmd.output(); // Ignore update errors
}
// Run install command
let mut install_cmd = if use_sudo {
let mut cmd = Command::new("sudo");
cmd.arg(manager);
cmd
} else {
Command::new(manager)
};
install_cmd.args(&install_args);
let output = install_cmd.output()?;
if output.status.success() {
// Verify numactl was installed
if Command::new("which")
.arg("numactl")
.output()?
.status
.success()
{
return Ok(true);
}
}
}
}
Ok(false)
}
// Remove automatic package installation
#[allow(dead_code)]
fn suggest_package_installation(missing_packages: &[&str]) {
if !missing_packages.is_empty() {
eprintln!(
"\nTo get complete hardware information, please install the missing utilities:"
);
eprintln!("\nFor Ubuntu/Debian:");
eprintln!(" sudo apt install {}", missing_packages.join(" "));
eprintln!("\nFor RHEL/Fedora:");
eprintln!(" sudo dnf install {}", missing_packages.join(" "));
}
}
/// Gets hostname of the server
fn get_hostname() -> Result<String, Box<dyn Error>> {
match Command::new("hostname").output() {
Ok(output) => Ok(String::from_utf8(output.stdout)?.trim().to_string()),
Err(_) => {
// Fallback to reading /etc/hostname or use system name
if let Ok(contents) = std::fs::read_to_string("/etc/hostname") {
Ok(contents.trim().to_string())
} else {
Ok("unknown".to_string())
}
}
}
}
fn get_fqdn() -> Result<String, Box<dyn Error>> {
match Command::new("hostname").args(&["-f"]).output() {
Ok(output) => Ok(String::from_utf8(output.stdout)?.trim().to_string()),
Err(_) => {
// Fallback to hostname if FQDN lookup fails
Self::get_hostname()
}
}
}
/// Gets PCI information for a device
fn get_pci_info(pci_addr: &str) -> Result<(String, String, String), Box<dyn Error>> {
// Run lspci with verbose output and machine-readable format
let output = match Command::new("lspci")
.args(&["-vmm", "-s", pci_addr])
.output()
{
Ok(output) => output,
Err(_) => {
// lspci not available, return unknown values
return Ok((
"Unknown".to_string(),
"Unknown".to_string(),
"Unknown".to_string(),
));
}
};
let output_str = String::from_utf8(output.stdout)?;
let mut vendor = String::new();
let mut device = String::new();
let mut vendor_id = String::new();
let mut device_id = String::new();
for line in output_str.lines() {
let parts: Vec<&str> = line.split(':').collect();
if parts.len() >= 2 {
let value = parts[1].trim();
match parts[0].trim() {
"Vendor" => vendor = value.to_string(),
"Device" => device = value.to_string(),
"SVendor" => {
if vendor.is_empty() {
vendor = value.to_string()
}
}
"SDevice" => {
if device.is_empty() {
device = value.to_string()
}
}
_ => {}
}
}
}
// Get vendor and device IDs using -n flag
let id_output = match Command::new("lspci").args(&["-n", "-s", pci_addr]).output() {
Ok(output) => output,
Err(_) => {
// Return early if lspci is not available
return Ok((vendor, device, "Unknown".to_string()));
}
};
let id_str = String::from_utf8(id_output.stdout)?;
if let Some(line) = id_str.lines().next() {
if let Some(ids) = line.split_whitespace().nth(2) {
let parts: Vec<&str> = ids.split(':').collect();
if parts.len() >= 2 {
vendor_id = parts[0].to_string();
device_id = parts[1].to_string();
}
}
}
let pci_id = format!("{}:{}", vendor_id, device_id);
Ok((vendor, device, pci_id))
}
/// Gets NUMA node for a PCI device
fn get_numa_node(pci_addr: &str) -> Option<i32> {
if let Ok(path) = std::fs::read_link(format!("/sys/bus/pci/devices/{}/numa_node", pci_addr))
{
if let Ok(content) = std::fs::read_to_string(path) {
if let Ok(node) = content.trim().parse() {
return Some(node);
}
}
}
None
}
fn collect_numa_topology() -> Result<HashMap<String, NumaNode>, Box<dyn Error>> {
let mut nodes = HashMap::new();
let mut collecting_distances = false;
// Get NUMA information using numactl
let output = Command::new("numactl").args(&["--hardware"]).output()?;
let output_str = String::from_utf8(output.stdout)?;
for line in output_str.lines() {
if line.starts_with("node ") && line.contains("size:") {
// Parse node and memory information
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 4 {
if let Ok(id) = parts[1].parse::<i32>() {
let memory = format!("{} {}", parts[3], parts[4]);
// Create new node entry
nodes.insert(
id.to_string(),
NumaNode {
id,
memory,
cpus: Vec::new(),
distances: HashMap::new(),
devices: Vec::new(),
},
);
}
}
} else if line.contains("node distances:") {
collecting_distances = true;
continue;
} else if collecting_distances && line.trim().starts_with("node") {
// Parse distance information
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() > 2 {
if let Ok(from_node) = parts[1].parse::<i32>() {
for (i, dist_str) in parts[2..].iter().enumerate() {
if let Ok(distance) = dist_str.parse::<u32>() {
if let Some(node) = nodes.get_mut(&from_node.to_string()) {
node.distances.insert(i.to_string(), distance);
}
}
}
}
}
}
}
// Get CPU to node mapping
let output = match Command::new("lscpu").args(&["-p=cpu,node"]).output() {
Ok(output) => output,
Err(_) => {
// lscpu not available, skip CPU to node mapping
return Ok(nodes);
}
};
let output_str = String::from_utf8(output.stdout)?;
for line in output_str.lines() {
if line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split(',').collect();
if parts.len() >= 2 {
if let (Ok(cpu), Ok(node)) = (parts[0].parse::<u32>(), parts[1].parse::<i32>()) {
if let Some(numa_node) = nodes.get_mut(&node.to_string()) {
numa_node.cpus.push(cpu);
}
}
}
}
// Sort CPUs within each node
for node in nodes.values_mut() {
node.cpus.sort();
}
Ok(nodes)
}
fn collect_ip_addresses() -> Result<Vec<InterfaceIPs>, Box<dyn Error>> {
let output = match Command::new("ip").args(&["-j", "addr"]).output() {
Ok(output) => output,
Err(_) => {
// ip command not available, return empty list
return Ok(Vec::new());
}
};
let json: serde_json::Value = serde_json::from_slice(&output.stdout)?;
let mut interfaces = Vec::new();
if let Some(ifaces) = json.as_array() {
for iface in ifaces {
if let Some(name) = iface["ifname"].as_str() {
if name == "lo" {
continue;
} // Skip loopback
let mut ip_addresses = Vec::new();
if let Some(addr_info) = iface["addr_info"].as_array() {
for addr in addr_info {
if addr["family"].as_str() == Some("inet") {
if let Some(ip) = addr["local"].as_str() {
ip_addresses.push(ip.to_string());
}
}
}
}
if !ip_addresses.is_empty() {
interfaces.push(InterfaceIPs {
interface: name.to_string(),
ip_addresses,
});
}
}
}
}
Ok(interfaces)
}
/// Gets system UUID and serial from dmidecode
fn get_system_info() -> Result<SystemInfo, Box<dyn Error>> {
let output = match Command::new("dmidecode").args(&["-t", "system"]).output() {
Ok(out) => {
if !out.status.success() {
Command::new("sudo")
.args(&["dmidecode", "-t", "system"])
.output()?
} else {
out
}
}
Err(_) => Command::new("sudo")
.args(&["dmidecode", "-t", "system"])
.output()?,
};
let stdout = String::from_utf8_lossy(&output.stdout);
if !output.status.success() || stdout.trim().is_empty() {
return Ok(SystemInfo {
uuid: "Unknown".to_string(),
serial: "Unknown".to_string(),
product_name: "Unknown".to_string(),
product_manufacturer: "Unknown".to_string(),
});
}
let uuid = Self::extract_dmidecode_value(&stdout, "UUID")
.unwrap_or_else(|_| "Unknown".to_string());
let serial = Self::extract_dmidecode_value(&stdout, "Serial Number")
.unwrap_or_else(|_| "Unknown".to_string());
let product_name = Self::extract_dmidecode_value(&stdout, "Product Name")
.unwrap_or_else(|_| "Unknown".to_string());
let product_manufacturer = Self::extract_dmidecode_value(&stdout, "Manufacturer")
.unwrap_or_else(|_| "Unknown".to_string());
Ok(SystemInfo {
uuid,
serial,
product_name,
product_manufacturer,
})
}
/// Collects all server information
pub fn collect() -> Result<Self, Box<dyn Error>> {
// Check dependencies first and warn about missing packages
let missing_packages = Self::check_dependencies()?;
// Automatically install numactl if it's missing
if missing_packages.contains(&"numactl") {
eprintln!("numactl is not installed. Attempting automatic installation...");
// Try to detect the package manager and install numactl
if Self::auto_install_numactl()? {
eprintln!("Successfully installed numactl.");
} else {
eprintln!("Warning: Could not automatically install numactl. NUMA information may be incomplete.");
}
}
// Check if running as root
let euid = unsafe { libc::geteuid() };
if euid != 0 {
eprintln!(
"\nWarning: This program requires root privileges to access all hardware information."
);
eprintln!(
"Please run it with: sudo {}",
std::env::args().next().unwrap_or_default()
);
eprintln!("Continuing with limited functionality...\n");
}
let hostname = Self::get_hostname()?;
let fqdn = Self::get_fqdn()?;
let hardware = Self::collect_hardware_info()?;
let network = Self::collect_network_info()?;
let system_info = Self::get_system_info()?;
let (bmc_ip, bmc_mac) = Self::collect_ipmi_info()?;
let os_ip = Self::collect_ip_addresses()?;
let summary = Self::generate_summary(&hardware, &network, &system_info)?;
Ok(ServerInfo {
summary,
hostname,
fqdn,
os_ip,
bmc_ip,
bmc_mac,
hardware,
network,
})
}
/// Calculates total storage in terabytes
fn calculate_total_storage_tb(storage: &StorageInfo) -> Result<f64, Box<dyn Error>> {
let mut total_bytes: u64 = 0;
for device in &storage.devices {
total_bytes += Self::parse_storage_size(&device.size)?;
}
Ok(total_bytes as f64 / (1024.0 * 1024.0 * 1024.0 * 1024.0))
}
/// Calculates total storage capacity
fn calculate_total_storage(storage: &StorageInfo) -> Result<String, Box<dyn Error>> {
let mut total_bytes: u64 = 0;
let re = Regex::new(r"(\d+(?:\.\d+)?)(B|K|M|G|T)")?;
for device in &storage.devices {
let size_str = device.size.replace(" ", "");
if let Some(caps) = re.captures(&size_str) {
let value: f64 = caps[1].parse()?;
let unit = &caps[2];
let multiplier = match unit {
"B" => 1_u64,
"K" => 1024_u64,
"M" => 1024_u64 * 1024,
"G" => 1024_u64 * 1024 * 1024,
"T" => 1024_u64 * 1024 * 1024 * 1024,
_ => 0_u64,
};
total_bytes += (value * multiplier as f64) as u64;
}
}
if total_bytes >= 1024 * 1024 * 1024 * 1024 {
Ok(format!(
"{:.1} TB",
total_bytes as f64 / (1024.0 * 1024.0 * 1024.0 * 1024.0)
))
} else {
Ok(format!(
"{:.1} GB",
total_bytes as f64 / (1024.0 * 1024.0 * 1024.0)
))
}
}
/// Gets filesystem information
fn get_filesystems() -> Result<Vec<String>, Box<dyn Error>> {
let output = match Command::new("df")
.args(["-h", "--output=source,fstype,size,used,avail,target"])
.output()
{
Ok(output) => output,
Err(_) => {
// df not available, return empty list
return Ok(Vec::new());
}
};
let output_str = String::from_utf8(output.stdout)?;
let mut filesystems = Vec::new();
for line in output_str.lines().skip(1) {
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() >= 6 {
filesystems.push(format!(
"{} ({}) - {} total, {} used, {} available, mounted on {}",
fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]
));
}
}
Ok(filesystems)
}
/// Gets BIOS information using dmidecode with minimal output