blob: 3dcb5d412cfef1d4f8c979ea4cad4c9f7cd543c8 [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
David Garcia49379ce2021-02-24 13:48:22 +010025from ipaddress import ip_network
David Garciac753dc52021-03-17 15:28:47 +010026import logging
27from typing import NoReturn, Optional
28from urllib.parse import urlparse
sousaedu2459af62021-01-15 16:50:26 +000029
sousaedu1ec36cc2021-03-03 01:12:49 +010030from oci_image import OCIImageResource
David Garcia49379ce2021-02-24 13:48:22 +010031from ops.framework import EventBase
sousaedu2459af62021-01-15 16:50:26 +000032from ops.main import main
David Garcia49379ce2021-02-24 13:48:22 +010033from opslib.osm.charm import CharmedOsmBase
David Garciac753dc52021-03-17 15:28:47 +010034from opslib.osm.interfaces.prometheus import PrometheusServer
David Garcia49379ce2021-02-24 13:48:22 +010035from opslib.osm.pod import (
David Garcia49379ce2021-02-24 13:48:22 +010036 ContainerV3Builder,
David Garciac753dc52021-03-17 15:28:47 +010037 FilesV3Builder,
38 IngressResourceV3Builder,
David Garcia49379ce2021-02-24 13:48:22 +010039 PodSpecV3Builder,
40)
David Garcia49379ce2021-02-24 13:48:22 +010041from opslib.osm.validator import (
42 ModelValidator,
43 validator,
44)
sousaedu1ec36cc2021-03-03 01:12:49 +010045import requests
David Garcia49379ce2021-02-24 13:48:22 +010046
sousaedu2459af62021-01-15 16:50:26 +000047
48logger = logging.getLogger(__name__)
49
David Garcia49379ce2021-02-24 13:48:22 +010050PORT = 9090
sousaedu2459af62021-01-15 16:50:26 +000051
52
David Garcia49379ce2021-02-24 13:48:22 +010053class ConfigModel(ModelValidator):
54 web_subpath: str
55 default_target: str
56 max_file_size: int
57 site_url: Optional[str]
sousaedu3cc03162021-04-29 16:53:12 +020058 cluster_issuer: Optional[str]
David Garciad68e0b42021-06-28 16:50:42 +020059 ingress_class: Optional[str]
David Garcia49379ce2021-02-24 13:48:22 +010060 ingress_whitelist_source_range: Optional[str]
61 tls_secret_name: Optional[str]
62 enable_web_admin_api: bool
sousaedu3ddbbd12021-08-24 19:57:24 +010063 image_pull_policy: Optional[str]
David Garcia49379ce2021-02-24 13:48:22 +010064
65 @validator("web_subpath")
66 def validate_web_subpath(cls, v):
67 if len(v) < 1:
68 raise ValueError("web-subpath must be a non-empty string")
69 return v
70
71 @validator("max_file_size")
72 def validate_max_file_size(cls, v):
73 if v < 0:
74 raise ValueError("value must be equal or greater than 0")
75 return v
76
77 @validator("site_url")
78 def validate_site_url(cls, v):
79 if v:
80 parsed = urlparse(v)
81 if not parsed.scheme.startswith("http"):
82 raise ValueError("value must start with http")
83 return v
84
85 @validator("ingress_whitelist_source_range")
86 def validate_ingress_whitelist_source_range(cls, v):
87 if v:
88 ip_network(v)
89 return v
sousaedu2459af62021-01-15 16:50:26 +000090
sousaedu3ddbbd12021-08-24 19:57:24 +010091 @validator("image_pull_policy")
92 def validate_image_pull_policy(cls, v):
93 values = {
94 "always": "Always",
95 "ifnotpresent": "IfNotPresent",
96 "never": "Never",
97 }
98 v = v.lower()
99 if v not in values.keys():
100 raise ValueError("value must be always, ifnotpresent or never")
101 return values[v]
102
sousaedu2459af62021-01-15 16:50:26 +0000103
David Garcia49379ce2021-02-24 13:48:22 +0100104class PrometheusCharm(CharmedOsmBase):
sousaedu2459af62021-01-15 16:50:26 +0000105
sousaedu2459af62021-01-15 16:50:26 +0000106 """Prometheus Charm."""
107
sousaedu2459af62021-01-15 16:50:26 +0000108 def __init__(self, *args) -> NoReturn:
109 """Prometheus Charm constructor."""
David Garcia49379ce2021-02-24 13:48:22 +0100110 super().__init__(*args, oci_image="image")
sousaedu2459af62021-01-15 16:50:26 +0000111
112 # Registering provided relation events
David Garcia49379ce2021-02-24 13:48:22 +0100113 self.prometheus = PrometheusServer(self, "prometheus")
sousaedu2459af62021-01-15 16:50:26 +0000114 self.framework.observe(
David Garcia49379ce2021-02-24 13:48:22 +0100115 self.on.prometheus_relation_joined, # pylint: disable=E1101
116 self._publish_prometheus_info,
sousaedu2459af62021-01-15 16:50:26 +0000117 )
118
sousaedu1ec36cc2021-03-03 01:12:49 +0100119 # Registering actions
120 self.framework.observe(
121 self.on.backup_action, # pylint: disable=E1101
122 self._on_backup_action,
123 )
124
sousaedu2459af62021-01-15 16:50:26 +0000125 def _publish_prometheus_info(self, event: EventBase) -> NoReturn:
David Garcia49379ce2021-02-24 13:48:22 +0100126 self.prometheus.publish_info(self.app.name, PORT)
sousaedu2459af62021-01-15 16:50:26 +0000127
sousaedu1ec36cc2021-03-03 01:12:49 +0100128 def _on_backup_action(self, event: EventBase) -> NoReturn:
sousaedub208a172021-05-13 14:30:25 +0200129 url = f"http://{self.model.app.name}:{PORT}/api/v1/admin/tsdb/snapshot"
sousaedu1ec36cc2021-03-03 01:12:49 +0100130 result = requests.post(url)
131
132 if result.status_code == 200:
133 event.set_results({"backup-name": result.json()["name"]})
134 else:
sousaedub208a172021-05-13 14:30:25 +0200135 event.fail(f"status-code: {result.status_code}")
sousaedu1ec36cc2021-03-03 01:12:49 +0100136
David Garcia49379ce2021-02-24 13:48:22 +0100137 def _build_files(self, config: ConfigModel):
138 files_builder = FilesV3Builder()
139 files_builder.add_file(
140 "prometheus.yml",
141 (
142 "global:\n"
143 " scrape_interval: 15s\n"
144 " evaluation_interval: 15s\n"
145 "alerting:\n"
146 " alertmanagers:\n"
147 " - static_configs:\n"
148 " - targets:\n"
149 "rule_files:\n"
150 "scrape_configs:\n"
151 " - job_name: 'prometheus'\n"
152 " static_configs:\n"
153 f" - targets: [{config.default_target}]\n"
154 ),
155 )
156 return files_builder.build()
157
158 def build_pod_spec(self, image_info):
159 # Validate config
160 config = ConfigModel(**dict(self.config))
161 # Create Builder for the PodSpec
162 pod_spec_builder = PodSpecV3Builder()
sousaedu1ec36cc2021-03-03 01:12:49 +0100163
164 # Build Backup Container
165 backup_image = OCIImageResource(self, "backup-image")
166 backup_image_info = backup_image.fetch()
167 backup_container_builder = ContainerV3Builder("prom-backup", backup_image_info)
168 backup_container = backup_container_builder.build()
169 # Add backup container to pod spec
170 pod_spec_builder.add_container(backup_container)
171
David Garcia49379ce2021-02-24 13:48:22 +0100172 # Build Container
sousaedu3ddbbd12021-08-24 19:57:24 +0100173 container_builder = ContainerV3Builder(
174 self.app.name, image_info, config.image_pull_policy
175 )
David Garcia49379ce2021-02-24 13:48:22 +0100176 container_builder.add_port(name=self.app.name, port=PORT)
177 container_builder.add_http_readiness_probe(
178 "/-/ready",
179 PORT,
180 initial_delay_seconds=10,
181 timeout_seconds=30,
182 )
183 container_builder.add_http_liveness_probe(
184 "/-/healthy",
185 PORT,
186 initial_delay_seconds=30,
187 period_seconds=30,
188 )
189 command = [
190 "/bin/prometheus",
191 "--config.file=/etc/prometheus/prometheus.yml",
192 "--storage.tsdb.path=/prometheus",
193 "--web.console.libraries=/usr/share/prometheus/console_libraries",
194 "--web.console.templates=/usr/share/prometheus/consoles",
195 f"--web.route-prefix={config.web_subpath}",
196 f"--web.external-url=http://localhost:{PORT}{config.web_subpath}",
197 ]
198 if config.enable_web_admin_api:
199 command.append("--web.enable-admin-api")
200 container_builder.add_command(command)
201 container_builder.add_volume_config(
202 "config", "/etc/prometheus", self._build_files(config)
203 )
204 container = container_builder.build()
205 # Add container to pod spec
206 pod_spec_builder.add_container(container)
207 # Add ingress resources to pod spec if site url exists
208 if config.site_url:
209 parsed = urlparse(config.site_url)
210 annotations = {
211 "nginx.ingress.kubernetes.io/proxy-body-size": "{}".format(
212 str(config.max_file_size) + "m"
213 if config.max_file_size > 0
214 else config.max_file_size
David Garciad68e0b42021-06-28 16:50:42 +0200215 )
sousaedu2459af62021-01-15 16:50:26 +0000216 }
David Garciad68e0b42021-06-28 16:50:42 +0200217 if config.ingress_class:
218 annotations["kubernetes.io/ingress.class"] = config.ingress_class
David Garcia49379ce2021-02-24 13:48:22 +0100219 ingress_resource_builder = IngressResourceV3Builder(
220 f"{self.app.name}-ingress", annotations
sousaedu2459af62021-01-15 16:50:26 +0000221 )
sousaedu2459af62021-01-15 16:50:26 +0000222
David Garcia49379ce2021-02-24 13:48:22 +0100223 if config.ingress_whitelist_source_range:
224 annotations[
225 "nginx.ingress.kubernetes.io/whitelist-source-range"
226 ] = config.ingress_whitelist_source_range
sousaedu2459af62021-01-15 16:50:26 +0000227
sousaedu3cc03162021-04-29 16:53:12 +0200228 if config.cluster_issuer:
229 annotations["cert-manager.io/cluster-issuer"] = config.cluster_issuer
230
David Garcia49379ce2021-02-24 13:48:22 +0100231 if parsed.scheme == "https":
232 ingress_resource_builder.add_tls(
233 [parsed.hostname], config.tls_secret_name
234 )
235 else:
236 annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
237
238 ingress_resource_builder.add_rule(parsed.hostname, self.app.name, PORT)
239 ingress_resource = ingress_resource_builder.build()
240 pod_spec_builder.add_ingress_resource(ingress_resource)
241 return pod_spec_builder.build()
sousaedu2459af62021-01-15 16:50:26 +0000242
243
244if __name__ == "__main__":
245 main(PrometheusCharm)