-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin_hot_plug_monitor.cpp
More file actions
590 lines (500 loc) · 19.8 KB
/
plugin_hot_plug_monitor.cpp
File metadata and controls
590 lines (500 loc) · 19.8 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
/*
╔═════════════════════════════════════════════════════════════════════╗
║ ThemisDB - Hybrid Database System ║
╠═════════════════════════════════════════════════════════════════════╣
File: plugin_hot_plug_monitor.cpp ║
Version: 0.0.36 ║
Last Modified: 2026-03-30 04:18:03 ║
Author: unknown ║
╠═════════════════════════════════════════════════════════════════════╣
Quality Metrics: ║
• Maturity Level: 🟢 PRODUCTION-READY ║
• Quality Score: 96.0/100 ║
• Total Lines: 584 ║
• Open Issues: TODOs: 0, Stubs: 0 ║
╠═════════════════════════════════════════════════════════════════════╣
Revision History: ║
• 2a1fb0423 2026-03-03 Merge branch 'develop' into copilot/audit-src-module-docu... ║
╠═════════════════════════════════════════════════════════════════════╣
Status: ✅ Production Ready ║
╚═════════════════════════════════════════════════════════════════════╝
*/
#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 <algorithm>
#include <set>
#ifdef _WIN32
#include <windows.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;
// ============================================================================
// Constructor & Destructor
// ============================================================================
PluginHotPlugMonitor::PluginHotPlugMonitor(
PluginManager* manager,
const std::string& directory,
const HotPlugConfig& config
) : plugin_manager_(manager),
watch_directory_(directory),
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 {
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
// ============================================================================
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
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)) {
plugin_manager_->unloadPlugin(plugin_name);
THEMIS_INFO("Auto-unloaded 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__
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
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__
void PluginHotPlugMonitor::watchDirectoryMacOS() {
// Use kqueue for macOS
int kq = kqueue();
if (kq == -1) {
THEMIS_ERROR("Failed to create kqueue: {}", strerror(errno));
return;
}
// Open directory for monitoring
int dir_fd = open(watch_directory_.c_str(), O_RDONLY);
if (dir_fd == -1) {
THEMIS_ERROR("Failed to open directory: {}", strerror(errno));
close(kq);
return;
}
// 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);
if (kevent(kq, &change, 1, nullptr, 0, nullptr) == -1) {
THEMIS_ERROR("Failed to add kevent: {}", strerror(errno));
close(dir_fd);
close(kq);
return;
}
// 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 timeout;
timeout.tv_sec = 1;
timeout.tv_nsec = 0;
while (running_) {
int nev = kevent(kq, nullptr, 0, &event, 1, &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();
}
}
close(dir_fd);
close(kq);
}
#endif // __APPLE__
// ============================================================================
// Public Interface
// ============================================================================
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;
}
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
// Wait for thread to finish
if (monitor_thread_.joinable()) {
monitor_thread_.join();
}
#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