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
24 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_ip_network(network
: str) -> bool:
32 """Validate IP network.
35 network (str): IP network range.
38 bool: True if valid, false otherwise.
51 def _validate_data(config_data
: Dict
[str, Any
], relation_data
: Dict
[str, Any
]) -> bool:
52 """Validates passed information.
55 config_data (Dict[str, Any]): configuration information.
56 relation_data (Dict[str, Any]): relation information
59 ValueError: when config and/or relation data is not valid.
62 "site_url": lambda value
, _
: isinstance(value
, str)
65 "ingress_whitelist_source_range": lambda value
, _
: _validate_ip_network(value
),
66 "tls_secret_name": lambda value
, _
: isinstance(value
, str)
70 relation_validators
= {
71 "kafka_host": lambda value
, _
: isinstance(value
, str) and len(value
) > 0,
72 "kafka_port": lambda value
, _
: isinstance(value
, str)
78 for key
, validator
in config_validators
.items():
79 valid
= validator(config_data
.get(key
), config_data
)
84 for key
, validator
in relation_validators
.items():
85 valid
= validator(relation_data
.get(key
), relation_data
)
91 raise ValueError("Errors found in: {}".format(", ".join(problems
)))
96 def _make_pod_ports(port
: int) -> List
[Dict
[str, Any
]]:
97 """Generate pod ports details.
100 port (int): port to expose.
103 List[Dict[str, Any]]: pod port details.
106 {"name": "prometheus-kafka-exporter", "containerPort": port
, "protocol": "TCP"}
110 def _make_pod_envconfig(
111 config
: Dict
[str, Any
], relation_state
: Dict
[str, Any
]
113 """Generate pod environment configuration.
116 config (Dict[str, Any]): configuration information.
117 relation_state (Dict[str, Any]): relation state information.
120 Dict[str, Any]: pod environment configuration.
127 def _make_pod_ingress_resources(
128 config
: Dict
[str, Any
], app_name
: str, port
: int
129 ) -> List
[Dict
[str, Any
]]:
130 """Generate pod ingress resources.
133 config (Dict[str, Any]): configuration information.
134 app_name (str): application name.
135 port (int): port to expose.
138 List[Dict[str, Any]]: pod ingress resources.
140 site_url
= config
.get("site_url")
145 parsed
= urlparse(site_url
)
147 if not parsed
.scheme
.startswith("http"):
150 ingress_whitelist_source_range
= config
["ingress_whitelist_source_range"]
154 if ingress_whitelist_source_range
:
156 "nginx.ingress.kubernetes.io/whitelist-source-range"
157 ] = ingress_whitelist_source_range
159 ingress_spec_tls
= None
161 if parsed
.scheme
== "https":
162 ingress_spec_tls
= [{"hosts": [parsed
.hostname
]}]
163 tls_secret_name
= config
["tls_secret_name"]
165 ingress_spec_tls
[0]["secretName"] = tls_secret_name
167 annotations
["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
170 "name": "{}-ingress".format(app_name
),
171 "annotations": annotations
,
175 "host": parsed
.hostname
,
181 "serviceName": app_name
,
192 ingress
["spec"]["tls"] = ingress_spec_tls
197 def _make_readiness_probe(port
: int) -> Dict
[str, Any
]:
198 """Generate readiness probe.
201 port (int): service port.
204 Dict[str, Any]: readiness probe.
208 "path": "/api/health",
211 "initialDelaySeconds": 10,
214 "successThreshold": 1,
215 "failureThreshold": 3,
219 def _make_liveness_probe(port
: int) -> Dict
[str, Any
]:
220 """Generate liveness probe.
223 port (int): service port.
226 Dict[str, Any]: liveness probe.
230 "path": "/api/health",
233 "initialDelaySeconds": 60,
234 "timeoutSeconds": 30,
235 "failureThreshold": 10,
239 def _make_pod_command(relation
: Dict
[str, Any
]) -> List
[str]:
240 """Generate the startup command.
243 relation (Dict[str, Any]): Relation information.
246 List[str]: command to startup the process.
250 "--kafka.server={}:{}".format(
251 relation
.get("kafka_host"), relation
.get("kafka_port")
259 image_info
: Dict
[str, str],
260 config
: Dict
[str, Any
],
261 relation_state
: Dict
[str, Any
],
262 app_name
: str = "prometheus-kafka-exporter",
265 """Generate the pod spec information.
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.
276 Dict[str, Any]: Pod spec dictionary for the charm.
281 _validate_data(config
, relation_state
)
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
)
295 "imageDetails": image_info
,
296 "imagePullPolicy": "Always",
298 "envConfig": env_config
,
301 "readinessProbe": readiness_probe
,
302 "livenessProbe": liveness_probe
,
306 "kubernetesResources": {
307 "ingressResources": ingress_resources
or [],