Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 112 additions & 2 deletions sunbeam-python/sunbeam/core/juju.py
Original file line number Diff line number Diff line change
Expand Up @@ -1010,20 +1010,26 @@ def get_app_config(self, app: str, model: str) -> Mapping:
if "not found" in e.stderr:
raise ApplicationNotFoundException(f"App {app!r} not found") from e
raise JujuException(
f"Failed to get config {config_value!r} from application {app!r}"
f"Failed to get config from application {app!r}"
) from e
return config_value

def set_app_config(self, app: str, model: str, config: dict) -> None:
"""Set charm config for an application.

The values are sent as YAML on stdin (`juju config <app> --file -`),
not as command-line arguments, so they don't show in the process
list or in jubilant's command log.

:app: Name of the application.
:model: Name of the model.
:config: Dictionary of config key-value pairs to set.
"""
with self._model(model) as juju:
try:
juju.config(app, config)
juju.cli(
"config", app, "--file", "-", stdin=yaml.safe_dump({app: config})
)
except jubilant.CLIError as e:
if "not found" in e.stderr:
raise ApplicationNotFoundException(f"App {app!r} not found") from e
Expand Down Expand Up @@ -1593,6 +1599,110 @@ def _wait_until_status(status: "jubilant.statustypes.Status"):
timeout=timeout,
)

@staticmethod
def _pending_subordinate_units(
status: "jubilant.statustypes.Status",
principal_app: str,
subordinate_app: str,
expected_status: Collection[str],
expected_workload_status_message: Collection[str] | None = None,
) -> dict[str, str]:
"""Return the subordinate units not yet in the expected workload status.

Subordinate units are listed under their principal unit, not under
the subordinate application, so they are collected from there. While
the subordinate is related to the principal, every principal unit
must have one; a principal unit without it is pending.

:return: Mapping of unit name to its current "status: message".
:raises JujuException: if the principal application is not in the status.
"""
subordinate = status.apps.get(subordinate_app)
if subordinate is None or principal_app not in subordinate.subordinate_to:
# Not deployed, or not related: there are no subordinate units.
return {}

principal = status.apps.get(principal_app)
if principal is None:
Comment thread
vsz-work marked this conversation as resolved.
Resolved
raise JujuException(
f"Application {principal_app!r} not found, cannot check the "
f"{subordinate_app!r} units"
)

pending: dict[str, str] = {}
for principal_name, unit in principal.units.items():
subs = {
name: sub
for name, sub in unit.subordinates.items()
if name.startswith(f"{subordinate_app}/")
}
if not subs:
pending[principal_name] = f"no {subordinate_app} unit"
for name, sub in subs.items():
current = sub.workload_status.current
message = sub.workload_status.message
if current not in expected_status or (
expected_workload_status_message is not None
and message not in expected_workload_status_message
):
pending[name] = f"{current}: {message}" if message else current
return pending

def wait_subordinate_units_status(
self,
model: str,
principal_app: str,
subordinate_app: str,
status: list[str],
workload_status_message: list[str] | None = None,
timeout: int = 10 * 60,
) -> None:
"""Wait for every unit of a subordinate app to reach a workload status.

The status of a subordinate application only reflects the most severe
status among its units, so every subordinate unit is checked instead.
While the subordinate is related to the principal, a principal unit
without the subordinate is waited for too.

:model: Name of the model.
:principal_app: Principal application the subordinate is related to.
:subordinate_app: Subordinate application to check the units of.
:status: Accepted workload status values.
:workload_status_message: Accepted workload status messages, any if None.
:timeout: Waiting timeout in seconds.
:raises TimeoutError: naming the units not in the expected status.
:raises JujuException: if the principal application is missing.
"""
last_pending: dict[str, str] = {}

def _ready(juju_status: "jubilant.statustypes.Status") -> bool:
nonlocal last_pending
last_pending = self._pending_subordinate_units(
juju_status,
principal_app,
subordinate_app,
status,
workload_status_message,
)
return not last_pending

LOG.debug(
"Waiting for %r units under %r to be %r with message %r",
subordinate_app,
principal_app,
status,
workload_status_message,
)
with self._model(model) as juju:
try:
self._wait(_ready, juju, delay=MODEL_DELAY, timeout=timeout)
except TimeoutError as e:
units = ", ".join(f"{u} ({s})" for u, s in sorted(last_pending.items()))
raise TimeoutError(
f"Timed out after {timeout} seconds waiting for {subordinate_app} "
f"units: {units or 'status unknown'}"
) from e

