From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id CD8961FF0FD for ; Tue, 27 Oct 2026 09:58:49 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 6932A21501; Tue, 27 Oct 2026 09:56:33 +0100 (CET) From: Hannes Laimer To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox-perl-rs v3 17/45] pve-rs: sdn: add microseg config binding Date: Tue, 27 Oct 2026 09:54:59 +0100 Message-ID: <20261027085527.702738-18-h.laimer@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261027085527.702738-1-h.laimer@proxmox.com> References: <20261027085527.702738-1-h.laimer@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1793091351834 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.333 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: MYIJFW2N5MVPSAAET55LDBWRZIXYLPBQ X-Message-ID-Hash: MYIJFW2N5MVPSAAET55LDBWRZIXYLPBQ X-MailFrom: h.laimer@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: Expose the microseg config to Perl, shaped like the other SDN config bindings. Which NICs an assignment wins is not stored, so the model answers it for a guest inventory the caller passes in. Creating an object returns its id, since rule and assignment ids are generated. Signed-off-by: Hannes Laimer --- pve-rs/Makefile | 1 + pve-rs/src/bindings/sdn/microseg.rs | 243 ++++++++++++++++++++++++++++ pve-rs/src/bindings/sdn/mod.rs | 1 + 3 files changed, 245 insertions(+) create mode 100644 pve-rs/src/bindings/sdn/microseg.rs diff --git a/pve-rs/Makefile b/pve-rs/Makefile index bb1cd2d5f73a..fc199ae5c9b8 100644 --- a/pve-rs/Makefile +++ b/pve-rs/Makefile @@ -33,6 +33,7 @@ PERLMOD_PACKAGES := \ PVE::RS::ResourceScheduling::Static \ PVE::RS::ResourceScheduling::Dynamic \ PVE::RS::SDN::Fabrics \ + PVE::RS::SDN::Microseg \ PVE::RS::SDN::PrefixLists \ PVE::RS::SDN::RouteMaps \ PVE::RS::SDN::WireGuard::PrivateKeys \ diff --git a/pve-rs/src/bindings/sdn/microseg.rs b/pve-rs/src/bindings/sdn/microseg.rs new file mode 100644 index 000000000000..5deaf5189aec --- /dev/null +++ b/pve-rs/src/bindings/sdn/microseg.rs @@ -0,0 +1,243 @@ +#[perlmod::package(name = "PVE::RS::SDN::Microseg", lib = "pve_rs")] +pub mod pve_rs_sdn_microseg { + //! The `PVE::RS::SDN::Microseg` package. + //! + //! This provides the configuration for SDN microseg, as well as helper methods for reading + //! / writing the configuration. + + use std::collections::{BTreeMap, HashMap}; + use std::ops::Deref; + use std::sync::Mutex; + + use anyhow::{Context, Error}; + use openssl::hash::{MessageDigest, hash}; + + use perlmod::Value; + use serde::Serialize; + + use proxmox_section_config::typed::{ApiSectionDataEntry, SectionConfigData}; + use proxmox_ve_config::sdn::microseg::api::{MicrosegCreate, MicrosegUpdate}; + use proxmox_ve_config::sdn::microseg::identity::{IdSpace, Registry}; + use proxmox_ve_config::sdn::microseg::{ + self, GroupSetRules, GuestInfo, MicrosegEntry, MicrosegId, MicrosegRunningConfig, + }; + + /// A SDN Microseg config instance. + pub struct PerlMicrosegConfig { + pub microseg: Mutex>, + } + + perlmod::declare_magic!(Box : &PerlMicrosegConfig as "PVE::RS::SDN::Microseg::Config"); + + /// Class method: Parse the raw configuration from `/etc/pve/sdn/microseg.cfg`. + #[export] + pub fn config(#[raw] class: Value, raw_config: &[u8]) -> Result { + let raw_config = std::str::from_utf8(raw_config)?; + let config = MicrosegEntry::parse_section_config("microseg.cfg", raw_config)?; + let entries: BTreeMap = config.into_iter().collect(); + + microseg::validate(&entries).context("microseg config")?; + + Ok( + perlmod::instantiate_magic!(&class, MAGIC => Box::new(PerlMicrosegConfig { + microseg: Mutex::new(entries), + })), + ) + } + + /// Class method: Parse the configuration from `/etc/pve/sdn/.running-config`. + #[export] + pub fn running_config( + #[raw] class: Value, + entries: BTreeMap, + ) -> Result { + microseg::validate(&entries)?; + + Ok( + perlmod::instantiate_magic!(&class, MAGIC => Box::new(PerlMicrosegConfig { + microseg: Mutex::new(entries), + })), + ) + } + + /// Method: Render the running config from this config, keeping the ids of `previous`, the + /// `identities` of the last one (`undef` renumbers everything). + #[export] + pub fn render( + #[try_from_ref] this: &PerlMicrosegConfig, + previous: Option, + ) -> Result { + let entries = this.microseg.lock().unwrap().deref().clone(); + let previous = previous.unwrap_or_default(); + // the quarantine is only as reliable as the clocks of the nodes that render + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .context("the system clock is set before 1970")? + .as_secs(); + microseg::render(&previous, entries, now) + } + + #[derive(Serialize)] + pub struct AssignmentMember { + vmid: u32, + nics: Vec, + } + + /// Method: Returns the guests and NICs each assignment wins in `inventory`, keyed by assignment + /// id. + #[export] + pub fn assigned_members( + #[try_from_ref] this: &PerlMicrosegConfig, + inventory: Vec, + ) -> HashMap> { + let entries = this.microseg.lock().unwrap(); + let mut members: HashMap> = HashMap::new(); + // sorted by guest, so a guest that already has an entry is the last one in the list + for nic in microseg::assigned_nics(entries.deref(), &inventory) { + let guests = members.entry(nic.assignment.to_string()).or_default(); + match guests.last_mut() { + Some(member) if member.vmid == nic.vmid => member.nics.push(nic.iface), + _ => guests.push(AssignmentMember { + vmid: nic.vmid, + nics: vec![nic.iface], + }), + } + } + members + } + + /// Method: Returns, for each group set an assignment names, the rules that fire on it. + #[export] + pub fn rules_by_group_set( + #[try_from_ref] this: &PerlMicrosegConfig, + ) -> Result, Error> { + let entries = this.microseg.lock().unwrap(); + microseg::rules_by_group_set(entries.deref()) + } + + /// Method: Returns each rule's place in the evaluation order, by rule id. + #[export] + pub fn rule_order( + #[try_from_ref] this: &PerlMicrosegConfig, + ) -> Result, Error> { + let entries = this.microseg.lock().unwrap(); + microseg::rule_order(entries.deref()) + } + + /// Method: Returns each assignment's place in the match order, by id. + #[export] + pub fn assignment_order(#[try_from_ref] this: &PerlMicrosegConfig) -> HashMap { + let entries = this.microseg.lock().unwrap(); + microseg::assignment_order(entries.deref()) + } + + /// Method: Whether a guest renamed from `old` to `new` enters or leaves the names a regex + /// assignment matches. + #[export] + pub fn name_match_changed( + #[try_from_ref] this: &PerlMicrosegConfig, + old: Option<&str>, + new: Option<&str>, + ) -> bool { + let entries = this.microseg.lock().unwrap(); + microseg::name_match_changed(entries.deref(), old, new) + } + + /// Method: Returns how specific each rule is, by rule id. + #[export] + pub fn rule_specificity( + #[try_from_ref] this: &PerlMicrosegConfig, + ) -> Result, Error> { + let entries = this.microseg.lock().unwrap(); + microseg::rule_specificity(entries.deref()) + } + + /// How much of the id space the `identities` of a running config use. + #[export] + pub fn id_space(identities: Option) -> IdSpace { + identities.unwrap_or_default().id_space() + } + + /// The microseg block of a running config as text. + #[export] + pub fn summary(microseg: MicrosegRunningConfig, inventory: Vec) -> String { + microseg::api::summary(µseg, &inventory) + } + + /// Method: Returns all microseg objects, keyed by id. + #[export] + pub fn to_sections( + #[try_from_ref] this: &PerlMicrosegConfig, + ) -> BTreeMap { + this.microseg.lock().unwrap().clone() + } + + /// Method: Convert the configuration into the section config string. + /// + /// Used for writing `/etc/pve/sdn/microseg.cfg` + #[export] + pub fn to_raw(#[try_from_ref] this: &PerlMicrosegConfig) -> Result { + let config = this.microseg.lock().unwrap(); + // id order keeps the output and its digest stable across calls + let data: SectionConfigData = config + .iter() + .map(|(id, entry)| (id.clone(), entry.clone())) + .collect(); + + MicrosegEntry::write_section_config("microseg.cfg", &data) + } + + /// Method: Generate a digest for the whole configuration. + #[export] + pub fn digest(#[try_from_ref] this: &PerlMicrosegConfig) -> Result { + let raw = to_raw(this)?; + let digest = hash(MessageDigest::sha256(), raw.as_bytes())?; + + Ok(hex::encode(digest)) + } + + /// Method: Returns a single microseg object. + #[export] + pub fn get(#[try_from_ref] this: &PerlMicrosegConfig, id: &str) -> Option { + this.microseg.lock().unwrap().get(id).cloned() + } + + /// The model's edits validate after they change the map, so a failed one must not reach the + /// stored config. + fn change( + this: &PerlMicrosegConfig, + change: impl FnOnce(&mut BTreeMap) -> Result, + ) -> Result { + let mut entries = this.microseg.lock().unwrap(); + let mut candidate = entries.clone(); + let result = change(&mut candidate)?; + *entries = candidate; + + Ok(result) + } + + /// Method: Create a new microseg object and return its id. + #[export] + pub fn create( + #[try_from_ref] this: &PerlMicrosegConfig, + create: MicrosegCreate, + ) -> Result { + change(this, |entries| microseg::api::create(entries, create)) + } + + /// Method: Update an existing microseg object. + #[export] + pub fn update( + #[try_from_ref] this: &PerlMicrosegConfig, + id: &str, + update: MicrosegUpdate, + ) -> Result<(), Error> { + change(this, |entries| microseg::api::update(entries, id, update)) + } + + /// Method: Delete a microseg object. + #[export] + pub fn delete(#[try_from_ref] this: &PerlMicrosegConfig, id: &str) -> Result<(), Error> { + change(this, |entries| microseg::api::delete(entries, id)) + } +} diff --git a/pve-rs/src/bindings/sdn/mod.rs b/pve-rs/src/bindings/sdn/mod.rs index dcae046a7e46..1d4c23fb4258 100644 --- a/pve-rs/src/bindings/sdn/mod.rs +++ b/pve-rs/src/bindings/sdn/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod fabrics; +pub(crate) mod microseg; pub(crate) mod prefix_lists; pub(crate) mod route_maps; pub(crate) mod wireguard; -- 2.47.3