Skip to main content

schedr_db/
workers.rs

1//! The worker registry: every worker the master has seen, with its state, kept after it is gone
2//! (offline or lost) so its logs can still be found (see archive/PROJECT.md, Worker lifecycle).
3//!
4//! The master is its only writer: on `Register`, at most once per heartbeat interval while the
5//! worker is connected, and on every change of state. At start it reads the registry back and
6//! counts every worker's lease from then (master downtime doesn't count against workers).
7
8use jiff::Timestamp;
9use schedr_model::WorkerState;
10
11use crate::database::{Database, DbError};
12use crate::query::{
13    db_time, from_json, from_name, in_tx, on_pool, optional_time, parse_time, sql, to_json,
14};
15
16#[cfg(test)]
17mod tests;
18
19/// What a worker reports when it registers.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct WorkerRegistration<'a> {
22    /// Its ID.
23    pub id: &'a str,
24    /// The incarnation of its agent process.
25    pub incarnation: &'a str,
26    /// Its protocol version (`major.minor`).
27    pub protocol_version: &'a str,
28    /// Its schedr version.
29    pub schedr_version: &'a str,
30    /// The queues it serves (none: `default`).
31    pub queues: &'a [String],
32    /// Its task slots.
33    pub slots: u32,
34    /// Its slots for wait steps.
35    pub watcher_slots: u32,
36    /// Where its log endpoint listens (empty until it has one).
37    pub log_endpoint: &'a str,
38}
39
40/// A worker in the registry.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct WorkerRecord {
43    /// Its ID.
44    pub id: String,
45    /// The incarnation it last registered with.
46    pub incarnation: String,
47    /// Its state.
48    pub state: WorkerState,
49    /// Its protocol version.
50    pub protocol_version: String,
51    /// Its schedr version.
52    pub schedr_version: String,
53    /// The queues it serves.
54    pub queues: Vec<String>,
55    /// Its task slots.
56    pub slots: u32,
57    /// Where its log endpoint listens.
58    pub log_endpoint: String,
59    /// When it last registered.
60    pub registered_at: Timestamp,
61    /// When the master last recorded a sign of life.
62    pub last_heartbeat_at: Timestamp,
63    /// When it went offline or was lost.
64    pub offline_at: Option<Timestamp>,
65    /// Its attempts still running (no end recorded).
66    pub running: u32,
67    /// Whether it is drained for maintenance (no new tasks until resumed).
68    pub drained: bool,
69    /// What is wrong with it now, as it last reported.
70    pub warnings: Vec<WorkerWarning>,
71    /// Its slots for wait steps.
72    pub watcher_slots: u32,
73    /// The processes running its wait steps, as its last heartbeat said.
74    pub watcher_hosts: Vec<WatcherHostRecord>,
75}
76
77/// A process running a worker's wait steps, or a code set whose hosts were lost.
78#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
79pub struct WatcherHostRecord {
80    /// The code it runs: its folders' names, the copies' hashes.
81    pub code: String,
82    /// The wait steps on it.
83    pub wait_steps: u32,
84    /// Its process's threads, the wait steps' among them.
85    pub threads: u32,
86    /// Those a wait step is tied to: running its `to_thread` calls, or started by it.
87    pub tied_threads: u32,
88    /// The memory it uses.
89    pub memory_bytes: u64,
90    /// Hosts of this code lost since the agent started: crashes and memory kills.
91    pub hosts_lost: u64,
92}
93
94/// Something wrong with a worker, as it reports it (e.g. a disabled fork server).
95#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
96pub struct WorkerWarning {
97    /// What kind, e.g. `fork_server_disabled`.
98    pub kind: String,
99    /// The interpreter it concerns; empty if none.
100    pub interpreter: String,
101    /// What it means for tasks, for people.
102    pub message: String,
103}
104
105type WorkerRow = (
106    String,
107    String,
108    String,
109    String,
110    String,
111    String,
112    i32,
113    String,
114    String,
115    String,
116    Option<String>,
117    i64,
118    bool,
119    String,
120    i32,
121    String,
122);
123
124impl Database {
125    /// Records a registration: the worker is active, with this incarnation and settings.
126    ///
127    /// # Errors
128    ///
129    /// [`DbError::Sqlx`] if the statement fails.
130    pub async fn register_worker(
131        &self,
132        worker: &WorkerRegistration<'_>,
133        now: Timestamp,
134    ) -> Result<(), DbError> {
135        const UPSERT: &str = "INSERT INTO workers (worker_id, incarnation_id, state, \
136            protocol_version, schedr_version, queues, slots, log_endpoint, registered_at, \
137            last_heartbeat_at, offline_at, watcher_slots, watcher_hosts) \
138            VALUES ($1, $2{uuid}, 'active', $3, $4, $5{json}, $6, $7, $8{ts}, $8{ts}, NULL, $9, \
139            $10{json}) \
140            ON CONFLICT (worker_id) DO UPDATE SET incarnation_id = excluded.incarnation_id, \
141            state = 'active', protocol_version = excluded.protocol_version, \
142            schedr_version = excluded.schedr_version, queues = excluded.queues, \
143            slots = excluded.slots, log_endpoint = excluded.log_endpoint, \
144            registered_at = excluded.registered_at, \
145            last_heartbeat_at = excluded.last_heartbeat_at, offline_at = NULL, \
146            watcher_slots = excluded.watcher_slots, watcher_hosts = excluded.watcher_hosts";
147        in_tx!(self, |tx, backend| {
148            sqlx::query(sql(backend, UPSERT))
149                .bind(worker.id)
150                .bind(worker.incarnation)
151                .bind(worker.protocol_version)
152                .bind(worker.schedr_version)
153                .bind(to_json(&worker.queues))
154                .bind(i32::try_from(worker.slots).unwrap_or(i32::MAX))
155                .bind(worker.log_endpoint)
156                .bind(db_time(now))
157                .bind(i32::try_from(worker.watcher_slots).unwrap_or(i32::MAX))
158                .bind("[]")
159                .execute(&mut *tx)
160                .await?;
161        });
162        Ok(())
163    }
164
165    /// Records a sign of life from a worker.
166    ///
167    /// # Errors
168    ///
169    /// [`DbError::Sqlx`] if the statement fails.
170    pub async fn worker_seen(&self, worker_id: &str, now: Timestamp) -> Result<(), DbError> {
171        const SEEN: &str = "UPDATE workers SET last_heartbeat_at = $1{ts} WHERE worker_id = $2";
172        in_tx!(self, |tx, backend| {
173            sqlx::query(sql(backend, SEEN))
174                .bind(db_time(now))
175                .bind(worker_id)
176                .execute(&mut *tx)
177                .await?;
178        });
179        Ok(())
180    }
181
182    /// Replaces a worker's warnings with what it reported now.
183    ///
184    /// # Errors
185    ///
186    /// [`DbError::Sqlx`] if the statement fails.
187    pub async fn set_worker_warnings(
188        &self,
189        worker_id: &str,
190        warnings: &[WorkerWarning],
191    ) -> Result<(), DbError> {
192        const SET: &str = "UPDATE workers SET warnings = $1{json} WHERE worker_id = $2";
193        in_tx!(self, |tx, backend| {
194            sqlx::query(sql(backend, SET))
195                .bind(to_json(&warnings))
196                .bind(worker_id)
197                .execute(&mut *tx)
198                .await?;
199        });
200        Ok(())
201    }
202
203    /// Replaces what a worker's hosts look like with what its heartbeat said now.
204    ///
205    /// # Errors
206    ///
207    /// [`DbError::Sqlx`] if the statement fails.
208    pub async fn set_worker_hosts(
209        &self,
210        worker_id: &str,
211        hosts: &[WatcherHostRecord],
212    ) -> Result<(), DbError> {
213        const SET: &str = "UPDATE workers SET watcher_hosts = $1{json} WHERE worker_id = $2";
214        in_tx!(self, |tx, backend| {
215            sqlx::query(sql(backend, SET))
216                .bind(to_json(&hosts))
217                .bind(worker_id)
218                .execute(&mut *tx)
219                .await?;
220        });
221        Ok(())
222    }
223
224    /// Records a worker's new state; going offline or lost also records when.
225    ///
226    /// # Errors
227    ///
228    /// [`DbError::Sqlx`] if the statement fails.
229    pub async fn set_worker_state(
230        &self,
231        worker_id: &str,
232        state: WorkerState,
233        now: Timestamp,
234    ) -> Result<(), DbError> {
235        const STATE: &str = "UPDATE workers SET state = $1, \
236            offline_at = CASE WHEN $2 THEN $3{ts} ELSE offline_at END WHERE worker_id = $4";
237        in_tx!(self, |tx, backend| {
238            sqlx::query(sql(backend, STATE))
239                .bind(state.to_string())
240                .bind(state.is_gone())
241                .bind(db_time(now))
242                .bind(worker_id)
243                .execute(&mut *tx)
244                .await?;
245        });
246        Ok(())
247    }
248
249    /// Drains a worker for maintenance, or resumes it; whether it is in the registry.
250    ///
251    /// # Errors
252    ///
253    /// [`DbError::Sqlx`] if the statement fails.
254    pub async fn set_worker_drained(
255        &self,
256        worker_id: &str,
257        drained: bool,
258    ) -> Result<bool, DbError> {
259        const DRAINED: &str = "UPDATE workers SET drained = $1 WHERE worker_id = $2";
260        let updated = in_tx!(self, |tx, backend| {
261            sqlx::query(sql(backend, DRAINED))
262                .bind(drained)
263                .bind(worker_id)
264                .execute(&mut *tx)
265                .await?
266                .rows_affected()
267        });
268        Ok(updated > 0)
269    }
270
271    /// Resumes a drained worker; whether it was drained (`None` for a worker not in the
272    /// registry).
273    ///
274    /// # Errors
275    ///
276    /// [`DbError::Sqlx`] if a statement fails.
277    pub async fn resume_worker(&self, worker_id: &str) -> Result<Option<bool>, DbError> {
278        const RESUME: &str = "UPDATE workers SET drained = $1 WHERE worker_id = $2 AND drained";
279        const KNOWN: &str = "SELECT 1 FROM workers WHERE worker_id = $1";
280        let (resumed, known) = in_tx!(self, |tx, backend| {
281            let resumed = sqlx::query(sql(backend, RESUME))
282                .bind(false)
283                .bind(worker_id)
284                .execute(&mut *tx)
285                .await?
286                .rows_affected();
287            let known: Option<i32> = sqlx::query_scalar(sql(backend, KNOWN))
288                .bind(worker_id)
289                .fetch_optional(&mut *tx)
290                .await?;
291            (resumed, known)
292        });
293        Ok(known.map(|_| resumed > 0))
294    }
295
296    /// Whether a worker is drained for maintenance (`false` for one not in the registry).
297    ///
298    /// # Errors
299    ///
300    /// [`DbError::Sqlx`] if the query fails.
301    pub async fn worker_drained(&self, worker_id: &str) -> Result<bool, DbError> {
302        const DRAINED: &str = "SELECT drained FROM workers WHERE worker_id = $1";
303        let drained: Option<bool> = on_pool!(self, |pool, backend| {
304            sqlx::query_scalar(sql(backend, DRAINED))
305                .bind(worker_id)
306                .fetch_optional(pool)
307                .await?
308        });
309        Ok(drained.unwrap_or(false))
310    }
311
312    /// Where one worker's log endpoint is, and its state (what the webserver needs to read a
313    /// log); `None` for a worker never registered.
314    ///
315    /// # Errors
316    ///
317    /// [`DbError`] if the query fails or the state doesn't read.
318    pub async fn worker_log_endpoint(
319        &self,
320        worker_id: &str,
321    ) -> Result<Option<(WorkerState, String)>, DbError> {
322        const ENDPOINT: &str = "SELECT state, log_endpoint FROM workers WHERE worker_id = $1";
323        let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
324            sqlx::query_as(sql(backend, ENDPOINT))
325                .bind(worker_id)
326                .fetch_optional(pool)
327                .await?
328        });
329        row.map(|(state, endpoint)| Ok((from_name("workers.state", state)?, endpoint)))
330            .transpose()
331    }
332
333    /// Every worker in the registry, by ID, with its running attempts counted.
334    ///
335    /// # Errors
336    ///
337    /// [`DbError`] if the query fails or stored data doesn't read.
338    pub async fn workers(&self) -> Result<Vec<WorkerRecord>, DbError> {
339        const WORKERS: &str = "SELECT w.worker_id, w.incarnation_id{text}, w.state, \
340            w.protocol_version, w.schedr_version, w.queues{text}, w.slots, w.log_endpoint, \
341            {ts<}w.registered_at{>ts}, {ts<}w.last_heartbeat_at{>ts}, {ts<}w.offline_at{>ts}, \
342            (SELECT COUNT(*) FROM attempts a WHERE a.worker_id = w.worker_id \
343             AND a.status IS NULL), w.drained, w.warnings{text}, w.watcher_slots, \
344            w.watcher_hosts{text} \
345            FROM workers w ORDER BY w.worker_id";
346        let rows: Vec<WorkerRow> = on_pool!(self, |pool, backend| {
347            sqlx::query_as(sql(backend, WORKERS))
348                .fetch_all(pool)
349                .await?
350        });
351        rows.into_iter().map(worker_record).collect()
352    }
353}
354
355fn worker_record(row: WorkerRow) -> Result<WorkerRecord, DbError> {
356    let (
357        id,
358        incarnation,
359        state,
360        protocol_version,
361        schedr_version,
362        queues,
363        slots,
364        log_endpoint,
365        registered,
366        heartbeat,
367        offline,
368        running,
369        drained,
370        warnings,
371        watcher_slots,
372        watcher_hosts,
373    ) = row;
374    Ok(WorkerRecord {
375        id,
376        incarnation,
377        state: from_name("workers.state", state)?,
378        protocol_version,
379        schedr_version,
380        queues: from_json("workers.queues", &queues)?,
381        slots: u32::try_from(slots).unwrap_or(0),
382        log_endpoint,
383        registered_at: parse_time("workers.registered_at", &registered)?,
384        last_heartbeat_at: parse_time("workers.last_heartbeat_at", &heartbeat)?,
385        offline_at: optional_time("workers.offline_at", offline)?,
386        running: u32::try_from(running).unwrap_or(0),
387        drained,
388        warnings: from_json("workers.warnings", &warnings)?,
389        watcher_slots: u32::try_from(watcher_slots).unwrap_or(0),
390        watcher_hosts: from_json("workers.watcher_hosts", &watcher_hosts)?,
391    })
392}