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 "mongodb_connection_string": lambda value
, _
: (
72 isinstance(value
, str) and value
.startswith("mongodb://")
77 for key
, validator
in config_validators
.items():
78 valid
= validator(config_data
.get(key
), config_data
)
83 for key
, validator
in relation_validators
.items():
84 valid
= validator(relation_data
.get(key
), relation_data
)
90 raise ValueError("Errors found in: {}".format(", ".join(problems
)))
95 def _make_pod_ports(port
: int) -> List
[Dict
[str, Any
]]:
96 """Generate pod ports details.
99 port (int): port to expose.
102 List[Dict[str, Any]]: pod port details.
106 "name": "mongo-exporter",
107 "containerPort": port
,
113 def _make_pod_envconfig(
114 config
: Dict
[str, Any
], relation_state
: Dict
[str, Any
]
116 """Generate pod environment configuration.
119 config (Dict[str, Any]): configuration information.
120 relation_state (Dict[str, Any]): relation state information.
123 Dict[str, Any]: pod environment configuration.
125 parsed
= urlparse(relation_state
.get("mongodb_connection_string"))
128 "MONGODB_URI": f
"mongodb://{parsed.netloc.split(',')[0]}{parsed.path}",
132 envconfig
["MONGODB_URI"] += f
"?{parsed.query}"
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.
143 config (Dict[str, Any]): configuration information.
144 app_name (str): application name.
145 port (int): port to expose.
148 List[Dict[str, Any]]: pod ingress resources.
150 site_url
= config
.get("site_url")
155 parsed
= urlparse(site_url
)
157 if not parsed
.scheme
.startswith("http"):
160 ingress_whitelist_source_range
= config
["ingress_whitelist_source_range"]
163 if ingress_whitelist_source_range
:
165 "nginx.ingress.kubernetes.io/whitelist-source-range"
166 ] = ingress_whitelist_source_range
168 ingress_spec_tls
= None
170 if parsed
.scheme
== "https":
171 ingress_spec_tls
= [{"hosts": [parsed
.hostname
]}]
172 tls_secret_name
= config
["tls_secret_name"]
174 ingress_spec_tls
[0]["secretName"] = tls_secret_name
176 annotations
["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
179 "name": "{}-ingress".format(app_name
),
180 "annotations": annotations
,
184 "host": parsed
.hostname
,
190 "serviceName": app_name
,
201 ingress
["spec"]["tls"] = ingress_spec_tls
206 def _make_readiness_probe(port
: int) -> Dict
[str, Any
]:
207 """Generate readiness probe.
210 port (int): service port.
213 Dict[str, Any]: readiness probe.
217 "path": "/api/health",
220 "initialDelaySeconds": 10,
223 "successThreshold": 1,
224 "failureThreshold": 3,
228 def _make_liveness_probe(port
: int) -> Dict
[str, Any
]:
229 """Generate liveness probe.
232 port (int): service port.
235 Dict[str, Any]: liveness probe.
239 "path": "/api/health",
242 "initialDelaySeconds": 60,
243 "timeoutSeconds": 30,
244 "failureThreshold": 10,
249 image_info
: Dict
[str, str],
250 config
: Dict
[str, Any
],
251 relation_state
: Dict
[str, Any
],
252 app_name
: str = "mongodb-exporter",
255 """Generate the pod spec information.
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.
266 Dict[str, Any]: Pod spec dictionary for the charm.
271 _validate_data(config
, relation_state
)
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
)
284 "imageDetails": image_info
,
285 "imagePullPolicy": "Always",
287 "envConfig": env_config
,
289 "readinessProbe": readiness_probe
,
290 "livenessProbe": liveness_probe
,
294 "kubernetesResources": {
295 "ingressResources": ingress_resources
or [],