Fetch Edge dependencies on demand from Git and remove local package mirror
This commit is contained in:
parent
4c24a187be
commit
dcbc39550a
|
|
@ -2,7 +2,8 @@
|
||||||
|
|
||||||
Основной `install_iomatex_edge.sh` теперь получает все пакеты и готовые runtime
|
Основной `install_iomatex_edge.sh` теперь получает все пакеты и готовые runtime
|
||||||
из нашего Git. Актуальные команды и состав — [в инструкции установки](offline/README.md).
|
из нашего Git. Актуальные команды и состав — [в инструкции установки](offline/README.md).
|
||||||
Зависимости находятся внутри `third_party/`; подготовка внешнего DEB-архива не нужна.
|
Зависимости хранятся в Git внутри `third_party/` и скачиваются по необходимости;
|
||||||
|
на Edge полный набор пакетов и `.git` больше не сохраняются.
|
||||||
Старые команды ниже сохраняются как справочная история, если расходятся с этой инструкцией.
|
Старые команды ниже сохраняются как справочная история, если расходятся с этой инструкцией.
|
||||||
|
|
||||||
Это простая инструкция по установке Edge после прошивки vendor image.
|
Это простая инструкция по установке Edge после прошивки vendor image.
|
||||||
|
|
|
||||||
|
|
@ -31,65 +31,26 @@ if [[ -z "$IOMATEX_GIT_USERNAME" || -z "$IOMATEX_GIT_PASSWORD" ]]; then
|
||||||
read -rsp 'Git password or token: ' IOMATEX_GIT_PASSWORD; echo
|
read -rsp 'Git password or token: ' IOMATEX_GIT_PASSWORD; echo
|
||||||
fi
|
fi
|
||||||
[[ -n "$IOMATEX_GIT_USERNAME" && -n "$IOMATEX_GIT_PASSWORD" ]] || exit 1
|
[[ -n "$IOMATEX_GIT_USERNAME" && -n "$IOMATEX_GIT_PASSWORD" ]] || exit 1
|
||||||
mkdir -p "$(dirname "$CHECKOUT_DIR")"
|
# Fetch only the shared delivery owner; it downloads a verified lightweight snapshot.
|
||||||
work=$(mktemp -d "$(dirname "$CHECKOUT_DIR")/.iomatex-bootstrap.XXXXXX")
|
work=$(mktemp -d)
|
||||||
trap 'rm -rf "$work"' EXIT
|
trap 'rm -rf "$work"' EXIT
|
||||||
cat > "$work/askpass" <<'ASKPASS'
|
python3 - "$GIT_URL" "$GIT_BRANCH" "$work/git_delivery.py" <<'PYTHON'
|
||||||
#!/usr/bin/env bash
|
import base64, json, os, pathlib, urllib.parse, urllib.request, sys
|
||||||
case "$1" in *Username*) printf '%s\n' "$IOMATEX_GIT_USERNAME";; *) printf '%s\n' "$IOMATEX_GIT_PASSWORD";; esac
|
url, branch, destination = sys.argv[1:]
|
||||||
ASKPASS
|
repo = urllib.parse.urlparse(url).path.strip('/').removesuffix('.git')
|
||||||
chmod 700 "$work/askpass"
|
base = 'https://git.it-screen.com/api/v1/repos/' + repo + '/'
|
||||||
export GIT_ASKPASS="$work/askpass" GIT_TERMINAL_PROMPT=0
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
mkdir -p "$(dirname "$CHECKOUT_DIR")"
|
def redirect_request(self, *args, **kwargs):
|
||||||
printf 'Fetching installer and bundled dependencies from %s (%s)\n' "$GIT_URL" "$GIT_BRANCH"
|
raise RuntimeError('Git download redirect refused')
|
||||||
if command -v git >/dev/null; then
|
headers = {'Authorization': 'Basic ' + base64.b64encode((os.environ['IOMATEX_GIT_USERNAME'] + ':' + os.environ['IOMATEX_GIT_PASSWORD']).encode()).decode()}
|
||||||
if [[ -d "$CHECKOUT_DIR/.git" ]]; then
|
opener = urllib.request.build_opener(NoRedirect)
|
||||||
[[ $(git -C "$CHECKOUT_DIR" remote get-url origin) == "$GIT_URL" ]] || { echo 'Checkout origin mismatch' >&2; exit 1; }
|
with opener.open(urllib.request.Request(base + 'branches/' + urllib.parse.quote(branch, safe=''), headers=headers), timeout=120) as r:
|
||||||
git -c http.followRedirects=false -C "$CHECKOUT_DIR" fetch origin "$GIT_BRANCH"
|
commit = json.load(r)['commit']['id']
|
||||||
git -C "$CHECKOUT_DIR" checkout "$GIT_BRANCH"
|
with opener.open(urllib.request.Request(base + 'raw/offline/git_delivery.py?ref=' + commit, headers=headers), timeout=120) as r:
|
||||||
git -C "$CHECKOUT_DIR" merge --ff-only FETCH_HEAD
|
pathlib.Path(destination).write_bytes(r.read())
|
||||||
else
|
PYTHON
|
||||||
git -c http.followRedirects=false clone --depth 1 --branch "$GIT_BRANCH" --single-branch "$GIT_URL" "$work/checkout"
|
python3 "$work/git_delivery.py" bootstrap "$GIT_URL" "$GIT_BRANCH" "$CHECKOUT_DIR"
|
||||||
[[ ! -e "$CHECKOUT_DIR" ]] || mv "$CHECKOUT_DIR" "${CHECKOUT_DIR}.before-$(date +%s)"
|
unset IOMATEX_GIT_USERNAME IOMATEX_GIT_PASSWORD
|
||||||
mv "$work/checkout" "$CHECKOUT_DIR"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
# No apt-get to bootstrap git: fetch the repository archive from the same Git host.
|
|
||||||
python3 - "$GIT_URL" "$GIT_BRANCH" "$work" <<'PY'
|
|
||||||
import base64, os, pathlib, sys, tarfile, urllib.parse, urllib.request
|
|
||||||
url, branch, work = sys.argv[1:]
|
|
||||||
class OwnGitOnly(urllib.request.HTTPRedirectHandler):
|
|
||||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
||||||
target = urllib.parse.urlparse(newurl)
|
|
||||||
if target.scheme != 'https' or target.hostname != 'git.it-screen.com':
|
|
||||||
raise RuntimeError('External redirect refused')
|
|
||||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
||||||
repo_path = urllib.parse.urlparse(url).path.removesuffix('.git').strip('/')
|
|
||||||
url = 'https://git.it-screen.com/api/v1/repos/' + repo_path + '/archive/' + urllib.parse.quote(branch, safe='') + '.tar.gz'
|
|
||||||
credentials = (os.environ['IOMATEX_GIT_USERNAME'] + ':' + os.environ['IOMATEX_GIT_PASSWORD']).encode()
|
|
||||||
request = urllib.request.Request(url, headers={'Authorization': 'Basic ' + base64.b64encode(credentials).decode()})
|
|
||||||
archive = pathlib.Path(work) / 'repository.tar.gz'
|
|
||||||
with urllib.request.build_opener(OwnGitOnly).open(request, timeout=600) as response, archive.open('wb') as output:
|
|
||||||
import shutil
|
|
||||||
shutil.copyfileobj(response, output)
|
|
||||||
dest = pathlib.Path(work) / 'checkout'
|
|
||||||
dest.mkdir()
|
|
||||||
with tarfile.open(archive) as source:
|
|
||||||
for item in source.getmembers():
|
|
||||||
parts = pathlib.PurePosixPath(item.name).parts
|
|
||||||
if len(parts) < 2: continue
|
|
||||||
item.name = str(pathlib.PurePosixPath(*parts[1:]))
|
|
||||||
if not (item.isfile() or item.isdir()) or not (dest / item.name).resolve().is_relative_to(dest.resolve()):
|
|
||||||
raise RuntimeError('Unsafe repository archive member')
|
|
||||||
source.extract(item, dest)
|
|
||||||
PY
|
|
||||||
[[ ! -e "$CHECKOUT_DIR" ]] || mv "$CHECKOUT_DIR" "${CHECKOUT_DIR}.before-$(date +%s)"
|
|
||||||
mv "$work/checkout" "$CHECKOUT_DIR"
|
|
||||||
fi
|
|
||||||
unset IOMATEX_GIT_USERNAME IOMATEX_GIT_PASSWORD GIT_ASKPASS GIT_TERMINAL_PROMPT
|
|
||||||
[[ -f "$CHECKOUT_DIR/offline/require-local.sh" ]] || { echo 'Incomplete installer repository' >&2; exit 1; }
|
|
||||||
source "$CHECKOUT_DIR/offline/require-local.sh"
|
|
||||||
(cd "$CHECKOUT_DIR/stage_itscreen" && sha256sum --check itscreen.sha256)
|
|
||||||
rm -rf "$work"
|
rm -rf "$work"
|
||||||
trap - EXIT
|
trap - EXIT
|
||||||
exec bash "$CHECKOUT_DIR/local_installer.sh" "$CHECKOUT_DIR" --non-interactive --reset-state --only "$STAGES"
|
exec bash "$CHECKOUT_DIR/local_installer.sh" "$CHECKOUT_DIR" --non-interactive --reset-state --only "$STAGES"
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,9 @@
|
||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Install a complete checkout without fetching anything, using its bundled packages.
|
# Legacy entrypoint: stages use on-demand downloads from our Git.
|
||||||
set -Eeuo pipefail
|
set -Eeuo pipefail
|
||||||
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||||
[[ ${EUID} -eq 0 ]] || { echo 'Run with sudo bash install_offline.sh [comma-separated-stages]' >&2; exit 1; }
|
[[ ${EUID} -eq 0 ]] || { echo 'Run with sudo bash install_offline.sh [comma-separated-stages]' >&2; exit 1; }
|
||||||
[[ $# -le 1 ]] || { echo 'Usage: install_offline.sh [comma-separated-stages]' >&2; exit 1; }
|
[[ $# -le 1 ]] || { echo 'Usage: install_offline.sh [comma-separated-stages]' >&2; exit 1; }
|
||||||
STAGES=${1:-stage_env,stage_wifi,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_itscreen,stage_reverse_tunnels}
|
STAGES=${1:-stage_env,stage_wifi,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_itscreen,stage_reverse_tunnels}
|
||||||
source "$ROOT/offline/require-local.sh"
|
source "$ROOT/offline/require-local.sh"
|
||||||
(cd "$ROOT/stage_itscreen" && sha256sum --check itscreen.sha256)
|
|
||||||
exec bash "$ROOT/local_installer.sh" "$ROOT" --non-interactive --reset-state --only "$STAGES"
|
exec bash "$ROOT/local_installer.sh" "$ROOT" --non-interactive --reset-state --only "$STAGES"
|
||||||
|
|
|
||||||
|
|
@ -1421,7 +1421,7 @@ else
|
||||||
else
|
else
|
||||||
if [[ "$USE_GIT_SOURCE" -eq 1 ]]; then
|
if [[ "$USE_GIT_SOURCE" -eq 1 ]]; then
|
||||||
[[ "$GIT_URL" == https://git.it-screen.com/* ]] || die "Only our Git is allowed"
|
[[ "$GIT_URL" == https://git.it-screen.com/* ]] || die "Only our Git is allowed"
|
||||||
prepare_git_source "$(default_git_checkout_dir)"
|
die "Use install_iomatex_edge.sh to update the lightweight snapshot; full Git clones on Edge are disabled"
|
||||||
else
|
else
|
||||||
PROJECT_DIR="$SCRIPT_DIR"
|
PROJECT_DIR="$SCRIPT_DIR"
|
||||||
SOURCE_TYPE="local"
|
SOURCE_TYPE="local"
|
||||||
|
|
|
||||||
|
|
@ -1,71 +1,78 @@
|
||||||
# Установка Edge: зависимости только из нашего Git
|
# Установка Edge: из нашего Git, без хранения пакетов на устройстве
|
||||||
|
|
||||||
Обычный `install_iomatex_edge.sh` получает полный репозиторий с
|
Обычный `install_iomatex_edge.sh` получает небольшой snapshot скриптов и метаданных
|
||||||
`https://git.it-screen.com/An-J/Iomatex_OS.git`, ветка `ci-cd`.
|
из `https://git.it-screen.com/An-J/Iomatex_OS.git`, ветка `ci-cd`.
|
||||||
DEB-пакеты, Node, зависимости и собранный Zigbee2MQTT хранятся в `third_party/`.
|
Он не делает Git clone и не скачивает полный архив репозитория: на Edge нет
|
||||||
Отдельное внешнее хранилище или предварительное копирование пакетов не нужно.
|
ни каталога всех DEB, ни скрытой копии пакетов в `.git`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo bash install_iomatex_edge.sh
|
sudo bash install_iomatex_edge.sh
|
||||||
# Включая установку Zigbee2MQTT:
|
# Включая Zigbee2MQTT:
|
||||||
sudo bash install_iomatex_edge.sh --with-z2m
|
sudo bash install_iomatex_edge.sh --with-z2m
|
||||||
```
|
```
|
||||||
|
|
||||||
Поддерживается vendor-образ Debian 11 Bullseye arm64 с Bash, Python 3,
|
Поддерживается vendor-образ Debian 11 Bullseye arm64 с Bash, Python 3,
|
||||||
CA certificates и рабочей сетью. Ядро, GPU-драйверы и bootloader относятся к образу.
|
CA certificates и рабочей сетью. Git для загрузки установщика не требуется.
|
||||||
Если Git ещё не установлен, bootstrap получает архив репозитория с того же Git
|
Ядро, GPU-драйверы и bootloader относятся к базовому образу.
|
||||||
через Python HTTPS; устанавливать Git из Debian для начальной загрузки не требуется.
|
|
||||||
По умолчанию checkout размещается в `/userdata/Iomatex_OS`, чтобы не заполнить
|
|
||||||
маленький корневой раздел. Не удаляйте checkout после установки.
|
|
||||||
|
|
||||||
Все этапы используют общий `offline/require-local.sh`: он проверяет SHA-256 и
|
## Как доставляются пакеты
|
||||||
активирует только локальный `file:` APT-источник из checkout. Сторонние source lists
|
|
||||||
исключены из выбора через `/etc/apt/apt.conf.d/99iomatex-offline`. Недостающий или
|
|
||||||
повреждённый пакет останавливает установку; сетевого fallback нет. Конфигурация
|
|
||||||
сохраняется для штатного продолжения после перезагрузки stage_env и отдельных
|
|
||||||
запусков stage-скриптов. APT cache расположен в `/userdata/iomatex-apt-cache`.
|
|
||||||
|
|
||||||
Для уже полученного полного checkout без повторного скачивания:
|
- Snapshot размещается в `/userdata/Iomatex_OS`. `.iomatex-source.json` фиксирует
|
||||||
|
commit и контрольные суммы скриптов. Локальные изменения отслеживаемых файлов
|
||||||
|
блокируют обновление; посторонние файлы, журналы и состояние сохраняются.
|
||||||
|
- Полный набор DEB, Node и архив Z2M постоянно хранится только в нашем Git
|
||||||
|
(`third_party/`). На рабочей станции обычный полный checkout по-прежнему допустим.
|
||||||
|
- Общий `offline/git_delivery.py` устанавливает APT transport `iomatex`.
|
||||||
|
APT использует небольшой локальный каталог пакетов, сам выбирает недостающие
|
||||||
|
зависимости и получает только нужные DEB через HTTPS API нашего Git.
|
||||||
|
- Все загрузки привязаны к одному commit и проверяются по SHA-256. Редиректы и
|
||||||
|
неизвестные объекты запрещены. Внешнего APT/NodeSource/GitHub/npm fallback нет.
|
||||||
|
- DEB находятся в `/userdata/iomatex-apt-cache` только во время установки. APT
|
||||||
|
удаляет их после dpkg; при следующем запуске также очищаются остатки прерванных
|
||||||
|
загрузок. Очистка не вмешивается в работающий APT, использующий cache lock.
|
||||||
|
- Клиент и Z2M-архив скачиваются во временный файл только соответствующим этапом
|
||||||
|
и удаляются при завершении или ошибке этого этапа. Установленные приложения и
|
||||||
|
рабочие node_modules остаются: это используемое ПО, а не установочный архив.
|
||||||
|
- Для продолжения после reboot и повторной установки данные доступа сохраняются
|
||||||
|
в `/etc/iomatex/git-credentials.json`, режим 0600, только root. Используйте
|
||||||
|
учётную запись развёртывания с доступом на чтение репозитория. Они не попадают
|
||||||
|
в Git, URI пакетов, командную строку APT или журнал установки. APT downloader
|
||||||
|
читает их перед снижением привилегий до `_apt`.
|
||||||
|
|
||||||
|
Настройка `/etc/apt/apt.conf.d/99iomatex-offline` сохраняет историческое имя, но
|
||||||
|
теперь выбирает только `iomatex://git.it-screen.com/`. Сторонние source lists
|
||||||
|
исключены. Каталог и source metadata находятся в `/var/lib/iomatex/packages`.
|
||||||
|
Отсутствие сети или неверные Git credentials приводят к ошибке загрузки.
|
||||||
|
Установка больше не является автономной: это сознательный обмен хранения на
|
||||||
|
загрузку по необходимости. Регистрация, MQTT и туннели используют сеть отдельно.
|
||||||
|
|
||||||
|
## Обновление уже установленного Edge
|
||||||
|
|
||||||
|
Запустите актуальный bootstrap. Он сначала получает и проверяет новый snapshot,
|
||||||
|
потом заменяет старый. Старый чистый полный checkout мигрируется с удалением
|
||||||
|
tracked payloads и `.git`; локальные правки не затираются. Конфигурации приложений
|
||||||
|
в `/etc`, `/opt` и `/userdata/itscreen` этим обновлением не удаляются.
|
||||||
|
Для запуска отдельных этапов из уже полученного snapshot:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo bash /userdata/Iomatex_OS/install_offline.sh
|
sudo bash /userdata/Iomatex_OS/stage_ui/ui_installer.sh
|
||||||
# Только отдельные этапы:
|
|
||||||
sudo bash /userdata/Iomatex_OS/install_offline.sh stage_ui,stage_itscreen
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Стандартный профиль включает stage_env, stage_wifi, stage_mqtt, stage_ui,
|
Исторический `install_offline.sh [stages]` оставлен как совместимый запуск этапов;
|
||||||
stage_avahi, stage_cockpit, stage_itscreen, stage_reverse_tunnels.
|
он тоже использует загрузку по необходимости. `local_installer.sh --git` больше
|
||||||
`--with-z2m` добавляет stage_z2m. Установщики dashboards/bridge также используют
|
не создаёт полный clone: для обновления snapshot используется публичный bootstrap.
|
||||||
тот же набор пакетов. IDE и компиляторы для разработки на Edge не устанавливаются.
|
Стандартный профиль включает восемь этапов и штатное продолжение после reboot.
|
||||||
Регистрация, MQTT, NTP и reverse tunnels используют сеть по назначению;
|
|
||||||
ограничение касается источников устанавливаемого ПО.
|
|
||||||
|
|
||||||
## Обновление набора на рабочей станции
|
## Подготовка нового набора сопровождающим
|
||||||
|
|
||||||
`offline/build.sh` — инструмент сопровождающего, НЕ часть установки на Edge.
|
`offline/build.sh` запускается только на рабочей станции. Он может обращаться
|
||||||
Только он обращается к подписанному архиву Debian и фиксированному security
|
к подписанному Debian archive/security snapshot, затем результат коммитится в
|
||||||
snapshot `20260831T235959Z`. Builder image закреплён по digest. APT signatures
|
наш Git. На Edge сборщик не вызывается. Состав и происхождение —
|
||||||
проверяются; истёкший Valid-Until отключён только для исторического snapshot.
|
`third_party/README.md`; cold dependency test проверяет полный набор без сети.
|
||||||
Разрешение зависимостей выполняется с пустым dpkg status.
|
При обновлении Node обновляйте также `third_party/node/Packages`, SHA256SUMS и
|
||||||
|
совместимый prebuilt Z2M runtime. Клиент 4.410.122 закреплён в
|
||||||
|
`stage_itscreen/itscreen.version` и `stage_itscreen/itscreen.sha256`.
|
||||||
|
|
||||||
Соберите новый каталог, проверьте его, затем замените `third_party/debian/bullseye-arm64`
|
Транспорт использует штатный
|
||||||
целиком и закоммитьте вместе с манифестами. Не редактируйте отдельные DEB на Edge.
|
[протокол APT methods](https://sources.debian.org/src/apt/2.2.4/doc/method.dbk/).
|
||||||
Node и Z2M обновляйте согласованно для arm64 и одной Node ABI; состав и происхождение
|
История проверок — `offline/TEST_REPORT_20260914.md`.
|
||||||
описаны в `third_party/README.md`. Пользовательские data/config/logs в runtime не входят.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./offline/build.sh /absolute/storage/new-bullseye-arm64
|
|
||||||
python3 offline/activate.py --verify third_party/debian/bullseye-arm64
|
|
||||||
bash offline/test_cold.sh third_party/debian/bullseye-arm64
|
|
||||||
python3 offline/test_bundle.py
|
|
||||||
python3 offline/test_qt_stack.py
|
|
||||||
```
|
|
||||||
|
|
||||||
Версия клиента зафиксирована в `stage_itscreen/itscreen.version` (4.410.122),
|
|
||||||
целостность — `stage_itscreen/itscreen.sha256`. Bootstrap проверяет бинарь.
|
|
||||||
На существующем Edge сохраняется вариант desktop Qt; на образе без Qt ставится GLES.
|
|
||||||
|
|
||||||
Перед переустановкой сохраняйте регистрацию, конфигурации, ключи и данные.
|
|
||||||
Первоначальная APT-конфигурация сохраняется в `/etc/apt/iomatex-before-offline-*`.
|
|
||||||
Этот набор обеспечивает повторяемость установки, но сам по себе не продлевает
|
|
||||||
поддержку безопасности Debian 11 и не является образом прошивки.
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,343 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Small Edge snapshot + on-demand, hash-checked downloads from our Git only.
|
||||||
|
APT method protocol: https://sources.debian.org/src/apt/2.2.4/doc/method.dbk/
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import fcntl
|
||||||
|
import gzip
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
|
import pwd
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
HOST = 'git.it-screen.com'
|
||||||
|
STATE = Path('/var/lib/iomatex/packages')
|
||||||
|
AUTH = Path('/etc/iomatex/git-credentials.json')
|
||||||
|
CACHE = Path('/userdata/iomatex-apt-cache')
|
||||||
|
DEBIAN = 'third_party/debian/bullseye-arm64'
|
||||||
|
|
||||||
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, *args, **kwargs):
|
||||||
|
raise ValueError('Git download redirect refused')
|
||||||
|
|
||||||
|
def safe_path(value):
|
||||||
|
p = PurePosixPath(value)
|
||||||
|
if p.is_absolute() or '..' in p.parts or not p.parts or any(c in value for c in '\r\n\\'):
|
||||||
|
raise ValueError('Unsafe repository path')
|
||||||
|
return p.as_posix()
|
||||||
|
|
||||||
|
def repo_name(url):
|
||||||
|
u = urllib.parse.urlparse(url)
|
||||||
|
if u.scheme != 'https' or u.netloc != HOST or u.query or u.fragment:
|
||||||
|
raise ValueError('Only HTTPS repositories on our Git are allowed')
|
||||||
|
name = u.path.strip('/').removesuffix('.git')
|
||||||
|
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', name):
|
||||||
|
raise ValueError('Invalid repository')
|
||||||
|
return name
|
||||||
|
|
||||||
|
def auth_from_env():
|
||||||
|
user, password = os.environ.get('IOMATEX_GIT_USERNAME'), os.environ.get('IOMATEX_GIT_PASSWORD')
|
||||||
|
if user and password:
|
||||||
|
return {'username': user, 'password': password}
|
||||||
|
return json.loads(AUTH.read_text())
|
||||||
|
|
||||||
|
def open_git(repo, endpoint, auth):
|
||||||
|
url = 'https://' + HOST + '/api/v1/repos/' + repo + '/' + endpoint
|
||||||
|
token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode()
|
||||||
|
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token})
|
||||||
|
return urllib.request.build_opener(NoRedirect).open(req, timeout=120)
|
||||||
|
|
||||||
|
def raw_endpoint(path, commit):
|
||||||
|
if not re.fullmatch('[a-f0-9]{40}', commit):
|
||||||
|
raise ValueError('Download must be pinned to a commit')
|
||||||
|
return 'raw/' + urllib.parse.quote(safe_path(path), safe='/') + '?ref=' + commit
|
||||||
|
|
||||||
|
def blob_hash(data):
|
||||||
|
return hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest()
|
||||||
|
|
||||||
|
def write_json(path, value, mode=0o644):
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd, tmp = tempfile.mkstemp(dir=path.parent)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, 'w') as f:
|
||||||
|
json.dump(value, f)
|
||||||
|
os.chmod(tmp, mode)
|
||||||
|
os.replace(tmp, path)
|
||||||
|
finally:
|
||||||
|
Path(tmp).unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def platform_check():
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
raise PermissionError('Run as root')
|
||||||
|
if subprocess.check_output(['dpkg', '--print-architecture'], text=True).strip() != 'arm64' or 'VERSION_CODENAME=bullseye' not in Path('/etc/os-release').read_text():
|
||||||
|
raise ValueError('Supported image: Debian 11 Bullseye arm64')
|
||||||
|
|
||||||
|
def is_payload(path):
|
||||||
|
return path.endswith(('.deb', '.tar.gz')) or path == 'stage_itscreen/itscreen'
|
||||||
|
|
||||||
|
def check_existing(dest):
|
||||||
|
if (dest / '.git').exists():
|
||||||
|
changed = subprocess.check_output(['git', '-C', str(dest), 'status', '--porcelain', '--untracked-files=no'], text=True)
|
||||||
|
if changed.strip():
|
||||||
|
raise ValueError('Existing checkout has tracked local changes; preserve them before updating')
|
||||||
|
elif (dest / '.iomatex-source.json').exists():
|
||||||
|
for entry in json.loads((dest / '.iomatex-source.json').read_text())['files']:
|
||||||
|
p = dest / entry['path']
|
||||||
|
if p.is_file() and blob_hash(p.read_bytes()) != entry['sha']:
|
||||||
|
raise ValueError('Local change in snapshot: ' + entry['path'])
|
||||||
|
elif dest.exists() and any(dest.iterdir()):
|
||||||
|
raise ValueError('Refusing to replace an unidentified nonempty directory')
|
||||||
|
|
||||||
|
def bootstrap(url, branch, checkout):
|
||||||
|
platform_check()
|
||||||
|
repo = repo_name(url)
|
||||||
|
requested = Path(checkout)
|
||||||
|
dest = requested.resolve()
|
||||||
|
if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink():
|
||||||
|
raise ValueError('Use a dedicated absolute installer subdirectory')
|
||||||
|
check_existing(dest)
|
||||||
|
if (dest / '.git').exists():
|
||||||
|
origin = subprocess.check_output(['git', '-C', str(dest), 'remote', 'get-url', 'origin'], text=True).strip()
|
||||||
|
if repo_name(origin) != repo:
|
||||||
|
raise ValueError('Existing checkout origin mismatch')
|
||||||
|
auth = auth_from_env()
|
||||||
|
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
|
||||||
|
commit = json.load(r)['commit']['id']
|
||||||
|
with open_git(repo, 'git/trees/' + commit + '?recursive=true', auth) as r:
|
||||||
|
tree = json.load(r)
|
||||||
|
if tree.get('truncated'):
|
||||||
|
raise ValueError('Git returned an incomplete repository tree')
|
||||||
|
files = []
|
||||||
|
for item in tree['tree']:
|
||||||
|
path = safe_path(item['path'])
|
||||||
|
if item['type'] == 'tree' or is_payload(path):
|
||||||
|
continue
|
||||||
|
if item['type'] != 'blob' or item['mode'] not in ('100644', '100755'):
|
||||||
|
raise ValueError('Unsupported Git tree member: ' + path)
|
||||||
|
files.append({k: item[k] for k in ('path', 'sha', 'mode')})
|
||||||
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with tempfile.TemporaryDirectory(prefix='.iomatex-install-', dir=dest.parent) as tmp:
|
||||||
|
staged = Path(tmp) / 'snapshot'
|
||||||
|
staged.mkdir()
|
||||||
|
def download(entry):
|
||||||
|
with open_git(repo, raw_endpoint(entry['path'], commit), auth) as r:
|
||||||
|
data = r.read()
|
||||||
|
if blob_hash(data) != entry['sha']:
|
||||||
|
raise ValueError('Git blob checksum mismatch: ' + entry['path'])
|
||||||
|
p = staged / entry['path']
|
||||||
|
p.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
p.write_bytes(data)
|
||||||
|
p.chmod(int(entry['mode'][-3:], 8))
|
||||||
|
with ThreadPoolExecutor(max_workers=6) as pool:
|
||||||
|
list(pool.map(download, files))
|
||||||
|
source = {'repo': repo, 'commit': commit, 'branch': branch, 'files': files}
|
||||||
|
write_json(staged / '.iomatex-source.json', source)
|
||||||
|
# Validate all metadata before replacing an existing installation snapshot.
|
||||||
|
catalog(staged)
|
||||||
|
previous = Path(tmp) / 'previous'
|
||||||
|
if dest.exists():
|
||||||
|
# Keep untracked operator files/state/logs, never carry the old Git pack or payloads.
|
||||||
|
tracked = set()
|
||||||
|
if (dest / '.git').exists():
|
||||||
|
tracked = set(subprocess.check_output(['git', '-C', str(dest), 'ls-files'], text=True).splitlines())
|
||||||
|
else:
|
||||||
|
tracked = {e['path'] for e in json.loads((dest / '.iomatex-source.json').read_text()).get('files', [])}
|
||||||
|
for p in dest.rglob('*'):
|
||||||
|
relative = p.relative_to(dest).as_posix()
|
||||||
|
if '.git' in p.relative_to(dest).parts or relative in tracked or relative == '.iomatex-source.json':
|
||||||
|
continue
|
||||||
|
if p.is_file() and not p.is_symlink() and not (staged / relative).exists():
|
||||||
|
(staged / relative).parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(p, staged / relative)
|
||||||
|
dest.rename(previous)
|
||||||
|
try:
|
||||||
|
staged.rename(dest)
|
||||||
|
write_json(AUTH, auth, 0o600)
|
||||||
|
# Execute the NEW activator from the downloaded commit, not an old bootstrap copy.
|
||||||
|
subprocess.run([sys.executable, str(dest / 'offline/git_delivery.py'), 'activate', str(dest)], check=True)
|
||||||
|
except BaseException:
|
||||||
|
if dest.exists(): shutil.rmtree(dest)
|
||||||
|
if previous.exists(): previous.rename(dest)
|
||||||
|
raise
|
||||||
|
print('Lightweight installer ready:', commit, str(dest), flush=True)
|
||||||
|
|
||||||
|
def manifest(path):
|
||||||
|
result = {}
|
||||||
|
for line in path.read_text().splitlines():
|
||||||
|
digest, name = line.split(' ', 1)
|
||||||
|
name = safe_path(name)
|
||||||
|
if not re.fullmatch('[a-f0-9]{64}', digest) or name in result:
|
||||||
|
raise ValueError('Invalid checksum manifest')
|
||||||
|
result[name] = digest
|
||||||
|
return result
|
||||||
|
|
||||||
|
def catalog(root):
|
||||||
|
root = Path(root)
|
||||||
|
sums = manifest(root / DEBIAN / 'SHA256SUMS')
|
||||||
|
runtime = manifest(root / 'third_party/SHA256SUMS')
|
||||||
|
for name, digest in sums.items():
|
||||||
|
if not name.endswith('.deb') and hashlib.sha256((root / DEBIAN / name).read_bytes()).hexdigest() != digest:
|
||||||
|
raise ValueError('Metadata checksum mismatch: ' + name)
|
||||||
|
if (root / DEBIAN / 'platform').read_text().splitlines() != ['bullseye', 'arm64']:
|
||||||
|
raise ValueError('Unsupported package catalog')
|
||||||
|
objects = {}
|
||||||
|
stanzas = []
|
||||||
|
for text, prefix, base, hashes in [
|
||||||
|
((root / DEBIAN / 'repo/Packages').read_text(), 'debian', DEBIAN + '/repo', {k.removeprefix('repo/'):v for k,v in sums.items() if k.endswith('.deb')}),
|
||||||
|
((root / 'third_party/node/Packages').read_text(), 'node', 'third_party/node', {k.removeprefix('node/'):v for k,v in runtime.items() if k.startswith('node/')}),
|
||||||
|
]:
|
||||||
|
for stanza in text.strip().split('\n\n'):
|
||||||
|
fields = dict(line.split(': ', 1) for line in stanza.splitlines() if ': ' in line and not line.startswith(' '))
|
||||||
|
name = safe_path(fields['Filename'].removeprefix('./'))
|
||||||
|
digest = fields['SHA256']
|
||||||
|
if hashes.get(name) != digest:
|
||||||
|
raise ValueError('Package index not covered by SHA256SUMS: ' + name)
|
||||||
|
logical = prefix + '/' + name
|
||||||
|
objects[logical] = {'path': base + '/' + name, 'sha256': digest, 'size': int(fields['Size'])}
|
||||||
|
stanzas.append(re.sub(r'^Filename: .*$', 'Filename: ' + logical, stanza, flags=re.M))
|
||||||
|
for name, digest in runtime.items():
|
||||||
|
objects['third_party/' + name] = {'path': 'third_party/' + name, 'sha256': digest}
|
||||||
|
digest = manifest(root / 'stage_itscreen/itscreen.sha256')['itscreen']
|
||||||
|
objects['stage_itscreen/itscreen'] = {'path': 'stage_itscreen/itscreen', 'sha256': digest}
|
||||||
|
return '\n\n'.join(stanzas) + '\n\n', objects
|
||||||
|
|
||||||
|
def activate(root):
|
||||||
|
platform_check()
|
||||||
|
root = Path(root).resolve()
|
||||||
|
source = json.loads((root / '.iomatex-source.json').read_text())
|
||||||
|
repo_name('https://' + HOST + '/' + source['repo'])
|
||||||
|
raw_endpoint('probe', source['commit'])
|
||||||
|
auth_from_env() # fail before modifying APT if reboot credentials are missing
|
||||||
|
text, objects = catalog(root)
|
||||||
|
STATE.mkdir(parents=True, exist_ok=True)
|
||||||
|
(STATE / 'Packages').write_text(text)
|
||||||
|
(STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0))
|
||||||
|
write_json(STATE / 'source.json', {'repo':source['repo'], 'commit':source['commit'], 'objects':objects})
|
||||||
|
owner = Path('/usr/local/lib/iomatex')
|
||||||
|
owner.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(root / 'offline/git_delivery.py', owner / 'git_delivery.py')
|
||||||
|
method = Path('/usr/lib/apt/methods/iomatex')
|
||||||
|
method.write_text('#!/bin/sh\nexec /usr/bin/python3 /usr/local/lib/iomatex/git_delivery.py apt-method\n')
|
||||||
|
method.chmod(0o755)
|
||||||
|
CACHE.mkdir(parents=True, exist_ok=True)
|
||||||
|
(CACHE / 'partial').mkdir(exist_ok=True)
|
||||||
|
apt = Path('/etc/apt')
|
||||||
|
(apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.it-screen.com/ ./\n')
|
||||||
|
(apt / 'apt.conf.d/99iomatex-offline').write_text(
|
||||||
|
'Dir::Etc::sourcelist "/etc/apt/iomatex-offline.list";\n'
|
||||||
|
'Dir::Etc::sourceparts "-";\n'
|
||||||
|
'Dir::Cache::archives "/userdata/iomatex-apt-cache/";\n'
|
||||||
|
'APT::Install-Recommends "false";\nAPT::Install-Suggests "false";\nAcquire::Languages "none";\n'
|
||||||
|
'APT::Keep-Downloaded-Packages "false";\nBinary::apt-get::APT::Keep-Downloaded-Packages "false";\n'
|
||||||
|
'DPkg::Post-Invoke { "rm -f /userdata/iomatex-apt-cache/*.deb /userdata/iomatex-apt-cache/partial/*.deb"; };\n')
|
||||||
|
cleanup()
|
||||||
|
print('Git-only APT ready; payloads downloaded on demand:', source['commit'], flush=True)
|
||||||
|
|
||||||
|
def cleanup():
|
||||||
|
CACHE.mkdir(parents=True, exist_ok=True)
|
||||||
|
with (CACHE / 'lock').open('a') as lock:
|
||||||
|
try: fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
except BlockingIOError: return
|
||||||
|
for folder in [CACHE, CACHE / 'partial']:
|
||||||
|
if folder.exists():
|
||||||
|
for p in folder.iterdir():
|
||||||
|
if p.is_file() and p.name != 'lock': p.unlink()
|
||||||
|
|
||||||
|
def download_object(config, key, dest, auth):
|
||||||
|
entry = config['objects'].get(key)
|
||||||
|
if entry is None:
|
||||||
|
raise FileNotFoundError('Object absent from the pinned Git catalog')
|
||||||
|
path = Path(dest)
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
size = 0
|
||||||
|
try:
|
||||||
|
with open_git(config['repo'], raw_endpoint(entry['path'], config['commit']), auth) as response, path.open('wb') as output:
|
||||||
|
while True:
|
||||||
|
chunk = response.read(1024 * 1024)
|
||||||
|
if not chunk: break
|
||||||
|
output.write(chunk)
|
||||||
|
digest.update(chunk)
|
||||||
|
size += len(chunk)
|
||||||
|
if digest.hexdigest() != entry['sha256'] or ('size' in entry and size != entry['size']):
|
||||||
|
raise ValueError('Git payload checksum or size mismatch')
|
||||||
|
except BaseException:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
return digest.hexdigest(), size
|
||||||
|
|
||||||
|
def message(code, fields):
|
||||||
|
print(code)
|
||||||
|
for k, v in fields.items():
|
||||||
|
print(k + ': ' + str(v).replace('\n', ' ').replace('\r', ' '))
|
||||||
|
print('', flush=True)
|
||||||
|
|
||||||
|
def apt_method():
|
||||||
|
def stopped(signum, frame):
|
||||||
|
raise SystemExit(0)
|
||||||
|
signal.signal(signal.SIGINT, stopped)
|
||||||
|
signal.signal(signal.SIGTERM, stopped)
|
||||||
|
config = json.loads((STATE / 'source.json').read_text())
|
||||||
|
auth = auth_from_env()
|
||||||
|
# APT launches this helper as root; read private credentials before dropping privileges.
|
||||||
|
if os.geteuid() == 0:
|
||||||
|
user = pwd.getpwnam('_apt')
|
||||||
|
os.setgroups([])
|
||||||
|
os.setgid(user.pw_gid)
|
||||||
|
os.setuid(user.pw_uid)
|
||||||
|
message('100 Capabilities', {'Version':'1.0', 'Single-Instance':'true', 'Pipeline':'false', 'Send-Config':'false'})
|
||||||
|
while True:
|
||||||
|
first = sys.stdin.readline()
|
||||||
|
if not first: return
|
||||||
|
if not first.strip(): continue
|
||||||
|
fields = {}
|
||||||
|
while True:
|
||||||
|
line = sys.stdin.readline().rstrip('\n')
|
||||||
|
if not line: break
|
||||||
|
k, _, value = line.partition(': ')
|
||||||
|
fields[k] = value
|
||||||
|
if not first.startswith('600 '): continue
|
||||||
|
uri, filename = fields.get('URI', ''), fields.get('Filename', '')
|
||||||
|
try:
|
||||||
|
u = urllib.parse.urlparse(uri)
|
||||||
|
if u.scheme != 'iomatex' or u.netloc != HOST or u.query or u.fragment:
|
||||||
|
raise ValueError('Unsupported APT source')
|
||||||
|
key = safe_path(urllib.parse.unquote(u.path).lstrip('/'))
|
||||||
|
if key not in ('Packages', 'Packages.gz') and key not in config['objects']:
|
||||||
|
raise FileNotFoundError('File absent from the pinned Git catalog')
|
||||||
|
message('200 URI Start', {'URI':uri})
|
||||||
|
if key in ('Packages', 'Packages.gz'):
|
||||||
|
data = (STATE / key).read_bytes()
|
||||||
|
Path(filename).write_bytes(data)
|
||||||
|
digest, size = hashlib.sha256(data).hexdigest(), len(data)
|
||||||
|
else:
|
||||||
|
digest, size = download_object(config, key, filename, auth)
|
||||||
|
message('201 URI Done', {'URI':uri, 'Filename':filename, 'Size':size, 'SHA256-Hash':digest})
|
||||||
|
except Exception as e:
|
||||||
|
# Never print authenticated URLs, response bodies, or credentials.
|
||||||
|
message('400 URI Failure', {'URI':uri, 'Message':type(e).__name__ + ': Git download failed or object absent'})
|
||||||
|
|
||||||
|
def main():
|
||||||
|
cmd = sys.argv[1]
|
||||||
|
if cmd == 'bootstrap': bootstrap(*sys.argv[2:])
|
||||||
|
elif cmd == 'activate': activate(sys.argv[2])
|
||||||
|
elif cmd == 'cleanup': cleanup()
|
||||||
|
elif cmd == 'fetch':
|
||||||
|
download_object(json.loads((STATE / 'source.json').read_text()), sys.argv[2], sys.argv[3], auth_from_env())
|
||||||
|
elif cmd == 'apt-method': apt_method()
|
||||||
|
else: raise ValueError('Unknown command')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
try: main()
|
||||||
|
except Exception as error:
|
||||||
|
print('Iomatex Git delivery failed: ' + type(error).__name__ + ': ' + str(error), file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
@ -1,12 +1,10 @@
|
||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Shared package-source owner for every installer; no external APT recovery.
|
# One owner for package sources across all stages. Payloads are never cached in the snapshot.
|
||||||
IOMATEX_PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
IOMATEX_PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
||||||
IOMATEX_PACKAGE_BUNDLE="$IOMATEX_PROJECT_ROOT/third_party/debian/bullseye-arm64"
|
|
||||||
if [[ ${EUID:-$(id -u)} -eq 0 ]]; then
|
if [[ ${EUID:-$(id -u)} -eq 0 ]]; then
|
||||||
[[ -f "$IOMATEX_PACKAGE_BUNDLE/SHA256SUMS" ]] || {
|
[[ -f "$IOMATEX_PROJECT_ROOT/.iomatex-source.json" ]] || {
|
||||||
echo 'ERROR: incomplete Iomatex_OS checkout: third_party packages missing; fetch the complete repository from our Git.' >&2
|
echo 'ERROR: initialize the lightweight Edge snapshot with install_iomatex_edge.sh first.' >&2
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
command -v python3 >/dev/null || { echo 'ERROR: the supported Debian vendor image must include Python 3 for bundle verification.' >&2; exit 1; }
|
python3 "$IOMATEX_PROJECT_ROOT/offline/git_delivery.py" activate "$IOMATEX_PROJECT_ROOT" || exit 1
|
||||||
python3 "$IOMATEX_PROJECT_ROOT/offline/activate.py" "$IOMATEX_PACKAGE_BUNDLE" || exit 1
|
|
||||||
fi
|
fi
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).parent))
|
||||||
|
import git_delivery as d
|
||||||
|
|
||||||
|
class DeliveryTest(unittest.TestCase):
|
||||||
|
def test_payloads_excluded_from_edge_snapshot(self):
|
||||||
|
for name in ['third_party/debian/bullseye-arm64/repo/a.deb', 'third_party/zigbee2mqtt/z.tar.gz', 'stage_itscreen/itscreen']:
|
||||||
|
self.assertTrue(d.is_payload(name))
|
||||||
|
for name in ['third_party/node/Packages', 'third_party/SHA256SUMS', 'local_installer.sh']:
|
||||||
|
self.assertFalse(d.is_payload(name))
|
||||||
|
|
||||||
|
def test_private_git_commit_url_escapes_literal_package_percent(self):
|
||||||
|
url=d.raw_endpoint('third_party/a_2%3a1.deb', 'a'*40)
|
||||||
|
self.assertIn('a_2%253a1.deb?ref=',url)
|
||||||
|
with self.assertRaises(ValueError): d.raw_endpoint('../secret','a'*40)
|
||||||
|
with self.assertRaises(ValueError): d.raw_endpoint('valid', 'ci-cd')
|
||||||
|
with self.assertRaises(ValueError): d.repo_name('https://git.it-screen.com.evil/repo/test')
|
||||||
|
|
||||||
|
def test_download_checks_hash_and_removes_failed_payload(self):
|
||||||
|
with tempfile.TemporaryDirectory() as folder:
|
||||||
|
target=Path(folder)/'package.deb'
|
||||||
|
data=b'package contents'
|
||||||
|
config={'repo':'An-J/Iomatex_OS','commit':'a'*40,'objects':{'debian/test.deb':{'path':'third_party/test.deb','sha256':hashlib.sha256(data).hexdigest(),'size':len(data)}}}
|
||||||
|
with patch.object(d,'open_git',return_value=io.BytesIO(data)):
|
||||||
|
d.download_object(config,'debian/test.deb',target,{})
|
||||||
|
self.assertEqual(target.read_bytes(),data)
|
||||||
|
with patch.object(d,'open_git',return_value=io.BytesIO(b'corrupt')):
|
||||||
|
with self.assertRaises(ValueError): d.download_object(config,'debian/test.deb',target,{})
|
||||||
|
self.assertFalse(target.exists())
|
||||||
|
|
||||||
|
def test_catalog_includes_node_and_vendor_plugin(self):
|
||||||
|
text, objects=d.catalog(Path(__file__).resolve().parents[1])
|
||||||
|
self.assertIn('Package: nodejs\n',text)
|
||||||
|
self.assertIn('Package: qt-video-oes-plugins\n',text)
|
||||||
|
self.assertEqual(582,len([k for k in objects if k.endswith('.deb') and not k.startswith('third_party/')]))
|
||||||
|
|
||||||
|
def test_snapshot_refuses_local_edits(self):
|
||||||
|
with tempfile.TemporaryDirectory() as folder:
|
||||||
|
root=Path(folder)
|
||||||
|
(root/'local_installer.sh').write_bytes(b'changed')
|
||||||
|
(root/'.iomatex-source.json').write_text(json.dumps({'files':[{'path':'local_installer.sh','sha':d.blob_hash(b'original')}]}))
|
||||||
|
with self.assertRaisesRegex(ValueError,'Local change'): d.check_existing(root)
|
||||||
|
|
||||||
|
def test_no_redirect_even_on_same_host(self):
|
||||||
|
with self.assertRaisesRegex(ValueError,'redirect refused'):
|
||||||
|
d.NoRedirect().redirect_request(None,None,302,'',{},'https://git.it-screen.com/other')
|
||||||
|
|
||||||
|
if __name__=='__main__': unittest.main()
|
||||||
|
|
@ -23,7 +23,8 @@ class GitOnlyTests(unittest.TestCase):
|
||||||
self.assertNotRegex(source, r'(?:https?://)(?:[^\s"\']*\.)?(?:debian.org|github.com|nodesource.com|npmjs.org)(?:[/:])', str(script))
|
self.assertNotRegex(source, r'(?:https?://)(?:[^\s"\']*\.)?(?:debian.org|github.com|nodesource.com|npmjs.org)(?:[/:])', str(script))
|
||||||
self.assertNotRegex(source, r'\b(?:npm|pnpm)\s+(?:install|add)\b', str(script))
|
self.assertNotRegex(source, r'\b(?:npm|pnpm)\s+(?:install|add)\b', str(script))
|
||||||
bootstrap = (ROOT / 'install_iomatex_edge.sh').read_text()
|
bootstrap = (ROOT / 'install_iomatex_edge.sh').read_text()
|
||||||
self.assertIn('http.followRedirects=false', bootstrap)
|
self.assertNotIn('git clone', bootstrap)
|
||||||
|
self.assertIn('git_delivery.py', bootstrap)
|
||||||
self.assertIn('/api/v1/repos/', bootstrap)
|
self.assertIn('/api/v1/repos/', bootstrap)
|
||||||
self.assertNotRegex(bootstrap, r'^\s*apt-get', re.M)
|
self.assertNotRegex(bootstrap, r'^\s*apt-get', re.M)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -302,18 +302,6 @@ install_packages_best_effort() {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
find_itscreen_binary() {
|
|
||||||
if [[ -f "${SCRIPT_DIR}/itscreen" ]]; then
|
|
||||||
echo "${SCRIPT_DIR}/itscreen"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
if [[ -f /home/iomatex/Downloads/itscreen ]]; then
|
|
||||||
echo "/home/iomatex/Downloads/itscreen"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
install_base_packages() {
|
install_base_packages() {
|
||||||
step "Preflight"
|
step "Preflight"
|
||||||
|
|
||||||
|
|
@ -475,24 +463,7 @@ install_qt_packages() {
|
||||||
install_qt_video_oes_plugin() {
|
install_qt_video_oes_plugin() {
|
||||||
step "Install Qt Video OES plugin"
|
step "Install Qt Video OES plugin"
|
||||||
|
|
||||||
local deb="${SCRIPT_DIR}/qt-video-oes-plugins_1.0.3_arm64.deb"
|
run_long "Install Qt Video OES plugin from our Git" 600 apt-get install -y qt-video-oes-plugins=1.0.3
|
||||||
|
|
||||||
if dpkg-query -W -f='${Status}\n' qt-video-oes-plugins 2>/dev/null | grep -qx 'install ok installed'; then
|
|
||||||
log "qt-video-oes-plugins already installed"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
[[ -f "$deb" ]] || die "Missing OES plugin package: $deb"
|
|
||||||
|
|
||||||
if ! run_long "Install Qt Video OES plugin" 600 apt-get install -y "$deb"; then
|
|
||||||
warn "apt failed to install Qt Video OES plugin directly; trying dpkg plus dependency repair"
|
|
||||||
dpkg -i "$deb" >>"$LOG" 2>&1 || true
|
|
||||||
run_long "Fix dependencies after OES plugin install" 600 apt-get install -f -y
|
|
||||||
fi
|
|
||||||
|
|
||||||
if ! dpkg-query -W -f='${Status}\n' qt-video-oes-plugins 2>/dev/null | grep -qx 'install ok installed'; then
|
|
||||||
die "qt-video-oes-plugins is not installed after dependency repair. See ${LOG}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
ldconfig
|
ldconfig
|
||||||
}
|
}
|
||||||
|
|
@ -513,12 +484,15 @@ cleanup_legacy_x11_hacks() {
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
install_itscreen_binary() {
|
install_itscreen_binary() (
|
||||||
local src
|
set -e
|
||||||
step "Install itscreen binary"
|
step "Install itscreen binary"
|
||||||
src="$(find_itscreen_binary)" || { echo "Binary not found"; exit 2; }
|
local src
|
||||||
|
src=$(mktemp /userdata/.iomatex-client.XXXXXX)
|
||||||
|
trap 'rm -f "$src"' EXIT
|
||||||
|
python3 "$IOMATEX_PROJECT_ROOT/offline/git_delivery.py" fetch stage_itscreen/itscreen "$src"
|
||||||
install -m 0755 -o "$ITS_USER" -g "$ITS_GROUP" "$src" "$ITS_BINARY"
|
install -m 0755 -o "$ITS_USER" -g "$ITS_GROUP" "$src" "$ITS_BINARY"
|
||||||
}
|
)
|
||||||
|
|
||||||
install_sudoers() {
|
install_sudoers() {
|
||||||
step "Grant power actions (reboot/shutdown) to itscreen (sudoers)"
|
step "Grant power actions (reboot/shutdown) to itscreen (sudoers)"
|
||||||
|
|
|
||||||
|
|
@ -999,11 +999,11 @@ install_base_packages() {
|
||||||
}
|
}
|
||||||
|
|
||||||
install_node_if_needed() {
|
install_node_if_needed() {
|
||||||
(cd "$IOMATEX_PROJECT_ROOT/third_party" && sha256sum --check SHA256SUMS) || die "Runtime bundle checksum failed"
|
|
||||||
if command -v node >/dev/null 2>&1 && [[ $(node -v) == v20.20.2 ]]; then
|
if command -v node >/dev/null 2>&1 && [[ $(node -v) == v20.20.2 ]]; then
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
apt_noninteractive install "$IOMATEX_PROJECT_ROOT/third_party/node/nodejs_20.20.2-1nodesource1_arm64.deb"
|
apt_noninteractive install nodejs=20.20.2-1nodesource1
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ensure_pnpm_available() {
|
ensure_pnpm_available() {
|
||||||
|
|
@ -1032,11 +1032,14 @@ ensure_directories() {
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
update_z2m_code() {
|
update_z2m_code() (
|
||||||
local staged previous
|
set -e
|
||||||
(cd "$IOMATEX_PROJECT_ROOT/third_party" && sha256sum --check SHA256SUMS) || die "Runtime bundle checksum failed"
|
local staged previous archive
|
||||||
|
archive=$(mktemp /userdata/.iomatex-z2m-runtime.XXXXXX)
|
||||||
|
trap 'rm -f "$archive"' EXIT
|
||||||
|
python3 "$IOMATEX_PROJECT_ROOT/offline/git_delivery.py" fetch third_party/zigbee2mqtt/zigbee2mqtt-2.9.2-node20-arm64.tar.gz "$archive"
|
||||||
staged=$(mktemp -d "$(dirname "$Z2M_DIR")/.iomatex-z2m.XXXXXX")
|
staged=$(mktemp -d "$(dirname "$Z2M_DIR")/.iomatex-z2m.XXXXXX")
|
||||||
if ! tar -xzf "$IOMATEX_PROJECT_ROOT/third_party/zigbee2mqtt/zigbee2mqtt-2.9.2-node20-arm64.tar.gz" -C "$staged"; then
|
if ! tar -xzf "$archive" -C "$staged"; then
|
||||||
rm -rf "$staged"
|
rm -rf "$staged"
|
||||||
die "Cannot unpack bundled Zigbee2MQTT"
|
die "Cannot unpack bundled Zigbee2MQTT"
|
||||||
fi
|
fi
|
||||||
|
|
@ -1051,7 +1054,7 @@ update_z2m_code() {
|
||||||
if [[ -d "$previous/data" ]]; then mv "$previous/data" "$Z2M_DATA_DIR"; else mkdir -p "$Z2M_DATA_DIR"; fi
|
if [[ -d "$previous/data" ]]; then mv "$previous/data" "$Z2M_DATA_DIR"; else mkdir -p "$Z2M_DATA_DIR"; fi
|
||||||
chown -R "$Z2M_USER:$Z2M_GROUP" "$Z2M_DIR"
|
chown -R "$Z2M_USER:$Z2M_GROUP" "$Z2M_DIR"
|
||||||
log "Installed bundled Zigbee2MQTT; previous runtime: $previous"
|
log "Installed bundled Zigbee2MQTT; previous runtime: $previous"
|
||||||
}
|
)
|
||||||
|
|
||||||
install_dependencies() {
|
install_dependencies() {
|
||||||
[[ -d "$Z2M_DIR/node_modules" ]] || die "Run stage 03_code: node_modules must come from our Git"
|
[[ -d "$Z2M_DIR/node_modules" ]] || die "Run stage 03_code: node_modules must come from our Git"
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
# Bundled installation dependencies
|
# Bundled installation dependencies
|
||||||
|
|
||||||
The Edge installer fetches these files only as part of our Git repository. There
|
The Edge installer fetches only needed payloads through our Git API, pinned to
|
||||||
is no APT/NodeSource/GitHub/npm fallback. This directory is ordinary Git content,
|
a commit, and removes temporary downloads after installation. The full bundle
|
||||||
|
stays in Git, not on Edge. There is no APT/NodeSource/GitHub/npm fallback. This directory is ordinary Git content,
|
||||||
not LFS pointers or links to another distribution server.
|
not LFS pointers or links to another distribution server.
|
||||||
|
|
||||||
* `debian/bullseye-arm64`: 581 DEBs, 525 arm64 + 56 all. Source: Debian signed
|
* `debian/bullseye-arm64`: 581 DEBs, 525 arm64 + 56 all. Source: Debian signed
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
Package: nodejs
|
||||||
|
Version: 20.20.2-1nodesource1
|
||||||
|
Architecture: arm64
|
||||||
|
Maintainer: NodeSource Support <support@nodesource.com>
|
||||||
|
Installed-Size: 191716
|
||||||
|
Depends: libc6 (>= 2.28), libgcc1 (>= 1:4.2), libstdc++6 (>= 5.2), python3, ca-certificates
|
||||||
|
Conflicts: nodejs-dev, nodejs-doc, nodejs-legacy, npm
|
||||||
|
Replaces: nodejs-dev (<= 0.8.22), nodejs-legacy, npm (<= 1.2.14)
|
||||||
|
Provides: nodejs-dev, nodejs-doc, nodejs-legacy, npm
|
||||||
|
Section: web
|
||||||
|
Priority: optional
|
||||||
|
Homepage: https://nodejs.org
|
||||||
|
Description: Node.js event-based server-side javascript engine
|
||||||
|
Node.js is similar in design to and influenced by systems like
|
||||||
|
Ruby's Event Machine or Python's Twisted.
|
||||||
|
.
|
||||||
|
It takes the event model a bit further - it presents the event
|
||||||
|
loop as a language construct instead of as a library.
|
||||||
|
.
|
||||||
|
Node.js is bundled with several useful libraries to handle server tasks :
|
||||||
|
System, Events, Standard I/O, Modules, Timers, Child Processes, POSIX,
|
||||||
|
HTTP, Multipart Parsing, TCP, DNS, Assert, Path, URL, Query Strings.
|
||||||
|
Filename: nodejs_20.20.2-1nodesource1_arm64.deb
|
||||||
|
Size: 31269488
|
||||||
|
SHA256: 030f99cbebfbb621fdfbc83df1f870416b00f9c3691ae68b3dbd162055c01cfb
|
||||||
|
|
||||||
Loading…
Reference in New Issue