Skip to content

Instantly share code, notes, and snippets.

@matthew-hollick
Last active June 26, 2024 13:47
Show Gist options
  • Save matthew-hollick/e34ac0e57de87c5b9e5474a72a6edabf to your computer and use it in GitHub Desktop.
Save matthew-hollick/e34ac0e57de87c5b9e5474a72a6edabf to your computer and use it in GitHub Desktop.
bash script to estimate cost percent of my kubernetes namespaces.
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 <namespace1> <namespace2> ..."
echo "Example: $0 fred jane"
exit 1
fi
#for ns in $@; do
# # Get memory limits for all pods in the namespace
# memory_limits=$(kubectl get pods -n $ns -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.resources.limits.memory}{"\n"}{end}{end}')
#
# # Sum up the memory limits
# sum_bytes=0
# for limit in $memory_limits; do
# bytes=$(to_bytes $limit)
# sum_bytes=$((sum_bytes + bytes))
# done
#
# # Add to total memory
# total_memory=$((total_memory + sum_bytes))
#
# # Print the result for this namespace
# printf "%-30s %d\n" "$ns:" "$sum_bytes"
#done
get_namespace_memory() {
kubectl get pods -n "$1" -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.resources.limits.memory}{"\n"}{end}{end}' | awk '{ sum += $1 } END { print sum }'
}
total_memory=$(kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.resources.limits.memory}{"\n"}{end}{end}' | awk '{ sum += $1 } END { print sum }')
specified_memory=0
for namespace in "$@"; do
ns_memory=$(get_namespace_memory "$namespace")
specified_memory=$((specified_memory + ns_memory))
done
# Not used, yolo stackexchange.
to_bytes() {
local value=$1
case ${value: -2} in
Ki) echo $((${value%Ki} * 1024)) ;;
Mi) echo $((${value%Mi} * 1024 * 1024)) ;;
Gi) echo $((${value%Gi} * 1024 * 1024 * 1024)) ;;
*) echo $value ;;
esac
}
# Convert to bytes
#total_bytes=$(to_bytes $total_memory)
#specified_bytes=$(to_bytes $specified_memory)
# Calculate percentage
percentage=$(awk "BEGIN {printf \"%.2f\", ($specified_memory / $total_memory) * 100}")
echo "Percentage of cluster memory allocated to pods in specified namespaces: $percentage%"
echo "Specified namespaces: $@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment