Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,12 @@ The dependency runs both ways. ci3 reads these from the repository it is buildin
- `scripts/process_flake_log.py` — optional; run by `parallelize` after a test run when present.
- `build-images/src/home/.gitconfig` — mounted into containers by `docker_isolate`.
- `CI3_EVENT_ENDPOINT`, `CI3_EVENT_TOKEN` and `CI3_EVENT_PROJECT` — optional; when all are set, `bootstrap_ec2` sends a `ci.instance` event per build instance through `send_event` to that OTLP endpoint, for example `https://otel.aztec-labs.com`.
- `CI3_LAUNCHER_WATCHDOG` — optional; `bootstrap_ec2` has a build instance shut itself down a few minutes after its launcher has gone (see `internal/source_launcher_watchdog`). Unset, this is on under GitHub Actions only; `0` turns it off and `1` turns it on elsewhere. It is always off with `NO_TERMINATE=1` and for releases.

### State shared between versions

A repository pins its own ci3, and a build can involve more than one pin: a repository and a
submodule of it each use their own. What has to stay compatible across versions is therefore not
the scripts but the state they share: redis key shapes (`ci-run-<org>/<repo>/<section>`,
`history_*`, `hb-*`, the test cache), S3 log keys (`logs/<prefix>/<key>.log.gz`), build-cache
`history_*`, `hb-*`, `ci3-launcher-*`, the test cache), S3 log keys (`logs/<prefix>/<key>.log.gz`), build-cache
artifact names, and the `<hash>[:VAR=val] <cmd>` test command format.
43 changes: 42 additions & 1 deletion bootstrap_ec2
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

NO_CD=1 source $(dirname "${BASH_SOURCE[0]}")/source
source $ci3/internal/source_refname
source $ci3/internal/source_launcher_watchdog

