helpers.go 8.3 KB

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