...

Source file src/github.com/containerd/cgroups/devices.go

Documentation: github.com/containerd/cgroups

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package cgroups
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"path/filepath"
    23  
    24  	specs "github.com/opencontainers/runtime-spec/specs-go"
    25  )
    26  
    27  const (
    28  	allowDeviceFile = "devices.allow"
    29  	denyDeviceFile  = "devices.deny"
    30  	wildcard        = -1
    31  )
    32  
    33  func NewDevices(root string) *devicesController {
    34  	return &devicesController{
    35  		root: filepath.Join(root, string(Devices)),
    36  	}
    37  }
    38  
    39  type devicesController struct {
    40  	root string
    41  }
    42  
    43  func (d *devicesController) Name() Name {
    44  	return Devices
    45  }
    46  
    47  func (d *devicesController) Path(path string) string {
    48  	return filepath.Join(d.root, path)
    49  }
    50  
    51  func (d *devicesController) Create(path string, resources *specs.LinuxResources) error {
    52  	if err := os.MkdirAll(d.Path(path), defaultDirPerm); err != nil {
    53  		return err
    54  	}
    55  	for _, device := range resources.Devices {
    56  		file := denyDeviceFile
    57  		if device.Allow {
    58  			file = allowDeviceFile
    59  		}
    60  		if device.Type == "" {
    61  			device.Type = "a"
    62  		}
    63  		if err := retryingWriteFile(
    64  			filepath.Join(d.Path(path), file),
    65  			[]byte(deviceString(device)),
    66  			defaultFilePerm,
    67  		); err != nil {
    68  			return err
    69  		}
    70  	}
    71  	return nil
    72  }
    73  
    74  func (d *devicesController) Update(path string, resources *specs.LinuxResources) error {
    75  	return d.Create(path, resources)
    76  }
    77  
    78  func deviceString(device specs.LinuxDeviceCgroup) string {
    79  	return fmt.Sprintf("%s %s:%s %s",
    80  		device.Type,
    81  		deviceNumber(device.Major),
    82  		deviceNumber(device.Minor),
    83  		device.Access,
    84  	)
    85  }
    86  
    87  func deviceNumber(number *int64) string {
    88  	if number == nil || *number == wildcard {
    89  		return "*"
    90  	}
    91  	return fmt.Sprint(*number)
    92  }
    93  

View as plain text