Skip to content

Commit

Permalink
Use on_error decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
mateoflorido committed Jan 30, 2024
1 parent 24b296a commit 8486a5f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 39 deletions.
72 changes: 34 additions & 38 deletions charms/k8s/src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import charms.contextual_status as status
import ops
from charms.contextual_status import WaitingStatus, on_error
from charms.k8s.v0.k8sd_api_manager import (
InvalidResponseError,
K8sdAPIManager,
Expand Down Expand Up @@ -53,58 +54,51 @@ def __init__(self, *args):
factory = UnixSocketConnectionFactory(unix_socket=K8SD_SNAP_SOCKET)
self.api_manager = K8sdAPIManager(factory)
self.snap_cache = SnapCache()

self.reconciler = Reconciler(self, self._reconcile)

self.framework.observe(self.on.update_status, self._on_update_status)

def _reconcile(self, _):
"""Reconcile state change events."""
try:
# TODO: Implement clustering using leader units.
self._install_k8s_snap()
self._apply_snap_requirements()
self._bootstrap_k8s_snap()
self._enable_components()
self._update_status()
except InvalidResponseError as e:
log.error("Invalid response from K8sd: %s", e)
status.add(ops.WaitingStatus("Waiting for K8sd API."))
except SnapError as e:
log.error("Failed to install k8s snap. Reason: %s", e.message)
status.add(ops.BlockedStatus("Failed to install k8s snap"))
except subprocess.CalledProcessError as e:
log.error("Failed to run subprocess: %s", e)
status.add(ops.WaitingStatus(""))
except K8sdConnectionError as e:
log.warning("Unable to contact K8sd API: %s", e)
status.add(ops.WaitingStatus("Waiting for K8sd API."))

# TODO: Implement clustering using leader units.
self._install_k8s_snap()
self._apply_snap_requirements()
self._bootstrap_k8s_snap()
self._enable_components()
self._update_status()

@on_error(WaitingStatus("Failed to apply snap requirements"), subprocess.CalledProcessError)
def _apply_snap_requirements(self):
"""Apply necessary snap requirements for the k8s snap.
This method executes necessary scripts to ensure that the snap
meets the network and interface requirements.
"""
self.unit.status = ops.MaintenanceStatus("Applying K8s requirements")
status.add(ops.MaintenanceStatus("Applying K8s requirements"))
commands = [
"/snap/k8s/current/k8s/connect-interfaces.sh",
"/snap/k8s/current/k8s/network-requirements.sh",
]
for c in commands:
subprocess.check_call(shlex.split(c))

@on_error(ops.WaitingStatus("Failed to bootstrap k8s snap"), subprocess.CalledProcessError)
def _bootstrap_k8s_snap(self):
"""Bootstrap the k8s if it's not already bootstrapped."""
if not self.api_manager.is_cluster_bootstrapped():
self.unit.status = ops.MaintenanceStatus("Bootstrapping Cluster")
status.add(ops.MaintenanceStatus("Bootstrapping Cluster"))
cmd = "k8s bootstrap"
subprocess.check_call(shlex.split(cmd), shell=False)
subprocess.check_call(shlex.split(cmd))

@on_error(
WaitingStatus("Waiting for enable components"), InvalidResponseError, K8sdConnectionError
)
def _enable_components(self):
"""Enable necessary components for the Kubernetes cluster."""
self.unit.status = ops.MaintenanceStatus("Enabling DNS")
status.add(ops.MaintenanceStatus("Enabling DNS"))
self.api_manager.enable_component("dns", True)
self.unit.status = ops.MaintenanceStatus("Enabling Network")
status.add(ops.MaintenanceStatus("Enabling Network"))
self.api_manager.enable_component("network", True)

def _get_snap_version(self) -> Optional[str]:
Expand All @@ -125,31 +119,33 @@ def _get_snap_version(self) -> Optional[str]:
log.info("Snap k8s not found or no version available.")
return None

@on_error(ops.BlockedStatus("Failed to install k8s snap."), SnapError)
def _install_k8s_snap(self):
"""Install the k8s snap package."""
self.unit.status = ops.MaintenanceStatus("Installing k8s snap")
status.add(ops.MaintenanceStatus("Installing k8s snap"))
k8s_snap = self.snap_cache["k8s"]
if not k8s_snap.present:
channel = self.config["channel"]
k8s_snap.ensure(SnapState.Latest, channel=channel)

@on_error(
ops.WaitingStatus("Failed to update status"),
subprocess.CalledProcessError,
InvalidResponseError,
K8sdConnectionError,
)
def _update_status(self):
"""Check k8s snap status."""
try:
if self.api_manager.is_cluster_ready():
if version := self._get_snap_version():
self.unit.set_workload_version(version)
else:
status.add(ops.WaitingStatus("Waiting for k8s to be ready."))
except InvalidResponseError:
log.info("Invalid Response from K8sd...")
status.add(ops.WaitingStatus("Waiting for K8s to be ready"))
except K8sdConnectionError:
log.exception("Unable to contact K8sdAPI")
status.add(ops.WaitingStatus("Waiting for K8sd API"))
if self.api_manager.is_cluster_ready():
if version := self._get_snap_version():
self.unit.set_workload_version(version)
else:
status.add(ops.WaitingStatus("Waiting for k8s to be ready."))

def _on_update_status(self, _):
"""Handle update-status event."""
if not self.reconciler.stored.reconciled:
return
with status.context(self.unit):
self._update_status()

Expand Down
2 changes: 1 addition & 1 deletion charms/k8s/tests/unit/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ def test_config_changed_invalid(harness):

def test_update_status(harness):
harness.charm.on.update_status.emit()
assert harness.model.unit.status == ops.WaitingStatus("Waiting for K8sd API")
assert harness.model.unit.status == ops.BlockedStatus("Failed to install k8s snap.")

0 comments on commit 8486a5f

Please sign in to comment.