helpers.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2016 Google Inc. All Rights Reserved.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package common
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "math"
  19. "os"
  20. "path"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/karrick/godirwalk"
  25. "github.com/opencontainers/runc/libcontainer/cgroups"
  26. "github.com/pkg/errors"
  27. "golang.org/x/sys/unix"
  28. "github.com/google/cadvisor/container"
  29. info "github.com/google/cadvisor/info/v1"
  30. "github.com/google/cadvisor/utils"
  31. "k8s.io/klog/v2"
  32. )
  33. func DebugInfo(watches map[string][]string) map[string][]string {
  34. out := make(map[string][]string)
  35. lines := make([]string, 0, len(watches))
  36. for containerName, cgroupWatches := range watches {
  37. lines = append(lines, fmt.Sprintf("%s:", containerName))
  38. for _, cg := range cgroupWatches {
  39. lines = append(lines, fmt.Sprintf("\t%s", cg))
  40. }
  41. }
  42. out["Inotify watches"] = lines
  43. return out
  44. }
  45. var bootTime = func() time.Time {
  46. now := time.Now()
  47. var sysinfo unix.Sysinfo_t
  48. if err := unix.Sysinfo(&sysinfo); err != nil {
  49. return now
  50. }
  51. sinceBoot := time.Duration(sysinfo.Uptime) * time.Second
  52. return now.Add(-1 * sinceBoot).Truncate(time.Minute)
  53. }()
  54. func GetSpec(cgroupPaths map[string]string, machineInfoFactory info.MachineInfoFactory, hasNetwork, hasFilesystem bool) (info.ContainerSpec, error) {
  55. return getSpecInternal(cgroupPaths, machineInfoFactory, hasNetwork, hasFilesystem, cgroups.IsCgroup2UnifiedMode())
  56. }
  57. func getSpecInternal(cgroupPaths map[string]string, machineInfoFactory info.MachineInfoFactory, hasNetwork, hasFilesystem, cgroup2UnifiedMode bool) (info.ContainerSpec, error) {
  58. var spec info.ContainerSpec
  59. // Assume unified hierarchy containers.
  60. // Get the lowest creation time from all hierarchies as the container creation time.
  61. now := time.Now()
  62. lowestTime := now
  63. for _, cgroupPathDir := range cgroupPaths {
  64. dir, err := os.Stat(cgroupPathDir)
  65. if err == nil && dir.ModTime().Before(lowestTime) {
  66. lowestTime = dir.ModTime()
  67. }
  68. // The modified time of the cgroup directory sometimes changes whenever a subcontainer is created.
  69. // eg. /docker will have creation time matching the creation of latest docker container.
  70. // Use clone_children/events as a workaround as it isn't usually modified. It is only likely changed
  71. // immediately after creating a container. If the directory modified time is lower, we use that.
  72. cgroupPathFile := path.Join(cgroupPathDir, "cgroup.clone_children")
  73. if cgroup2UnifiedMode {
  74. cgroupPathFile = path.Join(cgroupPathDir, "cgroup.events")
  75. }
  76. fi, err := os.Stat(cgroupPathFile)
  77. if err == nil && fi.ModTime().Before(lowestTime) {
  78. lowestTime = fi.ModTime()
  79. }
  80. }
  81. if lowestTime.Before(bootTime) {
  82. lowestTime = bootTime
  83. }
  84. if lowestTime != now {
  85. spec.CreationTime = lowestTime
  86. }
  87. // Get machine info.
  88. mi, err := machineInfoFactory.GetMachineInfo()
  89. if err != nil {
  90. return spec, err
  91. }
  92. // CPU.
  93. cpuRoot, ok := GetControllerPath(cgroupPaths, "cpu", cgroup2UnifiedMode)
  94. if ok {
  95. if utils.FileExists(cpuRoot) {
  96. if cgroup2UnifiedMode {
  97. spec.HasCpu = true
  98. weight := readUInt64(cpuRoot, "cpu.weight")
  99. if weight > 0 {
  100. limit, err := convertCPUWeightToCPULimit(weight)
  101. if err != nil {
  102. klog.Errorf("GetSpec: Failed to read CPULimit from %q: %s", path.Join(cpuRoot, "cpu.weight"), err)
  103. } else {
  104. spec.Cpu.Limit = limit
  105. }
  106. }
  107. max := readString(cpuRoot, "cpu.max")
  108. if max != "" {
  109. splits := strings.SplitN(max, " ", 2)
  110. if len(splits) != 2 {
  111. klog.Errorf("GetSpec: Failed to parse CPUmax from %q", path.Join(cpuRoot, "cpu.max"))
  112. } else {
  113. if splits[0] != "max" {
  114. spec.Cpu.Quota = parseUint64String(splits[0])
  115. }
  116. spec.Cpu.Period = parseUint64String(splits[1])
  117. }
  118. }
  119. } else {
  120. spec.HasCpu = true
  121. spec.Cpu.Limit = readUInt64(cpuRoot, "cpu.shares")
  122. spec.Cpu.Period = readUInt64(cpuRoot, "cpu.cfs_period_us")
  123. quota := readString(cpuRoot, "cpu.cfs_quota_us")
  124. if quota != "" && quota != "-1" {
  125. val, err := strconv.ParseUint(quota, 10, 64)
  126. if err != nil {
  127. klog.Errorf("GetSpec: Failed to parse CPUQuota from %q: %s", path.Join(cpuRoot, "cpu.cfs_quota_us"), err)
  128. } else {
  129. spec.Cpu.Quota = val
  130. }
  131. }
  132. }
  133. }
  134. }
  135. // Cpu Mask.
  136. // This will fail for non-unified hierarchies. We'll return the whole machine mask in that case.
  137. cpusetRoot, ok := GetControllerPath(cgroupPaths, "cpuset", cgroup2UnifiedMode)
  138. if ok {
  139. if utils.FileExists(cpusetRoot) {
  140. spec.HasCpu = true
  141. mask := ""
  142. if cgroup2UnifiedMode {
  143. mask = readString(cpusetRoot, "cpuset.cpus.effective")
  144. } else {
  145. mask = readString(cpusetRoot, "cpuset.cpus")
  146. }
  147. spec.Cpu.Mask = utils.FixCpuMask(mask, mi.NumCores)
  148. }
  149. }
  150. // Memory
  151. memoryRoot, ok := GetControllerPath(cgroupPaths, "memory", cgroup2UnifiedMode)
  152. if ok {
  153. if cgroup2UnifiedMode {
  154. if utils.FileExists(path.Join(memoryRoot, "memory.max")) {
  155. spec.HasMemory = true
  156. spec.Memory.Reservation = readUInt64(memoryRoot, "memory.high")
  157. spec.Memory.Limit = readUInt64(memoryRoot, "memory.max")
  158. spec.Memory.SwapLimit = readUInt64(memoryRoot, "memory.swap.max")
  159. }
  160. } else {
  161. if utils.FileExists(memoryRoot) {
  162. spec.HasMemory = true
  163. spec.Memory.Limit = readUInt64(memoryRoot, "memory.limit_in_bytes")
  164. spec.Memory.SwapLimit = readUInt64(memoryRoot, "memory.memsw.limit_in_bytes")
  165. spec.Memory.Reservation = readUInt64(memoryRoot, "memory.soft_limit_in_bytes")
  166. }
  167. }
  168. }
  169. // Hugepage
  170. hugepageRoot, ok := cgroupPaths["hugetlb"]
  171. if ok {
  172. if utils.FileExists(hugepageRoot) {
  173. spec.HasHugetlb = true
  174. }
  175. }
  176. // Processes, read it's value from pids path directly
  177. pidsRoot, ok := GetControllerPath(cgroupPaths, "pids", cgroup2UnifiedMode)
  178. if ok {
  179. if utils.FileExists(pidsRoot) {
  180. spec.HasProcesses = true
  181. spec.Processes.Limit = readUInt64(pidsRoot, "pids.max")
  182. }
  183. }
  184. spec.HasNetwork = hasNetwork
  185. spec.HasFilesystem = hasFilesystem
  186. ioControllerName := "blkio"
  187. if cgroup2UnifiedMode {
  188. ioControllerName = "io"
  189. }
  190. if blkioRoot, ok := GetControllerPath(cgroupPaths, ioControllerName, cgroup2UnifiedMode); ok && utils.FileExists(blkioRoot) {
  191. spec.HasDiskIo = true
  192. }
  193. return spec, nil
  194. }
  195. func GetControllerPath(cgroupPaths map[string]string, controllerName string, cgroup2UnifiedMode bool) (string, bool) {
  196. ok := false
  197. path := ""
  198. if cgroup2UnifiedMode {
  199. path, ok = cgroupPaths[""]
  200. } else {
  201. path, ok = cgroupPaths[controllerName]
  202. }
  203. return path, ok
  204. }
  205. func readString(dirpath string, file string) string {
  206. cgroupFile := path.Join(dirpath, file)
  207. // Read
  208. out, err := ioutil.ReadFile(cgroupFile)
  209. if err != nil {
  210. // Ignore non-existent files
  211. if !os.IsNotExist(err) {
  212. klog.Warningf("readString: Failed to read %q: %s", cgroupFile, err)
  213. }
  214. return ""
  215. }
  216. return strings.TrimSpace(string(out))
  217. }
  218. // Convert from [1-10000] to [2-262144]
  219. func convertCPUWeightToCPULimit(weight uint64) (uint64, error) {
  220. const (
  221. // minWeight is the lowest value possible for cpu.weight
  222. minWeight = 1
  223. // maxWeight is the highest value possible for cpu.weight
  224. maxWeight = 10000
  225. )
  226. if weight < minWeight || weight > maxWeight {
  227. return 0, fmt.Errorf("convertCPUWeightToCPULimit: invalid cpu weight: %v", weight)
  228. }
  229. return 2 + ((weight-1)*262142)/9999, nil
  230. }
  231. func parseUint64String(strValue string) uint64 {
  232. if strValue == "max" {
  233. return math.MaxUint64
  234. }
  235. if strValue == "" {
  236. return 0
  237. }
  238. val, err := strconv.ParseUint(strValue, 10, 64)
  239. if err != nil {
  240. klog.Errorf("parseUint64String: Failed to parse int %q: %s", strValue, err)
  241. return 0
  242. }
  243. return val
  244. }
  245. func readUInt64(dirpath string, file string) uint64 {
  246. out := readString(dirpath, file)
  247. if out == "max" {
  248. return math.MaxUint64
  249. }
  250. if out == "" {
  251. return 0
  252. }
  253. val, err := strconv.ParseUint(out, 10, 64)
  254. if err != nil {
  255. klog.Errorf("readUInt64: Failed to parse int %q from file %q: %s", out, path.Join(dirpath, file), err)
  256. return 0
  257. }
  258. return val
  259. }
  260. // Lists all directories under "path" and outputs the results as children of "parent".
  261. func ListDirectories(dirpath string, parent string, recursive bool, output map[string]struct{}) error {
  262. buf := make([]byte, godirwalk.MinimumScratchBufferSize)
  263. return listDirectories(dirpath, parent, recursive, output, buf)
  264. }
  265. func listDirectories(dirpath string, parent string, recursive bool, output map[string]struct{}, buf []byte) error {
  266. dirents, err := godirwalk.ReadDirents(dirpath, buf)
  267. if err != nil {
  268. // Ignore if this hierarchy does not exist.
  269. if os.IsNotExist(errors.Cause(err)) {
  270. err = nil
  271. }
  272. return err
  273. }
  274. for _, dirent := range dirents {
  275. // We only grab directories.
  276. if !dirent.IsDir() {
  277. continue
  278. }
  279. dirname := dirent.Name()
  280. name := path.Join(parent, dirname)
  281. output[name] = struct{}{}
  282. // List subcontainers if asked to.
  283. if recursive {
  284. err := listDirectories(path.Join(dirpath, dirname), name, true, output, buf)
  285. if err != nil {
  286. return err
  287. }
  288. }
  289. }
  290. return nil
  291. }
  292. func MakeCgroupPaths(mountPoints map[string]string, name string) map[string]string {
  293. cgroupPaths := make(map[string]string, len(mountPoints))
  294. for key, val := range mountPoints {
  295. cgroupPaths[key] = path.Join(val, name)
  296. }
  297. return cgroupPaths
  298. }
  299. func CgroupExists(cgroupPaths map[string]string) bool {
  300. // If any cgroup exists, the container is still alive.
  301. for _, cgroupPath := range cgroupPaths {
  302. if utils.FileExists(cgroupPath) {
  303. return true
  304. }
  305. }
  306. return false
  307. }
  308. func ListContainers(name string, cgroupPaths map[string]string, listType container.ListType) ([]info.ContainerReference, error) {
  309. containers := make(map[string]struct{})
  310. for _, cgroupPath := range cgroupPaths {
  311. err := ListDirectories(cgroupPath, name, listType == container.ListRecursive, containers)
  312. if err != nil {
  313. return nil, err
  314. }
  315. }
  316. // Make into container references.
  317. ret := make([]info.ContainerReference, 0, len(containers))
  318. for cont := range containers {
  319. ret = append(ret, info.ContainerReference{
  320. Name: cont,
  321. })
  322. }
  323. return ret, nil
  324. }
  325. // AssignDeviceNamesToDiskStats assigns the Device field on the provided DiskIoStats by looking up
  326. // the device major and minor identifiers in the provided device namer.
  327. func AssignDeviceNamesToDiskStats(namer DeviceNamer, stats *info.DiskIoStats) {
  328. assignDeviceNamesToPerDiskStats(
  329. namer,
  330. stats.IoMerged,
  331. stats.IoQueued,
  332. stats.IoServiceBytes,
  333. stats.IoServiceTime,
  334. stats.IoServiced,
  335. stats.IoTime,
  336. stats.IoWaitTime,
  337. stats.Sectors,
  338. )
  339. }
  340. // assignDeviceNamesToPerDiskStats looks up device names for the provided stats, caching names
  341. // if necessary.
  342. func assignDeviceNamesToPerDiskStats(namer DeviceNamer, diskStats ...[]info.PerDiskStats) {
  343. devices := make(deviceIdentifierMap)
  344. for _, stats := range diskStats {
  345. for i, stat := range stats {
  346. stats[i].Device = devices.Find(stat.Major, stat.Minor, namer)
  347. }
  348. }
  349. }
  350. // DeviceNamer returns string names for devices by their major and minor id.
  351. type DeviceNamer interface {
  352. // DeviceName returns the name of the device by its major and minor ids, or false if no
  353. // such device is recognized.
  354. DeviceName(major, minor uint64) (string, bool)
  355. }
  356. type MachineInfoNamer info.MachineInfo
  357. func (n *MachineInfoNamer) DeviceName(major, minor uint64) (string, bool) {
  358. for _, info := range n.DiskMap {
  359. if info.Major == major && info.Minor == minor {
  360. return "/dev/" + info.Name, true
  361. }
  362. }
  363. for _, info := range n.Filesystems {
  364. if info.DeviceMajor == major && info.DeviceMinor == minor {
  365. return info.Device, true
  366. }
  367. }
  368. return "", false
  369. }
  370. type deviceIdentifier struct {
  371. major uint64
  372. minor uint64
  373. }
  374. type deviceIdentifierMap map[deviceIdentifier]string
  375. // Find locates the device name by device identifier out of from, caching the result as necessary.
  376. func (m deviceIdentifierMap) Find(major, minor uint64, namer DeviceNamer) string {
  377. d := deviceIdentifier{major, minor}
  378. if s, ok := m[d]; ok {
  379. return s
  380. }
  381. s, _ := namer.DeviceName(major, minor)
  382. m[d] = s
  383. return s
  384. }