Moving exporter charms to use opslib
[osm/devops.git] / installers / charm / mongodb-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 "mongodb_connection_string": lambda value, _: (
75 isinstance(value, str) and value.startswith("mongodb://")
76 )
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 [
108 {
109 "name": "mongo-exporter",
110 "containerPort": port,
111 "protocol": "TCP",
112 }
113 ]
114
115
116 def _make_pod_envconfig(
117 config: Dict[str, Any], relation_state: Dict[str, Any]
118 ) -> Dict[str, Any]:
119 """Generate pod environment configuration.
120
121 Args:
122 config (Dict[str, Any]): configuration information.
123 relation_state (Dict[str, Any]): relation state information.
124
125 Returns:
126 Dict[str, Any]: pod environment configuration.
127 """
128 parsed = urlparse(relation_state.get("mongodb_connection_string"))
129
130 envconfig = {
131 "MONGODB_URI": f"mongodb://{parsed.netloc.split(',')[0]}{parsed.path}",
132 }
133
134 if parsed.query:
135 envconfig["MONGODB_URI"] += f"?{parsed.query}"
136
137 return envconfig
138
139
140 def _make_pod_ingress_resources(
141 config: Dict[str, Any], app_name: str, port: int
142 ) -> List[Dict[str, Any]]:
143 """Generate pod ingress resources.
144
145 Args:
146 config (Dict[str, Any]): configuration information.
147 app_name (str): application name.
148 port (int): port to expose.
149
150 Returns:
151 List[Dict[str, Any]]: pod ingress resources.
152 """
153 site_url = config.get("site_url")
154
155 if not site_url:
156 return
157
158 parsed = urlparse(site_url)
159
160 if not parsed.scheme.startswith("http"):
161 return
162
163 ingress_whitelist_source_range = config["ingress_whitelist_source_range"]
164 cluster_issuer = config["cluster_issuer"]
165
166 annotations = {}
167
168 if ingress_whitelist_source_range:
169 annotations[
170 "nginx.ingress.kubernetes.io/whitelist-source-range"
171 ] = ingress_whitelist_source_range
172
173 if cluster_issuer:
174 annotations["cert-manager.io/cluster-issuer"] = cluster_issuer
175
176 ingress_spec_tls = None
177
178 if parsed.scheme == "https":
179 ingress_spec_tls = [{"hosts": [parsed.hostname]}]
180 tls_secret_name = config["tls_secret_name"]
181 if tls_secret_name:
182 ingress_spec_tls[0]["secretName"] = tls_secret_name
183 else:
184 annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
185
186 ingress = {
187 "name": "{}-ingress".format(app_name),
188 "annotations": annotations,
189 "spec": {
190 "rules": [
191 {
192 "host": parsed.hostname,
193 "http": {
194 "paths": [
195 {
196 "path": "/",
197 "backend": {
198 "serviceName": app_name,
199 "servicePort": port,
200 },
201 }
202 ]
203 },
204 }
205 ]
206 },
207 }
208 if ingress_spec_tls:
209 ingress["spec"]["tls"] = ingress_spec_tls
210
211 return [ingress]
212
213
214 def _make_readiness_probe(port: int) -> Dict[str, Any]:
215 """Generate readiness probe.
216
217 Args:
218 port (int): service port.
219
220 Returns:
221 Dict[str, Any]: readiness probe.
222 """
223 return {
224 "httpGet": {
225 "path": "/api/health",
226 "port": port,
227 },
228 "initialDelaySeconds": 10,
229 "periodSeconds": 10,
230 "timeoutSeconds": 5,
231 "successThreshold": 1,
232 "failureThreshold": 3,
233 }
234
235
236 def _make_liveness_probe(port: int) -> Dict[str, Any]:
237 """Generate liveness probe.
238
239 Args:
240 port (int): service port.
241
242 Returns:
243 Dict[str, Any]: liveness probe.
244 """
245 return {
246 "httpGet": {
247 "path": "/api/health",
248 "port": port,
249 },
250 "initialDelaySeconds": 60,
251 "timeoutSeconds": 30,
252 "failureThreshold": 10,
253 }
254
255
256 def make_pod_spec(
257 image_info: Dict[str, str],
258 config: Dict[str, Any],
259 relation_state: Dict[str, Any],
260 app_name: str = "mongodb-exporter",
261 port: int = 9216,
262 ) -> Dict[str, Any]:
263 """Generate the pod spec information.
264
265 Args:
266 image_info (Dict[str, str]): Object provided by
267 OCIImageResource("image").fetch().
268 config (Dict[str, Any]): Configuration information.
269 relation_state (Dict[str, Any]): Relation state information.
270 app_name (str, optional): Application name. Defaults to "ro".
271 port (int, optional): Port for the container. Defaults to 9090.
272
273 Returns:
274 Dict[str, Any]: Pod spec dictionary for the charm.
275 """
276 if not image_info:
277 return None
278
279 _validate_data(config, relation_state)
280
281 ports = _make_pod_ports(port)
282 env_config = _make_pod_envconfig(config, relation_state)
283 readiness_probe = _make_readiness_probe(port)
284 liveness_probe = _make_liveness_probe(port)
285 ingress_resources = _make_pod_ingress_resources(config, app_name, port)
286
287 return {
288 "version": 3,
289 "containers": [
290 {
291 "name": app_name,
292 "imageDetails": image_info,
293 "imagePullPolicy": "Always",
294 "ports": ports,
295 "envConfig": env_config,
296 "kubernetes": {
297 "readinessProbe": readiness_probe,
298 "livenessProbe": liveness_probe,
299 },
300 }
301 ],
302 "kubernetesResources": {
303 "ingressResources": ingress_resources or [],
304 },
305 }