From 0ad35dc91b68b88ea7ffe0a35a82087d34342f12 Mon Sep 17 00:00:00 2001 From: ChengyuZhu6 Date: Mon, 2 Sep 2024 07:52:28 +0800 Subject: [PATCH] agent:cdh: Initialize CDH client as a global asynchronous instance Introduced a global `CDH_CLIENT` instance to hold the cdh client and implemented `init_cdh_client` function to initialize the cdh client if not already set. Fixes: #10231 Signed-off-by: ChengyuZhu6 --- src/agent/src/cdh.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/agent/src/cdh.rs b/src/agent/src/cdh.rs index ed07efef58..ba1b43b533 100644 --- a/src/agent/src/cdh.rs +++ b/src/agent/src/cdh.rs @@ -7,19 +7,20 @@ // Confidential Data Hub is a service running inside guest to provide resource related APIs. // https://github.com/confidential-containers/guest-components/tree/main/confidential-data-hub -use anyhow::Result; +use crate::AGENT_CONFIG; +use crate::CDH_SOCKET_URI; +use anyhow::{Context, Result}; use derivative::Derivative; use protocols::{ confidential_data_hub, confidential_data_hub_ttrpc_async, confidential_data_hub_ttrpc_async::{SealedSecretServiceClient, SecureMountServiceClient}, }; - -use crate::AGENT_CONFIG; -use crate::CDH_SOCKET_URI; +use tokio::sync::OnceCell; // Nanoseconds lazy_static! { static ref CDH_API_TIMEOUT: i64 = AGENT_CONFIG.cdh_api_timeout.as_nanos() as i64; + pub static ref CDH_CLIENT: OnceCell = OnceCell::new(); } const SEALED_SECRET_PREFIX: &str = "sealed."; @@ -90,6 +91,13 @@ impl CDHClient { } } +pub async fn init_cdh_client() -> Result<()> { + CDH_CLIENT + .get_or_try_init(|| async { CDHClient::new().context("Failed to create CDH Client") }) + .await?; + Ok(()) +} + #[cfg(test)] #[cfg(feature = "sealed-secret")] mod tests {