Skip to content

Commit cfd2894

Browse files
committed
fix(pro): detach machines from Ubuntu Pro before removing the charm
`sunbeam disable pro` removed the ubuntu-pro application, but the machines stayed attached to the Pro subscription and kept using seats. The charm only detaches a machine in config-changed, when its token goes from set to empty. Its stop, remove and juju-info relation hooks do nothing, so removing the application (which a single terraform apply with token="" does, because the resource count depends on the token) leaves every machine attached. Add a DetachUbuntuProStep that runs before the terraform removal. It empties the token through Juju and waits until every ubuntu-pro unit reports Blocked "No token configured". The application name and the token key are the same for the legacy ubuntu-advantage charm, so this also works on clusters deployed with it. If a unit does not detach within the timeout, disable fails and keeps the application, naming the units and the manual `pro detach` fallback. Running disable again is safe. Add JujuHelper.wait_subordinate_units_status. The existing waits only check a subordinate's application status, which turns blocked as soon as one unit does, so they cannot tell when all machines have detached. If disable fails after the detach, the token is empty in Juju but Terraform state still holds the old one: the provider only reads back non-default config values, and the charm's token default is "". A later `enable pro` with the same token would then change nothing. The enable step now compares the live token after the apply, sets it again if it differs and waits for the units to become active. Jira: OPEN-4916 Assisted-By: Claude Code (Claude Opus 5.5) Related-Bug: #2158218 Signed-off-by: Vítor Zeni <vitor.zeni@bairesdev.com>
1 parent 3d22886 commit cfd2894

4 files changed

Lines changed: 487 additions & 4 deletions

File tree

‎sunbeam-python/sunbeam/core/juju.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1593,6 +1593,92 @@ def _wait_until_status(status: "jubilant.statustypes.Status"):
15931593
timeout=timeout,
15941594
)
15951595

