1 #pragma once 2 3 #include <systemd/sd-event.h> 4 5 #include <filesystem> 6 #include <functional> 7 #include <map> 8 9 namespace phosphor 10 { 11 namespace software 12 { 13 namespace manager 14 { 15 16 namespace fs = std::filesystem; 17 18 /** @class SyncWatch 19 * 20 * @brief Adds inotify watch on persistent files to be synced 21 * 22 * The inotify watch is hooked up with sd-event, so that on call back, 23 * appropriate actions related to syncing files can be taken. 24 */ 25 class SyncWatch 26 { 27 public: 28 /** @brief ctor - hook inotify watch with sd-event 29 * 30 * @param[in] loop - sd-event object 31 * @param[in] syncCallback - The callback function for processing 32 * files 33 */ 34 SyncWatch(sd_event& loop, std::function<int(int, fs::path&)> syncCallback); 35 36 SyncWatch(const SyncWatch&) = delete; 37 SyncWatch& operator=(const SyncWatch&) = delete; 38 SyncWatch(SyncWatch&&) = default; 39 SyncWatch& operator=(SyncWatch&&) = delete; 40 41 /** @brief dtor - remove inotify watch and close fd's 42 */ 43 ~SyncWatch(); 44 45 private: 46 /** @brief sd-event callback 47 * 48 * @param[in] s - event source, floating (unused) in our case 49 * @param[in] fd - inotify fd 50 * @param[in] revents - events that matched for fd 51 * @param[in] userdata - pointer to SyncWatch object 52 * @returns 0 on success, -1 on fail 53 */ 54 static int callback(sd_event_source* s, int fd, uint32_t revents, 55 void* userdata); 56 57 /** @brief Adds an inotify watch to the specified file or directory path 58 * 59 * @param[in] path - The path to the file or directory 60 */ 61 void addInotifyWatch(const fs::path& path); 62 63 /** @brief Map of file descriptors, watch descriptors, and file paths */ 64 using fd = int; 65 using wd = int; 66 fd inotifyFd; 67 std::map<wd, fs::path> fileMap; 68 69 /** @brief The callback function for processing the inotify event */ 70 std::function<int(int, fs::path&)> syncCallback; 71 72 /** @brief Persistent sd_event loop */ 73 sd_event& loop; 74 }; 75 76 } // namespace manager 77 } // namespace software 78 } // namespace phosphor 79