kernel.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. // Copyright The OpenTelemetry Authors
  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 utils
  15. import (
  16. "bufio"
  17. "errors"
  18. "fmt"
  19. klog "github.com/sirupsen/logrus"
  20. "golang.org/x/sys/unix"
  21. "os"
  22. "strconv"
  23. "strings"
  24. "syscall"
  25. "time"
  26. "github.com/hashicorp/go-version"
  27. )
  28. var unameFn = syscall.Uname
  29. // parse logic adapted from https://github.com/golang/go/blob/go1.21.3/src/internal/syscall/unix/kernel_version_linux.go
  30. func GetLinuxKernelVersion() (*version.Version, error) {
  31. var uname syscall.Utsname
  32. if err := unameFn(&uname); err != nil {
  33. return nil, err
  34. }
  35. var (
  36. values [2]int
  37. value, vi int
  38. )
  39. for _, c := range uname.Release {
  40. if '0' <= c && c <= '9' {
  41. value = (value * 10) + int(c-'0')
  42. } else {
  43. // Note that we're assuming N.N.N here.
  44. // If we see anything else, we are likely to mis-parse it.
  45. values[vi] = value
  46. vi++
  47. if vi >= len(values) {
  48. break
  49. }
  50. value = 0
  51. }
  52. }
  53. ver := fmt.Sprintf("%s.%s", strconv.Itoa(values[0]), strconv.Itoa(values[1]))
  54. return version.NewVersion(ver)
  55. }
  56. type KernelLockdown uint8
  57. const (
  58. KernelLockdownNone KernelLockdown = iota + 1 // Linux Kernel security lockdown mode [none]
  59. KernelLockdownIntegrity // Linux Kernel security lockdown mode [integrity]
  60. KernelLockdownConfidentiality // Linux Kernel security lockdown mode [confidentiality]
  61. KernelLockdownOther // Linux Kernel security lockdown mode unknown
  62. )
  63. // Injectable for tests.
  64. var lockdownPath = "/sys/kernel/security/lockdown"
  65. func KernelLockdownMode() KernelLockdown {
  66. // If we can't find the file, assume no lockdown
  67. if _, err := os.Stat(lockdownPath); err == nil {
  68. f, err := os.Open(lockdownPath)
  69. if err != nil {
  70. return KernelLockdownIntegrity
  71. }
  72. defer f.Close()
  73. scanner := bufio.NewScanner(f)
  74. if scanner.Scan() {
  75. lockdown := scanner.Text()
  76. if strings.Contains(lockdown, "[none]") {
  77. return KernelLockdownNone
  78. } else if strings.Contains(lockdown, "[integrity]") {
  79. return KernelLockdownIntegrity
  80. } else if strings.Contains(lockdown, "[confidentiality]") {
  81. return KernelLockdownConfidentiality
  82. }
  83. return KernelLockdownOther
  84. }
  85. return KernelLockdownIntegrity
  86. }
  87. return KernelLockdownNone
  88. }
  89. // Injectable for tests, this file is one of the files LSCPU looks for.
  90. var cpuPresentPath = "/sys/devices/system/cpu/present"
  91. func GetCPUCountFromSysDevices() (int, error) {
  92. rawFile, err := os.ReadFile(cpuPresentPath)
  93. if err != nil {
  94. return 0, err
  95. }
  96. cpuCount, err := parseCPUList(string(rawFile))
  97. if err != nil {
  98. return 0, err
  99. }
  100. return cpuCount, nil
  101. }
  102. func parseCPUList(raw string) (int, error) {
  103. listPart := strings.Split(raw, ",")
  104. count := 0
  105. for _, v := range listPart {
  106. if strings.Contains(v, "-") {
  107. rangeC, err := parseCPURange(v)
  108. if err != nil {
  109. return 0, fmt.Errorf("error parsing line %s: %w", v, err)
  110. }
  111. count = count + rangeC
  112. } else {
  113. count++
  114. }
  115. }
  116. return count, nil
  117. }
  118. func parseCPURange(cpuRange string) (int, error) {
  119. var first, last int
  120. _, err := fmt.Sscanf(cpuRange, "%d-%d", &first, &last)
  121. if err != nil {
  122. return 0, fmt.Errorf("error reading from range %s: %w", cpuRange, err)
  123. }
  124. return (last - first) + 1, nil
  125. }
  126. var procInfoPath = "/proc/cpuinfo"
  127. func GetCPUCountFromProc() (int, error) {
  128. file, err := os.Open(procInfoPath)
  129. if err != nil {
  130. return 0, err
  131. }
  132. defer file.Close()
  133. scanner := bufio.NewScanner(file)
  134. count := 0
  135. for scanner.Scan() {
  136. if strings.Contains(scanner.Text(), "processor") {
  137. count++
  138. }
  139. }
  140. if err := scanner.Err(); err != nil {
  141. return 0, err
  142. }
  143. return count, nil
  144. }
  145. func GetCPUCount() (int, error) {
  146. var err error
  147. // First try to get the CPU count from /sys/devices
  148. cpuCount, e := GetCPUCountFromSysDevices()
  149. if e == nil {
  150. return cpuCount, nil
  151. }
  152. err = errors.Join(err, e)
  153. // If that fails, try to get the CPU count from /proc
  154. cpuCount, e = GetCPUCountFromProc()
  155. if e == nil {
  156. return cpuCount, nil
  157. }
  158. err = errors.Join(err, e)
  159. return 0, err
  160. }
  161. var bootTime time.Time
  162. // GetBootTime returns the time at which the machine was started, truncated to the nearest second
  163. func GetBootTime() (time.Time, error) {
  164. if !bootTime.IsZero() {
  165. return bootTime, nil
  166. }
  167. currentTime := time.Now()
  168. var info unix.Sysinfo_t
  169. if err := unix.Sysinfo(&info); err != nil {
  170. return time.Time{}, fmt.Errorf("error getting system uptime: %s", err)
  171. }
  172. bootTime = currentTime.Add(-time.Duration(info.Uptime) * time.Second).Truncate(time.Second)
  173. return bootTime, nil
  174. }
  175. func KtimeToTimestamp(t uint64) int64 {
  176. bT, err := GetBootTime()
  177. if err != nil {
  178. klog.Errorf("error getting boot time: %v", err)
  179. return int64(0)
  180. }
  181. return bT.Add(time.Duration(t) * time.Nanosecond).UnixNano()
  182. }