Skip to content

Commit 5b15da2

Browse files
committed
feat: remove container when pod is removed
1 parent db086ba commit 5b15da2

2 files changed

Lines changed: 29 additions & 8 deletions

File tree

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ Very nice!
4949

5050
# TODOS
5151

52-
- [ ] Pod deletion cleanup (stop containers if the pods are deleted via API)
5352
- [ ] etcd (k/v store for cluster state so restarts persist)
5453

5554
# Core Spec

pkg/kubelet/kubelet.go

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,7 @@ func (k *Kubelet) Sync() {
4646
for _, container := range containers {
4747
pod, exists := k.podStore.Get(container.Name)
4848
if !exists {
49-
log.Printf("sync: removing orphan container %s (%s)", container.Name, container.ID)
50-
if err := k.runtime.Stop(container.ID); err != nil {
51-
log.Printf("sync: failed to stop container %s: %v", container.ID, err)
52-
}
53-
if err := k.runtime.Remove(container.ID); err != nil {
54-
log.Printf("sync: failed to remove container %s: %v", container.ID, err)
55-
}
49+
k.removeContainer(container.Name, container.ID)
5650
continue
5751
}
5852

@@ -70,6 +64,32 @@ func (k *Kubelet) Sync() {
7064
}
7165
}
7266

67+
// cleanupOrphanedContainers stops and removes containers whose pods
68+
// no longer exist in the store (e.g. deleted via API or scaled down).
69+
func (k *Kubelet) cleanupOrphanedContainers() {
70+
containers, err := k.runtime.List()
71+
if err != nil {
72+
log.Printf("kubelet: failed to list containers for cleanup: %v", err)
73+
return
74+
}
75+
76+
for _, container := range containers {
77+
if _, exists := k.podStore.Get(container.Name); !exists {
78+
k.removeContainer(container.Name, container.ID)
79+
}
80+
}
81+
}
82+
83+
func (k *Kubelet) removeContainer(name string, id string) {
84+
log.Printf("kubelet: removing orphan container %s (%s)", name, id)
85+
if err := k.runtime.Stop(id); err != nil {
86+
log.Printf("kubelet: failed to stop container %s: %v", id, err)
87+
}
88+
if err := k.runtime.Remove(id); err != nil {
89+
log.Printf("kubelet: failed to remove container %s: %v", id, err)
90+
}
91+
}
92+
7393
func (k *Kubelet) Run() {
7494
k.Sync()
7595

@@ -84,6 +104,8 @@ func (k *Kubelet) Run() {
84104
}
85105
}
86106

107+
k.cleanupOrphanedContainers()
108+
87109
// polling
88110
k.updateHeartbeat()
89111
time.Sleep(POLL_INTERVAL)

0 commit comments

Comments
 (0)