Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
!docker/postgres-entrypoint.sh
!docker/Dockerfile.aio
!docker/cuda-requirements.txt
!docker/install-intel.sh
!docker/aio-entrypoint.sh
!config.example.yaml
!pyproject.toml
Expand Down
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,17 @@ jobs:
test "$(jq -r '[.services[] | has("build")] | any' <<<"$compose_json")" = false
build_json=$(docker compose -f docker-compose.yml -f docker-compose.build.yml config --format json)
test "$(jq -r '[.services[] | has("build")] | all' <<<"$build_json")" = true
intel_json=$(KEYSTONE_RENDER_GID=109 KEYSTONE_IMAGE_TAG=edge KEYSTONE_ACCEL_FFMPEG_HWACCEL=none \
docker compose -f docker-compose.yml -f docker-compose.intel.yml config --format json)
jq -e --arg gid "$gid" '
.services.keystone as $ks |
$ks.image == "ghcr.io/seearms/keystone:edge-intel" and
($ks.group_add | sort) == ([$gid, "109"] | sort) and
($ks.devices == ["/dev/dri:/dev/dri"] or
($ks.devices | map([.source, .target])) == [["/dev/dri", "/dev/dri"]]) and
$ks.environment.KEYSTONE_ACCEL_FFMPEG_HWACCEL == "none" and
.services.postgres.image == "ghcr.io/seearms/keystone-postgres:edge"
' <<<"$intel_json"
echo '# Operator settings survive a rerun' >> config.yaml
original=$(sha256sum .env config.yaml)
Expand Down
47 changes: 45 additions & 2 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ name: Docker
# Publishes ghcr.io/seearms/keystone, keystone-postgres and keystone-aio (both in
# one container, for Unraid) for amd64 and arm64. main pushes :edge; a vX.Y.Z tag
# pushes :X.Y.Z, :X.Y and :latest. Pull requests build the images without pushing.
# Keystone and Keystone AIO also publish corresponding -intel tags for amd64.
#
# Each platform builds on a native runner, because emulating arm64 with QEMU made the
# pip install layer about ten times slower. On pushes, each build uploads its image by
Expand Down Expand Up @@ -48,7 +49,8 @@ jobs:
steps:
- uses: actions/checkout@v4

- name: Tag matches the app version
- &check-version
name: Tag matches the app version
if: startsWith(github.ref, 'refs/tags/v')
run: |
version=$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')
Expand All @@ -59,7 +61,8 @@ jobs:
- uses: docker/setup-buildx-action@v3

- uses: docker/login-action@v3
- &ghcr-login
uses: docker/login-action@v3
if: github.event_name != 'pull_request'
with:
registry: ghcr.io
Expand Down Expand Up @@ -148,3 +151,43 @@ jobs:
for digest in *; do sources+=("$IMAGE@sha256:$digest"); done
docker buildx imagetools create "${tags[@]}" "${sources[@]}"
docker buildx imagetools inspect "$IMAGE:$DOCKER_METADATA_OUTPUT_VERSION"
intel:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
image:
- name: keystone
dockerfile: Dockerfile
- name: keystone-aio
dockerfile: docker/Dockerfile.aio
env: *image-env

steps:
- uses: actions/checkout@v4
- *check-version
- uses: docker/setup-buildx-action@v3
- *ghcr-login

- id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE }}
flavor: suffix=-intel,onlatest=true
tags: *tags

- uses: docker/build-push-action@v6
with:
context: .
file: ${{ matrix.image.dockerfile }}
target: intel
platforms: linux/amd64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha,scope=${{ env.IMAGE }}-amd64-intel
cache-to: ${{ github.event_name != 'pull_request' && format('type=gha,mode=max,scope={0}-amd64-intel', env.IMAGE) || '' }}
8 changes: 7 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM python:3.12-slim-bookworm AS runtime
FROM python:3.12-slim-trixie AS runtime

RUN apt-get update && apt-get install -y --no-install-recommends \
ffmpeg \
Expand Down Expand Up @@ -40,5 +40,11 @@ RUN --mount=type=bind,source=docker/cuda-requirements.txt,target=/tmp/cuda-requi
ENV NVIDIA_DRIVER_CAPABILITIES=compute,utility
USER keystone

