2 # Copyright 2021 Canonical Ltd.
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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
16 # For those usages not covered by the Apache License, Version 2.0 please
17 # contact: legal@canonical.com
19 # To get in touch with the maintainers, please contact:
20 # osm-charmers@lists.launchpad.net
23 from ipaddress
import ip_network
25 from typing
import Any
, Dict
, List
26 from urllib
.parse
import urlparse
28 logger
= logging
.getLogger(__name__
)
31 def _validate_max_file_size(max_file_size
: int, site_url
: str) -> bool:
32 """Validate max_file_size.
35 max_file_size (int): maximum file size allowed.
36 site_url (str): endpoint url.
39 bool: True if valid, false otherwise.
44 parsed
= urlparse(site_url
)
46 if not parsed
.scheme
.startswith("http"):
49 if max_file_size
is None:
52 return max_file_size
>= 0
55 def _validate_ip_network(network
: str) -> bool:
56 """Validate IP network.
59 network (str): IP network range.
62 bool: True if valid, false otherwise.
75 def _validate_data(config_data
: Dict
[str, Any
], relation_data
: Dict
[str, Any
]) -> bool:
76 """Validates passed information.
79 config_data (Dict[str, Any]): configuration information.
80 relation_data (Dict[str, Any]): relation information
83 ValueError: when config and/or relation data is not valid.
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)
91 "max_file_size": lambda value
, values
: _validate_max_file_size(
92 value
, values
.get("site_url")
94 "ingress_whitelist_source_range": lambda value
, _
: _validate_ip_network(value
),
95 "tls_secret_name": lambda value
, _
: isinstance(value
, str)
98 "enable_web_admin_api": lambda value
, _
: isinstance(value
, bool),
100 relation_validators
= {}
103 for key
, validator
in config_validators
.items():
104 valid
= validator(config_data
.get(key
), config_data
)
109 for key
, validator
in relation_validators
.items():
110 valid
= validator(relation_data
.get(key
), relation_data
)
115 if len(problems
) > 0:
116 raise ValueError("Errors found in: {}".format(", ".join(problems
)))
121 def _make_pod_ports(port
: int) -> List
[Dict
[str, Any
]]:
122 """Generate pod ports details.
125 port (int): port to expose.
128 List[Dict[str, Any]]: pod port details.
130 return [{"name": "prometheus", "containerPort": port
, "protocol": "TCP"}]
133 def _make_pod_envconfig(
134 config
: Dict
[str, Any
], relation_state
: Dict
[str, Any
]
136 """Generate pod environment configuration.
139 config (Dict[str, Any]): configuration information.
140 relation_state (Dict[str, Any]): relation state information.
143 Dict[str, Any]: pod environment configuration.
150 def _make_pod_ingress_resources(
151 config
: Dict
[str, Any
], app_name
: str, port
: int
152 ) -> List
[Dict
[str, Any
]]:
153 """Generate pod ingress resources.
156 config (Dict[str, Any]): configuration information.
157 app_name (str): application name.
158 port (int): port to expose.
161 List[Dict[str, Any]]: pod ingress resources.
163 site_url
= config
.get("site_url")
168 parsed
= urlparse(site_url
)
170 if not parsed
.scheme
.startswith("http"):
173 max_file_size
= config
["max_file_size"]
174 ingress_whitelist_source_range
= config
["ingress_whitelist_source_range"]
177 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
178 str(max_file_size
) + "m" if max_file_size
> 0 else max_file_size
182 if ingress_whitelist_source_range
:
184 "nginx.ingress.kubernetes.io/whitelist-source-range"
185 ] = ingress_whitelist_source_range
187 ingress_spec_tls
= None
189 if parsed
.scheme
== "https":
190 ingress_spec_tls
= [{"hosts": [parsed
.hostname
]}]
191 tls_secret_name
= config
["tls_secret_name"]
193 ingress_spec_tls
[0]["secretName"] = tls_secret_name
195 annotations
["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
198 "name": "{}-ingress".format(app_name
),
199 "annotations": annotations
,
203 "host": parsed
.hostname
,
209 "serviceName": app_name
,
220 ingress
["spec"]["tls"] = ingress_spec_tls
225 def _make_pod_files(config
: Dict
[str, Any
]) -> List
[Dict
[str, Any
]]:
226 """Generating ConfigMap information
229 config (Dict[str, Any]): configuration information.
232 List[Dict[str, Any]]: ConfigMap information.
237 "mountPath": "/etc/prometheus",
240 "path": "prometheus.yml",
243 " scrape_interval: 15s\n"
244 " evaluation_interval: 15s\n"
247 " - static_configs:\n"
251 " - job_name: 'prometheus'\n"
253 " - targets: [{}]\n".format(config
["default_target"])
263 def _make_readiness_probe(port
: int) -> Dict
[str, Any
]:
264 """Generate readiness probe.
267 port (int): service port.
270 Dict[str, Any]: readiness probe.
277 "initialDelaySeconds": 10,
278 "timeoutSeconds": 30,
282 def _make_liveness_probe(port
: int) -> Dict
[str, Any
]:
283 """Generate liveness probe.
286 port (int): service port.
289 Dict[str, Any]: liveness probe.
293 "path": "/-/healthy",
296 "initialDelaySeconds": 30,
301 def _make_pod_command(config
: Dict
[str, Any
], port
: int) -> List
[str]:
302 """Generate the startup command.
305 config (Dict[str, Any]): Configuration information.
309 List[str]: command to startup the process.
313 "--config.file=/etc/prometheus/prometheus.yml",
314 "--storage.tsdb.path=/prometheus",
315 "--web.console.libraries=/usr/share/prometheus/console_libraries",
316 "--web.console.templates=/usr/share/prometheus/consoles",
317 "--web.route-prefix={}".format(config
.get("web_subpath")),
318 "--web.external-url=http://localhost:{}{}".format(
319 port
, config
.get("web_subpath")
322 if config
.get("enable_web_admin_api"):
323 command
.append("--web.enable-admin-api")
328 image_info
: Dict
[str, str],
329 config
: Dict
[str, Any
],
330 relation_state
: Dict
[str, Any
],
331 app_name
: str = "prometheus",
334 """Generate the pod spec information.
337 image_info (Dict[str, str]): Object provided by
338 OCIImageResource("image").fetch().
339 config (Dict[str, Any]): Configuration information.
340 relation_state (Dict[str, Any]): Relation state information.
341 app_name (str, optional): Application name. Defaults to "ro".
342 port (int, optional): Port for the container. Defaults to 9090.
345 Dict[str, Any]: Pod spec dictionary for the charm.
350 _validate_data(config
, relation_state
)
352 ports
= _make_pod_ports(port
)
353 env_config
= _make_pod_envconfig(config
, relation_state
)
354 files
= _make_pod_files(config
)
355 readiness_probe
= _make_readiness_probe(port
)
356 liveness_probe
= _make_liveness_probe(port
)
357 ingress_resources
= _make_pod_ingress_resources(config
, app_name
, port
)
358 command
= _make_pod_command(config
, port
)
365 "imageDetails": image_info
,
366 "imagePullPolicy": "Always",
368 "envConfig": env_config
,
369 "volumeConfig": files
,
372 "readinessProbe": readiness_probe
,
373 "livenessProbe": liveness_probe
,
377 "kubernetesResources": {
378 "ingressResources": ingress_resources
or [],