mod hawkbit_builder;
mod hawkbit_progress;
mod hawkbit_update;
use crate::LOG;
use crate::util::download::DownloadClient;
use async_trait::async_trait;
use regex::Regex;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tracing::{error, info};
pub use hawkbit::ddi::ClientAuthorization;
use hawkbit::ddi::{CancelAction, Client, ConfigRequest, Execution, Finished};
use crate::update_source::{StreamError, UpdateSourceError};
use crate::update_workflow::UpdateError;
pub use self::hawkbit_builder::HawkbitBuilder;
pub use self::hawkbit_progress::HawkbitProgressReporter;
pub use self::hawkbit_update::{HawkbitUpdate, HawkbitUpdateInfo};
impl From<hawkbit::ddi::Error> for UpdateError {
fn from(e: hawkbit::ddi::Error) -> Self {
UpdateError::UpdateSourceError(UpdateSourceError::ConnectionError(format!(
"ddi error: {}",
e
)))
}
}
impl From<hawkbit::ddi::Error> for StreamError {
fn from(e: hawkbit::ddi::Error) -> Self {
StreamError::ReceiveError(format!("ddi error: {}", e))
}
}
#[derive(Debug)]
pub struct Hawkbit {
client: Client,
polling_interval: std::time::Duration,
options: HawkbitOptions,
}
#[async_trait]
pub trait AttributesFn: core::fmt::Debug + Sync + Send {
async fn run(&self) -> Option<HashMap<String, String>>;
}
#[derive(Debug, Clone)]
pub enum Attributes {
Script(String),
Function(Arc<dyn AttributesFn>),
Default,
}
#[derive(Clone, Debug)]
pub struct HawkbitOptions {
pub handle_cancel: bool,
pub handle_config: bool,
pub default_polling_interval: Duration,
pub server_cert: Option<String>,
pub client_cert: Option<String>,
pub attributes_script: Attributes,
pub timeout: Duration,
}
impl Hawkbit {
pub async fn new(
url: &str,
tenant: &str,
controller: &str,
authorization: ClientAuthorization,
options: HawkbitOptions,
) -> Result<Self, UpdateError> {
let server_cert = options.server_cert.as_deref();
let client_cert = options.client_cert.as_deref();
let builder =
DownloadClient::client_builder(server_cert, client_cert, Some(options.timeout))
.await
.map_err(|e| {
UpdateSourceError::ConfigurationError(format!(
"Failed to create client builder: {e}"
))
})?;
let client =
Client::new_from_client_builder(url, tenant, controller, authorization, builder)?;
Ok(Self {
client,
polling_interval: options.default_polling_interval,
options,
})
}
pub fn builder() -> HawkbitBuilder {
HawkbitBuilder::default()
}
pub fn preferred_polling_interval(&self) -> &std::time::Duration {
&self.polling_interval
}
async fn run_attributes_script(&self) -> Option<HashMap<String, String>> {
let script = match &self.options.attributes_script {
Attributes::Script(script) => script,
Attributes::Function(f) => return f.run().await,
Attributes::Default => return None,
};
info!(target = LOG, "Running attributes script");
let output = tokio::process::Command::new(script)
.output()
.await
.map_err(|e| {
error!(LOG, "Could not run attributes script: {:?}", e);
e
})
.ok()?;
if !output.status.success() {
error!(LOG, "Attributes script failed: {:?}", output);
return None;
}
serde_json::from_slice(&output.stdout)
.map_err(|e| {
error!(
LOG,
"Could not parse output of attributes script as json: {:?}", e
);
e
})
.ok()
}
pub async fn get_os_version(&self) -> Option<String> {
if let Ok(content) = tokio::fs::read_to_string("/etc/product-release").await {
if let Some(os_version) = Regex::new(r#"PRODUCT_VERSION="(.*)""#).ok().and_then(|re| {
re.captures(&content)
.map(|os_version| os_version[1].to_string())
}) {
return Some(os_version);
}
}
if let Ok(content) = tokio::fs::read_to_string("/etc/os-release").await {
if let Some(os_version) = Regex::new(r#"VERSION_ID=(.*)"#).ok().and_then(|re| {
re.captures(&content)
.map(|os_version| os_version[1].to_string())
}) {
return Some(os_version);
}
}
None
}
async fn handle_config_request(&self, request: ConfigRequest) -> Result<(), UpdateError> {
let data = match self.run_attributes_script().await {
Some(attributes) => attributes,
None => {
info!(target = LOG, "Uploading default config data");
HashMap::from([
(
"Client".to_string(),
format!("{} v{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")),
),
(
"OSVersion".to_string(),
self.get_os_version().await.unwrap_or("NA".to_string()),
),
])
}
};
request
.upload(
Execution::Closed,
Finished::Success,
Some(hawkbit::ddi::Mode::Replace),
data,
vec![],
)
.await?;
Ok(())
}
async fn handle_cancel_action(&self, cancel: CancelAction) -> Result<(), UpdateError> {
let action = cancel.id().await?;
info!(action, "Cancel action");
cancel
.send_feedback(Execution::Proceeding, Finished::None, vec!["Cancelling"])
.await?;
cancel
.send_feedback(Execution::Closed, Finished::Success, vec![])
.await?;
info!(target = LOG, "cancelled");
Ok(())
}
}