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