From 2aa3de574196a750ed90e9dcfd75632e0adc7567 Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sun, 29 Nov 2026 16:34:12 -0800 Subject: [PATCH] Deploy to the handset from the cluster CI builds an arm64 image (compositor, host, chandra-remote, modules) and deploys the updater pod that installs it on the phone. chandra-remote updates go in live (SIGUSR2 restarts it in place); the compositor waits for an idle, locked phone or an approval, and a locked session restarts locked. Host tests: the launcher no longer draws its label in a narrow panel. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/deploy.yaml | 116 +++++++++++++++ compositor/app/app.mbt | 1 + compositor/bin/main.mbt | 1 + compositor/host/lock.mbt | 11 ++ compositor/host/lock_test.mbt | 13 ++ docs/handset.md | 11 ++ handset/Dockerfile | 55 +++++++ handset/Dockerfile.dockerignore | 12 ++ handset/handset.sh | 249 ++++++++++++++++++++++++++++++++ handset/smoke.sh | 32 ++++ handset/test_handset.sh | 133 +++++++++++++++++ host/test/desktop.test.mjs | 3 +- remote/chandra-remote.c | 18 +++ remote/test_remote.py | 22 +++ 14 files changed, 675 insertions(+), 2 deletions(-) create mode 100644 .gitea/workflows/deploy.yaml create mode 100644 handset/Dockerfile create mode 100644 handset/Dockerfile.dockerignore create mode 100755 handset/handset.sh create mode 100755 handset/smoke.sh create mode 100644 handset/test_handset.sh diff --git a/.gitea/workflows/deploy.yaml b/.gitea/workflows/deploy.yaml new file mode 100644 index 0000000..7fb7caf --- /dev/null +++ b/.gitea/workflows/deploy.yaml @@ -0,0 +1,116 @@ +# Build the handset image (arm64) and install it on the phone: charts/chandra-handset in nandi/cluster. +name: Deploy to the handset + +on: + push: + branches: + - main + paths-ignore: ["docs/**", "**.md"] + workflow_dispatch: + +# One at a time, the newest waiting: a deploy is never cut off halfway. +concurrency: + group: deploy-handset + cancel-in-progress: false + +jobs: + build-and-deploy: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Load secrets from the cluster + env: + KUBECONFIG_B64: ${{ secrets.KUBECONFIG_B64 }} + run: | + set -euo pipefail + BIN="$RUNNER_TEMP/bin"; mkdir -p "$BIN" + PKG=https://git.site.latha.org/api/packages/nandi/generic + fetch() { curl -fsSL --retry 5 --retry-all-errors -o "$2" "$1"; } + fetch "$PKG/kubectl/v1.37.2/kubectl-linux-amd64" "$BIN/kubectl" + echo "c04487523e7aa7d1493f7808174c899db93d7a9cf57531420cd76b9bd415f8f4 $BIN/kubectl" | sha256sum -c - + chmod +x "$BIN/kubectl" + fetch "$PKG/helm/3.16.3/helm-linux-amd64.tar.gz" "$RUNNER_TEMP/helm.tgz" + echo "f5355c79190951eed23c5432a3b920e071f4c00a64f75e077de0dd4cb7b294ea $RUNNER_TEMP/helm.tgz" | sha256sum -c - + tar xzf "$RUNNER_TEMP/helm.tgz" -C "$RUNNER_TEMP" --strip-components=1 linux-amd64/helm + mv "$RUNNER_TEMP/helm" "$BIN/helm" + echo "$BIN" >> "$GITHUB_PATH" + echo "$KUBECONFIG_B64" | base64 -d > "$RUNNER_TEMP/kubeconfig" + chmod 600 "$RUNNER_TEMP/kubeconfig" + echo "KUBECONFIG=$RUNNER_TEMP/kubeconfig" >> "$GITHUB_ENV" + export KUBECONFIG="$RUNNER_TEMP/kubeconfig" + # Build secrets live in the k8s Secret chandra-handset/chandra-handset-ci (see `latha secret set`). + for k in DEPOT_TOKEN DEPOT_PROJECT_ID REGISTRY_TOKEN; do + v="$("$BIN/kubectl" -n chandra-handset get secret chandra-handset-ci -o go-template="{{index .data \"$k\" | base64decode}}")" + [ -n "$v" ] || { echo "missing $k in secret chandra-handset/chandra-handset-ci"; exit 1; } + echo "::add-mask::$v" + printf '%s=%s\n' "$k" "$v" >> "$GITHUB_ENV" + done + + - name: Install Depot CLI + run: | + curl -fsSL https://depot.dev/install-cli.sh | sh + echo "$HOME/.depot/bin" >> "$GITHUB_PATH" + + - name: Configure Registry Auth + env: + REG_USER: nandi + run: | + mkdir -p "$HOME/.docker" + AUTH=$(printf '%s:%s' "$REG_USER" "$REGISTRY_TOKEN" | base64 -w 0) + cat > "$HOME/.docker/config.json" < "$RUNNER_TEMP/askpass" + chmod 700 "$RUNNER_TEMP/askpass" + export GIT_ASKPASS="$RUNNER_TEMP/askpass" GIT_TERMINAL_PROMPT=0 + git clone --depth 1 https://nandi@git.site.latha.org/nandi/cluster.git "$RUNNER_TEMP/cluster" + cd "$RUNNER_TEMP/cluster" + + V=clusters/k3s-kplae-u30796/chandra-handset/values.yaml + sed -i "s/^\( *tag: \).*/\1\"${SHORT_SHA}\"/" $V + test "$(git diff --numstat | wc -l)" -le 1 + + # --atomic rolls back on failure, so the repo is only bumped for a deploy that worked. The phone has to be + # online. A compositor update then waits on the phone until it is idle or approved (handset/handset.sh). + helm upgrade --install chandra-handset charts/chandra-handset -n chandra-handset -f $V --atomic --wait --timeout 10m + kubectl -n chandra-handset get pods -o wide + + if ! git diff --quiet; then + # nandi/cluster main is protected: push a branch, open a PR, and let Gitea merge it once its checks pass. + BRANCH="deploy/chandra-handset-${SHORT_SHA}" + TITLE="chore(chandra-handset): deploy ${SHORT_SHA}" + git -c user.name=ci -c user.email=ci@site.latha.org commit -am "$TITLE" + git push --force origin "HEAD:refs/heads/$BRANCH" + API=https://git.site.latha.org/api/v1/repos/nandi/cluster + printf 'Authorization: token %s\n' "$CLUSTER_REPO_TOKEN" > "$RUNNER_TEMP/auth-header" + api() { curl -fsS --retry 3 -H @"$RUNNER_TEMP/auth-header" -H 'Content-Type: application/json' "$@"; } + PR=$(api -X POST "$API/pulls" -d "{\"head\":\"$BRANCH\",\"base\":\"main\",\"title\":\"$TITLE\",\"body\":\"Image bump from $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID (already deployed).\"}" \ + | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>console.log(JSON.parse(d).number))') + api -X POST "$API/pulls/$PR/merge" -d '{"Do":"merge","merge_when_checks_succeed":true,"delete_branch_after_merge":true}' + echo "Opened nandi/cluster PR #$PR (merges when its checks pass)" + fi diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index b5ae6f2..bd5c8fb 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -286,6 +286,7 @@ pub fn run(args : Array[String]) -> Int { @sys.log("--desktop " + desktop + ": no such desktop module") } if login { + comp.lock_if_marked(@host.lock_marker) // an update restarted a locked session comp.start_auth_agent() // polkit's password prompts (run0, pkexec): Chandra's dialog } if restore { diff --git a/compositor/bin/main.mbt b/compositor/bin/main.mbt index 9edd0bd..3d45b97 100644 --- a/compositor/bin/main.mbt +++ b/compositor/bin/main.mbt @@ -197,6 +197,7 @@ fn main { } if drm { comp.login_session = true + comp.lock_if_marked(@host.lock_marker) // an update restarted a locked session comp.start_auth_agent() // polkit's password prompts (run0, pkexec): Chandra's dialog } if restore { diff --git a/compositor/host/lock.mbt b/compositor/host/lock.mbt index cbf768b..9db8c4f 100644 --- a/compositor/host/lock.mbt +++ b/compositor/host/lock.mbt @@ -13,6 +13,17 @@ /// │ success: "unlocked" ───┘──► unlocked /// └── power off / chandra-ctl lock cancel: "unlock-failed" ──► stay locked +///| While this file exists a login session starts locked. Whoever restarts a locked session (the +/// handset updater, handset/handset.sh) puts it there as root, so the restart doesn't unlock it. +pub let lock_marker : String = "/run/chandra-start-locked" + +///| Lock the session if the file `path` is there (and not empty). +pub fn ChandraCompositor::lock_if_marked(self : ChandraCompositor, path : String) -> Unit { + if @sys.read_file_bytes(path).length() > 0 { + self.lock_now() + } +} + ///| Whether the session is locked right now. pub fn ChandraCompositor::is_locked(self : ChandraCompositor) -> Bool { self.locked diff --git a/compositor/host/lock_test.mbt b/compositor/host/lock_test.mbt index e7208ad..9091d2b 100644 --- a/compositor/host/lock_test.mbt +++ b/compositor/host/lock_test.mbt @@ -325,3 +325,16 @@ test "lock: agent drop clears unlock_pending and restarted agent resumes unlock @sys.unlink(hpath) r.comp.close() } + +///| +test "lock: a marked session starts locked" { + let comp = new_comp("lock-marker") + let path = "/tmp/chandra-lock-marker-" + @sys.getpid().to_string() + comp.lock_if_marked(path) + assert_false(comp.is_locked()) + ignore(@sys.write_file_bytes(path, b"1\n")) + comp.lock_if_marked(path) + assert_true(comp.is_locked()) + @sys.unlink(path) + comp.close() +} diff --git a/docs/handset.md b/docs/handset.md index 4c7cc12..0418d72 100644 --- a/docs/handset.md +++ b/docs/handset.md @@ -70,3 +70,14 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux - **Paste (web UI):** `Ctrl+V`, `Ctrl+Shift+V`, `Shift+Insert` (`Cmd+V` on a Mac) put this device's clipboard, text or an image (up to 16 MB, sent as PNG), on the phone's and then press the same keys there. This works over plain HTTP. If something was copied on the phone since the page was last focused, that is pasted instead. The **Paste** button (`KB` bar) and **Paste Image…** (menu) do the same, with `Ctrl+Shift+V` for text in terminals. In the launcher and the password dialog the text is typed in. The browser uploads to `POST /api/clipboard`; the compositor gets the data as a memfd over the control socket (`clipboard-set-fd`, `input-paste`). VNC clients can send text only. - `https://chandra-6t.tail.site.latha.org/` serves the web UI over HTTPS, tailnet only, from the `chandra-remote` chart in `nandi/cluster` (Caddy on the phone node, proxying to loopback `6080`). - By default (`~/.config/chandra/remote.conf`), `bind=tailscale`, `bind_loopback=1`, and `auth=none`, binding strictly to the Tailscale `100.64.0.0/10` interface + `127.0.0.1` so any device on the same Tailscale tailnet can connect directly with zero password prompt (`http://:6080/` or `:5900`), even while the handset's physical OLED screen is turned off (`chandra-ctl screen off`). Run `chandra-remote status` to inspect endpoints or `chandra-remote passwd [PASS|--none]` to configure optional password auth. + +## Deploying to the phone + +Every push to `main` builds an arm64 image ([`handset/Dockerfile`](../handset/Dockerfile)) and deploys it with the `chandra-handset` chart in `nandi/cluster`; the phone is a k3s node, so no SSH or root password is involved. The updater ([`handset/handset.sh`](../handset/handset.sh)) installs `chandra-remote` and its page at once, without ending the session. The compositor, its host and the panel modules need a session restart, so they wait until the phone has been locked with its screen off for 10 minutes, or until approved: + +```sh +kubectl -n chandra-handset exec deploy/chandra-handset -- handset status +kubectl -n chandra-handset exec deploy/chandra-handset -- handset approve # closes the phone's apps +``` + +A locked session restarts locked (`/run/chandra-start-locked`), and a session that doesn't come up is rolled back. The image build runs a smoke test (compositor, image paste) and the updater's tests (`handset/test_handset.sh`). diff --git a/handset/Dockerfile b/handset/Dockerfile new file mode 100644 index 0000000..47e2979 --- /dev/null +++ b/handset/Dockerfile @@ -0,0 +1,55 @@ +# Everything the handset runs, built for the phone (linux/arm64), plus the updater that installs it +# (handset.sh). Built by .gitea/workflows/deploy.yaml; build context: the repository. +FROM debian:trixie-slim AS build +RUN apt-get update -q && apt-get install -y -q --no-install-recommends \ + bash ca-certificates curl gcc git libc6-dev make pkg-config xz-utils \ + libdrm-dev libinput-dev libseat-dev libudev-dev libxkbcommon-dev \ + libssl-dev libturbojpeg0-dev libzstd-dev zlib1g-dev +# The compiler the repository is developed with. +ARG MOON_VERSION=0.10.20+65efd5b93 +RUN curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash -s -- "$MOON_VERSION" +ENV PATH=/root/.moon/bin:/src/.tools/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +WORKDIR /src +COPY scripts/versions.env scripts/setup-toolchain.sh scripts/ +RUN bash scripts/setup-toolchain.sh +COPY . . +RUN moon update && bash scripts/build-compositor-wasm.sh && bash scripts/build-modules.sh && bash scripts/build-wasmhost.sh +RUN moon build --target native --release --warn-list -a compositor/authagent +# Static but for glibc: the phone is a rolling distribution whose libcrypto moves on. +RUN gcc -O2 -Wall -Wextra -o build/chandra-remote remote/*.c \ + -l:libturbojpeg.a -l:libcrypto.a -l:libzstd.a -l:libz.a -lm -ldl -lpthread +RUN set -eu; live=/payload/live/usr/local session=/payload/session/usr/local; \ + install -D -m755 build/chandra-remote $live/bin/chandra-remote; \ + for f in index.html manifest.json icon.svg; do install -D -m644 remote/web/$f $live/share/chandra/remote/$f; done; \ + install -D -m755 build/wasmhost $session/bin/chandra-host; \ + for f in chandra-session chandra-ctl chandra-root; do install -D -m755 session/$f $session/bin/$f; done; \ + install -D -m755 _build/native/release/build/compositor/authagent/authagent.exe $session/lib/chandra/chandra-polkit-agent; \ + install -D -m644 build/compositor.wasm $session/share/chandra/compositor.wasm; \ + for f in build/components/*.wasm; do install -D -m644 $f $session/share/chandra/modules/${f##*/}; done; \ + cp -r config wit $session/share/chandra/; \ + find /payload -type f | sort + +# The gate: the built compositor must start on the built host, take a 1 MB image through +# chandra-remote, and answer for it. +FROM debian:trixie-slim AS smoke +RUN apt-get update -q && apt-get install -y -q --no-install-recommends \ + curl python3-minimal libpython3-stdlib libdrm2 libinput10 libseat1 libudev1 libxkbcommon0 xkb-data +COPY --from=build /payload /payload +COPY assets /payload/session/usr/local/share/chandra/assets +COPY handset/smoke.sh /smoke.sh +RUN bash /smoke.sh && touch /smoke-ok + +FROM alpine:3.22 AS updater-test +COPY handset /t +RUN sh /t/test_handset.sh && touch /updater-ok + +FROM alpine:3.22 +# nsenter, to act on the phone +RUN apk add --no-cache util-linux-misc +COPY --from=smoke /smoke-ok /smoke-ok +COPY --from=updater-test /updater-ok /updater-ok +COPY --from=build /payload /payload +COPY handset/handset.sh /usr/local/bin/handset +ARG RELEASE=dev +RUN chmod 755 /usr/local/bin/handset && echo "$RELEASE" > /payload/RELEASE +CMD ["handset", "run"] diff --git a/handset/Dockerfile.dockerignore b/handset/Dockerfile.dockerignore new file mode 100644 index 0000000..a22a044 --- /dev/null +++ b/handset/Dockerfile.dockerignore @@ -0,0 +1,12 @@ +.git +.delta +.context +.pixi +.tools +.mooncakes +_build +build +**/node_modules +**/__pycache__ +docs +*.log diff --git a/handset/handset.sh b/handset/handset.sh new file mode 100755 index 0000000..1fe48c8 --- /dev/null +++ b/handset/handset.sh @@ -0,0 +1,249 @@ +#!/bin/sh +# Chandra's updater on the handset. It runs in a privileged pod on the phone (charts/chandra-handset +# in nandi/cluster), one image per commit, with the phone's /usr/local at $HOST/usr/local. +# +# handset run install what can go in live, then wait to install the rest (the pod's command) +# handset status what is installed and what is waiting +# handset approve install the waiting compositor now: RESTARTS THE SESSION, closing its apps +# handset ready exit 0 when the live part is dealt with (the pod's readiness probe) +# +# payload/live chandra-remote and its web page: installed at once; chandra-remote restarts in +# place (SIGUSR2) and browsers reconnect. +# payload/session the compositor, its host, the panel modules...: installed only when approved, or +# when the phone has been locked with its screen off for $IDLE_MIN minutes. The +# session is restarted (locked again if it was), and everything is put back if it +# doesn't answer. A release that failed is not tried again unless approved. +set -u +HOST=${HOST:-/host} +PAYLOAD=${PAYLOAD:-/payload} +STATE=${STATE:-$HOST/var/lib/chandra-handset} +RUN=${RUN:-/tmp/handset} +RELEASE=${RELEASE:-$(cat "$PAYLOAD/RELEASE")} +IDLE_MIN=${IDLE_MIN:-10} +POLL=${POLL:-30} +SESSION_USER=${SESSION_USER:-nandi} +SESSION_UID=${SESSION_UID:-1000} +MARKER=/run/chandra-start-locked # compositor/host/lock.mbt + +log() { echo "$(date -u +%FT%TZ) $*"; } +# Run a command as the phone itself, not in the container. +onhost() { if [ -n "${FAKE_HOST:-}" ]; then "$FAKE_HOST" "$@"; else nsenter -t 1 -m -u -i -n -p -- "$@"; fi; } +ctl() { + onhost runuser -u "$SESSION_USER" -- env "XDG_RUNTIME_DIR=/run/user/$SESSION_UID" \ + timeout 5 /usr/local/bin/chandra-ctl --socket "/run/user/$SESSION_UID/chandra/wayland-moon-0.sock" "$@" 2>/dev/null +} + +# Files of a group ("live" or "session") that differ from what is installed, relative to /. +differing() { + (cd "$PAYLOAD/$1" && find . -type f | sed 's|^\./||' | sort) | while IFS= read -r f; do + cmp -s "$PAYLOAD/$1/$f" "$HOST/$f" || echo "$f" + done +} + +# Install FILES (a list, one per line) of GROUP, keeping what was there in $STATE/prev-GROUP. +install_files() { + group=$1 files=$2 prev="$STATE/prev-$1" + rm -rf "${STATE:?}/prev-${group:?}.new" && mkdir -p "$prev.new" || return 1 + printf '%s\n' "$files" > "$prev.new/FILES" + printf '%s\n' "$files" | while IFS= read -r f; do + if [ -e "$HOST/$f" ]; then + mkdir -p "$prev.new/$(dirname "$f")" && cp -p "$HOST/$f" "$prev.new/$f" || exit 1 + fi + done || return 1 + rm -rf "${STATE:?}/prev-${group:?}" && mv "$prev.new" "$prev" || return 1 + printf '%s\n' "$files" | while IFS= read -r f; do + mode=644 + case "$f" in */bin/*|*/lib/*) mode=755 ;; esac + mkdir -p "$HOST/$(dirname "$f")" && + cp "$PAYLOAD/$group/$f" "$HOST/$f.handset-new" && chown 0:0 "$HOST/$f.handset-new" && + chmod "$mode" "$HOST/$f.handset-new" && mv -f "$HOST/$f.handset-new" "$HOST/$f" || exit 1 + done +} + +# Put back what the last install_files GROUP replaced, and take out what it added. +restore_files() { + prev="$STATE/prev-$1" + while IFS= read -r f; do + [ -n "$f" ] || continue + if [ -e "$prev/$f" ]; then + cp -p "$prev/$f" "$HOST/$f.handset-new" && mv -f "$HOST/$f.handset-new" "$HOST/$f" + else + rm -f "${HOST:?}/${f:?}" + fi + done < "$prev/FILES" +} + +# Whether a program of the payload starts on this phone (its libraries are there). +starts() { + check="usr/local/lib/.handset-check" + mkdir -p "$HOST/usr/local/lib" && cp "$PAYLOAD/$1" "$HOST/$check" && chmod 755 "$HOST/$check" || return 1 + onhost ldd "/$check" > "$RUN/ldd" 2>&1; rc=$? + rm -f "${HOST:?}/usr/local/lib/.handset-check" + if [ $rc -ne 0 ] || grep -q 'not found' "$RUN/ldd"; then + log "ERROR: $1 doesn't start here:"; cat "$RUN/ldd" + return 1 + fi +} + +remote_pid() { onhost pgrep -x -u "$SESSION_USER" chandra-remote | head -n 1; } +remote_answers() { onhost curl -fsS -m 3 -o /dev/null http://127.0.0.1:6080/api/info 2>/dev/null; } + +# Whether a process catches SIGUSR2 (12). A chandra-remote from before it could restart in place +# would be killed by it. +catches_usr2() { + cgt=$(onhost sed -n 's/^SigCgt:[[:space:]]*//p' "/proc/$1/status") + [ -n "$cgt" ] && [ $((0x$(printf %s "$cgt" | tail -c 4) & 0x800)) -ne 0 ] +} + +# 0: installed. 1: failed. 2: must wait for the session restart. +apply_live() { + files=$(differing live) + [ -n "$files" ] || return 0 + pid=$(remote_pid) + if [ -n "$pid" ] && ! catches_usr2 "$pid"; then + log "live part waits for the session restart: the running chandra-remote can't restart in place" + return 2 + fi + starts live/usr/local/bin/chandra-remote || return 1 + log "installing live: $(echo $files)" + install_files live "$files" || { restore_files live; return 1; } + if [ -n "$pid" ]; then + case "$files" in + *bin/chandra-remote*) + onhost kill -USR2 "$pid" + sleep 1 + i=0 + while ! remote_answers; do + i=$((i + 1)) + if [ $i -gt 15 ]; then + log "ERROR: chandra-remote doesn't answer: putting the old one back" + restore_files live + pid=$(remote_pid); [ -n "$pid" ] && onhost kill -USR2 "$pid" + return 1 + fi + sleep 1 + done ;; + esac + fi + log "live part installed" +} + +session_up() { + i=0 + while [ $i -lt 20 ]; do + sleep "${UP_POLL:-2}" + onhost pgrep -x chandra-host > /dev/null && [ "$(ctl ping)" = "ok pong" ] && return 0 + i=$((i + 1)) + done + return 1 +} + +# Restart the login session; $1 = 1: it was locked, so it must come back locked, screen off. +restart_session() { + if [ "$1" = 1 ]; then onhost sh -c "echo 1 > $MARKER" || return 1; fi + onhost systemctl restart greetd + session_up || return 1 + if [ "$1" = 1 ]; then + # A compositor that doesn't know the marker is locked by hand. + [ "$(ctl lock status)" = "ok locked" ] || ctl lock > /dev/null + ctl screen off > /dev/null + # The marker stays until the session is known to be locked. + [ "$(ctl lock status)" = "ok locked" ] && onhost rm -f /run/chandra-start-locked + fi + return 0 +} + +apply_session() { + s_files=$(differing session) + l_files=$(differing live) + [ -n "$s_files$l_files" ] || return 0 + # Anything but a clear "unlocked" counts as locked. + locked=1 + [ "$(ctl lock status)" = "ok unlocked" ] && locked=0 + for p in session/usr/local/bin/chandra-host session/usr/local/lib/chandra/chandra-polkit-agent live/usr/local/bin/chandra-remote; do + starts "$p" || { echo "$RELEASE" > "$STATE/failed"; return 1; } + done + log "installing session: $(echo $s_files $l_files)" + ok=1 + if [ -n "$s_files" ]; then install_files session "$s_files" || ok=0; fi + if [ -n "$l_files" ] && [ $ok = 1 ]; then install_files live "$l_files" || ok=0; did_live=1; else did_live=0; fi + if [ $ok = 1 ] && restart_session $locked; then + rm -f "${STATE:?}/failed" + log "session restarted on $RELEASE (lock: $(ctl lock status))" + return 0 + fi + log "ERROR: the new session didn't come up: putting the old one back" + echo "$RELEASE" > "$STATE/failed" + [ -n "$s_files" ] && restore_files session + [ $did_live = 1 ] && restore_files live + restart_session $locked || log "ERROR: the old session doesn't answer either" + return 1 +} + +idle_now() { + [ "$(ctl lock status)" = "ok locked" ] || return 1 + case "$(ctl status)" in *" screen=off "*) return 0 ;; esac + return 1 +} + +status() { + echo "release $RELEASE" + live=$(differing live); session=$(differing session) + if [ -z "$live" ]; then echo "live: installed"; else echo "live: waiting:"; echo "$live" | sed 's/^/ /'; fi + if [ -z "$session" ]; then echo "session: installed"; else echo "session: waiting (handset approve):"; echo "$session" | sed 's/^/ /'; fi + if [ "$(cat "$STATE/failed" 2>/dev/null)" = "$RELEASE" ]; then + echo "session: this release FAILED; only 'handset approve' tries it again" + fi + echo "phone: $(ctl lock status) | $(ctl status)" +} + +mkdir -p "$RUN" +case "${1:-}" in + run) + mkdir -p "$STATE" && chmod 700 "$STATE" || exit 1 + rm -f "${RUN:?}/live-ready" "${RUN:?}/approve" + log "release $RELEASE" + apply_live + case $? in + 0) echo installed > "$RUN/live-ready" ;; + 2) echo waiting > "$RUN/live-ready" ;; + *) log "ERROR: live part not installed"; exit 1 ;; + esac + status + idle=0 rounds=0 + while :; do + if [ -n "$(differing session)$(differing live)" ]; then + if [ -e "$RUN/approve" ]; then + rm -f "${RUN:?}/approve" + log "approved" + apply_session; echo $? > "$RUN/approve-result" + elif [ "$(cat "$STATE/failed" 2>/dev/null)" != "$RELEASE" ] && idle_now; then + idle=$((idle + POLL)) + if [ $idle -ge $((IDLE_MIN * 60)) ]; then + log "locked and dark for $IDLE_MIN minutes" + apply_session + idle=0 + fi + else + idle=0 + fi + elif [ -e "$RUN/approve" ]; then + rm -f "${RUN:?}/approve"; echo 0 > "$RUN/approve-result" + fi + rounds=$((rounds + 1)) + if [ -n "${ROUNDS:-}" ] && [ $rounds -ge "$ROUNDS" ]; then exit 0; fi + # Wake at once for an approval. + i=0 + while [ $i -lt "$POLL" ] && [ ! -e "$RUN/approve" ]; do sleep 1; i=$((i + 1)); done + done ;; + approve) + rm -f "${RUN:?}/approve-result"; touch "$RUN/approve" + echo "installing $RELEASE and restarting the session..." + i=0 + while [ ! -e "$RUN/approve-result" ] && [ $i -lt 180 ]; do sleep 1; i=$((i + 1)); done + status + exit "$(cat "$RUN/approve-result" 2>/dev/null || echo 1)" ;; + ready) [ -e "$RUN/live-ready" ] ;; + status) status ;; + *) sed -n '2,19p' "$0"; exit 2 ;; +esac diff --git a/handset/smoke.sh b/handset/smoke.sh new file mode 100755 index 0000000..62d2693 --- /dev/null +++ b/handset/smoke.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Start the payload's compositor headless and put an image on its clipboard through chandra-remote. +set -euo pipefail +p=/payload +R=$(mktemp -d /tmp/smXXXX) +mkdir "$R/cfg" +export XDG_RUNTIME_DIR=$R XDG_CONFIG_HOME=$R/cfg HOME=$R CHANDRA_TEST_CONFIG=1 +touch "$R/log" "$R/rem" +trap 'rc=$?; [ $rc = 0 ] || cat "$R/log" "$R/rem"; exit $rc' EXIT +cd $p/session/usr/local/share/chandra +timeout 120 $p/session/usr/local/bin/chandra-host compositor.wasm --socket "$R/wt" \ + --theme config/themes/moon-night.json > "$R/log" 2>&1 & +for _ in $(seq 200); do [ -S "$R/chandra/wt.sock" ] && break; sleep .2; done +ctl() { python3 $p/session/usr/local/bin/chandra-ctl --socket "$R/chandra/wt.sock" "$@"; } +ctl ping | grep -qx 'ok pong' +ctl list | tail -n 1 +printf 'enabled=1\nbind=127.0.0.1\nauth=none\n' > "$R/r.conf" +$p/live/usr/local/bin/chandra-remote --config "$R/r.conf" --socket "$R/chandra/wt.sock" \ + --shm "$R/fb" --web-dir $p/live/usr/local/share/chandra/remote --bind 127.0.0.1 > "$R/rem" 2>&1 & +remote=$! +for _ in $(seq 50); do curl -fsS -m 2 -o /dev/null http://127.0.0.1:6080/ 2>/dev/null && break; sleep .2; done +python3 -c "import os,sys;sys.stdout.buffer.write(b'\x89PNG\r\n\x1a\n'+os.urandom(1<<20))" > "$R/p.png" +out=$(curl -fsS -m 30 -H Expect: -H 'X-Chandra-Remote: 1' -H 'Content-Type: image/png' \ + --data-binary "@$R/p.png" http://127.0.0.1:6080/api/clipboard) +echo "$out" +[ "$out" = '{"ok":true,"serial":1}' ] +# It restarts in place, and answers again. +kill -USR2 $remote +sleep 2 +curl -fsS -m 5 http://127.0.0.1:6080/api/clipboard +echo +echo "smoke ok" diff --git a/handset/test_handset.sh b/handset/test_handset.sh new file mode 100644 index 0000000..3b4f0e0 --- /dev/null +++ b/handset/test_handset.sh @@ -0,0 +1,133 @@ +#!/bin/sh +# Tests of handset.sh against a fake phone: a directory tree and a script standing in for the phone's +# commands. Run in the image's own shell: +# docker run --rm -v "$PWD/handset:/t:ro" alpine:3.22 sh /t/test_handset.sh +set -u +here=$(cd "$(dirname "$0")" && pwd) +T=$(mktemp -d) +export T HOST="$T/host" PAYLOAD="$T/payload" RUN="$T/run" RELEASE=r2 POLL=1 IDLE_MIN=0 UP_POLL=0 +export FAKE_HOST="$T/fake" +fails=0 +check() { if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: expected '$3', got '$2'"; fails=$((fails + 1)); fi; } +has() { if grep -q -- "$2" "$T/calls"; then r=yes; else r=no; fi; check "$1" "$r" "$3"; } + +cat > "$FAKE_HOST" <<'F' +#!/bin/sh +# The phone: state in $T/{lock,screen,usr2,alive,bad}; every call in $T/calls. +echo "$*" >> "$T/calls" +case "$*" in + *"chandra-ctl"*" ping") [ "$(cat "$T/alive")" = 1 ] && echo "ok pong" ;; + *"chandra-ctl"*" lock status") [ "$(cat "$T/alive")" = 1 ] && echo "ok $(cat "$T/lock")" ;; + *"chandra-ctl"*" lock") echo locked > "$T/lock"; echo "ok locked" ;; + *"chandra-ctl"*" screen off") echo off > "$T/screen" ;; + *"chandra-ctl"*" status") echo "ok 540x1170 rot=0 screen=$(cat "$T/screen") brightness=35" ;; + "pgrep -x chandra-host") [ "$(cat "$T/alive")" = 1 ] ;; + "pgrep "*chandra-remote) echo 42 ;; + "sed "*SigCgt*) if [ "$(cat "$T/usr2")" = 1 ]; then echo 0000000100004803; else echo 0000000100004003; fi ;; + "kill -USR2 42") ;; + "curl "*) [ "$(cat "$HOST/usr/local/bin/chandra-remote")" != broken ] ;; + "ldd "*) [ ! -e "$T/missing" ] || { echo "libfoo.so => not found"; exit 0; } ;; + "sh -c echo 1 > /run/chandra-start-locked") touch "$T/marker" ;; + "rm -f /run/chandra-start-locked") rm -f "${T:?}/marker" ;; + "systemctl restart greetd") + echo on > "$T/screen"; echo unlocked > "$T/lock"; echo 1 > "$T/alive" + c=$(cat "$HOST/usr/local/share/chandra/compositor.wasm") + # A compositor that knows the marker starts locked; a bad one doesn't start. + case "$c" in bad) echo 0 > "$T/alive" ;; new) [ -e "$T/marker" ] && echo locked > "$T/lock" ;; esac + [ ! -e "$T/marker" ] || echo "restarted with marker" >> "$T/calls" ;; + *) echo "fake: unexpected: $*" >> "$T/calls" ;; +esac +F +chmod +x "$FAKE_HOST" + +put() { mkdir -p "$(dirname "$2")"; echo "$1" > "$2"; } +# fresh LIVE SESSION: the phone has "old" everything; the payload has LIVE and SESSION. +fresh() { + for d in host payload run; do rm -rf "${T:?}/$d"; done + rm -f "${T:?}/missing" "${T:?}/marker" + put old "$HOST/usr/local/bin/chandra-remote" + put old "$HOST/usr/local/share/chandra/remote/index.html" + put old "$HOST/usr/local/share/chandra/compositor.wasm" + put old "$HOST/usr/local/bin/chandra-host" + put old "$HOST/usr/local/lib/chandra/chandra-polkit-agent" + put "$1" "$PAYLOAD/live/usr/local/bin/chandra-remote" + put "$1" "$PAYLOAD/live/usr/local/share/chandra/remote/index.html" + put "$2" "$PAYLOAD/session/usr/local/share/chandra/compositor.wasm" + put old "$PAYLOAD/session/usr/local/bin/chandra-host" + put old "$PAYLOAD/session/usr/local/lib/chandra/chandra-polkit-agent" + put added "$PAYLOAD/session/usr/local/share/chandra/modules/new one.wasm" + echo unlocked > "$T/lock"; echo on > "$T/screen"; echo 1 > "$T/usr2"; echo 1 > "$T/alive" + : > "$T/calls" +} +run() { ROUNDS=$1 sh "$here/handset.sh" run > "$T/out" 2>&1; echo $?; } +remote() { cat "$HOST/usr/local/bin/chandra-remote"; } +comp() { cat "$HOST/usr/local/share/chandra/compositor.wasm"; } +module() { [ -e "$HOST/usr/local/share/chandra/modules/new one.wasm" ] && echo yes || echo no; } + +fresh new new +check "in use: exits cleanly" "$(run 2)" 0 +check "in use: live installed" "$(remote)" new +check "in use: compositor waits" "$(comp)" old +has "in use: remote restarted in place" "kill -USR2 42" yes +has "in use: session left alone" "restart greetd" no +check "remote keeps its mode" "$(stat -c %a "$HOST/usr/local/bin/chandra-remote")" 755 +check "ready" "$(sh "$here/handset.sh" ready; echo $?)" 0 + +fresh new new; echo 0 > "$T/usr2" +run 2 > /dev/null +check "old remote: live waits" "$(remote)" old +has "old remote: not signalled" "kill" no + +fresh new new; echo locked > "$T/lock" +run 2 > /dev/null +check "locked, screen on: waits" "$(comp)" old +fresh new new; echo off > "$T/screen" +run 2 > /dev/null +check "unlocked, screen off: waits" "$(comp)" old + +fresh new new; echo locked > "$T/lock"; echo off > "$T/screen" +IDLE_MIN=1 run 2 > /dev/null +check "locked and dark, not long enough: waits" "$(comp)" old + +fresh new new; echo locked > "$T/lock"; echo off > "$T/screen" +run 1 > /dev/null +check "idle: compositor installed" "$(comp)" new +check "idle: new file installed" "$(module)" yes +has "idle: marker was there for the restart" "restarted with marker" yes +check "idle: locked again" "$(cat "$T/lock")" locked +check "idle: screen off again" "$(cat "$T/screen")" off +check "idle: marker removed" "$([ -e "$T/marker" ] && echo yes || echo no)" no + +fresh new knows-no-marker; echo locked > "$T/lock"; echo off > "$T/screen" +run 1 > /dev/null +check "a compositor without the marker is locked by hand" "$(cat "$T/lock")" locked + +fresh new bad; echo locked > "$T/lock"; echo off > "$T/screen" +check "bad compositor: updater lives on" "$(run 3)" 0 +check "bad compositor: rolled back" "$(comp)" old +check "bad compositor: added file taken out" "$(module)" no +check "bad compositor: locked after rollback" "$(cat "$T/lock")" locked +check "bad compositor: tried once" "$(grep -c 'restart greetd' "$T/calls")" 2 +check "bad compositor: marked failed" "$(cat "$HOST/var/lib/chandra-handset/failed")" r2 + +fresh new new +(sleep 2; sh "$here/handset.sh" approve > "$T/approve" 2>&1; echo $? > "$T/approve-rc") & +run 6 > /dev/null; wait +check "approve: exit code" "$(cat "$T/approve-rc")" 0 +check "approve: installed while in use" "$(comp)" new +check "approve: an unlocked session isn't locked" "$(cat "$T/lock")" unlocked +has "approve: no marker" "chandra-start-locked" no + +fresh broken new +check "broken remote: fails" "$(run 1)" 1 +check "broken remote: rolled back" "$(remote)" old +check "broken remote: page too" "$(cat "$HOST/usr/local/share/chandra/remote/index.html")" old +check "broken remote: not ready" "$(sh "$here/handset.sh" ready; echo $?)" 1 + +fresh new new; touch "$T/missing" +check "missing library: fails" "$(run 1)" 1 +check "missing library: nothing installed" "$(remote)" old + +has "only known commands were run" "fake: unexpected" no +rm -rf "${T:?}" +[ $fails = 0 ] && echo "all passed" || { echo "$fails failed"; exit 1; } diff --git a/host/test/desktop.test.mjs b/host/test/desktop.test.mjs index 963b847..1523b50 100644 --- a/host/test/desktop.test.mjs +++ b/host/test/desktop.test.mjs @@ -30,7 +30,6 @@ test('boots shell + widgets and composes a frame', async () => { assert.ok(t.includes('2:07 PM'), `clock text missing (Digital Clock starts in 12-hour mode): ${t}`); assert.ok(t.includes('Tue 24 Nov')); assert.ok(t.includes('chandra')); - assert.ok(t.includes('Applications')); assert.equal(desktop.faults.length, 0); }); @@ -150,7 +149,7 @@ test('component faults are surfaced loudly and isolated to the widget', async () assert.equal(desktop.faults.length, 1); assert.match(desktop.faults[0].message, /clock-digital.*render/); assert.ok(texts(f.ops).includes('clock-digital crashed'), 'visible error tile'); - assert.ok(texts(f.ops).includes('Applications'), 'other widgets still render'); + assert.ok(texts(f.ops).includes('chandra'), 'other widgets still render'); }); test('build manifests match scripts/components.txt', async () => { diff --git a/remote/chandra-remote.c b/remote/chandra-remote.c index 3c912f4..ecbb094 100644 --- a/remote/chandra-remote.c +++ b/remote/chandra-remote.c @@ -21,12 +21,19 @@ static volatile sig_atomic_t g_running = 1; static volatile sig_atomic_t g_reload = 0; +static volatile sig_atomic_t g_reexec = 0; static void on_term(int sig) { (void)sig; g_running = 0; } +static void on_usr2(int sig) { + (void)sig; + g_reexec = 1; + g_running = 0; +} + static void on_hup(int sig) { (void)sig; g_reload = 1; @@ -740,6 +747,11 @@ int main(int argc, char **argv) { signal(SIGINT, on_term); signal(SIGTERM, on_term); signal(SIGHUP, on_hup); + /* SIGUSR2: restart in place from the installed binary (an update), same pid and arguments. */ + char self_path[512]; + ssize_t self_len = readlink("/proc/self/exe", self_path, sizeof self_path - 1); + self_path[self_len > 0 ? self_len : 0] = 0; + if (self_path[0]) signal(SIGUSR2, on_usr2); /* Record PID for `chandra-remote status` / `passwd`. */ { @@ -870,6 +882,12 @@ int main(int argc, char **argv) { } pthread_mutex_unlock(&app.osk_mu); ctl_close(&app.ctl); + if (g_reexec) { + fprintf(stderr, "chandra-remote: restarting for an update\n"); + close_range(3, ~0U, CLOSE_RANGE_CLOEXEC); /* clients' sockets too: they reconnect */ + execv(self_path, argv); + fprintf(stderr, "chandra-remote: exec %s: %s\n", self_path, strerror(errno)); + } unlink(pid_path); return 0; } diff --git a/remote/test_remote.py b/remote/test_remote.py index 0f3dacb..5ede117 100644 --- a/remote/test_remote.py +++ b/remote/test_remote.py @@ -7,6 +7,7 @@ import json import mmap import os import shutil +import signal import socket import struct import subprocess @@ -831,6 +832,27 @@ class RemoteTests(unittest.TestCase): self.assertEqual(self.clip_request("POST", b"y", {**hdr, "Cookie": "chandra_remote=" + tok})[0], 200) self.assertEqual(self.ctl.clips, [("text/plain", b"x"), ("text/plain", b"y")]) + def test_09_sigusr2_restarts_in_place(self): + self.start_daemon(auth="none") + ws, status_line, _, _ = ws_connect("127.0.0.1", self.web_port) + self.assertIn("101", status_line) + ws.settimeout(5) + pid = self.proc.pid + self.proc.send_signal(signal.SIGUSR2) + while ws.recv(65536): # the client is let go, so it can reconnect + pass + ws.close() + deadline = time.time() + 5 + while time.time() < deadline: + try: + if self.clip_request("GET")[0] == 200: + break + except OSError: + time.sleep(0.05) + self.assertIsNone(self.proc.poll()) + self.assertEqual(self.proc.pid, pid) + self.assertEqual(self.clip_request("GET"), (200, {"ok": True, "serial": 0})) + if __name__ == "__main__": unittest.main()