cpus.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 pod
  15. import (
  16. "fmt"
  17. "path/filepath"
  18. "strconv"
  19. "sync"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/pkg/errors"
  22. hostapi "yunion.io/x/onecloud/pkg/apis/host"
  23. "yunion.io/x/onecloud/pkg/util/fileutils2"
  24. "yunion.io/x/onecloud/pkg/util/procutils"
  25. )
  26. func EnsureDir(dir string) error {
  27. out, err := procutils.NewRemoteCommandAsFarAsPossible("mkdir", "-p", dir).Output()
  28. if err != nil {
  29. return errors.Wrapf(err, "mkdir %s: %s", dir, out)
  30. }
  31. return nil
  32. }
  33. func EnsureFile(filename string, content string, mod string) error {
  34. cmds := []string{
  35. fmt.Sprintf("echo '%s' > %s", content, filename),
  36. }
  37. if mod != "" {
  38. cmds = append(cmds, fmt.Sprintf("chmod %s %s", mod, filename))
  39. }
  40. for _, cmd := range cmds {
  41. out, err := procutils.NewRemoteCommandAsFarAsPossible("sh", "-c", cmd).Output()
  42. if err != nil {
  43. return errors.Wrapf(err, "cmd %s: %s", cmd, out)
  44. }
  45. }
  46. return nil
  47. }
  48. func EnsureContainerSystemCpuDir(cpuDir string, cpuCount int64) error {
  49. if err := EnsureDir(cpuDir); err != nil {
  50. return err
  51. }
  52. for i := 0; i < int(cpuCount); i++ {
  53. singleCpuDir := filepath.Join(cpuDir, fmt.Sprintf("cpu%d", i))
  54. if err := EnsureDir(singleCpuDir); err != nil {
  55. return errors.Wrapf(err, "create cpu%d", i)
  56. }
  57. }
  58. // create other dirs
  59. freqDir := filepath.Join(cpuDir, "cpufreq")
  60. idleDir := filepath.Join(cpuDir, "cpuidle")
  61. hotplugDir := filepath.Join(cpuDir, "hotplug")
  62. powerDir := filepath.Join(cpuDir, "power")
  63. for _, dir := range []string{freqDir, idleDir, hotplugDir, powerDir} {
  64. if err := EnsureDir(dir); err != nil {
  65. return err
  66. }
  67. }
  68. // create files
  69. if err := EnsureFile(filepath.Join(cpuDir, "isolated"), "", "755"); err != nil {
  70. return err
  71. }
  72. if err := EnsureFile(filepath.Join(cpuDir, "kernel_max"), fmt.Sprintf("%d", cpuCount), "644"); err != nil {
  73. return err
  74. }
  75. if err := EnsureFile(filepath.Join(cpuDir, "modalias"), "", "755"); err != nil {
  76. return err
  77. }
  78. if err := EnsureFile(filepath.Join(cpuDir, "offline"), "", "755"); err != nil {
  79. return err
  80. }
  81. ensureCpuRangeFile := func(baseName string, mode string) error {
  82. if mode == "" {
  83. mode = "644"
  84. }
  85. if cpuCount > 1 {
  86. if err := EnsureFile(filepath.Join(cpuDir, baseName), fmt.Sprintf("0-%d", cpuCount-1), mode); err != nil {
  87. return err
  88. }
  89. return nil
  90. }
  91. if err := EnsureFile(filepath.Join(cpuDir, baseName), "0", mode); err != nil {
  92. return err
  93. }
  94. return nil
  95. }
  96. if err := ensureCpuRangeFile("online", "755"); err != nil {
  97. return err
  98. }
  99. if err := ensureCpuRangeFile("possible", ""); err != nil {
  100. return err
  101. }
  102. if err := ensureCpuRangeFile("present", ""); err != nil {
  103. return err
  104. }
  105. if err := EnsureFile(filepath.Join(cpuDir, "uevent"), "", "755"); err != nil {
  106. return err
  107. }
  108. return nil
  109. }
  110. type ContainerCPU struct {
  111. ContainerId string `json:"container_id"`
  112. Index int `json:"index"`
  113. }
  114. func NewContainerCPU(ctrId string, ctrIdx int) *ContainerCPU {
  115. return &ContainerCPU{
  116. ContainerId: ctrId,
  117. Index: ctrIdx,
  118. }
  119. }
  120. type HostContainerCPU struct {
  121. Index int `json:"index"`
  122. Containers map[string][]*ContainerCPU `json:"containers"`
  123. }
  124. func NewHostContainerCPU(hostIndex int) *HostContainerCPU {
  125. return &HostContainerCPU{
  126. Index: hostIndex,
  127. Containers: make(map[string][]*ContainerCPU),
  128. }
  129. }
  130. func (h *HostContainerCPU) HasContainer(ctrId string) bool {
  131. _, ok := h.Containers[ctrId]
  132. return ok
  133. }
  134. func (h *HostContainerCPU) DeleteContainer(ctrId string) {
  135. delete(h.Containers, ctrId)
  136. }
  137. func (h *HostContainerCPU) InsertContainer(ctrId string, ctrIdx int) {
  138. if h.Containers == nil {
  139. h.Containers = make(map[string][]*ContainerCPU)
  140. }
  141. if h.HasContainer(ctrId) {
  142. h.Containers[ctrId] = append(h.Containers[ctrId], NewContainerCPU(ctrId, ctrIdx))
  143. } else {
  144. h.Containers[ctrId] = []*ContainerCPU{NewContainerCPU(ctrId, ctrIdx)}
  145. }
  146. }
  147. var (
  148. hostContainerCPUMapLock = sync.Mutex{}
  149. )
  150. type HostContainerCPUMap struct {
  151. Map map[string]*HostContainerCPU `json:"map"`
  152. stateFile string
  153. }
  154. func NewHostContainerCPUMap(topo *hostapi.HostTopology, stateFile string) (*HostContainerCPUMap, error) {
  155. ret := make(map[string]*HostContainerCPU)
  156. if fileutils2.Exists(stateFile) {
  157. content, err := fileutils2.FileGetContents(stateFile)
  158. if err != nil {
  159. return nil, errors.Wrapf(err, "get file contents: %s", stateFile)
  160. }
  161. obj, err := jsonutils.ParseString(content)
  162. if err != nil {
  163. return nil, errors.Wrapf(err, "parse to json: %s", content)
  164. }
  165. hm := new(HostContainerCPUMap)
  166. if err := obj.Unmarshal(hm); err != nil {
  167. return nil, errors.Wrap(err, "unmarshal to HostContainerCPUMap")
  168. }
  169. hm.stateFile = stateFile
  170. return hm, nil
  171. }
  172. nodes := topo.Nodes
  173. for _, node := range nodes {
  174. for _, core := range node.Cores {
  175. for _, processor := range core.LogicalProcessors {
  176. ret[fmt.Sprintf("%d", processor)] = NewHostContainerCPU(processor)
  177. }
  178. }
  179. }
  180. return &HostContainerCPUMap{Map: ret, stateFile: stateFile}, nil
  181. }
  182. func (hm *HostContainerCPUMap) dumpToFile() error {
  183. return fileutils2.FilePutContents(hm.stateFile, jsonutils.Marshal(hm).PrettyString(), false)
  184. }
  185. func (hm *HostContainerCPUMap) Delete(ctrId string) error {
  186. hostContainerCPUMapLock.Lock()
  187. defer hostContainerCPUMapLock.Unlock()
  188. for _, cm := range hm.Map {
  189. if cm.HasContainer(ctrId) {
  190. cm.DeleteContainer(ctrId)
  191. }
  192. }
  193. return hm.dumpToFile()
  194. }
  195. func (hm *HostContainerCPUMap) Get(ctrId string, ctrCpuIndex int) (int, error) {
  196. hostContainerCPUMapLock.Lock()
  197. defer hostContainerCPUMapLock.Unlock()
  198. hostIndex := hm.findLeastUsedIndex(ctrId, ctrCpuIndex)
  199. if err := hm.markUsed(hostIndex, ctrId, ctrCpuIndex); err != nil {
  200. return 0, errors.Wrapf(err, "mark container %s %d used", ctrId, ctrCpuIndex)
  201. }
  202. return hostIndex, nil
  203. }
  204. func (hm *HostContainerCPUMap) findLeastUsedIndex(ctrId string, ctrCpuIndex int) int {
  205. unusedMap := make(map[string]*HostContainerCPU)
  206. usedMap := make(map[string]*HostContainerCPU)
  207. for idx, hc := range hm.Map {
  208. tmpHc := hc
  209. if tmpHc.HasContainer(ctrId) {
  210. usedMap[idx] = tmpHc
  211. } else {
  212. unusedMap[idx] = tmpHc
  213. }
  214. }
  215. if len(unusedMap) != 0 {
  216. for idx, _ := range unusedMap {
  217. idxNum, _ := strconv.Atoi(idx)
  218. return idxNum
  219. }
  220. }
  221. // find the least used index from usedMap
  222. isStart := true
  223. leastIndex := 0
  224. leastUsed := 0
  225. for idx, hc := range usedMap {
  226. cm := hc.Containers[ctrId]
  227. idxNum, _ := strconv.Atoi(idx)
  228. if isStart {
  229. leastIndex = idxNum
  230. leastUsed = len(cm)
  231. isStart = false
  232. continue
  233. }
  234. if len(cm) < leastUsed {
  235. leastUsed = len(cm)
  236. leastIndex = idxNum
  237. }
  238. }
  239. return leastIndex
  240. }
  241. func (hm *HostContainerCPUMap) markUsed(hostIdx int, ctrId string, ctrIdx int) error {
  242. hc := hm.Map[fmt.Sprintf("%d", hostIdx)]
  243. hc.InsertContainer(ctrId, ctrIdx)
  244. return hm.dumpToFile()
  245. }