cpuutils.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // Copyright 2019 Yunion
  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 cgroupv1
  15. import (
  16. "fmt"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "github.com/shirou/gopsutil/process"
  21. "yunion.io/x/log"
  22. "yunion.io/x/onecloud/pkg/util/fileutils2"
  23. )
  24. var systemCpu *CPU
  25. type CPU struct {
  26. DieList []*CPUDie
  27. }
  28. func NewCPU() (*CPU, error) {
  29. var cpu = new(CPU)
  30. cpu.DieList = make([]*CPUDie, 0)
  31. cpuinfo, err := fileutils2.FileGetContents("/proc/cpuinfo")
  32. if err != nil {
  33. return nil, err
  34. }
  35. var core *CPUCore
  36. for _, line := range strings.Split(cpuinfo, "\n") {
  37. parts := strings.Split(line, ":")
  38. if len(parts) == 2 {
  39. key := strings.TrimSpace(parts[0])
  40. val := strings.TrimSpace(parts[1])
  41. if key == "processor" {
  42. iVal, err := strconv.Atoi(val)
  43. if err != nil {
  44. return nil, err
  45. }
  46. if core != nil {
  47. cpu.AddCore(core)
  48. }
  49. core = NewCPUCore(iVal)
  50. } else if core != nil {
  51. core.setInfo(key, val)
  52. }
  53. }
  54. }
  55. if core != nil {
  56. cpu.AddCore(core)
  57. }
  58. return cpu, nil
  59. }
  60. func (c *CPU) AddCore(core *CPUCore) {
  61. for len(c.DieList) < core.PhysicalId+1 {
  62. c.DieList = append(c.DieList, NewCPUDie(len(c.DieList)))
  63. }
  64. c.DieList[core.PhysicalId].AddCore(core)
  65. }
  66. func (c *CPU) GetCpuset(idx int) string {
  67. if idx >= 0 && idx < len(c.DieList) {
  68. return c.DieList[idx].GetCoreStr()
  69. } else {
  70. return ""
  71. }
  72. }
  73. func (c *CPU) GetPhysicalNum() int {
  74. return len(c.DieList)
  75. }
  76. func (c *CPU) GetPhysicalId(cstr string) int {
  77. for _, d := range c.DieList {
  78. if d.GetCoreStr() == cstr {
  79. return d.Index
  80. }
  81. }
  82. return -1
  83. }
  84. type CPUCore struct {
  85. Index int
  86. VendorId string
  87. Mhz float64
  88. CacheSize string
  89. PhysicalId int
  90. CoreId int
  91. }
  92. func NewCPUCore(index int) *CPUCore {
  93. return &CPUCore{Index: index}
  94. }
  95. func (c *CPUCore) setInfo(k, v string) {
  96. switch k {
  97. case "vendor_id":
  98. c.VendorId = v
  99. case "cpu MHz":
  100. val, _ := strconv.ParseFloat(v, 64)
  101. c.Mhz = val
  102. case "cache size":
  103. c.CacheSize = strings.Split(v, " ")[0]
  104. case "physical id":
  105. val, _ := strconv.Atoi(v)
  106. c.PhysicalId = val
  107. case "core id":
  108. val, _ := strconv.Atoi(v)
  109. c.CoreId = val
  110. }
  111. }
  112. type CPUDie struct {
  113. Index int
  114. CoreList []*CPUCore
  115. }
  116. func (d *CPUDie) AddCore(core *CPUCore) {
  117. d.CoreList = append(d.CoreList, core)
  118. }
  119. func (d *CPUDie) GetCoreStr() string {
  120. coreIdx := []string{}
  121. for _, c := range d.CoreList {
  122. coreIdx = append(coreIdx, strconv.Itoa(c.Index))
  123. }
  124. sort.Slice(coreIdx, func(i int, j int) bool {
  125. si, _ := strconv.Atoi(coreIdx[i])
  126. sj, _ := strconv.Atoi(coreIdx[j])
  127. return si < sj
  128. })
  129. return strings.Join(coreIdx, ",")
  130. }
  131. func NewCPUDie(index int) *CPUDie {
  132. return &CPUDie{Index: index}
  133. }
  134. func GetSystemCpu() (*CPU, error) {
  135. if systemCpu == nil {
  136. var err error
  137. systemCpu, err = NewCPU()
  138. if err != nil {
  139. return nil, err
  140. }
  141. }
  142. return systemCpu, nil
  143. }
  144. func ParseCpusetStr(cpuset string) string {
  145. var (
  146. idxList = make([]string, 0)
  147. sets = strings.Split(cpuset, ",")
  148. )
  149. for _, idxstr := range sets {
  150. if strings.Contains(idxstr, "-") {
  151. ses := strings.Split(idxstr, "-")
  152. start, _ := strconv.Atoi(ses[0])
  153. end, _ := strconv.Atoi(ses[1])
  154. for start <= end {
  155. idxList = append(idxList, strconv.Itoa(start))
  156. start += 1
  157. }
  158. } else {
  159. idxList = append(idxList, idxstr)
  160. }
  161. }
  162. sort.Slice(idxList, func(i int, j int) bool {
  163. si, _ := strconv.Atoi(idxList[i])
  164. sj, _ := strconv.Atoi(idxList[j])
  165. return si < sj
  166. })
  167. return strings.Join(idxList, ",")
  168. }
  169. type ProcessCPUinfo struct {
  170. Pid int
  171. Share *float64
  172. Cpuset *int
  173. Util float64
  174. Weight float64
  175. }
  176. func (p *ProcessCPUinfo) String() string {
  177. share := -1.0
  178. if p.Share != nil {
  179. share = *p.Share
  180. }
  181. cpuset := -1
  182. if p.Cpuset != nil {
  183. cpuset = *p.Cpuset
  184. }
  185. return fmt.Sprintf("(%d, %f, %f, %f, %d)", p.Pid, p.Weight, p.Util, share, cpuset)
  186. }
  187. func Average(arr []float64) float64 {
  188. var total = 0.0
  189. for _, a := range arr {
  190. total += a
  191. }
  192. return total / float64(len(arr))
  193. }
  194. func GetProcessWeight(share *float64, util float64) float64 {
  195. if share != nil {
  196. return (*share) * (util*0.8 + 30)
  197. }
  198. return 0.0
  199. }
  200. func NewProcessCPUinfo(pid int) (*ProcessCPUinfo, error) {
  201. cpuinfo := new(ProcessCPUinfo)
  202. cpuinfo.Pid = pid
  203. spid := strconv.Itoa(pid)
  204. cpuTask := manager.NewCGroupCPUTask(spid, "", 0)
  205. if cpuTask.TaskIsExist() {
  206. share := cpuTask.GetParam("cpu.shares")
  207. ishare, err := strconv.ParseFloat(share, 64)
  208. if err != nil {
  209. log.Errorln(err)
  210. } else {
  211. ishare /= 1024.0
  212. cpuinfo.Share = &ishare
  213. }
  214. }
  215. cpusetTask := manager.NewCGroupCPUSetTask(fmt.Sprintf("%d", pid), "", "", "")
  216. if cpusetTask.TaskIsExist() {
  217. cpuset := cpusetTask.GetParam("cpuset.cpus")
  218. if len(cpuset) > 0 {
  219. c, err := GetSystemCpu()
  220. if err != nil {
  221. log.Errorln(err)
  222. } else {
  223. icpuset := c.GetPhysicalId(ParseCpusetStr(cpuset))
  224. cpuinfo.Cpuset = &icpuset
  225. }
  226. }
  227. }
  228. if cpuinfo.Share != nil {
  229. proc, err := process.NewProcess(int32(pid))
  230. if err != nil {
  231. log.Errorln(err)
  232. return nil, err
  233. }
  234. util, err := proc.CPUPercent()
  235. if err != nil {
  236. log.Errorln(err)
  237. return nil, err
  238. }
  239. util /= float64(*cpuinfo.Share)
  240. uHistory := FetchHistoryUtil()
  241. var utils = []float64{}
  242. if _, ok := uHistory[spid]; ok {
  243. utils = uHistory[spid]
  244. }
  245. utils = append(utils, util)
  246. for len(utils) > MAX_HISTORY_UTIL_COUNT {
  247. utils = utils[1:]
  248. }
  249. uHistory[spid] = utils
  250. cpuinfo.Util = Average(utils)
  251. }
  252. cpuinfo.Weight = GetProcessWeight(cpuinfo.Share, cpuinfo.Util)
  253. return cpuinfo, nil
  254. }
  255. type CPULoad struct {
  256. Processes []*ProcessCPUinfo
  257. }
  258. func (c *CPULoad) AddProcess(proc *ProcessCPUinfo) {
  259. if c.Processes == nil {
  260. c.Processes = make([]*ProcessCPUinfo, 0)
  261. }
  262. c.Processes = append(c.Processes, proc)
  263. }
  264. func (c *CPULoad) GetWeight() float64 {
  265. var wt = 0.0
  266. for _, p := range c.Processes {
  267. wt += p.Weight
  268. }
  269. return wt
  270. }
  271. func (c *CPULoad) Sort() {
  272. sort.Slice(c.Processes, func(i, j int) bool {
  273. return c.Processes[i].Weight < c.Processes[j].Weight
  274. })
  275. }