From d3e10dc31b0835d73887c615100ce1b1efdfb810 Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Tue, 22 Jul 2025 10:37:21 +0200 Subject: [PATCH] Rewrite child application management Forked applications are managed by a class, which can track more than one child. Systemd mode uses transient units, libsystemd is replaced by gdbus-codegen, the management objects shares the interface with forked application. --- dbus/org.freedesktop.systemd1.Manager.xml | 848 ++++++++++++++++++++++ dbus/org.freedesktop.systemd1.Unit.xml | 386 ++++++++++ server/CMakeLists.txt | 16 + server/main.cpp | 90 +-- server/start_application.cpp | 395 +++------- server/start_application.h | 61 +- server/start_systemd_unit.cpp | 248 +++++++ server/start_systemd_unit.h | 78 ++ 8 files changed, 1759 insertions(+), 363 deletions(-) create mode 100644 dbus/org.freedesktop.systemd1.Manager.xml create mode 100644 dbus/org.freedesktop.systemd1.Unit.xml create mode 100644 server/start_systemd_unit.cpp create mode 100644 server/start_systemd_unit.h diff --git a/dbus/org.freedesktop.systemd1.Manager.xml b/dbus/org.freedesktop.systemd1.Manager.xml new file mode 100644 index 00000000..366dc4b7 --- /dev/null +++ b/dbus/org.freedesktop.systemd1.Manager.xml @@ -0,0 +1,848 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dbus/org.freedesktop.systemd1.Unit.xml b/dbus/org.freedesktop.systemd1.Unit.xml new file mode 100644 index 00000000..d4afb589 --- /dev/null +++ b/dbus/org.freedesktop.systemd1.Unit.xml @@ -0,0 +1,386 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 2d38ac35..3a9d83e9 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -188,6 +188,22 @@ if (WIVRN_BUILD_SERVER) target_link_libraries(wivrn-server PUBLIC wivrn-server-dbus) target_link_libraries(wivrn-server PUBLIC PkgConfig::libnotify) + if(WIVRN_USE_SYSTEMD) + add_custom_command(OUTPUT systemd_manager.c systemd_manager.h + COMMAND ${GDBUS_CODEGEN} ${CMAKE_CURRENT_SOURCE_DIR}/../dbus/org.freedesktop.systemd1.Manager.xml --interface-prefix org.freedesktop.systemd1 --generate-c-code systemd_manager --c-namespace systemd + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../dbus/org.freedesktop.systemd1.Manager.xml ) + add_custom_command(OUTPUT systemd_unit.c systemd_unit.h + COMMAND ${GDBUS_CODEGEN} ${CMAKE_CURRENT_SOURCE_DIR}/../dbus/org.freedesktop.systemd1.Unit.xml --interface-prefix org.freedesktop.systemd1 --generate-c-code systemd_unit --c-namespace unit + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../dbus/org.freedesktop.systemd1.Manager.xml ) + target_sources(wivrn-server-dbus PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}/systemd_manager.c ${CMAKE_CURRENT_BINARY_DIR}/systemd_manager.h + ${CMAKE_CURRENT_BINARY_DIR}/systemd_unit.c ${CMAKE_CURRENT_BINARY_DIR}/systemd_unit.h) + target_sources( + wivrn-server + PRIVATE start_systemd_unit.cpp + ) + endif() + target_link_libraries( wivrn-server PRIVATE diff --git a/server/main.cpp b/server/main.cpp index 4e04048a..1b6dac85 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -33,7 +33,6 @@ #include #include #include -#include #include #include #include @@ -53,6 +52,10 @@ #include #include +#if WIVRN_USE_SYSTEMD +#include "start_systemd_unit.h" +#endif + // Insert the on load constructor to init trace marker. U_TRACE_TARGET_SETUP(U_TRACE_WHICH_SERVICE) @@ -124,21 +127,6 @@ int create_listen_socket() return fd; } -void display_child_status(int wstatus, const std::string & name) -{ - std::cerr << name << " exited, exit status " << WEXITSTATUS(wstatus); - if (WIFSIGNALED(wstatus)) - { - std::cerr << ", received signal " << sigabbrev_np(WTERMSIG(wstatus)) << " (" - << strsignal(WTERMSIG(wstatus)) << ")" - << (WCOREDUMP(wstatus) ? ", core dumped" : "") << std::endl; - } - else - { - std::cerr << std::endl; - } -} - static std::filesystem::path flatpak_app_path() { if (auto value = flatpak_key(flatpak::section::instance, "app-path")) @@ -197,9 +185,7 @@ guint server_kill_watch; pid_t server_pid; std::optional connection_thread; -guint app_watch; -guint app_kill_watch; -pid_t app_pid; +std::unique_ptr children; bool quitting_main_loop; bool do_fork; @@ -236,37 +222,6 @@ void stop_publishing(); void update_fsm(); -void start_app(const std::vector & args) -{ -#if WIVRN_USE_SYSTEMD - app_pid = use_systemd ? start_unit_file(args) : fork_application(args); -#else - app_pid = fork_application(); -#endif - - assert(app_watch == 0); - assert(app_kill_watch == 0); - if (app_pid > 0) - { - app_watch = g_child_watch_add(app_pid, [](pid_t, int status, void *) { - display_child_status(status, "Application"); - g_source_remove(app_watch); - if (app_kill_watch) - g_source_remove(app_kill_watch); - - app_watch = 0; - app_kill_watch = 0; - - update_fsm(); }, nullptr); - } - else - { - app_watch = 0; - if (app_pid < 0) - throw std::system_error(-app_pid, std::system_category()); - } -} - void start_server(configuration config) { server_pid = do_fork ? fork() : 0; @@ -339,17 +294,6 @@ void start_server(configuration config) runtime_setter.emplace(); } -void kill_app() -{ - kill(-app_pid, SIGTERM); - - // Send SIGKILL after 1s if it is still running - app_kill_watch = g_timeout_add(1000, [](void *) { - assert(app_pid > 0); - kill(-app_pid, SIGKILL); - return G_SOURCE_REMOVE; }, 0); -} - void kill_server() { // Write to the server's stdin to make it quit @@ -421,7 +365,7 @@ void stop_publishing() void update_fsm() { bool server_running = server_watch != 0 or connection_thread; - bool app_running = app_watch != 0; + bool app_running = children->running(); if (quitting_main_loop) { @@ -431,15 +375,18 @@ void update_fsm() kill_server(); if (app_running) - kill_app(); + children->stop(); if (not server_running and not app_running) + { + children.reset(nullptr); g_main_loop_quit(main_loop); + } } else { if (not server_running and app_running) - kill_app(); + children->stop(); if (not server_running) { @@ -483,7 +430,7 @@ gboolean headset_connected_success(void *) start_server(c); try { - start_app(c.application); + children->start_application(c.application); } catch (std::exception & e) { @@ -520,7 +467,7 @@ gboolean headset_connected_incorrect_pin(void *) gboolean headset_connected(gint fd, GIOCondition condition, gpointer user_data) { assert(server_watch == 0); - assert(app_watch == 0); + assert(not children->running()); assert(not connection_thread); assert(listener); @@ -817,6 +764,17 @@ void on_headset_info_packet(const wivrn::from_headset::headset_info_packet & inf void on_name_acquired(GDBusConnection * connection, const gchar * name, gpointer user_data) { +#if WIVRN_USE_SYSTEMD + if (use_systemd) + { + children = std::make_unique(connection, update_fsm); + } + else +#endif + { + children = std::make_unique(update_fsm); + } + dbus_server = wivrn_server_skeleton_new(); g_signal_connect(dbus_server, diff --git a/server/start_application.cpp b/server/start_application.cpp index 1932a042..83d73f9e 100644 --- a/server/start_application.cpp +++ b/server/start_application.cpp @@ -1,296 +1,79 @@ -// Copyright 2024, Gavin John et al. -// SPDX-License-Identifier: BSL-1.0 -/*! - * @file - * @brief Main file for WiVRn Monado service. - * @author Gavin John +/* + * WiVRn VR streaming + * Copyright (C) 2025 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ #include "start_application.h" -#include "driver/configuration.h" #include "utils/flatpak.h" +#include #include #include #include +#include #include -#include -#if WIVRN_USE_SYSTEMD -#include -#include -#include -#include - -namespace +namespace wivrn { -struct deleter -{ - void operator()(sd_bus * p) - { - sd_bus_unref(p); - } - void operator()(sd_bus_message * p) - { - sd_bus_message_unref(p); - } -}; +children_manager::~children_manager() {} -struct raii_sd_bus_error -{ - sd_bus_error data = SD_BUS_ERROR_NULL; +forked_children::forked_children(std::function state_changed_cb) : + state_changed_cb(state_changed_cb) {} - auto operator&() - { - return &data; - } - - ~raii_sd_bus_error() - { - sd_bus_error_free(&data); - } -}; - -using sd_bus_ptr = std::unique_ptr; -using sd_msg_ptr = std::unique_ptr; - -struct container -{ - container(sd_bus_message * msg, char type, const char * contents) : - msg(msg) - { - int ret = sd_bus_message_open_container(msg, type, contents); - if (ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_open_container failed"); - } - ~container() - { - int ret = sd_bus_message_close_container(msg); - if (ret < 0) - std::cerr << "sd_bus_message_close_container failed" << std::endl; - } - sd_bus_message * msg; -}; - -sd_bus_ptr get_user_bus() -{ - sd_bus * bus = nullptr; - int ret; - // reimplement sd_bus_open_user to honor the env variable - if (const char * bus_address = getenv("DBUS_SESSION_BUS_ADDRESS")) - { - if (ret = sd_bus_new(&bus); ret < 0) - throw std::system_error(-ret, std::system_category(), "failed to create dbus object"); - sd_bus_ptr res(bus); - - if (ret = sd_bus_set_address(bus, bus_address); ret < 0) - throw std::system_error(-ret, std::system_category(), std::string("failed to connect to dbus at address ") + bus_address); - - if (ret = sd_bus_set_bus_client(bus, 1); ret < 0) - throw std::system_error(-ret, std::system_category(), std::string("failed to configure dbus at address ") + bus_address); - if (ret = sd_bus_set_trusted(bus, 1); ret < 0) - throw std::system_error(-ret, std::system_category(), std::string("failed to trust dbus at address ") + bus_address); - - if (ret = sd_bus_start(bus); ret < 0) - throw std::system_error(-ret, std::system_category(), std::string("failed to start dbus connection ") + bus_address); - - return res; - } - if (ret = sd_bus_open_user(&bus); ret < 0) - throw std::system_error(-ret, std::system_category(), "failed to connect to dbus"); - - return sd_bus_ptr(bus); -} -} // namespace - -static int get_service_pid(sd_bus * bus, const std::string & service_name, pid_t & pid) -{ - sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message * msg = nullptr; - const char * destination = "org.freedesktop.systemd1"; - const char * path = "/org/freedesktop/systemd1"; - const char * interface = "org.freedesktop.systemd1.Manager"; - const char * member = "GetUnit"; - - int ret = 0; - - // Call the method - ret = sd_bus_call_method(bus, destination, path, interface, member, &error, &msg, "s", service_name.c_str()); - if (ret < 0) - { - std::cerr << "Failed to issue method call: " << error.message << std::endl; - goto finish; - } - - // Parse the response message - const char * object_path; - ret = sd_bus_message_read(msg, "o", &object_path); - if (ret < 0) - { - std::cerr << "Failed to parse response message: " << strerror(-ret) << std::endl; - goto finish; - } - - // Get the service's main PID - ret = sd_bus_get_property_trivial(bus, destination, object_path, "org.freedesktop.systemd1.Service", "MainPID", &error, 'u', &pid); - if (ret < 0) - { - std::cerr << "Failed to get PID: " << error.message << std::endl; - goto finish; - } - -finish: - sd_bus_error_free(&error); - sd_bus_message_unref(msg); - return ret; -} - -std::string start_service(sd_bus * bus, const std::string & service_name, const std::vector & args) -{ - assert(not args.empty()); - raii_sd_bus_error error; - sd_bus_message * msg = nullptr; - const char * destination = "org.freedesktop.systemd1"; - const char * path = "/org/freedesktop/systemd1"; - const char * interface = "org.freedesktop.systemd1.Manager"; - const char * member = "StartTransientUnit"; - const char * mode = "replace"; - - int ret = sd_bus_message_new_method_call(bus, &msg, destination, path, interface, member); - if (ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_new_method_call failed"); - sd_msg_ptr raii_msg(msg); - - // Name, mode - if (ret = sd_bus_message_append(msg, "ss", service_name.c_str(), mode); ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_append failed"); - - // Properties - { - container a(msg, 'a', "(sv)"); - if (ret = sd_bus_message_append(msg, "(sv)", "Description", "s", "Application spawned by WiVRn"); ret < 0) - throw std::system_error(-ret, std::system_category(), "failed to set description"); - - container r(msg, 'r', "sv"); - if (ret = sd_bus_message_append(msg, "s", "ExecStart"); ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_append failed"); - container v(msg, 'v', "a(sasb)"); - container a1(msg, 'a', "(sasb)"); - container r1(msg, 'r', "sasb"); - if (ret = sd_bus_message_append(msg, "s", args[0].c_str()); ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_append failed"); - - { - container a(msg, 'a', "s"); - for (const auto & arg: args) - { - if (ret = sd_bus_message_append(msg, "s", arg.c_str()); ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_append failed"); - } - } - - if (ret = sd_bus_message_append(msg, "b", false); ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_append failed"); - } - - // aux (empty) - if (ret = sd_bus_message_append(msg, "a(sa(sv))", 0); ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_append failed"); - - sd_bus_message * reply = nullptr; - if (ret = sd_bus_call(bus, msg, 0, &error, &reply); ret < 0) - throw std::system_error(-ret, std::system_category(), std::format("sd_bus_call failed: {}", error.data.message)); - sd_msg_ptr raii_reply(reply); - - char * object; - if (ret = sd_bus_message_read(reply, "o", &object); ret < 0) - throw std::system_error(-ret, std::system_category(), "sd_bus_message_read failed"); - - return object; -} - -bool is_service_active(sd_bus * bus, const std::string & service_name) -{ - sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message * msg = nullptr; - const char * destination = "org.freedesktop.systemd1"; - const char * path = "/org/freedesktop/systemd1"; - const char * interface = "org.freedesktop.systemd1.Manager"; - const char * member = "GetUnit"; - - bool is_active = false; - const char * object_path; - // Call the method - int ret = sd_bus_call_method(bus, destination, path, interface, member, &error, &msg, "s", service_name.c_str()); - if (ret < 0) - { - std::cerr << "Failed to issue method call: " << error.message << std::endl; - goto finish; - } - - // Parse the response message - ret = sd_bus_message_read(msg, "o", &object_path); - if (ret < 0) - { - std::cerr << "Failed to parse response message: " << strerror(-ret) << std::endl; - goto finish; - } - - // Check the service's ActiveState property - char * active_state; - ret = sd_bus_get_property_string(bus, destination, object_path, "org.freedesktop.systemd1.Unit", "ActiveState", &error, &active_state); - if (ret < 0) - { - std::cerr << "Failed to get ActiveState: " << error.message << std::endl; - goto finish; - } - - is_active = (std::string_view(active_state) == "active"); - -finish: - sd_bus_error_free(&error); - sd_bus_message_unref(msg); - return is_active; -} - -pid_t wivrn::start_unit_file(const std::vector & args) +void forked_children::start_application(const std::vector & args) { if (args.empty()) - return 0; + return; - std::string service_name = std::format("wivrn-application-{}.service", std::chrono::steady_clock::now().time_since_epoch().count()); - pid_t pid; - auto bus = get_user_bus(); - int ret = get_service_pid(bus.get(), service_name, pid); + pid_t application_pid = fork(); - if (ret < 0 || pid == 0) + if (application_pid < 0) + throw std::system_error(errno, std::system_category(), "fork"); + + if (application_pid > 0) { - auto obj = start_service(bus.get(), service_name, args); - std::cout << "started service: " << obj << std::endl; + guint app_watch = g_child_watch_add( + application_pid, + [](pid_t pid, int status, void * self_) { + auto self = (forked_children *)self_; + bool empty = self->children.empty(); + auto node = self->children.extract(pid); + if (not node) + { + std::cerr << "Failed to update child application information" << std::endl; + } + display_child_status(status, "Application"); + const auto & watches = node.mapped(); + g_source_remove(watches.child); + if (watches.kill) + g_source_remove(watches.kill); - // Wait until the service is active - while (!is_service_active(bus.get(), service_name)) - { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - } - - // Try to get the PID again - ret = get_service_pid(bus.get(), service_name, pid); - if (ret < 0) - throw std::system_error(-ret, std::system_category(), "failed to get application PID"); + if (self->state_changed_cb and self->children.empty() and not empty) + self->state_changed_cb(); + }, + this); + children.emplace(application_pid, watches{.child = app_watch}); + return; } - return pid; -} - -#endif - -static int exec_application(std::vector args) -{ - if (args.empty()) - return 0; + // Start a new process group so that all processes started by the + // application can be signaled + setpgrp(); std::vector tmp; std::vector argv; @@ -300,11 +83,10 @@ static int exec_application(std::vector args) { tmp.push_back("flatpak-spawn"); tmp.push_back("--host"); - for (auto & arg: tmp) - argv.push_back(arg.data()); } - for (auto & arg: args) + tmp.insert(tmp.end(), args.begin(), args.end()); + for (auto & arg: tmp) argv.push_back(arg.data()); argv.push_back(nullptr); @@ -319,28 +101,59 @@ static int exec_application(std::vector args) } execvp(executable.c_str(), argv.data()); - - perror("Cannot start application"); + perror("Failed to start application"); exit(EXIT_FAILURE); } -pid_t wivrn::fork_application(const std::vector & args) +forked_children::~forked_children() { - if (args.empty()) - return 0; - - pid_t application_pid = fork(); - if (application_pid < 0) - throw std::system_error(errno, std::system_category(), "fork"); - - if (application_pid == 0) + for (auto & [pid, watches]: children) { - // Start a new process group so that all processes started by the - // application can be signaled - setpgrp(); - - return exec_application(args); + g_source_remove(watches.child); + if (watches.kill) + g_source_remove(watches.kill); } - - return application_pid; } + +bool forked_children::running() const +{ + return not children.empty(); +} + +void forked_children::stop() +{ + for (auto & [pid, watches]: children) + { + kill(-pid, SIGTERM); + intptr_t pid_ptr = pid; + + // Send SIGKILL after 1s if it is still running + static_assert(sizeof(pid_t) < sizeof(intptr_t)); + watches.kill = g_timeout_add( + 1000, + [](void * pid_) { + auto pid = (intptr_t)pid_; + assert(pid > 0); + kill(-pid, SIGKILL); + return G_SOURCE_REMOVE; + }, + (void *)pid_ptr); + } +} + +void display_child_status(int wstatus, const std::string & name) +{ + std::cerr << name << " exited, exit status " << WEXITSTATUS(wstatus); + if (WIFSIGNALED(wstatus)) + { + std::cerr << ", received signal " << sigabbrev_np(WTERMSIG(wstatus)) << " (" + << strsignal(WTERMSIG(wstatus)) << ")" + << (WCOREDUMP(wstatus) ? ", core dumped" : "") << std::endl; + } + else + { + std::cerr << std::endl; + } +} + +} // namespace wivrn diff --git a/server/start_application.h b/server/start_application.h index 378d42aa..1001f4a2 100644 --- a/server/start_application.h +++ b/server/start_application.h @@ -1,17 +1,66 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once -#include "wivrn_config.h" - +#include +#include #include #include +#include #include namespace wivrn { -pid_t fork_application(const std::vector & args); +class children_manager +{ +public: + virtual ~children_manager(); -#if WIVRN_USE_SYSTEMD -pid_t start_unit_file(const std::vector & args); -#endif + virtual void start_application(const std::vector &) = 0; + + virtual bool running() const = 0; + + virtual void stop() = 0; +}; + +// Start applications using fork+exec +class forked_children : public children_manager +{ + struct watches + { + guint child = 0; + guint kill = 0; + }; + std::unordered_map children; + std::function state_changed_cb; + +public: + forked_children(std::function state_changed_cb); + virtual ~forked_children(); + + void start_application(const std::vector &) override; + + // true if any unit started by this object is still running + bool running() const override; + + void stop() override; +}; + +void display_child_status(int wstatus, const std::string & name); } // namespace wivrn diff --git a/server/start_systemd_unit.cpp b/server/start_systemd_unit.cpp new file mode 100644 index 00000000..5009f000 --- /dev/null +++ b/server/start_systemd_unit.cpp @@ -0,0 +1,248 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "start_systemd_unit.h" +#include "systemd_manager.h" +#include "systemd_unit.h" +#include +#include +#include + +#include +#include + +namespace wivrn +{ + +void systemd_units_manager::deleter::operator()(systemdManager * obj) +{ + g_object_unref(obj); +} +void systemd_units_manager::deleter::operator()(unitUnit * obj) +{ + g_object_unref(obj); +} + +systemd_units_manager::systemd_units_manager(GDBusConnection * connection, std::function state_changed_cb) : + connection(connection), state_changed_cb(state_changed_cb) +{ + GError * error = nullptr; + proxy.reset(systemd_manager_proxy_new_sync( + connection, + G_DBUS_PROXY_FLAGS_NONE, + "org.freedesktop.systemd1", + "/org/freedesktop/systemd1", + nullptr, + &error)); + + if (error) + { + std::runtime_error e(std::string("Failed to connect to systemd user session: ") + error->message); + g_error_free(error); + throw e; + } + + systemd_manager_call_subscribe_sync( + proxy.get(), + nullptr, + &error); + + if (error) + { + std::runtime_error e(std::string("Failed to subscribe to systemd messages: ") + error->message); + g_error_free(error); + throw e; + } + + g_signal_connect(proxy.get(), + "job-removed", + G_CALLBACK(&on_job_removed), + this); +} + +bool systemd_units_manager::running() const +{ + return not(jobs.empty() and units.empty()); +} + +void systemd_units_manager::stop() +{ + for (auto & unit: units) + { + unit_unit_call_stop(unit.get(), + "replace", + nullptr, + nullptr, + nullptr); + } +} + +void systemd_units_manager::on_job_removed( + systemdManagerProxy * connection, + guint32 id, + gchar * job, + gchar * unit, + gchar * result, + void * self_) +{ + auto self = (systemd_units_manager *)(self_); + + auto node = self->jobs.extract(job); + if (node.empty()) + return; + + if (strcmp(result, "done")) + { + std::cerr << "Failed to start application " << node.mapped() << ": " << result << std::endl; + return; + } + + std::string object = "/org/freedesktop/systemd1/unit/"; + for (char * c = unit; *c != '\0'; ++c) + { + if (std::isalnum(*c)) + object += *c; + else + object += std::format("_{:02x}", *c); + } + + unit_unit_proxy_new( + self->connection, + G_DBUS_PROXY_FLAGS_NONE, + "org.freedesktop.systemd1", + object.c_str(), + nullptr, + [](GObject * source_object, GAsyncResult * res, void * self_) { + auto self = (systemd_units_manager *)(self_); + + GError * error = nullptr; + + std::unique_ptr unit(unit_unit_proxy_new_finish(res, &error)); + if (error) + { + std::cerr << "failed to create unit proxy: " << error->message << std::endl; + g_error_free(error); + return; + } + + g_signal_connect(unit.get(), + "notify::active-state", + G_CALLBACK(on_unit_result), + self); + + bool changed = self->units.empty(); + + self->units.emplace(std::move(unit)); + if (changed and self->state_changed_cb) + self->state_changed_cb(); + }, + self); +} + +void systemd_units_manager::on_unit_result( + unitUnit * unit, + const GParamSpec * pspec, + void * self_) +{ + auto self = (systemd_units_manager *)(self_); + std::string_view state = unit_unit_get_active_state(unit); + bool empty = self->units.empty(); + if (state == "inactive" or state == "failed") + std::erase_if(self->units, [&](auto & o) { return o.get() == unit; }); + if (self->state_changed_cb and self->units.empty() and not empty) + self->state_changed_cb(); +} + +namespace +{ +struct variant_builder +{ + GVariantBuilder builder; + + variant_builder(const GVariantType * type) + { + g_variant_builder_init(&builder, type); + } + ~variant_builder() + { + g_variant_builder_clear(&builder); + } + auto operator&() + { + return &builder; + } + + GVariant * end() + { + return g_variant_builder_end(&builder); + } +}; + +}; // namespace + +void systemd_units_manager::start_application(const std::vector & args) +{ + if (args.empty()) + return; + + std::string service_name = std::format("wivrn-application-{}.service", std::chrono::steady_clock::now().time_since_epoch().count()); + + variant_builder b(G_VARIANT_TYPE("a(sv)")); + g_variant_builder_add(&b, + "(sv)", + "Description", + g_variant_new("s", "Application spawned by WiVRn")); + + variant_builder argv(G_VARIANT_TYPE("as")); + for (const auto & arg: args) + g_variant_builder_add(&argv, "s", arg.c_str()); + auto exec_start = + g_variant_new("(s@asb)", + args.front().c_str(), + g_variant_new("as", &argv), + false); + g_variant_builder_add(&b, + "(sv)", + "ExecStart", + g_variant_new_array( + nullptr, + &exec_start, + 1)); + + auto properties = b.end(); + auto aux = g_variant_new_array(G_VARIANT_TYPE("(sa(sv))"), nullptr, 0); + + gchar * job = nullptr; + GError * error = nullptr; + systemd_manager_call_start_transient_unit_sync( + proxy.get(), service_name.c_str(), "replace", properties, aux, &job, nullptr, &error); + + if (job) + { + jobs.emplace(job, std::move(service_name)); + g_free(job); + } + + if (error) + { + std::runtime_error e(std::format("start transient unit failed: {}", error->message)); + g_error_free(error); + throw e; + } +} +} // namespace wivrn diff --git a/server/start_systemd_unit.h b/server/start_systemd_unit.h new file mode 100644 index 00000000..31d53c37 --- /dev/null +++ b/server/start_systemd_unit.h @@ -0,0 +1,78 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "start_application.h" + +#include + +#include +#include +#include +#include +#include +#include + +#include "systemd_manager.h" +#include "systemd_unit.h" + +namespace wivrn +{ + +// Start applications in transient units +class systemd_units_manager : public children_manager +{ + struct deleter + { + void operator()(systemdManager *); + void operator()(unitUnit *); + }; + GDBusConnection * connection; + std::unique_ptr proxy; + std::unordered_map jobs; + std::unordered_set> units; + + std::function state_changed_cb; + +public: + systemd_units_manager(GDBusConnection * connection, std::function state_changed_cb); + + // create and start the transient unit + void start_application(const std::vector &) override; + + // true if any unit started by this object is still running + bool running() const override; + + void stop() override; + +private: + static void on_job_removed( + systemdManagerProxy * proxy, + guint32 id, + gchar * job, + gchar * unit, + gchar * result, + void * self); + + static void on_unit_result( + unitUnit * proxy, + const GParamSpec * pspec, + void * self); +}; +} // namespace wivrn