freezer.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright The containerd 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 cgroup1
  14. import (
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. "time"
  19. )
  20. func NewFreezer(root string) *freezerController {
  21. return &freezerController{
  22. root: filepath.Join(root, string(Freezer)),
  23. }
  24. }
  25. type freezerController struct {
  26. root string
  27. }
  28. func (f *freezerController) Name() Name {
  29. return Freezer
  30. }
  31. func (f *freezerController) Path(path string) string {
  32. return filepath.Join(f.root, path)
  33. }
  34. func (f *freezerController) Freeze(path string) error {
  35. return f.waitState(path, Frozen)
  36. }
  37. func (f *freezerController) Thaw(path string) error {
  38. return f.waitState(path, Thawed)
  39. }
  40. func (f *freezerController) changeState(path string, state State) error {
  41. return os.WriteFile(
  42. filepath.Join(f.root, path, "freezer.state"),
  43. []byte(strings.ToUpper(string(state))),
  44. defaultFilePerm,
  45. )
  46. }
  47. func (f *freezerController) state(path string) (State, error) {
  48. current, err := os.ReadFile(filepath.Join(f.root, path, "freezer.state"))
  49. if err != nil {
  50. return "", err
  51. }
  52. return State(strings.ToLower(strings.TrimSpace(string(current)))), nil
  53. }
  54. func (f *freezerController) waitState(path string, state State) error {
  55. for {
  56. if err := f.changeState(path, state); err != nil {
  57. return err
  58. }
  59. current, err := f.state(path)
  60. if err != nil {
  61. return err
  62. }
  63. if current == state {
  64. return nil
  65. }
  66. time.Sleep(1 * time.Millisecond)
  67. }
  68. }