-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcharm.py
executable file
·2246 lines (1963 loc) · 90 KB
/
charm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S LD_LIBRARY_PATH=lib python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""Charmed Kubernetes Operator for the PostgreSQL database."""
import itertools
import json
import logging
import os
import re
import shutil
import sys
import time
from pathlib import Path
from typing import Dict, List, Literal, Optional, Tuple, get_args
# First platform-specific import, will fail on wrong architecture
try:
import psycopg2
except ModuleNotFoundError:
from ops.main import main
from arch_utils import WrongArchitectureWarningCharm, is_wrong_architecture
# If the charm was deployed inside a host with different architecture
# (possibly due to user specifying an incompatible revision)
# then deploy an empty blocked charm with a warning.
if is_wrong_architecture() and __name__ == "__main__":
main(WrongArchitectureWarningCharm, use_juju_for_storage=True)
raise
from charms.data_platform_libs.v0.data_interfaces import DataPeerData, DataPeerUnitData
from charms.data_platform_libs.v0.data_models import TypedCharmBase
from charms.grafana_k8s.v0.grafana_dashboard import GrafanaDashboardProvider
from charms.loki_k8s.v1.loki_push_api import LogForwarder, LogProxyConsumer
from charms.observability_libs.v1.kubernetes_service_patch import KubernetesServicePatch
from charms.postgresql_k8s.v0.postgresql import (
REQUIRED_PLUGINS,
PostgreSQL,
PostgreSQLEnableDisableExtensionError,
PostgreSQLGetCurrentTimelineError,
PostgreSQLUpdateUserPasswordError,
)
from charms.postgresql_k8s.v0.postgresql_tls import PostgreSQLTLS
from charms.prometheus_k8s.v0.prometheus_scrape import MetricsEndpointProvider
from charms.rolling_ops.v0.rollingops import RollingOpsManager, RunWithLock
from charms.tempo_coordinator_k8s.v0.charm_tracing import trace_charm
from charms.tempo_coordinator_k8s.v0.tracing import TracingEndpointRequirer
from lightkube import ApiError, Client
from lightkube.models.core_v1 import ServicePort, ServiceSpec
from lightkube.models.meta_v1 import ObjectMeta
from lightkube.resources.core_v1 import Endpoints, Node, Pod, Service
from ops import main
from ops.charm import (
ActionEvent,
HookEvent,
LeaderElectedEvent,
RelationDepartedEvent,
WorkloadEvent,
)
from ops.jujuversion import JujuVersion
from ops.model import (
ActiveStatus,
BlockedStatus,
Container,
MaintenanceStatus,
ModelError,
Relation,
Unit,
UnknownStatus,
WaitingStatus,
)
from ops.pebble import (
ChangeError,
ExecError,
Layer,
PathError,
ProtocolError,
ServiceInfo,
ServiceStatus,
)
from requests import ConnectionError
from tenacity import RetryError, Retrying, stop_after_attempt, stop_after_delay, wait_fixed
from backups import CANNOT_RESTORE_PITR, S3_BLOCK_MESSAGES, PostgreSQLBackups
from config import CharmConfig
from constants import (
APP_SCOPE,
BACKUP_USER,
METRICS_PORT,
MONITORING_PASSWORD_KEY,
MONITORING_USER,
PATRONI_PASSWORD_KEY,
PEER,
PLUGIN_OVERRIDES,
POSTGRES_LOG_FILES,
REPLICATION_PASSWORD_KEY,
REPLICATION_USER,
REWIND_PASSWORD_KEY,
SECRET_DELETED_LABEL,
SECRET_INTERNAL_LABEL,
SECRET_KEY_OVERRIDES,
SPI_MODULE,
SYSTEM_USERS,
TLS_CA_FILE,
TLS_CERT_FILE,
TLS_KEY_FILE,
TRACING_PROTOCOL,
TRACING_RELATION_NAME,
UNIT_SCOPE,
USER,
USER_PASSWORD_KEY,
WORKLOAD_OS_GROUP,
WORKLOAD_OS_USER,
)
from patroni import NotReadyError, Patroni, SwitchoverFailedError
from relations.async_replication import (
REPLICATION_CONSUMER_RELATION,
REPLICATION_OFFER_RELATION,
PostgreSQLAsyncReplication,
)
from relations.db import EXTENSIONS_BLOCKING_MESSAGE, DbProvides
from relations.postgresql_provider import PostgreSQLProvider
from upgrade import PostgreSQLUpgrade, get_postgresql_k8s_dependencies_model
from utils import any_cpu_to_cores, any_memory_to_bytes, new_password
logger = logging.getLogger(__name__)
EXTENSIONS_DEPENDENCY_MESSAGE = "Unsatisfied plugin dependencies. Please check the logs"
EXTENSION_OBJECT_MESSAGE = "Cannot disable plugins: Existing objects depend on it. See logs"
INSUFFICIENT_SIZE_WARNING = "<10% free space on pgdata volume."
ORIGINAL_PATRONI_ON_FAILURE_CONDITION = "restart"
# http{x,core} clutter the logs with debug messages
logging.getLogger("httpcore").setLevel(logging.ERROR)
logging.getLogger("httpx").setLevel(logging.ERROR)
Scopes = Literal[APP_SCOPE, UNIT_SCOPE]
PASSWORD_USERS = [*SYSTEM_USERS, "patroni"]
@trace_charm(
tracing_endpoint="tracing_endpoint",
extra_types=(
DbProvides,
GrafanaDashboardProvider,
LogProxyConsumer,
MetricsEndpointProvider,
Patroni,
PostgreSQL,
PostgreSQLAsyncReplication,
PostgreSQLBackups,
PostgreSQLProvider,
PostgreSQLTLS,
PostgreSQLUpgrade,
RollingOpsManager,
),
)
class PostgresqlOperatorCharm(TypedCharmBase[CharmConfig]):
"""Charmed Operator for the PostgreSQL database."""
config_type = CharmConfig
def __init__(self, *args):
super().__init__(*args)
# Support for disabling the operator.
disable_file = Path(f"{os.environ.get('CHARM_DIR')}/disable")
if disable_file.exists():
logger.warning(
f"\n\tDisable file `{disable_file.resolve()}` found, the charm will skip all events."
"\n\tTo resume normal operations, please remove the file."
)
self.unit.status = BlockedStatus("Disabled")
sys.exit(0)
self.peer_relation_app = DataPeerData(
self.model,
relation_name=PEER,
secret_field_name=SECRET_INTERNAL_LABEL,
deleted_label=SECRET_DELETED_LABEL,
)
self.peer_relation_unit = DataPeerUnitData(
self.model,
relation_name=PEER,
secret_field_name=SECRET_INTERNAL_LABEL,
deleted_label=SECRET_DELETED_LABEL,
)
self._postgresql_service = "postgresql"
self.rotate_logs_service = "rotate-logs"
self.pgbackrest_server_service = "pgbackrest server"
self._metrics_service = "metrics_server"
self._unit = self.model.unit.name
self._name = self.model.app.name
self._namespace = self.model.name
self._context = {"namespace": self._namespace, "app_name": self._name}
self.cluster_name = f"patroni-{self._name}"
self.framework.observe(self.on.config_changed, self._on_config_changed)
self.framework.observe(self.on.leader_elected, self._on_leader_elected)
self.framework.observe(self.on[PEER].relation_changed, self._on_peer_relation_changed)
self.framework.observe(self.on.secret_changed, self._on_peer_relation_changed)
self.framework.observe(self.on[PEER].relation_departed, self._on_peer_relation_departed)
self.framework.observe(self.on.postgresql_pebble_ready, self._on_postgresql_pebble_ready)
self.framework.observe(self.on.pgdata_storage_detaching, self._on_pgdata_storage_detaching)
self.framework.observe(self.on.stop, self._on_stop)
self.framework.observe(self.on.get_password_action, self._on_get_password)
self.framework.observe(self.on.set_password_action, self._on_set_password)
self.framework.observe(self.on.get_primary_action, self._on_get_primary)
self.framework.observe(self.on.update_status, self._on_update_status)
self._storage_path = self.meta.storages["pgdata"].location
self.pgdata_path = f"{self._storage_path}/pgdata"
self.upgrade = PostgreSQLUpgrade(
self,
model=get_postgresql_k8s_dependencies_model(),
relation_name="upgrade",
substrate="k8s",
)
self.framework.observe(self.on.upgrade_charm, self._on_upgrade_charm)
self.postgresql_client_relation = PostgreSQLProvider(self)
self.legacy_db_relation = DbProvides(self, admin=False)
self.legacy_db_admin_relation = DbProvides(self, admin=True)
self.backup = PostgreSQLBackups(self, "s3-parameters")
self.tls = PostgreSQLTLS(self, PEER, [self.primary_endpoint, self.replicas_endpoint])
self.async_replication = PostgreSQLAsyncReplication(self)
self.restart_manager = RollingOpsManager(
charm=self, relation="restart", callback=self._restart
)
self.grafana_dashboards = GrafanaDashboardProvider(self)
self.metrics_endpoint = MetricsEndpointProvider(
self,
refresh_event=[self.on.start],
jobs=self._generate_metrics_jobs(self.is_tls_enabled),
)
self.loki_push = (
LogForwarder(
self,
relation_name="logging",
)
if self._pebble_log_forwarding_supported
else LogProxyConsumer(
self,
logs_scheme={"postgresql": {"log-files": POSTGRES_LOG_FILES}},
relation_name="logging",
)
)
postgresql_db_port = ServicePort(5432, name="database")
patroni_api_port = ServicePort(8008, name="api")
self.service_patcher = KubernetesServicePatch(self, [postgresql_db_port, patroni_api_port])
self.tracing = TracingEndpointRequirer(
self, relation_name=TRACING_RELATION_NAME, protocols=[TRACING_PROTOCOL]
)
@property
def tracing_endpoint(self) -> Optional[str]:
"""Otlp http endpoint for charm instrumentation."""
if self.tracing.is_ready():
return self.tracing.get_endpoint(TRACING_PROTOCOL)
@property
def _pebble_log_forwarding_supported(self) -> bool:
# https://github.com/canonical/operator/issues/1230
from ops.jujuversion import JujuVersion
juju_version = JujuVersion.from_environ()
return juju_version > JujuVersion(version=str("3.3"))
def _generate_metrics_jobs(self, enable_tls: bool) -> Dict:
"""Generate spec for Prometheus scraping."""
return [
{"static_configs": [{"targets": [f"*:{METRICS_PORT}"]}]},
{
"static_configs": [{"targets": ["*:8008"]}],
"scheme": "https" if enable_tls else "http",
"tls_config": {"insecure_skip_verify": True},
},
]
@property
def app_units(self) -> set[Unit]:
"""The peer-related units in the application."""
if not self._peers:
return set()
return {self.unit, *self._peers.units}
@property
def app_peer_data(self) -> Dict:
"""Application peer relation data object."""
relation = self.model.get_relation(PEER)
if relation is None:
return {}
return relation.data[self.app]
@property
def unit_peer_data(self) -> Dict:
"""Unit peer relation data object."""
relation = self.model.get_relation(PEER)
if relation is None:
return {}
return relation.data[self.unit]
def _peer_data(self, scope: Scopes) -> Dict:
"""Return corresponding databag for app/unit."""
relation = self.model.get_relation(PEER)
if relation is None:
return {}
return relation.data[self._scope_obj(scope)]
def _scope_obj(self, scope: Scopes):
if scope == APP_SCOPE:
return self.app
if scope == UNIT_SCOPE:
return self.unit
def peer_relation_data(self, scope: Scopes) -> DataPeerData:
"""Returns the peer relation data per scope."""
if scope == APP_SCOPE:
return self.peer_relation_app
elif scope == UNIT_SCOPE:
return self.peer_relation_unit
def _translate_field_to_secret_key(self, key: str) -> str:
"""Change 'key' to secrets-compatible key field."""
if not JujuVersion.from_environ().has_secrets:
return key
key = SECRET_KEY_OVERRIDES.get(key, key)
new_key = key.replace("_", "-")
return new_key.strip("-")
def get_secret(self, scope: Scopes, key: str) -> Optional[str]:
"""Get secret from the secret storage."""
if scope not in get_args(Scopes):
raise RuntimeError("Unknown secret scope.")
if not (peers := self.model.get_relation(PEER)):
return None
secret_key = self._translate_field_to_secret_key(key)
# Old translation in databag is to be taken
if result := self.peer_relation_data(scope).fetch_my_relation_field(peers.id, key):
return result
return self.peer_relation_data(scope).get_secret(peers.id, secret_key)
def set_secret(self, scope: Scopes, key: str, value: Optional[str]) -> Optional[str]:
"""Set secret from the secret storage."""
if scope not in get_args(Scopes):
raise RuntimeError("Unknown secret scope.")
if not value:
return self.remove_secret(scope, key)
if not (peers := self.model.get_relation(PEER)):
return None
secret_key = self._translate_field_to_secret_key(key)
# Old translation in databag is to be deleted
self.peer_relation_data(scope).delete_relation_data(peers.id, [key])
self.peer_relation_data(scope).set_secret(peers.id, secret_key, value)
def remove_secret(self, scope: Scopes, key: str) -> None:
"""Removing a secret."""
if scope not in get_args(Scopes):
raise RuntimeError("Unknown secret scope.")
if not (peers := self.model.get_relation(PEER)):
return None
secret_key = self._translate_field_to_secret_key(key)
if scope == APP_SCOPE:
self.peer_relation_app.delete_relation_data(peers.id, [secret_key])
else:
self.peer_relation_unit.delete_relation_data(peers.id, [secret_key])
@property
def is_cluster_initialised(self) -> bool:
"""Returns whether the cluster is already initialised."""
return "cluster_initialised" in self.app_peer_data
@property
def postgresql(self) -> PostgreSQL:
"""Returns an instance of the object used to interact with the database."""
return PostgreSQL(
primary_host=self.primary_endpoint,
current_host=self.endpoint,
user=USER,
password=self.get_secret(APP_SCOPE, f"{USER}-password"),
database="postgres",
system_users=SYSTEM_USERS,
)
@property
def endpoint(self) -> str:
"""Returns the endpoint of this instance's pod."""
return f"{self._unit.replace('/', '-')}.{self._build_service_name('endpoints')}"
@property
def primary_endpoint(self) -> str:
"""Returns the endpoint of the primary instance's service."""
return self._build_service_name("primary")
@property
def replicas_endpoint(self) -> str:
"""Returns the endpoint of the replicas instances' service."""
return self._build_service_name("replicas")
def _build_service_name(self, service: str) -> str:
"""Build a full k8s service name based on the service name."""
return f"{self._name}-{service}.{self._namespace}.svc.cluster.local"
def get_hostname_by_unit(self, unit_name: str) -> str:
"""Create a DNS name for a PostgreSQL unit.
Args:
unit_name: the juju unit name, e.g. "postgre-sql/1".
Returns:
A string representing the hostname of the PostgreSQL unit.
"""
unit_id = unit_name.split("/")[1]
return f"{self.app.name}-{unit_id}.{self.app.name}-endpoints"
def _get_endpoints_to_remove(self) -> List[str]:
"""List the endpoints that were part of the cluster but departed."""
old = self._endpoints
current = [self._get_hostname_from_unit(member) for member in self._hosts]
endpoints_to_remove = list(set(old) - set(current))
return endpoints_to_remove
def get_unit_ip(self, unit: Unit) -> Optional[str]:
"""Get the IP address of a specific unit."""
# Check if host is current host.
if unit == self.unit:
return str(self.model.get_binding(PEER).network.bind_address)
# Check if host is a peer.
elif unit in self._peers.data:
return str(self._peers.data[unit].get("private-address"))
# Return None if the unit is not a peer neither the current unit.
else:
return None
def _on_peer_relation_departed(self, event: RelationDepartedEvent) -> None:
"""The leader removes the departing units from the list of cluster members."""
# Allow leader to update endpoints if it isn't leaving.
if not self.unit.is_leader() or event.departing_unit == self.unit:
return
if "cluster_initialised" not in self._peers.data[self.app]:
logger.debug(
"Deferring on_peer_relation_departed: Cluster must be initialized before members can leave"
)
event.defer()
return
endpoints_to_remove = self._get_endpoints_to_remove()
self.postgresql_client_relation.update_read_only_endpoint()
self._remove_from_endpoints(endpoints_to_remove)
# Update the sync-standby endpoint in the async replication data.
self.async_replication.update_async_replication_data()
def _on_pgdata_storage_detaching(self, _) -> None:
# Change the primary if it's the unit that is being removed.
try:
primary = self._patroni.get_primary(unit_name_pattern=True)
except RetryError:
# Ignore the event if the primary couldn't be retrieved.
# If a switchover is needed, an automatic failover will be triggered
# when the unit is removed.
logger.debug("Early exit on_pgdata_storage_detaching: primary cannot be retrieved")
return
if self.unit.name != primary:
return
if not self._patroni.are_all_members_ready():
logger.warning(
"could not switchover because not all members are ready"
" - an automatic failover will be triggered"
)
return
# Try to switchover to another member and raise an exception if it doesn't succeed.
# If it doesn't happen on time, Patroni will automatically run a fail-over.
try:
# Get the current primary to check if it has changed later.
current_primary = self._patroni.get_primary()
# Trigger the switchover.
self._patroni.switchover()
# Wait for the switchover to complete.
self._patroni.primary_changed(current_primary)
logger.info("successful switchover")
except (RetryError, SwitchoverFailedError) as e:
logger.warning(
f"switchover failed with reason: {e} - an automatic failover will be triggered"
)
return
# Only update the connection endpoints if there is a primary.
# A cluster can have all members as replicas for some time after
# a failed switchover, so wait until the primary is elected.
endpoints_to_remove = self._get_endpoints_to_remove()
self.postgresql_client_relation.update_read_only_endpoint()
self._remove_from_endpoints(endpoints_to_remove)
def _on_peer_relation_changed(self, event: HookEvent) -> None: # noqa: C901
"""Reconfigure cluster members."""
# The cluster must be initialized first in the leader unit
# before any other member joins the cluster.
if "cluster_initialised" not in self._peers.data[self.app]:
if self.unit.is_leader():
if self._initialize_cluster(event):
logger.debug("Deferring on_peer_relation_changed: Leader initialized cluster")
else:
logger.debug("_initialized_cluster failed on _peer_relation_changed")
return
else:
logger.debug(
"Deferring on_peer_relation_changed: Cluster must be initialized before members can join"
)
event.defer()
return
# If the leader is the one receiving the event, it adds the new members,
# one at a time.
if self.unit.is_leader():
self._add_members(event)
# Don't update this member before it's part of the members list.
if self._endpoint not in self._endpoints:
return
# Update the list of the cluster members in the replicas to make them know each other.
# Update the cluster members in this unit (updating patroni configuration).
container = self.unit.get_container("postgresql")
if not container.can_connect():
logger.debug(
"Early exit on_peer_relation_changed: Waiting for container to become available"
)
return
try:
self.update_config()
except ValueError as e:
self.unit.status = BlockedStatus("Configuration Error. Please check the logs")
logger.error("Invalid configuration: %s", str(e))
return
# Should not override a blocked status
if isinstance(self.unit.status, BlockedStatus):
logger.debug("on_peer_relation_changed early exit: Unit in blocked status")
return
services = container.pebble.get_services(names=[self._postgresql_service])
if (
("restoring-backup" in self.app_peer_data or "restore-to-time" in self.app_peer_data)
and len(services) > 0
and not self._was_restore_successful(container, services[0])
):
logger.debug("on_peer_relation_changed early exit: Backup restore check failed")
return
# Validate the status of the member before setting an ActiveStatus.
if not self._patroni.member_started:
logger.debug("Deferring on_peer_relation_changed: Waiting for member to start")
self.unit.status = WaitingStatus("awaiting for member to start")
event.defer()
return
# Restart the workload if it's stuck on the starting state after a timeline divergence
# due to a backup that was restored.
if (
not self.is_primary
and not self.is_standby_leader
and (
self._patroni.member_replication_lag == "unknown"
or int(self._patroni.member_replication_lag) > 1000
)
):
logger.warning("Workload failure detected. Reinitialising unit.")
self.unit.status = MaintenanceStatus("reinitialising replica")
self._patroni.reinitialize_postgresql()
logger.debug("Deferring on_peer_relation_changed: reinitialising replica")
event.defer()
return
try:
self.postgresql_client_relation.update_read_only_endpoint()
except ModelError as e:
logger.warning("Cannot update read_only endpoints: %s", str(e))
# Start or stop the pgBackRest TLS server service when TLS certificate change.
if not self.backup.start_stop_pgbackrest_service():
# Ping primary to start its TLS server.
self.unit_peer_data.update({"start-tls-server": "True"})
logger.debug(
"Deferring on_peer_relation_changed: awaiting for TLS server service to start on primary"
)
event.defer()
return
else:
self.unit_peer_data.pop("start-tls-server", None)
self.backup.coordinate_stanza_fields()
# This is intended to be executed only when leader is reinitializing S3 connection due to the leader change.
if (
"s3-initialization-start" in self.app_peer_data
and "s3-initialization-done" not in self.unit_peer_data
and self.is_primary
and not self.backup._on_s3_credential_changed_primary(event)
):
return
# Clean-up unit initialization data after successful sync to the leader.
if "s3-initialization-done" in self.app_peer_data and not self.unit.is_leader():
self.unit_peer_data.update({
"stanza": "",
"s3-initialization-block-message": "",
"s3-initialization-done": "",
"s3-initialization-start": "",
})
self.async_replication.handle_read_only_mode()
def _on_config_changed(self, event) -> None:
"""Handle configuration changes, like enabling plugins."""
if not self.is_cluster_initialised:
logger.debug("Defer on_config_changed: cluster not initialised yet")
event.defer()
return
if not self.upgrade.idle:
logger.debug("Defer on_config_changed: upgrade in progress")
event.defer()
return
try:
self._validate_config_options()
# update config on every run
self.update_config()
except psycopg2.OperationalError:
logger.debug("Defer on_config_changed: Cannot connect to database")
event.defer()
return
except ValueError as e:
self.unit.status = BlockedStatus("Configuration Error. Please check the logs")
logger.error("Invalid configuration: %s", str(e))
return
if self.is_blocked and "Configuration Error" in self.unit.status.message:
self._set_active_status()
# Update the sync-standby endpoint in the async replication data.
self.async_replication.update_async_replication_data()
if not self.unit.is_leader():
return
# Enable and/or disable the extensions.
self.enable_disable_extensions()
# Unblock the charm after extensions are enabled (only if it's blocked due to application
# charms requesting extensions).
if self.unit.status.message != EXTENSIONS_BLOCKING_MESSAGE:
return
for relation in [
*self.model.relations.get("db", []),
*self.model.relations.get("db-admin", []),
]:
if not self.legacy_db_relation.set_up_relation(relation):
logger.debug(
"Early exit on_config_changed: legacy relation requested extensions that are still disabled"
)
return
def enable_disable_extensions(self, database: str = None) -> None:
"""Enable/disable PostgreSQL extensions set through config options.
Args:
database: optional database where to enable/disable the extension.
"""
if self._patroni.get_primary() is None:
logger.debug("Early exit enable_disable_extensions: standby cluster")
return
original_status = self.unit.status
extensions = {}
# collect extensions
for plugin in self.config.plugin_keys():
enable = self.config[plugin]
# Enable or disable the plugin/extension.
extension = "_".join(plugin.split("_")[1:-1])
if extension == "spi":
for ext in SPI_MODULE:
extensions[ext] = enable
continue
extension = PLUGIN_OVERRIDES.get(extension, extension)
if self._check_extension_dependencies(extension, enable):
self.unit.status = BlockedStatus(EXTENSIONS_DEPENDENCY_MESSAGE)
return
extensions[extension] = enable
if self.is_blocked and self.unit.status.message == EXTENSIONS_DEPENDENCY_MESSAGE:
self._set_active_status()
original_status = self.unit.status
self._handle_enable_disable_extensions(original_status, extensions, database)
def _handle_enable_disable_extensions(self, original_status, extensions, database) -> None:
"""Try enablind/disabling Postgresql extensions and handle exceptions appropriately."""
if not isinstance(original_status, UnknownStatus):
self.unit.status = WaitingStatus("Updating extensions")
try:
self.postgresql.enable_disable_extensions(extensions, database)
except psycopg2.errors.DependentObjectsStillExist as e:
logger.error(
"Failed to disable plugin: %s\nWas the plugin enabled manually? If so, update charm config with `juju config postgresql-k8s plugin_<plugin_name>_enable=True`",
str(e),
)
self.unit.status = BlockedStatus(EXTENSION_OBJECT_MESSAGE)
return
except PostgreSQLEnableDisableExtensionError as e:
logger.exception("failed to change plugins: %s", str(e))
if original_status.message == EXTENSION_OBJECT_MESSAGE:
self._set_active_status()
return
if not isinstance(original_status, UnknownStatus):
self.unit.status = original_status
def _check_extension_dependencies(self, extension: str, enable: bool) -> bool:
skip = False
if enable and extension in REQUIRED_PLUGINS:
for ext in REQUIRED_PLUGINS[extension]:
if not self.config[f"plugin_{ext}_enable"]:
skip = True
logger.exception(
"cannot enable %s, extension required %s to be enabled before",
extension,
ext,
)
return skip
def _add_members(self, event) -> None:
"""Add new cluster members.
This method is responsible for adding new members to the cluster
when new units are added to the application. This event is deferred if
one of the current units is copying data from the primary, to avoid
multiple units copying data at the same time, which can cause slow
transfer rates in these processes and overload the primary instance.
"""
# Only the leader can reconfigure.
if not self.unit.is_leader():
return
# Reconfiguration can be successful only if the cluster is initialised
# (i.e. first unit has bootstrap the cluster).
if "cluster_initialised" not in self._peers.data[self.app]:
return
try:
# Compare set of Patroni cluster members and Juju hosts
# to avoid the unnecessary reconfiguration.
if self._patroni.cluster_members == self._hosts:
return
logger.info("Reconfiguring cluster")
self.unit.status = MaintenanceStatus("reconfiguring cluster")
for member in self._hosts - self._patroni.cluster_members:
logger.debug("Adding %s to cluster", member)
self.add_cluster_member(member)
except NotReadyError:
logger.info("Deferring reconfigure: another member doing sync right now")
event.defer()
except RetryError:
logger.info("Deferring reconfigure: failed to obtain cluster members from Patroni")
event.defer()
def add_cluster_member(self, member: str) -> None:
"""Add member to the cluster if all members are already up and running.
Raises:
NotReadyError if either the new member or the current members are not ready.
"""
hostname = self._get_hostname_from_unit(member)
if not self._patroni.are_all_members_ready():
logger.info("not all members are ready")
raise NotReadyError("not all members are ready")
# Add the member to the list that should be updated in each other member.
self._add_to_endpoints(hostname)
# Add the labels needed for replication in this pod.
# This also enables the member as part of the cluster.
try:
self._patch_pod_labels(member)
except ApiError as e:
logger.error("failed to patch pod")
self.unit.status = BlockedStatus(f"failed to patch pod with error {e}")
return
@property
def _hosts(self) -> set:
"""List of the current Juju hosts.
Returns:
a set containing the current Juju hosts
with the names in the k8s pod name format
"""
peers = self.model.get_relation(PEER)
hosts = [self._unit_name_to_pod_name(self.unit.name)] + [
self._unit_name_to_pod_name(unit.name) for unit in peers.units
]
return set(hosts)
def _get_hostname_from_unit(self, member: str) -> str:
"""Create a DNS name for a PostgreSQL/Patroni cluster member.
Args:
member: the Patroni member name, e.g. "postgresql-k8s-0".
Returns:
A string representing the hostname of the PostgreSQL unit.
"""
unit_id = member.split("-")[-1]
return f"{self.app.name}-{unit_id}.{self.app.name}-endpoints"
def _on_leader_elected(self, event: LeaderElectedEvent) -> None:
"""Handle the leader-elected event."""
for password in {
USER_PASSWORD_KEY,
REPLICATION_PASSWORD_KEY,
REWIND_PASSWORD_KEY,
MONITORING_PASSWORD_KEY,
PATRONI_PASSWORD_KEY,
}:
if self.get_secret(APP_SCOPE, password) is None:
self.set_secret(APP_SCOPE, password, new_password())
# Add this unit to the list of cluster members
# (the cluster should start with only this member).
if self._endpoint not in self._endpoints:
self._add_to_endpoints(self._endpoint)
self._cleanup_old_cluster_resources()
if not self.fix_leader_annotation():
return
# Create resources and add labels needed for replication.
if self.upgrade.idle:
try:
self._create_services()
except ApiError:
logger.exception("failed to create k8s services")
self.unit.status = BlockedStatus("failed to create k8s services")
return
# Remove departing units when the leader changes.
self._remove_from_endpoints(self._get_endpoints_to_remove())
self._add_members(event)
def fix_leader_annotation(self) -> bool:
"""Fix the leader annotation if it's missing."""
client = Client()
try:
endpoint = client.get(Endpoints, name=self.cluster_name, namespace=self._namespace)
if "leader" not in endpoint.metadata.annotations:
patch = {
"metadata": {
"annotations": {"leader": self._unit_name_to_pod_name(self._unit)}
}
}
client.patch(
Endpoints, name=self.cluster_name, namespace=self._namespace, obj=patch
)
self.app_peer_data.pop("cluster_initialised", None)
logger.info("Fixed missing leader annotation")
except ApiError as e:
if e.status.code == 403:
self.on_deployed_without_trust()
return False
# Ignore the error only when the resource doesn't exist.
if e.status.code != 404:
raise e
return True
def _create_pgdata(self, container: Container):
"""Create the PostgreSQL data directory."""
if not container.exists(self.pgdata_path):
container.make_dir(
self.pgdata_path, permissions=0o770, user=WORKLOAD_OS_USER, group=WORKLOAD_OS_GROUP
)
# Also, fix the permissions from the parent directory.
container.exec([
"chown",
f"{WORKLOAD_OS_USER}:{WORKLOAD_OS_GROUP}",
self._storage_path,
]).wait()
def _on_postgresql_pebble_ready(self, event: WorkloadEvent) -> None:
"""Event handler for PostgreSQL container on PebbleReadyEvent."""
if self._endpoint in self._endpoints:
self._fix_pod()
# TODO: move this code to an "_update_layer" method in order to also utilize it in
# config-changed hook.
# Get the postgresql container so we can configure/manipulate it.
container = event.workload
if not container.can_connect():
logger.debug(
"Defer on_postgresql_pebble_ready: Waiting for container to become available"
)
event.defer()
return
# Create the PostgreSQL data directory. This is needed on cloud environments
# where the volume is mounted with more restrictive permissions.
self._create_pgdata(container)
self.unit.set_workload_version(self._patroni.rock_postgresql_version)
# Defer the initialization of the workload in the replicas
# if the cluster hasn't been bootstrap on the primary yet.
# Otherwise, each unit will create a different cluster and
# any update in the members list on the units won't have effect
# on fixing that.
if not self.unit.is_leader() and "cluster_initialised" not in self._peers.data[self.app]:
logger.debug(
"Deferring on_postgresql_pebble_ready: Not leader and cluster not initialized"
)
event.defer()
return
try:
self.push_tls_files_to_workload(container)
except (PathError, ProtocolError) as e:
logger.error(
"Deferring on_postgresql_pebble_ready: Cannot push TLS certificates: %r", e
)
event.defer()
return
# Start the database service.
self._update_pebble_layers()
# Ensure the member is up and running before marking the cluster as initialised.
if not self._patroni.member_started:
logger.debug("Deferring on_postgresql_pebble_ready: Waiting for cluster to start")
self.unit.status = WaitingStatus("awaiting for cluster to start")
event.defer()
return
if self.unit.is_leader() and not self._initialize_cluster(event):
return
# Update the archive command and replication configurations.
self.update_config()
# Enable/disable PostgreSQL extensions if they were set before the cluster
# was fully initialised.
self.enable_disable_extensions()
# Enable pgbackrest service
self.backup.start_stop_pgbackrest_service()
# All is well, set an ActiveStatus.
self._set_active_status()
def _set_active_status(self):
# The charm should not override this status outside of the function checking disk space.
if self.unit.status.message == INSUFFICIENT_SIZE_WARNING:
return
try:
if self.unit.is_leader() and "s3-initialization-block-message" in self.app_peer_data:
self.unit.status = BlockedStatus(
self.app_peer_data["s3-initialization-block-message"]
)
return
if self._patroni.get_primary(unit_name_pattern=True) == self.unit.name:
self.unit.status = ActiveStatus("Primary")
elif self.is_standby_leader:
self.unit.status = ActiveStatus("Standby")
elif self._patroni.member_started:
self.unit.status = ActiveStatus()
except (RetryError, ConnectionError) as e: