MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
test_domainwatcher.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2025 Contributors to the Media eXchange Layer project.
2// SPDX-License-Identifier: Apache-2.0
3
4#include <condition_variable>
5#include <cstdio>
6#include <cstdlib>
7#include <algorithm>
8#include <filesystem>
9#include <fstream>
10#include <list>
11#include <random>
12#include <string>
13#include <system_error>
14#include <thread>
15#include <fcntl.h>
16#include <unistd.h>
17#include <uuid.h>
18#include <sys/mman.h>
19#include <sys/stat.h>
20#include <catch2/catch_test_macros.hpp>
23#include "mxl-internal/Flow.hpp"
25#include "mxl/flowinfo.h"
26#include "../../tests/Utils.hpp"
27
28using namespace mxl::lib;
29namespace fs = std::filesystem;
30
31namespace
32{}
33
35{
36 MockFlowFiles(fs::path domain, uuids::uuid const& id)
37 : _domain{std::move(domain)}
38 , _id{id}
39 , _accessFileFd{-1}
40 {
41 auto flowDir = makeFlowDirectoryName(_domain, uuids::to_string(_id));
42 std::filesystem::create_directories(flowDir);
43 auto accessFilePath = makeFlowAccessFilePath(flowDir);
44 auto dataFilePath = makeFlowDataFilePath(flowDir);
45
46 _accessFileFd = ::open(accessFilePath.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0644);
47 if (_accessFileFd < 0)
48 {
49 auto const error = errno;
50 throw std::system_error{error, std::system_category(), "Failed to open access file"};
51 }
52
53 _dataFileFd = ::open(dataFilePath.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0644);
54
55 if (::ftruncate(_accessFileFd, sizeof(Grain)) < 0)
56 {
57 auto const error = errno;
58 throw std::system_error{error, std::system_category(), "Failed truncate access file"};
59 }
60
61 if (::ftruncate(_dataFileFd, sizeof(Flow)) < 0)
62 {
63 auto const error = errno;
64 throw std::system_error{error, std::system_category(), "Failed truncate access file"};
65 }
66 }
67
69 {
70 if (_accessFileFd > -1)
71 {
72 (void)::close(_accessFileFd);
73 }
74 if (_dataFileFd > -1)
75 {
76 (void)::close(_dataFileFd);
77 }
78
79 auto flowDir = makeFlowDirectoryName(_domain, uuids::to_string(_id));
80 fs::remove(makeFlowAccessFilePath(flowDir));
81 fs::remove(makeFlowDataFilePath(flowDir));
82 }
83
84 void touch()
85 {
86 auto times = std::array<::timespec, 2>{
87 timespec{.tv_sec = 0, .tv_nsec = UTIME_NOW },
88 timespec{.tv_sec = 0, .tv_nsec = UTIME_OMIT}
89 };
90 if (auto ret = ::futimens(_accessFileFd, times.data()); ret < 0)
91 {
92 auto const error = errno;
93 throw std::system_error(error, std::system_category(), "Failed to update flow access time");
94 }
95 }
96
97 fs::path _domain;
98 uuids::uuid _id;
101};
102
104{
105 MockWriter(std::filesystem::path const& domain, uuids::uuid id, DomainWatcher::ptr const& watcher)
106 : mxl::lib::DiscreteFlowWriter{id, domain}
107 , _info{}
108 , _id{id}
109 , _watcher{watcher}
110 {
111 _watcher->addFlow(this, _id);
112 _flowDataFd = ::open(makeFlowDataFilePath(domain, uuids::to_string(id)).c_str(), O_RDONLY | O_CLOEXEC, 0);
113 if (_flowDataFd < 0)
114 {
115 auto const error = errno;
116 throw std::system_error{error, std::system_category(), "Failed to open grain data file"};
117 }
118
119 _flowData = reinterpret_cast<Flow*>(::mmap(nullptr, sizeof(Flow), PROT_READ, MAP_SHARED, _flowDataFd, 0));
120 if (_flowData == MAP_FAILED)
121 {
122 auto const error = errno;
123 throw std::system_error{error, std::system_category(), "Failed to map grain data file"};
124 }
125 }
126
127 virtual ~MockWriter() override
128 {
129 _watcher->removeFlow(this, _id);
130 if ((_flowData != nullptr) && (_flowData != MAP_FAILED))
131 {
132 (void)::munmap(_flowData, sizeof(Flow));
133 }
134
135 if (_flowDataFd > -1)
136 {
137 (void)::close(_flowDataFd);
138 }
139 }
140
141 [[noreturn]]
142 virtual FlowData& getFlowData() override
143 {
144 // Implementation is not provided
145 std::terminate();
146 }
147
148 [[noreturn]]
149 virtual FlowData const& getFlowData() const override
150 {
151 // Implementation is not provided
152 std::terminate();
153 }
154
155 virtual ::mxlFlowInfo getFlowInfo() const override
156 {
157 return _info;
158 }
159
160 virtual ::mxlFlowConfigInfo getFlowConfigInfo() const override
161 {
162 return _info.config;
163 }
164
165 virtual ::mxlFlowRuntimeInfo getFlowRuntimeInfo() const override
166 {
167 return _info.runtime;
168 }
169
170 virtual bool isExclusive() const override
171 {
172 return false;
173 }
174
175 virtual bool makeExclusive() override
176 {
177 return false;
178 }
179
183 [[noreturn]]
184 virtual mxlGrainInfo getGrainInfo(std::uint64_t) const override
185 {
186 // Implementation is not provided
187 std::terminate();
188 };
189
190 virtual mxlStatus openGrain(std::uint64_t, mxlGrainInfo*, std::uint8_t**) override
191 {
192 return MXL_STATUS_OK;
193 }
194
195 virtual mxlStatus commit(mxlGrainInfo const&) override
196 {
197 return MXL_STATUS_OK;
198 }
199
200 virtual mxlStatus cancel() override
201 {
202 return MXL_STATUS_OK;
203 }
204
206 {
207 auto before = _lastReadTime;
208 _lastReadTime = _flowData->info.runtime.lastReadTime;
209 return before != _lastReadTime;
210 }
211
213 uuids::uuid _id;
214 DomainWatcher::ptr _watcher;
215
216 std::uint64_t _lastReadTime;
219};
220
221TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "Directory Watcher", "[directory watcher]")
222{
223 auto watcher = std::make_shared<DomainWatcher>(domain.native());
224
225 auto flowId1 = *uuids::uuid::from_string("5fbec3b1-1b0f-417d-9059-8b94a47197ed");
226 auto flowId2 = *uuids::uuid::from_string("6fbec3b1-1b0f-417d-9059-8b94a47197ed");
227
228 auto mockFiles = MockFlowFiles{domain, flowId1};
229 auto mockFiles2 = MockFlowFiles{domain, flowId2};
230
231 auto mockWriter1 = std::make_unique<MockWriter>(domain, flowId1, watcher);
232 auto mockWriter2 = std::make_unique<MockWriter>(domain, flowId1, watcher);
233 REQUIRE(watcher->count(flowId1) == 2);
234 REQUIRE(watcher->size() == 2);
235 auto mockWriter3 = std::make_unique<MockWriter>(domain, flowId2, watcher);
236 mockWriter1.reset();
237 REQUIRE(watcher->count(flowId1) == 1);
238 REQUIRE(watcher->count(flowId2) == 1);
239 REQUIRE(watcher->size() == 2);
240 mockWriter2.reset();
241 REQUIRE(watcher->count(flowId1) == 0);
242 REQUIRE(watcher->count(flowId2) == 1);
243 REQUIRE(watcher->size() == 1);
244 mockWriter3.reset();
245}
246
247TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "DomainWatcher triggers callback on file modifications", "[domainwatcher]")
248{
249 // This test checks that modifying a watched file triggers the callback with correct UUID and WatcherType.
250 auto watcher = std::make_shared<DomainWatcher>(domain);
251
252 // Create a flow directory and files, then add watchers for both Reader and Writer types
253 auto const flowId = *uuids::uuid::from_string("11111111-2222-3333-4444-555555555555"); // test UUID
254 auto mockFlow = MockFlowFiles{domain, flowId};
255
256 {
257 auto writer1 = MockWriter{domain, flowId, watcher};
258 auto writer2 = MockWriter{domain, flowId, watcher};
259
260 // Give the watcher thread a moment to register the inotify watch
261 std::this_thread::sleep_for(std::chrono::milliseconds(100));
262
263 // Modify the main data file and expect a Writer event
264 mockFlow.touch();
265 std::this_thread::sleep_for(std::chrono::milliseconds(100));
266
267 REQUIRE(writer1.checkReadTimeUpdated());
268 REQUIRE(writer2.checkReadTimeUpdated());
269 REQUIRE(!writer1.checkReadTimeUpdated());
270 REQUIRE(!writer2.checkReadTimeUpdated());
271
272 // Modify the main data file and expect a Writer event
273 mockFlow.touch();
274 std::this_thread::sleep_for(std::chrono::milliseconds(100));
275
276 REQUIRE(writer1.checkReadTimeUpdated());
277 REQUIRE(writer2.checkReadTimeUpdated());
278 }
279
280 REQUIRE(watcher->size() == 0);
281}
282
283TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "DomainWatcher thread start/stop behavior", "[domainwatcher]")
284{
285 // This test checks that modifying a watched file triggers the callback with correct UUID and WatcherType.
286 auto watcher = std::make_shared<DomainWatcher>(domain);
287
288 // Create a flow directory and files, then add watchers for both Reader and Writer types
289 auto const flowId = *uuids::uuid::from_string("11111111-2222-3333-4444-555555555555"); // test UUID
290 auto mockFlow = MockFlowFiles{domain, flowId};
291
292 {
293 auto mockWriter1 = MockWriter{domain, flowId, watcher};
294 auto mockWriter2 = MockWriter{domain, flowId, watcher};
295 REQUIRE(watcher->size() == 2);
296 REQUIRE(watcher->count(flowId) == 2);
297
298 std::this_thread::sleep_for(std::chrono::milliseconds(250));
299
300 mockFlow.touch();
301
302 std::this_thread::sleep_for(std::chrono::milliseconds(250));
303
304 REQUIRE(mockWriter1.checkReadTimeUpdated());
305 REQUIRE(mockWriter2.checkReadTimeUpdated());
306
307 watcher->stop();
308 std::this_thread::sleep_for(std::chrono::milliseconds(250));
309
310 mockFlow.touch();
311 std::this_thread::sleep_for(std::chrono::milliseconds(250));
312
313 REQUIRE(!mockWriter1.checkReadTimeUpdated());
314 REQUIRE(!mockWriter2.checkReadTimeUpdated());
315 }
316}
317
318TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "DomainWatcher error handling for invalid inputs", "[domainwatcher]")
319{
320 // Case 1: Using a valid domain path but adding a flow without creating the files
321 auto watcher = std::make_shared<DomainWatcher>(domain);
322
323 // Attempt to addFlow on a domain where the flow files don't exist (should throw because files are not present)
324 uuids::uuid dummyId = *uuids::uuid::from_string("01234567-89ab-cdef-0123-456789abcdef");
325 auto test = [&]()
326 {
327 auto mockWriter = MockWriter{domain, dummyId, watcher};
328 };
329
330 // The implementation throws std::system_error when inotify_add_watch fails
331 REQUIRE_THROWS_AS(test(), std::system_error);
332
333 // Removing a non-existant writer should not throw
334 REQUIRE_NOTHROW(watcher->removeFlow(nullptr, dummyId));
335 REQUIRE_NOTHROW(watcher->removeFlow(std::bit_cast<DiscreteFlowWriter*>(std::bit_cast<std::uintptr_t>(0x7f11251231231)), dummyId));
336}
337
338#ifdef __linux__ // This test uses /proc/self/fd which is Linux-specific
339TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "DomainWatcher cleans up file descriptors on destruction", "[domainwatcher]")
340{
341 // This test verifies that DomainWatcher closes its inotify/epoll descriptors upon destruction,
342 // so no file descriptor leaks occur.
343 // Helper: count open file descriptors (excluding the FD for /proc/self/fd itself)
344 auto countOpenFDs = []()
345 {
346 auto count = size_t{0};
347 for (auto& entry : std::filesystem::directory_iterator("/proc/self/fd"))
348 {
349 // Exclude the special entries "." and ".." if present
350 auto const name = entry.path().filename().string();
351 if (name == "." || name == "..")
352 {
353 continue;
354 }
355 count++;
356 }
357 return count;
358 };
359
360 auto const fdsBefore = countOpenFDs();
361 { // scope to ensure DomainWatcher destruction
362 auto watcher = std::make_shared<DomainWatcher>(domain);
363 // Add a watch to force inotify initialization if not already done in constructor
364 auto const flowId = *uuids::uuid::from_string("12345678-1234-5678-1234-567812345678");
365 auto flowFiles = MockFlowFiles{domain, flowId};
366 auto writer = MockWriter{domain, flowId, watcher};
367
368 auto const fdsWhileActive = countOpenFDs();
369 REQUIRE(fdsWhileActive > fdsBefore);
370 // (No need to trigger events here; we just want the watcher to open its fds)
371 } // DomainWatcher goes out of scope here, its destructor should close inotify/epoll fds
372 auto const fdsAfter = countOpenFDs();
373
374 // After destruction, the number of open fds should be back to the original count
375 // (The DomainWatcher should have closed the two fds it opened: inotify and epoll)
376 REQUIRE(fdsAfter == fdsBefore);
377}
378#endif // __linux__
379
380TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "DomainWatcher supports concurrent add/remove operations", "[domainwatcher]")
381{
382 // This test spawns multiple threads to add and remove flow watchers concurrently,
383 // to ensure thread safety (no crashes or race conditions and correct final state).
384 auto flowId = *uuids::uuid::from_string("12345678-1234-5678-1234-567812345678");
385 auto mockFiles = MockFlowFiles{domain, flowId};
386
387 std::random_device rd{};
388 std::mt19937 rng{rd()};
389
390 std::atomic<std::size_t> readyCount{0};
391 std::atomic<bool> startSignal{false};
392
393 constexpr auto iterations = 1024;
394 constexpr auto nWorkers = 8;
395 constexpr auto slots = 4;
396
397 struct Worker
398 {
399 std::vector<std::optional<MockWriter>> writers;
400 std::optional<std::thread> thread;
401 };
402
403 auto watcher = std::make_shared<DomainWatcher>(domain);
404 auto work = [&](Worker* w)
405 {
406 readyCount.fetch_add(1);
407 startSignal.wait(false);
408
409 auto dist = std::uniform_int_distribution{std::size_t{0}, w->writers.size() - 1};
410
411 for (std::size_t n = 0; n < iterations; ++n)
412 {
413 auto index = dist(rng);
414 auto& slot = w->writers.at(index);
415 if (slot)
416 {
417 slot.reset();
418 }
419 else
420 {
421 slot.emplace(domain, flowId, watcher);
422 }
423
424 if (index > (w->writers.size() / 2))
425 {
426 mockFiles.touch();
427 }
428 }
429 };
430
431 auto workers = std::list<Worker>{};
432 for (auto i = 0; i < nWorkers; ++i)
433 {
434 auto& w = workers.emplace_back(std::vector<std::optional<MockWriter>>{slots}, std::nullopt);
435 w.thread = std::thread{work, &w};
436 }
437
438 while (readyCount.load() != workers.size())
439 {
440 }
441
442 startSignal.store(true);
443 startSignal.notify_all();
444 // work work work...
445 std::ranges::for_each(workers,
446 [](Worker& w)
447 {
448 w.thread->join();
449 w.writers.clear();
450 });
451
452 REQUIRE(watcher->size() == 0);
453 REQUIRE(watcher->count(flowId) == 0);
454 {
455 auto mockWriter = MockWriter{domain, flowId, watcher};
456 REQUIRE(watcher->size() == 1);
457 REQUIRE(watcher->count(flowId) == 1);
458 }
459 REQUIRE(watcher->size() == 0);
460 REQUIRE(watcher->count(flowId) == 0);
461}
462
463TEST_CASE("DomainWatcher constructor throws on invalid domain path", "[domainwatcher]")
464{
465 // Ensure constructing on a non‐existent or non‐directory path throws
466 auto const homeDir = std::getenv("HOME");
467 REQUIRE(homeDir != nullptr);
468
469 // Case: path does not exist
470 auto bad1 = std::filesystem::path{homeDir} / "mxl_nonexistent_domain";
471 remove_all(bad1);
472 REQUIRE(!exists(bad1));
473 REQUIRE_THROWS_AS((mxl::lib::DomainWatcher{bad1}), std::filesystem::filesystem_error);
474
475 // Case: path exists but is a regular file
476 auto bad2 = std::filesystem::path{homeDir} / "mxl_not_a_dir";
477 remove_all(bad2);
478 {
479 auto touch = std::ofstream{bad2};
480 touch << "notadir";
481 }
482 REQUIRE(exists(bad2));
483 REQUIRE(is_regular_file(bad2));
484 REQUIRE_THROWS_AS((mxl::lib::DomainWatcher{bad2}), std::filesystem::filesystem_error);
485
486 // Clean up
487 remove_all(bad2);
488}
Internal shared-memory headers for discrete grains and event slots.
Paths and filenames utilities used by the MXL SDK.
struct mxlGrainInfo_t mxlGrainInfo
Public configuration and runtime metadata for MXL flows.
struct mxlFlowInfo_t mxlFlowInfo
mxlStatus
MXL SDK Status codes.
Definition mxl.h:22
@ MXL_STATUS_OK
Definition mxl.h:23
DomainWatcher(std::filesystem::path const &in_domain)
std::filesystem::path makeFlowAccessFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:29
std::filesystem::path makeFlowDataFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:17
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
std::filesystem::path makeFlowDirectoryName(std::filesystem::path const &domain, std::string const &uuid)
Definition PathUtils.cpp:11
MockFlowFiles(fs::path domain, uuids::uuid const &id)
virtual bool isExclusive() const override
virtual ~MockWriter() override
virtual FlowData const & getFlowData() const override
virtual::mxlFlowInfo getFlowInfo() const override
std::uint64_t _lastReadTime
virtual::mxlFlowRuntimeInfo getFlowRuntimeInfo() const override
virtual mxlStatus openGrain(std::uint64_t, mxlGrainInfo *, std::uint8_t **) override
virtual mxlStatus commit(mxlGrainInfo const &) override
virtual mxlGrainInfo getGrainInfo(std::uint64_t) const override
virtual::mxlFlowConfigInfo getFlowConfigInfo() const override
MockWriter(std::filesystem::path const &domain, uuids::uuid id, DomainWatcher::ptr const &watcher)
virtual bool makeExclusive() override
virtual mxlStatus cancel() override
DomainWatcher::ptr _watcher
virtual FlowData & getFlowData() override
TEST_CASE("DomainWatcher constructor throws on invalid domain path", "[domainwatcher]")
TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "Directory Watcher", "[directory watcher]")
constexpr auto w
mxlFlowWriter writer
auto const flowId
uint64_t index
REQUIRE(timeDelta< 33 '366 '667LL)