mirror of
https://codeberg.org/icewind/haze.git
synced 2026-06-03 09:04:12 +02:00
52 lines
1.5 KiB
Rust
52 lines
1.5 KiB
Rust
use crate::cloud::Cloud;
|
|
use bollard::config::NetworkCreateRequest;
|
|
use bollard::Docker;
|
|
use miette::{IntoDiagnostic, Result, WrapErr};
|
|
|
|
pub async fn clear_networks(docker: &Docker, instances: &[Cloud]) -> Result<()> {
|
|
let networks = docker
|
|
.list_networks(None)
|
|
.await
|
|
.into_diagnostic()
|
|
.wrap_err("Failed to list docker networks")?;
|
|
for network in networks {
|
|
if let Some(name) = network.name.as_deref() {
|
|
if let Some(id) = name.strip_prefix("haze-") {
|
|
if !instances.iter().any(|cloud| cloud.id == id) {
|
|
docker.remove_network(name).await.ok();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn get_network_id(docker: &Docker, name: &str) -> Result<Option<String>> {
|
|
let networks = docker
|
|
.list_networks(None)
|
|
.await
|
|
.into_diagnostic()
|
|
.wrap_err("Failed to list docker networks")?;
|
|
Ok(networks.into_iter().find_map(|network| {
|
|
if network.name.as_deref() == Some(name) {
|
|
Some(network.id.unwrap())
|
|
} else {
|
|
None
|
|
}
|
|
}))
|
|
}
|
|
|
|
pub async fn ensure_network_exists(docker: &Docker, name: &str) -> Result<String> {
|
|
if let Some(id) = get_network_id(docker, name).await? {
|
|
Ok(id)
|
|
} else {
|
|
Ok(docker
|
|
.create_network(NetworkCreateRequest {
|
|
name: name.into(),
|
|
..Default::default()
|
|
})
|
|
.await
|
|
.into_diagnostic()?
|
|
.id)
|
|
}
|
|
}
|