Repository navigation
Expand file tree
/
Copy pathplugin_hot_plug_monitor.cpp
More file actions
682 lines (584 loc) · 22.1 KB
/
Copy pathplugin_hot_plug_monitor.cpp
File metadata and controls
682 lines (584 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/**
* @file plugin_hot_plug_monitor.cpp
* @brief Canonical Doxygen file header for ThemisDB-generated maturity metadata.
* @version 0.0.47
* @note Maturity: 🟢 PRODUCTION-READY
* @note Score: 81/100
* @note Status: Production Ready
* @note This block is auto-generated and will be overwritten.
*/
#include "plugins/plugin_hot_plug_monitor.h"
#include "plugins/plugin_manager.h"
#include "utils/logger.h"
#include <filesystem>
#include <map>
#include <thread>
#include <chrono>
#include <future>
#include <algorithm>
#include <set>
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#elif defined(__APPLE__)
#include <CoreServices/CoreServices.h>
#include <sys/event.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#else
#include <sys/inotify.h>
#include <unistd.h>
#include <errno.h>
#include <cstring>
#include <poll.h>
#endif
namespace themis {
namespace plugins {
namespace fs = std::filesystem;
// ============================================================================
// RAII Helper Classes
// ============================================================================
namespace {
#ifdef _WIN32
inline int platformClose(int fd) noexcept {
return _close(fd);
}
#else
inline int platformClose(int fd) noexcept {
return ::close(fd);
}
#endif
}
// RAII wrapper for file descriptors (Unix/Linux/macOS)
struct FileDescriptorDeleter {
void operator()(int* fd_ptr) const noexcept {
if (fd_ptr && *fd_ptr >= 0) {
try {
(void)platformClose(*fd_ptr);
*fd_ptr = -1;
} catch (...) {
THEMIS_WARN("Exception during file descriptor cleanup");
}
}
delete fd_ptr;
}
};
using UniqueFileDescriptor = std::unique_ptr<int, FileDescriptorDeleter>;
/**
* @brief Helper function to create RAII-wrapped file descriptor
* @param[in] fd Input parameter.
* @return Return value.
* @details Calls: UniqueFileDescriptor(), release().
*/
inline UniqueFileDescriptor makeUniqueFileDescriptor(int fd) {
auto fd_ptr = std::make_unique<int>(fd);
return UniqueFileDescriptor(fd_ptr.release());
}
// ============================================================================
// Constructor & Destructor
// ============================================================================
PluginHotPlugMonitor::PluginHotPlugMonitor(
PluginManager* manager,
const std::string& directory,
const HotPlugConfig& config
) : watch_directory_(directory),
plugin_manager_(manager),
config_(config)
{
#ifdef _WIN32
dir_handle_ = nullptr;
#elif defined(__APPLE__)
fs_event_stream_ = nullptr;
#else
inotify_fd_ = -1;
watch_descriptor_ = -1;
#endif
}
PluginHotPlugMonitor::~PluginHotPlugMonitor() {
stop();
}
// ============================================================================
// Platform-specific helpers
// ============================================================================
bool PluginHotPlugMonitor::isPluginFile(const std::string& filename) const {
// Reject temporary/incomplete files produced by editors, package managers,
// and build tools during write operations (e.g. vim swaps, wget .part files).
// These files are never valid plugin binaries or manifests.
if (filename.starts_with(".") ||
filename.ends_with(".tmp") ||
filename.ends_with(".part") ||
filename.ends_with(".download") ||
filename.ends_with("~")) {
return false;
}
// Check for plugin-related file extensions
// Note: ends_with is C++20, but this project uses C++20
return filename.ends_with(".dll") ||
filename.ends_with(".so") ||
filename.ends_with(".dylib") ||
filename == "plugin.json";
}
std::string PluginHotPlugMonitor::extractPluginName(const std::string& filepath) const {
/**
* @brief P.
* @param[in] filepath Input parameter.
* @return Return value.
*/
fs::path p(filepath);
// If it's plugin.json, the parent directory name is the plugin name
if (p.filename() == "plugin.json") {
return p.parent_path().filename().string();
}
// For .dll/.so/.dylib files, use the stem (filename without extension)
return p.stem().string();
}
// ============================================================================
// Event Handling
// ============================================================================
/**
* @brief Handle File Event.
* @param[in] filename Input parameter.
* @param[in] event Input parameter.
* @details Calls: isPluginFile(), extractPluginName(), empty(), THEMIS_INFO(), std::this_thread::sleep_for(), std::chrono::milliseconds(), scanPluginDirectory(), loadPlugin().
*/
void PluginHotPlugMonitor::handleFileEvent(
const std::string& filename,
FileEvent event
) {
// Only process plugin files
if (!isPluginFile(filename)) {
return;
}
std::string full_path = watch_directory_ + "/" + filename;
std::string plugin_name = extractPluginName(full_path);
if (plugin_name.empty()) {
return;
}
try {
switch (event) {
case FileEvent::CREATED:
if (config_.auto_load) {
THEMIS_INFO("New plugin detected: {}", filename);
// Wait for file to be fully written
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// Rescan directory to discover new plugin
(void)plugin_manager_->scanPluginDirectory(watch_directory_);
// Try to load the plugin
auto result = plugin_manager_->loadPlugin(plugin_name);
if (result) {
THEMIS_INFO("Auto-loaded plugin: {}", plugin_name);
} else {
THEMIS_WARN("Failed to auto-load plugin {}: {}", plugin_name, result.error().message());
}
}
break;
case FileEvent::MODIFIED:
if (config_.auto_reload) {
THEMIS_INFO("Plugin modified: {}", filename);
// Wait for file to be fully written
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// Hot-reload if already loaded
if (plugin_manager_->isPluginLoaded(plugin_name)) {
auto reload_result = plugin_manager_->reloadPlugin(plugin_name);
if (reload_result.has_value()) {
THEMIS_INFO("Auto-reloaded plugin: {}", plugin_name);
} else {
THEMIS_WARN("Failed to reload plugin: {}", plugin_name);
}
}
}
break;
case FileEvent::DELETED:
if (config_.auto_unload) {
THEMIS_INFO("Plugin removed: {}", filename);
// Unload if loaded
if (plugin_manager_->isPluginLoaded(plugin_name)) {
auto unload_result = plugin_manager_->unloadPlugin(plugin_name);
if (unload_result.has_value()) {
THEMIS_INFO("Auto-unloaded plugin: {}", plugin_name);
} else {
THEMIS_WARN("Failed to auto-unload plugin: {}", plugin_name);
}
}
}
break;
}
} catch (const std::exception& e) {
THEMIS_ERROR("Error handling file event for {}: {}", filename, e.what());
}
}
// ============================================================================
// Linux Implementation (inotify)
// ============================================================================
#ifndef _WIN32
#ifndef __APPLE__
/**
* @brief Watch Directory Linux.
* @details Calls: __attribute__(), aligned(), __alignof__(), poll(), THEMIS_ERROR(), strerror(), read(), handleFileEvent().
*/
void PluginHotPlugMonitor::watchDirectoryLinux() {
char buffer[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
// Use poll to allow for interruption
struct pollfd pfd;
pfd.fd = inotify_fd_;
pfd.events = POLLIN;
while (running_) {
int poll_result = poll(&pfd, 1, 1000); // 1 second timeout
if (poll_result < 0) {
if (errno != EINTR) {
THEMIS_ERROR("poll error: {}", strerror(errno));
}
continue;
}
if (poll_result == 0) {
// Timeout, check if still running
continue;
}
ssize_t length = read(inotify_fd_, buffer, sizeof(buffer));
if (length < 0) {
if (errno != EINTR && errno != EAGAIN) {
THEMIS_ERROR("inotify read error: {}", strerror(errno));
}
continue;
}
// Process all events in the buffer
for (char* ptr = buffer; ptr < buffer + length; ) {
struct inotify_event* event = reinterpret_cast<struct inotify_event*>(ptr);
if (event->len > 0) {
FileEvent file_event = {};
if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
file_event = FileEvent::CREATED;
} else if (event->mask & IN_MODIFY) {
file_event = FileEvent::MODIFIED;
} else if (event->mask & (IN_DELETE | IN_MOVED_FROM)) {
file_event = FileEvent::DELETED;
} else {
// Ignore other events
ptr += sizeof(struct inotify_event) + event->len;
continue;
}
handleFileEvent(event->name, file_event);
}
ptr += sizeof(struct inotify_event) + event->len;
}
}
}
#endif // !__APPLE__
#endif // !_WIN32
// ============================================================================
// Windows Implementation (ReadDirectoryChangesW)
// ============================================================================
#ifdef _WIN32
/**
* @brief Watch Directory Windows.
* @details Calls: ReadDirectoryChangesW(), wfilename(), reserve(), size(), push_back(), handleFileEvent().
*/
void PluginHotPlugMonitor::watchDirectoryWindows() {
char buffer[4096];
DWORD bytes_returned;
while (running_) {
BOOL success = ReadDirectoryChangesW(
dir_handle_,
buffer,
sizeof(buffer),
TRUE, // Watch subdirectories
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
&bytes_returned,
nullptr,
nullptr
);
if (!success || !running_) {
break;
}
if (bytes_returned == 0) {
continue;
}
// Process events
FILE_NOTIFY_INFORMATION* fni = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(buffer);
bool has_more_events = true;
while (has_more_events) {
// Convert filename from wide char to narrow
int filename_length = fni->FileNameLength / sizeof(wchar_t);
std::wstring wfilename(fni->FileName, filename_length);
std::string filename = {};
filename.reserve(wfilename.size());
for (wchar_t wc : wfilename) {
filename.push_back(static_cast<char>(wc));
}
FileEvent event;
bool should_handle = true;
switch (fni->Action) {
case FILE_ACTION_ADDED:
event = FileEvent::CREATED;
break;
case FILE_ACTION_MODIFIED:
event = FileEvent::MODIFIED;
break;
case FILE_ACTION_REMOVED:
event = FileEvent::DELETED;
break;
case FILE_ACTION_RENAMED_NEW_NAME:
// A rename/move into the directory counts as a new file
event = FileEvent::CREATED;
break;
case FILE_ACTION_RENAMED_OLD_NAME:
// A rename/move out of the directory counts as a deletion
event = FileEvent::DELETED;
break;
default:
// Ignore other actions
should_handle = false;
break;
}
if (should_handle) {
handleFileEvent(filename, event);
}
// Check if there are more events
if (fni->NextEntryOffset == 0) {
has_more_events = false;
} else {
fni = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(
reinterpret_cast<char*>(fni) + fni->NextEntryOffset
);
}
}
}
}
#endif // _WIN32
// ============================================================================
// macOS Implementation (kqueue)
// ============================================================================
#ifdef __APPLE__
/**
* @brief Watch Directory Mac OS.
* @details Calls: kqueue(), THEMIS_ERROR(), strerror(), makeUniqueFileDescriptor(), open(), c_str(), EV_SET(), kevent().
*/
void PluginHotPlugMonitor::watchDirectoryMacOS() {
// Use kqueue for macOS
int kq = kqueue();
if (kq == -1) {
THEMIS_ERROR("Failed to create kqueue: {}", strerror(errno));
return;
}
// Wrap kqueue file descriptor for RAII cleanup
auto kq_guard = makeUniqueFileDescriptor(kq);
// Open directory for monitoring (add O_NONBLOCK to prevent indefinite blocking)
int dir_fd = open(watch_directory_.c_str(), O_RDONLY | O_NONBLOCK);
if (dir_fd == -1) {
THEMIS_ERROR("Failed to open directory: {}", strerror(errno));
return; // kq_guard will automatically close kq
}
// Wrap directory file descriptor for RAII cleanup
auto dir_guard = makeUniqueFileDescriptor(dir_fd);
// Setup kevent for directory monitoring
struct kevent change;
EV_SET(&change, dir_fd, EVFILT_VNODE,
EV_ADD | EV_ENABLE | EV_CLEAR,
NOTE_WRITE | NOTE_EXTEND | NOTE_DELETE,
0, nullptr);
// Add kevent with timeout to prevent indefinite blocking
struct timespec registration_timeout = {};
registration_timeout.tv_sec = 1; // tv_nsec stays 0 via value-initialization.
if (kevent(kq, &change, 1, nullptr, 0, ®istration_timeout) == -1) {
THEMIS_ERROR("Failed to add kevent: {}", strerror(errno));
return; // Both kq_guard and dir_guard will automatically cleanup
}
// Track files we've seen along with their last-write timestamps
std::map<std::string, fs::file_time_type> known_files;
auto scan_directory = [&]() {
std::map<std::string, fs::file_time_type> current_files;
try {
for (const auto& entry : fs::directory_iterator(watch_directory_)) {
// Skip symlinks pointing to non-existent targets
if (entry.is_symlink()) {
std::error_code ec = {};
if (!fs::exists(entry.path(), ec) || ec) {
THEMIS_WARN("Skipping broken symlink: {}", entry.path().string());
continue;
}
}
if (entry.is_regular_file()) {
std::string filename = entry.path().filename().string();
if (isPluginFile(filename)) {
std::error_code ec = {};
auto mtime = entry.last_write_time(ec);
if (!ec) {
current_files[filename] = mtime;
}
}
}
}
} catch (const std::exception& e) {
THEMIS_WARN("Error scanning plugin directory: {}", e.what());
}
// Detect new files and modified files (by mtime)
for (const auto& [file, mtime] : current_files) {
auto prev = known_files.find(file);
if (prev == known_files.end()) {
handleFileEvent(file, FileEvent::CREATED);
} else if (prev->second != mtime) {
handleFileEvent(file, FileEvent::MODIFIED);
}
}
// Detect deleted files
for (const auto& [file, _] : known_files) {
if (current_files.find(file) == current_files.end()) {
handleFileEvent(file, FileEvent::DELETED);
}
}
known_files = current_files;
};
// Initial scan
scan_directory();
// Monitor loop
struct kevent event;
struct timespec event_timeout = {};
event_timeout.tv_sec = 1;
while (running_) {
int nev = kevent(kq, nullptr, 0, &event, 1, &event_timeout);
if (nev < 0) {
if (errno != EINTR) {
THEMIS_ERROR("kevent error: {}", strerror(errno));
}
continue;
}
if (nev > 0) {
// Directory changed, rescan to detect what changed
scan_directory();
}
}
// dir_guard and kq_guard automatically close dir_fd and kq via RAII
}
#endif // __APPLE__
// ============================================================================
// Public Interface
// ============================================================================
/**
* @brief Start.
* @return True when the operation succeeds.
* @details Calls: THEMIS_WARN(), fs::exists(), THEMIS_ERROR(), fs::is_directory(), CreateFileA(), c_str(), std::thread(), watchDirectoryWindows().
*/
bool PluginHotPlugMonitor::start() {
if (running_) {
THEMIS_WARN("Hot-plug monitor already running");
return false;
}
// Verify directory exists
if (!fs::exists(watch_directory_)) {
THEMIS_ERROR("Watch directory does not exist: {}", watch_directory_);
return false;
}
if (!fs::is_directory(watch_directory_)) {
THEMIS_ERROR("Watch path is not a directory: {}", watch_directory_);
return false;
}
running_ = true;
#ifdef _WIN32
// Windows implementation
dir_handle_ = CreateFileA(
watch_directory_.c_str(),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
nullptr
);
if (dir_handle_ == INVALID_HANDLE_VALUE) {
THEMIS_ERROR("Failed to open directory for watching: {}", watch_directory_);
running_ = false;
return false;
}
monitor_thread_ = std::thread([this]() {
watchDirectoryWindows();
});
#elif defined(__APPLE__)
// macOS implementation
monitor_thread_ = std::thread([this]() {
watchDirectoryMacOS();
});
#else
// Linux implementation
inotify_fd_ = inotify_init1(IN_NONBLOCK);
if (inotify_fd_ < 0) {
THEMIS_ERROR("Failed to initialize inotify: {}", strerror(errno));
running_ = false;
return false;
}
watch_descriptor_ = inotify_add_watch(
inotify_fd_,
watch_directory_.c_str(),
IN_CREATE | IN_MODIFY | IN_DELETE | IN_MOVED_TO | IN_MOVED_FROM
);
if (watch_descriptor_ < 0) {
THEMIS_ERROR("Failed to add inotify watch: {}", strerror(errno));
close(inotify_fd_);
inotify_fd_ = -1;
running_ = false;
return false;
}
monitor_thread_ = std::thread([this]() {
watchDirectoryLinux();
});
#endif
THEMIS_INFO("Hot-plug monitoring started for: {}", watch_directory_);
return true;
}
/**
* @brief Stop.
* @details Calls: CloseHandle(), joinable(), get_future(), joiner(), std::move(), join(), set_value(), detach().
*/
void PluginHotPlugMonitor::stop() {
if (!running_) {
return;
}
running_ = false;
#ifdef _WIN32
// On Windows, ReadDirectoryChangesW can block indefinitely.
// Closing the watched directory handle first unblocks the monitor thread.
if (dir_handle_ != nullptr && dir_handle_ != INVALID_HANDLE_VALUE) {
CloseHandle(dir_handle_);
dir_handle_ = nullptr;
}
#endif
// Join the monitor thread. The thread's loop checks running_ (now false)
// and will exit at the next kevent/inotify/ReadDirectoryChangesW timeout
// (all configured with a 1-second poll interval). Block here using a
// helper thread that signals a promise when the join completes, so we can
// enforce an overall deadline without mis-using joinable().
if (monitor_thread_.joinable()) {
std::promise<void> joined_promise;
auto joined_future = joined_promise.get_future();
std::thread joiner([this, p = std::move(joined_promise)]() mutable {
monitor_thread_.join();
p.set_value();
});
joiner.detach();
const auto timeout_duration = std::chrono::seconds(5);
if (joined_future.wait_for(timeout_duration) != std::future_status::ready) {
THEMIS_WARN("Plugin hot-plug monitor thread did not join within {} ms",
std::chrono::duration_cast<std::chrono::milliseconds>(timeout_duration).count());
// The joiner thread will eventually finish the join and clean up;
// we do not detach monitor_thread_ here to avoid use-after-free.
}
}
#ifdef _WIN32
// Handle already closed before join to unblock ReadDirectoryChangesW.
#elif defined(__APPLE__)
// Cleanup handled in thread
#else
if (watch_descriptor_ >= 0) {
inotify_rm_watch(inotify_fd_, watch_descriptor_);
watch_descriptor_ = -1;
}
if (inotify_fd_ >= 0) {
close(inotify_fd_);
inotify_fd_ = -1;
}
#endif
THEMIS_INFO("Hot-plug monitoring stopped");
}
} // namespace plugins
} // namespace themis