From 236e4dc76213f54b2bad3a21ded944da002a36ca Mon Sep 17 00:00:00 2001 From: Luca Bello <36242061+lucabello@users.noreply.github.com> Date: Mon, 28 Aug 2023 13:51:33 +0200 Subject: [PATCH] fix: only add TLS config if cert file has been written to disk (#509) * fix: only add TLS config if cert file has been written to disk * stop prometheus when the relation is there but not the certs * fix lint * add comment * move checks to _configure and add WaitingStatus * tox fmt --- src/charm.py | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/charm.py b/src/charm.py index ceef5469..de256aa3 100755 --- a/src/charm.py +++ b/src/charm.py @@ -339,7 +339,7 @@ def external_url(self) -> str: return self.internal_url def _is_tls_enabled(self): - return bool(self.cert_handler.cert) + return self.cert_handler.enabled @property def _prometheus_layer(self) -> Layer: @@ -364,6 +364,10 @@ def _prometheus_layer(self) -> Layer: return Layer(layer_config) # pyright: ignore + def stop(self) -> None: + """Stop Prometheus.""" + self.container.stop("prometheus") + def _resource_reqs_from_config(self): limits = { "cpu": self.model.config.get("cpu"), @@ -407,6 +411,11 @@ def _on_server_cert_changed(self, _): self.grafana_source_provider.update_source(self.external_url) self._configure(_) + if ( + isinstance(self.unit.status, WaitingStatus) + and self.unit.status.message == "Waiting for TLS certificates to be written to file" + ): + self.unit.status = ActiveStatus() def _configure(self, _): """Reconfigure and either reload or restart Prometheus. @@ -892,10 +901,19 @@ def _generate_prometheus_config(self) -> bool: for filename, contents in certs.items(): self._push(filename, contents) - if web_config := self._web_config(): - self._push(WEB_CONFIG_PATH, yaml.safe_dump(web_config)) + if self._is_tls_enabled() and not self.container.exists(CERT_PATH): + # After a `stop`, the service will autostart on next call to `_configure`, which is + # expected to happen as soon as the the related CA replies with a cert. + self.stop() + if isinstance(self.unit.status, ActiveStatus): + self.unit.status = WaitingStatus( + "Waiting for TLS certificates to be written to file" + ) else: - self.container.remove_path(WEB_CONFIG_PATH, recursive=True) + if web_config := self._web_config(): + self._push(WEB_CONFIG_PATH, yaml.safe_dump(web_config)) + else: + self.container.remove_path(WEB_CONFIG_PATH, recursive=True) self._push(CONFIG_HASH_PATH, config_hash) logger.info("Pushed new configuration")