procfs_linux.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. type ProcFS struct{}
  32. func NewProcFS() ProcFSInterface {
  33. return &ProcFS{}
  34. }
  35. func containerNameFromProcCgroup(content string) (string, error) {
  36. lines := strings.Split(content, "\n")
  37. for _, line := range lines {
  38. entries := strings.SplitN(line, ":", 3)
  39. if len(entries) == 3 && entries[1] == "devices" {
  40. return strings.TrimSpace(entries[2]), nil
  41. }
  42. }
  43. return "", fmt.Errorf("could not find devices cgroup location")
  44. }
  45. // getFullContainerName gets the container name given the root process id of the container.
  46. // E.g. if the devices cgroup for the container is stored in /sys/fs/cgroup/devices/docker/nginx,
  47. // return docker/nginx. Assumes that the process is part of exactly one cgroup hierarchy.
  48. func (pfs *ProcFS) GetFullContainerName(pid int) (string, error) {
  49. filePath := path.Join("/proc", strconv.Itoa(pid), "cgroup")
  50. content, err := ioutil.ReadFile(filePath)
  51. if err != nil {
  52. if os.IsNotExist(err) {
  53. return "", os.ErrNotExist
  54. }
  55. return "", err
  56. }
  57. return containerNameFromProcCgroup(string(content))
  58. }
  59. // Find process(es) using a regular expression and send a specified
  60. // signal to each process
  61. func PKill(name string, sig syscall.Signal) error {
  62. if len(name) == 0 {
  63. return fmt.Errorf("name should not be empty")
  64. }
  65. re, err := regexp.Compile(name)
  66. if err != nil {
  67. return err
  68. }
  69. pids := getPids(re)
  70. if len(pids) == 0 {
  71. return fmt.Errorf("unable to fetch pids for process name : %q", name)
  72. }
  73. errList := []error{}
  74. for _, pid := range pids {
  75. if err = syscall.Kill(pid, sig); err != nil {
  76. errList = append(errList, err)
  77. }
  78. }
  79. return utilerrors.NewAggregate(errList)
  80. }
  81. // Find process(es) with a specified name (regexp match)
  82. // and return their pid(s)
  83. func PidOf(name string) ([]int, error) {
  84. if len(name) == 0 {
  85. return []int{}, fmt.Errorf("name should not be empty")
  86. }
  87. re, err := regexp.Compile("(^|/)" + name + "$")
  88. if err != nil {
  89. return []int{}, err
  90. }
  91. return getPids(re), nil
  92. }
  93. func getPids(re *regexp.Regexp) []int {
  94. pids := []int{}
  95. dirFD, err := os.Open("/proc")
  96. if err != nil {
  97. return nil
  98. }
  99. defer dirFD.Close()
  100. for {
  101. // Read a small number at a time in case there are many entries, we don't want to
  102. // allocate a lot here.
  103. ls, err := dirFD.Readdir(10)
  104. if err == io.EOF {
  105. break
  106. }
  107. if err != nil {
  108. return nil
  109. }
  110. for _, entry := range ls {
  111. if !entry.IsDir() {
  112. continue
  113. }
  114. // If the directory is not a number (i.e. not a PID), skip it
  115. pid, err := strconv.Atoi(entry.Name())
  116. if err != nil {
  117. continue
  118. }
  119. cmdline, err := ioutil.ReadFile(filepath.Join("/proc", entry.Name(), "cmdline"))
  120. if err != nil {
  121. klog.V(4).Infof("Error reading file %s: %+v", filepath.Join("/proc", entry.Name(), "cmdline"), err)
  122. continue
  123. }
  124. // The bytes we read have '\0' as a separator for the command line
  125. parts := bytes.SplitN(cmdline, []byte{0}, 2)
  126. if len(parts) == 0 {
  127. continue
  128. }
  129. // Split the command line itself we are interested in just the first part
  130. exe := strings.FieldsFunc(string(parts[0]), func(c rune) bool {
  131. return unicode.IsSpace(c) || c == ':'
  132. })
  133. if len(exe) == 0 {
  134. continue
  135. }
  136. // Check if the name of the executable is what we are looking for
  137. if re.MatchString(exe[0]) {
  138. // Grab the PID from the directory path
  139. pids = append(pids, pid)
  140. }
  141. }
  142. }
  143. return pids
  144. }