-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathtest_backups.py
More file actions
2081 lines (1869 loc) · 90.4 KB
/
test_backups.py
File metadata and controls
2081 lines (1869 loc) · 90.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
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
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
from os import cpu_count
from subprocess import CompletedProcess, TimeoutExpired
from unittest.mock import MagicMock, PropertyMock, call, mock_open, patch
import botocore
import pytest
from boto3.exceptions import S3UploadFailedError
from botocore.exceptions import ClientError
from jinja2 import Template
from ops import ActiveStatus, BlockedStatus, MaintenanceStatus, Unit
from ops.testing import Harness
from tenacity import RetryError, wait_fixed
from backups import ListBackupsError, PostgreSQLBackups
from charm import PostgresqlOperatorCharm
from constants import PEER
ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE = "the S3 repository has backups from another cluster"
FAILED_TO_ACCESS_CREATE_BUCKET_ERROR_MESSAGE = (
"failed to access/create the bucket, check your S3 settings"
)
FAILED_TO_INITIALIZE_STANZA_ERROR_MESSAGE = "failed to initialize stanza, check your S3 settings"
S3_PARAMETERS_RELATION = "s3-parameters"
@pytest.fixture(autouse=True)
def harness():
harness = Harness(PostgresqlOperatorCharm)
# Set up the initial relation and hooks.
peer_rel_id = harness.add_relation(PEER, "postgresql")
harness.add_relation_unit(peer_rel_id, "postgresql/0")
harness.begin()
yield harness
harness.cleanup()
def test_extract_error_message_with_error_in_stderr():
"""Test extracting error from stderr with ERROR marker."""
stderr = """2025-11-07 07:21:11.120 P00 ERROR: [056]: unable to find primary cluster - cannot proceed
HINT: are all available clusters in recovery?"""
result = PostgreSQLBackups._extract_error_message(stderr)
assert result == "ERROR: [056]: unable to find primary cluster - cannot proceed"
def test_extract_error_message_with_plain_stderr():
"""Test extracting error from stderr when no ERROR marker."""
stderr = "Connection refused: cannot connect to S3"
result = PostgreSQLBackups._extract_error_message(stderr)
assert result == "Connection refused: cannot connect to S3"
def test_extract_error_message_with_warning():
"""Test extracting warning message from stderr."""
stderr = "P00 WARN: configuration issue detected"
result = PostgreSQLBackups._extract_error_message(stderr)
assert result == "WARN: configuration issue detected"
def test_extract_error_message_with_multiple_errors():
"""Test extracting multiple ERROR/WARN lines from stderr."""
stderr = """P00 ERROR: first error
P00 WARN: warning message
P00 ERROR: second error"""
result = PostgreSQLBackups._extract_error_message(stderr)
assert result == "ERROR: first error; WARN: warning message; ERROR: second error"
def test_extract_error_message_with_empty_output():
"""Test with empty stderr returns helpful message."""
result = PostgreSQLBackups._extract_error_message("")
assert (
result
== "Unknown error occurred. Please check the logs at /var/snap/charmed-postgresql/common/var/log/pgbackrest"
)
def test_extract_error_message_fallback_to_stderr_last_line():
"""Test fallback to last line of stderr when no ERROR/WARN markers."""
stderr = "Line 1\nLine 2\nFinal error message"
result = PostgreSQLBackups._extract_error_message(stderr)
assert result == "Final error message"
def test_extract_error_message_cleans_debug_prefix():
"""Test that debug prefixes like 'P00 ERROR:' are cleaned up."""
stderr = "2025-11-07 07:21:11.120 P00 ERROR: test error message"
result = PostgreSQLBackups._extract_error_message(stderr)
assert result == "ERROR: test error message"
def test_stanza_name(harness):
assert (
harness.charm.backup.stanza_name
== f"{harness.charm.model.name}.{harness.charm.cluster_name}"
)
def test_tls_ca_chain_filename(harness):
# Test when the TLS CA chain is not available.
assert harness.charm.backup._tls_ca_chain_filename == ""
# Test when the TLS CA chain is available.
with harness.hooks_disabled():
remote_application = "s3-integrator"
s3_rel_id = harness.add_relation(S3_PARAMETERS_RELATION, remote_application)
harness.update_relation_data(
s3_rel_id,
remote_application,
{
"bucket": "fake-bucket",
"access-key": "fake-access-key",
"secret-key": "fake-secret-key",
"tls-ca-chain": '["fake-tls-ca-chain"]',
},
)
assert (
harness.charm.backup._tls_ca_chain_filename
== "/var/snap/charmed-postgresql/current/etc/pgbackrest/pgbackrest-tls-ca-chain.crt"
)
def test_are_backup_settings_ok(harness):
# Test without S3 relation.
assert harness.charm.backup._are_backup_settings_ok() == (
False,
"Relation with s3-integrator charm missing, cannot create/restore backup.",
)
# Test when there are missing S3 parameters.
harness.add_relation(S3_PARAMETERS_RELATION, "s3-integrator")
assert harness.charm.backup._are_backup_settings_ok() == (
False,
"Missing S3 parameters: ['bucket', 'access-key', 'secret-key']",
)
# Test when all required parameters are provided.
with patch("charm.PostgreSQLBackups._retrieve_s3_parameters") as _retrieve_s3_parameters:
_retrieve_s3_parameters.return_value = ["bucket", "access-key", "secret-key"], []
assert harness.charm.backup._are_backup_settings_ok() == (True, "")
def test_can_initialise_stanza(harness):
with patch("charm.Patroni.member_started", new_callable=PropertyMock) as _member_started:
# Test when Patroni or PostgreSQL hasn't started yet
# and the unit hasn't joined the peer relation yet.
_member_started.return_value = False
assert not harness.charm.backup._can_initialise_stanza
# Test when everything is ok to initialise the stanza.
_member_started.return_value = True
assert harness.charm.backup._can_initialise_stanza
def test_can_unit_perform_backup(harness):
with (
patch("charm.PostgreSQLBackups._are_backup_settings_ok") as _are_backup_settings_ok,
patch("charm.Patroni.member_started", new_callable=PropertyMock) as _member_started,
patch("ops.model.Application.planned_units") as _planned_units,
patch(
"charm.PostgresqlOperatorCharm.is_primary", new_callable=PropertyMock
) as _is_primary,
):
peer_rel_id = harness.model.get_relation(PEER).id
# Test when the charm fails to retrieve the primary.
_is_primary.side_effect = RetryError(last_attempt=1)
assert harness.charm.backup._can_unit_perform_backup() == (
False,
"Unit cannot perform backups as the database seems to be offline",
)
# Test when the unit is in a blocked state.
_is_primary.side_effect = None
_is_primary.return_value = True
harness.charm.unit.status = BlockedStatus("fake blocked state")
assert harness.charm.backup._can_unit_perform_backup() == (
False,
"Unit is in a blocking state",
)
# Test when running the check in the primary, there are replicas and TLS is enabled.
harness.charm.unit.status = ActiveStatus()
_planned_units.return_value = 2
assert harness.charm.backup._can_unit_perform_backup() == (
False,
"Unit cannot perform backups as it is the cluster primary",
)
# Test when Patroni or PostgreSQL hasn't started yet.
_is_primary.return_value = False
_member_started.return_value = False
assert harness.charm.backup._can_unit_perform_backup() == (
False,
"Unit cannot perform backups as it's not in running state",
)
# Test when the stanza was not initialised yet.
_member_started.return_value = True
assert harness.charm.backup._can_unit_perform_backup() == (
False,
"Stanza was not initialised",
)
# Test when S3 parameters are not ok.
with harness.hooks_disabled():
harness.update_relation_data(
peer_rel_id,
harness.charm.app.name,
{"stanza": harness.charm.backup.stanza_name},
)
_are_backup_settings_ok.return_value = (False, "fake error message")
assert harness.charm.backup._can_unit_perform_backup() == (False, "fake error message")
# Test when everything is ok to run a backup.
_are_backup_settings_ok.return_value = (True, None)
assert harness.charm.backup._can_unit_perform_backup() == (True, None)
def test_can_use_s3_repository(harness):
with (
patch("charm.Patroni.reload_patroni_configuration") as _reload_patroni_configuration,
patch("charm.PostgreSQLBackups._execute_command") as _execute_command,
patch("charm.Patroni.member_started", new_callable=PropertyMock) as _member_started,
patch("charm.PostgresqlOperatorCharm.update_config") as _update_config,
patch(
"charm.Patroni.get_postgresql_version", return_value="16.6"
) as _get_postgresql_version,
patch("charm.PostgresqlOperatorCharm.postgresql") as _postgresql,
patch(
"charm.PostgreSQLBackups._retrieve_s3_parameters",
return_value=({"path": "example"}, None),
),
patch("charm.PostgreSQLBackups._read_content_from_s3") as _read_content_from_s3,
):
# Test with bad model-uuid.
_read_content_from_s3.return_value = "bad"
assert harness.charm.backup.can_use_s3_repository() == (
False,
ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE,
)
# Test when nothing is returned from the pgBackRest info command.
_read_content_from_s3.return_value = harness.model.uuid
_execute_command.side_effect = TimeoutExpired(cmd="fake command", timeout=30)
with pytest.raises(TimeoutError):
harness.charm.backup.can_use_s3_repository()
assert False
# Test with bad pgBackRest error code.
_execute_command.side_effect = None
_execute_command.return_value = (1, "", "")
assert harness.charm.backup.can_use_s3_repository() == (
False,
FAILED_TO_INITIALIZE_STANZA_ERROR_MESSAGE,
)
pgbackrest_info_same_cluster_backup_output = (
0,
f'[{{"db": [{{"system-id": "12345"}}], "name": "{harness.charm.backup.stanza_name}"}}]',
"",
)
# Test when the cluster system id can be retrieved, but it's different from the stanza system id.
pgbackrest_info_other_cluster_system_id_backup_output = (
0,
f'[{{"db": [{{"system-id": "12345"}}], "name": "{harness.charm.backup.stanza_name}"}}]',
"",
)
other_instance_system_identifier_output = (
0,
"Database system identifier: 67890",
"",
)
_execute_command.side_effect = [
pgbackrest_info_other_cluster_system_id_backup_output,
other_instance_system_identifier_output,
]
assert harness.charm.backup.can_use_s3_repository() == (
False,
ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE,
)
# Invalid stanza name
pgbackrest_info_other_cluster_name_backup_output = (
0,
'[{"db": [{"system-id": "12345"}], "name": "[invalid]"}]',
"",
)
same_instance_system_identifier_output = (
0,
"Database system identifier: 12345",
"",
)
_execute_command.side_effect = [
pgbackrest_info_other_cluster_name_backup_output,
same_instance_system_identifier_output,
]
assert harness.charm.backup.can_use_s3_repository() == (
False,
FAILED_TO_INITIALIZE_STANZA_ERROR_MESSAGE,
)
# Test when the cluster system id can be retrieved, but it's different from the stanza system id.
pgbackrest_info_other_cluster_name_backup_output = (
0,
f'[{{"db": [{{"system-id": "12345"}}], "name": "another-model.{harness.charm.cluster_name}"}}]',
"",
)
same_instance_system_identifier_output = (
0,
"Database system identifier: 12345",
"",
)
_execute_command.side_effect = [
pgbackrest_info_other_cluster_name_backup_output,
same_instance_system_identifier_output,
]
assert harness.charm.backup.can_use_s3_repository() == (
False,
ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE,
)
# Test when the workload is not running.
_member_started.return_value = False
_execute_command.side_effect = [
pgbackrest_info_same_cluster_backup_output,
other_instance_system_identifier_output,
]
assert harness.charm.backup.can_use_s3_repository() == (
False,
ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE,
)
# Test when there is no backup from another cluster in the S3 repository.
_execute_command.side_effect = [
pgbackrest_info_same_cluster_backup_output,
same_instance_system_identifier_output,
]
assert harness.charm.backup.can_use_s3_repository() == (True, "")
# Empty db
_execute_command.side_effect = None
_execute_command.return_value = (1, "", "")
pgbackrest_info_other_cluster_name_backup_output = (
0,
f'[{{"db": [], "name": "another-model.{harness.charm.cluster_name}"}}]',
"",
)
assert harness.charm.backup.can_use_s3_repository() == (
False,
FAILED_TO_INITIALIZE_STANZA_ERROR_MESSAGE,
)
def test_construct_endpoint(harness):
# Test with an AWS endpoint without region.
s3_parameters = {"endpoint": "https://s3.amazonaws.com", "region": ""}
assert harness.charm.backup._construct_endpoint(s3_parameters) == "https://s3.amazonaws.com"
# Test with an AWS endpoint with region.
s3_parameters["region"] = "us-east-1"
assert (
harness.charm.backup._construct_endpoint(s3_parameters)
== "https://s3.us-east-1.amazonaws.com"
)
# Test with another cloud endpoint.
s3_parameters["endpoint"] = "https://storage.googleapis.com"
assert (
harness.charm.backup._construct_endpoint(s3_parameters) == "https://storage.googleapis.com"
)
@pytest.mark.parametrize(
"tls_ca_chain_filename",
["", "/var/snap/charmed-postgresql/current/etc/pgbackrest/pgbackrest-tls-ca-chain.crt"],
)
def test_create_bucket_if_not_exists(harness, tls_ca_chain_filename):
with (
patch("boto3.session.Session.resource") as _resource,
patch(
"charm.PostgreSQLBackups._tls_ca_chain_filename",
new_callable=PropertyMock(return_value=tls_ca_chain_filename),
) as _tls_ca_chain_filename,
patch("charm.PostgreSQLBackups._retrieve_s3_parameters") as _retrieve_s3_parameters,
patch("backups.Config") as _config,
):
# Test when there are missing S3 parameters.
_retrieve_s3_parameters.return_value = ([], ["bucket", "access-key", "secret-key"])
harness.charm.backup._create_bucket_if_not_exists()
_resource.assert_not_called()
# Test when the charm fails to create a boto3 session.
_retrieve_s3_parameters.return_value = (
{
"bucket": "test-bucket",
"access-key": "test-access-key",
"secret-key": "test-secret-key",
"endpoint": "test-endpoint",
"region": "test-region",
},
[],
)
_resource.side_effect = ValueError
with pytest.raises(ValueError):
harness.charm.backup._create_bucket_if_not_exists()
assert False
# Test when the bucket already exists.
_resource.reset_mock()
_config.reset_mock()
_resource.side_effect = None
head_bucket = _resource.return_value.Bucket.return_value.meta.client.head_bucket
create = _resource.return_value.Bucket.return_value.create
wait_until_exists = _resource.return_value.Bucket.return_value.wait_until_exists
harness.charm.backup._create_bucket_if_not_exists()
_resource.assert_called_once_with(
"s3",
endpoint_url="test-endpoint",
verify=(tls_ca_chain_filename or None),
config=_config.return_value,
)
_config.assert_called_once_with(
# https://github.com/boto/boto3/issues/4400#issuecomment-2600742103
request_checksum_calculation="when_required",
response_checksum_validation="when_required",
)
head_bucket.assert_called_once()
create.assert_not_called()
wait_until_exists.assert_not_called()
# Test when the bucket doesn't exist.
head_bucket.reset_mock()
head_bucket.side_effect = ClientError(
error_response={"Error": {"Code": "SomeFakeException", "message": "fake error"}},
operation_name="fake operation name",
)
harness.charm.backup._create_bucket_if_not_exists()
head_bucket.assert_called_once()
create.assert_called_once()
wait_until_exists.assert_called_once()
# Test when the bucket creation fails.
head_bucket.reset_mock()
create.reset_mock()
wait_until_exists.reset_mock()
create.side_effect = ClientError(
error_response={"Error": {"Code": "SomeFakeException", "message": "fake error"}},
operation_name="fake operation name",
)
with pytest.raises(ClientError):
harness.charm.backup._create_bucket_if_not_exists()
assert False
head_bucket.assert_called_once()
create.assert_called_once()
wait_until_exists.assert_not_called()
# Test when the bucket creation fails with InvalidLocationConstraint.
head_bucket.reset_mock()
create.reset_mock()
wait_until_exists.reset_mock()
create.side_effect = ClientError(
error_response={
"Error": {"Code": "InvalidLocationConstraint", "message": "fake error"}
},
operation_name="fake operation name",
)
with pytest.raises(ClientError):
harness.charm.backup._create_bucket_if_not_exists()
assert False
head_bucket.assert_called_once()
want = [
call(CreateBucketConfiguration={"LocationConstraint": "test-region"}),
call(),
]
create.assert_has_calls(want)
wait_until_exists.assert_not_called()
# Test when the bucket creation fails due to a timeout error.
head_bucket.reset_mock()
create.reset_mock()
wait_until_exists.reset_mock()
head_bucket.side_effect = botocore.exceptions.ConnectTimeoutError(
endpoint_url="fake endpoint URL"
)
with pytest.raises(botocore.exceptions.ConnectTimeoutError):
harness.charm.backup._create_bucket_if_not_exists()
assert False
head_bucket.assert_called_once()
create.assert_not_called()
wait_until_exists.assert_not_called()
def test_empty_data_files(harness):
with (
patch("shutil.rmtree") as _rmtree,
patch("os.path.isdir", return_value=True) as _isdir,
patch("os.path.islink", return_value=False) as _islink,
patch("os.path.isfile", return_value=False) as _isfile,
patch("os.listdir", return_value=["test_file.txt"]) as _listdir,
patch("pathlib.Path.is_dir") as _is_dir,
patch("pathlib.Path.exists") as _exists,
):
# Test when the data directory doesn't exist.
_exists.return_value = False
assert harness.charm.backup._empty_data_files()
_rmtree.assert_not_called()
# Test when the removal of the data files fails.
_exists.return_value = True
_is_dir.return_value = True
_rmtree.side_effect = OSError
assert not harness.charm.backup._empty_data_files()
_rmtree.assert_called_once_with(
"/var/snap/charmed-postgresql/common/data/archive/test_file.txt"
)
# Test when data files are successfully removed.
_rmtree.reset_mock()
_rmtree.side_effect = None
assert harness.charm.backup._empty_data_files()
_rmtree.assert_has_calls([
call("/var/snap/charmed-postgresql/common/data/archive/test_file.txt"),
call("/var/snap/charmed-postgresql/common/var/lib/postgresql/test_file.txt"),
call("/var/snap/charmed-postgresql/common/data/logs/test_file.txt"),
call("/var/snap/charmed-postgresql/common/data/temp/test_file.txt"),
])
def test_change_connectivity_to_database(harness):
with patch("charm.PostgresqlOperatorCharm.update_config") as _update_config:
peer_rel_id = harness.model.get_relation(PEER).id
# Ensure that there is no connectivity info in the unit relation databag.
with harness.hooks_disabled():
harness.update_relation_data(
peer_rel_id,
harness.charm.unit.name,
{"connectivity": ""},
)
# Test when connectivity should be turned on.
harness.charm.backup._change_connectivity_to_database(True)
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {"connectivity": "on"}
_update_config.assert_called_once()
# Test when connectivity should be turned off.
_update_config.reset_mock()
harness.charm.backup._change_connectivity_to_database(False)
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {
"connectivity": "off"
}
_update_config.assert_called_once()
def test_execute_command(harness):
with (
patch("backups.run") as _run,
):
# Test when the command fails.
command = ["rm", "-r", "/var/snap/charmed-postgresql/common/data/db"]
_run.return_value = CompletedProcess(command, 1, b"", b"fake stderr")
assert harness.charm.backup._execute_command(command) == (1, "", "fake stderr")
_run.assert_called_once_with(command, input=None, capture_output=True, timeout=None)
# Test when the command runs successfully.
_run.reset_mock()
_run.side_effect = None
_run.return_value = CompletedProcess(command, 0, b"fake stdout", b"")
assert harness.charm.backup._execute_command(
command, command_input=b"fake input", timeout=5
) == (0, "fake stdout", "")
_run.assert_called_once_with(command, input=b"fake input", capture_output=True, timeout=5)
def test_format_backup_list(harness):
with patch(
"charms.data_platform_libs.v0.s3.S3Requirer.get_s3_connection_info"
) as _get_s3_connection_info:
# Test when there are no backups.
_get_s3_connection_info.return_value = {
"bucket": " /test-bucket/ ",
"access-key": " test-access-key ",
"secret-key": " test-secret-key ",
"path": " test-path/ ",
}
assert (
harness.charm.backup._format_backup_list([])
== """Storage bucket name: test-bucket
Backups base path: /test-path/backup/
backup-id | action | status | reference-backup-id | LSN start/stop | start-time | finish-time | timeline | backup-path
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------"""
)
# Test when there are backups.
backup_list = [
(
"2023-01-01T09:00:00Z",
"full backup",
"failed: fake error",
"None",
"0/3000000 / 0/5000000",
"2023-01-01T09:00:00Z",
"2023-01-01T09:00:05Z",
"1",
"a/b/c",
),
(
"2023-01-01T10:00:00Z",
"full backup",
"finished",
"None",
"0/5000000 / 0/7000000",
"2023-01-01T10:00:00Z",
"2023-01-01T10:00:07Z",
"A",
"a/b/d",
),
(
"2023-01-01T11:00:00Z",
"restore",
"finished",
"None",
"n/a",
"2023-01-01T11:00:00Z",
"n/a",
"B",
"n/a",
),
]
assert (
harness.charm.backup._format_backup_list(backup_list)
== """Storage bucket name: test-bucket
Backups base path: /test-path/backup/
backup-id | action | status | reference-backup-id | LSN start/stop | start-time | finish-time | timeline | backup-path
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2023-01-01T09:00:00Z | full backup | failed: fake error | None | 0/3000000 / 0/5000000 | 2023-01-01T09:00:00Z | 2023-01-01T09:00:05Z | 1 | a/b/c
2023-01-01T10:00:00Z | full backup | finished | None | 0/5000000 / 0/7000000 | 2023-01-01T10:00:00Z | 2023-01-01T10:00:07Z | A | a/b/d
2023-01-01T11:00:00Z | restore | finished | None | n/a | 2023-01-01T11:00:00Z | n/a | B | n/a"""
)
def test_generate_backup_list_output(harness):
with (
patch(
"charms.data_platform_libs.v0.s3.S3Requirer.get_s3_connection_info"
) as _get_s3_connection_info,
patch("charm.PostgreSQLBackups._execute_command") as _execute_command,
):
_get_s3_connection_info.return_value = {
"bucket": " /test-bucket/ ",
"access-key": " test-access-key ",
"secret-key": " test-secret-key ",
"path": " test-path/ ",
}
# Test when no backups are returned.
_execute_command.side_effect = [(0, '[{"backup":[]}]', ""), (0, "{}", "")]
assert (
harness.charm.backup._generate_backup_list_output()
== """Storage bucket name: test-bucket
Backups base path: /test-path/backup/
backup-id | action | status | reference-backup-id | LSN start/stop | start-time | finish-time | timeline | backup-path
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------"""
)
# Test when backups are returned.
_execute_command.side_effect = [
(
0,
'[{"backup":[{"archive":{"start":"00000001000000000000000B"},"label":"20230101-090000F","error":"fake error","reference":null,"lsn":{"start":"0/3000000","stop":"0/5000000"},"timestamp":{"start":1719866711,"stop":1719866714}}]}]',
"",
),
(
0,
'{".":{"type":"path"},"archive/None.postgresql/14-1/00000002.history":{"type": "file","size": 32,"time": 1728937652}}',
"",
),
]
assert (
harness.charm.backup._generate_backup_list_output()
== """Storage bucket name: test-bucket
Backups base path: /test-path/backup/
backup-id | action | status | reference-backup-id | LSN start/stop | start-time | finish-time | timeline | backup-path
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2023-01-01T09:00:00Z | full backup | failed: fake error | None | 0/3000000 / 0/5000000 | 2024-07-01T20:45:11Z | 2024-07-01T20:45:14Z | 1 | /None.postgresql/20230101-090000F
2024-10-14T20:27:32Z | restore | finished | None | n/a | 2024-10-14T20:27:32Z | n/a | 2 | n/a"""
)
def test_list_backups(harness):
with patch("charm.PostgreSQLBackups._execute_command") as _execute_command:
# Test when the command that list the backups fails.
_execute_command.return_value = (1, "", "fake stderr")
with pytest.raises(ListBackupsError):
harness.charm.backup._list_backups(show_failed=True)
assert False
# Test when no backups are available.
_execute_command.return_value = (0, "[]", "")
assert harness.charm.backup._list_backups(show_failed=True) == dict[str, tuple[str, str]]()
# Test when some backups are available.
_execute_command.return_value = (
0,
'[{"backup":[{"archive":{"start":"00000001000000000000000B"},"label":"20230101-090000F","error":"fake error"},{"archive":{"start":"0000000A000000000000000B"},"label":"20230101-100000F","error":null}],"name":"test-stanza"}]',
"",
)
assert harness.charm.backup._list_backups(show_failed=True) == dict[str, tuple[str, str]]([
("2023-01-01T09:00:00Z", ("test-stanza", "1")),
("2023-01-01T10:00:00Z", ("test-stanza", "A")),
])
# Test when some backups are available, but it's not desired to list failed backups.
assert harness.charm.backup._list_backups(show_failed=False) == dict[str, tuple[str, str]]([
("2023-01-01T10:00:00Z", ("test-stanza", "A"))
])
def test_initialise_stanza(harness):
with (
patch("charm.Patroni.reload_patroni_configuration") as _reload_patroni_configuration,
patch("charm.Patroni.member_started", new_callable=PropertyMock) as _member_started,
patch("backups.wait_fixed", return_value=wait_fixed(0)),
patch("charm.PostgresqlOperatorCharm.update_config") as _update_config,
patch("charm.PostgreSQLBackups._execute_command") as _execute_command,
patch(
"charm.PostgreSQLBackups._s3_initialization_set_failure"
) as _s3_initialization_set_failure,
):
peer_rel_id = harness.model.get_relation(PEER).id
mock_event = MagicMock()
# Test when it's in a blocked state other than the ones can be solved by new S3 settings.
harness.charm.unit.status = BlockedStatus("fake blocked state")
harness.charm.backup._initialise_stanza(mock_event)
_execute_command.assert_not_called()
mock_event.defer.assert_called_once()
# Test when the blocked state is any of the blocked stated that can be solved
# by new S3 settings, but the stanza creation fails.
mock_event.reset_mock()
stanza_creation_command = [
"charmed-postgresql.pgbackrest",
"--config=/var/snap/charmed-postgresql/current/etc/pgbackrest/pgbackrest.conf",
"--log-level-stderr=warn",
f"--stanza={harness.charm.backup.stanza_name}",
"stanza-create",
]
_execute_command.return_value = (1, "", "fake stderr")
for blocked_state in [
ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE,
FAILED_TO_ACCESS_CREATE_BUCKET_ERROR_MESSAGE,
FAILED_TO_INITIALIZE_STANZA_ERROR_MESSAGE,
]:
_s3_initialization_set_failure.reset_mock()
_execute_command.reset_mock()
harness.charm.unit.status = BlockedStatus(blocked_state)
harness.charm.backup._initialise_stanza(mock_event)
_execute_command.assert_called_with(stanza_creation_command)
mock_event.defer.assert_not_called()
# Only the leader will display the blocked status.
assert isinstance(harness.charm.unit.status, MaintenanceStatus)
_s3_initialization_set_failure.assert_called_once_with(
FAILED_TO_INITIALIZE_STANZA_ERROR_MESSAGE
)
# Test when the failure in the stanza creation is due to a timeout.
_execute_command.reset_mock()
_execute_command.return_value = (49, "", "fake stderr")
with pytest.raises(TimeoutError):
harness.charm.backup._initialise_stanza(mock_event)
assert False
mock_event.defer.assert_not_called()
# Test when the archiving is working correctly (pgBackRest check command succeeds)
# and the unit is not the leader.
_execute_command.reset_mock()
_execute_command.return_value = (0, "fake stdout", "")
_member_started.return_value = True
harness.charm.backup._initialise_stanza(mock_event)
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == {}
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {
"stanza": f"{harness.charm.model.name}.postgresql",
}
assert isinstance(harness.charm.unit.status, MaintenanceStatus)
mock_event.defer.assert_not_called()
# Test when the unit is the leader.
with harness.hooks_disabled():
harness.set_leader()
harness.update_relation_data(peer_rel_id, harness.charm.unit.name, {"stanza": ""})
harness.charm.backup._initialise_stanza(mock_event)
_update_config.assert_not_called()
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == {
"stanza": f"{harness.charm.model.name}.postgresql",
}
_member_started.assert_not_called()
_reload_patroni_configuration.assert_not_called()
mock_event.defer.assert_not_called()
assert isinstance(harness.charm.unit.status, MaintenanceStatus)
def test_check_stanza(harness):
with (
patch("charm.PostgresqlOperatorCharm.update_config"),
patch("backups.wait_fixed", return_value=wait_fixed(0)),
patch("charm.Patroni.reload_patroni_configuration") as _reload_patroni_configuration,
patch("charm.PostgreSQLBackups._execute_command") as _execute_command,
patch(
"charm.PostgresqlOperatorCharm._set_primary_status_message"
) as _set_primary_status_message,
patch(
"charm.PostgreSQLBackups._s3_initialization_set_failure"
) as _s3_initialization_set_failure,
patch(
"charm.PostgresqlOperatorCharm.is_primary", new_callable=PropertyMock
) as _is_primary,
):
peer_rel_id = harness.model.get_relation(PEER).id
# Set peer data flag
with harness.hooks_disabled():
harness.update_relation_data(
peer_rel_id,
harness.charm.app.name,
{"s3-initialization-start": "test-stanza"},
)
_execute_command.return_value = (49, "", "fake stderr")
assert not harness.charm.backup.check_stanza()
_reload_patroni_configuration.assert_not_called()
_set_primary_status_message.assert_not_called()
_s3_initialization_set_failure.assert_called_once_with(
FAILED_TO_INITIALIZE_STANZA_ERROR_MESSAGE
)
# Test when the failure in the stanza check is due to an archive timeout.
_execute_command.reset_mock()
_s3_initialization_set_failure.reset_mock()
_execute_command.return_value = (82, "", "fake stderr")
with pytest.raises(TimeoutError):
harness.charm.backup.check_stanza()
_s3_initialization_set_failure.assert_not_called()
_execute_command.reset_mock()
_s3_initialization_set_failure.reset_mock()
_execute_command.return_value = (0, "fake stdout", "")
assert harness.charm.backup.check_stanza()
_execute_command.assert_called_once()
_set_primary_status_message.assert_called_once()
_s3_initialization_set_failure.assert_not_called()
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {
"s3-initialization-done": "True"
}
with harness.hooks_disabled():
harness.set_leader()
assert harness.charm.backup.check_stanza()
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == {}
def test_coordinate_stanza_fields(harness):
with (
patch("charm.PostgresqlOperatorCharm.update_config") as _update_config,
patch("charm.Patroni.reload_patroni_configuration") as _reload_patroni_configuration,
):
peer_rel_id = harness.model.get_relation(PEER).id
stanza_name = f"{harness.charm.model.name}.{harness.charm.app.name}"
peer_data_primary_error = {
"s3-initialization-done": "True",
"s3-initialization-block-message": ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE,
}
peer_data_primary_ok = {
"s3-initialization-done": "True",
"stanza": stanza_name,
}
peer_data_leader_start = {
"s3-initialization-start": "Thu Feb 24 05:00:00 2022",
}
peer_data_leader_error = {
"s3-initialization-done": "True",
"s3-initialization-block-message": ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE,
}
peer_data_leader_ok = {"s3-initialization-done": "True", "stanza": stanza_name}
peer_data_clean = {
"s3-initialization-start": "",
"s3-initialization-done": "",
"s3-initialization-block-message": "",
"stanza": "",
}
# Add a new unit to the relation.
new_unit_name = "postgresql-k8s/1"
new_unit = Unit(new_unit_name, None, harness.charm.app._backend, {})
harness.add_relation_unit(peer_rel_id, new_unit_name)
# Test with clear values.
harness.charm.backup.coordinate_stanza_fields()
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == {}
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {}
assert harness.get_relation_data(peer_rel_id, new_unit) == {}
# Test with primary failed prior leader s3 initialization sequence started.
with harness.hooks_disabled():
harness.update_relation_data(peer_rel_id, new_unit_name, peer_data_primary_error)
harness.charm.backup.coordinate_stanza_fields()
_update_config.assert_not_called()
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == {}
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {}
assert harness.get_relation_data(peer_rel_id, new_unit) == peer_data_primary_error
# Test with non-leader unit.
with harness.hooks_disabled():
harness.update_relation_data(
peer_rel_id, harness.charm.app.name, peer_data_leader_start
)
harness.charm.backup.coordinate_stanza_fields()
_update_config.assert_not_called()
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == peer_data_leader_start
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {}
assert harness.get_relation_data(peer_rel_id, new_unit) == peer_data_primary_error
# Leader should sync fail result from the primary.
with harness.hooks_disabled():
harness.set_leader()
harness.charm.backup.coordinate_stanza_fields()
_update_config.assert_called_once()
_reload_patroni_configuration.assert_not_called()
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == peer_data_leader_error
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {}
assert harness.get_relation_data(peer_rel_id, new_unit) == peer_data_primary_error
# Test with successful result from the primary.
_update_config.reset_mock()
with harness.hooks_disabled():
harness.update_relation_data(peer_rel_id, harness.charm.app.name, peer_data_clean)
harness.update_relation_data(
peer_rel_id, harness.charm.app.name, peer_data_leader_start
)
harness.update_relation_data(peer_rel_id, new_unit_name, peer_data_clean)
harness.update_relation_data(peer_rel_id, new_unit_name, peer_data_primary_ok)
harness.charm.backup.coordinate_stanza_fields()
_update_config.assert_called_once()
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == peer_data_leader_ok
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {}
assert harness.get_relation_data(peer_rel_id, new_unit) == peer_data_primary_ok
# Test when leader is waiting for the primary result.
_update_config.reset_mock()
with harness.hooks_disabled():
harness.update_relation_data(peer_rel_id, harness.charm.app.name, peer_data_clean)
harness.update_relation_data(
peer_rel_id, harness.charm.app.name, peer_data_leader_start
)
harness.update_relation_data(peer_rel_id, new_unit_name, peer_data_clean)
harness.charm.backup.coordinate_stanza_fields()
_update_config.assert_not_called()
assert harness.get_relation_data(peer_rel_id, harness.charm.app) == peer_data_leader_start
assert harness.get_relation_data(peer_rel_id, harness.charm.unit) == {}
assert harness.get_relation_data(peer_rel_id, new_unit) == {}
def test_is_primary_pgbackrest_service_running(harness):
with (
patch("charm.PostgreSQLBackups._execute_command") as _execute_command,
patch(
"charm.PostgresqlOperatorCharm.primary_endpoint", new_callable=PropertyMock
) as _primary_endpoint,
patch("charm.Patroni.get_primary") as _get_primary,
):
# Test when the pgBackRest fails to contact the primary server.
_get_primary.side_effect = None
_execute_command.return_value = (1, "", "fake stderr")
assert not harness.charm.backup._is_primary_pgbackrest_service_running
_execute_command.assert_called_once()
# Test when the endpoint is not generated.
_execute_command.reset_mock()
_primary_endpoint.return_value = None
assert not harness.charm.backup._is_primary_pgbackrest_service_running
_execute_command.assert_not_called()
# Test when the pgBackRest succeeds on contacting the primary server.
_execute_command.reset_mock()
_execute_command.return_value = (0, "fake stdout", "")
_primary_endpoint.return_value = "fake_endpoint"
assert harness.charm.backup._is_primary_pgbackrest_service_running
_execute_command.assert_called_once()
def test_on_s3_credential_changed(harness):
with (
patch(
"charm.PostgreSQLBackups._render_pgbackrest_conf_file"