BsLinuxFolderMonitor.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Platform/BsFolderMonitor.h"
  4. #include "FileSystem/BsFileSystem.h"
  5. #include "Error/BsException.h"
  6. #include <sys/inotify.h>
  7. namespace bs
  8. {
  9. struct FolderMonitor::FolderWatchInfo
  10. {
  11. FolderWatchInfo(const Path& folderToMonitor, int inHandle, bool monitorSubdirectories, FolderChangeBits filter);
  12. ~FolderWatchInfo();
  13. void startMonitor();
  14. void stopMonitor();
  15. void addPath(const Path& path);
  16. void removePath(const Path& path);
  17. Path getPath(INT32 handle);
  18. Path folderToMonitor;
  19. int dirHandle;
  20. bool monitorSubdirectories;
  21. FolderChangeBits filter;
  22. UnorderedMap<Path, INT32> pathToHandle;
  23. UnorderedMap<INT32, Path> handleToPath;
  24. };
  25. FolderMonitor::FolderWatchInfo::FolderWatchInfo(const Path& folderToMonitor, int inHandle, bool monitorSubdirectories,
  26. FolderChangeBits filter)
  27. : folderToMonitor(folderToMonitor), dirHandle(inHandle), monitorSubdirectories(monitorSubdirectories)
  28. , filter(filter)
  29. { }
  30. FolderMonitor::FolderWatchInfo::~FolderWatchInfo()
  31. {
  32. stopMonitor();
  33. }
  34. void FolderMonitor::FolderWatchInfo::startMonitor()
  35. {
  36. addPath(folderToMonitor);
  37. if(monitorSubdirectories)
  38. {
  39. FileSystem::iterate(folderToMonitor, nullptr, [this](const Path& path)
  40. {
  41. addPath(path);
  42. return true;
  43. });
  44. }
  45. }
  46. void FolderMonitor::FolderWatchInfo::stopMonitor()
  47. {
  48. for(auto& entry : pathToHandle)
  49. inotify_rm_watch(dirHandle, entry.second);
  50. pathToHandle.clear();
  51. }
  52. void FolderMonitor::FolderWatchInfo::addPath(const Path& path)
  53. {
  54. String pathString = path.toString();
  55. INT32 watchHandle = inotify_add_watch(dirHandle, pathString.c_str(), IN_ALL_EVENTS);
  56. if(watchHandle == -1)
  57. {
  58. String error = strerror(errno);
  59. LOGERR("Unable to start folder monitor for path: \"" + pathString +"\". Error: " + error);
  60. }
  61. pathToHandle[path] = watchHandle;
  62. handleToPath[watchHandle] = path;
  63. }
  64. void FolderMonitor::FolderWatchInfo::removePath(const Path& path)
  65. {
  66. auto iterFind = pathToHandle.find(path);
  67. if(iterFind != pathToHandle.end())
  68. {
  69. INT32 watchHandle = iterFind->second;
  70. pathToHandle.erase(iterFind);
  71. handleToPath.erase(watchHandle);
  72. }
  73. }
  74. Path FolderMonitor::FolderWatchInfo::getPath(INT32 handle)
  75. {
  76. auto iterFind = handleToPath.find(handle);
  77. if(iterFind != handleToPath.end())
  78. return iterFind->second;
  79. return Path::BLANK;
  80. }
  81. class FolderMonitor::FileNotifyInfo
  82. {
  83. };
  84. enum class FileActionType
  85. {
  86. Added,
  87. Removed,
  88. Modified,
  89. Renamed
  90. };
  91. struct FileAction
  92. {
  93. static FileAction* createAdded(const WString& fileName)
  94. {
  95. UINT8* bytes = (UINT8*)bs_alloc((UINT32)(sizeof(FileAction) + (fileName.size() + 1) * sizeof(WString::value_type)));
  96. FileAction* action = (FileAction*)bytes;
  97. bytes += sizeof(FileAction);
  98. action->oldName = nullptr;
  99. action->newName = (WString::value_type*)bytes;
  100. action->type = FileActionType::Added;
  101. memcpy(action->newName, fileName.data(), fileName.size() * sizeof(WString::value_type));
  102. action->newName[fileName.size()] = L'\0';
  103. action->lastSize = 0;
  104. action->checkForWriteStarted = false;
  105. return action;
  106. }
  107. static FileAction* createRemoved(const WString& fileName)
  108. {
  109. UINT8* bytes = (UINT8*)bs_alloc((UINT32)(sizeof(FileAction) + (fileName.size() + 1) * sizeof(WString::value_type)));
  110. FileAction* action = (FileAction*)bytes;
  111. bytes += sizeof(FileAction);
  112. action->oldName = nullptr;
  113. action->newName = (WString::value_type*)bytes;
  114. action->type = FileActionType::Removed;
  115. memcpy(action->newName, fileName.data(), fileName.size() * sizeof(WString::value_type));
  116. action->newName[fileName.size()] = L'\0';
  117. action->lastSize = 0;
  118. action->checkForWriteStarted = false;
  119. return action;
  120. }
  121. static FileAction* createModified(const WString& fileName)
  122. {
  123. UINT8* bytes = (UINT8*)bs_alloc((UINT32)(sizeof(FileAction) + (fileName.size() + 1) * sizeof(WString::value_type)));
  124. FileAction* action = (FileAction*)bytes;
  125. bytes += sizeof(FileAction);
  126. action->oldName = nullptr;
  127. action->newName = (WString::value_type*)bytes;
  128. action->type = FileActionType::Modified;
  129. memcpy(action->newName, fileName.data(), fileName.size() * sizeof(WString::value_type));
  130. action->newName[fileName.size()] = L'\0';
  131. action->lastSize = 0;
  132. action->checkForWriteStarted = false;
  133. return action;
  134. }
  135. static FileAction* createRenamed(const WString& oldFilename, const WString& newfileName)
  136. {
  137. UINT8* bytes = (UINT8*)bs_alloc((UINT32)(sizeof(FileAction) +
  138. (oldFilename.size() + newfileName.size() + 2) * sizeof(WString::value_type)));
  139. FileAction* action = (FileAction*)bytes;
  140. bytes += sizeof(FileAction);
  141. action->oldName = (WString::value_type*)bytes;
  142. bytes += (oldFilename.size() + 1) * sizeof(WString::value_type);
  143. action->newName = (WString::value_type*)bytes;
  144. action->type = FileActionType::Modified;
  145. memcpy(action->oldName, oldFilename.data(), oldFilename.size() * sizeof(WString::value_type));
  146. action->oldName[oldFilename.size()] = L'\0';
  147. memcpy(action->newName, newfileName.data(), newfileName.size() * sizeof(WString::value_type));
  148. action->newName[newfileName.size()] = L'\0';
  149. action->lastSize = 0;
  150. action->checkForWriteStarted = false;
  151. return action;
  152. }
  153. static void destroy(FileAction* action)
  154. {
  155. bs_free(action);
  156. }
  157. WString::value_type* oldName;
  158. WString::value_type* newName;
  159. FileActionType type;
  160. UINT64 lastSize;
  161. bool checkForWriteStarted;
  162. };
  163. struct FolderMonitor::Pimpl
  164. {
  165. Vector<FolderWatchInfo*> monitors;
  166. Vector<FileAction*> fileActions;
  167. Vector<FileAction*> activeFileActions;
  168. int inHandle;
  169. bool started;
  170. Mutex mainMutex;
  171. Thread* workerThread;
  172. };
  173. FolderMonitor::FolderMonitor()
  174. {
  175. m = bs_new<Pimpl>();
  176. m->workerThread = nullptr;
  177. m->inHandle = 0;
  178. m->started = false;
  179. }
  180. FolderMonitor::~FolderMonitor()
  181. {
  182. stopMonitorAll();
  183. // No need for mutex since we know worker thread is shut down by now
  184. for(auto& action : m->fileActions)
  185. FileAction::destroy(action);
  186. bs_delete(m);
  187. }
  188. void FolderMonitor::startMonitor(const Path& folderPath, bool subdirectories, FolderChangeBits changeFilter)
  189. {
  190. if(!FileSystem::isDirectory(folderPath))
  191. {
  192. LOGERR("Provided path \"" + folderPath.toString() + "\" is not a directory");
  193. return;
  194. }
  195. // Check if there is overlap with existing monitors
  196. for(auto& monitor : m->monitors)
  197. {
  198. // Identical monitor exists
  199. if(monitor->folderToMonitor.equals(folderPath))
  200. {
  201. LOGWRN("Folder is already monitored, cannot monitor it again.");
  202. return;
  203. }
  204. // This directory is part of a directory that's being monitored
  205. if(monitor->monitorSubdirectories && folderPath.includes(monitor->folderToMonitor))
  206. {
  207. LOGWRN("Folder is already monitored, cannot monitor it again.");
  208. return;
  209. }
  210. // This directory would include a directory of another monitor
  211. if(subdirectories && monitor->folderToMonitor.includes(folderPath))
  212. {
  213. LOGWRN("Cannot add a recursive monitor as it conflicts with a previously monitored path");
  214. return;
  215. }
  216. }
  217. // Initialize inotify if required
  218. if(!m->started)
  219. {
  220. Lock lock(m->mainMutex);
  221. m->inHandle = inotify_init();
  222. m->started = true;
  223. }
  224. FolderWatchInfo* watchInfo = bs_new<FolderWatchInfo>(folderPath, m->inHandle, subdirectories, changeFilter);
  225. // Register and start the monitor
  226. {
  227. Lock lock(m->mainMutex);
  228. m->monitors.push_back(watchInfo);
  229. watchInfo->startMonitor();
  230. }
  231. // Start the worker thread if it isn't already
  232. if(m->workerThread == nullptr)
  233. {
  234. m->workerThread = bs_new<Thread>(std::bind(&FolderMonitor::workerThreadMain, this));
  235. if(m->workerThread == nullptr)
  236. LOGERR("Failed to create a new worker thread for folder monitoring");
  237. }
  238. }
  239. void FolderMonitor::stopMonitor(const Path& folderPath)
  240. {
  241. auto findIter = std::find_if(m->monitors.begin(), m->monitors.end(),
  242. [&](const FolderWatchInfo* x) { return x->folderToMonitor == folderPath; });
  243. if(findIter != m->monitors.end())
  244. {
  245. // Special case if this is the last monitor
  246. if(m->monitors.size() == 1)
  247. stopMonitorAll();
  248. else
  249. {
  250. Lock lock(m->mainMutex);
  251. FolderWatchInfo* watchInfo = *findIter;
  252. watchInfo->stopMonitor();
  253. bs_delete(watchInfo);
  254. m->monitors.erase(findIter);
  255. }
  256. }
  257. }
  258. void FolderMonitor::stopMonitorAll()
  259. {
  260. if(m->started)
  261. {
  262. Lock lock(m->mainMutex);
  263. // First tell the thread it's ready to be shutdown
  264. m->started = false;
  265. // Remove all watches (this will also wake up the thread). Note that at least one watch must be present otherwise
  266. // the thread won't wake up (we ensure that elsewhere).
  267. for (auto& watchInfo : m->monitors)
  268. {
  269. watchInfo->stopMonitor();
  270. bs_delete(watchInfo);
  271. }
  272. m->monitors.clear();
  273. }
  274. // Wait for the thread to shutdown
  275. if(m->workerThread != nullptr)
  276. {
  277. m->workerThread->join();
  278. bs_delete(m->workerThread);
  279. m->workerThread = nullptr;
  280. }
  281. // Close the inotify handle
  282. {
  283. Lock lock(m->mainMutex);
  284. if (m->inHandle != 0)
  285. {
  286. close(m->inHandle);
  287. m->inHandle = 0;
  288. }
  289. }
  290. }
  291. void FolderMonitor::workerThreadMain()
  292. {
  293. static const UINT32 BUFFER_SIZE = 16384;
  294. bool shouldRun;
  295. INT32 watchHandle;
  296. {
  297. Lock(m->mainMutex);
  298. watchHandle = m->inHandle;
  299. shouldRun = m->started;
  300. }
  301. UINT8 buffer[BUFFER_SIZE];
  302. while(shouldRun)
  303. {
  304. INT32 length = (INT32)read(watchHandle, buffer, sizeof(buffer));
  305. // Handle was closed, shutdown thread
  306. if (length < 0)
  307. return;
  308. // Note: Must be after read, so shutdown can be started when we remove the watches (as then read() will return)
  309. {
  310. Lock(m->mainMutex);
  311. shouldRun = m->started;
  312. }
  313. INT32 readPos = 0;
  314. while(readPos < length)
  315. {
  316. inotify_event* event = (inotify_event*)&buffer[readPos];
  317. if(event->len > 0)
  318. {
  319. {
  320. Lock lock(m->mainMutex);
  321. Path path;
  322. FolderWatchInfo* monitor = nullptr;
  323. for (auto& entry : m->monitors)
  324. {
  325. path = entry->getPath(event->wd);
  326. if (!path.isEmpty())
  327. {
  328. path.append(event->name);
  329. monitor = entry;
  330. break;
  331. }
  332. }
  333. // This can happen if the path got removed during some recent previous event
  334. if(monitor == nullptr)
  335. goto next;
  336. // Need to add/remove sub-directories to/from watch list
  337. bool isDirectory = (event->mask & IN_ISDIR) != 0;
  338. if(isDirectory && monitor->monitorSubdirectories)
  339. {
  340. bool added = (event->mask & (IN_CREATE | IN_MOVED_TO)) != 0;
  341. bool removed = (event->mask & (IN_DELETE | IN_MOVED_FROM)) != 0;
  342. if(added)
  343. monitor->addPath(path);
  344. else if(removed)
  345. monitor->removePath(path);
  346. }
  347. // Actually trigger the events
  348. // File/folder was added
  349. if(((event->mask & (IN_CREATE | IN_MOVED_TO)) != 0))
  350. {
  351. if (isDirectory)
  352. {
  353. if (monitor->filter.isSet(FolderChangeBit::DirName))
  354. m->fileActions.push_back(FileAction::createAdded(path.toWString()));
  355. }
  356. else
  357. {
  358. if (monitor->filter.isSet(FolderChangeBit::FileName))
  359. m->fileActions.push_back(FileAction::createAdded(path.toWString()));
  360. }
  361. }
  362. // File/folder was removed
  363. if(((event->mask & (IN_DELETE | IN_MOVED_FROM)) != 0))
  364. {
  365. if(isDirectory)
  366. {
  367. if(monitor->filter.isSet(FolderChangeBit::DirName))
  368. m->fileActions.push_back(FileAction::createRemoved(path.toWString()));
  369. }
  370. else
  371. {
  372. if(monitor->filter.isSet(FolderChangeBit::FileName))
  373. m->fileActions.push_back(FileAction::createRemoved(path.toWString()));
  374. }
  375. }
  376. // File was modified
  377. if(((event->mask & IN_CLOSE_WRITE) != 0) && monitor->filter.isSet(FolderChangeBit::FileWrite))
  378. {
  379. m->fileActions.push_back(FileAction::createModified(path.toWString()));
  380. }
  381. // Note: Not reporting renames, instead a remove + add event is created. To support renames I'd need
  382. // to defer all event triggering until I have processed move event pairs and determined if the
  383. // move is a rename (i.e. parent folder didn't change). All events need to be deferred (not just
  384. // move events) in order to preserve the event ordering. For now this is too much hassle considering
  385. // no external code relies on the rename functionality.
  386. }
  387. }
  388. next:
  389. readPos += sizeof(inotify_event) + event->len;
  390. }
  391. }
  392. }
  393. void FolderMonitor::handleNotifications(FileNotifyInfo& notifyInfo, FolderWatchInfo& watchInfo)
  394. {
  395. // Do nothing
  396. }
  397. void FolderMonitor::_update()
  398. {
  399. {
  400. Lock lock(m->mainMutex);
  401. std::swap(m->fileActions, m->activeFileActions);
  402. }
  403. for(auto& action : m->activeFileActions)
  404. {
  405. switch (action->type)
  406. {
  407. case FileActionType::Added:
  408. if (!onAdded.empty())
  409. onAdded(Path(action->newName));
  410. break;
  411. case FileActionType::Removed:
  412. if (!onRemoved.empty())
  413. onRemoved(Path(action->newName));
  414. break;
  415. case FileActionType::Modified:
  416. if (!onModified.empty())
  417. onModified(Path(action->newName));
  418. break;
  419. case FileActionType::Renamed:
  420. if (!onRenamed.empty())
  421. onRenamed(Path(action->oldName), Path(action->newName));
  422. break;
  423. }
  424. FileAction::destroy(action);
  425. }
  426. m->activeFileActions.clear();
  427. }
  428. }