Skip to main content

schedr_db/
nodes.rs

1//! A deployment's nodes, for the Deployments page (decisions 121-123): each master (leader or
2//! standby) heartbeating its row, and each worker's master, process and configuration.
3//!
4//! Configurations are masked by the node that writes them, before they leave its process
5//! (`schedr_config::masked`): nothing here masks or unmasks.
6
7use jiff::{SignedDuration, Timestamp};
8
9use crate::database::{Database, DbError};
10use crate::query::{db_time, from_json, in_tx, on_pool, parse_time, sql, storable_json, to_json};
11
12#[cfg(test)]
13mod tests;
14
15/// How long a master's row stays after its last heartbeat before it is removed for good (one
16/// gone this long is long gone; the page shows only those heard from lately).
17pub const MASTER_ROW_KEPT: SignedDuration = SignedDuration::from_hours(1);
18
19/// A problem a node has now (decision 129): a warning, or an error, shown on its node.
20#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub struct NodeProblem {
22    /// An error (red); a warning (yellow) otherwise.
23    pub error: bool,
24    /// What it is, for people.
25    pub message: String,
26}
27
28/// A master as it heartbeats.
29#[derive(Debug, Clone, PartialEq)]
30pub struct MasterNode<'a> {
31    /// Its ID: its lease holder's.
32    pub master_id: &'a str,
33    /// The process it runs in (shared with a worker in standalone).
34    pub process_id: &'a str,
35    /// Its host name.
36    pub host: &'a str,
37    /// Its schedr version.
38    pub schedr_version: &'a str,
39    /// Its effective configuration, masked.
40    pub config: &'a serde_json::Value,
41    /// When it started.
42    pub started_at: Timestamp,
43    /// Its problems now.
44    pub problems: &'a [NodeProblem],
45    /// What its process uses now (decision 463); none without `/proc`.
46    pub usage: Option<&'a schedr_model::usage::NodeUsage>,
47}
48
49/// A master as stored.
50#[derive(Debug, Clone, PartialEq)]
51pub struct MasterRecord {
52    /// Its ID.
53    pub master_id: String,
54    /// The process it runs in.
55    pub process_id: String,
56    /// Its host name.
57    pub host: String,
58    /// Its schedr version.
59    pub schedr_version: String,
60    /// Its effective configuration, masked.
61    pub config: serde_json::Value,
62    /// When it started.
63    pub started_at: Timestamp,
64    /// When it was last heard from.
65    pub heard_at: Timestamp,
66    /// Whether it holds the lease now (the leader).
67    pub leading: bool,
68    /// Its problems when it last wrote its row.
69    pub problems: Vec<NodeProblem>,
70    /// What its process used then (decision 463).
71    pub usage: Option<schedr_model::usage::NodeUsage>,
72}
73
74/// A worker's node: which master it registered with, its process and configuration.
75#[derive(Debug, Clone, PartialEq)]
76pub struct WorkerNode {
77    /// Its ID.
78    pub worker_id: String,
79    /// The master it registered with last.
80    pub master_id: Option<String>,
81    /// The process it runs in.
82    pub process_id: Option<String>,
83    /// Its effective configuration, masked.
84    pub config: Option<serde_json::Value>,
85    /// What it used, by part, as it last said (decision 463; written at most once a minute).
86    pub usage: Option<schedr_model::usage::WorkerUsage>,
87}
88
89impl Database {
90    /// As [`Self::heartbeat_master_keeping`], rows kept for [`MASTER_ROW_KEPT`].
91    ///
92    /// # Errors
93    ///
94    /// [`DbError::Sqlx`] if a statement fails.
95    pub async fn heartbeat_master(
96        &self,
97        master: &MasterNode<'_>,
98        now: Timestamp,
99    ) -> Result<(), DbError> {
100        self.heartbeat_master_keeping(master, now, MASTER_ROW_KEPT)
101            .await
102    }
103
104    /// Writes `master`'s heartbeat (its row, made or brought up to date), and removes the rows
105    /// of masters not heard from for `kept` (`SCHEDR_HIDDEN__MASTER__NODE_ROW_KEPT`). A standby
106    /// heartbeats too: called on a database not [fenced](Database::fenced).
107    ///
108    /// # Errors
109    ///
110    /// [`DbError::Sqlx`] if a statement fails.
111    pub async fn heartbeat_master_keeping(
112        &self,
113        master: &MasterNode<'_>,
114        now: Timestamp,
115        kept: SignedDuration,
116    ) -> Result<(), DbError> {
117        const UPSERT: &str = "INSERT INTO masters (master_id, process_id, host, schedr_version, \
118            config, started_at, heard_at, problems, usage) \
119            VALUES ($1, $2, $3, $4, $5{json}, $6{ts}, $7{ts}, $8{json}, $9{json}) \
120            ON CONFLICT (master_id) DO UPDATE SET process_id = excluded.process_id, \
121            host = excluded.host, schedr_version = excluded.schedr_version, \
122            config = excluded.config, heard_at = excluded.heard_at, \
123            problems = excluded.problems, usage = excluded.usage";
124        const PRUNE: &str = "DELETE FROM masters WHERE heard_at < $1{ts}";
125        let config = storable_json(master.config.to_string());
126        let problems = storable_json(
127            serde_json::to_string(master.problems).unwrap_or_else(|_| "[]".to_owned()),
128        );
129        let usage = master.usage.map(to_json);
130        let gone = now.checked_sub(kept).unwrap_or(Timestamp::UNIX_EPOCH);
131        in_tx!(self, |tx, backend| {
132            sqlx::query(sql(backend, UPSERT))
133                .bind(master.master_id)
134                .bind(master.process_id)
135                .bind(master.host)
136                .bind(master.schedr_version)
137                .bind(&config)
138                .bind(db_time(master.started_at))
139                .bind(db_time(now))
140                .bind(&problems)
141                .bind(&usage)
142                .execute(&mut *tx)
143                .await?;
144            sqlx::query(sql(backend, PRUNE))
145                .bind(db_time(gone))
146                .execute(&mut *tx)
147                .await?;
148        });
149        Ok(())
150    }
151
152    /// The masters heard from since `since`, the leader (the lease's holder, its lease not
153    /// expired, by the database's clock) first, then by ID.
154    ///
155    /// # Errors
156    ///
157    /// [`DbError`] if the query fails or stored data doesn't read.
158    pub async fn masters(&self, since: Timestamp) -> Result<Vec<MasterRecord>, DbError> {
159        const MASTERS: &str = "SELECT m.master_id, m.process_id, m.host, m.schedr_version, \
160            m.config{text}, {ts<}m.started_at{>ts}, {ts<}m.heard_at{>ts}, m.problems{text}, \
161            m.usage{text} FROM masters m WHERE m.heard_at >= $1{ts} ORDER BY m.master_id";
162        type Row = (
163            String,
164            String,
165            String,
166            String,
167            String,
168            String,
169            String,
170            String,
171            Option<String>,
172        );
173        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
174            sqlx::query_as(sql(backend, MASTERS))
175                .bind(db_time(since))
176                .fetch_all(pool)
177                .await?
178        });
179        let holder = self.lease_holder().await?;
180        let mut masters = rows
181            .into_iter()
182            .map(
183                |(
184                    master_id,
185                    process_id,
186                    host,
187                    version,
188                    config,
189                    started,
190                    heard,
191                    problems,
192                    usage,
193                )| {
194                    Ok(MasterRecord {
195                        leading: holder.as_deref() == Some(master_id.as_str()),
196                        master_id,
197                        process_id,
198                        host,
199                        schedr_version: version,
200                        config: from_json("masters.config", &config)?,
201                        started_at: parse_time("masters.started_at", &started)?,
202                        heard_at: parse_time("masters.heard_at", &heard)?,
203                        problems: from_json("masters.problems", &problems)?,
204                        usage: usage.map(|u| from_json("masters.usage", &u)).transpose()?,
205                    })
206                },
207            )
208            .collect::<Result<Vec<_>, DbError>>()?;
209        masters.sort_by_key(|m| !m.leading);
210        Ok(masters)
211    }
212
213    /// Records the node a worker runs as: the master it registered with, its process and its
214    /// configuration (masked); each `None` when not known (an older agent sends neither).
215    ///
216    /// # Errors
217    ///
218    /// [`DbError::Sqlx`] if the statement fails.
219    pub async fn set_worker_node(
220        &self,
221        worker_id: &str,
222        master_id: Option<&str>,
223        process_id: Option<&str>,
224        config: Option<&serde_json::Value>,
225    ) -> Result<(), DbError> {
226        const SET: &str = "UPDATE workers SET master_id = $1, process_id = $2, config = $3{json} \
227            WHERE worker_id = $4";
228        let config = config.map(|c| storable_json(c.to_string()));
229        in_tx!(self, |tx, backend| {
230            sqlx::query(sql(backend, SET))
231                .bind(master_id)
232                .bind(process_id)
233                .bind(config)
234                .bind(worker_id)
235                .execute(&mut *tx)
236                .await?;
237        });
238        Ok(())
239    }
240
241    /// Every worker's node, by ID.
242    ///
243    /// # Errors
244    ///
245    /// [`DbError`] if the query fails or stored data doesn't read.
246    pub async fn worker_nodes(&self) -> Result<Vec<WorkerNode>, DbError> {
247        const NODES: &str = "SELECT worker_id, master_id, process_id, config{text}, usage{text} \
248            FROM workers ORDER BY worker_id";
249        type Row = (
250            String,
251            Option<String>,
252            Option<String>,
253            Option<String>,
254            Option<String>,
255        );
256        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
257            sqlx::query_as(sql(backend, NODES)).fetch_all(pool).await?
258        });
259        rows.into_iter()
260            .map(|(worker_id, master_id, process_id, config, usage)| {
261                Ok(WorkerNode {
262                    worker_id,
263                    master_id,
264                    process_id,
265                    config: config
266                        .map(|c| from_json("workers.config", &c))
267                        .transpose()?,
268                    usage: usage.map(|u| from_json("workers.usage", &u)).transpose()?,
269                })
270            })
271            .collect()
272    }
273
274    /// Records what a worker uses, by part (decision 463), as measured `now`.
275    ///
276    /// # Errors
277    ///
278    /// [`DbError::Sqlx`] if the statement fails.
279    pub async fn set_worker_usage(
280        &self,
281        worker_id: &str,
282        usage: &schedr_model::usage::WorkerUsage,
283        now: Timestamp,
284    ) -> Result<(), DbError> {
285        const SET: &str =
286            "UPDATE workers SET usage = $1{json}, usage_at = $3{ts} WHERE worker_id = $2";
287        in_tx!(self, |tx, backend| {
288            sqlx::query(sql(backend, SET))
289                .bind(to_json(usage))
290                .bind(worker_id)
291                .bind(db_time(now))
292                .execute(&mut *tx)
293                .await?;
294        });
295        Ok(())
296    }
297}