Use gofumpt to format code

gofumpt (mvdan.cc/gofumpt) is a fork of gofmt with stricter rules.

Brought to you by

	git ls-files \*.go | grep -v ^vendor/ | xargs gofumpt -s -w

Looking at the diff, all these changes make sense.

Also, replace gofmt with gofumpt in golangci.yml.

Signed-off-by: Kir Kolyshkin <kolyshkin@gmail.com>
This commit is contained in:
Kir Kolyshkin
2021-06-01 11:56:21 -07:00
parent 3a0234e1fe
commit e6048715e4
75 changed files with 195 additions and 216 deletions

View File

@@ -6,4 +6,4 @@ run:
linters: linters:
enable: enable:
- gofmt - gofumpt

View File

@@ -85,7 +85,7 @@ func prepareImagePaths(context *cli.Context) (string, string, error) {
imagePath = getDefaultImagePath(context) imagePath = getDefaultImagePath(context)
} }
if err := os.MkdirAll(imagePath, 0600); err != nil { if err := os.MkdirAll(imagePath, 0o600); err != nil {
return "", "", err return "", "", err
} }
@@ -109,7 +109,6 @@ func prepareImagePaths(context *cli.Context) (string, string, error) {
} }
return imagePath, parentPath, nil return imagePath, parentPath, nil
} }
func setPageServer(context *cli.Context, options *libcontainer.CriuOpts) { func setPageServer(context *cli.Context, options *libcontainer.CriuOpts) {

View File

@@ -224,7 +224,7 @@ func main() {
pidPath := ctx.String("pid-file") pidPath := ctx.String("pid-file")
if pidPath != "" { if pidPath != "" {
pid := fmt.Sprintf("%d\n", os.Getpid()) pid := fmt.Sprintf("%d\n", os.Getpid())
if err := ioutil.WriteFile(pidPath, []byte(pid), 0644); err != nil { if err := ioutil.WriteFile(pidPath, []byte(pid), 0o644); err != nil {
return err return err
} }
} }

View File

@@ -14,8 +14,7 @@ import (
"github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/configs"
) )
type BlkioGroup struct { type BlkioGroup struct{}
}
func (s *BlkioGroup) Name() string { func (s *BlkioGroup) Name() string {
return "blkio" return "blkio"
@@ -161,7 +160,7 @@ func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
filename string filename string
blkioStatEntriesPtr *[]cgroups.BlkioStatEntry blkioStatEntriesPtr *[]cgroups.BlkioStatEntry
} }
var bfqDebugStats = []blkioStatInfo{ bfqDebugStats := []blkioStatInfo{
{ {
filename: "blkio.bfq.sectors_recursive", filename: "blkio.bfq.sectors_recursive",
blkioStatEntriesPtr: &stats.BlkioStats.SectorsRecursive, blkioStatEntriesPtr: &stats.BlkioStats.SectorsRecursive,
@@ -195,7 +194,7 @@ func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive, blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive,
}, },
} }
var bfqStats = []blkioStatInfo{ bfqStats := []blkioStatInfo{
{ {
filename: "blkio.bfq.io_serviced_recursive", filename: "blkio.bfq.io_serviced_recursive",
blkioStatEntriesPtr: &stats.BlkioStats.IoServicedRecursive, blkioStatEntriesPtr: &stats.BlkioStats.IoServicedRecursive,
@@ -205,7 +204,7 @@ func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive, blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive,
}, },
} }
var cfqStats = []blkioStatInfo{ cfqStats := []blkioStatInfo{
{ {
filename: "blkio.sectors_recursive", filename: "blkio.sectors_recursive",
blkioStatEntriesPtr: &stats.BlkioStats.SectorsRecursive, blkioStatEntriesPtr: &stats.BlkioStats.SectorsRecursive,
@@ -239,7 +238,7 @@ func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive, blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive,
}, },
} }
var throttleRecursiveStats = []blkioStatInfo{ throttleRecursiveStats := []blkioStatInfo{
{ {
filename: "blkio.throttle.io_serviced_recursive", filename: "blkio.throttle.io_serviced_recursive",
blkioStatEntriesPtr: &stats.BlkioStats.IoServicedRecursive, blkioStatEntriesPtr: &stats.BlkioStats.IoServicedRecursive,
@@ -249,7 +248,7 @@ func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive, blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive,
}, },
} }
var baseStats = []blkioStatInfo{ baseStats := []blkioStatInfo{
{ {
filename: "blkio.throttle.io_serviced", filename: "blkio.throttle.io_serviced",
blkioStatEntriesPtr: &stats.BlkioStats.IoServicedRecursive, blkioStatEntriesPtr: &stats.BlkioStats.IoServicedRecursive,
@@ -259,7 +258,7 @@ func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive, blkioStatEntriesPtr: &stats.BlkioStats.IoServiceBytesRecursive,
}, },
} }
var orderedStats = [][]blkioStatInfo{ orderedStats := [][]blkioStatInfo{
bfqDebugStats, bfqDebugStats,
bfqStats, bfqStats,
cfqStats, cfqStats,
@@ -280,7 +279,7 @@ func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
return err return err
} }
*statInfo.blkioStatEntriesPtr = blkioStats *statInfo.blkioStatEntriesPtr = blkioStats
//finish if all stats are gathered // finish if all stats are gathered
if i == len(statGroup)-1 { if i == len(statGroup)-1 {
return nil return nil
} }

View File

@@ -459,7 +459,6 @@ func TestBlkioStatsNoFilesBFQDebug(t *testing.T) {
cpuset := &CpusetGroup{} cpuset := &CpusetGroup{}
actualStats := *cgroups.NewStats() actualStats := *cgroups.NewStats()
err := cpuset.GetStats(helper.CgroupPath, &actualStats) err := cpuset.GetStats(helper.CgroupPath, &actualStats)
if err != nil { if err != nil {
t.Errorf(fmt.Sprintf("test case '%s' failed unexpectedly: %s", testCase.desc, err)) t.Errorf(fmt.Sprintf("test case '%s' failed unexpectedly: %s", testCase.desc, err))
} }
@@ -576,7 +575,6 @@ func TestBlkioStatsNoFilesCFQ(t *testing.T) {
cpuset := &CpusetGroup{} cpuset := &CpusetGroup{}
actualStats := *cgroups.NewStats() actualStats := *cgroups.NewStats()
err := cpuset.GetStats(helper.CgroupPath, &actualStats) err := cpuset.GetStats(helper.CgroupPath, &actualStats)
if err != nil { if err != nil {
t.Errorf(fmt.Sprintf("test case '%s' failed unexpectedly: %s", testCase.desc, err)) t.Errorf(fmt.Sprintf("test case '%s' failed unexpectedly: %s", testCase.desc, err))
} }
@@ -759,6 +757,7 @@ func TestBlkioSetThrottleReadBpsDevice(t *testing.T) {
t.Fatal("Got the wrong value, set blkio.throttle.read_bps_device failed.") t.Fatal("Got the wrong value, set blkio.throttle.read_bps_device failed.")
} }
} }
func TestBlkioSetThrottleWriteBpsDevice(t *testing.T) { func TestBlkioSetThrottleWriteBpsDevice(t *testing.T) {
helper := NewCgroupTestUtil("blkio", t) helper := NewCgroupTestUtil("blkio", t)
defer helper.cleanup() defer helper.cleanup()
@@ -789,6 +788,7 @@ func TestBlkioSetThrottleWriteBpsDevice(t *testing.T) {
t.Fatal("Got the wrong value, set blkio.throttle.write_bps_device failed.") t.Fatal("Got the wrong value, set blkio.throttle.write_bps_device failed.")
} }
} }
func TestBlkioSetThrottleReadIOpsDevice(t *testing.T) { func TestBlkioSetThrottleReadIOpsDevice(t *testing.T) {
helper := NewCgroupTestUtil("blkio", t) helper := NewCgroupTestUtil("blkio", t)
defer helper.cleanup() defer helper.cleanup()
@@ -819,6 +819,7 @@ func TestBlkioSetThrottleReadIOpsDevice(t *testing.T) {
t.Fatal("Got the wrong value, set blkio.throttle.read_iops_device failed.") t.Fatal("Got the wrong value, set blkio.throttle.read_iops_device failed.")
} }
} }
func TestBlkioSetThrottleWriteIOpsDevice(t *testing.T) { func TestBlkioSetThrottleWriteIOpsDevice(t *testing.T) {
helper := NewCgroupTestUtil("blkio", t) helper := NewCgroupTestUtil("blkio", t)
defer helper.cleanup() defer helper.cleanup()

View File

@@ -13,8 +13,7 @@ import (
"github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/configs"
) )
type CpuGroup struct { type CpuGroup struct{}
}
func (s *CpuGroup) Name() string { func (s *CpuGroup) Name() string {
return "cpu" return "cpu"
@@ -26,7 +25,7 @@ func (s *CpuGroup) Apply(path string, d *cgroupData) error {
if path == "" { if path == "" {
return nil return nil
} }
if err := os.MkdirAll(path, 0755); err != nil { if err := os.MkdirAll(path, 0o755); err != nil {
return err return err
} }
// We should set the real-Time group scheduling settings before moving // We should set the real-Time group scheduling settings before moving

View File

@@ -128,7 +128,8 @@ func TestCpuStats(t *testing.T) {
expectedStats := cgroups.ThrottlingData{ expectedStats := cgroups.ThrottlingData{
Periods: nrPeriods, Periods: nrPeriods,
ThrottledPeriods: nrThrottled, ThrottledPeriods: nrThrottled,
ThrottledTime: throttledTime} ThrottledTime: throttledTime,
}
expectThrottlingDataEquals(t, expectedStats, actualStats.CpuStats.ThrottlingData) expectThrottlingDataEquals(t, expectedStats, actualStats.CpuStats.ThrottlingData)
} }

View File

@@ -32,8 +32,7 @@ const (
clockTicks uint64 = 100 clockTicks uint64 = 100
) )
type CpuacctGroup struct { type CpuacctGroup struct{}
}
func (s *CpuacctGroup) Name() string { func (s *CpuacctGroup) Name() string {
return "cpuacct" return "cpuacct"
@@ -144,7 +143,7 @@ func getPercpuUsageInModes(path string) ([]uint64, []uint64, error) {
defer file.Close() defer file.Close()
scanner := bufio.NewScanner(file) scanner := bufio.NewScanner(file)
scanner.Scan() //skipping header line scanner.Scan() // skipping header line
for scanner.Scan() { for scanner.Scan() {
lineFields := strings.SplitN(scanner.Text(), " ", cuacctUsageAllColumnsNumber+1) lineFields := strings.SplitN(scanner.Text(), " ", cuacctUsageAllColumnsNumber+1)

View File

@@ -44,12 +44,18 @@ func TestCpuacctStats(t *testing.T) {
expectedStats := cgroups.CpuUsage{ expectedStats := cgroups.CpuUsage{
TotalUsage: uint64(12262454190222160), TotalUsage: uint64(12262454190222160),
PercpuUsage: []uint64{1564936537989058, 1583937096487821, 1604195415465681, 1596445226820187, PercpuUsage: []uint64{
1481069084155629, 1478735613864327, 1477610593414743, 1476362015778086}, 1564936537989058, 1583937096487821, 1604195415465681, 1596445226820187,
PercpuUsageInKernelmode: []uint64{637727786389114, 638197595421064, 638956774598358, 637985531181620, 1481069084155629, 1478735613864327, 1477610593414743, 1476362015778086,
638837766495476, 638763309884944, 640081778921247, 638716766259495}, },
PercpuUsageInUsermode: []uint64{962250696038415, 981956408513304, 1002658817529022, 994937703492523, PercpuUsageInKernelmode: []uint64{
874843781648690, 872544369885276, 870104915696359, 870202363887496}, 637727786389114, 638197595421064, 638956774598358, 637985531181620,
638837766495476, 638763309884944, 640081778921247, 638716766259495,
},
PercpuUsageInUsermode: []uint64{
962250696038415, 981956408513304, 1002658817529022, 994937703492523,
874843781648690, 872544369885276, 870104915696359, 870202363887496,
},
UsageInKernelmode: (uint64(291429664) * nanosecondsInSecond) / clockTicks, UsageInKernelmode: (uint64(291429664) * nanosecondsInSecond) / clockTicks,
UsageInUsermode: (uint64(452278264) * nanosecondsInSecond) / clockTicks, UsageInUsermode: (uint64(452278264) * nanosecondsInSecond) / clockTicks,
} }
@@ -78,8 +84,10 @@ func TestCpuacctStatsWithoutUsageAll(t *testing.T) {
expectedStats := cgroups.CpuUsage{ expectedStats := cgroups.CpuUsage{
TotalUsage: uint64(12262454190222160), TotalUsage: uint64(12262454190222160),
PercpuUsage: []uint64{1564936537989058, 1583937096487821, 1604195415465681, 1596445226820187, PercpuUsage: []uint64{
1481069084155629, 1478735613864327, 1477610593414743, 1476362015778086}, 1564936537989058, 1583937096487821, 1604195415465681, 1596445226820187,
1481069084155629, 1478735613864327, 1477610593414743, 1476362015778086,
},
PercpuUsageInKernelmode: []uint64{}, PercpuUsageInKernelmode: []uint64{},
PercpuUsageInUsermode: []uint64{}, PercpuUsageInUsermode: []uint64{},
UsageInKernelmode: (uint64(291429664) * nanosecondsInSecond) / clockTicks, UsageInKernelmode: (uint64(291429664) * nanosecondsInSecond) / clockTicks,

View File

@@ -16,8 +16,7 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
type CpusetGroup struct { type CpusetGroup struct{}
}
func (s *CpusetGroup) Name() string { func (s *CpusetGroup) Name() string {
return "cpuset" return "cpuset"
@@ -156,7 +155,7 @@ func (s *CpusetGroup) ApplyDir(dir string, r *configs.Resources, pid int) error
if err := cpusetEnsureParent(filepath.Dir(dir)); err != nil { if err := cpusetEnsureParent(filepath.Dir(dir)); err != nil {
return err return err
} }
if err := os.Mkdir(dir, 0755); err != nil && !os.IsExist(err) { if err := os.Mkdir(dir, 0o755); err != nil && !os.IsExist(err) {
return err return err
} }
// We didn't inherit cpuset configs from parent, but we have // We didn't inherit cpuset configs from parent, but we have
@@ -206,7 +205,7 @@ func cpusetEnsureParent(current string) error {
if err := cpusetEnsureParent(parent); err != nil { if err := cpusetEnsureParent(parent); err != nil {
return err return err
} }
if err := os.Mkdir(current, 0755); err != nil && !os.IsExist(err) { if err := os.Mkdir(current, 0o755); err != nil && !os.IsExist(err) {
return err return err
} }
return cpusetCopyIfNeeded(current, parent) return cpusetCopyIfNeeded(current, parent)

View File

@@ -118,12 +118,12 @@ func TestCPUSetStatsCorrect(t *testing.T) {
MemorySpreadSlab: 1, MemorySpreadSlab: 1,
MemoryPressure: 34377, MemoryPressure: 34377,
SchedLoadBalance: 1, SchedLoadBalance: 1,
SchedRelaxDomainLevel: -1} SchedRelaxDomainLevel: -1,
}
if !reflect.DeepEqual(expectedStats, actualStats.CPUSetStats) { if !reflect.DeepEqual(expectedStats, actualStats.CPUSetStats) {
t.Fatalf("Expected Cpuset stats usage %#v but found %#v", t.Fatalf("Expected Cpuset stats usage %#v but found %#v",
expectedStats, actualStats.CPUSetStats) expectedStats, actualStats.CPUSetStats)
} }
} }
func TestCPUSetStatsMissingFiles(t *testing.T) { func TestCPUSetStatsMissingFiles(t *testing.T) {
@@ -226,7 +226,6 @@ func TestCPUSetStatsMissingFiles(t *testing.T) {
cpuset := &CpusetGroup{} cpuset := &CpusetGroup{}
actualStats := *cgroups.NewStats() actualStats := *cgroups.NewStats()
err := cpuset.GetStats(helper.CgroupPath, &actualStats) err := cpuset.GetStats(helper.CgroupPath, &actualStats)
if err != nil { if err != nil {
t.Errorf("failed unexpectedly: %q", err) t.Errorf("failed unexpectedly: %q", err)
} }

View File

@@ -16,8 +16,7 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
type FreezerGroup struct { type FreezerGroup struct{}
}
func (s *FreezerGroup) Name() string { func (s *FreezerGroup) Name() string {
return "freezer" return "freezer"

View File

@@ -64,8 +64,10 @@ func NewManager(cg *configs.Cgroup, paths map[string]string, rootless bool) cgro
} }
// The absolute path to the root of the cgroup hierarchies. // The absolute path to the root of the cgroup hierarchies.
var cgroupRootLock sync.Mutex var (
var cgroupRoot string cgroupRootLock sync.Mutex
cgroupRoot string
)
const defaultCgroupRoot = "/sys/fs/cgroup" const defaultCgroupRoot = "/sys/fs/cgroup"
@@ -393,7 +395,7 @@ func join(path string, pid int) error {
if path == "" { if path == "" {
return nil return nil
} }
if err := os.MkdirAll(path, 0755); err != nil { if err := os.MkdirAll(path, 0o755); err != nil {
return err return err
} }
return cgroups.WriteCgroupProc(path, pid) return cgroups.WriteCgroupProc(path, pid)

View File

@@ -11,8 +11,7 @@ import (
"github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/configs"
) )
type HugetlbGroup struct { type HugetlbGroup struct{}
}
func (s *HugetlbGroup) Name() string { func (s *HugetlbGroup) Name() string {
return "hugetlb" return "hugetlb"

View File

@@ -25,8 +25,7 @@ const (
cgroupMemoryMaxUsage = "memory.max_usage_in_bytes" cgroupMemoryMaxUsage = "memory.max_usage_in_bytes"
) )
type MemoryGroup struct { type MemoryGroup struct{}
}
func (s *MemoryGroup) Name() string { func (s *MemoryGroup) Name() string {
return "memory" return "memory"

View File

@@ -194,7 +194,7 @@ func TestMemorySetMemorySwappinessDefault(t *testing.T) {
helper := NewCgroupTestUtil("memory", t) helper := NewCgroupTestUtil("memory", t)
defer helper.cleanup() defer helper.cleanup()
swappinessBefore := 60 //default is 60 swappinessBefore := 60 // default is 60
swappinessAfter := uint64(0) swappinessAfter := uint64(0)
helper.writeFileContents(map[string]string{ helper.writeFileContents(map[string]string{
@@ -243,7 +243,8 @@ func TestMemoryStats(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
expectedStats := cgroups.MemoryStats{Cache: 512, Usage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100, Limit: 8192}, SwapUsage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100, Limit: 8192}, KernelUsage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100, Limit: 8192}, Stats: map[string]uint64{"cache": 512, "rss": 1024}, UseHierarchy: true, expectedStats := cgroups.MemoryStats{
Cache: 512, Usage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100, Limit: 8192}, SwapUsage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100, Limit: 8192}, KernelUsage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100, Limit: 8192}, Stats: map[string]uint64{"cache": 512, "rss": 1024}, UseHierarchy: true,
PageUsageByNUMA: cgroups.PageUsageByNUMA{ PageUsageByNUMA: cgroups.PageUsageByNUMA{
PageUsageByNUMAInner: cgroups.PageUsageByNUMAInner{ PageUsageByNUMAInner: cgroups.PageUsageByNUMAInner{
Total: cgroups.PageStats{Total: 44611, Nodes: map[uint8]uint64{0: 32631, 1: 7501, 2: 1982, 3: 2497}}, Total: cgroups.PageStats{Total: 44611, Nodes: map[uint8]uint64{0: 32631, 1: 7501, 2: 1982, 3: 2497}},
@@ -257,7 +258,8 @@ func TestMemoryStats(t *testing.T) {
Anon: cgroups.PageStats{Total: 46096, Nodes: map[uint8]uint64{0: 12597, 1: 18890, 2: 283, 3: 14326}}, Anon: cgroups.PageStats{Total: 46096, Nodes: map[uint8]uint64{0: 12597, 1: 18890, 2: 283, 3: 14326}},
Unevictable: cgroups.PageStats{Total: 20, Nodes: map[uint8]uint64{0: 0, 1: 0, 2: 0, 3: 20}}, Unevictable: cgroups.PageStats{Total: 20, Nodes: map[uint8]uint64{0: 0, 1: 0, 2: 0, 3: 20}},
}, },
}} },
}
expectMemoryStatEquals(t, expectedStats, actualStats.MemoryStats) expectMemoryStatEquals(t, expectedStats, actualStats.MemoryStats)
} }

View File

@@ -10,8 +10,7 @@ import (
"github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/configs"
) )
type NetClsGroup struct { type NetClsGroup struct{}
}
func (s *NetClsGroup) Name() string { func (s *NetClsGroup) Name() string {
return "net_cls" return "net_cls"

View File

@@ -8,8 +8,7 @@ import (
"github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/configs"
) )
type NetPrioGroup struct { type NetPrioGroup struct{}
}
func (s *NetPrioGroup) Name() string { func (s *NetPrioGroup) Name() string {
return "net_prio" return "net_prio"

View File

@@ -10,14 +10,12 @@ import (
"github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/configs"
) )
var ( var prioMap = []*configs.IfPrioMap{
prioMap = []*configs.IfPrioMap{ {
{ Interface: "test",
Interface: "test", Priority: 5,
Priority: 5, },
}, }
}
)
func TestNetPrioSetIfPrio(t *testing.T) { func TestNetPrioSetIfPrio(t *testing.T) {
helper := NewCgroupTestUtil("net_prio", t) helper := NewCgroupTestUtil("net_prio", t)

View File

@@ -7,8 +7,7 @@ import (
"github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/configs"
) )
type PerfEventGroup struct { type PerfEventGroup struct{}
}
func (s *PerfEventGroup) Name() string { func (s *PerfEventGroup) Name() string {
return "perf_event" return "perf_event"

View File

@@ -12,8 +12,7 @@ import (
"github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/configs"
) )
type PidsGroup struct { type PidsGroup struct{}
}
func (s *PidsGroup) Name() string { func (s *PidsGroup) Name() string {
return "pids" return "pids"

View File

@@ -50,7 +50,7 @@ func NewCgroupTestUtil(subsystem string, t *testing.T) *cgroupTestUtil {
} }
// Ensure the full mock cgroup path exists. // Ensure the full mock cgroup path exists.
err = os.MkdirAll(testCgroupPath, 0755) err = os.MkdirAll(testCgroupPath, 0o755)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -47,6 +47,7 @@ func setCpu(dirPath string, r *configs.Resources) error {
return nil return nil
} }
func statCpu(dirPath string, stats *cgroups.Stats) error { func statCpu(dirPath string, stats *cgroups.Stats) error {
f, err := fscommon.OpenFile(dirPath, "cpu.stat", os.O_RDONLY) f, err := fscommon.OpenFile(dirPath, "cpu.stat", os.O_RDONLY)
if err != nil { if err != nil {

View File

@@ -92,7 +92,7 @@ func CreateCgroupPath(path string, c *configs.Cgroup) (Err error) {
for i, e := range elements { for i, e := range elements {
current = filepath.Join(current, e) current = filepath.Join(current, e)
if i > 0 { if i > 0 {
if err := os.Mkdir(current, 0755); err != nil { if err := os.Mkdir(current, 0o755); err != nil {
if !os.IsExist(err) { if !os.IsExist(err) {
return err return err
} }

View File

@@ -82,9 +82,7 @@ func parseCgroupFile(path string) (string, error) {
} }
func parseCgroupFromReader(r io.Reader) (string, error) { func parseCgroupFromReader(r io.Reader) (string, error) {
var ( s := bufio.NewScanner(r)
s = bufio.NewScanner(r)
)
for s.Scan() { for s.Scan() {
var ( var (
text = s.Text() text = s.Text()

View File

@@ -62,7 +62,7 @@ func setDevices(dirPath string, r *configs.Resources) error {
if err != nil { if err != nil {
return err return err
} }
dirFD, err := unix.Open(dirPath, unix.O_DIRECTORY|unix.O_RDONLY, 0600) dirFD, err := unix.Open(dirPath, unix.O_DIRECTORY|unix.O_RDONLY, 0o600)
if err != nil { if err != nil {
return errors.Errorf("cannot get dir FD for %s", dirPath) return errors.Errorf("cannot get dir FD for %s", dirPath)
} }

View File

@@ -98,9 +98,7 @@ func (m *manager) GetAllPids() ([]int, error) {
} }
func (m *manager) GetStats() (*cgroups.Stats, error) { func (m *manager) GetStats() (*cgroups.Stats, error) {
var ( var errs []error
errs []error
)
st := cgroups.NewStats() st := cgroups.NewStats()

View File

@@ -68,7 +68,7 @@ func TestStatIo(t *testing.T) {
defer os.RemoveAll(fakeCgroupDir) defer os.RemoveAll(fakeCgroupDir)
statPath := filepath.Join(fakeCgroupDir, "io.stat") statPath := filepath.Join(fakeCgroupDir, "io.stat")
if err := ioutil.WriteFile(statPath, []byte(exampleIoStatData), 0644); err != nil { if err := ioutil.WriteFile(statPath, []byte(exampleIoStatData), 0o644); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -23,7 +23,7 @@ func TestWriteCgroupFileHandlesInterrupt(t *testing.T) {
cgroupName := fmt.Sprintf("test-eint-%d", time.Now().Nanosecond()) cgroupName := fmt.Sprintf("test-eint-%d", time.Now().Nanosecond())
cgroupPath := filepath.Join(memoryCgroupMount, cgroupName) cgroupPath := filepath.Join(memoryCgroupMount, cgroupName)
if err := os.MkdirAll(cgroupPath, 0755); err != nil { if err := os.MkdirAll(cgroupPath, 0o755); err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(cgroupPath) defer os.RemoveAll(cgroupPath)

View File

@@ -28,7 +28,8 @@ var (
func prepareOpenat2() error { func prepareOpenat2() error {
prepOnce.Do(func() { prepOnce.Do(func() {
fd, err := unix.Openat2(-1, cgroupfsDir, &unix.OpenHow{ fd, err := unix.Openat2(-1, cgroupfsDir, &unix.OpenHow{
Flags: unix.O_DIRECTORY | unix.O_PATH}) Flags: unix.O_DIRECTORY | unix.O_PATH,
})
if err != nil { if err != nil {
prepErr = &os.PathError{Op: "openat2", Path: cgroupfsDir, Err: err} prepErr = &os.PathError{Op: "openat2", Path: cgroupfsDir, Err: err}
if err != unix.ENOSYS { if err != unix.ENOSYS {
@@ -52,7 +53,6 @@ func prepareOpenat2() error {
// cgroupv2 has a single mountpoint and no "cpu,cpuacct" symlinks // cgroupv2 has a single mountpoint and no "cpu,cpuacct" symlinks
resolveFlags |= unix.RESOLVE_NO_XDEV | unix.RESOLVE_NO_SYMLINKS resolveFlags |= unix.RESOLVE_NO_XDEV | unix.RESOLVE_NO_SYMLINKS
} }
}) })
return prepErr return prepErr

View File

@@ -10,9 +10,7 @@ import (
"strings" "strings"
) )
var ( var ErrNotValidFormat = errors.New("line is not a valid key value format")
ErrNotValidFormat = errors.New("line is not a valid key value format")
)
// ParseUint converts a string to an uint64 integer. // ParseUint converts a string to an uint64 integer.
// Negative values are returned at zero as, due to kernel bugs, // Negative values are returned at zero as, due to kernel bugs,

View File

@@ -31,7 +31,7 @@ func TestGetCgroupParamsInt(t *testing.T) {
tempFile := filepath.Join(tempDir, cgroupFile) tempFile := filepath.Join(tempDir, cgroupFile)
// Success. // Success.
err = ioutil.WriteFile(tempFile, []byte(floatString), 0755) err = ioutil.WriteFile(tempFile, []byte(floatString), 0o755)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -43,7 +43,7 @@ func TestGetCgroupParamsInt(t *testing.T) {
} }
// Success with new line. // Success with new line.
err = ioutil.WriteFile(tempFile, []byte(floatString+"\n"), 0755) err = ioutil.WriteFile(tempFile, []byte(floatString+"\n"), 0o755)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -55,7 +55,7 @@ func TestGetCgroupParamsInt(t *testing.T) {
} }
// Success with negative values // Success with negative values
err = ioutil.WriteFile(tempFile, []byte("-12345"), 0755) err = ioutil.WriteFile(tempFile, []byte("-12345"), 0o755)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -68,7 +68,7 @@ func TestGetCgroupParamsInt(t *testing.T) {
// Success with negative values lesser than min int64 // Success with negative values lesser than min int64
s := strconv.FormatFloat(math.MinInt64, 'f', -1, 64) s := strconv.FormatFloat(math.MinInt64, 'f', -1, 64)
err = ioutil.WriteFile(tempFile, []byte(s), 0755) err = ioutil.WriteFile(tempFile, []byte(s), 0o755)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -80,7 +80,7 @@ func TestGetCgroupParamsInt(t *testing.T) {
} }
// Not a float. // Not a float.
err = ioutil.WriteFile(tempFile, []byte("not-a-float"), 0755) err = ioutil.WriteFile(tempFile, []byte("not-a-float"), 0o755)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -17,8 +17,7 @@ var (
dbusRootless bool dbusRootless bool
) )
type dbusConnManager struct { type dbusConnManager struct{}
}
// newDbusConnManager initializes systemd dbus connection manager. // newDbusConnManager initializes systemd dbus connection manager.
func newDbusConnManager(rootless bool) *dbusConnManager { func newDbusConnManager(rootless bool) *dbusConnManager {

View File

@@ -13,7 +13,7 @@ import (
) )
func TestSystemdVersion(t *testing.T) { func TestSystemdVersion(t *testing.T) {
var systemdVersionTests = []struct { systemdVersionTests := []struct {
verStr string verStr string
expectedVer int expectedVer int
expectErr bool expectErr bool

View File

@@ -238,7 +238,7 @@ func (m *legacyManager) joinCgroups(pid int) error {
} }
default: default:
if path, ok := m.paths[name]; ok { if path, ok := m.paths[name]; ok {
if err := os.MkdirAll(path, 0755); err != nil { if err := os.MkdirAll(path, 0o755); err != nil {
return err return err
} }
if err := cgroups.WriteCgroupProc(path, pid); err != nil { if err := cgroups.WriteCgroupProc(path, pid); err != nil {

View File

@@ -267,7 +267,6 @@ func RemovePaths(paths map[string]string) (err error) {
case retries - 1: case retries - 1:
logrus.WithError(err).Error("Failed to remove cgroup") logrus.WithError(err).Error("Failed to remove cgroup")
} }
} }
_, err := os.Stat(p) _, err := os.Stat(p)
// We need this strange way of checking cgroups existence because // We need this strange way of checking cgroups existence because

View File

@@ -388,7 +388,6 @@ func TestParseCgroupString(t *testing.T) {
} }
} }
} }
} }
func TestIgnoreCgroup2Mount(t *testing.T) { func TestIgnoreCgroup2Mount(t *testing.T) {

View File

@@ -4,5 +4,4 @@ package configs
// TODO Windows: This can ultimately be entirely factored out on Windows as // TODO Windows: This can ultimately be entirely factored out on Windows as
// cgroups are a Unix-specific construct. // cgroups are a Unix-specific construct.
type Cgroup struct { type Cgroup struct{}
}

View File

@@ -208,9 +208,11 @@ type Config struct {
RootlessCgroups bool `json:"rootless_cgroups,omitempty"` RootlessCgroups bool `json:"rootless_cgroups,omitempty"`
} }
type HookName string type (
type HookList []Hook HookName string
type Hooks map[HookName]HookList HookList []Hook
Hooks map[HookName]HookList
)
const ( const (
// Prestart commands are executed after the container namespaces are created, // Prestart commands are executed after the container namespaces are created,

View File

@@ -4,9 +4,7 @@ import (
"testing" "testing"
) )
var ( var HookNameList = []HookName{Prestart, CreateRuntime, CreateContainer, StartContainer, Poststart, Poststop}
HookNameList = []HookName{Prestart, CreateRuntime, CreateContainer, StartContainer, Poststart, Poststop}
)
func TestRemoveNamespace(t *testing.T) { func TestRemoveNamespace(t *testing.T) {
ns := Namespaces{ ns := Namespaces{

View File

@@ -190,7 +190,7 @@ exit 0
verifyCommand := fmt.Sprintf(verifyCommandTemplate, stateJson) verifyCommand := fmt.Sprintf(verifyCommandTemplate, stateJson)
filename := "/tmp/runc-hooktest.sh" filename := "/tmp/runc-hooktest.sh"
os.Remove(filename) os.Remove(filename)
if err := ioutil.WriteFile(filename, []byte(verifyCommand), 0700); err != nil { if err := ioutil.WriteFile(filename, []byte(verifyCommand), 0o700); err != nil {
t.Fatalf("Failed to create tmp file: %v", err) t.Fatalf("Failed to create tmp file: %v", err)
} }
defer os.Remove(filename) defer os.Remove(filename)

View File

@@ -4,5 +4,4 @@ package configs
// Namespace defines configuration for each namespace. It specifies an // Namespace defines configuration for each namespace. It specifies an
// alternate path that is able to be joined via setns. // alternate path that is able to be joined via setns.
type Namespace struct { type Namespace struct{}
}

View File

@@ -23,8 +23,7 @@ func New() Validator {
return &ConfigValidator{} return &ConfigValidator{}
} }
type ConfigValidator struct { type ConfigValidator struct{}
}
type check func(config *configs.Config) error type check func(config *configs.Config) error

View File

@@ -9,7 +9,7 @@ import (
// mount initializes the console inside the rootfs mounting with the specified mount label // mount initializes the console inside the rootfs mounting with the specified mount label
// and applying the correct ownership of the console. // and applying the correct ownership of the console.
func mountConsole(slavePath string) error { func mountConsole(slavePath string) error {
oldMask := unix.Umask(0000) oldMask := unix.Umask(0o000)
defer unix.Umask(oldMask) defer unix.Umask(oldMask)
f, err := os.Create("/dev/console") f, err := os.Create("/dev/console")
if err != nil && !os.IsExist(err) { if err != nil && !os.IsExist(err) {

View File

@@ -437,8 +437,8 @@ func (c *linuxContainer) createExecFifo() error {
if _, err := os.Stat(fifoName); err == nil { if _, err := os.Stat(fifoName); err == nil {
return fmt.Errorf("exec fifo %s already exists", fifoName) return fmt.Errorf("exec fifo %s already exists", fifoName)
} }
oldMask := unix.Umask(0000) oldMask := unix.Umask(0o000)
if err := unix.Mkfifo(fifoName, 0622); err != nil { if err := unix.Mkfifo(fifoName, 0o622); err != nil {
unix.Umask(oldMask) unix.Umask(oldMask)
return err return err
} }
@@ -699,7 +699,6 @@ func (c *linuxContainer) NotifyMemoryPressure(level PressureLevel) (<-chan struc
var criuFeatures *criurpc.CriuFeatures var criuFeatures *criurpc.CriuFeatures
func (c *linuxContainer) checkCriuFeatures(criuOpts *CriuOpts, rpcOpts *criurpc.CriuOpts, criuFeat *criurpc.CriuFeatures) error { func (c *linuxContainer) checkCriuFeatures(criuOpts *CriuOpts, rpcOpts *criurpc.CriuOpts, criuFeat *criurpc.CriuFeatures) error {
t := criurpc.CriuReqType_FEATURE_CHECK t := criurpc.CriuReqType_FEATURE_CHECK
// make sure the features we are looking for are really not from // make sure the features we are looking for are really not from
@@ -761,7 +760,6 @@ func compareCriuVersion(criuVersion int, minVersion int) error {
// checkCriuVersion checks Criu version greater than or equal to minVersion // checkCriuVersion checks Criu version greater than or equal to minVersion
func (c *linuxContainer) checkCriuVersion(minVersion int) error { func (c *linuxContainer) checkCriuVersion(minVersion int) error {
// If the version of criu has already been determined there is no need // If the version of criu has already been determined there is no need
// to ask criu for the version again. Use the value from c.criuVersion. // to ask criu for the version again. Use the value from c.criuVersion.
if c.criuVersion != 0 { if c.criuVersion != 0 {
@@ -970,7 +968,7 @@ func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error {
// Since a container can be C/R'ed multiple times, // Since a container can be C/R'ed multiple times,
// the checkpoint directory may already exist. // the checkpoint directory may already exist.
if err := os.Mkdir(criuOpts.ImagesDirectory, 0700); err != nil && !os.IsExist(err) { if err := os.Mkdir(criuOpts.ImagesDirectory, 0o700); err != nil && !os.IsExist(err) {
return err return err
} }
@@ -978,7 +976,7 @@ func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error {
criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work") criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work")
} }
if err := os.Mkdir(criuOpts.WorkDirectory, 0700); err != nil && !os.IsExist(err) { if err := os.Mkdir(criuOpts.WorkDirectory, 0o700); err != nil && !os.IsExist(err) {
return err return err
} }
@@ -1048,7 +1046,7 @@ func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error {
} }
} }
//pre-dump may need parentImage param to complete iterative migration // pre-dump may need parentImage param to complete iterative migration
if criuOpts.ParentImage != "" { if criuOpts.ParentImage != "" {
rpcOpts.ParentImg = proto.String(criuOpts.ParentImage) rpcOpts.ParentImg = proto.String(criuOpts.ParentImage)
rpcOpts.TrackMem = proto.Bool(true) rpcOpts.TrackMem = proto.Bool(true)
@@ -1146,7 +1144,7 @@ func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error {
return err return err
} }
err = ioutil.WriteFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename), fdsJSON, 0600) err = ioutil.WriteFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename), fdsJSON, 0o600)
if err != nil { if err != nil {
return err return err
} }
@@ -1217,7 +1215,7 @@ func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error {
if err := checkProcMount(c.config.Rootfs, dest, ""); err != nil { if err := checkProcMount(c.config.Rootfs, dest, ""); err != nil {
return err return err
} }
if err := os.MkdirAll(dest, 0755); err != nil { if err := os.MkdirAll(dest, 0o755); err != nil {
return err return err
} }
} }
@@ -1318,7 +1316,7 @@ func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error {
} }
// Since a container can be C/R'ed multiple times, // Since a container can be C/R'ed multiple times,
// the work directory may already exist. // the work directory may already exist.
if err := os.Mkdir(criuOpts.WorkDirectory, 0700); err != nil && !os.IsExist(err) { if err := os.Mkdir(criuOpts.WorkDirectory, 0o700); err != nil && !os.IsExist(err) {
return err return err
} }
workDir, err := os.Open(criuOpts.WorkDirectory) workDir, err := os.Open(criuOpts.WorkDirectory)
@@ -1340,7 +1338,7 @@ func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error {
// c.config.Rootfs is bind-mounted to a temporary directory // c.config.Rootfs is bind-mounted to a temporary directory
// to satisfy these requirements. // to satisfy these requirements.
root := filepath.Join(c.root, "criu-root") root := filepath.Join(c.root, "criu-root")
if err := os.Mkdir(root, 0755); err != nil { if err := os.Mkdir(root, 0o755); err != nil {
return err return err
} }
defer os.Remove(root) defer os.Remove(root)

View File

@@ -333,9 +333,7 @@ func TestGetContainerState(t *testing.T) {
} }
func TestGetContainerStateAfterUpdate(t *testing.T) { func TestGetContainerStateAfterUpdate(t *testing.T) {
var ( pid := os.Getpid()
pid = os.Getpid()
)
stat, err := system.Stat(pid) stat, err := system.Stat(pid)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@@ -11,10 +11,8 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
var ( // ErrNotADevice denotes that a file is not a valid linux device.
// ErrNotADevice denotes that a file is not a valid linux device. var ErrNotADevice = errors.New("not a device node")
ErrNotADevice = errors.New("not a device node")
)
// Testing dependencies // Testing dependencies
var ( var (

View File

@@ -291,7 +291,7 @@ func (l *LinuxFactory) Load(id string) (Container, error) {
if l.Root == "" { if l.Root == "" {
return nil, newGenericError(fmt.Errorf("invalid root"), ConfigInvalid) return nil, newGenericError(fmt.Errorf("invalid root"), ConfigInvalid)
} }
//when load, we need to check id is valid or not. // when load, we need to check id is valid or not.
if err := l.validateID(id); err != nil { if err := l.validateID(id); err != nil {
return nil, err return nil, err
} }

View File

@@ -894,7 +894,7 @@ func TestPassExtraFiles(t *testing.T) {
if out != "0 1 2 3 4 5" { if out != "0 1 2 3 4 5" {
t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to init, got '%s'", out) t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to init, got '%s'", out)
} }
var buf = []byte{0} buf := []byte{0}
_, err = pipeout1.Read(buf) _, err = pipeout1.Read(buf)
ok(t, err) ok(t, err)
out1 := string(buf) out1 := string(buf)
@@ -1245,7 +1245,7 @@ func TestHook(t *testing.T) {
} }
// write config of json format into config.json under bundle // write config of json format into config.json under bundle
f, err := os.OpenFile(filepath.Join(bundle, "config.json"), os.O_CREATE|os.O_RDWR, 0644) f, err := os.OpenFile(filepath.Join(bundle, "config.json"), os.O_CREATE|os.O_RDWR, 0o644)
ok(t, err) ok(t, err)
ok(t, json.NewEncoder(f).Encode(config)) ok(t, json.NewEncoder(f).Encode(config))
@@ -1347,7 +1347,8 @@ func TestRootfsPropagationSlaveMount(t *testing.T) {
Source: dir1host, Source: dir1host,
Destination: dir1cont, Destination: dir1cont,
Device: "bind", Device: "bind",
Flags: unix.MS_BIND | unix.MS_REC}) Flags: unix.MS_BIND | unix.MS_REC,
})
container, err := newContainer(t, config) container, err := newContainer(t, config)
ok(t, err) ok(t, err)
@@ -1462,7 +1463,8 @@ func TestRootfsPropagationSharedMount(t *testing.T) {
Source: dir1host, Source: dir1host,
Destination: dir1cont, Destination: dir1cont,
Device: "bind", Device: "bind",
Flags: unix.MS_BIND | unix.MS_REC}) Flags: unix.MS_BIND | unix.MS_REC,
})
container, err := newContainer(t, config) container, err := newContainer(t, config)
ok(t, err) ok(t, err)

View File

@@ -461,7 +461,7 @@ func TestExecinPassExtraFiles(t *testing.T) {
if out != "0 1 2 3 4 5" { if out != "0 1 2 3 4 5" {
t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to exec, got '%s'", out) t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to exec, got '%s'", out)
} }
var buf = []byte{0} buf := []byte{0}
_, err = pipeout1.Read(buf) _, err = pipeout1.Read(buf)
ok(t, err) ok(t, err)
out1 := string(buf) out1 := string(buf)

View File

@@ -103,7 +103,7 @@ func newTestRoot() (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
if err := os.MkdirAll(dir, 0700); err != nil { if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err return "", err
} }
testRoots = append(testRoots, dir) testRoots = append(testRoots, dir)
@@ -115,7 +115,7 @@ func newTestBundle() (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
if err := os.MkdirAll(dir, 0700); err != nil { if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err return "", err
} }
return dir, nil return dir, nil
@@ -127,7 +127,7 @@ func newRootfs() (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
if err := os.MkdirAll(dir, 0700); err != nil { if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err return "", err
} }
if err := copyBusybox(dir); err != nil { if err := copyBusybox(dir); err != nil {

View File

@@ -1,8 +1,6 @@
package intelrdt package intelrdt
var ( var cmtEnabled bool
cmtEnabled bool
)
// Check if Intel RDT/CMT is enabled. // Check if Intel RDT/CMT is enabled.
func IsCMTEnabled() bool { func IsCMTEnabled() bool {

View File

@@ -2,10 +2,8 @@
package intelrdt package intelrdt
var ( // The flag to indicate if Intel RDT/MBM is enabled
// The flag to indicate if Intel RDT/MBM is enabled var mbmEnabled bool
mbmEnabled bool
)
// Check if Intel RDT/MBM is enabled. // Check if Intel RDT/MBM is enabled.
func IsMBMEnabled() bool { func IsMBMEnabled() bool {

View File

@@ -64,5 +64,4 @@ func checkMBMStatCorrection(got MBMNumaNodeStats, expected MBMNumaNodeStats, t *
expected.MBMLocalBytes, expected.MBMLocalBytes,
got.MBMLocalBytes) got.MBMLocalBytes)
} }
} }

View File

@@ -10,9 +10,7 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
var ( var enabledMonFeatures monFeatures
enabledMonFeatures monFeatures
)
type monFeatures struct { type monFeatures struct {
mbmTotalBytes bool mbmTotalBytes bool

View File

@@ -26,7 +26,6 @@ func TestParseMonFeatures(t *testing.T) {
t.Run("No features available", func(t *testing.T) { t.Run("No features available", func(t *testing.T) {
parsedMonFeatures, err := parseMonFeatures(strings.NewReader("")) parsedMonFeatures, err := parseMonFeatures(strings.NewReader(""))
if err != nil { if err != nil {
t.Errorf("Error while parsing mon features err = %v", err) t.Errorf("Error while parsing mon features err = %v", err)
} }

View File

@@ -85,7 +85,7 @@ func ConfigureLogging(config Config) error {
if config.LogPipeFd > 0 { if config.LogPipeFd > 0 {
logrus.SetOutput(os.NewFile(uintptr(config.LogPipeFd), "logpipe")) logrus.SetOutput(os.NewFile(uintptr(config.LogPipeFd), "logpipe"))
} else if config.LogFilePath != "" { } else if config.LogFilePath != "" {
f, err := os.OpenFile(config.LogFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0644) f, err := os.OpenFile(config.LogFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0o644)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -83,8 +83,7 @@ func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) {
} }
// loopback is a network strategy that provides a basic loopback device // loopback is a network strategy that provides a basic loopback device
type loopback struct { type loopback struct{}
}
func (l *loopback) create(n *network, nspid int) error { func (l *loopback) create(n *network, nspid int) error {
return nil return nil

View File

@@ -35,7 +35,7 @@ func registerMemoryEvent(cgDir string, evName string, arg string) (<-chan struct
eventControlPath := filepath.Join(cgDir, "cgroup.event_control") eventControlPath := filepath.Join(cgDir, "cgroup.event_control")
data := fmt.Sprintf("%d %d %s", eventfd.Fd(), evFile.Fd(), arg) data := fmt.Sprintf("%d %d %s", eventfd.Fd(), evFile.Fd(), arg)
if err := ioutil.WriteFile(eventControlPath, []byte(data), 0700); err != nil { if err := ioutil.WriteFile(eventControlPath, []byte(data), 0o700); err != nil {
eventfd.Close() eventfd.Close()
evFile.Close() evFile.Close()
return nil, err return nil, err

View File

@@ -23,10 +23,10 @@ func testMemoryNotification(t *testing.T, evName string, notify notifyFunc, targ
} }
evFile := filepath.Join(memoryPath, evName) evFile := filepath.Join(memoryPath, evName)
eventPath := filepath.Join(memoryPath, "cgroup.event_control") eventPath := filepath.Join(memoryPath, "cgroup.event_control")
if err := ioutil.WriteFile(evFile, []byte{}, 0700); err != nil { if err := ioutil.WriteFile(evFile, []byte{}, 0o700); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(eventPath, []byte{}, 0700); err != nil { if err := ioutil.WriteFile(eventPath, []byte{}, 0o700); err != nil {
t.Fatal(err) t.Fatal(err)
} }
ch, err := notify(memoryPath) ch, err := notify(memoryPath)

View File

@@ -11,9 +11,7 @@ import (
) )
func newRestoredProcess(cmd *exec.Cmd, fds []string) (*restoredProcess, error) { func newRestoredProcess(cmd *exec.Cmd, fds []string) (*restoredProcess, error) {
var ( var err error
err error
)
pid := cmd.Process.Pid pid := cmd.Process.Pid
stat, err := system.Stat(pid) stat, err := system.Stat(pid)
if err != nil { if err != nil {

View File

@@ -143,7 +143,7 @@ func prepareRootfs(pipe io.ReadWriter, iConfig *initConfig) (err error) {
if cwd := iConfig.Cwd; cwd != "" { if cwd := iConfig.Cwd; cwd != "" {
// Note that spec.Process.Cwd can contain unclean value like "../../../../foo/bar...". // Note that spec.Process.Cwd can contain unclean value like "../../../../foo/bar...".
// However, we are safe to call MkDirAll directly because we are in the jail here. // However, we are safe to call MkDirAll directly because we are in the jail here.
if err := os.MkdirAll(cwd, 0755); err != nil { if err := os.MkdirAll(cwd, 0o755); err != nil {
return err return err
} }
} }
@@ -176,7 +176,7 @@ func finalizeRootfs(config *configs.Config) (err error) {
if config.Umask != nil { if config.Umask != nil {
unix.Umask(int(*config.Umask)) unix.Umask(int(*config.Umask))
} else { } else {
unix.Umask(0022) unix.Umask(0o022)
} }
return nil return nil
} }
@@ -262,7 +262,7 @@ func mountCgroupV1(m *configs.Mount, c *mountConfig) error {
for _, b := range binds { for _, b := range binds {
if c.cgroupns { if c.cgroupns {
subsystemPath := filepath.Join(c.root, b.Destination) subsystemPath := filepath.Join(c.root, b.Destination)
if err := os.MkdirAll(subsystemPath, 0755); err != nil { if err := os.MkdirAll(subsystemPath, 0o755); err != nil {
return err return err
} }
if err := utils.WithProcfd(c.root, b.Destination, func(procfd string) error { if err := utils.WithProcfd(c.root, b.Destination, func(procfd string) error {
@@ -306,7 +306,7 @@ func mountCgroupV2(m *configs.Mount, c *mountConfig) error {
if err != nil { if err != nil {
return err return err
} }
if err := os.MkdirAll(dest, 0755); err != nil { if err := os.MkdirAll(dest, 0o755); err != nil {
return err return err
} }
return utils.WithProcfd(c.root, m.Destination, func(procfd string) error { return utils.WithProcfd(c.root, m.Destination, func(procfd string) error {
@@ -398,13 +398,13 @@ func mountToRootfs(m *configs.Mount, c *mountConfig) error {
} else if fi.Mode()&os.ModeDir == 0 { } else if fi.Mode()&os.ModeDir == 0 {
return fmt.Errorf("filesystem %q must be mounted on ordinary directory", m.Device) return fmt.Errorf("filesystem %q must be mounted on ordinary directory", m.Device)
} }
if err := os.MkdirAll(dest, 0755); err != nil { if err := os.MkdirAll(dest, 0o755); err != nil {
return err return err
} }
// Selinux kernels do not support labeling of /proc or /sys // Selinux kernels do not support labeling of /proc or /sys
return mountPropagate(m, rootfs, "") return mountPropagate(m, rootfs, "")
case "mqueue": case "mqueue":
if err := os.MkdirAll(dest, 0755); err != nil { if err := os.MkdirAll(dest, 0o755); err != nil {
return err return err
} }
if err := mountPropagate(m, rootfs, ""); err != nil { if err := mountPropagate(m, rootfs, ""); err != nil {
@@ -414,7 +414,7 @@ func mountToRootfs(m *configs.Mount, c *mountConfig) error {
case "tmpfs": case "tmpfs":
stat, err := os.Stat(dest) stat, err := os.Stat(dest)
if err != nil { if err != nil {
if err := os.MkdirAll(dest, 0755); err != nil { if err := os.MkdirAll(dest, 0o755); err != nil {
return err return err
} }
} }
@@ -473,7 +473,7 @@ func mountToRootfs(m *configs.Mount, c *mountConfig) error {
if err := checkProcMount(rootfs, dest, m.Source); err != nil { if err := checkProcMount(rootfs, dest, m.Source); err != nil {
return err return err
} }
if err := os.MkdirAll(dest, 0755); err != nil { if err := os.MkdirAll(dest, 0o755); err != nil {
return err return err
} }
return mountPropagate(m, rootfs, mountLabel) return mountPropagate(m, rootfs, mountLabel)
@@ -582,7 +582,7 @@ func isProc(path string) (bool, error) {
} }
func setupDevSymlinks(rootfs string) error { func setupDevSymlinks(rootfs string) error {
var links = [][2]string{ links := [][2]string{
{"/proc/self/fd", "/dev/fd"}, {"/proc/self/fd", "/dev/fd"},
{"/proc/self/fd/0", "/dev/stdin"}, {"/proc/self/fd/0", "/dev/stdin"},
{"/proc/self/fd/1", "/dev/stdout"}, {"/proc/self/fd/1", "/dev/stdout"},
@@ -636,7 +636,7 @@ func reOpenDevNull() error {
// Create the device nodes in the container. // Create the device nodes in the container.
func createDevices(config *configs.Config) error { func createDevices(config *configs.Config) error {
useBindMount := userns.RunningInUserNS() || config.Namespaces.Contains(configs.NEWUSER) useBindMount := userns.RunningInUserNS() || config.Namespaces.Contains(configs.NEWUSER)
oldMask := unix.Umask(0000) oldMask := unix.Umask(0o000)
for _, node := range config.Devices { for _, node := range config.Devices {
// The /dev/ptmx device is setup by setupPtmx() // The /dev/ptmx device is setup by setupPtmx()
@@ -678,7 +678,7 @@ func createDeviceNode(rootfs string, node *devices.Device, bind bool) error {
if err != nil { if err != nil {
return err return err
} }
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err return err
} }
if bind { if bind {
@@ -799,7 +799,6 @@ func setReadonly() error {
} }
flags |= uintptr(s.Flags) flags |= uintptr(s.Flags)
return unix.Mount("", "/", "", flags, "") return unix.Mount("", "/", "", flags, "")
} }
func setupPtmx(config *configs.Config) error { func setupPtmx(config *configs.Config) error {
@@ -947,12 +946,12 @@ func createIfNotExists(path string, isDir bool) error {
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
if isDir { if isDir {
return os.MkdirAll(path, 0755) return os.MkdirAll(path, 0o755)
} }
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err return err
} }
f, err := os.OpenFile(path, os.O_CREATE, 0755) f, err := os.OpenFile(path, os.O_CREATE, 0o755)
if err != nil { if err != nil {
return err return err
} }
@@ -1031,7 +1030,7 @@ func maskPath(path string, mountLabel string) error {
// For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward. // For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
func writeSystemProperty(key, value string) error { func writeSystemProperty(key, value string) error {
keyPath := strings.Replace(key, ".", "/", -1) keyPath := strings.Replace(key, ".", "/", -1)
return ioutil.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644) return ioutil.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0o644)
} }
func remount(m *configs.Mount, rootfs string) error { func remount(m *configs.Mount, rootfs string) error {

View File

@@ -324,7 +324,8 @@ func generateEnosysStub(lastSyscalls lastSyscallMap) ([]bpf.Instruction, error)
bpf.JumpIf{ bpf.JumpIf{
Cond: bpf.JumpGreaterThan, Cond: bpf.JumpGreaterThan,
Val: uint32(sysno), Val: uint32(sysno),
SkipTrue: uint8(baseJumpEnosys + 1)}, SkipTrue: uint8(baseJumpEnosys + 1),
},
// ja [baseJumpFilter] // ja [baseJumpFilter]
bpf.Jump{Skip: baseJumpFilter}, bpf.Jump{Skip: baseJumpFilter},
} }
@@ -353,16 +354,20 @@ func generateEnosysStub(lastSyscalls lastSyscallMap) ([]bpf.Instruction, error)
case libseccomp.ArchAMD64: case libseccomp.ArchAMD64:
sectionTail = append([]bpf.Instruction{ sectionTail = append([]bpf.Instruction{
// jset (1<<30),[len(tail)-1] // jset (1<<30),[len(tail)-1]
bpf.JumpIf{Cond: bpf.JumpBitsSet, bpf.JumpIf{
Cond: bpf.JumpBitsSet,
Val: 1 << 30, Val: 1 << 30,
SkipTrue: uint8(len(sectionTail) - 1)}, SkipTrue: uint8(len(sectionTail) - 1),
},
}, sectionTail...) }, sectionTail...)
case libseccomp.ArchX32: case libseccomp.ArchX32:
sectionTail = append([]bpf.Instruction{ sectionTail = append([]bpf.Instruction{
// jset (1<<30),0,[len(tail)-1] // jset (1<<30),0,[len(tail)-1]
bpf.JumpIf{Cond: bpf.JumpBitsNotSet, bpf.JumpIf{
Cond: bpf.JumpBitsNotSet,
Val: 1 << 30, Val: 1 << 30,
SkipTrue: uint8(len(sectionTail) - 1)}, SkipTrue: uint8(len(sectionTail) - 1),
},
}, sectionTail...) }, sectionTail...)
default: default:
return nil, errors.Errorf("unknown amd64 native architecture %#x", scmpArch) return nil, errors.Errorf("unknown amd64 native architecture %#x", scmpArch)
@@ -402,12 +407,14 @@ func generateEnosysStub(lastSyscalls lastSyscallMap) ([]bpf.Instruction, error)
bpf.JumpIf{ bpf.JumpIf{
Cond: bpf.JumpGreaterThan, Cond: bpf.JumpGreaterThan,
Val: uint32(x86sysno), Val: uint32(x86sysno),
SkipTrue: uint8(baseJumpEnosys + 2), SkipFalse: 1}, SkipTrue: uint8(baseJumpEnosys + 2), SkipFalse: 1,
},
// jgt [x32 syscall],[baseJumpEnosys] // jgt [x32 syscall],[baseJumpEnosys]
bpf.JumpIf{ bpf.JumpIf{
Cond: bpf.JumpGreaterThan, Cond: bpf.JumpGreaterThan,
Val: uint32(x32sysno), Val: uint32(x32sysno),
SkipTrue: uint8(baseJumpEnosys + 1)}, SkipTrue: uint8(baseJumpEnosys + 1),
},
// ja [baseJumpFilter] // ja [baseJumpFilter]
bpf.Jump{Skip: baseJumpFilter}, bpf.Jump{Skip: baseJumpFilter},
}...) }...)
@@ -426,12 +433,14 @@ func generateEnosysStub(lastSyscalls lastSyscallMap) ([]bpf.Instruction, error)
bpf.JumpIf{ bpf.JumpIf{
Cond: bpf.JumpGreaterThan, Cond: bpf.JumpGreaterThan,
Val: uint32(x86sysno), Val: uint32(x86sysno),
SkipTrue: 1, SkipFalse: 2}, SkipTrue: 1, SkipFalse: 2,
},
// jle [x32 syscall],[baseJumpEnosys] // jle [x32 syscall],[baseJumpEnosys]
bpf.JumpIf{ bpf.JumpIf{
Cond: bpf.JumpLessOrEqual, Cond: bpf.JumpLessOrEqual,
Val: uint32(x32sysno), Val: uint32(x32sysno),
SkipTrue: 1}, SkipTrue: 1,
},
// ja [baseJumpEnosys+1] // ja [baseJumpEnosys+1]
bpf.Jump{Skip: baseJumpEnosys + 1}, bpf.Jump{Skip: baseJumpEnosys + 1},
// ja [baseJumpFilter] // ja [baseJumpFilter]
@@ -478,7 +487,8 @@ func generateEnosysStub(lastSyscalls lastSyscallMap) ([]bpf.Instruction, error)
bpf.JumpIf{ bpf.JumpIf{
Cond: bpf.JumpEqual, Cond: bpf.JumpEqual,
Val: uint32(nativeArch), Val: uint32(nativeArch),
SkipTrue: uint8(jump)}, SkipTrue: uint8(jump),
},
}, programTail...) }, programTail...)
} else { } else {
programTail = append([]bpf.Instruction{ programTail = append([]bpf.Instruction{
@@ -486,7 +496,8 @@ func generateEnosysStub(lastSyscalls lastSyscallMap) ([]bpf.Instruction, error)
bpf.JumpIf{ bpf.JumpIf{
Cond: bpf.JumpNotEqual, Cond: bpf.JumpNotEqual,
Val: uint32(nativeArch), Val: uint32(nativeArch),
SkipTrue: 1}, SkipTrue: 1,
},
// ja [jump] // ja [jump]
bpf.Jump{Skip: jump}, bpf.Jump{Skip: jump},
}, programTail...) }, programTail...)

View File

@@ -85,7 +85,7 @@ var AllowedDevices = []*devices.Device{
}, },
{ {
Path: "/dev/null", Path: "/dev/null",
FileMode: 0666, FileMode: 0o666,
Uid: 0, Uid: 0,
Gid: 0, Gid: 0,
Rule: devices.Rule{ Rule: devices.Rule{
@@ -98,7 +98,7 @@ var AllowedDevices = []*devices.Device{
}, },
{ {
Path: "/dev/random", Path: "/dev/random",
FileMode: 0666, FileMode: 0o666,
Uid: 0, Uid: 0,
Gid: 0, Gid: 0,
Rule: devices.Rule{ Rule: devices.Rule{
@@ -111,7 +111,7 @@ var AllowedDevices = []*devices.Device{
}, },
{ {
Path: "/dev/full", Path: "/dev/full",
FileMode: 0666, FileMode: 0o666,
Uid: 0, Uid: 0,
Gid: 0, Gid: 0,
Rule: devices.Rule{ Rule: devices.Rule{
@@ -124,7 +124,7 @@ var AllowedDevices = []*devices.Device{
}, },
{ {
Path: "/dev/tty", Path: "/dev/tty",
FileMode: 0666, FileMode: 0o666,
Uid: 0, Uid: 0,
Gid: 0, Gid: 0,
Rule: devices.Rule{ Rule: devices.Rule{
@@ -137,7 +137,7 @@ var AllowedDevices = []*devices.Device{
}, },
{ {
Path: "/dev/zero", Path: "/dev/zero",
FileMode: 0666, FileMode: 0o666,
Uid: 0, Uid: 0,
Gid: 0, Gid: 0,
Rule: devices.Rule{ Rule: devices.Rule{
@@ -150,7 +150,7 @@ var AllowedDevices = []*devices.Device{
}, },
{ {
Path: "/dev/urandom", Path: "/dev/urandom",
FileMode: 0666, FileMode: 0o666,
Uid: 0, Uid: 0,
Gid: 0, Gid: 0,
Rule: devices.Rule{ Rule: devices.Rule{
@@ -533,7 +533,7 @@ func CreateCgroupConfig(opts *CreateOpts, defaultDevs []*devices.Device) (*confi
if r.CPU.Shares != nil { if r.CPU.Shares != nil {
c.Resources.CpuShares = *r.CPU.Shares c.Resources.CpuShares = *r.CPU.Shares
//CpuWeight is used for cgroupv2 and should be converted // CpuWeight is used for cgroupv2 and should be converted
c.Resources.CpuWeight = cgroups.ConvertCPUSharesToCgroupV2Value(c.Resources.CpuShares) c.Resources.CpuWeight = cgroups.ConvertCPUSharesToCgroupV2Value(c.Resources.CpuShares)
} }
if r.CPU.Quota != nil { if r.CPU.Quota != nil {
@@ -691,7 +691,7 @@ next:
if spec.Linux != nil { if spec.Linux != nil {
for _, d := range spec.Linux.Devices { for _, d := range spec.Linux.Devices {
var uid, gid uint32 var uid, gid uint32
var filemode os.FileMode = 0666 var filemode os.FileMode = 0o666
if d.UID != nil { if d.UID != nil {
uid = *d.UID uid = *d.UID

View File

@@ -139,8 +139,8 @@ func TestCreateHooks(t *testing.T) {
if len(poststop) != 4 { if len(poststop) != 4 {
t.Error("Expected 4 Poststop hooks") t.Error("Expected 4 Poststop hooks")
} }
} }
func TestSetupSeccomp(t *testing.T) { func TestSetupSeccomp(t *testing.T) {
conf := &specs.LinuxSeccomp{ conf := &specs.LinuxSeccomp{
DefaultAction: "SCMP_ACT_ERRNO", DefaultAction: "SCMP_ACT_ERRNO",
@@ -173,7 +173,6 @@ func TestSetupSeccomp(t *testing.T) {
}, },
} }
seccomp, err := SetupSeccomp(conf) seccomp, err := SetupSeccomp(conf)
if err != nil { if err != nil {
t.Errorf("Couldn't create Seccomp config: %v", err) t.Errorf("Couldn't create Seccomp config: %v", err)
} }
@@ -214,7 +213,6 @@ func TestSetupSeccomp(t *testing.T) {
} }
} }
} }
func TestLinuxCgroupWithMemoryResource(t *testing.T) { func TestLinuxCgroupWithMemoryResource(t *testing.T) {
@@ -298,7 +296,6 @@ func TestLinuxCgroupSystemd(t *testing.T) {
} }
cgroup, err := CreateCgroupConfig(opts, nil) cgroup, err := CreateCgroupConfig(opts, nil)
if err != nil { if err != nil {
t.Errorf("Couldn't create Cgroup config: %v", err) t.Errorf("Couldn't create Cgroup config: %v", err)
} }
@@ -334,7 +331,6 @@ func TestLinuxCgroupSystemdWithEmptyPath(t *testing.T) {
} }
cgroup, err := CreateCgroupConfig(opts, nil) cgroup, err := CreateCgroupConfig(opts, nil)
if err != nil { if err != nil {
t.Errorf("Couldn't create Cgroup config: %v", err) t.Errorf("Couldn't create Cgroup config: %v", err)
} }
@@ -373,6 +369,7 @@ func TestLinuxCgroupSystemdWithInvalidPath(t *testing.T) {
t.Error("Expected to produce an error if not using the correct format for cgroup paths belonging to systemd") t.Error("Expected to produce an error if not using the correct format for cgroup paths belonging to systemd")
} }
} }
func TestLinuxCgroupsPathSpecified(t *testing.T) { func TestLinuxCgroupsPathSpecified(t *testing.T) {
cgroupsPath := "/user/cgroups/path/id" cgroupsPath := "/user/cgroups/path/id"
@@ -603,7 +600,7 @@ func TestInitSystemdProps(t *testing.T) {
spec.Annotations = map[string]string{tc.in.name: tc.in.value} spec.Annotations = map[string]string{tc.in.name: tc.in.value}
outMap, err := initSystemdProps(spec) outMap, err := initSystemdProps(spec)
//t.Logf("input %+v, expected %+v, got err:%v out:%+v", tc.in, tc.exp, err, outMap) // t.Logf("input %+v, expected %+v, got err:%v out:%+v", tc.in, tc.exp, err, outMap)
if tc.exp.isErr != (err != nil) { if tc.exp.isErr != (err != nil) {
t.Errorf("input %+v, expecting error: %v, got %v", tc.in, tc.exp.isErr, err) t.Errorf("input %+v, expecting error: %v, got %v", tc.in, tc.exp.isErr, err)
@@ -637,7 +634,6 @@ func TestNullProcess(t *testing.T) {
_, err := CreateLibcontainerConfig(&CreateOpts{ _, err := CreateLibcontainerConfig(&CreateOpts{
Spec: spec, Spec: spec,
}) })
if err != nil { if err != nil {
t.Errorf("Null process should be forbidden") t.Errorf("Null process should be forbidden")
} }
@@ -650,7 +646,7 @@ func TestCreateDevices(t *testing.T) {
// preferred the spec's device over the redundant default device // preferred the spec's device over the redundant default device
ttyUid := uint32(1000) ttyUid := uint32(1000)
ttyGid := uint32(1000) ttyGid := uint32(1000)
fm := os.FileMode(0666) fm := os.FileMode(0o666)
spec.Linux = &specs.Linux{ spec.Linux = &specs.Linux{
Devices: []specs.LinuxDevice{ Devices: []specs.LinuxDevice{
@@ -718,7 +714,7 @@ func TestCreateDevices(t *testing.T) {
if configDev.Path == "/dev/tty" { if configDev.Path == "/dev/tty" {
wantDev := &devices.Device{ wantDev := &devices.Device{
Path: "/dev/tty", Path: "/dev/tty",
FileMode: 0666, FileMode: 0o666,
Uid: 1000, Uid: 1000,
Gid: 1000, Gid: 1000,
Rule: devices.Rule{ Rule: devices.Rule{

View File

@@ -13,8 +13,8 @@ func Capture(userSkip int) Stacktrace {
) )
for i := skip; ; i++ { for i := skip; ; i++ {
pc, file, line, ok := runtime.Caller(i) pc, file, line, ok := runtime.Caller(i)
//detect if caller is repeated to avoid loop, gccgo // detect if caller is repeated to avoid loop, gccgo
//currently runs into a loop without this check // currently runs into a loop without this check
if !ok || pc == prevPc { if !ok || pc == prevPc {
break break
} }

View File

@@ -12,7 +12,7 @@ import (
const ( const (
minId = 0 minId = 0
maxId = 1<<31 - 1 //for 32-bit systems compatibility maxId = 1<<31 - 1 // for 32-bit systems compatibility
) )
var ( var (
@@ -401,7 +401,7 @@ func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (
// or the given group data is nil, the id will be returned as-is // or the given group data is nil, the id will be returned as-is
// provided it is in the legal range. // provided it is in the legal range.
func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) { func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) {
var groups = []Group{} groups := []Group{}
if group != nil { if group != nil {
var err error var err error
groups, err = ParseGroupFilter(group, func(g Group) bool { groups, err = ParseGroupFilter(group, func(g Group) bool {

View File

@@ -32,7 +32,7 @@ func TestSearchLabels(t *testing.T) {
func TestResolveRootfs(t *testing.T) { func TestResolveRootfs(t *testing.T) {
dir := "rootfs" dir := "rootfs"
if err := os.Mkdir(dir, 0600); err != nil { if err := os.Mkdir(dir, 0o600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.Remove(dir) defer os.Remove(dir)

View File

@@ -3,6 +3,7 @@
package main package main
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
@@ -12,8 +13,6 @@ import (
"text/tabwriter" "text/tabwriter"
"time" "time"
"encoding/json"
"github.com/opencontainers/runc/libcontainer" "github.com/opencontainers/runc/libcontainer"
"github.com/opencontainers/runc/libcontainer/user" "github.com/opencontainers/runc/libcontainer/user"
"github.com/opencontainers/runc/libcontainer/utils" "github.com/opencontainers/runc/libcontainer/utils"

View File

@@ -137,7 +137,7 @@ func main() {
// According to the XDG specification, we need to set anything in // According to the XDG specification, we need to set anything in
// XDG_RUNTIME_DIR to have a sticky bit if we don't want it to get // XDG_RUNTIME_DIR to have a sticky bit if we don't want it to get
// auto-pruned. // auto-pruned.
if err := os.MkdirAll(root, 0700); err != nil { if err := os.MkdirAll(root, 0o700); err != nil {
fmt.Fprintln(os.Stderr, "the path in $XDG_RUNTIME_DIR must be writable by the user") fmt.Fprintln(os.Stderr, "the path in $XDG_RUNTIME_DIR must be writable by the user")
fatal(err) fatal(err)
} }

View File

@@ -68,7 +68,7 @@ func (s *notifySocket) bindSocket() error {
return err return err
} }
err = os.Chmod(s.socketPath, 0777) err = os.Chmod(s.socketPath, 0o777)
if err != nil { if err != nil {
socket.Close() socket.Close()
return err return err
@@ -79,7 +79,7 @@ func (s *notifySocket) bindSocket() error {
} }
func (s *notifySocket) setupSocketDirectory() error { func (s *notifySocket) setupSocketDirectory() error {
return os.Mkdir(path.Dir(s.socketPath), 0755) return os.Mkdir(path.Dir(s.socketPath), 0o755)
} }
func notifySocketStart(context *cli.Context, notifySocketHost, id string) (*notifySocket, error) { func notifySocketStart(context *cli.Context, notifySocketHost, id string) (*notifySocket, error) {

View File

@@ -1,7 +1,10 @@
package main package main
import "fmt" import (
import "golang.org/x/sys/unix" "fmt"
"golang.org/x/sys/unix"
)
var rlimitMap = map[string]int{ var rlimitMap = map[string]int{
"RLIMIT_CPU": unix.RLIMIT_CPU, "RLIMIT_CPU": unix.RLIMIT_CPU,

View File

@@ -111,7 +111,7 @@ created by an unprivileged user.
if err != nil { if err != nil {
return err return err
} }
return ioutil.WriteFile(specConfig, data, 0666) return ioutil.WriteFile(specConfig, data, 0o666)
}, },
} }

View File

@@ -286,7 +286,7 @@ other options are ignored.
} }
config.Cgroups.Resources.CpuShares = *r.CPU.Shares config.Cgroups.Resources.CpuShares = *r.CPU.Shares
//CpuWeight is used for cgroupv2 and should be converted // CpuWeight is used for cgroupv2 and should be converted
config.Cgroups.Resources.CpuWeight = cgroups.ConvertCPUSharesToCgroupV2Value(*r.CPU.Shares) config.Cgroups.Resources.CpuWeight = cgroups.ConvertCPUSharesToCgroupV2Value(*r.CPU.Shares)
config.Cgroups.Resources.CpuRtPeriod = *r.CPU.RealtimePeriod config.Cgroups.Resources.CpuRtPeriod = *r.CPU.RealtimePeriod
config.Cgroups.Resources.CpuRtRuntime = *r.CPU.RealtimeRuntime config.Cgroups.Resources.CpuRtRuntime = *r.CPU.RealtimeRuntime

View File

@@ -209,7 +209,7 @@ func createPidFile(path string, process *libcontainer.Process) error {
tmpDir = filepath.Dir(path) tmpDir = filepath.Dir(path)
tmpName = filepath.Join(tmpDir, "."+filepath.Base(path)) tmpName = filepath.Join(tmpDir, "."+filepath.Base(path))
) )
f, err := os.OpenFile(tmpName, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666) f, err := os.OpenFile(tmpName, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0o666)
if err != nil { if err != nil {
return err return err
} }
@@ -296,9 +296,7 @@ func (r *runner) run(config *specs.Process) (int, error) {
if err != nil { if err != nil {
return -1, err return -1, err
} }
var ( detach := r.detach || (r.action == CT_ACT_CREATE)
detach = r.detach || (r.action == CT_ACT_CREATE)
)
// Setting up IO is a two stage process. We need to modify process to deal // Setting up IO is a two stage process. We need to modify process to deal
// with detaching containers, and then we get a tty after the container has // with detaching containers, and then we get a tty after the container has
// started. // started.