Add osm-nbi sidecar charm
[osm/devops.git] / installers / charm / osm-nbi / lib / charms / kafka_k8s / v0 / kafka.py
1 # Copyright 2022 Canonical Ltd.
2 # See LICENSE file for licensing details.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain 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,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Kafka library.
18
19 This [library](https://juju.is/docs/sdk/libraries) implements both sides of the
20 `kafka` [interface](https://juju.is/docs/sdk/relations).
21
22 The *provider* side of this interface is implemented by the
23 [kafka-k8s Charmed Operator](https://charmhub.io/kafka-k8s).
24
25 Any Charmed Operator that *requires* Kafka for providing its
26 service should implement the *requirer* side of this interface.
27
28 In a nutshell using this library to implement a Charmed Operator *requiring*
29 Kafka would look like
30
31 ```
32 $ charmcraft fetch-lib charms.kafka_k8s.v0.kafka
33 ```
34
35 `metadata.yaml`:
36
37 ```
38 requires:
39 kafka:
40 interface: kafka
41 limit: 1
42 ```
43
44 `src/charm.py`:
45
46 ```
47 from charms.kafka_k8s.v0.kafka import KafkaEvents, KafkaRequires
48 from ops.charm import CharmBase
49
50
51 class MyCharm(CharmBase):
52
53 on = KafkaEvents()
54
55 def __init__(self, *args):
56 super().__init__(*args)
57 self.kafka = KafkaRequires(self)
58 self.framework.observe(
59 self.on.kafka_available,
60 self._on_kafka_available,
61 )
62 self.framework.observe(
63 self.on["kafka"].relation_broken,
64 self._on_kafka_broken,
65 )
66
67 def _on_kafka_available(self, event):
68 # Get Kafka host and port
69 host: str = self.kafka.host
70 port: int = self.kafka.port
71 # host => "kafka-k8s"
72 # port => 9092
73
74 def _on_kafka_broken(self, event):
75 # Stop service
76 # ...
77 self.unit.status = BlockedStatus("need kafka relation")
78 ```
79
80 You can file bugs
81 [here](https://github.com/charmed-osm/kafka-k8s-operator/issues)!
82 """
83
84 from typing import Optional
85
86 from ops.charm import CharmBase, CharmEvents
87 from ops.framework import EventBase, EventSource, Object
88
89 # The unique Charmhub library identifier, never change it
90 from ops.model import Relation
91
92 LIBID = "eacc8c85082347c9aae740e0220b8376"
93
94 # Increment this major API version when introducing breaking changes
95 LIBAPI = 0
96
97 # Increment this PATCH version before using `charmcraft publish-lib` or reset
98 # to 0 if you are raising the major API version
99 LIBPATCH = 4
100
101
102 KAFKA_HOST_APP_KEY = "host"
103 KAFKA_PORT_APP_KEY = "port"
104
105
106 class _KafkaAvailableEvent(EventBase):
107 """Event emitted when Kafka is available."""
108
109
110 class KafkaEvents(CharmEvents):
111 """Kafka events.
112
113 This class defines the events that Kafka can emit.
114
115 Events:
116 kafka_available (_KafkaAvailableEvent)
117 """
118
119 kafka_available = EventSource(_KafkaAvailableEvent)
120
121
122 class KafkaRequires(Object):
123 """Requires-side of the Kafka relation."""
124
125 def __init__(self, charm: CharmBase, endpoint_name: str = "kafka") -> None:
126 super().__init__(charm, endpoint_name)
127 self.charm = charm
128 self._endpoint_name = endpoint_name
129
130 # Observe relation events
131 event_observe_mapping = {
132 charm.on[self._endpoint_name].relation_changed: self._on_relation_changed,
133 }
134 for event, observer in event_observe_mapping.items():
135 self.framework.observe(event, observer)
136
137 def _on_relation_changed(self, event) -> None:
138 if event.relation.app and all(
139 key in event.relation.data[event.relation.app]
140 for key in (KAFKA_HOST_APP_KEY, KAFKA_PORT_APP_KEY)
141 ):
142 self.charm.on.kafka_available.emit()
143
144 @property
145 def host(self) -> str:
146 """Get kafka hostname."""
147 relation: Relation = self.model.get_relation(self._endpoint_name)
148 return (
149 relation.data[relation.app].get(KAFKA_HOST_APP_KEY)
150 if relation and relation.app
151 else None
152 )
153
154 @property
155 def port(self) -> int:
156 """Get kafka port number."""
157 relation: Relation = self.model.get_relation(self._endpoint_name)
158 return (
159 int(relation.data[relation.app].get(KAFKA_PORT_APP_KEY))
160 if relation and relation.app
161 else None
162 )
163
164
165 class KafkaProvides(Object):
166 """Provides-side of the Kafka relation."""
167
168 def __init__(self, charm: CharmBase, endpoint_name: str = "kafka") -> None:
169 super().__init__(charm, endpoint_name)
170 self._endpoint_name = endpoint_name
171
172 def set_host_info(self, host: str, port: int, relation: Optional[Relation] = None) -> None:
173 """Set Kafka host and port.
174
175 This function writes in the application data of the relation, therefore,
176 only the unit leader can call it.
177
178 Args:
179 host (str): Kafka hostname or IP address.
180 port (int): Kafka port.
181 relation (Optional[Relation]): Relation to update.
182 If not specified, all relations will be updated.
183
184 Raises:
185 Exception: if a non-leader unit calls this function.
186 """
187 if not self.model.unit.is_leader():
188 raise Exception("only the leader set host information.")
189
190 if relation:
191 self._update_relation_data(host, port, relation)
192 return
193
194 for relation in self.model.relations[self._endpoint_name]:
195 self._update_relation_data(host, port, relation)
196
197 def _update_relation_data(self, host: str, port: int, relation: Relation) -> None:
198 """Update data in relation if needed."""
199 relation.data[self.model.app][KAFKA_HOST_APP_KEY] = host
200 relation.data[self.model.app][KAFKA_PORT_APP_KEY] = str(port)