Skip to main content

schedr_bin/
node.rs

1//! This process as a node of its deployment, for the Deployments page (decisions 121-123): the
2//! process's ID, its host, and a master's heartbeat of its row (leader or standby).
3
4use std::sync::OnceLock;
5use std::time::Duration;
6
7use jiff::Timestamp;
8use schedr_db::Database;
9use schedr_db::nodes::MasterNode;
10use schedr_master::problems::Problems;
11use tokio::sync::watch;
12
13use crate::roles::until;
14
15#[cfg(test)]
16mod tests;
17
18/// How often a master writes its row.
19pub const MASTER_HEARTBEAT: Duration = Duration::from_secs(10);
20
21/// This process's ID: made once, shared by the parts it runs (standalone's master and worker).
22#[must_use]
23pub fn process_id() -> &'static str {
24    static ID: OnceLock<String> = OnceLock::new();
25    ID.get_or_init(|| uuid::Uuid::now_v7().to_string())
26}
27
28/// A new master's ID: the holder it takes the lease as.
29#[must_use]
30pub fn new_master_id() -> String {
31    uuid::Uuid::now_v7().to_string()
32}
33
34/// This host's name (`unknown` if it isn't valid UTF-8 or is empty).
35#[must_use]
36pub fn host_name() -> String {
37    let name = rustix::system::uname();
38    let name = name.nodename().to_string_lossy();
39    if name.is_empty() {
40        "unknown".to_owned()
41    } else {
42        name.into_owned()
43    }
44}
45
46/// This process's webserver as a node of its deployment, with `config` (masked).
47#[must_use]
48pub fn webserver_node(config: serde_json::Value) -> schedr_api::views::NodeView {
49    schedr_api::views::NodeView {
50        process_id: process_id().to_owned(),
51        host: host_name(),
52        schedr_version: env!("CARGO_PKG_VERSION").to_owned(),
53        config,
54        // Read for each answer instead (`ApiState::usage`, decision 463).
55        usage: None,
56    }
57}
58
59/// A master's identity as its heartbeat writes it.
60#[derive(Debug, Clone)]
61pub struct MasterIdentity {
62    /// Its ID (its lease holder's).
63    pub master_id: String,
64    /// Its effective configuration, masked.
65    pub config: serde_json::Value,
66    /// Its problems now (decision 129), written with each beat.
67    pub problems: Problems,
68    /// How often its row is written (`node_heartbeat`).
69    pub heartbeat: std::time::Duration,
70    /// How long a gone master's row stays (`node_row_kept`).
71    pub row_kept: std::time::Duration,
72}
73
74/// Writes `master`'s row every `master.heartbeat` on `db` (not fenced: a standby writes too)
75/// until `stop`. A write that fails is logged once, until one succeeds; not while the schema
76/// isn't usable yet (it is being migrated).
77pub async fn heartbeat_master(db: Database, master: MasterIdentity, stop: watch::Receiver<u32>) {
78    let host = host_name();
79    let started_at = Timestamp::now();
80    let mut failing = false;
81    let beats = async {
82        loop {
83            let problems = master.problems.now();
84            // What its process uses (decision 463): in standalone the worker's and the
85            // webserver's too.
86            let usage = schedr_agent::memory::this_node();
87            let node = MasterNode {
88                master_id: &master.master_id,
89                process_id: process_id(),
90                host: &host,
91                schedr_version: env!("CARGO_PKG_VERSION"),
92                config: &master.config,
93                started_at,
94                problems: &problems,
95                usage: usage.as_ref(),
96            };
97            // Housekeeping: nothing a trigger depends on (decision 486).
98            match db
99                .quietly(
100                    db.heartbeat_master_keeping(
101                        &node,
102                        Timestamp::now(),
103                        jiff::SignedDuration::try_from(master.row_kept)
104                            .unwrap_or(jiff::SignedDuration::MAX),
105                    ),
106                )
107                .await
108            {
109                Ok(()) => failing = false,
110                Err(error) => {
111                    let usable = db
112                        .schema_status()
113                        .await
114                        .is_ok_and(|status| status.is_usable());
115                    if usable && !failing {
116                        tracing::warn!(%error, "can't write this master's row for the Deployments page");
117                        failing = true;
118                    }
119                }
120            }
121            tokio::time::sleep(master.heartbeat).await;
122        }
123    };
124    tokio::select! {
125        () = beats => {}
126        () = until(stop) => {}
127    }
128}