@@ -19,6 +19,7 @@ limitations under the License.
19
19
package stats
20
20
21
21
import (
22
+ "fmt"
22
23
"time"
23
24
24
25
"github.com/Microsoft/hcsshim"
@@ -40,18 +41,11 @@ func (p *criStatsProvider) listContainerNetworkStats() (map[string]*statsapi.Net
40
41
41
42
stats := make (map [string ]* statsapi.NetworkStats )
42
43
for _ , c := range containers {
43
- container , err := hcsshim . OpenContainer ( c . ID )
44
+ cstats , err := fetchContainerStats ( c )
44
45
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 )
46
47
continue
47
48
}
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
-
55
49
if len (cstats .Network ) > 0 {
56
50
stats [c .ID ] = hcsStatsToNetworkStats (cstats .Timestamp , cstats .Network )
57
51
}
@@ -60,6 +54,27 @@ func (p *criStatsProvider) listContainerNetworkStats() (map[string]*statsapi.Net
60
54
return stats , nil
61
55
}
62
56
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
+
63
78
// hcsStatsToNetworkStats converts hcsshim.Statistics.Network to statsapi.NetworkStats
64
79
func hcsStatsToNetworkStats (timestamp time.Time , hcsStats []hcsshim.NetworkStats ) * statsapi.NetworkStats {
65
80
result := & statsapi.NetworkStats {
0 commit comments