1use 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 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#[derive(Clone)]
70pub struct Standalone {
71 pub secret_storage: crate::secret_storage::SecretPlan,
73 pub data_dir: PathBuf,
75 pub log_mode: u32,
77 pub database_url: String,
79 pub grpc: SocketAddr,
81 pub http: SocketAddr,
83 pub logs: SocketAddr,
85 pub ops: SocketAddr,
87 pub auth_timings: schedr_api::auth::AuthTimings,
89 pub node_heartbeat: Duration,
91 pub node_row_kept: Duration,
93 pub schema_retry: Duration,
96 pub dag_versions_cached: usize,
98 pub worker_stop_after_failure: Duration,
102 pub loop_stall_timeout: Duration,
104 pub query_timeout: Duration,
106 pub notifications: bool,
108 pub notifications_url: Option<String>,
111 pub lease_period: Duration,
113 pub retention: LogRetention,
115 pub master: Settings,
117 pub outbox: MasterOutbox,
119 pub tick: Duration,
121 pub agent: AgentSettings,
123 pub parse: schedr_agent::parse::ParseLimits,
125 pub auth: AuthSection,
127 pub ui_token_file: Option<PathBuf>,
130 pub api_timings: crate::roles::ApiTimings,
133 pub change_notifications: bool,
135 pub ui: Option<LocalUi>,
137 pub migrate: bool,
139 pub config: serde_json::Value,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct Listening {
146 pub grpc: SocketAddr,
148 pub http: SocketAddr,
150 pub logs: SocketAddr,
152 pub ops: SocketAddr,
154}
155
156#[must_use]
158pub fn sqlite_file(data_dir: &Path) -> PathBuf {
159 data_dir.join("schedr.db")
160}
161
162pub 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 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 const fn lease(&self) -> (Duration, bool, bool) {
229 (self.lease_period, self.migrate, self.change_notifications)
230 }
231}
232
233async 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 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 const fn node_beat(&self) -> (&serde_json::Value, (Duration, Duration)) {
265 (&self.config, (self.node_heartbeat, self.node_row_kept))
266 }
267
268 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#[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 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 let (stop, stopped) = watch::channel(0);
320 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 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 let (request, requests) = watch::channel(0);
359 let (master_failed, failed) = watch::channel(false);
361 let forwarding = tokio::spawn(forward_requests(shutdown, request.clone()));
362 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
419fn 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
433async 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
450pub 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
469fn 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
490fn 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
530async 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
541pub const LOCK_FILE: &str = "standalone.lock";
543
544pub 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#[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
600pub 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 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}