Skip to main content

schedr_agent/
ctx.rs

1//! A command task's context channel (decisions 143-146): the agent's side of `schedr dag-ctx`
2//! and `schedr.script`.
3//!
4//! The task inherits one end of a datagram socket pair (`SCHEDR_CTX_FD`), and so does every
5//! process it starts. A call makes a stream socket pair of its own and sends one end over it
6//! (`SCM_RIGHTS`, one datagram); the agent serves each received end as a connection of its
7//! own (see `schedr_model::ctx`), until the attempt ends. A caller is accepted by the protocol
8//! it speaks, not its schedr version (decision 148). The agent never sends on the
9//! datagram socket, so concurrent callers can't take each other's answers.
10
11use std::io;
12use std::mem::MaybeUninit;
13use std::os::fd::OwnedFd;
14use std::pin::Pin;
15use std::sync::Arc;
16use std::task::{Context, Poll};
17
18use rustix::net::{
19    AddressFamily, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, SendFlags, SocketType,
20};
21use schedr_model::ctx::{CTX_PROTOCOL, CtxAnswer, CtxRequest, CtxRun, MAX_CTX_MESSAGE_SIZE};
22use schedr_model::runner::RunInfo;
23use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, Interest, ReadBuf};
24use tokio::net::{UnixDatagram, UnixStream};
25use tokio::task::JoinSet;
26
27use crate::handles::{AttemptHandles, HandleError};
28use crate::resource::{AttemptResource, ResourceError};
29use crate::secrets::{AttemptSecrets, ConnectionError, SecretError};
30
31#[cfg(test)]
32mod tests;
33
34/// The most connections a task may have open at once; an end sent beyond it is closed at
35/// once (the caller sees the connection close).
36pub const MAX_CONNECTIONS: usize = 64;
37
38/// The most descriptors read from one datagram: Linux's limit per message (`SCM_MAX_FD`), so a
39/// datagram isn't truncated and every descriptor it carries is closed (a datagram must carry
40/// exactly one). On macOS, truncated control data needs rustix 1.1.6's clamp of `cmsg_len`.
41const MAX_FDS_PER_DATAGRAM: usize = 253;
42
43/// What a task's processes can read over the channel.
44#[derive(Debug, Clone)]
45pub struct CtxInfo {
46    /// The run information.
47    pub run: CtxRun,
48    /// The run's parameters, as stored.
49    pub params: serde_json::Value,
50    /// The agent's schedr version (for a refusal's message; callers are accepted by their
51    /// protocol, decision 148).
52    pub version: String,
53    /// The attempt's secrets (`schedr task-ctx secret get`); none for a task without any.
54    pub secrets: Option<Arc<AttemptSecrets>>,
55    /// The attempt's cleanup handles (`schedr task-ctx cleanup`); none outside an attempt.
56    pub handles: Option<Arc<AttemptHandles>>,
57    /// The resource value it reports or reads (`schedr task-ctx resource`); none for a task
58    /// that is no resource's command part.
59    pub resource: Option<Arc<AttemptResource>>,
60    /// What it calls schedr's REST API with (`schedr task-ctx api`, M4.11h); none: it can't.
61    pub api: Option<crate::api::ApiCaller>,
62    /// The most connections the task may have open at once
63    /// (`SCHEDR_HIDDEN__WORKER__TASK_CONNECTIONS_OPEN`).
64    pub max_connections: usize,
65}
66
67impl CtxInfo {
68    /// The information of an attempt's run.
69    #[must_use]
70    pub fn of(run: &RunInfo, version: &str) -> Self {
71        Self {
72            run: CtxRun {
73                dag_id: run.dag_id.clone(),
74                id: run.run_id.clone(),
75                kind: run.kind,
76                planned_for: run.planned_for,
77                since: run.since,
78            },
79            params: run.params.clone(),
80            version: version.to_owned(),
81            secrets: None,
82            handles: None,
83            resource: None,
84            api: None,
85            max_connections: MAX_CONNECTIONS,
86        }
87    }
88}
89
90/// A new channel: the agent's end, and the task's end to pass to its process (close-on-exec,
91/// as every socket the agent makes; made inheritable only while that process starts).
92///
93/// # Errors
94///
95/// An I/O error if the socket pair can't be made.
96pub fn channel() -> io::Result<(UnixDatagram, OwnedFd)> {
97    let (ours, theirs) = std::os::unix::net::UnixDatagram::pair()?;
98    ours.set_nonblocking(true)?;
99    Ok((UnixDatagram::from_std(ours)?, OwnedFd::from(theirs)))
100}
101
102/// Serving a channel; stops (its connections closed) when dropped.
103#[derive(Debug)]
104pub struct Serving(tokio::task::JoinHandle<()>);
105
106impl Drop for Serving {
107    fn drop(&mut self) {
108        self.0.abort();
109    }
110}
111
112/// Serves the agent's end of a channel in the background, until the returned guard drops.
113#[must_use]
114pub fn serve(socket: UnixDatagram, info: CtxInfo) -> Serving {
115    Serving(tokio::spawn(accept(socket, Arc::new(info))))
116}
117
118/// Takes the ends sent over `socket` and serves each; its connections end with it.
119async fn accept(socket: UnixDatagram, info: Arc<CtxInfo>) {
120    let mut connections = JoinSet::new();
121    loop {
122        let end = match receive_end(&socket).await {
123            Ok(Some(end)) => end,
124            Ok(None) => continue,
125            Err(error) => {
126                tracing::warn!(%error, "the task's context channel failed; it is closed");
127                return;
128            }
129        };
130        while connections.try_join_next().is_some() {}
131        let Some(end) = connection(end) else {
132            continue;
133        };
134        let most = info.max_connections.max(1);
135        if connections.len() >= most {
136            tracing::debug!("a task has {most} context connections open; refused one");
137            // Said on the fresh connection (its buffer is empty, so the send doesn't wait),
138            // then closed.
139            let reason = format!(
140                "the task has {most} context connections open, the most the agent \
141                 serves at once"
142            );
143            if let Ok(frame) = framed(&CtxAnswer::Error { reason }) {
144                let _ = rustix::net::send(&end, &frame, SEND_FLAGS);
145            }
146            continue;
147        }
148        let stream = std::os::unix::net::UnixStream::from(end);
149        // Tokio expects a non-blocking socket when registering it (a debug assertion; a task
150        // clearing the flag in between makes its own accept task panic, nothing more). The
151        // reads and writes don't rely on the flag (`Received`).
152        if stream.set_nonblocking(true).is_err() {
153            continue;
154        }
155        let Ok(stream) = UnixStream::from_std(stream).map(Received) else {
156            continue;
157        };
158        let info = Arc::clone(&info);
159        connections.spawn(async move {
160            let mut stream = stream;
161            if let Err(error) = converse(&mut stream, &info).await {
162                tracing::debug!(%error, "a context connection ended");
163            }
164        });
165    }
166}
167
168/// A received end, read and written with `MSG_DONTWAIT` on each call. Its `O_NONBLOCK` flag
169/// can't be relied on: it belongs to the open file description, which the sender shares and
170/// can clear, and a blocking read would hold one of the runtime's threads.
171/// Tokio's stream gives the readiness only; its own reads and writes, which rely on that flag,
172/// are never used.
173#[derive(Debug)]
174struct Received(UnixStream);
175
176/// Sends never wait, and a closed peer is an error rather than `SIGPIPE` (Linux's flag;
177/// elsewhere Rust's runtime ignores `SIGPIPE` already).
178#[cfg(target_os = "linux")]
179const SEND_FLAGS: SendFlags = SendFlags::DONTWAIT.union(SendFlags::NOSIGNAL);
180#[cfg(not(target_os = "linux"))]
181const SEND_FLAGS: SendFlags = SendFlags::DONTWAIT;
182
183impl AsyncRead for Received {
184    fn poll_read(
185        self: Pin<&mut Self>,
186        cx: &mut Context<'_>,
187        buf: &mut ReadBuf<'_>,
188    ) -> Poll<io::Result<()>> {
189        let stream = &self.get_mut().0;
190        loop {
191            std::task::ready!(stream.poll_read_ready(cx))?;
192            let unfilled = buf.initialize_unfilled();
193            let read = stream.try_io(Interest::READABLE, || {
194                rustix::net::recv(stream, &mut *unfilled, RecvFlags::DONTWAIT)
195                    .map(|(n, _)| n)
196                    .map_err(io::Error::from)
197            });
198            match read {
199                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
200                result => return Poll::Ready(result.map(|n| buf.advance(n))),
201            }
202        }
203    }
204}
205
206impl AsyncWrite for Received {
207    fn poll_write(
208        self: Pin<&mut Self>,
209        cx: &mut Context<'_>,
210        data: &[u8],
211    ) -> Poll<io::Result<usize>> {
212        let stream = &self.get_mut().0;
213        loop {
214            std::task::ready!(stream.poll_write_ready(cx))?;
215            let sent = stream.try_io(Interest::WRITABLE, || {
216                rustix::net::send(stream, data, SEND_FLAGS).map_err(io::Error::from)
217            });
218            match sent {
219                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
220                result => return Poll::Ready(result),
221            }
222        }
223    }
224
225    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
226        Poll::Ready(Ok(()))
227    }
228
229    fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
230        let stream = &self.get_mut().0;
231        Poll::Ready(
232            rustix::net::shutdown(stream, rustix::net::Shutdown::Write).map_err(io::Error::from),
233        )
234    }
235}
236
237/// Receives one datagram: the end it carries, or `None` for one carrying none, several, or a
238/// truncated set (all closed).
239async fn receive_end(socket: &UnixDatagram) -> io::Result<Option<OwnedFd>> {
240    loop {
241        socket.readable().await?;
242        // Without `MSG_CMSG_CLOEXEC`, the ends are open across exec until marked; no process
243        // starts meanwhile.
244        #[cfg(not(target_os = "linux"))]
245        let _spawning = crate::process::SPAWNING.lock().await;
246        match socket.try_io(tokio::io::Interest::READABLE, || receive_now(socket)) {
247            Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
248            result => return result,
249        }
250    }
251}
252
253#[cfg(target_os = "linux")]
254const RECV_FLAGS: RecvFlags = RecvFlags::CMSG_CLOEXEC;
255#[cfg(not(target_os = "linux"))]
256const RECV_FLAGS: RecvFlags = RecvFlags::empty();
257
258fn receive_now(socket: &UnixDatagram) -> io::Result<Option<OwnedFd>> {
259    let mut data = [0_u8; 16];
260    let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(MAX_FDS_PER_DATAGRAM))];
261    let mut control = RecvAncillaryBuffer::new(&mut space);
262    let received = rustix::net::recvmsg(
263        socket,
264        &mut [io::IoSliceMut::new(&mut data)],
265        &mut control,
266        RECV_FLAGS,
267    )?;
268    let mut ends: Vec<OwnedFd> = Vec::new();
269    for message in control.drain() {
270        if let RecvAncillaryMessage::ScmRights(fds) = message {
271            ends.extend(fds);
272        }
273    }
274    #[cfg(not(target_os = "linux"))]
275    for end in &ends {
276        rustix::io::fcntl_setfd(end, rustix::io::FdFlags::CLOEXEC)?;
277    }
278    let whole = !received.flags.contains(rustix::net::ReturnFlags::CTRUNC);
279    Ok(match (whole, ends.len()) {
280        (true, 1) => ends.pop(),
281        _ => None,
282    })
283}
284
285/// The received end, if it is the end of a Unix stream socket (else closed).
286fn connection(end: OwnedFd) -> Option<OwnedFd> {
287    let stream = rustix::net::sockopt::socket_type(&end).ok() == Some(SocketType::STREAM);
288    let unix = rustix::net::getsockname(&end)
289        .is_ok_and(|address| address.address_family() == AddressFamily::UNIX);
290    if !(stream && unix) {
291        tracing::debug!("a task sent a descriptor that isn't a Unix stream socket; closed");
292        return None;
293    }
294    Some(end)
295}
296
297/// Why a conversation ended early.
298#[derive(Debug, thiserror::Error)]
299pub enum CtxError {
300    /// A message over [`MAX_CTX_MESSAGE_SIZE`].
301    #[error("a message of {0} bytes is over the limit of {MAX_CTX_MESSAGE_SIZE} bytes")]
302    TooLarge(u32),
303    /// Reading or writing failed.
304    #[error(transparent)]
305    Io(#[from] io::Error),
306    /// A message that doesn't encode.
307    #[error(transparent)]
308    Json(#[from] serde_json::Error),
309}
310
311/// One connection: the handshake, then one answer per request until the caller closes it.
312///
313/// # Errors
314///
315/// [`CtxError`] when the connection breaks or a message is over the limit.
316pub async fn converse<S: AsyncRead + AsyncWrite + Unpin>(
317    stream: &mut S,
318    info: &CtxInfo,
319) -> Result<(), CtxError> {
320    match read_request(stream).await? {
321        Some(Ok(CtxRequest::Hello { protocol, .. })) if protocol == CTX_PROTOCOL => {
322            write_answer(stream, &CtxAnswer::Welcome).await?;
323        }
324        Some(Ok(CtxRequest::Hello {
325            protocol,
326            schedr_version,
327        })) => {
328            let reason = format!(
329                "this schedr ({schedr_version}) speaks protocol {protocol} of the task's \
330                 context, the task's agent ({}) protocol {CTX_PROTOCOL}: use schedr {} (or one \
331                 speaking protocol {CTX_PROTOCOL}) in the task",
332                info.version, info.version
333            );
334            return write_answer(stream, &CtxAnswer::Refused { reason }).await;
335        }
336        Some(_) => return refuse(stream, "say `hello` first").await,
337        None => return Ok(()),
338    }
339    loop {
340        let answer = match read_request(stream).await? {
341            None => return Ok(()),
342            Some(Ok(CtxRequest::Hello { .. })) => {
343                return refuse(stream, "`hello` was said already").await;
344            }
345            Some(Ok(request)) => answer_to(info, request).await,
346            Some(Err(reason)) => return refuse(stream, &reason).await,
347        };
348        write_answer(stream, &answer).await?;
349    }
350}
351
352/// The answer to a request after the handshake.
353async fn answer_to(info: &CtxInfo, request: CtxRequest) -> CtxAnswer {
354    match request {
355        CtxRequest::ParamsGet => CtxAnswer::Params {
356            params: info.params.clone(),
357        },
358        CtxRequest::RunGet => CtxAnswer::Run(info.run.clone()),
359        CtxRequest::SecretGet { secret } => match &info.secrets {
360            Some(secrets) => match secrets.read(&secret).await {
361                Ok(value) => CtxAnswer::Secret { value },
362                Err(error) => CtxAnswer::SecretFailed {
363                    kind: error.kind().to_owned(),
364                    reason: error.to_string(),
365                },
366            },
367            None => CtxAnswer::SecretFailed {
368                kind: SecretError::Denied(String::new()).kind().to_owned(),
369                reason: format!("`{secret}` isn't declared in the task's `secrets=`"),
370            },
371        },
372        CtxRequest::ApiCall {
373            method,
374            path,
375            body,
376            idempotency_key,
377        } => match &info.api {
378            Some(api) => {
379                let request = crate::api::ApiRequest {
380                    method,
381                    path,
382                    body,
383                    idempotency_key,
384                    masked: false,
385                };
386                let request = request.masked_by(info.secrets.as_deref());
387                let note = request.note();
388                let (status, body) = api.call(request).await;
389                api_answer(status, body, note)
390            }
391            None => CtxAnswer::Error {
392                reason: crate::api::NO_MASTER.to_owned(),
393            },
394        },
395        CtxRequest::HandleAdd { handle } => {
396            let added = match info.handles.as_ref() {
397                Some(handles) => handles.add(handle).await,
398                None => Err(HandleError::NoCleanup),
399            };
400            match added {
401                Ok(()) => CtxAnswer::HandleAdded,
402                Err(error) => CtxAnswer::HandleRefused {
403                    reason: error.to_string(),
404                },
405            }
406        }
407        CtxRequest::HandleList => match info.handles.as_ref() {
408            Some(handles) if handles.in_cleanup() => CtxAnswer::Handles {
409                handles: handles.list(),
410            },
411            _ => CtxAnswer::Error {
412                reason: "`cleanup list` works only inside a cleanup".to_owned(),
413            },
414        },
415        CtxRequest::ConnectionGet { name } => {
416            let opened = match &info.secrets {
417                Some(secrets) => secrets.connection(&name).await,
418                None => Err(ConnectionError::NotFound(format!(
419                    "connection `{name}`: no connections are known for this task"
420                ))),
421            };
422            match opened {
423                Ok(values) => CtxAnswer::Connection { values },
424                Err(error) => CtxAnswer::ConnectionFailed {
425                    kind: error.kind().to_owned(),
426                    reason: error.to_string(),
427                },
428            }
429        }
430        CtxRequest::ConnectionEnvGet { name, prefix } => {
431            let given = match &info.secrets {
432                Some(secrets) => secrets.connection_env(&name, &prefix).await,
433                None => Err(ConnectionError::NotFound(format!(
434                    "connection `{name}`: no connections are known for this task"
435                ))),
436            };
437            match given {
438                Ok(variables) => CtxAnswer::ConnectionEnv { variables },
439                Err(error) => CtxAnswer::ConnectionFailed {
440                    kind: error.kind().to_owned(),
441                    reason: error.to_string(),
442                },
443            }
444        }
445        CtxRequest::ResourceSet { value } => resource_answer(info, Some(&value)),
446        CtxRequest::ResourceGet => resource_answer(info, None),
447        CtxRequest::Hello { .. } => CtxAnswer::Error {
448            reason: "`hello` was said already".to_owned(),
449        },
450    }
451}
452
453/// An API answer, or a 502 when it is over what the context's connection takes (Codex's
454/// review of M4.11h): the connection would break instead.
455fn api_answer(status: u16, body: serde_json::Value, note: Option<String>) -> CtxAnswer {
456    let size = serde_json::to_vec(&body).map_or(usize::MAX, |bytes| bytes.len());
457    let limit = usize::try_from(MAX_CTX_MESSAGE_SIZE).unwrap_or(usize::MAX);
458    // Room for the answer's own fields.
459    if size > limit.saturating_sub(1024) {
460        let error = format!(
461            "the API's answer is {size} bytes, over the {MAX_CTX_MESSAGE_SIZE} a task's context \
462             takes: ask for less (`limit=`)"
463        );
464        return CtxAnswer::ApiAnswer {
465            status: 502,
466            body: serde_json::json!({ "error": error }),
467            note,
468        };
469    }
470    CtxAnswer::ApiAnswer { status, body, note }
471}
472
473/// The answer to `resource set` (with the value) or `resource get`.
474fn resource_answer(info: &CtxInfo, set: Option<&serde_json::Value>) -> CtxAnswer {
475    let refused = |error: ResourceError| CtxAnswer::ResourceRefused {
476        reason: error.to_string(),
477    };
478    match (info.resource.as_ref(), set) {
479        (Some(resource), Some(value)) => match resource.set(value) {
480            Ok(()) => CtxAnswer::ResourceReported,
481            Err(error) => refused(error),
482        },
483        (Some(resource), None) => match resource.get() {
484            Ok(value) => CtxAnswer::Resource { value },
485            Err(error) => refused(error),
486        },
487        (None, Some(_)) => refused(ResourceError::NotSetup),
488        (None, None) => refused(ResourceError::NotCleanup),
489    }
490}
491
492async fn refuse<W: AsyncWrite + Unpin>(stream: &mut W, reason: &str) -> Result<(), CtxError> {
493    let reason = reason.to_owned();
494    write_answer(stream, &CtxAnswer::Error { reason }).await
495}
496
497/// The next request: `None` at the end of the stream, `Some(Err(why))` for one that doesn't
498/// read (an unknown type: a newer caller).
499async fn read_request<R: AsyncRead + Unpin>(
500    reader: &mut R,
501) -> Result<Option<Result<CtxRequest, String>>, CtxError> {
502    let mut header = [0; 4];
503    match reader.read_exact(&mut header).await {
504        Ok(_) => {}
505        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
506        Err(e) => return Err(e.into()),
507    }
508    let size = u32::from_be_bytes(header);
509    if size > MAX_CTX_MESSAGE_SIZE {
510        return Err(CtxError::TooLarge(size));
511    }
512    let mut body = vec![0; size as usize];
513    reader.read_exact(&mut body).await?;
514    Ok(Some(serde_json::from_slice(&body).map_err(|e| {
515        format!("not a request this agent knows: {e}")
516    })))
517}
518
519/// An answer as sent: its length, then its JSON.
520fn framed(answer: &CtxAnswer) -> Result<Vec<u8>, CtxError> {
521    let body = serde_json::to_vec(answer)?;
522    let size = u32::try_from(body.len())
523        .ok()
524        .filter(|&n| n <= MAX_CTX_MESSAGE_SIZE)
525        .ok_or(CtxError::TooLarge(u32::MAX))?;
526    let mut frame = size.to_be_bytes().to_vec();
527    frame.extend(body);
528    Ok(frame)
529}
530
531async fn write_answer<W: AsyncWrite + Unpin>(
532    writer: &mut W,
533    answer: &CtxAnswer,
534) -> Result<(), CtxError> {
535    writer.write_all(&framed(answer)?).await?;
536    writer.flush().await?;
537    Ok(())
538}