all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Lukas Wagner <l.wagner@proxmox.com>
To: pdm-devel@lists.proxmox.com
Subject: [pdm-devel] [PATCH datacenter-manager v5 01/11] pdm-api-types: views: add ViewConfig type
Date: Thu, 13 Nov 2025 13:16:34 +0100	[thread overview]
Message-ID: <20251113121644.236005-2-l.wagner@proxmox.com> (raw)
In-Reply-To: <20251113121644.236005-1-l.wagner@proxmox.com>

This type will be used to define views.

Signed-off-by: Lukas Wagner <l.wagner@proxmox.com>
Reviewed-by: Michael Köppl <m.koeppl@proxmox.com>
---

Notes:
    Changes since v2:
      - use ApiSectionDataEntry, as suggested by Dominik
      - Renamed ViewFilter* -> View*
      - Use SAFE_ID_FORMAT to check filter values where possible
    
    Changes since RFC:
      - Change config structure, instead of 'include-{x} value' we now do
        'include {x}:value'

 lib/pdm-api-types/src/lib.rs   |   8 ++
 lib/pdm-api-types/src/views.rs | 210 +++++++++++++++++++++++++++++++++
 2 files changed, 218 insertions(+)
 create mode 100644 lib/pdm-api-types/src/views.rs

diff --git a/lib/pdm-api-types/src/lib.rs b/lib/pdm-api-types/src/lib.rs
index 5ac99aa1..67a1a55f 100644
--- a/lib/pdm-api-types/src/lib.rs
+++ b/lib/pdm-api-types/src/lib.rs
@@ -107,6 +107,8 @@ pub mod subscription;
 
 pub mod sdn;
 
