state_file.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. "k8s.io/klog"
  19. "k8s.io/kubernetes/pkg/kubelet/cm/cpuset"
  20. "os"
  21. "sync"
  22. )
  23. type stateFileData struct {
  24. PolicyName string `json:"policyName"`
  25. DefaultCPUSet string `json:"defaultCpuSet"`
  26. Entries map[string]string `json:"entries,omitempty"`
  27. }
  28. var _ State = &stateFile{}
  29. type stateFile struct {
  30. sync.RWMutex
  31. stateFilePath string
  32. policyName string
  33. cache State
  34. }
  35. // NewFileState creates new State for keeping track of cpu/pod assignment with file backend
  36. func NewFileState(filePath string, policyName string) State {
  37. stateFile := &stateFile{
  38. stateFilePath: filePath,
  39. cache: NewMemoryState(),
  40. policyName: policyName,
  41. }
  42. if err := stateFile.tryRestoreState(); err != nil {
  43. // could not restore state, init new state file
  44. msg := fmt.Sprintf("[cpumanager] state file: unable to restore state from disk (%s)\n", err.Error()) +
  45. "Panicking because we cannot guarantee sane CPU affinity for existing containers.\n" +
  46. fmt.Sprintf("Please drain this node and delete the CPU manager state file \"%s\" before restarting Kubelet.", stateFile.stateFilePath)
  47. panic(msg)
  48. }
  49. return stateFile
  50. }
  51. // tryRestoreState tries to read state file, upon any error,
  52. // err message is logged and state is left clean. un-initialized
  53. func (sf *stateFile) tryRestoreState() error {
  54. sf.Lock()
  55. defer sf.Unlock()
  56. var err error
  57. // used when all parsing is ok
  58. tmpAssignments := make(ContainerCPUAssignments)
  59. tmpDefaultCPUSet := cpuset.NewCPUSet()
  60. tmpContainerCPUSet := cpuset.NewCPUSet()
  61. var content []byte
  62. content, err = ioutil.ReadFile(sf.stateFilePath)
  63. // If the state file does not exist or has zero length, write a new file.
  64. if os.IsNotExist(err) || len(content) == 0 {
  65. sf.storeState()
  66. klog.Infof("[cpumanager] state file: created new state file \"%s\"", sf.stateFilePath)
  67. return nil
  68. }
  69. // Fail on any other file read error.
  70. if err != nil {
  71. return err
  72. }
  73. // File exists; try to read it.
  74. var readState stateFileData
  75. if err = json.Unmarshal(content, &readState); err != nil {
  76. klog.Errorf("[cpumanager] state file: could not unmarshal, corrupted state file - \"%s\"", sf.stateFilePath)
  77. return err
  78. }
  79. if sf.policyName != readState.PolicyName {
  80. return fmt.Errorf("policy configured \"%s\" != policy from state file \"%s\"", sf.policyName, readState.PolicyName)
  81. }
  82. if tmpDefaultCPUSet, err = cpuset.Parse(readState.DefaultCPUSet); err != nil {
  83. klog.Errorf("[cpumanager] state file: could not parse state file - [defaultCpuSet:\"%s\"]", readState.DefaultCPUSet)
  84. return err
  85. }
  86. for containerID, cpuString := range readState.Entries {
  87. if tmpContainerCPUSet, err = cpuset.Parse(cpuString); err != nil {
  88. klog.Errorf("[cpumanager] state file: could not parse state file - container id: %s, cpuset: \"%s\"", containerID, cpuString)
  89. return err
  90. }
  91. tmpAssignments[containerID] = tmpContainerCPUSet
  92. }
  93. sf.cache.SetDefaultCPUSet(tmpDefaultCPUSet)
  94. sf.cache.SetCPUAssignments(tmpAssignments)
  95. klog.V(2).Infof("[cpumanager] state file: restored state from state file \"%s\"", sf.stateFilePath)
  96. klog.V(2).Infof("[cpumanager] state file: defaultCPUSet: %s", tmpDefaultCPUSet.String())
  97. return nil
  98. }
  99. // saves state to a file, caller is responsible for locking
  100. func (sf *stateFile) storeState() {
  101. var content []byte
  102. var err error
  103. data := stateFileData{
  104. PolicyName: sf.policyName,
  105. DefaultCPUSet: sf.cache.GetDefaultCPUSet().String(),
  106. Entries: map[string]string{},
  107. }
  108. for containerID, cset := range sf.cache.GetCPUAssignments() {
  109. data.Entries[containerID] = cset.String()
  110. }
  111. if content, err = json.Marshal(data); err != nil {
  112. panic("[cpumanager] state file: could not serialize state to json")
  113. }
  114. if err = ioutil.WriteFile(sf.stateFilePath, content, 0644); err != nil {
  115. panic("[cpumanager] state file not written")
  116. }
  117. return
  118. }
  119. func (sf *stateFile) GetCPUSet(containerID string) (cpuset.CPUSet, bool) {
  120. sf.RLock()
  121. defer sf.RUnlock()
  122. res, ok := sf.cache.GetCPUSet(containerID)
  123. return res, ok
  124. }
  125. func (sf *stateFile) GetDefaultCPUSet() cpuset.CPUSet {
  126. sf.RLock()
  127. defer sf.RUnlock()
  128. return sf.cache.GetDefaultCPUSet()
  129. }
  130. func (sf *stateFile) GetCPUSetOrDefault(containerID string) cpuset.CPUSet {
  131. sf.RLock()
  132. defer sf.RUnlock()
  133. return sf.cache.GetCPUSetOrDefault(containerID)
  134. }
  135. func (sf *stateFile) GetCPUAssignments() ContainerCPUAssignments {
  136. sf.RLock()
  137. defer sf.RUnlock()
  138. return sf.cache.GetCPUAssignments()
  139. }
  140. func (sf *stateFile) SetCPUSet(containerID string, cset cpuset.CPUSet) {
  141. sf.Lock()
  142. defer sf.Unlock()
  143. sf.cache.SetCPUSet(containerID, cset)
  144. sf.storeState()
  145. }
  146. func (sf *stateFile) SetDefaultCPUSet(cset cpuset.CPUSet) {
  147. sf.Lock()
  148. defer sf.Unlock()
  149. sf.cache.SetDefaultCPUSet(cset)
  150. sf.storeState()
  151. }
  152. func (sf *stateFile) SetCPUAssignments(a ContainerCPUAssignments) {
  153. sf.Lock()
  154. defer sf.Unlock()
  155. sf.cache.SetCPUAssignments(a)
  156. sf.storeState()
  157. }
  158. func (sf *stateFile) Delete(containerID string) {
  159. sf.Lock()
  160. defer sf.Unlock()
  161. sf.cache.Delete(containerID)
  162. sf.storeState()
  163. }
  164. func (sf *stateFile) ClearState() {
  165. sf.Lock()
  166. defer sf.Unlock()
  167. sf.cache.ClearState()
  168. sf.storeState()
  169. }