Add Ng-UI sidecar charm
[osm/devops.git] / installers / charm / osm-ng-ui / src / charm.py
1 #!/usr/bin/env python3
2 # Copyright 2022 Canonical Ltd.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15 #
16 # For those usages not covered by the Apache License, Version 2.0 please
17 # contact: legal@canonical.com
18 #
19 # To get in touch with the maintainers, please contact:
20 # osm-charmers@lists.launchpad.net
21 #
22 #
23 # Learn more at: https://juju.is/docs/sdk
24
25 """OSM NG-UI charm.
26
27 See more: https://charmhub.io/osm
28 """
29
30 import logging
31 import re
32 from typing import Any, Dict
33
34 from charms.nginx_ingress_integrator.v0.ingress import IngressRequires
35 from charms.observability_libs.v1.kubernetes_service_patch import KubernetesServicePatch
36 from charms.osm_libs.v0.utils import (
37 CharmError,
38 check_container_ready,
39 check_service_active,
40 )
41 from charms.osm_nbi.v0.nbi import NbiRequires
42 from lightkube.models.core_v1 import ServicePort
43 from ops.charm import CharmBase
44 from ops.framework import StoredState
45 from ops.main import main
46 from ops.model import ActiveStatus, Container
47
48 SERVICE_PORT = 80
49
50 logger = logging.getLogger(__name__)
51
52
53 class OsmNgUiCharm(CharmBase):
54 """OSM NG-UI Kubernetes sidecar charm."""
55
56 _stored = StoredState()
57
58 def __init__(self, *args):
59 super().__init__(*args)
60 self.ingress = IngressRequires(
61 self,
62 {
63 "service-hostname": self.external_hostname,
64 "service-name": self.app.name,
65 "service-port": SERVICE_PORT,
66 },
67 )
68 self._observe_charm_events()
69 self._patch_k8s_service()
70 self._stored.set_default(default_site_patched=False)
71 self.nbi = NbiRequires(self)
72 self.container: Container = self.unit.get_container("ng-ui")
73
74 @property
75 def external_hostname(self) -> str:
76 """External hostname property.
77
78 Returns:
79 str: the external hostname from config.
80 If not set, return the ClusterIP service name.
81 """
82 return self.config.get("external-hostname") or self.app.name
83
84 # ---------------------------------------------------------------------------
85 # Handlers for Charm Events
86 # ---------------------------------------------------------------------------
87
88 def _on_config_changed(self, _) -> None:
89 """Handler for the config-changed event."""
90 try:
91 self._validate_config()
92 self._check_relations()
93 # Check if the container is ready.
94 # Eventually it will become ready after the first pebble-ready event.
95 check_container_ready(self.container)
96
97 self._configure_service(self.container)
98 self._update_ingress_config()
99 # Update charm status
100 self._on_update_status()
101 except CharmError as e:
102 logger.debug(e.message)
103 self.unit.status = e.status
104
105 def _on_update_status(self, _=None) -> None:
106 """Handler for the update-status event."""
107 try:
108 self._check_relations()
109 check_container_ready(self.container)
110 check_service_active(self.container, "ng-ui")
111 self.unit.status = ActiveStatus()
112 except CharmError as e:
113 logger.debug(e.message)
114 self.unit.status = e.status
115
116 def _on_required_relation_broken(self, _) -> None:
117 """Handler for the kafka-broken event."""
118 # Check Pebble has started in the container
119 try:
120 check_container_ready(self.container)
121 check_service_active(self.container, "ng-ui")
122 self.container.stop("ng-ui")
123 self._stored.default_site_patched = False
124 except CharmError:
125 pass
126 finally:
127 self._on_update_status()
128
129 # ---------------------------------------------------------------------------
130 # Validation and configuration and more
131 # ---------------------------------------------------------------------------
132
133 def _patch_k8s_service(self) -> None:
134 port = ServicePort(SERVICE_PORT, name=f"{self.app.name}")
135 self.service_patcher = KubernetesServicePatch(self, [port])
136
137 def _observe_charm_events(self) -> None:
138 event_handler_mapping = {
139 # Core lifecycle events
140 self.on.ng_ui_pebble_ready: self._on_config_changed,
141 self.on.config_changed: self._on_config_changed,
142 self.on.update_status: self._on_update_status,
143 # Relation events
144 self.on["nbi"].relation_changed: self._on_config_changed,
145 self.on["nbi"].relation_broken: self._on_required_relation_broken,
146 }
147 for event, handler in event_handler_mapping.items():
148 self.framework.observe(event, handler)
149
150 def _validate_config(self) -> None:
151 """Validate charm configuration.
152
153 Raises:
154 CharmError: if charm configuration is invalid.
155 """
156 logger.debug("validating charm config")
157
158 def _check_relations(self) -> None:
159 """Validate charm relations.
160
161 Raises:
162 CharmError: if charm configuration is invalid.
163 """
164 logger.debug("check for missing relations")
165
166 if not self.nbi.host or not self.nbi.port:
167 raise CharmError("need nbi relation")
168
169 def _update_ingress_config(self) -> None:
170 """Update ingress config in relation."""
171 ingress_config = {
172 "service-hostname": self.external_hostname,
173 "max-body-size": self.config["max-body-size"],
174 }
175 if "tls-secret-name" in self.config:
176 ingress_config["tls-secret-name"] = self.config["tls-secret-name"]
177 logger.debug(f"updating ingress-config: {ingress_config}")
178 self.ingress.update_config(ingress_config)
179
180 def _configure_service(self, container: Container) -> None:
181 """Add Pebble layer with the ng-ui service."""
182 logger.debug(f"configuring {self.app.name} service")
183 self._patch_default_site(container)
184 container.add_layer("ng-ui", self._get_layer(), combine=True)
185 container.replan()
186
187 def _get_layer(self) -> Dict[str, Any]:
188 """Get layer for Pebble."""
189 return {
190 "summary": "ng-ui layer",
191 "description": "pebble config layer for ng-ui",
192 "services": {
193 "ng-ui": {
194 "override": "replace",
195 "summary": "ng-ui service",
196 "command": 'nginx -g "daemon off;"',
197 "startup": "enabled",
198 }
199 },
200 }
201
202 def _patch_default_site(self, container: Container) -> None:
203 max_body_size = self.config.get("max-body-size")
204 if (
205 self._stored.default_site_patched
206 and max_body_size == self._stored.default_site_max_body_size
207 ):
208 return
209 default_site_config = container.pull("/etc/nginx/sites-available/default").read()
210 default_site_config = re.sub(
211 "client_max_body_size .*\n",
212 f"client_max_body_size {max_body_size}M;\n",
213 default_site_config,
214 )
215 default_site_config = re.sub(
216 "proxy_pass .*\n",
217 f"proxy_pass https://{self.nbi.host}:{self.nbi.port};\n",
218 default_site_config,
219 )
220 container.push("/etc/nginx/sites-available/default", default_site_config)
221 self._stored.default_site_patched = True
222 self._stored.default_site_max_body_size = max_body_size
223
224
225 if __name__ == "__main__": # pragma: no cover
226 main(OsmNgUiCharm)