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
32 from urllib
.parse
import urlparse
34 from charms
.data_platform_libs
.v0
.data_interfaces
import DatabaseRequires
35 from charms
.kafka_k8s
.v0
.kafka
import KafkaEvents
, KafkaRequires
36 from charms
.nginx_ingress_integrator
.v0
.ingress
import IngressRequires
37 from charms
.observability_libs
.v1
.kubernetes_service_patch
import KubernetesServicePatch
38 from charms
.osm_libs
.v0
.utils
import (
42 check_container_ready
,
45 from charms
.osm_nbi
.v0
.nbi
import NbiProvides
46 from lightkube
.models
.core_v1
import ServicePort
47 from ops
.charm
import ActionEvent
, CharmBase
, RelationJoinedEvent
48 from ops
.framework
import StoredState
49 from ops
.main
import main
50 from ops
.model
import ActiveStatus
, Container
52 from legacy_interfaces
import KeystoneClient
56 config
="nbi-hostpath",
57 container_path
="/usr/lib/python3/dist-packages/osm_nbi",
60 config
="common-hostpath",
61 container_path
="/usr/lib/python3/dist-packages/osm_common",
66 logger
= logging
.getLogger(__name__
)
69 class OsmNbiCharm(CharmBase
):
70 """OSM NBI Kubernetes sidecar charm."""
73 _stored
= StoredState()
75 def __init__(self
, *args
):
76 super().__init
__(*args
)
77 self
.ingress
= IngressRequires(
80 "service-hostname": self
.external_hostname
,
81 "service-name": self
.app
.name
,
82 "service-port": SERVICE_PORT
,
85 self
.kafka
= KafkaRequires(self
)
86 self
.nbi
= NbiProvides(self
)
87 self
.mongodb_client
= DatabaseRequires(
88 self
, "mongodb", database_name
="osm", extra_user_roles
="admin"
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
_k
8s
_service
()
97 def external_hostname(self
) -> str:
98 """External hostname property.
101 str: the external hostname from config.
102 If not set, return the ClusterIP service name.
104 return self
.config
.get("external-hostname") or self
.app
.name
106 # ---------------------------------------------------------------------------
107 # Handlers for Charm Events
108 # ---------------------------------------------------------------------------
110 def _on_config_changed(self
, _
) -> None:
111 """Handler for the config-changed event."""
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
)
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
129 def _on_update_status(self
, _
=None) -> None:
130 """Handler for the update-status event."""
132 self
._validate
_config
()
133 self
._check
_relations
()
134 if self
.debug_mode
.started
:
136 check_container_ready(self
.container
)
137 check_service_active(self
.container
, "nbi")
138 self
.unit
.status
= ActiveStatus()
139 except CharmError
as e
:
140 logger
.debug(e
.message
)
141 self
.unit
.status
= e
.status
143 def _on_required_relation_broken(self
, _
) -> None:
144 """Handler for the kafka-broken event."""
145 # Check Pebble has started in the container
147 check_container_ready(self
.container
)
148 check_service_active(self
.container
, "nbi")
149 self
.container
.stop("nbi")
153 self
._on
_update
_status
()
155 def _update_nbi_relation(self
, event
: RelationJoinedEvent
= None) -> None:
156 """Handler for the nbi-relation-joined event."""
157 if self
.unit
.is_leader():
158 self
.nbi
.set_host_info(self
.app
.name
, SERVICE_PORT
, event
.relation
if event
else None)
160 def _on_get_debug_mode_information_action(self
, event
: ActionEvent
) -> None:
161 """Handler for the get-debug-mode-information action event."""
162 if not self
.debug_mode
.started
:
163 event
.fail("debug-mode has not started. Hint: juju config nbi debug-mode=true")
166 debug_info
= {"command": self
.debug_mode
.command
, "password": self
.debug_mode
.password
}
167 event
.set_results(debug_info
)
169 # ---------------------------------------------------------------------------
170 # Validation and configuration and more
171 # ---------------------------------------------------------------------------
173 def _patch_k8s_service(self
) -> None:
174 port
= ServicePort(SERVICE_PORT
, name
=f
"{self.app.name}")
175 self
.service_patcher
= KubernetesServicePatch(self
, [port
])
177 def _observe_charm_events(self
) -> None:
178 event_handler_mapping
= {
179 # Core lifecycle events
180 self
.on
.nbi_pebble_ready
: self
._on
_config
_changed
,
181 self
.on
.config_changed
: self
._on
_config
_changed
,
182 self
.on
.update_status
: self
._on
_update
_status
,
184 self
.on
.kafka_available
: self
._on
_config
_changed
,
185 self
.on
["kafka"].relation_broken
: self
._on
_required
_relation
_broken
,
186 self
.mongodb_client
.on
.database_created
: self
._on
_config
_changed
,
187 self
.on
["mongodb"].relation_broken
: self
._on
_required
_relation
_broken
,
188 self
.on
["keystone"].relation_changed
: self
._on
_config
_changed
,
189 self
.on
["keystone"].relation_broken
: self
._on
_required
_relation
_broken
,
191 self
.on
.get_debug_mode_information_action
: self
._on
_get
_debug
_mode
_information
_action
,
192 self
.on
.nbi_relation_joined
: self
._update
_nbi
_relation
,
195 for event
, handler
in event_handler_mapping
.items():
196 self
.framework
.observe(event
, handler
)
198 def _is_database_available(self
) -> bool:
200 return self
.mongodb_client
.is_resource_created()
204 def _validate_config(self
) -> None:
205 """Validate charm configuration.
208 CharmError: if charm configuration is invalid.
210 logger
.debug("validating charm config")
211 url
= self
.config
.get("prometheus-url")
213 raise CharmError("need prometheus-url config")
214 if not self
._is
_valid
_url
(url
):
215 raise CharmError(f
"Invalid value for prometheus-url config: '{url}'")
217 def _is_valid_url(self
, url
) -> bool:
218 return urlparse(url
).hostname
is not None
220 def _check_relations(self
) -> None:
221 """Validate charm relations.
224 CharmError: if charm configuration is invalid.
226 logger
.debug("check for missing relations")
227 missing_relations
= []
229 if not self
.kafka
.host
or not self
.kafka
.port
:
230 missing_relations
.append("kafka")
231 if not self
._is
_database
_available
():
232 missing_relations
.append("mongodb")
233 if self
.keystone_client
.is_missing_data_in_app():
234 missing_relations
.append("keystone")
236 if missing_relations
:
237 relations_str
= ", ".join(missing_relations
)
238 one_relation_missing
= len(missing_relations
) == 1
239 error_msg
= f
'need {relations_str} relation{"" if one_relation_missing else "s"}'
240 logger
.warning(error_msg
)
241 raise CharmError(error_msg
)
243 def _update_ingress_config(self
) -> None:
244 """Update ingress config in relation."""
246 "service-hostname": self
.external_hostname
,
247 "max-body-size": self
.config
["max-body-size"],
249 if "tls-secret-name" in self
.config
:
250 ingress_config
["tls-secret-name"] = self
.config
["tls-secret-name"]
251 logger
.debug(f
"updating ingress-config: {ingress_config}")
252 self
.ingress
.update_config(ingress_config
)
254 def _configure_service(self
, container
: Container
) -> None:
255 """Add Pebble layer with the nbi service."""
256 logger
.debug(f
"configuring {self.app.name} service")
257 container
.add_layer("nbi", self
._get
_layer
(), combine
=True)
260 def _get_layer(self
) -> Dict
[str, Any
]:
261 """Get layer for Pebble."""
262 prometheus
= urlparse(self
.config
["prometheus-url"])
264 "summary": "nbi layer",
265 "description": "pebble config layer for nbi",
268 "override": "replace",
269 "summary": "nbi service",
270 "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
271 "startup": "enabled",
274 "working-dir": "/app/osm_nbi", # This parameter has no effect in juju 2.9.x
276 # General configuration
277 "OSMNBI_SERVER_ENABLE_TEST": False,
278 "OSMNBI_STATIC_DIR": "/app/osm_nbi/html_public",
279 # Kafka configuration
280 "OSMNBI_MESSAGE_HOST": self
.kafka
.host
,
281 "OSMNBI_MESSAGE_PORT": self
.kafka
.port
,
282 "OSMNBI_MESSAGE_DRIVER": "kafka",
283 # Database configuration
284 "OSMNBI_DATABASE_DRIVER": "mongo",
285 "OSMNBI_DATABASE_URI": self
._get
_mongodb
_uri
(),
286 "OSMNBI_DATABASE_COMMONKEY": self
.config
["database-commonkey"],
287 # Storage configuration
288 "OSMNBI_STORAGE_DRIVER": "mongo",
289 "OSMNBI_STORAGE_PATH": "/app/storage",
290 "OSMNBI_STORAGE_COLLECTION": "files",
291 "OSMNBI_STORAGE_URI": self
._get
_mongodb
_uri
(),
292 # Prometheus configuration
293 "OSMNBI_PROMETHEUS_HOST": prometheus
.hostname
,
294 "OSMNBI_PROMETHEUS_PORT": prometheus
.port
if prometheus
.port
else "",
296 "OSMNBI_LOG_LEVEL": self
.config
["log-level"],
297 # Authentication environments
298 "OSMNBI_AUTHENTICATION_BACKEND": "keystone",
299 "OSMNBI_AUTHENTICATION_AUTH_URL": self
.keystone_client
.host
,
300 "OSMNBI_AUTHENTICATION_AUTH_PORT": self
.keystone_client
.port
,
301 "OSMNBI_AUTHENTICATION_USER_DOMAIN_NAME": self
.keystone_client
.user_domain_name
,
302 "OSMNBI_AUTHENTICATION_PROJECT_DOMAIN_NAME": self
.keystone_client
.project_domain_name
,
303 "OSMNBI_AUTHENTICATION_SERVICE_USERNAME": self
.keystone_client
.username
,
304 "OSMNBI_AUTHENTICATION_SERVICE_PASSWORD": self
.keystone_client
.password
,
305 "OSMNBI_AUTHENTICATION_SERVICE_PROJECT": self
.keystone_client
.service
,
306 # DISABLING INTERNAL SSL SERVER
307 "OSMNBI_SERVER_SSL_MODULE": "",
308 "OSMNBI_SERVER_SSL_CERTIFICATE": "",
309 "OSMNBI_SERVER_SSL_PRIVATE_KEY": "",
310 "OSMNBI_SERVER_SSL_PASS_PHRASE": "",
316 def _get_mongodb_uri(self
):
317 return list(self
.mongodb_client
.fetch_relation_data().values())[0]["uris"]
320 if __name__
== "__main__": # pragma: no cover