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_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 "site_url": lambda value
, _
: isinstance(value
, str)
89 "max_file_size": lambda value
, values
: _validate_max_file_size(
90 value
, values
.get("site_url")
92 "ingress_whitelist_source_range": lambda value
, _
: _validate_ip_network(value
),
93 "tls_secret_name": lambda value
, _
: isinstance(value
, str)
97 relation_validators
= {
98 "prometheus_host": lambda value
, _
: isinstance(value
, str) and len(value
) > 0,
99 "prometheus_port": lambda value
, _
: isinstance(value
, str)
105 for key
, validator
in config_validators
.items():
106 valid
= validator(config_data
.get(key
), config_data
)
111 for key
, validator
in relation_validators
.items():
112 valid
= validator(relation_data
.get(key
), relation_data
)
117 if len(problems
) > 0:
118 raise ValueError("Errors found in: {}".format(", ".join(problems
)))
123 def _make_pod_ports(port
: int) -> List
[Dict
[str, Any
]]:
124 """Generate pod ports details.
127 port (int): port to expose.
130 List[Dict[str, Any]]: pod port details.
132 return [{"name": "grafana", "containerPort": port
, "protocol": "TCP"}]
135 def _make_pod_envconfig(
136 config
: Dict
[str, Any
], relation_state
: Dict
[str, Any
]
138 """Generate pod environment configuration.
141 config (Dict[str, Any]): configuration information.
142 relation_state (Dict[str, Any]): relation state information.
145 Dict[str, Any]: pod environment configuration.
152 def _make_pod_ingress_resources(
153 config
: Dict
[str, Any
], app_name
: str, port
: int
154 ) -> List
[Dict
[str, Any
]]:
155 """Generate pod ingress resources.
158 config (Dict[str, Any]): configuration information.
159 app_name (str): application name.
160 port (int): port to expose.
163 List[Dict[str, Any]]: pod ingress resources.
165 site_url
= config
.get("site_url")
170 parsed
= urlparse(site_url
)
172 if not parsed
.scheme
.startswith("http"):
175 max_file_size
= config
["max_file_size"]
176 ingress_whitelist_source_range
= config
["ingress_whitelist_source_range"]
179 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
180 str(max_file_size
) + "m" if max_file_size
> 0 else max_file_size
184 if ingress_whitelist_source_range
:
186 "nginx.ingress.kubernetes.io/whitelist-source-range"
187 ] = ingress_whitelist_source_range
189 ingress_spec_tls
= None
191 if parsed
.scheme
== "https":
192 ingress_spec_tls
= [{"hosts": [parsed
.hostname
]}]
193 tls_secret_name
= config
["tls_secret_name"]
195 ingress_spec_tls
[0]["secretName"] = tls_secret_name
197 annotations
["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
200 "name": "{}-ingress".format(app_name
),
201 "annotations": annotations
,
205 "host": parsed
.hostname
,
211 "serviceName": app_name
,
222 ingress
["spec"]["tls"] = ingress_spec_tls
227 def _make_pod_files(relation
: Dict
[str, Any
]) -> List
[Dict
[str, Any
]]:
228 """Generating ConfigMap information
231 relation (Dict[str, Any]): relation information.
234 List[Dict[str, Any]]: ConfigMap information.
238 "name": "dashboards",
239 "mountPath": "/etc/grafana/provisioning/dashboards/",
242 "path": "dashboard-osm.yml",
251 " path: /etc/grafana/provisioning/dashboards/\n"
257 "name": "datasources",
258 "mountPath": "/etc/grafana/provisioning/datasources/",
261 "path": "datasource-prometheus.yml",
266 " is_default: true\n"
267 " name: osm_prometheus\n"
269 " type: prometheus\n"
271 " url: http://{}:{}\n".format(
272 relation
.get("prometheus_host"),
273 relation
.get("prometheus_port"),
284 def _make_readiness_probe(port
: int) -> Dict
[str, Any
]:
285 """Generate readiness probe.
288 port (int): service port.
291 Dict[str, Any]: readiness probe.
295 "path": "/api/health",
298 "initialDelaySeconds": 10,
301 "successThreshold": 1,
302 "failureThreshold": 3,
306 def _make_liveness_probe(port
: int) -> Dict
[str, Any
]:
307 """Generate liveness probe.
310 port (int): service port.
313 Dict[str, Any]: liveness probe.
317 "path": "/api/health",
320 "initialDelaySeconds": 60,
321 "timeoutSeconds": 30,
322 "failureThreshold": 10,
327 image_info
: Dict
[str, str],
328 config
: Dict
[str, Any
],
329 relation_state
: Dict
[str, Any
],
330 app_name
: str = "grafana",
333 """Generate the pod spec information.
336 image_info (Dict[str, str]): Object provided by
337 OCIImageResource("image").fetch().
338 config (Dict[str, Any]): Configuration information.
339 relation_state (Dict[str, Any]): Relation state information.
340 app_name (str, optional): Application name. Defaults to "ro".
341 port (int, optional): Port for the container. Defaults to 9090.
344 Dict[str, Any]: Pod spec dictionary for the charm.
349 _validate_data(config
, relation_state
)
351 ports
= _make_pod_ports(port
)
352 env_config
= _make_pod_envconfig(config
, relation_state
)
353 files
= _make_pod_files(relation_state
)
354 readiness_probe
= _make_readiness_probe(port
)
355 liveness_probe
= _make_liveness_probe(port
)
356 ingress_resources
= _make_pod_ingress_resources(config
, app_name
, port
)
363 "imageDetails": image_info
,
364 "imagePullPolicy": "Always",
366 "envConfig": env_config
,
367 "volumeConfig": files
,
369 "readinessProbe": readiness_probe
,
370 "livenessProbe": liveness_probe
,
374 "kubernetesResources": {
375 "ingressResources": ingress_resources
or [],