Skip to content

Commit

Permalink
feat : completed the code to remove unused docker images exceed speci…
Browse files Browse the repository at this point in the history
…fic size limit
  • Loading branch information
deexithparand committed Oct 26, 2024
1 parent 72d76fb commit ca98fe7
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 4 deletions.
6 changes: 6 additions & 0 deletions cmd/cleaner/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ func main() {
dc.CleanupStoppedContainerImages()
case f.VerboseMode:
dc.VerboseModeCleanup()
case f.SizeLimit.Value >= 0:
var unit string = f.GetSizeUnit()
if unit == "" {
log.Fatalf("Please specify a size unit (B, KB, MB, or GB)")
}
dc.RemoveExceedSizeLimit(f.SizeLimit.Value, unit)
default:
dc.RemoveUnusedImages()
}
Expand Down
62 changes: 59 additions & 3 deletions internal/docker/images.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ func (d *DockerClient) ListUnusedImages() ([]image.Summary, error) {
}
}

if len(unusedImages) > 0 {
fmt.Printf("Found %d unused images\n", len(unusedImages))
}
return unusedImages, nil
}

Expand Down Expand Up @@ -143,6 +140,65 @@ func formatLabels(labels map[string]string) string {
return strings.Join(labelStore, ", ")
}

// Remove Images that exceed a specific size limit
func (d *DockerClient) RemoveExceedSizeLimit(sizeLimit int64, unit string) {

var sizeLimitInBytes int64 = toBytes(sizeLimit, unit)

images, err := d.ListUnusedImages()
if err != nil {
log.Fatalf("Error listing images: %v", err)
}

if len(images) == 0 {
log.Println("No unused images found")
return
}

opts := image.RemoveOptions{Force: true}

removedImagesCount := 0
totalSizeCleaned := int64(0)

for _, image := range images {

// checking and removing images exceeding the threshold size
if image.Size >= sizeLimitInBytes {
_, err := d.CLI.ImageRemove(context.Background(), image.ID, opts)
if err != nil {
log.Printf("Failed to remove image %s: %v", image.ID, err)
} else {
log.Printf("Successfully removed image %s", image.ID)
}

totalSizeCleaned += image.Size
removedImagesCount++
}

}

if removedImagesCount > 0 {
log.Printf("Summary: Removed %d images (Total space freed: %s)", removedImagesCount, formatSize(totalSizeCleaned))
} else {
fmt.Printf("No Unused Images are exceeding the limit %d %s", sizeLimit, strings.ToUpper(unit))
}

}

// converts any value of any value to bytes
func toBytes(size int64, unit string) int64 {

var multipliers map[string]int64 = map[string]int64{
"b": 1,
"kb": 1024,
"mb": 1024 * 1024,
"gb": 1024 * 1024 * 1024,
}

return size * multipliers[unit]

}

// RemoveUnusedImages deletes unused Docker images
func (d *DockerClient) RemoveUnusedImages() {

Expand Down
34 changes: 33 additions & 1 deletion pkg/utils/flags.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,50 @@
package utils

import "flag"
import (
"flag"
)

type Size struct {
Value int64
Unit string
}

type Flags struct {
DryRun bool
RemoveStopped bool
VerboseMode bool
SizeLimit Size
B bool
KB bool
MB bool
GB bool
}

func (f *Flags) GetSizeUnit() string {
if f.B {
return "b"
} else if f.KB {
return "kb"
} else if f.MB {
return "mb"
} else if f.GB {
return "gb"
} else {
return ""
}
}

func ParseFlags() *Flags {
f := &Flags{}
flag.BoolVar(&f.DryRun, "dry-run", false, "List unused Docker images without deleting them")
flag.BoolVar(&f.RemoveStopped, "remove-stopped", false, "Remove Images Associated with Stopped Containers")
flag.BoolVar(&f.VerboseMode, "verbose", false, "Verbose mode provides additional details about each image during cleanup")
flag.Int64Var(&f.SizeLimit.Value, "size-limit", 0, "Specify the size limit to filter images (e.g., 500MB, 1GB)")
flag.BoolVar(&f.B, "B", false, "Specify the size unit as bytes")
flag.BoolVar(&f.KB, "KB", false, "Specify the size unit as kilobytes")
flag.BoolVar(&f.MB, "MB", false, "Specify the size unit as megabytes")
flag.BoolVar(&f.GB, "GB", false, "Specify the size unit as gigabytes")

flag.Parse()
return f
}

0 comments on commit ca98fe7

Please sign in to comment.