Skip to content
Open
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
80 changes: 59 additions & 21 deletions openstack_hypervisor/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,14 @@ def __init__(self, *args, **kwargs):
<secret ephemeral='no' private='no'>
<uuid>$uuid</uuid>
<usage type='ceph'>
<name>client.cinder-ceph secret</name>
<name>$usage</name>
</usage>
</secret>
""")

LEGACY_SECRET_USAGE = "client.cinder-ceph secret"
CEPH_ACCESS_USAGE_PREFIX = "ceph-access."

# As defined in the snap/snapcraft.yaml
MONITORING_SERVICES = [
"libvirt-exporter",
Expand Down Expand Up @@ -2257,10 +2260,12 @@ def _is_hw_virt_supported() -> bool:
return False


def _set_secret(conn, secret_uuid: str, secret_value: str) -> None:
def _set_secret(
conn, secret_uuid: str, secret_value: str, usage: str = LEGACY_SECRET_USAGE
) -> None:
"""Set the ceph access secret in libvirt."""
logging.info(f"Setting secret {secret_uuid}")
new_secret = conn.secretDefineXML(SECRET_XML.substitute(uuid=secret_uuid))
new_secret = conn.secretDefineXML(SECRET_XML.substitute(uuid=secret_uuid, usage=usage))
# nova assumes the secret is raw and always encodes it *1, so decode it
# before storing it.
# *1 https://opendev.org/openstack/nova/src/branch/stable/2023.1/nova/
Expand All @@ -2275,7 +2280,7 @@ def _get_libvirt():
return libvirt


def _ensure_secret(secret_uuid: str, secret_value: str) -> None:
def _ensure_secret(secret_uuid: str, secret_value: str, usage: str = LEGACY_SECRET_USAGE) -> None:
"""Ensure libvirt has the ceph access secret with the correct value."""
libvirt = _get_libvirt()
conn = libvirt.open("qemu:///system")
Expand All @@ -2292,35 +2297,68 @@ def _ensure_secret(secret_uuid: str, secret_value: str) -> None:
secret = None
else:
raise
# Secret is stored raw so encode it before comparison.
if secret == base64.b64encode(secret_value.encode()):
# Secret is stored decode fetched value before compare
if secret == base64.b64decode(secret_value):
logging.info(f"Secret {secret_uuid} has desired value.")
else:
logging.info(f"Secret {secret_uuid} has wrong value, replacing.")
secretobj.undefine()
_set_secret(conn, secret_uuid, secret_value)
_set_secret(conn, secret_uuid, secret_value, usage)
else:
logging.info(f"Secret {secret_uuid} not found, creating.")
_set_secret(conn, secret_uuid, secret_value)
_set_secret(conn, secret_uuid, secret_value, usage)


def _desired_ceph_secrets(snap: Snap) -> dict[str, tuple[str, str]]:
"""Libvirt secrets this host should have: {uuid: (key, usage)}."""
secrets: dict[str, tuple[str, str]] = {}
compute = snap.config.get_options("compute").as_dict().get("compute") or {}
if all(k in compute for k in ("rbd-secret-uuid", "rbd-key")):
secrets[compute["rbd-secret-uuid"]] = (
compute["rbd-key"],
LEGACY_SECRET_USAGE,
)
try:
backends = snap.config.get_options("ceph-access").as_dict().get("ceph-access") or {}
except UnknownConfigKey: # charm without multi-backend support
backends = {}
for app, creds in backends.items():
if creds and creds.get("uuid") and creds.get("key"):
secrets[creds["uuid"]] = (creds["key"], f"{CEPH_ACCESS_USAGE_PREFIX}{app}")
return secrets


def _prune_ceph_secrets(keep: set[str]) -> None:
"""Undefine per-backend secrets whose backend is gone."""
libvirt = _get_libvirt()
conn = libvirt.open("qemu:///system")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This opens libvirt even when the host has no Ceph settings. I injected an unavailable libvirt socket with an empty Ceph config. The previous implementation returned without opening the socket, while this path raised before the configure hook could reach Masakari or SR-IOV. Can we handle cleanup failure here so unrelated configuration can still proceed?

Configure hook order

for secret in conn.listAllSecrets():
if secret.usageType() != libvirt.VIR_SECRET_USAGE_TYPE_CEPH:
continue
if not (secret.usageID() or "").startswith(CEPH_ACCESS_USAGE_PREFIX):
continue
if secret.UUIDString() in keep:
continue
logging.info(f"Removing secret {secret.UUIDString()} ({secret.usageID()})")
secret.undefine()


def _configure_ceph(snap) -> None:
"""Configure ceph client.
"""Define one libvirt secret per backend and remove stale ones.

:param snap: the snap reference
:type snap: Snap
:return: None
A failing backend is logged and skipped so it cannot block the rest
of the configure hook.
"""
logging.info("Configuring ceph access")
context = (
snap.config.get_options(
"compute",
)
.as_dict()
.get("compute")
)
if all(k in context for k in ("rbd-key", "rbd-secret-uuid")):
_ensure_secret(context["rbd-secret-uuid"], context["rbd-key"])
libvirt = _get_libvirt()
desired = _desired_ceph_secrets(snap)
# Prune first, then add to handle same app getting new UUID
_prune_ceph_secrets(keep=set(desired))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a backend changes UUID, this removes the old secret before trying to define the replacement. I injected a failure in that second step: the old secret was already gone and configure returned normally. Could we preserve the old secret if the UUID change fails and add a regression test for that path?

