|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "os/exec" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/araddon/dateparse" |
| 13 | +) |
| 14 | + |
| 15 | +type ImageMetadata struct { |
| 16 | + Architecture string `json:"architecture"` |
| 17 | + ChangeableAttributes struct { |
| 18 | + DeleteEnabled bool `json:"deleteEnabled"` |
| 19 | + ListEnabled bool `json:"listEnabled"` |
| 20 | + ReadEnabled bool `json:"readEnabled"` |
| 21 | + WriteEnabled bool `json:"writeEnabled"` |
| 22 | + } `json:"changeableAttributes"` |
| 23 | + ConfigMediaType string `json:"configMediaType"` |
| 24 | + CreatedTime time.Time `json:"createdTime"` |
| 25 | + Digest string `json:"digest"` |
| 26 | + ImageSize int `json:"imageSize"` |
| 27 | + LastUpdateTime time.Time `json:"lastUpdateTime"` |
| 28 | + MediaType string `json:"mediaType"` |
| 29 | + Os string `json:"os"` |
| 30 | + Tags []string `json:"tags"` |
| 31 | +} |
| 32 | + |
| 33 | +const Layout = "2006-01-02T15:04:05" |
| 34 | + |
| 35 | +func isImageRunningInCluster(clusterImages []string, imageToDelete ImageMetadata, repository string) (string, error) { |
| 36 | + for _, clusterImage := range clusterImages { |
| 37 | + for _, tag := range imageToDelete.Tags { |
| 38 | + if strings.Contains(clusterImage, fmt.Sprintf("%s:%s", repository, tag)) { |
| 39 | + return clusterImage, fmt.Errorf("image is running in your provided k8s clusters") |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return "", nil |
| 45 | +} |
| 46 | + |
| 47 | +func main() { |
| 48 | + registryName := flag.String("registry", "", "Name of the Azure Container Registry") |
| 49 | + repositoryName := flag.String("repository", "", "Name of the repository in your registry") |
| 50 | + subscriptionId := flag.String("subscription", "", "ID of the subscription. If not specified it will use the default one") |
| 51 | + contexts := flag.String("contexts", "", "Comma-separated list of Kubernetes contexts. The deletion process will not start if any 'imageToDelete' is running in a cluster from the context list") |
| 52 | + deletionCutoffTimestamp := flag.String("timestamp", "01/01/2024", "All Images before the timestamp will get deleted") |
| 53 | + delay := flag.Float64("delay", 1, "Delay between deletion requests") |
| 54 | + dryRunMode := flag.Bool("dry-run", false, "Perform a dry run, print tags to be deleted but do not delete them") |
| 55 | + flag.Parse() |
| 56 | + |
| 57 | + if *repositoryName == "" || *registryName == "" { |
| 58 | + log.Println("You must provide the registry and repository") |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + if *subscriptionId != "" { |
| 63 | + _, err := exec.Command("bash", "-c", fmt.Sprintf("az account set --subscription %s", *subscriptionId)).Output() |
| 64 | + if err != nil { |
| 65 | + log.Println("Failed to set az subscription: ", err) |
| 66 | + return |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + var k8sImages []string |
| 71 | + if len(*contexts) >= 0 { |
| 72 | + for _, context := range strings.Split(*contexts, ",") { |
| 73 | + output, err := exec.Command( |
| 74 | + "bash", |
| 75 | + "-c", |
| 76 | + fmt.Sprintf("kubectl get pods --context %s --all-namespaces -o jsonpath=\"{.items[*].spec.containers[*].image}\"", context), |
| 77 | + ).Output() |
| 78 | + if err != nil { |
| 79 | + log.Println("Failed to set az subscription: ", err) |
| 80 | + return |
| 81 | + } |
| 82 | + |
| 83 | + for _, image := range strings.Split(string(output), " ") { |
| 84 | + k8sImages = append(k8sImages, image) |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + parsedDate, err := dateparse.ParseAny(*deletionCutoffTimestamp) |
| 90 | + if err != nil { |
| 91 | + log.Println("Unable to parse the provided date: ", err) |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + listManifestsCmd := fmt.Sprintf( |
| 96 | + "az acr manifest list-metadata --name %s --registry %s --orderby time_asc --query \"[?lastUpdateTime < '%s']\"", |
| 97 | + *repositoryName, *registryName, parsedDate.Format(Layout), |
| 98 | + ) |
| 99 | + |
| 100 | + manifestInformation, err := exec.Command("bash", "-c", listManifestsCmd).Output() |
| 101 | + if err != nil { |
| 102 | + log.Println("Failed to retrieve manifest information: ", err) |
| 103 | + } |
| 104 | + |
| 105 | + var imageMetadataList []ImageMetadata |
| 106 | + err = json.Unmarshal(manifestInformation, &imageMetadataList) |
| 107 | + if err != nil { |
| 108 | + log.Println("Error reading metadata: ", err) |
| 109 | + return |
| 110 | + } |
| 111 | + |
| 112 | + if len(imageMetadataList) == 0 { |
| 113 | + log.Printf("No Docker Images found which succeed the deletionCutoffTimestamp %s\n", parsedDate) |
| 114 | + return |
| 115 | + } |
| 116 | + |
| 117 | + var imagesToDelete []ImageMetadata |
| 118 | + for _, metadata := range imageMetadataList { |
| 119 | + if len(metadata.Tags) == 0 { |
| 120 | + continue |
| 121 | + } |
| 122 | + |
| 123 | + if len(k8sImages) != 0 { |
| 124 | + image, err := isImageRunningInCluster(k8sImages, metadata, *repositoryName) |
| 125 | + if err != nil { |
| 126 | + log.Fatalf("Error: The Image %s is running in one of your cluster. Please reconsider your deletion timestamp. \n", image) |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + if *dryRunMode { |
| 131 | + log.Printf("[DRY-RUN] Docker Image %s with tags %s would get deleted. Created Time: %s \n", *repositoryName, strings.Join(metadata.Tags, ","), metadata.CreatedTime) |
| 132 | + continue |
| 133 | + } |
| 134 | + |
| 135 | + if len(metadata.Digest) > 0 { |
| 136 | + imagesToDelete = append(imagesToDelete, metadata) |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + if len(imagesToDelete) == 0 { |
| 141 | + return |
| 142 | + } |
| 143 | + |
| 144 | + amountImages := 0 |
| 145 | + for _, imageToDelete := range imagesToDelete { |
| 146 | + log.Printf("Docker Image %s with tags %s will get deleted. Created Time: %s \n", *repositoryName, strings.Join(imageToDelete.Tags, ","), imageToDelete.CreatedTime) |
| 147 | + amountImages++ |
| 148 | + } |
| 149 | + |
| 150 | + log.Printf("%d Images will get deleted. Do you want to perfom the deletion? Please answer with yes\n", amountImages) |
| 151 | + |
| 152 | + var response string |
| 153 | + _, err = fmt.Scanln(&response) |
| 154 | + if err != nil { |
| 155 | + log.Println("Unable to read user input") |
| 156 | + return |
| 157 | + } |
| 158 | + |
| 159 | + if response != "yes" { |
| 160 | + log.Println("Goodbye!") |
| 161 | + return |
| 162 | + } |
| 163 | + |
| 164 | + log.Printf("Starting deletion process with a delay of %f s \n", *delay) |
| 165 | + for _, imageToDelete := range imagesToDelete { |
| 166 | + if len(imageToDelete.Digest) == 0 { |
| 167 | + log.Printf("Skipping image with tags: %s since it has not digest \n", strings.Join(imageToDelete.Tags, ",")) |
| 168 | + } |
| 169 | + |
| 170 | + deleteManifest := fmt.Sprintf( |
| 171 | + "az acr repository delete --name %s --image %s@%s --yes", |
| 172 | + *registryName, *repositoryName, imageToDelete.Digest, |
| 173 | + ) |
| 174 | + _, err := exec.Command("bash", "-c", deleteManifest).Output() |
| 175 | + if err != nil { |
| 176 | + log.Printf("Error fulfilling deletion command: %s\n", err) |
| 177 | + } |
| 178 | + |
| 179 | + log.Printf("Deleted image %s with tags: %s \n", *repositoryName, strings.Join(imageToDelete.Tags, ",")) |
| 180 | + time.Sleep(time.Second * time.Duration(*delay)) |
| 181 | + } |
| 182 | + |
| 183 | + log.Printf("Done. Goodbye!") |
| 184 | +} |
0 commit comments