MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
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
5#include <cstdint>
6#include <cstring>
7#include <algorithm>
8#include <atomic>
9#include <filesystem>
10#include <memory>
11#include <mutex>
12#include <system_error>
13#include <thread>
14#include <utility>
15#include <fcntl.h>
16#include <unistd.h>
17#include <uuid.h>
18#include <mxl/platform.h>
23
24#ifdef __APPLE__
25# include <sys/event.h>
26#elif __linux__
27# include <sys/epoll.h>
28# include <sys/eventfd.h>
29# include <sys/inotify.h>
30#endif
31
32namespace mxl::lib
33{
34 namespace
35 {
41 void updateReadTime(mxlFlowInfo& info, std::uint64_t time) noexcept
42 {
43 std::atomic_ref{info.runtime.lastReadTime}.store(time, std::memory_order_release);
44 }
45
46#ifdef __APPLE__
47 constexpr auto VNODE_EVENTS = static_cast<unsigned int>(NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB);
48
49 using KEvent = struct kevent;
50#endif
51 }
52
53 DomainWatcher::DomainWatcher(std::filesystem::path const& in_domain)
54 : _domain{in_domain}
55 , _running{true}
56 {
57 // Validate that the domain path is a directory
58 if (!std::filesystem::is_directory(in_domain))
59 {
60 throw std::filesystem::filesystem_error("Domain path is not a directory", in_domain, std::make_error_code(std::errc::not_a_directory));
61 }
62#ifdef __APPLE__
63 /* Open a kernel queue. */
64 _kq = kqueue();
65 if (_kq < 0)
66 {
67 auto const error = errno;
68 throw std::system_error(error, std::generic_category(), "Failed to create a kqueue");
69 }
70
71#elif defined __linux__
72 _inotifyFd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
73 if (_inotifyFd == -1)
74 {
75 auto const error = errno;
76 MXL_ERROR("inotify_init1 failed: {}", std::strerror(error));
77 throw std::system_error(error, std::generic_category(), "inotify_init1 failed");
78 }
79
80 // Create epoll instance (close-on-exec), so child processes do not inherit it.
81 // This is necessary to avoid file descriptor leaks in child processes.
82 _epollFd = epoll_create1(EPOLL_CLOEXEC);
83 if (_epollFd == -1)
84 {
85 auto const error = errno;
86 MXL_ERROR("epoll_create1 failed (errno {}: {})", error, std::strerror(error));
87 // Clean up inotify FD before throwing
88 ::close(_inotifyFd);
89 throw std::system_error(error, std::generic_category(), "epoll_create1 failed");
90 }
91
92 // Add inotify file descriptor to epoll
93 epoll_event event{};
94 event.events = EPOLLIN;
95 event.data.fd = _inotifyFd;
96 if (epoll_ctl(_epollFd, EPOLL_CTL_ADD, _inotifyFd, &event) == -1)
97 {
98 auto const error = errno;
99 MXL_ERROR("epoll_ctl ADD(inotify) failed: {}", std::strerror(error));
100 ::close(_inotifyFd);
101 ::close(_epollFd);
102 throw std::system_error(error, std::generic_category(), "epoll_ctl ADD inotify failed");
103 }
104
105 _eventFd = ::eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
106 if (_eventFd < 0)
107 {
108 auto const error = errno;
109 ::close(_inotifyFd);
110 ::close(_epollFd);
111 throw std::system_error{error, std::generic_category(), "failed to create evenfd"};
112 }
113
114 auto efdEvent = ::epoll_event{};
115 efdEvent.events = EPOLLIN;
116 efdEvent.data.fd = _eventFd;
117 if (::epoll_ctl(_epollFd, EPOLL_CTL_ADD, _eventFd, &efdEvent) == -1)
118 {
119 auto const error = errno;
120 ::close(_inotifyFd);
121 ::close(_epollFd);
122 ::close(_eventFd);
123 throw std::system_error(error, std::generic_category(), "epoll_ctl ADD eventfd failed");
124 }
125#endif
126
127 // Start event processing thread
128 try
129 {
130 _watchThread = std::thread(&DomainWatcher::processEvents, this);
131 }
132 catch (std::exception const& e)
133 {
134 MXL_ERROR("Failed to start watcher thread: {}", e.what());
135#ifdef __APPLE__
136 ::close(_kq);
137#elif defined __linux__
138 ::close(_inotifyFd);
139 ::close(_epollFd);
140 ::close(_eventFd);
141#endif
142 throw;
143 }
144 catch (...)
145 {
146 MXL_ERROR("Failed to start watcher thread: unknown exception");
147#ifdef __APPLE__
148 ::close(_kq);
149#elif defined __linux__
150 ::close(_inotifyFd);
151 ::close(_epollFd);
152 ::close(_eventFd);
153#endif
154 throw;
155 }
156 }
157
158 DomainWatcher::~DomainWatcher()
159 {
160 stop();
161
162#ifdef __APPLE__
163 ::close(_kq);
164#elif defined __linux__
165 // Linux: remove all inotify watches and close FDs
166 for (auto const& [wd, rec] : _watches)
167 {
168 if (inotify_rm_watch(_inotifyFd, wd) == -1)
169 {
170 auto const error = errno;
171 MXL_ERROR("Error removing inotify watch (wd={}): {}", wd, std::strerror(error));
172 }
173 }
174 if (::close(_inotifyFd) == -1)
175 {
176 auto const error = errno;
177 MXL_ERROR("Error closing inotify FD: {}", std::strerror(error));
178 }
179 if (::close(_eventFd) == -1)
180 {
181 auto const error = errno;
182 MXL_ERROR("Error closing epoll FD: {}", std::strerror(error));
183 }
184 if (::close(_epollFd) == -1)
185 {
186 auto const error = errno;
187 MXL_ERROR("Error closing epoll FD: {}", std::strerror(error));
188 }
189#endif
190 }
191
192 std::size_t DomainWatcher::count(uuids::uuid id) const noexcept
193 {
194 auto lock = std::scoped_lock{_mutex};
195 auto it = std::ranges::find_if(_watches, [id](auto const& item) noexcept { return item.second.id == id; });
196 if (it == _watches.end())
197 {
198 return 0;
199 }
200
201 return _watches.count(it->first);
202 }
203
204 std::size_t DomainWatcher::size() const noexcept
205 {
206 auto lock = std::scoped_lock{_mutex};
207 return _watches.size();
208 }
209
210 void DomainWatcher::addFlow(FlowWriter* writer, uuids::uuid id)
211 {
212 auto record = DomainWatcherRecord{
213 .id = id,
214 .fileName = makeFlowAccessFilePath(makeFlowDirectoryName(_domain, uuids::to_string(id))),
215 .fw = writer,
216 .flowData = {},
217 };
218 {
219 auto lock = std::scoped_lock{_mutex};
220 auto existingWd = -1;
221
222 // Check if this flow is already being watched
223 for (auto const& [wd, rec] : _watches)
224 {
225 if (rec.id == record.id)
226 {
227 existingWd = wd;
228 record.flowData = rec.flowData;
229 break;
230 }
231 }
232
233 if (existingWd == -1)
234 {
235 MXL_DEBUG("Record for {} not found, creating one.", uuids::to_string(record.id));
236
237#ifdef __APPLE__
238 existingWd = ::open(record.fileName.c_str(), O_EVTONLY | O_CLOEXEC);
239 if (existingWd != -1)
240 {
241 auto change = KEvent{};
242 EV_SET(&change,
243 existingWd,
244 EVFILT_VNODE,
245 EV_ADD | EV_CLEAR,
246 VNODE_EVENTS,
247 0,
248 std::bit_cast<void*>(static_cast<std::uintptr_t>(existingWd)));
249 if (::kevent(_kq, &change, 1, nullptr, 0, nullptr) == -1)
250 {
251 auto const error = errno;
252 ::close(existingWd);
253 errno = error;
254 existingWd = -1;
255 }
256 }
257#elif defined __linux__
258 // if not found, add the watch and add it to the maps
259 existingWd = ::inotify_add_watch(_inotifyFd, record.fileName.c_str(), IN_ACCESS | IN_ATTRIB);
260#endif
261 if (existingWd == -1)
262 {
263 auto const error = errno;
264 MXL_ERROR("Failed to add watch for file '{}': {}", record.fileName, std::strerror(error));
265 throw std::system_error{error, std::generic_category(), "Failed to add watch for file: " + record.fileName};
266 }
267 else
268 {
269 MXL_DEBUG("Added watch {} for file: {}", existingWd, record.fileName);
270 }
271 }
272
273 record.flowData = std::make_shared<SharedMemoryInstance<Flow>>(
274 makeFlowDataFilePath(_domain, uuids::to_string(record.id)).c_str(), AccessMode::READ_WRITE, 0U, LockMode::None);
275 _watches.emplace(existingWd, std::move(record));
276 }
277 }
278
279 void DomainWatcher::removeFlow(FlowWriter* writer, uuids::uuid id)
280 {
281 auto record = DomainWatcherRecord{
282 .id = id,
283 .fileName = makeFlowAccessFilePath(makeFlowDirectoryName(_domain, uuids::to_string(id))),
284 .fw = writer,
285 .flowData = {},
286 };
287 {
288 auto lock = std::scoped_lock{_mutex};
289
290 // Remove the record for this writer
291 auto it = std::ranges::find_if(_watches, [record](auto const& item) noexcept { return item.second == record; });
292 if (it == _watches.end())
293 {
294 return;
295 }
296
297 auto const wd = it->first;
298 _watches.erase(it);
299
300 // Remove the watch if there are no more writers interested in notification for this flow.
301 if (!_watches.contains(wd))
302 {
303#ifdef __APPLE__
304 if (::close(wd) == -1)
305 {
306 MXL_ERROR("Error closing file descriptor {} for '{}'", wd, record.fileName);
307 }
308#elif defined __linux__
309 if (::inotify_rm_watch(_inotifyFd, wd) == -1)
310 {
311 auto const error = errno;
312 if ((error != EINVAL) || std::filesystem::exists(record.fileName))
313 {
314 MXL_WARN("Failed to remove inotify watch (wd={}) for '{}': {}", wd, record.fileName, std::strerror(error));
315 }
316 }
317#endif
318 }
319 }
320 }
321
322 void DomainWatcher::processEvents()
323 {
324#ifdef __APPLE__
325
326 while (_running)
327 {
328 auto timeout = timespec{.tv_sec = 0, .tv_nsec = 250000000}; // 250 milliseconds
329
330 setWatch();
331
332 auto const eventCount = kevent(_kq,
333 _eventsToMonitor.data(),
334 static_cast<int>(_eventsToMonitor.size()),
335 _eventData.data(),
336 static_cast<int>(_eventData.size()),
337 &timeout);
338 if (eventCount < 0)
339 {
340 auto const error = errno;
341 MXL_ERROR("kevent error {}", std::strerror(error));
342 break;
343 }
344 else if (eventCount)
345 {
346 processPendingEvents(eventCount);
347 }
348 }
349
350#elif defined __linux__
351 epoll_event events[1];
352 alignas(alignof(struct inotify_event)) char buffer[4096] = {};
353
354 while (_running)
355 {
356 int nfds = ::epoll_wait(_epollFd, events, 1, 250);
357 if (nfds == -1)
358 {
359 auto const error = errno;
360 if (error == EINTR)
361 {
362 continue; // interrupted by signal, retry loop
363 }
364 MXL_ERROR("epoll_wait failed: {}", std::strerror(error));
365 break; // exit thread on critical epoll error
366 }
367 if (nfds == 0)
368 {
369 continue; // no events, continue looping
370 }
371
372 for (auto ev = events; ev != events + nfds; ++ev)
373 {
374 if (ev->data.fd == _eventFd)
375 {
376 auto value = ::eventfd_t{};
377 if (::read(_eventFd, &value, sizeof(::eventfd_t)) < 0)
378 {
379 MXL_WARN("Failed to read event file descriptor: {}", ::strerror(errno));
380 continue;
381 }
382
383 if (value > 0)
384 {
385 MXL_DEBUG("Domain watcher thread exit requested");
386 }
387 }
388 else
389 {
390 // We have an inotify event ready
391 auto length = ::read(_inotifyFd, buffer, sizeof buffer);
392 if (length == -1)
393 {
394 auto const error = errno;
395 if ((error == EINTR) || (error == EAGAIN))
396 {
397 continue; // spurious interrupt or non-blocking empty read, retry
398 }
399 MXL_ERROR("Error reading inotify events: {}", std::strerror(error));
400 break; // break on critical read error
401 }
402 if (length == 0)
403 {
404 continue; // nothing to read (should not happen if nfds > 0)
405 }
406
407 processEventBuffer(reinterpret_cast<::inotify_event const*>(buffer), length / sizeof(::inotify_event));
408 }
409 }
410 }
411#endif
412 }
413
414#ifdef __APPLE__
415
416 void DomainWatcher::setWatch()
417 {
418 auto lock = std::scoped_lock{_mutex};
419
420 /* Set up a list of events to monitor. */
421 _eventsToMonitor.resize(_watches.size() + 1);
422 _eventData.resize(_watches.size() + 1);
423
424 auto index = std::size_t{0};
425
426 for (auto const& [wd, rec] : _watches)
427 {
428 EV_SET(
429 &_eventsToMonitor[index], wd, EVFILT_VNODE, EV_ADD | EV_CLEAR, VNODE_EVENTS, 0, std::bit_cast<void*>(static_cast<std::uintptr_t>(wd)));
430 index++;
431 }
432
433 // Set user a user event that signals the poll thread to exit
434 EV_SET(&_eventsToMonitor[_eventsToMonitor.size() - 1], USER_IDENT, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, nullptr);
435 }
436
437 void DomainWatcher::processPendingEvents(int numEvents)
438 {
439 auto lock = std::scoped_lock{_mutex};
440 auto time = currentTime(Clock::TAI);
441 for (int eventIndex = 0; eventIndex < numEvents; eventIndex++)
442 {
443 if (_eventData[eventIndex].ident == USER_IDENT)
444 {
445 MXL_DEBUG("Domain watcher thread exit requested");
446 continue;
447 }
448
449 auto wd = static_cast<int>(std::bit_cast<std::uintptr_t>(_eventData[eventIndex].udata));
450 auto [it, _] = _watches.equal_range(wd);
451 if (it == _watches.end())
452 {
453 continue;
454 }
455
456 auto& [unused, rec] = *it;
457 updateReadTime(rec.flowData->get()->info, time.value);
458 }
459 }
460
461#elif defined __linux__
462 void DomainWatcher::processEventBuffer(::inotify_event const* buffer, std::size_t count)
463 {
464 auto lock = std::scoped_lock{_mutex};
465 auto time = currentTime(Clock::TAI);
466 for (auto p = buffer; p != buffer + count; ++p)
467 {
468 if ((p->mask & (IN_ACCESS | IN_MODIFY | IN_ATTRIB)) == 0)
469 {
470 continue;
471 }
472
473 auto [it, _] = _watches.equal_range(p->wd);
474 if (it == _watches.end())
475 {
476 continue;
477 }
478
479 try
480 {
481 auto& [_, record] = *it;
482 updateReadTime(record.flowData->get()->info, time.value);
483 }
484 catch (std::exception const& e)
485 {
486 MXL_ERROR("Exception in DomainWatcher callback: {}", e.what());
487 }
488 catch (...)
489 {
490 MXL_ERROR("Unknown exception in DomainWatcher callback");
491 }
492 }
493 }
494#elif defined __APPLE__
495 // TODO
496#endif
497
498} // namespace mxl::lib
#define MXL_ERROR(...)
Definition Logging.hpp:67
#define MXL_WARN(...)
Definition Logging.hpp:56
#define MXL_DEBUG(...)
Definition Logging.hpp:34
Paths and filenames utilities used by the MXL SDK.
struct mxlFlowInfo_t mxlFlowInfo
std::filesystem::path _domain
The monitored domain.
std::unordered_multimap< int, DomainWatcherRecord > _watches
Map of watch descriptors to file records. Multiple records could use the same watchfd.
std::filesystem::path makeFlowAccessFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:29
std::atomic< bool > _running
Controls the event processing thread.
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::mutex _mutex
Prodect maps.
std::thread _watchThread
Event processing thread.
std::filesystem::path makeFlowDirectoryName(std::filesystem::path const &domain, std::string const &uuid)
Definition PathUtils.cpp:11
Entry stored in the unordered_maps.
uint8_t * buffer
Set a mark at the beginning and the end of the grain payload.
mxlFlowWriter writer
uint64_t index
auto const currentTime
Definition test_time.cpp:58