for secret_uuid, (key, usage) in desired.items():
try:
_ensure_secret(secret_uuid, key, usage)
except libvirt.libvirtError:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If libvirt rejects the replacement, the old secret has already been undefined and this catch lets the configure hook succeed. I reproduced that with an injected libvirt error. Can we set the value in place when the UUID is unchanged and surface failed updates to the caller? A successful snap configuration change can otherwise leave the compute without the secret it needs. Secret replacement

logging.exception(f"Failed to configure libvirt secret {secret_uuid} ({usage})")


def _configure_networking(snap: Snap, ovs_cli: OVSCli, context: dict) -> None:
Expand Down
181 changes: 174 additions & 7 deletions tests/unit/test_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,21 +403,24 @@ def test_ensure_secret_new_secret(self, mocker):
mock_set_secret = mocker.patch.object(hooks, "_set_secret")
conn_mock.listSecrets.return_value = []
hooks._ensure_secret("uuid1", "secret")
mock_set_secret.assert_called_once_with(conn_mock, "uuid1", "secret")
mock_set_secret.assert_called_once_with(
conn_mock, "uuid1", "secret", hooks.LEGACY_SECRET_USAGE
)

def test_ensure_secret_secret_exists(self, mocker):
conn_mock = mocker.Mock()
mock_libvirt = mocker.Mock()
secret_mock = mocker.Mock()
secret_mock.value.return_value = b"c2VjcmV0"
secret_mock.value.return_value = b"secret"
mock_get_libvirt = mocker.patch.object(hooks, "_get_libvirt")
mock_get_libvirt.return_value = mock_libvirt
mock_libvirt.open.return_value = conn_mock
mock_set_secret = mocker.patch.object(hooks, "_set_secret")
conn_mock.listSecrets.return_value = ["uuid1"]
conn_mock.secretLookupByUUIDString.return_value = secret_mock
hooks._ensure_secret("uuid1", "secret")
hooks._ensure_secret("uuid1", "c2VjcmV0") # base64("secret")
assert not mock_set_secret.called
assert not secret_mock.undefine.called

def test_ensure_secret_secret_wrong_value(self, mocker):
conn_mock = mocker.Mock()
Expand All @@ -430,8 +433,10 @@ def test_ensure_secret_secret_wrong_value(self, mocker):
mock_set_secret = mocker.patch.object(hooks, "_set_secret")
conn_mock.listSecrets.return_value = ["uuid1"]
conn_mock.secretLookupByUUIDString.return_value = secret_mock
hooks._ensure_secret("uuid1", "secret")
mock_set_secret.assert_called_once_with(conn_mock, "uuid1", "secret")
hooks._ensure_secret("uuid1", "c2VjcmV0")
mock_set_secret.assert_called_once_with(
conn_mock, "uuid1", "c2VjcmV0", hooks.LEGACY_SECRET_USAGE
)

