procfs_linux.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // +build linux
  2. /*
  3. Copyright 2015 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package procfs
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. "syscall"
  27. "unicode"
  28. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  29. "k8s.io/klog"
  30. )
  31. // ProcFS provides a helper for getting container name via pid.
  32. type ProcFS struct{}
  33. // NewProcFS returns a ProcFS object.
  34. func NewProcFS() ProcFSInterface {
  35. return &ProcFS{}
  36. }
  37. func containerNameFromProcCgroup(content string) (string, error) {
  38. lines := strings.Split(content, "\n")
  39. for _, line := range lines {
  40. entries := strings.SplitN(line, ":", 3)
  41. if len(entries) == 3 && entries[1] == "devices" {
  42. return strings.TrimSpace(entries[2]), nil
  43. }
  44. }
  45. return "", fmt.Errorf("could not find devices cgroup location")
  46. }
  47. // GetFullContainerName gets the container name given the root process id of the container.
  48. // E.g. if the devices cgroup for the container is stored in /sys/fs/cgroup/devices/docker/nginx,
  49. // return docker/nginx. Assumes that the process is part of exactly one cgroup hierarchy.
  50. func (pfs *ProcFS) GetFullContainerName(pid int) (string, error) {
  51. filePath := path.Join("/proc", strconv.Itoa(pid), "cgroup")
  52. content, err := ioutil.ReadFile(filePath)
  53. if err != nil {
  54. if os.IsNotExist(err) {
  55. return "", os.ErrNotExist
  56. }
  57. return "", err
  58. }
  59. return containerNameFromProcCgroup(string(content))
  60. }
  61. // PKill finds process(es) using a regular expression and send a specified
  62. // signal to each process.
  63. func PKill(name string, sig syscall.Signal) error {
  64. if len(name) == 0 {
  65. return fmt.Errorf("name should not be empty")
  66. }
  67. re, err := regexp.Compile(name)
  68. if err != nil {
  69. return err
  70. }
  71. pids := getPids(re)
  72. if len(pids) == 0 {
  73. return fmt.Errorf("unable to fetch pids for process name : %q", name)
  74. }
  75. errList := []error{}
  76. for _, pid := range pids {
  77. if err = syscall.Kill(pid, sig); err != nil {
  78. errList = append(errList, err)
  79. }
  80. }
  81. return utilerrors.NewAggregate(errList)
  82. }
  83. // PidOf finds process(es) with a specified name (regexp match)
  84. // and return their pid(s).
  85. func PidOf(name string) ([]int, error) {
  86. if len(name) == 0 {
  87. return []int{}, fmt.Errorf("name should not be empty")
  88. }
  89. re, err := regexp.Compile("(^|/)" + name + "$")
  90. if err != nil {
  91. return []int{}, err
  92. }
  93. return getPids(re), nil
  94. }
  95. func getPids(re *regexp.Regexp) []int {
  96. pids := []int{}
  97. dirFD, err := os.Open("/proc")
  98. if err != nil {
  99. return nil
  100. }
  101. defer dirFD.Close()
  102. for {
  103. // Read a small number at a time in case there are many entries, we don't want to
  104. // allocate a lot here.
  105. ls, err := dirFD.Readdir(10)
  106. if err == io.EOF {
  107. break
  108. }
  109. if err != nil {
  110. return nil
  111. }
  112. for _, entry := range ls {
  113. if !entry.IsDir() {
  114. continue
  115. }
  116. // If the directory is not a number (i.e. not a PID), skip it
  117. pid, err := strconv.Atoi(entry.Name())
  118. if err != nil {
  119. continue
  120. }
  121. cmdline, err := ioutil.ReadFile(filepath.Join("/proc", entry.Name(), "cmdline"))
  122. if err != nil {
  123. klog.V(4).Infof("Error reading file %s: %+v", filepath.Join("/proc", entry.Name(), "cmdline"), err)
  124. continue
  125. }
  126. // The bytes we read have '\0' as a separator for the command line
  127. parts := bytes.SplitN(cmdline, []byte{0}, 2)
  128. if len(parts) == 0 {
  129. continue
  130. }
  131. // Split the command line itself we are interested in just the first part
  132. exe := strings.FieldsFunc(string(parts[0]), func(c rune) bool {
  133. return unicode.IsSpace(c) || c == ':'
  134. })
  135. if len(exe) == 0 {
  136. continue
  137. }
  138. // Check if the name of the executable is what we are looking for
  139. if re.MatchString(exe[0]) {
  140. // Grab the PID from the directory path
  141. pids = append(pids, pid)
  142. }
  143. }
  144. }
  145. return pids
  146. }