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 A41271FF0C0 for ; Wed, 18 Nov 2026 10:53:44 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id A31BB2175B; Wed, 18 Nov 2026 10:45:17 +0100 (CET) From: Lukas Wagner To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox-backup v2 46/63] notifications: adapt to proxmox-notify API changes Date: Wed, 18 Nov 2026 10:43:30 +0100 Message-ID: <20261118094348.273646-47-l.wagner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261118094348.273646-1-l.wagner@proxmox.com> References: <20261118094348.273646-1-l.wagner@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1794995040854 X-SPAM-LEVEL: Spam detection results: 0 AWL -0.814 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) KAM_MAILER 2 Automated Mailer Tag Left in Email 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: QWCZC2GHQ7VUYWBXXMH7IWGML4ZBPONI X-Message-ID-Hash: QWCZC2GHQ7VUYWBXXMH7IWGML4ZBPONI X-MailFrom: l.wagner@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: proxmox-notify no longer keeps a global context. Instead, a Context instance is passed explicitly when parsing the configuration and sending notifications. Keep a lazily initialized PBS context in server::notifications and drop the explicit init() calls from the daemons and proxmox-daily-update. Notifications are now created via Notification::template_builder and carry an explicit recipient: either a set of email addresses for datastores and tape jobs in legacy-sendmail mode, or the matchers when using the notification system. Determining the recipient, including the legacy notify=never/error filtering, is moved into shared helpers. Since legacy-sendmail notifications are no longer sent by calling the sendmail endpoint directly, they now take the same path as all other notifications, including being queued when sent from an unprivileged process. The remaining changes are mechanical: API types now live in proxmox_notify::api_types, the Deleteable* types were renamed to Deletable*, and config digests are passed as ConfigDigest instead of hex-encoded strings. The 'api-types', 'api-impl' and 'send-impl' features of proxmox-notify are enabled accordingly. This changes should not have any observable effect for the user, with one tiny exception. Now, notifications sent via the 'legacy-sendmail' mode still read and parse the config, due to the unified code paths while sending. As a result, unlike before, a broken notification config would also cause a failed delivery for 'legacy-sendmail' notifications. Signed-off-by: Lukas Wagner --- Cargo.toml | 2 +- pbs-config/Cargo.toml | 10 +- pbs-config/src/notifications.rs | 10 +- src/api2/config/notifications/gotify.rs | 31 +- src/api2/config/notifications/matchers.rs | 29 +- src/api2/config/notifications/sendmail.rs | 29 +- src/api2/config/notifications/smtp.rs | 29 +- src/api2/config/notifications/targets.rs | 13 +- src/api2/config/notifications/webhook.rs | 29 +- src/bin/docgen.rs | 7 +- src/bin/proxmox-backup-api.rs | 1 - src/bin/proxmox-backup-manager.rs | 1 - src/bin/proxmox-backup-proxy.rs | 1 - src/bin/proxmox-daily-update.rs | 3 - .../notifications/gotify.rs | 2 +- .../notifications/matchers.rs | 2 +- .../notifications/sendmail.rs | 2 +- .../notifications/smtp.rs | 2 +- .../notifications/webhook.rs | 2 +- src/server/notifications/mod.rs | 449 ++++++++---------- 20 files changed, 301 insertions(+), 353 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 67245fede..b83924a85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -230,7 +230,7 @@ proxmox-ldap.workspace = true proxmox-metrics.workspace = true proxmox-network-api = { workspace = true, features = [ "impl" ] } proxmox-network-types.workspace = true -proxmox-notify = { workspace = true, features = [ "pbs-context", "legacy-matchers" ] } +proxmox-notify = { workspace = true, features = [ "pbs-context", "legacy-matchers", "api-impl", "send-impl", "api-types" ]} proxmox-openid.workspace = true proxmox-product-config.workspace = true proxmox-parallel-handler.workspace = true diff --git a/pbs-config/Cargo.toml b/pbs-config/Cargo.toml index dfc1acf61..8cc9102a2 100644 --- a/pbs-config/Cargo.toml +++ b/pbs-config/Cargo.toml @@ -21,7 +21,15 @@ serde_json.workspace = true proxmox-http.workspace = true proxmox-lang.workspace = true -proxmox-notify.workspace = true +proxmox-notify = { + workspace = true, + features = [ + "pbs-context", + "legacy-matchers", + "api-impl", + "api-types", + ] +} proxmox-router = { workspace = true, default-features = false } proxmox-product-config.workspace = true proxmox-s3-client.workspace = true diff --git a/pbs-config/src/notifications.rs b/pbs-config/src/notifications.rs index 53555bda9..9031feafb 100644 --- a/pbs-config/src/notifications.rs +++ b/pbs-config/src/notifications.rs @@ -22,19 +22,23 @@ pub fn lock_config() -> Result { } /// Load notification config. -pub fn config() -> Result { +pub fn config(context: &proxmox_notify::Context) -> Result { let content = proxmox_sys::fs::file_read_optional_string(NOTIFICATION_CONFIG_PATH)?.unwrap_or_default(); let priv_content = proxmox_sys::fs::file_read_optional_string(NOTIFICATION_PRIV_CONFIG_PATH)? .unwrap_or_default(); - Ok(Config::new(&content, &priv_content)?) + Ok(Config::parse_section_config( + &content, + &priv_content, + Some(context.default_config()), + )?) } /// Save notification config. pub fn save_config(config: Config) -> Result<(), Error> { - let (cfg, priv_cfg) = config.write()?; + let (cfg, priv_cfg) = config.to_section_config()?; replace_privileged_config(NOTIFICATION_CONFIG_PATH, cfg.as_bytes())?; proxmox_product_config::replace_secret_config( NOTIFICATION_PRIV_CONFIG_PATH, diff --git a/src/api2/config/notifications/gotify.rs b/src/api2/config/notifications/gotify.rs index 1f14b377b..99f93cb77 100644 --- a/src/api2/config/notifications/gotify.rs +++ b/src/api2/config/notifications/gotify.rs @@ -1,16 +1,18 @@ use anyhow::Error; use serde_json::Value; -use proxmox_notify::endpoints::gotify::{ - DeleteableGotifyProperty, GotifyConfig, GotifyConfigUpdater, GotifyPrivateConfig, - GotifyPrivateConfigUpdater, +use proxmox_config_digest::ConfigDigest; +use proxmox_notify::api_types::{ + DeletableGotifyProperty, ENTITY_NAME_SCHEMA, GotifyConfig, GotifyConfigUpdater, + GotifyPrivateConfig, GotifyPrivateConfigUpdater, }; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; use proxmox_router::{Permission, Router, RpcEnvironment}; use proxmox_schema::api; use pbs_api_types::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY, PROXMOX_CONFIG_DIGEST_SCHEMA}; +use crate::server; + #[api( protected: true, input: { @@ -30,7 +32,7 @@ pub fn list_endpoints( _param: Value, _rpcenv: &mut dyn RpcEnvironment, ) -> Result, Error> { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let endpoints = proxmox_notify::api::gotify::get_endpoints(&config)?; @@ -53,10 +55,10 @@ pub fn list_endpoints( )] /// Get a gotify endpoint. pub fn get_endpoint(name: String, rpcenv: &mut dyn RpcEnvironment) -> Result { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let endpoint = proxmox_notify::api::gotify::get_endpoint(&config, &name)?; - rpcenv["digest"] = hex::encode(config.digest()).into(); + rpcenv["digest"] = config.digest().to_hex().into(); Ok(endpoint) } @@ -85,7 +87,7 @@ pub fn add_endpoint( _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; let private_endpoint_config = GotifyPrivateConfig { name: endpoint.name.clone(), token, @@ -117,7 +119,7 @@ pub fn add_endpoint( type: Array, optional: true, items: { - type: DeleteableGotifyProperty, + type: DeletableGotifyProperty, } }, digest: { @@ -135,13 +137,12 @@ pub fn update_endpoint( name: String, updater: GotifyConfigUpdater, token: Option, - delete: Option>, - digest: Option, + delete: Option>, + digest: Option, _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; - let digest = digest.map(hex::decode).transpose()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::gotify::update_endpoint( &mut config, @@ -149,7 +150,7 @@ pub fn update_endpoint( updater, GotifyPrivateConfigUpdater { token }, delete.as_deref(), - digest.as_deref(), + digest, )?; pbs_config::notifications::save_config(config)?; @@ -172,7 +173,7 @@ pub fn update_endpoint( /// Delete gotify endpoint. pub fn delete_endpoint(name: String, _rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::gotify::delete_gotify_endpoint(&mut config, &name)?; pbs_config::notifications::save_config(config)?; diff --git a/src/api2/config/notifications/matchers.rs b/src/api2/config/notifications/matchers.rs index 504d26d40..d639ef36d 100644 --- a/src/api2/config/notifications/matchers.rs +++ b/src/api2/config/notifications/matchers.rs @@ -1,13 +1,17 @@ use anyhow::Error; use serde_json::Value; -use proxmox_notify::matcher::{DeleteableMatcherProperty, MatcherConfig, MatcherConfigUpdater}; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; +use proxmox_config_digest::ConfigDigest; +use proxmox_notify::api_types::{ + DeletableMatcherProperty, ENTITY_NAME_SCHEMA, MatcherConfig, MatcherConfigUpdater, +}; use proxmox_router::{Permission, Router, RpcEnvironment}; use proxmox_schema::api; use pbs_api_types::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY, PROXMOX_CONFIG_DIGEST_SCHEMA}; +use crate::server; + #[api( protected: true, input: { @@ -27,7 +31,7 @@ pub fn list_matchers( _param: Value, _rpcenv: &mut dyn RpcEnvironment, ) -> Result, Error> { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let matchers = proxmox_notify::api::matcher::get_matchers(&config)?; @@ -59,7 +63,7 @@ pub fn get_matcher( migrate_to_expression: bool, rpcenv: &mut dyn RpcEnvironment, ) -> Result { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let matcher = if migrate_to_expression { proxmox_notify::api::matcher::get_matcher_as_expression(&config, &name)? @@ -67,7 +71,7 @@ pub fn get_matcher( proxmox_notify::api::matcher::get_matcher(&config, &name)? }; - rpcenv["digest"] = hex::encode(config.digest()).into(); + rpcenv["digest"] = config.digest().to_hex().into(); Ok(matcher) } @@ -89,7 +93,7 @@ pub fn get_matcher( /// Add a new notification matcher. pub fn add_matcher(matcher: MatcherConfig, _rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::matcher::add_matcher(&mut config, matcher)?; @@ -113,7 +117,7 @@ pub fn add_matcher(matcher: MatcherConfig, _rpcenv: &mut dyn RpcEnvironment) -> type: Array, optional: true, items: { - type: DeleteableMatcherProperty, + type: DeletableMatcherProperty, } }, digest: { @@ -130,20 +134,19 @@ pub fn add_matcher(matcher: MatcherConfig, _rpcenv: &mut dyn RpcEnvironment) -> pub fn update_matcher( name: String, updater: MatcherConfigUpdater, - delete: Option>, - digest: Option, + delete: Option>, + digest: Option, _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; - let digest = digest.map(hex::decode).transpose()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::matcher::update_matcher( &mut config, &name, updater, delete.as_deref(), - digest.as_deref(), + digest, )?; pbs_config::notifications::save_config(config)?; @@ -166,7 +169,7 @@ pub fn update_matcher( /// Delete notification matcher. pub fn delete_matcher(name: String, _rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::matcher::delete_matcher(&mut config, &name)?; pbs_config::notifications::save_config(config)?; diff --git a/src/api2/config/notifications/sendmail.rs b/src/api2/config/notifications/sendmail.rs index b8ce6b2b1..875784afc 100644 --- a/src/api2/config/notifications/sendmail.rs +++ b/src/api2/config/notifications/sendmail.rs @@ -1,15 +1,17 @@ use anyhow::Error; use serde_json::Value; -use proxmox_notify::endpoints::sendmail::{ - DeleteableSendmailProperty, SendmailConfig, SendmailConfigUpdater, +use proxmox_config_digest::ConfigDigest; +use proxmox_notify::api_types::{ + DeletableSendmailProperty, ENTITY_NAME_SCHEMA, SendmailConfig, SendmailConfigUpdater, }; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; use proxmox_router::{Permission, Router, RpcEnvironment}; use proxmox_schema::api; use pbs_api_types::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY, PROXMOX_CONFIG_DIGEST_SCHEMA}; +use crate::server; + #[api( protected: true, input: { @@ -29,7 +31,7 @@ pub fn list_endpoints( _param: Value, _rpcenv: &mut dyn RpcEnvironment, ) -> Result, Error> { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let endpoints = proxmox_notify::api::sendmail::get_endpoints(&config)?; @@ -55,10 +57,10 @@ pub fn get_endpoint( name: String, rpcenv: &mut dyn RpcEnvironment, ) -> Result { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let endpoint = proxmox_notify::api::sendmail::get_endpoint(&config, &name)?; - rpcenv["digest"] = hex::encode(config.digest()).into(); + rpcenv["digest"] = config.digest().to_hex().into(); Ok(endpoint) } @@ -83,7 +85,7 @@ pub fn add_endpoint( _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::sendmail::add_endpoint(&mut config, endpoint)?; @@ -107,7 +109,7 @@ pub fn add_endpoint( type: Array, optional: true, items: { - type: DeleteableSendmailProperty, + type: DeletableSendmailProperty, } }, digest: { @@ -124,20 +126,19 @@ pub fn add_endpoint( pub fn update_endpoint( name: String, updater: SendmailConfigUpdater, - delete: Option>, - digest: Option, + delete: Option>, + digest: Option, _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; - let digest = digest.map(hex::decode).transpose()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::sendmail::update_endpoint( &mut config, &name, updater, delete.as_deref(), - digest.as_deref(), + digest, )?; pbs_config::notifications::save_config(config)?; @@ -160,7 +161,7 @@ pub fn update_endpoint( /// Delete sendmail endpoint. pub fn delete_endpoint(name: String, _rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::sendmail::delete_endpoint(&mut config, &name)?; pbs_config::notifications::save_config(config)?; diff --git a/src/api2/config/notifications/smtp.rs b/src/api2/config/notifications/smtp.rs index 8df2ab18c..6d9313403 100644 --- a/src/api2/config/notifications/smtp.rs +++ b/src/api2/config/notifications/smtp.rs @@ -1,16 +1,18 @@ use anyhow::Error; use serde_json::Value; -use proxmox_notify::endpoints::smtp::{ - DeleteableSmtpProperty, SmtpConfig, SmtpConfigUpdater, SmtpPrivateConfig, +use proxmox_config_digest::ConfigDigest; +use proxmox_notify::api_types::{ + DeletableSmtpProperty, ENTITY_NAME_SCHEMA, SmtpConfig, SmtpConfigUpdater, SmtpPrivateConfig, SmtpPrivateConfigUpdater, }; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; use proxmox_router::{Permission, Router, RpcEnvironment}; use proxmox_schema::api; use pbs_api_types::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY, PROXMOX_CONFIG_DIGEST_SCHEMA}; +use crate::server; + #[api( protected: true, input: { @@ -30,7 +32,7 @@ pub fn list_endpoints( _param: Value, _rpcenv: &mut dyn RpcEnvironment, ) -> Result, Error> { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let endpoints = proxmox_notify::api::smtp::get_endpoints(&config)?; @@ -53,10 +55,10 @@ pub fn list_endpoints( )] /// Get a smtp endpoint. pub fn get_endpoint(name: String, rpcenv: &mut dyn RpcEnvironment) -> Result { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let endpoint = proxmox_notify::api::smtp::get_endpoint(&config, &name)?; - rpcenv["digest"] = hex::encode(config.digest()).into(); + rpcenv["digest"] = config.digest().to_hex().into(); Ok(endpoint) } @@ -86,7 +88,7 @@ pub fn add_endpoint( _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; let private_endpoint_config = SmtpPrivateConfig { name: endpoint.name.clone(), password, @@ -118,7 +120,7 @@ pub fn add_endpoint( type: Array, optional: true, items: { - type: DeleteableSmtpProperty, + type: DeletableSmtpProperty, } }, digest: { @@ -136,13 +138,12 @@ pub fn update_endpoint( name: String, updater: SmtpConfigUpdater, password: Option, - delete: Option>, - digest: Option, + delete: Option>, + digest: Option, _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; - let digest = digest.map(hex::decode).transpose()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::smtp::update_endpoint( &mut config, @@ -150,7 +151,7 @@ pub fn update_endpoint( updater, SmtpPrivateConfigUpdater { password }, delete.as_deref(), - digest.as_deref(), + digest, )?; pbs_config::notifications::save_config(config)?; @@ -173,7 +174,7 @@ pub fn update_endpoint( /// Delete smtp endpoint. pub fn delete_endpoint(name: String, _rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::smtp::delete_endpoint(&mut config, &name)?; pbs_config::notifications::save_config(config)?; diff --git a/src/api2/config/notifications/targets.rs b/src/api2/config/notifications/targets.rs index ee9f2b26d..bf0cfa3de 100644 --- a/src/api2/config/notifications/targets.rs +++ b/src/api2/config/notifications/targets.rs @@ -1,14 +1,15 @@ use anyhow::Error; use serde_json::Value; -use proxmox_notify::api::Target; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; +use proxmox_notify::api_types::{ENTITY_NAME_SCHEMA, Target}; use proxmox_router::{Permission, Router, RpcEnvironment, SubdirMap, list_subdirs_api_method}; use proxmox_schema::api; use proxmox_sortable_macro::sortable; use pbs_api_types::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY}; +use crate::server; + #[api( protected: true, input: { @@ -25,7 +26,7 @@ use pbs_api_types::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY}; )] /// List all notification targets. pub fn list_targets(_param: Value, _rpcenv: &mut dyn RpcEnvironment) -> Result, Error> { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let targets = proxmox_notify::api::get_targets(&config)?; Ok(targets) @@ -46,8 +47,10 @@ pub fn list_targets(_param: Value, _rpcenv: &mut dyn RpcEnvironment) -> Result Result<(), Error> { - let config = pbs_config::notifications::config()?; - proxmox_notify::api::common::test_target(&config, &name)?; + let context = server::notifications::context(); + + let config = pbs_config::notifications::config(context)?; + proxmox_notify::test_target(context, &config, &name)?; Ok(()) } diff --git a/src/api2/config/notifications/webhook.rs b/src/api2/config/notifications/webhook.rs index 4a0400245..76c5a4eea 100644 --- a/src/api2/config/notifications/webhook.rs +++ b/src/api2/config/notifications/webhook.rs @@ -1,15 +1,17 @@ use anyhow::Error; use serde_json::Value; -use proxmox_notify::endpoints::webhook::{ - DeleteableWebhookProperty, WebhookConfig, WebhookConfigUpdater, +use proxmox_config_digest::ConfigDigest; +use proxmox_notify::api_types::{ + DeletableWebhookProperty, ENTITY_NAME_SCHEMA, WebhookConfig, WebhookConfigUpdater, }; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; use proxmox_router::{Permission, Router, RpcEnvironment}; use proxmox_schema::api; use pbs_api_types::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY, PROXMOX_CONFIG_DIGEST_SCHEMA}; +use crate::server; + #[api( protected: true, input: { @@ -29,7 +31,7 @@ pub fn list_endpoints( _param: Value, _rpcenv: &mut dyn RpcEnvironment, ) -> Result, Error> { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let endpoints = proxmox_notify::api::webhook::get_endpoints(&config)?; @@ -52,10 +54,10 @@ pub fn list_endpoints( )] /// Get a webhook endpoint. pub fn get_endpoint(name: String, rpcenv: &mut dyn RpcEnvironment) -> Result { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(server::notifications::context())?; let endpoint = proxmox_notify::api::webhook::get_endpoint(&config, &name)?; - rpcenv["digest"] = hex::encode(config.digest()).into(); + rpcenv["digest"] = config.digest().to_hex().into(); Ok(endpoint) } @@ -80,7 +82,7 @@ pub fn add_endpoint( _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::webhook::add_endpoint(&mut config, endpoint)?; @@ -104,7 +106,7 @@ pub fn add_endpoint( type: Array, optional: true, items: { - type: DeleteableWebhookProperty, + type: DeletableWebhookProperty, } }, digest: { @@ -121,20 +123,19 @@ pub fn add_endpoint( pub fn update_endpoint( name: String, updater: WebhookConfigUpdater, - delete: Option>, - digest: Option, + delete: Option>, + digest: Option, _rpcenv: &mut dyn RpcEnvironment, ) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; - let digest = digest.map(hex::decode).transpose()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::webhook::update_endpoint( &mut config, &name, updater, delete.as_deref(), - digest.as_deref(), + digest, )?; pbs_config::notifications::save_config(config)?; @@ -157,7 +158,7 @@ pub fn update_endpoint( /// Delete webhook endpoint. pub fn delete_endpoint(name: String, _rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> { let _lock = pbs_config::notifications::lock_config()?; - let mut config = pbs_config::notifications::config()?; + let mut config = pbs_config::notifications::config(server::notifications::context())?; proxmox_notify::api::webhook::delete_endpoint(&mut config, &name)?; pbs_config::notifications::save_config(config)?; diff --git a/src/bin/docgen.rs b/src/bin/docgen.rs index ad85b9e55..3bea65854 100644 --- a/src/bin/docgen.rs +++ b/src/bin/docgen.rs @@ -3,6 +3,7 @@ use anyhow::{Error, bail}; use proxmox_schema::ApiType; use proxmox_schema::format::dump_enum_properties; use proxmox_section_config::dump_section_config; +use proxmox_section_config::typed::ApiSectionDataEntry; use pbs_api_types::PRIVILEGES; @@ -29,9 +30,11 @@ fn main() -> Result<(), Error> { "apidata.js" => generate_api_tree(), "datastore.cfg" => dump_section_config(&pbs_config::datastore::CONFIG), "domains.cfg" => dump_section_config(&pbs_config::domains::CONFIG), - "notifications.cfg" => dump_section_config(proxmox_notify::config::config_parser()), + "notifications.cfg" => { + dump_section_config(proxmox_notify::ConfigEntity::section_config()) + } "notifications-priv.cfg" => { - dump_section_config(proxmox_notify::config::private_config_parser()) + dump_section_config(proxmox_notify::PrivateConfigEntity::section_config()) } "tape.cfg" => dump_section_config(&pbs_config::drive::CONFIG), "tape-job.cfg" => dump_section_config(&pbs_config::tape_job::CONFIG), diff --git a/src/bin/proxmox-backup-api.rs b/src/bin/proxmox-backup-api.rs index 710a70042..aad3fabc3 100644 --- a/src/bin/proxmox-backup-api.rs +++ b/src/bin/proxmox-backup-api.rs @@ -77,7 +77,6 @@ async fn run() -> Result<(), Error> { let _ = csrf_secret(); // load with lazy_static proxmox_backup::auth_helpers::setup_auth_context(true); - proxmox_backup::server::notifications::init()?; let mut command_sock = proxmox_daemon::command_socket::CommandSocket::new(backup_user.gid); proxmox_acme_api::init(configdir!("/acme"), true)?; diff --git a/src/bin/proxmox-backup-manager.rs b/src/bin/proxmox-backup-manager.rs index 46bbc514c..ae58339fb 100644 --- a/src/bin/proxmox-backup-manager.rs +++ b/src/bin/proxmox-backup-manager.rs @@ -669,7 +669,6 @@ async fn run() -> Result<(), Error> { .stderr_on_no_workertask() .tasklog_pbs() .init()?; - proxmox_backup::server::notifications::init()?; proxmox_product_config::init(pbs_config::backup_user()?, pbs_config::priv_user()?); proxmox_acme_api::init(configdir!("/acme"), false)?; diff --git a/src/bin/proxmox-backup-proxy.rs b/src/bin/proxmox-backup-proxy.rs index 22abfdbdb..a550f285b 100644 --- a/src/bin/proxmox-backup-proxy.rs +++ b/src/bin/proxmox-backup-proxy.rs @@ -186,7 +186,6 @@ async fn run() -> Result<(), Error> { .init()?; proxmox_backup::auth_helpers::setup_auth_context(false); - proxmox_backup::server::notifications::init()?; metric_collection::init()?; proxmox_acme_api::init(configdir!("/acme"), false)?; diff --git a/src/bin/proxmox-daily-update.rs b/src/bin/proxmox-daily-update.rs index 597722497..4f5e39c8f 100644 --- a/src/bin/proxmox-daily-update.rs +++ b/src/bin/proxmox-daily-update.rs @@ -1,7 +1,6 @@ use anyhow::Error; use serde_json::json; -use proxmox_notify::context::pbs::PBS_CONTEXT; use proxmox_router::{ApiHandler, RpcEnvironment, cli::*}; use proxmox_subscription::SubscriptionStatus; @@ -102,8 +101,6 @@ async fn run(rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> { proxmox_rest_server::register_task_control_commands(&mut command_sock)?; command_sock.spawn(proxmox_rest_server::last_worker_future())?; - proxmox_notify::context::set_context(&PBS_CONTEXT); - proxmox_acme_api::init(configdir!("/acme"), false)?; do_update(rpcenv).await diff --git a/src/bin/proxmox_backup_manager/notifications/gotify.rs b/src/bin/proxmox_backup_manager/notifications/gotify.rs index 0a6ebe053..43fe64dfd 100644 --- a/src/bin/proxmox_backup_manager/notifications/gotify.rs +++ b/src/bin/proxmox_backup_manager/notifications/gotify.rs @@ -1,7 +1,7 @@ use anyhow::Error; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; use serde_json::Value; +use proxmox_notify::api_types::ENTITY_NAME_SCHEMA; use proxmox_router::{ApiHandler, RpcEnvironment, cli::*}; use proxmox_schema::api; diff --git a/src/bin/proxmox_backup_manager/notifications/matchers.rs b/src/bin/proxmox_backup_manager/notifications/matchers.rs index 4d648bcbb..37823317d 100644 --- a/src/bin/proxmox_backup_manager/notifications/matchers.rs +++ b/src/bin/proxmox_backup_manager/notifications/matchers.rs @@ -1,7 +1,7 @@ use anyhow::Error; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; use serde_json::Value; +use proxmox_notify::api_types::ENTITY_NAME_SCHEMA; use proxmox_router::{ApiHandler, RpcEnvironment, cli::*}; use proxmox_schema::api; diff --git a/src/bin/proxmox_backup_manager/notifications/sendmail.rs b/src/bin/proxmox_backup_manager/notifications/sendmail.rs index a15b73a7e..07c9d16d6 100644 --- a/src/bin/proxmox_backup_manager/notifications/sendmail.rs +++ b/src/bin/proxmox_backup_manager/notifications/sendmail.rs @@ -1,7 +1,7 @@ use anyhow::Error; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; use serde_json::Value; +use proxmox_notify::api_types::ENTITY_NAME_SCHEMA; use proxmox_router::{ApiHandler, RpcEnvironment, cli::*}; use proxmox_schema::api; diff --git a/src/bin/proxmox_backup_manager/notifications/smtp.rs b/src/bin/proxmox_backup_manager/notifications/smtp.rs index 3c1d9f762..1bce6498b 100644 --- a/src/bin/proxmox_backup_manager/notifications/smtp.rs +++ b/src/bin/proxmox_backup_manager/notifications/smtp.rs @@ -1,7 +1,7 @@ use anyhow::Error; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; use serde_json::Value; +use proxmox_notify::api_types::ENTITY_NAME_SCHEMA; use proxmox_router::{ApiHandler, RpcEnvironment, cli::*}; use proxmox_schema::api; diff --git a/src/bin/proxmox_backup_manager/notifications/webhook.rs b/src/bin/proxmox_backup_manager/notifications/webhook.rs index 302940edf..8810f581c 100644 --- a/src/bin/proxmox_backup_manager/notifications/webhook.rs +++ b/src/bin/proxmox_backup_manager/notifications/webhook.rs @@ -1,7 +1,7 @@ use anyhow::Error; use serde_json::Value; -use proxmox_notify::schema::ENTITY_NAME_SCHEMA; +use proxmox_notify::api_types::ENTITY_NAME_SCHEMA; use proxmox_router::{ApiHandler, RpcEnvironment, cli::*}; use proxmox_schema::api; diff --git a/src/server/notifications/mod.rs b/src/server/notifications/mod.rs index 21bec254b..1e71cd39d 100644 --- a/src/server/notifications/mod.rs +++ b/src/server/notifications/mod.rs @@ -1,12 +1,13 @@ -use std::collections::HashMap; use std::path::Path; +use std::sync::OnceLock; use std::time::{Duration, Instant}; use anyhow::Error; use const_format::concatcp; use nix::unistd::Uid; -use proxmox_notify::context::pbs::PBS_CONTEXT; +use proxmox_notify::context::pbs::PBSContext; +use proxmox_notify::{Context, EmailRecipient, Notification, Recipient, Severity}; use proxmox_schema::ApiType; use proxmox_sys::fs::{CreateOptions, create_path}; @@ -15,8 +16,6 @@ use pbs_api_types::{ APTUpdateInfo, DataStoreConfig, DatastoreNotify, GarbageCollectionStatus, NotificationMode, Notify, SyncJobConfig, TapeBackupJobSetup, User, Userid, VerificationJobConfig, }; -use proxmox_notify::endpoints::sendmail::{SendmailConfig, SendmailEndpoint}; -use proxmox_notify::{Endpoint, Notification, Severity}; const SPOOL_DIR: &str = concatcp!(pbs_buildcfg::PROXMOX_BACKUP_STATE_DIR, "/notifications"); @@ -29,10 +28,11 @@ use template_data::{ TapeLoadTemplateData, VerifyErrTemplateData, VerifyOkTemplateData, }; -/// Initialize the notification system by setting context in proxmox_notify -pub fn init() -> Result<(), Error> { - proxmox_notify::context::set_context(&PBS_CONTEXT); - Ok(()) +static CONTEXT: OnceLock = OnceLock::new(); + +/// Get a reference to the static notification context for PBS. +pub fn context() -> &'static Context { + CONTEXT.get_or_init(|| Context::new(PBSContext)) } /// Create the directory which will be used to temporarily store notifications @@ -78,10 +78,12 @@ async fn send_queued_notifications() -> Result<(), Error> { // Make sure that we send the oldest notification first notifications.sort_unstable_by_key(|n| n.timestamp()); + let context = context(); + let res = tokio::task::spawn_blocking(move || { - let config = pbs_config::notifications::config()?; + let config = pbs_config::notifications::config(context)?; for notification in notifications { - if let Err(err) = proxmox_notify::api::common::send(&config, ¬ification) { + if let Err(err) = proxmox_notify::send(context, &config, ¬ification) { log::error!("failed to send notification: {err}"); } } @@ -111,9 +113,11 @@ pub async fn notification_worker() { } fn send_notification(notification: Notification) -> Result<(), Error> { + let context = context(); + if nix::unistd::ROOT == Uid::current() { - let config = pbs_config::notifications::config()?; - proxmox_notify::api::common::send(&config, ¬ification)?; + let config = pbs_config::notifications::config(context)?; + proxmox_notify::send(context, &config, ¬ification)?; } else { let ser = serde_json::to_vec(¬ification)?; let path = Path::new(SPOOL_DIR).join(format!("{id}.json", id = notification.id())); @@ -129,19 +133,6 @@ fn send_notification(notification: Notification) -> Result<(), Error> { Ok(()) } -fn send_sendmail_legacy_notification(notification: Notification, email: &str) -> Result<(), Error> { - let endpoint = SendmailEndpoint { - config: SendmailConfig { - mailto: vec![email.into()], - ..Default::default() - }, - }; - - endpoint.send(¬ification)?; - - Ok(()) -} - /// Summary of a successful Tape Job #[derive(Default)] pub struct TapeBackupJobSummary { @@ -158,50 +149,33 @@ pub fn send_gc_status( status: &GarbageCollectionStatus, result: &Result<(), Error>, ) -> Result<(), Error> { - let metadata = HashMap::from([ - ("datastore".into(), datastore.into()), - ("hostname".into(), proxmox_sys::nodename().into()), - ("type".into(), "gc".into()), - ]); + let Some(recipient) = + datastore_notification_recipient(datastore, |n| n.gc, Notify::Always, result.is_ok()) + else { + return Ok(()); + }; - let notification = match result { + let builder = match result { Ok(()) => { let template_data = GcOkTemplateData::new(datastore.to_string(), status); - Notification::from_template( - Severity::Info, - "gc-ok", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("gc-ok", serde_json::to_value(template_data)?) + .severity(Severity::Info) } Err(err) => { let template_data = GcErrTemplateData::new(datastore.to_string(), format!("{err:#}")); - Notification::from_template( - Severity::Error, - "gc-err", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("gc-err", serde_json::to_value(template_data)?) + .severity(Severity::Error) } }; - let (email, notify, mode) = lookup_datastore_notify_settings(datastore); - match mode { - NotificationMode::LegacySendmail => { - let notify = notify.gc.unwrap_or(Notify::Always); + let notification = builder + .field("type", "gc") + .field("datastore", datastore) + .field("hostname", proxmox_sys::nodename()) + .recipient(recipient) + .build()?; - if notify == Notify::Never || (result.is_ok() && notify == Notify::Error) { - return Ok(()); - } - - if let Some(email) = email { - send_sendmail_legacy_notification(notification, &email)?; - } - } - NotificationMode::NotificationSystem => { - send_notification(notification)?; - } - } + send_notification(notification)?; Ok(()) } @@ -210,14 +184,16 @@ pub fn send_verify_status( job: VerificationJobConfig, result: &Result, Error>, ) -> Result<(), Error> { - let metadata = HashMap::from([ - ("job-id".into(), job.id.clone()), - ("datastore".into(), job.store.clone()), - ("hostname".into(), proxmox_sys::nodename().into()), - ("type".into(), "verify".into()), - ]); + // Failed snapshots are reported via `Ok`, but still count as an error for the notify setting. + let is_ok = matches!(result, Ok(errors) if errors.is_empty()); - let notification = match result { + let Some(recipient) = + datastore_notification_recipient(&job.store, |n| n.verify, Notify::Always, is_ok) + else { + return Ok(()); + }; + + let builder = match result { Err(_) => { // aborted job - do not send any notification return Ok(()); @@ -228,12 +204,8 @@ pub fn send_verify_status( datastore: job.store.clone(), job_id: job.id.clone(), }; - Notification::from_template( - Severity::Info, - "verify-ok", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("verify-ok", serde_json::to_value(template_data)?) + .severity(Severity::Info) } Ok(errors) => { let template_data = VerifyErrTemplateData { @@ -242,34 +214,20 @@ pub fn send_verify_status( job_id: job.id.clone(), failed_snapshot_list: errors.clone(), }; - Notification::from_template( - Severity::Error, - "verify-err", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("verify-err", serde_json::to_value(template_data)?) + .severity(Severity::Error) } }; - let (email, notify, mode) = lookup_datastore_notify_settings(&job.store); - match mode { - NotificationMode::LegacySendmail => { - let notify = notify.verify.unwrap_or(Notify::Always); + let notification = builder + .field("type", "verify") + .field("job-id", job.id) + .field("datastore", job.store) + .field("hostname", proxmox_sys::nodename()) + .recipient(recipient) + .build()?; - if notify == Notify::Never - || (matches!(result, Ok(errors) if errors.is_empty()) && notify == Notify::Error) - { - return Ok(()); - } - - if let Some(email) = email { - send_sendmail_legacy_notification(notification, &email)?; - } - } - NotificationMode::NotificationSystem => { - send_notification(notification)?; - } - } + send_notification(notification)?; Ok(()) } @@ -279,14 +237,13 @@ pub fn send_prune_status( jobname: &str, result: &Result<(), Error>, ) -> Result<(), Error> { - let metadata = HashMap::from([ - ("job-id".into(), jobname.to_string()), - ("datastore".into(), store.into()), - ("hostname".into(), proxmox_sys::nodename().into()), - ("type".into(), "prune".into()), - ]); + let Some(recipient) = + datastore_notification_recipient(store, |n| n.prune, Notify::Error, result.is_ok()) + else { + return Ok(()); + }; - let notification = match result { + let builder = match result { Ok(()) => { let template_data = PruneOkTemplateData { common: CommonData::new(), @@ -294,12 +251,8 @@ pub fn send_prune_status( job_id: jobname.to_string(), }; - Notification::from_template( - Severity::Info, - "prune-ok", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("prune-ok", serde_json::to_value(template_data)?) + .severity(Severity::Info) } Err(err) => { let template_data = PruneErrTemplateData { @@ -309,45 +262,32 @@ pub fn send_prune_status( error: format!("{err:#}"), }; - Notification::from_template( - Severity::Error, - "prune-err", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("prune-err", serde_json::to_value(template_data)?) + .severity(Severity::Error) } }; - let (email, notify, mode) = lookup_datastore_notify_settings(store); - match mode { - NotificationMode::LegacySendmail => { - let notify = notify.prune.unwrap_or(Notify::Error); + let notification = builder + .field("type", "prune") + .field("job-id", jobname) + .field("datastore", store) + .field("hostname", proxmox_sys::nodename()) + .recipient(recipient) + .build()?; - if notify == Notify::Never || (result.is_ok() && notify == Notify::Error) { - return Ok(()); - } - - if let Some(email) = email { - send_sendmail_legacy_notification(notification, &email)?; - } - } - NotificationMode::NotificationSystem => { - send_notification(notification)?; - } - } + send_notification(notification)?; Ok(()) } pub fn send_sync_status(job: &SyncJobConfig, result: &Result<(), Error>) -> Result<(), Error> { - let metadata = HashMap::from([ - ("job-id".into(), job.id.clone()), - ("datastore".into(), job.store.clone()), - ("hostname".into(), proxmox_sys::nodename().into()), - ("type".into(), "sync".into()), - ]); + let Some(recipient) = + datastore_notification_recipient(&job.store, |n| n.sync, Notify::Always, result.is_ok()) + else { + return Ok(()); + }; - let notification = match result { + let builder = match result { Ok(()) => { let template_data = SyncOkTemplateData { common: CommonData::new(), @@ -356,12 +296,8 @@ pub fn send_sync_status(job: &SyncJobConfig, result: &Result<(), Error>) -> Resu remote: job.remote.clone(), remote_datastore: job.remote_store.clone(), }; - Notification::from_template( - Severity::Info, - "sync-ok", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("sync-ok", serde_json::to_value(template_data)?) + .severity(Severity::Info) } Err(err) => { let template_data = SyncErrTemplateData { @@ -372,32 +308,20 @@ pub fn send_sync_status(job: &SyncJobConfig, result: &Result<(), Error>) -> Resu remote_datastore: job.remote_store.clone(), error: format!("{err:#}"), }; - Notification::from_template( - Severity::Error, - "sync-err", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("sync-err", serde_json::to_value(template_data)?) + .severity(Severity::Error) } }; - let (email, notify, mode) = lookup_datastore_notify_settings(&job.store); - match mode { - NotificationMode::LegacySendmail => { - let notify = notify.sync.unwrap_or(Notify::Always); + let notification = builder + .field("type", "sync") + .field("job-id", &job.id) + .field("datastore", &job.store) + .field("hostname", proxmox_sys::nodename()) + .recipient(recipient) + .build()?; - if notify == Notify::Never || (result.is_ok() && notify == Notify::Error) { - return Ok(()); - } - - if let Some(email) = email { - send_sendmail_legacy_notification(notification, &email)?; - } - } - NotificationMode::NotificationSystem => { - send_notification(notification)?; - } - } + send_notification(notification)?; Ok(()) } @@ -408,20 +332,13 @@ pub fn send_tape_backup_status( result: &Result<(), Error>, summary: TapeBackupJobSummary, ) -> Result<(), Error> { - let mut metadata = HashMap::from([ - ("datastore".into(), job.store.clone()), - ("media-pool".into(), job.pool.clone()), - ("hostname".into(), proxmox_sys::nodename().into()), - ("type".into(), "tape-backup".into()), - ]); - - if let Some(id) = id { - metadata.insert("job-id".into(), id.into()); - } + let Some(recipient) = tape_notification_recipient(&TapeNotificationMode::from(job)) else { + return Ok(()); + }; let duration = summary.duration.as_secs(); - let notification = match result { + let mut builder = match result { Ok(()) => { let template_data = TapeBackupOkTemplateData { common: CommonData::new(), @@ -434,12 +351,8 @@ pub fn send_tape_backup_status( snapshot_list: summary.snapshot_list, }; - Notification::from_template( - Severity::Info, - "tape-backup-ok", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("tape-backup-ok", serde_json::to_value(template_data)?) + .severity(Severity::Info) } Err(err) => { let template_data = TapeBackupErrTemplateData { @@ -454,30 +367,25 @@ pub fn send_tape_backup_status( error: format!("{err:#}"), }; - Notification::from_template( - Severity::Error, - "tape-backup-err", - serde_json::to_value(template_data)?, - metadata, - ) + Notification::template_builder("tape-backup-err", serde_json::to_value(template_data)?) + .severity(Severity::Error) } }; - let mode = TapeNotificationMode::from(job); - - match &mode { - TapeNotificationMode::LegacySendmail { notify_user } => { - let email = lookup_user_email(notify_user); - - if let Some(email) = email { - send_sendmail_legacy_notification(notification, &email)?; - } - } - TapeNotificationMode::NotificationSystem => { - send_notification(notification)?; - } + if let Some(id) = id { + builder = builder.field("job-id", id); } + let notification = builder + .field("type", "tape-backup") + .field("datastore", &job.store) + .field("media-pool", &job.pool) + .field("hostname", proxmox_sys::nodename()) + .recipient(recipient) + .build()?; + + send_notification(notification)?; + Ok(()) } @@ -489,10 +397,9 @@ pub fn send_load_media_notification( label_text: &str, reason: Option, ) -> Result<(), Error> { - let metadata = HashMap::from([ - ("hostname".into(), proxmox_sys::nodename().into()), - ("type".into(), "tape-load".into()), - ]); + let Some(recipient) = tape_notification_recipient(mode) else { + return Ok(()); + }; let device_type = if changer { "changer" } else { "drive" }; @@ -505,45 +412,28 @@ pub fn send_load_media_notification( tape_label: label_text.into(), }; - let notification = Notification::from_template( - Severity::Notice, - "tape-load", - serde_json::to_value(template_data)?, - metadata, - ); + let notification = + Notification::template_builder("tape-load", serde_json::to_value(template_data)?) + .severity(Severity::Notice) + .field("type", "tape-load") + .field("hostname", proxmox_sys::nodename()) + .recipient(recipient) + .build()?; - match mode { - TapeNotificationMode::LegacySendmail { notify_user } => { - let email = lookup_user_email(notify_user); - - if let Some(email) = email { - send_sendmail_legacy_notification(notification, &email)?; - } - } - TapeNotificationMode::NotificationSystem => { - send_notification(notification)?; - } - } + send_notification(notification)?; Ok(()) } pub fn send_updates_available(updates: &[&APTUpdateInfo]) -> Result<(), Error> { - let hostname = proxmox_sys::nodename().to_string(); - - let metadata = HashMap::from([ - ("hostname".into(), hostname), - ("type".into(), "package-updates".into()), - ]); - let template_data = PackageUpdatesTemplateData::new(updates); - let notification = Notification::from_template( - Severity::Info, - "package-updates", - serde_json::to_value(template_data)?, - metadata, - ); + let notification = + Notification::template_builder("package-updates", serde_json::to_value(template_data)?) + .severity(Severity::Info) + .field("type", "package-updates") + .field("hostname", proxmox_sys::nodename()) + .build()?; send_notification(notification)?; Ok(()) @@ -556,22 +446,17 @@ pub fn send_certificate_renewal_mail(result: &Result<(), Error>) -> Result<(), E _ => return Ok(()), }; - let metadata = HashMap::from([ - ("hostname".into(), proxmox_sys::nodename().into()), - ("type".into(), "acme".into()), - ]); - let template_data = AcmeErrTemplateData { common: CommonData::new(), error, }; - let notification = Notification::from_template( - Severity::Error, - "acme-err", - serde_json::to_value(template_data)?, - metadata, - ); + let notification = + Notification::template_builder("acme-err", serde_json::to_value(template_data)?) + .severity(Severity::Error) + .field("type", "acme") + .field("hostname", proxmox_sys::nodename()) + .build()?; send_notification(notification)?; Ok(()) @@ -584,12 +469,6 @@ pub fn send_datastore_threshold_exceeded( limit: u64, value: u64, ) -> Result<(), Error> { - let metadata = HashMap::from([ - ("datastore".into(), datastore.into()), - ("hostname".into(), proxmox_sys::nodename().into()), - ("type".into(), "thresholds".into()), - ]); - let is_traffic = threshold == "uploaded" || threshold == "downloaded"; let template_data = DatastoreThresholdExceededTemplateData::new( datastore.to_string(), @@ -599,12 +478,13 @@ pub fn send_datastore_threshold_exceeded( is_traffic, ); - let notification = Notification::from_template( - Severity::Warning, - "thresholds-exceeded", - serde_json::to_value(template_data)?, - metadata, - ); + let notification = + Notification::template_builder("thresholds-exceeded", serde_json::to_value(template_data)?) + .severity(Severity::Warning) + .field("type", "thresholds") + .field("datastore", datastore) + .field("hostname", proxmox_sys::nodename()) + .build()?; send_notification(notification)?; Ok(()) @@ -621,6 +501,55 @@ pub fn lookup_user_email(userid: &Userid) -> Option { None } +/// Determine the recipient for a datastore-related notification. +/// +/// Returns `None` if no notification should be sent, either because the legacy notify +/// settings of the datastore suppress it or because the notify user has no email address. +fn datastore_notification_recipient( + store: &str, + notify_setting: fn(&DatastoreNotify) -> Option, + default: Notify, + is_ok: bool, +) -> Option { + let (email, notify, mode) = lookup_datastore_notify_settings(store); + + match mode { + NotificationMode::LegacySendmail => { + let notify = notify_setting(¬ify).unwrap_or(default); + + if notify == Notify::Never || (is_ok && notify == Notify::Error) { + return None; + } + + email.map(|email| { + Recipient::Email(EmailRecipient { + mailto: vec![email], + ..Default::default() + }) + }) + } + NotificationMode::NotificationSystem => Some(Recipient::Matcher), + } +} + +/// Determine the recipient for a tape-related notification. +/// +/// Returns `None` if no notification should be sent because the notify user has no email +/// address. +fn tape_notification_recipient(mode: &TapeNotificationMode) -> Option { + match mode { + TapeNotificationMode::LegacySendmail { notify_user } => { + lookup_user_email(notify_user).map(|email| { + Recipient::Email(EmailRecipient { + mailto: vec![email], + ..Default::default() + }) + }) + } + TapeNotificationMode::NotificationSystem => Some(Recipient::Matcher), + } +} + /// Lookup Datastore notify settings pub fn lookup_datastore_notify_settings( store: &str, -- 2.47.3