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
4 changes: 3 additions & 1 deletion aws/ami_update.sh
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ 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
# create-image below reboots the instance to image it. That reboot comes from EC2, so terminate-on-shutdown
# probably would not apply, but keep shutdown as stop here as a precaution.
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
17 changes: 17 additions & 0 deletions aws_terminate_instance
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,26 @@ fi

iid=$(cat $state_path/iid 2>/dev/null || true)
sir=$(cat $state_path/sir 2>/dev/null || true)
launch_id=$(cat $state_path/launch_id 2>/dev/null || true)

export AWS_DEFAULT_REGION=us-east-2

# A fleet was requested (there is a launch id) but no instance id was recorded. Usually no instance was
# started, for example when there was no capacity. But if the launch was interrupted while create-fleet
# was running, AWS may have started one whose id never came back to us. Look for it by its CI3LaunchId
# tag (set in aws_request_instance_type). A just-launched instance can take a moment to show up, so look
# up to three times, two seconds apart.
if [ -z "$iid" ] && [ -n "$launch_id" ]; then
for attempt in 1 2 3; do
iid=$(aws ec2 describe-instances \
--filters "Name=tag:CI3LaunchId,Values=$launch_id" "Name=instance-state-name,Values=pending,running" \
--query "Reservations[].Instances[].InstanceId" --output text 2>/dev/null | tr '\n\t' ' ' | xargs || true)
[ -n "$iid" ] && [ "$iid" != None ] && break
iid=""
[ "$attempt" -lt 3 ] && sleep 2
done
fi

if [ -n "$iid" ]; then
echo "Terminating instance: $iid..."
dump_fail "aws ec2 terminate-instances --instance-ids $iid" > /dev/null
Expand Down
11 changes: 11 additions & 0 deletions 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_shutdown_timer

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 @@ -253,10 +254,20 @@ for pass_env_name in ${CI3_PASS_ENV:-}; do
pass_env_args+=" -e $pass_env_name=$(printf %q "${!pass_env_name:-}")"
done

# The first thing the build does on the instance is set its own shutdown timer (AWS_SHUTDOWN_TIME), so
# the build never runs on the short boot timer. Provisioning has already done this once; doing it again
# here makes sure of it. See internal/source_shutdown_timer.
shutdown_timer_cmd=""
if [ "$NO_TERMINATE" -ne 1 ]; then
shutdown_timer_cmd=$(claim_shutdown_or_fail "$AWS_SHUTDOWN_TIME")
fi

