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