Guest User

Untitled

a guest
Jul 7th, 2015
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. JQPATH=$(which jq)
  4. if [ "x$JQPATH" == "x" ]; then
  5. echo "Couldn't find jq executable." 1>&2
  6. exit 2
  7. fi
  8.  
  9. set -eu
  10. shopt -s nullglob
  11.  
  12. readonly base_dir=/var/lib/docker/registry
  13. readonly output_dir=$(mktemp -d -t trace-images-XXXX)
  14. readonly jq=$JQPATH
  15.  
  16. readonly repository_dir=$base_dir/repositories
  17. readonly image_dir=$base_dir/images
  18.  
  19. readonly all_images=$output_dir/all
  20. readonly used_images=$output_dir/used
  21. readonly unused_images=$output_dir/unused
  22.  
  23. function info() {
  24. echo -e "\nArtifacts available in $output_dir"
  25. }
  26. trap info EXIT ERR INT
  27.  
  28. function image_history() {
  29. local readonly image_hash=$1
  30. $jq '.[]' $image_dir/$image_hash/ancestry | tr -d '"'
  31. }
  32.  
  33. echo "Collecting orphan images"
  34. for library in $repository_dir/*; do
  35. echo "Library $(basename $library)" >&2
  36.  
  37. for repo in $library/*; do
  38. echo " Repo $(basename $repo)" >&2
  39.  
  40. for tag in $repo/tag_*; do
  41. echo " Tag $(basename $tag)" >&2
  42.  
  43. tagged_image=$(cat $tag)
  44. image_history $tagged_image
  45. done
  46. done
  47. done | sort | uniq > $used_images
  48.  
  49. ls $image_dir > $all_images
  50.  
  51. grep -v -F -f $used_images $all_images > $unused_images
  52.  
  53. readonly all_image_count=$(wc -l $all_images | awk '{print $1}')
  54. readonly used_image_count=$(wc -l $used_images | awk '{print $1}')
  55. readonly unused_image_count=$(wc -l $unused_images | awk '{print $1}')
  56. readonly unused_image_size=$(cd $image_dir; du -hc $(cat $unused_images) | tail -n1 | cut -f1)
  57.  
  58. echo "${all_image_count} images, ${used_image_count} used, ${unused_image_count} unused"
  59. echo "Unused images consume ${unused_image_size}"
  60.  
  61. echo -e "\nTrimming _index_images..."
  62. readonly unused_images_flatten=$output_dir/unused.flatten
  63. cat $unused_images | sed -e 's/\(.*\)/\"\1\" /' | tr -d "\n" > $unused_images_flatten
  64.  
  65. for library in $repository_dir/*; do
  66. echo "Library $(basename $library)" >&2
  67.  
  68. for repo in $library/*; do
  69. echo " Repo $(basename $repo)" >&2
  70. mkdir -p "$output_dir/$(basename $repo)"
  71. jq '.' "$repo/_index_images" > "$output_dir/$(basename $repo)/_index_images.old"
  72. jq -s '.[0] - [ .[1:][] | {id: .} ]' "$repo/_index_images" $unused_images_flatten > "$output_dir/$(basename $repo)/_index_images"
  73. cp "$output_dir/$(basename $repo)/_index_images" "$repo/_index_images"
  74. done
  75. done
  76.  
  77. echo -e "\nRemoving images"
  78. cat $unused_images | xargs -I{} rm -rf $image_dir/{}
Add Comment
Please, Sign In to add comment