-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjson_parser.rs
More file actions
272 lines (239 loc) · 8.67 KB
/
json_parser.rs
File metadata and controls
272 lines (239 loc) · 8.67 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
//! JSON parsing utilities for LXD command output
//!
//! This module provides the `LxdJsonParser` which handles parsing of complex JSON
//! responses from LXD commands and converts them into structured Rust types.
//!
//! ## Key Features
//!
//! - Parsing LXD list command JSON output into instance information
//! - IP address extraction from LXD network configuration
//! - Error handling for malformed or unexpected JSON structures
//! - Type-safe conversion from JSON to Rust structs
//!
//! The parser encapsulates all JSON handling logic and provides a clean interface
//! for converting LXD command output into usable data structures.
use std::net::IpAddr;
use anyhow::{anyhow, Context, Result};
use serde_json::Value;
use super::instance::{InstanceInfo, InstanceName};
/// A JSON parser for LXD responses.
///
/// This parser handles the complex JSON structure returned by LXD commands
/// and converts them into structured Rust types. It encapsulates all the
/// JSON parsing logic and can be unit tested independently.
pub(crate) struct LxdJsonParser;
impl LxdJsonParser {
/// Parse JSON output from lxc list command into structured instance information
///
/// # Arguments
///
/// * `json_output` - JSON string from lxc list command
///
/// # Returns
///
/// * `Ok(Vec<InstanceInfo>)` - Parsed instance information
/// * `Err(anyhow::Error)` - JSON parsing error
pub fn parse_instances_json(json_output: &str) -> Result<Vec<InstanceInfo>> {
let instances: Value =
serde_json::from_str(json_output).context("Failed to parse LXC list output as JSON")?;
let instances_array = instances
.as_array()
.ok_or_else(|| anyhow!("Expected JSON array from lxc list"))?;
let mut result = Vec::new();
for instance_value in instances_array {
let name_str = instance_value["name"]
.as_str()
.ok_or_else(|| anyhow!("Instance missing name field"))?;
let name = InstanceName::new(name_str.to_string())
.with_context(|| format!("Invalid instance name: {name_str}"))?;
let ip_address = Self::extract_ipv4_address(instance_value)?;
result.push(InstanceInfo { name, ip_address });
}
Ok(result)
}
/// Extract IPv4 address from instance JSON data
///
/// # Arguments
///
/// * `instance` - JSON value representing an instance
///
/// # Returns
///
/// * `Ok(Option<IpAddr>)` - IPv4 address if found, None otherwise
/// * `Err(anyhow::Error)` - Error parsing IP address
fn extract_ipv4_address(instance: &Value) -> Result<Option<IpAddr>> {
let network = instance["state"]["network"].as_object();
if let Some(network) = network {
// Iterate through all network interfaces (eth0, enp5s0, etc.)
for (interface_name, interface_data) in network {
// Skip loopback interface
if interface_name == "lo" {
continue;
}
if let Some(addresses) = interface_data["addresses"].as_array() {
for addr in addresses {
if addr["family"].as_str() == Some("inet") {
if let Some(ip_str) = addr["address"].as_str() {
let ip = ip_str.parse::<IpAddr>().with_context(|| {
format!("Failed to parse IP address: {ip_str}")
})?;
return Ok(Some(ip));
}
}
}
}
}
}
Ok(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_should_parse_instance_ip_from_valid_json() {
// Mock JSON response similar to what LXD returns
let mock_json = r#"[
{
"name": "test-instance",
"state": {
"network": {
"eth0": {
"addresses": [
{
"family": "inet6",
"address": "fe80::1"
},
{
"family": "inet",
"address": "192.168.1.100"
}
]
}
}
}
}
]"#;
let instances = LxdJsonParser::parse_instances_json(mock_json).unwrap();
assert_eq!(instances.len(), 1);
assert_eq!(instances[0].name.as_str(), "test-instance");
assert_eq!(
instances[0].ip_address.unwrap().to_string(),
"192.168.1.100"
);
}
#[test]
fn it_should_handle_empty_instance_list() {
// Mock empty JSON response
let mock_json = r"[]";
let instances = LxdJsonParser::parse_instances_json(mock_json).unwrap();
assert!(instances.is_empty());
}
#[test]
fn it_should_handle_instance_without_ipv4_address() {
// Mock JSON response without IPv4 address
let mock_json = r#"[
{
"name": "test-instance",
"state": {
"network": {
"eth0": {
"addresses": [
{
"family": "inet6",
"address": "fe80::1"
}
]
}
}
}
}
]"#;
let instances = LxdJsonParser::parse_instances_json(mock_json).unwrap();
assert_eq!(instances.len(), 1);
assert_eq!(instances[0].name.as_str(), "test-instance");
assert!(instances[0].ip_address.is_none());
}
#[test]
fn it_should_handle_malformed_json() {
let malformed_json = r"{ invalid json }";
let result = LxdJsonParser::parse_instances_json(malformed_json);
assert!(result.is_err());
}
#[test]
fn it_should_extract_ipv4_address_from_instance_json() {
let instance_json = serde_json::json!({
"name": "test-instance",
"state": {
"network": {
"eth0": {
"addresses": [
{
"family": "inet6",
"address": "fe80::1"
},
{
"family": "inet",
"address": "192.168.1.100"
}
]
}
}
}
});
let result = LxdJsonParser::extract_ipv4_address(&instance_json).unwrap();
assert_eq!(result.unwrap().to_string(), "192.168.1.100");
}
#[test]
fn it_should_return_none_when_no_ipv4_address_found() {
let instance_json = serde_json::json!({
"name": "test-instance",
"state": {
"network": {
"eth0": {
"addresses": [
{
"family": "inet6",
"address": "fe80::1"
}
]
}
}
}
});
let result = LxdJsonParser::extract_ipv4_address(&instance_json).unwrap();
assert!(result.is_none());
}
#[test]
fn it_should_return_none_when_no_network_interfaces() {
let instance_json = serde_json::json!({
"name": "test-instance",
"state": {
"network": {}
}
});
let result = LxdJsonParser::extract_ipv4_address(&instance_json).unwrap();
assert!(result.is_none());
}
#[test]
fn it_should_fail_when_instance_missing_name() {
let mock_json = r#"[
{
"state": {
"network": {
"eth0": {
"addresses": [
{
"family": "inet",
"address": "192.168.1.100"
}
]
}
}
}
}
]"#;
let result = LxdJsonParser::parse_instances_json(mock_json);
assert!(result.is_err());
}
}