Skip to main content

schedr_agent/
connection_jobs.rs

1//! `schedr connections check` and `test` on this worker (decisions 174, 193, 198-200): a
2//! check renders each connection through the worker's secret storages, saying of every
3//! secret it names whether it is there (never a value); a test opens one connection in a
4//! runner and runs its check, as a one-off attempt beside the tasks (no slot), stopped after
5//! its timeout. One job at a time per worker.
6
7use std::path::PathBuf;
8use std::sync::Arc;
9use std::time::Duration;
10
11use schedr_model::commands::{ConnectionReport, SecretReport, SecretState};
12use schedr_model::connection::Registry;
13use schedr_model::runner::{ErrorSummary, RunInfo};
14use serde_json::json;
15
16use crate::attempt::AttemptSpec;
17use crate::secrets::{AttemptSecrets, SecretError, SecretStores};
18
19#[cfg(test)]
20mod tests;
21
22/// How long a test's process gets from SIGTERM to SIGKILL, unless `connection_job_cancel_grace`
23/// says.
24pub const CANCEL_GRACE: Duration = Duration::from_secs(5);
25
26/// A connections job, as the master sent it.
27#[derive(Debug, Clone)]
28pub struct ConnectionJob {
29    /// The root.
30    pub root: String,
31    /// The root's code, where a test imports the connection's file.
32    pub code_dir: Option<PathBuf>,
33    /// The connections to check (their files with them).
34    pub registry: Arc<Registry>,
35    /// A test: the connection, and how long it may take.
36    pub test: Option<(String, Duration)>,
37    /// How long a test's process gets from SIGTERM to SIGKILL.
38    pub cancel_grace: Duration,
39    /// A test's attempt ID (its folders, its journal record).
40    pub attempt_id: String,
41    /// When its time is up: an answer comes by then (a test's process stopped).
42    pub deadline: tokio::time::Instant,
43}
44
45/// Renders each connection of `registry` (decision 174): its secrets present or missing,
46/// and whether it renders, a refused one with why.
47pub async fn check(stores: &Arc<SecretStores>, registry: &Arc<Registry>) -> Vec<ConnectionReport> {
48    let mut reports = Vec::new();
49    for (name, why) in &registry.refused {
50        reports.push(failed(name, why.clone()));
51    }
52    for (name, def) in &registry.connections {
53        let mut secrets = Vec::new();
54        for secret in def.secrets() {
55            let (state, message) = match stores.fetch(secret).await {
56                Ok(_) => (SecretState::Present, None),
57                // As an attempt reads it: the default stands in, in a storage the worker has.
58                Err(SecretError::NotFound(_))
59                    if secret.default.is_some() && stores.storage_of(secret).is_ok() =>
60                {
61                    (SecretState::Default, None)
62                }
63                Err(SecretError::NotFound(_)) => (SecretState::Missing, None),
64                Err(SecretError::Denied(why)) => (SecretState::Denied, Some(why)),
65                Err(SecretError::Unavailable(why)) => (SecretState::Unavailable, Some(why)),
66            };
67            secrets.push(SecretReport {
68                secret: secret.to_string(),
69                state,
70                message,
71            });
72        }
73        let attempt = AttemptSecrets::none(Arc::clone(stores))
74            .with_connections(Arc::clone(registry), vec![name.clone()]);
75        let error = attempt
76            .connection(name)
77            .await
78            .err()
79            .map(|e| attempt.mask.mask_text(&e.to_string()));
80        // Read twice (states, then the rendering): ok only when both say so.
81        let all_there = secrets
82            .iter()
83            .all(|s| matches!(s.state, SecretState::Present | SecretState::Default));
84        let error = error.or_else(|| {
85            (!all_there).then(|| format!("connection `{name}`: a secret it names isn't there"))
86        });
87        reports.push(ConnectionReport {
88            name: name.clone(),
89            ok: error.is_none(),
90            secrets,
91            error,
92            duration_ms: None,
93        });
94    }
95    reports
96}
97
98/// The one-off attempt a test of `name` runs (decision 198): a Python "task" of the
99/// connection's file, its runner told to open and check the connection instead.
100///
101/// # Errors
102///
103/// Why it can't run: a refused connection, or one with no file recorded.
104pub fn test_spec(
105    job: &ConnectionJob,
106    name: &str,
107    timeout: Duration,
108    attempt_id: String,
109) -> Result<AttemptSpec, String> {
110    if let Some(why) = job.registry.refused.get(name) {
111        return Err(why.clone());
112    }
113    let Some(path) = job.registry.files.get(name) else {
114        return Err(format!(
115            "connection `{name}`: no file of root `{}` defines it",
116            job.root
117        ));
118    };
119    // Imported from the root's code only (the master refuses such a path too).
120    let inside = std::path::Path::new(path)
121        .components()
122        .all(|c| matches!(c, std::path::Component::Normal(_)));
123    if path.is_empty() || !inside {
124        return Err(format!(
125            "connection `{name}`: `{path}` isn't a path inside root `{}`",
126            job.root
127        ));
128    }
129    let timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
130    // Never forked from the preloaded server: a test is rare, and its imports its own.
131    let task = serde_json::from_value(json!({
132        "id": name,
133        "kind": "python",
134        "connections": [name],
135        "settings": {"retries": 0, "retry_delay_ms": 0, "timeout_ms": timeout_ms,
136                     "queue": "default", "max_output_size": 65_536, "preload": false,
137                     "fresh_process": false},
138        "output_type": {"type": "none"},
139    }))
140    .map_err(|e| format!("connection `{name}` can't be tested by this name: {e}"))?;
141    let now = jiff::Timestamp::now();
142    Ok(AttemptSpec {
143        attempt_id,
144        task,
145        dag_root: job.root.clone(),
146        dag_path: path.clone(),
147        run: RunInfo {
148            dag_id: String::new(),
149            run_id: String::new(),
150            kind: schedr_model::RunKind::Manual,
151            planned_for: now,
152            since: now,
153            try_number: 1,
154            map_index: None,
155            params: json!({}),
156            event: None,
157            first_started: None,
158        },
159        inputs: std::collections::BTreeMap::new(),
160        outcomes: std::collections::BTreeMap::new(),
161        cancel_grace: job.cancel_grace,
162        secrets: std::collections::BTreeMap::new(),
163        mask: crate::mask::Mask::default(),
164        code_dir: job.code_dir.clone(),
165        script_dir: None,
166        root_copies: std::collections::BTreeMap::new(),
167        connections: Arc::clone(&job.registry),
168        trigger: None,
169        connection_env: std::collections::BTreeMap::new(),
170        connection_test: Some(name.to_owned()),
171        cleanup_handles: None,
172        moved_cleanup: false,
173        journal: None,
174        handle_sink: None,
175        api: None,
176        cleanup_gate: None,
177    })
178}
179
180/// A test's report from its attempt's end (its error masked as any attempt's is).
181#[must_use]
182pub fn test_report(
183    name: &str,
184    finished: &schedr_proto::pb::Finished,
185    took: Duration,
186) -> ConnectionReport {
187    use schedr_proto::pb::AttemptStatus;
188    let status = AttemptStatus::try_from(finished.status).unwrap_or(AttemptStatus::Unspecified);
189    let summary: Option<ErrorSummary> = serde_json::from_slice(&finished.error_summary_json).ok();
190    let error = match status {
191        AttemptStatus::Success => None,
192        AttemptStatus::TimedOut => Some(format!(
193            "stopped after its timeout ({:.1} s)",
194            took.as_secs_f64()
195        )),
196        _ => Some(
197            summary
198                .map(|e| {
199                    if e.exception.is_empty() {
200                        e.message
201                    } else {
202                        format!("{}: {}", e.exception, e.message)
203                    }
204                })
205                .filter(|m| !m.is_empty())
206                .unwrap_or_else(|| format!("the test ended {}", status.as_str_name())),
207        ),
208    };
209    ConnectionReport {
210        name: name.to_owned(),
211        ok: error.is_none(),
212        secrets: Vec::new(),
213        error,
214        duration_ms: Some(u64::try_from(took.as_millis()).unwrap_or(u64::MAX)),
215    }
216}
217
218/// Why a job ran out of its time while doing `what`.
219#[must_use]
220pub fn out_of_time(what: &str) -> String {
221    format!("its time was up during its {what}")
222}
223
224/// A connection that couldn't be checked or tested, with why.
225#[must_use]
226pub fn failed(name: &str, why: String) -> ConnectionReport {
227    ConnectionReport {
228        name: name.to_owned(),
229        ok: false,
230        secrets: Vec::new(),
231        error: Some(why),
232        duration_ms: None,
233    }
234}