Skip to content

Commit acb321e

Browse files
authored
Merge pull request kubernetes#78594 from benmoss/windows-kubelet-memory-leak
Fix memory leak from not closing hcs containers
2 parents f532d5c + 1fcad1b commit acb321e

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

pkg/kubelet/stats/cri_stats_provider_windows.go

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ limitations under the License.
1919
package stats
2020

2121
import (
22+
"fmt"
2223
"time"
2324

2425
"github.com/Microsoft/hcsshim"
@@ -40,18 +41,11 @@ func (p *criStatsProvider) listContainerNetworkStats() (map[string]*statsapi.Net
4041

4142
stats := make(map[string]*statsapi.NetworkStats)
4243
for _, c := range containers {
43-
container, err := hcsshim.OpenContainer(c.ID)
44+
cstats, err := fetchContainerStats(c)
4445
if err != nil {
45-
klog.V(4).Infof("Failed to open container %q with error '%v', continue to get stats for other containers", c.ID, err)
46+
klog.V(4).Infof("Failed to fetch statistics for container %q with error '%v', continue to get stats for other containers", c.ID, err)
4647
continue
4748
}
48-
49-
cstats, err := container.Statistics()
50-
if err != nil {
51-
klog.V(4).Infof("Failed to get statistics for container %q with error '%v', continue to get stats for other containers", c.ID, err)
52-
continue
53-
}
54-
5549
if len(cstats.Network) > 0 {
5650
stats[c.ID] = hcsStatsToNetworkStats(cstats.Timestamp, cstats.Network)
5751
}
@@ -60,6 +54,27 @@ func (p *criStatsProvider) listContainerNetworkStats() (map[string]*statsapi.Net
6054
return stats, nil
6155
}
6256

57+
func fetchContainerStats(c hcsshim.ContainerProperties) (stats hcsshim.Statistics, err error) {
58+
var (
59+
container hcsshim.Container
60+
)
61+
container, err = hcsshim.OpenContainer(c.ID)
62+
if err != nil {
63+
return
64+
}
65+
defer func() {
66+
if closeErr := container.Close(); closeErr != nil {
67+
if err != nil {
68+
err = fmt.Errorf("failed to close container after error %v; close error: %v", err, closeErr)
69+
} else {
70+
err = closeErr
71+
}
72+
}
73+
}()
74+
75+
return container.Statistics()
76+
}
77+
6378
// hcsStatsToNetworkStats converts hcsshim.Statistics.Network to statsapi.NetworkStats
6479
func hcsStatsToNetworkStats(timestamp time.Time, hcsStats []hcsshim.NetworkStats) *statsapi.NetworkStats {
6580
result := &statsapi.NetworkStats{

0 commit comments

Comments
 (0)