-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhardware_report.rs
More file actions
349 lines (299 loc) · 11.1 KB
/
hardware_report.rs
File metadata and controls
349 lines (299 loc) · 11.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
/*
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.
*/
use hardware_report::posting::post_data;
use hardware_report::ServerInfo;
use std::collections::HashMap;
use std::error::Error;
use std::process::Command;
use structopt::StructOpt;
#[derive(Debug)]
enum FileFormat {
Toml,
Json,
}
impl std::str::FromStr for FileFormat {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_uppercase().as_str() {
"TOML" => Ok(FileFormat::Toml),
"JSON" => Ok(FileFormat::Json),
_ => Err("File format must be either 'toml' or 'json'".to_string()),
}
}
}
impl std::fmt::Display for FileFormat {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
FileFormat::Toml => write!(f, "TOML"),
FileFormat::Json => write!(f, "JSON"),
}
}
}
#[derive(StructOpt)]
#[structopt(name = "hardware_report")]
struct Opt {
/// Enable posting to remote server
#[structopt(long)]
post: bool,
/// Remote endpoint URL
#[structopt(long, default_value = "")]
endpoint: String,
/// Authentication token
#[structopt(long, env = "HARDWARE_REPORT_TOKEN")]
auth_token: Option<String>,
/// Labels in key=value format (only included in POST payload, not in output file)
#[structopt(long = "label", parse(try_from_str = parse_label))]
labels: Vec<(String, String)>,
/// Output file format (toml or json)
#[structopt(long, default_value = "toml")]
file_format: FileFormat,
/// Save POST payload to specified file for debugging (only works with --post)
#[structopt(long)]
save_payload: Option<String>,
/// Skip TLS certificate verification (not recommended for production use)
#[structopt(long)]
skip_tls_verify: bool,
/// No summary output to console
#[structopt(long)]
noout: bool,
/// Enable NetBox integration
#[structopt(long)]
netbox: bool,
/// NetBox URL (required with --netbox)
#[structopt(long, env = "NETBOX_URL")]
netbox_url: Option<String>,
/// NetBox API token (required with --netbox)
#[structopt(long, env = "NETBOX_TOKEN")]
netbox_token: Option<String>,
/// NetBox site name (default: "Digital Ocean")
#[structopt(long, default_value = "Digital Ocean")]
netbox_site: String,
/// NetBox device role (default: "production")
#[structopt(long, default_value = "production")]
netbox_role: String,
/// Dry run mode for NetBox (preview changes without applying)
#[structopt(long)]
netbox_dry_run: bool,
}
fn parse_label(s: &str) -> Result<(String, String), String> {
let parts: Vec<&str> = s.split('=').collect();
if parts.len() == 2 {
Ok((parts[0].to_string(), parts[1].to_string()))
} else {
Err("Label must be in key=value format".to_string())
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let opt = Opt::from_args();
// Collect server information
let server_info = ServerInfo::collect()?;
// Generate summary output for console only if no_summary is false
if !opt.noout {
println!("System Summary:");
println!("==============");
println!("Hostname: {}", server_info.hostname);
println!("FQDN: {}", server_info.fqdn);
println!("System UUID: {}", server_info.summary.system_info.uuid);
println!("System Serial: {}", server_info.summary.system_info.serial);
println!("CPU: {}", server_info.summary.cpu_summary);
println!(
"Total: {} Cores, {} Threads",
server_info.summary.cpu_topology.total_cores,
server_info.summary.cpu_topology.total_threads
);
// Fix memory output format - add the missing format specifier
println!(
"Memory: {} {} @ {}",
server_info.hardware.memory.total,
server_info.hardware.memory.type_,
server_info.hardware.memory.speed
);
println!(
"Storage: {} (Total: {:.2} TB)",
server_info.summary.total_storage, server_info.summary.total_storage_tb
);
// Calculate total storage
let total_storage = server_info
.hardware
.storage
.devices
.iter()
.map(|device| device.size.clone())
.collect::<Vec<String>>()
.join(" + ");
println!("Available Disks: {}", total_storage);
// Get BIOS information from dmidecode
let output = Command::new("dmidecode").args(["-t", "bios"]).output()?;
let bios_str = String::from_utf8(output.stdout)?;
println!(
"BIOS: {} {} ({})",
ServerInfo::extract_dmidecode_value(&bios_str, "Vendor")?,
ServerInfo::extract_dmidecode_value(&bios_str, "Version")?,
ServerInfo::extract_dmidecode_value(&bios_str, "Release Date")?
);
// Get chassis information from dmidecode
let output = Command::new("dmidecode").args(["-t", "chassis"]).output()?;
let chassis_str = String::from_utf8(output.stdout)?;
println!(
"Chassis: {} {} (S/N: {})",
ServerInfo::extract_dmidecode_value(&chassis_str, "Manufacturer")?,
ServerInfo::extract_dmidecode_value(&chassis_str, "Type")?,
ServerInfo::extract_dmidecode_value(&chassis_str, "Serial Number")?
);
// Get motherboard information from server_info
println!(
"Motherboard: {} {} v{} (S/N: {})",
server_info.summary.motherboard.manufacturer,
server_info.summary.motherboard.product_name,
server_info.summary.motherboard.version,
server_info.summary.motherboard.serial
);
println!("\nNetwork Interfaces:");
for nic in &server_info.network.interfaces {
println!(
" {} - {} {} ({}) [Speed: {}] [NUMA: {}]",
nic.name,
nic.vendor,
nic.model,
nic.pci_id,
nic.speed.as_deref().unwrap_or("Unknown"),
nic.numa_node
.map_or("Unknown".to_string(), |n| n.to_string())
);
}
println!("\nGPUs:");
for gpu in &server_info.hardware.gpus.devices {
println!(
" {} - {} ({}) [NUMA: {}]",
gpu.name,
gpu.vendor,
gpu.pci_id,
gpu.numa_node
.map_or("Unknown".to_string(), |n| n.to_string())
);
}
println!("\nNUMA Topology:");
for (node_id, node) in &server_info.summary.numa_topology {
println!(" Node {}:", node_id);
println!(" Memory: {}", node.memory);
println!(" CPUs: {:?}", node.cpus);
if !node.devices.is_empty() {
println!(" Devices:");
for device in &node.devices {
println!(
" {} - {} (PCI ID: {})",
device.type_, device.name, device.pci_id
);
}
}
println!(" Distances:");
let mut distances: Vec<_> = node.distances.iter().collect();
distances.sort_by_key(|&(k, _)| k);
for (to_node, distance) in distances {
println!(" To Node {}: {}", to_node, distance);
}
}
// Get filesystem information
println!("\nFilesystems:");
let output = Command::new("df")
.args(["-h", "--output=source,fstype,size,used,avail,target"])
.output()?;
let fs_str = String::from_utf8(output.stdout)?;
for line in fs_str.lines().skip(1) {
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() >= 6 {
println!(
" {} ({}) - {} total, {} used, {} available, mounted on {}",
fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]
);
}
}
}
// Get chassis serial number and sanitize it for use as the file_name
let chassis_serial = server_info.summary.chassis.serial.clone();
let safe_filename = sanitize_filename(&chassis_serial);
fn sanitize_filename(filename: &str) -> String {
filename
.chars()
.map(|c| {
if c.is_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect::<String>()
}
println!(
"\nCreating {} output for system serial number: {}",
opt.file_format, safe_filename
);
let output_filename = format!(
"{}_hardware_report.{}",
safe_filename,
match opt.file_format {
FileFormat::Toml => "toml",
FileFormat::Json => "json",
}
);
// Convert to specified format and write to file
let output_string = match opt.file_format {
FileFormat::Toml => toml::to_string_pretty(&server_info)?,
FileFormat::Json => serde_json::to_string_pretty(&server_info)?,
};
std::fs::write(&output_filename, output_string)?;
println!("Configuration has been written to {}", output_filename);
// Handle posting if enabled
if opt.post {
let labels: HashMap<String, String> = opt.labels.into_iter().collect();
post_data(
&server_info,
labels,
&opt.endpoint,
opt.auth_token.as_deref(),
opt.save_payload.as_deref(),
opt.skip_tls_verify,
)
.await?;
println!("\nSuccessfully posted data to remote server");
}
// Handle NetBox integration if enabled
if opt.netbox {
if opt.netbox_url.is_none() {
eprintln!("Error: --netbox-url is required when using --netbox");
std::process::exit(1);
}
if opt.netbox_token.is_none() {
eprintln!("Error: --netbox-token is required when using --netbox");
std::process::exit(1);
}
use hardware_report::netbox::sync_to_netbox;
sync_to_netbox(
&server_info,
opt.netbox_url.as_ref().unwrap(),
opt.netbox_token.as_ref().unwrap(),
Some(&opt.netbox_site),
Some(&opt.netbox_role),
opt.skip_tls_verify,
opt.netbox_dry_run,
)
.await?;
if opt.netbox_dry_run {
println!("\nNetBox dry run completed - no changes were made");
} else {
println!("\nSuccessfully synchronized data to NetBox");
}
}
Ok(())
}