snapctl: how it works

the shared mechanism for app developers for Ubuntu Core developers for snapd developers for administrators for users

snapctl is the command a snap runs from its hooks, apps and services to talk to snapd without the snapd-control interface that the full REST API needs. Each call is one POST to /v2/snapctl on /run/snapd-snap.socket carrying a cookie that names the snap; snapd checks the uid, the context and the command's own rules, then runs the command inside snapd.

On the map: snapctl district

▶ Watch this deck — 10 scenes, ~8 min

01 Why snapctl and not the REST API for app developers for Ubuntu Core developers for snapd developers for administrators

WHY SNAPCTL acme-agentconfigure hookneeds: serverone settingsnapd /run/snapd.socketthe full REST API only through snapd-control root in the snap can theninstall, remove, connect anything /run/snapd-snap.socket/v2/snapctlevery confined snap, no interface cookie → acme-agenta narrow API that acts for the calling snap
acme-agent's configure hook needs one setting; the full REST API on /run/snapd.socket is reachable only through snapd-control, which lets root in the snap install, remove and connect anything; /run/snapd-snap.socket is open to every confined snap and /v2/snapctl on it needs no interface; the cookie names acme-agent

The full REST API on /run/snapd.socket is open to a confined snap only through snapd-control, which grants what the snap command can do. /run/snapd-snap.socket is open to every confined snap, and /v2/snapctl on it needs no interface: the cookie in each call names the snap.

acme-agent's configure hook needs the server address you've just set. The snap command asks snapd's REST API for things like that, so why can't the hook? That API listens on snapd's main socket, and a confined snap reaches it only through the snapd-control interface. Connect that, and root in the snap can install, remove and connect anything, which is a lot to hand over for reading one setting. There is a second socket that every confined snap can reach, and one endpoint there needs no interface at all: /v2/snapctl. The cookie in each call names the snap, and the commands act for that snap.

02 One call, one request for app developers for Ubuntu Core developers for snapd developers for administrators

ONE CALL acme-agentconfigure hook$ snapctl get serverSNAP_COOKIE=… /run/snapd-snap.socketPOST /v2/snapctl{"context-id": "…","args": ["get","server"]} snapdcookie → contextuid checkruns get {"stdout": "acme.example:8883\n", "stderr": ""}acme.example:8883 every command runs inside snapd; the client only carries the call and prints the reply
The configure hook of acme-agent runs snapctl get server; the client sends one POST to /v2/snapctl over /run/snapd-snap.socket; snapd resolves the cookie, checks the uid and runs get; the reply carries the output back; snapctl and the command code meet only over the socket

snapctl is a thin client: each call is one POST /v2/snapctl on /run/snapd-snap.socket with the cookie and the arguments. The command runs inside snapd, and the reply carries its output. The address in the drawing is an example.

So what actually happens when the configure hook runs snapctl get server? Less than you might expect on the snap's side. The snapctl binary reads SNAP_COOKIE from its environment and sends one POST to /v2/snapctl on the snapd-snap.socket: the cookie and the arguments, nothing more. Inside snapd, the cookie becomes a context, the caller's uid is checked, the arguments are parsed, and get runs in the daemon. The reply carries stdout and stderr, and snapctl prints them and exits. So every snapctl command is really code in snapd. The client is the same thin messenger for all of them.

04 Changes land when the hook succeeds for app developers for Ubuntu Core developers for snapd developers

NOW OR LATER in a hookconfigure hook$ snapctl set interval=60transaction (pending)commit registered exit 0hook done → commitcommitted exit 1 or timeoutdiscardedexcept remove: failure ignored same rule for set-health and for writes in confdb hooks from an app or serviceacme-agent.agent$ snapctl set interval=60ephemeral contextmade for one callcommitted at end of request a failed hook leaves no configuration behind
In a hook, snapctl set writes to a pending transaction committed only when the hook exits 0 and discarded if it fails; from an app, an ephemeral context commits at the end of the request

In a hook, snapctl set, snapctl set-health and confdb writes take effect only if the hook exits 0; snapd commits them anyway for hooks whose failure it ignores, such as remove. From an app or service they take effect when the snapctl call returns.

The configure hook sets interval to 60, then trips over a bad server address. Should the interval stick? No. snapctl set in a hook writes to a transaction and registers its commit for when the hook is done. Exit zero, and the commit runs. Fail or time out, and none of that work runs, unless snapd ignores the hook's failure, as it does for remove. set-health, and confdb writes made in a confdb hook, follow the same rule. From the agent service there's no hook to wait for: each call gets its own context, which is done when the call ends, so the value is stored at once.