def is_k8s_model(self, model: str) -> bool:
"""Return True if the model is a k8s (CAAS) model.

Expand Down
90 changes: 89 additions & 1 deletion sunbeam-python/sunbeam/features/pro/feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@
from sunbeam.clusterd.client import Client
from sunbeam.core.common import BaseStep, Result, ResultType, StepContext, run_plan
from sunbeam.core.deployment import Deployment
from sunbeam.core.juju import JujuException, JujuHelper, JujuStepHelper
from sunbeam.core.juju import (
ApplicationNotFoundException,
JujuException,
JujuHelper,
JujuStepHelper,
)
from sunbeam.core.manifest import (
AddManifestStep,
CharmManifest,
Expand Down Expand Up @@ -44,6 +49,11 @@
UBUNTU_PRO_CHANNEL = "latest/stable"
APP_TIMEOUT = 300 # 5 minutes, managing the application should be fast
UNIT_TIMEOUT = 1200 # 15 minutes, adding / removing units can take a long time
PRINCIPAL_APPLICATION = "sunbeam-machine"
# The charm runs `pro detach` when its token is emptied, and then reports
# this message. Removing the application does not detach the machines.
DETACHED_MESSAGE = "No token configured"
Comment thread
hemanthnakkina marked this conversation as resolved.
Resolved
DETACH_TIMEOUT = 600 # 10 minutes, one config-changed hook per machine


class ProFeatureConfig(FeatureConfig):
Expand Down Expand Up @@ -101,6 +111,27 @@ def run(self, context: StepContext) -> Result:
except (JujuException, TerraformException, TerraformStateLockedException) as e:
return Result(ResultType.FAILED, str(e))

# Disable empties the token through Juju, outside Terraform. If disable
# failed after that, Terraform state still holds the old token, so the
# apply above changes nothing. Set the token again in that case.
try:
live_config = self.jhelper.get_app_config(APPLICATION, self.model)
if live_config.get("token") != self.token:
self.jhelper.set_app_config(
Comment thread
vsz-work marked this conversation as resolved.
Resolved
APPLICATION, self.model, {"token": self.token}
)
# The units still report "No token configured" until the
# charm runs, so wait for them to attach first.
self.jhelper.wait_subordinate_units_status(
self.model,
PRINCIPAL_APPLICATION,
APPLICATION,
status=["active"],
timeout=APP_TIMEOUT,
)
except (JujuException, TimeoutError) as e:
return Result(ResultType.FAILED, str(e))

# Note(gboutry): application is in state unknown when it's deployed
# without units
try:
Expand Down Expand Up @@ -130,6 +161,62 @@ def run(self, context: StepContext) -> Result:
return Result(ResultType.COMPLETED)


class DetachUbuntuProStep(BaseStep, JujuStepHelper):
"""Detach the machines from Ubuntu Pro before the charm is removed.

The charm only detaches a machine when its token is emptied, so this
must run before the application is removed.
"""

def __init__(self, jhelper: JujuHelper, model: str):
super().__init__(
"Detach Ubuntu Pro", "Detaching machines from Ubuntu Pro subscription"
)
self.jhelper = jhelper
self.model = model

def is_skip(self, context: StepContext) -> Result:
"""Skip when the application is not deployed."""
try:
self.jhelper.get_application(APPLICATION, self.model)
Comment thread
vsz-work marked this conversation as resolved.
Resolved
except ApplicationNotFoundException:
LOG.debug("%s is not deployed, nothing to detach", APPLICATION)
return Result(ResultType.SKIPPED)
except JujuException as e:
return Result(ResultType.FAILED, str(e))
return Result(ResultType.COMPLETED)

def run(self, context: StepContext) -> Result:
"""Empty the token and wait for every unit to detach."""
try:
self.jhelper.set_app_config(APPLICATION, self.model, {"token": ""})
Comment thread
hemanthnakkina marked this conversation as resolved.
Resolved
except ApplicationNotFoundException:
return Result(ResultType.COMPLETED)
except JujuException as e:
return Result(ResultType.FAILED, str(e))

try:
self.jhelper.wait_subordinate_units_status(
Comment thread
vsz-work marked this conversation as resolved.
Resolved
self.model,
PRINCIPAL_APPLICATION,
APPLICATION,
status=["blocked"],
workload_status_message=[DETACHED_MESSAGE],
timeout=DETACH_TIMEOUT,
)
except TimeoutError as e:
return Result(
ResultType.FAILED,
f"{e}. {APPLICATION} was not removed. Run 'sunbeam disable pro' "
"again, or run 'sudo pro detach --assume-yes' on the machines "
"listed.",
)
except JujuException as e:
return Result(ResultType.FAILED, str(e))

return Result(ResultType.COMPLETED)


class DisableUbuntuProApplicationStep(BaseStep, JujuStepHelper):
"""Disable Ubuntu Pro application using Terraform."""

Expand Down Expand Up @@ -270,6 +357,7 @@ def run_disable_plans(self, deployment: Deployment, show_hints: bool):
jhelper = JujuHelper(deployment.juju_controller)
plan = [
TerraformInitStep(tfhelper),
DetachUbuntuProStep(jhelper, deployment.openstack_machines_model),
DisableUbuntuProApplicationStep(
deployment.get_client(),
tfhelper,
Expand Down
Loading
Loading