Merge remote-tracking branch 'origin/master' into paas
[osm/devops.git] / installers / charm / osm-nbi / 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 NBI charm.
26
27 See more: https://charmhub.io/osm
28 """
29
30 import logging
31 from typing import Any, Dict
32
33 from charms.kafka_k8s.v0.kafka import KafkaEvents, KafkaRequires
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 DebugMode,
39 HostPath,
40 check_container_ready,
41 check_service_active,
42 )
43 from charms.osm_nbi.v0.nbi import NbiProvides
44 from charms.osm_temporal.v0.temporal import TemporalRequires
45 from lightkube.models.core_v1 import ServicePort
46 from ops.charm import ActionEvent, CharmBase, RelationJoinedEvent
47 from ops.framework import StoredState
48 from ops.main import main
49 from ops.model import ActiveStatus, Container
50
51 from legacy_interfaces import KeystoneClient, MongoClient, PrometheusClient
52
53 HOSTPATHS = [
54 HostPath(
55 config="nbi-hostpath",
56 container_path="/usr/lib/python3/dist-packages/osm_nbi",
57 ),
58 HostPath(
59 config="common-hostpath",
60 container_path="/usr/lib/python3/dist-packages/osm_common",
61 ),
62 ]
63 SERVICE_PORT = 9999
64
65 logger = logging.getLogger(__name__)
66
67
68 class OsmNbiCharm(CharmBase):
69 """OSM NBI Kubernetes sidecar charm."""
70
71 on = KafkaEvents()
72 _stored = StoredState()
73
74 def __init__(self, *args):
75 super().__init__(*args)
76 self.ingress = IngressRequires(
77 self,
78 {
79 "service-hostname": self.external_hostname,
80 "service-name": self.app.name,
81 "service-port": SERVICE_PORT,
82 },
83 )
84 self.kafka = KafkaRequires(self)
85 self.nbi = NbiProvides(self)
86 self.temporal = TemporalRequires(self)
87 self.mongodb_client = MongoClient(self, "mongodb")
88 self.prometheus_client = PrometheusClient(self, "prometheus")
89 self.keystone_client = KeystoneClient(self, "keystone")
90 self._observe_charm_events()
91 self.container: Container = self.unit.get_container("nbi")
92 self.debug_mode = DebugMode(self, self._stored, self.container, HOSTPATHS)
93 self._patch_k8s_service()
94
95 @property
96 def external_hostname(self) -> str:
97 """External hostname property.
98
99 Returns:
100 str: the external hostname from config.
101 If not set, return the ClusterIP service name.
102 """
103 return self.config.get("external-hostname") or self.app.name
104
105 # ---------------------------------------------------------------------------
106 # Handlers for Charm Events
107 # ---------------------------------------------------------------------------
108
109 def _on_config_changed(self, _) -> None:
110 """Handler for the config-changed event."""
111 try:
112 self._validate_config()
113 self._check_relations()
114 # Check if the container is ready.
115 # Eventually it will become ready after the first pebble-ready event.
116 check_container_ready(self.container)
117
118 if not self.debug_mode.started:
119 self._configure_service(self.container)
120 self._update_ingress_config()
121 self._update_nbi_relation()
122 # Update charm status
123 self._on_update_status()
124 except CharmError as e:
125 logger.debug(e.message)
126 self.unit.status = e.status
127
128 def _on_update_status(self, _=None) -> None:
129 """Handler for the update-status event."""
130 try:
131 self._check_relations()
132 if self.debug_mode.started:
133 return
134 check_container_ready(self.container)
135 check_service_active(self.container, "nbi")
136 self.unit.status = ActiveStatus()
137 except CharmError as e:
138 logger.debug(e.message)
139 self.unit.status = e.status
140
141 def _on_required_relation_broken(self, _) -> None:
142 """Handler for the kafka-broken event."""
143 # Check Pebble has started in the container
144 try:
145 check_container_ready(self.container)
146 check_service_active(self.container, "nbi")
147 self.container.stop("nbi")
148 except CharmError:
149 pass
150 finally:
151 self._on_update_status()
152
153 def _update_nbi_relation(self, event: RelationJoinedEvent = None) -> None:
154 """Handler for the nbi-relation-joined event."""
155 if self.unit.is_leader():
156 self.nbi.set_host_info(self.app.name, SERVICE_PORT, event.relation if event else None)
157
158 def _on_get_debug_mode_information_action(self, event: ActionEvent) -> None:
159 """Handler for the get-debug-mode-information action event."""
160 if not self.debug_mode.started:
161 event.fail("debug-mode has not started. Hint: juju config nbi debug-mode=true")
162 return
163
164 debug_info = {"command": self.debug_mode.command, "password": self.debug_mode.password}
165 event.set_results(debug_info)
166
167 # ---------------------------------------------------------------------------
168 # Validation and configuration and more
169 # ---------------------------------------------------------------------------
170
171 def _patch_k8s_service(self) -> None:
172 port = ServicePort(SERVICE_PORT, name=f"{self.app.name}")
173 self.service_patcher = KubernetesServicePatch(self, [port])
174
175 def _observe_charm_events(self) -> None:
176 event_handler_mapping = {
177 # Core lifecycle events
178 self.on.nbi_pebble_ready: self._on_config_changed,
179 self.on.config_changed: self._on_config_changed,
180 self.on.update_status: self._on_update_status,
181 # Relation events
182 self.on.kafka_available: self._on_config_changed,
183 self.on["kafka"].relation_broken: self._on_required_relation_broken,
184 # Action events
185 self.on.get_debug_mode_information_action: self._on_get_debug_mode_information_action,
186 self.on.nbi_relation_joined: self._update_nbi_relation,
187 self.on["temporal"].relation_changed: self._on_config_changed,
188 self.on["temporal"].relation_broken: self._on_required_relation_broken,
189 }
190 for relation in [self.on[rel_name] for rel_name in ["mongodb", "prometheus", "keystone"]]:
191 event_handler_mapping[relation.relation_changed] = self._on_config_changed
192 event_handler_mapping[relation.relation_broken] = self._on_required_relation_broken
193
194 for event, handler in event_handler_mapping.items():
195 self.framework.observe(event, handler)
196
197 def _validate_config(self) -> None:
198 """Validate charm configuration.
199
200 Raises:
201 CharmError: if charm configuration is invalid.
202 """
203 logger.debug("validating charm config")
204
205 def _check_relations(self) -> None:
206 """Validate charm relations.
207
208 Raises:
209 CharmError: if charm configuration is invalid.
210 """
211 logger.debug("check for missing relations")
212 missing_relations = []
213
214 if not self.kafka.host or not self.kafka.port:
215 missing_relations.append("kafka")
216 if self.mongodb_client.is_missing_data_in_unit():
217 missing_relations.append("mongodb")
218 if self.prometheus_client.is_missing_data_in_app():
219 missing_relations.append("prometheus")
220 if self.keystone_client.is_missing_data_in_app():
221 missing_relations.append("keystone")
222 if not self.temporal.host or not self.temporal.port:
223 missing_relations.append("temporal")
224
225 if missing_relations:
226 relations_str = ", ".join(missing_relations)
227 one_relation_missing = len(missing_relations) == 1
228 error_msg = f'need {relations_str} relation{"" if one_relation_missing else "s"}'
229 logger.warning(error_msg)
230 raise CharmError(error_msg)
231
232 def _update_ingress_config(self) -> None:
233 """Update ingress config in relation."""
234 ingress_config = {
235 "service-hostname": self.external_hostname,
236 "max-body-size": self.config["max-body-size"],
237 }
238 if "tls-secret-name" in self.config:
239 ingress_config["tls-secret-name"] = self.config["tls-secret-name"]
240 logger.debug(f"updating ingress-config: {ingress_config}")
241 self.ingress.update_config(ingress_config)
242
243 def _configure_service(self, container: Container) -> None:
244 """Add Pebble layer with the nbi service."""
245 logger.debug(f"configuring {self.app.name} service")
246 container.add_layer("nbi", self._get_layer(), combine=True)
247 container.replan()
248
249 def _get_layer(self) -> Dict[str, Any]:
250 """Get layer for Pebble."""
251 return {
252 "summary": "nbi layer",
253 "description": "pebble config layer for nbi",
254 "services": {
255 "nbi": {
256 "override": "replace",
257 "summary": "nbi service",
258 "command": "python3 -m osm_nbi.nbi",
259 "startup": "enabled",
260 "user": "appuser",
261 "group": "appuser",
262 "environment": {
263 # General configuration
264 "OSMNBI_SERVER_ENABLE_TEST": False,
265 "OSMNBI_STATIC_DIR": "/app/osm_nbi/html_public",
266 # Kafka configuration
267 "OSMNBI_MESSAGE_HOST": self.kafka.host,
268 "OSMNBI_MESSAGE_PORT": self.kafka.port,
269 "OSMNBI_MESSAGE_DRIVER": "kafka",
270 # Database configuration
271 "OSMNBI_DATABASE_DRIVER": "mongo",
272 "OSMNBI_DATABASE_URI": self.mongodb_client.connection_string,
273 "OSMNBI_DATABASE_COMMONKEY": self.config["database-commonkey"],
274 # Storage configuration
275 "OSMNBI_STORAGE_DRIVER": "mongo",
276 "OSMNBI_STORAGE_PATH": "/app/storage",
277 "OSMNBI_STORAGE_COLLECTION": "files",
278 "OSMNBI_STORAGE_URI": self.mongodb_client.connection_string,
279 # Prometheus configuration
280 "OSMNBI_PROMETHEUS_HOST": self.prometheus_client.hostname,
281 "OSMNBI_PROMETHEUS_PORT": self.prometheus_client.port,
282 # Log configuration
283 "OSMNBI_LOG_LEVEL": self.config["log-level"],
284 # Authentication environments
285 "OSMNBI_AUTHENTICATION_BACKEND": "keystone",
286 "OSMNBI_AUTHENTICATION_AUTH_URL": self.keystone_client.host,
287 "OSMNBI_AUTHENTICATION_AUTH_PORT": self.keystone_client.port,
288 "OSMNBI_AUTHENTICATION_USER_DOMAIN_NAME": self.keystone_client.user_domain_name,
289 "OSMNBI_AUTHENTICATION_PROJECT_DOMAIN_NAME": self.keystone_client.project_domain_name,
290 "OSMNBI_AUTHENTICATION_SERVICE_USERNAME": self.keystone_client.username,
291 "OSMNBI_AUTHENTICATION_SERVICE_PASSWORD": self.keystone_client.password,
292 "OSMNBI_AUTHENTICATION_SERVICE_PROJECT": self.keystone_client.service,
293 # DISABLING INTERNAL SSL SERVER
294 "OSMNBI_SERVER_SSL_MODULE": "",
295 "OSMNBI_SERVER_SSL_CERTIFICATE": "",
296 "OSMNBI_SERVER_SSL_PRIVATE_KEY": "",
297 "OSMNBI_SERVER_SSL_PASS_PHRASE": "",
298 # Temporal configuration
299 "OSMNBI_TEMPORAL_HOST": self.temporal.host,
300 "OSMNBI_TEMPORAL_PORT": self.temporal.port,
301 },
302 }
303 },
304 }
305
306
307 if __name__ == "__main__": # pragma: no cover
308 main(OsmNbiCharm)