home_assistant.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. //! Home Assistant REST API client for `power on`/`power off`.
  2. //!
  3. //! Talks to HA via `POST /api/services/<domain>/<service>` and uses
  4. //! `Authorization: Bearer <token>`. The HA domain for a switch is the
  5. //! part before the first dot in the entity_id (e.g. `switch.dgx1` →
  6. //! domain `switch`, service `turn_off` or `turn_on`).
  7. use anyhow::{Context, Result, anyhow};
  8. use serde_json::json;
  9. use std::sync::OnceLock;
  10. use std::time::Duration;
  11. use tracing::{debug, info, warn};
  12. use crate::config::{Cluster, Config, HomeAssistantConfig};
  13. /// Process-wide shared HA client, built once. The fleet probe rebuilds HA
  14. /// state every 30 s across several clusters — a fresh `Client` per call
  15. /// re-parses the system CA bundle (rustls) and allocates ~1.7 MB of TLS
  16. /// setup each time, ~2 GB/h of churn in the long-running dashboard.
  17. static SHARED_CLIENT: OnceLock<Option<Client>> = OnceLock::new();
  18. /// The shared client for long-lived callers (the web dashboard's probe
  19. /// loop); CLI paths (one-shot `power`) may keep using `Client::new`.
  20. pub fn shared_client(config: &Config) -> Option<Client> {
  21. SHARED_CLIENT
  22. .get_or_init(|| {
  23. config
  24. .home_assistant
  25. .as_ref()
  26. .and_then(|ha| Client::new(ha).ok())
  27. })
  28. .clone()
  29. }
  30. /// Thin async wrapper around the HA REST API.
  31. ///
  32. /// `base_url` is the HA root URL (`http://homeassistant.local:8123`),
  33. /// `token` is the long-lived access token used as bearer auth.
  34. #[derive(Clone)]
  35. pub struct Client {
  36. base_url: String,
  37. token: String,
  38. http: reqwest::Client,
  39. }
  40. impl Client {
  41. /// Construct a new client. The reqwest client is built once and
  42. /// reused so connection pooling works across the parallel calls in
  43. /// the `power` subcommand.
  44. pub fn new(cfg: &HomeAssistantConfig) -> Result<Self> {
  45. let base_url = cfg.url.trim_end_matches('/').to_string();
  46. if base_url.is_empty() {
  47. anyhow::bail!("[home_assistant].url must be set");
  48. }
  49. let http = reqwest::Client::builder()
  50. .timeout(Duration::from_secs(10))
  51. .build()
  52. .context("building reqwest client")?;
  53. Ok(Self {
  54. base_url,
  55. token: cfg.token.clone(),
  56. http,
  57. })
  58. }
  59. /// Build `https://.../api/services/<domain>/<service>` for the given
  60. /// `entity_id`. Domain is the prefix before the first `.`; pass an
  61. /// empty fallback for ambiguous input.
  62. fn endpoint(entity_id: &str, service: &str) -> Result<(String, String)> {
  63. let (domain, entity) = entity_id.split_once('.').ok_or_else(|| {
  64. anyhow!(
  65. "entity_id '{}' has no domain (e.g. 'switch.foo')",
  66. entity_id
  67. )
  68. })?;
  69. if entity.is_empty() {
  70. anyhow::bail!("entity_id '{}' has empty entity name", entity_id);
  71. }
  72. Ok((
  73. domain.to_string(),
  74. format!("/api/services/{}/{}", domain, service),
  75. ))
  76. }
  77. /// POST `/api/services/<domain>/<service>` with `{"entity_id": ...}`.
  78. async fn call_service(&self, entity_id: &str, service: &str) -> Result<()> {
  79. let (_domain, path) = Self::endpoint(entity_id, service)?;
  80. let url = format!("{}{}", self.base_url, path);
  81. debug!("HA POST {}", url);
  82. let resp = self
  83. .http
  84. .post(&url)
  85. .bearer_auth(&self.token)
  86. .json(&json!({ "entity_id": entity_id }))
  87. .send()
  88. .await
  89. .with_context(|| format!("calling HA at {}", url))?;
  90. let status = resp.status();
  91. if !status.is_success() {
  92. let body = resp.text().await.unwrap_or_default();
  93. anyhow::bail!(
  94. "HA {} {} returned {}: {}",
  95. service,
  96. entity_id,
  97. status,
  98. body.trim()
  99. );
  100. }
  101. Ok(())
  102. }
  103. /// `switch.turn_off` for the given entity.
  104. pub async fn turn_off(&self, entity_id: &str) -> Result<()> {
  105. info!("HA turn_off {}", entity_id);
  106. self.call_service(entity_id, "turn_off").await
  107. }
  108. /// `switch.turn_on` for the given entity.
  109. pub async fn turn_on(&self, entity_id: &str) -> Result<()> {
  110. info!("HA turn_on {}", entity_id);
  111. self.call_service(entity_id, "turn_on").await
  112. }
  113. /// GET `/api/states/<entity_id>` and return the state string.
  114. /// Returns `None` if the entity doesn't exist or isn't reachable.
  115. /// Logs a warning when the HTTP request or JSON parsing fails so
  116. /// callers (e.g. `entity_is_on`) can distinguish "entity is off"
  117. /// from "HA is unreachable" via the log.
  118. pub async fn get_state(&self, entity_id: &str) -> Option<String> {
  119. let url = format!("{}/api/states/{}", self.base_url, entity_id);
  120. let resp = match self.http.get(&url).bearer_auth(&self.token).send().await {
  121. Ok(r) => r,
  122. Err(e) => {
  123. warn!("HA GET {} failed: {}", url, e);
  124. return None;
  125. }
  126. };
  127. if !resp.status().is_success() {
  128. warn!("HA GET {} returned {}", url, resp.status());
  129. return None;
  130. }
  131. let body: serde_json::Value = match resp.json().await {
  132. Ok(v) => v,
  133. Err(e) => {
  134. warn!("HA GET {} JSON parse failed: {}", url, e);
  135. return None;
  136. }
  137. };
  138. body.get("state").and_then(|s| s.as_str()).map(String::from)
  139. }
  140. }
  141. /// HA states for a cluster's `extra_entities` (parallel GETs).
  142. #[derive(Clone, Debug, Default, PartialEq)]
  143. pub struct EntityStates {
  144. /// A *blocking* entity reports anything other than "on" — including
  145. /// HA being unreachable (unknown is treated as off, same as the
  146. /// `health` command has always done). Blocking-off takes the whole
  147. /// cluster down.
  148. pub blocking_off: bool,
  149. /// Non-blocking entities (`blocks = false`) that are not "on" —
  150. /// tracked and displayed, but they never affect up/down.
  151. pub soft_off: Vec<String>,
  152. }
  153. /// Probe the cluster's `extra_entities`. No HA config and no `[mikrotik]`
  154. /// backend for an entity → that entity is "nothing to check", not off
  155. /// (legacy semantics). Mikrotik devices (exact name match from
  156. /// [`crate::config`]) are probed through the RouterOS API instead of HA:
  157. /// logged in = on, unreachable/rejected login = off (a dead router takes
  158. /// the cluster down like any other blocking switch).
  159. pub async fn extra_entities_states(config: &Config, cluster: &Cluster) -> EntityStates {
  160. if cluster.extra_entities.is_empty() {
  161. return EntityStates::default();
  162. }
  163. let ha_client: Option<Client> = shared_client(config);
  164. let has_ha = ha_client.is_some();
  165. let mut handles = Vec::new();
  166. for e in &cluster.extra_entities {
  167. let id = e.entity().to_string();
  168. let is_mikrotik = config
  169. .mikrotik
  170. .as_ref()
  171. .is_some_and(|m| m.devices.iter().any(|d| d.name == id.as_str()));
  172. // A non-mikrotik entity without an HA backend is "nothing to check",
  173. // not off — only entities with a configured backend flip the verdict.
  174. if !is_mikrotik && !has_ha {
  175. continue;
  176. }
  177. let config = config.clone();
  178. let client = ha_client.clone();
  179. let blocks = e.blocks();
  180. handles.push(crate::locale::spawn_with_locale(async move {
  181. (
  182. id.clone(),
  183. blocks,
  184. entity_state(&config, client.as_ref(), &id).await,
  185. )
  186. }));
  187. }
  188. let mut st = EntityStates::default();
  189. for h in futures::future::join_all(handles).await {
  190. let Ok((id, blocks, state)) = h else {
  191. continue;
  192. };
  193. let on = matches!(&state, Some(s) if s == "on");
  194. if !on {
  195. if blocks {
  196. st.blocking_off = true;
  197. } else {
  198. st.soft_off.push(id);
  199. }
  200. }
  201. }
  202. st
  203. }
  204. /// The state of one entity through the correct backend: a `[mikrotik]`
  205. /// device is probed with a RouterOS API login (logged in = "on";
  206. /// unreachable or rejected login = "off", like a switch that does not
  207. /// answer), everything else goes through HA REST.
  208. /// Returns `None` only when the entity has no configured backend at all
  209. /// (unknown — callers keep the "nothing to check ≠ off" semantics).
  210. pub async fn entity_state(
  211. config: &Config,
  212. client: Option<&Client>,
  213. entity_id: &str,
  214. ) -> Option<String> {
  215. if let Some(dev) = config
  216. .mikrotik
  217. .as_ref()
  218. .and_then(|m| m.devices.iter().find(|d| d.name == entity_id))
  219. {
  220. return match crate::mikrotik::ping_device(dev).await {
  221. Ok(()) => Some("on".to_string()),
  222. Err(e) => {
  223. warn!("RouterOS ping {entity_id} failed: {e}");
  224. Some("off".to_string())
  225. }
  226. };
  227. }
  228. let client = client?;
  229. client
  230. .get_state(entity_id)
  231. .await
  232. .map(|s| if s == "on" { "on".into() } else { "off".into() })
  233. }
  234. /// Parse `switch.dgx1` into `("switch", "dgx1")` so callers can build
  235. /// their own endpoints if needed. Exposed for the `power` subcommand
  236. /// and for tests.
  237. pub fn split_entity(entity_id: &str) -> Result<(&str, &str)> {
  238. let (domain, entity) = entity_id.split_once('.').ok_or_else(|| {
  239. anyhow!(
  240. "entity_id '{}' has no domain (e.g. 'switch.foo')",
  241. entity_id
  242. )
  243. })?;
  244. if domain.is_empty() || entity.is_empty() {
  245. anyhow::bail!("entity_id '{}' has empty domain or entity name", entity_id);
  246. }
  247. Ok((domain, entity))
  248. }
  249. /// Emit a deprecation-style warning if a HA token looks suspiciously
  250. /// short. HA tokens are typically 100+ chars; anything shorter is
  251. /// almost certainly a placeholder.
  252. pub fn warn_if_token_looks_short(token: &str) {
  253. if token.len() < 20 {
  254. warn!(
  255. "[home_assistant].token looks suspiciously short ({} chars); \
  256. did you paste a placeholder?",
  257. token.len()
  258. );
  259. }
  260. }
  261. #[cfg(test)]
  262. mod tests {
  263. use super::*;
  264. #[tokio::test]
  265. async fn mikrotik_entity_unreachable_is_blocking_off() {
  266. // A `[mikrotik]` device referenced from `extra_entities` is probed
  267. // through the RouterOS API: unreachable (closed port) = off, and a
  268. // blocking entity takes the cluster down — the r18-class "dead
  269. // entity silently skipped" failure mode must not exist.
  270. let toml = r#"
  271. ssh_user = "u"
  272. [[clusters]]
  273. name = "c1"
  274. nodes = [{ name = "n1", ssh_ip = "10.0.0.1", rank = 0 }]
  275. extra_entities = ["rt"]
  276. [mikrotik]
  277. [[mikrotik.devices]]
  278. name = "rt"
  279. address = "127.0.0.1"
  280. username = "x"
  281. password = "y"
  282. api_port = 1
  283. "#;
  284. let config: crate::config::Config = toml::from_str(toml).unwrap();
  285. let cluster = &config.clusters[0];
  286. let st = extra_entities_states(&config, cluster).await;
  287. assert!(
  288. st.blocking_off,
  289. "unreachable mikrotik device must be blocking-off"
  290. );
  291. }
  292. #[tokio::test]
  293. async fn mikrotik_device_without_backend_not_reported_off() {
  294. // No [mikrotik] section, no HA → the entity has no backend at all:
  295. // "nothing to check", not off (legacy semantics).
  296. let toml = r#"
  297. ssh_user = "u"
  298. [[clusters]]
  299. name = "c1"
  300. nodes = [{ name = "n1", ssh_ip = "10.0.0.1", rank = 0 }]
  301. extra_entities = ["rt"]
  302. "#;
  303. let config: crate::config::Config = toml::from_str(toml).unwrap();
  304. let cluster = &config.clusters[0];
  305. let st = extra_entities_states(&config, cluster).await;
  306. assert!(!st.blocking_off);
  307. assert!(st.soft_off.is_empty());
  308. }
  309. #[test]
  310. fn split_entity_basic() {
  311. assert_eq!(split_entity("switch.dgx1").unwrap(), ("switch", "dgx1"));
  312. assert_eq!(
  313. split_entity("light.living_room").unwrap(),
  314. ("light", "living_room")
  315. );
  316. }
  317. #[test]
  318. fn split_entity_no_domain_errors() {
  319. assert!(split_entity("dgx1").is_err());
  320. }
  321. #[test]
  322. fn split_entity_empty_entity_errors() {
  323. assert!(split_entity("switch.").is_err());
  324. }
  325. #[test]
  326. fn split_entity_empty_domain_errors() {
  327. assert!(split_entity(".thing").is_err());
  328. }
  329. #[test]
  330. fn endpoint_extracts_domain() {
  331. let (_d, path) = Client::endpoint("switch.dgx1", "turn_off").unwrap();
  332. assert_eq!(path, "/api/services/switch/turn_off");
  333. let (_d, path) = Client::endpoint("light.kitchen", "turn_on").unwrap();
  334. assert_eq!(path, "/api/services/light/turn_on");
  335. }
  336. #[test]
  337. fn endpoint_rejects_no_domain() {
  338. assert!(Client::endpoint("plain", "turn_off").is_err());
  339. }
  340. }