#!/bin/bash set -e usage () { cat </dev/null)" \ -gt $remove_if_not_used_since ] 2>/dev/null; then # Untag the image. Use $image_id to handle previously-untagged # images and other cases when we have no repo or tag reference. docker rmi -f "$image_id" 2>/dev/null \ || echo "NOTE: Cannot remove $image_tuple" fi done # Prune untagged images. docker image prune -f else echo "DRY_RUN: NOT REMOVING UNUSED IMAGES" fi # This is a workaround for https://issues.jenkins-ci.org/browse/JENKINS-49097. # Matrix jobs leave stale ssh-agent processes, which accumulate into hundreds. # This cleanup has nothing to do with docker containers, but creating # a separate script/job for a one-liner doesn't seem to worth it. if [ "$cleanup_ssh_agent_hours" -gt "0" ]; then res=0; killall --older-than ${cleanup_ssh_agent_hours}h -u $USER ssh-agent & wait $! || res=$? # Killall can fail for several reasons: # return-code 127: command not found # return-code 1: in general means no ssh-agent process was found # In the first case, we want the cleanup job to fail, so that we # know we need to install killall # The second case is OK, unless killall fails for another # reason. Assume OK for now. if [ $res != 0 ]; then case $res in 127) echo "WARNING: could not kill stale ssh-agent processes (killall command not found)" echo "Increasing exit code to indicate killall is missing" status=$(($status|16)) ;; 1) echo "WARNING: could not kill stale ssh-agent processes or there was no stale ssh-agent older than ${cleanup_ssh_agent_hours}h" ;; esac fi fi # Check if we have more containers than max_containers nb_containers=$($DOCKER ps -a | wc -l) if [ ${max_containers} -gt 0 ] && [ ${nb_containers} -gt ${max_containers} ]; then echo "ERROR: Too many containers left after cleanup: ${nb_containers} (max: ${max_containers})" status=$(($status|32)) fi exit $status