Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# !/bin/bash
# Script to use Fleetctl to stop and start containers using a rolling restart
# By Troy Fontaine with rolling restart script from http://engineering.rainchasers.com/coreos/fleet/2015/03/03/rolling-unit-restart.html
# Grab list of containers and assign to array
container_list=($(fleetctl list-units -fields=unit -no-legend | cut -f2 ))
# Prepare variable for later use
container=""
restart ()
{
fleetctl list-units | grep $1@ | cut -f1 -d. | while read -r unit ; do
unit_index=`echo $unit | cut -f2 -d@`
printf "unit:> %s index:> %s\n" $unit $unit_index
printf "stopping:> %s\n" $unit
fleetctl stop $unit
printf "waiting:> for %s to stop " $unit;
is_running=1
while [ $is_running -ne 0 ]; do
is_running=`fleetctl list-units | grep running | grep $unit | wc -l`;
sleep 1;
printf ".";
done
printf "\n"
printf "starting:> %s\n" $unit
fleetctl start $unit
printf "waiting:> for %s to start " $unit;
while [ $is_running -eq 0 ]; do
is_running=`fleetctl list-units | grep running | grep $unit | wc -l`;
sleep 1;
printf ".";
done
printf "\n"
fleetctl list-units | grep $unit
done
}
usage ()
{
echo "script to restart all commonly updated services"
echo
echo "To recreate all containers:"
echo "$0 all"
echo
echo "To start one container"
echo "$0 <containername> (e.g. $0 fraud_service)"
echo
echo "To recreate one or a few containers pass them as a space seperated list:"
echo "$0 http_service fraud_service card_ui"
echo
}
if [ "$#" == 0 ]; then
usage
fi
if [ "$#" -ge 1 ]; then
if [ "$1" == "all" ]; then
echo "Restarting all units individually by service"
# Loop through container list
for unit_name in "${container_list[@]}"
do
# Check if unit name's variable contains anything
if [ ${#unit_name} -le 10 ]; then
# Skip if variable not long enough to contain "@#.service" in the name
shift
fi
# Remove trailing @#.service text from title
container=${unit_name%??????????}
# Since we grab the whole list of containers, skip matching names as they were already restarted
if [ "$container" != "$lastcontainer" ]; then
restart "$container"
fi
# Used to check for duplicates
lastcontainer=$container
done
exit 0
elif [ "$1" == "testall" ]; then
echo "Restarting all units individually by service"
for unit_name in "${container_list[@]}"
do
echo "Test Restart $unit_name"
done
exit 0
elif [ "$1" == "test" ]; then
for unit_name in "$@"
do
echo "Test ad-hoc restart of $unit_name"
done
exit 0
else
for unit_name in "$@"
do
echo "Ad-hoc restart of $unit_name"
restart $unit_name
done
exit 0
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.