Hooks: how they work
the shared mechanism for users for app developers for Ubuntu Core developers for snapd developers for administrators
A snap is a read-only image and snapd does the generic work of each operation so a snap that must check a setting or migrate its data or react to a connection ships a hook. A hook is an executable under a name snapd knows. snapd runs it at a set moment of a change, almost always as a run-hook task under its own confinement profile and one hook per snap at a time. A failing hook fails its task and undoes the change unless snapd ignores that hook's errors and a hook may run again after snapd restarts.
On the map: hooks district
01 Why a snap needs hooks
A snap's files are read-only and snapd does the generic work of each operation. A hook is an executable inside the snap whose name snapd knows; snapd runs it at a fixed point of a change, so the snap can check a setting, migrate its data or react to a connection.
Acme-agent reaches the gateway as a read-only image. Snapd mounts it, connects its plugs and starts its daemon, all without the snap's help. But some steps only the snap can take. Is the interval you just set a sensible value? Revision 42 stores its data differently, so who moves the old data over? And what should the agent do when a plug is connected? Snapd can't know. So the snap ships small programs under names snapd knows, and snapd runs each one at its moment, as a step of the change. Those are hooks: twenty-one names in four groups, and four more for components.
02 Three places make a hook type for snapd developers
Pattern, handler, task. Exactly one handler may match a hook name. gate-auto-refresh is still accepted in a snap, but snapd creates no task for it and registers no handler, so a leftover task from an older snapd completes without running the script.
Adding a hook type to snapd? Three places have to agree. First, the name needs a pattern in supportedHooks, or snapd drops the file from the snap without a word. Second, exactly one handler registered with the hook manager must match the name. With none, an optional task quietly does nothing, and a required one fails with an internal error. Third, the owning manager creates the run-hook task and picks its flags: optional, ignore error, a timeout, an undo hook. gate-auto-refresh lost its handler: the pattern stays, and a shipped script doesn't run. And snapstate gets its hook tasks through function variables that hookstate sets.
03 snapd checks the shape of a name, not its meaning for app developers for snapd developers
Unknown names are skipped without an error, and a plug or slot name in a parametric hook is not checked against snap.yaml. Check the spelling: post-refresh, and the plug's own name after connect-plug-. A component's explicit hook with an unknown name fails with unsupported component hook.
You've packed acme-agent with its hooks and installed it, and one of them doesn't run. Why? Snapd keeps a hook file only if its name matches a known pattern. Configure runs on snap set. Connect-plug-network runs when the plug named network is connected. But post_refresh, or configure.sh, match nothing, so snapd skips them, even when they're declared in snap.yaml. For names with a plug in them, snapd checks only the shape: connect-plug-networks installs fine, and no connection produces that name. Snap pack and snap install say nothing. What is checked: every file in meta/hooks must be executable, and components can't declare unknown hooks.
04 A plug listed under a hook leaves the apps for app developers for snapd developers
hooks: remove: plugs: [network] binds network to the remove hook and to apps that list it, and no longer to every app and hook. A plug name that is not declared under plugs: becomes an implicit plug whose interface is that name.
Acme-agent declares the network plug once, at the top of snap.yaml. A plug like that is unscoped: it's bound to every app and every hook, so the agent daemon can reach its server. Now the remove hook should tell the server the gateway is leaving, so you list network under it. Listing a plug scopes it. It's bound to the remove hook and to apps that list it by name. The agent lists nothing, so it loses network, and so does the configure hook. So list network under the agent too. And a name under a hook that isn't declared at all becomes a new plug of that interface.
05 From a task to a confined process for app developers for Ubuntu Core developers for snapd developers for administrators
snap run --hook=<name> <snap> reproduces the process by hand, but without the per-run cookie, so snapctl inside it has no context. A successful hook's output is discarded: echo is visible only when the hook fails.
You type snap set acme-agent interval=5. What starts the configure hook? The change gets a run-hook task naming the snap and the hook. Snapd turns that into a snap run --hook command, in its own process group. The revision is left unset, so the current one runs, and a fresh cookie in SNAP_COOKIE lets snapctl find its way back. snap-confine applies the hook's own profile. snap-exec adds the environment and command-chain, then runs the file as root. Output goes into a buffer that keeps only the tail. On success it's thrown away; on failure it becomes the task's error.
06 One hook per snap at a time for app developers for snapd developers for administrators
snapd serialises hook tasks per snap instance, not per change, so a hook task does not overlap another hook task of the same snap; fde-setup and prepare-serial-request run without a task and are outside this rule. The order between independent chains is not fixed. The certs provider is an example.
You remove acme-agent, which has three connections, each with a disconnect hook. Auto-disconnect adds one chain of tasks per connection, with no order between them. So could two of the agent's hooks run at once? No. The hook manager runs one hook task per snap at a time. While disconnect-plug-network runs, the other two wait their turn, in either order. The certs provider has a disconnect-slot hook too, but it belongs to another snap, so it can run alongside. Component hooks share their snap's turn, and each parallel instance is a snap of its own. Hooks also wait while the snap's base is unlinked, say during a base refresh.
07 A failing hook fails the change, unless snapd ignores it
A failing hook fails snap install, snap refresh, snap set or snap connect, and the change is undone. snap remove and snap disconnect complete even when the snap's hook fails. Only the tail of the output is kept: 100 lines or 10 KiB.
Say acme-agent's install hook can't find something it needs and exits with an error. Snap install stops and prints the end of what the hook wrote. Then the change undoes what it had done, so the snap isn't installed, and whatever the hook set through snapctl is dropped. Some hooks can't stop their operation, though. The remove hook, the disconnect hooks during snap disconnect and snap remove, the hooks that undo a connection, and confdb observers all run with errors ignored. Their failure shows only as ignoring failure in hook, in the change's log. And a hook that runs out of time fails like one that exits with an error.
08 A hook may run twice for app developers for Ubuntu Core developers for snapd developers for administrators
Hooks run again only across a snapd stop or a pending restart, not after a failure. Make every hook idempotent.
Acme-agent's post-refresh hook is halfway through when snapd itself stops, for its own refresh or a reboot. What happens to the hook? Snapd waits for running hooks, up to the default hook timeout of ten minutes, then stops them. The task runner treats that as a retry, so the task goes back to Do. When snapd starts again, the hook runs again, from its first line. A hook that fails isn't run again; its change fails. A hook that would start while a restart is pending waits, then runs. So write hooks that give the same result twice: set a value with snapctl, don't append to a file.
09 Where to go from here
Roads: the four hook groups, snapctl, the overlord, confinement and packaging.
That's the machinery every hook shares. Each group of hooks has a deck of its own, showing where its hooks sit among the tasks of a change: install and refresh, device setup, interface hooks, and the confdb hooks. The snapctl deck covers what a hook calls back into, and the time limits it runs under. The overlord explains changes and tasks. Confinement covers the profile a hook runs under. And snap packaging shows how the hooks get into the snap in the first place.
Read more
What you see of hooks
Hook tasks appear in snap changes, snap change <id> and snap tasks <id> under these summaries:
| Summary | Hook |
|---|---|
Run install hook of "<snap>" snap if present | install |
Run pre-refresh hook of "<snap>" snap if present | pre-refresh |
Run post-refresh hook of "<snap>" snap if present | post-refresh |
Run remove hook of "<snap>" snap if present | remove |
Run configure hook of "<snap>" snap, or ... if present during install and refresh | configure |
Run default-configure hook of "<snap>" snap if present | default-configure |
Run health check of "<snap>" snap | check-health |
Run prepare-device hook, Run install-device hook | the gadget's device hooks |
Run hook <name> of snap "<snap>" | interface and confdb hooks |
A task whose hook the snap does not ship completes without running anything; the words "if present" mark those tasks.
Messages
| Message | Meaning |
|---|---|
run hook "<name>": <output> | the hook exited with an error; the output is the tail that was kept, framed by ----- lines when it has several |
ignoring failure in hook "<name>": <error> | a hook whose errors are ignored failed; the change goes on. Also logged to the journal |
<exceeded maximum runtime of <duration>> | appended to the output when the time limit killed the hook |
<aborted> | appended when the change was aborted while the hook ran |
snap "<snap>" has no "configure" hook | snap set on a snap that ships no configure hook |
The output buffer keeps the last 100 lines or 10 KiB. A hook that succeeds leaves no output anywhere: use snapctl or a file in $SNAP_COMMON to leave a trace.
for app developers for Ubuntu Core developers for snapd developers for administrators
The process a hook runs in
| Item | Value |
|---|---|
| Command | snap run --hook <name> -r <revision> <snap>, or <snap>+<component> for a component hook; the revision is unset (the current one) except for check-health and fde-setup |
| User | root |
| Process group | its own; the whole group is killed at the time limit |
| Security tag | snap.<snap>.hook.<name>, or snap.<snap>+<component>.hook.<name> |
| Plugs | every unscoped plug of the snap, plus the plugs listed under the hook in hooks: |
| Environment | the usual SNAP* variables, SNAP_COOKIE (and SNAP_CONTEXT) set by snapd, the snap's environment: and then the hook's; components add SNAP_COMPONENT, SNAP_COMPONENT_NAME, SNAP_COMPONENT_VERSION, SNAP_COMPONENT_REVISION |
| Default time limit | 10 minutes; see snapctl: how it works for the hooks with other limits |
| Runs again | when snapd stops while it runs, or a restart is pending when it would start |
snap run --hook=<name> <snap> runs a hook by hand. It gets no cookie from snapd, so snapctl calls inside it have no context.
for app developers for snapd developers
Where hook files come from
- An executable in
meta/hooks/<name>of the snap, or of a component. snapcraft builds it fromsnap/hooks/<name>. - An entry under
hooks:in snap.yaml addsplugs,slots,environmentorcommand-chain. Listing a plug there scopes it to that hook and to the apps that list it. - Every file in
meta/hooks/must be executable:"<file>" should be executable, and isn't. default-configurerequiresconfigure. Base and snapd snaps may not shipconfigureordefault-configure; a snap withbase: nonemay not have hooks.- A name that matches no pattern is dropped without a message. In a component, an explicit hook with such a name fails with
unsupported component hook.
for snapd developers
HookSetup flags
| Flag | Effect |
|---|---|
Optional | a missing hook file, or no registered handler, completes the task without running anything |
IgnoreError | a failure is logged as ignoring failure in hook and the task is Done; Handler.Error is not called |
Timeout | the time limit; zero means 10 minutes |
Always | run the Go handler without a script; declared, but set by no production code |
undo-hook-setup | a hook run when the task is undone, such as unprepare-plug-<plug> for prepare-plug-<plug> |
Two hooks run without a task, through HookManager.EphemeralRunHook: fde-setup and prepare-serial-request. They are not serialised per snap, cause no change conflicts, have no undo and cannot be aborted. See Hooks: device setup.
for snapd developers
Adding a hook type
1. Add a pattern to supportedHooks, and to supportedComponentHooks if components may ship it (snap/hooktypes.go). 2. Register exactly one handler for the pattern with HookManager.Register in the owning manager. 3. Create run-hook tasks with hookstate.HookTask or HookTaskWithUndo and choose the flags above, or call EphemeralRunHook when no task is wanted. Mark the task Optional so that a downgrade to a snapd without the handler does not fail it. 4. Hooks created by snapstate go through function variables that hookstate sets in its init, such as snapstate.SetupInstallHook, to avoid an import cycle. 5. Decide which snapctl commands make sense in the new context.
To retire a hook, keep its pattern and stop registering its handler, as with gate-auto-refresh: snaps that ship it still install, and a leftover task completes without running it.
Further reading
- Supported snap hooks: the published list of hooks, with what each is for and examples.
- Use snapctl: the commands a hook uses to talk back to snapd.
- Interface hooks: the connect and disconnect hooks and the attributes they read and write.
- The snap format: the
hooks:section of snap.yaml.
Roads from here
GETTING SNAPS
- Snap packaging — how a snap is packed with its hooks
INTERFACES AND CONFINEMENT
- Confinement — the confinement each hook runs under
RUNNING SNAPS
- The overlord — changes and tasks and the run-hook task among them
SNAPCTL · the snap's API into snapd
- snapctl: how it works — how a hook talks back to snapd and its timeouts
HOOKS · code snapd runs inside a snap
- Hooks: install, configure, refresh, remove — install configure refresh remove and check-health and where each runs
- Hooks: device setup — the gadget and kernel hooks and the two that run without a task
- Hooks: interface hooks — the hooks around connecting and disconnecting a plug
- Hooks: confdb hooks — the hooks a confdb custodian or observer runs