1596+
@staticmethod
1597+
def _pending_subordinate_units(
1598+
status: "jubilant.statustypes.Status",
1599+
principal_app: str,
1600+
subordinate_app: str,
1601+
expected_status: Collection[str],
1602+
expected_workload_status_message: Collection[str] | None = None,
1603+
) -> dict[str, str]:
1604+
"""Return the subordinate units not yet in the expected workload status.
1605+
1606+
Subordinate units are listed under their principal unit, not under
1607+
the subordinate application, so they are collected from there.
1608+
1609+
:return: Mapping of unit name to its current "status: message".
1610+
"""
1611+
principal = status.apps.get(principal_app)
1612+
if principal is None:
1613+
return {}
1614+
1615+
pending: dict[str, str] = {}
1616+
for unit in principal.units.values():
1617+
for name, sub in unit.subordinates.items():
1618+
if not name.startswith(f"{subordinate_app}/"):
1619+
continue
1620+
current = sub.workload_status.current
1621+
message = sub.workload_status.message
1622+
if current not in expected_status or (
1623+
expected_workload_status_message is not None
1624+
and message not in expected_workload_status_message
1625+
):
1626+
pending[name] = f"{current}: {message}" if message else current
1627+
return pending
1628+
1629+
def wait_subordinate_units_status(
1630+
self,
1631+
model: str,
1632+
principal_app: str,
1633+
subordinate_app: str,
1634+
status: list[str],
1635+
workload_status_message: list[str] | None = None,
1636+
timeout: int = 10 * 60,
1637+
) -> None:
1638+
"""Wait for every unit of a subordinate app to reach a workload status.
1639+
1640+
The status of a subordinate application only reflects the most severe
1641+
status among its units, so every subordinate unit is checked instead.
1642+
Principal units without the subordinate are not waited for.
1643+
1644+
:model: Name of the model.
1645+
:principal_app: Principal application the subordinate is related to.
1646+
:subordinate_app: Subordinate application to check the units of.
1647+
:status: Accepted workload status values.
1648+
:workload_status_message: Accepted workload status messages, any if None.
1649+
:timeout: Waiting timeout in seconds.
1650+
:raises TimeoutError: naming the units not in the expected status.
1651+
"""
1652+
last_pending: dict[str, str] = {}
1653+
1654+
def _ready(juju_status: "jubilant.statustypes.Status") -> bool:
1655+
nonlocal last_pending
1656+
last_pending = self._pending_subordinate_units(
1657+
juju_status,
1658+
principal_app,
1659+
subordinate_app,
1660+
status,
1661+
workload_status_message,
1662+
)
1663+
return not last_pending
1664+
1665+
LOG.debug(
1666+
"Waiting for %r units under %r to be %r with message %r",
1667+
subordinate_app,
1668+
principal_app,
1669+
status,
1670+
workload_status_message,
1671+
)
1672+
with self._model(model) as juju:
1673+
try:
1674+
self._wait(_ready, juju, delay=MODEL_DELAY, timeout=timeout)
1675+
except TimeoutError as e:
1676+
units = ", ".join(f"{u} ({s})" for u, s in sorted(last_pending.items()))
1677+
raise TimeoutError(
1678+
f"Timed out after {timeout} seconds waiting for {subordinate_app} "
1679+
f"units: {units or 'status unknown'}"
1680+
) from e
1681+
15961682
def is_k8s_model(self, model: str) -> bool:
15971683
"""Return True if the model is a k8s (CAAS) model.
15981684

‎sunbeam-python/sunbeam/features/pro/feature.py‎

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@
1616
from sunbeam.clusterd.client import Client
1717
from sunbeam.core.common import BaseStep, Result, ResultType, StepContext, run_plan
1818
from sunbeam.core.deployment import Deployment
19-
from sunbeam.core.juju import JujuException, JujuHelper, JujuStepHelper
19+
from sunbeam.core.juju import (
20+
ApplicationNotFoundException,
21+
JujuException,
22+
JujuHelper,
23+
JujuStepHelper,
24+
)
2025
from sunbeam.core.manifest import (
2126
FeatureConfig,
2227
Manifest,
@@ -42,6 +47,11 @@
4247
UBUNTU_PRO_CHANNEL = "latest/stable"
4348
APP_TIMEOUT = 300 # 5 minutes, managing the application should be fast
4449
UNIT_TIMEOUT = 1200 # 15 minutes, adding / removing units can take a long time
50+
PRINCIPAL_APPLICATION = "sunbeam-machine"
51+
# The charm runs `pro detach` when its token is emptied, and then reports
52+
# this message. Removing the application does not detach the machines.
53+
DETACHED_MESSAGE = "No token configured"
54+
DETACH_TIMEOUT = 600 # 10 minutes, one config-changed hook per machine
4555

4656

4757
class ProFeatureConfig(FeatureConfig):
@@ -99,6 +109,28 @@ def run(self, context: StepContext) -> Result:
99109
except (JujuException, TerraformException, TerraformStateLockedException) as e:
100110
return Result(ResultType.FAILED, str(e))
101111

112+
# Disable empties the token through Juju, outside Terraform. If disable
113+
# failed after that, Terraform state still holds the old token, so the
114+
# apply above changes nothing. Set the token again in that case.
115+
try:
116+
live_config = self.jhelper.get_app_config(APPLICATION, self.model)
117+
if live_config.get("token") != self.token:
118+
self.jhelper.set_app_config(
119+
APPLICATION, self.model, {"token": self.token}
120+
)
121+
# The units still report "No token configured" until the
122+
# charm runs, so wait for them to attach first.
123+
self.jhelper.wait_subordinate_units_status(
124+
self.model,
125+
PRINCIPAL_APPLICATION,
126+
APPLICATION,
127+
status=["active"],
128+
timeout=APP_TIMEOUT,
129+
)
130+
except (JujuException, TimeoutError) as e:
131+
LOG.debug("Failed to empty the %s token", APPLICATION)
132+
return Result(ResultType.FAILED, str(e))
133+
102134
# Note(gboutry): application is in state unknown when it's deployed
103135
# without units
104136
try:
@@ -128,6 +160,58 @@ def run(self, context: StepContext) -> Result:
128160
return Result(ResultType.COMPLETED)
129161

130162

163+
class DetachUbuntuProStep(BaseStep, JujuStepHelper):
164+
"""Detach the machines from Ubuntu Pro before the charm is removed.
165+
166+
The charm only detaches a machine when its token is emptied, so this
167+
must run before the application is removed.
168+
"""
169+
170+
def __init__(self, jhelper: JujuHelper, model: str):
171+
super().__init__(
172+
"Detach Ubuntu Pro", "Detaching machines from Ubuntu Pro subscription"
173+
)
174+
self.jhelper = jhelper
175+
self.model = model
176+
177+
def is_skip(self, context: StepContext) -> Result:
178+
"""Skip when the application is not deployed."""
179+
try:
180+
self.jhelper.get_application(APPLICATION, self.model)
181+
except ApplicationNotFoundException:
182+
LOG.debug("%s is not deployed, nothing to detach", APPLICATION)
183+
return Result(ResultType.SKIPPED)
184+
return Result(ResultType.COMPLETED)
185+
186+
def run(self, context: StepContext) -> Result:
187+
"""Empty the token and wait for every unit to detach."""
188+
try:
189+
self.jhelper.set_app_config(APPLICATION, self.model, {"token": ""})
190+
except ApplicationNotFoundException:
191+
return Result(ResultType.COMPLETED)
192+
except JujuException as e:
193+
return Result(ResultType.FAILED, str(e))
194+
195+
try:
196+
self.jhelper.wait_subordinate_units_status(
197+
self.model,
198+
PRINCIPAL_APPLICATION,
199+
APPLICATION,
200+
status=["blocked"],
201+
workload_status_message=[DETACHED_MESSAGE],
202+
timeout=DETACH_TIMEOUT,
203+
)
204+
except TimeoutError as e:
205+
return Result(
206+
ResultType.FAILED,
207+
f"{e}. {APPLICATION} was not removed. Run 'sunbeam disable pro' "
208+
"again, or run 'sudo pro detach --assume-yes' on the machines "
209+
"listed.",
210+
)
211+
212+
return Result(ResultType.COMPLETED)
213+
214+
131215
class DisableUbuntuProApplicationStep(BaseStep, JujuStepHelper):
132216
"""Disable Ubuntu Pro application using Terraform."""
133217

@@ -246,6 +330,7 @@ def run_disable_plans(self, deployment: Deployment, show_hints: bool):
246330
jhelper = JujuHelper(deployment.juju_controller)
247331
plan = [
248332
TerraformInitStep(tfhelper),
333+
DetachUbuntuProStep(jhelper, deployment.openstack_machines_model),
249334
DisableUbuntuProApplicationStep(
250335
deployment.get_client(),
251336
tfhelper,

‎sunbeam-python/tests/unit/sunbeam/core/test_juju.py‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1433,3 +1433,169 @@ def test_snapshot_workload_status_mixed_present_and_absent(jhelper, status):
14331433
status.apps["present"] = app_mock
14341434
result = jhelper.snapshot_workload_status("test-model", ["present", "absent"])
14351435
assert result == {"present": "active"}
1436+
1437+
1438+
def _machine_app(charm: str, **extra) -> dict:
1439+
"""Minimal machine-model application status, as `juju status` reports it."""
1440+
return {
1441+
"charm": charm,
1442+
"charm-origin": "charmhub",
1443+
"charm-name": charm,
1444+
"charm-rev": 1,
1445+
"exposed": False,
1446+
**extra,
1447+
}
1448+
1449+
1450+
def _machine_status(subordinates_by_principal: dict) -> jubilant.statustypes.Status:
1451+
"""Build a status where sunbeam-machine units carry ubuntu-pro subordinates.
1452+
1453+
:subordinates_by_principal: principal unit -> {sub unit: (status, message)}
1454+
"""
1455+
units = {
1456+
principal: {
1457+
"machine": str(i),
1458+
"subordinates": {
1459+
name: {"workload-status": {"current": current, "message": message}}
1460+
for name, (current, message) in subs.items()
1461+
},
1462+
}
1463+
for i, (principal, subs) in enumerate(subordinates_by_principal.items())
1464+
}
1465+
return jubilant.statustypes.Status._from_dict(
1466+
{
1467+
"model": {
1468+
"name": "test-model",
1469+
"controller": "test-controller",
1470+
"cloud": "localhost",
1471+
"version": "3.6.29",
1472+
"type": "iaas",
1473+
"model-status": {},
1474+
},
1475+
"machines": {},
1476+
"applications": {
1477+
"sunbeam-machine": _machine_app("sunbeam-machine", units=units),
1478+
"ubuntu-pro": _machine_app(
1479+
"ubuntu-pro", **{"subordinate-to": ["sunbeam-machine"]}
1480+
),
1481+
},
1482+
}
1483+
)
1484+
1485+
1486+
DETACHED = ("blocked", "No token configured")
1487+
1488+
1489+
@pytest.mark.parametrize(
1490+
"subordinates, expected",
1491+
[
1492+
(
1493+
{
1494+
"sunbeam-machine/0": {"ubuntu-pro/0": DETACHED},
1495+
"sunbeam-machine/1": {"ubuntu-pro/1": DETACHED},
1496+
},
1497+
{},
1498+
),
1499+
(
1500+
{
1501+
"sunbeam-machine/0": {"ubuntu-pro/0": DETACHED},
1502+
"sunbeam-machine/1": {
1503+
"ubuntu-pro/1": ("active", "Attached (esm-infra)")
1504+
},
1505+
},
1506+
{"ubuntu-pro/1": "active: Attached (esm-infra)"},
1507+
),
1508+
(
1509+
# Blocked for another reason, e.g. a failed attach before the hook ran
1510+
{"sunbeam-machine/0": {"ubuntu-pro/0": ("blocked", "attach failed")}},
1511+
{"ubuntu-pro/0": "blocked: attach failed"},
1512+
),
1513+
(
1514+
# Other subordinates on the same machine are ignored
1515+
{
1516+
"sunbeam-machine/0": {
1517+
"ubuntu-pro/0": DETACHED,
1518+
"openstack-hypervisor/0": ("active", ""),
1519+
}
1520+
},
1521+
{},
1522+
),
1523+
(
1524+
# A machine without the subordinate has nothing to detach
1525+
{"sunbeam-machine/0": {}},
1526+
{},
1527+
),
1528+
],
1529+
)
1530+
def test_pending_subordinate_units(subordinates, expected):
1531+
status = _machine_status(subordinates)
1532+
1533+
pending = jujulib.JujuHelper._pending_subordinate_units(
1534+
status,
1535+
"sunbeam-machine",
1536+
"ubuntu-pro",
1537+
["blocked"],
1538+
["No token configured"],
1539+
)
1540+
1541+
assert pending == expected
1542+
1543+
1544+
def test_pending_subordinate_units_missing_principal():
1545+
status = _machine_status({})
1546+
status.apps.pop("sunbeam-machine")
1547+
1548+
assert (
1549+
jujulib.JujuHelper._pending_subordinate_units(
1550+
status, "sunbeam-machine", "ubuntu-pro", ["blocked"]
1551+
)
1552+
== {}
1553+
)
1554+
1555+
1556+
def test_wait_subordinate_units_status_ready(jhelper: jujulib.JujuHelper, juju):
1557+
status = _machine_status({"sunbeam-machine/0": {"ubuntu-pro/0": DETACHED}})
1558+
1559+
def _wait(ready, **kwargs):
1560+
assert ready(status)
1561+
1562+
juju.wait.side_effect = _wait
1563+
1564+
jhelper.wait_subordinate_units_status(
1565+
"test-model",
1566+
"sunbeam-machine",
1567+
"ubuntu-pro",
1568+
["blocked"],
1569+
["No token configured"],
1570+
timeout=60,
1571+
)
1572+
1573+
juju.wait.assert_called_once()
1574+
1575+
1576+
def test_wait_subordinate_units_status_timeout(jhelper: jujulib.JujuHelper, juju):
1577+
status = _machine_status(
1578+
{
1579+
"sunbeam-machine/0": {"ubuntu-pro/0": DETACHED},
1580+
"sunbeam-machine/1": {"ubuntu-pro/1": ("active", "Attached (esm-infra)")},
1581+
}
1582+
)
1583+
1584+
def _wait(ready, **kwargs):
1585+
assert not ready(status)
1586+
raise TimeoutError("jubilant timeout")
1587+
1588+
juju.wait.side_effect = _wait
1589+
1590+
with pytest.raises(TimeoutError) as exc:
1591+
jhelper.wait_subordinate_units_status(
1592+
"test-model",
1593+
"sunbeam-machine",
1594+
"ubuntu-pro",
1595+
["blocked"],
1596+
["No token configured"],
1597+
timeout=60,
1598+
)
1599+
1600+
assert "ubuntu-pro/1 (active: Attached (esm-infra))" in str(exc.value)
1601+
assert "ubuntu-pro/0" not in str(exc.value)

0 commit comments

Comments
 (0)