| David Garcia | 36c8772 | 2021-08-30 18:01:22 +0200 | [diff] [blame] | 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 | import logging |
| 26 | from typing import NoReturn |
| 27 | |
| 28 | |
| 29 | from ops.framework import EventBase |
| 30 | from ops.main import main |
| 31 | from opslib.osm.charm import CharmedOsmBase |
| 32 | from opslib.osm.interfaces.zookeeper import ZookeeperCluster, ZookeeperServer |
| 33 | from opslib.osm.pod import ContainerV3Builder, PodSpecV3Builder |
| 34 | from opslib.osm.validator import ModelValidator, validator |
| 35 | |
| 36 | logger = logging.getLogger(__name__) |
| 37 | |
| 38 | CLIENT_PORT = 2181 |
| 39 | SERVER_PORT = 2888 |
| 40 | LEADER_ELECTION_PORT = 3888 |
| 41 | |
| 42 | |
| 43 | class ConfigModel(ModelValidator): |
| 44 | log_level: str |
| 45 | image_pull_policy: str |
| 46 | min_session_timeout: int |
| 47 | max_session_timeout: int |
| 48 | purge_interval: int |
| 49 | snap_retain_count: int |
| 50 | max_client_cnxns: int |
| 51 | heap: int |
| 52 | sync_limit: int |
| 53 | init_limit: int |
| 54 | tick_time: int |
| sousaedu | 540d937 | 2021-09-29 01:53:30 +0100 | [diff] [blame] | 55 | security_context: bool |
| David Garcia | 36c8772 | 2021-08-30 18:01:22 +0200 | [diff] [blame] | 56 | |
| 57 | @validator("log_level") |
| 58 | def validate_log_level(cls, v): |
| 59 | if v not in {"INFO", "DEBUG"}: |
| 60 | raise ValueError("value must be INFO or DEBUG") |
| 61 | return v |
| 62 | |
| 63 | @validator("image_pull_policy") |
| 64 | def validate_image_pull_policy(cls, v): |
| 65 | values = { |
| 66 | "always": "Always", |
| 67 | "ifnotpresent": "IfNotPresent", |
| 68 | "never": "Never", |
| 69 | } |
| 70 | v = v.lower() |
| 71 | if v not in values.keys(): |
| 72 | raise ValueError("value must be always, ifnotpresent or never") |
| 73 | return values[v] |
| 74 | |
| 75 | |
| 76 | class ZookeeperCharm(CharmedOsmBase): |
| 77 | """Zookeeper Charm.""" |
| 78 | |
| 79 | def __init__(self, *args) -> NoReturn: |
| 80 | """Zookeeper Charm constructor.""" |
| 81 | super().__init__(*args, oci_image="image") |
| 82 | # Initialize Zookeeper cluster relation |
| 83 | self.zookeeper_cluster = ZookeeperCluster(self, "cluster", CLIENT_PORT) |
| 84 | self.framework.observe(self.on["cluster"].relation_changed, self._setup_cluster) |
| 85 | # Initialize Zookeeper relation |
| 86 | self.zookeeper_server = ZookeeperServer(self, "zookeeper") |
| 87 | self.framework.observe(self.on["zookeeper"].relation_joined, self._publish_info) |
| 88 | |
| 89 | @property |
| 90 | def num_units(self): |
| 91 | return self.zookeeper_cluster.num_units |
| 92 | |
| 93 | @property |
| 94 | def zookeeper_uri(self): |
| 95 | return self.zookeeper_cluster.zookeeper_uri |
| 96 | |
| 97 | def _setup_cluster(self, event: EventBase): |
| 98 | """Publishes Zookeeper information and reconfigures the pod. |
| 99 | |
| 100 | Args: |
| 101 | event (EventBase): Zookeeper Cluster relation event. |
| 102 | """ |
| sousaedu | 540d937 | 2021-09-29 01:53:30 +0100 | [diff] [blame] | 103 | self._publish_info(event) |
| David Garcia | 36c8772 | 2021-08-30 18:01:22 +0200 | [diff] [blame] | 104 | self.configure_pod() |
| 105 | |
| 106 | def _publish_info(self, event: EventBase): |
| 107 | """Publishes Zookeeper information. |
| 108 | |
| 109 | Args: |
| 110 | event (EventBase): Zookeeper relation event. |
| 111 | """ |
| 112 | if self.unit.is_leader(): |
| 113 | zk_uri = self.zookeeper_uri |
| 114 | if zk_uri: |
| 115 | self.zookeeper_server.publish_info(zk_uri) |
| 116 | else: |
| 117 | event.defer() |
| 118 | |
| 119 | def build_pod_spec(self, image_info): |
| 120 | # Validate config |
| 121 | config = ConfigModel(**dict(self.config)) |
| 122 | |
| 123 | # Create Builder for the PodSpec |
| sousaedu | 540d937 | 2021-09-29 01:53:30 +0100 | [diff] [blame] | 124 | pod_spec_builder = PodSpecV3Builder( |
| 125 | enable_security_context=config.security_context |
| 126 | ) |
| David Garcia | 36c8772 | 2021-08-30 18:01:22 +0200 | [diff] [blame] | 127 | |
| 128 | # Build Container |
| 129 | container_builder = ContainerV3Builder( |
| sousaedu | 540d937 | 2021-09-29 01:53:30 +0100 | [diff] [blame] | 130 | self.app.name, |
| 131 | image_info, |
| 132 | config.image_pull_policy, |
| 133 | run_as_non_root=config.security_context, |
| David Garcia | 36c8772 | 2021-08-30 18:01:22 +0200 | [diff] [blame] | 134 | ) |
| 135 | |
| 136 | container_builder.add_port(name="client", port=CLIENT_PORT) |
| 137 | container_builder.add_port(name="server", port=SERVER_PORT) |
| 138 | container_builder.add_port(name="leader-election", port=LEADER_ELECTION_PORT) |
| 139 | container_builder.add_tcpsocket_readiness_probe( |
| 140 | CLIENT_PORT, |
| 141 | initial_delay_seconds=10, |
| 142 | timeout_seconds=5, |
| 143 | failure_threshold=6, |
| 144 | success_threshold=1, |
| 145 | ) |
| 146 | container_builder.add_tcpsocket_liveness_probe( |
| 147 | CLIENT_PORT, initial_delay_seconds=20 |
| 148 | ) |
| 149 | container_builder.add_command( |
| 150 | [ |
| 151 | "sh", |
| 152 | "-c", |
| 153 | " ".join( |
| 154 | [ |
| 155 | "start-zookeeper", |
| 156 | f"--servers={self.num_units}", |
| 157 | "--data_dir=/var/lib/zookeeper/data", |
| 158 | "--data_log_dir=/var/lib/zookeeper/data/log", |
| 159 | "--conf_dir=/opt/zookeeper/conf", |
| 160 | f"--client_port={CLIENT_PORT}", |
| 161 | f"--election_port={LEADER_ELECTION_PORT}", |
| 162 | f"--server_port={SERVER_PORT}", |
| 163 | f"--tick_time={config.tick_time}", |
| 164 | f"--init_limit={config.init_limit}", |
| 165 | f"--sync_limit={config.sync_limit}", |
| 166 | f"--heap={config.heap}M", |
| 167 | f"--max_client_cnxns={config.max_client_cnxns}", |
| 168 | f"--snap_retain_count={config.snap_retain_count}", |
| 169 | f"--purge_interval={config.purge_interval}", |
| 170 | f"--max_session_timeout={config.max_session_timeout}", |
| 171 | f"--min_session_timeout={config.min_session_timeout}", |
| 172 | f"--log_level={config.log_level}", |
| 173 | ] |
| 174 | ), |
| 175 | ] |
| 176 | ) |
| 177 | |
| 178 | container = container_builder.build() |
| 179 | |
| 180 | # Add container to pod spec |
| 181 | pod_spec_builder.add_container(container) |
| 182 | |
| 183 | return pod_spec_builder.build() |
| 184 | |
| 185 | |
| 186 | if __name__ == "__main__": |
| 187 | main(ZookeeperCharm) |