ec7f2d9a5810c45387d2fd84c7bb3822c6d36e92
[osm/devops.git] / installers / charm / pol / 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 """Validate input data.
33
34 Args:
35 config_data (Dict[str, Any]): configuration data.
36 relation_data (Dict[str, Any]): relation data.
37 """
38 config_validators = {
39 "log_level": lambda value, _: isinstance(value, str)
40 and value in ("INFO", "DEBUG"),
41 }
42 relation_validators = {
43 "message_host": lambda value, _: isinstance(value, str) and len(value) > 0,
44 "message_port": lambda value, _: isinstance(value, int) and value > 0,
45 "database_uri": lambda value, _: isinstance(value, str)
46 and value.startswith("mongodb://"),
47 }
48 problems = []
49
50 for key, validator in config_validators.items():
51 valid = validator(config_data.get(key), config_data)
52
53 if not valid:
54 problems.append(key)
55
56 for key, validator in relation_validators.items():
57 valid = validator(relation_data.get(key), relation_data)
58
59 if not valid:
60 problems.append(key)
61
62 if len(problems) > 0:
63 raise ValueError("Errors found in: {}".format(", ".join(problems)))
64
65
66 def _make_pod_ports(port: int) -> List[Dict[str, Any]]:
67 """Generate pod ports details.
68
69 Args:
70 port (int): port to expose.
71
72 Returns:
73 List[Dict[str, Any]]: pod port details.
74 """
75 return [{"name": "pol", "containerPort": port, "protocol": "TCP"}]
76
77
78 def _make_pod_envconfig(
79 config: Dict[str, Any], relation_state: Dict[str, Any]
80 ) -> Dict[str, Any]:
81 """Generate pod environment configuration.
82
83 Args:
84 config (Dict[str, Any]): configuration information.
85 relation_state (Dict[str, Any]): relation state information.
86
87 Returns:
88 Dict[str, Any]: pod environment configuration.
89 """
90 envconfig = {
91 # General configuration
92 "ALLOW_ANONYMOUS_LOGIN": "yes",
93 "OSMPOL_GLOBAL_LOGLEVEL": config["log_level"],
94 # Kafka configuration
95 "OSMPOL_MESSAGE_HOST": relation_state["message_host"],
96 "OSMPOL_MESSAGE_DRIVER": "kafka",
97 "OSMPOL_MESSAGE_PORT": relation_state["message_port"],
98 # Database configuration
99 "OSMPOL_DATABASE_DRIVER": "mongo",
100 "OSMPOL_DATABASE_URI": relation_state["database_uri"],
101 }
102
103 return envconfig
104
105
106 def _make_startup_probe() -> Dict[str, Any]:
107 """Generate startup probe.
108
109 Returns:
110 Dict[str, Any]: startup probe.
111 """
112 return {
113 "exec": {"command": ["/usr/bin/pgrep", "python3"]},
114 "initialDelaySeconds": 60,
115 "timeoutSeconds": 5,
116 }
117
118
119 def _make_readiness_probe() -> Dict[str, Any]:
120 """Generate readiness probe.
121
122 Returns:
123 Dict[str, Any]: readiness probe.
124 """
125 return {
126 "exec": {
127 "command": ["sh", "-c", "osm-pol-healthcheck || exit 1"],
128 },
129 "periodSeconds": 10,
130 "timeoutSeconds": 5,
131 "successThreshold": 1,
132 "failureThreshold": 3,
133 }
134
135
136 def _make_liveness_probe() -> Dict[str, Any]:
137 """Generate liveness probe.
138
139 Returns:
140 Dict[str, Any]: liveness probe.
141 """
142 return {
143 "exec": {
144 "command": ["sh", "-c", "osm-pol-healthcheck || exit 1"],
145 },
146 "initialDelaySeconds": 45,
147 "periodSeconds": 10,
148 "timeoutSeconds": 5,
149 "successThreshold": 1,
150 "failureThreshold": 3,
151 }
152
153
154 def make_pod_spec(
155 image_info: Dict[str, str],
156 config: Dict[str, Any],
157 relation_state: Dict[str, Any],
158 app_name: str = "pol",
159 port: int = 80,
160 ) -> Dict[str, Any]:
161 """Generate the pod spec information.
162
163 Args:
164 image_info (Dict[str, str]): Object provided by
165 OCIImageResource("image").fetch().
166 config (Dict[str, Any]): Configuration information.
167 relation_state (Dict[str, Any]): Relation state information.
168 app_name (str, optional): Application name. Defaults to "pol".
169 port (int, optional): Port for the container. Defaults to 80.
170
171 Returns:
172 Dict[str, Any]: Pod spec dictionary for the charm.
173 """
174 if not image_info:
175 return None
176
177 _validate_data(config, relation_state)
178
179 ports = _make_pod_ports(port)
180 env_config = _make_pod_envconfig(config, relation_state)
181
182 return {
183 "version": 3,
184 "containers": [
185 {
186 "name": app_name,
187 "imageDetails": image_info,
188 "imagePullPolicy": "Always",
189 "ports": ports,
190 "envConfig": env_config,
191 }
192 ],
193 "kubernetesResources": {
194 "ingressResources": [],
195 },
196 }