Refactoring Prometheus Charm to use Operator Framework
[osm/devops.git] / installers / charm / prometheus / 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_max_file_size(max_file_size: int, site_url: str) -> bool:
32 """Validate max_file_size.
33
34 Args:
35 max_file_size (int): maximum file size allowed.
36 site_url (str): endpoint url.
37
38 Returns:
39 bool: True if valid, false otherwise.
40 """
41 if not site_url:
42 return True
43
44 parsed = urlparse(site_url)
45
46 if not parsed.scheme.startswith("http"):
47 return True
48
49 if max_file_size is None:
50 return False
51
52 return max_file_size >= 0
53
54
55 def _validate_ip_network(network: str) -> bool:
56 """Validate IP network.
57
58 Args:
59 network (str): IP network range.
60
61 Returns:
62 bool: True if valid, false otherwise.
63 """
64 if not network:
65 return True
66
67 try:
68 ip_network(network)
69 except ValueError:
70 return False
71
72 return True
73
74
75 def _validate_data(config_data: Dict[str, Any], relation_data: Dict[str, Any]) -> bool:
76 """Validates passed information.
77
78 Args:
79 config_data (Dict[str, Any]): configuration information.
80 relation_data (Dict[str, Any]): relation information
81
82 Raises:
83 ValueError: when config and/or relation data is not valid.
84 """
85 config_validators = {
86 "web_subpath": lambda value, _: isinstance(value, str) and len(value) > 0,
87 "default_target": lambda value, _: isinstance(value, str),
88 "site_url": lambda value, _: isinstance(value, str)
89 if value is not None
90 else True,
91 "max_file_size": lambda value, values: _validate_max_file_size(
92 value, values.get("site_url")
93 ),
94 "ingress_whitelist_source_range": lambda value, _: _validate_ip_network(value),
95 "tls_secret_name": lambda value, _: isinstance(value, str)
96 if value is not None
97 else True,
98 }
99 relation_validators = {}
100 problems = []
101
102 for key, validator in config_validators.items():
103 valid = validator(config_data.get(key), config_data)
104
105 if not valid:
106 problems.append(key)
107
108 for key, validator in relation_validators.items():
109 valid = validator(relation_data.get(key), relation_data)
110
111 if not valid:
112 problems.append(key)
113
114 if len(problems) > 0:
115 raise ValueError("Errors found in: {}".format(", ".join(problems)))
116
117 return True
118
119
120 def _make_pod_ports(port: int) -> List[Dict[str, Any]]:
121 """Generate pod ports details.
122
123 Args:
124 port (int): port to expose.
125
126 Returns:
127 List[Dict[str, Any]]: pod port details.
128 """
129 return [{"name": "prometheus", "containerPort": port, "protocol": "TCP"}]
130
131
132 def _make_pod_envconfig(
133 config: Dict[str, Any], relation_state: Dict[str, Any]
134 ) -> Dict[str, Any]:
135 """Generate pod environment configuration.
136
137 Args:
138 config (Dict[str, Any]): configuration information.
139 relation_state (Dict[str, Any]): relation state information.
140
141 Returns:
142 Dict[str, Any]: pod environment configuration.
143 """
144 envconfig = {}
145
146 return envconfig
147
148
149 def _make_pod_ingress_resources(
150 config: Dict[str, Any], app_name: str, port: int
151 ) -> List[Dict[str, Any]]:
152 """Generate pod ingress resources.
153
154 Args:
155 config (Dict[str, Any]): configuration information.
156 app_name (str): application name.
157 port (int): port to expose.
158
159 Returns:
160 List[Dict[str, Any]]: pod ingress resources.
161 """
162 site_url = config.get("site_url")
163
164 if not site_url:
165 return
166
167 parsed = urlparse(site_url)
168
169 if not parsed.scheme.startswith("http"):
170 return
171
172 max_file_size = config["max_file_size"]
173 ingress_whitelist_source_range = config["ingress_whitelist_source_range"]
174
175 annotations = {
176 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
177 str(max_file_size) + "m" if max_file_size > 0 else max_file_size
178 ),
179 }
180
181 if ingress_whitelist_source_range:
182 annotations[
183 "nginx.ingress.kubernetes.io/whitelist-source-range"
184 ] = ingress_whitelist_source_range
185
186 ingress_spec_tls = None
187
188 if parsed.scheme == "https":
189 ingress_spec_tls = [{"hosts": [parsed.hostname]}]
190 tls_secret_name = config["tls_secret_name"]
191 if tls_secret_name:
192 ingress_spec_tls[0]["secretName"] = tls_secret_name
193 else:
194 annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
195
196 ingress = {
197 "name": "{}-ingress".format(app_name),
198 "annotations": annotations,
199 "spec": {
200 "rules": [
201 {
202 "host": parsed.hostname,
203 "http": {
204 "paths": [
205 {
206 "path": "/",
207 "backend": {
208 "serviceName": app_name,
209 "servicePort": port,
210 },
211 }
212 ]
213 },
214 }
215 ]
216 },
217 }
218 if ingress_spec_tls:
219 ingress["spec"]["tls"] = ingress_spec_tls
220
221 return [ingress]
222
223
224 def _make_pod_files(config: Dict[str, Any]) -> List[Dict[str, Any]]:
225 """Generating ConfigMap information
226
227 Args:
228 config (Dict[str, Any]): configuration information.
229
230 Returns:
231 List[Dict[str, Any]]: ConfigMap information.
232 """
233 files = [
234 {
235 "name": "config",
236 "mountPath": "/etc/prometheus",
237 "files": [
238 {
239 "path": "prometheus.yml",
240 "content": (
241 "global:"
242 " scrape_interval: 15s"
243 " evaluation_interval: 15s"
244 "alerting:"
245 " alertmanagers:"
246 " - static_configs:"
247 " - targets:"
248 "rule_files:"
249 "scrape_configs:"
250 " - job_name: 'prometheus'"
251 " static_configs:"
252 " - targets: [{}]".format(config["default_target"])
253 ),
254 }
255 ],
256 }
257 ]
258
259 return files
260
261
262 def _make_readiness_probe(port: int) -> Dict[str, Any]:
263 """Generate readiness probe.
264
265 Args:
266 port (int): service port.
267
268 Returns:
269 Dict[str, Any]: readiness probe.
270 """
271 return {
272 "httpGet": {
273 "path": "/-/ready",
274 "port": port,
275 },
276 "initialDelaySeconds": 10,
277 "timeoutSeconds": 30,
278 }
279
280
281 def _make_liveness_probe(port: int) -> Dict[str, Any]:
282 """Generate liveness probe.
283
284 Args:
285 port (int): service port.
286
287 Returns:
288 Dict[str, Any]: liveness probe.
289 """
290 return {
291 "httpGet": {
292 "path": "/-/healthy",
293 "port": port,
294 },
295 "initialDelaySeconds": 30,
296 "periodSeconds": 30,
297 }
298
299
300 def _make_pod_command(config: Dict[str, Any], port: int) -> List[str]:
301 """Generate the startup command.
302
303 Args:
304 config (Dict[str, Any]): Configuration information.
305 port (int): port.
306
307 Returns:
308 List[str]: command to startup the process.
309 """
310 return [
311 "sh",
312 "-c",
313 "/bin/prometheus",
314 "--config.file=/etc/prometheus/prometheus.yml",
315 "--storage.tsdb.path=/prometheus",
316 "--web.console.libraries=/usr/share/prometheus/console_libraries",
317 "--web.console.templates=/usr/share/prometheus/consoles",
318 "--web.route-prefix={}".format(config.get("web_subpath")),
319 "--web.external-url=http://localhost:{}{}".format(
320 port, config.get("web_subpath")
321 ),
322 ]
323
324
325 def make_pod_spec(
326 image_info: Dict[str, str],
327 config: Dict[str, Any],
328 relation_state: Dict[str, Any],
329 app_name: str = "prometheus",
330 port: int = 9090,
331 ) -> Dict[str, Any]:
332 """Generate the pod spec information.
333
334 Args:
335 image_info (Dict[str, str]): Object provided by
336 OCIImageResource("image").fetch().
337 config (Dict[str, Any]): Configuration information.
338 relation_state (Dict[str, Any]): Relation state information.
339 app_name (str, optional): Application name. Defaults to "ro".
340 port (int, optional): Port for the container. Defaults to 9090.
341
342 Returns:
343 Dict[str, Any]: Pod spec dictionary for the charm.
344 """
345 if not image_info:
346 return None
347
348 _validate_data(config, relation_state)
349
350 ports = _make_pod_ports(port)
351 env_config = _make_pod_envconfig(config, relation_state)
352 files = _make_pod_files(config)
353 readiness_probe = _make_readiness_probe(port)
354 liveness_probe = _make_liveness_probe(port)
355 ingress_resources = _make_pod_ingress_resources(config, app_name, port)
356 command = _make_pod_command(config, port)
357
358 return {
359 "version": 3,
360 "containers": [
361 {
362 "name": app_name,
363 "imageDetails": image_info,
364 "imagePullPolicy": "Always",
365 "ports": ports,
366 "envConfig": env_config,
367 "volumeConfig": files,
368 "command": command,
369 "kubernetes": {
370 "readinessProbe": readiness_probe,
371 "livenessProbe": liveness_probe,
372 },
373 }
374 ],
375 "kubernetesResources": {
376 "ingressResources": ingress_resources or [],
377 },
378 }