20. Handle UnitTearingDown exception

During the instantiation of charm_refresh.Kubernetes or charm_refresh.Machines, UnitTearingDown will be raised when the unit (that is running the charm code) is tearing down.

This happens:

  • On a unit that is removed during scale down

  • During application removal

  • On subordinate charms when the relation with the principal charm is removed

When UnitTearingDown is raised, a refresh may be in progress.

Example charm.py
class PostgreSQLCharm(ops.CharmBase):
    def __init__(self, *args):
        # [...]

        try:
            self.refresh = charm_refresh.Machines(
                MachinesPostgreSQLRefresh(
                    workload_name="PostgreSQL",
                    charm_name="postgresql",
                )
            )
        except charm_refresh.PeerRelationNotReady:
            # [...]
        except charm_refresh.UnitTearingDown:
            (1)
            self.unit.status = ops.MaintenanceStatus("Tearing down")
            snap.uninstall()
            sys.exit() (2)
        # [...]
1 Gracefully shut down & clean up
2 This may be incompatible with your charm code or charm code dependencies that depend on executing code during specific Juju events. In those cases, a more complex approach may be needed