mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-24 23:36:04 +00:00
fix(onboarding): a smoother first run, from the child-process setting to the Steam sign-in (#3114)
The child-process fix always uses the guided pairing flow, Finish setup opens the setting directly and queues the Steam launch, the Play button carries the first-run progress, the setup bar weighs each download by its real size, and the Steam client packages download over four connections and unpack one at a time under a flock.
This commit is contained in:
1 parent
46ec222fa5
commit
39debda0b0
67 files changed
+1151
-2078
No files matched your search
@@ -132,6 +132,138 @@ fetch() {
|
||||
done
|
||||
}
|
||||
|
||||
# The same decisions as fetch for the parallel workers, with curl in the foreground and a plain sleep between tries:
|
||||
# the shell here cannot open /dev/fd for process substitution from a background job.
|
||||
fetch_one() {
|
||||
local url=$1 dest=$2 size=$3 sum=$4 part=$5 failures=0 bad=0 finished=0 before rc http wait
|
||||
while :; do
|
||||
if [ -f "$dest" ] && { [ "$finished" = 1 ] || { [ "$size" -gt 0 ] && [ "$(size_of "$dest")" -ge "$size" ]; }; }; then
|
||||
echo "$sum $dest" | sha256sum -c --quiet 2>/dev/null && return 0
|
||||
rm -f "$dest"
|
||||
finished=0 bad=$((bad + 1))
|
||||
[ "$bad" -lt 3 ] || { echo "droiddeck-steam-install: $part does not match its checksum" >&2; return 1; }
|
||||
fi
|
||||
before=$(size_of "$dest")
|
||||
http=$(curl -fsSL "${limits[@]}" -w '%{http_code}' -C - -o "$dest" "$url") && rc=0 || rc=$?
|
||||
if [ "$rc" = 0 ]; then finished=1; continue; fi
|
||||
case "$rc:${http:-}" in
|
||||
22:416 | 33:*) rm -f "$dest" ;;
|
||||
22:4??)
|
||||
echo "droiddeck-steam-install: $part: HTTP $http from ${url%/*}" >&2
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
if [ "$(size_of "$dest")" -gt "$before" ]; then failures=0; else failures=$((failures + 1)); fi
|
||||
if [ "$failures" -gt "${#delays[@]}" ]; then
|
||||
echo "droiddeck-steam-install: could not download $part (curl exit $rc); what arrived is kept for the next try" >&2
|
||||
return 1
|
||||
fi
|
||||
wait=${delays[$((failures > 0 ? failures - 1 : 0))]}
|
||||
step "downloading Steam: $part - interrupted (curl exit $rc), trying again in ${wait} s"
|
||||
sleep "$wait"
|
||||
done
|
||||
}
|
||||
|
||||
parallel=${DD_STEAM_PARALLEL:-4}
|
||||
case $parallel in ''|*[!0-9]*|0) parallel=1 ;; esac
|
||||
flock_command=${DD_STEAM_FLOCK:-flock}
|
||||
command -v "$flock_command" > /dev/null 2>&1 || parallel=1
|
||||
|
||||
# unzip creates parent directories without guarding against another unzip doing the same, so two packages unpacked into
|
||||
# one tree at once fail now and then. Unpacking is quick next to downloading, so the workers take turns on a flock: the
|
||||
# kernel hands it on when its holder ends, however it ends, so there is no stale lock to recover.
|
||||
unzip_alone() {
|
||||
local rc
|
||||
( "$flock_command" 9 && unzip -qo "$1" -d "$steam_root" ) 9> "$state/unzip.lock" && rc=0 || rc=$?
|
||||
return $rc
|
||||
}
|
||||
|
||||
# Fetches every line of a list ("block file sum size") into $dir with up to $parallel connections. With a third
|
||||
# argument each package is also unpacked into the client as it lands. One connection tops out near half of what a
|
||||
# Wi-Fi link carries, so the packages arrive about twice as fast. Workers take the next unclaimed line themselves
|
||||
# (mkdir is atomic) and only plain background jobs and wait on a pid are used, so nothing depends on job control.
|
||||
run_parallel() {
|
||||
local list=$1 dir=$2 unpack=${3:-} state index=0 block file sum size
|
||||
local -a blocks=() files=() sums=() sizes=() pids=()
|
||||
state=$work/parallel
|
||||
rm -rf "$state"
|
||||
mkdir -p "$state"
|
||||
while read -r block file sum size; do
|
||||
index=$((index + 1))
|
||||
blocks[index]=$block files[index]=$file sums[index]=$sum sizes[index]=$size
|
||||
if [ -n "$unpack" ] && [ -f "$dir/$file.unpacked" ]; then
|
||||
: > "$state/$index.done"
|
||||
: > "$state/claim.$index"
|
||||
fi
|
||||
done < "$list"
|
||||
local count=$index total_bytes=0
|
||||
for index in $(seq 1 "$count"); do total_bytes=$((total_bytes + sizes[index])); done
|
||||
local slot
|
||||
for slot in $(seq 1 "$parallel"); do
|
||||
(
|
||||
trap ': > "$state/exit.$slot"' EXIT
|
||||
while [ ! -e "$state/failed" ]; do
|
||||
index=0
|
||||
for n in $(seq 1 "$count"); do
|
||||
if mkdir "$state/claim.$n" 2>/dev/null; then index=$n; break; fi
|
||||
done
|
||||
[ "$index" -gt 0 ] || exit 0
|
||||
file=${files[index]}
|
||||
fetched=""
|
||||
for host in "${cdn_order[@]}"; do
|
||||
if fetch_one "$host/$file" "$dir/$file" "${sizes[index]}" "${sums[index]}" "${blocks[index]}"; then
|
||||
fetched=$host
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$fetched" ]; then
|
||||
echo "droiddeck-steam-install: $file failed on every CDN" >&2
|
||||
: > "$state/failed"
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "$unpack" ]; then
|
||||
unzip_alone "$dir/$file" || { : > "$state/failed"; exit 1; }
|
||||
: > "$dir/$file.unpacked"
|
||||
rm -f "$dir/$file"
|
||||
fi
|
||||
: > "$state/$index.done"
|
||||
done
|
||||
) &
|
||||
pids+=($!)
|
||||
done
|
||||
local shown="" got n alive mark current last="" since=$SECONDS stall=${DD_STEAM_STALL:-90}
|
||||
while :; do
|
||||
alive=0
|
||||
for slot in $(seq 1 "$parallel"); do [ -e "$state/exit.$slot" ] || alive=1; done
|
||||
got=0 n=0 current=""
|
||||
for index in $(seq 1 "$count"); do
|
||||
if [ -e "$state/$index.done" ]; then
|
||||
got=$((got + sizes[index])) n=$((n + 1))
|
||||
elif [ -e "$state/claim.$index" ]; then
|
||||
current=$index
|
||||
[ -f "$dir/${files[index]}" ] && got=$((got + $(size_of "$dir/${files[index]}")))
|
||||
fi
|
||||
done
|
||||
mark=$((got / 1000000))
|
||||
if [ -n "$current" ] && [ "$mark" != "$shown" ]; then
|
||||
shown=$mark
|
||||
step "downloading Steam: ${blocks[current]} ($((n + 1))/$count), $mark of $((total_bytes / 1000000)) MB"
|
||||
fi
|
||||
[ "$n" -lt "$count" ] || alive=0
|
||||
if [ "$got" != "$last" ]; then last=$got since=$SECONDS; fi
|
||||
# A worker killed from outside never writes its exit marker. Stop reporting once nothing has moved for a while
|
||||
# and wait on the workers: wait returns the killed one's status, so the install fails instead of hanging.
|
||||
[ $((SECONDS - since)) -lt "$stall" ] || alive=0
|
||||
[ "$alive" = 1 ] || break
|
||||
sleep 1
|
||||
done
|
||||
local failed=""
|
||||
for slot in "${pids[@]}"; do wait "$slot" || failed=1; done
|
||||
[ ! -e "$state/failed" ] || failed=1
|
||||
rm -rf "$state"
|
||||
[ -z "$failed" ]
|
||||
}
|
||||
|
||||
fetch_manifest() {
|
||||
cdn=""
|
||||
for candidate in $cdn_list; do
|
||||
@@ -193,6 +325,9 @@ if [ -n "$cache_only" ]; then
|
||||
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache")
|
||||
done_bytes=0
|
||||
i=0
|
||||
if [ "$parallel" -gt 1 ]; then
|
||||
run_parallel "$work/cache" "$cache" || exit 1
|
||||
else
|
||||
while read -r block file sum size; do
|
||||
i=$((i + 1))
|
||||
progress "$cache/$file" "$block"
|
||||
@@ -206,6 +341,7 @@ if [ -n "$cache_only" ]; then
|
||||
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
|
||||
done_bytes=$((done_bytes + size))
|
||||
done < "$work/cache"
|
||||
fi
|
||||
echo "$version" > "$cached"
|
||||
exit 0
|
||||
fi
|
||||
@@ -228,6 +364,9 @@ for left in "$parts"/*; do
|
||||
grep -qF " $name " "$work/parts" || rm -rf "$left"
|
||||
done
|
||||
done_bytes=0
|
||||
if [ "$parallel" -gt 1 ]; then
|
||||
run_parallel "$work/parts" "$parts" unpack || exit 1
|
||||
else
|
||||
while read -r block file sum size; do
|
||||
i=$((${i:-0} + 1))
|
||||
if [ -f "$parts/$file.unpacked" ]; then
|
||||
@@ -248,6 +387,7 @@ while read -r block file sum size; do
|
||||
rm -f "$parts/$file"
|
||||
done_bytes=$((done_bytes + size))
|
||||
done < "$work/parts"
|
||||
fi
|
||||
find "$steam_root" -depth -name '*\\*' | while read -r odd; do
|
||||
fixed=${odd//\\//}
|
||||
mkdir -p "$(dirname "$fixed")"
|
||||
|
||||
@@ -2,8 +2,10 @@ import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
@@ -12,6 +14,8 @@ SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/dr
|
||||
|
||||
|
||||
class SteamInstallTest(unittest.TestCase):
|
||||
parallel = '1'
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
@@ -47,19 +51,29 @@ if host_fail and host_fail in url:
|
||||
action = []
|
||||
plan = os.environ.get('TEST_PLAN')
|
||||
if plan and os.path.exists(plan):
|
||||
lines = open(plan).read().splitlines()
|
||||
for n, line in enumerate(lines):
|
||||
if line.split()[0] == name:
|
||||
action = line.split()[1:]
|
||||
del lines[n]
|
||||
open(plan, 'w').write(''.join(l + '\\n' for l in lines))
|
||||
break
|
||||
import fcntl
|
||||
with open(plan + '.lock', 'w') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
lines = open(plan).read().splitlines()
|
||||
for n, line in enumerate(lines):
|
||||
if line.split()[0] == name:
|
||||
action = line.split()[1:]
|
||||
del lines[n]
|
||||
open(plan, 'w').write(''.join(l + '\\n' for l in lines))
|
||||
break
|
||||
if action[:1] == ['fail']:
|
||||
done(int(action[1]), '000')
|
||||
if action[:1] == ['http']:
|
||||
done(22, action[1])
|
||||
if action[:1] == ['killworker']:
|
||||
import signal
|
||||
os.kill(os.getppid(), signal.SIGKILL)
|
||||
import time
|
||||
time.sleep(6)
|
||||
if action[:1] == ['norange'] and offset:
|
||||
done(33)
|
||||
import time
|
||||
time.sleep(float(os.environ.get('TEST_SLEEP', '0')))
|
||||
data = open(os.path.join(os.environ['TEST_CDN'], name), 'rb').read()
|
||||
end = int(action[1]) if action[:1] == ['cut'] else len(data)
|
||||
with open(out, 'ab' if offset else 'wb') as target:
|
||||
@@ -79,7 +93,8 @@ done(28 if end < len(data) else 0)
|
||||
self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data),
|
||||
PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
|
||||
TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests),
|
||||
TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0')
|
||||
TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0',
|
||||
DD_STEAM_PARALLEL=self.parallel)
|
||||
for channel in ('steamdeck_publicbeta', 'steamdeck_stable'):
|
||||
archive = self.cdn / (channel + '.zip')
|
||||
with zipfile.ZipFile(archive, 'w') as package:
|
||||
@@ -92,9 +107,13 @@ done(28 if end < len(data) else 0)
|
||||
f'\t\t"file" "{archive.name}"\n\t\t"sha2" "{digest}"\n'
|
||||
'\t}\n}\n')
|
||||
|
||||
def install(self, fail_host=None, *args, **extra):
|
||||
def install(self, fail_host=None, *args, timeout=None, **extra):
|
||||
env = self.env if fail_host is None else dict(self.env, TEST_FAIL_HOST=fail_host)
|
||||
return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True)
|
||||
try:
|
||||
return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True,
|
||||
timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.fail(f'the installer did not finish within {timeout} s')
|
||||
|
||||
def channel(self, **extra):
|
||||
result = self.install(None, '--channel', **extra)
|
||||
@@ -455,5 +474,165 @@ done(28 if end < len(data) else 0)
|
||||
self.assertFalse(self.download.exists())
|
||||
|
||||
|
||||
class SteamInstallParallelTest(SteamInstallTest):
|
||||
"""The same behaviour with several connections at once."""
|
||||
parallel = '4'
|
||||
test_progress_is_counted_in_megabytes_across_parts = None
|
||||
|
||||
def many_parts(self, count=10):
|
||||
return self.publish(**{f'p{i}_all': 300_000 for i in range(count)})
|
||||
|
||||
def test_many_parts_arrive_and_unpack_together(self):
|
||||
self.many_parts()
|
||||
result = self.install()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
for i in range(10):
|
||||
self.assertTrue((self.steam / f'parts/p{i}_all').is_file(), i)
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
|
||||
self.assertFalse(self.download.exists())
|
||||
|
||||
def test_every_part_is_requested_once_when_several_arrive_together(self):
|
||||
files = self.many_parts()
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
requested = self.requested()
|
||||
for name in files.values():
|
||||
self.assertEqual(1, requested.count(name), name)
|
||||
|
||||
def test_one_part_that_no_cdn_has_fails_the_install_and_leaves_no_ready_marker(self):
|
||||
files = self.many_parts()
|
||||
missing = files['p4_all']
|
||||
self.plan_for(missing, 'http 404', 'http 404', 'http 404')
|
||||
result = self.install()
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
|
||||
self.assertIn('failed on every CDN', result.stderr)
|
||||
|
||||
def test_a_retry_after_a_failure_finishes_what_is_left(self):
|
||||
files = self.many_parts()
|
||||
self.plan_for(files['p4_all'], 'http 404', 'http 404', 'http 404')
|
||||
self.assertNotEqual(0, self.install().returncode)
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.assertTrue((self.steam / 'parts/p4_all').is_file())
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
|
||||
|
||||
def test_progress_is_reported_while_several_parts_arrive(self):
|
||||
self.many_parts()
|
||||
result = self.install(TEST_SLEEP='1.2', **{})
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
lines = [line for line in result.stdout.splitlines() if 'downloading Steam:' in line and ' of ' in line]
|
||||
self.assertGreaterEqual(len(lines), 2, result.stdout)
|
||||
self.assertIn(' MB', lines[-1])
|
||||
|
||||
def test_packages_are_unpacked_one_at_a_time(self):
|
||||
source = SCRIPT.read_text()
|
||||
region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')]
|
||||
self.assertNotIn('unzip -qo', region)
|
||||
self.assertIn('unzip_alone', region)
|
||||
self.assertIn('"$flock_command" 9', source)
|
||||
|
||||
def unzip_alone_script(self):
|
||||
source = SCRIPT.read_text()
|
||||
start = source.index('unzip_alone() {')
|
||||
function = source[start:source.index('\n}\n', start) + 3]
|
||||
return 'state=$1\nsteam_root=$2\nflock_command=flock\n' + function + '\nunzip_alone "$3"\n'
|
||||
|
||||
def unzip_alone_archive(self, name='one.zip', entry='steamrtarm64/steam'):
|
||||
archive = self.root / name
|
||||
with zipfile.ZipFile(archive, 'w') as package:
|
||||
package.writestr(entry, 'client')
|
||||
self.steam.mkdir(parents=True, exist_ok=True)
|
||||
(self.root / 'state').mkdir(exist_ok=True)
|
||||
return archive
|
||||
|
||||
def run_unzip_alone(self, archive, timeout, env=None):
|
||||
arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)]
|
||||
try:
|
||||
return subprocess.run(arguments, text=True, capture_output=True, timeout=timeout, env=env)
|
||||
except subprocess.TimeoutExpired:
|
||||
return None
|
||||
|
||||
def hold_the_lock(self):
|
||||
"""Starts a process that holds the unzip lock and returns once it says it has it."""
|
||||
ready = self.root / 'holder-ready'
|
||||
holder = subprocess.Popen(
|
||||
['flock', str(self.root / 'state/unzip.lock'), 'sh', '-c', f'touch {ready}; sleep 60'], start_new_session=True)
|
||||
self.addCleanup(lambda: os.killpg(holder.pid, signal.SIGKILL) if holder.poll() is None else None)
|
||||
deadline = time.monotonic() + 10
|
||||
while not ready.exists():
|
||||
self.assertLess(time.monotonic(), deadline, 'the holder never took the lock')
|
||||
time.sleep(0.05)
|
||||
return holder
|
||||
|
||||
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
|
||||
def test_a_package_waits_for_a_worker_that_is_unpacking(self):
|
||||
archive = self.unzip_alone_archive()
|
||||
self.hold_the_lock()
|
||||
self.assertIsNone(self.run_unzip_alone(archive, timeout=4), 'unzip_alone did not wait for the holder')
|
||||
self.assertFalse((self.steam / 'steamrtarm64/steam').exists())
|
||||
|
||||
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
|
||||
def test_a_worker_killed_while_unpacking_hands_the_lock_on(self):
|
||||
archive = self.unzip_alone_archive()
|
||||
holder = self.hold_the_lock()
|
||||
os.killpg(holder.pid, signal.SIGKILL)
|
||||
holder.wait()
|
||||
result = self.run_unzip_alone(archive, timeout=20)
|
||||
self.assertIsNotNone(result, 'the lock of a killed worker was never handed on')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertTrue((self.steam / 'steamrtarm64/steam').is_file())
|
||||
|
||||
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
|
||||
def test_several_workers_never_unpack_at_the_same_moment(self):
|
||||
log = self.root / 'unzip.log'
|
||||
fake = self.bin / 'unzip'
|
||||
fake.write_text('''#!/usr/bin/env python3
|
||||
import os, sys, time
|
||||
log = os.environ['TEST_UNZIP_LOG']
|
||||
with open(log, 'a') as out:
|
||||
out.write(f'start {os.getpid()}\\n')
|
||||
time.sleep(0.3)
|
||||
with open(log, 'a') as out:
|
||||
out.write(f'end {os.getpid()}\\n')
|
||||
''')
|
||||
fake.chmod(0o755)
|
||||
archive = self.unzip_alone_archive()
|
||||
env = dict(self.env, TEST_UNZIP_LOG=str(log))
|
||||
arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)]
|
||||
workers = [subprocess.Popen(arguments, env=env) for _ in range(8)]
|
||||
for worker in workers:
|
||||
self.assertEqual(0, worker.wait(timeout=60))
|
||||
lines = log.read_text().split()
|
||||
events = lines[0::2]
|
||||
self.assertEqual(['start', 'end'] * 8, events, 'two workers unpacked at the same time')
|
||||
|
||||
def test_without_flock_the_downloads_go_one_at_a_time(self):
|
||||
self.two_parts()
|
||||
result = self.install(DD_STEAM_FLOCK='flock-that-is-not-installed')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
# Only the sequential path counts parts as (1/2) and (2/2).
|
||||
self.assertIn('downloading Steam: a_all (1/2), 0 of 2 MB\n', result.stdout)
|
||||
self.assertIn('downloading Steam: client_linuxarm64_linuxarm64 (2/2), 1 of 2 MB\n', result.stdout)
|
||||
|
||||
def test_the_parallel_workers_use_no_process_substitution(self):
|
||||
source = SCRIPT.read_text()
|
||||
region = source[source.index('fetch_one() {'):source.index('fetch_manifest() {')]
|
||||
self.assertNotIn('<(', region)
|
||||
reporter = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')]
|
||||
self.assertNotIn('kill -0', reporter)
|
||||
|
||||
def test_a_worker_killed_from_outside_fails_the_install_instead_of_hanging_it(self):
|
||||
files = self.many_parts()
|
||||
self.plan_for(files['p3_all'], 'killworker')
|
||||
result = self.install(timeout=40, DD_STEAM_STALL='3')
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
|
||||
|
||||
def test_the_cache_pass_with_several_connections_keeps_every_package(self):
|
||||
self.cache_manifest()
|
||||
result = self.install(None, '--cache')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-cached').read_text())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user