Files
krata/network/src/lib.rs

88 lines
2.3 KiB
Rust
Raw Normal View History

use std::time::Duration;
use anyhow::Result;
use autonet::{AutoNetworkChangeset, AutoNetworkCollector, NetworkMetadata};
2024-02-13 10:03:28 +00:00
use futures::{future::join_all, TryFutureExt};
use log::warn;
use tokio::time::sleep;
2024-02-13 10:03:28 +00:00
use uuid::Uuid;
use vbridge::VirtualBridge;
2024-02-09 08:04:23 +00:00
use crate::backend::NetworkBackend;
pub mod autonet;
2024-02-10 21:13:47 +00:00
pub mod backend;
pub mod chandev;
pub mod icmp;
pub mod nat;
pub mod pkt;
2024-02-10 21:13:47 +00:00
pub mod proxynat;
pub mod raw_socket;
pub mod vbridge;
pub struct NetworkService {
pub bridge: VirtualBridge,
}
impl NetworkService {
pub fn new() -> Result<NetworkService> {
Ok(NetworkService {
bridge: VirtualBridge::new()?,
})
}
}
impl NetworkService {
pub async fn watch(&mut self) -> Result<()> {
let mut collector = AutoNetworkCollector::new()?;
loop {
let changeset = collector.read_changes()?;
2024-02-13 10:03:28 +00:00
self.process_network_changeset(&mut collector, changeset)?;
sleep(Duration::from_secs(2)).await;
}
}
2024-02-13 10:03:28 +00:00
fn process_network_changeset(
&mut self,
collector: &mut AutoNetworkCollector,
changeset: AutoNetworkChangeset,
) -> Result<()> {
let futures = changeset
.added
.iter()
.map(|metadata| {
self.add_network_backend(metadata.clone())
.map_err(|x| (metadata.clone(), x))
})
.collect::<Vec<_>>();
let failed = futures::executor::block_on(async move {
let mut failed: Vec<Uuid> = Vec::new();
let results = join_all(futures).await;
for result in results {
if let Err((metadata, error)) = result {
warn!(
"failed to launch network backend for hypha guest {}: {}",
metadata.uuid, error
);
failed.push(metadata.uuid);
}
}
failed
});
for uuid in failed {
collector.mark_unknown(uuid)?;
}
Ok(())
}
2024-02-13 10:03:28 +00:00
async fn add_network_backend(&self, metadata: NetworkMetadata) -> Result<()> {
let mut network = NetworkBackend::new(metadata, self.bridge.clone())?;
network.init().await?;
network.launch().await?;
Ok(())
}
}