Fix validation error for ImagePullPolicy in charms
[osm/devops.git] / installers / charm / ng-ui / src / charm.py
1 #!/usr/bin/env python3
2 # Copyright 2021 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 # pylint: disable=E0213
24
25
26 from ipaddress import ip_network
27 import logging
28 from pathlib import Path
29 from string import Template
30 from typing import NoReturn, Optional
31 from urllib.parse import urlparse
32
33 from ops.main import main
34 from opslib.osm.charm import CharmedOsmBase, RelationsMissing
35 from opslib.osm.interfaces.http import HttpClient
36 from opslib.osm.pod import (
37 ContainerV3Builder,
38 FilesV3Builder,
39 IngressResourceV3Builder,
40 PodSpecV3Builder,
41 )
42 from opslib.osm.validator import ModelValidator, validator
43
44
45 logger = logging.getLogger(__name__)
46
47
48 class ConfigModel(ModelValidator):
49 port: int
50 server_name: str
51 max_file_size: int
52 site_url: Optional[str]
53 cluster_issuer: Optional[str]
54 ingress_class: Optional[str]
55 ingress_whitelist_source_range: Optional[str]
56 tls_secret_name: Optional[str]
57 image_pull_policy: str
58
59 @validator("port")
60 def validate_port(cls, v):
61 if v <= 0:
62 raise ValueError("value must be greater than 0")
63 return v
64
65 @validator("max_file_size")
66 def validate_max_file_size(cls, v):
67 if v < 0:
68 raise ValueError("value must be equal or greater than 0")
69 return v
70
71 @validator("site_url")
72 def validate_site_url(cls, v):
73 if v:
74 parsed = urlparse(v)
75 if not parsed.scheme.startswith("http"):
76 raise ValueError("value must start with http")
77 return v
78
79 @validator("ingress_whitelist_source_range")
80 def validate_ingress_whitelist_source_range(cls, v):
81 if v:
82 ip_network(v)
83 return v
84
85 @validator("image_pull_policy")
86 def validate_image_pull_policy(cls, v):
87 values = {
88 "always": "Always",
89 "ifnotpresent": "IfNotPresent",
90 "never": "Never",
91 }
92 v = v.lower()
93 if v not in values.keys():
94 raise ValueError("value must be always, ifnotpresent or never")
95 return values[v]
96
97
98 class NgUiCharm(CharmedOsmBase):
99 def __init__(self, *args) -> NoReturn:
100 super().__init__(*args, oci_image="image")
101
102 self.nbi_client = HttpClient(self, "nbi")
103 self.framework.observe(self.on["nbi"].relation_changed, self.configure_pod)
104 self.framework.observe(self.on["nbi"].relation_broken, self.configure_pod)
105
106 def _check_missing_dependencies(self, config: ConfigModel):
107 missing_relations = []
108
109 if self.nbi_client.is_missing_data_in_app():
110 missing_relations.append("nbi")
111
112 if missing_relations:
113 raise RelationsMissing(missing_relations)
114
115 def _build_files(self, config: ConfigModel):
116 files_builder = FilesV3Builder()
117 files_builder.add_file(
118 "default",
119 Template(Path("templates/default.template").read_text()).substitute(
120 port=config.port,
121 server_name=config.server_name,
122 max_file_size=config.max_file_size,
123 nbi_host=self.nbi_client.host,
124 nbi_port=self.nbi_client.port,
125 ),
126 )
127 return files_builder.build()
128
129 def build_pod_spec(self, image_info):
130 # Validate config
131 config = ConfigModel(**dict(self.config))
132 # Check relations
133 self._check_missing_dependencies(config)
134 # Create Builder for the PodSpec
135 pod_spec_builder = PodSpecV3Builder()
136 # Build Container
137 container_builder = ContainerV3Builder(
138 self.app.name, image_info, config.image_pull_policy
139 )
140 container_builder.add_port(name=self.app.name, port=config.port)
141 container = container_builder.build()
142 container_builder.add_tcpsocket_readiness_probe(
143 config.port,
144 initial_delay_seconds=45,
145 timeout_seconds=5,
146 )
147 container_builder.add_tcpsocket_liveness_probe(
148 config.port,
149 initial_delay_seconds=45,
150 timeout_seconds=15,
151 )
152 container_builder.add_volume_config(
153 "configuration",
154 "/etc/nginx/sites-available/",
155 self._build_files(config),
156 )
157 # Add container to pod spec
158 pod_spec_builder.add_container(container)
159 # Add ingress resources to pod spec if site url exists
160 if config.site_url:
161 parsed = urlparse(config.site_url)
162 annotations = {
163 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
164 str(config.max_file_size) + "m"
165 if config.max_file_size > 0
166 else config.max_file_size
167 )
168 }
169 if config.ingress_class:
170 annotations["kubernetes.io/ingress.class"] = config.ingress_class
171 ingress_resource_builder = IngressResourceV3Builder(
172 f"{self.app.name}-ingress", annotations
173 )
174
175 if config.ingress_whitelist_source_range:
176 annotations[
177 "nginx.ingress.kubernetes.io/whitelist-source-range"
178 ] = config.ingress_whitelist_source_range
179
180 if config.cluster_issuer:
181 annotations["cert-manager.io/cluster-issuer"] = config.cluster_issuer
182
183 if parsed.scheme == "https":
184 ingress_resource_builder.add_tls(
185 [parsed.hostname], config.tls_secret_name
186 )
187 else:
188 annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
189
190 ingress_resource_builder.add_rule(
191 parsed.hostname, self.app.name, config.port
192 )
193 ingress_resource = ingress_resource_builder.build()
194 pod_spec_builder.add_ingress_resource(ingress_resource)
195 return pod_spec_builder.build()
196
197
198 if __name__ == "__main__":
199 main(NgUiCharm)