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)
99 relation_validators
= {}
102 for key
, validator
in config_validators
.items():
103 valid
= validator(config_data
.get(key
), config_data
)
108 for key
, validator
in relation_validators
.items():
109 valid
= validator(relation_data
.get(key
), relation_data
)
114 if len(problems
) > 0:
115 raise ValueError("Errors found in: {}".format(", ".join(problems
)))
120 def _make_pod_ports(port
: int) -> List
[Dict
[str, Any
]]:
121 """Generate pod ports details.
124 port (int): port to expose.
127 List[Dict[str, Any]]: pod port details.
129 return [{"name": "prometheus", "containerPort": port
, "protocol": "TCP"}]
132 def _make_pod_envconfig(
133 config
: Dict
[str, Any
], relation_state
: Dict
[str, Any
]
135 """Generate pod environment configuration.
138 config (Dict[str, Any]): configuration information.
139 relation_state (Dict[str, Any]): relation state information.
142 Dict[str, Any]: pod environment configuration.
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.
155 config (Dict[str, Any]): configuration information.
156 app_name (str): application name.
157 port (int): port to expose.
160 List[Dict[str, Any]]: pod ingress resources.
162 site_url
= config
.get("site_url")
167 parsed
= urlparse(site_url
)
169 if not parsed
.scheme
.startswith("http"):
172 max_file_size
= config
["max_file_size"]
173 ingress_whitelist_source_range
= config
["ingress_whitelist_source_range"]
176 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
177 str(max_file_size
) + "m" if max_file_size
> 0 else max_file_size
181 if ingress_whitelist_source_range
:
183 "nginx.ingress.kubernetes.io/whitelist-source-range"
184 ] = ingress_whitelist_source_range
186 ingress_spec_tls
= None
188 if parsed
.scheme
== "https":
189 ingress_spec_tls
= [{"hosts": [parsed
.hostname
]}]
190 tls_secret_name
= config
["tls_secret_name"]
192 ingress_spec_tls
[0]["secretName"] = tls_secret_name
194 annotations
["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
197 "name": "{}-ingress".format(app_name
),
198 "annotations": annotations
,
202 "host": parsed
.hostname
,
208 "serviceName": app_name
,
219 ingress
["spec"]["tls"] = ingress_spec_tls
224 def _make_pod_files(config
: Dict
[str, Any
]) -> List
[Dict
[str, Any
]]:
225 """Generating ConfigMap information
228 config (Dict[str, Any]): configuration information.
231 List[Dict[str, Any]]: ConfigMap information.
236 "mountPath": "/etc/prometheus",
239 "path": "prometheus.yml",
242 " scrape_interval: 15s\n"
243 " evaluation_interval: 15s\n"
246 " - static_configs:\n"
250 " - job_name: 'prometheus'\n"
252 " - targets: [{}]\n".format(config
["default_target"])
262 def _make_readiness_probe(port
: int) -> Dict
[str, Any
]:
263 """Generate readiness probe.
266 port (int): service port.
269 Dict[str, Any]: readiness probe.
276 "initialDelaySeconds": 10,
277 "timeoutSeconds": 30,
281 def _make_liveness_probe(port
: int) -> Dict
[str, Any
]:
282 """Generate liveness probe.
285 port (int): service port.
288 Dict[str, Any]: liveness probe.
292 "path": "/-/healthy",
295 "initialDelaySeconds": 30,
300 def _make_pod_command(config
: Dict
[str, Any
], port
: int) -> List
[str]:
301 """Generate the startup command.
304 config (Dict[str, Any]): Configuration information.
308 List[str]: command to startup the process.
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")
326 image_info
: Dict
[str, str],
327 config
: Dict
[str, Any
],
328 relation_state
: Dict
[str, Any
],
329 app_name
: str = "prometheus",
332 """Generate the pod spec information.
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.
343 Dict[str, Any]: Pod spec dictionary for the charm.
348 _validate_data(config
, relation_state
)
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
)
363 "imageDetails": image_info
,
364 "imagePullPolicy": "Always",
366 "envConfig": env_config
,
367 "volumeConfig": files
,
370 "readinessProbe": readiness_probe
,
371 "livenessProbe": liveness_probe
,
375 "kubernetesResources": {
376 "ingressResources": ingress_resources
or [],