05 What snap users see of snapctl for users for administrators

FROM THE OUTSIDE snaps call snapctl; you see the effect through your own commands $ snap services acme-agentService Startup Current Notesacme-agent.uploader disabled inactive -a service the snap disabledkept that way across refreshes $ snap list acme-agentName Version Rev Tracking Publisher Notesacme-agent 1.4 42 latest/stable acme blockedhealth reported by the snapshown in Notes when not okay $ snap set acme-agent interval=60configure hookservice restartedone snap set change: the restart runs after the hook succeeds snapctl acts through snapd, on the snap that called it
Three effects of acme-agent's snapctl calls: snap services shows a service the snap disabled, kept across refreshes; snap list shows the health status blocked in the Notes column; snap set runs the configure hook and then a service restart in the same change

A service the snap disabled, a health status in the Notes column of snap list, and a restart inside the snap set change all come from the snap's own snapctl calls. The revision, publisher and "blocked" status are examples.

You won't run snapctl yourself. Snaps run it from their hooks and services, and you see the results through your own commands. Here are three you might meet on the gateway. Snap services shows the uploader as disabled because acme-agent switched it off while it was being installed, and a refresh keeps it that way. Snap list shows blocked in the Notes column, because the agent reported its health and the status isn't okay. And after snap set, the agent's service restarts: its configure hook asked for that, and the restart runs once the hook has succeeded.

06 The hook decides what a command does for app developers for Ubuntu Core developers for snapd developers

SAME COMMAND, THREE PATHS $ snapctl restart acme-agent.agent from the configure hook: the hook's own changerun-hookrestart tasksfinal tasksqueued: runs after the hook, only if it succeeds from default-configure: the install changerestart tasksright afterstart-snap-services from the service or another hook: a new changeservice-controlRunning service command for snap "acme-agent"snapctl waits up to half the configure hook timeout one hook onlyreboot: install-devicefde-setup-request: fde-setupget --previous: change/save/observe-view
snapctl restart acme-agent.agent takes three paths: from the configure hook it queues tasks into the hook's change, from default-configure it runs right after start-snap-services, from an app or another hook it creates a service-control change and waits; reboot, fde-setup-request and get --previous work only in one hook

From configure, snapctl restart queues into the hook's change; from default-configure it runs right after start-snap-services; elsewhere it creates a service-control change and waits. reboot, fde-setup-request and get --previous work only in particular hooks.

The same command can do different things depending on where you call it. Take snapctl restart acme-agent.agent. From the configure hook, it adds its tasks to the hook's own change, so the restart runs after the hook, and only if the hook succeeds. From default-configure, the tasks go right after the step that starts the snap's services on first install. From the service itself, or any other hook, it creates a service-control change and waits for it. And some commands only work in one hook: reboot in the gadget's install-device hook, fde-setup-request in fde-setup, and get --previous in three confdb hooks.

07 Four checks before a command runs for app developers for Ubuntu Core developers for snapd developers for administrators

FOUR CHECKS 1 · socket/run/snapd-snap.socket: open to every snap; /v2/snapctl needs no interfaceGET /v2/snaps without snap-refresh-observe → 403 Forbidden 2 · uidcannot use "set" with uid 1000, try with sudonon-root callers: 11 commands, refresh only with --tracking; hooks run as rootget services set-health is-connected system-mode refresh model version is-ready tasks change 3 · contextthe cookie must resolve; only version and -h work without onecannot invoke snapctl operation commands (here "get") from outside of a snap 4 · the command's own ruleshook name: reboot, fde-setup-request · interface: mount, kmod · snap type or brand: modelmount needs mount-control · kmod needs kernel-module-load a command reaches its code only after all four
Four checks in order: the snap socket serves /v2/snapctl to every snap and other endpoints only with an interface, non-root callers may use eleven commands, the cookie must resolve to a context, and each command applies its own hook, interface or snap type rules

Socket, uid, context, then the command's own rules. Non-root callers may use get services set-health is-connected system-mode refresh model version is-ready tasks change; refresh then accepts only --tracking. The uid 1000 in the refusal is an example.

An open socket doesn't mean anything goes. Every call passes four checks. First the socket: /v2/snapctl is served only on the snapd-snap.socket, which every snap can reach; other endpoints there need a connected interface. Second the uid, from the socket's peer credentials. A non-root caller may use eleven commands, and refresh then allows only tracking. Hooks run as root, so this limits apps that users start. Third the context: without a known cookie, only version and help work. Fourth the command's own rules: some need a particular hook, some an interface such as mount-control, and model needs the right snap or brand.

