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
.data_platform_libs
.v0
.data_interfaces
import DatabaseRequires
34 from charms
.kafka_k8s
.v0
.kafka
import KafkaEvents
, KafkaRequires
35 from charms
.osm_libs
.v0
.utils
import (
39 check_container_ready
,
42 from ops
.charm
import ActionEvent
, CharmBase
43 from ops
.framework
import StoredState
44 from ops
.main
import main
45 from ops
.model
import ActiveStatus
, Container
47 from legacy_interfaces
import MysqlClient
51 config
="pol-hostpath",
52 container_path
="/usr/lib/python3/dist-packages/osm_policy_module",
55 config
="common-hostpath",
56 container_path
="/usr/lib/python3/dist-packages/osm_common",
60 logger
= logging
.getLogger(__name__
)
63 class OsmPolCharm(CharmBase
):
64 """OSM POL Kubernetes sidecar charm."""
67 _stored
= StoredState()
68 container_name
= "pol"
71 def __init__(self
, *args
):
72 super().__init
__(*args
)
74 self
.kafka
= KafkaRequires(self
)
75 self
.mongodb_client
= DatabaseRequires(self
, "mongodb", database_name
="osm")
76 self
.mysql_client
= MysqlClient(self
, "mysql")
77 self
._observe
_charm
_events
()
78 self
.container
: Container
= self
.unit
.get_container(self
.container_name
)
79 self
.debug_mode
= DebugMode(self
, self
._stored
, self
.container
, HOSTPATHS
)
81 # ---------------------------------------------------------------------------
82 # Handlers for Charm Events
83 # ---------------------------------------------------------------------------
85 def _on_config_changed(self
, _
) -> None:
86 """Handler for the config-changed event."""
88 self
._validate
_config
()
89 self
._check
_relations
()
90 # Check if the container is ready.
91 # Eventually it will become ready after the first pebble-ready event.
92 check_container_ready(self
.container
)
94 if not self
.debug_mode
.started
:
95 self
._configure
_service
(self
.container
)
97 self
._on
_update
_status
()
98 except CharmError
as e
:
99 logger
.debug(e
.message
)
100 self
.unit
.status
= e
.status
102 def _on_update_status(self
, _
=None) -> None:
103 """Handler for the update-status event."""
105 self
._validate
_config
()
106 self
._check
_relations
()
107 check_container_ready(self
.container
)
108 if self
.debug_mode
.started
:
110 check_service_active(self
.container
, self
.service_name
)
111 self
.unit
.status
= ActiveStatus()
112 except CharmError
as e
:
113 logger
.debug(e
.message
)
114 self
.unit
.status
= e
.status
116 def _on_required_relation_broken(self
, _
) -> None:
117 """Handler for the kafka-broken event."""
118 # Check Pebble has started in the container
120 check_container_ready(self
.container
)
121 check_service_active(self
.container
, self
.service_name
)
122 self
.container
.stop(self
.container_name
)
125 self
._on
_update
_status
()
127 def _on_get_debug_mode_information_action(self
, event
: ActionEvent
) -> None:
128 """Handler for the get-debug-mode-information action event."""
129 if not self
.debug_mode
.started
:
130 event
.fail("debug-mode has not started. Hint: juju config pol debug-mode=true")
133 debug_info
= {"command": self
.debug_mode
.command
, "password": self
.debug_mode
.password
}
134 event
.set_results(debug_info
)
136 # ---------------------------------------------------------------------------
137 # Validation and configuration and more
138 # ---------------------------------------------------------------------------
140 def _observe_charm_events(self
) -> None:
141 event_handler_mapping
= {
142 # Core lifecycle events
143 self
.on
.pol_pebble_ready
: self
._on
_config
_changed
,
144 self
.on
.config_changed
: self
._on
_config
_changed
,
145 self
.on
.update_status
: self
._on
_update
_status
,
147 self
.on
.kafka_available
: self
._on
_config
_changed
,
148 self
.on
["kafka"].relation_broken
: self
._on
_required
_relation
_broken
,
149 self
.on
["mysql"].relation_changed
: self
._on
_config
_changed
,
150 self
.on
["mysql"].relation_broken
: self
._on
_config
_changed
,
151 self
.mongodb_client
.on
.database_created
: self
._on
_config
_changed
,
152 self
.on
["mongodb"].relation_broken
: self
._on
_required
_relation
_broken
,
154 self
.on
.get_debug_mode_information_action
: self
._on
_get
_debug
_mode
_information
_action
,
157 for event
, handler
in event_handler_mapping
.items():
158 self
.framework
.observe(event
, handler
)
160 def _is_database_available(self
) -> bool:
162 return self
.mongodb_client
.is_resource_created()
166 def _validate_config(self
) -> None:
167 """Validate charm configuration.
170 CharmError: if charm configuration is invalid.
172 logger
.debug("validating charm config")
174 def _check_relations(self
) -> None:
175 """Validate charm relations.
178 CharmError: if charm configuration is invalid.
180 logger
.debug("check for missing relations")
181 missing_relations
= []
183 if not self
.kafka
.host
or not self
.kafka
.port
:
184 missing_relations
.append("kafka")
185 if not self
._is
_database
_available
():
186 missing_relations
.append("mongodb")
187 if not self
.config
.get("mysql-uri") and self
.mysql_client
.is_missing_data_in_unit():
188 missing_relations
.append("mysql")
190 if missing_relations
:
191 relations_str
= ", ".join(missing_relations
)
192 one_relation_missing
= len(missing_relations
) == 1
193 error_msg
= f
'need {relations_str} relation{"" if one_relation_missing else "s"}'
194 logger
.warning(error_msg
)
195 raise CharmError(error_msg
)
197 def _configure_service(self
, container
: Container
) -> None:
198 """Add Pebble layer with the pol service."""
199 logger
.debug(f
"configuring {self.app.name} service")
200 container
.add_layer("pol", self
._get
_layer
(), combine
=True)
203 def _get_layer(self
) -> Dict
[str, Any
]:
204 """Get layer for Pebble."""
206 "summary": "pol layer",
207 "description": "pebble config layer for pol",
210 "override": "replace",
211 "summary": "pol service",
212 "command": "/bin/bash scripts/start.sh",
213 "startup": "enabled",
217 # General configuration
218 "OSMPOL_GLOBAL_LOGLEVEL": self
.config
["log-level"],
219 # Kafka configuration
220 "OSMPOL_MESSAGE_HOST": self
.kafka
.host
,
221 "OSMPOL_MESSAGE_PORT": self
.kafka
.port
,
222 "OSMPOL_MESSAGE_DRIVER": "kafka",
223 # Database Mongodb configuration
224 "OSMPOL_DATABASE_DRIVER": "mongo",
225 "OSMPOL_DATABASE_URI": self
._get
_mongodb
_uri
(),
226 # Database MySQL configuration
227 "OSMPOL_SQL_DATABASE_URI": self
._get
_mysql
_uri
(),
233 def _get_mysql_uri(self
):
234 return self
.config
.get("mysql-uri") or self
.mysql_client
.get_root_uri("pol")
236 def _get_mongodb_uri(self
):
237 return list(self
.mongodb_client
.fetch_relation_data().values())[0]["uris"]
240 if __name__
== "__main__": # pragma: no cover