-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplica.rs
More file actions
1690 lines (1564 loc) · 50.5 KB
/
Copy pathreplica.rs
File metadata and controls
1690 lines (1564 loc) · 50.5 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
use std::{collections::HashSet, sync::Arc, time::Duration};
use jiff::{SignedDuration, Timestamp};
use k8s_openapi::{
api::{
apps::v1::Deployment,
batch::v1::Job,
core::v1::{Pod, Secret},
},
apimachinery::pkg::{api::resource::Quantity, apis::meta::v1::Time},
};
use kube::{
Api, Client, Resource, ResourceExt,
api::{Patch, PatchParams, PostParams},
runtime::{
controller::Action,
events::{Event, EventType},
},
};
use kube_quantity::ParsedQuantity;
use rand::RngExt;
use rust_decimal::Decimal;
use tracing::{debug, info, warn};
use super::{
jobs::{JobStatus, classify_job},
postgres,
postgres::DEFAULT_PG_VERSION,
restore::{build_credential_reset_job, credential_reset_job_name},
};
use crate::{
context::Context,
error::{Error, Result},
kopia,
types::*,
};
use scheduling::ScheduleDecision;
mod resources;
pub(super) mod scheduling;
mod schema_migration;
mod status;
#[cfg(test)]
mod tests;
use resources::*;
/// True when no schema migration is currently in flight for this replica
/// — i.e. the sweep can safely delete the previous Active restore without
/// pulling the rug out from under a running `pg_dump | psql`.
///
/// Returns `true` when `persistent_schemas` is unset (no migration ever
/// runs) or when `schemaMigrationPhase` is anything other than `active`.
/// Coded as "not in flight" rather than enumerating terminal phases so
/// future additions (the operator's set of phase labels has grown over
/// time: `complete`, `partial`, `failed: <reason>`, `timeout-skipped`)
/// don't silently block the sweep.
pub fn persistent_schemas_migration_settled(replica: &PostgresPhysicalReplica) -> bool {
if replica.spec.persistent_schemas.is_none() {
return true;
}
let phase = replica
.status
.as_ref()
.and_then(|s| s.schema_migration_phase.as_deref());
!matches!(phase, Some("active"))
}
/// Generate a random password for analytics credentials.
pub(crate) fn generate_password() -> String {
let mut rng = rand::rng();
let chars: Vec<char> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
.chars()
.collect();
(0..32)
.map(|_| chars[rng.random_range(0..chars.len())])
.collect()
}
pub async fn reconcile(replica: Arc<PostgresPhysicalReplica>, ctx: Arc<Context>) -> Result<Action> {
let name = replica.name_any();
let namespace = replica
.namespace()
.ok_or_else(|| Error::MissingNamespace(name.clone()))?;
let now = Timestamp::now();
ctx.last_reconcile
.store(now.as_second(), std::sync::atomic::Ordering::Relaxed);
ctx.metrics
.reconciliations_total
.with_label_values(&["replica"])
.inc();
let client = &ctx.client;
// Validate kopia Secret
let secret_name = replica
.spec
.kopia_secret_ref
.name
.as_deref()
.unwrap_or_default();
let secrets: Api<Secret> = Api::namespaced(client.clone(), &namespace);
let secret = match secrets.get(secret_name).await {
Ok(s) => s,
Err(e) => {
warn!(
replica = name,
secret = ?replica.spec.kopia_secret_ref,
error = %e,
"kopia secret not found"
);
replica
.update_condition(
client,
"KopiaSecretValid",
"False",
"SecretNotFound",
&format!("Secret {secret_name} not found: {e}"),
)
.await?;
return Ok(Action::requeue(Duration::from_secs(60)));
}
};
let _creds = match kopia::validate_kopia_secret(&secret) {
Ok(c) => {
replica
.update_condition(
client,
"KopiaSecretValid",
"True",
"SecretValid",
"All required keys present",
)
.await?;
c
}
Err(e) => {
warn!(replica = name, error = %e, "kopia secret invalid");
replica
.update_condition(
client,
"KopiaSecretValid",
"False",
"SecretInvalid",
&e.to_string(),
)
.await?;
return Ok(Action::requeue(Duration::from_secs(60)));
}
};
replica.ensure_credentials_secret(client).await?;
replica.ensure_service(client).await?;
replica
.update_status_field(client, "serviceName", &name)
.await?;
replica.update_connection_info(client).await?;
// Check child PostgresPhysicalRestore resources
let restores: Api<PostgresPhysicalRestore> = Api::namespaced(client.clone(), &namespace);
let restore_list = restores
.list(&kube::api::ListParams::default().labels(&format!("pgro.bes.au/replica={name}")))
.await?;
// Find current active restore and any in-progress restores
let active_restore = restore_list
.items
.iter()
.find(|r| r.status.as_ref().and_then(|s| s.phase.as_ref()) == Some(&RestorePhase::Active));
let switching_restore = restore_list.items.iter().find(|r| {
r.status.as_ref().and_then(|s| s.phase.as_ref()) == Some(&RestorePhase::Switching)
});
let in_progress_restore = restore_list.items.iter().find(|r| {
matches!(
r.status.as_ref().and_then(|s| s.phase.as_ref()),
Some(RestorePhase::Pending) | Some(RestorePhase::Restoring) | Some(RestorePhase::Ready)
)
});
// Handle schema migration for persistent_schemas configuration
if replica.spec.persistent_schemas.is_some()
&& let Some(switching) = switching_restore
{
let migration_complete = reconcile_schema_migration(
client,
&ctx,
&replica,
&namespace,
switching,
active_restore,
)
.await?;
if !migration_complete {
return Ok(Action::requeue(Duration::from_secs(30)));
}
}
// Handle switchover: if a restore is in Switching phase, update Service selector
if let Some(switching) = switching_restore {
let switching_name = switching.name_any();
info!(
replica = name,
restore = switching_name,
"performing blue-green switchover"
);
// Mark the new restore's pod ready for traffic BEFORE pointing the
// Service at it. The Service selector requires the
// `ready-for-traffic=true` label (see [[READY_FOR_TRAFFIC_LABEL]]),
// so until the operator sets the label, no external client can
// reach the restore via the Service — operator-side prep work
// (DROP SCHEMA, migration Job) runs without external interference.
switching.mark_pod_ready_for_traffic(client).await?;
// Update Service selector to point to the new restore
switching.update_service_selector(client, &name).await?;
// Transition the switching restore to Active
switching.update_phase(client, RestorePhase::Active).await?;
let now = Timestamp::now();
switching.update_activated_at(client, Time(now)).await?;
// Update replica status
let replicas: Api<PostgresPhysicalReplica> = Api::namespaced(client.clone(), &namespace);
let previous_restore = replica
.status
.as_ref()
.and_then(|s| s.current_restore.clone());
let patch = serde_json::json!({
"status": {
"phase": "Ready",
"currentRestore": switching_name,
"previousRestore": previous_restore,
"lastRestoreCompletedAt": Time(now),
"consecutiveRestoreFailures": 0,
}
});
replicas
.patch_status(
&name,
&PatchParams::apply("postgres-restore-operator"),
&Patch::Merge(&patch),
)
.await?;
// Clear the scheduling-suspended condition if it was set
if replica
.status
.as_ref()
.and_then(|s| {
s.conditions
.iter()
.find(|c| c.type_ == "RestoreSchedulingSuspended")
})
.is_some_and(|c| c.status == "True")
{
replica
.update_condition(
client,
"RestoreSchedulingSuspended",
"False",
"RestoreSucceeded",
"Consecutive failure counter reset after successful restore",
)
.await?;
}
ctx.metrics.switchovers_total.inc();
// Record event on replica CR
if let Err(e) = ctx
.recorder
.publish(
&Event {
type_: EventType::Normal,
reason: "RestoreCompleted".into(),
note: Some(format!("Switchover to restore {switching_name} completed")),
action: "Restore".into(),
secondary: Some(switching.object_ref(&())),
},
&replica.object_ref(&()),
)
.await
{
warn!(replica = name, error = %e, "failed to publish RestoreCompleted event");
}
// Send notifications
replica
.send_notifications(client, &ctx.http_client, switching, &ctx.metrics)
.await;
return Ok(Action::requeue(Duration::from_secs(10)));
}
// Sweep stale Active restores after grace period.
//
// Any Active restore for this replica that isn't the current one is a
// leftover from a prior cycle and should be deleted once the grace
// period elapses. Sweep-based rather than tracking a single
// `previousRestore` pointer means cleanup converges even if multiple
// stale restores accumulate (e.g. from a bug or operator restart
// during a switchover).
let current_restore_name = replica
.status
.as_ref()
.and_then(|s| s.current_restore.as_deref());
if let Some(current) = current_restore_name {
// Gate the sweep on "migration isn't actively in flight": the
// gate's only purpose is to keep us from deleting the migration's
// source restore while pg_dump | psql still has it open. Any
// terminal phase (`complete`, `partial`, `timeout-skipped`,
// `failed: …`) — and `None` (no migration has run since this
// replica was first reconciled, or a previous sweep cleared the
// field) — all mean "no migration in flight, sweep is safe".
//
// Coded as "not in flight" rather than enumerating every terminal
// phase so future additions don't have to remember to update this
// gate. Previously this was an allow-list of `complete`/`partial`,
// which silently blocked the sweep when `timeout-skipped` was
// added — the replica then accumulated stale Active restores,
// hit the too-many-restores guardrail, and couldn't recover
// automatically.
let migration_complete = persistent_schemas_migration_settled(&replica);
let grace_period =
SignedDuration::try_from(replica.spec.switchover_grace_period.0).unwrap_or_default();
let last_completed = replica
.status
.as_ref()
.and_then(|s| s.last_restore_completed_at.as_ref());
// Refuse to sweep if status.currentRestore doesn't match any live
// Active restore — likely an inconsistent state where another path
// (manual intervention, controller startup) should resolve it.
// Filter on Active phase too so the sweep can't fire while the
// "current" is mid-switchover, even if a future flow change lets
// this block run with a non-Active current.
let has_matching_current = restore_list.items.iter().any(|r| {
r.name_any() == current
&& r.status.as_ref().and_then(|s| s.phase.as_ref()) == Some(&RestorePhase::Active)
});
if migration_complete
&& has_matching_current
&& let Some(completed_at) = last_completed
&& now.duration_since(completed_at.0) > grace_period
{
let stale: Vec<String> = restore_list
.items
.iter()
.filter(|r| {
r.status.as_ref().and_then(|s| s.phase.as_ref()) == Some(&RestorePhase::Active)
&& r.name_any() != current
})
.map(|r| r.name_any())
.collect();
if !stale.is_empty() {
info!(
replica = name,
count = stale.len(),
current = current,
"sweeping stale Active restores after grace period"
);
let mut all_deleted = true;
for stale_name in &stale {
if let Err(e) = restores.delete(stale_name, &Default::default()).await {
warn!(restore = stale_name, error = %e, "failed to delete stale restore");
all_deleted = false;
}
}
// Only clear schemaMigrationPhase if every delete succeeded.
// Clearing it while a stale restore survives would set
// migration_complete=false on the next reconcile (when
// persistent_schemas is configured), blocking the sweep
// from retrying until the next switchover re-marks
// complete. Leave the next reconcile to retry instead.
if all_deleted {
let replicas: Api<PostgresPhysicalReplica> =
Api::namespaced(client.clone(), &namespace);
let patch = serde_json::json!({
"status": {
"previousRestore": null,
"schemaMigrationJob": null,
"schemaMigrationPhase": null,
}
});
replicas
.patch_status(
&name,
&PatchParams::apply("postgres-restore-operator"),
&Patch::Merge(&patch),
)
.await?;
} else {
warn!(
replica = name,
"some stale restores failed to delete; leaving schemaMigrationPhase set so next reconcile retries"
);
}
}
}
}
// Clean up failed restores.
// We explicitly delete associated pods before deleting the restore CR
// because Kubernetes cascade deletion can leave pods orphaned, and the
// pvc-protection finalizer blocks PVC deletion while any pod still
// references the PVC.
let failed_restores: Vec<_> = restore_list
.items
.iter()
.filter(|r| r.status.as_ref().and_then(|s| s.phase.as_ref()) == Some(&RestorePhase::Failed))
.collect();
let pods: Api<Pod> = Api::namespaced(client.clone(), &namespace);
for failed in &failed_restores {
let failed_name = failed.name_any();
if let Some(created_at) = failed.status.as_ref().and_then(|s| s.created_at.as_ref()) {
let age = now.duration_since(created_at.0);
if age > SignedDuration::from_secs(300) {
info!(
replica = name,
restore = failed_name,
"cleaning up failed restore"
);
// Delete pods by label first so PVC protection finalizers can resolve
if let Ok(pod_list) = pods
.list(
&kube::api::ListParams::default()
.labels(&format!("pgro.bes.au/restore={failed_name}")),
)
.await
{
for pod in &pod_list.items {
let pod_name = pod.metadata.name.as_deref().unwrap_or("");
if let Err(e) = pods.delete(pod_name, &Default::default()).await {
warn!(pod = pod_name, error = %e, "failed to delete pod for failed restore");
}
}
}
if let Err(e) = restores.delete(&failed_name, &Default::default()).await {
warn!(restore = failed_name, error = %e, "failed to delete failed restore");
}
}
}
}
// Sweep for orphaned pods: pods with a pgro.bes.au/replica label but no
// ownerReferences. These can be left behind when cascade deletion from a
// restore CR (or the replica CR for snapshot-list jobs) fails to
// propagate to the Job's pods.
let known_restores: HashSet<String> = restore_list.items.iter().map(|r| r.name_any()).collect();
if let Ok(all_replica_pods) = pods
.list(&kube::api::ListParams::default().labels(&format!("pgro.bes.au/replica={name}")))
.await
{
for pod in &all_replica_pods.items {
let has_owner = pod
.metadata
.owner_references
.as_ref()
.is_some_and(|refs| !refs.is_empty());
if has_owner {
continue;
}
let labels = pod.metadata.labels.as_ref();
let restore_label = labels.and_then(|l| l.get("pgro.bes.au/restore"));
let job_type_label = labels.and_then(|l| l.get("pgro.bes.au/job-type"));
// Skip pods whose restore CR still exists
if let Some(restore_name) = restore_label
&& known_restores.contains(restore_name)
{
continue;
}
let pod_name = pod.metadata.name.as_deref().unwrap_or("");
let reason = if let Some(restore_name) = restore_label {
format!("restore {restore_name} no longer exists")
} else if let Some(job_type) = job_type_label {
format!("orphaned {job_type} pod")
} else {
"orphaned pod with no restore or job-type label".to_string()
};
info!(pod = pod_name, reason, "deleting orphaned pod");
if let Err(e) = pods.delete(pod_name, &Default::default()).await {
warn!(pod = pod_name, error = %e, "failed to delete orphaned pod");
}
}
}
// Process any existing snapshot-list job regardless of scheduling state.
// This runs before the in-progress / should_restore gates so that
// completed jobs are always cleaned up promptly.
let snapshot_job_name = format!("{name}-snapshot-list");
let jobs: Api<Job> = Api::namespaced(client.clone(), &namespace);
let snapshot_job = jobs.get_opt(&snapshot_job_name).await?;
if let Some(ref job) = snapshot_job {
match classify_job(job) {
JobStatus::Succeeded => {
let raw = ctx.snapshot_results.take(&namespace, &name);
let Some(ref raw) = raw else {
let completion_time =
job.status.as_ref().and_then(|s| s.completion_time.as_ref());
let stale = completion_time
.is_some_and(|t| now.duration_since(t.0) > SignedDuration::from_secs(60));
if stale {
warn!(
replica = name,
job = snapshot_job_name,
"snapshot list job results unreadable after 60s, deleting stale job"
);
if let Err(e) = jobs.delete(&snapshot_job_name, &Default::default()).await {
warn!(job = snapshot_job_name, error = %e, "failed to delete stale snapshot list job");
}
return Ok(Action::requeue(Duration::from_secs(10)));
}
info!(
replica = name,
job = snapshot_job_name,
"snapshot list job succeeded but results not yet available, retrying"
);
return Ok(Action::requeue(Duration::from_secs(5)));
};
// We have the data — safe to delete the job now.
if let Err(e) = jobs.delete(&snapshot_job_name, &Default::default()).await {
warn!(job = snapshot_job_name, error = %e, "failed to delete snapshot list job");
}
match kopia::parse_snapshot_list_output(raw) {
Ok(all_snapshots) => {
let filtered = kopia::filter_snapshots(
&all_snapshots,
replica.spec.snapshot_filter.as_ref(),
);
let latest = kopia::latest_snapshot(&filtered);
if let Some(snap) = latest {
let size = snap.total_size_bytes();
replica
.update_status_field(client, "latestAvailableSnapshot", &snap.id)
.await?;
replica
.update_condition(
client,
"SnapshotAvailable",
"True",
"SnapshotFound",
&format!("Snapshot {} available ({size} bytes)", snap.id),
)
.await?;
let current_snapshot_id =
active_restore.map(|r| r.spec.snapshot.as_str());
if current_snapshot_id == Some(&snap.id) {
debug!(
replica = name,
snapshot = snap.id,
"latest snapshot already active, skipping"
);
} else {
info!(
replica = name,
snapshot = snap.id,
size,
"new snapshot available, creating restore"
);
let info = SnapshotInfo {
id: snap.id.clone(),
size,
start_time: snap.start_time.clone(),
};
let created =
replica.create_restore_for_snapshot(client, &info).await?;
if created {
ctx.metrics.restores_started_total.inc();
if let Err(e) = ctx
.recorder
.publish(
&Event {
type_: EventType::Normal,
reason: "RestoreStarted".into(),
note: Some(format!(
"Started restore from snapshot {}",
snap.id
)),
action: "Restore".into(),
secondary: None,
},
&replica.object_ref(&()),
)
.await
{
warn!(replica = name, error = %e, "failed to publish RestoreStarted event");
}
} else if let Err(e) = ctx
.recorder
.publish(
&Event {
type_: EventType::Warning,
reason: "RestoreCreationBlocked".into(),
note: Some(format!(
"Refused to create restore for snapshot {} — \
too many restores already exist",
snap.id
)),
action: "Restore".into(),
secondary: None,
},
&replica.object_ref(&()),
)
.await
{
warn!(replica = name, error = %e, "failed to publish RestoreCreationBlocked event");
}
}
} else {
warn!(
replica = name,
"snapshot list job returned no matching snapshots"
);
replica
.update_condition(
client,
"SnapshotAvailable",
"False",
"NoMatchingSnapshots",
"Snapshot list job returned no snapshots matching the configured filter",
)
.await?;
}
}
Err(e) => {
warn!(
replica = name,
error = %e,
"failed to parse snapshot list job output"
);
replica
.update_condition(
client,
"SnapshotAvailable",
"False",
"ParseError",
&format!("Failed to parse snapshot list output: {e}"),
)
.await?;
}
}
}
JobStatus::Failed => {
warn!(replica = name, "snapshot list job failed");
// Extend the TTL to 24 hours so the failed Job's pods (and
// their logs) stick around long enough for someone to
// investigate. We deliberately do *not* proactively delete
// failed Jobs the way we do for successful ones.
const FAILED_JOB_TTL_SECS: i32 = 86_400; // 24 hours
let ttl_patch = serde_json::json!({
"spec": { "ttlSecondsAfterFinished": FAILED_JOB_TTL_SECS }
});
if let Err(e) = jobs
.patch(
&snapshot_job_name,
&PatchParams::apply("postgres-restore-operator"),
&Patch::Merge(&ttl_patch),
)
.await
{
warn!(job = snapshot_job_name, error = %e, "failed to extend TTL on failed snapshot list job");
}
replica
.update_condition(
client,
"SnapshotAvailable",
"False",
"JobFailed",
"Snapshot list job failed, check job logs for details",
)
.await?;
}
JobStatus::Active => {
return Ok(Action::requeue(Duration::from_secs(10)));
}
}
}
// Clear the legacy RestoreSchedulingSuspended condition on existing
// replicas if still True (left over from the suspension behaviour we
// removed — see commit dropping MAX_CONSECUTIVE_FAILURES). The
// operator no longer suspends; bounded backoff via
// scheduling::failure_backoff_delay is the new rate limit, applied in
// fail_restore when each failure increments the counter.
if replica
.status
.as_ref()
.and_then(|s| {
s.conditions
.iter()
.find(|c| c.type_ == "RestoreSchedulingSuspended")
})
.is_some_and(|c| c.status == "True")
{
info!(
replica = name,
"clearing legacy RestoreSchedulingSuspended condition (suspension removed)"
);
replica
.update_condition(
client,
"RestoreSchedulingSuspended",
"False",
"SuspensionRemoved",
"Operator no longer suspends on consecutive failures; backoff is used instead",
)
.await?;
}
// Decide whether to trigger a new restore
if let Some(in_progress) = in_progress_restore {
let phase = in_progress.status.as_ref().and_then(|s| s.phase.as_ref());
debug!(
replica = name,
restore = in_progress.name_any(),
phase = ?phase,
"restore already in progress, waiting"
);
replica
.update_phase(client, ReplicaPhase::Restoring)
.await?;
return Ok(Action::requeue(Duration::from_secs(30)));
}
let never_restored = active_restore.is_none()
&& replica
.status
.as_ref()
.and_then(|s| s.last_restore_completed_at.as_ref())
.is_none();
// Detect when the active Restore CR referenced in status has been deleted
let active_restore_deleted = active_restore.is_none()
&& in_progress_restore.is_none()
&& replica
.status
.as_ref()
.and_then(|s| s.current_restore.as_ref())
.is_some();
// Detect if the schedule or jitter has changed since we last computed nextScheduledRestore
let current_hash = replica.schedule_input_hash();
let schedule_changed = replica
.status
.as_ref()
.and_then(|s| s.schedule_input_hash.as_ref())
.is_none_or(|h| h != ¤t_hash);
// Recompute nextScheduledRestore when missing or when schedule config changed
if (schedule_changed
|| replica
.status
.as_ref()
.and_then(|s| s.next_scheduled_restore.as_ref())
.is_none())
&& let Some(next) = replica.compute_next_scheduled_restore(now)
{
if schedule_changed {
debug!(
replica = %name,
schedule = %replica.spec.schedule,
jitter = %replica.spec.schedule_jitter,
next = %next,
"schedule config changed, recomputing nextScheduledRestore"
);
}
replica
.update_schedule_status(client, next, ¤t_hash)
.await?;
}
if never_restored {
info!(
replica = name,
"no successful restore yet, triggering immediately"
);
}
if active_restore_deleted {
info!(
replica = name,
"active restore CR was deleted, triggering immediate replacement"
);
}
let schedule_decision = replica.check_schedule();
let should_restore = never_restored
|| active_restore_deleted
|| matches!(schedule_decision, ScheduleDecision::Trigger);
if should_restore && snapshot_job.is_none() {
// Check concurrent restore limit
let mut queue = ctx.restore_queue.write().await;
if !queue.can_start(ctx.max_concurrent_restores()) {
queue.enqueue(name.clone());
let position = queue.position(&name);
let pending_len = queue.pending.len();
drop(queue);
let replicas: Api<PostgresPhysicalReplica> =
Api::namespaced(client.clone(), &namespace);
let patch = serde_json::json!({
"status": {
"queuePosition": position,
}
});
replicas
.patch_status(
&name,
&PatchParams::apply("postgres-restore-operator"),
&Patch::Merge(&patch),
)
.await?;
ctx.metrics.queue_depth.set(pending_len as i64);
return Ok(Action::requeue(Duration::from_secs(30)));
}
drop(queue);
info!(replica = name, "creating snapshot list job");
let callback_url = ctx.snapshot_callback_url(&namespace, &name);
let job = build_snapshot_list_job(
&replica,
&snapshot_job_name,
&namespace,
&ctx.kopia_image(),
&callback_url,
)?;
jobs.create(&PostParams::default(), &job).await?;
return Ok(Action::requeue(Duration::from_secs(10)));
}
// Advance the schedule only after the restore decision has been fully
// processed (or skipped by TTL). Bumping before the should_restore
// block caused watch-triggered reconciliations to see the future
// nextScheduledRestore and skip snapshot-job processing entirely.
if matches!(
schedule_decision,
ScheduleDecision::Trigger | ScheduleDecision::SkippedByTtl
) && let Some(next) = replica.compute_next_scheduled_restore(now)
{
replica
.update_schedule_status(client, next, ¤t_hash)
.await?;
}
// Update phase based on current state
if active_restore.is_some() {
replica.update_phase(client, ReplicaPhase::Ready).await?;
} else {
replica.update_phase(client, ReplicaPhase::Pending).await?;
}
// Clear queue position if not queued
let replicas: Api<PostgresPhysicalReplica> = Api::namespaced(client.clone(), &namespace);
let patch = serde_json::json!({
"status": {
"queuePosition": 0,
}
});
replicas
.patch_status(
&name,
&PatchParams::apply("postgres-restore-operator"),
&Patch::Merge(&patch),
)
.await?;
Ok(Action::requeue(Duration::from_secs(300)))
}
/// Reconcile schema migration for persistent_schemas configuration.
///
/// This function manages the migration of specified schemas from the previous
/// restore to the new restore during switchover. It creates and monitors a
/// Kubernetes Job that runs pg_dump|psql to transfer the schemas.
///
/// Returns `Ok(true)` when migration is complete (or skipped), `Ok(false)` when
/// in progress, or `Err` on permanent failure.
/// Returns true if a tokio_postgres error is an authentication failure.
/// We detect this by inspecting the SQLSTATE code (28P01 = invalid_password,
/// 28000 = invalid_authorization_specification) and the error message text as
/// a fallback for cases where the code is not surfaced.
fn is_auth_error(e: &Error) -> bool {
let Error::Postgres(pg_err) = e else {
return false;
};
if let Some(db_err) = pg_err.as_db_error() {
let code = db_err.code();
return code == &tokio_postgres::error::SqlState::INVALID_PASSWORD
|| code == &tokio_postgres::error::SqlState::INVALID_AUTHORIZATION_SPECIFICATION;
}
// Fallback: match the error message text that Postgres emits for auth failures.
let msg = pg_err.to_string().to_lowercase();
msg.contains("password authentication failed") || msg.contains("no password assigned")
}
/// Ensure the credential-reset Job exists and has run for the given restore.
///
/// The sequence is:
/// 1. Scale the restore deployment to 0 (so the PVC is free).
/// 2. Create a Job that uses `postgres --single` to ALTER ROLE.
/// 3. While the job is running, return `Ok(false)` (caller retries).
/// 4. When the job succeeds, scale the deployment back to 1 and return
/// `Ok(true)` so the caller re-attempts the connection on the next loop.
/// 5. If the job fails, log a warning and return `Ok(false)` — it will be
/// retried on the next reconcile once the job has been deleted.
///
/// Idempotent: safe to call repeatedly while the job is in flight.
async fn ensure_credential_reset(
client: &Client,
namespace: &str,
restore: &PostgresPhysicalRestore,
replica: &PostgresPhysicalReplica,
) -> Result<bool> {
let restore_name = restore.name_any();
let job_name = credential_reset_job_name(&restore_name);
let jobs: Api<Job> = Api::namespaced(client.clone(), namespace);
let deployments: Api<Deployment> = Api::namespaced(client.clone(), namespace);
// Check for an existing reset job first.
if let Some(job) = jobs.get_opt(&job_name).await? {
match classify_job(&job) {
JobStatus::Active => {
// Still running — nothing to do yet.
return Ok(false);
}
JobStatus::Succeeded => {
info!(
restore = %restore_name,
job = %job_name,
"credential reset job succeeded, scaling deployment back up"
);
// Scale the deployment back to 1.
let scale_patch = serde_json::json!({
"spec": { "replicas": 1 }
});
if let Err(e) = deployments
.patch(
&restore_name,
&PatchParams::apply("postgres-restore-operator"),
&Patch::Merge(&scale_patch),
)
.await
{
warn!(restore = %restore_name, error = %e, "failed to scale deployment back up after credential reset");
}
// Delete the completed job.
if let Err(e) = jobs.delete(&job_name, &Default::default()).await {
warn!(job = %job_name, error = %e, "failed to delete completed credential reset job");
}
// Return true: credentials are fixed, caller should retry connection.
return Ok(true);
}
JobStatus::Failed => {
warn!(
restore = %restore_name,
job = %job_name,
"credential reset job failed; will retry on next reconcile"
);
// Delete the failed job so we create a fresh one next time.
if let Err(e) = jobs.delete(&job_name, &Default::default()).await {
warn!(job = %job_name, error = %e, "failed to delete failed credential reset job");
}
// Scale back up so the restore remains accessible in the meantime.
let scale_patch = serde_json::json!({
"spec": { "replicas": 1 }
});
if let Err(e) = deployments
.patch(