Files
Library/include/Void/System/Process.hpp
T

368 lines
13 KiB
C++

#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <functional>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Process
{
inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxLineBytes = 64ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStdinBytes = 4ULL * 1024ULL * 1024ULL;
/// Captured output from a completed subprocess.
struct Output {
int exit_code{0};
std::string out; ///< captured stdout
std::string err; ///< captured stderr
};
/// Live line callbacks for run_streaming() and communicate_blocking().
struct StreamCallbacks {
std::function<void(std::string_view line)> on_stdout;
std::function<void(std::string_view line)> on_stderr;
};
enum class OverflowPolicy {
fail_and_terminate,
drain_and_truncate,
};
enum class EnvMode {
inherit,
allowlist,
explicit_only,
};
struct EnvironmentPolicy {
EnvMode mode{EnvMode::inherit};
std::vector<std::string> allowlist{};
std::vector<std::pair<std::string, std::string>> set_vars{};
std::vector<std::string> unset_keys{};
std::vector<std::string> redacted_keys{};
};
struct CaptureLimits {
std::size_t max_stdout_bytes{kDefaultMaxStdoutBytes};
std::size_t max_stderr_bytes{kDefaultMaxStderrBytes};
std::size_t max_line_bytes{kDefaultMaxLineBytes};
std::size_t max_stdin_bytes{kDefaultMaxStdinBytes};
OverflowPolicy overflow_policy{OverflowPolicy::fail_and_terminate};
};
struct SpawnOptions {
std::filesystem::path executable{};
std::vector<std::string> arguments{};
std::optional<std::filesystem::path> working_directory{};
EnvironmentPolicy environment{};
bool stdin_pipe{true};
bool stdout_pipe{true};
bool stderr_pipe{true};
bool search_path{true};
bool new_process_group{true};
std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}};
};
struct ExitStatus {
bool exited{false};
int code{-1};
int signal{0};
int raw_status{0};
};
struct CommunicateResult {
ExitStatus status{};
std::string out{};
std::string err{};
bool stdout_truncated{false};
bool stderr_truncated{false};
bool timed_out{false};
bool cancelled{false};
bool overflowed{false};
};
class Child
{
public:
Child() noexcept = default;
Child(long long pid,
long long pgid,
bool owns_process_group,
Void::System::OwnedFd stdin_fd,
Void::System::OwnedFd stdout_fd,
Void::System::OwnedFd stderr_fd,
std::chrono::milliseconds kill_grace) noexcept;
~Child() noexcept;
Child(const Child&) = delete;
Child& operator=(const Child&) = delete;
Child(Child&& other) noexcept;
Child& operator=(Child&& other) noexcept;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] bool process_group_alive() const noexcept;
[[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept;
[[nodiscard]] int stdin_fd() const noexcept;
[[nodiscard]] int stdout_fd() const noexcept;
[[nodiscard]] int stderr_fd() const noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdin_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdout_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stderr_fd() noexcept;
void close_stdin() noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_signal(int sig) noexcept;
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
terminate(std::chrono::milliseconds grace = std::chrono::milliseconds{-1});
[[nodiscard]] Void::Result::Result<std::optional<ExitStatus>, Void::Result::Error>
try_wait();
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
wait_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
std::chrono::milliseconds kill_grace = std::chrono::milliseconds{-1});
private:
long long pid_{-1};
long long pgid_{-1};
bool owns_group_{false};
bool reaped_{true};
ExitStatus cached_status_{};
Void::System::OwnedFd stdin_{};
Void::System::OwnedFd stdout_{};
Void::System::OwnedFd stderr_{};
std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}};
void reset_and_reap() noexcept;
};
[[nodiscard]] Void::Result::Result<Child, Void::Result::Error>
spawn(const SpawnOptions& options);
inline constexpr std::size_t kDefaultBinaryOutputBufferBytes = 1024ULL * 1024ULL;
/// Why a BinarySession operation stopped before completing.
enum class BinaryFailureCode : std::int32_t {
none = 0,
timeout = 1,
cancelled = 2,
truncated = 3,
closed = 4,
buffer_full = 5,
io_error = 6,
};
/// Successful (possibly partial) BinarySession operation.
struct BinaryTransfer {
std::size_t bytes{0};
bool eof{false}; ///< the stream reached end-of-file
bool exited{false}; ///< the child exit status is known (see status)
bool truncated{false}; ///< output was discarded because a buffer was full
ExitStatus status{};
};
/// Structured BinarySession failure. `bytes_transferred` lets callers resume
/// from the exact offset that was not transferred.
struct BinaryError {
std::size_t bytes_transferred{0};
bool eof{false};
BinaryFailureCode failure{BinaryFailureCode::io_error};
Void::Result::Error error{};
};
struct BinarySessionOptions {
std::size_t max_stdout_buffer{kDefaultBinaryOutputBufferBytes};
std::size_t max_stderr_buffer{kDefaultBinaryOutputBufferBytes};
/// When true, output beyond a buffer cap is drained and discarded (marked
/// truncated) instead of applying backpressure to the child.
bool truncate_output_on_overflow{false};
};
/// Incremental binary I/O session over a spawned child's pipes.
///
/// Each call drives both output directions: while stdout is being read,
/// stderr is drained into its bounded buffer (and vice versa), so a child
/// flooding one stream cannot block the other as long as buffering allows.
/// Pipes are non-blocking; operations are poll-driven and bounded by an
/// optional timeout and a stop token (or cancel()).
class BinarySession
{
public:
BinarySession() noexcept = default;
explicit BinarySession(Child child, BinarySessionOptions options = {});
~BinarySession() noexcept;
BinarySession(const BinarySession&) = delete;
BinarySession& operator=(const BinarySession&) = delete;
BinarySession(BinarySession&& other) noexcept;
BinarySession& operator=(BinarySession&& other) noexcept;
[[nodiscard]] static Void::Result::Result<BinarySession, Void::Result::Error>
spawn(const SpawnOptions& options, BinarySessionOptions session_options = {});
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] Child& child() noexcept { return child_; }
[[nodiscard]] const Child& child() const noexcept { return child_; }
[[nodiscard]] long long pid() const noexcept { return child_.pid(); }
/// Writes as much of `data` as the child accepts. Returns the transferred
/// count; on timeout/cancellation/closure the BinaryError reports it.
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> write_stdin(
std::span<const std::byte> data,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {});
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stdout(
std::span<std::byte> out,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {});
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stderr(
std::span<std::byte> out,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {});
/// Closes the child's stdin (flush-free half-close). Idempotent.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> close_stdin();
/// Waits for the child while continuing to drain both output streams.
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error> wait(
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {});
/// Terminates the child (and its process group) with the configured grace.
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error> terminate(
std::chrono::milliseconds grace = std::chrono::milliseconds{-1});
/// Requests cancellation of the next/current operation. Safe to call from
/// another thread.
void cancel() noexcept { cancelled_.store(true, std::memory_order_release); }
[[nodiscard]] bool cancelled() const noexcept
{
return cancelled_.load(std::memory_order_acquire);
}
[[nodiscard]] bool stdout_eof() const noexcept { return stdout_eof_; }
[[nodiscard]] bool stderr_eof() const noexcept { return stderr_eof_; }
[[nodiscard]] bool stdout_truncated() const noexcept { return stdout_truncated_; }
[[nodiscard]] bool stderr_truncated() const noexcept { return stderr_truncated_; }
[[nodiscard]] std::size_t buffered_stdout() const noexcept
{
return stdout_buffer_.size() - stdout_offset_;
}
[[nodiscard]] std::size_t buffered_stderr() const noexcept
{
return stderr_buffer_.size() - stderr_offset_;
}
private:
struct PollFill {
bool stdin_broken{false};
bool idle{false};
BinaryFailureCode failure{BinaryFailureCode::none};
Void::Result::Error error{};
};
[[nodiscard]] PollFill poll_fill(int timeout_ms,
std::span<const std::byte> stdin_data,
std::size_t& stdin_written,
bool discard_on_full);
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stream(
bool is_stdout,
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop);
void note_exit() noexcept;
Child child_{};
Void::System::OwnedFd stdin_{};
Void::System::OwnedFd stdout_{};
Void::System::OwnedFd stderr_{};
std::vector<std::byte> stdout_buffer_{};
std::size_t stdout_offset_{0};
std::vector<std::byte> stderr_buffer_{};
std::size_t stderr_offset_{0};
bool stdout_eof_{true};
bool stderr_eof_{true};
bool stdin_closed_{true};
bool stdout_truncated_{false};
bool stderr_truncated_{false};
BinarySessionOptions options_{};
std::atomic<bool> cancelled_{false};
ExitStatus status_{};
bool reaped_{false};
};
[[nodiscard]] Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child& child,
std::string_view stdin_data = {},
CaptureLimits limits = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
const StreamCallbacks* callbacks = nullptr);
/// Run an executable synchronously, capturing stdout and stderr separately.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr arrive.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Run a command through /bin/sh -c "command".
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Replace the current process image while preserving its PID and inherited
/// environment.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments);
/// Replace the current process image with explicit open-descriptor cleanup policy.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments,
bool close_extra_fds);
/// Opt the current process into Linux PR_SET_CHILD_SUBREAPER so orphaned
/// descendant processes in spawned process groups reparent to this process
/// and can be reaped directly via waitpid(-pgid, ...).
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
enable_subreaper() noexcept;
} // namespace Void::Process