Skip to content
Merged
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,7 +126,8 @@ 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`.
- **`exec` into `bootstrap_ec2` or `bootstrap_ec2_multi`**, all the way from the CI step: `run: exec ./ci.sh fast` in the workflow, `exec bootstrap_ec2 …` in `ci.sh`. CI cancels a job by signalling only the process it started (GitHub Actions sends that one process SIGINT, then SIGTERM, then SIGKILL 10 seconds later), so that process must be the ci3 script that terminates the instances. A script in between that runs it without `exec`, including as part of a pipeline, keeps the signal to itself, and the instances run on until their shutdown timers. `tests/cancel_test` covers this.
- **Permission to renew a build instance's lease.** Each build instance shuts itself down, and so terminates, once its `LeaseUntil` tag has passed, and whoever launched it renews that tag every minute while it runs (`internal/source_instance_lease`). The AWS role that launches instances, in CI and on a build instance launching another (such as the benchmark box), needs `ec2:CreateTags` for the `LeaseUntil` key on instances tagged `Group=build-instance`. Without it, every instance shuts down 10 minutes after boot.
- **`exec` into `bootstrap_ec2` or `bootstrap_ec2_multi`**, all the way from the CI step: `run: exec ./ci.sh fast` in the workflow, `exec bootstrap_ec2 …` in `ci.sh`. CI cancels a job by signalling only the process it started (GitHub Actions sends that one process SIGINT, then SIGTERM, then SIGKILL 10 seconds later), so that process must be the ci3 script that terminates the instances. A script in between that runs it without `exec`, including as part of a pipeline, keeps the signal to itself, and the instances run on until their leases run out. `tests/cancel_test` covers this.

### State shared between versions

Expand Down
5 changes: 4 additions & 1 deletion aws/ami_update.sh
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ esac
# Request new instance (ami: ubuntu 24.04 LTS). Like a build instance, it has no key pair and is driven over SSM.
state_dir=$(mktemp -d /tmp/aws_request_instance.XXXXXX)
trap on_exit EXIT
AMI=$ami aws_request_instance ami_update_$arch 4 $arch $state_dir
# Like a build instance's, its lease is renewed while this script runs (see internal/source_instance_lease).
# create-image below reboots the instance to image it, so shutdown stays as stop rather than terminate.
aws_instance_lease $state_dir $(($(date +%s) + ${AWS_SHUTDOWN_TIME:-60} * 60)) $$ &
AMI=$ami AWS_SHUTDOWN_TERMINATES=0 aws_request_instance ami_update_$arch 4 $arch $state_dir
iid=$(cat $state_dir/iid | tr -d '\n\r' | xargs)

echo "Instance id: $iid"
Expand Down
9 changes: 0 additions & 9 deletions aws_terminate_instance
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,6 @@ export AWS_DEFAULT_REGION=us-east-2
if [ -n "$iid" ]; then
echo "Terminating instance: $iid..."
dump_fail "aws ec2 terminate-instances --instance-ids $iid" > /dev/null
# Instances it launched itself (tagged by aws_request_instance_type), such as a benchmark box:
# they cannot be cleaned up from inside an instance that is being terminated.
children=$(aws ec2 describe-instances \
--filters "Name=tag:ParentInstance,Values=$iid" "Name=instance-state-name,Values=pending,running,stopping,stopped" \
--query 'Reservations[].Instances[].InstanceId' --output text 2>/dev/null || true)
if [ -n "$children" ]; then
echo "Terminating instances it launched: $children..."
dump_fail "aws ec2 terminate-instances --instance-ids $children" > /dev/null
fi
fi

if [ -n "$sir" ]; then
Expand Down
20 changes: 18 additions & 2 deletions bootstrap_ec2
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,30 @@ function report_instance {
evicted="$1" >/dev/null 2>&1 &
}

# Terminates our instance, and any instance it launched, when the script exits.
# Terminates our instance when the script exits.
function cleanup {
# First: a cancelled job may not live through the termination.
report_instance false
stop_lease
if [ -d "${state_dir:-}" ]; then
aws_terminate_instance "$state_dir" >/dev/null 2>&1
fi
}

# The instance shuts itself down unless its lease keeps being renewed (see
# internal/source_instance_lease). This renews it until the run's deadline, AWS_SHUTDOWN_TIME from now,
# for as long as this script is alive, whatever ends it.
lease_pid=
function start_lease {
[ "$NO_TERMINATE" -eq 1 ] && return
aws_instance_lease "$state_dir" $(($(date +%s) + AWS_SHUTDOWN_TIME * 60)) $$ &
lease_pid=$!
}
function stop_lease {
[ -n "$lease_pid" ] && kill "$lease_pid" 2>/dev/null
lease_pid=
}

# Cancellation. CI cancels by signalling only the process it started, so a caller must exec into this
# script, and everything slow here runs in the background under `wait`, which a signal interrupts at
# once (bash runs a trap only after a foreground command finishes). The child is stopped first, so
Expand Down Expand Up @@ -144,6 +159,7 @@ fi

# Request new instance.
requested_at=$(date +%s)
start_lease
interruptible aws_request_instance "$instance_name" "$cores" "$arch" "$state_dir"
ready_at=$(date +%s)
sir=""
Expand Down Expand Up @@ -412,7 +428,6 @@ start_build() {
-e GITHUB_ACTOR=${GITHUB_ACTOR:-} \
-e EC2_INSTANCE_TYPE=${EC2_INSTANCE_TYPE:-unknown} \
-e EC2_SPOT=${EC2_SPOT:-unknown} \
-e CI3_PARENT_INSTANCE_ID=$iid \
-e BENCH_UPLOAD=${BENCH_UPLOAD:-} \
-e AZTEC_TOOLCHAIN_DEFAULT_MAJOR_VERSION=${AZTEC_TOOLCHAIN_DEFAULT_MAJOR_VERSION:-} \
-e DRY_RUN=${DRY_RUN:-} \
Expand Down Expand Up @@ -459,6 +474,7 @@ 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
stop_lease
NO_SPOT=1 exec "$0" "$@"
else
# Print CI log URL at the end for easy access (avoid scrolling up).
Expand Down
31 changes: 31 additions & 0 deletions internal/aws_instance_lease
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
# Renews a build instance's lease for as long as the process that launched it is alive (see
# internal/source_instance_lease).
#
# aws_instance_lease <state dir> <deadline> <owner pid>
#
# Once the instance id appears in <state dir>/iid, it sets the instance's LeaseUntil tag to
# CI3_LEASE_SECONDS (default 300) from now, every CI3_LEASE_RENEW (default 60) seconds, but never past
# <deadline>, in seconds since the epoch. It exits once <owner pid> is gone.
set -uo pipefail

state_dir=$1
deadline=$2
owner=$3
lease=${CI3_LEASE_SECONDS:-300}
renew=${CI3_LEASE_RENEW:-60}
export AWS_DEFAULT_REGION=us-east-2

while kill -0 "$owner" 2>/dev/null; do
iid=$(tr -d '[:space:]' 2>/dev/null <"$state_dir/iid")
if [ -z "$iid" ]; then
sleep 1
continue
fi
lease_until=$(($(date +%s) + lease))
((lease_until > deadline)) && lease_until=$deadline
if ! aws ec2 create-tags --resources "$iid" --tags "Key=LeaseUntil,Value=$lease_until" >/dev/null 2>&1; then
echo "aws_instance_lease: could not renew the lease of $iid." >&2
fi
sleep "$renew"
done
28 changes: 16 additions & 12 deletions internal/aws_request_instance_type
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env bash
source $(dirname "${BASH_SOURCE[0]}")/../source
source $(dirname "${BASH_SOURCE[0]}")/source_instance_lease

name=$1
ami=$2
Expand Down Expand Up @@ -71,10 +72,6 @@ tags_json="{\"Key\":\"Name\",\"Value\":\"$name\"},{\"Key\":\"Group\",\"Value\":\
[ -n "${GITHUB_ACTOR:-}" ] && tags_json+=",{\"Key\":\"GithubActor\",\"Value\":\"${GITHUB_ACTOR//[\[\]]/}\"}"
[ -n "${CI_MODE:-}" ] && tags_json+=",{\"Key\":\"CICommand\",\"Value\":\"$CI_MODE\"}"
[ -n "${CI_DASHBOARD:-}" ] && tags_json+=",{\"Key\":\"Dashboard\",\"Value\":\"$CI_DASHBOARD\"}"
# Launched from a build instance (bootstrap_ec2 passes its id in): whoever terminates that instance
# terminates this one too (see aws_terminate_instance), since nothing inside a terminating instance
# gets to clean up.
[ -n "${CI3_PARENT_INSTANCE_ID:-}" ] && tags_json+=",{\"Key\":\"ParentInstance\",\"Value\":\"$CI3_PARENT_INSTANCE_ID\"}"
# Repo is the cost allocation tag that splits the shared account's EC2 and EBS bill by repository.
# Lowercased: CI's GITHUB_REPOSITORY and a local checkout's origin url can differ in case, and a
# cost allocation tag groups by exact value.
Expand All @@ -86,10 +83,24 @@ if [ "${UNSAFE_AWS_KEEP_ALIVE:-0}" -eq 1 ]; then
tags_json+=",{\"Key\":\"Keep-Alive\",\"Value\":\"true\"}"
fi

# The instance shuts itself down when its lease runs out (see source_instance_lease), and terminates
# rather than stops when it does, so it stops costing anything, its volume included. NO_TERMINATE
# instances are meant to stay up, so they get neither. AWS_SHUTDOWN_TERMINATES=0 keeps the lease but
# leaves shutdown as stop, for a caller that powers the instance down on purpose (aws/ami_update.sh
# images it).
lease_json=""
if [ "${NO_TERMINATE:-0}" -ne 1 ]; then
lease_json="\"UserData\": \"$(lease_user_data | base64 -w 0)\", \"MetadataOptions\": { \"InstanceMetadataTags\": \"enabled\" },"
if [ "${AWS_SHUTDOWN_TERMINATES:-1}" -eq 1 ]; then
lease_json+=" \"InstanceInitiatedShutdownBehavior\": \"terminate\","
fi
fi

# Common launch config shared by every pool. Sizes/AZs vary per fleet override.
lt_data=$(cat <<EOF
{
"ImageId": "$ami",
$lease_json
"IamInstanceProfile": { "Name": "$CI3_INSTANCE_PROFILE_NAME" },
"SecurityGroupIds": ["$sg_id"],
"BlockDeviceMappings": [
Expand Down Expand Up @@ -238,7 +249,7 @@ while [ -z "${ip:-}" ]; do
echo $ip > $ip_path
done

# Wait for SSM registration and set the shutdown timer.
# Wait for SSM registration.
>&2 echo "Waiting for SSM registration for instance $iid..."
SECONDS=0
while (( SECONDS < 300 )); do
Expand All @@ -256,10 +267,3 @@ if [ "$ssm_status" != "Online" ]; then
>&2 echo "Timed out waiting for SSM to see instance $iid"
exit 1
fi

# Fire-and-forget. Non-fatal: a failed timer shouldn't abort provisioning (reaper catches orphans).
if [ "${NO_TERMINATE:-0}" -ne 1 ]; then
>&2 echo "Setting shutdown timer (+${AWS_SHUTDOWN_TIME:-60} min) via SSM..."
SSM_NO_WAIT=1 ssm_send_command "$iid" "sudo shutdown -h +${AWS_SHUTDOWN_TIME:-60}" || \
>&2 echo "Warning: failed to set shutdown timer via SSM (non-fatal)."
fi
51 changes: 51 additions & 0 deletions internal/source_instance_lease
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Build instance leases.
#
# Every build instance shuts itself down, and so terminates, once its lease runs out. The lease is the
# time in the instance's LeaseUntil tag. Whoever launched the instance keeps renewing it while it is
# alive (internal/aws_instance_lease), so an instance outlives its launcher by at most one lease period,
# however the launcher ended: cancelled, killed, or on a runner that died. The renewal stops at the run's
# deadline, so a run that goes on too long ends the same way.
#
# The instance reads the tag through its metadata service, which needs no credentials. A watchdog, started
# at boot from the instance's user data, checks it every 30 seconds. It starts with a lease of 10 minutes
# from boot, enough for the first renewal to land, and from then on keeps the latest lease it has read: if
# it cannot read the tag, the last lease it saw still runs out. It runs as a systemd service that restarts
# if it dies, and keeps the lease in /run, so a restart does not extend it.

# Prints the watchdog. CI3_IMDS, CI3_LEASE_POLL and CI3_LEASE_STATE are for tests; nothing else should set
# them.
function lease_watchdog_script {
cat <<'WATCHDOG'
#!/bin/sh
imds=${CI3_IMDS:-http://169.254.169.254}
poll=${CI3_LEASE_POLL:-30}
state=${CI3_LEASE_STATE:-/run/ci3-lease}
[ -s "$state" ] || echo $(($(date +%s) + ${CI3_LEASE_INITIAL:-600})) >"$state"
lease=$(cat "$state")
while :; do
token=$(curl -sf -m 5 -X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 60' "$imds/latest/api/token")
tag=$(curl -sf -m 5 -H "X-aws-ec2-metadata-token: $token" "$imds/latest/meta-data/tags/instance/LeaseUntil")
case "$tag" in
'' | *[!0-9]*) ;;
*) lease=$tag && echo "$lease" >"$state" ;;
esac
if [ "$(date +%s)" -ge "$lease" ]; then
echo "ci3: the lease ran out at $(date -d "@$lease"); shutting down."
shutdown -h now
exit 0
fi
sleep "$poll"
done
WATCHDOG
}

# Prints the instance's user data, which installs the watchdog in /run, so it is never part of an image
# made from the instance, and starts it.
function lease_user_data {
echo '#!/bin/sh'
echo "cat >/run/ci3-lease-watchdog <<'WATCHDOG_EOF'"
lease_watchdog_script
echo 'WATCHDOG_EOF'
echo 'chmod +x /run/ci3-lease-watchdog'
echo 'systemd-run --unit=ci3-lease-watchdog --property=Restart=always --property=RestartSec=5 /run/ci3-lease-watchdog'
}
28 changes: 10 additions & 18 deletions tests/cancel_test
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,16 @@ case "$1 $2" in
log "launched i-$n"
echo "{\"Instances\":[{\"InstanceIds\":[\"i-$n\"],\"InstanceType\":\"m6a.32xlarge\"}]}" ;;
"ec2 describe-instances")
if [[ "$args" == *tag:ParentInstance* ]]; then
parent=$(grep -o 'tag:ParentInstance,Values=[^ ]*' <<<"$args" | cut -d= -f2)
cat "$state/children-of-$parent" 2>/dev/null || true
elif [[ "$args" == *instance-id* ]]; then
echo 10.0.0.1
fi ;;
if [[ "$args" == *instance-id* ]]; then echo 10.0.0.1; fi ;;
"ec2 terminate-instances")
sleep "${STUB_TERMINATE_DELAY:-0}"
for id in ${args#*--instance-ids }; do [[ "$id" == i-* ]] && log "terminated $id"; done ;;
"ec2 describe-instance-status") echo running ;;
"ssm describe-instance-information") echo Online ;;
"ssm send-command")
iid=$(grep -o -- '--instance-ids [^ ]*' <<<"$args" | cut -d' ' -f2)
params=; prev=
for a in "$@"; do [ "$prev" = --parameters ] && params=$a; prev=$a; done
script=$(jq -r '.commands[0]' <<<"$params" | grep -o 'echo "[A-Za-z0-9+/=]*"' | cut -d'"' -f2 | base64 -d)
if [[ "$script" == *"shutdown -h"* ]]; then echo timer-$iid; else log "command on $iid"; echo cmd-$iid; fi ;;
log "command on $iid"
echo cmd-$iid ;;
"ssm get-command-invocation")
log "polling $(grep -o -- '--command-id [^ ]*' <<<"$args" | cut -d' ' -f2)"
echo "{\"Status\":\"$(cat "$state/ssm_status" 2>/dev/null || echo InProgress)\",\"ResponseCode\":0}" ;;
Expand Down Expand Up @@ -122,7 +115,6 @@ function run_case {
shift 6
mkdir -p "$state"
: >"$state/calls"
echo i-child >"$state/children-of-i-1"
local ended
ended=$(env -i PATH="$tmp/bin:$PATH" HOME="$tmp" REPO="$tmp/repo" STUB_STATE="$state" CI=1 CI_REDIS_AVAILABLE=0 \
GITHUB_REPOSITORY=test/repo REF_NAME=test AWS_DEFAULT_REGION=us-east-2 \
Expand All @@ -138,20 +130,20 @@ function run_case {
fi
}

check "CI cancel while the build runs terminates the instance and the ones it launched" \
ci "polling cmd-i-1" "i-1 i-child" 1 "$script_dir/bootstrap_ec2" "./bootstrap.sh ci-fast"
check "CI cancel while the build runs terminates the instance" \
ci "polling cmd-i-1" "i-1" 1 "$script_dir/bootstrap_ec2" "./bootstrap.sh ci-fast"

STUB_FLEET_DELAY=3 check "CI cancel while the instance is being requested terminates it" \
ci "requesting fleet" "i-1 i-child" 0 "$script_dir/bootstrap_ec2" "./bootstrap.sh ci-fast"
ci "requesting fleet" "i-1" 0 "$script_dir/bootstrap_ec2" "./bootstrap.sh ci-fast"

STUB_TERMINATE_DELAY=1 check "Ctrl-C, twice, while the build runs terminates the instance" \
terminal "polling cmd-i-1" "i-1 i-child" 1 "$script_dir/bootstrap_ec2" "./bootstrap.sh ci-fast"
terminal "polling cmd-i-1" "i-1" 1 "$script_dir/bootstrap_ec2" "./bootstrap.sh ci-fast"

check "CI cancel of a multi-job run terminates every job's instance" \
ci "polling cmd-i-1|polling cmd-i-2" "i-1 i-2 i-child" 2 "$script_dir/bootstrap_ec2_multi" "x-a amd64 ci-fast" "x-b amd64 ci-fast"
ci "polling cmd-i-1|polling cmd-i-2" "i-1 i-2" 2 "$script_dir/bootstrap_ec2_multi" "x-a amd64 ci-fast" "x-b amd64 ci-fast"

STUB_TERMINATE_DELAY=1 check "Ctrl-C, twice, of a multi-job run terminates every job's instance" \
terminal "polling cmd-i-1|polling cmd-i-2" "i-1 i-2 i-child" 2 "$script_dir/bootstrap_ec2_multi" "x-a amd64 ci-fast" "x-b amd64 ci-fast"
terminal "polling cmd-i-1|polling cmd-i-2" "i-1 i-2" 2 "$script_dir/bootstrap_ec2_multi" "x-a amd64 ci-fast" "x-b amd64 ci-fast"

wait
for i in $(seq 1 $case_n); do
Expand All @@ -165,7 +157,7 @@ done
# as a build that runs these tests.
function leftover {
local pid
for pid in $(pgrep -f "$script_dir/(bootstrap_ec2|internal/ssm_send_command|denoise|aws_request_instance)"); do
for pid in $(pgrep -f "$script_dir/(bootstrap_ec2|internal/ssm_send_command|internal/aws_instance_lease|denoise|aws_request_instance)"); do
tr '\0' '\n' <"/proc/$pid/environ" 2>/dev/null | grep -q "^STUB_STATE=$tmp/" && ps -o pid=,args= -p "$pid" | cut -c1-120
done
return 0
Expand Down
Loading
Loading