Skip to main content

folk_runtime_fork/
master.rs

1//! Prefork master management: spawn the master PHP process and issue fork commands.
2
3use std::os::unix::io::{AsRawFd, OwnedFd};
4
5use anyhow::{Context, Result, bail};
6use folk_protocol::{FrameCodec, RpcMessage};
7use futures_util::{SinkExt, StreamExt};
8use rmpv::Value;
9use tokio::net::UnixStream;
10use tokio_util::codec::Framed;
11use tracing::{debug, info};
12
13use crate::scm_rights::send_fds;
14
15/// Manages the prefork master PHP process.
16pub struct PreforkMaster {
17    control: Framed<UnixStream, FrameCodec>,
18    pid: u32,
19    /// Socket for sending FDs to the master via `SCM_RIGHTS`.
20    fork_socket: UnixStream,
21}
22
23impl PreforkMaster {
24    /// Spawn the PHP prefork master (`FOLK_RUNTIME=fork-master`).
25    /// Waits for `control.fork-ready` within `boot_timeout`.
26    pub async fn spawn(php: &str, script: &str, boot_timeout: std::time::Duration) -> Result<Self> {
27        // Re-use PipeRuntime's spawn_worker for the initial master process,
28        // but set FOLK_RUNTIME=fork so the PHP side enters ForkMasterLoop.
29        let spawned = folk_runtime_pipe::spawn::spawn_worker_with_runtime(php, script, "fork")
30            .context("spawn prefork master")?;
31        let mut control = Framed::new(spawned.control_master, FrameCodec::new());
32        let pid = spawned.child.id().unwrap_or(0);
33
34        // Wait for fork-ready
35        let ready = tokio::time::timeout(boot_timeout, control.next())
36            .await
37            .context("boot timeout")?
38            .context("EOF before fork-ready")?
39            .context("decode fork-ready")?;
40
41        match ready {
42            RpcMessage::Notify { ref method, .. } if method == "control.fork-ready" => {
43                info!(pid, "prefork master ready");
44            },
45            other => bail!("expected control.fork-ready, got {other:?}"),
46        }
47
48        Ok(Self {
49            control,
50            pid,
51            fork_socket: spawned.task_master,
52        })
53    }
54
55    /// Send the master a fork command + two socket FDs (task + control for the new child).
56    /// Returns the child's PID from the master's reply.
57    #[allow(unsafe_code)]
58    pub async fn fork_worker(&mut self, task_child: &OwnedFd, ctrl_child: &OwnedFd) -> Result<u32> {
59        // Send FDs via SCM_RIGHTS over fork_socket
60        unsafe {
61            send_fds(
62                self.fork_socket.as_raw_fd(),
63                &[task_child.as_raw_fd(), ctrl_child.as_raw_fd()],
64            )?;
65        }
66
67        // Send fork command on control channel
68        self.control
69            .send(RpcMessage::notify("fork.spawn", Value::Nil))
70            .await?;
71
72        // Receive child PID from master
73        let reply = tokio::time::timeout(std::time::Duration::from_secs(10), self.control.next())
74            .await
75            .context("fork reply timeout")?
76            .context("EOF from master")?
77            .context("decode fork reply")?;
78
79        match reply {
80            RpcMessage::Notify { method, params } if method == "fork.spawned" => {
81                #[allow(clippy::cast_possible_truncation)]
82                let pid = params
83                    .as_map()
84                    .and_then(|m| m.iter().find(|(k, _)| k.as_str() == Some("pid")))
85                    .and_then(|(_, v)| v.as_u64())
86                    .context("missing pid in fork.spawned")? as u32;
87                debug!(child_pid = pid, "child forked");
88                Ok(pid)
89            },
90            other => bail!("unexpected reply to fork.spawn: {other:?}"),
91        }
92    }
93
94    /// Shut down the prefork master.
95    #[allow(unsafe_code, clippy::cast_possible_wrap)]
96    pub async fn shutdown(&mut self) -> Result<()> {
97        let _ = self
98            .control
99            .send(RpcMessage::notify("control.shutdown", Value::Nil))
100            .await;
101        unsafe {
102            libc::kill(self.pid as libc::pid_t, libc::SIGTERM);
103        }
104        Ok(())
105    }
106}