def test_ensure_secret_secret_missing_value(self, mocker):
class FakeError(Exception):
Expand All @@ -450,8 +455,10 @@ def get_error_code(self):
mock_set_secret = mocker.patch.object(hooks, "_set_secret")
conn_mock.listSecrets.return_value = ["uuid1"]
conn_mock.secretLookupByUUIDString.return_value = secret_mock
hooks._ensure_secret("uuid1", "secret")
mock_set_secret.assert_called_once_with(conn_mock, "uuid1", "secret")
hooks._ensure_secret("uuid1", "c2VjcmV0")
mock_set_secret.assert_called_once_with(
conn_mock, "uuid1", "c2VjcmV0", hooks.LEGACY_SECRET_USAGE
)

def test_detect_compute_flavors_no_rights(self, mocker, snap):
mocker.patch("pathlib.Path.read_text", mock.Mock(side_effect=PermissionError))
Expand Down Expand Up @@ -2037,3 +2044,163 @@ def test_falls_back_to_data_dir_when_no_old_revisions(self, snap, short_env):

dest = snap.paths.common / "var/lib/libvirt"
assert (dest / "nvram").is_dir()


class _Opts(dict):
def as_dict(self):
return dict(self)


def _config(snap, mocker, compute=None, ceph_access=None):
"""snap.config.get_options returning compute and (optionally) ceph-access."""

def get_options(*keys):
if keys == ("compute",):
return _Opts({"compute": compute or {}})
if keys == ("ceph-access",):
if ceph_access is None:
raise UnknownConfigKey("ceph-access")
return _Opts({"ceph-access": ceph_access})
raise AssertionError(f"unexpected keys {keys}")

mocker.patch.object(snap.config, "get_options", side_effect=get_options)


def _secret(mocker, uuid, usage, usage_type=5):
s = mocker.Mock()
s.UUIDString.return_value = uuid
s.usageID.return_value = usage
s.usageType.return_value = usage_type
return s


@pytest.fixture
def libvirt_mock(mocker):
lv = mocker.Mock()
lv.VIR_SECRET_USAGE_TYPE_CEPH = 5
lv.libvirtError = type("libvirtError", (Exception,), {})
mocker.patch.object(hooks, "_get_libvirt", return_value=lv)
lv.open.return_value.listAllSecrets.return_value = []
return lv


class TestCephSecrets:
def test_set_secret_usage_in_xml(self, mocker):
conn = mocker.Mock()
hooks._set_secret(conn, "u1", "c2VjcmV0", "ceph-access.ceph-a")
xml = conn.secretDefineXML.call_args.args[0]
assert "<name>ceph-access.ceph-a</name>" in xml

def test_desired_legacy_only(self, snap, mocker):
"""Old charm (no ceph-access key): only the legacy secret."""
_config(snap, mocker, compute={"rbd-secret-uuid": "u1", "rbd-key": "k1"})
assert hooks._desired_ceph_secrets(snap) == {"u1": ("k1", hooks.LEGACY_SECRET_USAGE)}

def test_desired_backends(self, snap, mocker):
_config(
snap,
mocker,
ceph_access={
"ceph-a": {"uuid": "u1", "key": "k1"},
"ceph-b": {"uuid": "u2", "key": "k2"},
},
)
assert hooks._desired_ceph_secrets(snap) == {
"u1": ("k1", "ceph-access.ceph-a"),
"u2": ("k2", "ceph-access.ceph-b"),
}

