helpers.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. "os"
  19. "path"
  20. "path/filepath"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/google/cadvisor/container"
  25. info "github.com/google/cadvisor/info/v1"
  26. "github.com/google/cadvisor/utils"
  27. "github.com/karrick/godirwalk"
  28. "github.com/opencontainers/runc/libcontainer/cgroups"
  29. "github.com/pkg/errors"
  30. "k8s.io/klog"
  31. )
  32. func DebugInfo(watches map[string][]string) map[string][]string {
  33. out := make(map[string][]string)
  34. lines := make([]string, 0, len(watches))
  35. for containerName, cgroupWatches := range watches {
  36. lines = append(lines, fmt.Sprintf("%s:", containerName))
  37. for _, cg := range cgroupWatches {
  38. lines = append(lines, fmt.Sprintf("\t%s", cg))
  39. }
  40. }
  41. out["Inotify watches"] = lines
  42. return out
  43. }
  44. // findFileInAncestorDir returns the path to the parent directory that contains the specified file.
  45. // "" is returned if the lookup reaches the limit.
  46. func findFileInAncestorDir(current, file, limit string) (string, error) {
  47. for {
  48. fpath := path.Join(current, file)
  49. _, err := os.Stat(fpath)
  50. if err == nil {
  51. return current, nil
  52. }
  53. if !os.IsNotExist(err) {
  54. return "", err
  55. }
  56. if current == limit {
  57. return "", nil
  58. }
  59. current = filepath.Dir(current)
  60. }
  61. }
  62. func GetSpec(cgroupPaths map[string]string, machineInfoFactory info.MachineInfoFactory, hasNetwork, hasFilesystem bool) (info.ContainerSpec, error) {
  63. var spec info.ContainerSpec
  64. // Assume unified hierarchy containers.
  65. // Get the lowest creation time from all hierarchies as the container creation time.
  66. now := time.Now()
  67. lowestTime := now
  68. for _, cgroupPath := range cgroupPaths {
  69. // The modified time of the cgroup directory changes whenever a subcontainer is created.
  70. // eg. /docker will have creation time matching the creation of latest docker container.
  71. // Use clone_children as a workaround as it isn't usually modified. It is only likely changed
  72. // immediately after creating a container.
  73. cgroupPath = path.Join(cgroupPath, "cgroup.clone_children")
  74. fi, err := os.Stat(cgroupPath)
  75. if err == nil && fi.ModTime().Before(lowestTime) {
  76. lowestTime = fi.ModTime()
  77. }
  78. }
  79. if lowestTime != now {
  80. spec.CreationTime = lowestTime
  81. }
  82. // Get machine info.
  83. mi, err := machineInfoFactory.GetMachineInfo()
  84. if err != nil {
  85. return spec, err
  86. }
  87. // CPU.
  88. cpuRoot, ok := cgroupPaths["cpu"]
  89. if ok {
  90. if utils.FileExists(cpuRoot) {
  91. spec.HasCpu = true
  92. spec.Cpu.Limit = readUInt64(cpuRoot, "cpu.shares")
  93. spec.Cpu.Period = readUInt64(cpuRoot, "cpu.cfs_period_us")
  94. quota := readString(cpuRoot, "cpu.cfs_quota_us")
  95. if quota != "" && quota != "-1" {
  96. val, err := strconv.ParseUint(quota, 10, 64)
  97. if err != nil {
  98. klog.Errorf("GetSpec: Failed to parse CPUQuota from %q: %s", path.Join(cpuRoot, "cpu.cfs_quota_us"), err)
  99. }
  100. spec.Cpu.Quota = val
  101. }
  102. }
  103. }
  104. // Cpu Mask.
  105. // This will fail for non-unified hierarchies. We'll return the whole machine mask in that case.
  106. cpusetRoot, ok := cgroupPaths["cpuset"]
  107. if ok {
  108. if utils.FileExists(cpusetRoot) {
  109. spec.HasCpu = true
  110. mask := ""
  111. if cgroups.IsCgroup2UnifiedMode() {
  112. mask = readString(cpusetRoot, "cpuset.cpus.effective")
  113. } else {
  114. mask = readString(cpusetRoot, "cpuset.cpus")
  115. }
  116. spec.Cpu.Mask = utils.FixCpuMask(mask, mi.NumCores)
  117. }
  118. }
  119. // Memory
  120. memoryRoot, ok := cgroupPaths["memory"]
  121. if ok {
  122. if !cgroups.IsCgroup2UnifiedMode() {
  123. if utils.FileExists(memoryRoot) {
  124. spec.HasMemory = true
  125. spec.Memory.Limit = readUInt64(memoryRoot, "memory.limit_in_bytes")
  126. spec.Memory.SwapLimit = readUInt64(memoryRoot, "memory.memsw.limit_in_bytes")
  127. spec.Memory.Reservation = readUInt64(memoryRoot, "memory.soft_limit_in_bytes")
  128. }
  129. } else {
  130. memoryRoot, err := findFileInAncestorDir(memoryRoot, "memory.max", "/sys/fs/cgroup")
  131. if err != nil {
  132. return spec, err
  133. }
  134. if memoryRoot != "" {
  135. spec.HasMemory = true
  136. spec.Memory.Reservation = readUInt64(memoryRoot, "memory.high")
  137. spec.Memory.Limit = readUInt64(memoryRoot, "memory.max")
  138. spec.Memory.SwapLimit = readUInt64(memoryRoot, "memory.swap.max")
  139. }
  140. }
  141. }
  142. // Processes, read it's value from pids path directly
  143. pidsRoot, ok := cgroupPaths["pids"]
  144. if ok {
  145. if utils.FileExists(pidsRoot) {
  146. spec.HasProcesses = true
  147. spec.Processes.Limit = readUInt64(pidsRoot, "pids.max")
  148. }
  149. }
  150. spec.HasNetwork = hasNetwork
  151. spec.HasFilesystem = hasFilesystem
  152. ioControllerName := "blkio"
  153. if cgroups.IsCgroup2UnifiedMode() {
  154. ioControllerName = "io"
  155. }
  156. if blkioRoot, ok := cgroupPaths[ioControllerName]; ok && utils.FileExists(blkioRoot) {
  157. spec.HasDiskIo = true
  158. }
  159. return spec, nil
  160. }
  161. func readString(dirpath string, file string) string {
  162. cgroupFile := path.Join(dirpath, file)
  163. // Read
  164. out, err := ioutil.ReadFile(cgroupFile)
  165. if err != nil {
  166. // Ignore non-existent files
  167. if !os.IsNotExist(err) {
  168. klog.Warningf("readString: Failed to read %q: %s", cgroupFile, err)
  169. }
  170. return ""
  171. }
  172. return strings.TrimSpace(string(out))
  173. }
  174. func readUInt64(dirpath string, file string) uint64 {
  175. out := readString(dirpath, file)
  176. if out == "" || out == "max" {
  177. return 0
  178. }
  179. val, err := strconv.ParseUint(out, 10, 64)
  180. if err != nil {
  181. klog.Errorf("readUInt64: Failed to parse int %q from file %q: %s", out, path.Join(dirpath, file), err)
  182. return 0
  183. }
  184. return val
  185. }
  186. // Lists all directories under "path" and outputs the results as children of "parent".
  187. func ListDirectories(dirpath string, parent string, recursive bool, output map[string]struct{}) error {
  188. buf := make([]byte, godirwalk.DefaultScratchBufferSize)
  189. return listDirectories(dirpath, parent, recursive, output, buf)
  190. }
  191. func listDirectories(dirpath string, parent string, recursive bool, output map[string]struct{}, buf []byte) error {
  192. dirents, err := godirwalk.ReadDirents(dirpath, buf)
  193. if err != nil {
  194. // Ignore if this hierarchy does not exist.
  195. if os.IsNotExist(errors.Cause(err)) {
  196. err = nil
  197. }
  198. return err
  199. }
  200. for _, dirent := range dirents {
  201. // We only grab directories.
  202. if !dirent.IsDir() {
  203. continue
  204. }
  205. dirname := dirent.Name()
  206. name := path.Join(parent, dirname)
  207. output[name] = struct{}{}
  208. // List subcontainers if asked to.
  209. if recursive {
  210. err := listDirectories(path.Join(dirpath, dirname), name, true, output, buf)
  211. if err != nil {
  212. return err
  213. }
  214. }
  215. }
  216. return nil
  217. }
  218. func MakeCgroupPaths(mountPoints map[string]string, name string) map[string]string {
  219. cgroupPaths := make(map[string]string, len(mountPoints))
  220. for key, val := range mountPoints {
  221. cgroupPaths[key] = path.Join(val, name)
  222. }
  223. return cgroupPaths
  224. }
  225. func CgroupExists(cgroupPaths map[string]string) bool {
  226. // If any cgroup exists, the container is still alive.
  227. for _, cgroupPath := range cgroupPaths {
  228. if utils.FileExists(cgroupPath) {
  229. return true
  230. }
  231. }
  232. return false
  233. }
  234. func ListContainers(name string, cgroupPaths map[string]string, listType container.ListType) ([]info.ContainerReference, error) {
  235. containers := make(map[string]struct{})
  236. for _, cgroupPath := range cgroupPaths {
  237. err := ListDirectories(cgroupPath, name, listType == container.ListRecursive, containers)
  238. if err != nil {
  239. return nil, err
  240. }
  241. }
  242. // Make into container references.
  243. ret := make([]info.ContainerReference, 0, len(containers))
  244. for cont := range containers {
  245. ret = append(ret, info.ContainerReference{
  246. Name: cont,
  247. })
  248. }
  249. return ret, nil
  250. }
  251. // AssignDeviceNamesToDiskStats assigns the Device field on the provided DiskIoStats by looking up
  252. // the device major and minor identifiers in the provided device namer.
  253. func AssignDeviceNamesToDiskStats(namer DeviceNamer, stats *info.DiskIoStats) {
  254. assignDeviceNamesToPerDiskStats(
  255. namer,
  256. stats.IoMerged,
  257. stats.IoQueued,
  258. stats.IoServiceBytes,
  259. stats.IoServiceTime,
  260. stats.IoServiced,
  261. stats.IoTime,
  262. stats.IoWaitTime,
  263. stats.Sectors,
  264. )
  265. }
  266. // assignDeviceNamesToPerDiskStats looks up device names for the provided stats, caching names
  267. // if necessary.
  268. func assignDeviceNamesToPerDiskStats(namer DeviceNamer, diskStats ...[]info.PerDiskStats) {
  269. devices := make(deviceIdentifierMap)
  270. for _, stats := range diskStats {
  271. for i, stat := range stats {
  272. stats[i].Device = devices.Find(stat.Major, stat.Minor, namer)
  273. }
  274. }
  275. }
  276. // DeviceNamer returns string names for devices by their major and minor id.
  277. type DeviceNamer interface {
  278. // DeviceName returns the name of the device by its major and minor ids, or false if no
  279. // such device is recognized.
  280. DeviceName(major, minor uint64) (string, bool)
  281. }
  282. type MachineInfoNamer info.MachineInfo
  283. func (n *MachineInfoNamer) DeviceName(major, minor uint64) (string, bool) {
  284. for _, info := range n.DiskMap {
  285. if info.Major == major && info.Minor == minor {
  286. return "/dev/" + info.Name, true
  287. }
  288. }
  289. for _, info := range n.Filesystems {
  290. if info.DeviceMajor == major && info.DeviceMinor == minor {
  291. return info.Device, true
  292. }
  293. }
  294. return "", false
  295. }
  296. type deviceIdentifier struct {
  297. major uint64
  298. minor uint64
  299. }
  300. type deviceIdentifierMap map[deviceIdentifier]string
  301. // Find locates the device name by device identifier out of from, caching the result as necessary.
  302. func (m deviceIdentifierMap) Find(major, minor uint64, namer DeviceNamer) string {
  303. d := deviceIdentifier{major, minor}
  304. if s, ok := m[d]; ok {
  305. return s
  306. }
  307. s, _ := namer.DeviceName(major, minor)
  308. m[d] = s
  309. return s
  310. }