Current section
Files
Jump to
Current section
Files
guides/device.md
# On a device
`Precompiled.install/1` installs a signed precompiled library into a
running Nerves device, from an IEx shell on it (over ssh or the console),
with no Mix, no Hex and no compiler on the device. Something goes wrong in
the field and you need `recon` or another diagnostic tool: install it on
that device instead of shipping a debug firmware. It picks the build made
for the device's own Nerves system and versions, checks every byte through
the signed chain, loads it and starts it. It never replaces anything the
firmware has, and nothing it installs is loaded at boot.
## Setup
mix igniter.install precompiled --device
(which also sets up the build-time step of [Setup](setup.md)), or by hand,
in the firmware's `mix.exs`: the dependency without `runtime: false`, so
the library ships in the firmware, and `castore` when the system has no
CA certificates of its own (see [CA certificates](trust.md#ca-certificates)):
```elixir
{:precompiled, "~> 0.10.0", targets: @all_targets},
{:castore, "~> 1.0", targets: @all_targets}
```
Nothing else. It is on by default and uses the official signed source,
`https://compatibility.nerves-project.org/api/precompiled`, checked
against the root this library ships. Nothing runs on its own: it only
ever acts when someone with a shell on the device calls it.
To limit it, turn it off, or point it elsewhere, set
`config :precompiled, :device` in the firmware's config
(`config/target.exs`, say):
```elixir
config :precompiled, :device,
allow: [:recon, :circuits_gpio]
# or, to turn it off in this firmware:
config :precompiled, :device, enabled: false
```
| Key | Default | Meaning |
| --- | --- | --- |
| `enabled` | `true` | `false` disables installing: `install/2` returns `{:error, :disabled}`. `list/1`, `uninstall/2` and `clean/1` keep working, so what is installed can still be removed. |
| `allow` | any app | A list of apps: only those may be installed, closure members included. |
| `source` | the official API | Another source: an `https://` API root, or a `file://` bundle dir. The only place a network source can be set. |
| `dir` | `/data/precompiled` | Where installs are stored. |
| `max_bytes` | 64 MB | The size bound of that store. |
| `max_document_bytes` | 32 MB | The size bound of the store's document cache, apart from `max_bytes`, so the store can take both (96 MB by default; see [The cache](#the-cache)). `0` keeps no documents. |
| `cacerts_path` | none | A PEM CA bundle to verify the source with. |
| `root` | the shipped `root.json` | Another trust anchor. Set here only: a call cannot pass it. |
| `content` | the batch's | Mirror or CDN origins (`https://`) to fetch files from. Set here only: a call cannot pass it. |
| `deadline_seconds`, `max_closure`, `start`, `closure`, `quiet` | as in the options below | Firmware-wide defaults for those `install/2` options. |
`enabled` and `allow` are read from the firmware's config only: a call can
neither pass, widen nor clear them. Any other key under `:device` is
ignored.
Online installs need `:inets`, `:ssl` and `:public_key` in the release
(Nerves firmware with networking usually has them). A firmware that only
installs from bundles can leave them out; an online call then returns
`{:error, {:missing_app, app}}`.
## Usage
```elixir
Precompiled.install(:recon)
Precompiled.install({:circuits_gpio, "2.3.1"})
Precompiled.install([:recon, {:circuits_gpio, "~> 2.3"}])
Precompiled.install(:recon, dry_run: true)
Precompiled.install(:recon, source: "file:///media/usb/precompiled")
Precompiled.list()
Precompiled.uninstall(:recon)
Precompiled.clean()
```
A bare name takes the newest version with a build that matches; a version
or a requirement narrows it. Absent runtime dependencies are installed with
the package, as one unit: anything that fails takes the code path and the
loaded apps back to how they were. Each step prints one line:
```
precompiled: system nerves_system_rpi4 2.2.1, OTP 29, Elixir 1.20.3, aarch64
precompiled: circuits_gpio 2.3.1 PLAN nerves_system_rpi4, 198 KB
precompiled: circuits_gpio 2.3.1 OK /data/precompiled/circuits_gpio-2.3.1
precompiled: 1 installed, 198 KB, 2.1 s
precompiled: downloaded 1.1 MB (documents 912 KB, files 199 KB), reused 0 KB from the cache (documents 0 KB, files 0 KB)
{:ok, [%Precompiled.Installed{app: :circuits_gpio, ...}]}
```
The last line says what the call downloaded and what the store gave it
instead (see [The cache](#the-cache)). Documents are the root, the batch,
the manifests and the systems table; files are the `.app` files read
while planning and the files of the builds installed. A build's `.app` is
read twice, once while planning and once with the build, so a first call
downloads it twice, and a later call that finds the build in the store
counts it as reused twice: the reused bytes are what the call would have
downloaded without the store.
- `install/2` returns `{:ok, [%Precompiled.Installed{}]}` with the apps it
installed (`[]` when everything was already there), or
`{:error, reason}`. It never raises on the network or on bad input.
- `dry_run: true` plans, checks the trust chain and fetches only the
manifests and `.app` files, and returns `{:ok, %Precompiled.Plan{}}`,
whose `transfer` field holds the numbers of that last line.
- `list/1` prints and returns what is in the store, each with its size,
the batch it was checked against, and whether it is loaded; or
`{:error, reason}` for a bad option or an unsafe store.
- `uninstall/2` stops the app, unloads it, purges its modules and takes it
off the code path. Its files stay in the store as a cache
(`remove: true` drops them). It refuses while other installed apps need
it (`cascade: true` uninstalls those first) or while other processes run
its code (`force: true`). Only running code counts: open resources are
not detected, so an uninstall goes ahead while a shell still holds, say,
a GPIO handle from `Circuits.GPIO.open/2`. Close such handles
(`Circuits.GPIO.close/1`) first.
- `clean/1` empties the store and its document cache, but keeps what is
loaded.
The options of `install/2`:
| Option | Default | Meaning |
| --- | --- | --- |
| `:source` | the `:device` config, else the official API | `file://DIR` for a bundle only. A per-call `https://` or `http://` source returns `{:error, {:source_not_allowed, source}}`: a network source is firmware config only (see [Trust](trust.md)). A per-call `:content` returns `{:error, {:content_not_allowed, origins}}` the same way. |
| `:deadline_seconds` | as on the host | See [Configuration](configuration.md). |
| `:cacerts_path` | none | A PEM CA bundle (see [CA certificates](trust.md#ca-certificates)). |
| `:dir` | `/data/precompiled` | The store. Its trust state lives in `DIR/.trust`, so another `:dir` has its own trust state, starting again from the shipped root. |
| `:start` | `true` | Start the installed apps (`:temporary`). `false` only loads them. |
| `:closure` | `true` | Install absent runtime dependencies. `false` refuses with `{:needs, [{app, vsn}]}` instead. |
| `:max_closure` | 25 | The most apps one call installs. |
| `:max_bytes` | 64 MB | The size bound of the store. |
| `:max_document_bytes` | 32 MB | The size bound of the document cache, apart from `max_bytes`; `0` keeps none. |
| `:dry_run` | `false` | Plan only, as above. |
| `:report` | none | With `dry_run: true`, also write the device facts and the plan as JSON to this path, for `mix precompiled.bundle --device-report`. |
| `:quiet` | `false` | Print nothing. |
An unknown option is refused (`{:bad_option, key}`), never ignored.
`list/1` and `clean/1` take `dir` and `quiet`; they also accept the other
options of `install/2` and `uninstall/2`, so one options list serves all
calls, and ignore them.
[`Precompiled`](https://hexdocs.pm/precompiled/Precompiled.html#module-return-values)'s module documentation lists every error reason.
## Mix.install in Nerves Livebook
A runtime with no Mix, such as Nerves Livebook's, can serve a notebook's
`Mix.install/2` with `Precompiled.mix_install/2`:
```elixir
defmodule Mix do
def install(deps, opts \\ []), do: Precompiled.mix_install(deps, opts)
end
```
It takes the deps and options `Mix.install/2` takes and returns `:ok`, or
raises `Precompiled.InstallError`, whose message says why in words:
```
** (Precompiled.InstallError) the firmware has kino 0.14.2, which does not match "~> 0.15"; a device never replaces an app its firmware has: change the requirement (to "~> 0.14.2") or update the firmware
```
- **What the device has is skipped.** A dep the firmware has, or one this
library installed earlier in this VM, is skipped when its version meets
the requirement (any version when there is none). Another version
raises. For one installed earlier the message says how to get the other
version: `Precompiled.uninstall/2` it and run the cell again, or reboot.
- **The rest installs in one `install/2` call**, with everything above:
the signed chain, the closure and its conflicts, and an optional
dependency installed when the same list names it (`[:axon, :kino]`).
- **A re-run is free.** Running the cell again installs nothing and asks
the source nothing. Another notebook's call with other deps installs
those too, where `Mix.install/2` would raise in the same VM: a device's
VM outlives a notebook.
- **Starting** follows `Mix.install/2`: every dep is started, the ones the
device had included, except a `runtime: false` dep, which is only
loaded; `start_applications: false` starts nothing. The firmware's
`start` default is not read here. With a `runtime: false` dep the rest
is started after the install, and one that fails to start raises with
the apps left loaded (`install/2` alone takes them back).
- **Versions** are compared as Mix compares a dep it has. OTP's read as
OTP shortens them (`kernel` `10.4` is `10.4.0`); a four-part one
(`ssl` `11.7.8.1`) is checked against no requirement: give that app
without one.
- **`config:`** is put into the application env (`persistent: true`)
before anything is planned, as `Mix.install/2` puts it before it
compiles. The builds are then compared with those values: a build whose
compile read a key the notebook sets to another value (or read it unset)
is refused, and one that read the same value installs.
- It may not name an app of OTP (`ssl`, `public_key`, `kernel`, ...) or
of Elixir (`logger`, ...), nor `:precompiled`, its runtime closure or
the apps it reads for trust, transport and device facts (`castore`,
`nerves_runtime`, `nerves_time`): their env decides how this call and
every later one verifies the source, connects and reads the device,
which only the firmware decides. To change Logger's level from a
notebook, call `Logger.configure/1` at runtime instead.
- A device cannot recompile what it already has, so `config:` that
changes a key which an app on the device read at compile time raises
and changes nothing. For an app installed earlier, from any store
dir, those reads are the ones its build was matched on, manifest and
`.app`, which this VM records when it activates the build: nothing on
the store's disk changes them, and a cached build loaded again after a
reboot records them again. For a firmware app they are only its
`.app`'s, which Mix writes for `Application.compile_env/3` and nothing
else (see [Known limitations](limitations.md#on-a-device)).
- While any app on the device has reads that cannot be told (a firmware
`.app` that does not read, an app loaded from a store that this VM did
not activate), every `config:` is refused, naming that app: what it
read may be any app's keys. For an installed one, reboot or uninstall
it; for a firmware one, drop `config:` or update the firmware.
- The checks, the put and the install run under the store's lock, as
one step: a refused call puts nothing (a disabled install, a bad
source, a missing network app, an unsafe store), and two notebooks at
once cannot interleave. When the install itself then fails (no build
matches, a download), the config stays put, as with `Mix.install/2`.
It refuses, naming the dep and the option, what a device cannot honour:
`path:`, `git:`, `github:` and the other git options, `organization:`,
another `repo:` or `hex:` package, `env:` other than `:prod`, `compile:`,
`manager:`, a dep's non-empty `system_env:`, `app: false`, and `only:` and
`targets:` (a device has no Mix env or target to pick deps by). Of the
options it refuses `config_path:`, `lockfile:` and a non-empty
`system_env:` (a device cannot check a build against variables set for
its compile), and ignores those that change no build here (`force:`,
`consolidate_protocols:`, `compilers:`, `stop_unused_applications:`,
`runtime_config:`).
`elixir:` and `verbose:` work as in `Mix.install/2`. Any other option is
one of `install/2`'s above, except `dry_run:`, `report:` and `start:`.
[`Precompiled.mix_install/2`](https://hexdocs.pm/precompiled/Precompiled.html#mix_install/2)
has the full tables.
## What it refuses
- **Anything the device already has.** An app the firmware has, loaded or
only shipped in the release, is never replaced: `install(:logger)`
returns `{:error, {:already_present, :logger, vsn}}`. Apps are matched by
name and exact version: a build made against `nerves_ssh` 1.3.3 is
refused on a device with 1.3.2 (`NO built against nerves_ssh 1.3.3,
device has 1.3.2`).
- **Conflicts.** A module that is already loaded, or that the code path
already finds, refuses the install (`{:module_loaded, mod, path}`,
`{:module_conflict, mod, path}`), and so do two versions of one app in
one call (`{:conflict, app, vsns}`).
- **Other systems.** A system build serves only the Nerves system it was
made for, matched by name (read from `/usr/lib/os-release`); builds are
made for official Nerves systems. It must be for the device's exact
system version, or for another release of that system: a beam-only
build always (without the source scan a build machine runs, see
[Known limitations](limitations.md#matching)), a native one when the
batch's systems table says the device's release has the same toolchain
series, an OTP no older than the build's and every library the build
needs ([What matches](matching.md#the-fine-print)). The exact version
wins, then the closest older release, then the lowest newer one. A
`pure_elixir` build serves any device, and a device whose system is not
known takes `pure_elixir` builds only. When both kinds match, the system
build wins. A native library made for another CPU is refused
(`{:elf, why}`).
- **Missing libraries.** Before a native build is installed, every library
it needs is looked up in the device's own `/lib` and `/usr/lib`, and
must define the symbol versions the build needs. This holds for the
exact system version too. A build that needs something the device does
not have is refused (`{:libs, app, reason}`, with `reason.code`
`:needed_lib_missing` or `:symbol_version_missing`).
- **noexec.** A build with native code is refused when the store is on a
`noexec` mount (`{:noexec, mount}`).
- **An unset clock.** An online call does not wait for NTP: right after
boot, NervesTime's saved or estimated time is usually close enough, and
the batch's own time checks decide (expiry, a future issue time, a clock
before this library's build). When one of them refuses the batch while
the clock is not synchronized yet (`NervesTime.synchronized?/0` when
`nerves_time` is in the firmware), the call prints `the batch looks
expired or not yet valid, and the clock is not NTP-synchronized yet;
wait for NTP, then retry` and returns
`{:error, {:clock_unsynchronized, now}}`. Wait for NTP, then retry. With
a synchronized clock, an expired batch is refused as such. A bundle
needs no NTP: one without
`offline.json` is judged by its batch's expiry against the device clock,
which must be sane; one with a signed `offline.json` needs no clock.
## Reporting a miss from a device
When an install misses or fails and it should not, send what it found
from the device's shell:
```elixir
Precompiled.install(:circuits_gpio)
Precompiled.report()
```
Every `install/2` but a dry run records its outcome in the store, in
`DIR/.last-install.json`: one line per package it planned or missed, with
HIT, MISS or FAIL and the reason code. Only the last install is kept, and
`report/1` sends that one. A call refused before it ran (an app already
present, a bad option, `enabled: false`) replaces it with a record that no
install ran, so an older install is never sent. It shows the summary first and asks
`Send this report to <host>? [y/N]`; only `y` or `yes` sends.
| Option | Effect |
| --- | --- |
| *(none)* | Shows the report, then asks; anything but `y` or `yes` sends nothing |
| `yes: true` | Skips the question and sends |
| `contact: "@you"` | Adds a handle for follow-up questions (at most 100 characters once redacted) |
| `dump: true` | Prints the exact JSON and sends nothing; `dump: "/data/report.json"` writes it instead |
| `dir:` | The store, as for `install/2` |
The question needs an interactive shell: IEx on the console or over ssh.
From an `rpc` or a script, with no terminal to answer on, it shows the
summary and cancels; `yes: true` sends without asking, as
`Precompiled.Host.report(yes: true)` does in Livebook.
The report goes to the configured source's `/reports`, over the same
https and CA certificates as the install: the firmware's `config
:precompiled, :device, source:`, or the official API. It never takes a
source per call, and a `file://` bundle has nowhere to send to
(`{:error, :bundle_source}`). `enabled: false` in the firmware turns it
off too (`:off`).
A line is sent only when the signed batch lists its package, as a
package or as a dependency of a build the install planned: a private
package's name stays on the device, shown in the summary as `not sent:
not in the public index`. Otherwise, what is sent is what the host's report sends (see
[Troubleshooting](troubleshooting.md#what-is-sent-and-what-never-is)),
with the device's facts in place of the build's: the Elixir and OTP
versions, OS family and CPU architecture; the target, Nerves system and
version when the source knows that system (its systems table lists it,
or the install used a build made for it), `custom` otherwise; and the
version and checksum of each package the install planned and of its
build's dependencies. Never sent: the printed details, paths, the host
name, serial numbers, config values or environment variables.
A new report prints its id, the one thing needed to retract it
([Retracting a report](troubleshooting.md#retracting-a-report)).
`report/1` never raises; it returns what happened (`{:sent, id, false}`,
`:cancelled`, `:no_report`, `{:error, why}`, ...).
## The cache
Installs stay in the store on `/data` across reboots, but nothing is
loaded at boot: after a reboot `list/0` shows them as cached, not loaded.
Installing the same build again loads it from the store with no download,
after checking every cached file against the signed hashes of the current
batch; a cached build the batch no longer names, or one whose files
changed, is downloaded again and never loaded. The builds in the store
are bounded by `max_bytes`: the least recently used builds that are not
loaded are evicted to make room before anything is downloaded.
`Precompiled.clean/0` empties the store.
A network install also keeps the documents it fetches by their sha256,
each manifest and the batch's systems table, in the store's document
cache (`/data/precompiled/.documents`), and the next call reads them from
there instead of downloading them again. On a device they are most of
what an install downloads: a systems table of 180 KB and a manifest of up
to a few MB, against a few hundred KB of files. A copy is used only when
its bytes hash to the sha256 the verified batch names, the same check a
download gets, so it is byte for byte what the source would send; any
other copy is removed and the document downloaded again. The batch and
the root are never kept there: every call asks for the batch (a
conditional request), so a new batch is seen at once.
The document cache has its own bound, `max_document_bytes` (32 MB),
apart from `max_bytes`, and drops the least recently used documents
first. So the store can take up to `max_bytes` plus `max_document_bytes`
on `/data`, 96 MB by default. A call writes the documents it fetched
after its install, also after one that failed. When staging finds the
disk full, the call empties the document cache, keeps no documents
itself, and stages once more; with no documents to free, or when the
disk is still full, it fails with `{:enospc, path}`. On a small `/data`,
set `max_document_bytes: 0` in the `:device` config, or call
`Precompiled.clean/0`. A dry run reads the document cache but never
writes it. A `file://` bundle install neither reads nor writes it, but
empties it like any install when the disk is full. `Precompiled.clean/0`
empties it with the rest.
When the source cannot be reached and the batch kept in `.trust` still
passes its checks, a call plans from the kept documents, so a build that
is in the store installs again with no network; one that is not still
needs its files downloaded. A kept batch that has expired, or that is
more than 24 hours old, is refused as it is online, kept documents or
not.
The store dir is created `0700`, and must not be writable by group or
others and must be owned by the VM's user. One call at a time changes it.
The same store reached through a link (`/data` is a link to `/root` on
Nerves) is one store; the store dir itself must not be a symlink.
## Bundles: installing with no network
A bundle is a directory with the API's own layout, holding exactly what a
device needs, written on a host with network:
mix precompiled.bundle recon circuits_gpio@2.3.1 --out bundle \
--system nerves_system_rpi4@2.2.1 --otp 29 --elixir 1.20.3
It plans on the host as the device would, from the device's facts: the
flags (`--pure` for a device with no Nerves system, `--cpu` for another
CPU than `aarch64-unknown-linux-gnu`), or the JSON a dry run wrote on the
device itself (`Precompiled.install(:recon, dry_run: true, report:
"/data/report.json")`, then `--device-report report.json`). Every byte is
checked against its signed hash before it is written. `mix help
precompiled.bundle` has the details.
Copy the directory to the device (a USB stick, or `sftp` to `/data`) and
install from it:
```elixir
Precompiled.install([:recon, :circuits_gpio], source: "file:///data/bundle")
```
A `file://` install opens no connection and needs no network apps. The
device checks everything again, exactly as over https. A bundle's
`batch.json` is the online batch, so it is valid for 24 hours after the
portal issued it. For a device that stays offline longer, the bundle
carries an `offline.json`, signed by the root's `offline` role with
`mix portal.precompiled.sign_offline` from the portal's repository (see
its `PRECOMPILED_API.md`, "Offline bundles"), within a day of the batch's
issue. An offline document has no expiry and needs no clock. The device
honours it only from a `file://` source, only when its root has an
`offline` role (a device can adopt a newer root from the bundle's
`root.json`, when that root chains from the one it trusts), and never with
a sequence below the highest it has seen. The root this library ships has
no `offline` role yet, so for now a bundle is valid for its batch's 24
hours.
## Trust and CA certificates
The device checks the same signed chain as the host: see
[Trust on the device](trust.md#trust-on-the-device) and
[CA certificates](trust.md#ca-certificates).
## Not supported
- **Hot upgrades.** An app that is present is refused, never replaced:
no appups and no `code_change`.
- **Surviving a firmware update.** Nothing is loaded at boot anyway. After
an update a cached build is used only when it still matches the new
firmware; the firmware itself should include what it needs.
- **Git, path or private packages**, and anything that is not in the
signed batch.
- **Protocol consolidation.** An installed protocol implementation for a
protocol the release consolidated is not dispatched; the install says so
with a `WARN` line.