6c91baff6a5fc2b7a016791c93cecf59bc3fc8af
[osm/devops.git] / installers / charm / ro / src / pod_spec.py
1 #!/usr/bin/env python3
2 # Copyright 2020 Canonical Ltd.
3 #
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
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
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
14 # under the License.
15 #
16 # For those usages not covered by the Apache License, Version 2.0 please
17 # contact: legal@canonical.com
18 #
19 # To get in touch with the maintainers, please contact:
20 # osm-charmers@lists.launchpad.net
21 ##
22
23 import logging
24 from typing import Any, Dict, List, NoReturn
25
26 logger = logging.getLogger(__name__)
27
28
29 def _validate_data(
30 config_data: Dict[str, Any], relation_data: Dict[str, Any]
31 ) -> NoReturn:
32 """Validates passed information.
33
34 Args:
35 config_data (Dict[str, Any]): configuration information.
36 relation_data (Dict[str, Any]): relation information
37
38 Raises:
39 ValueError: when config and/or relation data is not valid.
40 """
41 config_validators = {
42 "enable_ng_ro": lambda value, _: isinstance(value, bool),
43 "database_commonkey": lambda value, values: (
44 isinstance(value, str) and len(value) > 0
45 )
46 if values.get("enable_ng_ro", True)
47 else True,
48 "log_level": lambda value, _: isinstance(value, str)
49 and value in ("INFO", "DEBUG"),
50 "vim_database": lambda value, values: (
51 isinstance(value, str) and len(value) > 0
52 )
53 if not values.get("enable_ng_ro", True)
54 else True,
55 "ro_database": lambda value, values: (isinstance(value, str) and len(value) > 0)
56 if not values.get("enable_ng_ro", True)
57 else True,
58 "openmano_tenant": lambda value, values: (
59 isinstance(value, str) and len(value) > 0
60 )
61 if not values.get("enable_ng_ro", True)
62 else True,
63 }
64 relation_validators = {
65 "kafka_host": lambda value, _: (isinstance(value, str) and len(value) > 0)
66 if config_data.get("enable_ng_ro", True)
67 else True,
68 "kafka_port": lambda value, _: (isinstance(value, str) and len(value) > 0)
69 if config_data.get("enable_ng_ro", True)
70 else True,
71 "mongodb_connection_string": lambda value, _: (
72 isinstance(value, str) and value.startswith("mongodb://")
73 )
74 if config_data.get("enable_ng_ro", True)
75 else True,
76 "mysql_host": lambda value, _: (isinstance(value, str) and len(value) > 0)
77 if not config_data.get("enable_ng_ro", True)
78 else True,
79 "mysql_port": lambda value, _: (isinstance(value, int) and value > 0)
80 if not config_data.get("enable_ng_ro", True)
81 else True,
82 "mysql_user": lambda value, _: (isinstance(value, str) and len(value) > 0)
83 if not config_data.get("enable_ng_ro", True)
84 else True,
85 "mysql_password": lambda value, _: (isinstance(value, str) and len(value) > 0)
86 if not config_data.get("enable_ng_ro", True)
87 else True,
88 "mysql_root_password": lambda value, _: (
89 isinstance(value, str) and len(value) > 0
90 )
91 if not config_data.get("enable_ng_ro", True)
92 else True,
93 }
94 problems = []
95
96 for key, validator in config_validators.items():
97 valid = validator(config_data.get(key), config_data)
98
99 if not valid:
100 problems.append(key)
101
102 for key, validator in relation_validators.items():
103 valid = validator(relation_data.get(key), relation_data)
104
105 if not valid:
106 problems.append(key)
107
108 if len(problems) > 0:
109 raise ValueError("Errors found in: {}".format(", ".join(problems)))
110
111
112 def _make_pod_ports(port: int) -> List[Dict[str, Any]]:
113 """Generate pod ports details.
114
115 Args:
116 port (int): port to expose.
117
118 Returns:
119 List[Dict[str, Any]]: pod port details.
120 """
121 return [{"name": "ro", "containerPort": port, "protocol": "TCP"}]
122
123
124 def _make_pod_envconfig(
125 config: Dict[str, Any], relation_state: Dict[str, Any]
126 ) -> Dict[str, Any]:
127 """Generate pod environment configuration.
128
129 Args:
130 config (Dict[str, Any]): configuration information.
131 relation_state (Dict[str, Any]): relation state information.
132
133 Returns:
134 Dict[str, Any]: pod environment configuration.
135 """
136 envconfig = {
137 # General configuration
138 "OSMRO_LOG_LEVEL": config["log_level"],
139 }
140
141 if config.get("enable_ng_ro", True):
142 # Kafka configuration
143 envconfig["OSMRO_MESSAGE_DRIVER"] = "kafka"
144 envconfig["OSMRO_MESSAGE_HOST"] = relation_state["kafka_host"]
145 envconfig["OSMRO_MESSAGE_PORT"] = relation_state["kafka_port"]
146
147 # MongoDB configuration
148 envconfig["OSMRO_DATABASE_DRIVER"] = "mongo"
149 envconfig["OSMRO_DATABASE_URI"] = relation_state["mongodb_connection_string"]
150 envconfig["OSMRO_DATABASE_COMMONKEY"] = config["database_commonkey"]
151 else:
152 envconfig["RO_DB_HOST"] = relation_state["mysql_host"]
153 envconfig["RO_DB_OVIM_HOST"] = relation_state["mysql_host"]
154 envconfig["RO_DB_PORT"] = relation_state["mysql_port"]
155 envconfig["RO_DB_OVIM_PORT"] = relation_state["mysql_port"]
156 envconfig["RO_DB_USER"] = relation_state["mysql_user"]
157 envconfig["RO_DB_OVIM_USER"] = relation_state["mysql_user"]
158 envconfig["RO_DB_PASSWORD"] = relation_state["mysql_password"]
159 envconfig["RO_DB_OVIM_PASSWORD"] = relation_state["mysql_password"]
160 envconfig["RO_DB_ROOT_PASSWORD"] = relation_state["mysql_root_password"]
161 envconfig["RO_DB_OVIM_ROOT_PASSWORD"] = relation_state["mysql_root_password"]
162 envconfig["RO_DB_NAME"] = config["ro_database"]
163 envconfig["RO_DB_OVIM_NAME"] = config["vim_database"]
164 envconfig["OPENMANO_TENANT"] = config["openmano_tenant"]
165
166 return envconfig
167
168
169 def _make_startup_probe() -> Dict[str, Any]:
170 """Generate startup probe.
171
172 Returns:
173 Dict[str, Any]: startup probe.
174 """
175 return {
176 "exec": {"command": ["/usr/bin/pgrep", "python3"]},
177 "initialDelaySeconds": 60,
178 "timeoutSeconds": 5,
179 }
180
181
182 def _make_readiness_probe(port: int) -> Dict[str, Any]:
183 """Generate readiness probe.
184
185 Args:
186 port (int): service port.
187
188 Returns:
189 Dict[str, Any]: readiness probe.
190 """
191 return {
192 "httpGet": {
193 "path": "/openmano/tenants",
194 "port": port,
195 },
196 "periodSeconds": 10,
197 "timeoutSeconds": 5,
198 "successThreshold": 1,
199 "failureThreshold": 3,
200 }
201
202
203 def _make_liveness_probe(port: int) -> Dict[str, Any]:
204 """Generate liveness probe.
205
206 Args:
207 port (int): service port.
208
209 Returns:
210 Dict[str, Any]: liveness probe.
211 """
212 return {
213 "httpGet": {
214 "path": "/openmano/tenants",
215 "port": port,
216 },
217 "initialDelaySeconds": 600,
218 "periodSeconds": 10,
219 "timeoutSeconds": 5,
220 "successThreshold": 1,
221 "failureThreshold": 3,
222 }
223
224
225 def make_pod_spec(
226 image_info: Dict[str, str],
227 config: Dict[str, Any],
228 relation_state: Dict[str, Any],
229 app_name: str = "ro",
230 port: int = 9090,
231 ) -> Dict[str, Any]:
232 """Generate the pod spec information.
233
234 Args:
235 image_info (Dict[str, str]): Object provided by
236 OCIImageResource("image").fetch().
237 config (Dict[str, Any]): Configuration information.
238 relation_state (Dict[str, Any]): Relation state information.
239 app_name (str, optional): Application name. Defaults to "ro".
240 port (int, optional): Port for the container. Defaults to 9090.
241
242 Returns:
243 Dict[str, Any]: Pod spec dictionary for the charm.
244 """
245 if not image_info:
246 return None
247
248 _validate_data(config, relation_state)
249
250 ports = _make_pod_ports(port)
251 env_config = _make_pod_envconfig(config, relation_state)
252 startup_probe = _make_startup_probe()
253 readiness_probe = _make_readiness_probe(port)
254 liveness_probe = _make_liveness_probe(port)
255
256 return {
257 "version": 3,
258 "containers": [
259 {
260 "name": app_name,
261 "imageDetails": image_info,
262 "imagePullPolicy": "Always",
263 "ports": ports,
264 "envConfig": env_config,
265 "kubernetes": {
266 "startupProbe": startup_probe,
267 "readinessProbe": readiness_probe,
268 "livenessProbe": liveness_probe,
269 },
270 }
271 ],
272 "kubernetesResources": {
273 "ingressResources": [],
274 },
275 }