blob: 3d72cace76d0ebed42174c5cffc222205d82739c [file] [log] [blame]
sousaedu2459af62021-01-15 16:50:26 +00001#!/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
David Garcia49379ce2021-02-24 13:48:22 +010023# pylint: disable=E0213
24
sousaedu2459af62021-01-15 16:50:26 +000025import logging
David Garcia49379ce2021-02-24 13:48:22 +010026from typing import Optional, NoReturn
27from ipaddress import ip_network
sousaedu2459af62021-01-15 16:50:26 +000028
David Garcia49379ce2021-02-24 13:48:22 +010029from ops.framework import EventBase
sousaedu2459af62021-01-15 16:50:26 +000030from ops.main import main
sousaedu2459af62021-01-15 16:50:26 +000031
David Garcia49379ce2021-02-24 13:48:22 +010032from opslib.osm.charm import CharmedOsmBase
33
34from opslib.osm.pod import (
35 IngressResourceV3Builder,
36 FilesV3Builder,
37 ContainerV3Builder,
38 PodSpecV3Builder,
39)
40
41
42from opslib.osm.validator import (
43 ModelValidator,
44 validator,
45)
46
47from opslib.osm.interfaces.prometheus import PrometheusServer
48from urllib.parse import urlparse
sousaedu2459af62021-01-15 16:50:26 +000049
50logger = logging.getLogger(__name__)
51
David Garcia49379ce2021-02-24 13:48:22 +010052PORT = 9090
sousaedu2459af62021-01-15 16:50:26 +000053
54
David Garcia49379ce2021-02-24 13:48:22 +010055class ConfigModel(ModelValidator):
56 web_subpath: str
57 default_target: 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 enable_web_admin_api: bool
63
64 @validator("web_subpath")
65 def validate_web_subpath(cls, v):
66 if len(v) < 1:
67 raise ValueError("web-subpath must be a non-empty string")
68 return v
69
70 @validator("max_file_size")
71 def validate_max_file_size(cls, v):
72 if v < 0:
73 raise ValueError("value must be equal or greater than 0")
74 return v
75
76 @validator("site_url")
77 def validate_site_url(cls, v):
78 if v:
79 parsed = urlparse(v)
80 if not parsed.scheme.startswith("http"):
81 raise ValueError("value must start with http")
82 return v
83
84 @validator("ingress_whitelist_source_range")
85 def validate_ingress_whitelist_source_range(cls, v):
86 if v:
87 ip_network(v)
88 return v
sousaedu2459af62021-01-15 16:50:26 +000089
90
David Garcia49379ce2021-02-24 13:48:22 +010091class PrometheusCharm(CharmedOsmBase):
sousaedu2459af62021-01-15 16:50:26 +000092
sousaedu2459af62021-01-15 16:50:26 +000093 """Prometheus Charm."""
94
sousaedu2459af62021-01-15 16:50:26 +000095 def __init__(self, *args) -> NoReturn:
96 """Prometheus Charm constructor."""
David Garcia49379ce2021-02-24 13:48:22 +010097 super().__init__(*args, oci_image="image")
sousaedu2459af62021-01-15 16:50:26 +000098
99 # Registering provided relation events
David Garcia49379ce2021-02-24 13:48:22 +0100100 self.prometheus = PrometheusServer(self, "prometheus")
sousaedu2459af62021-01-15 16:50:26 +0000101 self.framework.observe(
David Garcia49379ce2021-02-24 13:48:22 +0100102 self.on.prometheus_relation_joined, # pylint: disable=E1101
103 self._publish_prometheus_info,
sousaedu2459af62021-01-15 16:50:26 +0000104 )
105
106 def _publish_prometheus_info(self, event: EventBase) -> NoReturn:
David Garcia49379ce2021-02-24 13:48:22 +0100107 self.prometheus.publish_info(self.app.name, PORT)
sousaedu2459af62021-01-15 16:50:26 +0000108
David Garcia49379ce2021-02-24 13:48:22 +0100109 def _build_files(self, config: ConfigModel):
110 files_builder = FilesV3Builder()
111 files_builder.add_file(
112 "prometheus.yml",
113 (
114 "global:\n"
115 " scrape_interval: 15s\n"
116 " evaluation_interval: 15s\n"
117 "alerting:\n"
118 " alertmanagers:\n"
119 " - static_configs:\n"
120 " - targets:\n"
121 "rule_files:\n"
122 "scrape_configs:\n"
123 " - job_name: 'prometheus'\n"
124 " static_configs:\n"
125 f" - targets: [{config.default_target}]\n"
126 ),
127 )
128 return files_builder.build()
129
130 def build_pod_spec(self, image_info):
131 # Validate config
132 config = ConfigModel(**dict(self.config))
133 # Create Builder for the PodSpec
134 pod_spec_builder = PodSpecV3Builder()
135 # Build Container
136 container_builder = ContainerV3Builder(self.app.name, image_info)
137 container_builder.add_port(name=self.app.name, port=PORT)
138 container_builder.add_http_readiness_probe(
139 "/-/ready",
140 PORT,
141 initial_delay_seconds=10,
142 timeout_seconds=30,
143 )
144 container_builder.add_http_liveness_probe(
145 "/-/healthy",
146 PORT,
147 initial_delay_seconds=30,
148 period_seconds=30,
149 )
150 command = [
151 "/bin/prometheus",
152 "--config.file=/etc/prometheus/prometheus.yml",
153 "--storage.tsdb.path=/prometheus",
154 "--web.console.libraries=/usr/share/prometheus/console_libraries",
155 "--web.console.templates=/usr/share/prometheus/consoles",
156 f"--web.route-prefix={config.web_subpath}",
157 f"--web.external-url=http://localhost:{PORT}{config.web_subpath}",
158 ]
159 if config.enable_web_admin_api:
160 command.append("--web.enable-admin-api")
161 container_builder.add_command(command)
162 container_builder.add_volume_config(
163 "config", "/etc/prometheus", self._build_files(config)
164 )
165 container = container_builder.build()
166 # Add container to pod spec
167 pod_spec_builder.add_container(container)
168 # Add ingress resources to pod spec if site url exists
169 if config.site_url:
170 parsed = urlparse(config.site_url)
171 annotations = {
172 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
173 str(config.max_file_size) + "m"
174 if config.max_file_size > 0
175 else config.max_file_size
176 ),
sousaedu2459af62021-01-15 16:50:26 +0000177 }
David Garcia49379ce2021-02-24 13:48:22 +0100178 ingress_resource_builder = IngressResourceV3Builder(
179 f"{self.app.name}-ingress", annotations
sousaedu2459af62021-01-15 16:50:26 +0000180 )
sousaedu2459af62021-01-15 16:50:26 +0000181
David Garcia49379ce2021-02-24 13:48:22 +0100182 if config.ingress_whitelist_source_range:
183 annotations[
184 "nginx.ingress.kubernetes.io/whitelist-source-range"
185 ] = config.ingress_whitelist_source_range
sousaedu2459af62021-01-15 16:50:26 +0000186
David Garcia49379ce2021-02-24 13:48:22 +0100187 if parsed.scheme == "https":
188 ingress_resource_builder.add_tls(
189 [parsed.hostname], config.tls_secret_name
190 )
191 else:
192 annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
193
194 ingress_resource_builder.add_rule(parsed.hostname, self.app.name, PORT)
195 ingress_resource = ingress_resource_builder.build()
196 pod_spec_builder.add_ingress_resource(ingress_resource)
197 return pod_spec_builder.build()
sousaedu2459af62021-01-15 16:50:26 +0000198
199
200if __name__ == "__main__":
201 main(PrometheusCharm)