Skip to content

Commit 6ed8a92

Browse files
authored
[DPE-3039] Update Snap (#291)
* Update Snap * Bump libs * More verbose statuses for replicas
1 parent 943e4bf commit 6ed8a92

File tree

4 files changed

+35
-37
lines changed

4 files changed

+35
-37
lines changed

lib/charms/data_platform_libs/v0/data_interfaces.py

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ def _on_topic_requested(self, event: TopicRequestedEvent):
320320

321321
# Increment this PATCH version before using `charmcraft publish-lib` or reset
322322
# to 0 if you are raising the major API version
323-
LIBPATCH = 23
323+
LIBPATCH = 24
324324

325325
PYDEPS = ["ops>=2.0.0"]
326326

@@ -526,7 +526,16 @@ def get_content(self) -> Dict[str, str]:
526526
"""Getting cached secret content."""
527527
if not self._secret_content:
528528
if self.meta:
529-
self._secret_content = self.meta.get_content()
529+
try:
530+
self._secret_content = self.meta.get_content(refresh=True)
531+
except (ValueError, ModelError) as err:
532+
# https://bugs.launchpad.net/juju/+bug/2042596
533+
# Only triggered when 'refresh' is set
534+
msg = "ERROR either URI or label should be used for getting an owned secret but not both"
535+
if isinstance(err, ModelError) and msg not in str(err):
536+
raise
537+
# Due to: ValueError: Secret owner cannot use refresh=True
538+
self._secret_content = self.meta.get_content()
530539
return self._secret_content
531540

532541
def set_content(self, content: Dict[str, str]) -> None:
@@ -1085,7 +1094,7 @@ def _delete_relation_secret(
10851094
secret = self._get_relation_secret(relation.id, group)
10861095

10871096
if not secret:
1088-
logging.error("Can't update secret for relation %s", str(relation.id))
1097+
logging.error("Can't delete secret for relation %s", str(relation.id))
10891098
return False
10901099

10911100
old_content = secret.get_content()
@@ -1827,7 +1836,8 @@ def _assign_relation_alias(self, relation_id: int) -> None:
18271836

18281837
# We need to set relation alias also on the application level so,
18291838
# it will be accessible in show-unit juju command, executed for a consumer application unit
1830-
self.update_relation_data(relation_id, {"alias": available_aliases[0]})
1839+
if self.local_unit.is_leader():
1840+
self.update_relation_data(relation_id, {"alias": available_aliases[0]})
18311841

18321842
def _emit_aliased_event(self, event: RelationChangedEvent, event_name: str) -> None:
18331843
"""Emit an aliased event to a particular relation if it has an alias.
@@ -1914,6 +1924,9 @@ def _on_relation_created_event(self, event: RelationCreatedEvent) -> None:
19141924

19151925
# Sets both database and extra user roles in the relation
19161926
# if the roles are provided. Otherwise, sets only the database.
1927+
if not self.local_unit.is_leader():
1928+
return
1929+
19171930
if self.extra_user_roles:
19181931
self.update_relation_data(
19191932
event.relation.id,
@@ -2173,6 +2186,9 @@ def _on_relation_created_event(self, event: RelationCreatedEvent) -> None:
21732186
"""Event emitted when the Kafka relation is created."""
21742187
super()._on_relation_created_event(event)
21752188

2189+
if not self.local_unit.is_leader():
2190+
return
2191+
21762192
# Sets topic, extra user roles, and "consumer-group-prefix" in the relation
21772193
relation_data = {
21782194
f: getattr(self, f.replace("-", "_"), "")
@@ -2345,6 +2361,9 @@ def _on_relation_created_event(self, event: RelationCreatedEvent) -> None:
23452361
"""Event emitted when the OpenSearch relation is created."""
23462362
super()._on_relation_created_event(event)
23472363

2364+
if not self.local_unit.is_leader():
2365+
return
2366+
23482367
# Sets both index and extra user roles in the relation if the roles are provided.
23492368
# Otherwise, sets only the index.
23502369
data = {"index": self.index}

lib/charms/grafana_agent/v0/cos_agent.py

Lines changed: 6 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -206,17 +206,15 @@ def __init__(self, *args):
206206
```
207207
"""
208208

209-
import base64
210209
import json
211210
import logging
212-
import lzma
213211
from collections import namedtuple
214212
from itertools import chain
215213
from pathlib import Path
216214
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Set, Union
217215

218216
import pydantic
219-
from cosl import JujuTopology
217+
from cosl import GrafanaDashboard, JujuTopology
220218
from cosl.rules import AlertRules
221219
from ops.charm import RelationChangedEvent
222220
from ops.framework import EventBase, EventSource, Object, ObjectEvents
@@ -236,7 +234,7 @@ class _MetricsEndpointDict(TypedDict):
236234

237235
LIBID = "dc15fa84cef84ce58155fb84f6c6213a"
238236
LIBAPI = 0
239-
LIBPATCH = 6
237+
LIBPATCH = 7
240238

241239
PYDEPS = ["cosl", "pydantic < 2"]
242240

@@ -251,31 +249,6 @@ class _MetricsEndpointDict(TypedDict):
251249
SnapEndpoint = namedtuple("SnapEndpoint", "owner, name")
252250

253251

254-
class GrafanaDashboard(str):
255-
"""Grafana Dashboard encoded json; lzma-compressed."""
256-
257-
# TODO Replace this with a custom type when pydantic v2 released (end of 2023 Q1?)
258-
# https://github.com/pydantic/pydantic/issues/4887
259-
@staticmethod
260-
def _serialize(raw_json: Union[str, bytes]) -> "GrafanaDashboard":
261-
if not isinstance(raw_json, bytes):
262-
raw_json = raw_json.encode("utf-8")
263-
encoded = base64.b64encode(lzma.compress(raw_json)).decode("utf-8")
264-
return GrafanaDashboard(encoded)
265-
266-
def _deserialize(self) -> Dict:
267-
try:
268-
raw = lzma.decompress(base64.b64decode(self.encode("utf-8"))).decode()
269-
return json.loads(raw)
270-
except json.decoder.JSONDecodeError as e:
271-
logger.error("Invalid Dashboard format: %s", e)
272-
return {}
273-
274-
def __repr__(self):
275-
"""Return string representation of self."""
276-
return "<GrafanaDashboard>"
277-
278-
279252
class CosAgentProviderUnitData(pydantic.BaseModel):
280253
"""Unit databag model for `cos-agent` relation."""
281254

@@ -748,6 +721,10 @@ def metrics_jobs(self) -> List[Dict]:
748721
"job_name": job["job_name"],
749722
"metrics_path": job["path"],
750723
"static_configs": [{"targets": [f"localhost:{job['port']}"]}],
724+
# We include insecure_skip_verify because we are always scraping localhost.
725+
# Even if we have the certs for the scrape targets, we'd rather specify the scrape
726+
# jobs with localhost rather than the SAN DNS the cert was issued for.
727+
"tls_config": {"insecure_skip_verify": True},
751728
}
752729

753730
scrape_jobs.append(job)

src/cluster.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@
4343

4444
PG_BASE_CONF_PATH = f"{POSTGRESQL_CONF_PATH}/postgresql.conf"
4545

46+
RUNNING_STATES = ["running", "streaming"]
47+
4648

4749
class NotReadyError(Exception):
4850
"""Raised when not all cluster members healthy or finished initial sync."""
@@ -297,7 +299,7 @@ def are_all_members_ready(self) -> bool:
297299
# because sometimes there may exist (for some period of time) only
298300
# replicas after a failed switchover.
299301
return all(
300-
member["state"] == "running" for member in cluster_status.json()["members"]
302+
member["state"] in RUNNING_STATES for member in cluster_status.json()["members"]
301303
) and any(member["role"] == "leader" for member in cluster_status.json()["members"])
302304

303305
def get_patroni_health(self) -> Dict[str, str]:
@@ -366,7 +368,7 @@ def member_started(self) -> bool:
366368
except RetryError:
367369
return False
368370

369-
return response["state"] == "running"
371+
return response["state"] in RUNNING_STATES
370372

371373
@property
372374
def member_inactive(self) -> bool:
@@ -381,7 +383,7 @@ def member_inactive(self) -> bool:
381383
except RetryError:
382384
return True
383385

384-
return response["state"] not in ["running", "starting", "restarting"]
386+
return response["state"] not in [*RUNNING_STATES, "starting", "restarting"]
385387

386388
@property
387389
def member_replication_lag(self) -> str:

src/constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
# Snap constants.
3333
PGBACKREST_EXECUTABLE = "charmed-postgresql.pgbackrest"
3434
POSTGRESQL_SNAP_NAME = "charmed-postgresql"
35-
SNAP_PACKAGES = [(POSTGRESQL_SNAP_NAME, {"revision": "87"})]
35+
SNAP_PACKAGES = [(POSTGRESQL_SNAP_NAME, {"revision": "89"})]
3636

3737
SNAP_COMMON_PATH = "/var/snap/charmed-postgresql/common"
3838
SNAP_CURRENT_PATH = "/var/snap/charmed-postgresql/current"

0 commit comments

Comments
 (0)