|
|
@@ -10,11 +10,14 @@ import com.github.dockerjava.api.model.Image;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
|
import java.io.IOException;
|
|
|
+import java.util.HashMap;
|
|
|
import java.util.List;
|
|
|
import java.util.Map;
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
/**
|
|
|
+ * 删除和运行容器依赖镜像不同 tag 的镜像
|
|
|
+ *
|
|
|
* @author reghao
|
|
|
* @date 2024-07-29 16:17:47
|
|
|
*/
|
|
|
@@ -45,18 +48,31 @@ public class ImageCleanTask implements Runnable {
|
|
|
Map<String, Image> map = docker.images().stream()
|
|
|
.collect(Collectors.toMap(Image::getId, image -> image));
|
|
|
List<InspectContainerResponse> list = docker.psAll();
|
|
|
+ // repo -> imageId
|
|
|
+ Map<String, String> repoMap = new HashMap<>();
|
|
|
for (InspectContainerResponse response : list) {
|
|
|
String imageId = response.getImageId();
|
|
|
- Boolean running = response.getState().getRunning();
|
|
|
- if (running != null && running) {
|
|
|
- Image image = map.remove(imageId);
|
|
|
- try {
|
|
|
- rmImage(image);
|
|
|
- } catch (Exception e) {
|
|
|
- e.printStackTrace();
|
|
|
+ Image image = map.get(imageId);
|
|
|
+ if (image != null) {
|
|
|
+ String[] repoTags = image.getRepoTags();
|
|
|
+ if (repoTags != null && repoTags.length > 1) {
|
|
|
+ String repo = repoTags[0].split(":")[0];
|
|
|
+ repoMap.put(repo, imageId);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ map.values().forEach(image -> {
|
|
|
+ String imageId = image.getId();
|
|
|
+ String[] repoTags = image.getRepoTags();
|
|
|
+ if (repoTags != null && repoTags.length > 1) {
|
|
|
+ String repo = repoTags[0].split(":")[0];
|
|
|
+ String imageId0 = repoMap.get(repo);
|
|
|
+ if (imageId0 != null && !imageId.equals(imageId0)) {
|
|
|
+ rmImage(image);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ });
|
|
|
}
|
|
|
|
|
|
private void rmImage(Image image) {
|