Skip to content

Instantly share code, notes, and snippets.

@190ikp
Last active April 20, 2022 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 190ikp/aeba97b031101f2b5800f20a716caba8 to your computer and use it in GitHub Desktop.
Save 190ikp/aeba97b031101f2b5800f20a716caba8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -euo pipefail
# moving all stopping LXD container from node to node.
function get_stopping_containers() {
lxc list --format json |
jq -rc 'map({"name": .name, "node": .location, "status": .state.status, "disk_limit": .expanded_devices.root.size, "disk_usage": .state.disk.root.usage} |
select(.status == "Stopped" and .node == '\""$1"\"')) |
.[]'
}
function check_disk_limit() {
local limit
local flag=0
limit=$(echo "$1" | jq -r .disk_limit)
if [ "$limit" != 'null' ]; then
local prefix=${limit: -2}
limit=${limit/%??/}
case $prefix in
"MB" ) prefix=2 ;;
"GB" ) prefix=3 ;;
"TB" ) prefix=4 ;;
* ) prefix=0
flag=1 ;;
esac
local usage
usage=$(echo "$1" | jq -r .disk_usage)
usage=$((usage/(1000**prefix)))
if [ "$usage" -ge "$limit" ]; then
flag=1
fi
fi
echo "$flag"
}
export SRC_HOST=$1
export DST_HOST=$2
export CONTAINER_NAME
echo "Starting to move All stopping containers on $SRC_HOST to $DST_HOST..."
get_stopping_containers "$SRC_HOST" |
while read -r container; do
CONTAINER_NAME=$(echo "$container" | jq -r .name)
case "$(check_disk_limit "$container")" in
0 ) echo "Starting to move $CONTAINER_NAME to $DST_HOST..."
lxc move "$CONTAINER_NAME" "$CONTAINER_NAME" --target "$DST_HOST"
echo 'Done.' ;;
1 ) echo "Can't pass disk limit check! Skipping $CONTAINER_NAME..." ;;
* ) echo "Something went wrong! Skipping $CONTAINER_NAME..." ;;
esac
done
echo "All stopping containers on $SRC_HOST have been moved to $DST_HOST. Exit..."
@190ikp
Copy link
Author

190ikp commented Apr 20, 2022

Now we should use lxc cluster evacuate "$SRC_HOST" to maintain the node with LXD 5.0 or higher.
read the doc: https://linuxcontainers.org/lxd/docs/master/clustering/#evacuating-and-restoring-cluster-members

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment