Skip to main content

schedr_bin/
standalone.rs

1//! `schedr standalone`: every role in one process, on localhost, with SQLite by default (see
2//! archive/PROJECT.md, Master–worker protocol: standalone uses the same gRPC protocol).
3//!
4//! The master's gRPC service, the REST API, the master's loop and one worker agent with its log
5//! endpoint run side by side; the agent talks to the master over gRPC on localhost like any
6//! worker, and the API reads logs from the endpoint (no TLS: neither listens beyond
7//! localhost, whatever `[tls]` says). `--migrate` migrates the database at start (a laptop);
8//! without it, a schema that isn't up to date is refused (production migrates as a step of its
9//! own, `schedr db migrate`). When the master fails (another took the lease over), the whole
10//! process ends, its tasks interrupted: restarted, it waits as a standby.
11//!
12//! In one pod (for testing on a cluster, see archive/PROJECT.md): `--listen 0.0.0.0` opens the REST
13//! API to a Service, SIGTERM stops it cleanly, and a lock in the data directory refuses a
14//! second standalone on the same data (two pods on one volume would schedule every run twice).
15
16use std::collections::BTreeMap;
17use std::net::{IpAddr, Ipv4Addr, SocketAddr};
18use std::path::{Path, PathBuf};
19use std::time::Duration;
20
21use prometheus_client::registry::Registry;
22use schedr_agent::agent::AgentSettings;
23use schedr_agent::memory::STANDALONE_RESERVE;
24use schedr_agent::metrics::AgentMetrics;
25use schedr_agent::retention::LogRetention;
26use schedr_api::metrics::ApiMetrics;
27use schedr_config::{AuthMode, AuthSection, Config};
28use schedr_db::Database;
29use schedr_master::core::Settings;
30use schedr_master::metrics::MasterMetrics;
31use schedr_master::problems::Problems;
32use tokio::sync::watch;
33
34use crate::app::AppError;
35use crate::node::{MasterIdentity, heartbeat_master, new_master_id, webserver_node};
36use crate::ops::{Health, Ops, ops_line, serve_ops};
37use crate::roles::{
38    LocalUi, MasterOutbox, Observed, WorkerLinks, agent_settings, check_timeouts, data_dir,
39    docs_dir, lead, listen, lock_journal, log_retention, master_outbox, master_settings,
40    memory_text, no_auth_warning, role_auth, run_worker, serve_api, serve_master, stop_on_signal,
41};
42use schedr_config::masked::masked;
43
44#[cfg(test)]
45mod tests;
46
47impl std::fmt::Debug for Standalone {
48    /// Its addresses and folders, the database URLs' passwords hidden (B206's review); the
49    /// configuration masked as its own `Debug` masks it.
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        let url = |url: &str| schedr_db::redact_password(url);
52        f.debug_struct("Standalone")
53            .field("data_dir", &self.data_dir)
54            .field("database_url", &url(&self.database_url))
55            .field(
56                "notifications_url",
57                &self.notifications_url.as_deref().map(url),
58            )
59            .field("grpc", &self.grpc)
60            .field("http", &self.http)
61            .field("ops", &self.ops)
62            .field("migrate", &self.migrate)
63            .field("config", &self.config)
64            .finish_non_exhaustive()
65    }
66}
67
68/// Everything `schedr standalone` runs, read from the configuration.
69#[derive(Clone)]
70pub struct Standalone {
71    /// The secret storages, made once the database is connected (`db` among them).
72    pub secret_storage: crate::secret_storage::SecretPlan,
73    /// Where logs, the worker's journal and the SQLite database go.
74    pub data_dir: PathBuf,
75    /// The mode of its worker's logs (`[worker] log_mode`, B182).
76    pub log_mode: u32,
77    /// The database (`[database] url`, else SQLite in the data directory).
78    pub database_url: String,
79    /// The master's gRPC address.
80    pub grpc: SocketAddr,
81    /// The REST API's address.
82    pub http: SocketAddr,
83    /// The worker's log endpoint's address.
84    pub logs: SocketAddr,
85    /// The ops port's address.
86    pub ops: SocketAddr,
87    /// How the users and the UI's token are followed.
88    pub auth_timings: schedr_api::auth::AuthTimings,
89    /// How often its row of the deployment's nodes is written.
90    pub node_heartbeat: Duration,
91    /// How long a gone master's row stays (`SCHEDR_HIDDEN__MASTER__NODE_ROW_KEPT`).
92    pub node_row_kept: Duration,
93    /// How often it tries again to reach a database it can't reach at its start
94    /// (`SCHEDR_HIDDEN__WEBSERVER__SCHEMA_RETRY`).
95    pub schema_retry: Duration,
96    /// The DAG versions kept parsed (`SCHEDR_HIDDEN__DATABASE__DAG_VERSIONS_CACHED`).
97    pub dag_versions_cached: usize,
98    /// How long the worker gets to stop once the master failed: its tasks are interrupted at
99    /// once (nothing could record them), so this is only for a worker stuck on its way out
100    /// (B151).
101    pub worker_stop_after_failure: Duration,
102    /// How long a loop may go without turning before liveness fails.
103    pub loop_stall_timeout: Duration,
104    /// The longest a database query may take.
105    pub query_timeout: Duration,
106    /// `[database] notifications`: whether new commands are announced and listened for.
107    pub notifications: bool,
108    /// `[database] notifications_url`: what the master listens through, if not the database's
109    /// own connection.
110    pub notifications_url: Option<String>,
111    /// The master's lease (one master per database).
112    pub lease_period: Duration,
113    /// What logs the worker keeps.
114    pub retention: LogRetention,
115    /// The master's timing.
116    pub master: Settings,
117    /// `[notifications]`, checked, and its sender's timings.
118    pub outbox: MasterOutbox,
119    /// How often the master's loop runs.
120    pub tick: Duration,
121    /// The worker agent.
122    pub agent: AgentSettings,
123    /// How long one DAG file may take to import, and how many are parsed at once.
124    pub parse: schedr_agent::parse::ParseLimits,
125    /// Who the user is (`[webserver.auth]`).
126    pub auth: AuthSection,
127    /// The token a UI elsewhere presents to pass users' names on (`[webserver] ui_token_file`:
128    /// a federation of standalones, decision 36).
129    pub ui_token_file: Option<PathBuf>,
130    /// How long the webserver waits, and how often live pages refresh when the database's
131    /// changes can't be followed.
132    pub api_timings: crate::roles::ApiTimings,
133    /// Whether the writes announce their changes (applied with `--migrate`).
134    pub change_notifications: bool,
135    /// The web UI it serves next to its API; none with `--no-ui`.
136    pub ui: Option<LocalUi>,
137    /// Whether to migrate the database at start (`--migrate`).
138    pub migrate: bool,
139    /// Its configuration, masked: shown on the Deployments page for its master and worker.
140    pub config: serde_json::Value,
141}
142
143/// The addresses standalone listens on, once it does.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct Listening {
146    /// The master's gRPC address.
147    pub grpc: SocketAddr,
148    /// The REST API's address.
149    pub http: SocketAddr,
150    /// The worker's log endpoint's address.
151    pub logs: SocketAddr,
152    /// The ops port's address.
153    pub ops: SocketAddr,
154}
155
156/// Standalone's SQLite file in the data directory, without `[database] url`.
157#[must_use]
158pub fn sqlite_file(data_dir: &Path) -> PathBuf {
159    data_dir.join("schedr.db")
160}
161
162/// Reads the standalone setup from the configuration and the environment (`env` gives the
163/// data directory's default, the host name and what tasks may inherit).
164///
165/// # Errors
166///
167/// [`AppError::BadArgument`] when there is no data directory to use, or the DAG interpreter
168/// isn't defined.
169pub fn plan(config: &Config, env: &BTreeMap<String, String>) -> Result<Standalone, AppError> {
170    check_timeouts(config)?;
171    let data_dir = data_dir(config, env)?;
172    let database_url = config
173        .database
174        .url
175        .clone()
176        .unwrap_or_else(|| format!("sqlite://{}", sqlite_file(&data_dir).display()));
177    let localhost = |port| SocketAddr::from((Ipv4Addr::LOCALHOST, port));
178    Ok(Standalone {
179        grpc: localhost(config.master.grpc_port),
180        http: localhost(config.webserver.port),
181        logs: localhost(config.worker.log_port),
182        ops: localhost(config.ops.port),
183        loop_stall_timeout: config.timings.loop_stall_timeout,
184        query_timeout: config.timings.query_timeout,
185        notifications: config.database.notifications,
186        notifications_url: config.database.notifications_url.clone(),
187        lease_period: config.timings.lease_period,
188        retention: log_retention(config),
189        log_mode: crate::roles::log_mode(config),
190        master: schedr_master::core::Settings {
191            // Its webserver is this process: sampled with the master (decision 464).
192            with_webserver: true,
193            ..master_settings(config)
194        },
195        outbox: master_outbox(config, env)?,
196        tick: config.timings.tick_interval,
197        agent: agent_settings(config, env, &data_dir, STANDALONE_RESERVE)?,
198        secret_storage: crate::secret_storage::SecretPlan::new(&config.secret_storage, env)
199            .renewing(&config.timings),
200        parse: schedr_agent::parse::ParseLimits::configured(
201            config.dags.parse_file_timeout,
202            config.dags.parse_concurrency,
203        ),
204        auth: config.webserver.auth.clone(),
205        ui_token_file: config.webserver.ui_token_file.clone(),
206        api_timings: crate::roles::ApiTimings::of(config),
207        change_notifications: config.database.change_notifications,
208        auth_timings: crate::roles::auth_timings(&config.timings, &config.limits),
209        node_heartbeat: config.timings.node_heartbeat,
210        node_row_kept: config.timings.node_row_kept,
211        schema_retry: config.timings.schema_retry,
212        dag_versions_cached: config.limits.dag_versions_cached,
213        worker_stop_after_failure: config.timings.worker_stop_after_failure,
214        ui: Some(LocalUi {
215            timings: crate::roles::ui_timings(&config.timings, &config.limits),
216            docs_dir: docs_dir(config),
217        }),
218        migrate: false,
219        config: masked(config),
220        database_url,
221        data_dir,
222    })
223}
224
225impl Standalone {
226    /// How it takes the master's lease ([`lead`]): its period, `--migrate`, and the change
227    /// notifications to apply with a migration.
228    const fn lease(&self) -> (Duration, bool, bool) {
229        (self.lease_period, self.migrate, self.change_notifications)
230    }
231}
232
233/// Standalone's listeners (gRPC, HTTP, logs, ops) and where they listen.
234async fn bind(setup: &Standalone) -> Result<([tokio::net::TcpListener; 4], Listening), AppError> {
235    let io = |what: &str, e: std::io::Error| AppError::BadArgument(format!("{what}: {e}"));
236    let grpc = listen(setup.grpc).await?;
237    let http = listen(setup.http).await?;
238    let logs = listen(setup.logs).await?;
239    let ops = listen(setup.ops).await?;
240    let addresses = Listening {
241        ops: ops.local_addr().map_err(|e| io("ops address", e))?,
242        grpc: grpc.local_addr().map_err(|e| io("gRPC address", e))?,
243        http: http.local_addr().map_err(|e| io("HTTP address", e))?,
244        logs: logs
245            .local_addr()
246            .map_err(|e| io("log endpoint address", e))?,
247    };
248    Ok(([grpc, http, logs, ops], addresses))
249}
250
251impl Standalone {
252    /// Its database, connected, with its notifications and DAG cache as configured.
253    async fn database(&self) -> Result<Database, AppError> {
254        Ok(
255            Database::connect_with_timeout(&self.database_url, self.query_timeout)
256                .await?
257                .with_notifications(self.notifications, self.notifications_url.clone())
258                .with_dag_versions_cached(self.dag_versions_cached),
259        )
260    }
261
262    /// Its master's row: the configuration shown, how often it is written and how long it
263    /// stays once gone.
264    const fn node_beat(&self) -> (&serde_json::Value, (Duration, Duration)) {
265        (&self.config, (self.node_heartbeat, self.node_row_kept))
266    }
267
268    /// What the master's loop runs with: its tick, the events' limit and the notifications.
269    fn master_loop(
270        &self,
271    ) -> (
272        Duration,
273        (usize, schedr_api::state::ApiLimits),
274        MasterOutbox,
275    ) {
276        (
277            self.tick,
278            (self.api_timings.max_event_size, self.api_timings.limits),
279            self.outbox.clone(),
280        )
281    }
282}
283
284/// Runs standalone until asked to stop (`shutdown` counts the requests): its worker drains
285/// first (a second request interrupts its tasks at once), then the master and the API stop,
286/// so interrupted tasks are recorded; `listening` gets the addresses once bound. A failing
287/// master ends it too, its worker's tasks interrupted at once (nothing can record them).
288///
289/// # Errors
290///
291/// [`AppError`] if the data directory, the database or a port can't be set up, the schema
292/// isn't up to date (without `migrate`), or the master fails.
293#[expect(
294    clippy::too_many_lines,
295    reason = "the start in order: data, database, servers, roles"
296)]
297pub async fn run(
298    setup: Standalone,
299    listening: impl FnOnce(Listening),
300    shutdown: watch::Receiver<u32>,
301) -> Result<(), AppError> {
302    let lease = setup.lease();
303    let io = |what: &str, e: std::io::Error| AppError::BadArgument(format!("{what}: {e}"));
304    tokio::fs::create_dir_all(&setup.data_dir)
305        .await
306        .map_err(|e| io(&format!("can't create {}", setup.data_dir.display()), e))?;
307    let _lock = lock_data_dir(&setup.data_dir)?;
308    let _journal_lock = lock_journal(&setup.agent)?;
309    // After the lock: a second standalone on the data directory stops before touching it.
310    schedr_agent::connection_env::prepare(&setup.agent.setup.connection_dir)
311        .map_err(AppError::BadArgument)?;
312    crate::roles::secure_logs(setup.log_mode, &setup.agent.setup.log_dir)?;
313    let ([grpc, http, logs, ops], addresses) = bind(&setup).await?;
314    let auth = standalone_auth(&setup, addresses.http)?;
315    listening(addresses);
316    let (tick, max_event_size, outbox) = setup.master_loop();
317
318    // The master and the API stop once the worker has drained.
319    let (stop, stopped) = watch::channel(0);
320    // One ops port for every part.
321    let health = Health::new(setup.loop_stall_timeout);
322    let (registry, master_observed, api_observed, agent_observed) = observed(&health);
323
324    let ops_server = tokio::spawn(serve_ops(
325        ops,
326        Ops::new(registry, health.clone()),
327        stopped.clone(),
328    ));
329    // The ops port answers (`/readyz`: starting) meanwhile. One master per database: an
330    // up-to-date schema lets the API and the worker start while the master waits for the
331    // lease (a standby); with `--migrate`, one to migrate is migrated by the lease's holder.
332    let connected = crate::roles::once_reached(
333        ("standalone", &setup.database_url),
334        setup.schema_retry,
335        shutdown.clone(),
336        || setup.database(),
337    );
338    let Some(db) = connected.await? else {
339        return Ok(());
340    };
341    let secrets = setup.secret_storage.for_role(Some(&db))?;
342    let (master_id, problems, heartbeat) = heartbeat(&db, setup.node_beat(), &stopped);
343    let mut agent = setup.agent;
344    agent.log_endpoint = format!("http://{}", addresses.logs);
345    agent.secrets = secrets;
346    let leading = lead(
347        &db,
348        &setup.database_url,
349        lease,
350        (shutdown.clone(), setup.schema_retry),
351        ("standalone", master_id),
352    );
353    let Some(leadership) = leading.await? else {
354        return Ok(());
355    };
356    // The worker's stop requests: the signals', and the master's failure (two at once: its
357    // tasks interrupted, nothing could record them).
358    let (request, requests) = watch::channel(0);
359    // Once the master failed, the worker gets `worker_stop_after_failure` to stop (B151).
360    let (master_failed, failed) = watch::channel(false);
361    let forwarding = tokio::spawn(forward_requests(shutdown, request.clone()));
362    // Boxed: the roles' futures are large.
363    let master_db = db.clone();
364    let master = Box::pin(async {
365        let served = Box::pin(serve_master(
366            master_db,
367            setup.master,
368            (tick, problems, max_event_size, outbox),
369            grpc,
370            None,
371            leadership,
372            master_observed,
373            stopped.clone(),
374        ))
375        .await;
376        if let Err(error) = &served {
377            tracing::error!(%error, "the master failed: standalone stops");
378            request.send_modify(|requests| *requests = (*requests).max(2));
379            let _ = master_failed.send(true);
380        }
381        served
382    });
383    let node = webserver_node(setup.config.clone());
384    let api = Box::pin(serve_api(
385        db,
386        (auth, setup.api_timings, node),
387        (http, None),
388        None,
389        setup.ui.clone(),
390        api_observed,
391        stopped.clone(),
392    ));
393    let links = WorkerLinks {
394        master_url: format!("http://{}", addresses.grpc),
395        tls: None,
396        log_listener: logs,
397        retention: setup.retention,
398        max_message_size: setup.master.max_message_size,
399    };
400    let worker = Box::pin(run_worker(
401        agent,
402        setup.parse,
403        links,
404        agent_observed,
405        requests,
406    ));
407    let given = setup.worker_stop_after_failure;
408    let worker = worker_then_stop(worker, failed, stop, given);
409    let (master, api, ()) = tokio::join!(master, api, worker);
410    forwarding.abort();
411    heartbeat.abort();
412    if let Ok(Err(error)) = ops_server.await {
413        tracing::warn!(%error, "the ops port failed");
414    }
415    master?;
416    api
417}
418
419/// Who a standalone's requests are from, by `setup`, on `http`.
420fn standalone_auth(
421    setup: &Standalone,
422    http: SocketAddr,
423) -> Result<schedr_api::auth::Auth, AppError> {
424    role_auth(
425        "webserver",
426        &setup.auth,
427        http,
428        setup.ui_token_file.as_deref(),
429        setup.auth_timings,
430    )
431}
432
433/// Runs the worker (given `given` once `failed`), then stops the master
434/// and the API.
435async fn worker_then_stop(
436    worker: impl Future<Output = ()>,
437    failed: watch::Receiver<bool>,
438    stop: watch::Sender<u32>,
439    given: Duration,
440) {
441    if !ended_within(worker, failed, given).await {
442        tracing::error!(
443            "the worker didn't stop within {}s of the master's failure: stopping anyway",
444            given.as_secs()
445        );
446    }
447    let _ = stop.send(1);
448}
449
450/// Runs `work` to its end, or until `bound` after `failed` turned true: whether it ended.
451/// `failed` closing without turning true bounds nothing.
452pub async fn ended_within(
453    work: impl Future<Output = ()>,
454    mut failed: watch::Receiver<bool>,
455    bound: Duration,
456) -> bool {
457    let cut_short = async {
458        if failed.wait_for(|failed| *failed).await.is_err() {
459            std::future::pending::<()>().await;
460        }
461        tokio::time::sleep(bound).await;
462    };
463    tokio::select! {
464        () = work => true,
465        () = cut_short => false,
466    }
467}
468
469/// Its master's row on the Deployments page, written from now on until `stopped`: the
470/// master's ID (to take the lease as), its problems (the master reports them there) and the
471/// writing task.
472fn heartbeat(
473    db: &Database,
474    (config, (beat, row_kept)): (&serde_json::Value, (Duration, Duration)),
475    stopped: &watch::Receiver<u32>,
476) -> (String, Problems, tokio::task::JoinHandle<()>) {
477    let problems = Problems::default();
478    let identity = MasterIdentity {
479        master_id: new_master_id(),
480        config: config.clone(),
481        problems: problems.clone(),
482        heartbeat: beat,
483        row_kept,
484    };
485    let master_id = identity.master_id.clone();
486    let task = tokio::spawn(heartbeat_master(db.clone(), identity, stopped.clone()));
487    (master_id, problems, task)
488}
489
490/// The ops port's registry with every part's metrics, and what each part reports to it.
491fn observed(
492    health: &Health,
493) -> (
494    Registry,
495    Observed<'_, MasterMetrics>,
496    Observed<'_, ApiMetrics>,
497    Observed<'_, AgentMetrics>,
498) {
499    let (master_metrics, api_metrics, agent_metrics) = (
500        MasterMetrics::default(),
501        ApiMetrics::default(),
502        AgentMetrics::default(),
503    );
504    let mut registry = Registry::default();
505    let schedr = registry.sub_registry_with_prefix("schedr");
506    master_metrics.register(schedr);
507    api_metrics.register(schedr);
508    agent_metrics.register(schedr);
509    let part = |name| health.starting(name);
510    (
511        registry,
512        Observed {
513            metrics: master_metrics,
514            health,
515            ready: part("master"),
516        },
517        Observed {
518            metrics: api_metrics,
519            health,
520            ready: part("webserver"),
521        },
522        Observed {
523            metrics: agent_metrics,
524            health,
525            ready: part("worker"),
526        },
527    )
528}
529
530/// Passes the stop requests counted by `from` on to `to` (never lowering its count).
531async fn forward_requests(mut from: watch::Receiver<u32>, to: watch::Sender<u32>) {
532    loop {
533        let requests = *from.borrow_and_update();
534        to.send_modify(|count| *count = (*count).max(requests));
535        if from.changed().await.is_err() {
536            return;
537        }
538    }
539}
540
541/// The name of the lock file in the data directory.
542pub const LOCK_FILE: &str = "standalone.lock";
543
544/// Takes the data directory's lock for as long as the returned file is open: one standalone
545/// per data directory (and its SQLite database).
546///
547/// # Errors
548///
549/// [`AppError::BadArgument`] if another process holds it, or the file can't be opened.
550pub fn lock_data_dir(data_dir: &Path) -> Result<std::fs::File, AppError> {
551    let path = data_dir.join(LOCK_FILE);
552    let file = std::fs::OpenOptions::new()
553        .create(true)
554        .truncate(false)
555        .write(true)
556        .open(&path)
557        .map_err(|e| {
558            let hint = if e.kind() == std::io::ErrorKind::PermissionDenied {
559                ": the data directory must be writable by this user (on Kubernetes, give the \
560                 pod an fsGroup the user belongs to)"
561            } else {
562                ""
563            };
564            AppError::BadArgument(format!("can't open {}: {e}{hint}", path.display()))
565        })?;
566    rustix::fs::flock(&file, rustix::fs::FlockOperation::NonBlockingLockExclusive).map_err(
567        |errno| {
568            if errno == rustix::io::Errno::WOULDBLOCK {
569                AppError::BadArgument(format!(
570                    "another schedr standalone is using {} (it holds {}): one standalone per \
571                     data directory; on Kubernetes run one replica (a StatefulSet, or a \
572                     Deployment with strategy Recreate)",
573                    data_dir.display(),
574                    path.display()
575                ))
576            } else {
577                AppError::BadArgument(format!(
578                    "can't lock {}: {errno} (a network filesystem? the data directory needs a \
579                     local disk or block storage)",
580                    path.display()
581                ))
582            }
583        },
584    )?;
585    Ok(file)
586}
587
588/// The line standalone prints once it listens.
589#[must_use]
590pub fn banner(listening: Listening, setup: &Standalone) -> String {
591    format!(
592        "schedr standalone: API on http://{}, master on {}, {}, data in {}",
593        listening.http,
594        listening.grpc,
595        ops_line(listening.ops),
596        setup.data_dir.display()
597    )
598}
599
600/// Runs `schedr standalone` until Ctrl-C or SIGTERM, the REST API on `listen` (127.0.0.1 when
601/// not given); the banner goes to the log once it listens.
602///
603/// # Errors
604///
605/// As [`plan`] and [`run`].
606pub async fn command(
607    config: &Config,
608    env: &BTreeMap<String, String>,
609    listen: Option<IpAddr>,
610    (migrate, no_ui): (bool, bool),
611) -> Result<(), AppError> {
612    let stop = stop_on_signal();
613    let mut setup = plan(config, env)?;
614    crate::roles::warn_without_dag_roots(config, true);
615    setup.migrate = migrate;
616    if no_ui {
617        setup.ui = None;
618    }
619    if let Some(address) = listen {
620        // Probes and scrapes come from outside the pod too.
621        setup.http.set_ip(address);
622        setup.ops.set_ip(address);
623    }
624    let shown = setup.clone();
625    Box::pin(run(
626        setup,
627        |listening| {
628            if shown.auth.mode == AuthMode::None
629                && let Some(warning) =
630                    no_auth_warning(listening.http, "reach it with kubectl port-forward")
631            {
632                tracing::warn!("{warning}");
633            }
634            tracing::info!("{}", banner(listening, &shown));
635            tracing::info!("{}", memory_text(&shown.agent.setup.memory));
636        },
637        stop,
638    ))
639    .await
640}