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