|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2024 Canonical |
| 3 | +# See LICENSE file for licensing details. |
| 4 | + |
| 5 | +"""Tester Charm.""" |
| 6 | + |
| 7 | +import logging |
| 8 | + |
| 9 | +import ops |
| 10 | +from charms.observability_libs.v1.cert_handler import CertHandler |
| 11 | + |
| 12 | +# Log messages can be retrieved using juju debug-log |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | +VALID_LOG_LEVELS = ["info", "debug", "warning", "error", "critical"] |
| 16 | + |
| 17 | +KEY_PATH = "/tmp/server.key" |
| 18 | +CERT_PATH = "/tmp/server.cert" |
| 19 | +CA_CERT_PATH = "/tmp/ca.cert" |
| 20 | + |
| 21 | + |
| 22 | +class TesterCharm(ops.CharmBase): |
| 23 | + """Tester Charm.""" |
| 24 | + |
| 25 | + def __init__(self, *args): |
| 26 | + super().__init__(*args) |
| 27 | + self._name = "httpbin" |
| 28 | + self._container = self.unit.get_container(self._name) |
| 29 | + self.cert_handler = CertHandler( |
| 30 | + charm=self, |
| 31 | + key="tester-server-cert", |
| 32 | + sans=["charm.tester"], |
| 33 | + ) |
| 34 | + self.framework.observe(self.cert_handler.on.cert_changed, self._on_server_cert_changed) |
| 35 | + self.framework.observe(self.on["httpbin"].pebble_ready, self._on_httpbin_pebble_ready) |
| 36 | + self.framework.observe(self.on.config_changed, self._on_config_changed) |
| 37 | + |
| 38 | + def _on_server_cert_changed(self, _): |
| 39 | + self._update_cert() |
| 40 | + |
| 41 | + def _on_httpbin_pebble_ready(self, event: ops.PebbleReadyEvent): |
| 42 | + """Define and start a workload using the Pebble API. |
| 43 | +
|
| 44 | + Change this example to suit your needs. You'll need to specify the right entrypoint and |
| 45 | + environment configuration for your specific workload. |
| 46 | +
|
| 47 | + Learn more about interacting with Pebble at at https://juju.is/docs/sdk/pebble. |
| 48 | + """ |
| 49 | + # Get a reference the container attribute on the PebbleReadyEvent |
| 50 | + container = event.workload |
| 51 | + # Add initial Pebble config layer using the Pebble API |
| 52 | + container.add_layer("httpbin", self._pebble_layer, combine=True) |
| 53 | + # Make Pebble reevaluate its plan, ensuring any services are started if enabled. |
| 54 | + container.replan() |
| 55 | + # Learn more about statuses in the SDK docs: |
| 56 | + # https://juju.is/docs/sdk/constructs#heading--statuses |
| 57 | + self.unit.status = ops.ActiveStatus() |
| 58 | + |
| 59 | + def _on_config_changed(self, event: ops.ConfigChangedEvent): |
| 60 | + """Handle changed configuration. |
| 61 | +
|
| 62 | + Change this example to suit your needs. If you don't need to handle config, you can remove |
| 63 | + this method. |
| 64 | +
|
| 65 | + Learn more about config at https://juju.is/docs/sdk/config |
| 66 | + """ |
| 67 | + # Fetch the new config value |
| 68 | + log_level = self.model.config["log-level"].lower() |
| 69 | + |
| 70 | + # Do some validation of the configuration option |
| 71 | + if log_level in VALID_LOG_LEVELS: |
| 72 | + # Verify that we can connect to the Pebble API in the workload container |
| 73 | + if self._container.can_connect(): |
| 74 | + # Push an updated layer with the new config |
| 75 | + self._container.add_layer("httpbin", self._pebble_layer, combine=True) |
| 76 | + self._container.replan() |
| 77 | + |
| 78 | + logger.debug("Log level for gunicorn changed to '%s'", log_level) |
| 79 | + self.unit.status = ops.ActiveStatus() |
| 80 | + else: |
| 81 | + # We were unable to connect to the Pebble API, so we defer this event |
| 82 | + event.defer() |
| 83 | + self.unit.status = ops.WaitingStatus("waiting for Pebble API") |
| 84 | + else: |
| 85 | + # In this case, the config option is bad, so block the charm and notify the operator. |
| 86 | + self.unit.status = ops.BlockedStatus("invalid log level: '{log_level}'") |
| 87 | + |
| 88 | + @property |
| 89 | + def _pebble_layer(self) -> ops.pebble.LayerDict: |
| 90 | + """Return a dictionary representing a Pebble layer.""" |
| 91 | + return { |
| 92 | + "summary": "httpbin layer", |
| 93 | + "description": "pebble config layer for httpbin", |
| 94 | + "services": { |
| 95 | + "httpbin": { |
| 96 | + "override": "replace", |
| 97 | + "summary": "httpbin", |
| 98 | + "command": "gunicorn -b 0.0.0.0:80 httpbin:app -k gevent", |
| 99 | + "startup": "enabled", |
| 100 | + "environment": { |
| 101 | + "GUNICORN_CMD_ARGS": f"--log-level {self.model.config['log-level']}" |
| 102 | + }, |
| 103 | + } |
| 104 | + }, |
| 105 | + } |
| 106 | + |
| 107 | + def _is_cert_available(self) -> bool: |
| 108 | + return ( |
| 109 | + self.cert_handler.enabled |
| 110 | + and (self.cert_handler.server_cert is not None) |
| 111 | + and (self.cert_handler.private_key is not None) |
| 112 | + and (self.cert_handler.ca_cert is not None) |
| 113 | + ) |
| 114 | + |
| 115 | + def _update_cert(self): |
| 116 | + if not self._container.can_connect(): |
| 117 | + return |
| 118 | + |
| 119 | + if self._is_cert_available(): |
| 120 | + # Save the workload certificates |
| 121 | + self._container.push( |
| 122 | + CERT_PATH, |
| 123 | + self.cert_handler.server_cert, # pyright: ignore |
| 124 | + make_dirs=True, |
| 125 | + ) |
| 126 | + self._container.push( |
| 127 | + KEY_PATH, |
| 128 | + self.cert_handler.private_key, # pyright: ignore |
| 129 | + make_dirs=True, |
| 130 | + ) |
| 131 | + # Save the CA among the trusted CAs and trust it |
| 132 | + self._container.push( |
| 133 | + CA_CERT_PATH, |
| 134 | + self.cert_handler.ca_cert, # pyright: ignore |
| 135 | + make_dirs=True, |
| 136 | + ) |
| 137 | + |
| 138 | + |
| 139 | +if __name__ == "__main__": # pragma: nocover |
| 140 | + ops.main(TesterCharm) # type: ignore |
0 commit comments