cri_stats_provider_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package stats
  14. import (
  15. "math/rand"
  16. "os"
  17. "path/filepath"
  18. "runtime"
  19. "testing"
  20. "time"
  21. gomock "github.com/golang/mock/gomock"
  22. cadvisorfs "github.com/google/cadvisor/fs"
  23. cadvisorapiv2 "github.com/google/cadvisor/info/v2"
  24. "github.com/stretchr/testify/assert"
  25. "k8s.io/apimachinery/pkg/api/resource"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/types"
  28. "k8s.io/apimachinery/pkg/util/uuid"
  29. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  30. critest "k8s.io/cri-api/pkg/apis/testing"
  31. statsapi "k8s.io/kubernetes/pkg/kubelet/apis/stats/v1alpha1"
  32. cadvisortest "k8s.io/kubernetes/pkg/kubelet/cadvisor/testing"
  33. "k8s.io/kubernetes/pkg/kubelet/cm"
  34. kubecontainertest "k8s.io/kubernetes/pkg/kubelet/container/testing"
  35. "k8s.io/kubernetes/pkg/kubelet/kuberuntime"
  36. "k8s.io/kubernetes/pkg/kubelet/leaky"
  37. kubepodtest "k8s.io/kubernetes/pkg/kubelet/pod/testing"
  38. serverstats "k8s.io/kubernetes/pkg/kubelet/server/stats"
  39. "k8s.io/kubernetes/pkg/volume"
  40. )
  41. const (
  42. offsetInodeUsage = iota
  43. offsetUsage
  44. )
  45. const (
  46. seedRoot = 0
  47. seedKubelet = 200
  48. seedMisc = 300
  49. seedSandbox0 = 1000
  50. seedContainer0 = 2000
  51. seedSandbox1 = 3000
  52. seedContainer1 = 4000
  53. seedContainer2 = 5000
  54. seedSandbox2 = 6000
  55. seedContainer3 = 7000
  56. seedSandbox3 = 8000
  57. seedContainer5 = 9000
  58. )
  59. const (
  60. pName0 = "pod0"
  61. pName1 = "pod1"
  62. pName2 = "pod2"
  63. pName3 = "pod3"
  64. )
  65. const (
  66. cName0 = "container0-name"
  67. cName1 = "container1-name"
  68. cName2 = "container2-name"
  69. cName3 = "container3-name"
  70. cName5 = "container5-name"
  71. cName6 = "container6-name"
  72. cName7 = "container7-name"
  73. )
  74. func TestCRIListPodStats(t *testing.T) {
  75. var (
  76. imageFsMountpoint = "/test/mount/point"
  77. unknownMountpoint = "/unknown/mount/point"
  78. imageFsInfo = getTestFsInfo(2000)
  79. rootFsInfo = getTestFsInfo(1000)
  80. sandbox0 = makeFakePodSandbox("sandbox0-name", "sandbox0-uid", "sandbox0-ns", false)
  81. sandbox0Cgroup = "/" + cm.GetPodCgroupNameSuffix(types.UID(sandbox0.PodSandboxStatus.Metadata.Uid))
  82. container0 = makeFakeContainer(sandbox0, cName0, 0, false)
  83. containerStats0 = makeFakeContainerStats(container0, imageFsMountpoint)
  84. containerLogStats0 = makeFakeLogStats(1000)
  85. container1 = makeFakeContainer(sandbox0, cName1, 0, false)
  86. containerStats1 = makeFakeContainerStats(container1, unknownMountpoint)
  87. containerLogStats1 = makeFakeLogStats(2000)
  88. sandbox1 = makeFakePodSandbox("sandbox1-name", "sandbox1-uid", "sandbox1-ns", false)
  89. sandbox1Cgroup = "/" + cm.GetPodCgroupNameSuffix(types.UID(sandbox1.PodSandboxStatus.Metadata.Uid))
  90. container2 = makeFakeContainer(sandbox1, cName2, 0, false)
  91. containerStats2 = makeFakeContainerStats(container2, imageFsMountpoint)
  92. containerLogStats2 = makeFakeLogStats(3000)
  93. sandbox2 = makeFakePodSandbox("sandbox2-name", "sandbox2-uid", "sandbox2-ns", false)
  94. sandbox2Cgroup = "/" + cm.GetPodCgroupNameSuffix(types.UID(sandbox2.PodSandboxStatus.Metadata.Uid))
  95. container3 = makeFakeContainer(sandbox2, cName3, 0, true)
  96. containerStats3 = makeFakeContainerStats(container3, imageFsMountpoint)
  97. container4 = makeFakeContainer(sandbox2, cName3, 1, false)
  98. containerStats4 = makeFakeContainerStats(container4, imageFsMountpoint)
  99. containerLogStats4 = makeFakeLogStats(4000)
  100. sandbox3 = makeFakePodSandbox("sandbox3-name", "sandbox3-uid", "sandbox3-ns", false)
  101. container5 = makeFakeContainer(sandbox3, cName5, 0, true)
  102. containerStats5 = makeFakeContainerStats(container5, imageFsMountpoint)
  103. containerLogStats5 = makeFakeLogStats(5000)
  104. // Terminated pod sandbox
  105. sandbox4 = makeFakePodSandbox("sandbox1-name", "sandbox1-uid", "sandbox1-ns", true)
  106. container6 = makeFakeContainer(sandbox4, cName6, 0, true)
  107. containerStats6 = makeFakeContainerStats(container6, imageFsMountpoint)
  108. // Terminated pod
  109. sandbox5 = makeFakePodSandbox("sandbox1-name", "sandbox5-uid", "sandbox1-ns", true)
  110. container7 = makeFakeContainer(sandbox5, cName7, 0, true)
  111. containerStats7 = makeFakeContainerStats(container7, imageFsMountpoint)
  112. podLogName0 = "pod-log-0"
  113. podLogName1 = "pod-log-1"
  114. podLogStats0 = makeFakeLogStats(5000)
  115. podLogStats1 = makeFakeLogStats(6000)
  116. )
  117. var (
  118. mockCadvisor = new(cadvisortest.Mock)
  119. mockRuntimeCache = new(kubecontainertest.MockRuntimeCache)
  120. mockPodManager = new(kubepodtest.MockManager)
  121. resourceAnalyzer = new(fakeResourceAnalyzer)
  122. fakeRuntimeService = critest.NewFakeRuntimeService()
  123. fakeImageService = critest.NewFakeImageService()
  124. )
  125. infos := map[string]cadvisorapiv2.ContainerInfo{
  126. "/": getTestContainerInfo(seedRoot, "", "", ""),
  127. "/kubelet": getTestContainerInfo(seedKubelet, "", "", ""),
  128. "/system": getTestContainerInfo(seedMisc, "", "", ""),
  129. sandbox0.PodSandboxStatus.Id: getTestContainerInfo(seedSandbox0, pName0, sandbox0.PodSandboxStatus.Metadata.Namespace, leaky.PodInfraContainerName),
  130. sandbox0Cgroup: getTestContainerInfo(seedSandbox0, "", "", ""),
  131. container0.ContainerStatus.Id: getTestContainerInfo(seedContainer0, pName0, sandbox0.PodSandboxStatus.Metadata.Namespace, cName0),
  132. container1.ContainerStatus.Id: getTestContainerInfo(seedContainer1, pName0, sandbox0.PodSandboxStatus.Metadata.Namespace, cName1),
  133. sandbox1.PodSandboxStatus.Id: getTestContainerInfo(seedSandbox1, pName1, sandbox1.PodSandboxStatus.Metadata.Namespace, leaky.PodInfraContainerName),
  134. sandbox1Cgroup: getTestContainerInfo(seedSandbox1, "", "", ""),
  135. container2.ContainerStatus.Id: getTestContainerInfo(seedContainer2, pName1, sandbox1.PodSandboxStatus.Metadata.Namespace, cName2),
  136. sandbox2.PodSandboxStatus.Id: getTestContainerInfo(seedSandbox2, pName2, sandbox2.PodSandboxStatus.Metadata.Namespace, leaky.PodInfraContainerName),
  137. sandbox2Cgroup: getTestContainerInfo(seedSandbox2, "", "", ""),
  138. container4.ContainerStatus.Id: getTestContainerInfo(seedContainer3, pName2, sandbox2.PodSandboxStatus.Metadata.Namespace, cName3),
  139. }
  140. options := cadvisorapiv2.RequestOptions{
  141. IdType: cadvisorapiv2.TypeName,
  142. Count: 2,
  143. Recursive: true,
  144. }
  145. mockCadvisor.
  146. On("ContainerInfoV2", "/", options).Return(infos, nil).
  147. On("RootFsInfo").Return(rootFsInfo, nil).
  148. On("GetDirFsInfo", imageFsMountpoint).Return(imageFsInfo, nil).
  149. On("GetDirFsInfo", unknownMountpoint).Return(cadvisorapiv2.FsInfo{}, cadvisorfs.ErrNoSuchDevice)
  150. fakeRuntimeService.SetFakeSandboxes([]*critest.FakePodSandbox{
  151. sandbox0, sandbox1, sandbox2, sandbox3, sandbox4, sandbox5,
  152. })
  153. fakeRuntimeService.SetFakeContainers([]*critest.FakeContainer{
  154. container0, container1, container2, container3, container4, container5, container6, container7,
  155. })
  156. fakeRuntimeService.SetFakeContainerStats([]*runtimeapi.ContainerStats{
  157. containerStats0, containerStats1, containerStats2, containerStats3, containerStats4, containerStats5, containerStats6, containerStats7,
  158. })
  159. ephemeralVolumes := makeFakeVolumeStats([]string{"ephVolume1, ephVolumes2"})
  160. persistentVolumes := makeFakeVolumeStats([]string{"persisVolume1, persisVolumes2"})
  161. resourceAnalyzer.podVolumeStats = serverstats.PodVolumeStats{
  162. EphemeralVolumes: ephemeralVolumes,
  163. PersistentVolumes: persistentVolumes,
  164. }
  165. fakeLogStats := map[string]*volume.Metrics{
  166. kuberuntime.BuildContainerLogsDirectory("sandbox0-ns", "sandbox0-name", types.UID("sandbox0-uid"), cName0): containerLogStats0,
  167. kuberuntime.BuildContainerLogsDirectory("sandbox0-ns", "sandbox0-name", types.UID("sandbox0-uid"), cName1): containerLogStats1,
  168. kuberuntime.BuildContainerLogsDirectory("sandbox1-ns", "sandbox1-name", types.UID("sandbox1-uid"), cName2): containerLogStats2,
  169. kuberuntime.BuildContainerLogsDirectory("sandbox2-ns", "sandbox2-name", types.UID("sandbox2-uid"), cName3): containerLogStats4,
  170. kuberuntime.BuildContainerLogsDirectory("sandbox3-ns", "sandbox3-name", types.UID("sandbox3-uid"), cName5): containerLogStats5,
  171. filepath.Join(kuberuntime.BuildPodLogsDirectory("sandbox0-ns", "sandbox0-name", types.UID("sandbox0-uid")), podLogName0): podLogStats0,
  172. filepath.Join(kuberuntime.BuildPodLogsDirectory("sandbox1-ns", "sandbox1-name", types.UID("sandbox1-uid")), podLogName1): podLogStats1,
  173. }
  174. fakeLogStatsProvider := NewFakeLogMetricsService(fakeLogStats)
  175. ctrl := gomock.NewController(t)
  176. defer ctrl.Finish()
  177. fakeOS := &kubecontainertest.FakeOS{}
  178. fakeOS.ReadDirFn = func(path string) ([]os.FileInfo, error) {
  179. var fileInfos []os.FileInfo
  180. mockFI := kubecontainertest.NewMockFileInfo(ctrl)
  181. switch path {
  182. case kuberuntime.BuildPodLogsDirectory("sandbox0-ns", "sandbox0-name", types.UID("sandbox0-uid")):
  183. mockFI.EXPECT().Name().Return(podLogName0)
  184. case kuberuntime.BuildPodLogsDirectory("sandbox1-ns", "sandbox1-name", types.UID("sandbox1-uid")):
  185. mockFI.EXPECT().Name().Return(podLogName1)
  186. default:
  187. return nil, nil
  188. }
  189. mockFI.EXPECT().IsDir().Return(false)
  190. fileInfos = append(fileInfos, mockFI)
  191. return fileInfos, nil
  192. }
  193. provider := NewCRIStatsProvider(
  194. mockCadvisor,
  195. resourceAnalyzer,
  196. mockPodManager,
  197. mockRuntimeCache,
  198. fakeRuntimeService,
  199. fakeImageService,
  200. fakeLogStatsProvider,
  201. fakeOS,
  202. )
  203. stats, err := provider.ListPodStats()
  204. assert := assert.New(t)
  205. assert.NoError(err)
  206. assert.Equal(4, len(stats))
  207. podStatsMap := make(map[statsapi.PodReference]statsapi.PodStats)
  208. for _, s := range stats {
  209. podStatsMap[s.PodRef] = s
  210. }
  211. p0 := podStatsMap[statsapi.PodReference{Name: "sandbox0-name", UID: "sandbox0-uid", Namespace: "sandbox0-ns"}]
  212. assert.Equal(sandbox0.CreatedAt, p0.StartTime.UnixNano())
  213. assert.Equal(2, len(p0.Containers))
  214. checkEphemeralStorageStats(assert, p0, ephemeralVolumes, []*runtimeapi.ContainerStats{containerStats0, containerStats1},
  215. []*volume.Metrics{containerLogStats0, containerLogStats1}, podLogStats0)
  216. containerStatsMap := make(map[string]statsapi.ContainerStats)
  217. for _, s := range p0.Containers {
  218. containerStatsMap[s.Name] = s
  219. }
  220. c0 := containerStatsMap[cName0]
  221. assert.Equal(container0.CreatedAt, c0.StartTime.UnixNano())
  222. checkCRICPUAndMemoryStats(assert, c0, infos[container0.ContainerStatus.Id].Stats[0])
  223. checkCRIRootfsStats(assert, c0, containerStats0, &imageFsInfo)
  224. checkCRILogsStats(assert, c0, &rootFsInfo, containerLogStats0)
  225. c1 := containerStatsMap[cName1]
  226. assert.Equal(container1.CreatedAt, c1.StartTime.UnixNano())
  227. checkCRICPUAndMemoryStats(assert, c1, infos[container1.ContainerStatus.Id].Stats[0])
  228. checkCRIRootfsStats(assert, c1, containerStats1, nil)
  229. checkCRILogsStats(assert, c1, &rootFsInfo, containerLogStats1)
  230. checkCRINetworkStats(assert, p0.Network, infos[sandbox0.PodSandboxStatus.Id].Stats[0].Network)
  231. checkCRIPodCPUAndMemoryStats(assert, p0, infos[sandbox0Cgroup].Stats[0])
  232. p1 := podStatsMap[statsapi.PodReference{Name: "sandbox1-name", UID: "sandbox1-uid", Namespace: "sandbox1-ns"}]
  233. assert.Equal(sandbox1.CreatedAt, p1.StartTime.UnixNano())
  234. assert.Equal(1, len(p1.Containers))
  235. checkEphemeralStorageStats(assert, p1, ephemeralVolumes, []*runtimeapi.ContainerStats{containerStats2},
  236. []*volume.Metrics{containerLogStats2}, podLogStats1)
  237. c2 := p1.Containers[0]
  238. assert.Equal(cName2, c2.Name)
  239. assert.Equal(container2.CreatedAt, c2.StartTime.UnixNano())
  240. checkCRICPUAndMemoryStats(assert, c2, infos[container2.ContainerStatus.Id].Stats[0])
  241. checkCRIRootfsStats(assert, c2, containerStats2, &imageFsInfo)
  242. checkCRILogsStats(assert, c2, &rootFsInfo, containerLogStats2)
  243. checkCRINetworkStats(assert, p1.Network, infos[sandbox1.PodSandboxStatus.Id].Stats[0].Network)
  244. checkCRIPodCPUAndMemoryStats(assert, p1, infos[sandbox1Cgroup].Stats[0])
  245. p2 := podStatsMap[statsapi.PodReference{Name: "sandbox2-name", UID: "sandbox2-uid", Namespace: "sandbox2-ns"}]
  246. assert.Equal(sandbox2.CreatedAt, p2.StartTime.UnixNano())
  247. assert.Equal(1, len(p2.Containers))
  248. checkEphemeralStorageStats(assert, p2, ephemeralVolumes, []*runtimeapi.ContainerStats{containerStats4},
  249. []*volume.Metrics{containerLogStats4}, nil)
  250. c3 := p2.Containers[0]
  251. assert.Equal(cName3, c3.Name)
  252. assert.Equal(container4.CreatedAt, c3.StartTime.UnixNano())
  253. checkCRICPUAndMemoryStats(assert, c3, infos[container4.ContainerStatus.Id].Stats[0])
  254. checkCRIRootfsStats(assert, c3, containerStats4, &imageFsInfo)
  255. checkCRILogsStats(assert, c3, &rootFsInfo, containerLogStats4)
  256. checkCRINetworkStats(assert, p2.Network, infos[sandbox2.PodSandboxStatus.Id].Stats[0].Network)
  257. checkCRIPodCPUAndMemoryStats(assert, p2, infos[sandbox2Cgroup].Stats[0])
  258. p3 := podStatsMap[statsapi.PodReference{Name: "sandbox3-name", UID: "sandbox3-uid", Namespace: "sandbox3-ns"}]
  259. assert.Equal(sandbox3.CreatedAt, p3.StartTime.UnixNano())
  260. assert.Equal(1, len(p3.Containers))
  261. c5 := p3.Containers[0]
  262. assert.Equal(cName5, c5.Name)
  263. assert.Equal(container5.CreatedAt, c5.StartTime.UnixNano())
  264. assert.NotNil(c5.CPU.Time)
  265. assert.Zero(*c5.CPU.UsageCoreNanoSeconds)
  266. assert.Zero(*c5.CPU.UsageNanoCores)
  267. assert.NotNil(c5.Memory.Time)
  268. assert.Zero(*c5.Memory.WorkingSetBytes)
  269. mockCadvisor.AssertExpectations(t)
  270. }
  271. func TestCRIListPodCPUAndMemoryStats(t *testing.T) {
  272. var (
  273. imageFsMountpoint = "/test/mount/point"
  274. unknownMountpoint = "/unknown/mount/point"
  275. sandbox0 = makeFakePodSandbox("sandbox0-name", "sandbox0-uid", "sandbox0-ns", false)
  276. sandbox0Cgroup = "/" + cm.GetPodCgroupNameSuffix(types.UID(sandbox0.PodSandboxStatus.Metadata.Uid))
  277. container0 = makeFakeContainer(sandbox0, cName0, 0, false)
  278. containerStats0 = makeFakeContainerStats(container0, imageFsMountpoint)
  279. container1 = makeFakeContainer(sandbox0, cName1, 0, false)
  280. containerStats1 = makeFakeContainerStats(container1, unknownMountpoint)
  281. sandbox1 = makeFakePodSandbox("sandbox1-name", "sandbox1-uid", "sandbox1-ns", false)
  282. sandbox1Cgroup = "/" + cm.GetPodCgroupNameSuffix(types.UID(sandbox1.PodSandboxStatus.Metadata.Uid))
  283. container2 = makeFakeContainer(sandbox1, cName2, 0, false)
  284. containerStats2 = makeFakeContainerStats(container2, imageFsMountpoint)
  285. sandbox2 = makeFakePodSandbox("sandbox2-name", "sandbox2-uid", "sandbox2-ns", false)
  286. sandbox2Cgroup = "/" + cm.GetPodCgroupNameSuffix(types.UID(sandbox2.PodSandboxStatus.Metadata.Uid))
  287. container3 = makeFakeContainer(sandbox2, cName3, 0, true)
  288. containerStats3 = makeFakeContainerStats(container3, imageFsMountpoint)
  289. container4 = makeFakeContainer(sandbox2, cName3, 1, false)
  290. containerStats4 = makeFakeContainerStats(container4, imageFsMountpoint)
  291. sandbox3 = makeFakePodSandbox("sandbox3-name", "sandbox3-uid", "sandbox3-ns", false)
  292. container5 = makeFakeContainer(sandbox3, cName5, 0, true)
  293. containerStats5 = makeFakeContainerStats(container5, imageFsMountpoint)
  294. // Terminated pod sandbox
  295. sandbox4 = makeFakePodSandbox("sandbox1-name", "sandbox1-uid", "sandbox1-ns", true)
  296. container6 = makeFakeContainer(sandbox4, cName6, 0, true)
  297. containerStats6 = makeFakeContainerStats(container6, imageFsMountpoint)
  298. // Terminated pod
  299. sandbox5 = makeFakePodSandbox("sandbox1-name", "sandbox5-uid", "sandbox1-ns", true)
  300. container7 = makeFakeContainer(sandbox5, cName7, 0, true)
  301. containerStats7 = makeFakeContainerStats(container7, imageFsMountpoint)
  302. )
  303. var (
  304. mockCadvisor = new(cadvisortest.Mock)
  305. mockRuntimeCache = new(kubecontainertest.MockRuntimeCache)
  306. mockPodManager = new(kubepodtest.MockManager)
  307. resourceAnalyzer = new(fakeResourceAnalyzer)
  308. fakeRuntimeService = critest.NewFakeRuntimeService()
  309. )
  310. infos := map[string]cadvisorapiv2.ContainerInfo{
  311. "/": getTestContainerInfo(seedRoot, "", "", ""),
  312. "/kubelet": getTestContainerInfo(seedKubelet, "", "", ""),
  313. "/system": getTestContainerInfo(seedMisc, "", "", ""),
  314. sandbox0.PodSandboxStatus.Id: getTestContainerInfo(seedSandbox0, pName0, sandbox0.PodSandboxStatus.Metadata.Namespace, leaky.PodInfraContainerName),
  315. sandbox0Cgroup: getTestContainerInfo(seedSandbox0, "", "", ""),
  316. container0.ContainerStatus.Id: getTestContainerInfo(seedContainer0, pName0, sandbox0.PodSandboxStatus.Metadata.Namespace, cName0),
  317. container1.ContainerStatus.Id: getTestContainerInfo(seedContainer1, pName0, sandbox0.PodSandboxStatus.Metadata.Namespace, cName1),
  318. sandbox1.PodSandboxStatus.Id: getTestContainerInfo(seedSandbox1, pName1, sandbox1.PodSandboxStatus.Metadata.Namespace, leaky.PodInfraContainerName),
  319. sandbox1Cgroup: getTestContainerInfo(seedSandbox1, "", "", ""),
  320. container2.ContainerStatus.Id: getTestContainerInfo(seedContainer2, pName1, sandbox1.PodSandboxStatus.Metadata.Namespace, cName2),
  321. sandbox2.PodSandboxStatus.Id: getTestContainerInfo(seedSandbox2, pName2, sandbox2.PodSandboxStatus.Metadata.Namespace, leaky.PodInfraContainerName),
  322. sandbox2Cgroup: getTestContainerInfo(seedSandbox2, "", "", ""),
  323. container4.ContainerStatus.Id: getTestContainerInfo(seedContainer3, pName2, sandbox2.PodSandboxStatus.Metadata.Namespace, cName3),
  324. }
  325. options := cadvisorapiv2.RequestOptions{
  326. IdType: cadvisorapiv2.TypeName,
  327. Count: 2,
  328. Recursive: true,
  329. }
  330. mockCadvisor.
  331. On("ContainerInfoV2", "/", options).Return(infos, nil)
  332. fakeRuntimeService.SetFakeSandboxes([]*critest.FakePodSandbox{
  333. sandbox0, sandbox1, sandbox2, sandbox3, sandbox4, sandbox5,
  334. })
  335. fakeRuntimeService.SetFakeContainers([]*critest.FakeContainer{
  336. container0, container1, container2, container3, container4, container5, container6, container7,
  337. })
  338. fakeRuntimeService.SetFakeContainerStats([]*runtimeapi.ContainerStats{
  339. containerStats0, containerStats1, containerStats2, containerStats3, containerStats4, containerStats5, containerStats6, containerStats7,
  340. })
  341. ephemeralVolumes := makeFakeVolumeStats([]string{"ephVolume1, ephVolumes2"})
  342. persistentVolumes := makeFakeVolumeStats([]string{"persisVolume1, persisVolumes2"})
  343. resourceAnalyzer.podVolumeStats = serverstats.PodVolumeStats{
  344. EphemeralVolumes: ephemeralVolumes,
  345. PersistentVolumes: persistentVolumes,
  346. }
  347. provider := NewCRIStatsProvider(
  348. mockCadvisor,
  349. resourceAnalyzer,
  350. mockPodManager,
  351. mockRuntimeCache,
  352. fakeRuntimeService,
  353. nil,
  354. nil,
  355. &kubecontainertest.FakeOS{},
  356. )
  357. stats, err := provider.ListPodCPUAndMemoryStats()
  358. assert := assert.New(t)
  359. assert.NoError(err)
  360. assert.Equal(4, len(stats))
  361. podStatsMap := make(map[statsapi.PodReference]statsapi.PodStats)
  362. for _, s := range stats {
  363. podStatsMap[s.PodRef] = s
  364. }
  365. p0 := podStatsMap[statsapi.PodReference{Name: "sandbox0-name", UID: "sandbox0-uid", Namespace: "sandbox0-ns"}]
  366. assert.Equal(sandbox0.CreatedAt, p0.StartTime.UnixNano())
  367. assert.Equal(2, len(p0.Containers))
  368. assert.Nil(p0.EphemeralStorage)
  369. assert.Nil(p0.VolumeStats)
  370. assert.Nil(p0.Network)
  371. checkCRIPodCPUAndMemoryStats(assert, p0, infos[sandbox0Cgroup].Stats[0])
  372. containerStatsMap := make(map[string]statsapi.ContainerStats)
  373. for _, s := range p0.Containers {
  374. containerStatsMap[s.Name] = s
  375. }
  376. c0 := containerStatsMap[cName0]
  377. assert.Equal(container0.CreatedAt, c0.StartTime.UnixNano())
  378. checkCRICPUAndMemoryStats(assert, c0, infos[container0.ContainerStatus.Id].Stats[0])
  379. assert.Nil(c0.Rootfs)
  380. assert.Nil(c0.Logs)
  381. assert.Nil(c0.Accelerators)
  382. assert.Nil(c0.UserDefinedMetrics)
  383. c1 := containerStatsMap[cName1]
  384. assert.Equal(container1.CreatedAt, c1.StartTime.UnixNano())
  385. checkCRICPUAndMemoryStats(assert, c1, infos[container1.ContainerStatus.Id].Stats[0])
  386. assert.Nil(c1.Rootfs)
  387. assert.Nil(c1.Logs)
  388. assert.Nil(c1.Accelerators)
  389. assert.Nil(c1.UserDefinedMetrics)
  390. p1 := podStatsMap[statsapi.PodReference{Name: "sandbox1-name", UID: "sandbox1-uid", Namespace: "sandbox1-ns"}]
  391. assert.Equal(sandbox1.CreatedAt, p1.StartTime.UnixNano())
  392. assert.Equal(1, len(p1.Containers))
  393. assert.Nil(p1.EphemeralStorage)
  394. assert.Nil(p1.VolumeStats)
  395. assert.Nil(p1.Network)
  396. checkCRIPodCPUAndMemoryStats(assert, p1, infos[sandbox1Cgroup].Stats[0])
  397. c2 := p1.Containers[0]
  398. assert.Equal(cName2, c2.Name)
  399. assert.Equal(container2.CreatedAt, c2.StartTime.UnixNano())
  400. checkCRICPUAndMemoryStats(assert, c2, infos[container2.ContainerStatus.Id].Stats[0])
  401. assert.Nil(c2.Rootfs)
  402. assert.Nil(c2.Logs)
  403. assert.Nil(c2.Accelerators)
  404. assert.Nil(c2.UserDefinedMetrics)
  405. p2 := podStatsMap[statsapi.PodReference{Name: "sandbox2-name", UID: "sandbox2-uid", Namespace: "sandbox2-ns"}]
  406. assert.Equal(sandbox2.CreatedAt, p2.StartTime.UnixNano())
  407. assert.Equal(1, len(p2.Containers))
  408. assert.Nil(p2.EphemeralStorage)
  409. assert.Nil(p2.VolumeStats)
  410. assert.Nil(p2.Network)
  411. checkCRIPodCPUAndMemoryStats(assert, p2, infos[sandbox2Cgroup].Stats[0])
  412. c3 := p2.Containers[0]
  413. assert.Equal(cName3, c3.Name)
  414. assert.Equal(container4.CreatedAt, c3.StartTime.UnixNano())
  415. checkCRICPUAndMemoryStats(assert, c3, infos[container4.ContainerStatus.Id].Stats[0])
  416. assert.Nil(c2.Rootfs)
  417. assert.Nil(c2.Logs)
  418. assert.Nil(c2.Accelerators)
  419. assert.Nil(c2.UserDefinedMetrics)
  420. p3 := podStatsMap[statsapi.PodReference{Name: "sandbox3-name", UID: "sandbox3-uid", Namespace: "sandbox3-ns"}]
  421. assert.Equal(sandbox3.CreatedAt, p3.StartTime.UnixNano())
  422. assert.Equal(1, len(p3.Containers))
  423. c5 := p3.Containers[0]
  424. assert.Equal(cName5, c5.Name)
  425. assert.Equal(container5.CreatedAt, c5.StartTime.UnixNano())
  426. assert.NotNil(c5.CPU.Time)
  427. assert.Zero(*c5.CPU.UsageCoreNanoSeconds)
  428. assert.Zero(*c5.CPU.UsageNanoCores)
  429. assert.NotNil(c5.Memory.Time)
  430. assert.Zero(*c5.Memory.WorkingSetBytes)
  431. mockCadvisor.AssertExpectations(t)
  432. }
  433. func TestCRIImagesFsStats(t *testing.T) {
  434. var (
  435. imageFsMountpoint = "/test/mount/point"
  436. imageFsInfo = getTestFsInfo(2000)
  437. imageFsUsage = makeFakeImageFsUsage(imageFsMountpoint)
  438. )
  439. var (
  440. mockCadvisor = new(cadvisortest.Mock)
  441. mockRuntimeCache = new(kubecontainertest.MockRuntimeCache)
  442. mockPodManager = new(kubepodtest.MockManager)
  443. resourceAnalyzer = new(fakeResourceAnalyzer)
  444. fakeRuntimeService = critest.NewFakeRuntimeService()
  445. fakeImageService = critest.NewFakeImageService()
  446. fakeLogStatsProvider = NewFakeLogMetricsService(nil)
  447. )
  448. mockCadvisor.On("GetDirFsInfo", imageFsMountpoint).Return(imageFsInfo, nil)
  449. fakeImageService.SetFakeFilesystemUsage([]*runtimeapi.FilesystemUsage{
  450. imageFsUsage,
  451. })
  452. provider := NewCRIStatsProvider(
  453. mockCadvisor,
  454. resourceAnalyzer,
  455. mockPodManager,
  456. mockRuntimeCache,
  457. fakeRuntimeService,
  458. fakeImageService,
  459. fakeLogStatsProvider,
  460. &kubecontainertest.FakeOS{},
  461. )
  462. stats, err := provider.ImageFsStats()
  463. assert := assert.New(t)
  464. assert.NoError(err)
  465. assert.Equal(imageFsUsage.Timestamp, stats.Time.UnixNano())
  466. assert.Equal(imageFsInfo.Available, *stats.AvailableBytes)
  467. assert.Equal(imageFsInfo.Capacity, *stats.CapacityBytes)
  468. assert.Equal(imageFsInfo.InodesFree, stats.InodesFree)
  469. assert.Equal(imageFsInfo.Inodes, stats.Inodes)
  470. assert.Equal(imageFsUsage.UsedBytes.Value, *stats.UsedBytes)
  471. assert.Equal(imageFsUsage.InodesUsed.Value, *stats.InodesUsed)
  472. mockCadvisor.AssertExpectations(t)
  473. }
  474. func makeFakePodSandbox(name, uid, namespace string, terminated bool) *critest.FakePodSandbox {
  475. p := &critest.FakePodSandbox{
  476. PodSandboxStatus: runtimeapi.PodSandboxStatus{
  477. Metadata: &runtimeapi.PodSandboxMetadata{
  478. Name: name,
  479. Uid: uid,
  480. Namespace: namespace,
  481. },
  482. State: runtimeapi.PodSandboxState_SANDBOX_READY,
  483. CreatedAt: time.Now().UnixNano(),
  484. },
  485. }
  486. if terminated {
  487. p.PodSandboxStatus.State = runtimeapi.PodSandboxState_SANDBOX_NOTREADY
  488. }
  489. p.PodSandboxStatus.Id = string(uuid.NewUUID())
  490. return p
  491. }
  492. func makeFakeContainer(sandbox *critest.FakePodSandbox, name string, attempt uint32, terminated bool) *critest.FakeContainer {
  493. sandboxID := sandbox.PodSandboxStatus.Id
  494. c := &critest.FakeContainer{
  495. SandboxID: sandboxID,
  496. ContainerStatus: runtimeapi.ContainerStatus{
  497. Metadata: &runtimeapi.ContainerMetadata{Name: name, Attempt: attempt},
  498. Image: &runtimeapi.ImageSpec{},
  499. ImageRef: "fake-image-ref",
  500. CreatedAt: time.Now().UnixNano(),
  501. },
  502. }
  503. c.ContainerStatus.Labels = map[string]string{
  504. "io.kubernetes.pod.name": sandbox.Metadata.Name,
  505. "io.kubernetes.pod.uid": sandbox.Metadata.Uid,
  506. "io.kubernetes.pod.namespace": sandbox.Metadata.Namespace,
  507. "io.kubernetes.container.name": name,
  508. }
  509. if terminated {
  510. c.ContainerStatus.State = runtimeapi.ContainerState_CONTAINER_EXITED
  511. } else {
  512. c.ContainerStatus.State = runtimeapi.ContainerState_CONTAINER_RUNNING
  513. }
  514. c.ContainerStatus.Id = string(uuid.NewUUID())
  515. return c
  516. }
  517. func makeFakeContainerStats(container *critest.FakeContainer, imageFsMountpoint string) *runtimeapi.ContainerStats {
  518. containerStats := &runtimeapi.ContainerStats{
  519. Attributes: &runtimeapi.ContainerAttributes{
  520. Id: container.ContainerStatus.Id,
  521. Metadata: container.ContainerStatus.Metadata,
  522. },
  523. WritableLayer: &runtimeapi.FilesystemUsage{
  524. Timestamp: time.Now().UnixNano(),
  525. FsId: &runtimeapi.FilesystemIdentifier{Mountpoint: imageFsMountpoint},
  526. UsedBytes: &runtimeapi.UInt64Value{Value: rand.Uint64() / 100},
  527. InodesUsed: &runtimeapi.UInt64Value{Value: rand.Uint64() / 100},
  528. },
  529. }
  530. if container.State == runtimeapi.ContainerState_CONTAINER_EXITED {
  531. containerStats.Cpu = nil
  532. containerStats.Memory = nil
  533. } else {
  534. containerStats.Cpu = &runtimeapi.CpuUsage{
  535. Timestamp: time.Now().UnixNano(),
  536. UsageCoreNanoSeconds: &runtimeapi.UInt64Value{Value: rand.Uint64()},
  537. }
  538. containerStats.Memory = &runtimeapi.MemoryUsage{
  539. Timestamp: time.Now().UnixNano(),
  540. WorkingSetBytes: &runtimeapi.UInt64Value{Value: rand.Uint64()},
  541. }
  542. }
  543. return containerStats
  544. }
  545. func makeFakeImageFsUsage(fsMountpoint string) *runtimeapi.FilesystemUsage {
  546. return &runtimeapi.FilesystemUsage{
  547. Timestamp: time.Now().UnixNano(),
  548. FsId: &runtimeapi.FilesystemIdentifier{Mountpoint: fsMountpoint},
  549. UsedBytes: &runtimeapi.UInt64Value{Value: rand.Uint64()},
  550. InodesUsed: &runtimeapi.UInt64Value{Value: rand.Uint64()},
  551. }
  552. }
  553. func makeFakeVolumeStats(volumeNames []string) []statsapi.VolumeStats {
  554. volumes := make([]statsapi.VolumeStats, len(volumeNames))
  555. availableBytes := rand.Uint64()
  556. capacityBytes := rand.Uint64()
  557. usedBytes := rand.Uint64() / 100
  558. inodes := rand.Uint64()
  559. inodesFree := rand.Uint64()
  560. inodesUsed := rand.Uint64() / 100
  561. for i, name := range volumeNames {
  562. fsStats := statsapi.FsStats{
  563. Time: metav1.NewTime(time.Now()),
  564. AvailableBytes: &availableBytes,
  565. CapacityBytes: &capacityBytes,
  566. UsedBytes: &usedBytes,
  567. Inodes: &inodes,
  568. InodesFree: &inodesFree,
  569. InodesUsed: &inodesUsed,
  570. }
  571. volumes[i] = statsapi.VolumeStats{
  572. FsStats: fsStats,
  573. Name: name,
  574. }
  575. }
  576. return volumes
  577. }
  578. func checkCRICPUAndMemoryStats(assert *assert.Assertions, actual statsapi.ContainerStats, cs *cadvisorapiv2.ContainerStats) {
  579. assert.Equal(cs.Timestamp.UnixNano(), actual.CPU.Time.UnixNano())
  580. assert.Equal(cs.Cpu.Usage.Total, *actual.CPU.UsageCoreNanoSeconds)
  581. assert.Equal(cs.CpuInst.Usage.Total, *actual.CPU.UsageNanoCores)
  582. assert.Equal(cs.Memory.Usage, *actual.Memory.UsageBytes)
  583. assert.Equal(cs.Memory.WorkingSet, *actual.Memory.WorkingSetBytes)
  584. assert.Equal(cs.Memory.RSS, *actual.Memory.RSSBytes)
  585. assert.Equal(cs.Memory.ContainerData.Pgfault, *actual.Memory.PageFaults)
  586. assert.Equal(cs.Memory.ContainerData.Pgmajfault, *actual.Memory.MajorPageFaults)
  587. }
  588. func checkCRIRootfsStats(assert *assert.Assertions, actual statsapi.ContainerStats, cs *runtimeapi.ContainerStats, imageFsInfo *cadvisorapiv2.FsInfo) {
  589. assert.Equal(cs.WritableLayer.Timestamp, actual.Rootfs.Time.UnixNano())
  590. if imageFsInfo != nil {
  591. assert.Equal(imageFsInfo.Available, *actual.Rootfs.AvailableBytes)
  592. assert.Equal(imageFsInfo.Capacity, *actual.Rootfs.CapacityBytes)
  593. assert.Equal(*imageFsInfo.InodesFree, *actual.Rootfs.InodesFree)
  594. assert.Equal(*imageFsInfo.Inodes, *actual.Rootfs.Inodes)
  595. } else {
  596. assert.Nil(actual.Rootfs.AvailableBytes)
  597. assert.Nil(actual.Rootfs.CapacityBytes)
  598. assert.Nil(actual.Rootfs.InodesFree)
  599. assert.Nil(actual.Rootfs.Inodes)
  600. }
  601. assert.Equal(cs.WritableLayer.UsedBytes.Value, *actual.Rootfs.UsedBytes)
  602. assert.Equal(cs.WritableLayer.InodesUsed.Value, *actual.Rootfs.InodesUsed)
  603. }
  604. func checkCRILogsStats(assert *assert.Assertions, actual statsapi.ContainerStats, rootFsInfo *cadvisorapiv2.FsInfo, logStats *volume.Metrics) {
  605. assert.Equal(rootFsInfo.Timestamp, actual.Logs.Time.Time)
  606. assert.Equal(rootFsInfo.Available, *actual.Logs.AvailableBytes)
  607. assert.Equal(rootFsInfo.Capacity, *actual.Logs.CapacityBytes)
  608. assert.Equal(*rootFsInfo.InodesFree, *actual.Logs.InodesFree)
  609. assert.Equal(*rootFsInfo.Inodes, *actual.Logs.Inodes)
  610. assert.Equal(uint64(logStats.Used.Value()), *actual.Logs.UsedBytes)
  611. assert.Equal(uint64(logStats.InodesUsed.Value()), *actual.Logs.InodesUsed)
  612. }
  613. func checkEphemeralStorageStats(assert *assert.Assertions,
  614. actual statsapi.PodStats,
  615. volumes []statsapi.VolumeStats,
  616. containers []*runtimeapi.ContainerStats,
  617. containerLogStats []*volume.Metrics,
  618. podLogStats *volume.Metrics) {
  619. var totalUsed, inodesUsed uint64
  620. for _, container := range containers {
  621. totalUsed = totalUsed + container.WritableLayer.UsedBytes.Value
  622. inodesUsed = inodesUsed + container.WritableLayer.InodesUsed.Value
  623. }
  624. for _, volume := range volumes {
  625. totalUsed = totalUsed + *volume.FsStats.UsedBytes
  626. inodesUsed = inodesUsed + *volume.FsStats.InodesUsed
  627. }
  628. for _, logStats := range containerLogStats {
  629. totalUsed = totalUsed + uint64(logStats.Used.Value())
  630. inodesUsed = inodesUsed + uint64(logStats.InodesUsed.Value())
  631. }
  632. if podLogStats != nil {
  633. totalUsed = totalUsed + uint64(podLogStats.Used.Value())
  634. inodesUsed = inodesUsed + uint64(podLogStats.InodesUsed.Value())
  635. }
  636. assert.Equal(int(totalUsed), int(*actual.EphemeralStorage.UsedBytes))
  637. assert.Equal(int(inodesUsed), int(*actual.EphemeralStorage.InodesUsed))
  638. }
  639. func checkCRINetworkStats(assert *assert.Assertions, actual *statsapi.NetworkStats, expected *cadvisorapiv2.NetworkStats) {
  640. assert.Equal(expected.Interfaces[0].RxBytes, *actual.RxBytes)
  641. assert.Equal(expected.Interfaces[0].RxErrors, *actual.RxErrors)
  642. assert.Equal(expected.Interfaces[0].TxBytes, *actual.TxBytes)
  643. assert.Equal(expected.Interfaces[0].TxErrors, *actual.TxErrors)
  644. }
  645. func checkCRIPodCPUAndMemoryStats(assert *assert.Assertions, actual statsapi.PodStats, cs *cadvisorapiv2.ContainerStats) {
  646. if runtime.GOOS != "linux" {
  647. return
  648. }
  649. assert.Equal(cs.Timestamp.UnixNano(), actual.CPU.Time.UnixNano())
  650. assert.Equal(cs.Cpu.Usage.Total, *actual.CPU.UsageCoreNanoSeconds)
  651. assert.Equal(cs.CpuInst.Usage.Total, *actual.CPU.UsageNanoCores)
  652. assert.Equal(cs.Memory.Usage, *actual.Memory.UsageBytes)
  653. assert.Equal(cs.Memory.WorkingSet, *actual.Memory.WorkingSetBytes)
  654. assert.Equal(cs.Memory.RSS, *actual.Memory.RSSBytes)
  655. assert.Equal(cs.Memory.ContainerData.Pgfault, *actual.Memory.PageFaults)
  656. assert.Equal(cs.Memory.ContainerData.Pgmajfault, *actual.Memory.MajorPageFaults)
  657. }
  658. func makeFakeLogStats(seed int) *volume.Metrics {
  659. m := &volume.Metrics{}
  660. m.Used = resource.NewQuantity(int64(seed+offsetUsage), resource.BinarySI)
  661. m.InodesUsed = resource.NewQuantity(int64(seed+offsetInodeUsage), resource.BinarySI)
  662. return m
  663. }
  664. func TestGetContainerUsageNanoCores(t *testing.T) {
  665. var value0 uint64
  666. var value1 uint64 = 10000000000
  667. tests := []struct {
  668. desc string
  669. cpuUsageCache map[string]*cpuUsageRecord
  670. stats *runtimeapi.ContainerStats
  671. expected *uint64
  672. }{
  673. {
  674. desc: "should return nil if stats is nil",
  675. cpuUsageCache: map[string]*cpuUsageRecord{},
  676. },
  677. {
  678. desc: "should return nil if cpu stats is nil",
  679. cpuUsageCache: map[string]*cpuUsageRecord{},
  680. stats: &runtimeapi.ContainerStats{
  681. Attributes: &runtimeapi.ContainerAttributes{
  682. Id: "1",
  683. },
  684. Cpu: nil,
  685. },
  686. },
  687. {
  688. desc: "should return nil if usageCoreNanoSeconds is nil",
  689. cpuUsageCache: map[string]*cpuUsageRecord{},
  690. stats: &runtimeapi.ContainerStats{
  691. Attributes: &runtimeapi.ContainerAttributes{
  692. Id: "1",
  693. },
  694. Cpu: &runtimeapi.CpuUsage{
  695. Timestamp: 1,
  696. UsageCoreNanoSeconds: nil,
  697. },
  698. },
  699. },
  700. {
  701. desc: "should return nil if cpu stats is not cached yet",
  702. cpuUsageCache: map[string]*cpuUsageRecord{},
  703. stats: &runtimeapi.ContainerStats{
  704. Attributes: &runtimeapi.ContainerAttributes{
  705. Id: "1",
  706. },
  707. Cpu: &runtimeapi.CpuUsage{
  708. Timestamp: 1,
  709. UsageCoreNanoSeconds: &runtimeapi.UInt64Value{
  710. Value: 10000000000,
  711. },
  712. },
  713. },
  714. },
  715. {
  716. desc: "should return zero value if cached cpu stats is equal to current value",
  717. stats: &runtimeapi.ContainerStats{
  718. Attributes: &runtimeapi.ContainerAttributes{
  719. Id: "1",
  720. },
  721. Cpu: &runtimeapi.CpuUsage{
  722. Timestamp: 1,
  723. UsageCoreNanoSeconds: &runtimeapi.UInt64Value{
  724. Value: 10000000000,
  725. },
  726. },
  727. },
  728. cpuUsageCache: map[string]*cpuUsageRecord{
  729. "1": {
  730. stats: &runtimeapi.CpuUsage{
  731. Timestamp: 0,
  732. UsageCoreNanoSeconds: &runtimeapi.UInt64Value{
  733. Value: 10000000000,
  734. },
  735. },
  736. },
  737. },
  738. expected: &value0,
  739. },
  740. {
  741. desc: "should return correct value if cached cpu stats is not equal to current value",
  742. stats: &runtimeapi.ContainerStats{
  743. Attributes: &runtimeapi.ContainerAttributes{
  744. Id: "1",
  745. },
  746. Cpu: &runtimeapi.CpuUsage{
  747. Timestamp: int64(time.Second / time.Nanosecond),
  748. UsageCoreNanoSeconds: &runtimeapi.UInt64Value{
  749. Value: 20000000000,
  750. },
  751. },
  752. },
  753. cpuUsageCache: map[string]*cpuUsageRecord{
  754. "1": {
  755. stats: &runtimeapi.CpuUsage{
  756. Timestamp: 0,
  757. UsageCoreNanoSeconds: &runtimeapi.UInt64Value{
  758. Value: 10000000000,
  759. },
  760. },
  761. },
  762. },
  763. expected: &value1,
  764. },
  765. }
  766. for _, test := range tests {
  767. provider := &criStatsProvider{cpuUsageCache: test.cpuUsageCache}
  768. // Before the update, the cached value should be nil
  769. cached := provider.getContainerUsageNanoCores(test.stats)
  770. assert.Nil(t, cached)
  771. // Update the cache and get the latest value.
  772. real := provider.getAndUpdateContainerUsageNanoCores(test.stats)
  773. assert.Equal(t, test.expected, real, test.desc)
  774. // After the update, the cached value should be up-to-date
  775. cached = provider.getContainerUsageNanoCores(test.stats)
  776. assert.Equal(t, test.expected, cached, test.desc)
  777. }
  778. }