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

▶ Watch this deck — 9 scenes, ~7 min

01 Why a snap needs hooks

WHY HOOKS acme-agent a read-only image snapd, on its own mount it connect plugs start the daemon only the snap knows is the new interval a sensible value? revision 42 stores its data differently a plug was connected: now what? configure post-refresh connect-plug-network hooks: run by snapd, as steps of a change lifecycle 8 device 4 interfaces 4 patterns, plug or slot confdb 5 patterns components: install pre-refresh post-refresh remove
acme-agent is a read-only image; snapd mounts it, connects its plugs and starts its daemon on its own; three questions only the snap can answer, whether a new interval is sensible, how revision 42 moves old data, and what to do when a plug is connected, are answered by the configure, post-refresh and connect-plug-network hooks, which snapd runs as steps of a change; hooks come in four groups, with four more for components

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

THREE PLACES MAKE A HOOK TYPE 1 snap/hooktypes.go supportedHooks: ^configure$ … ^connect-(?:plug|slot)-[-a-z0-9]+$ 21 patterns, and supportedComponentHooks: 4 2 HookManager.Register(regexp, HandlerGenerator) configstate ^configure$ ifacestate ^connect-plug-[-a-z0-9]+$ devicestate ^prepare-device$ 3 hookstate.HookTask(st, summary, &HookSetup{…}, data) Optional IgnoreError Timeout undo-hook-setup gate-auto-refresh 1 pattern: kept 2 handler: not registered 3 no new task; a leftover one returns at once, the script does not run snapstate.SetupInstallHook = SetupInstallHook (set in hookstate's init)
Three stacked panels: the supportedHooks patterns, a handler registered with HookManager.Register, and HookTask creating a run-hook task with flags; beside them gate-auto-refresh keeps its pattern but has no handler, so its optional task returns at once

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

THE SHAPE OF A NAME meta/hooks/example names configureruns on snap set connect-plug-networkruns when plug network connects post_refreshignored: no such hook configure.shignored: no such hook connect-plug-networksaccepted, does not run: no plug networks $ snap pack . built: acme-agent_1.0_all.snap $ snap install --dangerous \ acme-agent_1.0_all.snap acme-agent 1.0 installed no warning, no error every file in meta/hooks/ must be executable, or validation fails components: an unknown explicit hook name is an error: unsupported component hook: "…"
Five files in acme-agent's meta/hooks with snapd's verdict: configure and connect-plug-network run, post_refresh and configure.sh are ignored, connect-plug-networks is accepted but does not run; snap pack and snap install print no warning; component hooks with unknown explicit names are an error

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

A PLUG SCOPED TO ONE HOOK name: acme-agent plugs: network: apps: agent: daemon: simple acme-agent app agent hook remove hook configure (implicit) network unscoped: bound to every app and every hook hooks: remove: plugs: [network] listed under remove: scoped to it the agent and the configure hook lose network the fix: list it under the agent too agent: plugs: [network] a name under a hook that is not declared anywhere becomes a new plug of that interface
acme-agent's snap.yaml declares the network plug at the top, so it is bound to the agent app and to every hook; listing network under the remove hook scopes it, so it is bound only to the remove hook, and the agent app and the implicit configure hook lose it; the fix is to list network under the agent too; an undeclared name under a hook becomes an implicit plug

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

FROM A TASK TO A CONFINED PROCESS run-hook hook-setup: snap: acme-agent hook: configure $ snap run --hook configure -r unset acme-agent SNAP_COOKIE=<per-run id> own process group; -r unset: the current revision snap-confine snap.acme-agent.hook.configure the hook's own profile snap-exec snap and hook environment command-chain $SNAP/meta/hooks/configure as root output buffer: last 100 lines / 10 KiB exit 0 → discarded exit ≠ 0 → run hook "configure": <tail>
After snap set acme-agent interval=5, a run-hook task for the configure hook of acme-agent becomes snap run --hook with a per-run cookie, then snap-confine with the security tag snap.acme-agent.hook.configure, then snap-exec, which executes meta/hooks/configure as root; output is kept in a buffer and shown only if the hook fails

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

ONE HOOK PER SNAP AT A TIME auto-disconnect Disconnect interfaces of snap "acme-agent" disconnect-slot-certs disconnect-plug-certs disconnect-plug-network disconnect-plug-log-observe disconnect disconnect disconnect plug certs plug network plug log-observe Doing Do: held, same snap is running a hook Do: waits Doing: in the certs provider component hooks take their snap's turn; each parallel instance is a snap of its own also held: every hook while the snap's base is unlinked; confdb hooks while the snap is inactive
Removing acme-agent: auto-disconnect injects three chains, one per connection; disconnect-plug-network is running while the snap's other disconnect hooks wait; the certs provider's disconnect-slot-certs hook runs at the same time because it belongs to another snap

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 THE CHANGE $ snap install acme-agent error: cannot perform the following tasks: - Run install hook of "acme-agent" snap if present (run hook "install": ----- looking for the device id... no device id found -----) example output only the tail: 100 lines / 10 KiB install change mount … make current connect plugs set up aliases install hook ✗ undo errors ignored, logged remove disconnect-plug-… / -slot-… unprepare-… (undo) observe-view-… ignoring failure in hook "remove" a timeout counts as a failure:time limits: see the snapctl deck
snap install of acme-agent, whose install hook fails, prints the tail of the hook's output; the install change undoes its completed tasks; remove, disconnect, undo and observe-view hooks run with errors ignored and only logged

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

A HOOK MAY RUN TWICE run-hook post-refresh Doing snapd stops snapd refresh, reboot task status: Do error during stop → Retry snapd starts run-hook post-refresh Doing, from the first line failed: not retried snapd stopped: run again restart pending: wait, then run example hook lines echo "$SNAP_REVISION" >> "$SNAP_DATA/history"appends twice snapctl set data-format=2same result twice
The post-refresh hook task of acme-agent is Doing when snapd stops; the task goes back to Do as a retry; after snapd starts the hook runs again from the first line; failed hooks are not retried; appending to a file is not safe to repeat, setting a value with snapctl is

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 Hooks: how they work Install and refreshthe lifecycle hooks Device setupgadget and kernel hooks Interface hooksconnect and disconnect confdb hookscustodians and observers snapctl: how it workscalls back and timeouts The overlordchanges and tasks Confinementthe profile a hook runs under Snap packaginghooks in meta/hooks
Roads from Hooks: how they work: the four hook groups (install and refresh, device setup, interface hooks, confdb hooks), then snapctl, the overlord, confinement and snap packaging

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:

SummaryHook
Run install hook of "<snap>" snap if presentinstall
Run pre-refresh hook of "<snap>" snap if presentpre-refresh
Run post-refresh hook of "<snap>" snap if presentpost-refresh
Run remove hook of "<snap>" snap if presentremove
Run configure hook of "<snap>" snap, or ... if present during install and refreshconfigure
Run default-configure hook of "<snap>" snap if presentdefault-configure
Run health check of "<snap>" snapcheck-health
Run prepare-device hook, Run install-device hookthe 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

MessageMeaning
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" hooksnap 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

ItemValue
Commandsnap 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
Userroot
Process groupits own; the whole group is killed at the time limit
Security tagsnap.<snap>.hook.<name>, or snap.<snap>+<component>.hook.<name>
Plugsevery unscoped plug of the snap, plus the plugs listed under the hook in hooks:
Environmentthe 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 limit10 minutes; see snapctl: how it works for the hooks with other limits
Runs againwhen 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 from snap/hooks/<name>.
  • An entry under hooks: in snap.yaml adds plugs, slots, environment or command-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-configure requires configure. Base and snapd snaps may not ship configure or default-configure; a snap with base: none may 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

FlagEffect
Optionala missing hook file, or no registered handler, completes the task without running anything
IgnoreErrora failure is logged as ignoring failure in hook and the task is Done; Handler.Error is not called
Timeoutthe time limit; zero means 10 minutes
Alwaysrun the Go handler without a script; declared, but set by no production code
undo-hook-setupa 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

Roads from here

GETTING SNAPS

INTERFACES AND CONFINEMENT

RUNNING SNAPS

  • The overlord — changes and tasks and the run-hook task among them

SNAPCTL · the snap's API into snapd

HOOKS · code snapd runs inside a snap