cmd=${1:?usage: $(basename "$0") '<command-to-run-inside-devbox>'}
# The repository being built, and the checkout directory named after it. ci3 is shared by
Expand Down Expand Up @@ -75,6 +76,9 @@ function report_instance {
function cleanup {
# First: a cancelled job may not live through the termination.
report_instance false
# Stop refreshing the launcher's key (see internal/source_launcher_watchdog). If this process is SIGKILLed
# instead, cleanup never runs, but then the loop notices for itself and stops.
stop_launcher_heartbeat
if [ -d "${state_dir:-}" ]; then
aws_terminate_instance "$state_dir" >/dev/null 2>&1
fi
Expand Down Expand Up @@ -153,6 +157,17 @@ if [ -n "${AZTEC_NR_GITHUB_MIRROR_DEPLOY_KEY:-}" ]; then
export AZTEC_NR_GITHUB_MIRROR_DEPLOY_KEY_B64=$(base64 -w 0 <<<"$AZTEC_NR_GITHUB_MIRROR_DEPLOY_KEY")
fi

# --- Launcher watchdog ---
# If this process dies, the instance should not build on with nobody waiting for the result. While we run, we
# keep a Redis key alive; the build container watches it and has the instance shut down once it has gone. See
# internal/source_launcher_watchdog for the details, including when it is off. CI3_LAUNCHER_WATCHDOG tells the
# container whether to watch: it is 1 only if the key was written.
if launcher_watchdog_wanted && start_launcher_heartbeat "$(launcher_key "$CI_LOG_ID")"; then
CI3_LAUNCHER_WATCHDOG=1
else
CI3_LAUNCHER_WATCHDOG=0
fi

run_cmd="PARENT_LOG_ID=\$ci_log_id run 2>&1 | ci3/add_timestamps | DUP=1 ci3/cache_log 'CI run' \$ci_log_id"

# --- Container script ---
Expand Down Expand Up @@ -200,6 +215,16 @@ container_script=$(
# Heartbeat.
while true; do redis_cli SETEX hb-\$ci_log_id 60 1 &>/dev/null || true; sleep 30; done &

# Launcher watchdog, the reverse direction: notice when the launcher has gone, and leave the host a flag
# file telling it to shut the instance down (see ci3/internal/source_launcher_watchdog). The line saying
# so is appended to this run's log file, which cache_log publishes to the dashboard while the build runs
# (best effort: the instance may go down before the next publish), and also goes to this script's output.
if [ "\${CI3_LAUNCHER_WATCHDOG:-0}" = 1 ]; then
source \$ci3/internal/source_launcher_watchdog
watch_launcher 60 3 \$CI3_LAUNCHER_GONE_FILE redis_cli EXISTS "\$(launcher_key \$ci_log_id)" \\
| tee -a /tmp/\$ci_log_id &
fi

function run {
echo "env: REF_NAME=\$REF_NAME COMMIT_HASH=\$COMMIT_HASH TARGET_BRANCH=\$TARGET_BRANCH"
if semver check "\$REF_NAME"; then
Expand Down Expand Up @@ -257,6 +282,10 @@ host_script=$(
cat <<EOF
set -euo pipefail

# The build container leaves this flag when the launcher has gone (see the monitoring loop below). A new
# instance has none, but make sure one left by an earlier build can never stop this one.
sudo rm -f $CI3_LAUNCHER_GONE_FILE

# This runtime guard should be baked into the build image. Unattended upgrades
# can restart SSM while CI is running, leaving SSM commands stuck InProgress.
echo "HOST: disabling apt periodic upgrades..."
Expand Down Expand Up @@ -364,6 +393,7 @@ start_build() {
-e PARENT_LOG_ID=${PARENT_LOG_ID:-} \
-e NO_CACHE=${NO_CACHE:-} \
-e NO_FAIL_FAST=${NO_FAIL_FAST:-} \
-e CI3_LAUNCHER_WATCHDOG=$CI3_LAUNCHER_WATCHDOG \
-e CI_REDIS='ci-redis-tiered.lzka0i.ng.0001.use2.cache.amazonaws.com' \
-e SSH_CONNECTION=' ' \
-e LOCAL_USER_ID=\$local_uid \
Expand Down Expand Up @@ -412,8 +442,17 @@ start_build &
build_pid=\$!
echo "HOST: devbox container launched (pid=\$build_pid). Monitoring for spot termination..."

# While the docker container is running, check for spot termination notices.
# While the docker container is running, check for spot termination notices, and for the build container's
# word that the launcher has gone.
while kill -0 \$build_pid &>/dev/null; do
# Nobody is waiting for this build any more, so stop paying for it. Whether the instance then terminates
# or only stops depends on its InstanceInitiatedShutdownBehavior: terminate if the launch template sets it,
# stop otherwise (a stopped instance no longer runs, but keeps its volume until it is cleaned up).
if [ -f $CI3_LAUNCHER_GONE_FILE ]; then
echo 'HOST: the launcher has gone (see the build log); shutting the instance down.'
sudo shutdown -h now
exit 1
fi
# The check for the file allows for testing spot termination logic.
if [ -f /tmp/spot_term ] || curl -fs -H 'X-aws-ec2-metadata-token: '\$aws_token http://169.254.169.254/latest/meta-data/spot/termination-time &>/dev/null; then
echo 'Spot will be terminated! Exiting early.'
Expand Down Expand Up @@ -442,6 +481,8 @@ if [ "$exit_code" -eq 155 ]; then
echo "Spot was evicted. Retrying with on-demand instance."
# exec skips the EXIT trap, and the evicted instance needs no termination.
report_instance true
# exec keeps our pid, so the refresh loop would outlive us, keeping an old key alive. The retry starts its own.
stop_launcher_heartbeat
NO_SPOT=1 exec "$0" "$@"
else
# Print CI log URL at the end for easy access (avoid scrolling up).
Expand Down
114 changes: 114 additions & 0 deletions internal/source_launcher_watchdog
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Launcher watchdog: a build instance shuts itself down when whatever launched it has gone.
#
# bootstrap_ec2 runs on a CI runner, starts a build on an EC2 instance and waits for the result. If the runner
# side dies (the job is cancelled, the runner crashes, the job times out) nothing tells the instance, which
# builds on with nobody waiting until its shutdown timer, an hour or more away. So the two sides keep in touch
# through the Redis they already share:
#
# 1. Launcher (bootstrap_ec2, on the runner). It sets the key ci3-launcher-<CI_LOG_ID> with a 120 s expiry
# and refreshes it every 30 s for as long as it runs. If the launcher dies, the key expires.
# 2. Build container (bootstrap_ec2's container script). It checks every 60 s whether the key exists. Once
# the key has been missing for 3 checks in a row, it writes a flag file to /tmp, which the container
# shares with the host.
# 3. Host (bootstrap_ec2's host script). It sees the flag file and shuts the instance down.
#
# From the launcher dying to the flag file: up to 120 s for the key to expire, then up to 180 s of checks,
# so about 5 minutes.
#
# Two rules keep this from killing a build whose launcher is alive:
# - The container does nothing until it has seen the key at least once. That proves both sides talk to the
# same Redis; if they did not, the key would look missing forever.
# - Only a clear "the key does not exist" reply counts as a miss. A Redis error, a timeout or any other
# reply tells us nothing, so it changes nothing.

# Where the container leaves the flag for the host. /tmp on the host is mounted at /tmp in the container.
CI3_LAUNCHER_GONE_FILE=/tmp/ci3-launcher-gone

# The Redis key the launcher keeps alive, for a given CI_LOG_ID.
function launcher_key {
echo "ci3-launcher-$1"
}

# Launcher side. Succeeds if this launch should use the watchdog.
# - CI3_LAUNCHER_WATCHDOG=0 turns it off and =1 turns it on. Left unset, it is on only under GitHub Actions:
# someone launching from a laptop may close the lid and still expect the build to finish.
# - Never with NO_TERMINATE, whose instances are meant to outlive their launcher.
# - Never for a release (REF_NAME is a semver): a release should not be cut short by a runner hiccup.
function launcher_watchdog_wanted {
case "${CI3_LAUNCHER_WATCHDOG:-}" in
0) return 1 ;;
1) ;;
*) [ "${GITHUB_ACTIONS:-}" = true ] || return 1 ;;
esac
[ "${NO_TERMINATE:-0}" != 1 ] || return 1
! semver check "${REF_NAME:-}" &>/dev/null
}

# Launcher side. Sets the key $1 and starts a background loop that refreshes it, recording the loop's pid in
# launcher_heartbeat_pid. Fails, starting nothing, if Redis is unavailable or the first write does not succeed:
# then the container must not be told to watch, since it would never see the key.
function start_launcher_heartbeat {
local key=$1
# The pid of the launcher itself ($$ is the main shell's pid, even inside the loop below).
local launcher_pid=$$
[ "${CI_REDIS_AVAILABLE:-0}" = 1 ] || return 1
# redis_cli hides redis-cli's exit code, so judge by the reply: SETEX answers OK, and nothing else will do.
[ "$(redis_cli SETEX "$key" 120 1 2>/dev/null)" = OK ] || return 1
# Refresh every 30 s, so a single slow or failed write (redis_cli gives up after 30 s) still leaves the key
# alive. The loop also stops by itself if the launcher is gone: normally cleanup kills it, but if the launcher
# was SIGKILLed and the loop somehow was not, it must not keep the key alive for a launcher that has gone.
# Its output goes nowhere, so it never holds open a pipe that a caller (parallel, the CI runner) waits on.
(
while sleep 30 && kill -0 "$launcher_pid" 2>/dev/null; do
redis_cli SETEX "$key" 120 1 &>/dev/null
done
) </dev/null &>/dev/null &
launcher_heartbeat_pid=$!
}

# Launcher side. Stops the refresh loop, if one is running. Safe to call more than once, and harmless if the
# loop has already died.
function stop_launcher_heartbeat {
if [ -n "${launcher_heartbeat_pid:-}" ]; then
kill "$launcher_heartbeat_pid" 2>/dev/null || true
launcher_heartbeat_pid=
fi
}

# Container side. Usage: watch_launcher <interval-seconds> <miss-limit> <flag-file> <check-command...>
# Runs the check command every <interval-seconds>. It should print 1 if the launcher's key exists and 0 if it
# does not; anything else, or nothing, counts as an error. After <miss-limit> misses in a row, once the key has
# been seen, it prints a line saying so, creates <flag-file> and returns. Otherwise it runs until killed.
# The body is a subshell, so the caller's set -e cannot end the loop early, and its variables stay local.
function watch_launcher() (
set +e
local interval=$1 miss_limit=$2 flag_file=$3
shift 3
# armed: the key has been seen at least once. misses: checks in a row since then that found it missing.
local armed=0 misses=0 reply
while true; do
reply=$("$@" 2>/dev/null)
case "$reply" in
1)
armed=1
misses=0
;;
0)
if [ "$armed" = 1 ]; then
misses=$((misses + 1))
fi
;;
*)
# An error, a timeout or an unexpected reply: we learned nothing, so count nothing.
;;
esac
if [ "$misses" -ge "$miss_limit" ]; then
echo "LAUNCHER WATCHDOG: the process that launched this build has stopped checking in" \
"(missed $misses checks, ${interval}s apart). It has gone, so nobody is waiting for this build:" \
"shutting this instance down."
touch "$flag_file"
return 0
fi
sleep "$interval"
done
)
Loading