use std::fmt;
use std::time::Duration;
use serde::Serialize;
use tokio::time::Instant;
use tr064::{Action, Client, Service};
use super::{Changer, Error, Event, subject};
use crate::generic;
use crate::identity::Identity;
use crate::redact;
const SERVICE: &str = "DeviceConfig1";
const ACTION: &str = "Reboot";
pub const WARNING: &str = "the device restarts: internet, WLAN and telephony are down \
for a few minutes, and so is everything connected through it";
#[derive(Debug, Clone, Serialize)]
pub struct RebootPlan {
pub device: Identity,
pub model: Option<String>,
pub name: Option<String>,
pub uptime: Option<u64>,
pub class: String,
pub warning: &'static str,
pub token: String,
pub expires_in: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
Accepted,
Rebooting,
Back,
Timeout,
Unknown,
}
impl State {
pub fn meaning(self) -> &'static str {
match self {
Self::Accepted => "the device accepted the restart",
Self::Rebooting => "the device stopped answering",
Self::Back => "the device restarted and answers again",
Self::Timeout => "the device is not back within the time to wait",
Self::Unknown => {
"the connection broke while the restart was sent; the device may or may not restart"
}
}
}
}
impl fmt::Display for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Accepted => "accepted",
Self::Rebooting => "rebooting",
Self::Back => "back",
Self::Timeout => "timeout",
Self::Unknown => "unknown",
};
f.write_str(name)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Report {
pub device: Identity,
pub outcome: State,
pub uptime_before: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub uptime: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub waited: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Wait {
pub interval: Duration,
pub budget: Duration,
}
impl Default for Wait {
fn default() -> Self {
Self {
interval: Duration::from_secs(5),
budget: Duration::from_mins(5),
}
}
}
#[derive(Debug)]
pub struct Reboot {
report: Report,
udn: String,
probe: Probe,
}
impl Reboot {
pub fn report(&self) -> &Report {
&self.report
}
}
#[derive(Debug)]
pub(super) struct Probe {
service: Service,
action: Action,
}
#[derive(Debug)]
pub(super) struct Info {
model: Option<String>,
pub(super) serial: Option<String>,
uptime: Option<u64>,
}
impl Probe {
pub(super) async fn new(client: &Client) -> Result<Self, Error> {
let (service, scpd) = generic::service(client, "DeviceInfo1").await?;
let action = generic::action(&service, &scpd, "GetInfo")?.clone();
Ok(Self { service, action })
}
async fn first(client: &Client) -> Result<(Self, Info), Error> {
let probe = Self::new(client).await?;
let info = probe.read(client).await?;
Ok((probe, info))
}
pub(super) async fn read(&self, client: &Client) -> Result<Info, Error> {
let out = generic::send(client, &self.service, &self.action, &[]).await?;
let get = |name: &str| {
out.iter()
.find(|(n, _)| n == name)
.map(|(_, value)| value.clone())
};
Ok(Info {
model: get("NewModelName").map(|v| redact::value("NewModelName", &v)),
serial: get("NewSerialNumber"),
uptime: get("NewUpTime").and_then(|v| v.parse().ok()),
})
}
}
impl Changer {
pub async fn plan_reboot(&mut self) -> Result<RebootPlan, Error> {
let plan = self.plan(SERVICE, ACTION, &[]).await?;
let description = self.client.description().await?;
let info = Probe::new(&self.client).await?.read(&self.client).await?;
Ok(RebootPlan {
device: plan.device,
model: info.model,
name: description
.device
.friendly_name
.map(|v| redact::value("friendlyName", &v)),
uptime: info.uptime,
class: plan.class,
warning: WARNING,
token: plan.token,
expires_in: plan.expires_in,
})
}
pub async fn reboot(&mut self, token: &str) -> Result<Reboot, Error> {
let change = subject(SERVICE, ACTION, &[]);
let checked = self.checked(change).await?;
let (probe, before) = match Probe::first(&self.client).await {
Ok(first) => first,
Err(error) => return Err(self.refuse(change, error)),
};
let (outcome, error) = match self.send(&checked, change, token).await {
Ok(service) => {
let _ = self.log(Event::Applied, subject(&service, ACTION, &[]), None, None);
(State::Accepted, None)
}
Err(Error::Call(generic::Error::Tr064(
error @ (tr064::Error::Http(_)
| tr064::Error::Xml(_)
| tr064::Error::InvalidResponse(_)),
))) => (State::Unknown, Some(error.to_string())),
Err(error) => return Err(error),
};
let udn = self.identity.clone().map_or_default(|(_, udn)| udn);
Ok(Reboot {
report: Report {
device: checked.identity,
outcome,
uptime_before: before.uptime,
uptime: None,
waited: None,
error,
},
udn,
probe,
})
}
pub async fn wait(
&self,
reboot: &Reboot,
wait: Wait,
mut progress: impl FnMut(State),
) -> Result<Report, Error> {
let start = Instant::now();
let deadline = start + wait.budget;
let mut report = reboot.report.clone();
let mut down = false;
loop {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
break;
}
tokio::time::sleep(wait.interval.min(left)).await;
let left = deadline.saturating_duration_since(Instant::now());
let read = reboot.probe.read(&self.client);
let Ok(Ok(info)) = tokio::time::timeout(left, read).await else {
if !down {
down = true;
progress(State::Rebooting);
}
continue;
};
let restarted = info
.uptime
.zip(report.uptime_before)
.map_or(down, |(now, before)| now < before);
if restarted {
let serial = info.serial.unwrap_or_default();
let identity = Identity::of(&reboot.udn, &serial);
if identity != report.device {
return Err(Error::OtherDevice(identity));
}
report.outcome = State::Back;
report.uptime = info.uptime;
report.waited = Some(start.elapsed().as_secs());
return Ok(report);
}
}
report.outcome = State::Timeout;
report.waited = Some(start.elapsed().as_secs());
Ok(report)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_and_explains_the_states() {
let states = [
(State::Accepted, "accepted"),
(State::Rebooting, "rebooting"),
(State::Back, "back"),
(State::Timeout, "timeout"),
(State::Unknown, "unknown"),
];
for (state, name) in states {
assert_eq!(state.to_string(), name);
assert_eq!(
serde_json::to_value(state).unwrap(),
serde_json::json!(name)
);
assert_ne!(state.meaning(), "");
}
assert_eq!(Wait::default().budget, Duration::from_secs(300));
}
}