2019-10-17 15:00:27 +08:00
|
|
|
// +build linux
|
|
|
|
|
2019-11-07 16:25:49 +08:00
|
|
|
package fs2
|
2019-10-17 15:00:27 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/opencontainers/runc/libcontainer/cgroups/ebpf"
|
|
|
|
"github.com/opencontainers/runc/libcontainer/cgroups/ebpf/devicefilter"
|
|
|
|
"github.com/opencontainers/runc/libcontainer/configs"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"golang.org/x/sys/unix"
|
|
|
|
)
|
|
|
|
|
|
|
|
func isRWM(cgroupPermissions string) bool {
|
|
|
|
r := false
|
|
|
|
w := false
|
|
|
|
m := false
|
|
|
|
for _, rn := range cgroupPermissions {
|
|
|
|
switch rn {
|
|
|
|
case 'r':
|
|
|
|
r = true
|
|
|
|
case 'w':
|
|
|
|
w = true
|
|
|
|
case 'm':
|
|
|
|
m = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return r && w && m
|
|
|
|
}
|
|
|
|
|
|
|
|
// the logic is from crun
|
|
|
|
// https://github.com/containers/crun/blob/0.10.2/src/libcrun/cgroup.c#L1644-L1652
|
|
|
|
func canSkipEBPFError(cgroup *configs.Cgroup) bool {
|
|
|
|
for _, dev := range cgroup.Resources.Devices {
|
|
|
|
if dev.Allow || !isRWM(dev.Permissions) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-11-07 16:25:49 +08:00
|
|
|
func setDevices(dirPath string, cgroup *configs.Cgroup) error {
|
2019-12-06 14:53:07 +08:00
|
|
|
devices := cgroup.Devices
|
|
|
|
if allowAllDevices := cgroup.Resources.AllowAllDevices; allowAllDevices != nil {
|
|
|
|
// never set by OCI specconv, but *allowAllDevices=false is still used by the integration test
|
|
|
|
if *allowAllDevices == true {
|
|
|
|
return errors.New("libcontainer AllowAllDevices is not supported, use Devices")
|
|
|
|
}
|
|
|
|
for _, ad := range cgroup.Resources.AllowedDevices {
|
|
|
|
d := *ad
|
|
|
|
d.Allow = true
|
|
|
|
devices = append(devices, &d)
|
|
|
|
}
|
2019-10-17 15:00:27 +08:00
|
|
|
}
|
|
|
|
if len(cgroup.Resources.DeniedDevices) != 0 {
|
|
|
|
// never set by OCI specconv
|
|
|
|
return errors.New("libcontainer DeniedDevices is not supported, use Devices")
|
|
|
|
}
|
2019-12-06 14:53:07 +08:00
|
|
|
insts, license, err := devicefilter.DeviceFilter(devices)
|
2019-10-17 15:00:27 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-11-07 16:25:49 +08:00
|
|
|
dirFD, err := unix.Open(dirPath, unix.O_DIRECTORY|unix.O_RDONLY, 0600)
|
2019-10-17 15:00:27 +08:00
|
|
|
if err != nil {
|
2019-11-07 16:25:49 +08:00
|
|
|
return errors.Errorf("cannot get dir FD for %s", dirPath)
|
2019-10-17 15:00:27 +08:00
|
|
|
}
|
|
|
|
defer unix.Close(dirFD)
|
|
|
|
if _, err := ebpf.LoadAttachCgroupDeviceFilter(insts, license, dirFD); err != nil {
|
|
|
|
if !canSkipEBPFError(cgroup) {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|