From 0d06e364ede63bc2991f97f9bb325b76a20306e2 Mon Sep 17 00:00:00 2001 From: seeARMS <3957773+seeARMS@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:42:34 -0800 Subject: [PATCH 1/2] Add Intel GPU Docker images and device setup --- .dockerignore | 1 + .github/workflows/ci.yml | 11 +++++++ .github/workflows/docker.yml | 50 ++++++++++++++++++++++++++++- Dockerfile | 8 ++++- README.md | 28 +++++++++++++++-- docker-compose.intel.yml | 11 +++++++ docker/Dockerfile.aio | 9 +++++- docker/aio-entrypoint.sh | 17 +++++++++- docker/install-intel.sh | 37 ++++++++++++++++++++++ scripts/setup-compose.py | 30 ++++++++++++++---- tests/test_aio_entrypoint.py | 59 +++++++++++++++++++++++++++++++++-- tests/test_intel_packaging.py | 59 +++++++++++++++++++++++++++++++++++ tests/test_setup_compose.py | 37 ++++++++++++++++++++++ unraid/keystone.xml | 7 ++++- 14 files changed, 349 insertions(+), 15 deletions(-) create mode 100644 docker-compose.intel.yml create mode 100644 docker/install-intel.sh create mode 100644 tests/test_intel_packaging.py diff --git a/.dockerignore b/.dockerignore index 829b740..34f56a1 100644 --- a/.dockerignore +++ b/.dockerignore @@ -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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef25b8c..df7e442 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index f6d9e40..b3437c1 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -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 @@ -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"])') @@ -148,3 +150,49 @@ 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 + + - uses: docker/login-action@v3 + if: github.event_name != 'pull_request' + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - 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) || '' }} diff --git a/Dockerfile b/Dockerfile index e0f82a1..6aa7930 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 \ @@ -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 diff --git a/README.md b/README.md index b780625..719447f 100644 --- a/README.md +++ b/README.md @@ -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 `). @@ -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`. 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: @@ -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 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 diff --git a/docker-compose.intel.yml b/docker-compose.intel.yml new file mode 100644 index 0000000..c054993 --- /dev/null +++ b/docker-compose.intel.yml @@ -0,0 +1,11 @@ +services: + keystone: + 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} diff --git a/docker/Dockerfile.aio b/docker/Dockerfile.aio index c5d9e05..f94ebc9 100644 --- a/docker/Dockerfile.aio +++ b/docker/Dockerfile.aio @@ -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 \ @@ -36,3 +36,10 @@ VOLUME ["/data"] 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 diff --git a/docker/aio-entrypoint.sh b/docker/aio-entrypoint.sh index 7260296..5c188ee 100755 --- a/docker/aio-entrypoint.sh +++ b/docker/aio-entrypoint.sh @@ -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 diff --git a/docker/install-intel.sh b/docker/install-intel.sh new file mode 100644 index 0000000..1c5caa0 --- /dev/null +++ b/docker/install-intel.sh @@ -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 < "$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" diff --git a/scripts/setup-compose.py b/scripts/setup-compose.py index 91a6d81..e71e56f 100644 --- a/scripts/setup-compose.py +++ b/scripts/setup-compose.py @@ -20,6 +20,7 @@ import os import re import secrets +import stat import subprocess import sys import urllib.request @@ -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") @@ -143,6 +145,17 @@ def parse_env(text: str) -> dict[str, str]: 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") @@ -611,23 +624,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(): diff --git a/tests/test_aio_entrypoint.py b/tests/test_aio_entrypoint.py index f7fbb5c..db00c03 100644 --- a/tests/test_aio_entrypoint.py +++ b/tests/test_aio_entrypoint.py @@ -93,6 +93,21 @@ def test_unraid_template_variables(): assert aiport.get("Default") == "false|true" assert aiport.text == "false" + for target, default in { + "PROVIDER": "|auto|openvino|cpu", + "OPENVINO_DEVICE": "", + "FFMPEG_HWACCEL": "|auto|vaapi|none", + }.items(): + field = variables[f"KEYSTONE_ACCEL_{target}"] + assert field.get("Default") == default + assert field.get("Display") == "advanced" + assert field.get("Required") == "false" + assert not field.text + + assert container.findtext("Repository") == "ghcr.io/seearms/keystone-aio:latest" + assert "ghcr.io/seearms/keystone-aio:latest-intel" in container.findtext("Overview", "") + assert not container.findall("./Config[@Type='Device']") + @pytest.fixture(scope="module") def aio_bash(): @@ -116,10 +131,29 @@ def aio_start(tmp_path, aio_bash): pgdata.mkdir() (pgdata / "PG_VERSION").write_text("17\n") config_path = tmp_path / "config.yaml" + # Point the real startup script at test devices without touching the host's /dev/dri. + entrypoint = tmp_path / ENTRYPOINT.name + entrypoint.write_text(ENTRYPOINT.read_text().replace("/dev/dri/", f"{tmp_path}/dri/")) stubs = { "install": 'if [ "$1" != "-d" ]; then cp "$EXAMPLE_CONFIG" "$KEYSTONE_CONFIG"; fi', "chown": "exit 0", - "setpriv": 'shift 4; exec "$@"', + "setpriv": r"""is_keystone=false +if [ "$1" = "--reuid=keystone" ]; then is_keystone=true; fi +while [ "$#" -gt 0 ] && [ "$1" != "--" ]; do + if "$is_keystone"; then printf '%s\n' "$1" >> "$SETPRIV_LOG"; fi + shift +done +test "$#" -gt 0 || exit 1 +shift +exec "$@" +""", + "id": 'test "$*" = "-G keystone" && echo "10001 78 107"', + "stat": """case "${3##*/}" in + renderD128|card1) echo 109 ;; + card0) echo 107 ;; + *) exit 1 ;; +esac +""", "postgres": 'echo "$$" > "$PGDATA/test.pid"; exec sleep 15', "pg_isready": 'while [ ! -s "$PGDATA/test.pid" ]; do sleep 0.01; done', "psql": 'if [ "${6:-}" = "-c" ]; then echo 1; else cat >/dev/null; fi', @@ -145,6 +179,7 @@ def aio_start(tmp_path, aio_bash): "PATH": f"{bin_dir}{os.pathsep}{os.defpath}", "EXAMPLE_CONFIG": str(EXAMPLE_CONFIG), "TEST_PYTHON": sys.executable, + "SETPRIV_LOG": str(tmp_path / "setpriv.log"), "PGDATA": str(pgdata), "KEYSTONE_CONFIG": str(config_path), "KEYSTONE_STATE_DIR": str(tmp_path / "state"), @@ -154,7 +189,7 @@ def aio_start(tmp_path, aio_bash): def start(**overrides): result = subprocess.run( - [aio_bash, ENTRYPOINT], + [aio_bash, entrypoint], env={**env, **overrides}, capture_output=True, text=True, @@ -166,6 +201,26 @@ def start(**overrides): return start, config_path +@pytest.mark.parametrize("has_dri", [False, True]) +def test_aio_keystone_supplementary_groups(aio_start, has_dri): + start, config_path = aio_start + dri = config_path.parent / "dri" + dri.mkdir() + (dri / "renderD129").touch() # A regular file should never supply a group. + if has_dri: + for name in ("renderD128", "card0", "card1"): + (dri / name).symlink_to("/dev/null") + + start() + + groups = "--groups=78,107,109,10001" if has_dri else "--init-groups" + assert (config_path.parent / "setpriv.log").read_text().splitlines() == [ + "--reuid=keystone", + "--regid=keystone", + groups, + ] + + @pytest.mark.parametrize("provider", [None, "", "ollama"]) def test_aio_enables_ollama_after_adding_url(aio_start, provider): start, config_path = aio_start diff --git a/tests/test_intel_packaging.py b/tests/test_intel_packaging.py new file mode 100644 index 0000000..bbfe157 --- /dev/null +++ b/tests/test_intel_packaging.py @@ -0,0 +1,59 @@ +import re +import subprocess +from pathlib import Path + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize("dockerfile", ["Dockerfile", "docker/Dockerfile.aio"]) +def test_intel_image_is_opt_in(dockerfile): + contents = (ROOT / dockerfile).read_text() + stages = re.findall(r"^FROM (\S+) AS (\S+)$", contents, re.MULTILINE) + expected = [("python:3.12-slim-trixie", "runtime")] + if dockerfile == "Dockerfile": + expected.append(("runtime", "cuda")) + assert stages == [*expected, ("runtime", "intel"), ("runtime", "cpu")] + + intel = contents.split("FROM runtime AS intel\n", 1)[1].partition("FROM runtime AS cpu")[0] + assert "sh /tmp/install-intel.sh" in intel + assert "KEYSTONE_ACCEL_FFMPEG_HWACCEL" not in contents + if dockerfile == "Dockerfile": + assert re.search(r"^USER keystone$", intel, re.MULTILINE) + + +def test_intel_install_script_syntax(): + subprocess.run(["sh", "-n", ROOT / "docker/install-intel.sh"], check=True) + + +def test_intel_workflow_builds_only_amd64_and_pushes_only_outside_prs(): + workflow = yaml.load((ROOT / ".github/workflows/docker.yml").read_text(), Loader=yaml.BaseLoader) + assert "pull_request" in workflow["on"] + images = workflow["jobs"]["image"]["strategy"]["matrix"] + assert {platform["arch"] for platform in images["platform"]} == {"amd64", "arm64"} + assert {image["name"] for image in images["image"]} == { + "keystone", "keystone-postgres", "keystone-aio", + } + + intel = workflow["jobs"]["intel"] + assert intel["runs-on"] == "ubuntu-latest" + assert {image["name"]: image["dockerfile"] for image in intel["strategy"]["matrix"]["image"]} == { + "keystone": "Dockerfile", + "keystone-aio": "docker/Dockerfile.aio", + } + actions = {step.get("uses"): step["with"] for step in intel["steps"] if "with" in step} + metadata = actions["docker/metadata-action@v5"] + assert metadata["flavor"] == "suffix=-intel,onlatest=true" + assert metadata["tags"].splitlines() == [ + "type=edge,branch=main", + "type=semver,pattern={{version}}", + "type=semver,pattern={{major}}.{{minor}}", + "type=sha", + ] + build = actions["docker/build-push-action@v6"] + assert build["target"] == "intel" + assert build["platforms"] == "linux/amd64" + assert build["tags"] == "${{ steps.meta.outputs.tags }}" + assert build["push"] == "${{ github.event_name != 'pull_request' }}" diff --git a/tests/test_setup_compose.py b/tests/test_setup_compose.py index 8c872ba..92c8887 100644 --- a/tests/test_setup_compose.py +++ b/tests/test_setup_compose.py @@ -127,6 +127,7 @@ def test_github_ref_validation(monkeypatch: pytest.MonkeyPatch): def test_clone_free_setup_with_existing_compose_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): mod = _load_setup_module() calls = _stub_privileged_cmds(monkeypatch) + monkeypatch.setattr(mod, "DRI_DIR", tmp_path / "absent-dri") existing_compose = "services:\n # custom\n" (tmp_path / "docker-compose.yml").write_text(existing_compose, encoding="utf-8") @@ -152,6 +153,7 @@ def fake_urlopen(req, timeout=30): env_text = (tmp_path / ".env").read_text(encoding="utf-8") assert "KEYSTONE_CONTROLLER_IP=192.0.2.10\n" in env_text assert f"KEYSTONE_CONFIG_GID={os.getgid() or '10001'}\n" in env_text + assert "KEYSTONE_RENDER_GID" not in env_text assert stat.S_IMODE((tmp_path / ".env").stat().st_mode) == 0o600 config_text = (tmp_path / "config.yaml").read_text(encoding="utf-8") assert ' host: "192.0.2.10"' in config_text @@ -174,6 +176,41 @@ def fake_urlopen(req, timeout=30): assert (tmp_path / "config.yaml").read_text(encoding="utf-8") == config_text +def test_render_device_gid_uses_first_character_device(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + mod = _load_setup_module() + monkeypatch.setattr(mod, "DRI_DIR", tmp_path) + (tmp_path / "card0").symlink_to("/dev/null") + (tmp_path / "renderD128").touch() + (tmp_path / "renderD129").symlink_to("/dev/zero") + assert mod.render_device_gid() == Path("/dev/zero").stat().st_gid + + +@pytest.mark.parametrize("existing_env", [False, True]) +def test_setup_records_render_gid(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, existing_env: bool): + mod = _load_setup_module() + _stub_privileged_cmds(monkeypatch) + monkeypatch.setattr(mod, "render_device_gid", lambda: 109) + monkeypatch.setenv("KEYSTONE_CONTROLLER_IP", "192.0.2.10") + (tmp_path / "docker-compose.yml").write_text(COMPOSE_YAML) + (tmp_path / "config.yaml").write_text(EXAMPLE_YAML) + env_file = tmp_path / ".env" + previous = "KEYSTONE_CONFIG_GID=1000\n# Retain the existing password and settings\nKEYSTONE_PG_ADMIN_PASSWORD=test" + if existing_env: + env_file.write_text(previous) + + mod.main(target=tmp_path) + contents = env_file.read_text() + assert contents.endswith("\nKEYSTONE_RENDER_GID=109\n") + if existing_env: + assert contents == f"{previous}\nKEYSTONE_RENDER_GID=109\n" + assert stat.S_IMODE(env_file.stat().st_mode) == 0o600 + + # Preserve an established GID on later runs, including operator overrides. + monkeypatch.setattr(mod, "render_device_gid", lambda: 110) + mod.main(target=tmp_path) + assert env_file.read_text() == contents + + def test_clone_free_setup_fetches_missing_compose_file_and_uses_env_ip( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): diff --git a/unraid/keystone.xml b/unraid/keystone.xml index 5aa6512..8eab35c 100644 --- a/unraid/keystone.xml +++ b/unraid/keystone.xml @@ -15,7 +15,9 @@ Give the container its own IP address on your LAN (Network Type br0 with a fixed Find Anything, Speech-to-Text, License Plates, and Enhance Face are on by default in this template; Face Recognition (InsightFace non-commercial weights) and the virtual AI Port are opt-in below. Event descriptions require a vision server (Ollama, OpenAI-compatible, OpenAI, or Anthropic); set Vision provider to disabled (or leave the vision URL blank with the default Ollama provider) to skip descriptions while Find Anything search still works. -This image includes the PostgreSQL search database Protect uses for Find Anything. Everything is stored under the appdata path. Other settings are in config.yaml there; the fields below override it. +This image includes the PostgreSQL search database Protect uses for Find Anything. Everything is stored under the appdata path. Other settings are in config.yaml there. Non-empty template fields override it. + +For Intel GPU acceleration, switch Repository to ghcr.io/seearms/keystone-aio:latest-intel and add a Device with /dev/dri as the host and container path. Keystone automatically adds the render and card device groups when it starts. For AI Port hardware video decode, set FFmpeg hardware acceleration to auto or set acceleration.ffmpeg_hwaccel to auto in config.yaml. HomeAutomation: Security: Tools:Utilities https://raw.githubusercontent.com/seeARMS/keystone/main/unraid/keystone.xml @@ -34,5 +36,8 @@ This image includes the PostgreSQL search database Protect uses for Find Anythin true false false + + + 127.0.0.1 From 22be034035973086652660f6f763acc19a773658 Mon Sep 17 00:00:00 2001 From: seeARMS <3957773+seeARMS@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:52:04 -0800 Subject: [PATCH 2/2] Address handoff-review findings for Intel Docker and setup --- .github/workflows/docker.yml | 11 +++-------- README.md | 4 ++-- docker-compose.intel.yml | 1 + scripts/setup-compose.py | 11 +++++++++-- tests/test_setup_compose.py | 6 ++++++ unraid/keystone.xml | 2 +- 6 files changed, 22 insertions(+), 13 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index b3437c1..abd0abe 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -61,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 @@ -170,13 +171,7 @@ jobs: - uses: actions/checkout@v4 - *check-version - uses: docker/setup-buildx-action@v3 - - - uses: docker/login-action@v3 - if: github.event_name != 'pull_request' - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} + - *ghcr-login - id: meta uses: docker/metadata-action@v5 diff --git a/README.md b/README.md index 719447f..2f1e5a1 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,7 @@ 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`. 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. +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`. @@ -449,7 +449,7 @@ Off by default so existing installs don't kick off a multi-hour backfill unexpec ### Optional Intel GPU / NPU acceleration (OpenVINO & 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 include both runtimes. [Unraid setup](#unraid) uses the all-in-one image. +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`. diff --git a/docker-compose.intel.yml b/docker-compose.intel.yml index c054993..157331b 100644 --- a/docker-compose.intel.yml +++ b/docker-compose.intel.yml @@ -1,5 +1,6 @@ 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. diff --git a/scripts/setup-compose.py b/scripts/setup-compose.py index e71e56f..2641ae0 100644 --- a/scripts/setup-compose.py +++ b/scripts/setup-compose.py @@ -139,9 +139,16 @@ 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 diff --git a/tests/test_setup_compose.py b/tests/test_setup_compose.py index 92c8887..830091c 100644 --- a/tests/test_setup_compose.py +++ b/tests/test_setup_compose.py @@ -210,6 +210,12 @@ def test_setup_records_render_gid(tmp_path: Path, monkeypatch: pytest.MonkeyPatc mod.main(target=tmp_path) assert env_file.read_text() == contents + # Also preserve Compose's `export KEY=VALUE` dotenv syntax. + exported = "KEYSTONE_CONFIG_GID=1000\nexport KEYSTONE_RENDER_GID=450\nKEYSTONE_PG_ADMIN_PASSWORD=test\n" + env_file.write_text(exported) + mod.main(target=tmp_path) + assert env_file.read_text() == exported + def test_clone_free_setup_fetches_missing_compose_file_and_uses_env_ip( tmp_path: Path, monkeypatch: pytest.MonkeyPatch diff --git a/unraid/keystone.xml b/unraid/keystone.xml index 8eab35c..9b2dcd4 100644 --- a/unraid/keystone.xml +++ b/unraid/keystone.xml @@ -17,7 +17,7 @@ Find Anything, Speech-to-Text, License Plates, and Enhance Face are on by defaul This image includes the PostgreSQL search database Protect uses for Find Anything. Everything is stored under the appdata path. Other settings are in config.yaml there. Non-empty template fields override it. -For Intel GPU acceleration, switch Repository to ghcr.io/seearms/keystone-aio:latest-intel and add a Device with /dev/dri as the host and container path. Keystone automatically adds the render and card device groups when it starts. For AI Port hardware video decode, set FFmpeg hardware acceleration to auto or set acceleration.ffmpeg_hwaccel to auto in config.yaml. +For Intel GPU acceleration, switch Repository to ghcr.io/seearms/keystone-aio:latest-intel (or :edge-intel before the next versioned release is tagged) and add a Device with /dev/dri as the host and container path. Keystone automatically adds the render and card device groups when it starts. For AI Port hardware video decode, set FFmpeg hardware acceleration to auto or set acceleration.ffmpeg_hwaccel to auto in config.yaml. HomeAutomation: Security: Tools:Utilities https://raw.githubusercontent.com/seeARMS/keystone/main/unraid/keystone.xml