@@ -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+
7393func (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