-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
5304 lines (4410 loc) · 169 KB
/
Copy pathserver.js
File metadata and controls
5304 lines (4410 loc) · 169 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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ScottiBYTE Incus Backup
// Install: npm install express multer
// Run: node --check server.js && node server.js
const express = require('express');
const multer = require('multer');
const { execFile } = require('child_process');
const fs = require('fs');
const path = require('path');
const app = express();
const APP_VERSION = process.env.APP_VERSION || process.env.npm_package_version || 'development';
const PORT = Number(process.env.PORT || 3030);
const BACKUP_DIR = process.env.INCUS_BACKUP_DIR || path.join(__dirname, 'backups');
const UPLOAD_DIR = path.join(BACKUP_DIR, '.uploads');
const METADATA_FILE = path.join(BACKUP_DIR, 'metadata.json');
const SETTINGS_FILE = path.join(BACKUP_DIR, 'settings.json');
const INVENTORY_CACHE_MS = Number(process.env.INCUS_INVENTORY_CACHE_MS || 30000);
const COMPLETED_JOB_TTL_MS = Number(process.env.INCUS_COMPLETED_JOB_TTL_MS || 180000);
const SCHEDULER_INTERVAL_MS = Number(process.env.INCUS_SCHEDULER_INTERVAL_MS || 60000);
const SCHEDULED_BACKUP_CONCURRENCY = Math.max(1, Number(process.env.INCUS_SCHEDULED_BACKUP_CONCURRENCY || 1));
const SELF_INSTANCE_NAME = process.env.INCUS_BACKUP_SELF_INSTANCE || 'IncusBackup';
fs.mkdirSync(BACKUP_DIR, { recursive: true });
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
app.use(express.json({ limit: '4mb' }));
app.use(express.urlencoded({ extended: true }));
app.use('/backups', express.static(BACKUP_DIR));
const upload = multer({ dest: UPLOAD_DIR });
const jobs = new Map();
const remoteInstanceCache = new Map();
let systemEvents = [];
let schedulerTimer = null;
let schedulerBusy = false;
let scheduledBackupRunning = 0;
const scheduledBackupQueue = [];
const scheduledQueuedKeys = new Set();
const scheduledRunningKeys = new Set();
function runIncus(args, options = {}) {
return new Promise((resolve, reject) => {
execFile('incus', args, {
timeout: options.timeout === 0 ? 0 : options.timeout || 30000,
maxBuffer: options.maxBuffer || 1024 * 1024 * 50,
}, (error, stdout, stderr) => {
if (error) {
reject({ message: error.message, stdout, stderr, code: error.code });
return;
}
resolve((stdout || '').trim());
});
});
}
function safeName(value) {
return String(value || '')
.trim()
.replace(/[^a-zA-Z0-9_.-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
}
function formatBytes(bytes) {
if (!bytes || bytes <= 0) return '0 B';
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
return (bytes / Math.pow(1024, index)).toFixed(index === 0 ? 0 : 1) + ' ' + units[index];
}
function formatDuration(seconds) {
seconds = Math.max(0, Math.floor(Number(seconds || 0)));
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
return String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0');
}
function getFileSizeBytes(filePath) {
try {
if (!filePath || !fs.existsSync(filePath)) return 0;
return fs.statSync(filePath).size;
} catch {
return 0;
}
}
function backupFileName(remote, instanceName) {
const now = new Date().toISOString().replace(/[:.]/g, '-');
return safeName(remote) + '--' + safeName(instanceName) + '--' + now + '.tar.gz';
}
function addSystemEvent(level, message) {
systemEvents.unshift({
level,
message,
at: new Date().toISOString(),
});
systemEvents = systemEvents.slice(0, 50);
}
function readMetadata() {
try {
if (!fs.existsSync(METADATA_FILE)) return { backups: {} };
const parsed = JSON.parse(fs.readFileSync(METADATA_FILE, 'utf8'));
if (!parsed.backups) parsed.backups = {};
return parsed;
} catch {
return { backups: {} };
}
}
function writeMetadata(metadata) {
fs.writeFileSync(METADATA_FILE, JSON.stringify(metadata, null, 2));
}
function defaultSettings() {
return { instancePolicies: {} };
}
function readSettings() {
try {
if (!fs.existsSync(SETTINGS_FILE)) return defaultSettings();
const parsed = JSON.parse(fs.readFileSync(SETTINGS_FILE, 'utf8'));
return {
...defaultSettings(),
...parsed,
instancePolicies: parsed.instancePolicies || {},
};
} catch {
return defaultSettings();
}
}
function writeSettings(settings) {
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2));
}
function instancePolicyKey(remote, instance) {
return String(remote || '') + ':' + String(instance || '');
}
function isSelfInstance(instance) {
return String(instance || '').toLowerCase() === String(SELF_INSTANCE_NAME || 'IncusBackup').toLowerCase();
}
function safeBackupModeForInstance(instance, requestedMode) {
const mode = ['live', 'stop-restart'].includes(String(requestedMode || '')) ? String(requestedMode) : 'live';
if (isSelfInstance(instance) && mode === 'stop-restart') {
addSystemEvent('warn', 'Self-protection: forced ' + SELF_INSTANCE_NAME + ' backup mode to Live to avoid stopping the backup application.');
return 'live';
}
return mode;
}
function pruneStaleInstancePolicies(settings, instances) {
const activeKeys = new Set(instances.map((item) => instancePolicyKey(item.remote, item.name)));
for (const key of Object.keys(settings.instancePolicies || {})) {
if (!activeKeys.has(key)) delete settings.instancePolicies[key];
}
return settings;
}
function updateBackupMetadata(file, patch) {
const metadata = readMetadata();
metadata.backups[file] = {
...(metadata.backups[file] || {}),
...patch,
file,
updatedAt: new Date().toISOString(),
};
writeMetadata(metadata);
}
function removeBackupMetadata(file) {
const metadata = readMetadata();
delete metadata.backups[file];
writeMetadata(metadata);
}
function getAgeInfo(modifiedIso) {
const ageDays = Math.floor((Date.now() - new Date(modifiedIso).getTime()) / 86400000);
let status = 'fresh';
if (ageDays > 30) status = 'old';
else if (ageDays > 7) status = 'aging';
return { ageDays, status };
}
function getBackupFiles() {
const metadata = readMetadata();
return fs.readdirSync(BACKUP_DIR)
.filter((file) => file.endsWith('.tar.gz'))
.map((file) => {
const fullPath = path.join(BACKUP_DIR, file);
const stat = fs.statSync(fullPath);
const modified = stat.mtime.toISOString();
const age = getAgeInfo(modified);
return {
name: file,
sizeBytes: stat.size,
size: formatBytes(stat.size),
modified,
ageDays: age.ageDays,
ageStatus: age.status,
url: '/backups/' + encodeURIComponent(file),
metadata: metadata.backups[file] || {},
};
})
.sort((a, b) => new Date(b.modified) - new Date(a.modified));
}
function createJob(type, title, details = {}) {
const id = Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
const job = {
id,
type,
title,
status: 'running',
phase: 'queued',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
completedAt: null,
message: 'Queued',
bytesWritten: 0,
bytesWrittenHuman: '0 B',
elapsedSeconds: 0,
elapsedHuman: '00:00:00',
result: null,
error: null,
...details,
};
jobs.set(id, job);
addSystemEvent('info', title + ' queued');
return job;
}
function updateJob(id, patch) {
const job = jobs.get(id);
if (!job) return;
const previousStatus = job.status;
Object.assign(job, patch, { updatedAt: new Date().toISOString() });
if (patch.status === 'completed' && previousStatus !== 'completed') {
job.completedAt = new Date().toISOString();
addSystemEvent('success', job.message || job.title + ' completed');
}
if (patch.status === 'failed' && previousStatus !== 'failed') {
job.completedAt = new Date().toISOString();
addSystemEvent('error', (job.title || 'Job') + ' failed: ' + (job.error || job.message || 'Unknown error'));
}
}
function cleanupExpiredJobs() {
const now = Date.now();
for (const [id, job] of jobs.entries()) {
if (job.status === 'completed' && job.completedAt) {
const age = now - new Date(job.completedAt).getTime();
if (age > COMPLETED_JOB_TTL_MS) jobs.delete(id);
}
}
}
function recentJobs() {
cleanupExpiredJobs();
return Array.from(jobs.values())
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
.slice(0, 100);
}
async function getRemotes() {
const output = await runIncus(['remote', 'list', '--format', 'json'], { timeout: 10000 });
const data = JSON.parse(output || '{}');
const remotes = [];
for (const [name, info] of Object.entries(data)) {
const protocol = info.Protocol || info.protocol || '';
const addr = info.Addr || info.addr || '';
const isPublic = Boolean(info.Public || info.public);
if (protocol !== 'incus') continue;
if (addr === 'unix://') continue;
if (isPublic) continue;
if (['images', 'ubuntu', 'ubuntu-daily'].includes(name)) continue;
remotes.push({
name,
addr,
protocol,
authType: info.AuthType || info.authType || '',
project: info.Project || info.project || 'default',
public: isPublic,
static: Boolean(info.Static || info.static),
global: Boolean(info.Global || info.global),
});
}
return remotes.sort((a, b) => a.name.localeCompare(b.name));
}
async function listInstancesForRemote(remoteName) {
const cached = remoteInstanceCache.get(remoteName);
if (cached && Date.now() - cached.createdAt < INVENTORY_CACHE_MS) {
return cached.instances;
}
console.log('Scanning remote:', remoteName);
const output = await runIncus(
['query', remoteName + ':/1.0/instances?recursion=1'],
{ timeout: 30000, maxBuffer: 1024 * 1024 * 50 }
);
const rawInstances = JSON.parse(output || '[]');
const mapped = rawInstances.map((item) => ({
remote: remoteName,
name: item.name || '',
status: item.status || 'Unknown',
type: item.type || 'instance',
architecture: item.architecture || '',
created_at: item.created_at || '',
last_used_at: item.last_used_at || '',
location: item.location || '',
project: item.project || 'default',
profiles: Array.isArray(item.profiles) ? item.profiles : [],
stateful: Boolean(item.stateful),
}));
remoteInstanceCache.set(remoteName, { createdAt: Date.now(), instances: mapped });
return mapped;
}
function parseVersionText(output) {
const text = String(output || '').replaceAll('\r', '');
for (const line of text.split('\n')) {
const lower = line.toLowerCase();
if (lower.includes('server version:')) return line.split(':').slice(1).join(':').trim();
if (lower.includes('server_version:')) return line.split(':').slice(1).join(':').replaceAll('"', '').trim();
}
return 'version unknown';
}
async function getRemoteServerInfo(remoteName) {
try {
const output = await runIncus(['version', remoteName + ':'], {
timeout: 8000,
maxBuffer: 1024 * 1024 * 5,
});
const version = parseVersionText(output);
if (version !== 'version unknown') return { serverVersion: version, apiStatus: 'ok' };
} catch {}
try {
const output = await runIncus(['info', remoteName + ':', '--format', 'json'], {
timeout: 8000,
maxBuffer: 1024 * 1024 * 5,
});
const parsed = JSON.parse(output || '{}');
const environment = parsed.environment || (parsed.metadata && parsed.metadata.environment) || {};
const version =
environment.server_version ||
environment.serverVersion ||
parsed.server_version ||
parsed.serverVersion ||
(parsed.metadata && parsed.metadata.server_version) ||
'version unknown';
if (version !== 'version unknown') return { serverVersion: version, apiStatus: 'ok' };
} catch {}
try {
const output = await runIncus(['query', remoteName + ':/1.0'], {
timeout: 8000,
maxBuffer: 1024 * 1024 * 5,
});
const parsed = JSON.parse(output || '{}');
const metadata = parsed.metadata || {};
const environment = metadata.environment || {};
return {
serverVersion:
environment.server_version ||
environment.serverVersion ||
metadata.server_version ||
metadata.serverVersion ||
metadata.api_version ||
'version unknown',
apiStatus: parsed.status || 'ok',
};
} catch (err) {
return {
serverVersion: 'offline',
apiStatus: 'unreachable',
error: err.stderr || err.message,
};
}
}
async function checkRemote(remote) {
const started = Date.now();
try {
const info = await getRemoteServerInfo(remote.name);
if (info.apiStatus === 'unreachable') throw new Error(info.error || 'Remote unreachable');
const instances = await listInstancesForRemote(remote.name);
const containerCount = instances.filter((item) => item.type === 'container').length;
const vmCount = instances.filter((item) => item.type === 'virtual-machine').length;
const runningCount = instances.filter((item) => item.status === 'Running').length;
const stoppedCount = instances.filter((item) => item.status === 'Stopped').length;
return {
...remote,
reachable: true,
latencyMs: Date.now() - started,
serverVersion: info.serverVersion,
apiStatus: info.apiStatus,
instanceCount: instances.length,
containerCount,
vmCount,
runningCount,
stoppedCount,
error: null,
};
} catch (err) {
return {
...remote,
reachable: false,
latencyMs: Date.now() - started,
serverVersion: 'offline',
apiStatus: 'unreachable',
instanceCount: 0,
containerCount: 0,
vmCount: 0,
runningCount: 0,
stoppedCount: 0,
error: err.stderr || err.message,
};
}
}
async function getInstanceStatus(remote, instance) {
try {
const output = await runIncus(
['query', remote + ':/1.0/instances/' + encodeURIComponent(instance) + '/state'],
{ timeout: 10000, maxBuffer: 1024 * 1024 * 5 }
);
const parsed = JSON.parse(output || '{}');
return parsed.status || (parsed.metadata && parsed.metadata.status) || 'Unknown';
} catch {
return 'Unknown';
}
}
async function instanceExists(remote, instance) {
try {
await runIncus(['info', remote + ':' + instance], {
timeout: 15000,
maxBuffer: 1024 * 1024 * 10,
});
return true;
} catch {
return false;
}
}
async function stopInstance(remote, instance, jobId) {
updateJob(jobId, {
phase: 'stopping',
message: 'Stopping instance before export: ' + remote + ':' + instance,
});
await runIncus(['stop', remote + ':' + instance, '--timeout', '120'], {
timeout: 180000,
maxBuffer: 1024 * 1024 * 10,
});
remoteInstanceCache.delete(remote);
updateJob(jobId, {
phase: 'stopped',
message: 'Instance stopped. Starting export archive: ' + remote + ':' + instance,
});
}
async function startInstance(remote, instance, jobId) {
updateJob(jobId, {
phase: 'restarting',
message: 'Restarting instance after export: ' + remote + ':' + instance,
});
await runIncus(['start', remote + ':' + instance], {
timeout: 120000,
maxBuffer: 1024 * 1024 * 10,
});
remoteInstanceCache.delete(remote);
}
function normalizeServerSchedule(schedule) {
schedule = schedule || {};
const rawFrequency = ['off', 'hourly', 'daily', 'weekly', 'monthly'].includes(schedule.frequency)
? schedule.frequency
: 'off';
const enabled = Boolean(schedule.enabled) && rawFrequency !== 'off';
const frequency = enabled ? rawFrequency : 'off';
return {
enabled,
frequency,
everyHours: Math.max(1, Math.min(168, Number(schedule.everyHours || 24))),
time: /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(String(schedule.time || '')) ? String(schedule.time) : '02:00',
dayOfWeek: Math.max(0, Math.min(6, Number(schedule.dayOfWeek ?? 0))),
dayOfMonth: Math.max(1, Math.min(31, Number(schedule.dayOfMonth || 1))),
retentionCount: Math.max(1, Math.min(365, Number(schedule.retentionCount || 7))),
runMissed: Boolean(schedule.runMissed),
lastRunSlot: String(schedule.lastRunSlot || ''),
lastQueuedAt: schedule.lastQueuedAt || null,
lastStartedAt: schedule.lastStartedAt || null,
lastFinishedAt: schedule.lastFinishedAt || null,
lastStatus: schedule.lastStatus || null,
lastError: schedule.lastError || null,
lastJobId: schedule.lastJobId || null,
};
}
function schedulerPad(value) {
return String(value).padStart(2, '0');
}
function schedulerYmd(date) {
return date.getFullYear() + '-' + schedulerPad(date.getMonth() + 1) + '-' + schedulerPad(date.getDate());
}
function schedulerTimeParts(value) {
const parts = String(value || '02:00').split(':');
return [
Math.max(0, Math.min(23, Number(parts[0] || 2))),
Math.max(0, Math.min(59, Number(parts[1] || 0))),
];
}
function schedulerMinuteDate(date) {
const d = new Date(date);
d.setSeconds(0, 0);
return d;
}
function schedulerLastDayOfMonth(year, monthIndex) {
return new Date(year, monthIndex + 1, 0).getDate();
}
function schedulerSlotKey(schedule, date) {
const d = schedulerMinuteDate(date);
if (schedule.frequency === 'hourly') {
return 'hourly:' + schedulerYmd(d) + 'T' + schedulerPad(d.getHours());
}
const [h, m] = schedulerTimeParts(schedule.time);
return schedule.frequency + ':' + schedulerYmd(d) + 'T' + schedulerPad(h) + ':' + schedulerPad(m);
}
function schedulerBuildDateLike(baseDate, hour, minute) {
const d = new Date(baseDate);
d.setHours(hour, minute, 0, 0);
return d;
}
function schedulerDueNow(schedule, now) {
const current = schedulerMinuteDate(now);
if (!schedule.enabled || schedule.frequency === 'off') return null;
if (schedule.frequency === 'hourly') {
if (current.getMinutes() !== 0) return null;
if ((current.getHours() % schedule.everyHours) !== 0) return null;
return { date: current, slotKey: schedulerSlotKey(schedule, current), missed: false };
}
const [hour, minute] = schedulerTimeParts(schedule.time);
if (current.getHours() !== hour || current.getMinutes() !== minute) return null;
if (schedule.frequency === 'daily') {
return { date: current, slotKey: schedulerSlotKey(schedule, current), missed: false };
}
if (schedule.frequency === 'weekly') {
if (current.getDay() !== schedule.dayOfWeek) return null;
return { date: current, slotKey: schedulerSlotKey(schedule, current), missed: false };
}
if (schedule.frequency === 'monthly') {
const targetDay = Math.min(schedule.dayOfMonth, schedulerLastDayOfMonth(current.getFullYear(), current.getMonth()));
if (current.getDate() !== targetDay) return null;
return { date: current, slotKey: schedulerSlotKey(schedule, current), missed: false };
}
return null;
}
function schedulerMostRecentDue(schedule, now) {
const current = schedulerMinuteDate(now);
if (!schedule.enabled || schedule.frequency === 'off') return null;
if (schedule.frequency === 'hourly') {
const candidate = new Date(current);
candidate.setMinutes(0, 0, 0);
while ((candidate.getHours() % schedule.everyHours) !== 0) {
candidate.setHours(candidate.getHours() - 1);
}
return { date: candidate, slotKey: schedulerSlotKey(schedule, candidate), missed: true };
}
const [hour, minute] = schedulerTimeParts(schedule.time);
if (schedule.frequency === 'daily') {
const candidate = schedulerBuildDateLike(current, hour, minute);
if (candidate > current) candidate.setDate(candidate.getDate() - 1);
return { date: candidate, slotKey: schedulerSlotKey(schedule, candidate), missed: true };
}
if (schedule.frequency === 'weekly') {
const candidate = schedulerBuildDateLike(current, hour, minute);
const daysBack = (candidate.getDay() - schedule.dayOfWeek + 7) % 7;
candidate.setDate(candidate.getDate() - daysBack);
if (candidate > current) candidate.setDate(candidate.getDate() - 7);
return { date: candidate, slotKey: schedulerSlotKey(schedule, candidate), missed: true };
}
if (schedule.frequency === 'monthly') {
let candidate = new Date(current);
const targetDay = Math.min(schedule.dayOfMonth, schedulerLastDayOfMonth(candidate.getFullYear(), candidate.getMonth()));
candidate.setDate(targetDay);
candidate.setHours(hour, minute, 0, 0);
if (candidate > current) {
candidate = new Date(current.getFullYear(), current.getMonth() - 1, 1, hour, minute, 0, 0);
const previousTargetDay = Math.min(schedule.dayOfMonth, schedulerLastDayOfMonth(candidate.getFullYear(), candidate.getMonth()));
candidate.setDate(previousTargetDay);
}
return { date: candidate, slotKey: schedulerSlotKey(schedule, candidate), missed: true };
}
return null;
}
function schedulerMissWindowMs(schedule) {
if (schedule.frequency === 'hourly') return Math.max(2, schedule.everyHours + 1) * 3600000;
if (schedule.frequency === 'daily') return 36 * 3600000;
if (schedule.frequency === 'weekly') return 8 * 86400000;
if (schedule.frequency === 'monthly') return 32 * 86400000;
return 0;
}
function schedulerDueSlot(schedule, now) {
const due = schedulerDueNow(schedule, now);
if (due && schedule.lastRunSlot !== due.slotKey) return due;
if (!schedule.runMissed) return null;
const missed = schedulerMostRecentDue(schedule, now);
if (!missed) return null;
if (schedule.lastRunSlot === missed.slotKey) return null;
const age = schedulerMinuteDate(now).getTime() - missed.date.getTime();
if (age <= 0) return null;
if (age > schedulerMissWindowMs(schedule)) return null;
return missed;
}
function schedulerPatchSchedule(remote, instance, patch) {
const settings = readSettings();
const key = instancePolicyKey(remote, instance);
const existing = (settings.instancePolicies || {})[key];
if (!existing) return;
settings.instancePolicies[key] = {
...existing,
remote,
instance,
schedule: {
...(existing.schedule || {}),
...patch,
schedulerUpdatedAt: new Date().toISOString(),
},
updatedAt: new Date().toISOString(),
};
writeSettings(settings);
}
function scheduledJobAlreadyRunning(remote, instance) {
return Array.from(jobs.values()).some((job) =>
job.status === 'running' &&
job.sourceRemote === remote &&
job.sourceInstance === instance
);
}
function scheduledBackupKey(remote, instance) {
return instancePolicyKey(remote, instance);
}
function queueScheduledBackup(remote, instance, policy, schedule, due) {
const key = scheduledBackupKey(remote, instance);
if (scheduledQueuedKeys.has(key) || scheduledRunningKeys.has(key) || scheduledJobAlreadyRunning(remote, instance)) {
return;
}
const requestedBackupMode = ['live', 'stop-restart'].includes(policy.backupMode) ? policy.backupMode : 'live';
const backupMode = safeBackupModeForInstance(instance, requestedBackupMode);
const exportScope = ['instance-only', 'include-snapshots'].includes(policy.exportScope) ? policy.exportScope : 'instance-only';
scheduledQueuedKeys.add(key);
scheduledBackupQueue.push({
key,
remote,
instance,
backupMode,
exportScope,
retentionCount: schedule.retentionCount,
slotKey: due.slotKey,
missed: Boolean(due.missed),
});
schedulerPatchSchedule(remote, instance, {
lastRunSlot: due.slotKey,
lastQueuedAt: new Date().toISOString(),
lastStatus: 'queued',
lastError: null,
});
addSystemEvent(
'info',
'Scheduled backup queued for ' + remote + ':' + instance + (due.missed ? ' (missed run)' : '')
);
processScheduledBackupQueue();
}
async function waitForScheduledJob(jobId) {
return new Promise((resolve) => {
const timer = setInterval(() => {
const job = jobs.get(jobId);
if (!job) return;
if (job.status !== 'running') {
clearInterval(timer);
resolve(job);
}
}, 5000);
});
}
function enforceScheduledRetention(remote, instance, retentionCount) {
retentionCount = Math.max(1, Math.min(365, Number(retentionCount || 7)));
const files = getBackupFiles()
.filter((file) => {
const m = file.metadata || {};
return m.sourceRemote === remote && m.sourceInstance === instance;
})
.sort((a, b) => new Date(b.modified) - new Date(a.modified));
const remove = files.slice(retentionCount);
for (const file of remove) {
const fullPath = path.join(BACKUP_DIR, file.name);
try {
if (fs.existsSync(fullPath)) fs.unlinkSync(fullPath);
removeBackupMetadata(file.name);
addSystemEvent('info', 'Retention removed old backup ' + file.name);
} catch (err) {
addSystemEvent('error', 'Retention failed for ' + file.name + ': ' + err.message);
}
}
}
function processScheduledBackupQueue() {
while (scheduledBackupRunning < SCHEDULED_BACKUP_CONCURRENCY && scheduledBackupQueue.length > 0) {
const task = scheduledBackupQueue.shift();
scheduledQueuedKeys.delete(task.key);
scheduledRunningKeys.add(task.key);
scheduledBackupRunning += 1;
(async () => {
let jobId = null;
try {
const response = await fetch('http://127.0.0.1:' + PORT + '/api/export', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
remote: task.remote,
instance: task.instance,
backupMode: task.backupMode,
exportScope: task.exportScope,
}),
});
const data = await response.json().catch(() => ({}));
if (!response.ok || !data.ok) {
throw new Error(data.error || ('Scheduled export request failed with HTTP ' + response.status));
}
jobId = data.jobId;
schedulerPatchSchedule(task.remote, task.instance, {
lastStartedAt: new Date().toISOString(),
lastStatus: 'running',
lastError: null,
lastJobId: jobId,
});
addSystemEvent('info', 'Scheduled backup started for ' + task.remote + ':' + task.instance);
const job = await waitForScheduledJob(jobId);
schedulerPatchSchedule(task.remote, task.instance, {
lastFinishedAt: new Date().toISOString(),
lastStatus: job.status,
lastError: job.status === 'failed' ? (job.error || job.message || 'Scheduled backup failed') : null,
lastJobId: jobId,
});
if (job.status === 'completed') {
enforceScheduledRetention(task.remote, task.instance, task.retentionCount);
}
} catch (err) {
schedulerPatchSchedule(task.remote, task.instance, {
lastFinishedAt: new Date().toISOString(),
lastStatus: 'failed',
lastError: err.message || String(err),
lastJobId: jobId,
});
addSystemEvent('error', 'Scheduled backup failed for ' + task.remote + ':' + task.instance + ': ' + (err.message || String(err)));
} finally {
scheduledRunningKeys.delete(task.key);
scheduledBackupRunning = Math.max(0, scheduledBackupRunning - 1);
processScheduledBackupQueue();
}
})();
}
}
async function schedulerTick() {
if (schedulerBusy) return;
schedulerBusy = true;
try {
const settings = readSettings();
const now = new Date();
for (const [key, policy] of Object.entries(settings.instancePolicies || {})) {
const splitAt = key.indexOf(':');
const remote = policy.remote || (splitAt >= 0 ? key.slice(0, splitAt) : '');
const instance = policy.instance || (splitAt >= 0 ? key.slice(splitAt + 1) : '');
if (!remote || !instance) continue;
const schedule = normalizeServerSchedule(policy.schedule);
if (!schedule.enabled) continue;
const due = schedulerDueSlot(schedule, now);
if (!due) continue;
queueScheduledBackup(remote, instance, policy, schedule, due);
}
} catch (err) {
addSystemEvent('error', 'Scheduler tick failed: ' + (err.message || String(err)));
} finally {
schedulerBusy = false;
}
}
function startScheduler() {
if (schedulerTimer) return;
schedulerTimer = setInterval(schedulerTick, SCHEDULER_INTERVAL_MS);
setTimeout(() => {
schedulerTick();
}, 5000);
console.log(
'Scheduled backup engine active. Interval ' +
Math.round(SCHEDULER_INTERVAL_MS / 1000) +
' seconds. Concurrency ' +
SCHEDULED_BACKUP_CONCURRENCY +
'.'
);
addSystemEvent('info', 'Scheduled backup engine started');
}
app.get('/api/health', async (req, res) => {
try {
const version = await runIncus(['version'], { timeout: 10000 });
const remotes = await getRemotes();
const checked = [];
for (const remote of remotes) checked.push(await checkRemote(remote));
const backupFiles = getBackupFiles();
const currentJobs = recentJobs();
const totals = {
remotes: checked.length,
reachableRemotes: checked.filter((remote) => remote.reachable).length,
instances: checked.reduce((sum, remote) => sum + (remote.instanceCount || 0), 0),
containers: checked.reduce((sum, remote) => sum + (remote.containerCount || 0), 0),
virtualMachines: checked.reduce((sum, remote) => sum + (remote.vmCount || 0), 0),
running: checked.reduce((sum, remote) => sum + (remote.runningCount || 0), 0),
stopped: checked.reduce((sum, remote) => sum + (remote.stoppedCount || 0), 0),
backups: backupFiles.length,
activeJobs: currentJobs.filter((job) => job.status === 'running').length,
failedJobs: currentJobs.filter((job) => job.status === 'failed').length,
};
res.json({ ok: true, version: APP_VERSION, incus: version, backupDir: BACKUP_DIR, remotes: checked, totals });
} catch (err) {
res.status(500).json({ ok: false, error: err.stderr || err.message });
}
});
app.get('/api/instances', async (req, res) => {
try {
const remotes = await getRemotes();
const instances = [];
const errors = [];
for (const remote of remotes) {
try {
instances.push(...await listInstancesForRemote(remote.name));
} catch (err) {
errors.push({ remote: remote.name, error: err.stderr || err.message });
}
}
instances.sort((a, b) => a.remote.localeCompare(b.remote) || a.name.localeCompare(b.name));
const settings = pruneStaleInstancePolicies(readSettings(), instances);
writeSettings(settings);
res.json({ ok: true, remotes, instances, errors, settings });
} catch (err) {
res.status(500).json({ ok: false, error: err.stderr || err.message });
}
});
app.get('/api/backups', (req, res) => {
try {
res.json({ ok: true, backupDir: BACKUP_DIR, files: getBackupFiles() });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
app.get('/api/jobs', (req, res) => {
res.json({ ok: true, jobs: recentJobs(), events: systemEvents });
});
app.get('/api/settings', (req, res) => {
res.json({ ok: true, settings: readSettings() });
});
app.post('/api/settings/instance-policy', (req, res) => {
const remote = safeName(req.body.remote);
const instance = safeName(req.body.instance);
const backupMode = String(req.body.backupMode || '');
const exportScope = String(req.body.exportScope || '');
if (!remote) return res.status(400).json({ ok: false, error: 'Missing remote name.' });
if (!instance) return res.status(400).json({ ok: false, error: 'Missing instance name.' });