forked from marcpope/borgbackupserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscheduler.php
More file actions
2447 lines (2207 loc) · 112 KB
/
scheduler.php
File metadata and controls
2447 lines (2207 loc) · 112 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
#!/usr/bin/env php
<?php
date_default_timezone_set('UTC');
/**
* Scheduler CLI - Run via cron every minute:
* * * * * * php /path/to/borgbackupserver/scheduler.php
*/
require_once __DIR__ . '/vendor/autoload.php';
use BBS\Core\Config;
use BBS\Services\SchedulerService;
use BBS\Services\QueueManager;
use BBS\Services\NotificationService;
use BBS\Services\UpdateService;
use BBS\Services\RemoteSshService;
Config::load();
$db = \BBS\Core\Database::getInstance();
// Step 1: Mark agents offline if no heartbeat in 3x poll interval
$pollInterval = $db->fetchOne("SELECT `value` FROM settings WHERE `key` = 'agent_poll_interval'");
$threshold = ((int)($pollInterval['value'] ?? 30)) * 3;
$now = date('Y-m-d H:i:s');
$cutoff = date('Y-m-d H:i:s', time() - $threshold);
$stale = $db->query(
"UPDATE agents SET status = 'offline'
WHERE status = 'online'
AND last_heartbeat IS NOT NULL
AND last_heartbeat < ?",
[$cutoff]
);
if ($stale->rowCount() > 0) {
echo date('Y-m-d H:i:s') . " Marked {$stale->rowCount()} agent(s) offline (no heartbeat in {$threshold}s)\n";
}
// Hysteresis on agent_offline notifications: only fire once the agent has
// been continuously offline for >= agent_offline_notify_minutes (default 5).
// BBS isn't a real-time monitoring system — sub-minute detection is too
// noisy on residential ISPs and laptops, where short network blips cause
// status to flap several times an hour. The agent's *status* still flips
// to offline at the 90s threshold above (so dashboards and queues react
// quickly), but the user-visible notification + push/email dispatch waits
// for the longer threshold. Only fires once per outage by checking for
// an unresolved agent_offline notification for the agent.
$notifyMinutes = max(1, (int) ($db->fetchOne("SELECT `value` FROM settings WHERE `key` = 'agent_offline_notify_minutes'")['value'] ?? 5));
$notifyThresholdSec = $notifyMinutes * 60;
$notifyCutoff = date('Y-m-d H:i:s', time() - $notifyThresholdSec);
$candidates = $db->fetchAll(
"SELECT a.id, a.name
FROM agents a
LEFT JOIN notifications n
ON n.type = 'agent_offline'
AND n.agent_id = a.id
AND n.resolved_at IS NULL
WHERE a.status = 'offline'
AND a.last_heartbeat IS NOT NULL
AND a.last_heartbeat < ?
AND n.id IS NULL",
[$notifyCutoff]
);
if (!empty($candidates)) {
$notificationService = new NotificationService();
foreach ($candidates as $offAgent) {
$notificationService->notify(
'agent_offline',
$offAgent['id'],
null,
"Client \"{$offAgent['name']}\" has been offline for at least {$notifyMinutes} minute" . ($notifyMinutes === 1 ? '' : 's'),
'warning'
);
}
}
// Step 2: Fail jobs for agents that are offline (sent or running only)
// Queued jobs are left alone — the agent may come back online and pick them up.
// Excludes:
// - Server-side tasks (prune, compact, catalog, etc.) — run by the scheduler, don't need the agent.
// - Management tasks (update_borg, update_agent) — these should wait for the
// agent to come back online and pick them up, not fail at 5am because the
// client's laptop was asleep (#144). They get their own grace-period sweep
// in Step 2c below.
$staleJobs = $db->fetchAll("
SELECT bj.id, bj.agent_id, bj.task_type, bj.backup_plan_id, bj.repository_id,
bj.status, bj.retry_count, a.name as agent_name
FROM backup_jobs bj
JOIN agents a ON a.id = bj.agent_id
WHERE bj.status IN ('sent', 'running')
AND a.status = 'offline'
AND bj.task_type NOT IN ('prune', 'compact', 's3_sync', 's3_restore', 'repo_check', 'repo_repair', 'break_lock', 'catalog_sync', 'catalog_rebuild', 'catalog_rebuild_full', 'archive_delete', 'update_borg', 'update_agent')
");
// Auto-retry settings (#249). Only kicks in for offline-induced backup
// failures; real errors (borg path missing, encryption failed, etc.) are
// reported by the agent via /api/agent/status and never enter this sweep.
$autoRetryEnabled = (($db->fetchOne("SELECT `value` FROM settings WHERE `key` = 'auto_retry_failed_backups'")['value'] ?? '1') === '1');
$autoRetryMax = max(0, (int) ($db->fetchOne("SELECT `value` FROM settings WHERE `key` = 'auto_retry_max_attempts'")['value'] ?? 3));
foreach ($staleJobs as $sj) {
$isBackup = ($sj['task_type'] === 'backup' && !empty($sj['backup_plan_id']));
$attempt = ((int) $sj['retry_count']) + 1;
$willRetry = $isBackup && $autoRetryEnabled && $attempt <= $autoRetryMax;
$errorLog = $willRetry
? "Agent offline during backup — rescheduled (attempt {$attempt} of {$autoRetryMax}) for when agent reconnects"
: ($isBackup && $autoRetryEnabled
? "Agent went offline — no heartbeat in {$threshold}s; retry limit ({$autoRetryMax}) exhausted"
: "Agent went offline — no heartbeat in {$threshold}s");
$db->update('backup_jobs', [
'status' => 'failed',
'completed_at' => date('Y-m-d H:i:s'),
'error_log' => $errorLog,
], 'id = ?', [$sj['id']]);
if ($willRetry) {
// Re-queue the same plan; agent picks it up when it reconnects.
// parent_job_id chains the retries so the UI can show history.
$db->insert('backup_jobs', [
'backup_plan_id' => $sj['backup_plan_id'],
'agent_id' => $sj['agent_id'],
'repository_id' => $sj['repository_id'],
'task_type' => 'backup',
'status' => 'queued',
'retry_count' => $attempt,
'parent_job_id' => $sj['id'],
]);
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'info',
'message' => "Agent \"{$sj['agent_name']}\" went offline during backup — rescheduled (attempt {$attempt} of {$autoRetryMax}) for when agent reconnects",
]);
echo date('Y-m-d H:i:s') . " Re-queued: plan {$sj['backup_plan_id']} (attempt {$attempt}/{$autoRetryMax}) — agent \"{$sj['agent_name']}\" offline\n";
continue;
}
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'error',
'message' => "Job #{$sj['id']} ({$sj['task_type']}) failed — agent \"{$sj['agent_name']}\" went offline"
. ($isBackup && $autoRetryEnabled ? " (retry limit {$autoRetryMax} exhausted)" : ""),
]);
// Fire backup_failed notification if it was a backup. When auto-retry
// is exhausted (or disabled), force the email so dedup doesn't swallow
// the terminal failure.
if ($isBackup) {
$notificationService = $notificationService ?? new NotificationService();
$planRow = $db->fetchOne("SELECT name FROM backup_plans WHERE id = ?", [$sj['backup_plan_id']]);
$planName = $planRow['name'] ?? '';
$exhausted = $autoRetryEnabled && $autoRetryMax > 0;
$msg = $exhausted
? "Backup failed for plan \"{$planName}\" on client \"{$sj['agent_name']}\" — agent went offline; retry limit ({$autoRetryMax}) exhausted"
: "Backup failed for plan \"{$planName}\" on client \"{$sj['agent_name']}\" — agent went offline";
$notificationService->notify(
'backup_failed',
$sj['agent_id'],
(int)$sj['backup_plan_id'],
$msg,
'critical',
null,
$exhausted // forceEmail on retry exhaustion
);
}
echo date('Y-m-d H:i:s') . " Failed: job #{$sj['id']} ({$sj['task_type']}) — agent \"{$sj['agent_name']}\" offline\n";
}
// Step 2b: Auto-fail zombie jobs — running >24h on online agents with no recent progress
// Safety net for agents that don't support check_jobs or lost status reports that were never retried
// Excludes server-side tasks (prune, compact, catalog, etc.) — those are managed by the scheduler
$zombieJobs = $db->fetchAll("
SELECT bj.id, bj.agent_id, bj.task_type, bj.backup_plan_id, a.name as agent_name
FROM backup_jobs bj
JOIN agents a ON a.id = bj.agent_id
WHERE bj.status IN ('running', 'sent')
AND a.status = 'online'
AND bj.task_type NOT IN ('prune', 'compact', 's3_sync', 's3_restore', 'repo_check', 'repo_repair', 'break_lock', 'catalog_sync', 'catalog_rebuild', 'catalog_rebuild_full', 'archive_delete')
AND bj.queued_at < DATE_SUB(NOW(), INTERVAL 24 HOUR)
AND (bj.last_progress_at IS NULL OR bj.last_progress_at < DATE_SUB(NOW(), INTERVAL 60 MINUTE))
");
foreach ($zombieJobs as $zj) {
$db->update('backup_jobs', [
'status' => 'failed',
'completed_at' => date('Y-m-d H:i:s'),
'error_log' => 'Job timed out — running for over 24 hours with no recent progress',
], 'id = ?', [$zj['id']]);
$db->insert('server_log', [
'agent_id' => $zj['agent_id'],
'backup_job_id' => $zj['id'],
'level' => 'error',
'message' => "Job #{$zj['id']} ({$zj['task_type']}) auto-failed — running >24h with no progress on online agent \"{$zj['agent_name']}\"",
]);
if ($zj['task_type'] === 'backup' && $zj['backup_plan_id']) {
$notificationService = $notificationService ?? new NotificationService();
$planRow = $db->fetchOne("SELECT name FROM backup_plans WHERE id = ?", [$zj['backup_plan_id']]);
$planName = $planRow['name'] ?? '';
$notificationService->notify(
'backup_failed',
$zj['agent_id'],
(int)$zj['backup_plan_id'],
"Backup failed for plan \"{$planName}\" on client \"{$zj['agent_name']}\" — job timed out (>24h)",
'critical'
);
}
echo date('Y-m-d H:i:s') . " Auto-failed: job #{$zj['id']} ({$zj['task_type']}) — running >24h on online agent \"{$zj['agent_name']}\"\n";
}
// Step 2c: Fail stale management tasks (update_borg, update_agent) after 7 days
// unpicked. These are excluded from Step 2 so they don't fail the moment the
// client's laptop goes to sleep, but we still need a safety valve — if an agent
// has been gone for a week and still hasn't polled for its pending update, the
// job is effectively abandoned and should stop cluttering the queue.
$staleMgmtCutoffDays = 7;
$staleMgmt = $db->fetchAll("
SELECT bj.id, bj.agent_id, bj.task_type, a.name as agent_name
FROM backup_jobs bj
JOIN agents a ON a.id = bj.agent_id
WHERE bj.status IN ('queued', 'sent')
AND bj.task_type IN ('update_borg', 'update_agent')
AND bj.queued_at < DATE_SUB(NOW(), INTERVAL {$staleMgmtCutoffDays} DAY)
");
foreach ($staleMgmt as $sm) {
$db->update('backup_jobs', [
'status' => 'failed',
'completed_at' => date('Y-m-d H:i:s'),
'error_log' => "Agent did not pick up the update within {$staleMgmtCutoffDays} days",
], 'id = ?', [$sm['id']]);
$db->insert('server_log', [
'agent_id' => $sm['agent_id'],
'backup_job_id' => $sm['id'],
'level' => 'warning',
'message' => "Job #{$sm['id']} ({$sm['task_type']}) expired — agent \"{$sm['agent_name']}\" did not poll for the update in {$staleMgmtCutoffDays} days",
]);
echo date('Y-m-d H:i:s') . " Expired: job #{$sm['id']} ({$sm['task_type']}) — agent \"{$sm['agent_name']}\" offline >{$staleMgmtCutoffDays}d\n";
}
// Step 3: Check schedules and create queued jobs
$scheduler = new SchedulerService();
$created = $scheduler->run();
foreach ($created as $job) {
echo date('Y-m-d H:i:s') . " Queued: {$job['plan']} (job #{$job['job_id']}, agent #{$job['agent_id']})\n";
}
// Step 3b: Auto-queue catalog rebuilds for repos with unindexed archives
try {
$ch = \BBS\Core\ClickHouse::getInstance();
if ($ch->isAvailable()) {
// Get all archive IDs currently in ClickHouse
$chArchives = $ch->fetchAll("SELECT DISTINCT archive_id FROM file_catalog");
$indexedIds = array_flip(array_column($chArchives, 'archive_id'));
// Find repos that have archives not yet in ClickHouse
// Skip archives created in the last 30 minutes — the normal post-backup
// catalog indexing handles those; triggering a rebuild too early causes loops
$repos = $db->fetchAll(
"SELECT r.id, r.agent_id, r.path, r.name, r.storage_type, r.storage_location_id, a.id AS archive_id
FROM repositories r
JOIN archives a ON a.repository_id = r.id
WHERE a.created_at < DATE_SUB(NOW(), INTERVAL 30 MINUTE)"
);
$needsRebuild = [];
foreach ($repos as $row) {
if (!isset($indexedIds[$row['archive_id']])) {
$needsRebuild[$row['id']] = $row;
}
}
foreach ($needsRebuild as $repoId => $info) {
$agentId = $info['agent_id'];
// Skip repos whose data doesn't exist on disk (e.g. after restore to a new server)
if ($info['storage_type'] === 'local' || empty($info['storage_type'])) {
$checkPath = \BBS\Services\BorgCommandBuilder::getLocalRepoPath($info);
if (!empty($checkPath) && !is_dir($checkPath)) {
continue;
}
}
// Check for pending/running rebuild on this repo OR any repo for same agent
// Concurrent rebuilds for same agent contend on borg repo locks
// Also skip if a rebuild completed in the last 24 hours (prevents infinite loop
// when some archives can never be indexed, e.g. corrupted or inaccessible)
$pending = $db->fetchOne(
"SELECT id FROM backup_jobs
WHERE (repository_id = ? OR agent_id = ?) AND task_type IN ('catalog_rebuild', 'catalog_rebuild_full')
AND (status IN ('queued','sent','running')
OR (status IN ('completed','failed') AND completed_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)))",
[$repoId, $agentId]
);
if (!$pending) {
$db->insert('backup_jobs', [
'agent_id' => $agentId,
'repository_id' => $repoId,
'task_type' => 'catalog_rebuild',
'status' => 'queued',
]);
echo date('Y-m-d H:i:s') . " Auto-queued catalog_rebuild for repo #{$repoId} (missing archives in ClickHouse)\n";
}
}
}
} catch (\Exception $e) {
// ClickHouse not available yet — skip auto-rebuild
}
// Step 4: Process queue - promote queued jobs to sent
$queueManager = new QueueManager();
$promoted = $queueManager->processQueue();
foreach ($promoted as $job) {
echo date('Y-m-d H:i:s') . " Sent: job #{$job['id']} ({$job['task_type']}) to agent #{$job['agent_id']}\n";
}
// Step 4b: Execute server-side jobs (prune/compact) locally
$serverJobs = $queueManager->getServerSideJobs();
foreach ($serverJobs as $sj) {
$repo = [
'path' => $sj['repo_path'],
'encryption' => $sj['encryption'],
'passphrase_encrypted' => $sj['passphrase_encrypted'],
'agent_id' => $sj['repo_agent_id'] ?? $sj['agent_id'],
'name' => $sj['repo_name'],
'storage_type' => $sj['storage_type'] ?? 'local',
'storage_location_id' => $sj['storage_location_id'] ?? null,
];
$isRemoteSsh = ($repo['storage_type'] === 'remote_ssh');
// Use local path for server-side execution (null for remote SSH repos)
$localPath = \BBS\Services\BorgCommandBuilder::getLocalRepoPath($repo);
$localRepo = $localPath ? array_merge($repo, ['path' => $localPath]) : $repo;
$plan = [
'prune_minutes' => $sj['prune_minutes'] ?? 0,
'prune_hours' => $sj['prune_hours'] ?? 0,
'prune_days' => $sj['prune_days'] ?? 7,
'prune_weeks' => $sj['prune_weeks'] ?? 4,
'prune_months' => $sj['prune_months'] ?? 6,
'prune_years' => $sj['prune_years'] ?? 0,
];
// Atomically claim the job. Cron runs this scheduler every minute, so
// a long-running compact/prune can overlap with the next invocation:
// both instances fetch the same 'sent' row via getServerSideJobs() before
// either marks it 'running'. Without this guard both would execute the
// same job (issue #163). The WHERE status='sent' clause makes the claim
// atomic — if another scheduler already transitioned the row, rowCount()
// is 0 and we skip this iteration.
$startedAt = date('Y-m-d H:i:s');
$claim = $db->query(
"UPDATE backup_jobs SET status='running', started_at=? WHERE id=? AND status='sent'",
[$startedAt, $sj['id']]
);
if ($claim->rowCount() === 0) {
echo date('Y-m-d H:i:s') . " Skipped job #{$sj['id']} ({$sj['task_type']}) — already claimed by another scheduler run\n";
continue;
}
echo date('Y-m-d H:i:s') . " Executing server-side: job #{$sj['id']} ({$sj['task_type']})\n";
// S3 sync — uses rclone, not borg (skip for remote SSH repos — already offsite)
if ($sj['task_type'] === 's3_sync') {
if ($isRemoteSsh) {
$db->update('backup_jobs', [
'status' => 'completed',
'completed_at' => date('Y-m-d H:i:s'),
'duration_seconds' => 0,
], 'id = ?', [$sj['id']]);
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'info',
'message' => 'S3 sync skipped — remote SSH repos are already offsite',
]);
echo date('Y-m-d H:i:s') . " S3 sync job #{$sj['id']} skipped (remote SSH repo)\n";
continue;
}
$pluginManager = $pluginManager ?? new \BBS\Services\PluginManager();
// Resolve plugin config — from job's plugin_config_id or plan plugins
$config = [];
if (!empty($sj['plugin_config_id'])) {
$namedConfig = $pluginManager->getPluginConfig((int) $sj['plugin_config_id']);
if ($namedConfig) {
$config = json_decode($namedConfig['config'], true) ?: [];
}
}
$s3Service = new \BBS\Services\S3SyncService();
$creds = $s3Service->resolveCredentials($config);
$s3Repo = $db->fetchOne("SELECT * FROM repositories WHERE id = ?", [$sj['repository_id']]);
$s3Agent = $db->fetchOne("SELECT * FROM agents WHERE id = ?", [$sj['agent_id']]);
if (!$s3Repo || !$s3Agent) {
$s3Result = 'failed';
$s3Error = 'Repository or agent not found';
} else {
$runAsUser = $sj['ssh_unix_user'] ?? null;
$syncResult = $s3Service->syncRepository($s3Repo, $s3Agent, $creds, $runAsUser);
$s3Result = $syncResult['success'] ? 'completed' : 'failed';
$s3Output = $syncResult['output'] ?? '';
$s3Error = $syncResult['success'] ? null : $s3Output;
}
$now = date('Y-m-d H:i:s');
$db->update('backup_jobs', [
'status' => $s3Result,
'completed_at' => $now,
'duration_seconds' => max(0, strtotime($now) - strtotime($startedAt)),
'error_log' => $s3Error,
], 'id = ?', [$sj['id']]);
$logMessage = $s3Result === 'completed'
? 'S3 sync completed' . (!empty($s3Output) ? ": {$s3Output}" : '')
: 'S3 sync failed: ' . $s3Error;
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => $s3Result === 'completed' ? 'info' : 'error',
'message' => $logMessage,
]);
// Update last_sync_at in repository_s3_configs after successful sync
if ($s3Result === 'completed' && !empty($sj['repository_id'])) {
$db->update('repository_s3_configs', [
'last_sync_at' => $now,
], 'repository_id = ?', [$sj['repository_id']]);
}
// Send notifications for S3 sync results
$notificationService = new \BBS\Services\NotificationService();
if ($s3Result === 'failed') {
$repoName = $s3Repo['name'] ?? 'unknown';
$agentName = $s3Agent['name'] ?? 'unknown';
$notificationService->notify(
's3_sync_failed',
$sj['agent_id'],
$sj['repository_id'] ? (int)$sj['repository_id'] : null,
"S3 sync failed for repository \"{$repoName}\" on client \"{$agentName}\" — " . ($s3Error ?? 'unknown error'),
'critical'
);
} elseif ($s3Result === 'completed') {
$repoName = $s3Repo['name'] ?? 'unknown';
$agentName = $s3Agent['name'] ?? 'unknown';
$notificationService->notify(
's3_sync_done',
$sj['agent_id'],
$sj['repository_id'] ? (int)$sj['repository_id'] : null,
"S3 sync completed for repository \"{$repoName}\" on client \"{$agentName}\"" . (!empty($s3Output) ? " — {$s3Output}" : ''),
'info'
);
}
// Generate and upload manifest after successful sync (streams to file for large catalogs)
if ($s3Result === 'completed' && $s3Repo && $s3Agent) {
$passphrase = '';
if (!empty($s3Repo['passphrase_encrypted'])) {
try {
$passphrase = \BBS\Services\Encryption::decrypt($s3Repo['passphrase_encrypted']);
} catch (\Exception $e) {
// May already be plaintext
}
}
$manifestGenResult = $s3Service->generateManifestFile($s3Repo, $s3Agent, $passphrase);
if ($manifestGenResult['success']) {
$manifestUploadResult = $s3Service->uploadManifestFile($manifestGenResult['file'], $s3Repo, $s3Agent, $creds);
if ($manifestUploadResult['success']) {
echo date('Y-m-d H:i:s') . " Manifest uploaded ({$manifestGenResult['archives']} archives, {$manifestGenResult['files']} files)\n";
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'info',
'message' => "Manifest uploaded: {$manifestGenResult['archives']} archives, {$manifestGenResult['files']} files cataloged",
]);
} else {
echo date('Y-m-d H:i:s') . " Warning: manifest upload failed: {$manifestUploadResult['output']}\n";
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'warning',
'message' => 'Manifest upload failed: ' . $manifestUploadResult['output'],
]);
}
} else {
echo date('Y-m-d H:i:s') . " Warning: manifest generation failed\n";
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'warning',
'message' => 'Manifest generation failed (no file catalog to backup)',
]);
}
}
echo date('Y-m-d H:i:s') . " S3 sync job #{$sj['id']} {$s3Result}\n";
continue;
}
// S3 restore — uses rclone to download from S3
if ($sj['task_type'] === 's3_restore') {
$pluginManager = $pluginManager ?? new \BBS\Services\PluginManager();
// Resolve plugin config — from job's plugin_config_id
$config = [];
if (!empty($sj['plugin_config_id'])) {
$namedConfig = $pluginManager->getPluginConfig((int) $sj['plugin_config_id']);
if ($namedConfig) {
$config = json_decode($namedConfig['config'], true) ?: [];
}
}
$s3Service = new \BBS\Services\S3SyncService();
$creds = $s3Service->resolveCredentials($config);
$s3Repo = $db->fetchOne("SELECT * FROM repositories WHERE id = ?", [$sj['repository_id']]);
$s3Agent = $db->fetchOne("SELECT * FROM agents WHERE id = ?", [$sj['agent_id']]);
// For "copy" mode, source_repository_id tells us where to pull S3 data from
$sourceRepo = null;
if (!empty($sj['source_repository_id'])) {
$sourceRepo = $db->fetchOne("SELECT * FROM repositories WHERE id = ?", [$sj['source_repository_id']]);
}
if (!$s3Repo || !$s3Agent) {
$s3Result = 'failed';
$s3Error = 'Repository or agent not found';
} else {
$runAsUser = $sj['ssh_unix_user'] ?? null;
$restoreResult = $s3Service->restoreRepository($s3Repo, $s3Agent, $creds, $runAsUser, $sourceRepo);
$s3Result = $restoreResult['success'] ? 'completed' : 'failed';
$s3Output = $restoreResult['output'] ?? '';
$s3Error = $restoreResult['success'] ? null : $s3Output;
}
$now = date('Y-m-d H:i:s');
$db->update('backup_jobs', [
'status' => $s3Result,
'completed_at' => $now,
'duration_seconds' => max(0, strtotime($now) - strtotime($startedAt)),
'error_log' => $s3Error,
], 'id = ?', [$sj['id']]);
$logMessage = $s3Result === 'completed'
? 'S3 restore completed' . (!empty($s3Output) ? ": {$s3Output}" : '')
: 'S3 restore failed: ' . $s3Error;
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => $s3Result === 'completed' ? 'info' : 'error',
'message' => $logMessage,
]);
echo date('Y-m-d H:i:s') . " S3 restore job #{$sj['id']} {$s3Result}\n";
// After successful S3 restore, clear borg cache to prevent "repository relocated" errors
// This happens because S3 copies share the same internal borg repository UUID
if ($s3Result === 'completed' && !empty($sj['ssh_unix_user'])) {
$clearCmd = ['sudo', '/usr/local/bin/bbs-ssh-helper', 'clear-borg-cache', $sj['ssh_unix_user']];
exec(implode(' ', array_map('escapeshellarg', $clearCmd)) . ' 2>&1', $clearOutput, $clearRet);
if ($clearRet === 0) {
echo date('Y-m-d H:i:s') . " Cleared borg cache for {$sj['ssh_unix_user']}\n";
}
}
// After successful S3 restore, try to import manifest first (fast path)
// Falls back to catalog_sync if no manifest exists (slow path via borg commands)
if ($s3Result === 'completed' && $sj['repository_id'] && $s3Repo && $s3Agent) {
$manifestDownload = $s3Service->downloadManifestFile($s3Repo, $s3Agent, $creds, $sourceRepo);
if ($manifestDownload['success'] && $manifestDownload['file']) {
// Fast path: import from manifest
echo date('Y-m-d H:i:s') . " Found manifest, importing catalog...\n";
$importResult = $s3Service->importManifestFile($manifestDownload['file'], $sj['repository_id']);
if ($importResult['success']) {
echo date('Y-m-d H:i:s') . " Manifest imported ({$importResult['archives']} archives, {$importResult['files']} files)\n";
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'level' => 'info',
'message' => "Catalog imported from manifest: {$importResult['archives']} archives, {$importResult['files']} files",
]);
} else {
// Manifest import failed, fall back to catalog_sync
echo date('Y-m-d H:i:s') . " Manifest import failed: {$importResult['error']}, falling back to catalog_sync\n";
$db->insert('backup_jobs', [
'agent_id' => $sj['agent_id'],
'repository_id' => $sj['repository_id'],
'task_type' => 'catalog_sync',
'status' => 'queued',
]);
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'level' => 'warning',
'message' => "Manifest import failed ({$importResult['error']}), catalog_sync queued",
]);
}
} else {
// No manifest found (legacy S3 backup or external repo), queue catalog_sync
echo date('Y-m-d H:i:s') . " No manifest found, queuing catalog_sync (slow path)...\n";
$catalogSyncJob = [
'agent_id' => $sj['agent_id'],
'repository_id' => $sj['repository_id'],
'task_type' => 'catalog_sync',
'status' => 'queued',
];
$db->insert('backup_jobs', $catalogSyncJob);
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'level' => 'info',
'message' => "No manifest in S3, catalog_sync queued for repository after S3 restore",
]);
echo date('Y-m-d H:i:s') . " Queued catalog_sync for repo #{$sj['repository_id']} after S3 restore\n";
}
}
continue;
}
// Catalog sync — runs borg list to rebuild archives table
if ($sj['task_type'] === 'catalog_sync') {
$csRepo = $db->fetchOne("SELECT * FROM repositories WHERE id = ?", [$sj['repository_id']]);
if (!$csRepo) {
$db->update('backup_jobs', [
'status' => 'failed',
'completed_at' => date('Y-m-d H:i:s'),
'error_log' => 'Repository not found',
], 'id = ?', [$sj['id']]);
echo date('Y-m-d H:i:s') . " Catalog sync job #{$sj['id']} failed: repository not found\n";
continue;
}
$passphrase = '';
if (!empty($csRepo['passphrase_encrypted'])) {
try {
$passphrase = \BBS\Services\Encryption::decrypt($csRepo['passphrase_encrypted']);
} catch (\Exception $e) {
// May already be plaintext or missing
}
}
// Remote SSH repos: use RemoteSshService, Local repos: use bbs-ssh-helper or direct borg
if ($isRemoteSsh && !empty($sj['remote_ssh_config_id'])) {
$remoteSshService = $remoteSshService ?? new RemoteSshService();
$remoteConfig = $remoteSshService->getById((int) $sj['remote_ssh_config_id']);
if (!$remoteConfig) {
$db->update('backup_jobs', [
'status' => 'failed',
'completed_at' => date('Y-m-d H:i:s'),
'error_log' => 'Remote SSH config not found',
], 'id = ?', [$sj['id']]);
echo date('Y-m-d H:i:s') . " Catalog sync job #{$sj['id']} failed: remote SSH config not found\n";
continue;
}
$csResult = $remoteSshService->runBorgCommand($remoteConfig, $csRepo['path'], ['list', '--json', $csRepo['path']], $passphrase);
$csOutput = $csResult['output'] ?? '';
$csError = $csResult['stderr'] ?? '';
$csExitCode = $csResult['exit_code'] ?? -1;
} else {
$csLocalPath = \BBS\Services\BorgCommandBuilder::getLocalRepoPath($csRepo);
// Run borg list via bbs-ssh-helper (handles sudo to the repo-owning user).
// Passphrase is piped on stdin ("-" marker) so it's not visible in `ps`.
$runAsUser = $sj['ssh_unix_user'] ?? null;
if ($runAsUser) {
$csCmd = [
'sudo', '/usr/local/bin/bbs-ssh-helper', 'borg-list',
$runAsUser, '-', $csLocalPath
];
$csEnv = [];
} else {
// No unix user — run directly as www-data (legacy mode)
$csCmd = ['borg', 'list', '--json', $csLocalPath];
$csEnv = [];
if ($passphrase) {
$csEnv['BORG_PASSPHRASE'] = $passphrase;
}
$csEnv['BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK'] = 'yes';
$csEnv['BORG_RELOCATED_REPO_ACCESS_IS_OK'] = 'yes';
$csEnv['BORG_BASE_DIR'] = '/tmp/bbs-borg-www-data';
$csEnv['HOME'] = '/tmp/bbs-borg-www-data';
}
// When running via helper (runAsUser is set), env is handled by the helper
$csEnvStrings = $runAsUser ? null : array_filter($_SERVER, 'is_string') + $csEnv;
$csProc = proc_open($csCmd, [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $csPipes, null, $csEnvStrings);
$csOutput = '';
$csError = '';
$csExitCode = -1;
if (is_resource($csProc)) {
if ($runAsUser) {
fwrite($csPipes[0], $passphrase . "\n");
}
fclose($csPipes[0]);
$csOutput = stream_get_contents($csPipes[1]);
$csError = stream_get_contents($csPipes[2]);
fclose($csPipes[1]);
fclose($csPipes[2]);
$csExitCode = proc_close($csProc);
}
}
// Use remote repo path for archive info commands
$csArchivePath = $isRemoteSsh ? $csRepo['path'] : ($csLocalPath ?? $csRepo['path']);
$csNow = date('Y-m-d H:i:s');
if ($csExitCode <= 1) {
$csData = json_decode($csOutput, true);
// Safety check: if JSON parse failed, fail the job rather than deleting all archive records
if ($csData === null || !isset($csData['archives'])) {
$stderrHint = !empty($csError) ? trim($csError) : '';
$stdoutHint = trim(substr($csOutput, 0, 500));
$errorMsg = "borg list output was not valid JSON";
if ($stderrHint) {
$errorMsg .= ": " . $stderrHint;
} elseif ($stdoutHint) {
$errorMsg .= ": " . $stdoutHint;
} else {
$errorMsg .= " (empty output, exit code {$csExitCode})";
}
$db->update('backup_jobs', [
'status' => 'failed',
'completed_at' => $csNow,
'duration_seconds' => max(0, strtotime($csNow) - strtotime($startedAt)),
'error_log' => $errorMsg,
], 'id = ?', [$sj['id']]);
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'error',
'message' => "Catalog sync failed: {$errorMsg}",
]);
echo date('Y-m-d H:i:s') . " Catalog sync job #{$sj['id']} failed: {$errorMsg}\n";
continue;
}
$archives = $csData['archives'] ?? [];
// Clear existing archives for this repo and rebuild
$db->delete('archives', 'repository_id = ?', [$csRepo['id']]);
// Set progress bar for archive processing
$totalArchiveCount = count($archives);
$db->update('backup_jobs', [
'files_total' => $totalArchiveCount,
'files_processed' => 0,
], 'id = ?', [$sj['id']]);
$archiveCount = 0;
$totalSize = 0;
foreach ($archives as $ar) {
$archiveName = $ar['name'] ?? 'unknown';
$createdAt = isset($ar['start']) ? date('Y-m-d H:i:s', strtotime($ar['start'])) : $csNow;
$originalSize = 0;
$deduplicatedSize = 0;
$fileCount = 0;
// Run borg info to get archive sizes
if ($isRemoteSsh && isset($remoteConfig)) {
$infoResult = $remoteSshService->runBorgCommand($remoteConfig, $csRepo['path'], ['info', '--json', $csRepo['path'] . '::' . $archiveName], $passphrase);
if ($infoResult['success']) {
$infoData = json_decode($infoResult['output'], true);
$archiveInfo = $infoData['archives'][0] ?? [];
$stats = $archiveInfo['stats'] ?? [];
$originalSize = (int) ($stats['original_size'] ?? 0);
$deduplicatedSize = (int) ($stats['deduplicated_size'] ?? 0);
$fileCount = (int) ($stats['nfiles'] ?? 0);
}
} else {
$archivePath = "{$csArchivePath}::{$archiveName}";
$runAsUser = $sj['ssh_unix_user'] ?? null;
if ($runAsUser) {
$infoCmd = [
'sudo', '/usr/local/bin/bbs-ssh-helper', 'borg-cmd',
$runAsUser, '-', 'info', '--json', $archivePath
];
$infoEnvStrings = null;
} else {
$infoCmd = ['borg', 'info', '--json', $archivePath];
$infoEnv = [];
if ($passphrase) {
$infoEnv['BORG_PASSPHRASE'] = $passphrase;
}
$infoEnv['BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK'] = 'yes';
$infoEnv['BORG_RELOCATED_REPO_ACCESS_IS_OK'] = 'yes';
$infoEnv['BORG_BASE_DIR'] = '/tmp/bbs-borg-www-data';
$infoEnv['HOME'] = '/tmp/bbs-borg-www-data';
$infoEnvStrings = array_filter($_SERVER, 'is_string') + $infoEnv;
}
$infoProc = proc_open($infoCmd, [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $infoPipes, null, $infoEnvStrings);
if (is_resource($infoProc)) {
if ($runAsUser) {
fwrite($infoPipes[0], $passphrase . "\n");
}
fclose($infoPipes[0]);
$infoOutput = stream_get_contents($infoPipes[1]);
fclose($infoPipes[1]);
fclose($infoPipes[2]);
$infoExitCode = proc_close($infoProc);
if ($infoExitCode === 0) {
$infoData = json_decode($infoOutput, true);
$archiveInfo = $infoData['archives'][0] ?? [];
$stats = $archiveInfo['stats'] ?? [];
$originalSize = (int) ($stats['original_size'] ?? 0);
$deduplicatedSize = (int) ($stats['deduplicated_size'] ?? 0);
$fileCount = (int) ($stats['nfiles'] ?? 0);
}
}
}
$db->insert('archives', [
'repository_id' => $csRepo['id'],
'archive_name' => $archiveName,
'created_at' => $createdAt,
'file_count' => $fileCount,
'original_size' => $originalSize,
'deduplicated_size' => $deduplicatedSize,
]);
$archiveCount++;
$totalSize += $deduplicatedSize;
// Update progress
$db->update('backup_jobs', [
'files_processed' => $archiveCount,
'last_progress_at' => $db->now(),
], 'id = ?', [$sj['id']]);
echo date('Y-m-d H:i:s') . " Catalog sync {$archiveCount}/{$totalArchiveCount}: {$archiveName}\n";
}
// Repo size: prefer borg's own dedup-aware unique_csize over the
// sum of per-archive deduplicated_size, which is the *incremental*
// contribution at archive-creation time and goes wrong as soon as
// anything is pruned/compacted (#258).
$sshUnixUser = $sj['ssh_unix_user'] ?? null;
$repoUniqueSize = \BBS\Services\RepositorySizeService::fetchRepoUniqueCsize($csRepo, $sshUnixUser);
$sizeForRepo = $repoUniqueSize ?? $totalSize;
$db->update('repositories', [
'archive_count' => $archiveCount,
'size_bytes' => $sizeForRepo,
], 'id = ?', [$csRepo['id']]);
$db->update('backup_jobs', [
'status' => 'completed',
'completed_at' => $csNow,
'duration_seconds' => max(0, strtotime($csNow) - strtotime($startedAt)),
], 'id = ?', [$sj['id']]);
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'info',
'message' => "Catalog sync completed: {$archiveCount} archives found",
]);
echo date('Y-m-d H:i:s') . " Catalog sync job #{$sj['id']} completed: {$archiveCount} archives\n";
// Auto-queue catalog_rebuild to populate file catalog for all archives
if ($archiveCount > 0) {
$db->insert('backup_jobs', [
'agent_id' => $sj['agent_id'],
'repository_id' => $sj['repository_id'],
'task_type' => 'catalog_rebuild',
'status' => 'queued',
]);
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'level' => 'info',
'message' => "Catalog rebuild queued for {$archiveCount} archives after catalog sync",
]);
echo date('Y-m-d H:i:s') . " Queued catalog_rebuild for repo #{$sj['repository_id']} ({$archiveCount} archives)\n";
}
} else {
// Error may be in $csOutput (due to 2>&1 in helper) or $csError
$errorMsg = trim($csError ?: $csOutput) ?: "borg list failed with exit code {$csExitCode}";
$db->update('backup_jobs', [
'status' => 'failed',
'completed_at' => $csNow,
'duration_seconds' => max(0, strtotime($csNow) - strtotime($startedAt)),
'error_log' => $errorMsg,
], 'id = ?', [$sj['id']]);
$db->insert('server_log', [
'agent_id' => $sj['agent_id'],
'backup_job_id' => $sj['id'],
'level' => 'error',
'message' => "Catalog sync failed: " . $errorMsg,
]);
echo date('Y-m-d H:i:s') . " Catalog sync job #{$sj['id']} failed: {$errorMsg}\n";
}
continue;
}
// Catalog rebuild — extract file listings from all archives to populate per-agent catalog table
if ($sj['task_type'] === 'catalog_rebuild' || $sj['task_type'] === 'catalog_rebuild_full') {
$isFullRebuild = ($sj['task_type'] === 'catalog_rebuild_full');
$crRepo = $db->fetchOne("SELECT * FROM repositories WHERE id = ?", [$sj['repository_id']]);
if (!$crRepo) {
$db->update('backup_jobs', [
'status' => 'failed',
'completed_at' => date('Y-m-d H:i:s'),
'error_log' => 'Repository not found',
], 'id = ?', [$sj['id']]);
echo date('Y-m-d H:i:s') . " Catalog rebuild job #{$sj['id']} failed: repository not found\n";
continue;
}
$crLocalPath = \BBS\Services\BorgCommandBuilder::getLocalRepoPath($crRepo);
$passphrase = '';
if (!empty($crRepo['passphrase_encrypted'])) {
try {
$passphrase = \BBS\Services\Encryption::decrypt($crRepo['passphrase_encrypted']);
} catch (\Exception $e) {
// May already be plaintext or missing
}
}
$agentId = $sj['agent_id'];
$repoName = $crRepo['name'] ?? "repo #{$crRepo['id']}";
// Log: Starting
$db->insert('server_log', [
'agent_id' => $agentId,
'backup_job_id' => $sj['id'],
'level' => 'info',
'message' => "Starting catalog rebuild for repository \"{$repoName}\"",
]);
echo date('Y-m-d H:i:s') . " Catalog rebuild job #{$sj['id']}: starting for \"{$repoName}\"\n";
// Sync archives from borg before rebuilding catalog (ensures DB is fresh)
$syncOutput = '';
$syncExitCode = -1;
if ($isRemoteSsh && !empty($sj['remote_ssh_config_id'])) {
$remoteSshService = $remoteSshService ?? new RemoteSshService();
$syncRemoteConfig = $remoteSshService->getById((int) $sj['remote_ssh_config_id']);
if ($syncRemoteConfig) {
$syncResult = $remoteSshService->runBorgCommand($syncRemoteConfig, $crRepo['path'], ['list', '--json', $crRepo['path']], $passphrase);
$syncOutput = $syncResult['output'] ?? '';
$syncExitCode = $syncResult['exit_code'] ?? -1;
}
} else {
$runAsUserSync = $sj['ssh_unix_user'] ?? null;
if ($runAsUserSync) {
$syncCmd = ['sudo', '/usr/local/bin/bbs-ssh-helper', 'borg-list', $runAsUserSync, '-', $crLocalPath];
$syncEnvStrings = null;
} else {
$syncCmd = ['borg', 'list', '--json', $crLocalPath];
$syncEnv = [];
if ($passphrase) $syncEnv['BORG_PASSPHRASE'] = $passphrase;
$syncEnv['BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK'] = 'yes';
$syncEnv['BORG_RELOCATED_REPO_ACCESS_IS_OK'] = 'yes';
$syncEnv['BORG_BASE_DIR'] = '/tmp/bbs-borg-www-data';
$syncEnv['HOME'] = '/tmp/bbs-borg-www-data';
$syncEnvStrings = array_filter($_SERVER, 'is_string') + $syncEnv;
}
$syncProc = proc_open($syncCmd, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $syncPipes, null, $syncEnvStrings);
if (is_resource($syncProc)) {
if ($runAsUserSync) {
fwrite($syncPipes[0], $passphrase . "\n");
}
fclose($syncPipes[0]);
$syncOutput = stream_get_contents($syncPipes[1]);
fclose($syncPipes[1]);
fclose($syncPipes[2]);
$syncExitCode = proc_close($syncProc);
}
}
if ($syncExitCode <= 1 && $syncOutput) {
$syncData = json_decode($syncOutput, true);
if ($syncData === null || !isset($syncData['archives'])) {
echo date('Y-m-d H:i:s') . " Catalog rebuild job #{$sj['id']}: borg list returned invalid JSON, skipping archive sync\n";
$syncData = ['archives' => []];