Last active
April 18, 2024 04:55
-
-
Save humangrass/a773ae1a7e3ef675c0290b2f6e8f48f7 to your computer and use it in GitHub Desktop.
Docker container stopper. Allows you to close various containers that continue to work for more than a certain time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
setup_logger() { | |
local path="$1" | |
exec 3>&1 4>&2 | |
exec 1>>"$path" 2>&1 | |
} | |
log() { | |
local message="$1" | |
echo "$(date '+%Y-%m-%d %H:%M:%S %z') - $message" | |
} | |
stop_old_containers() { | |
local image_name="$1" | |
local container_lifetime="$2" | |
current_time=$(date -u +%s) | |
local container_ids | |
container_ids=$(docker ps --filter ancestor="$image_name" --format "{{.ID}}") | |
for container_id in $container_ids; do | |
created_at=$(docker inspect -f '{{.Created}}' "$container_id" | cut -d '.' -f1) | |
created_at_unix=$(date -d "$created_at" -u +%s) | |
how_long_exist=$((current_time - created_at_unix)) | |
if ((how_long_exist >= container_lifetime)); then | |
command=$(docker inspect -f '{{.Config.Cmd}}' "$container_id") | |
log "Stopping container $container_id: $command" | |
docker stop "$container_id" | |
fi | |
done | |
} | |
main() { | |
local log_file='/var/log/helpers/stopper.log' # default path to log file | |
local images='parsers-python|parsers-php|parsers-go|parsers-selenium' # default images | |
local lifetime=1200 # default lifetime is 20 minutes | |
while [[ $# -gt 0 ]]; do | |
case $1 in | |
-i|--images) | |
images="$2" | |
shift | |
;; | |
-lt|--lifetime) | |
lifetime="$2" | |
shift | |
;; | |
--log) | |
log_file="$2" | |
shift | |
;; | |
*) | |
log "Unknown option: $1" | |
exit 1 | |
;; | |
esac | |
shift | |
done | |
setup_logger "$log_file" | |
IFS='|' read -ra image_list <<< "$images" | |
for image_name in "${image_list[@]}"; do | |
log "Start checking containers by $image_name image" | |
stop_old_containers "$image_name" "$lifetime" | |
done | |
log "Done!" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment