Skip to content

Commit c509611

Browse files
authored
[MISC] Config hash (#1166)
* Use Patroni API for is_restart_pending * Cached props * Magic sleep and legacy rel names * Hash config value and restart only on change * Tweaks * Legacy interface fix * Fix legacy test * Increase idle period * Wrong username * Remove copypasta
1 parent 1a89287 commit c509611

File tree

9 files changed

+141
-97
lines changed

9 files changed

+141
-97
lines changed

lib/charms/tempo_coordinator_k8s/v0/charm_tracing.py

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -266,20 +266,20 @@ def _remove_stale_otel_sdk_packages():
266266
if name.startswith("opentelemetry_"):
267267
otel_distributions[name].append(distribution)
268268

269-
otel_logger.debug(f"Found {len(otel_distributions)} opentelemetry distributions")
269+
otel_logger.debug("Found %d opentelemetry distributions", len(otel_distributions))
270270

271271
# If we have multiple distributions with the same name, remove any that have 0 associated files
272272
for name, distributions_ in otel_distributions.items():
273273
if len(distributions_) <= 1:
274274
continue
275275

276276
otel_logger.debug(
277-
f"Package {name} has multiple ({len(distributions_)}) distributions."
277+
"Package %s has multiple (%d) distributions.", name, len(distributions_)
278278
)
279279
for distribution in distributions_:
280280
if not distribution.files: # Not None or empty list
281281
path = distribution._path # type: ignore
282-
otel_logger.info(f"Removing empty distribution of {name} at {path}.")
282+
otel_logger.info("Removing empty distribution of %s at %s.", name, path)
283283
shutil.rmtree(path)
284284

285285
otel_logger.debug("Successfully applied _remove_stale_otel_sdk_packages patch. ")
@@ -350,7 +350,7 @@ def _remove_stale_otel_sdk_packages():
350350
# Increment this PATCH version before using `charmcraft publish-lib` or reset
351351
# to 0 if you are raising the major API version
352352

353-
LIBPATCH = 10
353+
LIBPATCH = 11
354354

355355
PYDEPS = ["opentelemetry-exporter-otlp-proto-http==1.21.0"]
356356

@@ -430,7 +430,8 @@ def _prune(self, queue: Sequence[bytes]) -> Sequence[bytes]:
430430
if overflow > 0:
431431
n_dropped_spans += overflow
432432
logger.warning(
433-
f"charm tracing buffer exceeds max history length ({self._max_event_history_length} events)"
433+
"charm tracing buffer exceeds max history length (%d events)",
434+
self._max_event_history_length,
434435
)
435436

436437
new_spans = deque(queue[-self._max_event_history_length :])
@@ -446,19 +447,21 @@ def _prune(self, queue: Sequence[bytes]) -> Sequence[bytes]:
446447
# only do this once
447448
if not logged_drop:
448449
logger.warning(
449-
f"charm tracing buffer exceeds size limit ({self._max_buffer_size_mib}MiB)."
450+
"charm tracing buffer exceeds size limit (%dMiB).",
451+
self._max_buffer_size_mib,
450452
)
451453
logged_drop = True
452454

453455
if n_dropped_spans > 0:
454456
dev_logger.debug(
455-
f"charm tracing buffer overflow: dropped {n_dropped_spans} older spans. "
456-
f"Please increase the buffer limits, or ensure the spans can be flushed."
457+
"charm tracing buffer overflow: dropped %d older spans. "
458+
"Please increase the buffer limits, or ensure the spans can be flushed.",
459+
n_dropped_spans,
457460
)
458461
return new_spans
459462

460463
def _save(self, spans: Sequence[ReadableSpan], replace: bool = False):
461-
dev_logger.debug(f"saving {len(spans)} new spans to buffer")
464+
dev_logger.debug("saving %d new spans to buffer", len(spans))
462465
old = [] if replace else self.load()
463466
queue = old + [self._serialize(spans)]
464467
new_buffer = self._prune(queue)
@@ -480,7 +483,7 @@ def _write(self, spans: Sequence[bytes]):
480483
# ensure the destination folder exists
481484
db_file_dir = self._db_file.parent
482485
if not db_file_dir.exists():
483-
dev_logger.info(f"creating buffer dir: {db_file_dir}")
486+
dev_logger.info("creating buffer dir: %s", db_file_dir)
484487
db_file_dir.mkdir(parents=True)
485488

486489
self._db_file.write_bytes(self._SPANSEP.join(spans))
@@ -496,15 +499,15 @@ def load(self) -> List[bytes]:
496499
try:
497500
spans = self._db_file.read_bytes().split(self._SPANSEP)
498501
except Exception:
499-
logger.exception(f"error parsing {self._db_file}")
502+
logger.exception("error parsing %s", self._db_file)
500503
return []
501504
return spans
502505

503506
def drop(self, n_spans: Optional[int] = None):
504507
"""Drop some currently buffered spans from the cache file."""
505508
current = self.load()
506509
if n_spans:
507-
dev_logger.debug(f"dropping {n_spans} spans from buffer")
510+
dev_logger.debug("dropping %d spans from buffer", n_spans)
508511
new = current[n_spans:]
509512
else:
510513
dev_logger.debug("emptying buffer")
@@ -693,7 +696,7 @@ def _get_tracing_endpoint(
693696
)
694697

695698
dev_logger.debug(
696-
f"Setting up span exporter to endpoint: {tracing_endpoint}/v1/traces"
699+
"Setting up span exporter to endpoint: %s/v1/traces", tracing_endpoint
697700
)
698701
return f"{tracing_endpoint}/v1/traces"
699702

@@ -711,13 +714,17 @@ def _get_server_cert(
711714

712715
if server_cert is None:
713716
logger.warning(
714-
f"{charm_type}.{server_cert_attr} is None; sending traces over INSECURE connection."
717+
"%s.%s is None; sending traces over INSECURE connection.",
718+
charm_type,
719+
server_cert_attr,
715720
)
716721
return
717722
if not isinstance(server_cert, (str, Path)):
718723
logger.warning(
719-
f"{charm_type}.{server_cert_attr} has unexpected type {type(server_cert)}; "
720-
f"sending traces over INSECURE connection."
724+
"%s.%s has unexpected type %s; sending traces over INSECURE connection.",
725+
charm_type,
726+
server_cert_attr,
727+
type(server_cert),
721728
)
722729
return
723730
path = Path(server_cert)
@@ -862,13 +869,13 @@ def wrap_init(self: CharmBase, framework: Framework, *args, **kwargs):
862869

863870
# log a trace id, so we can pick it up from the logs (and jhack) to look it up in tempo.
864871
root_trace_id = hex(span.get_span_context().trace_id)[2:] # strip 0x prefix
865-
logger.debug(f"Starting root trace with id={root_trace_id!r}.")
872+
logger.debug("Starting root trace with id=%r.", root_trace_id)
866873

867874
span_token = opentelemetry.context.attach(ctx) # type: ignore
868875

869876
@contextmanager
870877
def wrap_event_context(event_name: str):
871-
dev_logger.debug(f"entering event context: {event_name}")
878+
dev_logger.debug("entering event context: %s", event_name)
872879
# when the framework enters an event context, we create a span.
873880
with _span("event: " + event_name) as event_context_span:
874881
if event_context_span:
@@ -1059,7 +1066,7 @@ def _autoinstrument(
10591066
Minimum 10MiB.
10601067
:param buffer_path: path to buffer file to use for saving buffered spans.
10611068
"""
1062-
dev_logger.debug(f"instrumenting {charm_type}")
1069+
dev_logger.debug("instrumenting %s", charm_type)
10631070
_setup_root_span_initializer(
10641071
charm_type,
10651072
tracing_endpoint_attr,
@@ -1083,12 +1090,12 @@ def trace_type(cls: _T) -> _T:
10831090
It assumes that this class is only instantiated after a charm type decorated with `@trace_charm`
10841091
has been instantiated.
10851092
"""
1086-
dev_logger.debug(f"instrumenting {cls}")
1093+
dev_logger.debug("instrumenting %s", cls)
10871094
for name, method in inspect.getmembers(cls, predicate=inspect.isfunction):
1088-
dev_logger.debug(f"discovered {method}")
1095+
dev_logger.debug("discovered %s", method)
10891096

10901097
if method.__name__.startswith("__"):
1091-
dev_logger.debug(f"skipping {method} (dunder)")
1098+
dev_logger.debug("skipping %s (dunder)", method)
10921099
continue
10931100

10941101
# the span title in the general case should be:
@@ -1134,7 +1141,7 @@ def trace_function(function: _F, name: Optional[str] = None) -> _F:
11341141

11351142

11361143
def _trace_callable(callable: _F, qualifier: str, name: Optional[str] = None) -> _F:
1137-
dev_logger.debug(f"instrumenting {callable}")
1144+
dev_logger.debug("instrumenting %s", callable)
11381145

11391146
# sig = inspect.signature(callable)
11401147
@functools.wraps(callable)

src/backups.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import tempfile
1313
import time
1414
from datetime import datetime, timezone
15+
from functools import cached_property
1516
from io import BytesIO
1617
from pathlib import Path
1718
from subprocess import TimeoutExpired, run
@@ -86,7 +87,7 @@ def __init__(self, charm, relation_name: str):
8687
self.framework.observe(self.charm.on.list_backups_action, self._on_list_backups_action)
8788
self.framework.observe(self.charm.on.restore_action, self._on_restore_action)
8889

89-
@property
90+
@cached_property
9091
def stanza_name(self) -> str:
9192
"""Stanza name, composed by model and cluster name."""
9293
return f"{self.model.name}.{self.charm.cluster_name}"

0 commit comments

Comments
 (0)