Moving exporter charms to use opslib
[osm/devops.git] / installers / charm / mysqld-exporter / src / pod_spec.py
1 #!/usr/bin/env python3
2 # Copyright 2021 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 from ipaddress import ip_network
24 import logging
25 from typing import Any, Dict, List
26 from urllib.parse import urlparse
27
28 logger = logging.getLogger(__name__)
29
30
31 def _validate_ip_network(network: str) -> bool:
32 """Validate IP network.
33
34 Args:
35 network (str): IP network range.
36
37 Returns:
38 bool: True if valid, false otherwise.
39 """
40 if not network:
41 return True
42
43 try:
44 ip_network(network)
45 except ValueError:
46 return False
47
48 return True
49
50
51 def _validate_data(config_data: Dict[str, Any], relation_data: Dict[str, Any]) -> bool:
52 """Validates passed information.
53
54 Args:
55 config_data (Dict[str, Any]): configuration information.
56 relation_data (Dict[str, Any]): relation information
57
58 Raises:
59 ValueError: when config and/or relation data is not valid.
60 """
61 config_validators = {
62 "site_url": lambda value, _: isinstance(value, str)
63 if value is not None
64 else True,
65 "cluster_issuer": lambda value, _: isinstance(value, str)
66 if value is not None
67 else True,
68 "ingress_whitelist_source_range": lambda value, _: _validate_ip_network(value),
69 "tls_secret_name": lambda value, _: isinstance(value, str)
70 if value is not None
71 else True,
72 }
73 relation_validators = {
74 "mysql_host": lambda value, _: isinstance(value, str) and len(value) > 0,
75 "mysql_port": lambda value, _: isinstance(value, str) and int(value) > 0,
76 "mysql_user": lambda value, _: isinstance(value, str) and len(value) > 0,
77 "mysql_password": lambda value, _: isinstance(value, str) and len(value) > 0,
78 "mysql_root_password": lambda value, _: isinstance(value, str)
79 and len(value) > 0,
80 }
81 problems = []
82
83 for key, validator in config_validators.items():
84 valid = validator(config_data.get(key), config_data)
85
86 if not valid:
87 problems.append(key)
88
89 for key, validator in relation_validators.items():
90 valid = validator(relation_data.get(key), relation_data)
91
92 if not valid:
93 problems.append(key)
94
95 if len(problems) > 0:
96 raise ValueError("Errors found in: {}".format(", ".join(problems)))
97
98 return True
99
100
101 def _make_pod_ports(port: int) -> List[Dict[str, Any]]:
102 """Generate pod ports details.
103
104 Args:
105 port (int): port to expose.
106
107 Returns:
108 List[Dict[str, Any]]: pod port details.
109 """
110 return [{"name": "mysqld-exporter", "containerPort": port, "protocol": "TCP"}]
111
112
113 def _make_pod_envconfig(
114 config: Dict[str, Any], relation_state: Dict[str, Any]
115 ) -> Dict[str, Any]:
116 """Generate pod environment configuration.
117
118 Args:
119 config (Dict[str, Any]): configuration information.
120 relation_state (Dict[str, Any]): relation state information.
121
122 Returns:
123 Dict[str, Any]: pod environment configuration.
124 """
125 envconfig = {
126 "DATA_SOURCE_NAME": "root:{mysql_root_password}@({mysql_host}:{mysql_port})/".format(
127 **relation_state
128 )
129 }
130
131 return envconfig
132
133
134 def _make_pod_ingress_resources(
135 config: Dict[str, Any], app_name: str, port: int
136 ) -> List[Dict[str, Any]]:
137 """Generate pod ingress resources.
138
139 Args:
140 config (Dict[str, Any]): configuration information.
141 app_name (str): application name.
142 port (int): port to expose.
143
144 Returns:
145 List[Dict[str, Any]]: pod ingress resources.
146 """
147 site_url = config.get("site_url")
148
149 if not site_url:
150 return
151
152 parsed = urlparse(site_url)
153
154 if not parsed.scheme.startswith("http"):
155 return
156
157 ingress_whitelist_source_range = config["ingress_whitelist_source_range"]
158 cluster_issuer = config["cluster_issuer"]
159
160 annotations = {}
161
162 if ingress_whitelist_source_range:
163 annotations[
164 "nginx.ingress.kubernetes.io/whitelist-source-range"
165 ] = ingress_whitelist_source_range
166
167 if cluster_issuer:
168 annotations["cert-manager.io/cluster-issuer"] = cluster_issuer
169
170 ingress_spec_tls = None
171
172 if parsed.scheme == "https":
173 ingress_spec_tls = [{"hosts": [parsed.hostname]}]
174 tls_secret_name = config["tls_secret_name"]
175 if tls_secret_name:
176 ingress_spec_tls[0]["secretName"] = tls_secret_name
177 else:
178 annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
179
180 ingress = {
181 "name": "{}-ingress".format(app_name),
182 "annotations": annotations,
183 "spec": {
184 "rules": [
185 {
186 "host": parsed.hostname,
187 "http": {
188 "paths": [
189 {
190 "path": "/",
191 "backend": {
192 "serviceName": app_name,
193 "servicePort": port,
194 },
195 }
196 ]
197 },
198 }
199 ]
200 },
201 }
202 if ingress_spec_tls:
203 ingress["spec"]["tls"] = ingress_spec_tls
204
205 return [ingress]
206
207
208 def _make_readiness_probe(port: int) -> Dict[str, Any]:
209 """Generate readiness probe.
210
211 Args:
212 port (int): service port.
213
214 Returns:
215 Dict[str, Any]: readiness probe.
216 """
217 return {
218 "httpGet": {
219 "path": "/api/health",
220 "port": port,
221 },
222 "initialDelaySeconds": 10,
223 "periodSeconds": 10,
224 "timeoutSeconds": 5,
225 "successThreshold": 1,
226 "failureThreshold": 3,
227 }
228
229
230 def _make_liveness_probe(port: int) -> Dict[str, Any]:
231 """Generate liveness probe.
232
233 Args:
234 port (int): service port.
235
236 Returns:
237 Dict[str, Any]: liveness probe.
238 """
239 return {
240 "httpGet": {
241 "path": "/api/health",
242 "port": port,
243 },
244 "initialDelaySeconds": 60,
245 "timeoutSeconds": 30,
246 "failureThreshold": 10,
247 }
248
249
250 def make_pod_spec(
251 image_info: Dict[str, str],
252 config: Dict[str, Any],
253 relation_state: Dict[str, Any],
254 app_name: str = "mysqld-exporter",
255 port: int = 9104,
256 ) -> Dict[str, Any]:
257 """Generate the pod spec information.
258
259 Args:
260 image_info (Dict[str, str]): Object provided by
261 OCIImageResource("image").fetch().
262 config (Dict[str, Any]): Configuration information.
263 relation_state (Dict[str, Any]): Relation state information.
264 app_name (str, optional): Application name. Defaults to "ro".
265 port (int, optional): Port for the container. Defaults to 9090.
266
267 Returns:
268 Dict[str, Any]: Pod spec dictionary for the charm.
269 """
270 if not image_info:
271 return None
272
273 _validate_data(config, relation_state)
274
275 ports = _make_pod_ports(port)
276 env_config = _make_pod_envconfig(config, relation_state)
277 readiness_probe = _make_readiness_probe(port)
278 liveness_probe = _make_liveness_probe(port)
279 ingress_resources = _make_pod_ingress_resources(config, app_name, port)
280
281 return {
282 "version": 3,
283 "containers": [
284 {
285 "name": app_name,
286 "imageDetails": image_info,
287 "imagePullPolicy": "Always",
288 "ports": ports,
289 "envConfig": env_config,
290 "kubernetes": {
291 "readinessProbe": readiness_probe,
292 "livenessProbe": liveness_probe,
293 },
294 }
295 ],
296 "kubernetesResources": {
297 "ingressResources": ingress_resources or [],
298 },
299 }