blob: 4d2bb85d6b6043319cdaea26a359989fcd5db14e [file] [log] [blame]
beierlma4a37f72020-06-26 12:55:01 -04001#!/usr/bin/env python3
David Garcia49379ce2021-02-24 13:48:22 +01002# Copyright 2021 Canonical Ltd.
beierlma4a37f72020-06-26 12:55:01 -04003#
David Garciaef349d92020-12-10 21:16:12 +01004# 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
beierlma4a37f72020-06-26 12:55:01 -04007#
David Garciaef349d92020-12-10 21:16:12 +01008# http://www.apache.org/licenses/LICENSE-2.0
beierlma4a37f72020-06-26 12:55:01 -04009#
David Garciaef349d92020-12-10 21:16:12 +010010# 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##
beierlma4a37f72020-06-26 12:55:01 -040022
David Garcia49379ce2021-02-24 13:48:22 +010023# pylint: disable=E0213
24
25
beierlmb1a1c462020-10-23 14:54:56 -040026import logging
David Garcia49379ce2021-02-24 13:48:22 +010027from typing import Optional, NoReturn
28from ipaddress import ip_network
29from urllib.parse import urlparse
beierlma4a37f72020-06-26 12:55:01 -040030
beierlma4a37f72020-06-26 12:55:01 -040031from ops.main import main
beierlma4a37f72020-06-26 12:55:01 -040032
David Garcia49379ce2021-02-24 13:48:22 +010033from opslib.osm.charm import CharmedOsmBase, RelationsMissing
34
35from opslib.osm.pod import (
36 ContainerV3Builder,
37 PodSpecV3Builder,
38 FilesV3Builder,
39 IngressResourceV3Builder,
40)
41
42
43from opslib.osm.validator import (
44 ModelValidator,
45 validator,
46)
47
48from opslib.osm.interfaces.http import HttpClient
49from string import Template
50from pathlib import Path
beierlmb1a1c462020-10-23 14:54:56 -040051
beierlma4a37f72020-06-26 12:55:01 -040052logger = logging.getLogger(__name__)
53
David Garcia49379ce2021-02-24 13:48:22 +010054
55class ConfigModel(ModelValidator):
56 port: int
57 server_name: str
58 max_file_size: int
59 site_url: Optional[str]
60 ingress_whitelist_source_range: Optional[str]
61 tls_secret_name: Optional[str]
62
63 @validator("port")
64 def validate_port(cls, v):
65 if v <= 0:
66 raise ValueError("value must be greater than 0")
67 return v
68
69 @validator("max_file_size")
70 def validate_max_file_size(cls, v):
71 if v < 0:
72 raise ValueError("value must be equal or greater than 0")
73 return v
74
75 @validator("site_url")
76 def validate_site_url(cls, v):
77 if v:
78 parsed = urlparse(v)
79 if not parsed.scheme.startswith("http"):
80 raise ValueError("value must start with http")
81 return v
82
83 @validator("ingress_whitelist_source_range")
84 def validate_ingress_whitelist_source_range(cls, v):
85 if v:
86 ip_network(v)
87 return v
beierlma4a37f72020-06-26 12:55:01 -040088
David Garciaef349d92020-12-10 21:16:12 +010089
David Garcia49379ce2021-02-24 13:48:22 +010090class NgUiCharm(CharmedOsmBase):
David Garciaef349d92020-12-10 21:16:12 +010091 def __init__(self, *args) -> NoReturn:
David Garcia49379ce2021-02-24 13:48:22 +010092 super().__init__(*args, oci_image="image")
David Garciaef349d92020-12-10 21:16:12 +010093
David Garcia49379ce2021-02-24 13:48:22 +010094 self.nbi_client = HttpClient(self, "nbi")
95 self.framework.observe(self.on["nbi"].relation_changed, self.configure_pod)
96 self.framework.observe(self.on["nbi"].relation_broken, self.configure_pod)
David Garciaef349d92020-12-10 21:16:12 +010097
David Garcia49379ce2021-02-24 13:48:22 +010098 def _check_missing_dependencies(self, config: ConfigModel):
99 missing_relations = []
beierlma4a37f72020-06-26 12:55:01 -0400100
David Garcia49379ce2021-02-24 13:48:22 +0100101 if self.nbi_client.is_missing_data_in_app():
102 missing_relations.append("nbi")
David Garciaef349d92020-12-10 21:16:12 +0100103
David Garcia49379ce2021-02-24 13:48:22 +0100104 if missing_relations:
105 raise RelationsMissing(missing_relations)
David Garciaef349d92020-12-10 21:16:12 +0100106
David Garcia49379ce2021-02-24 13:48:22 +0100107 def _build_files(self, config: ConfigModel):
108 files_builder = FilesV3Builder()
109 files_builder.add_file(
110 "default",
111 Template(Path("files/default").read_text()).substitute(
112 port=config.port,
113 server_name=config.server_name,
114 max_file_size=config.max_file_size,
115 nbi_host=self.nbi_client.host,
116 nbi_port=self.nbi_client.port,
117 ),
beierlma4a37f72020-06-26 12:55:01 -0400118 )
David Garcia49379ce2021-02-24 13:48:22 +0100119 return files_builder.build()
beierlma4a37f72020-06-26 12:55:01 -0400120
David Garcia49379ce2021-02-24 13:48:22 +0100121 def build_pod_spec(self, image_info):
122 # Validate config
123 config = ConfigModel(**dict(self.config))
124 # Check relations
125 self._check_missing_dependencies(config)
126 # Create Builder for the PodSpec
127 pod_spec_builder = PodSpecV3Builder()
128 # Build Container
129 container_builder = ContainerV3Builder(self.app.name, image_info)
130 container_builder.add_port(name=self.app.name, port=config.port)
131 container = container_builder.build()
132 container_builder.add_tcpsocket_readiness_probe(
133 config.port,
134 initial_delay_seconds=45,
135 timeout_seconds=5,
David Garciaef349d92020-12-10 21:16:12 +0100136 )
David Garcia49379ce2021-02-24 13:48:22 +0100137 container_builder.add_tcpsocket_liveness_probe(
138 config.port,
139 initial_delay_seconds=45,
140 timeout_seconds=15,
141 )
142 container_builder.add_volume_config(
143 "configuration",
144 "/etc/nginx/sites-available/",
145 self._build_files(config),
146 )
147 # Add container to pod spec
148 pod_spec_builder.add_container(container)
149 # Add ingress resources to pod spec if site url exists
150 if config.site_url:
151 parsed = urlparse(config.site_url)
152 annotations = {
153 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
154 str(config.max_file_size) + "m"
155 if config.max_file_size > 0
156 else config.max_file_size
157 ),
158 }
159 ingress_resource_builder = IngressResourceV3Builder(
160 f"{self.app.name}-ingress", annotations
David Garciaef349d92020-12-10 21:16:12 +0100161 )
David Garciaef349d92020-12-10 21:16:12 +0100162
David Garcia49379ce2021-02-24 13:48:22 +0100163 if config.ingress_whitelist_source_range:
164 annotations[
165 "nginx.ingress.kubernetes.io/whitelist-source-range"
166 ] = config.ingress_whitelist_source_range
David Garciaef349d92020-12-10 21:16:12 +0100167
David Garcia49379ce2021-02-24 13:48:22 +0100168 if parsed.scheme == "https":
169 ingress_resource_builder.add_tls(
170 [parsed.hostname], config.tls_secret_name
171 )
172 else:
173 annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
David Garciaef349d92020-12-10 21:16:12 +0100174
David Garcia49379ce2021-02-24 13:48:22 +0100175 ingress_resource_builder.add_rule(
176 parsed.hostname, self.app.name, config.port
David Garciaef349d92020-12-10 21:16:12 +0100177 )
David Garcia49379ce2021-02-24 13:48:22 +0100178 ingress_resource = ingress_resource_builder.build()
179 pod_spec_builder.add_ingress_resource(ingress_resource)
180 return pod_spec_builder.build()
beierlma4a37f72020-06-26 12:55:01 -0400181
182
183if __name__ == "__main__":
David Garciaef349d92020-12-10 21:16:12 +0100184 main(NgUiCharm)