08 Hooks run under a timeout for app developers for Ubuntu Core developers for snapd developers for administrators

TIME LIMITS one hook per snap at a timerun-hook task$ snap run --hook configure -r 42 acme-agentSNAP_COOKIE set by snapd · revision 42 is an example default: 10mconfigure, default-configure: 5m (SNAPD_CONFIGURE_HOOK_TIMEOUT)check-health: 30s (SNAPD_CHECK_HEALTH_HOOK_TIMEOUT)fde-setup: 5mconfigure process group killed<exceeded maximum runtime of 5m0s> task error: run hook "configure": …the change undoes completed tasks remove hook: failure ignored and logged a failed hook keeps none of its snapctl work (remove: kept)
A run-hook task runs snap run --hook configure; timeouts are 10 minutes by default, 5 for configure, 30 seconds for check-health and 5 for fde-setup; an overrun hook's process group is killed, the task fails and the change undoes completed tasks; a failed hook keeps none of its snapctl work, except a remove hook whose failure is ignored

Hooks are run-hook tasks with a timeout: 10 minutes by default, 5 for configure, 30 seconds for check-health, 5 minutes for fde-setup. A hook that overruns is killed and its task fails with <exceeded maximum runtime of …>. Revision 42 in the drawing is an example.

What if acme-agent's configure hook hangs, waiting for a server that never answers? snapd won't wait forever. A hook runs as a run-hook task that starts snap run --hook, one hook per snap at a time, and each hook has a time limit: ten minutes by default, five for configure and default-configure, thirty seconds for check-health, and five minutes for fde-setup. When time runs out, snapd kills the process group and adds exceeded maximum runtime to the output. The task fails, and the change undoes what it had done. Unless snapd ignores that hook's failure, as for remove, the hook's snapctl work is dropped too.

09 Where to go from here

ROADS snapctl: how it works Configuration and healthget set unset set-health Services, refresh and changesstart stop install refresh reboot Device and systemmodel system-mode mountkmod fde-setup Hookswhen snapd runs each hookOverlordchanges, tasks, run-hook snapd-controlthe full API, for a snap
Roads from snapctl: configuration and health, services refresh and changes, device and system, hooks, the overlord and snapd-control

Roads: the three snapctl groups, hooks, the overlord and the snapd-control interface.

One socket, one cookie, and a context that decides when work lands. That's the machinery under every snapctl command. Three decks take the commands in groups. Configuration and health covers get, set, unset and set-health, and when their changes land. Services, refresh and changes covers start, stop, restart, components, refresh, reboot and the changes a snap starts itself. Device and system covers model, system-mode, mount, kmod and fde-setup. The hooks deck explains when snapd runs each hook, the overlord covers changes and the run-hook task, and snapd-control has its own scene with the interfaces.

10 Every command at a glance

EVERY SNAPCTL COMMAND commandwherewhoeffect changefrom apps and hooksnon-root allowedreads only failonly in change-view hooks (confdb)root onlychanges state directly fde-setup-requestonly in the fde-setup hookroot onlyreads only fde-setup-resultonly in the fde-setup hookroot onlychanges state directly getfrom apps and hooksnon-root allowedreads only installfrom apps and hooksroot onlycreates or joins a change is-connectedfrom apps and hooksnon-root allowedreads only is-readyfrom apps and hooksnon-root allowedreads only kmodfrom apps and hooksroot onlychanges state directly modelfrom apps and hooksnon-root allowedreads only mountfrom apps and hooksroot onlychanges state directly rebootonly in the install-device hookroot onlychanges state directly refreshfrom apps onlynon-root allowedreads only removefrom apps and hooksroot onlycreates or joins a change restartfrom apps and hooksroot onlycreates or joins a change servicesfrom apps and hooksnon-root allowedreads only setfrom apps and hooksroot onlysaved when the hook or call ends set-healthfrom apps and hooksnon-root allowedsaved when the hook or call ends startfrom apps and hooksroot onlycreates or joins a change stopfrom apps and hooksroot onlycreates or joins a change system-modefrom apps and hooksnon-root allowedreads only tasksfrom apps and hooksnon-root allowedreads only umountfrom apps and hooksroot onlychanges state directly unsetfrom apps and hooksroot onlysaved when the hook or call ends versionanywhere, no context needednon-root allowedreads only
Every snapctl command with where it may run, who may run it, and what it does to state

25 commands: 11 non-root, 5 create or join a change, 3 saved when the hook or call ends, 4 hook-specific.

