userver: userver/engine/io/sys_linux/inotify.hpp Source File
Loading...
Searching...
No Matches
inotify.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/io/sys_linux/inotify.hpp
4/// @brief Linux-specific fs notification API
5
6#if defined(__linux__) || defined(DOXYGEN)
7
8#include <sys/inotify.h>
9
10#include <optional>
11#include <queue>
12#include <string>
13#include <unordered_map>
14
15#include <userver/engine/io/fd_poller.hpp>
16#include <userver/logging/fwd.hpp>
17#include <userver/utils/flags.hpp>
18
19USERVER_NAMESPACE_BEGIN
20
21namespace engine::io::sys_linux {
22
23/// @brief Notification event type
24enum class EventType {
25 kNone = 0,
26 kAccess = IN_ACCESS,
27 kAttribChanged = IN_ATTRIB,
28 kCloseWrite = IN_CLOSE_WRITE,
29 kCloseNoWrite = IN_CLOSE_NOWRITE,
30 kCreate = IN_CREATE,
31 kDelete = IN_DELETE,
32 kDeleteSelf = IN_DELETE_SELF,
33 kModify = IN_MODIFY,
34 kMoveSelf = IN_MOVE_SELF,
35 kMovedFrom = IN_MOVED_FROM,
36 kMovedTo = IN_MOVED_TO,
37 kOpen = IN_OPEN,
38
39 kIsDir = IN_ISDIR, // event occurred against dir
40 kOnlyDir = IN_ONLYDIR, // catch only dir events
41};
42
43std::string ToString(EventType);
44
45/// @brief A set of notification event types
46using EventTypeMask = utils::Flags<EventType>;
47
48std::string ToString(EventTypeMask);
49
50/// @brief Notification event
51struct Event {
52 std::string path;
53 EventTypeMask mask;
54
55 bool operator==(const Event& other) const { return path == other.path && mask == other.mask; }
56};
57
58logging::LogHelper& operator<<(logging::LogHelper& lh, const Event& event) noexcept;
59
60/// @brief File descriptor that allows one to monitor filesystem events, such as
61/// file creation, modification, etc.
62class Inotify final {
63public:
64 Inotify();
65
66 Inotify(const Inotify&) = delete;
67
68 Inotify(Inotify&&) = delete;
69
70 ~Inotify();
71
72 Inotify& operator=(Inotify&&) = delete;
73
74 Inotify& operator=(const Inotify&) = delete;
75
76 /// Start to watch on the file path. Afterwards file events will be signaled
77 /// through Poll() results.
78 void AddWatch(const std::string& path, EventTypeMask flags);
79
80 /// Stop watching file events previously registered through AddWatch().
81 void RmWatch(const std::string& path);
82
83 /// Read file events with event types previously registered through
84 /// AddWatch(). Poll() blocks current coroutine until the event is obtained
85 /// or the coroutine is cancelled.
86 std::optional<Event> Poll(engine::Deadline deadline);
87
88private:
89 void Dispatch();
90
91 FdPoller fd_;
92 std::queue<Event> pending_events_;
93 std::unordered_map<std::string, int> path_to_wd_;
94 std::unordered_map<int, std::string> wd_to_path_;
95};
96
97} // namespace engine::io::sys_linux
98
99USERVER_NAMESPACE_END
100
101#endif