12#include <system_error>
25# include <sys/event.h>
27# include <sys/epoll.h>
28# include <sys/eventfd.h>
29# include <sys/inotify.h>
41 void updateReadTime(
mxlFlowInfo& info, std::uint64_t time)
noexcept
43 std::atomic_ref{info.runtime.lastReadTime}.store(time, std::memory_order_release);
47 constexpr auto VNODE_EVENTS =
static_cast<unsigned int>(NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB);
49 using KEvent =
struct kevent;
53 DomainWatcher::DomainWatcher(std::filesystem::path
const& in_domain)
58 if (!std::filesystem::is_directory(in_domain))
60 throw std::filesystem::filesystem_error(
"Domain path is not a directory", in_domain, std::make_error_code(std::errc::not_a_directory));
67 auto const error = errno;
68 throw std::system_error(error, std::generic_category(),
"Failed to create a kqueue");
71#elif defined __linux__
72 _inotifyFd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
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");
82 _epollFd = epoll_create1(EPOLL_CLOEXEC);
85 auto const error = errno;
86 MXL_ERROR(
"epoll_create1 failed (errno {}: {})", error, std::strerror(error));
89 throw std::system_error(error, std::generic_category(),
"epoll_create1 failed");
94 event.events = EPOLLIN;
95 event.data.fd = _inotifyFd;
96 if (epoll_ctl(_epollFd, EPOLL_CTL_ADD, _inotifyFd, &event) == -1)
98 auto const error = errno;
99 MXL_ERROR(
"epoll_ctl ADD(inotify) failed: {}", std::strerror(error));
102 throw std::system_error(error, std::generic_category(),
"epoll_ctl ADD inotify failed");
105 _eventFd = ::eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
108 auto const error = errno;
111 throw std::system_error{error, std::generic_category(),
"failed to create evenfd"};
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)
119 auto const error = errno;
123 throw std::system_error(error, std::generic_category(),
"epoll_ctl ADD eventfd failed");
130 _watchThread = std::thread(&DomainWatcher::processEvents,
this);
132 catch (std::exception
const& e)
134 MXL_ERROR(
"Failed to start watcher thread: {}", e.what());
137#elif defined __linux__
146 MXL_ERROR(
"Failed to start watcher thread: unknown exception");
149#elif defined __linux__
158 DomainWatcher::~DomainWatcher()
164#elif defined __linux__
166 for (
auto const& [wd, rec] :
_watches)
168 if (inotify_rm_watch(_inotifyFd, wd) == -1)
170 auto const error = errno;
171 MXL_ERROR(
"Error removing inotify watch (wd={}): {}", wd, std::strerror(error));
174 if (::close(_inotifyFd) == -1)
176 auto const error = errno;
177 MXL_ERROR(
"Error closing inotify FD: {}", std::strerror(error));
179 if (::close(_eventFd) == -1)
181 auto const error = errno;
182 MXL_ERROR(
"Error closing epoll FD: {}", std::strerror(error));
184 if (::close(_epollFd) == -1)
186 auto const error = errno;
187 MXL_ERROR(
"Error closing epoll FD: {}", std::strerror(error));
192 std::size_t DomainWatcher::count(uuids::uuid
id)
const noexcept
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; });
204 std::size_t DomainWatcher::size() const noexcept
206 auto lock = std::scoped_lock{
_mutex};
219 auto lock = std::scoped_lock{
_mutex};
220 auto existingWd = -1;
223 for (
auto const& [wd, rec] :
_watches)
225 if (rec.id == record.id)
228 record.flowData = rec.flowData;
233 if (existingWd == -1)
235 MXL_DEBUG(
"Record for {} not found, creating one.", uuids::to_string(record.id));
238 existingWd = ::open(record.fileName.c_str(), O_EVTONLY | O_CLOEXEC);
239 if (existingWd != -1)
241 auto change = KEvent{};
248 std::bit_cast<void*>(
static_cast<std::uintptr_t
>(existingWd)));
249 if (::kevent(_kq, &change, 1,
nullptr, 0,
nullptr) == -1)
251 auto const error = errno;
257#elif defined __linux__
259 existingWd = ::inotify_add_watch(_inotifyFd, record.fileName.c_str(), IN_ACCESS | IN_ATTRIB);
261 if (existingWd == -1)
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};
269 MXL_DEBUG(
"Added watch {} for file: {}", existingWd, record.fileName);
273 record.flowData = std::make_shared<SharedMemoryInstance<Flow>>(
275 _watches.emplace(existingWd, std::move(record));
288 auto lock = std::scoped_lock{
_mutex};
291 auto it = std::ranges::find_if(
_watches, [record](
auto const& item)
noexcept {
return item.second == record; });
297 auto const wd = it->first;
304 if (::close(wd) == -1)
306 MXL_ERROR(
"Error closing file descriptor {} for '{}'", wd, record.fileName);
308#elif defined __linux__
309 if (::inotify_rm_watch(_inotifyFd, wd) == -1)
311 auto const error = errno;
312 if ((error != EINVAL) || std::filesystem::exists(record.fileName))
314 MXL_WARN(
"Failed to remove inotify watch (wd={}) for '{}': {}", wd, record.fileName, std::strerror(error));
322 void DomainWatcher::processEvents()
328 auto timeout = timespec{.tv_sec = 0, .tv_nsec = 250000000};
332 auto const eventCount = kevent(_kq,
333 _eventsToMonitor.data(),
334 static_cast<int>(_eventsToMonitor.size()),
336 static_cast<int>(_eventData.size()),
340 auto const error = errno;
341 MXL_ERROR(
"kevent error {}", std::strerror(error));
346 processPendingEvents(eventCount);
350#elif defined __linux__
351 epoll_event events[1];
352 alignas(
alignof(
struct inotify_event)) char
buffer[4096] = {};
356 int nfds = ::epoll_wait(_epollFd, events, 1, 250);
359 auto const error = errno;
364 MXL_ERROR(
"epoll_wait failed: {}", std::strerror(error));
372 for (
auto ev = events; ev != events + nfds; ++ev)
374 if (ev->data.fd == _eventFd)
376 auto value = ::eventfd_t{};
377 if (::read(_eventFd, &value,
sizeof(::eventfd_t)) < 0)
379 MXL_WARN(
"Failed to read event file descriptor: {}", ::strerror(errno));
385 MXL_DEBUG(
"Domain watcher thread exit requested");
391 auto length = ::read(_inotifyFd,
buffer,
sizeof buffer);
394 auto const error = errno;
395 if ((error == EINTR) || (error == EAGAIN))
399 MXL_ERROR(
"Error reading inotify events: {}", std::strerror(error));
407 processEventBuffer(
reinterpret_cast<::inotify_event const*
>(
buffer), length /
sizeof(::inotify_event));
416 void DomainWatcher::setWatch()
418 auto lock = std::scoped_lock{_mutex};
421 _eventsToMonitor.resize(_watches.size() + 1);
422 _eventData.resize(_watches.size() + 1);
424 auto index = std::size_t{0};
426 for (
auto const& [wd, rec] : _watches)
429 &_eventsToMonitor[
index], wd, EVFILT_VNODE, EV_ADD | EV_CLEAR, VNODE_EVENTS, 0, std::bit_cast<void*>(
static_cast<std::uintptr_t
>(wd)));
434 EV_SET(&_eventsToMonitor[_eventsToMonitor.size() - 1], USER_IDENT, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0,
nullptr);
437 void DomainWatcher::processPendingEvents(
int numEvents)
439 auto lock = std::scoped_lock{
_mutex};
441 for (
int eventIndex = 0; eventIndex < numEvents; eventIndex++)
443 if (_eventData[eventIndex].ident == USER_IDENT)
445 MXL_DEBUG(
"Domain watcher thread exit requested");
449 auto wd =
static_cast<int>(std::bit_cast<std::uintptr_t>(_eventData[eventIndex].udata));
450 auto [it, _] =
_watches.equal_range(wd);
456 auto& [unused, rec] = *it;
457 updateReadTime(rec.flowData->get()->info, time.value);
461#elif defined __linux__
462 void DomainWatcher::processEventBuffer(::inotify_event
const*
buffer, std::size_t count)
464 auto lock = std::scoped_lock{
_mutex};
468 if ((p->mask & (IN_ACCESS | IN_MODIFY | IN_ATTRIB)) == 0)
473 auto [it, _] =
_watches.equal_range(p->wd);
481 auto& [_, record] = *it;
482 updateReadTime(record.flowData->get()->info, time.value);
484 catch (std::exception
const& e)
486 MXL_ERROR(
"Exception in DomainWatcher callback: {}", e.what());
490 MXL_ERROR(
"Unknown exception in DomainWatcher callback");
494#elif defined __APPLE__
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)
std::atomic< bool > _running
Controls the event processing thread.
std::filesystem::path makeFlowDataFilePath(std::filesystem::path const &flowDirectory)
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)
Entry stored in the unordered_maps.
uint8_t * buffer
Set a mark at the beginning and the end of the grain payload.