def test_desired_shared_uuid_defined_once(self, snap, mocker):
"""compute.rbd-* pointing at a backend's uuid: one entry, backend usage."""
_config(
snap,
mocker,
compute={"rbd-secret-uuid": "u1", "rbd-key": "k1"},
ceph_access={"ceph-a": {"uuid": "u1", "key": "k1"}},
)
assert hooks._desired_ceph_secrets(snap) == {"u1": ("k1", "ceph-access.ceph-a")}

def test_desired_skips_incomplete(self, snap, mocker):
_config(snap, mocker, ceph_access={"ceph-a": {"uuid": "u1"}})
assert hooks._desired_ceph_secrets(snap) == {}

def test_configure_defines_each_backend(self, snap, mocker, libvirt_mock):
_config(
snap,
mocker,
ceph_access={
"ceph-a": {"uuid": "u1", "key": "k1"},
"ceph-b": {"uuid": "u2", "key": "k2"},
},
)
ensure = mocker.patch.object(hooks, "_ensure_secret")
hooks._configure_ceph(snap)
ensure.assert_any_call("u1", "k1", "ceph-access.ceph-a")
ensure.assert_any_call("u2", "k2", "ceph-access.ceph-b")

def test_configure_continues_after_failure(self, snap, mocker, libvirt_mock):
"""One failing backend does not stop the others (P3)."""
_config(
snap,
mocker,
ceph_access={
"ceph-a": {"uuid": "u1", "key": "k1"},
"ceph-b": {"uuid": "u2", "key": "k2"},
},
)
ensure = mocker.patch.object(
hooks,
"_ensure_secret",
side_effect=[libvirt_mock.libvirtError("boom"), None],
)
hooks._configure_ceph(snap)
assert ensure.call_count == 2

def test_prune_removes_stale_backend(self, snap, mocker, libvirt_mock):
stale = _secret(mocker, "u-old", "ceph-access.ceph-old")
libvirt_mock.open.return_value.listAllSecrets.return_value = [stale]
_config(snap, mocker, ceph_access={"ceph-a": {"uuid": "u1", "key": "k1"}})
mocker.patch.object(hooks, "_ensure_secret")
hooks._configure_ceph(snap)
stale.undefine.assert_called_once()

def test_prune_keeps_foreign_and_legacy(self, snap, mocker, libvirt_mock):
"""Legacy-usage, non-ceph and other-named secrets are never removed."""
legacy = _secret(mocker, "u-leg", hooks.LEGACY_SECRET_USAGE)
other = _secret(mocker, "u-x", "client.someone secret")
volume = _secret(mocker, "u-v", "/var/lib/vol", usage_type=1)
libvirt_mock.open.return_value.listAllSecrets.return_value = [
legacy,
other,
volume,
]
_config(snap, mocker, ceph_access={})
mocker.patch.object(hooks, "_ensure_secret")
hooks._configure_ceph(snap)
for s in (legacy, other, volume):
s.undefine.assert_not_called()

def test_prune_keeps_uuid_still_used_by_compute(self, snap, mocker, libvirt_mock):
"""Backend removed but nova's fallback still points at it: kept."""
s = _secret(mocker, "u1", "ceph-access.ceph-a")
libvirt_mock.open.return_value.listAllSecrets.return_value = [s]
_config(
snap,
mocker,
compute={"rbd-secret-uuid": "u1", "rbd-key": "k1"},
ceph_access={},
)
mocker.patch.object(hooks, "_ensure_secret")
hooks._configure_ceph(snap)
s.undefine.assert_not_called()

def test_prune_before_define(self, snap, mocker, libvirt_mock):
"""Re-created backend (same app, new uuid): old secret goes first."""
old = _secret(mocker, "u-old", "ceph-access.ceph-a")
libvirt_mock.open.return_value.listAllSecrets.return_value = [old]
_config(snap, mocker, ceph_access={"ceph-a": {"uuid": "u-new", "key": "k"}})
order = []
old.undefine.side_effect = lambda: order.append("undefine")
mocker.patch.object(hooks, "_ensure_secret", side_effect=lambda *a: order.append("ensure"))
hooks._configure_ceph(snap)
assert order == ["undefine", "ensure"]
Loading