2 # Copyright 2022 Canonical Ltd.
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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
16 # For those usages not covered by the Apache License, Version 2.0 please
17 # contact: legal@canonical.com
19 # To get in touch with the maintainers, please contact:
20 # osm-charmers@lists.launchpad.net
23 # Learn more at: https://juju.is/docs/sdk
27 See more: https://charmhub.io/osm
31 from typing
import Any
, Dict
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 (
40 check_container_ready
,
43 from charms
.osm_nbi
.v0
.nbi
import NbiProvides
44 from lightkube
.models
.core_v1
import ServicePort
45 from ops
.charm
import ActionEvent
, CharmBase
, RelationJoinedEvent
46 from ops
.framework
import StoredState
47 from ops
.main
import main
48 from ops
.model
import ActiveStatus
, Container
50 from legacy_interfaces
import KeystoneClient
, MongoClient
, PrometheusClient
54 config
="nbi-hostpath",
55 container_path
="/usr/lib/python3/dist-packages/osm_nbi",
58 config
="common-hostpath",
59 container_path
="/usr/lib/python3/dist-packages/osm_common",
64 logger
= logging
.getLogger(__name__
)
67 class OsmNbiCharm(CharmBase
):
68 """OSM NBI Kubernetes sidecar charm."""
71 _stored
= StoredState()
73 def __init__(self
, *args
):
74 super().__init
__(*args
)
75 self
.ingress
= IngressRequires(
78 "service-hostname": self
.external_hostname
,
79 "service-name": self
.app
.name
,
80 "service-port": SERVICE_PORT
,
83 self
.kafka
= KafkaRequires(self
)
84 self
.nbi
= NbiProvides(self
)
85 self
.mongodb_client
= MongoClient(self
, "mongodb")
86 self
.prometheus_client
= PrometheusClient(self
, "prometheus")
87 self
.keystone_client
= KeystoneClient(self
, "keystone")
88 self
._observe
_charm
_events
()
89 self
.container
: Container
= self
.unit
.get_container("nbi")
90 self
.debug_mode
= DebugMode(self
, self
._stored
, self
.container
, HOSTPATHS
)
91 self
._patch
_k
8s
_service
()
94 def external_hostname(self
) -> str:
95 """External hostname property.
98 str: the external hostname from config.
99 If not set, return the ClusterIP service name.
101 return self
.config
.get("external-hostname") or self
.app
.name
103 # ---------------------------------------------------------------------------
104 # Handlers for Charm Events
105 # ---------------------------------------------------------------------------
107 def _on_config_changed(self
, _
) -> None:
108 """Handler for the config-changed event."""
110 self
._validate
_config
()
111 self
._check
_relations
()
112 # Check if the container is ready.
113 # Eventually it will become ready after the first pebble-ready event.
114 check_container_ready(self
.container
)
116 if not self
.debug_mode
.started
:
117 self
._configure
_service
(self
.container
)
118 self
._update
_ingress
_config
()
119 self
._update
_nbi
_relation
()
120 # Update charm status
121 self
._on
_update
_status
()
122 except CharmError
as e
:
123 logger
.debug(e
.message
)
124 self
.unit
.status
= e
.status
126 def _on_update_status(self
, _
=None) -> None:
127 """Handler for the update-status event."""
129 self
._check
_relations
()
130 if self
.debug_mode
.started
:
132 check_container_ready(self
.container
)
133 check_service_active(self
.container
, "nbi")
134 self
.unit
.status
= ActiveStatus()
135 except CharmError
as e
:
136 logger
.debug(e
.message
)
137 self
.unit
.status
= e
.status
139 def _on_required_relation_broken(self
, _
) -> None:
140 """Handler for the kafka-broken event."""
141 # Check Pebble has started in the container
143 check_container_ready(self
.container
)
144 check_service_active(self
.container
, "nbi")
145 self
.container
.stop("nbi")
149 self
._on
_update
_status
()
151 def _update_nbi_relation(self
, event
: RelationJoinedEvent
= None) -> None:
152 """Handler for the nbi-relation-joined event."""
153 if self
.unit
.is_leader():
154 self
.nbi
.set_host_info(self
.app
.name
, SERVICE_PORT
, event
.relation
if event
else None)
156 def _on_get_debug_mode_information_action(self
, event
: ActionEvent
) -> None:
157 """Handler for the get-debug-mode-information action event."""
158 if not self
.debug_mode
.started
:
159 event
.fail("debug-mode has not started. Hint: juju config nbi debug-mode=true")
162 debug_info
= {"command": self
.debug_mode
.command
, "password": self
.debug_mode
.password
}
163 event
.set_results(debug_info
)
165 # ---------------------------------------------------------------------------
166 # Validation and configuration and more
167 # ---------------------------------------------------------------------------
169 def _patch_k8s_service(self
) -> None:
170 port
= ServicePort(SERVICE_PORT
, name
=f
"{self.app.name}")
171 self
.service_patcher
= KubernetesServicePatch(self
, [port
])
173 def _observe_charm_events(self
) -> None:
174 event_handler_mapping
= {
175 # Core lifecycle events
176 self
.on
.nbi_pebble_ready
: self
._on
_config
_changed
,
177 self
.on
.config_changed
: self
._on
_config
_changed
,
178 self
.on
.update_status
: self
._on
_update
_status
,
180 self
.on
.kafka_available
: self
._on
_config
_changed
,
181 self
.on
["kafka"].relation_broken
: self
._on
_required
_relation
_broken
,
183 self
.on
.get_debug_mode_information_action
: self
._on
_get
_debug
_mode
_information
_action
,
184 self
.on
.nbi_relation_joined
: self
._update
_nbi
_relation
,
186 for relation
in [self
.on
[rel_name
] for rel_name
in ["mongodb", "prometheus", "keystone"]]:
187 event_handler_mapping
[relation
.relation_changed
] = self
._on
_config
_changed
188 event_handler_mapping
[relation
.relation_broken
] = self
._on
_required
_relation
_broken
190 for event
, handler
in event_handler_mapping
.items():
191 self
.framework
.observe(event
, handler
)
193 def _validate_config(self
) -> None:
194 """Validate charm configuration.
197 CharmError: if charm configuration is invalid.
199 logger
.debug("validating charm config")
201 def _check_relations(self
) -> None:
202 """Validate charm relations.
205 CharmError: if charm configuration is invalid.
207 logger
.debug("check for missing relations")
208 missing_relations
= []
210 if not self
.kafka
.host
or not self
.kafka
.port
:
211 missing_relations
.append("kafka")
212 if self
.mongodb_client
.is_missing_data_in_unit():
213 missing_relations
.append("mongodb")
214 if self
.prometheus_client
.is_missing_data_in_app():
215 missing_relations
.append("prometheus")
216 if self
.keystone_client
.is_missing_data_in_app():
217 missing_relations
.append("keystone")
219 if missing_relations
:
220 relations_str
= ", ".join(missing_relations
)
221 one_relation_missing
= len(missing_relations
) == 1
222 error_msg
= f
'need {relations_str} relation{"" if one_relation_missing else "s"}'
223 logger
.warning(error_msg
)
224 raise CharmError(error_msg
)
226 def _update_ingress_config(self
) -> None:
227 """Update ingress config in relation."""
229 "service-hostname": self
.external_hostname
,
230 "max-body-size": self
.config
["max-body-size"],
232 if "tls-secret-name" in self
.config
:
233 ingress_config
["tls-secret-name"] = self
.config
["tls-secret-name"]
234 logger
.debug(f
"updating ingress-config: {ingress_config}")
235 self
.ingress
.update_config(ingress_config
)
237 def _configure_service(self
, container
: Container
) -> None:
238 """Add Pebble layer with the nbi service."""
239 logger
.debug(f
"configuring {self.app.name} service")
240 container
.add_layer("nbi", self
._get
_layer
(), combine
=True)
243 def _get_layer(self
) -> Dict
[str, Any
]:
244 """Get layer for Pebble."""
246 "summary": "nbi layer",
247 "description": "pebble config layer for nbi",
250 "override": "replace",
251 "summary": "nbi service",
252 "command": "python3 -m osm_nbi.nbi",
253 "startup": "enabled",
257 # General configuration
258 "OSMNBI_SERVER_ENABLE_TEST": False,
259 "OSMNBI_STATIC_DIR": "/app/osm_nbi/html_public",
260 # Kafka configuration
261 "OSMNBI_MESSAGE_HOST": self
.kafka
.host
,
262 "OSMNBI_MESSAGE_PORT": self
.kafka
.port
,
263 "OSMNBI_MESSAGE_DRIVER": "kafka",
264 # Database configuration
265 "OSMNBI_DATABASE_DRIVER": "mongo",
266 "OSMNBI_DATABASE_URI": self
.mongodb_client
.connection_string
,
267 "OSMNBI_DATABASE_COMMONKEY": self
.config
["database-commonkey"],
268 # Storage configuration
269 "OSMNBI_STORAGE_DRIVER": "mongo",
270 "OSMNBI_STORAGE_PATH": "/app/storage",
271 "OSMNBI_STORAGE_COLLECTION": "files",
272 "OSMNBI_STORAGE_URI": self
.mongodb_client
.connection_string
,
273 # Prometheus configuration
274 "OSMNBI_PROMETHEUS_HOST": self
.prometheus_client
.hostname
,
275 "OSMNBI_PROMETHEUS_PORT": self
.prometheus_client
.port
,
277 "OSMNBI_LOG_LEVEL": self
.config
["log-level"],
278 # Authentication environments
279 "OSMNBI_AUTHENTICATION_BACKEND": "keystone",
280 "OSMNBI_AUTHENTICATION_AUTH_URL": self
.keystone_client
.host
,
281 "OSMNBI_AUTHENTICATION_AUTH_PORT": self
.keystone_client
.port
,
282 "OSMNBI_AUTHENTICATION_USER_DOMAIN_NAME": self
.keystone_client
.user_domain_name
,
283 "OSMNBI_AUTHENTICATION_PROJECT_DOMAIN_NAME": self
.keystone_client
.project_domain_name
,
284 "OSMNBI_AUTHENTICATION_SERVICE_USERNAME": self
.keystone_client
.username
,
285 "OSMNBI_AUTHENTICATION_SERVICE_PASSWORD": self
.keystone_client
.password
,
286 "OSMNBI_AUTHENTICATION_SERVICE_PROJECT": self
.keystone_client
.service
,
287 # DISABLING INTERNAL SSL SERVER
288 "OSMNBI_SERVER_SSL_MODULE": "",
289 "OSMNBI_SERVER_SSL_CERTIFICATE": "",
290 "OSMNBI_SERVER_SSL_PRIVATE_KEY": "",
291 "OSMNBI_SERVER_SSL_PASS_PHRASE": "",
298 if __name__
== "__main__": # pragma: no cover