+pub mod views;
+
 const_regex! {
     // just a rough check - dummy acceptor is used before persisting
     pub OPENSSL_CIPHERS_REGEX = r"^[0-9A-Za-z_:, +!\-@=.]+$";
@@ -154,6 +156,12 @@ pub const REALM_ID_SCHEMA: Schema = StringSchema::new("Realm name.")
     .max_length(32)
     .schema();
 
+pub const VIEW_ID_SCHEMA: Schema = StringSchema::new("View name.")
+    .format(&PROXMOX_SAFE_ID_FORMAT)
+    .min_length(2)
+    .max_length(32)
+    .schema();
+
 pub const VMID_SCHEMA: Schema = IntegerSchema::new("A guest ID").minimum(1).schema();
 pub const SNAPSHOT_NAME_SCHEMA: Schema = StringSchema::new("The name of the snapshot")
     .format(&PROXMOX_SAFE_ID_FORMAT)
diff --git a/lib/pdm-api-types/src/views.rs b/lib/pdm-api-types/src/views.rs
new file mode 100644
index 00000000..ef39cc62
--- /dev/null
+++ b/lib/pdm-api-types/src/views.rs
@@ -0,0 +1,210 @@
+use std::{fmt::Display, str::FromStr, sync::OnceLock};
+
+use anyhow::bail;
+use const_format::concatcp;
+use serde::{Deserialize, Serialize};
+
+use proxmox_schema::{
+    api, api_types::SAFE_ID_REGEX_STR, const_regex, ApiStringFormat, ApiType, ArraySchema, Schema,
+    StringSchema, Updater,
+};
+use proxmox_section_config::{typed::ApiSectionDataEntry, SectionConfig, SectionConfigPlugin};
+
+use crate::{
+    remotes::REMOTE_ID_SCHEMA, resource::ResourceType, PROXMOX_SAFE_ID_REGEX, VIEW_ID_SCHEMA,
+};
+
+const_regex! {
+    /// Regex for matching global resource IDs
+    pub GLOBAL_RESOURCE_ID_REGEX = concatcp!(r"^", SAFE_ID_REGEX_STR, r"(\/", SAFE_ID_REGEX_STR, r")+$");
+}
+
+/// Schema for filter rules.
+pub const FILTER_RULE_SCHEMA: Schema = StringSchema::new("Filter rule for resources.")
+    .format(&ApiStringFormat::VerifyFn(verify_filter_rule))
+    .type_text(
+        "resource-type:<storage|qemu|lxc|sdn-zone|datastore|node>\
+            |resource-pool:<pool-name>\
+            |tag:<tag-name>\
+            |remote:<remote-name>\
+            |resource-id:<resource-id>",
+    )
+    .schema();
+
+/// Schema for list of filter rules.
+pub const FILTER_RULE_LIST_SCHEMA: Schema =
+    ArraySchema::new("List of filter rules.", &FILTER_RULE_SCHEMA).schema();
+
+#[api(
+    properties: {
+        "id": {
+            schema: VIEW_ID_SCHEMA,
+        },
+        "include": {
+            schema: FILTER_RULE_LIST_SCHEMA,
+            optional: true,
+        },
+        "exclude": {
+            schema: FILTER_RULE_LIST_SCHEMA,
+            optional: true,
+        }
+    }
+)]
+#[derive(Clone, Debug, Default, Deserialize, Serialize, Updater, PartialEq)]
+#[serde(rename_all = "kebab-case")]
+/// View definition
+pub struct ViewConfig {
+    /// View name.
+    #[updater(skip)]
+    pub id: String,
+
+    /// List of includes.
+    #[serde(default, skip_serializing_if = "Vec::is_empty")]
+    #[updater(serde(skip_serializing_if = "Option::is_none"))]
+    pub include: Vec<FilterRule>,
+
+    /// List of excludes.
+    #[serde(default, skip_serializing_if = "Vec::is_empty")]
+    #[updater(serde(skip_serializing_if = "Option::is_none"))]
+    pub exclude: Vec<FilterRule>,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
+#[serde(rename_all = "kebab-case")]
+/// Enum for the different sections in the 'views.cfg' file.
+pub enum ViewConfigEntry {
+    /// 'view' section
+    View(ViewConfig),
+}
+
+const VIEW_SECTION_NAME: &str = "view";
+
+impl ApiSectionDataEntry for ViewConfigEntry {
+    fn section_config() -> &'static SectionConfig {
+        static CONFIG: OnceLock<SectionConfig> = OnceLock::new();
+
+        CONFIG.get_or_init(|| {
+            let mut this = SectionConfig::new(&VIEW_ID_SCHEMA);
+
+            this.register_plugin(SectionConfigPlugin::new(
+                VIEW_SECTION_NAME.into(),
+                Some("id".to_string()),
+                ViewConfig::API_SCHEMA.unwrap_object_schema(),
+            ));
+            this
+        })
+    }
+
+    fn section_type(&self) -> &'static str {
+        match self {
+            ViewConfigEntry::View(_) => VIEW_SECTION_NAME,
+        }
+    }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+/// Filter rule for includes/excludes.
+pub enum FilterRule {
+    /// Match a resource type.
+    ResourceType(ResourceType),
+    /// Match a resource pools (for PVE guests).
+    ResourcePool(String),
+    /// Match a (global) resource ID, e.g. 'remote/<remote>/guest/<vmid>'.
+    ResourceId(String),
+    /// Match a tag (for PVE guests).
+    Tag(String),
+    /// Match a remote.
+    Remote(String),
+}
+
+impl FromStr for FilterRule {
+    type Err = anyhow::Error;
+
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
+        Ok(match s.split_once(':') {
+            Some(("resource-type", value)) => FilterRule::ResourceType(value.parse()?),
+            Some(("resource-pool", value)) => {
+                if !PROXMOX_SAFE_ID_REGEX.is_match(value) {
+                    bail!("invalid resource-pool value: {value}");
+                }
+                FilterRule::ResourcePool(value.to_string())
+            }
+            Some(("resource-id", value)) => {
+                if !GLOBAL_RESOURCE_ID_REGEX.is_match(value) {
+                    bail!("invalid resource-id value: {value}");
+                }
+
+                FilterRule::ResourceId(value.to_string())
+            }
+            Some(("tag", value)) => {
+                if !PROXMOX_SAFE_ID_REGEX.is_match(value) {
+                    bail!("invalid tag value: {value}");
+                }
+                FilterRule::Tag(value.to_string())
+            }
+            Some(("remote", value)) => {
+                let _ = REMOTE_ID_SCHEMA.parse_simple_value(value)?;
+                FilterRule::Remote(value.to_string())
+            }
+            Some((ty, _)) => bail!("invalid type: {ty}"),
+            None => bail!("invalid filter rule: {s}"),
+        })
+    }
+}
+
+// used for serializing below, caution!
+impl Display for FilterRule {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            FilterRule::ResourceType(resource_type) => write!(f, "resource-type:{resource_type}"),
+            FilterRule::ResourcePool(pool) => write!(f, "resource-pool:{pool}"),
+            FilterRule::ResourceId(id) => write!(f, "resource-id:{id}"),
+            FilterRule::Tag(tag) => write!(f, "tag:{tag}"),
+            FilterRule::Remote(remote) => write!(f, "remote:{remote}"),
+        }
+    }
+}
+
+proxmox_serde::forward_deserialize_to_from_str!(FilterRule);
+proxmox_serde::forward_serialize_to_display!(FilterRule);
+
+fn verify_filter_rule(input: &str) -> Result<(), anyhow::Error> {
+    FilterRule::from_str(input).map(|_| ())
+}
+
+#[cfg(test)]
+mod test {
+    use anyhow::Error;
+
+    use crate::views::FilterRule;
+
+    fn parse_and_check_display(input: &str) -> Result<bool, Error> {
+        let rule: FilterRule = input.parse()?;
+
+        Ok(input == format!("{rule}"))
+    }
+
+    #[test]
+    fn test_filter_rule() {
+        assert!(parse_and_check_display("abc").is_err());
+        assert!(parse_and_check_display("abc:").is_err());
+
+        assert!(parse_and_check_display("resource-type:").is_err());
+        assert!(parse_and_check_display("resource-type:lxc").unwrap());
+        assert!(parse_and_check_display("resource-type:qemu").unwrap());
+        assert!(parse_and_check_display("resource-type:abc").is_err());
+
+        assert!(parse_and_check_display("resource-pool:").is_err());
+        assert!(parse_and_check_display("resource-pool:somepool").unwrap());
+
+        assert!(parse_and_check_display("resource-id:").is_err());
+        assert!(parse_and_check_display("resource-id:remote/someremote/guest/100").unwrap());
+        assert!(parse_and_check_display("resource-id:remote").is_err());
+
+        assert!(parse_and_check_display("tag:").is_err());
+        assert!(parse_and_check_display("tag:sometag").unwrap());
+
+        assert!(parse_and_check_display("remote:someremote").unwrap());
+        assert!(parse_and_check_display("remote:a").is_err());
+    }
+}
-- 
2.47.3



