Skip to content

Commit b20eaf2

Browse files
Make install handler idempotent (#92)
Fixes #84 juju can call `install` twice (https://chat.charmhub.io/charmhub/pl/maxrc5tasin3bjsoxbt3st9o1w)
1 parent 02e897a commit b20eaf2

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/machine_charm.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def _read_only_endpoint(self) -> str:
6262
# =======================
6363

6464
def _on_install(self, _) -> None:
65-
snap.install(unit=self.unit)
65+
snap.install(unit=self.unit, model_uuid=self.model.uuid)
6666
self.unit.set_workload_version(self.get_workload(event=None).version)
6767

6868
def _on_remove(self, _) -> None:

src/snap.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,22 @@
2323
_UNIX_USERNAME = "snap_daemon"
2424

2525

26-
def install(*, unit: ops.Unit):
26+
def install(*, unit: ops.Unit, model_uuid: str):
2727
"""Install snap."""
28-
if _snap.present:
28+
installed_by_unit = pathlib.Path(
29+
"/var/snap", _SNAP_NAME, "common", "installed_by_mysql_router_charm_unit"
30+
)
31+
unique_unit_name = f"{model_uuid}_{unit.name}"
32+
# This charm can override/use an existing snap installation only if the snap was previously
33+
# installed by this charm.
34+
# Otherwise, the snap could be in use by another charm (e.g. MySQL Server charm, a different
35+
# MySQL Router charm).
36+
if _snap.present and not (
37+
installed_by_unit.exists() and installed_by_unit.read_text() == unique_unit_name
38+
):
39+
logger.debug(
40+
f"{installed_by_unit.exists() and installed_by_unit.read_text()=} {unique_unit_name=}"
41+
)
2942
logger.error(f"{_SNAP_NAME} snap already installed on machine. Installation aborted")
3043
raise Exception(f"Multiple {_SNAP_NAME} snap installs not supported on one machine")
3144
logger.debug(f"Installing {_SNAP_NAME=}, {_REVISION=}")
@@ -45,6 +58,8 @@ def _set_retry_status(_) -> None:
4558
):
4659
with attempt:
4760
_snap.ensure(state=snap_lib.SnapState.Present, revision=_REVISION)
61+
installed_by_unit.write_text(unique_unit_name)
62+
logger.debug(f"Wrote {unique_unit_name=} to {installed_by_unit.name=}")
4863
_snap.hold()
4964
logger.debug(f"Installed {_SNAP_NAME=}, {_REVISION=}")
5065

0 commit comments

Comments
 (0)