Move lcm certificate to lcm folder in OSM helm chart
[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.data_platform_libs.v0.data_interfaces import DatabaseRequires
34 from charms.kafka_k8s.v0.kafka import KafkaEvents, KafkaRequires
35 from charms.nginx_ingress_integrator.v0.ingress import IngressRequires
36 from charms.observability_libs.v1.kubernetes_service_patch import KubernetesServicePatch
37 from charms.osm_libs.v0.utils import (
38 CharmError,
39 DebugMode,
40 HostPath,
41 check_container_ready,
42 check_service_active,
43 )
44 from charms.osm_nbi.v0.nbi import NbiProvides
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, 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.mongodb_client = DatabaseRequires(
87 self, "mongodb", database_name="osm", extra_user_roles="admin"
88 )
89 self.prometheus_client = PrometheusClient(self, "prometheus")
90 self.keystone_client = KeystoneClient(self, "keystone")
91 self._observe_charm_events()
92 self.container: Container = self.unit.get_container("nbi")
93 self.debug_mode = DebugMode(self, self._stored, self.container, HOSTPATHS)
94 self._patch_k8s_service()
95
96 @property
97 def external_hostname(self) -> str:
98 """External hostname property.
99
100 Returns:
101 str: the external hostname from config.
102 If not set, return the ClusterIP service name.
103 """
104 return self.config.get("external-hostname") or self.app.name
105
106 # ---------------------------------------------------------------------------
107 # Handlers for Charm Events
108 # ---------------------------------------------------------------------------
109
110 def _on_config_changed(self, _) -> None:
111 """Handler for the config-changed event."""
112 try:
113 self._validate_config()
114 self._check_relations()
115 # Check if the container is ready.
116 # Eventually it will become ready after the first pebble-ready event.
117 check_container_ready(self.container)
118
119 if not self.debug_mode.started:
120 self._configure_service(self.container)
121 self._update_ingress_config()
122 self._update_nbi_relation()
123 # Update charm status
124 self._on_update_status()
125 except CharmError as e:
126 logger.debug(e.message)
127 self.unit.status = e.status
128
129 def _on_update_status(self, _=None) -> None:
130 """Handler for the update-status event."""
131 try:
132 self._check_relations()
133 if self.debug_mode.started:
134 return
135 check_container_ready(self.container)
136 check_service_active(self.container, "nbi")
137 self.unit.status = ActiveStatus()
138 except CharmError as e:
139 logger.debug(e.message)
140 self.unit.status = e.status
141
142 def _on_required_relation_broken(self, _) -> None:
143 """Handler for the kafka-broken event."""
144 # Check Pebble has started in the container
145 try:
146 check_container_ready(self.container)
147 check_service_active(self.container, "nbi")
148 self.container.stop("nbi")
149 except CharmError:
150 pass
151 finally:
152 self._on_update_status()
153
154 def _update_nbi_relation(self, event: RelationJoinedEvent = None) -> None:
155 """Handler for the nbi-relation-joined event."""
156 if self.unit.is_leader():
157 self.nbi.set_host_info(self.app.name, SERVICE_PORT, event.relation if event else None)
158
159 def _on_get_debug_mode_information_action(self, event: ActionEvent) -> None:
160 """Handler for the get-debug-mode-information action event."""
161 if not self.debug_mode.started:
162 event.fail("debug-mode has not started. Hint: juju config nbi debug-mode=true")
163 return
164
165 debug_info = {"command": self.debug_mode.command, "password": self.debug_mode.password}
166 event.set_results(debug_info)
167
168 # ---------------------------------------------------------------------------
169 # Validation and configuration and more
170 # ---------------------------------------------------------------------------
171
172 def _patch_k8s_service(self) -> None:
173 port = ServicePort(SERVICE_PORT, name=f"{self.app.name}")
174 self.service_patcher = KubernetesServicePatch(self, [port])
175
176 def _observe_charm_events(self) -> None:
177 event_handler_mapping = {
178 # Core lifecycle events
179 self.on.nbi_pebble_ready: self._on_config_changed,
180 self.on.config_changed: self._on_config_changed,
181 self.on.update_status: self._on_update_status,
182 # Relation events
183 self.on.kafka_available: self._on_config_changed,
184 self.on["kafka"].relation_broken: self._on_required_relation_broken,
185 self.mongodb_client.on.database_created: self._on_config_changed,
186 self.on["mongodb"].relation_broken: self._on_required_relation_broken,
187 # Action events
188 self.on.get_debug_mode_information_action: self._on_get_debug_mode_information_action,
189 self.on.nbi_relation_joined: self._update_nbi_relation,
190 }
191 for relation in [self.on[rel_name] for rel_name in ["prometheus", "keystone"]]:
192 event_handler_mapping[relation.relation_changed] = self._on_config_changed
193 event_handler_mapping[relation.relation_broken] = self._on_required_relation_broken
194
195 for event, handler in event_handler_mapping.items():
196 self.framework.observe(event, handler)
197
198 def _is_database_available(self) -> bool:
199 try:
200 return self.mongodb_client.is_resource_created()
201 except KeyError:
202 return False
203
204 def _validate_config(self) -> None:
205 """Validate charm configuration.
206
207 Raises:
208 CharmError: if charm configuration is invalid.
209 """
210 logger.debug("validating charm config")
211
212 def _check_relations(self) -> None:
213 """Validate charm relations.
214
215 Raises:
216 CharmError: if charm configuration is invalid.
217 """
218 logger.debug("check for missing relations")
219 missing_relations = []
220
221 if not self.kafka.host or not self.kafka.port:
222 missing_relations.append("kafka")
223 if not self._is_database_available():
224 missing_relations.append("mongodb")
225 if self.prometheus_client.is_missing_data_in_app():
226 missing_relations.append("prometheus")
227 if self.keystone_client.is_missing_data_in_app():
228 missing_relations.append("keystone")
229
230 if missing_relations:
231 relations_str = ", ".join(missing_relations)
232 one_relation_missing = len(missing_relations) == 1
233 error_msg = f'need {relations_str} relation{"" if one_relation_missing else "s"}'
234 logger.warning(error_msg)
235 raise CharmError(error_msg)
236
237 def _update_ingress_config(self) -> None:
238 """Update ingress config in relation."""
239 ingress_config = {
240 "service-hostname": self.external_hostname,
241 "max-body-size": self.config["max-body-size"],
242 }
243 if "tls-secret-name" in self.config:
244 ingress_config["tls-secret-name"] = self.config["tls-secret-name"]
245 logger.debug(f"updating ingress-config: {ingress_config}")
246 self.ingress.update_config(ingress_config)
247
248 def _configure_service(self, container: Container) -> None:
249 """Add Pebble layer with the nbi service."""
250 logger.debug(f"configuring {self.app.name} service")
251 container.add_layer("nbi", self._get_layer(), combine=True)
252 container.replan()
253
254 def _get_layer(self) -> Dict[str, Any]:
255 """Get layer for Pebble."""
256 return {
257 "summary": "nbi layer",
258 "description": "pebble config layer for nbi",
259 "services": {
260 "nbi": {
261 "override": "replace",
262 "summary": "nbi service",
263 "command": "/bin/sh -c 'cd /app/osm_nbi && python3 -m osm_nbi.nbi'", # cd /app/osm_nbi is needed until we upgrade Juju to 3.x
264 "startup": "enabled",
265 "user": "appuser",
266 "group": "appuser",
267 "working-dir": "/app/osm_nbi", # This parameter has no effect in juju 2.9.x
268 "environment": {
269 # General configuration
270 "OSMNBI_SERVER_ENABLE_TEST": False,
271 "OSMNBI_STATIC_DIR": "/app/osm_nbi/html_public",
272 # Kafka configuration
273 "OSMNBI_MESSAGE_HOST": self.kafka.host,
274 "OSMNBI_MESSAGE_PORT": self.kafka.port,
275 "OSMNBI_MESSAGE_DRIVER": "kafka",
276 # Database configuration
277 "OSMNBI_DATABASE_DRIVER": "mongo",
278 "OSMNBI_DATABASE_URI": self._get_mongodb_uri(),
279 "OSMNBI_DATABASE_COMMONKEY": self.config["database-commonkey"],
280 # Storage configuration
281 "OSMNBI_STORAGE_DRIVER": "mongo",
282 "OSMNBI_STORAGE_PATH": "/app/storage",
283 "OSMNBI_STORAGE_COLLECTION": "files",
284 "OSMNBI_STORAGE_URI": self._get_mongodb_uri(),
285 # Prometheus configuration
286 "OSMNBI_PROMETHEUS_HOST": self.prometheus_client.hostname,
287 "OSMNBI_PROMETHEUS_PORT": self.prometheus_client.port,
288 # Log configuration
289 "OSMNBI_LOG_LEVEL": self.config["log-level"],
290 # Authentication environments
291 "OSMNBI_AUTHENTICATION_BACKEND": "keystone",
292 "OSMNBI_AUTHENTICATION_AUTH_URL": self.keystone_client.host,
293 "OSMNBI_AUTHENTICATION_AUTH_PORT": self.keystone_client.port,
294 "OSMNBI_AUTHENTICATION_USER_DOMAIN_NAME": self.keystone_client.user_domain_name,
295 "OSMNBI_AUTHENTICATION_PROJECT_DOMAIN_NAME": self.keystone_client.project_domain_name,
296 "OSMNBI_AUTHENTICATION_SERVICE_USERNAME": self.keystone_client.username,
297 "OSMNBI_AUTHENTICATION_SERVICE_PASSWORD": self.keystone_client.password,
298 "OSMNBI_AUTHENTICATION_SERVICE_PROJECT": self.keystone_client.service,
299 # DISABLING INTERNAL SSL SERVER
300 "OSMNBI_SERVER_SSL_MODULE": "",
301 "OSMNBI_SERVER_SSL_CERTIFICATE": "",
302 "OSMNBI_SERVER_SSL_PRIVATE_KEY": "",
303 "OSMNBI_SERVER_SSL_PASS_PHRASE": "",
304 },
305 }
306 },
307 }
308
309 def _get_mongodb_uri(self):
310 return list(self.mongodb_client.fetch_relation_data().values())[0]["uris"]
311
312
313 if __name__ == "__main__": # pragma: no cover
314 main(OsmNbiCharm)