Skip to content

Instantly share code, notes, and snippets.

@poeticninja
Created October 7, 2016 18:54

Revisions

  1. poeticninja created this gist Oct 7, 2016.
    65 changes: 65 additions & 0 deletions docker-cache-experimental.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    #!/usr/bin/env bash

    image_archive="image-archive.tar"
    image_metadata="docker-image-metadata.tar.gz"

    function cache_images() {
    images_to_cache=$(docker images | awk '{print $3}' | grep -v '<none>' | tail -n +2 | while read line; do docker history -q $line | grep -v '<missing>'; done | uniq)

    if [ -n "$images_to_cache" ]; then
    printf "Saving the following images:\n$images_to_cache\n\n"
    docker save -o /tmp/$image_archive $(echo ${images_to_cache[@]});
    sudo mv /tmp/$image_archive $destination
    echo "Images saved to $cached_image_archive_path"

    echo "Saving image metadata ..."
    sudo tar czf /tmp/$image_metadata -C /var/lib/docker/image .
    sudo mv /tmp/$image_metadata $destination

    echo "Done."
    else
    echo "No images found."
    fi
    }

    function restore_images() {
    if [ -e $cached_image_archive_path ] && [ -e $cached_image_metadata_path ]; then
    echo "Restoring images ..."
    docker load < $cached_image_archive_path
    sudo tar xf $cached_image_metadata_path -C /var/lib/docker/image
    echo "Images restored."
    docker images
    ignore_semaphore_cache
    else
    echo "No image backup found. Please use the 'snapshot' action to create one."
    fi
    }

    function ignore_semaphore_cache() {
    semaphore_cache_dir=$(basename $SEMAPHORE_CACHE_DIR)
    cache_ignored=$(grep $semaphore_cache_dir .dockerignore &> /dev/null)

    if ! [ $? -eq 0 ]; then
    echo "Adding Semaphore's cache directory to .dockerignore"
    echo "$semaphore_cache_dir" >> .dockerignore
    fi
    }

    function docker-cache() {
    destination=$SEMAPHORE_CACHE_DIR
    cached_image_archive_path="$destination/$image_archive"
    cached_image_metadata_path="$destination/$image_metadata"

    case "$1" in
    "snapshot" )
    cache_images
    ;;
    "restore" )
    restore_images
    ;;
    * )
    echo "'$1' action unknown"
    echo "Usage: docker-cache <snapshot|restore>"
    ;;
    esac
    }