-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathconfig_watcher.js
More file actions
758 lines (639 loc) · 30.6 KB
/
config_watcher.js
File metadata and controls
758 lines (639 loc) · 30.6 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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
const chokidar = require("chokidar");
const fs = require("fs-extra");
const path = require("path");
const log = require("./log").logger("watcher");
var machine = require("./machine"); // source for status info
// Directories to watch
const watchDirs = ["/opt/fabmo/config/", "/opt/fabmo/macros/"];
// Directory to store backups
const backupBaseDir = "/opt/fabmo_backup/";
// Backup timing constraints (relaxed for production efficiency)
const MIN_BACKUP_SPACING_MS = 30000; // 30 seconds between backups (was 10s)
const DEFERRED_BATCH_WINDOW_MS = 60000; // 60 seconds to batch changes (was 12s)
const BACKUP_RETRY_DELAY_MS = 30000; // 30 seconds between retry attempts (was 10s)
const MAX_BACKUP_RETRIES = 10; // 10 attempts = ~5 minutes tolerance (was 5)
// Debounce function
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// Track retries for backup attempts
let backupRetries = new Map(); // filepath -> retry count
function processBackup(filePath, currentTime) {
// Initialize retry count if not present
if (!backupRetries.has(filePath)) {
backupRetries.set(filePath, 0);
}
isToolIdle((idle) => {
if (!idle) {
const retryCount = backupRetries.get(filePath);
// Check if we've exceeded max retries
if (retryCount >= MAX_BACKUP_RETRIES) {
log.warn(`Backup abandoned for ${filePath} after ${MAX_BACKUP_RETRIES} retries (${Math.round(MAX_BACKUP_RETRIES * BACKUP_RETRY_DELAY_MS / 60000)} minutes) - tool not idle`);
backupRetries.delete(filePath);
pendingUpdates.delete(filePath);
return;
}
log.debug(`Tool not idle (state=${machine.machine.status.state}). Delaying backup for ${filePath} (attempt ${retryCount + 1}/${MAX_BACKUP_RETRIES})`);
backupRetries.set(filePath, retryCount + 1);
setTimeout(() => processBackup(filePath, currentTime), BACKUP_RETRY_DELAY_MS);
} else {
// Clear retry count on success
backupRetries.delete(filePath);
// Validate JSON before backing up
if (path.extname(filePath) === '.json') {
fs.readFile(filePath, 'utf8', (readErr, data) => {
if (readErr) {
log.warn(`Cannot read file for backup validation: ${filePath} - ${readErr.message}`);
return;
}
try {
JSON.parse(data); // Validate JSON
performBackup(filePath, currentTime);
} catch (parseErr) {
log.warn(`Skipping backup of invalid JSON file: ${filePath} - ${parseErr.message}`);
return;
}
});
} else {
// Non-JSON files, backup normally
performBackup(filePath, currentTime);
}
}
});
}
// Track the last backup time and pending updates
let lastBackupTime = 0;
let pendingUpdates = new Map(); // filepath -> { flagged: true, lastAttempt: timestamp }
let deferredTimer = null;
// Function to check if tool is idle (stricter than "busy" check)
// Only backup when machine is truly idle - not running, manual, pausing, stopping, etc.
function isToolIdle(callback) {
const state = machine.machine.status.state;
// Only consider idle if machine state is explicitly "idle"
// This prevents backups during:
// - running: Active job execution
// - manual: Manual control (keyboard/pendant)
// - paused: Job paused (may resume soon)
// - stopped: Job stopped (transitioning)
// - probing: Probing operation
// - homing: Homing operation
const isIdle = state === "idle";
if (!isIdle) {
log.debug(`Tool not idle - state=${state}, deferring backup`);
}
callback(isIdle);
}
// Setup deferred update handling with relaxed timing
const createBackup = debounce((filePath) => {
const currentTime = Date.now();
// Check if we're within the minimum spacing window
if (currentTime - lastBackupTime < MIN_BACKUP_SPACING_MS) {
const waitTime = Math.round((MIN_BACKUP_SPACING_MS - (currentTime - lastBackupTime)) / 1000);
log.debug(`Backup request for ${filePath} deferred due to ${MIN_BACKUP_SPACING_MS/1000}s spacing constraint (${waitTime}s remaining)`);
// Flag this file for deferred backup
pendingUpdates.set(filePath, {
flagged: true,
lastAttempt: currentTime,
originalTime: pendingUpdates.get(filePath)?.originalTime || currentTime
});
// Set up or reset the deferred timer
setupDeferredBackupTimer();
return;
}
// Clear any pending flag for this file since we're processing it now
pendingUpdates.delete(filePath);
// Proceed with immediate backup
processBackup(filePath, currentTime);
}, 10);
// Set up timer to handle deferred backups (batches multi-file changes)
function setupDeferredBackupTimer() {
if (deferredTimer) {
clearTimeout(deferredTimer);
}
// Wait for batch window to accumulate changes, then process all flagged updates
deferredTimer = setTimeout(() => {
processDeferredBackups();
}, DEFERRED_BATCH_WINDOW_MS);
}
// Process all flagged deferred backups
function processDeferredBackups() {
const currentTime = Date.now();
const pendingCount = pendingUpdates.size;
if (pendingCount === 0) {
deferredTimer = null;
return;
}
log.info(`Processing ${pendingCount} deferred backup(s) after ${DEFERRED_BATCH_WINDOW_MS/1000}s batch window`);
// Calculate total wait time for first deferred update
let maxWaitTime = 0;
for (const [filePath, updateInfo] of pendingUpdates.entries()) {
if (updateInfo.flagged && updateInfo.originalTime) {
const waitTime = currentTime - updateInfo.originalTime;
if (waitTime > maxWaitTime) {
maxWaitTime = waitTime;
}
}
}
if (maxWaitTime > 0) {
log.info(`Longest deferred backup waited ${Math.round(maxWaitTime/1000)}s`);
}
for (const [filePath, updateInfo] of pendingUpdates.entries()) {
if (updateInfo.flagged) {
log.debug(`Executing deferred backup for: ${filePath}`);
processBackup(filePath, currentTime);
}
}
// Clear all pending updates
pendingUpdates.clear();
deferredTimer = null;
}
// Helper function to perform the actual backup
function performBackup(filePath, currentTime) {
const watchDir = watchDirs.find((dir) => filePath.startsWith(dir));
const relativePath = path.relative(watchDir, filePath);
const backupDir = path.join(backupBaseDir, path.basename(watchDir));
const backupPath = path.join(backupDir, relativePath);
log.debug(`Creating backup for ${filePath} at ${backupPath}`);
fs.copy(filePath, backupPath, (err) => {
if (err) {
log.error(`Error creating backup for ${filePath}:`, err);
} else {
log.debug(`Backup created for ${filePath}`);
lastBackupTime = currentTime;
// Log if this was a deferred backup
const wasPending = pendingUpdates.has(filePath);
if (wasPending) {
const originalTime = pendingUpdates.get(filePath).originalTime;
const deferDelay = Math.round((currentTime - originalTime) / 1000);
log.info(`Deferred backup completed for ${filePath} (delayed ${deferDelay}s)`);
}
}
});
}
// Function to copy existing files to the backup directory if they do not already exist
function copyExistingFiles() {
return new Promise((resolve) => {
let pendingOps = 0;
let completedOps = 0;
const results = [];
watchDirs.forEach((watchDir) => {
const backupDir = path.join(backupBaseDir, path.basename(watchDir));
log.info(`Processing watch directory: ${watchDir}`);
fs.ensureDirSync(backupDir);
if (!fs.existsSync(watchDir)) {
log.warn(`Source directory ${watchDir} does not exist, skipping copy.`);
return;
}
const files = fs.readdirSync(watchDir); // Make this synchronous
log.info(`Found ${files.length} files in ${watchDir}: ${files.join(', ')}`);
if (files.length === 0) {
return;
}
files.forEach((file) => {
const srcPath = path.join(watchDir, file);
const destPath = path.join(backupDir, file);
try {
const srcStats = fs.statSync(srcPath);
if (!srcStats.isFile()) {
return;
}
pendingOps++;
// Check if backup exists
fs.stat(destPath, (backupErr, backupStats) => {
if (backupErr) {
// No backup exists - create initial backup
log.info(`Creating initial backup for new file: ${file}`);
fs.copy(srcPath, destPath, (copyErr) => {
completedOps++;
if (copyErr) {
log.error(`Error creating initial backup for ${srcPath}: ${copyErr.message}`);
results.push({ file, status: 'error', error: copyErr.message });
} else {
log.info(`Created initial backup for ${srcPath}`);
results.push({ file, status: 'created' });
}
if (completedOps >= pendingOps) {
log.info(`Initial backup completed: ${results.length} files processed`);
resolve(results);
}
});
} else {
// Backup exists - check if source is newer
if (srcStats.mtime > backupStats.mtime) {
log.info(`Updating backup for modified file: ${file}`);
fs.copy(srcPath, destPath, (copyErr) => {
completedOps++;
if (copyErr) {
log.error(`Error updating backup for ${srcPath}: ${copyErr.message}`);
results.push({ file, status: 'error', error: copyErr.message });
} else {
log.info(`Updated backup for ${srcPath}`);
results.push({ file, status: 'updated' });
}
if (completedOps >= pendingOps) {
log.info(`Initial backup completed: ${results.length} files processed`);
resolve(results);
}
});
} else {
completedOps++;
log.debug(`Backup up-to-date for: ${file} (preserving previous version)`);
results.push({ file, status: 'up-to-date' });
if (completedOps >= pendingOps) {
log.info(`Initial backup completed: ${results.length} files processed`);
resolve(results);
}
}
}
});
} catch (statErr) {
log.debug(`Cannot read source file ${srcPath}: ${statErr.message}`);
}
});
});
// Handle case where no operations were started
if (pendingOps === 0) {
log.info("No files to backup - completing immediately");
resolve([]);
}
});
}
// Function to copy backup at the start of the session with rotation
function copyBackupAtStart(callback, engineVersion) {
const atStartBaseDir = "/opt/fabmo_backup_atStart/";
const maxBackups = 5;
fs.pathExists(backupBaseDir, (err, exists) => {
if (err) {
log.error(`Error checking existence of ${backupBaseDir}:`, err);
callback(err);
return;
}
if (!exists) {
log.info(`Backup base directory ${backupBaseDir} does not exist. Skipping backup.`);
callback();
return;
}
log.info(`Ensuring directory exists: ${atStartBaseDir}`);
fs.ensureDirSync(atStartBaseDir);
// Create timestamped subdirectory name
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hour = String(now.getHours()).padStart(2, '0');
const minute = String(now.getMinutes()).padStart(2, '0');
const second = String(now.getSeconds()).padStart(2, '0');
const timestampedDirName = `atStart_${year}_${month}_${day}_${hour}${minute}${second}`;
const newBackupDir = path.join(atStartBaseDir, timestampedDirName);
// Get existing backup directories and sort by creation time (oldest first)
fs.readdir(atStartBaseDir, (readErr, files) => {
if (readErr) {
log.warn(`Could not read existing backups directory: ${readErr.message}`);
files = []; // Continue with empty list
}
// Filter for directories that match our naming pattern and get their stats
const existingBackups = [];
let pendingStats = 0;
const processBackups = () => {
// Sort by creation time (oldest first)
existingBackups.sort((a, b) => a.mtime - b.mtime);
// Remove oldest backups if we have >= maxBackups
if (existingBackups.length >= maxBackups) {
const backupsToRemove = existingBackups.slice(0, existingBackups.length - maxBackups + 1);
log.info(`Found ${existingBackups.length} existing backups, removing ${backupsToRemove.length} oldest`);
// Remove old backups
backupsToRemove.forEach(backup => {
try {
fs.rmSync(backup.fullPath, { recursive: true, force: true });
log.info(`Removed old backup: ${backup.name}`);
} catch (rmErr) {
log.warn(`Could not remove old backup ${backup.name}: ${rmErr.message}`);
}
});
}
// Copy only config and macros directories
log.info(`Creating new timestamped backup: ${timestampedDirName}`);
// Ensure the target directory exists
fs.ensureDirSync(newBackupDir);
// Copy only the essential directories
const essentialDirs = ['config', 'macros'];
let pendingCopies = essentialDirs.length;
let copyErrors = [];
essentialDirs.forEach(dirName => {
const sourceDir = path.join(backupBaseDir, dirName);
const targetDir = path.join(newBackupDir, dirName);
// Check if source directory exists before copying
if (fs.existsSync(sourceDir)) {
log.info(`Copying ${dirName} from ${sourceDir} to ${targetDir}`);
fs.copy(sourceDir, targetDir, (copyErr) => {
pendingCopies--;
if (copyErr) {
log.error(`Error copying ${dirName} directory:`, copyErr);
copyErrors.push(copyErr);
} else {
log.info(`Successfully copied ${dirName} directory`);
}
// Check if all copies are complete
if (pendingCopies === 0) {
if (copyErrors.length > 0) {
log.error(`Errors occurred during backup creation: ${copyErrors.length} errors`);
callback(copyErrors[0]); // Return first error
} else {
log.info(`Timestamped backup created successfully at ${newBackupDir}`);
// Create a marker file with metadata
const markerInfo = {
created_at: now.toISOString(),
backup_type: "atStart_rotated",
source_dir: backupBaseDir,
fabmo_version: engineVersion || "unknown",
directories_included: essentialDirs
};
try {
fs.writeFileSync(path.join(newBackupDir, "backup_info.json"), JSON.stringify(markerInfo, null, 2));
log.debug("Created backup metadata file");
} catch (metaErr) {
log.warn("Could not create backup metadata: " + metaErr.message);
}
callback();
}
}
});
} else {
pendingCopies--;
log.warn(`Source directory ${sourceDir} does not exist, skipping`);
// Check if all copies are complete
if (pendingCopies === 0) {
if (copyErrors.length > 0) {
callback(copyErrors[0]);
} else {
log.info(`Timestamped backup created successfully at ${newBackupDir}`);
// Create a marker file with metadata
const markerInfo = {
created_at: now.toISOString(),
backup_type: "atStart_rotated",
source_dir: backupBaseDir,
fabmo_version: engineVersion || "unknown",
directories_included: essentialDirs.filter(dir => fs.existsSync(path.join(backupBaseDir, dir)))
};
try {
fs.writeFileSync(path.join(newBackupDir, "backup_info.json"), JSON.stringify(markerInfo, null, 2));
log.debug("Created backup metadata file");
} catch (metaErr) {
log.warn("Could not create backup metadata: " + metaErr.message);
}
callback();
}
}
}
});
};
if (files.length === 0) {
processBackups();
return;
}
// Check each file to see if it's a backup directory
files.forEach(file => {
if (file.startsWith('atStart_') && file.match(/atStart_\d{4}_\d{2}_\d{2}_\d{6}/)) {
const fullPath = path.join(atStartBaseDir, file);
pendingStats++;
fs.stat(fullPath, (statErr, stats) => {
pendingStats--;
if (!statErr && stats.isDirectory()) {
existingBackups.push({
name: file,
fullPath: fullPath,
mtime: stats.mtime.getTime()
});
} else if (statErr) {
log.warn(`Could not stat backup directory ${fullPath}: ${statErr.message}`);
}
if (pendingStats === 0) {
processBackups();
}
});
} else {
log.debug(`Skipping non-backup file/directory: ${file}`);
}
});
// Handle case where no valid backup directories were found
if (pendingStats === 0) {
processBackups();
}
});
});
}
// Function to create a pre-auto-profile backup
function createPreAutoProfileBackup(callback) {
const preAutoProfileBackupDir = "/opt/fabmo_backup/pre_auto_profile/";
const userConfigBackupDir = "/opt/fabmo_backup/config/";
const userMacrosBackupDir = "/opt/fabmo_backup/macros/";
const liveMacrosDir = "/opt/fabmo/macros/";
// Check if user backup data exists - if it does, ALWAYS use it
if (!fs.existsSync(userConfigBackupDir)) {
log.info("No user backup data exists - skipping pre-auto-profile backup creation");
return callback(null);
}
log.info("Creating pre-auto-profile backup from user data at: " + preAutoProfileBackupDir);
try {
// Ensure backup directory exists (this will overwrite any existing backup)
fs.ensureDirSync(preAutoProfileBackupDir + "config/");
fs.ensureDirSync(preAutoProfileBackupDir + "macros/");
// Always create fresh backup from current user data
log.info("Copying user config data from: " + userConfigBackupDir);
fs.copy(userConfigBackupDir, preAutoProfileBackupDir + "config/", function(configErr) {
if (configErr) {
log.error("Failed to copy user config backup: " + configErr.message);
return callback(configErr);
}
log.info("User config data copied successfully");
// Copy macros (with fallback)
const macrosSource = fs.existsSync(userMacrosBackupDir) ? userMacrosBackupDir : liveMacrosDir;
fs.copy(macrosSource, preAutoProfileBackupDir + "macros/", function(macrosErr) {
if (macrosErr) {
log.warn("Failed to copy macros: " + macrosErr.message);
}
// Create backup info with current timestamp
var marker = {
created_at: new Date().toISOString(),
backup_type: "pre_auto_profile",
source: "user_backup_data",
config_files_backed_up: true,
macros_backed_up: !macrosErr,
note: "Fresh backup created for this auto-profile session"
};
fs.writeFileSync(preAutoProfileBackupDir + "backup_info.json", JSON.stringify(marker, null, 2));
log.info("Fresh pre-auto-profile backup created successfully from current user data");
callback(null);
});
});
} catch (err) {
log.error("Error creating pre-auto-profile backup: " + err.message);
callback(err);
}
}
// Function to restore from pre-auto-profile backup
function restoreFromPreAutoProfileBackup(callback) {
const preAutoProfileBackupDir = "/opt/fabmo_backup/pre_auto_profile/";
const configDir = "/opt/fabmo/config/";
const macrosDir = "/opt/fabmo/macros/";
log.info("Restoring from pre-auto-profile backup...");
// Check if backup exists
if (!fs.existsSync(preAutoProfileBackupDir)) {
return callback(new Error("No pre-auto-profile backup found"));
}
try {
// Restore config directory
fs.copy(preAutoProfileBackupDir + "config/", configDir, function(configErr) {
if (configErr) {
log.error("Failed to restore config directory: " + configErr.message);
return callback(configErr);
}
// Restore macros directory
fs.copy(preAutoProfileBackupDir + "macros/", macrosDir, function(macrosErr) {
if (macrosErr) {
log.error("Failed to restore macros directory: " + macrosErr.message);
return callback(macrosErr);
}
log.info("Pre-auto-profile backup restored successfully");
callback(null);
});
});
} catch (err) {
log.error("Error restoring from pre-auto-profile backup: " + err.message);
callback(err);
}
}
// Function to check if pre-auto-profile backup exists
function hasPreAutoProfileBackup() {
const preAutoProfileBackupDir = "/opt/fabmo_backup/pre_auto_profile/";
const backupInfoFile = preAutoProfileBackupDir + "backup_info.json";
return fs.existsSync(preAutoProfileBackupDir) && fs.existsSync(backupInfoFile);
}
// Function to get pre-auto-profile backup info
function getPreAutoProfileBackupInfo(callback) {
const preAutoProfileBackupDir = "/opt/fabmo_backup/pre_auto_profile/";
const backupInfoFile = preAutoProfileBackupDir + "backup_info.json";
if (!fs.existsSync(backupInfoFile)) {
return callback(new Error("No pre-auto-profile backup info found"));
}
fs.readFile(backupInfoFile, "utf8", function(err, data) {
if (err) {
return callback(err);
}
try {
const info = JSON.parse(data);
callback(null, info);
} catch (parseErr) {
callback(parseErr);
}
});
}
// Function to start the watcher
async function startWatcher() {
// Wait for initial file copying to complete
log.info("Starting initial backup of existing files...");
try {
const results = await copyExistingFiles();
log.info(`Initial backup completed: ${results.length} operations`);
} catch (err) {
log.error("Error during initial backup:", err);
}
// Initialize watcher with awaitWriteFinish
const watcher = chokidar.watch(watchDirs, {
persistent: true,
ignoreInitial: false,
awaitWriteFinish: {
stabilityThreshold: 500, // Adjust this value as needed
pollInterval: 50,
},
});
// Watch for file changes
watcher
.on("add", (filePath) => {
//log.info(`File added: ${filePath}`);
createBackup(filePath);
})
.on("change", (filePath) => {
//log.info(`File changed: ${filePath}`);
createBackup(filePath);
});
log.info(`Watching for changes in ${watchDirs.join(", ")}`);
// Function to gracefully shut down the watcher
function shutdownWatcher() {
log.info("Shutting down file watcher...");
watcher
.close()
.then(() => {
log.info("File watcher shut down successfully.");
process.exit(0);
})
.catch((err) => {
log.error("Error shutting down file watcher:", err);
process.exit(1);
});
}
// Handle process events for graceful shutdown
process.on("exit", shutdownWatcher);
process.on("SIGINT", shutdownWatcher);
process.on("SIGTERM", shutdownWatcher);
process.on("uncaughtException", (err) => {
log.error("Uncaught exception:", err);
shutdownWatcher();
});
}
// Enhanced shutdown handling to process pending backups
function shutdownWatcher() {
log.info("Shutting down watcher...");
// Process any remaining deferred backups before shutdown
if (pendingUpdates.size > 0) {
log.info(`Processing ${pendingUpdates.size} pending backup(s) before shutdown`);
processDeferredBackups();
}
if (deferredTimer) {
clearTimeout(deferredTimer);
}
log.info("Watcher shutdown complete");
}
// Add status reporting for debugging
function getBackupStatus() {
return {
lastBackupTime: new Date(lastBackupTime).toISOString(),
pendingUpdates: Array.from(pendingUpdates.entries()).map(([path, info]) => ({
path: path,
flagged: info.flagged,
waitingSeconds: Math.round((Date.now() - info.originalTime) / 1000)
})),
deferredTimerActive: !!deferredTimer
};
}
// Clean up pre-auto-profile backup (when user dismisses restore)
function cleanupPreAutoProfileBackup(callback) {
const backupDir = '/opt/fabmo_backup/pre_auto_profile';
if (!fs.existsSync(backupDir)) {
return callback(null);
}
try {
// Remove the entire directory
fs.rmSync(backupDir, { recursive: true, force: true });
log.info("Pre-auto-profile backup directory removed");
callback(null);
} catch (err) {
log.error("Error removing pre-auto-profile backup: " + err.message);
callback(err);
}
}
// Export the status function for debugging
module.exports = {
startWatcher,
copyBackupAtStart,
createPreAutoProfileBackup,
restoreFromPreAutoProfileBackup,
hasPreAutoProfileBackup,
getPreAutoProfileBackupInfo,
getBackupStatus: getBackupStatus,
cleanupPreAutoProfileBackup: cleanupPreAutoProfileBackup
};