_______________________________________________
pdm-devel mailing list
pdm-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pdm-devel

  reply	other threads:[~2025-11-13 12:16 UTC|newest]

Thread overview: 15+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-11-13 12:16 [pdm-devel] [PATCH datacenter-manager v5 00/11] backend implementation for view filters Lukas Wagner
2025-11-13 12:16 ` Lukas Wagner [this message]
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 02/11] pdm-config: views: add support for views Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 03/11] acl: add '/view' and '/view/{view-id}' as allowed ACL paths Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 04/11] views: add implementation for view resource filtering Lukas Wagner
2025-11-13 19:54   ` Thomas Lamprecht
2025-11-14 13:25     ` Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 05/11] api: resources: list: add support for view parameter Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 06/11] api: resources: top entities: " Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 07/11] api: resources: status: " Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 08/11] api: subscription " Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 09/11] api: remote-tasks: " Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 10/11] pdm-client: resource list: add " Lukas Wagner
2025-11-13 12:16 ` [pdm-devel] [PATCH datacenter-manager v5 11/11] pdm-client: top entities: " Lukas Wagner
2025-11-13 14:42 ` [pdm-devel] applied: [PATCH datacenter-manager v5 00/11] backend implementation for view filters Dominik Csapak

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20251113121644.236005-2-l.wagner@proxmox.com \
    --to=l.wagner@proxmox.com \
    --cc=pdm-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal