feat(daemon,platform): add Unix-socket daemon core, split Linux platform backends, and fix CMake feature-carrier translation
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 7s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 7s
This commit is contained in:
1 parent
55ea305528
commit
0bde74f739
20 files changed
+1194
-21
No files matched your search
@@ -0,0 +1,691 @@
|
||||
#include <Void/Build/Daemon/Daemon.hpp>
|
||||
|
||||
#include <Void/Build/State/StateStore.hpp>
|
||||
#include <Void/Build/Watch/Watcher.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <poll.h>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/un.h>
|
||||
#include <system_error>
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
namespace Void::Build::Daemon {
|
||||
namespace {
|
||||
|
||||
using JsonValue = Void::Json::Strict::Value;
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
constexpr std::size_t kMaxRequestBytes = 64U * 1024U;
|
||||
constexpr std::size_t kMaxJsonDepth = 16U;
|
||||
constexpr int kListenBacklog = 8;
|
||||
constexpr auto kClientIoTimeout = std::chrono::milliseconds{2000};
|
||||
constexpr auto kProbeTimeout = std::chrono::milliseconds{1000};
|
||||
|
||||
Void::Result::Error make_error(Void::Result::ErrorKind kind, std::string message,
|
||||
int system_errno = 0) {
|
||||
std::error_code sys{};
|
||||
if (system_errno != 0) {
|
||||
sys = std::error_code{system_errno, std::system_category()};
|
||||
}
|
||||
return Void::Result::Error{kind, std::move(message), {}, sys};
|
||||
}
|
||||
|
||||
int poll_timeout_ms(std::chrono::milliseconds timeout) noexcept {
|
||||
if (timeout.count() <= 0) {
|
||||
return 0;
|
||||
}
|
||||
const auto maximum = static_cast<long long>(std::numeric_limits<int>::max());
|
||||
return timeout.count() > maximum ? std::numeric_limits<int>::max()
|
||||
: static_cast<int>(timeout.count());
|
||||
}
|
||||
|
||||
class UniqueFd {
|
||||
public:
|
||||
UniqueFd() = default;
|
||||
explicit UniqueFd(int fd) noexcept : fd_{fd} {}
|
||||
~UniqueFd() { reset(); }
|
||||
|
||||
UniqueFd(const UniqueFd &) = delete;
|
||||
UniqueFd &operator=(const UniqueFd &) = delete;
|
||||
|
||||
UniqueFd(UniqueFd &&other) noexcept : fd_{std::exchange(other.fd_, -1)} {}
|
||||
UniqueFd &operator=(UniqueFd &&other) noexcept {
|
||||
if (this != &other) {
|
||||
reset(std::exchange(other.fd_, -1));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
[[nodiscard]] int get() const noexcept { return fd_; }
|
||||
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
|
||||
|
||||
int release() noexcept { return std::exchange(fd_, -1); }
|
||||
|
||||
void reset(int fd = -1) noexcept {
|
||||
if (fd_ >= 0) {
|
||||
::close(fd_);
|
||||
}
|
||||
fd_ = fd;
|
||||
}
|
||||
|
||||
private:
|
||||
int fd_{-1};
|
||||
};
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> set_close_on_exec(int fd) {
|
||||
const int flags = ::fcntl(fd, F_GETFD);
|
||||
if (flags < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: fcntl(F_GETFD) failed", errno)};
|
||||
}
|
||||
if (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::io,
|
||||
"daemon: fcntl(F_SETFD, FD_CLOEXEC) failed", errno)};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<sockaddr_un, Void::Result::Error>
|
||||
make_address(const std::filesystem::path &socket_path) {
|
||||
const std::string text = socket_path.string();
|
||||
if (text.empty()) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: socket path must not be empty")};
|
||||
}
|
||||
sockaddr_un address{};
|
||||
address.sun_family = AF_UNIX;
|
||||
if (text.size() >= sizeof(address.sun_path)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
std::format("daemon: socket path '{}' is {} bytes; a Unix socket address holds at "
|
||||
"most {} bytes including the terminator",
|
||||
text, text.size(), sizeof(address.sun_path) - 1))};
|
||||
}
|
||||
std::memcpy(address.sun_path, text.c_str(), text.size() + 1);
|
||||
return address;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> write_all(int fd, std::string_view data) {
|
||||
while (!data.empty()) {
|
||||
const ssize_t written = ::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
|
||||
if (written < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: send failed", errno)};
|
||||
}
|
||||
data.remove_prefix(static_cast<std::size_t>(written));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
read_line(int fd, std::chrono::milliseconds timeout) {
|
||||
const auto deadline = Clock::now() + timeout;
|
||||
std::string line;
|
||||
line.reserve(256);
|
||||
char buffer[4096];
|
||||
|
||||
while (true) {
|
||||
if (const auto newline = line.find('\n'); newline != std::string::npos) {
|
||||
line.resize(newline);
|
||||
if (!line.empty() && line.back() == '\r') {
|
||||
line.pop_back();
|
||||
}
|
||||
return line;
|
||||
}
|
||||
if (line.size() > kMaxRequestBytes) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: request exceeds 64 KiB")};
|
||||
}
|
||||
|
||||
auto remaining =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - Clock::now());
|
||||
if (remaining.count() < 0) {
|
||||
remaining = std::chrono::milliseconds{0};
|
||||
}
|
||||
pollfd descriptor{fd, POLLIN, 0};
|
||||
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(remaining));
|
||||
if (ready < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
|
||||
}
|
||||
if (ready == 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::timeout,
|
||||
"daemon: timed out waiting for request line")};
|
||||
}
|
||||
|
||||
const ssize_t count = ::read(fd, buffer, sizeof(buffer));
|
||||
if (count < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: read failed", errno)};
|
||||
}
|
||||
if (count == 0) {
|
||||
if (line.empty()) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::io,
|
||||
"daemon: connection closed before request")};
|
||||
}
|
||||
return line;
|
||||
}
|
||||
line.append(buffer, static_cast<std::size_t>(count));
|
||||
if (line.size() > kMaxRequestBytes) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: request exceeds 64 KiB")};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<UniqueFd, Void::Result::Error>
|
||||
connect_socket(const std::filesystem::path &socket_path, std::chrono::milliseconds timeout) {
|
||||
auto address = make_address(socket_path);
|
||||
if (!address) {
|
||||
return std::unexpected{std::move(address.error())};
|
||||
}
|
||||
|
||||
UniqueFd fd{::socket(AF_UNIX, SOCK_STREAM, 0)};
|
||||
if (!fd.valid()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: socket() failed", errno)};
|
||||
}
|
||||
if (auto cloexec = set_close_on_exec(fd.get()); !cloexec) {
|
||||
return std::unexpected{std::move(cloexec.error())};
|
||||
}
|
||||
|
||||
const int flags = ::fcntl(fd.get(), F_GETFL);
|
||||
if (flags < 0 || ::fcntl(fd.get(), F_SETFL, flags | O_NONBLOCK) < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: fcntl(F_SETFL) failed", errno)};
|
||||
}
|
||||
|
||||
int result =
|
||||
::connect(fd.get(), reinterpret_cast<const sockaddr *>(&*address), sizeof(sockaddr_un));
|
||||
if (result < 0 && errno != EINPROGRESS) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot connect to '{}'", socket_path.string()), errno)};
|
||||
}
|
||||
if (result < 0) {
|
||||
pollfd descriptor{fd.get(), POLLOUT, 0};
|
||||
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(timeout));
|
||||
if (ready < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
|
||||
}
|
||||
if (ready == 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::timeout,
|
||||
"daemon: timed out connecting to socket")};
|
||||
}
|
||||
int socket_error = 0;
|
||||
socklen_t length = sizeof(socket_error);
|
||||
if (::getsockopt(fd.get(), SOL_SOCKET, SO_ERROR, &socket_error, &length) < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: getsockopt failed", errno)};
|
||||
}
|
||||
if (socket_error != 0) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot connect to '{}'", socket_path.string()), socket_error)};
|
||||
}
|
||||
}
|
||||
|
||||
if (::fcntl(fd.get(), F_SETFL, flags) < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: fcntl restore failed", errno)};
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
std::string serialize_response(const JsonValue &value) {
|
||||
auto serialized = Void::Json::Strict::serialize(value);
|
||||
if (serialized) {
|
||||
return *serialized;
|
||||
}
|
||||
return R"({"ok":false,"error":"daemon: response serialization failed"})";
|
||||
}
|
||||
|
||||
std::string error_response(std::string_view message) {
|
||||
JsonValue::Object object;
|
||||
object.emplace("ok", JsonValue{false});
|
||||
object.emplace("error", JsonValue{std::string{message}});
|
||||
return serialize_response(JsonValue{std::move(object)});
|
||||
}
|
||||
|
||||
std::string ok_response(std::string_view op) {
|
||||
JsonValue::Object object;
|
||||
object.emplace("ok", JsonValue{true});
|
||||
object.emplace("op", JsonValue{std::string{op}});
|
||||
return serialize_response(JsonValue{std::move(object)});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct DaemonServer::Impl {
|
||||
struct DispatchResult {
|
||||
std::string response;
|
||||
bool shutdown{false};
|
||||
};
|
||||
|
||||
Impl(DaemonOptions daemon_options, std::filesystem::path path, State::StateStore state,
|
||||
Watch::InotifyWatcher project_watcher)
|
||||
: options{std::move(daemon_options)}, socket_path{std::move(path)},
|
||||
state_store{std::move(state)}, watcher{std::move(project_watcher)},
|
||||
started{Clock::now()} {}
|
||||
|
||||
~Impl() { close_socket(); }
|
||||
|
||||
Impl(const Impl &) = delete;
|
||||
Impl &operator=(const Impl &) = delete;
|
||||
|
||||
[[nodiscard]] DaemonStatus current_status() const;
|
||||
[[nodiscard]] std::string status_response() const;
|
||||
DispatchResult dispatch(std::string_view line);
|
||||
|
||||
void close_socket() noexcept {
|
||||
if (listen_fd >= 0) {
|
||||
::close(listen_fd);
|
||||
listen_fd = -1;
|
||||
}
|
||||
if (!created_socket) {
|
||||
return;
|
||||
}
|
||||
created_socket = false;
|
||||
struct stat current{};
|
||||
if (::lstat(socket_path.c_str(), ¤t) == 0 && current.st_dev == socket_device &&
|
||||
current.st_ino == socket_inode) {
|
||||
::unlink(socket_path.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
DaemonOptions options;
|
||||
std::filesystem::path socket_path;
|
||||
State::StateStore state_store;
|
||||
Watch::InotifyWatcher watcher;
|
||||
Clock::time_point started;
|
||||
int listen_fd{-1};
|
||||
bool created_socket{false};
|
||||
dev_t socket_device{};
|
||||
ino_t socket_inode{};
|
||||
std::uint64_t watch_events{0};
|
||||
std::string last_event_path;
|
||||
std::uint64_t sequence{0};
|
||||
};
|
||||
|
||||
DaemonStatus DaemonServer::Impl::current_status() const {
|
||||
DaemonStatus status;
|
||||
status.pid = static_cast<std::uint64_t>(::getpid());
|
||||
status.uptime_ms = static_cast<std::uint64_t>(
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - started).count());
|
||||
status.recorded_actions = state_store.recorded_action_count();
|
||||
status.watched_directories = watcher.watched_directory_count();
|
||||
status.watch_events = watch_events;
|
||||
status.last_event_path = last_event_path;
|
||||
status.sequence = sequence;
|
||||
return status;
|
||||
}
|
||||
|
||||
std::string DaemonServer::Impl::status_response() const {
|
||||
const DaemonStatus status = current_status();
|
||||
JsonValue::Object object;
|
||||
object.emplace("ok", JsonValue{true});
|
||||
object.emplace("op", JsonValue{std::string{"status"}});
|
||||
object.emplace("pid", JsonValue{static_cast<std::int64_t>(status.pid)});
|
||||
object.emplace("uptime_ms", JsonValue{static_cast<std::int64_t>(status.uptime_ms)});
|
||||
object.emplace("recorded_actions",
|
||||
JsonValue{static_cast<std::int64_t>(status.recorded_actions)});
|
||||
object.emplace("watched_directories",
|
||||
JsonValue{static_cast<std::int64_t>(status.watched_directories)});
|
||||
object.emplace("watch_events", JsonValue{static_cast<std::int64_t>(status.watch_events)});
|
||||
object.emplace("last_event_path", JsonValue{status.last_event_path});
|
||||
object.emplace("sequence", JsonValue{static_cast<std::int64_t>(status.sequence)});
|
||||
return serialize_response(JsonValue{std::move(object)});
|
||||
}
|
||||
|
||||
DaemonServer::Impl::DispatchResult DaemonServer::Impl::dispatch(std::string_view line) {
|
||||
auto parsed = Void::Json::Strict::parse(line, kMaxJsonDepth);
|
||||
if (!parsed) {
|
||||
return {error_response(std::format("malformed JSON: {}", parsed.error().message)), false};
|
||||
}
|
||||
const auto *object = std::get_if<JsonValue::Object>(&parsed->value);
|
||||
if (object == nullptr) {
|
||||
return {error_response("request must be a JSON object"), false};
|
||||
}
|
||||
const auto op = object->find("op");
|
||||
if (op == object->end()) {
|
||||
return {error_response("request is missing \"op\""), false};
|
||||
}
|
||||
const auto *name = std::get_if<std::string>(&op->second.value);
|
||||
if (name == nullptr) {
|
||||
return {error_response("\"op\" must be a string"), false};
|
||||
}
|
||||
|
||||
if (*name == "ping") {
|
||||
return {ok_response("ping"), false};
|
||||
}
|
||||
if (*name == "status") {
|
||||
return {status_response(), false};
|
||||
}
|
||||
if (*name == "shutdown") {
|
||||
return {ok_response("shutdown"), true};
|
||||
}
|
||||
if (*name == "gc") {
|
||||
std::uint64_t max_bytes = 0;
|
||||
if (const auto entry = object->find("max_bytes"); entry != object->end()) {
|
||||
const auto *value = std::get_if<std::int64_t>(&entry->second.value);
|
||||
if (value == nullptr) {
|
||||
return {error_response("\"max_bytes\" must be an integer"), false};
|
||||
}
|
||||
if (*value < 0) {
|
||||
return {error_response("\"max_bytes\" must be non-negative"), false};
|
||||
}
|
||||
max_bytes = static_cast<std::uint64_t>(*value);
|
||||
}
|
||||
auto stats = state_store.gc(max_bytes);
|
||||
if (!stats) {
|
||||
return {error_response(stats.error().format()), false};
|
||||
}
|
||||
JsonValue::Object response;
|
||||
response.emplace("ok", JsonValue{true});
|
||||
response.emplace("op", JsonValue{std::string{"gc"}});
|
||||
response.emplace("removed_blobs",
|
||||
JsonValue{static_cast<std::int64_t>(stats->removed_blobs)});
|
||||
response.emplace("freed_bytes", JsonValue{static_cast<std::int64_t>(stats->freed_bytes)});
|
||||
response.emplace("retained_blobs",
|
||||
JsonValue{static_cast<std::int64_t>(stats->retained_blobs)});
|
||||
response.emplace("cleaned_staging_files",
|
||||
JsonValue{static_cast<std::int64_t>(stats->cleaned_staging_files)});
|
||||
return {serialize_response(JsonValue{std::move(response)}), false};
|
||||
}
|
||||
if (*name == "recover") {
|
||||
auto recovered = state_store.recover();
|
||||
if (!recovered) {
|
||||
return {error_response(recovered.error().format()), false};
|
||||
}
|
||||
JsonValue::Object response;
|
||||
response.emplace("ok", JsonValue{true});
|
||||
response.emplace("op", JsonValue{std::string{"recover"}});
|
||||
response.emplace("recovered", JsonValue{static_cast<std::int64_t>(*recovered)});
|
||||
return {serialize_response(JsonValue{std::move(response)}), false};
|
||||
}
|
||||
|
||||
return {error_response(std::format("unknown op '{}'", *name)), false};
|
||||
}
|
||||
|
||||
DaemonServer::DaemonServer(std::unique_ptr<Impl> impl) noexcept : impl_{std::move(impl)} {}
|
||||
|
||||
DaemonServer::~DaemonServer() = default;
|
||||
DaemonServer::DaemonServer(DaemonServer &&) noexcept = default;
|
||||
DaemonServer &DaemonServer::operator=(DaemonServer &&) noexcept = default;
|
||||
|
||||
Void::Result::Result<DaemonServer, Void::Result::Error>
|
||||
DaemonServer::create(DaemonOptions options) {
|
||||
if (options.project_root.empty()) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: project_root must not be empty")};
|
||||
}
|
||||
if (options.build_root.empty()) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: build_root must not be empty")};
|
||||
}
|
||||
if (options.poll_interval.count() < 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: poll_interval must be non-negative")};
|
||||
}
|
||||
|
||||
std::filesystem::path socket_path = options.socket_path;
|
||||
if (socket_path.empty()) {
|
||||
socket_path = options.build_root / ".vbs" / "vbs-daemon.sock";
|
||||
}
|
||||
auto address = make_address(socket_path);
|
||||
if (!address) {
|
||||
return std::unexpected{std::move(address.error())};
|
||||
}
|
||||
|
||||
auto state_store = State::StateStore::open(options.build_root / ".vbs");
|
||||
if (!state_store) {
|
||||
return std::unexpected{state_store.error().with_context("daemon: opening state store")};
|
||||
}
|
||||
auto watcher = Watch::InotifyWatcher::create(options.project_root);
|
||||
if (!watcher) {
|
||||
return std::unexpected{watcher.error().with_context("daemon: creating project watcher")};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
if (socket_path.has_parent_path()) {
|
||||
std::filesystem::create_directories(socket_path.parent_path(), ec);
|
||||
if (ec) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot create socket directory '{}': {}",
|
||||
socket_path.parent_path().string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
|
||||
const auto existing = std::filesystem::symlink_status(socket_path, ec);
|
||||
if (ec && ec != std::errc::no_such_file_or_directory) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot inspect socket path '{}': {}",
|
||||
socket_path.string(), ec.message()))};
|
||||
}
|
||||
if (!ec && std::filesystem::exists(existing)) {
|
||||
const auto probe = request(socket_path, R"({"op":"ping"})", kProbeTimeout);
|
||||
bool live = false;
|
||||
if (probe) {
|
||||
auto parsed = Void::Json::Strict::parse(*probe, kMaxJsonDepth);
|
||||
if (parsed) {
|
||||
if (const auto *object = std::get_if<JsonValue::Object>(&parsed->value)) {
|
||||
if (const auto ok = object->find("ok");
|
||||
ok != object->end() && std::get_if<bool>(&ok->second.value) != nullptr &&
|
||||
std::get<bool>(ok->second.value)) {
|
||||
live = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::conflict,
|
||||
std::format("daemon: already running at '{}'", socket_path.string()))};
|
||||
}
|
||||
if (!std::filesystem::is_socket(existing)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::conflict,
|
||||
std::format("daemon: '{}' exists and is not a socket", socket_path.string()))};
|
||||
}
|
||||
std::filesystem::remove(socket_path, ec);
|
||||
if (ec) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot remove stale socket '{}': {}",
|
||||
socket_path.string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
|
||||
UniqueFd listen_fd{::socket(AF_UNIX, SOCK_STREAM, 0)};
|
||||
if (!listen_fd.valid()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: socket() failed", errno)};
|
||||
}
|
||||
if (auto cloexec = set_close_on_exec(listen_fd.get()); !cloexec) {
|
||||
return std::unexpected{std::move(cloexec.error())};
|
||||
}
|
||||
|
||||
bool bound = false;
|
||||
const auto unlink_if_bound = [&]() noexcept {
|
||||
if (bound) {
|
||||
::unlink(socket_path.c_str());
|
||||
}
|
||||
};
|
||||
|
||||
if (::bind(listen_fd.get(), reinterpret_cast<const sockaddr *>(&*address),
|
||||
sizeof(sockaddr_un)) < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot bind '{}'", socket_path.string()), errno)};
|
||||
}
|
||||
bound = true;
|
||||
|
||||
if (::chmod(socket_path.c_str(), 0600) < 0) {
|
||||
const int saved = errno;
|
||||
unlink_if_bound();
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot chmod socket '{}'", socket_path.string()), saved)};
|
||||
}
|
||||
if (::listen(listen_fd.get(), kListenBacklog) < 0) {
|
||||
const int saved = errno;
|
||||
unlink_if_bound();
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot listen on '{}'", socket_path.string()), saved)};
|
||||
}
|
||||
|
||||
struct stat socket_stat{};
|
||||
if (::lstat(socket_path.c_str(), &socket_stat) != 0) {
|
||||
const int saved = errno;
|
||||
unlink_if_bound();
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot stat socket '{}'", socket_path.string()), saved)};
|
||||
}
|
||||
|
||||
auto impl = std::make_unique<Impl>(std::move(options), socket_path, std::move(*state_store),
|
||||
std::move(*watcher));
|
||||
impl->listen_fd = listen_fd.release();
|
||||
impl->created_socket = true;
|
||||
impl->socket_device = socket_stat.st_dev;
|
||||
impl->socket_inode = socket_stat.st_ino;
|
||||
return DaemonServer{std::move(impl)};
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> DaemonServer::run(std::stop_token stop) {
|
||||
if (!impl_) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: server has been moved from")};
|
||||
}
|
||||
auto &impl = *impl_;
|
||||
if (impl.listen_fd < 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: server is not listening")};
|
||||
}
|
||||
|
||||
std::size_t served = 0;
|
||||
bool shutdown_requested = false;
|
||||
while (!stop.stop_requested() && !shutdown_requested &&
|
||||
(impl.options.max_requests == 0 || served < impl.options.max_requests)) {
|
||||
pollfd descriptor{impl.listen_fd, POLLIN, 0};
|
||||
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(impl.options.poll_interval));
|
||||
if (ready < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
impl.close_socket();
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
|
||||
}
|
||||
|
||||
if (ready > 0 && (descriptor.revents & POLLIN) != 0) {
|
||||
sockaddr_un peer{};
|
||||
socklen_t peer_length = sizeof(peer);
|
||||
const int client =
|
||||
::accept(impl.listen_fd, reinterpret_cast<sockaddr *>(&peer), &peer_length);
|
||||
if (client < 0) {
|
||||
if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) {
|
||||
impl.close_socket();
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: accept failed", errno)};
|
||||
}
|
||||
} else {
|
||||
UniqueFd client_fd{client};
|
||||
if (auto cloexec = set_close_on_exec(client_fd.get()); !cloexec) {
|
||||
continue;
|
||||
}
|
||||
auto line = read_line(client_fd.get(), kClientIoTimeout);
|
||||
if (line) {
|
||||
Impl::DispatchResult result = impl.dispatch(*line);
|
||||
static_cast<void>(write_all(client_fd.get(), result.response + "\n"));
|
||||
++served;
|
||||
shutdown_requested = result.shutdown;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto batch =
|
||||
impl.watcher.poll_events(std::chrono::milliseconds{0}, std::chrono::milliseconds{0});
|
||||
if (!batch) {
|
||||
// Watcher failures are surfaced through the next scan; the daemon stays alive.
|
||||
continue;
|
||||
}
|
||||
if (batch->overflowed || batch->rescan_required) {
|
||||
static_cast<void>(impl.watcher.rescan_watches());
|
||||
++impl.sequence;
|
||||
}
|
||||
if (!batch->changed_paths.empty()) {
|
||||
impl.watch_events += batch->changed_paths.size();
|
||||
impl.last_event_path = batch->changed_paths.back().string();
|
||||
++impl.sequence;
|
||||
}
|
||||
}
|
||||
impl.close_socket();
|
||||
return {};
|
||||
}
|
||||
|
||||
const std::filesystem::path &DaemonServer::socket_path() const noexcept {
|
||||
static const std::filesystem::path empty;
|
||||
return impl_ ? impl_->socket_path : empty;
|
||||
}
|
||||
|
||||
DaemonStatus DaemonServer::status() const {
|
||||
if (!impl_) {
|
||||
return {};
|
||||
}
|
||||
return impl_->current_status();
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
request(const std::filesystem::path &socket_path, std::string_view request_json,
|
||||
std::chrono::milliseconds timeout) {
|
||||
if (request_json.find('\n') != std::string_view::npos ||
|
||||
request_json.find('\r') != std::string_view::npos) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: request must be a single JSON line")};
|
||||
}
|
||||
if (request_json.size() > kMaxRequestBytes) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: request exceeds 64 KiB")};
|
||||
}
|
||||
|
||||
auto fd = connect_socket(socket_path, timeout);
|
||||
if (!fd) {
|
||||
return std::unexpected{std::move(fd.error())};
|
||||
}
|
||||
std::string payload{request_json};
|
||||
payload.push_back('\n');
|
||||
if (auto written = write_all(fd->get(), payload); !written) {
|
||||
return std::unexpected{std::move(written.error())};
|
||||
}
|
||||
return read_line(fd->get(), timeout);
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Daemon
|
||||
+132
@@ -2,6 +2,7 @@
|
||||
#include <Void/Build/BootstrapConfig.hpp>
|
||||
#include <Void/Build/Bridge/CMakeBridge.hpp>
|
||||
#include <Void/Build/Config/Frontend.hpp>
|
||||
#include <Void/Build/Daemon/Daemon.hpp>
|
||||
#include <Void/Build/Editor/CompDb.hpp>
|
||||
#include <Void/Build/Execution/Scheduler.hpp>
|
||||
#include <Void/Build/Graph/Graph.hpp>
|
||||
@@ -26,6 +27,7 @@
|
||||
#include <Void/Build/Watch/Watcher.hpp>
|
||||
#include <Void/Configuration/Argparse.hpp>
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/SignalWatcher.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
@@ -1529,6 +1531,109 @@ int execute_gc_command(const GcCmdOptions &opts) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct DaemonCmdOptions {
|
||||
std::string project_arg;
|
||||
std::optional<std::string> build_arg;
|
||||
std::optional<std::string> socket_arg;
|
||||
std::string max_bytes_arg{"0"};
|
||||
std::string max_requests_arg{"0"};
|
||||
};
|
||||
|
||||
std::filesystem::path resolve_daemon_socket(const DaemonCmdOptions &opts,
|
||||
const std::filesystem::path &build_root) {
|
||||
return opts.socket_arg ? std::filesystem::path{*opts.socket_arg}
|
||||
: build_root / ".vbs" / "vbs-daemon.sock";
|
||||
}
|
||||
|
||||
int execute_daemon_command(std::string_view sub, const DaemonCmdOptions &opts) {
|
||||
const std::filesystem::path project_root{opts.project_arg};
|
||||
const std::filesystem::path build_root =
|
||||
opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build");
|
||||
const auto socket_path = resolve_daemon_socket(opts, build_root);
|
||||
|
||||
if (sub == "run") {
|
||||
std::size_t max_requests = 0;
|
||||
const auto [ptr, ec] = std::from_chars(
|
||||
opts.max_requests_arg.data(),
|
||||
opts.max_requests_arg.data() + opts.max_requests_arg.size(), max_requests);
|
||||
if (ec != std::errc{} ||
|
||||
ptr != opts.max_requests_arg.data() + opts.max_requests_arg.size()) {
|
||||
std::cerr << "vbs daemon run: invalid --max-requests value '" << opts.max_requests_arg
|
||||
<< "'\n";
|
||||
return 2;
|
||||
}
|
||||
Daemon::DaemonOptions daemon_opts;
|
||||
daemon_opts.project_root = project_root;
|
||||
daemon_opts.build_root = build_root;
|
||||
daemon_opts.socket_path = socket_path;
|
||||
daemon_opts.max_requests = max_requests;
|
||||
auto server = Daemon::DaemonServer::create(std::move(daemon_opts));
|
||||
if (!server) {
|
||||
std::cerr << "vbs daemon: " << server.error().message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
Void::Log::info("Daemon", "Serving '{}' (Ctrl+C to stop)...", socket_path.string());
|
||||
std::stop_source stop_src;
|
||||
auto sig = Void::Process::SignalWatcher::create();
|
||||
std::jthread sig_thread([&] {
|
||||
if (sig) {
|
||||
(void)sig->wait();
|
||||
stop_src.request_stop();
|
||||
}
|
||||
});
|
||||
auto result = server->run(stop_src.get_token());
|
||||
if (!result) {
|
||||
std::cerr << "vbs daemon: " << result.error().message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string request_json;
|
||||
if (sub == "status") {
|
||||
request_json = R"({"op":"status"})";
|
||||
} else if (sub == "stop") {
|
||||
request_json = R"({"op":"shutdown"})";
|
||||
} else if (sub == "recover") {
|
||||
request_json = R"({"op":"recover"})";
|
||||
} else if (sub == "gc") {
|
||||
std::uint64_t max_bytes = 0;
|
||||
const auto [ptr, ec] =
|
||||
std::from_chars(opts.max_bytes_arg.data(),
|
||||
opts.max_bytes_arg.data() + opts.max_bytes_arg.size(), max_bytes);
|
||||
if (ec != std::errc{} || ptr != opts.max_bytes_arg.data() + opts.max_bytes_arg.size()) {
|
||||
std::cerr << "vbs daemon gc: invalid --max-bytes value '" << opts.max_bytes_arg
|
||||
<< "'\n";
|
||||
return 2;
|
||||
}
|
||||
request_json = std::format(R"({{"op":"gc","max_bytes":{}}})", max_bytes);
|
||||
} else {
|
||||
std::cerr << "vbs daemon: unknown command '" << sub << "'\n";
|
||||
return 2;
|
||||
}
|
||||
|
||||
auto response = Daemon::request(socket_path, request_json);
|
||||
if (!response) {
|
||||
std::cerr << "vbs daemon: " << response.error().message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
std::cout << *response << '\n';
|
||||
const auto parsed = Void::Json::Strict::parse(*response);
|
||||
if (!parsed) {
|
||||
return 1;
|
||||
}
|
||||
const auto *object = std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
|
||||
if (object == nullptr) {
|
||||
return 1;
|
||||
}
|
||||
const auto ok = object->find("ok");
|
||||
if (ok == object->end()) {
|
||||
return 1;
|
||||
}
|
||||
const auto *flag = std::get_if<bool>(&ok->second.value);
|
||||
return (flag != nullptr && *flag) ? 0 : 1;
|
||||
}
|
||||
|
||||
struct GenTestsCmdOptions {
|
||||
std::optional<std::string> input_arg;
|
||||
std::optional<std::string> out_arg;
|
||||
@@ -2185,6 +2290,8 @@ int main(int argc, char **argv) {
|
||||
graph_opts.project_arg = cwd;
|
||||
IdeCmdOptions ide_opts;
|
||||
ide_opts.project_arg = cwd;
|
||||
DaemonCmdOptions daemon_opts;
|
||||
daemon_opts.project_arg = cwd;
|
||||
|
||||
auto add_log_flags = [&](Void::Argparse::Parser &p, bool allow_short_v = true) {
|
||||
p.flag("--verbose", allow_short_v ? "-v" : "", "Enable verbose debug logs", verbose)
|
||||
@@ -2406,6 +2513,28 @@ int main(int argc, char **argv) {
|
||||
configure_ide_common(
|
||||
ide_cmd.subcommand("query", "Emit versioned JSON workspace, target, and compdb metadata"));
|
||||
|
||||
auto &daemon_cmd = root.subcommand("daemon", "Run or control the persistent build daemon");
|
||||
auto configure_daemon_common = [&](Void::Argparse::Parser &p) {
|
||||
p.option_default("--project", "-C", "Project directory", daemon_opts.project_arg, cwd)
|
||||
.option("--build-dir", "-B", "Build output directory", daemon_opts.build_arg)
|
||||
.option("--socket", "", "Unix socket path (default: <build>/.vbs/vbs-daemon.sock)",
|
||||
daemon_opts.socket_arg);
|
||||
add_log_flags(p);
|
||||
};
|
||||
auto &daemon_run_cmd = daemon_cmd.subcommand("run", "Run the daemon in the foreground");
|
||||
configure_daemon_common(daemon_run_cmd);
|
||||
daemon_run_cmd.option_default("--max-requests", "", "Stop after N requests (0 = unlimited)",
|
||||
daemon_opts.max_requests_arg, "0");
|
||||
configure_daemon_common(daemon_cmd.subcommand("status", "Query the running daemon's status"));
|
||||
configure_daemon_common(daemon_cmd.subcommand("stop", "Ask the running daemon to shut down"));
|
||||
configure_daemon_common(
|
||||
daemon_cmd.subcommand("recover", "Run interrupted-state recovery in the daemon"));
|
||||
auto &daemon_gc_cmd = daemon_cmd.subcommand("gc", "Run CAS garbage collection in the daemon");
|
||||
configure_daemon_common(daemon_gc_cmd);
|
||||
daemon_gc_cmd.option_default("--max-bytes", "",
|
||||
"Target maximum retained CAS bytes (0=unreferenced only)",
|
||||
daemon_opts.max_bytes_arg, "0");
|
||||
|
||||
const auto parsed = root.parse_detailed(argc, argv);
|
||||
if (parsed.is_help()) {
|
||||
std::cout << parsed.message;
|
||||
@@ -2496,6 +2625,9 @@ int main(int argc, char **argv) {
|
||||
if (cmd == "ide") {
|
||||
return execute_ide_command(parsed.matched_command_path.at(1), ide_opts);
|
||||
}
|
||||
if (cmd == "daemon") {
|
||||
return execute_daemon_command(parsed.matched_command_path.at(1), daemon_opts);
|
||||
}
|
||||
|
||||
std::cerr << "vbs: unhandled subcommand '" << cmd << "'\n";
|
||||
return 2;
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
|
||||
#if !defined(__linux__)
|
||||
#error \
|
||||
"VoidBuildSystem's process and file backends currently support Linux hosts only (Track C2/C3 ports are planned)"
|
||||
#endif
|
||||
|
||||
namespace Void::Build::Platform {
|
||||
namespace {
|
||||
|
||||
@@ -11,6 +11,11 @@
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
|
||||
#if !defined(__linux__)
|
||||
#error \
|
||||
"VoidBuildSystem's process and file backends currently support Linux hosts only (Track C2/C3 ports are planned)"
|
||||
#endif
|
||||
|
||||
namespace Void::Build::Platform {
|
||||
namespace {
|
||||
|
||||
@@ -1152,6 +1152,12 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) {
|
||||
done_utility:
|
||||
continue;
|
||||
}
|
||||
// CMake synthesizes @cmake_cxx_std@(synth_N) INTERFACE_LIBRARY carriers for
|
||||
// target_compile_features standards. The -std flag is already lowered from each
|
||||
// consumer's compile groups, so these feature-only targets have no graph effect.
|
||||
if (pt.type == "INTERFACE_LIBRARY" && pt.name.starts_with("@cmake_cxx_std")) {
|
||||
continue;
|
||||
}
|
||||
if (pt.type == "GLOBAL_TARGET") {
|
||||
add_unsupported(
|
||||
pt.name, "utility_target",
|
||||
@@ -1551,6 +1557,9 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) {
|
||||
}
|
||||
} else if (out.targets_by_id.contains(dep_id)) {
|
||||
link_deps.push_back(dep_id);
|
||||
} else if (dep_id.starts_with("@cmake_cxx_std")) {
|
||||
// Feature-only INTERFACE_LIBRARY carrier skipped above; the standard is
|
||||
// already encoded in the consumer's compile options.
|
||||
} else {
|
||||
add_unsupported(pt.name, "untranslated_dependency_edge",
|
||||
std::format("target '{}' depends on untranslated CMake target '{}'",
|
||||
|
||||
Reference in new issue
Block a user