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
27 from pathlib
import Path
28 from string
import Template
30 logger
= logging
.getLogger(__name__
)
33 def _validate_max_file_size(max_file_size
: int, site_url
: str) -> bool:
34 """Validate max_file_size.
37 max_file_size (int): maximum file size allowed.
38 site_url (str): endpoint url.
41 bool: True if valid, false otherwise.
46 parsed
= urlparse(site_url
)
48 if not parsed
.scheme
.startswith("http"):
51 if max_file_size
is None:
54 return max_file_size
>= 0
57 def _validate_ip_network(network
: str) -> bool:
58 """Validate IP network.
61 network (str): IP network range.
64 bool: True if valid, false otherwise.
77 def _validate_data(config_data
: Dict
[str, Any
], relation_data
: Dict
[str, Any
]) -> bool:
78 """Validates passed information.
81 config_data (Dict[str, Any]): configuration information.
82 relation_data (Dict[str, Any]): relation information
85 ValueError: when config and/or relation data is not valid.
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
= {
100 "prometheus_host": lambda value
, _
: isinstance(value
, str) and len(value
) > 0,
101 "prometheus_port": lambda value
, _
: isinstance(value
, str)
107 for key
, validator
in config_validators
.items():
108 valid
= validator(config_data
.get(key
), config_data
)
113 for key
, validator
in relation_validators
.items():
114 valid
= validator(relation_data
.get(key
), relation_data
)
119 if len(problems
) > 0:
120 raise ValueError("Errors found in: {}".format(", ".join(problems
)))
125 def _make_pod_ports(port
: int) -> List
[Dict
[str, Any
]]:
126 """Generate pod ports details.
129 port (int): port to expose.
132 List[Dict[str, Any]]: pod port details.
134 return [{"name": "grafana", "containerPort": port
, "protocol": "TCP"}]
137 def _make_pod_envconfig(
138 config
: Dict
[str, Any
], relation_state
: Dict
[str, Any
]
140 """Generate pod environment configuration.
143 config (Dict[str, Any]): configuration information.
144 relation_state (Dict[str, Any]): relation state information.
147 Dict[str, Any]: pod environment configuration.
154 def _make_pod_ingress_resources(
155 config
: Dict
[str, Any
], app_name
: str, port
: int
156 ) -> List
[Dict
[str, Any
]]:
157 """Generate pod ingress resources.
160 config (Dict[str, Any]): configuration information.
161 app_name (str): application name.
162 port (int): port to expose.
165 List[Dict[str, Any]]: pod ingress resources.
167 site_url
= config
.get("site_url")
172 parsed
= urlparse(site_url
)
174 if not parsed
.scheme
.startswith("http"):
177 max_file_size
= config
["max_file_size"]
178 ingress_whitelist_source_range
= config
["ingress_whitelist_source_range"]
181 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
182 str(max_file_size
) + "m" if max_file_size
> 0 else max_file_size
186 if ingress_whitelist_source_range
:
188 "nginx.ingress.kubernetes.io/whitelist-source-range"
189 ] = ingress_whitelist_source_range
191 ingress_spec_tls
= None
193 if parsed
.scheme
== "https":
194 ingress_spec_tls
= [{"hosts": [parsed
.hostname
]}]
195 tls_secret_name
= config
["tls_secret_name"]
197 ingress_spec_tls
[0]["secretName"] = tls_secret_name
199 annotations
["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
202 "name": "{}-ingress".format(app_name
),
203 "annotations": annotations
,
207 "host": parsed
.hostname
,
213 "serviceName": app_name
,
224 ingress
["spec"]["tls"] = ingress_spec_tls
230 config
: Dict
[str, Any
], relation
: Dict
[str, Any
]
231 ) -> List
[Dict
[str, Any
]]:
232 """Generating ConfigMap information
235 config (Dict[str, Any]): configuration information.
236 relation (Dict[str, Any]): relation information.
239 List[Dict[str, Any]]: ConfigMap information.
241 template_data
= {**config
, **relation
}
244 if config
.get("osm_dashboards", False):
248 "path": "kafka_exporter_dashboard.yaml",
250 Path("files/kafka_exporter_dashboard.yaml").read_text()
254 "path": "mongodb_exporter_dashboard.yaml",
256 Path("files/mongodb_exporter_dashboard.yaml").read_text()
260 "path": "mysql_exporter_dashboard.yaml",
262 Path("files/mysql_exporter_dashboard.yaml").read_text()
266 "path": "nodes_exporter_dashboard.yaml",
268 Path("files/nodes_exporter_dashboard.yaml").read_text()
272 "path": "summary_dashboard.yaml",
274 Path("files/summary_dashboard.yaml").read_text()
282 "path": "dashboard_osm.yaml",
283 "content": Template(Path("files/default_dashboards.yaml").read_text()),
289 "name": "dashboards",
290 "mountPath": "/etc/grafana/provisioning/dashboards/",
294 "name": "datasources",
295 "mountPath": "/etc/grafana/provisioning/datasources/",
298 "path": "datasource_prometheus.yaml",
300 Path("files/default_dashboards.yaml").read_text()
301 ).substitute(template_data
),
310 def _make_readiness_probe(port
: int) -> Dict
[str, Any
]:
311 """Generate readiness probe.
314 port (int): service port.
317 Dict[str, Any]: readiness probe.
321 "path": "/api/health",
324 "initialDelaySeconds": 10,
327 "successThreshold": 1,
328 "failureThreshold": 3,
332 def _make_liveness_probe(port
: int) -> Dict
[str, Any
]:
333 """Generate liveness probe.
336 port (int): service port.
339 Dict[str, Any]: liveness probe.
343 "path": "/api/health",
346 "initialDelaySeconds": 60,
347 "timeoutSeconds": 30,
348 "failureThreshold": 10,
353 image_info
: Dict
[str, str],
354 config
: Dict
[str, Any
],
355 relation_state
: Dict
[str, Any
],
356 app_name
: str = "grafana",
359 """Generate the pod spec information.
362 image_info (Dict[str, str]): Object provided by
363 OCIImageResource("image").fetch().
364 config (Dict[str, Any]): Configuration information.
365 relation_state (Dict[str, Any]): Relation state information.
366 app_name (str, optional): Application name. Defaults to "ro".
367 port (int, optional): Port for the container. Defaults to 9090.
370 Dict[str, Any]: Pod spec dictionary for the charm.
375 _validate_data(config
, relation_state
)
377 ports
= _make_pod_ports(port
)
378 env_config
= _make_pod_envconfig(config
, relation_state
)
379 files
= _make_pod_files(relation_state
)
380 readiness_probe
= _make_readiness_probe(port
)
381 liveness_probe
= _make_liveness_probe(port
)
382 ingress_resources
= _make_pod_ingress_resources(config
, app_name
, port
)
389 "imageDetails": image_info
,
390 "imagePullPolicy": "Always",
392 "envConfig": env_config
,
393 "volumeConfig": files
,
395 "readinessProbe": readiness_probe
,
396 "livenessProbe": liveness_probe
,
400 "kubernetesResources": {
401 "ingressResources": ingress_resources
or [],