diff --git a/src/core/camera_reader/AGENTS.md b/src/core/camera_reader/AGENTS.md index 732ad6314a..4c34cf1b5b 100644 --- a/src/core/camera_reader/AGENTS.md +++ b/src/core/camera_reader/AGENTS.md @@ -11,4 +11,5 @@ SPDX-License-Identifier: Apache-2.0 - **No copies and no conversions here.** A view is the plugin's buffer. Pixel conversion, if a consumer wants it, is a separate step on top. - **A frame set outlives its reader safely.** Both share one state object; keep it that way rather than making `FrameSet` point back at the reader. - **Releasing must never throw or block.** It runs in destructors, possibly on another thread; a plugin that is gone takes its frames back by itself. +- **Between `fork` and `exec`, system calls only.** The program that links the reader may have threads holding locks at that moment, so the launcher prepares everything before it forks. It also never touches the host's signal handlers, and starts the plugin detached so that nothing is left for the host to reap. - **The plugin is trusted for content, not for bounds.** Check a frame event against the group before handing out views. diff --git a/src/core/camera_reader/README.md b/src/core/camera_reader/README.md index 6c3763e75c..2cb588432a 100644 --- a/src/core/camera_reader/README.md +++ b/src/core/camera_reader/README.md @@ -31,6 +31,13 @@ while (auto frames = reader.next(std::chrono::seconds(1))) endpoint, the group does not exist, or the subscription does not fit the pool. - **Which plugin.** By default the reader looks for this user's plugin on its default endpoint. A `PluginLocation` names another instance of the plugin, or a socket path. +- **If no plugin is running, the reader starts one** and waits for it: the `camera_plugin` + next to the program, or on `PATH`, or the one named in `PluginLocation`. The plugin started + this way belongs to nobody, serves any other reader that comes along, and exits by itself + once no reader has been connected for a while (30 seconds unless told otherwise). When + several readers start one at the same moment, one plugin gets the endpoint and serves them + all. Set `start_if_absent` to false to be told instead; a plugin behind an explicit socket + path is never started. - **One reader reads one group.** For two groups, open two readers; `descriptor()` lets an application wait on several at once. - A `FrameSet` may be given back from another thread than the one that calls `next`, and diff --git a/src/core/camera_reader/cpp/CMakeLists.txt b/src/core/camera_reader/cpp/CMakeLists.txt index c2ad541a18..4bfdb7d887 100644 --- a/src/core/camera_reader/cpp/CMakeLists.txt +++ b/src/core/camera_reader/cpp/CMakeLists.txt @@ -6,6 +6,8 @@ cmake_minimum_required(VERSION 3.20) # What an application links to read cameras from the camera plugin. add_library(camera_reader STATIC camera_reader.cpp + plugin_launcher.cpp + plugin_launcher.hpp ) target_include_directories(camera_reader INTERFACE diff --git a/src/core/camera_reader/cpp/camera_reader.cpp b/src/core/camera_reader/cpp/camera_reader.cpp index fc904c0bca..a955bbfd12 100644 --- a/src/core/camera_reader/cpp/camera_reader.cpp +++ b/src/core/camera_reader/cpp/camera_reader.cpp @@ -3,6 +3,8 @@ #include "inc/camera_reader/camera_reader.hpp" +#include "plugin_launcher.hpp" + #include #include #include @@ -14,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -55,30 +58,8 @@ std::optional receive(MessageSocket& socket, std::span buff } } -MessageSocket connect_to(const PluginLocation& plugin) -{ - if (!plugin.endpoint.empty() && !plugin.instance.empty()) - { - throw CameraReaderError("a camera plugin is named by its endpoint or by its instance, not both"); - } - std::string endpoint = plugin.endpoint; - try - { - if (endpoint.empty()) - { - endpoint = default_endpoint_path(plugin.instance); - } - return MessageSocket::connect(endpoint); - } - catch (const std::system_error& error) - { - throw CameraReaderError("no camera plugin answers on '" + endpoint + "': " + error.code().message()); - } - catch (const std::invalid_argument& error) - { - throw CameraReaderError(error.what()); - } -} +// How long a plugin that this reader started gets until it answers. +constexpr std::chrono::seconds START_TIMEOUT(20); // Says hello and returns what the plugin publishes. std::vector greet(MessageSocket& socket, WireEncoder& encoder, std::span buffer) @@ -110,6 +91,114 @@ std::vector greet(MessageSocket& socket, WireEncoder& encoder, } } +// A connection that got through the handshake. +struct Greeted +{ + MessageSocket socket; + std::vector groups; +}; + +// Whether the plugin behind `alive` is gone, waiting up to `wait` to find out. +bool plugin_is_gone(const UniqueFd& alive, std::chrono::milliseconds wait) +{ + pollfd entry = { alive.get(), POLLIN, 0 }; + return ::poll(&entry, 1, static_cast(wait.count())) > 0; +} + +// Starts a plugin for `endpoint` and connects to it once it serves. +Greeted start_and_connect(const PluginLocation& plugin, + const std::string& endpoint, + WireEncoder& encoder, + std::span buffer) +{ + const std::string nobody = "no camera plugin answers on '" + endpoint + "'"; + const std::string executable = find_plugin_executable(plugin.executable); + if (executable.empty()) + { + throw CameraReaderError( + nobody + ", and there is no camera_plugin to start" + + (plugin.executable.empty() ? " next to this program or on PATH" : " at '" + plugin.executable + "'")); + } + std::vector arguments = { "--exit-when-idle=" + std::to_string(plugin.exit_when_idle_seconds) }; + if (!plugin.instance.empty()) + { + arguments.push_back("--instance=" + plugin.instance); + } + UniqueFd alive; + try + { + alive = launch_plugin(executable, arguments); + } + catch (const std::system_error& error) + { + throw CameraReaderError(nobody + ", and '" + executable + "' could not be started: " + error.code().message()); + } + + // Another reader may have started a plugin at the same moment. Only one of the two plugins + // gets the endpoint, so this one being gone does not mean nobody serves: keep trying. + const auto deadline = std::chrono::steady_clock::now() + START_TIMEOUT; + std::string last_failure = "it did not start serving"; + bool gone = false; + while (std::chrono::steady_clock::now() < deadline) + { + try + { + MessageSocket socket = MessageSocket::connect(endpoint); + std::vector groups = greet(socket, encoder, buffer); + return { std::move(socket), std::move(groups) }; + } + catch (const CameraReaderError& error) + { + last_failure = error.what(); + } + catch (const std::system_error&) + { + if (gone) + { + break; // the plugin ended and still nobody listens + } + } + gone = gone || plugin_is_gone(alive, std::chrono::milliseconds(20)); + if (gone) + { + last_failure = "it stopped before it served; its log says why"; + } + } + throw CameraReaderError(nobody + ". '" + executable + "' was started for it, but " + last_failure); +} + +// Connects to the plugin, starting one first when that is wanted and needed, and says hello. +Greeted connect_to(const PluginLocation& plugin, WireEncoder& encoder, std::span buffer) +{ + if (!plugin.endpoint.empty() && !plugin.instance.empty()) + { + throw CameraReaderError("a camera plugin is named by its endpoint or by its instance, not both"); + } + std::string endpoint = plugin.endpoint; + try + { + if (endpoint.empty()) + { + endpoint = default_endpoint_path(plugin.instance); + } + MessageSocket socket = MessageSocket::connect(endpoint); + std::vector groups = greet(socket, encoder, buffer); + return { std::move(socket), std::move(groups) }; + } + catch (const std::system_error& error) + { + if (plugin.endpoint.empty() && plugin.start_if_absent) + { + return start_and_connect(plugin, endpoint, encoder, buffer); + } + throw CameraReaderError("no camera plugin answers on '" + endpoint + "': " + error.code().message()); + } + catch (const std::invalid_argument& error) + { + throw CameraReaderError(error.what()); + } +} + } // namespace namespace detail @@ -262,17 +351,16 @@ void FrameSet::release() noexcept std::vector CameraReader::list(const PluginLocation& plugin) { - MessageSocket socket = connect_to(plugin); WireEncoder encoder; std::vector buffer(MAX_WIRE_MESSAGE_BYTES); - return greet(socket, encoder, buffer); + return connect_to(plugin, encoder, buffer).groups; } CameraReader CameraReader::open(const std::string& group, const ReaderOptions& options, const PluginLocation& plugin) { - auto state = std::make_shared(connect_to(plugin)); WireEncoder encoder; - greet(state->socket, encoder, state->buffer); + std::vector handshake_buffer(MAX_WIRE_MESSAGE_BYTES); + auto state = std::make_shared(connect_to(plugin, encoder, handshake_buffer).socket); if (state->socket.send(encoder.encode(SubscribeMessage{ group, options })) != SendStatus::SENT) { diff --git a/src/core/camera_reader/cpp/inc/camera_reader/camera_reader.hpp b/src/core/camera_reader/cpp/inc/camera_reader/camera_reader.hpp index d05ef16de4..c874f0a08d 100644 --- a/src/core/camera_reader/cpp/inc/camera_reader/camera_reader.hpp +++ b/src/core/camera_reader/cpp/inc/camera_reader/camera_reader.hpp @@ -42,11 +42,23 @@ class CameraDisconnected : public CameraReaderError using CameraReaderError::CameraReaderError; }; -// Which camera plugin to read from. Left empty, it is this user's plugin on this machine. +// Which camera plugin to read from. Left as it is, it is this user's plugin on this machine, +// started if it is not running. struct PluginLocation { std::string endpoint; // a socket path; empty for the default endpoint of `instance` std::string instance; // a named plugin instance; empty for the default one + + // When no plugin answers on a default endpoint, start one and wait for it. A plugin behind + // an explicit `endpoint` is somebody else's to start. + bool start_if_absent = true; + + // The camera_plugin to start; empty for the one next to this program, or on PATH. + std::string executable; + + // A plugin started this way exits once no reader has been connected for this long; + // 0 keeps it running. + std::uint32_t exit_when_idle_seconds = 30; }; /** @@ -141,14 +153,15 @@ class CameraReader public: /** * @brief What a camera plugin publishes. - * @throws CameraReaderError if no plugin answers or the plugin refuses this reader. + * @throws CameraReaderError if no plugin answers and none could be started, or the plugin + * refuses this reader. */ static std::vector list(const PluginLocation& plugin = {}); /** * @brief Subscribe to one group. A reader for a second group is a second CameraReader. - * @throws CameraReaderError if no plugin answers or the plugin refuses the subscription; - * the message says why. + * @throws CameraReaderError if no plugin answers and none could be started, or the plugin + * refuses the subscription; the message says why. */ static CameraReader open(const std::string& group, const ReaderOptions& options = {}, diff --git a/src/core/camera_reader/cpp/plugin_launcher.cpp b/src/core/camera_reader/cpp/plugin_launcher.cpp new file mode 100644 index 0000000000..0d9de9e85f --- /dev/null +++ b/src/core/camera_reader/cpp/plugin_launcher.cpp @@ -0,0 +1,130 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "plugin_launcher.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::camera +{ + +namespace +{ + +constexpr const char* PLUGIN_EXECUTABLE = "camera_plugin"; + +bool can_run(const std::filesystem::path& path) +{ + std::error_code ignored; + return std::filesystem::is_regular_file(path, ignored) && ::access(path.c_str(), X_OK) == 0; +} + +// Closes every descriptor from `first` up except `keep`. Runs between fork and exec, so it +// uses nothing but system calls. +void close_others(int first, int keep, long limit) +{ +#ifdef SYS_close_range + if (::syscall(SYS_close_range, static_cast(first), static_cast(keep - 1), 0U) == 0 && + ::syscall(SYS_close_range, static_cast(keep + 1), ~0U, 0U) == 0) + { + return; + } +#endif + for (int fd = first; fd < limit; ++fd) + { + if (fd != keep) + { + ::close(fd); + } + } +} + +} // namespace + +std::string find_plugin_executable(const std::string& preferred) +{ + if (!preferred.empty()) + { + return can_run(preferred) ? preferred : std::string(); + } + std::error_code ignored; + const std::filesystem::path self = std::filesystem::read_symlink("/proc/self/exe", ignored); + if (!self.empty() && can_run(self.parent_path() / PLUGIN_EXECUTABLE)) + { + return (self.parent_path() / PLUGIN_EXECUTABLE).string(); + } + const char* search = std::getenv("PATH"); + std::istringstream directories(search != nullptr ? search : ""); + for (std::string directory; std::getline(directories, directory, ':');) + { + if (!directory.empty() && can_run(std::filesystem::path(directory) / PLUGIN_EXECUTABLE)) + { + return (std::filesystem::path(directory) / PLUGIN_EXECUTABLE).string(); + } + } + return {}; +} + +UniqueFd launch_plugin(const std::string& executable, const std::vector& arguments) +{ + // Everything the new process needs is prepared here: after fork() it may only make system + // calls, because other threads of this process may hold locks at that moment. + std::vector owned = { executable }; + owned.insert(owned.end(), arguments.begin(), arguments.end()); + std::vector argv; + for (std::string& argument : owned) + { + argv.push_back(argument.data()); + } + argv.push_back(nullptr); + const long descriptor_limit = ::sysconf(_SC_OPEN_MAX); + + // The plugin holds the write end for as long as it lives; nothing is ever written. + int alive[2] = { -1, -1 }; + if (::pipe2(alive, O_CLOEXEC) != 0) + { + throw std::system_error(errno, std::generic_category(), "creating a pipe to the camera plugin"); + } + UniqueFd reading(alive[0]); + UniqueFd writing(alive[1]); + + const pid_t child = ::fork(); + if (child < 0) + { + throw std::system_error(errno, std::generic_category(), "starting the camera plugin"); + } + if (child == 0) + { + // A session of its own, and a parent that exits at once: the plugin is then adopted by + // the system, which collects it when it ends. + ::setsid(); + if (::fork() != 0) + { + ::_exit(0); + } + const int null = ::open("/dev/null", O_RDWR); + ::dup2(null, STDIN_FILENO); + ::dup2(null, STDOUT_FILENO); + ::dup2(null, STDERR_FILENO); + ::fcntl(writing.get(), F_SETFD, 0); // stays open across exec + close_others(STDERR_FILENO + 1, writing.get(), descriptor_limit); + ::execv(argv[0], argv.data()); + ::_exit(127); + } + int status = 0; + while (::waitpid(child, &status, 0) < 0 && errno == EINTR) + { + } + return reading; +} + +} // namespace core::camera diff --git a/src/core/camera_reader/cpp/plugin_launcher.hpp b/src/core/camera_reader/cpp/plugin_launcher.hpp new file mode 100644 index 0000000000..237efd1048 --- /dev/null +++ b/src/core/camera_reader/cpp/plugin_launcher.hpp @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +#include +#include + +namespace core::camera +{ + +/** + * @brief The camera_plugin executable a reader starts: `preferred` when given, else the one + * next to this program, else the first on PATH. + * @return Its path, or nothing when there is none to run. + */ +std::string find_plugin_executable(const std::string& preferred); + +/** + * @brief Start a camera plugin as a process that belongs to nobody: it outlives this process + * and leaves no zombie behind when it exits. + * @return A descriptor that reads end-of-file once that plugin is gone. + * @throws std::system_error if no process could be started. + */ +UniqueFd launch_plugin(const std::string& executable, const std::vector& arguments); + +} // namespace core::camera diff --git a/src/plugins/camera/CMakeLists.txt b/src/plugins/camera/CMakeLists.txt index ffbd4ebe0d..285f24c9ba 100644 --- a/src/plugins/camera/CMakeLists.txt +++ b/src/plugins/camera/CMakeLists.txt @@ -7,6 +7,10 @@ if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") return() endif() +# app/ copies the manifest next to the executable, which makes that directory one the plugin +# manager can start the plugin from. +set(CAMERA_PLUGIN_MANIFEST "${CMAKE_CURRENT_SOURCE_DIR}/plugin.yaml") + add_subdirectory(core) add_subdirectory(backends) add_subdirectory(app) diff --git a/src/plugins/camera/README.md b/src/plugins/camera/README.md index 798b617f49..3a2593fc5a 100644 --- a/src/plugins/camera/README.md +++ b/src/plugins/camera/README.md @@ -53,6 +53,12 @@ holds the newest frame set, one slot for the camera to write ahead, and the wind readers; a reader that does not fit is refused with the numbers. A reader that wants every frame in order counts its window twice, because the frames waiting for it are kept as well. +**Who starts it.** Any of: by hand or from a service, as above; the plugin manager, like +every other plugin (`plugin.yaml` sits next to the executable); or a reader, when it finds no +plugin on a default endpoint. A reader passes `--exit-when-idle=SECONDS`, so a plugin it +started exits by itself once no reader has been connected for that long. A plugin started any +other way runs until it is told to stop. + A misspelt argument, option or setting is an error, not something ignored. `SIGINT` and `SIGTERM` stop the plugin cleanly; readers see their connection close. `--list-backends` prints the backends of the build. diff --git a/src/plugins/camera/app/CMakeLists.txt b/src/plugins/camera/app/CMakeLists.txt index c46ec1d5e6..85fc67803f 100644 --- a/src/plugins/camera/app/CMakeLists.txt +++ b/src/plugins/camera/app/CMakeLists.txt @@ -15,4 +15,8 @@ target_link_libraries(camera_plugin PRIVATE Threads::Threads ) +add_custom_command(TARGET camera_plugin POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CAMERA_PLUGIN_MANIFEST}" "$/plugin.yaml" + COMMENT "Putting the camera plugin's manifest next to its executable") + install(TARGETS camera_plugin RUNTIME DESTINATION plugins/camera) diff --git a/src/plugins/camera/app/main.cpp b/src/plugins/camera/app/main.cpp index 3eec4de0fb..0071db29f1 100644 --- a/src/plugins/camera/app/main.cpp +++ b/src/plugins/camera/app/main.cpp @@ -29,7 +29,7 @@ namespace constexpr std::string_view USAGE = "Usage: camera_plugin [--config=FILE | --camera=ID:BACKEND[:KEY=VALUE,...] ... | --auto]\n" - " [--endpoint=PATH | --instance=NAME] [--slots=N]\n" + " [--endpoint=PATH | --instance=NAME] [--slots=N] [--exit-when-idle=SECONDS]\n" " camera_plugin --list-backends\n" "\n" "Owns cameras and serves their frames to readers in other processes. Without arguments it\n" @@ -43,10 +43,13 @@ constexpr std::string_view USAGE = " --instance=NAME run as a named instance beside the default one, on its own endpoint\n" " --endpoint=PATH the socket file readers connect to, instead of a default endpoint\n" " --slots=N frames kept per stream (default 8); a reader with a larger window needs more\n" + " --exit-when-idle=SECONDS\n" + " exit once no reader has been connected for this long; a reader that starts\n" + " the plugin itself passes this, so the plugin does not outstay its use\n" " --list-backends print the backends this build has and exit\n"; // How often the plugin logs what each camera did. -constexpr time_t ACTIVITY_LOG_SECONDS = 10; +constexpr std::uint32_t ACTIVITY_LOG_SECONDS = 10; // The value of `--name=value` in `arg`, or nothing when `arg` is another flag. std::optional flag_value(std::string_view arg, std::string_view name) @@ -58,6 +61,17 @@ std::optional flag_value(std::string_view arg, std::string_vie return std::nullopt; } +std::uint32_t number_of(std::string_view flag, std::string_view text) +{ + std::uint32_t value = 0; + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value); + if (error != std::errc() || end != text.data() + text.size()) + { + throw std::invalid_argument(std::string(flag) + " takes a whole number, not '" + std::string(text) + "'"); + } + return value; +} + struct Arguments { std::string endpoint; @@ -65,6 +79,7 @@ struct Arguments std::string config_file; std::vector cameras; std::optional slots; + std::uint32_t exit_when_idle_seconds = 0; // 0: run until told to stop bool automatic = false; bool list_backends = false; bool help = false; @@ -106,13 +121,11 @@ Arguments parse(int argc, char** argv) } else if (const auto slots = flag_value(arg, "--slots")) { - std::uint32_t count = 0; - const auto [end, error] = std::from_chars(slots->data(), slots->data() + slots->size(), count); - if (error != std::errc() || end != slots->data() + slots->size()) - { - throw std::invalid_argument("--slots takes a whole number, not '" + std::string(*slots) + "'"); - } - arguments.slots = count; + arguments.slots = number_of("--slots", *slots); + } + else if (const auto idle = flag_value(arg, "--exit-when-idle")) + { + arguments.exit_when_idle_seconds = number_of("--exit-when-idle", *idle); } else if (flag_value(arg, "--plugin-root-id")) { @@ -225,17 +238,35 @@ int main(int argc, char** argv) host.start(); logger->info("camera plugin serves {} camera(s) on '{}'", host.camera_count(), endpoint); - // Sleeps until a signal says stop, waking now and then to log what the cameras did. - const timespec activity_interval = { ACTIVITY_LOG_SECONDS, 0 }; - int received = 0; - while ((received = sigtimedwait(&stop_signals, nullptr, &activity_interval)) <= 0) + // Sleeps until a signal says stop, waking once a second to keep count: of the time + // since the cameras' activity was logged, and of the time without a reader. + const timespec second = { 1, 0 }; + std::uint32_t since_activity_log = 0; + std::uint32_t idle_seconds = 0; + for (;;) { - if (errno == EAGAIN) + const int received = sigtimedwait(&stop_signals, nullptr, &second); + if (received > 0) + { + logger->info("camera plugin stops on signal {}", received); + break; + } + if (errno != EAGAIN) + { + continue; // interrupted; not a second gone by + } + if (++since_activity_log >= ACTIVITY_LOG_SECONDS) { host.log_activity(); + since_activity_log = 0; + } + idle_seconds = host.reader_count() == 0 ? idle_seconds + 1 : 0; + if (arguments.exit_when_idle_seconds != 0 && idle_seconds >= arguments.exit_when_idle_seconds) + { + logger->info("camera plugin stops: no reader for {} second(s)", idle_seconds); + break; } } - logger->info("camera plugin stops on signal {}", received); host.stop(); return 0; } diff --git a/tests/cpp/plugins/camera/CMakeLists.txt b/tests/cpp/plugins/camera/CMakeLists.txt index b737591533..e86521a60f 100644 --- a/tests/cpp/plugins/camera/CMakeLists.txt +++ b/tests/cpp/plugins/camera/CMakeLists.txt @@ -17,6 +17,7 @@ target_link_libraries(camera_plugin_tests PRIVATE camera::plugin_backends camera::backend_synthetic camera::camera_reader + teleop_plugin_manager Catch2::Catch2WithMain Threads::Threads ) @@ -24,6 +25,7 @@ target_link_libraries(camera_plugin_tests PRIVATE # Some cases start the plugin or the bench as a process of its own. target_compile_definitions(camera_plugin_tests PRIVATE CAMERA_PLUGIN_EXECUTABLE="$" + CAMERA_PLUGIN_DIRECTORY="$" CAMERA_BENCH_EXECUTABLE="$" ) add_dependencies(camera_plugin_tests camera_plugin camera_bench) diff --git a/tests/cpp/plugins/camera/test_camera_plugin.cpp b/tests/cpp/plugins/camera/test_camera_plugin.cpp index 0b138ea150..4294be0eaf 100644 --- a/tests/cpp/plugins/camera/test_camera_plugin.cpp +++ b/tests/cpp/plugins/camera/test_camera_plugin.cpp @@ -8,9 +8,11 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -18,6 +20,8 @@ #include #include #include +#include +#include #include #include #include @@ -149,11 +153,20 @@ class PluginProcess } } - // Waits for the process to end and returns its exit code, or -1 if it did not exit by itself. - int wait() + // Waits for the process to end and returns its exit code: -1 if a signal ended it, -2 if it + // was still running after `timeout`. + int wait(std::chrono::seconds timeout = 30s) { + const auto deadline = std::chrono::steady_clock::now() + timeout; int status = 0; - REQUIRE(::waitpid(m_pid, &status, 0) == m_pid); + while (::waitpid(m_pid, &status, WNOHANG) == 0) + { + if (std::chrono::steady_clock::now() > deadline) + { + return -2; + } + std::this_thread::sleep_for(10ms); + } m_pid = -1; return WIFEXITED(status) ? WEXITSTATUS(status) : -1; } @@ -188,6 +201,43 @@ std::optional open_when_ready(const core::camera::PluginLocation& return std::nullopt; } +bool wait_until(const std::function& condition, std::chrono::seconds timeout = 20s) +{ + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (!condition()) + { + if (std::chrono::steady_clock::now() > deadline) + { + return false; + } + std::this_thread::sleep_for(10ms); + } + return true; +} + +// A user's runtime and configuration directories for one test and the plugins it starts, with +// one small synthetic camera named 'head' in the configuration file. +struct UserDirectories +{ + TemporaryDirectory directory; + std::filesystem::path config_file = directory.path() / "config" / "isaaccapture" / "cameras.yaml"; + std::filesystem::path default_socket = directory.path() / "run" / "isaaccapture" / "camera.sock"; + ScopedEnvironment runtime{ "XDG_RUNTIME_DIR", (directory.path() / "run").string() }; + ScopedEnvironment config_home{ "XDG_CONFIG_HOME", (directory.path() / "config").string() }; + + UserDirectories() + { + std::filesystem::create_directories(config_file.parent_path()); + std::filesystem::create_directories(directory.path() / "run"); + std::ofstream(config_file) << "cameras:\n" + " head:\n" + " backend: synthetic\n" + " width: 160\n" + " height: 120\n" + " fps: 120\n"; + } +}; + // Reads whatever is still on its way; ends by throwing when the plugin's side has closed. void read_until_closed(CameraReader& reader) { @@ -372,6 +422,102 @@ TEST_CASE("a plugin without arguments serves its configuration file where reader REQUIRE(PluginProcess({ "--instance=fifth", "--config=" + (directory.path() / "missing.yaml").string() }).wait() == 1); } +TEST_CASE("a plugin told to exit when idle leaves once its readers have", "[unit][camera_plugin][process]") +{ + TemporaryDirectory directory; + const std::string endpoint = directory.socket_path(); + PluginProcess plugin({ "--endpoint=" + endpoint, "--camera=head:synthetic:width=64,height=48", "--exit-when-idle=2" }); + { + std::optional reader = open_when_ready({ .endpoint = endpoint }, "head"); + REQUIRE(reader.has_value()); + // With a reader connected it stays, for longer than its idle time. + const auto until = std::chrono::steady_clock::now() + 3s; + while (std::chrono::steady_clock::now() < until) + { + REQUIRE(reader->next(2s).has_value()); + } + } + REQUIRE(plugin.wait() == 0); + REQUIRE_FALSE(std::filesystem::exists(endpoint)); +} + +TEST_CASE("a reader starts the plugin when none is running", "[unit][camera_plugin][process]") +{ + const UserDirectories user; + const core::camera::PluginLocation location{ .executable = CAMERA_PLUGIN_EXECUTABLE, .exit_when_idle_seconds = 2 }; + + // Two readers at the same moment each start a plugin. One plugin gets the endpoint and + // serves both readers; the other finds the endpoint taken and leaves. + std::array, 2> readers; + std::array errors; + std::vector threads; + for (std::size_t i = 0; i < readers.size(); ++i) + { + threads.emplace_back( + [&, i] + { + try + { + readers[i] = CameraReader::open("head", {}, location); + } + catch (const std::exception& error) + { + errors[i] = error.what(); + } + }); + } + for (std::thread& thread : threads) + { + thread.join(); + } + for (std::size_t i = 0; i < readers.size(); ++i) + { + REQUIRE(errors[i].empty()); + REQUIRE(readers[i].has_value()); + const std::optional frames = readers[i]->next(2s); + REQUIRE(frames.has_value()); + require_synthetic(frames->image(0), 0); + } + REQUIRE(std::filesystem::is_socket(user.default_socket)); + + // The plugin does not outstay its readers. + readers[0].reset(); + readers[1].reset(); + REQUIRE(wait_until([&] { return !std::filesystem::exists(user.default_socket); })); + + // Starting is the default but not forced, and only a plugin that exists can be started. + REQUIRE_THROWS_WITH( + CameraReader::open("head", {}, { .start_if_absent = false }), ContainsSubstring("no camera plugin answers on")); + REQUIRE_THROWS_WITH(CameraReader::open("head", {}, { .executable = "/nonexistent/camera_plugin" }), + ContainsSubstring("there is no camera_plugin to start at '/nonexistent/camera_plugin'")); + REQUIRE_FALSE(std::filesystem::exists(user.default_socket)); + + // A plugin that starts and has no camera to serve is reported, not waited for. + std::filesystem::remove(user.config_file); + REQUIRE_THROWS_WITH(CameraReader::open("head", {}, location), ContainsSubstring("it stopped before it served")); +} + +TEST_CASE("the plugin manager can start the camera plugin", "[unit][camera_plugin][process]") +{ + TemporaryDirectory directory; + const std::string endpoint = directory.socket_path(); + + // A plugin directory is a manifest next to its executable; the build tree has one. + core::PluginManager manager({ std::filesystem::path(CAMERA_PLUGIN_DIRECTORY).parent_path().string() }); + const std::vector names = manager.get_plugin_names(); + REQUIRE(std::find(names.begin(), names.end(), "camera") != names.end()); + { + const std::unique_ptr plugin = manager.start( + "camera", "camera_test", { "--endpoint=" + endpoint, "--camera=head:synthetic:width=64,height=48" }); + std::optional reader = open_when_ready({ .endpoint = endpoint }, "head"); + REQUIRE(reader.has_value()); + REQUIRE(reader->next(2s).has_value()); + REQUIRE_NOTHROW(plugin->check_health()); + } + // The handle going away stops the plugin, which removes its socket file on the way out. + REQUIRE_FALSE(std::filesystem::exists(endpoint)); +} + TEST_CASE("the plugin refuses arguments it cannot use", "[unit][camera_plugin][process]") { TemporaryDirectory directory;