use std::collections::HashMap;
use std::fmt::Debug;
use std::process::ExitCode;
use std::time::Duration;
use futures::future::BoxFuture;
use thiserror::Error;
use tokio::time::{sleep, timeout};
use tracing::error;
use crate::consent_handler::{ConsentHandler, ConsentHandlerError};
use crate::installer::{InstallProgress, Installer, InstallerError};
use crate::integrity_check::IntegrityCheckWithProgress;
use crate::persistent_store::{PersistentStore, StoreError};
use crate::progress_reporter::{ProgressMessage, ProgressReporter, UpdateState};
use crate::update_source::{UpdateInfo, UpdateSource, UpdateSourceError};
use crate::update_trigger::{UpdateTrigger, UpdateTriggerError};
#[derive(Debug, Error)]
pub enum UpdateError {
#[error("No pending updates.")]
NoPendingUpdates,
#[error("Consent denied.")]
ConsentDenied,
#[error("Consent request timed out.")]
ConsentTimeout,
#[error("External rollback detected")]
ExternalRollback,
#[error("Rollback needed: {0}")]
RollbackNeeded(String),
#[error(transparent)]
ConsentHandlerError(#[from] ConsentHandlerError),
#[error(transparent)]
StoreError(#[from] StoreError),
#[error(transparent)]
InstallerError(#[from] InstallerError),
#[error(transparent)]
UpdateSourceError(#[from] UpdateSourceError),
#[error(transparent)]
UpdateTriggerError(#[from] UpdateTriggerError),
}
pub trait WorkflowOptions: Debug + Clone {
fn ignore_previously_declined(&self) -> bool;
fn consent_timeout(&self) -> Duration;
}
#[derive(Debug, Clone)]
pub struct UpdateOptions {
pub ignore_previously_declined: bool,
pub consent_timeout: Duration,
}
impl WorkflowOptions for UpdateOptions {
fn ignore_previously_declined(&self) -> bool {
self.ignore_previously_declined
}
fn consent_timeout(&self) -> Duration {
self.consent_timeout
}
}
pub async fn monitor_update(
source: &mut impl UpdateSource,
store: &mut impl PersistentStore,
progress: &mut impl ProgressReporter,
check: &mut impl IntegrityCheckWithProgress,
) -> Result<(), UpdateError> {
if let Some(version) = store.load("update_needs_testing").await? {
let mut attempt = 1;
let update_info = loop {
let update_info = source.check_for_updates().await;
if let Err(UpdateError::NoPendingUpdates) = &update_info {
error!(
"Pending update ({}) not found on the server. This is probably an error.",
version
);
store.delete("update_needs_testing").await?;
return Ok(());
}
if update_info.is_ok() || attempt >= 10 {
break update_info;
} else {
error!("Could not connect to the server (Attempt {attempt}).");
attempt += 1;
sleep(Duration::from_secs(60)).await;
}
}?;
if update_info.version() != version {
error!(
"Pending update ({}) does not match the installed update needing testing ({}). This is probably an error.",
update_info.version(),
version
);
store.delete("update_needs_testing").await?;
return Ok(());
}
let update = update_info.update()?;
let message = ProgressMessage {
state: UpdateState::Pending,
cnt_of: (4, 5),
message: "Update installed, testing in progress".to_string(),
};
progress
.report_retry(&update, &message, 10, Duration::from_secs(60))
.await?;
match check.system_is_ok_with_progress().await {
Ok(msgs) => {
for msg in msgs {
progress
.report_retry(&update, &msg, 10, Duration::from_secs(60))
.await?;
}
let message = ProgressMessage {
state: UpdateState::Finished,
cnt_of: (5, 5),
message: "Update installed successfully".to_string(),
};
progress
.report_retry(&update, &message, 10, Duration::from_secs(60))
.await?;
if let Err(e) = store.delete("update_needs_testing").await {
error!("Could not delete update_needs_testing key: {e}");
}
}
Err(err) => {
let message = ProgressMessage {
state: UpdateState::Failed(err.to_string()),
cnt_of: (2, 2),
message: format!("Post-update check failed: {err}"),
};
progress
.report_retry(&update, &message, 10, Duration::from_secs(60))
.await
.ok();
match err {
UpdateError::ExternalRollback | UpdateError::RollbackNeeded(_) => {
if let Err(e) = store.delete("update_needs_testing").await {
error!("Could not delete update_needs_testing key: {e}");
}
}
_ => {}
}
return Err(err);
}
}
}
Ok(())
}
pub async fn update_with_consent_flow<A: WorkflowOptions>(
trigger: &mut impl UpdateTrigger<A>,
source: &mut impl UpdateSource,
consent: &mut impl ConsentHandler,
installer: &impl Installer,
store: &mut impl PersistentStore,
progress: &mut impl ProgressReporter,
) -> Result<(), UpdateError> {
let options = trigger.update_triggered().await?;
let mut update_info = source.check_for_updates().await?;
if store
.load(&update_info.version())
.await?
.is_some_and(|status| status == "installed")
{
return Err(UpdateError::NoPendingUpdates);
}
if options.ignore_previously_declined()
&& store
.load(&update_info.version())
.await?
.is_some_and(|status| status == "declined")
{
return Err(UpdateError::NoPendingUpdates);
}
if update_info.needs_consent() {
match timeout(
options.consent_timeout(),
consent.ask_for_consent(&update_info),
)
.await
{
Ok(result) => {
if result? {
update_info.give_consent().await?;
} else {
store.save(&update_info.version(), "declined").await?;
return Err(UpdateError::ConsentDenied);
}
}
Err(_) => {
return Err(UpdateError::ConsentTimeout);
}
}
}
let update = update_info.update()?;
let message = ProgressMessage {
state: UpdateState::Pending,
cnt_of: (0, 5),
message: "Update consent given, starting update".to_string(),
};
progress.report(&update, &message).await?;
let mut install_progress = installer.install(&update)?;
while let Some(feedback) = install_progress.next().await? {
let message = ProgressMessage {
state: UpdateState::Installing,
cnt_of: feedback
.progress
.map(|(mut a, mut b)| {
while a > u32::MAX as u64 || b > u32::MAX as u64 {
a >>= 10;
b >>= 10;
}
(a as u32, b as u32)
})
.unwrap_or((2, 5)),
message: format!("Status: {} Message: {}", feedback.status, feedback.message),
};
progress.report(&update, &message).await?;
}
let message = ProgressMessage {
state: UpdateState::Pending,
cnt_of: (3, 5),
message: "Installation finished, saving state to prepare for reboot".to_string(),
};
progress.report(&update, &message).await?;
store.save(&update_info.version(), "installed").await?;
store
.save("update_needs_testing", &update_info.version())
.await?;
let message = ProgressMessage {
state: UpdateState::Pending,
cnt_of: (3, 5),
message: "Update installed, checking success after next reboot".to_string(),
};
progress.report(&update, &message).await?;
Ok(())
}
pub async fn consent_flow_no_install(
source: &mut impl UpdateSource,
consent: &mut impl ConsentHandler,
store: &mut impl PersistentStore,
progress: &mut impl ProgressReporter,
options: UpdateOptions,
) -> Result<(), UpdateError> {
let mut update_info = source.check_for_updates().await?;
if options.ignore_previously_declined
&& store
.load(&update_info.version())
.await?
.is_some_and(|status| status == "declined")
{
return Err(UpdateError::NoPendingUpdates);
}
if update_info.needs_consent() {
match timeout(
options.consent_timeout,
consent.ask_for_consent(&update_info),
)
.await
{
Ok(result) => {
if result? {
update_info.give_consent().await?;
let message = ProgressMessage {
state: UpdateState::Pending,
cnt_of: (0, 0),
message: "Update consent given, starting update".to_string(),
};
progress.report(&update_info.update()?, &message).await?;
} else {
store.save(&update_info.version(), "declined").await?;
return Err(UpdateError::ConsentDenied);
}
}
Err(_) => {
return Err(UpdateError::ConsentTimeout);
}
}
}
Ok(())
}
#[derive(Debug, Error)]
pub enum WorkflowError {
#[error("Invalid workflow configuration: {0}")]
InvalidConfiguration(String),
#[error("Workflow execution failed: {0}")]
ExecutionFailed(String),
}
type WorkflowFn =
fn(HashMap<String, String>) -> BoxFuture<'static, Result<ExitCode, WorkflowError>>;
pub struct WorkflowPlugin {
pub name: &'static str,
pub func: WorkflowFn,
}
impl WorkflowPlugin {
pub const fn new(name: &'static str, func: WorkflowFn) -> Self {
Self { name, func }
}
}
inventory::collect!(WorkflowPlugin);
pub fn get_config(config: &HashMap<String, String>, key: &str) -> Result<String, WorkflowError> {
config
.get(key)
.cloned()
.ok_or(WorkflowError::InvalidConfiguration(format!(
"{key} not found in config"
)))
}
pub fn get_config_as_bool(
config: &HashMap<String, String>,
key: &str,
) -> Result<bool, WorkflowError> {
get_config(config, key)?
.to_lowercase()
.parse()
.map_err(|_| {
WorkflowError::InvalidConfiguration(format!("failed to parse {} as bool", key))
})
}
pub fn get_config_as_u64(
config: &HashMap<String, String>,
key: &str,
) -> Result<u64, WorkflowError> {
get_config(config, key)?
.parse::<u64>()
.map_err(|_| WorkflowError::InvalidConfiguration(format!("failed to parse {} as u64", key)))
}