#!/bin/bash

set -euo pipefail

dir=$1
test_tmpdir=$(pwd)

cd ${dir}
env PYTHONUNBUFFERED=1 setsid python -m SimpleHTTPServer 0 >${test_tmpdir}/httpd-output &
child_pid=$!

for x in $(seq 50); do
    sed -e 's,Serving HTTP on 0.0.0.0 port \([0-9]*\) \.\.\.,\1,' < ${test_tmpdir}/httpd-output > ${test_tmpdir}/httpd-port
    if ! cmp ${test_tmpdir}/httpd-output ${test_tmpdir}/httpd-port 1>/dev/null; then
        break
    fi
    sleep 0.1
done
port=$(cat ${test_tmpdir}/httpd-port)
echo "http://127.0.0.1:${port}" > ${test_tmpdir}/httpd-address
echo "$child_pid" > ${test_tmpdir}/httpd-pid

#!/bin/bash

set -euo pipefail

dir=$1
test_tmpdir=$(pwd)

cd ${dir}
env PYTHONUNBUFFERED=1 setsid python -m SimpleHTTPServer 0 >${test_tmpdir}/httpd-output &
child_pid=$!

for x in $(seq 50); do
    # Snapshot the output
    cp ${test_tmpdir}/httpd-output{,.tmp}
    # If it's non-empty, see whether it matches our regexp
    if test -s ${test_tmpdir}/httpd-output.tmp; then
        sed -e 's,Serving HTTP on 0.0.0.0 port \([0-9]*\) \.\.\.,\1,' < ${test_tmpdir}/httpd-output.tmp > ${test_tmpdir}/httpd-port
        if ! cmp ${test_tmpdir}/httpd-output.tmp ${test_tmpdir}/httpd-port 1>/dev/null; then
            # If so, we've successfully extracted the port
            break
        fi
    fi
    sleep 0.1
done
port=$(cat ${test_tmpdir}/httpd-port)
echo "http://127.0.0.1:${port}" > ${test_tmpdir}/httpd-address
echo "$child_pid" > ${test_tmpdir}/httpd-pid

Fix race condition in tmp webserver
tests: Fix race condition in tmp webserver

I was seeing this when trying to run flatpak's tests in ostree's CI:
https://github.com/ostreedev/ostree/pull/824

The race here is that the python process can still be writing to the output
while sed is reading it, and hence we'll find a difference on the next line.
Fix this by making a tmp copy of the file, which then both sed and cmp will
read consistently.

I'm not *entirely* sure this will fix the problem as I couldn't easily reproduce
the race locally, but I believe it at least fixes *a* race.