FROM runtime AS intel
USER root
RUN --mount=type=bind,source=docker/install-intel.sh,target=/tmp/install-intel.sh \
sh /tmp/install-intel.sh
USER keystone

# Keep the published multi-architecture image CPU-only.
FROM runtime AS cpu
28 changes: 26 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ docker compose up -d

During setup, enter your UniFi Protect controller's IP address. If you want event descriptions, enter your Ollama or AI server URL; **press Enter to skip descriptions for now** (Find Anything search still works right away).

On Linux amd64 hosts with an Intel GPU, use the [Intel Compose override](#optional-intel-gpu--npu-acceleration-openvino--va-api) to run `ghcr.io/seearms/keystone:latest-intel` with access to `/dev/dri`.

> **Docker Desktop on macOS/Windows and OrbStack on macOS:** Prefer [native Homebrew on macOS](#macos--apple-silicon-homebrew) or a Linux VM bridged to Protect's LAN. These Docker runtimes can rewrite inbound LAN source addresses, so adoption and PostgreSQL's `pg_hba.conf` see a VM gateway (for example, `192.0.2.1`) or `127.0.0.1` (OrbStack host mode) in place of Protect's IP. LAN UDP `10001` broadcasts do not reach the VM through published ports.
>
> If NAT is unavoidable, keep the controller setting pointed at Protect. Set `KEYSTONE_CONTROLLER_TRUSTED_PEERS` to the observed gateway IP or a comma-separated list of source IPs/CIDRs and `KEYSTONE_DEVICE_ADVERTISE_IP` to the address Protect can reach. Set both in Compose's `.env` or in the `keystone-aio` container environment. Every host behind the same gateway can pass the source-IP check, so restrict access to the published ports to Protect before NAT. For initial discovery when LAN UDP `10001` broadcasts cannot reach the container, use one of the [cross-VLAN / routed adoption](#adopting-across-vlans) options (UDP `10001` relay or `keystone announce --port <PROTECT_UDP_PORT>`).
Expand Down Expand Up @@ -135,6 +137,10 @@ wget -O /boot/config/plugins/dockerMan/templates-user/my-Keystone.xml \

Then go to **Docker → Add Container** and choose **Keystone**. Set **Network Type** to `br0` with a fixed IP, enter your Protect controller's IP (and optionally a vision provider/URL for descriptions), and apply. Everything is stored in `/mnt/user/appdata/keystone`; template fields override the matching settings in `config.yaml`.

For Intel GPU acceleration on an amd64 host with `/dev/dri`, switch **Repository** to `ghcr.io/seearms/keystone-aio:latest-intel` (or `:edge-intel` before the next versioned release is tagged). Choose **Add another Path, Port, Variable, Label or Device**, select **Device**, and map `/dev/dri` to `/dev/dri`. At startup, the container grants the Keystone user the numeric groups of the mapped render and card devices automatically.

The template's advanced acceleration fields use `config.yaml` when left blank. Set **Acceleration provider** to `auto` for automatic inference provider selection and **FFmpeg hardware acceleration** to `auto` to enable AI Port hardware video decode, or set those options in the acceleration section of `config.yaml`.

### macOS / Apple Silicon (Homebrew)

Use macOS Sequoia (15) or newer on an Apple Silicon or Intel Mac on the same LAN as UniFi Protect. Keystone runs natively on macOS so Protect can discover it over UDP without a Docker VM (Docker Desktop does not support LAN host networking). Run these commands as the Homebrew owner. If you started the selected PostgreSQL cluster manually with `pg_ctl`, stop it with the same cluster manager after setup and before `install-daemons`. The LaunchDaemon then starts the cluster with its updated listen address:
Expand Down Expand Up @@ -443,12 +449,30 @@ Off by default so existing installs don't kick off a multi-hour backfill unexpec

### Optional Intel GPU / NPU acceleration (OpenVINO & VA-API)

Keystone defaults to CPU and software video decode on Linux so it works everywhere with no drivers. On Intel Core Ultra, Arc, or N100 hosts, you can offload ONNX models to OpenVINO and AI Port video decode to VA-API:
On compatible Intel GPUs, Keystone can offload supported ONNX models to OpenVINO and AI Port video decode to VA-API. The amd64 `:latest-intel` images (or `:edge-intel` from `main` before the next versioned release is tagged) include both runtimes. [Unraid setup](#unraid) uses the all-in-one image.

For **Docker Compose**, run these commands in your Keystone Compose directory on a Linux amd64 host with a `/dev/dri/renderD*` device. Use the current setup script so it can record the render device's owning group as `KEYSTONE_RENDER_GID` in `.env`.

```bash
pip install -e ".[openvino]"
curl -fsSLO https://raw.githubusercontent.com/seeARMS/keystone/main/docker-compose.intel.yml
curl -fsSLO https://raw.githubusercontent.com/seeARMS/keystone/main/scripts/setup-compose.py
python3 setup-compose.py
docker compose -f docker-compose.yml -f docker-compose.intel.yml up -d
```

In a repository checkout, use the included override and run `python3 scripts/setup-compose.py` for setup. Keep both `-f` options on later Compose commands, including image updates. The override appends `-intel` to `KEYSTONE_IMAGE_TAG` for Keystone, so set the base tag in `.env` (for example `edge`). If your host has multiple GPUs, set `KEYSTONE_RENDER_GID` to the owning group of the node selected by `acceleration.ffmpeg_device`.

The Intel Compose override supplies `KEYSTONE_ACCEL_FFMPEG_HWACCEL=auto`. To use software decode with this override, set `KEYSTONE_ACCEL_FFMPEG_HWACCEL=none` in `.env`. An explicit environment value takes precedence over `config.yaml`.

For **native installs**, install compatible OpenVINO and VA-API drivers for your hardware and replace the CPU ONNX Runtime wheel after installing Keystone.

```bash
pip uninstall -y onnxruntime
pip install 'onnxruntime-openvino>=1.21.0' 'openvino>=2025.0.0'
```

Configure inference and video decode under `acceleration` in `config.yaml`.

```yaml
acceleration:
provider: auto # auto | cpu | openvino | coreml | cuda | migraphx
Expand Down
12 changes: 12 additions & 0 deletions docker-compose.intel.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
services:
keystone:
# Set KEYSTONE_IMAGE_TAG=edge in .env to pull :edge-intel before the next versioned release is tagged.
image: ghcr.io/seearms/keystone:${KEYSTONE_IMAGE_TAG:-latest}-intel
# For a local build, run docker build --target intel -t keystone-intel:local .
# and set image: keystone-intel:local above.
devices:
- /dev/dri:/dev/dri
group_add:
- ${KEYSTONE_RENDER_GID:-10001}
environment:
KEYSTONE_ACCEL_FFMPEG_HWACCEL: ${KEYSTONE_ACCEL_FFMPEG_HWACCEL:-auto}
9 changes: 8 additions & 1 deletion docker/Dockerfile.aio
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Keystone and its Find Anything database in one container, for hosts such as Unraid
# where Keystone gets its own LAN IP. Protect expects both at that address.
FROM python:3.12-slim-trixie
FROM python:3.12-slim-trixie AS runtime

# The entrypoint creates the database cluster in /data, not the package at build time.
RUN mkdir -p /etc/postgresql-common/createcluster.d \
Expand All @@ -25,7 +25,7 @@

RUN pip install --no-cache-dir ".[mqtt]"

ENV PATH=/usr/lib/postgresql/17/bin:$PATH \

Check warning on line 28 in docker/Dockerfile.aio

View workflow job for this annotation

GitHub Actions / image (keystone-aio, docker/Dockerfile.aio, arm64, ubuntu-24.04-arm)

Sensitive data should not be used in the ARG or ENV commands

SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data (ENV "KEYSTONE_DEVICE_SYNC_POSTGRES_PASSWORD") More info: https://docs.docker.com/go/dockerfile/rule/secrets-used-in-arg-or-env/

Check warning on line 28 in docker/Dockerfile.aio

View workflow job for this annotation

GitHub Actions / intel (keystone-aio, docker/Dockerfile.aio)

Sensitive data should not be used in the ARG or ENV commands

SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data (ENV "KEYSTONE_DEVICE_SYNC_POSTGRES_PASSWORD") More info: https://docs.docker.com/go/dockerfile/rule/secrets-used-in-arg-or-env/

Check warning on line 28 in docker/Dockerfile.aio

View workflow job for this annotation

GitHub Actions / image (keystone-aio, docker/Dockerfile.aio, amd64, ubuntu-latest)

Sensitive data should not be used in the ARG or ENV commands

SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data (ENV "KEYSTONE_DEVICE_SYNC_POSTGRES_PASSWORD") More info: https://docs.docker.com/go/dockerfile/rule/secrets-used-in-arg-or-env/
PGDATA=/data/postgres \
KEYSTONE_CONFIG=/data/config.yaml \
KEYSTONE_STATE_DIR=/data/state \
Expand All @@ -36,3 +36,10 @@
EXPOSE 443 5432 8080 8088 10001/udp

ENTRYPOINT ["tini", "--", "/app/docker/aio-entrypoint.sh"]

FROM runtime AS intel
RUN --mount=type=bind,source=docker/install-intel.sh,target=/tmp/install-intel.sh \
sh /tmp/install-intel.sh

# Keep the published multi-architecture image CPU-only.
FROM runtime AS cpu
17 changes: 16 additions & 1 deletion docker/aio-entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,24 @@ END $$;
GRANT "unifi-protect" TO keystone WITH ADMIN TRUE, INHERIT FALSE, SET FALSE;
EOF

# Use the host's numeric device groups even if the container has no matching names.
dri_gids=()
for device in /dev/dri/renderD* /dev/dri/card*; do
[ -c "$device" ] || continue
if gid=$(stat -Lc '%g' "$device"); then
dri_gids+=("$gid")
fi
done
keystone_groups=--init-groups
if (( ${#dri_gids[@]} )); then
existing_gids=$(id -G keystone)
gids=$(printf '%s\n' "${dri_gids[@]}" "$existing_gids" | tr ' ' '\n' | sort -un | paste -sd, -)
keystone_groups="--groups=$gids"
fi

# Resolve container-only vision defaults on every start. The YAML stays editable
# and adding a URL later takes effect without undoing a persisted setting.
setpriv --reuid=keystone --regid=keystone --init-groups -- python3 - <<'PY' &
setpriv --reuid=keystone --regid=keystone "$keystone_groups" -- python3 - <<'PY' &
import os
from pathlib import Path
Expand Down
37 changes: 37 additions & 0 deletions docker/install-intel.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/bin/sh
set -eu

# Trixie ships VA-API and the ICD loaders. Use Intel's matched compute-runtime
# and graphics compiler release packages for the OpenCL and Level Zero drivers.
# https://github.com/intel/compute-runtime/releases/tag/26.09.37435.1
temp_dir=$(mktemp -d)
trap 'rm -rf "$temp_dir"' EXIT
install -d -o _apt -m 0755 "$temp_dir"
compute_release=https://github.com/intel/compute-runtime/releases/download/26.09.37435.1
igc_release=https://github.com/intel/intel-graphics-compiler/releases/download/v2.30.1
while read -r sha256 url; do
/usr/lib/apt/apt-helper download-file "$url" "$temp_dir/${url##*/}" "SHA256:$sha256"
done <<EOF
9d712f71c18baee076de9961dda71e8089291e1bd0deb5d649ab5ba5de114f97 $compute_release/libigdgmm12_22.9.0_amd64.deb
611c758c169a81c91bfc0b089cb6a53949ec2b6aedbf892635a579c529c63e7a $compute_release/intel-opencl-icd_26.09.37435.1-0_amd64.deb
9fb35fbccbb5f85a60283803de961398ec8ae7d23bfd07f1f272307f596972c9 $compute_release/libze-intel-gpu1_26.09.37435.1-0_amd64.deb
0a3114a6f74bf6382d5976633c262ff4c392273828424fce04c7185071f8b2ca $igc_release/intel-igc-core-2_2.30.1+20950_amd64.deb
9b24a5778af3c4a6bd211a21e7b6860fde9c6869b29c7c4423b5b1a949db13fd $igc_release/intel-igc-opencl-2_2.30.1+20950_amd64.deb
EOF

apt-get update
apt-get install -y --no-install-recommends \
intel-media-va-driver ocl-icd-libopencl1 libva-drm2 libze1 "$temp_dir"/*.deb
rm -rf /var/lib/apt/lists/*

# Both wheels install the same onnxruntime module. Installing .[openvino]
# would also pull in the CPU wheel through Keystone's base dependencies.
python3 - > "$temp_dir/openvino-requirements.txt" <<'PY'
import tomllib
with open("pyproject.toml", "rb") as config:
requirements = tomllib.load(config)["project"]["optional-dependencies"]["openvino"]
print(*requirements, sep="\n")
PY
pip uninstall -y onnxruntime
pip install --no-cache-dir -r "$temp_dir/openvino-requirements.txt"
41 changes: 33 additions & 8 deletions scripts/setup-compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import os
import re
import secrets
import stat
import subprocess
import sys
import urllib.request
Expand All @@ -29,6 +30,7 @@
from typing import NamedTuple

KEYSTONE_ID = "10001" # UID and GID of the keystone user in the image
DRI_DIR = Path("/dev/dri")
RAW_BASE_URL = "https://raw.githubusercontent.com/seeARMS/keystone"
COMPOSE_FILENAMES = ("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml")

Expand Down Expand Up @@ -137,12 +139,30 @@ def create_file(path: Path, contents: str, *, mode: int = 0o600) -> None:
def parse_env(text: str) -> dict[str, str]:
values = {}
for line in text.splitlines():
key, sep, value = line.partition("=")
stripped = line.lstrip()
if not stripped or stripped.startswith("#"):
continue
key, sep, value = stripped.partition("=")
if sep:
values[key.strip()] = value.strip().strip("'\"")
name = key.strip()
if name.startswith("export") and len(name) > 6 and name[6].isspace():
name = name[6:].lstrip()
if name:
values[name] = value.strip().strip("'\"")
return values


def render_device_gid() -> int | None:
for device in sorted(DRI_DIR.glob("renderD*")):
try:
info = device.stat()
except OSError:
continue
if stat.S_ISCHR(info.st_mode):
return info.st_gid
return None


def yaml_quote(value: str) -> str:
# JSON quoting plus YAML's escapes for non-ASCII characters, without a PyYAML dependency.
encoded = json.dumps(value, ensure_ascii=False).encode("ascii", "backslashreplace").decode("ascii")
Expand Down Expand Up @@ -611,23 +631,28 @@ def main(target: Path | None = None) -> None:
env_controller = "KEYSTONE_CONTROLLER_IP" in os.environ or env_file.exists()
env_vision = _has_vision_env(os.environ)

group_defaults = {"KEYSTONE_CONFIG_GID": str(os.getgid() or KEYSTONE_ID)}
render_gid = render_device_gid()
if render_gid is not None:
group_defaults["KEYSTONE_RENDER_GID"] = str(render_gid)
if not env_file.exists():
if config.exists():
print("Use the controller.host address from your existing config.yaml.")
group_settings = "".join(f"{key}={value}\n" for key, value in group_defaults.items())
create_file(
env_file,
f"KEYSTONE_CONTROLLER_IP={controller_address(os.environ)}\n"
f"KEYSTONE_PG_ADMIN_PASSWORD={secrets.token_hex(32)}\n"
f"KEYSTONE_CONFIG_GID={os.getgid() or KEYSTONE_ID}\n",
f"{group_settings}",
)
env_text = env_file.read_text(encoding="utf-8")
env = parse_env(env_text)
if "KEYSTONE_CONFIG_GID" not in env:
# Migrate .env files from before Compose used the operator's group to read config.yaml.
env["KEYSTONE_CONFIG_GID"] = str(os.getgid() or KEYSTONE_ID)
separator = "" if env_text.endswith("\n") else "\n"
missing_groups = {key: value for key, value in group_defaults.items() if key not in env}
if missing_groups:
separator = "\n" if env_text and not env_text.endswith("\n") else ""
with env_file.open("a", encoding="utf-8") as f:
f.write(f"{separator}KEYSTONE_CONFIG_GID={env['KEYSTONE_CONFIG_GID']}\n")
f.write(separator + "".join(f"{key}={value}\n" for key, value in missing_groups.items()))
env.update(missing_groups)

created: tuple[VisionChoice, dict[str, bool], str | None, str, str] | None = None
if not config.exists():
Expand Down
Loading
Loading