Every snapctl command, 25 in one table at a glance. 11 may run as non-root: change, get, is-connected, is-ready and 7 others. 5 create a change or add tasks to the running one: install, remove, restart, start and one other. 3 commands, set, set-health, unset, are saved only when the hook succeeds or the call ends. 4 work only inside one particular hook: fail in change-view, fde-setup-request in fde-setup, fde-setup-result in fde-setup, reboot in install-device. The refresh command now works only from apps. With the view option, get and set can also start a confdb change. The rest read state or change it directly. Each command is described in full in the list under this deck.

Read more

The catalogue below this deck lists every snapctl command. This page collects the parts of the mechanism that the commands share.

for app developers for Ubuntu Core developers for snapd developers for administrators

Two sockets

/run/snapd.socket/run/snapd-snap.socket
Used bythe snap commandsnapctl
Open to a confined snaponly with snapd-control connectedalways (base AppArmor template)
/v2/snapctlnot servedserved, no interface needed, no login
Other endpointsthe full REST APIa few, each only with a connected interface such as snap-refresh-observe; otherwise 403 Forbidden
Identity of the callerthe logged-in user or rootthe cookie in the request body

snapctl never reads ~/.snap/auth.json.

for app developers for Ubuntu Core developers for snapd developers for administrators

The request

PartContent
Method and pathPOST /v2/snapctl
Bodycontext-id (the cookie), args, and stdin only for fde-setup-result (at most 4,000,000 bytes)
HeaderX-Snapctl-Features: async
Replystdout, stderr, and change-id when an install or remove runs asynchronously
Environment read by the clientSNAP_COOKIE, then SNAP_CONTEXT for compatibility

Two arguments are handled in the client and do not reach snapd: user-open <url> and the retired internal configure-core. snapctl and snap-exec are one binary that picks its role from the name it was started as.

for app developers for snapd developers

Errors and exit codes

snapd returnsClient does
successprints stdout and stderr, exits 0
kind unsuccessful with an exit code (HTTP 200)prints stdout and stderr, exits with that code
403 Forbidden (uid check, or refresh by non-root)prints error: <message>, exits 1
any other errorprints error: snapctl: <message>, exits 1

Commands that use the exit code: is-ready (0 done, 2 finished without success, 3 not ready) and is-connected (1 not connected; with --pid or --apparmor-label, 10 for an unconnected classic snap and 11 for a process that is not a snap).

Cookies and contexts

HookApp or service
Who sets SNAP_COOKIEsnapd, when it starts the hooksnap-confine, from /var/lib/snapd/cookie/snap.<instance> (mode 0600)
Valuea new 32-byte token for each hook runa 39-byte token for the snap
Lifetimewhile the hook runsfrom the first install of the instance to the removal of its last revision; kept across refreshes
Contextthe hook's context, shared by all calls in that runa new ephemeral context for every call
When buffered work is committedwhen the hook exits 0, or when its failure is ignored (for example remove)when the call returns

At start-up snapd creates missing cookies and rebuilds them all if it finds a stale or duplicate one. The fde-setup and prepare-serial-request hooks run without a task; they have a hook name but behave as ephemeral contexts.

Who may call what

CheckRuleRefusal
uidroot may run every command; others only get, services, set-health, is-connected, system-mode, refresh (with --tracking only), model, version, is-ready, tasks, change, and any -h/--helpcannot use "set" with uid 1000, try with sudo
contextevery command except version needs a known cookiecannot invoke snapctl operation commands (here "get") from outside of a snap
hookreboot in install-device; fde-setup-request and -result in fde-setup; fail in change-view-*; set :<plug> in prepare-*; get :<plug> in interface hooks; get --previous in save-view-*, change-view-*, observe-view-*per command
interfacemount needs mount-control; kmod needs kernel-module-load; model needs snapd-control unless the snap is a gadget or kernel or from the model's brandper command

for app developers for Ubuntu Core developers for snapd developers for administrators

Hook time limits

HookLimitOverride
any hook not listed10 minutesnone
configure, default-configure5 minutesSNAPD_CONFIGURE_HOOK_TIMEOUT
check-health30 secondsSNAPD_CHECK_HEALTH_HOOK_TIMEOUT
fde-setup5 minutesnone

A hook that overruns has its process group killed; the output ends in <exceeded maximum runtime of …> and the task fails with run hook "<hook>": …. Only one hook of a snap runs at a time.

Further reading

Roads from here

RUNNING SNAPS

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

SNAPCTL · the snap's API into snapd

INTERFACE FAMILIES · every interface, grouped by what it touches

HOOKS · code snapd runs inside a snap

DESKTOP · snaps in a user session