use std::collections::{BTreeSet, HashSet};
use uuid::Uuid;
use super::plan::{Change, PlannedAction, Resolved, Target};
use super::{Done, Manifest, Step, StepError, action, lookup};
use crate::AxiamError;
use crate::management::models::{
CreateNetworkReplyProfileRequest, CreateNetworkSegmentRequest, NetworkPolicyResponse,
NetworkReplyProfile, NetworkReplyProfileInput, NetworkSegmentKind, NetworkSegmentResponse,
RadiusServiceType, RadiusTerminationAction, ReplaceNetworkPolicyRequest,
ReplaceNetworkReplyProfileRequest, ReplaceNetworkSegmentRequest,
};
#[derive(Debug, Clone, Default, PartialEq)]
pub struct NetworkSpec {
pub policy: Option<NetworkPolicySpec>,
pub segments: Vec<NetworkSegmentSpec>,
pub profiles: Vec<NetworkProfileSpec>,
}
impl NetworkSpec {
#[must_use]
pub fn is_empty(&self) -> bool {
self.policy.is_none() && self.segments.is_empty() && self.profiles.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetworkPolicySpec {
pub session_timeout_max_secs: i32,
}
impl NetworkPolicySpec {
#[must_use]
pub fn new(session_timeout_max_secs: i32) -> Self {
Self {
session_timeout_max_secs,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct NetworkSegmentSpec {
pub key: String,
pub site: String,
pub kind: NetworkSegmentKind,
pub name: String,
pub vlan_id: i32,
pub rank: Option<Option<i32>>,
pub filter_ids: Option<Vec<String>>,
pub enabled: Option<bool>,
}
impl NetworkSegmentSpec {
pub fn new(
key: impl Into<String>,
site: impl Into<String>,
kind: NetworkSegmentKind,
name: impl Into<String>,
vlan_id: i32,
) -> Self {
Self {
key: key.into(),
site: site.into(),
kind,
name: name.into(),
vlan_id,
rank: None,
filter_ids: None,
enabled: None,
}
}
pub fn access(
key: impl Into<String>,
site: impl Into<String>,
name: impl Into<String>,
vlan_id: i32,
rank: i32,
) -> Self {
Self::new(key, site, NetworkSegmentKind::Access, name, vlan_id).with_rank(rank)
}
pub fn quarantine(
key: impl Into<String>,
site: impl Into<String>,
name: impl Into<String>,
vlan_id: i32,
) -> Self {
Self::new(key, site, NetworkSegmentKind::Quarantine, name, vlan_id)
}
#[must_use]
pub fn with_rank(mut self, rank: i32) -> Self {
self.rank = Some(Some(rank));
self
}
#[must_use]
pub fn with_no_rank(mut self) -> Self {
self.rank = Some(None);
self
}
#[must_use]
pub fn with_filter_ids(
mut self,
filter_ids: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
self.filter_ids = Some(filter_ids.into_iter().map(Into::into).collect());
self
}
#[must_use]
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct NetworkProfileSpec {
pub segment: String,
pub session_timeout_secs: i32,
pub termination_action: Option<RadiusTerminationAction>,
pub idle_timeout_secs: Option<Option<i32>>,
pub filter_id: Option<Option<String>>,
pub service_type: Option<Option<RadiusServiceType>>,
}
impl NetworkProfileSpec {
pub fn new(segment: impl Into<String>, session_timeout_secs: i32) -> Self {
Self {
segment: segment.into(),
session_timeout_secs,
termination_action: None,
idle_timeout_secs: None,
filter_id: None,
service_type: None,
}
}
#[must_use]
pub fn with_termination_action(mut self, action: RadiusTerminationAction) -> Self {
self.termination_action = Some(action);
self
}
#[must_use]
pub fn with_idle_timeout_secs(mut self, secs: i32) -> Self {
self.idle_timeout_secs = Some(Some(secs));
self
}
#[must_use]
pub fn with_no_idle_timeout(mut self) -> Self {
self.idle_timeout_secs = Some(None);
self
}
#[must_use]
pub fn with_filter_id(mut self, filter_id: impl Into<String>) -> Self {
self.filter_id = Some(Some(filter_id.into()));
self
}
#[must_use]
pub fn with_no_filter_id(mut self) -> Self {
self.filter_id = Some(None);
self
}
#[must_use]
pub fn with_service_type(mut self, service_type: RadiusServiceType) -> Self {
self.service_type = Some(Some(service_type));
self
}
#[must_use]
pub fn with_no_service_type(mut self) -> Self {
self.service_type = Some(None);
self
}
}
fn unknown_open_enum(segment: &str, member: &str, value: &str) -> AxiamError {
crate::management::error::local_refusal(
"manifest.plan",
member,
format!(
"network profile of segment {segment:?}: {member} is {value:?} on the server, a \
value this SDK does not know and never re-sends; state {member} in the manifest to \
replace it (CONTRACT.md §27.6.2)"
),
)
}
fn kind_wire(kind: &NetworkSegmentKind) -> &str {
match kind {
NetworkSegmentKind::Access => "access",
NetworkSegmentKind::Quarantine => "quarantine",
NetworkSegmentKind::Unknown(other) => other,
}
}
pub(crate) fn validate(spec: &NetworkSpec, problems: &mut Vec<String>) {
let mut keys: HashSet<&str> = HashSet::new();
let mut natural: HashSet<(&str, &str, &str)> = HashSet::new();
for segment in &spec.segments {
if !keys.insert(segment.key.as_str()) {
problems.push(format!(
"network segment key {:?} is declared more than once",
segment.key
));
}
if !natural.insert((
segment.site.as_str(),
kind_wire(&segment.kind),
segment.name.as_str(),
)) {
problems.push(format!(
"network segment {:?} (site {:?}, kind {:?}) is declared more than once; one \
natural key is one server row",
segment.name,
segment.site,
kind_wire(&segment.kind)
));
}
if let Some(filter_ids) = &segment.filter_ids {
let mut seen: HashSet<&str> = HashSet::new();
for name in filter_ids {
if !seen.insert(name.as_str()) {
problems.push(format!(
"network segment {:?} lists Filter-Id {name:?} more than once; \
filter_ids is a set",
segment.key
));
}
}
}
}
let mut profiled: HashSet<&str> = HashSet::new();
for profile in &spec.profiles {
if !keys.contains(profile.segment.as_str()) {
problems.push(format!(
"a network profile names segment {:?}, which no segment of the manifest declares",
profile.segment
));
}
if !profiled.insert(profile.segment.as_str()) {
problems.push(format!(
"network segment {:?} has more than one profile; a segment has at most one",
profile.segment
));
}
}
}
#[derive(Debug, Default)]
pub(crate) struct NetworkSnapshot {
pub(crate) policy: Option<NetworkPolicyResponse>,
pub(crate) segments: Vec<NetworkSegmentResponse>,
pub(crate) profiles: Vec<NetworkReplyProfile>,
}
impl<'c> Manifest<'c> {
pub(super) async fn read_network(
&self,
spec: &NetworkSpec,
) -> Result<NetworkSnapshot, AxiamError> {
let network = self.client.network();
let start = || crate::management::page::PageRequest::first(super::PLAN_PAGE);
let policy = if spec.policy.is_some() {
Some(network.get_policy().await?)
} else {
None
};
let segments = if spec.segments.is_empty() && spec.profiles.is_empty() {
Vec::new()
} else {
network.list_segments_all(None, start()).await?
};
let profiles = if spec.profiles.is_empty() {
Vec::new()
} else {
network.list_profiles_all(start()).await?
};
Ok(NetworkSnapshot {
policy,
segments,
profiles,
})
}
}
#[derive(Debug, Clone)]
pub(super) enum NetStep {
ReplacePolicy { body: ReplaceNetworkPolicyRequest },
CreateSegment {
key: String,
body: CreateNetworkSegmentRequest,
},
ReplaceSegment {
key: String,
id: Uuid,
body: ReplaceNetworkSegmentRequest,
},
CreateProfile {
segment: String,
profile: NetworkReplyProfileInput,
},
ReplaceProfile {
segment: String,
version: i64,
profile: NetworkReplyProfileInput,
},
}
fn as_set(names: &[String]) -> BTreeSet<&str> {
names.iter().map(String::as_str).collect()
}
fn change(drifted: bool) -> Change {
if drifted {
Change::Update
} else {
Change::NoChange
}
}
pub(super) fn plan(
spec: &NetworkSpec,
snapshot: &NetworkSnapshot,
resolved: &mut Resolved,
steps: &mut Vec<(PlannedAction, Step)>,
) -> Result<(), AxiamError> {
if let Some(stated) = &spec.policy {
let read = snapshot.policy.as_ref().ok_or_else(|| {
AxiamError::network("internal: the network policy was not read although it is stated")
})?;
let drifted = read.session_timeout_max_secs != stated.session_timeout_max_secs;
steps.push((
action(
change(drifted),
Target::NetworkPolicy,
"policy",
format!(
"network policy: session_timeout_max_secs {}",
stated.session_timeout_max_secs
),
),
if drifted {
Step::Network(NetStep::ReplacePolicy {
body: ReplaceNetworkPolicyRequest {
session_timeout_max_secs: stated.session_timeout_max_secs,
version: read.version,
},
})
} else {
Step::Noop
},
));
}
for segment in &spec.segments {
let summary = format!(
"network segment {:?} ({} on site {:?})",
segment.name,
kind_wire(&segment.kind),
segment.site
);
let found = snapshot.segments.iter().find(|r| {
r.site_key == segment.site && r.kind == segment.kind && r.name == segment.name
});
match found {
Some(read) => {
resolved
.network_segments
.insert(segment.key.clone(), read.id);
resolved
.network_segment_versions
.insert(segment.key.clone(), read.version);
let drifted = read.vlan_id != segment.vlan_id
|| segment
.rank
.as_ref()
.is_some_and(|stated| *stated != read.rank)
|| segment
.filter_ids
.as_ref()
.is_some_and(|stated| as_set(stated) != as_set(&read.filter_ids))
|| segment.enabled.is_some_and(|stated| stated != read.enabled);
steps.push((
action(
change(drifted),
Target::NetworkSegment,
&segment.key,
summary,
),
if drifted {
Step::Network(NetStep::ReplaceSegment {
key: segment.key.clone(),
id: read.id,
body: ReplaceNetworkSegmentRequest {
version: read.version,
vlan_id: segment.vlan_id,
filter_ids: segment
.filter_ids
.clone()
.unwrap_or_else(|| read.filter_ids.clone()),
enabled: segment.enabled.unwrap_or(read.enabled),
rank: match segment.rank {
Some(stated) => stated,
None => read.rank,
},
},
})
} else {
Step::Noop
},
));
}
None => steps.push((
action(
Change::Create,
Target::NetworkSegment,
&segment.key,
summary,
),
Step::Network(NetStep::CreateSegment {
key: segment.key.clone(),
body: CreateNetworkSegmentRequest {
kind: segment.kind.clone(),
site_key: segment.site.clone(),
name: segment.name.clone(),
vlan_id: segment.vlan_id,
filter_ids: segment.filter_ids.clone(),
rank: segment.rank.flatten(),
enabled: segment.enabled,
},
}),
)),
}
}
for segment in &spec.segments {
let Some(stated) = spec.profiles.iter().find(|p| p.segment == segment.key) else {
continue;
};
let summary = format!(
"network profile of segment {:?} (session_timeout_secs {})",
segment.name, stated.session_timeout_secs
);
let read = resolved
.network_segments
.get(&segment.key)
.and_then(|id| snapshot.profiles.iter().find(|p| p.segment_id == *id));
match read {
Some(read) => {
let drifted = read.session_timeout_secs != stated.session_timeout_secs
|| stated
.termination_action
.as_ref()
.is_some_and(|s| *s != read.termination_action)
|| stated
.idle_timeout_secs
.is_some_and(|s| s != read.idle_timeout_secs)
|| stated
.filter_id
.as_ref()
.is_some_and(|s| *s != read.filter_id)
|| stated
.service_type
.as_ref()
.is_some_and(|s| *s != read.service_type);
if drifted {
if stated.termination_action.is_none()
&& let RadiusTerminationAction::Unknown(value) = &read.termination_action
{
return Err(unknown_open_enum(&segment.key, "termination_action", value));
}
if stated.service_type.is_none()
&& let Some(RadiusServiceType::Unknown(value)) = &read.service_type
{
return Err(unknown_open_enum(&segment.key, "service_type", value));
}
}
steps.push((
action(
change(drifted),
Target::NetworkProfile,
&segment.key,
summary,
),
if drifted {
Step::Network(NetStep::ReplaceProfile {
segment: segment.key.clone(),
version: read.version,
profile: NetworkReplyProfileInput {
dictionary: Some(read.dictionary.clone()),
session_timeout_secs: stated.session_timeout_secs,
termination_action: Some(
stated
.termination_action
.clone()
.unwrap_or_else(|| read.termination_action.clone()),
),
idle_timeout_secs: stated
.idle_timeout_secs
.unwrap_or(read.idle_timeout_secs),
filter_id: stated
.filter_id
.clone()
.unwrap_or_else(|| read.filter_id.clone()),
service_type: stated
.service_type
.clone()
.unwrap_or_else(|| read.service_type.clone()),
},
})
} else {
Step::Noop
},
));
}
None => steps.push((
action(
Change::Create,
Target::NetworkProfile,
&segment.key,
summary,
),
Step::Network(NetStep::CreateProfile {
segment: segment.key.clone(),
profile: NetworkReplyProfileInput {
dictionary: None,
session_timeout_secs: stated.session_timeout_secs,
termination_action: stated.termination_action.clone(),
idle_timeout_secs: stated.idle_timeout_secs.flatten(),
filter_id: stated.filter_id.clone().flatten(),
service_type: stated.service_type.clone().flatten(),
},
}),
)),
}
}
Ok(())
}
impl<'c> Manifest<'c> {
pub(super) async fn run_network(
&self,
step: NetStep,
resolved: &mut Resolved,
) -> Result<Done, StepError> {
let network = self.client.network();
match step {
NetStep::ReplacePolicy { body } => {
network.replace_policy(&body).await?;
}
NetStep::CreateSegment { key, body } => {
let created = network.create_segment(&body).await?;
resolved.network_segments.insert(key.clone(), created.id);
resolved
.network_segment_versions
.insert(key, created.version);
}
NetStep::ReplaceSegment { key, id, body } => {
let replaced = network.replace_segment(id, &body).await?;
resolved
.network_segment_versions
.insert(key, replaced.version);
}
NetStep::CreateProfile { segment, profile } => {
let segment_id = lookup(&resolved.network_segments, &segment, "network segment")?;
let segment_version = segment_version(resolved, &segment)?;
network
.create_profile(&CreateNetworkReplyProfileRequest {
segment_id,
segment_version,
profile,
})
.await?;
}
NetStep::ReplaceProfile {
segment,
version,
profile,
} => {
let segment_id = lookup(&resolved.network_segments, &segment, "network segment")?;
let segment_version = segment_version(resolved, &segment)?;
network
.replace_profile(
segment_id,
&ReplaceNetworkReplyProfileRequest {
profile,
segment_version,
version,
},
)
.await?;
}
}
Ok(Done::Plain)
}
}
fn segment_version(resolved: &Resolved, key: &str) -> Result<i64, AxiamError> {
resolved
.network_segment_versions
.get(key)
.copied()
.ok_or_else(|| {
AxiamError::network(format!(
"internal: network segment key {key:?} has no version: it was consumed before \
the step that creates it ran"
))
})
}