host_script=$(
cat <<EOF
set -euo pipefail

$shutdown_timer_cmd

# 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
59 changes: 54 additions & 5 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_shutdown_timer

name=$1
ami=$2
Expand All @@ -13,6 +14,16 @@ spec_path=$state_dir/lt_data.json
iid_path=$state_dir/iid
ip_path=$state_dir/ip
lt_path=$state_dir/launch_template_id
launch_id_path=$state_dir/launch_id

# Minutes an instance lives after boot if nobody claims it (see source_shutdown_timer). It must be longer
# than provisioning can take before the claim lands: up to 300 s waiting for SSM, then up to three claim
# attempts of 60 s each, 5 s apart, about 8 minutes in all.
AWS_BOOT_SHUTDOWN_TIME=${AWS_BOOT_SHUTDOWN_TIME:-15}
if ! [[ "$AWS_BOOT_SHUTDOWN_TIME" =~ ^[0-9]+$ ]] || [ "$AWS_BOOT_SHUTDOWN_TIME" -lt 10 ]; then
echo_stderr "AWS_BOOT_SHUTDOWN_TIME must be a whole number of minutes, at least 10: $AWS_BOOT_SHUTDOWN_TIME"
exit 1
fi

export AWS_DEFAULT_REGION=us-east-2

Expand Down Expand Up @@ -56,8 +67,13 @@ if [ "${#subnets[@]}" -eq 0 ]; then
exit 1
fi

# An id unique to this request. It names the launch template and is tagged on the instance as CI3LaunchId,
# so aws_terminate_instance can find the instance even if its instance id never came back to us. The name
# part is cut to 96 characters to keep the whole within the 128-character launch template name limit.
launch_id="ci3-${name:0:96}-$$-$(date +%s)-$RANDOM"

# Instance tags, applied at launch via the launch template (propagate to fleet instances).
tags_json="{\"Key\":\"Name\",\"Value\":\"$name\"},{\"Key\":\"Group\",\"Value\":\"build-instance\"}"
tags_json="{\"Key\":\"Name\",\"Value\":\"$name\"},{\"Key\":\"Group\",\"Value\":\"build-instance\"},{\"Key\":\"CI3LaunchId\",\"Value\":\"$launch_id\"}"
[ -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\"}"
Expand All @@ -72,10 +88,24 @@ if [ "${UNSAFE_AWS_KEEP_ALIVE:-0}" -eq 1 ]; then
tags_json+=",{\"Key\":\"Keep-Alive\",\"Value\":\"true\"}"
fi

# Add the boot timer (as user data), and make the instance terminate rather than stop when it shuts
# itself down, so a timed-out instance stops costing anything, its volume included. NO_TERMINATE
# instances are meant to stay up, so they get neither. AWS_SHUTDOWN_TERMINATES=0 keeps the timer but
# leaves shutdown as stop, for callers that power the instance down on purpose (aws/ami_update.sh images it).
lifetime_json=""
if [ "${NO_TERMINATE:-0}" -ne 1 ]; then
user_data=$(boot_shutdown_script "$AWS_BOOT_SHUTDOWN_TIME" | base64 -w 0)
lifetime_json="\"UserData\": \"$user_data\","
if [ "${AWS_SHUTDOWN_TERMINATES:-1}" -eq 1 ]; then
lifetime_json+=" \"InstanceInitiatedShutdownBehavior\": \"terminate\","
fi
fi

# Common launch config shared by every pool. Sizes/AZs vary per fleet override.
lt_data=$(cat <<EOF
{
"ImageId": "$ami",
$lifetime_json
"IamInstanceProfile": { "Name": "$CI3_INSTANCE_PROFILE_NAME" },
"SecurityGroupIds": ["$sg_id"],
"BlockDeviceMappings": [
Expand All @@ -98,7 +128,7 @@ EOF
)
echo "$lt_data" > "$spec_path"

lt_name="ci3-${name}-$$-$(date +%s)"
lt_name=$launch_id
lt_id=$(aws ec2 create-launch-template \
--launch-template-name "$lt_name" \
--launch-template-data "$lt_data" \
Expand Down Expand Up @@ -147,6 +177,9 @@ if [ "${NO_SPOT:-0}" -ne 1 ]; then
SECONDS=0
while true; do
echo "Requesting spot fleet $info ($spot_strategy, ${spot_timeout}s budget)..."
# Record the launch id just before asking for an instance: from this point an instance can exist
# whose id we do not know yet, and aws_terminate_instance uses this file to look for it.
echo "$launch_id" > "$launch_id_path"
resp=$(aws ec2 create-fleet \
--type instant \
--target-capacity-specification "TotalTargetCapacity=1,DefaultTargetCapacityType=spot" \
Expand Down Expand Up @@ -176,6 +209,8 @@ if [ -z "$iid" ]; then
SECONDS=0
while true; do
echo "Requesting on-demand fleet $info ($ondemand_strategy)..."
# As for spot above.
echo "$launch_id" > "$launch_id_path"
resp=$(aws ec2 create-fleet \
--type instant \
--target-capacity-specification "TotalTargetCapacity=1,DefaultTargetCapacityType=on-demand" \
Expand Down Expand Up @@ -244,9 +279,23 @@ if [ "$ssm_status" != "Online" ]; then
exit 1
fi

# Fire-and-forget. Non-fatal: a failed timer shouldn't abort provisioning (reaper catches orphans).
# Claim the instance: replace the boot timer with the caller's AWS_SHUTDOWN_TIME (see source_shutdown_timer).
# Callers go on to run long jobs, and an unclaimed instance shuts down when the boot timer runs out, so a
# claim that fails is fatal: the instance is terminated and provisioning fails. One failed SSM command
# should not cost a run, so it tries three times first.
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)."
claimed=0
for attempt in 1 2 3; do
if SSM_POLL_TIMEOUT=60 ssm_send_command "$iid" "$(claim_shutdown_cmd "${AWS_SHUTDOWN_TIME:-60}")" >&2; then
claimed=1
break
fi
[ "$attempt" -lt 3 ] && { >&2 echo "Setting the shutdown timer failed; retrying..."; sleep 5; }
done
if [ "$claimed" -ne 1 ]; then
>&2 echo "Could not set the shutdown timer on $iid; terminating it."
aws ec2 terminate-instances --instance-ids "$iid" >/dev/null 2>&1 || true
exit 1
fi
fi
43 changes: 43 additions & 0 deletions internal/source_shutdown_timer
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Shutdown timers on build instances.
#
# Every build instance should shut itself down eventually, even if whatever launched it has died. This
# works in two steps:
# 1. Boot timer. When the instance boots, its user data (run by cloud-init) sets a short timer,
# `shutdown -h +15` by default. An instance that nobody goes on to use is gone in 15 minutes.
# 2. Claim. Whoever uses the instance replaces that timer with a longer one, long enough for its job.
# aws_request_instance_type claims the instance once SSM is online, and bootstrap_ec2 claims it
# again at the start of the build.
#
# On the instance, a later `shutdown -h +N` replaces any earlier one. Boot is not guaranteed to finish
# before the first SSM command arrives, so a slow boot script could replace a claim with the 15-minute
# timer and kill the build. To prevent that:
# - The boot script and the claim both run under one lock (flock), so they never interleave.
# - A claim leaves a marker file once its timer is set, and the boot script does nothing if the marker
# exists.
# So whichever runs first, the claim's timer is the one that stays.

# Directory for the lock and the marker on the instance. /run is emptied at every boot, so a marker never
# survives a reboot. Tests override this to run the commands locally; nothing else should.
CI3_TIMER_DIR=${CI3_TIMER_DIR:-/run}

# Prints the user-data script for the boot timer ($1 minutes). Under the lock, it sets the timer only if
# no claim has been made yet.
function boot_shutdown_script {
cat <<SCRIPT
#!/bin/sh
flock "$CI3_TIMER_DIR/ci3-timer.lock" sh -c '[ -e "$CI3_TIMER_DIR/ci3-claimed" ] || shutdown -h +$1'
SCRIPT
}

# Prints the command that claims the instance with a $1-minute timer. Under the lock, it sets the timer
# and then writes the marker. The marker is written only if the timer was set, so a failed claim leaves
# the boot timer in place rather than no timer at all.
function claim_shutdown_cmd {
echo "sudo flock \"$CI3_TIMER_DIR/ci3-timer.lock\" sh -c 'shutdown -h +$1 && touch \"$CI3_TIMER_DIR/ci3-claimed\"'"
}

# Prints a script line that claims the instance with a $1-minute timer, and stops the script with an
# error if it cannot.
function claim_shutdown_or_fail {
echo "$(claim_shutdown_cmd "$1") || { echo 'HOST: could not set the shutdown timer.' >&2; exit 1; }"
}
Loading