kernel.go 5.1 KB

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