mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-10-10 16:52:47 +03:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f65500c37 | ||
|
|
2ef2323fbd | ||
|
|
9f2cfb747c | ||
|
|
aabbda35fd | ||
|
|
69b76c091e | ||
|
|
2c33d40d0e | ||
|
|
ec9c88efa1 | ||
|
|
6b6766c04e | ||
|
|
6997d3d330 | ||
|
|
11c2183cc3 | ||
|
|
760d24e9af | ||
|
|
624d2a7ca9 | ||
|
|
e72657b53e | ||
|
|
1be9818f1a | ||
|
|
e37a3e9a63 | ||
|
|
f0772ce580 | ||
|
|
88ff2dd9e8 | ||
|
|
9def198180 | ||
|
|
3708a567cc | ||
|
|
9deb34fa16 | ||
|
|
d109cc0ef8 | ||
|
|
d5cfc8ca84 | ||
|
|
f795ffa250 | ||
|
|
cc93ea037b | ||
|
|
9e353892c7 | ||
|
|
774bba415e |
@@ -59,10 +59,16 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Start container
|
||||
run: |
|
||||
mkdir -p /tmp/frigate-config
|
||||
mkdir -p /tmp/frigate-config /tmp/frigate-media
|
||||
printf 'mqtt:\n enabled: false\ncameras: {}\n' > /tmp/frigate-config/config.yml
|
||||
# simulate a root-era install: root-owned 0600 jwt secret pre-exists
|
||||
docker run --rm -v /tmp/frigate-config:/config --entrypoint bash \
|
||||
${{ steps.setup.outputs.image-name }}-amd64 \
|
||||
-c "python3 -c 'import secrets; open(\"/config/.jwt_secret\",\"w\").write(secrets.token_hex(64))' && chmod 600 /config/.jwt_secret && chown 0:0 /config/.jwt_secret"
|
||||
docker run -d --name frigate --shm-size 256m \
|
||||
-v /tmp/frigate-config:/config \
|
||||
-v /tmp/frigate-media:/media/frigate \
|
||||
--mount type=tmpfs,target=/tmp/cache,tmpfs-size=100000000 \
|
||||
-p 5000:5000 -p 8971:8971 \
|
||||
${{ steps.setup.outputs.image-name }}-amd64
|
||||
- name: Wait for API
|
||||
@@ -91,16 +97,93 @@ jobs:
|
||||
echo "response carries frame-ancestors, which breaks cross-origin iframe embedding"
|
||||
exit 1
|
||||
fi
|
||||
docker exec frigate /usr/local/nginx/sbin/nginx -t
|
||||
# -t must NOT run as root: ngx_create_paths would chown the live cache
|
||||
# and temp dirs to the `user root` directive user, breaking the workers.
|
||||
# stdout goes to /dev/null because -t reopens the config's
|
||||
# error_log/access_log /dev/stdout by path, and the docker exec pipe
|
||||
# is root-owned; -t reports on stderr, so nothing is lost
|
||||
docker exec frigate /command/s6-setuidgid frigate bash -c '/usr/local/nginx/sbin/nginx -e stderr -t -c /tmp/nginx/conf/nginx.conf >/dev/null'
|
||||
docker exec frigate stat -c %a /etc/letsencrypt/live/frigate/privkey.pem | grep -qx 600
|
||||
docker exec frigate stat -c %a /dev/shm/go2rtc.yaml | grep -qx 640
|
||||
- name: Assert services run as non-root
|
||||
run: |
|
||||
ps_out=$(docker exec frigate ps -eo user=,comm=)
|
||||
echo "$ps_out"
|
||||
assert_nonroot() {
|
||||
# the process must exist AND no instance of it may run as root
|
||||
echo "$ps_out" | grep -qw "$1" || { echo "$1 is not running"; exit 1; }
|
||||
if echo "$ps_out" | grep -w "$1" | grep -q '^root'; then
|
||||
echo "$1 is running as root"; exit 1
|
||||
fi
|
||||
}
|
||||
assert_nonroot python3
|
||||
assert_nonroot go2rtc
|
||||
assert_nonroot nginx
|
||||
# root-era jwt secret must have been captured by the sweep and the
|
||||
# auth stack must be functional: wrong creds => clean 401, not 500
|
||||
docker exec frigate stat -c %u /config/.jwt_secret | grep -qx "$(docker exec frigate id -u frigate)"
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:5000/api/login \
|
||||
-H 'content-type: application/json' -d '{"user":"admin","password":"definitely-wrong"}')
|
||||
[ "$code" = "401" ] || { echo "login endpoint returned $code"; exit 1; }
|
||||
# nginx runtime state must belong to the runtime user (a root nginx -t
|
||||
# in the step above would have chowned it to root)
|
||||
owners=$(docker exec frigate stat -c %U /tmp/nginx /dev/shm/nginx_cache)
|
||||
echo "$owners"
|
||||
if echo "$owners" | grep -qvx frigate; then
|
||||
echo "nginx runtime dirs are not owned by frigate"; exit 1
|
||||
fi
|
||||
# runtime user can write recordings storage
|
||||
docker exec frigate /command/s6-setuidgid frigate touch /media/frigate/.write-probe
|
||||
docker exec frigate rm /media/frigate/.write-probe
|
||||
# /tmp/cache is a tmpfs mount here, as the docs recommend: it arrives
|
||||
# root-owned, and the ZMQ IPC sockets live in it
|
||||
docker exec frigate /command/s6-setuidgid frigate touch /tmp/cache/.write-probe
|
||||
docker exec frigate rm /tmp/cache/.write-probe
|
||||
# bundled models must be readable by the runtime user: they are baked
|
||||
# in as root, and archive members can carry root-only modes
|
||||
docker exec frigate /command/s6-setuidgid frigate sh -c '
|
||||
for f in /cpu_model.tflite /edgetpu_model.tflite /cpu_audio_model.tflite \
|
||||
/labelmap.txt /audio-labelmap.txt /openvino-model/*; do
|
||||
[ -e "$f" ] || continue
|
||||
test -r "$f" || { echo "$f is not readable by the runtime user"; exit 1; }
|
||||
done'
|
||||
- name: Assert escape hatch restores root
|
||||
run: |
|
||||
mkdir -p /tmp/frigate-config-root
|
||||
printf 'mqtt:\n enabled: false\ncameras: {}\n' > /tmp/frigate-config-root/config.yml
|
||||
# pre-seed a sentinel: the assertion below is that the escape hatch
|
||||
# DELETES it. Against a fresh dir the absence check passes vacuously
|
||||
# and proves nothing about the rm -f in the prepare script.
|
||||
echo "2:1000:1000" > /tmp/frigate-config-root/.permissions_version
|
||||
docker run -d --name frigate-root --shm-size 256m \
|
||||
-e FRIGATE_RUN_AS_ROOT=true \
|
||||
-v /tmp/frigate-config-root:/config \
|
||||
${{ steps.setup.outputs.image-name }}-amd64
|
||||
up=0
|
||||
for i in $(seq 1 60); do
|
||||
docker exec frigate-root curl -fs http://127.0.0.1:5000/api/version && up=1 && break
|
||||
sleep 5
|
||||
done
|
||||
if [ "$up" -ne 1 ]; then echo "escape hatch container never healthy"; docker logs frigate-root; exit 1; fi
|
||||
ps_out=$(docker exec frigate-root ps -eo user=,comm=)
|
||||
echo "$ps_out"
|
||||
echo "$ps_out" | grep -w python3 | grep -q '^root'
|
||||
echo "$ps_out" | grep -w go2rtc | grep -q '^root'
|
||||
echo "$ps_out" | grep -w nginx | grep -q '^root'
|
||||
# escape hatch must have DELETED the pre-seeded sentinel. written as
|
||||
# an if because bash exempts a negated command from set -e
|
||||
if docker exec frigate-root test -f /config/.permissions_version; then
|
||||
echo "escape hatch did not delete the sweep sentinel"; exit 1
|
||||
fi
|
||||
docker rm -f frigate-root
|
||||
- name: Assert PUID/PGID remapping
|
||||
run: |
|
||||
mkdir -p /tmp/frigate-config-puid
|
||||
mkdir -p /tmp/frigate-config-puid /tmp/frigate-media-puid
|
||||
printf 'mqtt:\n enabled: false\ncameras: {}\n' > /tmp/frigate-config-puid/config.yml
|
||||
docker run -d --name frigate-puid --shm-size 256m \
|
||||
-e PUID=1500 -e PGID=1500 \
|
||||
-v /tmp/frigate-config-puid:/config \
|
||||
-v /tmp/frigate-media-puid:/media/frigate \
|
||||
${{ steps.setup.outputs.image-name }}-amd64
|
||||
up=0
|
||||
for i in $(seq 1 60); do
|
||||
@@ -110,7 +193,7 @@ jobs:
|
||||
if [ "$up" -ne 1 ]; then echo "PUID container never became healthy"; docker logs frigate-puid; exit 1; fi
|
||||
docker exec frigate-puid id -u frigate | grep -qx 1500
|
||||
docker exec frigate-puid id -g frigate | grep -qx 1500
|
||||
docker exec frigate-puid cat /config/.permissions_version | grep -qx "1:1500:1500"
|
||||
docker exec frigate-puid cat /config/.permissions_version | grep -qx "2:1500:1500"
|
||||
# second boot must skip the sweep (sentinel hit). Poll rather than
|
||||
# sleep: the string can only come from the second boot (the first
|
||||
# had no sentinel), so grepping the full log is unambiguous.
|
||||
|
||||
@@ -146,6 +146,10 @@ RUN wget -q https://github.com/openvinotoolkit/open_model_zoo/raw/master/data/da
|
||||
RUN wget -qO - https://www.kaggle.com/api/v1/models/google/yamnet/tfLite/classification-tflite/1/download | tar xvz && mv 1.tflite cpu_audio_model.tflite
|
||||
COPY audio-labelmap.txt .
|
||||
|
||||
# tar restores the archive's modes and the yamnet member ships 0700, so without
|
||||
# this the unprivileged runtime user cannot read the audio model
|
||||
RUN chmod -R a+rX /rootfs
|
||||
|
||||
|
||||
FROM wget AS s6-overlay
|
||||
ARG TARGETARCH
|
||||
|
||||
@@ -6,6 +6,26 @@ set -o errexit -o nounset -o pipefail
|
||||
|
||||
# Logs should be sent to stdout so that s6 can collect them
|
||||
|
||||
# Signal the master directly rather than running `nginx -s reload`. That would
|
||||
# have root parse /tmp/nginx/conf, which the unprivileged nginx user can
|
||||
# rewrite, and nginx acts on path directives while loading a config: it creates
|
||||
# them and chowns them to the configured user.
|
||||
function reload_nginx() {
|
||||
local pid
|
||||
|
||||
if ! pid=$(cat /tmp/nginx/nginx.pid 2>/dev/null); then
|
||||
echo "[ERROR] No nginx pid file found, not reloading"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ ! "$pid" =~ ^[0-9]+$ ]] || [[ "$(cat "/proc/${pid}/comm" 2>/dev/null)" != "nginx" ]]; then
|
||||
echo "[ERROR] nginx pid file does not name a running nginx process, not reloading"
|
||||
return 0
|
||||
fi
|
||||
|
||||
kill -HUP "$pid"
|
||||
}
|
||||
|
||||
echo "[INFO] Starting certsync..."
|
||||
|
||||
lefile="/etc/letsencrypt/live/frigate/fullchain.pem"
|
||||
@@ -49,7 +69,7 @@ do
|
||||
then
|
||||
echo "[INFO] Reloading nginx to refresh TLS certificate"
|
||||
echo "$lefile: $leprint"
|
||||
/usr/local/nginx/sbin/nginx -s reload
|
||||
reload_nginx
|
||||
fi
|
||||
|
||||
sleep 60
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
|
||||
set -o errexit -o nounset -o pipefail
|
||||
|
||||
# $HOME is /root from the container env and survives s6-setuidgid, so cache
|
||||
# and telemetry writes (huggingface, openvino) fail after the drop. Set it
|
||||
# before opt_in_out so the opt-out marker lands where the service will look.
|
||||
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
|
||||
export HOME=/config
|
||||
fi
|
||||
|
||||
# opt out of openvino telemetry
|
||||
if [ -e /usr/local/bin/opt_in_out ]; then
|
||||
/usr/local/bin/opt_in_out --opt_out > /dev/null 2>&1
|
||||
@@ -30,4 +37,8 @@ cd /opt/frigate || echo "[ERROR] Failed to change working directory to /opt/frig
|
||||
|
||||
# Replace the bash process with the Frigate process, redirecting stderr to stdout
|
||||
exec 2>&1
|
||||
exec python3 -u -m frigate
|
||||
if [[ "$(id -u)" -ne 0 || "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]]; then
|
||||
exec python3 -u -m frigate
|
||||
else
|
||||
exec s6-setuidgid frigate python3 -u -m frigate
|
||||
fi
|
||||
|
||||
@@ -110,6 +110,16 @@ fi
|
||||
readonly homekit_config_path="/config/go2rtc_homekit.yml"
|
||||
setup_homekit_config "${homekit_config_path}"
|
||||
|
||||
if [[ "$(id -u)" -eq 0 && "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
|
||||
chown go2rtc:go2rtc /dev/shm/go2rtc.yaml 2>/dev/null || true
|
||||
# go2rtc rewrites this in place (os.WriteFile, no rename), so owning the
|
||||
# file is enough; /config grants frigate-data traverse only. Tolerated so
|
||||
# a chown-refusing mount (NFS root_squash) degrades pairing persistence
|
||||
# instead of crash-looping the service
|
||||
chown go2rtc:frigate-data "${homekit_config_path}" 2>/dev/null && chmod 664 "${homekit_config_path}" 2>/dev/null || \
|
||||
echo "[WARN] Could not hand ${homekit_config_path} to the go2rtc user; HomeKit pairing changes may not persist"
|
||||
fi
|
||||
|
||||
readonly config_path="/config"
|
||||
|
||||
if [[ -x "${config_path}/go2rtc" ]]; then
|
||||
@@ -125,4 +135,8 @@ echo "[INFO] Starting go2rtc..."
|
||||
# Use HomeKit config as the primary config so writebacks go there
|
||||
# The main config from Frigate will be loaded as a secondary config
|
||||
exec 2>&1
|
||||
exec "${binary_path}" -config="${homekit_config_path}" -config=/dev/shm/go2rtc.yaml
|
||||
if [[ "$(id -u)" -ne 0 || "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]]; then
|
||||
exec "${binary_path}" -config="${homekit_config_path}" -config=/dev/shm/go2rtc.yaml
|
||||
else
|
||||
exec s6-setuidgid go2rtc "${binary_path}" -config="${homekit_config_path}" -config=/dev/shm/go2rtc.yaml
|
||||
fi
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
set -e
|
||||
|
||||
# Wait for PID file to exist.
|
||||
while ! test -f /run/nginx.pid; do sleep 1; done
|
||||
while ! test -f /tmp/nginx/nginx.pid; do sleep 1; done
|
||||
|
||||
@@ -59,10 +59,20 @@ function set_worker_processes() {
|
||||
cpus=4
|
||||
fi
|
||||
|
||||
# we need to catch any errors because sed will fail if user has bind mounted a custom nginx file
|
||||
sed -i "s/worker_processes auto;/worker_processes ${cpus};/" /usr/local/nginx/conf/nginx.conf || true
|
||||
sed -i "s/worker_processes auto;/worker_processes ${cpus};/" /tmp/nginx/conf/nginx.conf
|
||||
}
|
||||
|
||||
# Rebuilt root-owned and fresh every start. A previous unprivileged nginx owned
|
||||
# this tree, and the cp and tempio writes below run as root: without wiping it
|
||||
# first, a planted symlink here would let those writes land on any root file.
|
||||
# rm does not traverse symlinks, and the bare mkdir fails closed if /tmp/nginx
|
||||
# is raced into a symlink before we can create it.
|
||||
rm -rf /tmp/nginx
|
||||
mkdir /tmp/nginx
|
||||
mkdir -p /tmp/nginx/conf /tmp/nginx/client_body /tmp/nginx/proxy \
|
||||
/tmp/nginx/fastcgi /tmp/nginx/uwsgi /tmp/nginx/scgi
|
||||
cp -r /usr/local/nginx/conf/. /tmp/nginx/conf/
|
||||
|
||||
set_worker_processes
|
||||
|
||||
# ensure the directory for ACME challenges exists
|
||||
@@ -87,15 +97,40 @@ nginx_settings=$(python3 /usr/local/nginx/get_nginx_settings.py)
|
||||
# build templates for optional FRIGATE_BASE_PATH environment variable
|
||||
echo "$nginx_settings" | \
|
||||
tempio -template /usr/local/nginx/templates/base_path.gotmpl \
|
||||
-out /usr/local/nginx/conf/base_path.conf
|
||||
-out /tmp/nginx/conf/base_path.conf
|
||||
|
||||
# build templates for additional network settings
|
||||
echo "$nginx_settings" | \
|
||||
tempio -template /usr/local/nginx/templates/listen.gotmpl \
|
||||
-out /usr/local/nginx/conf/listen.conf
|
||||
-out /tmp/nginx/conf/listen.conf
|
||||
|
||||
if [[ "$(id -u)" -eq 0 && "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
|
||||
chown -R frigate:frigate /tmp/nginx
|
||||
# heal the cache if a root `nginx -t` chowned it (ngx_create_paths chowns
|
||||
# every cycle path to the `user` directive user when run as root)
|
||||
if [ -d /dev/shm/nginx_cache ]; then
|
||||
chown -R frigate:frigate /dev/shm/nginx_cache
|
||||
fi
|
||||
# error_log/access_log /dev/stdout make nginx REOPEN the s6 log pipe by
|
||||
# path, and s6 created it root-owned 0600; without this the non-root
|
||||
# master exits with "open() /dev/stdout failed (13: Permission denied)"
|
||||
chown frigate /dev/stdout
|
||||
# self-signed certs are root-generated; tolerant because mounted certs may be :ro
|
||||
if [ -f "$letsencrypt_path/privkey.pem" ]; then
|
||||
chown frigate:frigate "$letsencrypt_path/privkey.pem" "$letsencrypt_path/fullchain.pem" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# Replace the bash process with the NGINX process, redirecting stderr to stdout
|
||||
exec 2>&1
|
||||
exec \
|
||||
s6-notifyoncheck -t 30000 -n 1 \
|
||||
nginx
|
||||
# -e stderr: the compile-time default error log under /usr/local/nginx/logs
|
||||
# is not writable by the runtime user and would alert before config load
|
||||
if [[ "$(id -u)" -ne 0 || "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]]; then
|
||||
exec \
|
||||
s6-notifyoncheck -t 30000 -n 1 \
|
||||
nginx -e stderr -c /tmp/nginx/conf/nginx.conf
|
||||
else
|
||||
exec \
|
||||
s6-notifyoncheck -t 30000 -n 1 \
|
||||
s6-setuidgid frigate nginx -e stderr -c /tmp/nginx/conf/nginx.conf
|
||||
fi
|
||||
|
||||
@@ -153,7 +153,31 @@ if [[ "$(id -u)" -eq 0 ]]; then
|
||||
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]]; then
|
||||
rm -f /config/.permissions_version
|
||||
else
|
||||
/usr/local/bin/fix-ownership --sentinel /config/.permissions_version \
|
||||
# Only bless the sentinel when a mount backs /media/frigate itself or
|
||||
# below it. A parent /media mount doesn't count: a dedicated
|
||||
# /media/frigate volume added later would be shadowed and skipped.
|
||||
sentinel_args=(--sentinel /config/.permissions_version)
|
||||
if ! awk '$2 == "/media/frigate" || $2 ~ /^\/media\/frigate\//' /proc/mounts | grep -q .; then
|
||||
sentinel_args=()
|
||||
fi
|
||||
/usr/local/bin/fix-ownership "${sentinel_args[@]}" \
|
||||
"${PUID:-1000}" "${PGID:-1000}" /config /media/frigate
|
||||
fi
|
||||
fi
|
||||
|
||||
# Not in the image, and the runtime user cannot create it under root-owned
|
||||
# /media. Must stay after the sweep, which reads an absent /media/frigate as an
|
||||
# unmounted volume rather than a swept one
|
||||
if [[ "$(id -u)" -eq 0 && ! -d /media/frigate ]]; then
|
||||
mkdir -p /media/frigate
|
||||
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
|
||||
chown "${PUID:-1000}:${PGID:-1000}" /media/frigate
|
||||
fi
|
||||
fi
|
||||
|
||||
# Usually a tmpfs mount, so it arrives root-owned and is outside the swept
|
||||
# volumes. The runtime user binds its ZMQ IPC sockets in here.
|
||||
if [[ "$(id -u)" -eq 0 && "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
|
||||
mkdir -p /tmp/cache
|
||||
chown "${PUID:-1000}:${PGID:-1000}" /tmp/cache
|
||||
fi
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
# on every boot)
|
||||
#
|
||||
# Only files whose uid OR gid differs are touched, so re-runs are cheap.
|
||||
# lost+found is skipped: it belongs to the filesystem, not to Frigate, and
|
||||
# fsck puts recovered fragments of arbitrary files there under root-only 0700.
|
||||
# Top-level /config additionally grants group frigate-data TRAVERSE ONLY
|
||||
# (g+rx) so the separate go2rtc user can reach its pre-created HomeKit file
|
||||
# on hosts where /config is mounted 0700. Never g+w: directory write means
|
||||
@@ -22,7 +24,7 @@ set -o errexit -o nounset -o pipefail
|
||||
# Permissions-layout epoch. Bump to force a one-time re-sweep on upgrade
|
||||
# (e.g. when the privilege-drop release must capture files created as root
|
||||
# since the previous sweep).
|
||||
schema=1
|
||||
schema=2
|
||||
|
||||
dry_run=0
|
||||
sentinel=""
|
||||
@@ -76,11 +78,13 @@ for path in "$@"; do
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "[INFO] fix-ownership: scanning ${path} for ownership mismatches; this may take a while on large filesystems"
|
||||
|
||||
# find may fail mid-walk on a live volume (file deleted under it) or on a
|
||||
# stale mount. Tolerate it rather than aborting under errexit, but never
|
||||
# read a failed scan as "nothing to do": that would record the sweep as
|
||||
# complete without having looked.
|
||||
if ! count=$(find "$path" \( -not -uid "$target_uid" -o -not -gid "$target_gid" \) -printf '.' 2>/dev/null | wc -c); then
|
||||
if ! count=$(find "$path" -name lost+found -prune -o \( -not -uid "$target_uid" -o -not -gid "$target_gid" \) -printf '.' 2>/dev/null | wc -c); then
|
||||
swept_clean=0
|
||||
echo "[WARN] fix-ownership: could not scan ${path}; will retry on next boot"
|
||||
continue
|
||||
@@ -98,17 +102,41 @@ for path in "$@"; do
|
||||
echo "[WARN] fix-ownership: ${path} contains symlinked directories; ownership behind them is not managed and must be aligned by hand"
|
||||
fi
|
||||
|
||||
echo "[WARN] fix-ownership: adjusting ownership of ${count} entries under ${path}; on large recordings volumes this can take a long time"
|
||||
echo "[WARN] fix-ownership: adjusting ownership of ${count} entries under ${path}"
|
||||
if [[ "$dry_run" -eq 1 ]]; then
|
||||
echo "[INFO] fix-ownership: dry run, not changing ${path}"
|
||||
continue
|
||||
fi
|
||||
|
||||
find "$path" \( -not -uid "$target_uid" -o -not -gid "$target_gid" \) \
|
||||
-exec chown -h "${target_uid}:${target_gid}" {} + || {
|
||||
# -print feeds the progress counter while -exec {} + keeps the chown
|
||||
# batched; the scan above is what makes a real percentage possible
|
||||
started=$SECONDS
|
||||
if find "$path" -name lost+found -prune -o \( -not -uid "$target_uid" -o -not -gid "$target_gid" \) \
|
||||
-print -exec chown -h "${target_uid}:${target_gid}" {} + \
|
||||
| awk -v total="$count" -v path="$path" '
|
||||
BEGIN { next_pct = 5 }
|
||||
{
|
||||
pct = int(NR * 100 / total)
|
||||
if (pct > 100) pct = 100
|
||||
if (pct >= next_pct) {
|
||||
printf "[INFO] fix-ownership: %s %d%% (%d/%d entries)\n", path, pct, NR, total
|
||||
# mawk block-buffers to a pipe; without this the whole
|
||||
# progress log arrives at once when the sweep ends
|
||||
fflush()
|
||||
while (next_pct <= pct) next_pct += 5
|
||||
}
|
||||
}'; then
|
||||
elapsed=$((SECONDS - started))
|
||||
if [[ "$elapsed" -ge 60 ]]; then
|
||||
elapsed="$((elapsed / 60))m $((elapsed % 60))s"
|
||||
else
|
||||
elapsed="${elapsed}s"
|
||||
fi
|
||||
echo "[INFO] fix-ownership: finished ${path} in ${elapsed}"
|
||||
else
|
||||
swept_clean=0
|
||||
echo "[WARN] fix-ownership: some entries under ${path} could not be updated (deleted mid-sweep or chown denied); will retry on next mismatch"
|
||||
}
|
||||
fi
|
||||
done
|
||||
|
||||
# go2rtc (separate user) must be able to REACH its HomeKit state in /config.
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
# Copied to /tmp/nginx/conf at startup and loaded with -c from there. Relative
|
||||
# includes resolve against the -c file, but every other path directive resolves
|
||||
# against the compile-time --prefix, so non-include paths must stay absolute.
|
||||
|
||||
daemon off;
|
||||
# Ignored by a non-root master; required by FRIGATE_RUN_AS_ROOT so workers
|
||||
# stay root instead of the compiled-in default user
|
||||
user root;
|
||||
worker_processes auto;
|
||||
|
||||
error_log /dev/stdout warn;
|
||||
pid /var/run/nginx.pid;
|
||||
pid /tmp/nginx/nginx.pid;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
@@ -13,6 +19,12 @@ http {
|
||||
map_hash_bucket_size 256;
|
||||
server_tokens off;
|
||||
|
||||
client_body_temp_path /tmp/nginx/client_body;
|
||||
proxy_temp_path /tmp/nginx/proxy;
|
||||
fastcgi_temp_path /tmp/nginx/fastcgi;
|
||||
uwsgi_temp_path /tmp/nginx/uwsgi;
|
||||
scgi_temp_path /tmp/nginx/scgi;
|
||||
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
|
||||
@@ -36,6 +36,16 @@ if ! [[ "$puid" =~ ^[0-9]+$ && "$pgid" =~ ^[0-9]+$ ]]; then
|
||||
fi
|
||||
|
||||
echo "[INFO] Using image ${IMAGE} (override with FRIGATE_IMAGE=...)"
|
||||
if ! docker image inspect "${IMAGE}" >/dev/null 2>&1; then
|
||||
echo "[INFO] ${IMAGE} is not present locally and has to be pulled first; this may take a while"
|
||||
fi
|
||||
|
||||
if [[ -n "$dry_run_flag" ]]; then
|
||||
echo "[INFO] Dry run: reporting what would change under ${config_dir} and ${media_dir}, changing nothing"
|
||||
else
|
||||
echo "[INFO] Aligning ${config_dir} and ${media_dir} to ${puid}:${pgid}; this may take a while on large filesystems"
|
||||
fi
|
||||
|
||||
# shellcheck disable=SC2086
|
||||
docker run --rm \
|
||||
-v "${config_dir}:/config" \
|
||||
|
||||
@@ -13,6 +13,16 @@ TRT_VER=${TRT_VER:-$(cat /etc/TENSORRT_VER)}
|
||||
OUTPUT_FOLDER="${MODEL_CACHE_DIR}/${TRT_VER}"
|
||||
YOLO_MODELS=${YOLO_MODELS:-""}
|
||||
|
||||
# This runs as root after prepare's sentinel-guarded sweep, so the dirs and
|
||||
# engines it creates below are the runtime user's to fix up, on every exit path
|
||||
function hand_off_ownership() {
|
||||
if [[ "$(id -u)" -eq 0 && "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
|
||||
/usr/local/bin/fix-ownership "${PUID:-1000}" "${PGID:-1000}" \
|
||||
/config/model_cache "${MODEL_CACHE_DIR}"
|
||||
fi
|
||||
}
|
||||
trap hand_off_ownership EXIT
|
||||
|
||||
# Create output folder
|
||||
mkdir -p ${OUTPUT_FOLDER}
|
||||
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
---
|
||||
id: non_root
|
||||
title: Running as a non-root user
|
||||
---
|
||||
|
||||
Frigate's services run as an unprivileged user inside the container. The main Frigate process and nginx run as `frigate`, and go2rtc runs as its own more restricted `go2rtc` user. Only the s6 init system and the certsync helper stay root.
|
||||
|
||||
By default the runtime user is uid/gid `1000:1000`. You can change it with `PUID`/`PGID`, or bypass Frigate's user handling entirely with Docker's own `user:`.
|
||||
|
||||
## Run modes
|
||||
|
||||
| Mode | How to enable | Ownership of `/config` and `/media/frigate` | `read_only: true` |
|
||||
| -------------------------------- | -------------------------------------- | ---------------------------------------------------------- | ----------------- |
|
||||
| Default | nothing, this is the default | Aligned to `1000:1000` on first boot | Not supported |
|
||||
| `PUID`/`PGID` | `PUID=1001`, `PGID=1001` | Aligned to the values you set, on first boot | Not supported |
|
||||
| Docker-native user | `user: "1001:1001"` | You own it, Frigate never changes ownership | Not supported |
|
||||
| Root (escape hatch) | `FRIGATE_RUN_AS_ROOT=true` | Never touched | Not supported |
|
||||
|
||||
`PUID`/`PGID` remapping runs `usermod` at startup, which writes to `/etc/passwd`, so it can't work with a read-only root filesystem. That combination fails fast at startup with a message pointing here rather than failing obscurely later.
|
||||
|
||||
`FRIGATE_RUN_AS_ROOT` is matched against the exact lowercase string `true`. `True`, `TRUE`, and `1` are all ignored.
|
||||
|
||||
## Migrating an existing install
|
||||
|
||||
Volumes created by earlier versions of Frigate are owned by root. Ownership has to be aligned with the runtime user once.
|
||||
|
||||
There are two independent prerequisites to upgrading, and doing one without the other is the most common way this goes wrong. This section covers volume ownership. If you use a Coral, a GPU, or any other accelerator, read [Hardware device access](#hardware-device-access) as well: those devices are reachable today because Frigate runs as root, and they need host side work that has nothing to do with your volumes.
|
||||
|
||||
This happens automatically on the first boot after upgrading, but on large recordings volumes it's much better to do it from the host beforehand. The boot sweep runs before any service starts, so a multi-terabyte `/media/frigate` can hold the container in startup long enough for Docker's healthcheck to mark it unhealthy, and orchestrators that react to health will restart it mid-sweep. If you'd rather not run the script, raise the healthcheck start period instead (`--start-period=1800s`, or `start_period: 1800s` under `healthcheck:` in compose).
|
||||
|
||||
Grab `fix-permissions.sh` from `docker/migration/` in the Frigate repo and dry run it first:
|
||||
|
||||
```bash
|
||||
./fix-permissions.sh --dry-run /path/to/your/config /path/to/your/storage
|
||||
```
|
||||
|
||||
That reports how many entries would change and touches nothing. When it looks right, run it without `--dry-run`:
|
||||
|
||||
```bash
|
||||
./fix-permissions.sh /path/to/your/config /path/to/your/storage
|
||||
```
|
||||
|
||||
Both the script and the boot sweep report progress as they go, so you can tell a slow sweep apart from a stuck one:
|
||||
|
||||
```
|
||||
[INFO] fix-ownership: scanning /media/frigate for ownership mismatches; this may take a while on large filesystems
|
||||
[WARN] fix-ownership: adjusting ownership of 4823941 entries under /media/frigate
|
||||
[INFO] fix-ownership: /media/frigate 5% (241197/4823941 entries)
|
||||
[INFO] fix-ownership: /media/frigate 10% (482394/4823941 entries)
|
||||
[INFO] fix-ownership: finished /media/frigate in 12m 4s
|
||||
```
|
||||
|
||||
The scan has no percentage behind it because the total isn't known until it finishes. Watch the boot sweep with `docker logs -f frigate`.
|
||||
|
||||
Pass `PUID` and `PGID` as the third and fourth arguments if you're not using the default `1000:1000`. The script wraps the same `fix-ownership` helper the container uses, so it's the same logic either way. Override the image it pulls with `FRIGATE_IMAGE=...` if you're not on `stable`.
|
||||
|
||||
Once the volumes are aligned, start Frigate normally. A sentinel at `/config/.permissions_version` records what was done, so later boots skip the sweep entirely unless you change `PUID`/`PGID`.
|
||||
|
||||
`lost+found` is left alone. It belongs to the filesystem rather than to Frigate, and `fsck` recovers fragments of arbitrary files into it under root-only permissions, so handing it to the runtime user would expose whatever ends up there. Expect to see it still owned by root afterward, on any volume that's a dedicated mount.
|
||||
|
||||
If something under your volumes genuinely can't be chowned, a read-only btrfs snapshot directory for example, the sweep warns and names the path, and it deliberately doesn't write the sentinel. That means it retries on the next boot rather than recording a migration that didn't finish. Either move those paths outside `/media/frigate` or expect the scan to repeat.
|
||||
|
||||
### Network storage
|
||||
|
||||
Storing recordings on a NAS is common, and ownership behaves differently there. Check what you have before migrating anything:
|
||||
|
||||
```bash
|
||||
findmnt -T /path/to/your/storage -o TARGET,FSTYPE,OPTIONS
|
||||
```
|
||||
|
||||
**SMB and CIFS** don't store ownership per file at all. It's synthesized from the mount options, so a per-file `chown` fails, and you don't need one. Mount the share as the uid and gid Frigate will run as, and every file already looks correct to the sweep:
|
||||
|
||||
```
|
||||
//nas/frigate /media/frigate cifs credentials=/root/.smb,uid=1000,gid=1000,file_mode=0664,dir_mode=0775 0 0
|
||||
```
|
||||
|
||||
**NFS** exports default to `root_squash` on most servers, which maps the container's root to `nobody`. The recursive chown then fails outright, you get `[WARN] fix-ownership: some entries under /media/frigate could not be updated`, and because the sweep didn't finish it deliberately doesn't write the sentinel, so it retries on the next boot and every boot after.
|
||||
|
||||
The best fix is to not chown over NFS at all. Do it on the server, locally, where there's no squash and no network round trip per file:
|
||||
|
||||
```bash
|
||||
# on the NAS itself, against the exported directory
|
||||
chown -R 1000:1000 /export/frigate
|
||||
```
|
||||
|
||||
Frigate's own sweep then finds nothing to change and records the sentinel normally. If you can't get a shell on the server, the alternatives are to export temporarily with `no_root_squash`, migrate, and put it back, or to leave ownership alone and set `PUID`/`PGID` to whichever uid already owns the files.
|
||||
|
||||
Either way the uid has to mean the same thing on both machines. NFS sends numeric uids, so container uid 1000 is simply uid 1000 on the server no matter what the usernames are.
|
||||
|
||||
Expect the first boot to be slow even when nothing needs changing, because verifying ownership costs a round trip per file. The sentinel makes that a one-time price. **If the sweep runs on every boot rather than once, ownership isn't actually being applied**, and the warning above will tell you so.
|
||||
|
||||
Keep `/config` on local storage regardless. Frigate's database is SQLite and network shares handle its locking poorly. That's a pre-existing recommendation, not something running non-root introduces.
|
||||
|
||||
## Rolling back
|
||||
|
||||
Set `FRIGATE_RUN_AS_ROOT=true` and restart. Everything runs as root again, exactly as it did before. This is the fastest way to get a broken install running while you work out a device permission problem, and it's the recommended fallback for hardware you can't grant access to.
|
||||
|
||||
The escape hatch never changes ownership, and it deletes the sweep sentinel on startup, so switching back to non-root later re-sweeps whatever root created in the meantime. Toggling in either direction is safe.
|
||||
|
||||
## Hardware device access
|
||||
|
||||
This is the part most likely to need work on your host, and it catches people out for a specific reason: your accelerator almost certainly works today *because* Frigate runs as root. Device nodes are commonly owned by `root:root`, and root either matches the file's group or bypasses the check entirely. The runtime user does neither, so a node that was fine yesterday can become unreadable with no change to your Frigate config at all.
|
||||
|
||||
Nothing inside the container can fix that. Device node permissions are set by the host, so the fix belongs there too.
|
||||
|
||||
### Read what your device actually requires
|
||||
|
||||
Find the node and look at its owner, group, and mode:
|
||||
|
||||
```bash
|
||||
ls -ln /dev/dri/renderD128
|
||||
crw-rw---- 1 0 105 226, 128 Jul 5 10:12 /dev/dri/renderD128
|
||||
# ^ ^ ^
|
||||
# | | group GID 105
|
||||
# | owner UID 0 (root)
|
||||
# mode: owner rw, group rw, other none
|
||||
```
|
||||
|
||||
Then ask which of the three permission sets the runtime user lands in. It isn't the owner (that's root), so it gets the group bits only if it belongs to that GID, and otherwise falls through to "other". In the example above "other" is empty, so without membership in group 105 the runtime user cannot open the node at all.
|
||||
|
||||
The trap is a node that looks permissive but isn't. A USB Coral defaults to this:
|
||||
|
||||
```bash
|
||||
ls -ln /dev/bus/usb/004/003
|
||||
crw-rw-r-- 1 0 0 189, 386 Jul 5 10:12 /dev/bus/usb/004/003
|
||||
```
|
||||
|
||||
That's group `0`, so "other" applies to everyone else, and "other" here is read only. `libedgetpu` needs to *write* to the node, so detection fails with `No EdgeTPU was detected` as though no Coral were attached. Read access alone is not enough for most accelerators.
|
||||
|
||||
### Grant access
|
||||
|
||||
Give the runtime user the GID with `EXTRA_GROUPS`, a comma separated list of numeric host GIDs. They're added to both the `frigate` and `go2rtc` users at startup, which matters because go2rtc needs render and video access of its own to run hardware accelerated restreams.
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
EXTRA_GROUPS: "105,44" # host render and video GIDs
|
||||
```
|
||||
|
||||
Use numeric GIDs from the host, not names. Group names don't have to agree between the host and the container, and the kernel only checks the number. If the GID doesn't exist in the image, Frigate creates a placeholder group for it.
|
||||
|
||||
Two things that look like they should work and don't:
|
||||
|
||||
- Docker's `group_add` has no effect in the default or `PUID` modes. `s6-setuidgid` rebuilds the supplementary group list from `/etc/group` when it drops privileges, which discards whatever Docker gave the init process. It *is* the right tool with Docker-native `user:`, where no privilege drop happens and `EXTRA_GROUPS` in turn does nothing.
|
||||
- `privileged: true` doesn't help. It grants capabilities to root, and the runtime user isn't root, so ordinary file permissions on the node still apply.
|
||||
|
||||
If the node's group is `root` or the mode denies the group, no `EXTRA_GROUPS` value can help. You need a udev rule first.
|
||||
|
||||
### Verify before you rely on it
|
||||
|
||||
Check the group landed, then check the runtime user can actually open the node. Test for write, not just read:
|
||||
|
||||
```bash
|
||||
docker exec frigate id frigate
|
||||
docker exec frigate /command/s6-setuidgid frigate sh -c 'test -w /dev/dri/renderD128 && echo ok'
|
||||
docker exec frigate /command/s6-setuidgid go2rtc sh -c 'test -w /dev/dri/renderD128 && echo ok'
|
||||
```
|
||||
|
||||
Permission probes are still only a proxy for the driver working. These exercise the real libraries as the runtime user:
|
||||
|
||||
```bash
|
||||
docker exec frigate /command/s6-setuidgid frigate vainfo
|
||||
docker exec frigate /command/s6-setuidgid frigate python3 -c "import openvino as ov; print(ov.Core().available_devices)"
|
||||
```
|
||||
|
||||
`vainfo` should reach `va_openDriver() returns 0` and list profiles. Complaints about `XDG_RUNTIME_DIR` or an X server above that are normal and harmless. OpenVINO must list `GPU`; if it returns only `CPU`, detection has quietly fallen back and inference will be far slower without any error in the log.
|
||||
|
||||
If something isn't working, the fastest way to tell a permissions problem from anything else is to start the container once with `FRIGATE_RUN_AS_ROOT=true`. If the device appears as root and not otherwise, it's node permissions and a udev rule is the fix. If it's missing either way, the problem is your device mapping or the host, and it isn't related to running non-root.
|
||||
|
||||
### udev rules by device
|
||||
|
||||
Rules go in `/etc/udev/rules.d/` on the host and take effect after:
|
||||
|
||||
```bash
|
||||
sudo udevadm control --reload-rules && sudo udevadm trigger
|
||||
```
|
||||
|
||||
An already-connected device sometimes keeps its original ownership through a trigger. If `ls -ln` doesn't show the new group, replug it, or reboot for a built-in device.
|
||||
|
||||
**Coral USB** needs two rules, because the device re-enumerates after firmware load. It appears as Global Unichip `1a6e` cold and Google `18d1` once running, with a different node each time. A rule covering only `1a6e` gives you a Coral that initializes once and then disappears mid-run.
|
||||
|
||||
```
|
||||
SUBSYSTEM=="usb", ATTRS{idVendor}=="1a6e", GROUP="plugdev", MODE="0664"
|
||||
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", GROUP="plugdev", MODE="0664"
|
||||
```
|
||||
|
||||
Map the whole `/dev/bus/usb` rather than a single node, for the same re-enumeration reason. Most hosts already put `plugdev` at GID 46 and the image agrees, so you often need no `EXTRA_GROUPS` entry for a USB Coral. Confirm with `getent group plugdev` and add the number if your host differs.
|
||||
|
||||
**Coral PCIe** is frequently `crw------- root root`, which nothing but root can open:
|
||||
|
||||
```
|
||||
SUBSYSTEM=="apex", MODE="0660", GROUP="apex"
|
||||
```
|
||||
|
||||
Create the group with `sudo groupadd -f apex`, then add its GID to `EXTRA_GROUPS`.
|
||||
|
||||
**Hailo** follows the same shape. Grant `/dev/hailo0` a group and add that GID:
|
||||
|
||||
```
|
||||
SUBSYSTEM=="hailo_chardev", MODE="0660", GROUP="hailo"
|
||||
```
|
||||
|
||||
**Intel and AMD GPUs** usually need nothing beyond `EXTRA_GROUPS`, since distributions ship a `render` group owning `/dev/dri/renderD128` already. Note the GID often differs between host and image, so pass the host's number rather than assuming the name resolves. Debian based images have no `render` group at all.
|
||||
|
||||
### Quick reference
|
||||
|
||||
| Hardware | Device(s) | What non-root needs |
|
||||
| ------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| Intel/AMD GPU (VAAPI/QSV) | `/dev/dri/renderD128` | Host render GID in `EXTRA_GROUPS`, from `getent group render` |
|
||||
| Intel/AMD NPU | `/dev/accel` | udev rule granting a group, then that GID in `EXTRA_GROUPS` |
|
||||
| Coral USB | `/dev/bus/usb` | udev rules for both `1a6e` and `18d1`; usually already covered by `plugdev` 46 |
|
||||
| Coral PCIe | `/dev/apex_0` | udev rule granting a group, then that GID in `EXTRA_GROUPS` |
|
||||
| Hailo | `/dev/hailo0` | udev rule granting a group, then that GID in `EXTRA_GROUPS` |
|
||||
| NVIDIA | nvidia runtime | Nothing, works with the nvidia-container-toolkit defaults |
|
||||
| AMD ROCm | `/dev/kfd`, `/dev/dri` | Host `video` and `render` GIDs in `EXTRA_GROUPS` |
|
||||
| Raspberry Pi | `/dev/video11` | Host `video` GID in `EXTRA_GROUPS` |
|
||||
| Rockchip | `/dev/dri`, `/dev/dma_heap`, `/dev/rga`, `/dev/mpp_service` | Commonly `root:root` `0600`, so all four need udev rules. If you can't grant all four, use `FRIGATE_RUN_AS_ROOT` |
|
||||
| Axera (AXCL) | `/dev/ax_*` per the AXCL driver docs | Unverified. Check node ownership on your hardware before assuming this works |
|
||||
| Synaptics SL1680 | per the Synaptics docs | Unverified |
|
||||
| MemryX | per the MemryX docs | Still requires `privileged: true`, which means root. Out of scope for non-root operation |
|
||||
| Nvidia Jetson | nvidia runtime plus Jetson nodes | Unverified. The nvidia runtime handles mapping, but check `/dev/nvhost-*` ownership on your board |
|
||||
| VeriSilicon NPU (Teflon) | per the driver, commonly `/dev/galcore` | Unverified. Check node ownership on your hardware before assuming this works |
|
||||
| CPU detector | none | Nothing, no device is opened |
|
||||
| DeepStack, CodeProject.AI | none | Nothing, inference happens over the network |
|
||||
| ZMQ detector | none | Nothing, inference happens over a socket |
|
||||
| Apple Silicon | none | Nothing, the NPU client runs on the host and Frigate reaches it over the network |
|
||||
|
||||
## Known limitations
|
||||
|
||||
`telemetry.stats.network_bandwidth` uses nethogs, which needs `CAP_NET_ADMIN` and `CAP_NET_RAW` and therefore root. The stat is disabled automatically when Frigate isn't running as root, with one warning in the log. Use `FRIGATE_RUN_AS_ROOT=true` if you need it.
|
||||
|
||||
go2rtc's ffmpeg processes no longer appear in Intel GPU stats. Frigate reads per-process GPU usage from `/proc/<pid>/fdinfo`, which the kernel won't let one user read for another user's processes, so anything go2rtc spawns is invisible to it. Overall GPU utilization is unaffected.
|
||||
|
||||
If you mount your own TLS certificate at `/etc/letsencrypt/live/frigate`, the private key has to be readable by the runtime user. Frigate won't change ownership of a certificate you supplied, since the mount may be read-only.
|
||||
|
||||
If you're debugging nginx, run the config check as the runtime user with stdout discarded: `docker exec frigate /command/s6-setuidgid frigate bash -c 'nginx -t -c /tmp/nginx/conf/nginx.conf >/dev/null'`. Running `nginx -t` as root hands nginx's runtime directories to root as a side effect, which breaks the running workers until the service restarts, and the config's `/dev/stdout` logs can't be reopened through a root-owned `docker exec` pipe (the results print on stderr either way).
|
||||
@@ -548,9 +548,7 @@ services:
|
||||
|
||||
### Recommended security options
|
||||
|
||||
Frigate does not need elevated container privileges for most setups. The
|
||||
following hardens the container; add the `devices`/`group_add` entries your
|
||||
hardware requires (see the hardware acceleration docs):
|
||||
Frigate does not need elevated container privileges for most setups. The following hardens the container; add the `devices`/`group_add` entries your hardware requires (see the hardware acceleration docs):
|
||||
|
||||
```yaml
|
||||
services:
|
||||
@@ -564,15 +562,14 @@ services:
|
||||
|
||||
:::note
|
||||
|
||||
`telemetry.stats.network_bandwidth` uses nethogs, which requires root with
|
||||
NET_ADMIN/NET_RAW capabilities. If you enable that stat, omit `cap_drop: [ALL]`
|
||||
or add `cap_add: [NET_ADMIN, NET_RAW]`.
|
||||
`telemetry.stats.network_bandwidth` uses nethogs, which requires root with NET_ADMIN/NET_RAW capabilities. If you enable that stat, omit `cap_drop: [ALL]` or add `cap_add: [NET_ADMIN, NET_RAW]`.
|
||||
|
||||
Platforms that genuinely require `privileged: true` (MemryX, some QNAP setups)
|
||||
are called out in their own sections and are unaffected by this guidance.
|
||||
Platforms that genuinely require `privileged: true` (MemryX, some QNAP setups) are called out in their own sections and are unaffected by this guidance.
|
||||
|
||||
:::
|
||||
|
||||
Frigate's services run as an unprivileged user inside the container. See [Running as a non-root user](../configuration/non_root.md) for the run modes, the one time volume ownership migration, and what each accelerator needs on the host.
|
||||
|
||||
**Docker CLI**
|
||||
|
||||
If you can't use Docker Compose, you can run the container with something similar to this:
|
||||
|
||||
@@ -122,6 +122,7 @@ const sidebars: SidebarsConfig = {
|
||||
"configuration/ffmpeg_presets",
|
||||
"configuration/pwa",
|
||||
"configuration/tls",
|
||||
"configuration/non_root",
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
Vendored
+3
-5
@@ -1476,12 +1476,10 @@ paths:
|
||||
- Classification
|
||||
summary: Get custom classification attributes
|
||||
description: |-
|
||||
**Access:** Any authenticated user.
|
||||
**Access:** Admin role required.
|
||||
|
||||
Returns custom classification attributes for a given object type.
|
||||
Only includes models with classification_type set to 'attribute'.
|
||||
Callers without access to every camera only receive values that have been
|
||||
recorded on the cameras they can access.
|
||||
By default returns a flat sorted list of all attribute labels.
|
||||
If group_by_model is true, returns attributes grouped by model name.
|
||||
operationId: get_custom_attributes_classification_attributes_get
|
||||
@@ -1512,8 +1510,8 @@ paths:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
security:
|
||||
- frigateUserAuth: []
|
||||
x-required-role: any
|
||||
- frigateAdminAuth: []
|
||||
x-required-role: admin
|
||||
/classification/{name}/train:
|
||||
get:
|
||||
tags:
|
||||
|
||||
@@ -86,7 +86,6 @@ def require_admin_by_default():
|
||||
"/categorized_object_names",
|
||||
"/plus/models",
|
||||
"/recognized_license_plates",
|
||||
"/classification/attributes",
|
||||
"/timeline",
|
||||
"/timeline/hourly",
|
||||
"/recordings/storage",
|
||||
|
||||
@@ -11,14 +11,10 @@ from typing import Any
|
||||
import cv2
|
||||
from fastapi import APIRouter, Depends, Request, UploadFile
|
||||
from fastapi.responses import JSONResponse
|
||||
from peewee import DoesNotExist, fn
|
||||
from peewee import DoesNotExist
|
||||
from playhouse.shortcuts import model_to_dict
|
||||
|
||||
from frigate.api.auth import (
|
||||
allow_any_authenticated,
|
||||
get_allowed_cameras_for_filter,
|
||||
require_role,
|
||||
)
|
||||
from frigate.api.auth import require_role
|
||||
from frigate.api.defs.request.classification_body import (
|
||||
AudioTranscriptionBody,
|
||||
DeleteFaceImagesBody,
|
||||
@@ -743,81 +739,18 @@ def get_classification_dataset(name: str):
|
||||
)
|
||||
|
||||
|
||||
def get_observed_attributes(
|
||||
model_attributes: dict[str, list[str]],
|
||||
object_labels: set[str],
|
||||
allowed_cameras: list[str],
|
||||
) -> dict[str, set[str]]:
|
||||
"""Get the attribute values recorded on the given cameras.
|
||||
|
||||
Args:
|
||||
model_attributes: Labels each attribute model can emit, keyed by model name
|
||||
object_labels: Object types those models run on
|
||||
allowed_cameras: Cameras the caller has access to
|
||||
|
||||
Returns:
|
||||
Values seen for each model, keyed by model name
|
||||
"""
|
||||
if not model_attributes or not object_labels or not allowed_cameras:
|
||||
return {}
|
||||
|
||||
model_names = list(model_attributes.keys())
|
||||
|
||||
query = (
|
||||
Event.select(
|
||||
*[
|
||||
fn.json_extract(Event.data, f'$."{model_name}"')
|
||||
for model_name in model_names
|
||||
]
|
||||
)
|
||||
.where(
|
||||
(Event.camera << allowed_cameras) & (Event.label << sorted(object_labels))
|
||||
)
|
||||
.distinct()
|
||||
.tuples()
|
||||
)
|
||||
|
||||
targets = {
|
||||
model_name: set(attributes)
|
||||
for model_name, attributes in model_attributes.items()
|
||||
}
|
||||
observed: dict[str, set[str]] = {model_name: set() for model_name in model_names}
|
||||
|
||||
for row in query.iterator():
|
||||
found = False
|
||||
|
||||
for model_name, value in zip(model_names, row):
|
||||
if isinstance(value, str) and value not in observed[model_name]:
|
||||
observed[model_name].add(value)
|
||||
found = True
|
||||
|
||||
if found and all(
|
||||
observed[model_name] >= targets[model_name] for model_name in model_names
|
||||
):
|
||||
break
|
||||
|
||||
return observed
|
||||
|
||||
|
||||
@router.get(
|
||||
"/classification/attributes",
|
||||
dependencies=[Depends(allow_any_authenticated())],
|
||||
summary="Get custom classification attributes",
|
||||
description="""Returns custom classification attributes for a given object type.
|
||||
Only includes models with classification_type set to 'attribute'.
|
||||
Callers without access to every camera only receive values that have been
|
||||
recorded on the cameras they can access.
|
||||
By default returns a flat sorted list of all attribute labels.
|
||||
If group_by_model is true, returns attributes grouped by model name.""",
|
||||
)
|
||||
def get_custom_attributes(
|
||||
request: Request,
|
||||
object_type: str = None,
|
||||
group_by_model: bool = False,
|
||||
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
|
||||
request: Request, object_type: str = None, group_by_model: bool = False
|
||||
):
|
||||
models_with_attributes = {}
|
||||
objects_by_model = {}
|
||||
|
||||
for (
|
||||
model_key,
|
||||
@@ -848,32 +781,6 @@ def get_custom_attributes(
|
||||
if attributes:
|
||||
model_name = model_config.name or model_key
|
||||
models_with_attributes[model_name] = sorted(attributes)
|
||||
objects_by_model[model_name] = model_objects
|
||||
|
||||
# the dataset holds every label a model can emit, including ones never
|
||||
# applied to an event, so callers without full camera access are limited to
|
||||
# the values actually recorded on the cameras they can see
|
||||
all_cameras = set(request.app.frigate_config.cameras.keys())
|
||||
|
||||
if models_with_attributes and not all_cameras.issubset(allowed_cameras):
|
||||
observed = get_observed_attributes(
|
||||
models_with_attributes,
|
||||
set().union(*objects_by_model.values()),
|
||||
allowed_cameras,
|
||||
)
|
||||
models_with_attributes = {
|
||||
model_name: [
|
||||
attribute
|
||||
for attribute in attributes
|
||||
if attribute in observed.get(model_name, set())
|
||||
]
|
||||
for model_name, attributes in models_with_attributes.items()
|
||||
}
|
||||
models_with_attributes = {
|
||||
model_name: attributes
|
||||
for model_name, attributes in models_with_attributes.items()
|
||||
if attributes
|
||||
}
|
||||
|
||||
if group_by_model:
|
||||
return JSONResponse(content=models_with_attributes)
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
"""Tests for GET /classification/attributes."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import unittest
|
||||
|
||||
from frigate.api.auth import get_allowed_cameras_for_filter
|
||||
from frigate.const import CLIPS_DIR
|
||||
from frigate.models import Event, Recordings, ReviewSegment
|
||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||
|
||||
# "limited_user" only reaches front_door, so it never sees the values that were
|
||||
# recorded on back_door.
|
||||
_CONFIG = {
|
||||
"mqtt": {"host": "mqtt"},
|
||||
"auth": {"roles": {"limited_user": ["front_door"]}},
|
||||
"classification": {
|
||||
"custom": {
|
||||
"delivery_service": {
|
||||
"enabled": True,
|
||||
"object_config": {
|
||||
"objects": ["car"],
|
||||
"classification_type": "attribute",
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
"cameras": {
|
||||
"front_door": {
|
||||
"ffmpeg": {
|
||||
"inputs": [{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}]
|
||||
},
|
||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
||||
},
|
||||
"back_door": {
|
||||
"ffmpeg": {
|
||||
"inputs": [{"path": "rtsp://10.0.0.2:554/video", "roles": ["detect"]}]
|
||||
},
|
||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class TestClassificationAttributesAccess(BaseTestHttp):
|
||||
"""The attribute list is read from the training dataset on disk, which holds
|
||||
every label a model can emit regardless of which camera recorded it. Callers
|
||||
without full camera access are cut back to the values on their own cameras,
|
||||
so these tests pin that scoping.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp([Event, ReviewSegment, Recordings])
|
||||
self.minimal_config = _CONFIG
|
||||
self.app = super().create_app()
|
||||
self.model_dir = os.path.join(CLIPS_DIR, "delivery_service")
|
||||
|
||||
for category in ("DHL", "Amazon", "Hermes", "none"):
|
||||
os.makedirs(
|
||||
os.path.join(self.model_dir, "dataset", category), exist_ok=True
|
||||
)
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.model_dir, ignore_errors=True)
|
||||
self.app.dependency_overrides.clear()
|
||||
super().tearDown()
|
||||
|
||||
def _insert_event(self, event_id: str, camera: str, attribute: str | None):
|
||||
data = {"type": "object", "score": 0.9}
|
||||
|
||||
if attribute is not None:
|
||||
data["delivery_service"] = attribute
|
||||
|
||||
Event.insert(
|
||||
id=event_id,
|
||||
label="car",
|
||||
camera=camera,
|
||||
start_time=100,
|
||||
end_time=200,
|
||||
top_score=0.9,
|
||||
score=0.9,
|
||||
false_positive=False,
|
||||
zones=[],
|
||||
thumbnail="",
|
||||
has_clip=True,
|
||||
has_snapshot=True,
|
||||
region=[],
|
||||
box=[],
|
||||
area=0,
|
||||
retain_indefinitely=False,
|
||||
ratio=1.0,
|
||||
plus_id=None,
|
||||
model_hash="",
|
||||
detector_type="cpu",
|
||||
model_type="ssd",
|
||||
data=data,
|
||||
).execute()
|
||||
|
||||
def _get(self, role: str, **params):
|
||||
# the base class resolves every camera by default, so drop the override
|
||||
# to exercise the real role to allowed-cameras resolution
|
||||
self.app.dependency_overrides.pop(get_allowed_cameras_for_filter, None)
|
||||
|
||||
with AuthTestClient(self.app) as client:
|
||||
return client.get(
|
||||
"/classification/attributes",
|
||||
params=params,
|
||||
headers={"remote-user": "test", "remote-role": role},
|
||||
)
|
||||
|
||||
def _insert_split_events(self):
|
||||
self._insert_event("front", "front_door", "DHL")
|
||||
self._insert_event("back", "back_door", "Amazon")
|
||||
|
||||
def test_admin_gets_every_trained_label(self):
|
||||
self._insert_split_events()
|
||||
assert self._get("admin").json() == ["Amazon", "DHL", "Hermes"]
|
||||
|
||||
def test_viewer_gets_every_trained_label(self):
|
||||
self._insert_split_events()
|
||||
assert self._get("viewer").json() == ["Amazon", "DHL", "Hermes"]
|
||||
|
||||
def test_restricted_role_only_gets_its_own_cameras(self):
|
||||
self._insert_split_events()
|
||||
assert self._get("limited_user").json() == ["DHL"]
|
||||
|
||||
def test_restricted_role_grouped_by_model(self):
|
||||
self._insert_split_events()
|
||||
assert self._get("limited_user", group_by_model="true").json() == {
|
||||
"delivery_service": ["DHL"]
|
||||
}
|
||||
|
||||
def test_restricted_role_with_no_recorded_values(self):
|
||||
self._insert_event("back", "back_door", "Amazon")
|
||||
assert self._get("limited_user").json() == []
|
||||
assert self._get("limited_user", group_by_model="true").json() == {}
|
||||
|
||||
def test_restricted_role_ignores_events_without_the_attribute(self):
|
||||
self._insert_event("front", "front_door", None)
|
||||
assert self._get("limited_user").json() == []
|
||||
|
||||
def test_restricted_role_with_a_dotted_model_name(self):
|
||||
# model names are unrestricted config keys, and an unquoted "." in the
|
||||
# json path would be read as a nested lookup and match nothing
|
||||
self.app.frigate_config.classification.custom["delivery.service"] = (
|
||||
self.app.frigate_config.classification.custom.pop("delivery_service")
|
||||
)
|
||||
self.app.frigate_config.classification.custom[
|
||||
"delivery.service"
|
||||
].name = "delivery.service"
|
||||
os.rename(self.model_dir, os.path.join(CLIPS_DIR, "delivery.service"))
|
||||
self.model_dir = os.path.join(CLIPS_DIR, "delivery.service")
|
||||
|
||||
data = {"type": "object", "score": 0.9, "delivery.service": "DHL"}
|
||||
Event.insert(
|
||||
id="front",
|
||||
label="car",
|
||||
camera="front_door",
|
||||
start_time=100,
|
||||
end_time=200,
|
||||
top_score=0.9,
|
||||
score=0.9,
|
||||
false_positive=False,
|
||||
zones=[],
|
||||
thumbnail="",
|
||||
has_clip=True,
|
||||
has_snapshot=True,
|
||||
region=[],
|
||||
box=[],
|
||||
area=0,
|
||||
retain_indefinitely=False,
|
||||
ratio=1.0,
|
||||
plus_id=None,
|
||||
model_hash="",
|
||||
detector_type="cpu",
|
||||
model_type="ssd",
|
||||
data=data,
|
||||
).execute()
|
||||
|
||||
assert self._get("limited_user").json() == ["DHL"]
|
||||
|
||||
def test_object_type_filters_out_unrelated_models(self):
|
||||
self._insert_split_events()
|
||||
assert self._get("limited_user", object_type="person").json() == []
|
||||
assert self._get("limited_user", object_type="car").json() == ["DHL"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Tests for bandwidth stats privilege handling."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from frigate.util import services
|
||||
|
||||
|
||||
class TestBandwidthStatsPrivileges(unittest.TestCase):
|
||||
def setUp(self):
|
||||
services._bandwidth_warning_logged = False
|
||||
|
||||
@patch("frigate.util.services.sp.run")
|
||||
@patch("frigate.util.services.os.geteuid", return_value=1000)
|
||||
def test_returns_empty_and_warns_once_without_root(self, _, sp_run):
|
||||
config = MagicMock()
|
||||
with self.assertLogs("frigate.util.services", level="WARNING") as logs:
|
||||
assert services.get_bandwidth_stats(config) == {}
|
||||
assert services.get_bandwidth_stats(config) == {}
|
||||
sp_run.assert_not_called()
|
||||
warnings = [m for m in logs.output if "require root" in m]
|
||||
assert len(warnings) == 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -187,8 +187,23 @@ def get_physical_interfaces(interfaces) -> list:
|
||||
return physical_interfaces
|
||||
|
||||
|
||||
_bandwidth_warning_logged = False
|
||||
|
||||
|
||||
def get_bandwidth_stats(config) -> dict[str, dict]:
|
||||
"""Get bandwidth usages for each ffmpeg process id"""
|
||||
global _bandwidth_warning_logged
|
||||
|
||||
if os.geteuid() != 0:
|
||||
if not _bandwidth_warning_logged:
|
||||
logger.warning(
|
||||
"Network bandwidth stats require root (nethogs needs CAP_NET_ADMIN/CAP_NET_RAW) "
|
||||
"and are disabled; set FRIGATE_RUN_AS_ROOT=true or disable "
|
||||
"telemetry.stats.network_bandwidth to silence this warning"
|
||||
)
|
||||
_bandwidth_warning_logged = True
|
||||
return {}
|
||||
|
||||
usages = {}
|
||||
top_command = ["nethogs", "-t", "-v0", "-c5", "-d1"] + get_physical_interfaces(
|
||||
config.telemetry.network_interfaces
|
||||
|
||||
Reference in New Issue
Block a user