state_file.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package state
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "sync"
  20. "k8s.io/klog"
  21. "k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/containermap"
  22. "k8s.io/kubernetes/pkg/kubelet/cm/cpuset"
  23. )
  24. type stateFileDataV1 struct {
  25. PolicyName string `json:"policyName"`
  26. DefaultCPUSet string `json:"defaultCpuSet"`
  27. Entries map[string]string `json:"entries,omitempty"`
  28. }
  29. type stateFileDataV2 struct {
  30. PolicyName string `json:"policyName"`
  31. DefaultCPUSet string `json:"defaultCpuSet"`
  32. Entries map[string]map[string]string `json:"entries,omitempty"`
  33. }
  34. var _ State = &stateFile{}
  35. type stateFile struct {
  36. sync.RWMutex
  37. stateFilePath string
  38. policyName string
  39. cache State
  40. initialContainers containermap.ContainerMap
  41. }
  42. // NewFileState creates new State for keeping track of cpu/pod assignment with file backend
  43. func NewFileState(filePath string, policyName string, initialContainers containermap.ContainerMap) (State, error) {
  44. stateFile := &stateFile{
  45. stateFilePath: filePath,
  46. cache: NewMemoryState(),
  47. policyName: policyName,
  48. initialContainers: initialContainers,
  49. }
  50. if err := stateFile.tryRestoreState(); err != nil {
  51. // could not restore state, init new state file
  52. klog.Errorf("[cpumanager] state file: unable to restore state from disk (%v)"+
  53. " We cannot guarantee sane CPU affinity for existing containers."+
  54. " Please drain this node and delete the CPU manager state file \"%s\" before restarting Kubelet.",
  55. err, stateFile.stateFilePath)
  56. return nil, err
  57. }
  58. return stateFile, nil
  59. }
  60. // migrateV1StateToV2State() converts state from the v1 format to the v2 format
  61. func (sf *stateFile) migrateV1StateToV2State(src *stateFileDataV1, dst *stateFileDataV2) error {
  62. if src.PolicyName != "" {
  63. dst.PolicyName = src.PolicyName
  64. }
  65. if src.DefaultCPUSet != "" {
  66. dst.DefaultCPUSet = src.DefaultCPUSet
  67. }
  68. for containerID, cset := range src.Entries {
  69. podUID, containerName, err := sf.initialContainers.GetContainerRef(containerID)
  70. if err != nil {
  71. return fmt.Errorf("containerID '%v' not found in initial containers list", containerID)
  72. }
  73. if dst.Entries == nil {
  74. dst.Entries = make(map[string]map[string]string)
  75. }
  76. if _, exists := dst.Entries[podUID]; !exists {
  77. dst.Entries[podUID] = make(map[string]string)
  78. }
  79. dst.Entries[podUID][containerName] = cset
  80. }
  81. return nil
  82. }
  83. // tryRestoreState tries to read state file, upon any error,
  84. // err message is logged and state is left clean. un-initialized
  85. func (sf *stateFile) tryRestoreState() error {
  86. sf.Lock()
  87. defer sf.Unlock()
  88. var err error
  89. var content []byte
  90. content, err = ioutil.ReadFile(sf.stateFilePath)
  91. // If the state file does not exist or has zero length, write a new file.
  92. if os.IsNotExist(err) || len(content) == 0 {
  93. err := sf.storeState()
  94. if err != nil {
  95. return err
  96. }
  97. klog.Infof("[cpumanager] state file: created new state file \"%s\"", sf.stateFilePath)
  98. return nil
  99. }
  100. // Fail on any other file read error.
  101. if err != nil {
  102. return err
  103. }
  104. // File exists; try to read it.
  105. var readStateV1 stateFileDataV1
  106. var readStateV2 stateFileDataV2
  107. if err = json.Unmarshal(content, &readStateV1); err != nil {
  108. readStateV1 = stateFileDataV1{} // reset it back to 0
  109. if err = json.Unmarshal(content, &readStateV2); err != nil {
  110. klog.Errorf("[cpumanager] state file: could not unmarshal, corrupted state file - \"%s\"", sf.stateFilePath)
  111. return err
  112. }
  113. }
  114. if err = sf.migrateV1StateToV2State(&readStateV1, &readStateV2); err != nil {
  115. klog.Errorf("[cpumanager] state file: could not migrate v1 state to v2 state - \"%s\"", sf.stateFilePath)
  116. return err
  117. }
  118. if sf.policyName != readStateV2.PolicyName {
  119. return fmt.Errorf("policy configured \"%s\" != policy from state file \"%s\"", sf.policyName, readStateV2.PolicyName)
  120. }
  121. var tmpDefaultCPUSet cpuset.CPUSet
  122. if tmpDefaultCPUSet, err = cpuset.Parse(readStateV2.DefaultCPUSet); err != nil {
  123. klog.Errorf("[cpumanager] state file: could not parse state file - [defaultCpuSet:\"%s\"]", readStateV2.DefaultCPUSet)
  124. return err
  125. }
  126. var tmpContainerCPUSet cpuset.CPUSet
  127. tmpAssignments := ContainerCPUAssignments{}
  128. for pod := range readStateV2.Entries {
  129. tmpAssignments[pod] = make(map[string]cpuset.CPUSet)
  130. for container, cpuString := range readStateV2.Entries[pod] {
  131. if tmpContainerCPUSet, err = cpuset.Parse(cpuString); err != nil {
  132. klog.Errorf("[cpumanager] state file: could not parse state file - pod: %s, container: %s, cpuset: \"%s\"", pod, container, cpuString)
  133. return err
  134. }
  135. tmpAssignments[pod][container] = tmpContainerCPUSet
  136. }
  137. }
  138. sf.cache.SetDefaultCPUSet(tmpDefaultCPUSet)
  139. sf.cache.SetCPUAssignments(tmpAssignments)
  140. klog.V(2).Infof("[cpumanager] state file: restored state from state file \"%s\"", sf.stateFilePath)
  141. klog.V(2).Infof("[cpumanager] state file: defaultCPUSet: %s", tmpDefaultCPUSet.String())
  142. return nil
  143. }
  144. // saves state to a file, caller is responsible for locking
  145. func (sf *stateFile) storeState() error {
  146. var content []byte
  147. var err error
  148. data := stateFileDataV2{
  149. PolicyName: sf.policyName,
  150. DefaultCPUSet: sf.cache.GetDefaultCPUSet().String(),
  151. Entries: map[string]map[string]string{},
  152. }
  153. assignments := sf.cache.GetCPUAssignments()
  154. for pod := range assignments {
  155. data.Entries[pod] = map[string]string{}
  156. for container, cset := range assignments[pod] {
  157. data.Entries[pod][container] = cset.String()
  158. }
  159. }
  160. if content, err = json.Marshal(data); err != nil {
  161. return fmt.Errorf("[cpumanager] state file: could not serialize state to json")
  162. }
  163. if err = ioutil.WriteFile(sf.stateFilePath, content, 0644); err != nil {
  164. return fmt.Errorf("[cpumanager] state file not written")
  165. }
  166. return nil
  167. }
  168. func (sf *stateFile) GetCPUSet(podUID string, containerName string) (cpuset.CPUSet, bool) {
  169. sf.RLock()
  170. defer sf.RUnlock()
  171. res, ok := sf.cache.GetCPUSet(podUID, containerName)
  172. return res, ok
  173. }
  174. func (sf *stateFile) GetDefaultCPUSet() cpuset.CPUSet {
  175. sf.RLock()
  176. defer sf.RUnlock()
  177. return sf.cache.GetDefaultCPUSet()
  178. }
  179. func (sf *stateFile) GetCPUSetOrDefault(podUID string, containerName string) cpuset.CPUSet {
  180. sf.RLock()
  181. defer sf.RUnlock()
  182. return sf.cache.GetCPUSetOrDefault(podUID, containerName)
  183. }
  184. func (sf *stateFile) GetCPUAssignments() ContainerCPUAssignments {
  185. sf.RLock()
  186. defer sf.RUnlock()
  187. return sf.cache.GetCPUAssignments()
  188. }
  189. func (sf *stateFile) SetCPUSet(podUID string, containerName string, cset cpuset.CPUSet) {
  190. sf.Lock()
  191. defer sf.Unlock()
  192. sf.cache.SetCPUSet(podUID, containerName, cset)
  193. err := sf.storeState()
  194. if err != nil {
  195. klog.Warningf("store state to checkpoint error: %v", err)
  196. }
  197. }
  198. func (sf *stateFile) SetDefaultCPUSet(cset cpuset.CPUSet) {
  199. sf.Lock()
  200. defer sf.Unlock()
  201. sf.cache.SetDefaultCPUSet(cset)
  202. err := sf.storeState()
  203. if err != nil {
  204. klog.Warningf("store state to checkpoint error: %v", err)
  205. }
  206. }
  207. func (sf *stateFile) SetCPUAssignments(a ContainerCPUAssignments) {
  208. sf.Lock()
  209. defer sf.Unlock()
  210. sf.cache.SetCPUAssignments(a)
  211. err := sf.storeState()
  212. if err != nil {
  213. klog.Warningf("store state to checkpoint error: %v", err)
  214. }
  215. }
  216. func (sf *stateFile) Delete(podUID string, containerName string) {
  217. sf.Lock()
  218. defer sf.Unlock()
  219. sf.cache.Delete(podUID, containerName)
  220. err := sf.storeState()
  221. if err != nil {
  222. klog.Warningf("store state to checkpoint error: %v", err)
  223. }
  224. }
  225. func (sf *stateFile) ClearState() {
  226. sf.Lock()
  227. defer sf.Unlock()
  228. sf.cache.ClearState()
  229. err := sf.storeState()
  230. if err != nil {
  231. klog.Warningf("store state to checkpoint error: %v", err)
  232. }
  233. }