-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.rs
More file actions
648 lines (587 loc) · 19.4 KB
/
Copy pathtests.rs
File metadata and controls
648 lines (587 loc) · 19.4 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
use std::collections::BTreeMap;
use jiff::Span;
use k8s_openapi::api::core::v1::{
Affinity, LocalObjectReference, NodeAffinity, NodeSelector, NodeSelectorRequirement,
NodeSelectorTerm, ResourceRequirements, SecretReference,
};
use k8s_openapi::apimachinery::pkg::api::resource::Quantity;
use kube::ResourceExt;
use super::builders::{build_deployment, build_restore_job, build_version_detect_job};
use crate::{types::*, util::TimeSpan};
#[test]
fn deployment_uses_affinity_not_node_selector() {
let mut replica = PostgresPhysicalReplica::new(
"test-replica",
PostgresPhysicalReplicaSpec {
kopia_secret_ref: SecretReference {
name: Some("kopia-secret".to_string()),
namespace: None,
},
snapshot_filter: None,
schedule: "0 */6 * * *".into(),
schedule_jitter: TimeSpan(Span::new().minutes(10)),
minimum_ttl: None,
switchover_grace_period: TimeSpan(Span::new().minutes(5)),
analytics_username: "analytics".to_string(),
storage_class: None,
storage_size_override: None,
resources: None,
service_annotations: None,
pod_annotations: None,
affinity: None,
tolerations: vec![],
read_only: true,
postgres_extra_config: None,
notifications: vec![],
persistent_schemas: None,
storage_size_maximum: Quantity("2Ti".to_string()),
event_publisher: None,
},
);
replica.spec.affinity = Some(Affinity {
node_affinity: Some(NodeAffinity {
required_during_scheduling_ignored_during_execution: Some(NodeSelector {
node_selector_terms: vec![NodeSelectorTerm {
match_expressions: Some(vec![NodeSelectorRequirement {
key: "kubernetes.io/os".to_string(),
operator: "In".to_string(),
values: Some(vec!["linux".to_string()]),
}]),
..Default::default()
}],
}),
..Default::default()
}),
pod_affinity: None,
pod_anti_affinity: None,
});
let mut restore = PostgresPhysicalRestore::new(
"test-restore",
PostgresPhysicalRestoreSpec {
replica: LocalObjectReference {
name: "test-replica".to_string(),
},
snapshot: "snap123".to_string(),
snapshot_size: Quantity("10Gi".to_string()),
snapshot_time: None,
storage_size: Quantity("11Gi".to_string()),
},
);
restore.metadata.uid = Some("uid-123".to_string());
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy
.spec
.as_ref()
.unwrap()
.template
.spec
.as_ref()
.unwrap();
assert!(
pod_spec.affinity.is_some(),
"pod spec must have affinity set"
);
assert!(
pod_spec.node_selector.is_none(),
"pod spec must not have node_selector"
);
}
fn test_restore_and_replica() -> (PostgresPhysicalRestore, PostgresPhysicalReplica) {
let replica = PostgresPhysicalReplica::new(
"test-replica",
PostgresPhysicalReplicaSpec {
kopia_secret_ref: SecretReference {
name: Some("kopia-secret".to_string()),
namespace: None,
},
snapshot_filter: None,
schedule: "0 */6 * * *".into(),
schedule_jitter: TimeSpan(Span::new().minutes(10)),
minimum_ttl: None,
switchover_grace_period: TimeSpan(Span::new().minutes(5)),
analytics_username: "analytics".to_string(),
storage_class: None,
storage_size_override: None,
resources: None,
service_annotations: None,
pod_annotations: None,
affinity: None,
tolerations: vec![],
read_only: true,
postgres_extra_config: None,
notifications: vec![],
persistent_schemas: None,
storage_size_maximum: Quantity("2Ti".to_string()),
event_publisher: None,
},
);
let mut restore = PostgresPhysicalRestore::new(
"test-restore",
PostgresPhysicalRestoreSpec {
replica: LocalObjectReference {
name: "test-replica".to_string(),
},
snapshot: "snap123".to_string(),
snapshot_size: Quantity("10Gi".to_string()),
snapshot_time: None,
storage_size: Quantity("11Gi".to_string()),
},
);
restore.metadata.uid = Some("uid-123".to_string());
(restore, replica)
}
#[test]
fn restore_job_has_ttl_seconds_after_finished() {
let (restore, replica) = test_restore_and_replica();
let job = build_restore_job(
&restore,
"test-restore-restore",
"default",
&replica,
"kopia:latest",
)
.unwrap();
let ttl = job
.spec
.as_ref()
.unwrap()
.ttl_seconds_after_finished
.expect("restore job must set ttlSecondsAfterFinished");
assert!(ttl > 0, "ttlSecondsAfterFinished must be positive");
}
#[test]
fn restore_job_mounts_persistent_kopia_cache() {
// Kopia's cache and logs used to land on the pod's writable layer at
// /tmp/kopia, causing the restore pod to be evicted under
// ephemeral-storage pressure (observed in production at ~10 GiB
// usage). Mount a per-replica PVC at /tmp/kopia so the cache persists
// across restores and doesn't count toward ephemeral-storage.
let (restore, replica) = test_restore_and_replica();
let job = build_restore_job(
&restore,
"test-restore-restore",
"default",
&replica,
"kopia:latest",
)
.unwrap();
let pod_spec = job.spec.unwrap().template.spec.unwrap();
let volumes = pod_spec.volumes.as_ref().expect("pod must declare volumes");
let cache_volume = volumes
.iter()
.find(|v| v.name == "kopia-cache")
.expect("restore Job pod must include a kopia-cache volume");
let claim_name = cache_volume
.persistent_volume_claim
.as_ref()
.expect("kopia-cache volume must reference a PVC")
.claim_name
.as_str();
assert_eq!(
claim_name,
super::builders::kopia_cache_pvc_name(&restore.spec.replica.name),
"kopia-cache volume must reference the per-replica cache PVC"
);
let mounts = pod_spec.containers[0]
.volume_mounts
.as_ref()
.expect("restore container must declare volume mounts");
assert!(
mounts
.iter()
.any(|m| m.name == "kopia-cache" && m.mount_path == "/tmp/kopia"),
"restore container must mount kopia-cache at /tmp/kopia"
);
}
#[test]
fn kopia_cache_pvc_owned_by_replica() {
let (restore, replica) = test_restore_and_replica();
let pvc =
super::builders::build_kopia_cache_pvc(&replica, &restore.spec.snapshot_size, "default");
let owner_refs = pvc
.metadata
.owner_references
.as_ref()
.expect("cache PVC must have owner references");
assert_eq!(owner_refs.len(), 1);
assert_eq!(owner_refs[0].kind, "PostgresPhysicalReplica");
assert_eq!(owner_refs[0].name, replica.name_any());
let access_modes = pvc
.spec
.as_ref()
.unwrap()
.access_modes
.as_ref()
.expect("cache PVC must declare access modes");
assert_eq!(access_modes, &vec!["ReadWriteOnce".to_string()]);
}
#[test]
fn cache_size_needs_grow_ratchet() {
let small = Quantity("10Gi".to_string());
let bigger = Quantity("20Gi".to_string());
assert!(
super::builders::cache_size_needs_grow(&small, &bigger),
"must grow when desired > current"
);
assert!(
!super::builders::cache_size_needs_grow(&bigger, &small),
"must NOT shrink when desired < current"
);
assert!(
!super::builders::cache_size_needs_grow(&small, &small),
"equal sizes must not trigger a grow"
);
}
#[test]
fn kopia_cache_pvc_size_floors_at_10gi() {
// For a small snapshot, 20% would be sub-Gi; the floor catches that.
let small = Quantity("1Gi".to_string());
let size = super::builders::kopia_cache_pvc_size(&small);
let parsed = kube_quantity::ParsedQuantity::try_from(size).unwrap();
let floor = kube_quantity::ParsedQuantity::try_from("10Gi").unwrap();
assert!(
parsed >= floor,
"sub-floor snapshot must clamp to at least 10Gi"
);
}
#[test]
fn kopia_cache_pvc_size_scales_with_snapshot() {
// For a 100Gi snapshot, 20% = 20Gi which is above the 10Gi floor.
let big = Quantity("100Gi".to_string());
let size = super::builders::kopia_cache_pvc_size(&big);
let parsed = kube_quantity::ParsedQuantity::try_from(size).unwrap();
let expected = kube_quantity::ParsedQuantity::try_from("20Gi").unwrap();
let floor = kube_quantity::ParsedQuantity::try_from("10Gi").unwrap();
assert!(parsed > floor, "100Gi snapshot must not hit the floor");
assert_eq!(
parsed, expected,
"100Gi snapshot must produce exactly 20Gi cache"
);
}
#[test]
fn version_detect_job_has_ttl_seconds_after_finished() {
let (restore, _replica) = test_restore_and_replica();
let job = build_version_detect_job(&restore, "test-version-detect", "default", "test-pvc");
let ttl = job
.spec
.as_ref()
.unwrap()
.ttl_seconds_after_finished
.expect("version-detect job must set ttlSecondsAfterFinished");
assert!(ttl > 0, "ttlSecondsAfterFinished must be positive");
}
#[test]
fn deployment_has_dshm_volume_with_default_resources() {
let (mut restore, replica) = test_restore_and_replica();
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let dshm_vol = pod_spec
.volumes
.as_ref()
.unwrap()
.iter()
.find(|v| v.name == "dshm")
.expect("dshm volume must exist");
let empty_dir = dshm_vol.empty_dir.as_ref().expect("dshm must be emptyDir");
assert_eq!(empty_dir.medium.as_deref(), Some("Memory"));
// Default 1Gi request: min(512Mi, ceil(36% of 1Gi)) = min(512Mi, 369Mi) = 369Mi
assert_eq!(empty_dir.size_limit.as_ref().unwrap().0, "369Mi");
}
#[test]
fn deployment_has_dshm_volume_with_custom_resources() {
let (mut restore, mut replica) = test_restore_and_replica();
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
replica.spec.resources = Some(ResourceRequirements {
requests: Some(BTreeMap::from([(
"memory".to_string(),
Quantity("4Gi".to_string()),
)])),
limits: Some(BTreeMap::from([(
"memory".to_string(),
Quantity("8Gi".to_string()),
)])),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let dshm_vol = pod_spec
.volumes
.as_ref()
.unwrap()
.iter()
.find(|v| v.name == "dshm")
.expect("dshm volume must exist");
let empty_dir = dshm_vol.empty_dir.as_ref().expect("dshm must be emptyDir");
assert_eq!(empty_dir.medium.as_deref(), Some("Memory"));
// 4Gi request, 8Gi limit: min(4Gi/2, ceil(36% of 8Gi)) = min(2048Mi, 2950Mi) = 2048Mi
assert_eq!(empty_dir.size_limit.as_ref().unwrap().0, "2048Mi");
}
#[test]
fn deployment_mounts_dshm_on_postgres_and_setup_auth() {
let (mut restore, replica) = test_restore_and_replica();
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let postgres = &pod_spec.containers[0];
assert_eq!(postgres.name, "postgres");
let pg_mounts = postgres.volume_mounts.as_ref().unwrap();
let pg_shm = pg_mounts
.iter()
.find(|m| m.mount_path == "/dev/shm")
.expect("postgres container must mount /dev/shm");
assert_eq!(pg_shm.name, "dshm");
let setup_auth = pod_spec
.init_containers
.as_ref()
.unwrap()
.iter()
.find(|c| c.name == "setup-auth")
.expect("setup-auth init container must exist");
let sa_mounts = setup_auth.volume_mounts.as_ref().unwrap();
assert!(
!sa_mounts.iter().any(|m| m.mount_path == "/dev/shm"),
"setup-auth must NOT mount /dev/shm (it never uses shared memory)"
);
}
#[test]
fn deployment_init_script_sets_shared_buffers() {
let (mut restore, replica) = test_restore_and_replica();
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let setup_auth = pod_spec
.init_containers
.as_ref()
.unwrap()
.iter()
.find(|c| c.name == "setup-auth")
.expect("setup-auth init container must exist");
let script = &setup_auth.args.as_ref().unwrap()[0];
// Default 1Gi: SHM=369Mi, shared_buffers = floor(70% of 369) = 258MB
assert!(
script.contains("shared_buffers = 258MB"),
"init script must set shared_buffers to computed value, got script containing: {}",
script
.lines()
.find(|l| l.contains("shared_buffers"))
.unwrap_or("<not found>")
);
// The sed block must strip shared_buffers from source config
assert!(
script.contains("shared_buffers[[:space:]]*="),
"sed must strip shared_buffers from source config"
);
}
#[test]
fn deployment_init_script_grants_superuser_for_read_write() {
// Read-write restores grant SUPERUSER to the analytics user. The
// granular pg_*_all_data + pg_maintain + CREATE ON DATABASE set was
// tried and didn't cover DDL on existing schemas the user does not own
// (CREATE TABLE in public on PG >= 15, dropping persistent_schemas
// owned by other users on migration). Falling back to superuser keeps
// the use cases working on every PG version.
let (mut restore, mut replica) = test_restore_and_replica();
replica.spec.read_only = false;
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("18".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let setup_auth = pod_spec
.init_containers
.as_ref()
.unwrap()
.iter()
.find(|c| c.name == "setup-auth")
.expect("setup-auth init container must exist");
let script = &setup_auth.args.as_ref().unwrap()[0];
assert!(
script.contains("ALTER ROLE ${ANALYTICS_USERNAME} WITH SUPERUSER"),
"read-write init script must grant superuser to analytics"
);
assert!(
!script.contains("GRANT pg_write_all_data"),
"read-write init script must not use the predefined pg_write_all_data role"
);
}
#[test]
fn deployment_init_script_grants_read_only_on_pg14_plus() {
// PG >= 14 read-only uses pg_read_all_data instead of superuser to keep
// the surface area minimal. Below PG 14 the read-only path falls through
// to the superuser branch (no predefined read role).
let (mut restore, mut replica) = test_restore_and_replica();
replica.spec.read_only = true;
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("18".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let setup_auth = pod_spec
.init_containers
.as_ref()
.unwrap()
.iter()
.find(|c| c.name == "setup-auth")
.expect("setup-auth init container must exist");
let script = &setup_auth.args.as_ref().unwrap()[0];
assert!(
script.contains("GRANT pg_read_all_data TO ${ANALYTICS_USERNAME}"),
"read-only init script must grant pg_read_all_data"
);
}
#[test]
fn deployment_init_script_overrides_listen_addresses() {
// Some source backups carry `listen_addresses = 'localhost'` in
// postgresql.conf, which restricts the restored postgres to localhost
// only and breaks operator → restore connections (e.g. schema
// migration discovery). Strip the source value and append our own '*'
// so the restored pod is reachable on the pod IP.
let (mut restore, replica) = test_restore_and_replica();
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let setup_auth = pod_spec
.init_containers
.as_ref()
.unwrap()
.iter()
.find(|c| c.name == "setup-auth")
.expect("setup-auth init container must exist");
let script = &setup_auth.args.as_ref().unwrap()[0];
assert!(
script.contains("listen_addresses[[:space:]]*="),
"sed must strip listen_addresses from source config"
);
assert!(
script.contains(r#"listen_addresses = '*'"#),
"init script must append listen_addresses = '*' override"
);
}
#[test]
fn init_script_sets_initial_stage_based_on_reindex_flag() {
let (mut restore, replica) = test_restore_and_replica();
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let setup_auth = pod_spec
.init_containers
.as_ref()
.unwrap()
.iter()
.find(|c| c.name == "setup-auth")
.expect("setup-auth init container must exist");
let script = &setup_auth.args.as_ref().unwrap()[0];
assert!(
script.contains("stage text NOT NULL DEFAULT 'restored'"),
"table must include stage column"
);
assert!(
script.contains("last_transition_time timestamptz NOT NULL DEFAULT now()"),
"table must include last_transition_time column"
);
assert!(
script.contains("ADD COLUMN IF NOT EXISTS stage"),
"must add stage column for existing tables carried in snapshot"
);
assert!(
script.contains("ADD COLUMN IF NOT EXISTS last_transition_time"),
"must add last_transition_time column for existing tables carried in snapshot"
);
assert!(
script.contains("PGRO_STAGE=restored") && script.contains("PGRO_STAGE=ready"),
"init must pick stage based on needs-reindex flag"
);
assert!(
script.contains("'${PGRO_STAGE}'"),
"insert must use the chosen stage"
);
}
#[test]
fn postgres_container_updates_stage_around_reindex() {
let (mut restore, replica) = test_restore_and_replica();
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let postgres = pod_spec
.containers
.iter()
.find(|c| c.name == "postgres")
.expect("postgres container must exist");
let script = &postgres.args.as_ref().unwrap()[0];
let reindexing_pos = script
.find("stage = 'reindexing'")
.expect("must update stage to reindexing before the REINDEX loop");
let ready_pos = script
.find("stage = 'ready'")
.expect("must update stage to ready after the REINDEX loop");
assert!(
reindexing_pos < ready_pos,
"reindexing update must come before ready update"
);
assert!(
reindexing_pos < script.find("REINDEX INDEX").unwrap(),
"reindexing update must come before any REINDEX call"
);
assert!(
script[..ready_pos].contains("rm -f /pgdata/needs-reindex"),
"ready update must happen after the needs-reindex flag is cleared"
);
}
#[test]
fn deployment_shared_buffers_with_custom_resources() {
let (mut restore, mut replica) = test_restore_and_replica();
restore.status = Some(PostgresPhysicalRestoreStatus {
postgres_version: Some("16".to_string()),
..Default::default()
});
replica.spec.resources = Some(ResourceRequirements {
requests: Some(BTreeMap::from([(
"memory".to_string(),
Quantity("2Gi".to_string()),
)])),
..Default::default()
});
let deploy = build_deployment(&restore, "test-restore", "default", &replica).unwrap();
let pod_spec = deploy.spec.unwrap().template.spec.unwrap();
let setup_auth = pod_spec
.init_containers
.as_ref()
.unwrap()
.iter()
.find(|c| c.name == "setup-auth")
.expect("setup-auth init container must exist");
let script = &setup_auth.args.as_ref().unwrap()[0];
// 2Gi request: SHM=738Mi, shared_buffers = floor(70% of 738) = 516MB
assert!(
script.contains("shared_buffers = 516MB"),
"init script must set shared_buffers for 2Gi request"
);
}