1use 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
18pub const MASTER_HEARTBEAT: Duration = Duration::from_secs(10);
20
21#[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#[must_use]
30pub fn new_master_id() -> String {
31 uuid::Uuid::now_v7().to_string()
32}
33
34#[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#[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 usage: None,
56 }
57}
58
59#[derive(Debug, Clone)]
61pub struct MasterIdentity {
62 pub master_id: String,
64 pub config: serde_json::Value,
66 pub problems: Problems,
68 pub heartbeat: std::time::Duration,
70 pub row_kept: std::time::Duration,
72}
73
74pub 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 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 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}