Skip to content

Commit

Permalink
Implement workaround for unsanitary response data
Browse files Browse the repository at this point in the history
  • Loading branch information
ByteOtter committed Sep 5, 2024
1 parent df2053e commit fabd4ec
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 74 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ toml = "0.7.6"
# This may not work in your environment. You can get your schema by visiting
# https://your.netbox-instance.com/api/schema.
# The yaml file will be downloaded and you can generate your client by using https://github.com/The-Nazara-Project/Thanix.
thanix_client = "1.1.0"
# thanix_client = "1.1.0"
# Uncomment this line if you are using a custom thanix client implementation.
# Change the path to be relative to this Cargo.toml file.
# The package parameter is the name of your client package. This is needed if you assigned a custom name upon creation.
# thanix_client = { package = "thanix_client", path = "path/to/your/crate" }
thanix_client = { package = "thanix_client", path = "/home/christopher/Codebase/nazara-project/Thanix/output/" }

[dev-dependencies]
mockall = "0.11.4"
21 changes: 11 additions & 10 deletions src/publisher/api_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,10 @@ extern crate thanix_client;
use reqwest::Error as ReqwestError;
use thanix_client::{
paths::{
dcim_devices_create, dcim_interfaces_create, dcim_interfaces_list,
ipam_ip_addresses_create, DcimDevicesCreateResponse, DcimInterfacesCreateResponse,
DcimInterfacesListQuery,
dcim_devices_create, dcim_interfaces_create, dcim_interfaces_list, ipam_ip_addresses_create, DcimDevicesCreateResponse, DcimInterfacesListQuery
},
types::{
Interface, WritableDeviceWithConfigContextRequest, WritableIPAddressRequest,
WritableInterfaceRequest,
Interface, WritableDeviceWithConfigContextRequest, WritableIPAddressRequest, WritableInterfaceRequest
},
util::ThanixClient,
};
Expand Down Expand Up @@ -120,7 +117,7 @@ pub fn create_interface(
match dcim_interfaces_create(client, payload) {
Ok(response) => match response {
thanix_client::paths::DcimInterfacesCreateResponse::Http201(result) => {
println!("\x1b[32m[success]\x1b[0m Interface created successfully. New Interface ID: '{}'", result.id);
println!("\x1b[32m[success]\x1b[0m Interface created successfully. New Interface-ID: '{}'", result.id);
Ok(result.id)
}
thanix_client::paths::DcimInterfacesCreateResponse::Other(other_response) => {
Expand Down Expand Up @@ -152,7 +149,7 @@ pub fn create_ip(
Ok(response) => match response {
thanix_client::paths::IpamIpAddressesCreateResponse::Http201(result) => {
println!(
"\x1b[32m[success]\x1b[0m IP Address created successfully. New IP ID: '{}'",
"\x1b[32m[success]\x1b[0m IP Address created successfully. New IP-ID: '{}'",
result.id
);
Ok(result.id)
Expand All @@ -174,13 +171,16 @@ pub fn get_interface_by_name(
state: &ThanixClient,
payload: &WritableInterfaceRequest,
) -> Result<Interface, NetBoxApiError> {
println!("Trying to retrieve interface by name '{}'...", payload.name);
println!(
"Trying to retrieve interface by name '{}'...",
payload.name.as_ref().unwrap()
);

match dcim_interfaces_list(state, DcimInterfacesListQuery::default()) {
Ok(response) => {
let interface_list: Vec<Interface> = match response {
thanix_client::paths::DcimInterfacesListResponse::Http200(interfaces) => {
interfaces.results
interfaces.results.unwrap()
}
thanix_client::paths::DcimInterfacesListResponse::Other(response) => {
let err: NetBoxApiError = NetBoxApiError::Other(response.text().unwrap());
Expand All @@ -195,7 +195,7 @@ pub fn get_interface_by_name(
}
Err(NetBoxApiError::Other(format!(
"No Inteface '{}' with name found. Creation possibly failed.",
payload.name
payload.name.as_ref().unwrap()
)))
}
Err(e) => {
Expand All @@ -204,3 +204,4 @@ pub fn get_interface_by_name(
}
}
}

11 changes: 7 additions & 4 deletions src/publisher/publisher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ pub fn probe(client: &ThanixClient) -> Result<(), NetBoxApiError> {
///
/// # Parameters
///
/// - `client: &ThanixClient` - Reference to a `thanix_client` instance
/// - `client: &ThanixClient` - Reference to a `thanix_client` instance.
/// - `machine: Machine` - Information about the host machine collected by the `collector` module.
/// - `config_data: ConfigData` - Nazara's configuration.
///
/// # Returns
///
Expand Down Expand Up @@ -99,10 +101,11 @@ pub fn register_machine(
};
let interface_id: i64;
// TODO: Check if interface ID is valid, if not, create new interface.
// Create new interface object if no interface ID is given, or the given ID does
// not exist.
if config_data.nwi.id.is_none() || !interface_exists(client, &config_data.nwi.id) {
let interface_payload: WritableInterfaceRequest =
translator::information_to_interface(
&client,
&machine,
config_data.clone(),
&device_id,
Expand All @@ -129,9 +132,9 @@ pub fn register_machine(
}

let ip_payload: WritableIPAddressRequest =
translator::information_to_ip(client, &machine, &config_data, interface_id);
translator::information_to_ip(&machine, &config_data, interface_id);

let ip_id = match create_ip(client, ip_payload) {
let _ = match create_ip(client, ip_payload) {
Ok(id) => id,
Err(e) => {
eprintln!("{}", e);
Expand Down
96 changes: 38 additions & 58 deletions src/publisher/translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
//!
//! This module handles the translation and processing of the data sent to or received from NetBox.
//!
//! TODO:
//! - Identify primary IPv4 or IPv6 using the primary_network_interface field from `ConfigData`.
use core::net::IpAddr;
use std::collections::HashMap;
use std::process;
use std::str::FromStr;
use thanix_client::paths::{
Expand All @@ -20,8 +17,6 @@ use thanix_client::util::ThanixClient;
use crate::collectors::network_collector::NetworkInformation;
use crate::{configuration::config_parser::ConfigData, Machine};

use super::publisher_exceptions::NetBoxApiError;

/// Translate the machine information to a `WritableDeviceWithConfigContextRequest` required by
/// NetBox's API.
///
Expand Down Expand Up @@ -94,7 +89,7 @@ pub fn information_to_device(
payload.comments = config_data.system.comments;
// payload.config_template = todo!();
payload.custom_fields = config_data.system.custom_fields;
// payload.description = todo!();
payload.description = config_data.system.description;
// payload.local_context_data = todo!();
// payload.oob_ip = todo!();
payload.primary_ip4 = get_primary_addresses(
Expand Down Expand Up @@ -154,7 +149,6 @@ pub fn information_to_vm(
///
/// * payload: `WritableInterfaceRequest` - Payload for creating an interface.
pub fn information_to_interface(
state: &ThanixClient,
machine: &Machine,
config_data: ConfigData,
device_id: &i64,
Expand All @@ -163,22 +157,17 @@ pub fn information_to_interface(

let mut payload: WritableInterfaceRequest = WritableInterfaceRequest::default();

payload.device = device_id.to_owned();
// payload.vdcs = todo!();
// payload.module = todo!();
payload.name = match &config_data.system.primary_network_interface {
Some(interface_name) => interface_name.to_owned(),
None => String::from("Nazara Generic Network Interface"),
};
// payload.label = todo!();
payload.device = Some(device_id.to_owned());
payload.name = config_data.system.primary_network_interface.clone();

// FIXME:
payload.r#type = config_data.nwi.r#type;
payload.r#type = Some(config_data.nwi.r#type);
payload.parent = config_data.nwi.parent;
payload.bridge = config_data.nwi.bridge;
payload.lag = config_data.nwi.lag;
payload.mtu = config_data.nwi.mtu;

// Get the interfce we are looking for as primary, then get its parameters.
// Get the interface we are looking for as primary, then get its parameters.
// These filter statements can probably be split off into their own function.
payload.mac_address = match &config_data.system.primary_network_interface {
Some(nwi_name) => {
Expand All @@ -200,15 +189,23 @@ pub fn information_to_interface(
}
None => None,
};
payload.description = String::from("This interface was automatically created by Nazara.");
payload.mode = config_data.nwi.mode.unwrap_or(String::from(""));
payload.rf_role = config_data.nwi.rf_role.unwrap_or(String::from(""));
payload.rf_channel = config_data.nwi.rf_channel.unwrap_or(String::from(""));
payload.poe_mode = config_data.nwi.poe_mode.unwrap_or(String::from(""));
payload.poe_type = config_data.nwi.poe_type.unwrap_or(String::from(""));
payload.description = Some(String::from(
"This interface was automatically created by Nazara.",
));
payload.mode = Some(config_data.nwi.mode.unwrap_or(String::from("")));
payload.rf_role = Some(config_data.nwi.rf_role.unwrap_or(String::from("")));
payload.rf_channel = Some(config_data.nwi.rf_channel.unwrap_or(String::from("")));
payload.poe_mode = Some(config_data.nwi.poe_mode.unwrap_or(String::from("")));
payload.poe_type = Some(config_data.nwi.poe_type.unwrap_or(String::from("")));
payload.custom_fields = config_data.nwi.custom_fields;
payload.mark_connected = config_data.nwi.mark_connected;
payload.enabled = config_data.nwi.enabled;
payload.mark_connected = Some(config_data.nwi.mark_connected);
payload.enabled = Some(config_data.nwi.enabled);
payload.vdcs = Some(config_data.nwi.vdcs.unwrap_or_default());
payload.label = Some(config_data.nwi.label.unwrap_or_default());
payload.mgmt_only = Some(config_data.nwi.mgmt_only);
payload.tagged_vlans = Some(config_data.nwi.tagged_vlans.unwrap_or_default());
payload.wireless_lans = Some(config_data.nwi.wireless_lans.unwrap_or_default());
payload.tags = Some(Vec::new());

payload
}
Expand All @@ -222,7 +219,6 @@ pub fn information_to_interface(
/// * config_data: `&ConfigData` - Data read from the config file.
/// * interface_id: `i64` - ID of the network interface this IP belongs to.
pub fn information_to_ip(
state: &ThanixClient,
machine: &Machine,
config_data: &ConfigData,
interface_id: i64,
Expand All @@ -231,19 +227,30 @@ pub fn information_to_ip(

let mut payload: WritableIPAddressRequest = WritableIPAddressRequest::default();

// payload.address = todo!();
let local_interface: &NetworkInformation = machine
.network_information
.iter()
.find(|s| {
s.name
== <std::option::Option<std::string::String> as Clone>::clone(
&config_data.system.primary_network_interface,
)
.unwrap()
})
.unwrap();
payload.address = format!("{}", local_interface.v4ip.unwrap());
// payload.vrf = todo!();
// payload.tenant = todo!();
// payload.status = todo!();
payload.status = String::from("active");
// payload.role = todo!();
// payload.assigned_object_type = todo!();
// payload.assigned_object_id = todo!();
payload.assigned_object_type = Some(String::from("dcim.interface"));
payload.assigned_object_id = Some(interface_id as u64);
// payload.nat_inside = todo!();
// payload.dns_name = todo!();
payload.description = String::from("This Address was automatically created by Nazara.");
payload.comments = String::from("Automatically created by Nazara. Dummy only.");
// payload.tags = todo!();
payload.custom_fields = Some(HashMap::new());
payload.custom_fields = config_data.nwi.custom_fields.clone();

payload
}
Expand Down Expand Up @@ -383,7 +390,6 @@ fn get_primary_addresses(
},
}
}
println!();
result
}

Expand Down Expand Up @@ -459,29 +465,3 @@ fn get_site_id(state: &ThanixClient, config_data: &ConfigData) -> Option<i64> {
}
None
}

/// Create a new IP-Adress object in NetBox if the collected IP Adresses for the preferred interface
/// do not exist yet.
///
/// # Parameters
///
/// * state: `&ThanixClient` - The `ThanixClient` object used for API connection.
/// * config_data: `&ConfigData` - The config information which identifies the preferred network
/// interface.
/// * sys_info: `&Machine` - Collected system information which contains the IP Adresses to create.
///
/// # Returns
///
/// Return `Ok(i64)` containing the ID of the created IP Adress entry if the creation was
/// successful. Otherwise, return `NetBoxApiError`.
///
/// # Panics
///
/// This function panics if the connection to NetBox fails.
fn create_ip_adresses(
state: &ThanixClient,
config_data: &ConfigData,
sys_info: &Machine,
) -> Result<i64, NetBoxApiError> {
todo!();
}

0 comments on commit fabd4ec

Please sign in to comment.