diff --git a/lib/charms/tempo_k8s/v1/charm_tracing.py b/lib/charms/tempo_k8s/v1/charm_tracing.py index dc84e3f4e..ebe022e00 100644 --- a/lib/charms/tempo_k8s/v1/charm_tracing.py +++ b/lib/charms/tempo_k8s/v1/charm_tracing.py @@ -9,21 +9,57 @@ This means that, if your charm is related to, for example, COS' Tempo charm, you will be able to inspect in real time from the Grafana dashboard the execution flow of your charm. -To start using this library, you need to do two things: +# Quickstart +Fetch the following charm libs (and ensure the minimum version/revision numbers are satisfied): + + charmcraft fetch-lib charms.tempo_k8s.v2.tracing # >= 1.10 + charmcraft fetch-lib charms.tempo_k8s.v1.charm_tracing # >= 2.7 + +Then edit your charm code to include: + +```python +# import the necessary charm libs +from charms.tempo_k8s.v2.tracing import TracingEndpointRequirer, charm_tracing_config +from charms.tempo_k8s.v1.charm_tracing import charm_tracing + +# decorate your charm class with charm_tracing: +@charm_tracing( + # forward-declare the instance attributes that the instrumentor will look up to obtain the + # tempo endpoint and server certificate + tracing_endpoint="tracing_endpoint", + server_cert="server_cert" +) +class MyCharm(CharmBase): + _path_to_cert = "/path/to/cert.crt" + # path to cert file **in the charm container**. Its presence will be used to determine whether + # the charm is ready to use tls for encrypting charm traces. If your charm does not support tls, + # you can ignore this and pass None to charm_tracing_config. + # If you do support TLS, you'll need to make sure that the server cert is copied to this location + # and kept up to date so the instrumentor can use it. + + def __init__(self, ...): + ... + self.tracing = TracingEndpointRequirer(self, ...) + self.tracing_endpoint, self.server_cert = charm_tracing_config(self.tracing, self._path_to_cert) +``` + +# Detailed usage +To use this library, you need to do two things: 1) decorate your charm class with `@trace_charm(tracing_endpoint="my_tracing_endpoint")` -2) add to your charm a "my_tracing_endpoint" (you can name this attribute whatever you like) **property** -that returns an otlp http/https endpoint url. If you are using the `TracingEndpointProvider` as -`self.tracing = TracingEndpointProvider(self)`, the implementation could be: +2) add to your charm a "my_tracing_endpoint" (you can name this attribute whatever you like) +**property**, **method** or **instance attribute** that returns an otlp http/https endpoint url. +If you are using the ``charms.tempo_k8s.v2.tracing.TracingEndpointRequirer`` as +``self.tracing = TracingEndpointRequirer(self)``, the implementation could be: ``` @property def my_tracing_endpoint(self) -> Optional[str]: '''Tempo endpoint for charm tracing''' if self.tracing.is_ready(): - return self.tracing.otlp_http_endpoint() + return self.tracing.get_endpoint("otlp_http") else: return None ``` @@ -33,19 +69,52 @@ def my_tracing_endpoint(self) -> Optional[str]: - every event as a span (including custom events) - every charm method call (except dunders) as a span -if you wish to add more fine-grained information to the trace, you can do so by getting a hold of the tracer like so: + +## TLS support +If your charm integrates with a TLS provider which is also trusted by the tracing provider (the Tempo charm), +you can configure ``charm_tracing`` to use TLS by passing a ``server_cert`` parameter to the decorator. + +If your charm is not trusting the same CA as the Tempo endpoint it is sending traces to, +you'll need to implement a cert-transfer relation to obtain the CA certificate from the same +CA that Tempo is using. + +For example: +``` +from charms.tempo_k8s.v1.charm_tracing import trace_charm +@trace_charm( + tracing_endpoint="my_tracing_endpoint", + server_cert="_server_cert" +) +class MyCharm(CharmBase): + self._server_cert = "/path/to/server.crt" + ... + + def on_tls_changed(self, e) -> Optional[str]: + # update the server cert on the charm container for charm tracing + Path(self._server_cert).write_text(self.get_server_cert()) + + def on_tls_broken(self, e) -> Optional[str]: + # remove the server cert so charm_tracing won't try to use tls anymore + Path(self._server_cert).unlink() +``` + + +## More fine-grained manual instrumentation +if you wish to add more spans to the trace, you can do so by getting a hold of the tracer like so: ``` import opentelemetry ... - @property - def tracer(self) -> opentelemetry.trace.Tracer: - return opentelemetry.trace.get_tracer(type(self).__name__) +def get_tracer(self) -> opentelemetry.trace.Tracer: + return opentelemetry.trace.get_tracer(type(self).__name__) ``` By default, the tracer is named after the charm type. If you wish to override that, you can pass -a different `service_name` argument to `trace_charm`. +a different ``service_name`` argument to ``trace_charm``. + +See the official opentelemetry Python SDK documentation for usage: +https://opentelemetry-python.readthedocs.io/en/latest/ -*Upgrading from `v0`:* +## Upgrading from `v0` If you are upgrading from `charm_tracing` v0, you need to take the following steps (assuming you already have the newest version of the library in your charm): @@ -55,8 +124,9 @@ def tracer(self) -> opentelemetry.trace.Tracer: `opentelemetry-exporter-otlp-proto-http>=1.21.0`. -2) Update the charm method referenced to from `@trace` and `@trace_charm`, -to return from `TracingEndpointRequirer.otlp_http_endpoint()` instead of `grpc_http`. For example: +2) Update the charm method referenced to from ``@trace`` and ``@trace_charm``, +to return from ``TracingEndpointRequirer.get_endpoint("otlp_http")`` instead of ``grpc_http``. +For example: ``` from charms.tempo_k8s.v0.charm_tracing import trace_charm @@ -72,7 +142,7 @@ class MyCharm(CharmBase): def my_tracing_endpoint(self) -> Optional[str]: '''Tempo endpoint for charm tracing''' if self.tracing.is_ready(): - return self.tracing.otlp_grpc_endpoint() + return self.tracing.otlp_grpc_endpoint() # OLD API, DEPRECATED. else: return None ``` @@ -93,13 +163,13 @@ class MyCharm(CharmBase): def my_tracing_endpoint(self) -> Optional[str]: '''Tempo endpoint for charm tracing''' if self.tracing.is_ready(): - return self.tracing.otlp_http_endpoint() + return self.tracing.get_endpoint("otlp_http") # NEW API, use this. else: return None ``` -3) If you were passing a certificate using `server_cert`, you need to change it to provide an *absolute* path to -the certificate file. +3) If you were passing a certificate (str) using `server_cert`, you need to change it to +provide an *absolute* path to the certificate file instead. """ import functools @@ -122,6 +192,7 @@ def my_tracing_endpoint(self) -> Optional[str]: ) import opentelemetry +import ops from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import Span, TracerProvider @@ -146,14 +217,23 @@ def my_tracing_endpoint(self) -> Optional[str]: # Increment this PATCH version before using `charmcraft publish-lib` or reset # to 0 if you are raising the major API version -LIBPATCH = 10 +LIBPATCH = 11 PYDEPS = ["opentelemetry-exporter-otlp-proto-http==1.21.0"] logger = logging.getLogger("tracing") +dev_logger = logging.getLogger("tracing-dev") + +# set this to 0 if you are debugging/developing this library source +dev_logger.setLevel(logging.CRITICAL) + +_CharmType = Type[CharmBase] # the type CharmBase and any subclass thereof +_C = TypeVar("_C", bound=_CharmType) +_T = TypeVar("_T", bound=type) +_F = TypeVar("_F", bound=Type[Callable]) tracer: ContextVar[Tracer] = ContextVar("tracer") -_GetterType = Union[Callable[[CharmBase], Optional[str]], property] +_GetterType = Union[Callable[[_CharmType], Optional[str]], property] CHARM_TRACING_ENABLED = "CHARM_TRACING_ENABLED" @@ -219,11 +299,6 @@ def _span(name: str) -> Generator[Optional[Span], Any, Any]: yield None -_C = TypeVar("_C", bound=Type[CharmBase]) -_T = TypeVar("_T", bound=type) -_F = TypeVar("_F", bound=Type[Callable]) - - class TracingError(RuntimeError): """Base class for errors raised by this module.""" @@ -232,60 +307,78 @@ class UntraceableObjectError(TracingError): """Raised when an object you're attempting to instrument cannot be autoinstrumented.""" -def _get_tracing_endpoint(tracing_endpoint_getter, self, charm): - if isinstance(tracing_endpoint_getter, property): - tracing_endpoint = tracing_endpoint_getter.__get__(self) - else: # method or callable - tracing_endpoint = tracing_endpoint_getter(self) +class TLSError(TracingError): + """Raised when the tracing endpoint is https but we don't have a cert yet.""" + + +def _get_tracing_endpoint( + tracing_endpoint_attr: str, + charm_instance: object, + charm_type: type, +): + _tracing_endpoint = getattr(charm_instance, tracing_endpoint_attr) + if callable(_tracing_endpoint): + tracing_endpoint = _tracing_endpoint() + else: + tracing_endpoint = _tracing_endpoint if tracing_endpoint is None: - logger.debug( - f"{charm}.{tracing_endpoint_getter} returned None; quietly disabling " - f"charm_tracing for the run." - ) return + elif not isinstance(tracing_endpoint, str): raise TypeError( - f"{charm}.{tracing_endpoint_getter} should return a tempo endpoint (string); " + f"{charm_type.__name__}.{tracing_endpoint_attr} should resolve to a tempo endpoint (string); " f"got {tracing_endpoint} instead." ) - else: - logger.debug(f"Setting up span exporter to endpoint: {tracing_endpoint}/v1/traces") + + dev_logger.debug(f"Setting up span exporter to endpoint: {tracing_endpoint}/v1/traces") return f"{tracing_endpoint}/v1/traces" -def _get_server_cert(server_cert_getter, self, charm): - if isinstance(server_cert_getter, property): - server_cert = server_cert_getter.__get__(self) - else: # method or callable - server_cert = server_cert_getter(self) +def _get_server_cert( + server_cert_attr: str, + charm_instance: ops.CharmBase, + charm_type: Type[ops.CharmBase], +): + _server_cert = getattr(charm_instance, server_cert_attr) + if callable(_server_cert): + server_cert = _server_cert() + else: + server_cert = _server_cert if server_cert is None: logger.warning( - f"{charm}.{server_cert_getter} returned None; sending traces over INSECURE connection." + f"{charm_type}.{server_cert_attr} is None; sending traces over INSECURE connection." ) return elif not Path(server_cert).is_absolute(): raise ValueError( - f"{charm}.{server_cert_getter} should return a valid tls cert absolute path (string | Path)); " + f"{charm_type}.{server_cert_attr} should resolve to a valid tls cert absolute path (string | Path)); " f"got {server_cert} instead." ) return server_cert def _setup_root_span_initializer( - charm: Type[CharmBase], - tracing_endpoint_getter: _GetterType, - server_cert_getter: Optional[_GetterType], + charm_type: _CharmType, + tracing_endpoint_attr: str, + server_cert_attr: Optional[str], service_name: Optional[str] = None, ): """Patch the charm's initializer.""" - original_init = charm.__init__ + original_init = charm_type.__init__ @functools.wraps(original_init) def wrap_init(self: CharmBase, framework: Framework, *args, **kwargs): + # we're using 'self' here because this is charm init code, makes sense to read what's below + # from the perspective of the charm. Self.unit.name... + original_init(self, framework, *args, **kwargs) + # we call this from inside the init context instead of, say, _autoinstrument, because we want it to + # be checked on a per-charm-instantiation basis, not on a per-type-declaration one. if not is_enabled(): + # this will only happen during unittesting, hopefully, so it's fine to log a + # bit more verbosely logger.info("Tracing DISABLED: skipping root span initialization") return @@ -311,25 +404,24 @@ def wrap_init(self: CharmBase, framework: Framework, *args, **kwargs): } ) provider = TracerProvider(resource=resource) - try: - tracing_endpoint = _get_tracing_endpoint(tracing_endpoint_getter, self, charm) - except Exception: - # if anything goes wrong with retrieving the endpoint, we go on with tracing disabled. - # better than breaking the charm. - logger.exception( - f"exception retrieving the tracing " - f"endpoint from {charm}.{tracing_endpoint_getter}; " - f"proceeding with charm_tracing DISABLED. " - ) - return + + # if anything goes wrong with retrieving the endpoint, we let the exception bubble up. + tracing_endpoint = _get_tracing_endpoint(tracing_endpoint_attr, self, charm_type) if not tracing_endpoint: + # tracing is off if tracing_endpoint is None return server_cert: Optional[Union[str, Path]] = ( - _get_server_cert(server_cert_getter, self, charm) if server_cert_getter else None + _get_server_cert(server_cert_attr, self, charm_type) if server_cert_attr else None ) + if tracing_endpoint.startswith("https://") and not server_cert: + raise TLSError( + "Tracing endpoint is https, but no server_cert has been passed." + "Please point @trace_charm to a `server_cert` attr." + ) + exporter = OTLPSpanExporter( endpoint=tracing_endpoint, certificate_file=str(Path(server_cert).absolute()) if server_cert else None, @@ -361,6 +453,7 @@ def wrap_init(self: CharmBase, framework: Framework, *args, **kwargs): @contextmanager def wrap_event_context(event_name: str): + dev_logger.info(f"entering event context: {event_name}") # when the framework enters an event context, we create a span. with _span("event: " + event_name) as event_context_span: if event_context_span: @@ -374,6 +467,7 @@ def wrap_event_context(event_name: str): @functools.wraps(original_close) def wrap_close(): + dev_logger.info("tearing down tracer and flushing traces") span.end() opentelemetry.context.detach(span_token) # type: ignore tracer.reset(_tracer_token) @@ -385,7 +479,7 @@ def wrap_close(): framework.close = wrap_close return - charm.__init__ = wrap_init + charm_type.__init__ = wrap_init # type: ignore def trace_charm( @@ -393,7 +487,7 @@ def trace_charm( server_cert: Optional[str] = None, service_name: Optional[str] = None, extra_types: Sequence[type] = (), -): +) -> Callable[[_T], _T]: """Autoinstrument the decorated charm with tracing telemetry. Use this function to get out-of-the-box traces for all events emitted on this charm and all @@ -401,7 +495,7 @@ def trace_charm( Usage: >>> from charms.tempo_k8s.v1.charm_tracing import trace_charm - >>> from charms.tempo_k8s.v1.tracing import TracingEndpointProvider + >>> from charms.tempo_k8s.v1.tracing import TracingEndpointRequirer >>> from ops import CharmBase >>> >>> @trace_charm( @@ -411,7 +505,7 @@ def trace_charm( >>> >>> def __init__(self, framework: Framework): >>> ... - >>> self.tracing = TracingEndpointProvider(self) + >>> self.tracing = TracingEndpointRequirer(self) >>> >>> @property >>> def tempo_otlp_http_endpoint(self) -> Optional[str]: @@ -420,24 +514,28 @@ def trace_charm( >>> else: >>> return None >>> - :param server_cert: method or property on the charm type that returns an - optional absolute path to a tls certificate to be used when sending traces to a remote server. - If it returns None, an _insecure_ connection will be used. - :param tracing_endpoint: name of a property on the charm type that returns an - optional (fully resolvable) tempo url. If None, tracing will be effectively disabled. Else, traces will be - pushed to that endpoint. + + :param tracing_endpoint: name of a method, property or attribute on the charm type that returns an + optional (fully resolvable) tempo url to which the charm traces will be pushed. + If None, tracing will be effectively disabled. + :param server_cert: name of a method, property or attribute on the charm type that returns an + optional absolute path to a CA certificate file to be used when sending traces to a remote server. + If it returns None, an _insecure_ connection will be used. To avoid errors in transient + situations where the endpoint is already https but there is no certificate on disk yet, it + is recommended to disable tracing (by returning None from the tracing_endpoint) altogether + until the cert has been written to disk. :param service_name: service name tag to attach to all traces generated by this charm. Defaults to the juju application name this charm is deployed under. :param extra_types: pass any number of types that you also wish to autoinstrument. For example, charm libs, relation endpoint wrappers, workload abstractions, ... """ - def _decorator(charm_type: Type[CharmBase]): + def _decorator(charm_type: _T) -> _T: """Autoinstrument the wrapped charmbase type.""" _autoinstrument( charm_type, - tracing_endpoint_getter=getattr(charm_type, tracing_endpoint), - server_cert_getter=getattr(charm_type, server_cert) if server_cert else None, + tracing_endpoint_attr=tracing_endpoint, + server_cert_attr=server_cert, service_name=service_name, extra_types=extra_types, ) @@ -447,12 +545,12 @@ def _decorator(charm_type: Type[CharmBase]): def _autoinstrument( - charm_type: Type[CharmBase], - tracing_endpoint_getter: _GetterType, - server_cert_getter: Optional[_GetterType] = None, + charm_type: _T, + tracing_endpoint_attr: str, + server_cert_attr: Optional[str] = None, service_name: Optional[str] = None, extra_types: Sequence[type] = (), -) -> Type[CharmBase]: +) -> _T: """Set up tracing on this charm class. Use this function to get out-of-the-box traces for all events emitted on this charm and all @@ -464,29 +562,32 @@ def _autoinstrument( >>> from ops.main import main >>> _autoinstrument( >>> MyCharm, - >>> tracing_endpoint_getter=MyCharm.tempo_otlp_http_endpoint, + >>> tracing_endpoint_attr="tempo_otlp_http_endpoint", >>> service_name="MyCharm", >>> extra_types=(Foo, Bar) >>> ) >>> main(MyCharm) :param charm_type: the CharmBase subclass to autoinstrument. - :param server_cert_getter: method or property on the charm type that returns an - optional absolute path to a tls certificate to be used when sending traces to a remote server. - This needs to be a valid path to a certificate. - :param tracing_endpoint_getter: method or property on the charm type that returns an - optional tempo url. If None, tracing will be effectively disabled. Else, traces will be - pushed to that endpoint. + :param tracing_endpoint_attr: name of a method, property or attribute on the charm type that returns an + optional (fully resolvable) tempo url to which the charm traces will be pushed. + If None, tracing will be effectively disabled. + :param server_cert_attr: name of a method, property or attribute on the charm type that returns an + optional absolute path to a CA certificate file to be used when sending traces to a remote server. + If it returns None, an _insecure_ connection will be used. To avoid errors in transient + situations where the endpoint is already https but there is no certificate on disk yet, it + is recommended to disable tracing (by returning None from the tracing_endpoint) altogether + until the cert has been written to disk. :param service_name: service name tag to attach to all traces generated by this charm. Defaults to the juju application name this charm is deployed under. :param extra_types: pass any number of types that you also wish to autoinstrument. For example, charm libs, relation endpoint wrappers, workload abstractions, ... """ - logger.info(f"instrumenting {charm_type}") + dev_logger.info(f"instrumenting {charm_type}") _setup_root_span_initializer( charm_type, - tracing_endpoint_getter, - server_cert_getter=server_cert_getter, + tracing_endpoint_attr, + server_cert_attr=server_cert_attr, service_name=service_name, ) trace_type(charm_type) @@ -503,12 +604,12 @@ def trace_type(cls: _T) -> _T: It assumes that this class is only instantiated after a charm type decorated with `@trace_charm` has been instantiated. """ - logger.info(f"instrumenting {cls}") + dev_logger.info(f"instrumenting {cls}") for name, method in inspect.getmembers(cls, predicate=inspect.isfunction): - logger.info(f"discovered {method}") + dev_logger.info(f"discovered {method}") if method.__name__.startswith("__"): - logger.info(f"skipping {method} (dunder)") + dev_logger.info(f"skipping {method} (dunder)") continue new_method = trace_method(method) @@ -536,7 +637,7 @@ def trace_function(function: _F) -> _F: def _trace_callable(callable: _F, qualifier: str) -> _F: - logger.info(f"instrumenting {callable}") + dev_logger.info(f"instrumenting {callable}") # sig = inspect.signature(callable) @functools.wraps(callable) diff --git a/src/charm.py b/src/charm.py index f921ee523..0111fa344 100755 --- a/src/charm.py +++ b/src/charm.py @@ -50,7 +50,7 @@ PGB_CONF_DIR, PGB_LOG_DIR, PGBOUNCER_EXECUTABLE, - POSTGRESQL_SNAP_NAME, + PGBOUNCER_SNAP_NAME, SECRET_DELETED_LABEL, SECRET_INTERNAL_LABEL, SECRET_KEY_OVERRIDES, @@ -131,7 +131,7 @@ def __init__(self, *args): metrics_endpoints=[ {"path": "/metrics", "port": self.config["metrics_port"]}, ], - log_slots=[f"{POSTGRESQL_SNAP_NAME}:logs"], + log_slots=[f"{PGBOUNCER_SNAP_NAME}:logs"], refresh_events=[self.on.config_changed], ) @@ -209,7 +209,7 @@ def _on_install(self, _) -> None: """ self.unit.status = MaintenanceStatus("Installing and configuring PgBouncer") - # Install the charmed PostgreSQL snap. + # Install the charmed PgBouncer snap. try: self._install_snap_packages(packages=SNAP_PACKAGES) except snap.SnapError: @@ -219,9 +219,8 @@ def _on_install(self, _) -> None: # Try to disable pgbackrest service try: cache = snap.SnapCache() - selected_snap = cache["charmed-postgresql"] + selected_snap = cache[PGBOUNCER_SNAP_NAME] selected_snap.alias("psql") - selected_snap.stop(services=["pgbackrest-service"], disable=True) except snap.SnapError as e: error_message = "Failed to stop and disable pgbackrest snap service" logger.exception(error_message, exc_info=e) @@ -439,7 +438,9 @@ def _get_readonly_dbs(self, databases: Dict) -> Dict[str, str]: readonly_dbs = {} if self.backend.relation and "*" in databases: read_only_endpoints = self.backend.get_read_only_endpoints() - r_hosts = ",".join([r_host.split(":")[0] for r_host in read_only_endpoints]) + sorted_rhosts = [r_host.split(":")[0] for r_host in read_only_endpoints] + sorted_rhosts.sort() + r_hosts = ",".join(sorted_rhosts) if r_hosts: for r_host in read_only_endpoints: r_port = r_host.split(":")[1] @@ -644,7 +645,7 @@ def generate_relation_databases(self) -> Dict[str, Dict[str, Union[str, bool]]]: if "admin" in roles or "superuser" in roles or "createdb" in roles: add_wildcard = True if add_wildcard: - databases["*"] = {"name": "*", "auth_dbname": database} + databases["*"] = {"name": "*", "auth_dbname": database, "legacy": False} self.set_relation_databases(databases) return databases @@ -660,7 +661,9 @@ def _get_relation_config(self) -> [Dict[str, Dict[str, Union[str, bool]]]]: host, port = postgres_endpoint.split(":") read_only_endpoints = self.backend.get_read_only_endpoints() - r_hosts = ",".join([r_host.split(":")[0] for r_host in read_only_endpoints]) + sorted_rhosts = [r_host.split(":")[0] for r_host in read_only_endpoints] + sorted_rhosts.sort() + r_hosts = ",".join(sorted_rhosts) if r_hosts: for r_host in read_only_endpoints: r_port = r_host.split(":")[1] diff --git a/src/constants.py b/src/constants.py index d91dd3fda..21289974e 100644 --- a/src/constants.py +++ b/src/constants.py @@ -10,22 +10,22 @@ AUTH_FILE_NAME = "userlist.txt" # Snap constants. -PGBOUNCER_EXECUTABLE = "charmed-postgresql.pgbouncer" -POSTGRESQL_SNAP_NAME = "charmed-postgresql" +PGBOUNCER_SNAP_NAME = "charmed-pgbouncer" +PGBOUNCER_EXECUTABLE = f"{PGBOUNCER_SNAP_NAME}.pgbouncer" SNAP_PACKAGES = [ ( - POSTGRESQL_SNAP_NAME, - {"revision": {"aarch64": "112", "x86_64": "113"}, "channel": "14/stable"}, + PGBOUNCER_SNAP_NAME, + {"revision": {"aarch64": "4", "x86_64": "3"}, "channel": "1/stable"}, ) ] -SNAP_COMMON_PATH = "/var/snap/charmed-postgresql/common" -SNAP_CURRENT_PATH = "/var/snap/charmed-postgresql/current" +SNAP_COMMON_PATH = f"/var/snap/{PGBOUNCER_SNAP_NAME}/common" +SNAP_CURRENT_PATH = f"/var/snap/{PGBOUNCER_SNAP_NAME}/current" PGB_CONF_DIR = f"{SNAP_CURRENT_PATH}/etc/pgbouncer" PGB_LOG_DIR = f"{SNAP_COMMON_PATH}/var/log/pgbouncer" -SNAP_TMP_DIR = "/tmp/snap-private-tmp/snap.charmed-postgresql/tmp" +SNAP_TMP_DIR = f"/tmp/snap-private-tmp/snap.{PGBOUNCER_SNAP_NAME}/tmp" # PGB config DATABASES = "databases" @@ -61,7 +61,7 @@ "ca": "cauth", } -SOCKET_LOCATION = "/tmp/snap-private-tmp/snap.charmed-postgresql/tmp/pgbouncer/instance_0" +SOCKET_LOCATION = f"/tmp/snap-private-tmp/snap.{PGBOUNCER_SNAP_NAME}/tmp/pgbouncer/instance_0" TRACING_RELATION_NAME = "tracing" TRACING_PROTOCOL = "otlp_http" diff --git a/src/relations/pgbouncer_provider.py b/src/relations/pgbouncer_provider.py index d9eab5546..d87e7b87b 100644 --- a/src/relations/pgbouncer_provider.py +++ b/src/relations/pgbouncer_provider.py @@ -126,7 +126,7 @@ def _on_database_requested(self, event: DatabaseRequestedEvent) -> None: dbs = self.charm.generate_relation_databases() dbs[str(event.relation.id)] = {"name": database, "legacy": False} roles = extra_user_roles.lower().split(",") - if "admin" in roles or "superuser" in roles: + if "admin" in roles or "superuser" in roles or "createdb" in roles: dbs["*"] = {"name": "*", "auth_dbname": database} self.charm.set_relation_databases(dbs) diff --git a/src/upgrade.py b/src/upgrade.py index 804c6fd52..ff8a81f76 100644 --- a/src/upgrade.py +++ b/src/upgrade.py @@ -90,6 +90,7 @@ def _on_upgrade_granted(self, event: UpgradeGrantedEvent) -> None: if self.charm.unit.is_leader(): self.charm.generate_relation_databases() + self.charm.create_instance_directories() self.charm.render_pgb_config() self.charm.render_utility_files() self.charm.reload_pgbouncer() diff --git a/templates/pgbouncer.service.j2 b/templates/pgbouncer.service.j2 index a95a6a284..385e9fd41 100644 --- a/templates/pgbouncer.service.j2 +++ b/templates/pgbouncer.service.j2 @@ -5,9 +5,9 @@ After=network.target [Service] Type=simple ExecStartPre=-/usr/bin/install -o snap_daemon -g snap_daemon -m 700 -d \ - /var/snap/charmed-postgresql/common/var/log/pgbouncer/{{ app_name }}/instance_%i/ \ + /var/snap/charmed-pgbouncer/common/var/log/pgbouncer/{{ app_name }}/instance_%i/ \ {{ snap_tmp_dir }}/{{ app_name }}/instance_%i/ -ExecStart=/snap/bin/charmed-postgresql.pgbouncer-server {{ conf_dir }}/{{ app_name }}/instance_%i/pgbouncer.ini +ExecStart=/snap/bin/charmed-pgbouncer.pgbouncer-server {{ conf_dir }}/{{ app_name }}/instance_%i/pgbouncer.ini KillSignal=SIGINT ExecReload=kill -HUP $MAINPID Restart=always diff --git a/templates/prometheus-exporter.service.j2 b/templates/prometheus-exporter.service.j2 index 0dcee1f83..7a54c5c79 100644 --- a/templates/prometheus-exporter.service.j2 +++ b/templates/prometheus-exporter.service.j2 @@ -4,7 +4,7 @@ After=network.target {{ pgb_service }}@.target [Service] Type=simple -ExecStart=/snap/bin/charmed-postgresql.prometheus-pgbouncer-exporter --web.listen-address=:{{ metrics_port }} --pgBouncer.connectionString="postgres://{{ stats_user }}:{{ stats_password }}@localhost:{{ listen_port }}/pgbouncer?sslmode=disable" +ExecStart=/snap/bin/charmed-pgbouncer.prometheus-pgbouncer-exporter --web.listen-address=:{{ metrics_port }} --pgBouncer.connectionString="postgres://{{ stats_user }}:{{ stats_password }}@localhost:{{ listen_port }}/pgbouncer?sslmode=disable" Restart=always RestartSec=5s diff --git a/tests/unit/relations/test_pgbouncer_provider.py b/tests/unit/relations/test_pgbouncer_provider.py index a4178e13d..b817b841b 100644 --- a/tests/unit/relations/test_pgbouncer_provider.py +++ b/tests/unit/relations/test_pgbouncer_provider.py @@ -47,6 +47,7 @@ def setUp(self): new_callable=PropertyMock, return_value=sentinel.client_rels, ) + @patch("charm.PgBouncerCharm.render_pgb_config") @patch("relations.backend_database.BackendDatabaseRequires.check_backend", return_value=True) @patch( "relations.backend_database.BackendDatabaseRequires.postgres", new_callable=PropertyMock @@ -83,6 +84,7 @@ def test_on_database_requested( _pg_databag, _pg, _check_backend, + _render_pgb_config, _, ): self.harness.set_leader() @@ -130,6 +132,7 @@ def test_on_database_requested( "1": {"name": "test-db", "legacy": False}, "*": {"name": "*", "auth_dbname": "test-db"}, }) + _render_pgb_config.assert_called_once_with(reload_pgbouncer=True) @patch("relations.backend_database.BackendDatabaseRequires.check_backend", return_value=True) @patch( diff --git a/tests/unit/test_charm.py b/tests/unit/test_charm.py index 0a5486208..dcb9a3a48 100644 --- a/tests/unit/test_charm.py +++ b/tests/unit/test_charm.py @@ -80,7 +80,7 @@ def test_on_install( _install, _snap_cache, ): - pg_snap = _snap_cache.return_value["charmed-postgresql"] + pg_snap = _snap_cache.return_value["charmed-pgbouncer"] self.charm.on.install.emit() _install.assert_called_once_with(packages=SNAP_PACKAGES) @@ -222,29 +222,29 @@ def test_install_snap_packages(self, _snap_cache): # Test for problem with snap update. with self.assertRaises(snap.SnapError): - self.charm._install_snap_packages([("postgresql", {"channel": "14/edge"})]) - _snap_cache.return_value.__getitem__.assert_called_once_with("postgresql") + self.charm._install_snap_packages([("pgbouncer", {"channel": "1/edge"})]) + _snap_cache.return_value.__getitem__.assert_called_once_with("pgbouncer") _snap_cache.assert_called_once_with() - _snap_package.ensure.assert_called_once_with(snap.SnapState.Latest, channel="14/edge") + _snap_package.ensure.assert_called_once_with(snap.SnapState.Latest, channel="1/edge") # Test with a not found package. _snap_cache.reset_mock() _snap_package.reset_mock() _snap_package.ensure.side_effect = snap.SnapNotFoundError with self.assertRaises(snap.SnapNotFoundError): - self.charm._install_snap_packages([("postgresql", {"channel": "14/edge"})]) - _snap_cache.return_value.__getitem__.assert_called_once_with("postgresql") + self.charm._install_snap_packages([("pgbouncer", {"channel": "1/edge"})]) + _snap_cache.return_value.__getitem__.assert_called_once_with("pgbouncer") _snap_cache.assert_called_once_with() - _snap_package.ensure.assert_called_once_with(snap.SnapState.Latest, channel="14/edge") + _snap_package.ensure.assert_called_once_with(snap.SnapState.Latest, channel="1/edge") # Then test a valid one. _snap_cache.reset_mock() _snap_package.reset_mock() _snap_package.ensure.side_effect = None - self.charm._install_snap_packages([("postgresql", {"channel": "14/edge"})]) + self.charm._install_snap_packages([("pgbouncer", {"channel": "1/edge"})]) _snap_cache.assert_called_once_with() - _snap_cache.return_value.__getitem__.assert_called_once_with("postgresql") - _snap_package.ensure.assert_called_once_with(snap.SnapState.Latest, channel="14/edge") + _snap_cache.return_value.__getitem__.assert_called_once_with("pgbouncer") + _snap_package.ensure.assert_called_once_with(snap.SnapState.Latest, channel="1/edge") _snap_package.hold.assert_not_called() # Test revision @@ -504,6 +504,46 @@ def test_on_update_status(self, _update_leader, _update_status, _collect_readonl _update_status.assert_called_once_with() _collect_readonly_dbs.assert_called_once_with() + @patch( + "charm.BackendDatabaseRequires.auth_user", + new_callable=PropertyMock, + return_value="auth_user", + ) + @patch( + "charm.BackendDatabaseRequires.postgres_databag", + new_callable=PropertyMock, + return_value={}, + ) + @patch( + "charm.BackendDatabaseRequires.relation", new_callable=PropertyMock, return_value=Mock() + ) + @patch_network_get(private_address="1.1.1.1") + def test_get_readonly_dbs(self, _backend_rel, _postgres_databag, _): + with self.harness.hooks_disabled(): + self.harness.update_relation_data( + self.rel_id, self.charm.app.name, {"readonly_dbs": '["includedb"]'} + ) + + # Returns empty if no wildcard + assert self.charm._get_readonly_dbs({}) == {} + + # Returns empty if no readonly backends + assert self.charm._get_readonly_dbs({"*": {"name": "*", "auth_dbname": "authdb"}}) == {} + + _postgres_databag.return_value = { + "endpoints": "HOST:PORT", + "read-only-endpoints": "HOST2:PORT,HOST3:PORT", + } + assert self.charm._get_readonly_dbs({"*": {"name": "*", "auth_dbname": "authdb"}}) == { + "includedb_readonly": { + "auth_dbname": "authdb", + "auth_user": "auth_user", + "dbname": "includedb", + "host": "HOST2,HOST3", + "port": "PORT", + } + } + @patch("charm.BackendDatabaseRequires.postgres") @patch( "charm.PgBouncerCharm.get_relation_databases", return_value={"1": {"name": "excludeddb"}} diff --git a/tests/unit/test_upgrade.py b/tests/unit/test_upgrade.py index 916f95004..30ee1c6c9 100644 --- a/tests/unit/test_upgrade.py +++ b/tests/unit/test_upgrade.py @@ -42,6 +42,7 @@ def test_log_rollback_instructions(self, _logger: Mock): @patch("charm.PgBouncerCharm.get_secret") @patch("charm.BackendDatabaseRequires.postgres", return_value=True, new_callable=PropertyMock) + @patch("charm.PgBouncerCharm.create_instance_directories") @patch("charm.PgBouncerCharm.update_status") @patch("charm.PgbouncerUpgrade.on_upgrade_changed") @patch("charm.PgbouncerUpgrade.set_unit_completed") @@ -66,6 +67,7 @@ def test_on_upgrade_granted( _set_unit_completed: Mock, _on_upgrade_changed: Mock, _update_status: Mock, + _create_instance_directories: Mock, _, __, ): @@ -83,6 +85,7 @@ def test_on_upgrade_granted( _cluster_checks.assert_called_once_with() _set_unit_completed.assert_called_once_with() _update_status.assert_called_once_with() + _create_instance_directories.asssert_called_once_with() assert not _generate_relation_databases.called # Test extra call as leader @@ -97,6 +100,7 @@ def test_on_upgrade_granted( @patch("charm.PgBouncerCharm.get_secret") @patch("upgrade.wait_fixed", return_value=tenacity.wait_fixed(0)) @patch("charm.BackendDatabaseRequires.postgres", return_value=True, new_callable=PropertyMock) + @patch("charm.PgBouncerCharm.create_instance_directories") @patch("charm.PgbouncerUpgrade.on_upgrade_changed") @patch("charm.PgbouncerUpgrade.set_unit_completed") @patch("charm.PgbouncerUpgrade._cluster_checks") @@ -120,6 +124,7 @@ def test_on_upgrade_granted_error( _, __, ___, + ____, ): _cluster_checks.side_effect = ClusterNotReadyError("test", "test")