Skip to main content

schedr_bin/
lib.rs

1//! The schedr binary's library part: everything `main.rs` runs, kept here so it can be tested.
2//!
3//! [`run`] takes the arguments, the environment, a file reader and the output streams as
4//! inputs, so the whole command line can be exercised in unit tests.
5
6use std::collections::BTreeMap;
7use std::ffi::OsString;
8use std::io::{self, Write};
9use std::path::Path;
10
11use clap::Parser;
12use clap::error::ErrorKind;
13
14pub mod app;
15pub mod cli;
16pub mod ctx;
17pub use schedr_client as client;
18pub mod interpreter;
19pub mod local;
20pub mod logging;
21pub mod node;
22pub mod ops;
23pub mod roles;
24pub mod secret_storage;
25pub mod secrets;
26pub mod standalone;
27pub mod task_api;
28pub use schedr_client::times;
29pub mod user;
30
31#[cfg(test)]
32mod tests;
33
34/// The schedr version, shared by the binary and the Python package.
35pub const VERSION: &str = env!("CARGO_PKG_VERSION");
36
37/// Exit code for wrong usage (unknown command, bad arguments).
38pub const EXIT_USAGE: u8 = 2;
39
40/// Runs `schedr` with the given arguments (including the program name) and returns the
41/// process exit code: 0 on success, 1 on an error, 2 on wrong usage.
42pub fn run<I, T>(
43    args: I,
44    env: &BTreeMap<String, String>,
45    read_file: impl Fn(&Path) -> io::Result<String>,
46    stdout_is_terminal: bool,
47    out: &mut impl Write,
48    err: &mut impl Write,
49) -> u8
50where
51    I: IntoIterator<Item = T>,
52    T: Into<OsString> + Clone,
53{
54    let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
55    let mut cli = match cli::Cli::try_parse_from(&args) {
56        Ok(cli) => cli,
57        Err(e) if matches!(e.kind(), ErrorKind::DisplayHelp | ErrorKind::DisplayVersion) => {
58            return report(out, &e.to_string(), 0);
59        }
60        // clap quotes what it refused, and a `secrets` argument may be a value (`get etl/db
61        // password=...`): only the kind of mistake (Grok's finding in M4.6c's review).
62        Err(e) if args.iter().skip(1).any(|a| a == "secrets") => {
63            let message = format!(
64                "error: {}\n\nRun `schedr secrets --help` (the arguments aren't shown: one may \
65                 be a secret's value)\n",
66                e.kind()
67            );
68            return report(err, &message, EXIT_USAGE);
69        }
70        Err(e) => return report(err, &e.to_string(), EXIT_USAGE),
71    };
72    // Inside a task, before the configuration: a task may have none, and the call is one
73    // request on the task's channel (decision 147: the descriptor is adopted before any
74    // thread starts).
75    // A task's start under a hard memory cap: nothing else first, its program replaces this.
76    if let cli::Command::TaskExec {
77        data_limit,
78        command,
79    } = &cli.command
80    {
81        return task_exec(*data_limit, command, err);
82    }
83    if let cli::Command::DagCtx { command } = &cli.command {
84        return match ctx::run_dag_ctx(command, env, VERSION, out) {
85            Ok(()) => 0,
86            Err(message) => report(err, &format!("error: {message}\n"), 1),
87        };
88    }
89    if let cli::Command::TaskCtx { command } = &cli.command {
90        return match ctx::run_task_ctx(command, env, VERSION, (&mut *out, &mut *err)) {
91            Ok(()) => 0,
92            Err(message) => report(err, &format!("error: {message}\n"), 1),
93        };
94    }
95    // The working folder, for `--dag-path .`; none (removed) leaves `.` unnamed, refused.
96    let cwd = std::env::current_dir().unwrap_or_default();
97    let overrides = match cli.command.overrides(&cwd) {
98        Ok(overrides) => overrides,
99        Err(message) => return report(err, &format!("error: {message}\n"), EXIT_USAGE),
100    };
101    let config = match app::load_config_with(cli.config.as_deref(), env, read_file, &overrides) {
102        Ok(config) => config,
103        Err(e) => return report(err, &format!("error: {e}\n"), e.exit_code()),
104    };
105    if let Some(client) = cli.command.client_args_mut() {
106        client.timeouts = schedr_client::Timeouts {
107            connect: config.timings.client_connect_timeout,
108            request: config.timings.client_request_timeout,
109            command_wait: config.timings.client_command_wait,
110        };
111    }
112    if let Err(message) = logging::init(&config.log, stdout_is_terminal) {
113        return report(err, &format!("error: {message}\n"), 1);
114    }
115    for name in &config.timings.overridden {
116        tracing::warn!("{name} is set: an unsupported timing, at your own risk");
117    }
118    for name in &config.limits.overridden {
119        tracing::warn!("{name} is set: an unsupported limit, at your own risk");
120    }
121    let runtime = match tokio::runtime::Builder::new_multi_thread()
122        .enable_all()
123        .build()
124    {
125        Ok(runtime) => runtime,
126        Err(e) => {
127            return report(
128                err,
129                &format!("error: can't start the async runtime: {e}\n"),
130                1,
131            );
132        }
133    };
134    match runtime.block_on(app::execute(&cli.command, &config, env, out, err)) {
135        Ok(()) => 0,
136        Err(e) => report(err, &format!("error: {e}\n"), e.exit_code()),
137    }
138}
139
140/// Writes `message` to `stream` and returns `code` (a failed write can't be reported anyway).
141fn report(stream: &mut impl Write, message: &str, code: u8) -> u8 {
142    let _ = stream.write_all(message.as_bytes());
143    code
144}
145
146/// `schedr task-exec`: sets `RLIMIT_DATA` to `limit` (current and maximum: the task can't raise
147/// it) and runs `command` in this process's place, so its pid, process group, environment and
148/// inherited descriptors stay the worker's to watch. Returns only when that fails.
149fn task_exec(limit: u64, command: &[std::ffi::OsString], err: &mut impl Write) -> u8 {
150    use std::os::unix::process::CommandExt as _;
151    let cap = rustix::process::Rlimit {
152        current: Some(limit),
153        maximum: Some(limit),
154    };
155    if let Err(error) = rustix::process::setrlimit(rustix::process::Resource::Data, cap) {
156        return report(
157            err,
158            &format!("error: can't cap the task's memory: {error}\n"),
159            1,
160        );
161    }
162    let Some((program, args)) = command.split_first() else {
163        return report(err, "error: task-exec: no program given\n", EXIT_USAGE);
164    };
165    let error = std::process::Command::new(program).args(args).exec();
166    report(
167        err,
168        &format!(
169            "error: can't start `{}`: {error}\n",
170            program.to_string_lossy()
171        ),
172        127,
173    )
174}