|
| 1 | +#!/bin/bash |
| 2 | +# Function to handle errors |
| 3 | +handle_error() { |
| 4 | + local exit_code=$? |
| 5 | + local line_number=$1 |
| 6 | + local command=$2 |
| 7 | + echo "Error occurred at line $line_number with exit code $exit_code in command $command" |
| 8 | + exit $exit_code |
| 9 | +} |
| 10 | +trap 'handle_error $LINENO ${BASH_COMMAND%% *}' ERR |
| 11 | +echo "This is line $LINENO" |
| 12 | + |
| 13 | +convert_gb_to_bytes() { |
| 14 | + local gb="$1" |
| 15 | + local bytes |
| 16 | + bytes=$(echo "scale=0; $gb * 1024^3" | bc) |
| 17 | + printf "%.0f\n" "$bytes" |
| 18 | +} |
| 19 | + |
| 20 | +# Check if bc is installed |
| 21 | +install_bc() { |
| 22 | + if ! command -v bc &> /dev/null; then |
| 23 | + echo "bc is not installed. Installing..." |
| 24 | + # Install bc using apt-get (for Debian-based systems) |
| 25 | + sudo apt-get update |
| 26 | + sudo apt-get install -y bc |
| 27 | + fi |
| 28 | +} |
| 29 | + |
| 30 | +check_image_size() { |
| 31 | + IMAGE="$1" |
| 32 | + THRESHOLD_IN_GB="$2" |
| 33 | + |
| 34 | + # call install_bc |
| 35 | + install_bc |
| 36 | + |
| 37 | + CONTAINER_ID=$(docker ps -q --filter "label=test-container=$IMAGE") |
| 38 | + # Find the image ID of the container |
| 39 | + IMAGE_ID=$(docker inspect --format='{{.Image}}' "$CONTAINER_ID") |
| 40 | + # Find the size of the image |
| 41 | + IMAGE_SIZE=$(docker image inspect --format='{{.Size}}' "$IMAGE_ID") |
| 42 | + # Output the size |
| 43 | + echo "Size of the image $IMAGE_ID: $IMAGE_SIZE bytes" |
| 44 | + threshold=$(convert_gb_to_bytes "$THRESHOLD_IN_GB") |
| 45 | + # Retrieve the Docker image size |
| 46 | + echo -e "\nThreshold is $threshold bytes ie $THRESHOLD_IN_GB GB" |
| 47 | + # Remove the 'MB' from the size string and convert to an integer |
| 48 | + image_size=${IMAGE_SIZE%bytes} |
| 49 | + image_size=${image_size//.} |
| 50 | + # Check if the image size is above the threshold |
| 51 | + echo -e "\n🧪 Checking image size of $IMAGE :" |
| 52 | + if [ -n $image_size ] && [ $image_size -gt $threshold ]; then |
| 53 | + echo -e "\nImage size exceeds the threshold of $THRESHOLD_IN_GB gb" |
| 54 | + echo -e "\n❌ Image size check failed." |
| 55 | + else |
| 56 | + echo -e "\n✅ Passed!" |
| 57 | + fi |
| 58 | +} |
0 commit comments