devices.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. "fmt"
  16. "os"
  17. "path/filepath"
  18. specs "github.com/opencontainers/runtime-spec/specs-go"
  19. )
  20. const (
  21. allowDeviceFile = "devices.allow"
  22. denyDeviceFile = "devices.deny"
  23. wildcard = -1
  24. )
  25. func NewDevices(root string) *devicesController {
  26. return &devicesController{
  27. root: filepath.Join(root, string(Devices)),
  28. }
  29. }
  30. type devicesController struct {
  31. root string
  32. }
  33. func (d *devicesController) Name() Name {
  34. return Devices
  35. }
  36. func (d *devicesController) Path(path string) string {
  37. return filepath.Join(d.root, path)
  38. }
  39. func (d *devicesController) Create(path string, resources *specs.LinuxResources) error {
  40. if err := os.MkdirAll(d.Path(path), defaultDirPerm); err != nil {
  41. return err
  42. }
  43. for _, device := range resources.Devices {
  44. file := denyDeviceFile
  45. if device.Allow {
  46. file = allowDeviceFile
  47. }
  48. if device.Type == "" {
  49. device.Type = "a"
  50. }
  51. if err := os.WriteFile(
  52. filepath.Join(d.Path(path), file),
  53. []byte(deviceString(device)),
  54. defaultFilePerm,
  55. ); err != nil {
  56. return err
  57. }
  58. }
  59. return nil
  60. }
  61. func (d *devicesController) Update(path string, resources *specs.LinuxResources) error {
  62. return d.Create(path, resources)
  63. }
  64. func deviceString(device specs.LinuxDeviceCgroup) string {
  65. return fmt.Sprintf("%s %s:%s %s",
  66. device.Type,
  67. deviceNumber(device.Major),
  68. deviceNumber(device.Minor),
  69. device.Access,
  70. )
  71. }
  72. func deviceNumber(number *int64) string {
  73. if number == nil || *number == wildcard {
  74. return "*"
  75. }
  76. return fmt.Sprint(*number)
  77. }