Sha256: ee7f9e11f372512e27ac361e9e372d064029753415f0b4cd0301a25a01f24690

Contents?: true

Size: 1.58 KB

Versions: 5

Compression:

Stored size: 1.58 KB

Contents

require "active_support/duration"
require "active_support/core_ext/numeric/time"

class Kamal::Commands::Prune < Kamal::Commands::Base
  def dangling_images
    docker :image, :prune, "--force", "--filter", "label=service=#{config.service}"
  end

  def tagged_images
    pipe \
      docker(:image, :ls, *service_filter, "--format", "'{{.ID}} {{.Repository}}:{{.Tag}}'"),
      "grep -v -w \"#{active_image_list}\"",
      "while read image tag; do docker rmi $tag; done"
  end

  def app_containers(keep_last: 5)
    pipe \
      docker(:ps, "-q", "-a", *service_filter, *stopped_containers_filters),
      "tail -n +#{keep_last + 1}",
      "while read container_id; do docker rm $container_id; done"
  end

  def healthcheck_containers
    docker :container, :prune, "--force", *healthcheck_service_filter
  end

  private
    def stopped_containers_filters
      [ "created", "exited", "dead" ].flat_map { |status| ["--filter", "status=#{status}"] }
    end

    def active_image_list
      # Pull the images that are used by any containers
      # Append repo:latest - to avoid deleting the latest tag
      # Append repo:<none> - to avoid deleting dangling images that are in use. Unused dangling images are deleted separately
      "$(docker container ls -a --format '{{.Image}}\\|' --filter label=service=#{config.service} | tr -d '\\n')#{config.latest_image}\\|#{config.repository}:<none>"
    end

    def service_filter
      [ "--filter", "label=service=#{config.service}" ]
    end

    def healthcheck_service_filter
      [ "--filter", "label=service=#{config.healthcheck_service}" ]
    end
  end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
kamal-1.3.1 lib/kamal/commands/prune.rb
kamal-1.3.0 lib/kamal/commands/prune.rb
kamal-1.2.0 lib/kamal/commands/prune.rb
kamal-1.1.0 lib/kamal/commands/prune.rb
kamal-1.0.0 lib/kamal/commands/prune.rb