bump to golangci-lint v1.50.0

Used `go fmt` rules to migrate away from deprecated functions, for
instance `gofmt -w -s -r 'ioutil.TempDir(a, b) -> os.MkdirTemp(a, b)'`

Signed-off-by: Valentin Rothberg <vrothberg@redhat.com>
This commit is contained in:
Valentin Rothberg 2022-10-17 14:49:34 +02:00
parent a1b59acaba
commit e17483b871
77 changed files with 310 additions and 333 deletions

View File

@ -11,7 +11,7 @@ on:
permissions: read-all
env:
LINT_VERSION: v1.45
LINT_VERSION: v1.50
jobs:
codespell:
@ -31,7 +31,7 @@ jobs:
fetch-depth: 2
- uses: actions/setup-go@f6164bd8c8acb4a71fb2791a8b6c4024ff038dab # v3
with:
go-version: 1.18
go-version: 1.19
- name: install deps
run: |
sudo apt-get -qq update

View File

@ -72,7 +72,7 @@ vendor:
.PHONY: install.tools
install.tools: build/golangci-lint .install.md2man
build/golangci-lint: VERSION=v1.45.2
build/golangci-lint: VERSION=v1.50.0
build/golangci-lint:
curl -fsSL https://raw.githubusercontent.com/golangci/golangci-lint/$(VERSION)/install.sh | sh -s -- -b ./build $(VERSION)

View File

@ -2,7 +2,6 @@ package libimage
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -48,7 +47,7 @@ func TestCorruptedLayers(t *testing.T) {
// image will still be listed in the container storage but attempting
// to use it will yield "layer not known" errors.
indexPath := filepath.Join(runtime.store.GraphRoot(), "vfs-layers/layers.json")
data, err := ioutil.ReadFile(indexPath)
data, err := os.ReadFile(indexPath)
require.NoError(t, err, "loading layers.json")
layers := []*storage.Layer{}
err = json.Unmarshal(data, &layers)

View File

@ -73,7 +73,8 @@ func (r *Runtime) filterImages(ctx context.Context, images []*Image, options *Li
// compileImageFilters creates `filterFunc`s for the specified filters. The
// required format is `key=value` with the following supported keys:
// after, since, before, containers, dangling, id, label, readonly, reference, intermediate
//
// after, since, before, containers, dangling, id, label, readonly, reference, intermediate
func (r *Runtime) compileImageFilters(ctx context.Context, options *ListImagesOptions) (map[string][]filterFunc, error) {
logrus.Tracef("Parsing image filters %s", options.Filters)

View File

@ -2,7 +2,6 @@ package libimage
import (
"context"
"io/ioutil"
"os"
"testing"
@ -15,7 +14,7 @@ func TestLoad(t *testing.T) {
tmpdir := t.TempDir()
os.Setenv("TMPDIR", tmpdir)
defer func() {
dir, err := ioutil.ReadDir(tmpdir)
dir, err := os.ReadDir(tmpdir)
require.NoError(t, err)
require.Len(t, dir, 0)
os.Unsetenv("TMPDIR")

View File

@ -3,7 +3,6 @@ package manifests
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -47,7 +46,7 @@ func TestSaveLoad(t *testing.T) {
t.Skip("Test can only run as root")
}
dir, err := ioutil.TempDir("", "manifests")
dir, err := os.MkdirTemp("", "manifests")
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(dir)
@ -165,7 +164,7 @@ func TestReference(t *testing.T) {
}
ctx := context.Background()
dir, err := ioutil.TempDir("", "manifests")
dir, err := os.MkdirTemp("", "manifests")
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(dir)
@ -265,7 +264,7 @@ func TestPush(t *testing.T) {
}
ctx := context.Background()
dir, err := ioutil.TempDir("", "manifests")
dir, err := os.MkdirTemp("", "manifests")
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(dir)
@ -285,7 +284,7 @@ func TestPush(t *testing.T) {
}
}()
dest, err := ioutil.TempDir("", "manifests")
dest, err := os.MkdirTemp("", "manifests")
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(dest)

View File

@ -69,9 +69,9 @@ func toPlatformString(os, arch, variant string) string {
// Checks whether the image matches the specified platform.
// Returns
// * 1) a matching error that can be used for logging (or returning) what does not match
// * 2) a bool indicating whether architecture, os or variant were set (some callers need that to decide whether they need to throw an error)
// * 3) a fatal error that occurred prior to check for matches (e.g., storage errors etc.)
// - 1) a matching error that can be used for logging (or returning) what does not match
// - 2) a bool indicating whether architecture, os or variant were set (some callers need that to decide whether they need to throw an error)
// - 3) a fatal error that occurred prior to check for matches (e.g., storage errors etc.)
func (i *Image) matchesPlatform(ctx context.Context, os, arch, variant string) (error, bool, error) {
if err := i.isCorrupted(""); err != nil {
return err, false, nil

View File

@ -2,7 +2,6 @@ package libimage
import (
"context"
"io/ioutil"
"os"
"testing"
@ -24,7 +23,7 @@ func TestPush(t *testing.T) {
pushOptions := &PushOptions{}
pushOptions.Writer = os.Stdout
workdir, err := ioutil.TempDir("", "libimagepush")
workdir, err := os.MkdirTemp("", "libimagepush")
require.NoError(t, err)
defer os.RemoveAll(workdir)
@ -86,7 +85,7 @@ func TestPushOtherPlatform(t *testing.T) {
pushOptions := &PushOptions{}
pushOptions.Writer = os.Stdout
tmp, err := ioutil.TempFile("", "")
tmp, err := os.CreateTemp("", "")
require.NoError(t, err)
tmp.Close()
defer os.Remove(tmp.Name())

View File

@ -1,7 +1,6 @@
package libimage
import (
"io/ioutil"
"os"
"testing"
@ -27,7 +26,7 @@ type testNewRuntimeOptions struct {
// is a clean-up function that should be called by users to make sure all
// temporary test data gets removed.
func testNewRuntime(t *testing.T, options ...testNewRuntimeOptions) (runtime *Runtime, cleanup func()) {
workdir, err := ioutil.TempDir("", "testStorageRuntime")
workdir, err := os.MkdirTemp("", "testStorageRuntime")
require.NoError(t, err)
storeOptions := &storage.StoreOptions{
RunRoot: workdir,

View File

@ -2,7 +2,6 @@ package libimage
import (
"context"
"io/ioutil"
"os"
"strings"
"testing"
@ -28,7 +27,7 @@ func TestSave(t *testing.T) {
// reload the images for each test.
saveOptions := &SaveOptions{}
saveOptions.Writer = os.Stdout
imageCache, err := ioutil.TempFile("", "saveimagecache")
imageCache, err := os.CreateTemp("", "saveimagecache")
require.NoError(t, err)
imageCache.Close()
defer os.Remove(imageCache.Name())
@ -72,7 +71,7 @@ func TestSave(t *testing.T) {
_, err = runtime.Load(ctx, imageCache.Name(), loadOptions)
require.NoError(t, err)
tmp, err := ioutil.TempDir("", "libimagesavetest")
tmp, err := os.MkdirTemp("", "libimagesavetest")
require.NoError(t, err)
defer os.RemoveAll(tmp)
if !test.isDir {

View File

@ -7,7 +7,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
@ -329,7 +328,7 @@ func (n *cniNetwork) createCNIConfigListFromNetwork(network *types.Network, writ
cniPathName := ""
if writeToDisk {
cniPathName = filepath.Join(n.cniConfigDir, network.Name+".conflist")
err = ioutil.WriteFile(cniPathName, b, 0o644)
err = os.WriteFile(cniPathName, b, 0o644)
if err != nil {
return nil, "", err
}

View File

@ -5,7 +5,6 @@ package cni_test
import (
"bytes"
"io/ioutil"
"net"
"os"
"path/filepath"
@ -28,7 +27,7 @@ var _ = Describe("Config", func() {
BeforeEach(func() {
var err error
cniConfDir, err = ioutil.TempDir("", "podman_cni_test")
cniConfDir, err = os.MkdirTemp("", "podman_cni_test")
if err != nil {
Fail("Failed to create tmpdir")
}
@ -1202,17 +1201,17 @@ var _ = Describe("Config", func() {
BeforeEach(func() {
dir := "testfiles/valid"
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
Fail("Failed to read test directory")
}
for _, file := range files {
filename := file.Name()
data, err := ioutil.ReadFile(filepath.Join(dir, filename))
data, err := os.ReadFile(filepath.Join(dir, filename))
if err != nil {
Fail("Failed to copy test files")
}
err = ioutil.WriteFile(filepath.Join(cniConfDir, filename), data, 0o700)
err = os.WriteFile(filepath.Join(cniConfDir, filename), data, 0o700)
if err != nil {
Fail("Failed to copy test files")
}
@ -1557,17 +1556,17 @@ var _ = Describe("Config", func() {
Context("network load invalid existing ones", func() {
BeforeEach(func() {
dir := "testfiles/invalid"
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
Fail("Failed to read test directory")
}
for _, file := range files {
filename := file.Name()
data, err := ioutil.ReadFile(filepath.Join(dir, filename))
data, err := os.ReadFile(filepath.Join(dir, filename))
if err != nil {
Fail("Failed to copy test files")
}
err = ioutil.WriteFile(filepath.Join(cniConfDir, filename), data, 0o700)
err = os.WriteFile(filepath.Join(cniConfDir, filename), data, 0o700)
if err != nil {
Fail("Failed to copy test files")
}
@ -1598,7 +1597,7 @@ func grepNotFile(path, match string) {
}
func grepFile(not bool, path, match string) {
data, err := ioutil.ReadFile(path)
data, err := os.ReadFile(path)
ExpectWithOffset(1, err).To(BeNil())
matcher := ContainSubstring(match)
if not {

View File

@ -16,7 +16,7 @@ package cni_test
import (
"bytes"
"io/ioutil"
"io"
"net"
"os"
"path/filepath"
@ -78,7 +78,7 @@ var _ = Describe("run CNI", func() {
}
var err error
cniConfDir, err = ioutil.TempDir("", "podman_cni_test")
cniConfDir, err = os.MkdirTemp("", "podman_cni_test")
if err != nil {
Fail("Failed to create tmpdir")
}
@ -919,17 +919,17 @@ var _ = Describe("run CNI", func() {
Context("network setup test with networks from disk", func() {
BeforeEach(func() {
dir := "testfiles/valid"
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
Fail("Failed to read test directory")
}
for _, file := range files {
filename := file.Name()
data, err := ioutil.ReadFile(filepath.Join(dir, filename))
data, err := os.ReadFile(filepath.Join(dir, filename))
if err != nil {
Fail("Failed to copy test files")
}
err = ioutil.WriteFile(filepath.Join(cniConfDir, filename), data, 0o700)
err = os.WriteFile(filepath.Join(cniConfDir, filename), data, 0o700)
if err != nil {
Fail("Failed to copy test files")
}
@ -1384,7 +1384,7 @@ func runNetListener(wg *sync.WaitGroup, protocol, ip string, port int, expectedD
Expect(err).To(BeNil())
err = conn.SetDeadline(time.Now().Add(1 * time.Second))
Expect(err).To(BeNil())
data, err := ioutil.ReadAll(conn)
data, err := io.ReadAll(conn)
Expect(err).To(BeNil())
Expect(string(data)).To(Equal(expectedData))
conn.Close()

View File

@ -1,7 +1,7 @@
package etchosts
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -274,7 +274,7 @@ func TestNew(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
baseHostFile := tt.baseFileName
if !tt.noWriteBaseFile {
f, err := ioutil.TempFile(t.TempDir(), "basehosts")
f, err := os.CreateTemp(t.TempDir(), "basehosts")
assert.NoErrorf(t, err, "failed to create base host file: %v", err)
defer f.Close()
baseHostFile = f.Name()
@ -299,7 +299,7 @@ func TestNew(t *testing.T) {
}
assert.NoError(t, err, "New() failed")
content, err := ioutil.ReadFile(targetFile)
content, err := os.ReadFile(targetFile)
assert.NoErrorf(t, err, "failed to read target host file: %v", err)
assert.Equal(t, tt.expectedTargetFileContent, string(content), "check hosts content")
})
@ -346,7 +346,7 @@ func TestAdd(t *testing.T) {
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
f, err := ioutil.TempFile(t.TempDir(), "hosts")
f, err := os.CreateTemp(t.TempDir(), "hosts")
assert.NoErrorf(t, err, "failed to create base host file: %v", err)
defer f.Close()
hostFile := f.Name()
@ -364,7 +364,7 @@ func TestAdd(t *testing.T) {
}
assert.NoError(t, err, "Add() failed")
content, err := ioutil.ReadFile(hostFile)
content, err := os.ReadFile(hostFile)
assert.NoErrorf(t, err, "failed to read host file: %v", err)
assert.Equal(t, tt.expectedTargetFileContent, string(content), "check hosts content")
@ -442,7 +442,7 @@ func TestAddIfExists(t *testing.T) {
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
f, err := ioutil.TempFile(t.TempDir(), "hosts")
f, err := os.CreateTemp(t.TempDir(), "hosts")
assert.NoErrorf(t, err, "failed to create base host file: %v", err)
defer f.Close()
hostFile := f.Name()
@ -460,7 +460,7 @@ func TestAddIfExists(t *testing.T) {
}
assert.NoError(t, err, "AddIfExists() failed")
content, err := ioutil.ReadFile(hostFile)
content, err := os.ReadFile(hostFile)
assert.NoErrorf(t, err, "failed to read host file: %v", err)
assert.Equal(t, tt.expectedTargetFileContent, string(content), "check hosts content")
@ -505,7 +505,7 @@ func TestRemove(t *testing.T) {
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
f, err := ioutil.TempFile(t.TempDir(), "hosts")
f, err := os.CreateTemp(t.TempDir(), "hosts")
assert.NoErrorf(t, err, "failed to create base host file: %v", err)
defer f.Close()
hostFile := f.Name()
@ -519,7 +519,7 @@ func TestRemove(t *testing.T) {
err = Remove(hostFile, tt.entries)
assert.NoError(t, err, "Remove() failed")
content, err := ioutil.ReadFile(hostFile)
content, err := os.ReadFile(hostFile)
assert.NoErrorf(t, err, "failed to read host file: %v", err)
assert.Equal(t, tt.expectedTargetFileContent, string(content), "check hosts content")

View File

@ -5,7 +5,6 @@ package netavark_test
import (
"bytes"
"io/ioutil"
"net"
"os"
"path/filepath"
@ -28,7 +27,7 @@ var _ = Describe("Config", func() {
BeforeEach(func() {
var err error
networkConfDir, err = ioutil.TempDir("", "podman_netavark_test")
networkConfDir, err = os.MkdirTemp("", "podman_netavark_test")
if err != nil {
Fail("Failed to create tmpdir")
}
@ -1053,17 +1052,17 @@ var _ = Describe("Config", func() {
Context("network load valid existing ones", func() {
BeforeEach(func() {
dir := "testfiles/valid"
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
Fail("Failed to read test directory")
}
for _, file := range files {
filename := file.Name()
data, err := ioutil.ReadFile(filepath.Join(dir, filename))
data, err := os.ReadFile(filepath.Join(dir, filename))
if err != nil {
Fail("Failed to copy test files")
}
err = ioutil.WriteFile(filepath.Join(networkConfDir, filename), data, 0o700)
err = os.WriteFile(filepath.Join(networkConfDir, filename), data, 0o700)
if err != nil {
Fail("Failed to copy test files")
}
@ -1327,17 +1326,17 @@ var _ = Describe("Config", func() {
Context("network load invalid existing ones", func() {
BeforeEach(func() {
dir := "testfiles/invalid"
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
Fail("Failed to read test directory")
}
for _, file := range files {
filename := file.Name()
data, err := ioutil.ReadFile(filepath.Join(dir, filename))
data, err := os.ReadFile(filepath.Join(dir, filename))
if err != nil {
Fail("Failed to copy test files")
}
err = ioutil.WriteFile(filepath.Join(networkConfDir, filename), data, 0o700)
err = os.WriteFile(filepath.Join(networkConfDir, filename), data, 0o700)
if err != nil {
Fail("Failed to copy test files")
}
@ -1359,7 +1358,7 @@ var _ = Describe("Config", func() {
})
func grepInFile(path, match string) {
data, err := ioutil.ReadFile(path)
data, err := os.ReadFile(path)
ExpectWithOffset(1, err).To(BeNil())
ExpectWithOffset(1, string(data)).To(ContainSubstring(match))
}

View File

@ -6,7 +6,6 @@ package netavark
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"os"
@ -25,7 +24,7 @@ var _ = Describe("IPAM", func() {
BeforeEach(func() {
var err error
networkConfDir, err = ioutil.TempDir("", "podman_netavark_test")
networkConfDir, err = os.MkdirTemp("", "podman_netavark_test")
if err != nil {
Fail("Failed to create tmpdir")
}

View File

@ -7,7 +7,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
@ -174,7 +173,7 @@ func (n *netavarkNetwork) loadNetworks() error {
n.networks = nil
n.modTime = modTime
files, err := ioutil.ReadDir(n.networkConfigDir)
files, err := os.ReadDir(n.networkConfigDir)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}

View File

@ -15,7 +15,7 @@ package netavark_test
// })
import (
"io/ioutil"
"io"
"net"
"os"
"strconv"
@ -75,7 +75,7 @@ var _ = Describe("run netavark", func() {
}
var err error
confDir, err = ioutil.TempDir("", "podman_netavark_test")
confDir, err = os.MkdirTemp("", "podman_netavark_test")
if err != nil {
Fail("Failed to create tmpdir")
}
@ -799,7 +799,7 @@ func runNetListener(wg *sync.WaitGroup, protocol, ip string, port int, expectedD
defer conn.Close()
err = conn.SetDeadline(time.Now().Add(1 * time.Second))
Expect(err).To(BeNil())
data, err := ioutil.ReadAll(conn)
data, err := io.ReadAll(conn)
Expect(err).To(BeNil())
Expect(string(data)).To(Equal(expectedData))
}()

View File

@ -6,7 +6,6 @@ package network
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
@ -37,11 +36,12 @@ const (
// NetworkBackend returns the network backend name and interface
// It returns either the CNI or netavark backend depending on what is set in the config.
// If the the backend is set to "" we will automatically assign the backend on the following conditions:
// 1. read ${graphroot}/defaultNetworkBackend
// 2. find netavark binary (if not installed use CNI)
// 3. check containers, images and CNI networks and if there are some we have an existing install and should continue to use CNI
// 1. read ${graphroot}/defaultNetworkBackend
// 2. find netavark binary (if not installed use CNI)
// 3. check containers, images and CNI networks and if there are some we have an existing install and should continue to use CNI
//
// revive does not like the name because the package is already called network
//
//nolint:revive
func NetworkBackend(store storage.Store, conf *config.Config, syslog bool) (types.NetworkBackend, types.ContainerNetwork, error) {
backend := types.NetworkBackend(conf.Network.NetworkBackend)
@ -100,7 +100,7 @@ func NetworkBackend(store storage.Store, conf *config.Config, syslog bool) (type
func defaultNetworkBackend(store storage.Store, conf *config.Config) (backend types.NetworkBackend, err error) {
// read defaultNetworkBackend file
file := filepath.Join(store.GraphRoot(), defaultNetworkBackendFileName)
b, err := ioutil.ReadFile(file)
b, err := os.ReadFile(file)
if err == nil {
val := string(b)
if val == string(types.Netavark) {

View File

@ -40,12 +40,11 @@ var (
)
// filterResolvDNS cleans up the config in resolvConf. It has two main jobs:
// 1. If a netns is enabled, it looks for localhost (127.*|::1) entries in the provided
// resolv.conf, removing local nameserver entries, and, if the resulting
// cleaned config has no defined nameservers left, adds default DNS entries
// 2. Given the caller provides the enable/disable state of IPv6, the filter
// code will remove all IPv6 nameservers if it is not enabled for containers
//
// 1. If a netns is enabled, it looks for localhost (127.*|::1) entries in the provided
// resolv.conf, removing local nameserver entries, and, if the resulting
// cleaned config has no defined nameservers left, adds default DNS entries
// 2. Given the caller provides the enable/disable state of IPv6, the filter
// code will remove all IPv6 nameservers if it is not enabled for containers
func filterResolvDNS(resolvConf []byte, ipv6Enabled bool, netnsEnabled bool) []byte {
// If we're using the host netns, we have nothing to do besides hash the file.
if !netnsEnabled {

View File

@ -2,7 +2,6 @@ package supported
import (
"errors"
"io/ioutil"
"os"
"testing"
@ -51,7 +50,7 @@ func TestApparmorVerifier(t *testing.T) {
mock.UnshareIsRootlessReturns(false)
mock.RuncIsEnabledReturns(true)
file, err := ioutil.TempFile("", "")
file, err := os.CreateTemp("", "")
require.Nil(t, err)
fileInfo, err := file.Stat()
require.Nil(t, err)

View File

@ -1,7 +1,6 @@
package auth
import (
"io/ioutil"
"os"
"testing"
@ -52,7 +51,7 @@ var _ = Describe("Config", func() {
// Then
gomega.Expect(err).To(gomega.BeNil())
conf, _ := ioutil.TempFile("", "authfile")
conf, _ := os.CreateTemp("", "authfile")
defer os.Remove(conf.Name())
// When // When
err = CheckAuthFile(conf.Name())

View File

@ -8,7 +8,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
@ -143,7 +142,7 @@ func getAvailableControllers(exclude map[string]controllerHandler, cgroup2 bool)
basePath := cgroupRoot + userSlice
controllersFile = fmt.Sprintf("%s/cgroup.controllers", basePath)
}
controllersFileBytes, err := ioutil.ReadFile(controllersFile)
controllersFileBytes, err := os.ReadFile(controllersFile)
if err != nil {
return nil, fmt.Errorf("failed while reading controllers for cgroup v2: %w", err)
}
@ -294,7 +293,7 @@ func (c *CgroupControl) initialize() (err error) {
}
func readFileAsUint64(path string) (uint64, error) {
data, err := ioutil.ReadFile(path)
data, err := os.ReadFile(path)
if err != nil {
return 0, err
}
@ -310,7 +309,7 @@ func readFileAsUint64(path string) (uint64, error) {
}
func readFileByKeyAsUint64(path, key string) (uint64, error) {
content, err := ioutil.ReadFile(path)
content, err := os.ReadFile(path)
if err != nil {
return 0, err
}
@ -533,7 +532,7 @@ func (c *CgroupControl) AddPid(pid int) error {
if c.cgroup2 {
p := filepath.Join(cgroupRoot, c.path, "cgroup.procs")
if err := ioutil.WriteFile(p, pidString, 0o644); err != nil {
if err := os.WriteFile(p, pidString, 0o644); err != nil {
return fmt.Errorf("write %s: %w", p, err)
}
return nil
@ -556,7 +555,7 @@ func (c *CgroupControl) AddPid(pid int) error {
continue
}
p := filepath.Join(c.getCgroupv1Path(n), "tasks")
if err := ioutil.WriteFile(p, pidString, 0o644); err != nil {
if err := os.WriteFile(p, pidString, 0o644); err != nil {
return fmt.Errorf("write %s: %w", p, err)
}
}

View File

@ -8,7 +8,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
@ -96,7 +95,7 @@ func getAvailableControllers(exclude map[string]controllerHandler, cgroup2 bool)
basePath := cgroupRoot + userSlice
controllersFile = fmt.Sprintf("%s/cgroup.controllers", basePath)
}
controllersFileBytes, err := ioutil.ReadFile(controllersFile)
controllersFileBytes, err := os.ReadFile(controllersFile)
if err != nil {
return nil, fmt.Errorf("failed while reading controllers for cgroup v2: %w", err)
}
@ -247,7 +246,7 @@ func (c *CgroupControl) initialize() (err error) {
}
func readFileAsUint64(path string) (uint64, error) {
data, err := ioutil.ReadFile(path)
data, err := os.ReadFile(path)
if err != nil {
return 0, err
}
@ -263,7 +262,7 @@ func readFileAsUint64(path string) (uint64, error) {
}
func readFileByKeyAsUint64(path, key string) (uint64, error) {
content, err := ioutil.ReadFile(path)
content, err := os.ReadFile(path)
if err != nil {
return 0, err
}
@ -516,7 +515,7 @@ func (c *CgroupControl) AddPid(pid int) error {
continue
}
p := filepath.Join(c.getCgroupv1Path(n), "tasks")
if err := ioutil.WriteFile(p, pidString, 0o644); err != nil {
if err := os.WriteFile(p, pidString, 0o644); err != nil {
return fmt.Errorf("write %s: %w", p, err)
}
}

View File

@ -7,7 +7,6 @@ import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
@ -99,12 +98,12 @@ func UserOwnsCurrentSystemdCgroup() (bool, error) {
func rmDirRecursively(path string) error {
killProcesses := func(signal syscall.Signal) {
if signal == unix.SIGKILL {
if err := ioutil.WriteFile(filepath.Join(path, "cgroup.kill"), []byte("1"), 0o600); err == nil {
if err := os.WriteFile(filepath.Join(path, "cgroup.kill"), []byte("1"), 0o600); err == nil {
return
}
}
// kill all the processes that are still part of the cgroup
if procs, err := ioutil.ReadFile(filepath.Join(path, "cgroup.procs")); err == nil {
if procs, err := os.ReadFile(filepath.Join(path, "cgroup.procs")); err == nil {
for _, pidS := range strings.Split(string(procs), "\n") {
if pid, err := strconv.Atoi(pidS); err == nil {
_ = unix.Kill(pid, signal)
@ -116,7 +115,7 @@ func rmDirRecursively(path string) error {
if err := os.Remove(path); err == nil || errors.Is(err, os.ErrNotExist) {
return nil
}
entries, err := ioutil.ReadDir(path)
entries, err := os.ReadDir(path)
if err != nil {
return err
}

View File

@ -5,7 +5,7 @@ package cgroups
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
spec "github.com/opencontainers/runtime-spec/specs-go"
@ -31,7 +31,7 @@ func (c *pidHandler) Apply(ctr *CgroupControl, res *spec.LinuxResources) error {
}
p := filepath.Join(PIDRoot, "pids.max")
return ioutil.WriteFile(p, []byte(fmt.Sprintf("%d\n", res.Pids.Limit)), 0o644)
return os.WriteFile(p, []byte(fmt.Sprintf("%d\n", res.Pids.Limit)), 0o644)
}
// Create the cgroup

View File

@ -53,18 +53,20 @@ func systemdCreate(path string, c *systemdDbus.Conn) error {
}
/*
systemdDestroyConn is copied from containerd/cgroups/systemd.go file, that
has the following license:
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
systemdDestroyConn is copied from containerd/cgroups/systemd.go file, that
has the following license:
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
func systemdDestroyConn(path string, c *systemdDbus.Conn) error {
name := filepath.Base(path)

View File

@ -108,22 +108,22 @@ func systemdCreate(resources *configs.Resources, path string, c *systemdDbus.Con
}
/*
systemdDestroyConn is copied from containerd/cgroups/systemd.go file, that
has the following license:
systemdDestroyConn is copied from containerd/cgroups/systemd.go file, that
has the following license:
Copyright The containerd Authors.
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
func systemdDestroyConn(path string, c *systemdDbus.Conn) error {
name := filepath.Base(path)

View File

@ -4,7 +4,6 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
@ -24,7 +23,7 @@ func readAcct(ctr *CgroupControl, name string) (uint64, error) {
func readAcctList(ctr *CgroupControl, name string) ([]uint64, error) {
p := filepath.Join(ctr.getCgroupv1Path(CPUAcct), name)
data, err := ioutil.ReadFile(p)
data, err := os.ReadFile(p)
if err != nil {
return nil, err
}
@ -54,7 +53,7 @@ func GetSystemCPUUsage() (uint64, error) {
return readFileAsUint64(p)
}
files, err := ioutil.ReadDir(cgroupRoot)
files, err := os.ReadDir(cgroupRoot)
if err != nil {
return 0, err
}
@ -90,7 +89,7 @@ func cpusetCopyFileFromParent(dir, file string, cgroupv2 bool) ([]byte, error) {
if cgroupv2 {
parentPath = fmt.Sprintf("%s.effective", parentPath)
}
data, err := ioutil.ReadFile(parentPath)
data, err := os.ReadFile(parentPath)
if err != nil {
// if the file doesn't exist, it is likely that the cpuset controller
// is not enabled in the kernel.
@ -106,7 +105,7 @@ func cpusetCopyFileFromParent(dir, file string, cgroupv2 bool) ([]byte, error) {
if err != nil {
return nil, err
}
if err := ioutil.WriteFile(path, data, 0o644); err != nil {
if err := os.WriteFile(path, data, 0o644); err != nil {
return nil, fmt.Errorf("write %s: %w", path, err)
}
return data, nil
@ -126,7 +125,7 @@ func createCgroupv2Path(path string) (deferredError error) {
if !strings.HasPrefix(path, cgroupRoot+"/") {
return fmt.Errorf("invalid cgroup path %s", path)
}
content, err := ioutil.ReadFile(cgroupRoot + "/cgroup.controllers")
content, err := os.ReadFile(cgroupRoot + "/cgroup.controllers")
if err != nil {
return err
}
@ -154,7 +153,7 @@ func createCgroupv2Path(path string) (deferredError error) {
// We enable the controllers for all the path components except the last one. It is not allowed to add
// PIDs if there are already enabled controllers.
if i < len(elements[3:])-1 {
if err := ioutil.WriteFile(filepath.Join(current, "cgroup.subtree_control"), res, 0o755); err != nil {
if err := os.WriteFile(filepath.Join(current, "cgroup.subtree_control"), res, 0o755); err != nil {
return err
}
}

View File

@ -1,7 +1,6 @@
package chown
import (
"io/ioutil"
"os"
"runtime"
"syscall"
@ -16,7 +15,7 @@ func TestDangerousHostPath(t *testing.T) {
}
// Create a temp dir that is not dangerous
td, err := ioutil.TempDir("/tmp", "validDir")
td, err := os.MkdirTemp("/tmp", "validDir")
if err != nil {
t.Fatal(err)
}
@ -66,7 +65,7 @@ func TestChangeHostPathOwnership(t *testing.T) {
}
// Create a temp dir that is not dangerous
td, err := ioutil.TempDir("/tmp", "validDir")
td, err := os.MkdirTemp("/tmp", "validDir")
if err != nil {
t.Fatal(err)
}

View File

@ -579,6 +579,7 @@ type SecretConfig struct {
// ConfigMapConfig represents the "configmap" TOML config table
//
// revive does not like the name because the package is already called config
//
//nolint:revive
type ConfigMapConfig struct {
// Driver specifies the configmap driver to use.
@ -1037,10 +1038,11 @@ func (c *Config) Capabilities(user string, addCapabilities, dropCapabilities []s
// Device parses device mapping string to a src, dest & permissions string
// Valid values for device looklike:
// '/dev/sdc"
// '/dev/sdc:/dev/xvdc"
// '/dev/sdc:/dev/xvdc:rwm"
// '/dev/sdc:rm"
//
// '/dev/sdc"
// '/dev/sdc:/dev/xvdc"
// '/dev/sdc:/dev/xvdc:rwm"
// '/dev/sdc:rm"
func Device(device string) (src, dst, permissions string, err error) {
permissions = "rwm"
split := strings.Split(device, ":")

View File

@ -5,7 +5,6 @@ package config
import (
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
@ -37,7 +36,7 @@ var _ = Describe("Config Local", func() {
})
It("should fail on invalid CNIPluginDirs", func() {
validDirPath, err := ioutil.TempDir("", "config-empty")
validDirPath, err := os.MkdirTemp("", "config-empty")
if err != nil {
panic(err)
}
@ -54,7 +53,7 @@ var _ = Describe("Config Local", func() {
})
It("should fail in validating invalid PluginDir", func() {
validDirPath, err := ioutil.TempDir("", "config-empty")
validDirPath, err := os.MkdirTemp("", "config-empty")
if err != nil {
panic(err)
}
@ -71,7 +70,7 @@ var _ = Describe("Config Local", func() {
})
It("should fail on invalid CNIPluginDirs", func() {
validDirPath, err := ioutil.TempDir("", "config-empty")
validDirPath, err := os.MkdirTemp("", "config-empty")
if err != nil {
panic(err)
}
@ -88,7 +87,7 @@ var _ = Describe("Config Local", func() {
})
It("should fail on invalid subnet pool", func() {
validDirPath, err := ioutil.TempDir("", "config-empty")
validDirPath, err := os.MkdirTemp("", "config-empty")
if err != nil {
panic(err)
}
@ -149,7 +148,7 @@ var _ = Describe("Config Local", func() {
})
It("should fail during runtime", func() {
validDirPath, err := ioutil.TempDir("", "config-empty")
validDirPath, err := os.MkdirTemp("", "config-empty")
if err != nil {
panic(err)
}

View File

@ -4,7 +4,6 @@
package config
import (
"io/ioutil"
"os"
. "github.com/onsi/ginkgo/v2"
@ -15,7 +14,7 @@ var _ = Describe("Config Remote", func() {
BeforeEach(beforeEach)
It("should succeed on invalid CNIPluginDirs", func() {
validDirPath, err := ioutil.TempDir("", "config-empty")
validDirPath, err := os.MkdirTemp("", "config-empty")
if err != nil {
panic(err)
}
@ -107,7 +106,7 @@ var _ = Describe("Config Remote", func() {
})
It("should succeed on invalid CNIPluginDirs", func() {
validDirPath, err := ioutil.TempDir("", "config-empty")
validDirPath, err := os.MkdirTemp("", "config-empty")
if err != nil {
panic(err)
}
@ -124,7 +123,7 @@ var _ = Describe("Config Remote", func() {
})
It("should succeed in validating invalid PluginDir", func() {
validDirPath, err := ioutil.TempDir("", "config-empty")
validDirPath, err := os.MkdirTemp("", "config-empty")
if err != nil {
panic(err)
}

View File

@ -2,7 +2,7 @@ package config
import (
"bytes"
"io/ioutil"
"io"
"os"
"sort"
"strings"
@ -122,7 +122,7 @@ var _ = Describe("Config", func() {
testFile := "testdata/temp.conf"
content := `[engine]
image_copy_tmp_dir="storage"`
err := ioutil.WriteFile(testFile, []byte(content), os.ModePerm)
err := os.WriteFile(testFile, []byte(content), os.ModePerm)
// Then
gomega.Expect(err).To(gomega.BeNil())
defer os.Remove(testFile)
@ -519,7 +519,7 @@ image_copy_tmp_dir="storage"`
BeforeEach(func() {
ConfPath.Value, ConfPath.IsSet = os.LookupEnv("CONTAINERS_CONF")
conf, _ := ioutil.TempFile("", "containersconf")
conf, _ := os.CreateTemp("", "containersconf")
os.Setenv("CONTAINERS_CONF", conf.Name())
})
@ -551,7 +551,7 @@ image_copy_tmp_dir="storage"`
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
f, err := os.Open(path)
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
data, err := ioutil.ReadAll(f)
data, err := io.ReadAll(f)
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
gomega.Expect(string(data)).ShouldNot(gomega.ContainSubstring("cpus"))
gomega.Expect(string(data)).ShouldNot(gomega.ContainSubstring("disk_size"))
@ -694,7 +694,7 @@ image_copy_tmp_dir="storage"`
It("test addConfigs", func() {
tmpFilePath := func(dir, prefix string) string {
file, err := ioutil.TempFile(dir, prefix)
file, err := os.CreateTemp(dir, prefix)
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
conf := file.Name() + ".conf"
@ -710,7 +710,7 @@ image_copy_tmp_dir="storage"`
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
gomega.Expect(newConfigs).To(gomega.Equal(configs))
dir, err := ioutil.TempDir("", "configTest")
dir, err := os.MkdirTemp("", "configTest")
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
defer os.RemoveAll(dir)
file1 := tmpFilePath(dir, "b")
@ -719,13 +719,13 @@ image_copy_tmp_dir="storage"`
file4 := tmpFilePath(dir, "1")
// create a file in dir that is not a .conf to make sure
// it does not show up in configs
_, err = ioutil.TempFile(dir, "notconf")
_, err = os.CreateTemp(dir, "notconf")
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
subdir, err := ioutil.TempDir(dir, "")
subdir, err := os.MkdirTemp(dir, "")
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
// create a file in subdir, to make sure it does not
// show up in configs
_, err = ioutil.TempFile(subdir, "")
_, err = os.CreateTemp(subdir, "")
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
newConfigs, err = addConfigs(dir, configs)
@ -776,7 +776,7 @@ image_copy_tmp_dir="storage"`
testFile := "testdata/temp.conf"
content := `[containers]
env=["foo=bar"]`
err = ioutil.WriteFile(testFile, []byte(content), os.ModePerm)
err = os.WriteFile(testFile, []byte(content), os.ModePerm)
defer os.Remove(testFile)
gomega.Expect(err).To(gomega.BeNil())
oldEnv, set = os.LookupEnv("CONTAINERS_CONF")
@ -807,14 +807,14 @@ env=["foo=bar"]`
conf, err := ReadCustomConfig()
gomega.Expect(err).ToNot(gomega.HaveOccurred())
f, err := ioutil.TempFile("", "container-common-test")
f, err := os.CreateTemp("", "container-common-test")
gomega.Expect(err).ToNot(gomega.HaveOccurred())
defer f.Close()
defer os.Remove(f.Name())
os.Setenv("CONTAINERS_CONF", f.Name())
err = conf.Write()
gomega.Expect(err).ToNot(gomega.HaveOccurred())
b, err := ioutil.ReadFile(f.Name())
b, err := os.ReadFile(f.Name())
gomega.Expect(err).ToNot(gomega.HaveOccurred())
// config should only contain empty stanzas
gomega.Expect(string(b)).To(gomega.

View File

@ -685,4 +685,3 @@ func useUserConfigLocations() bool {
// GetRootlessUID == -1 on Windows, so exclude negative range
return unshare.GetRootlessUID() > 0
}

View File

@ -7,7 +7,7 @@ func getDefaultCgroupsMode() string {
// In theory, FreeBSD should be able to use shm locks but in practice,
// this causes cryptic error messages from the kernel that look like:
//
// comm podman pid 90813: handling rb error 22
// comm podman pid 90813: handling rb error 22
//
// These seem to be related to fork/exec code paths. Fall back to
// file-based locks.

View File

@ -2,7 +2,6 @@ package config
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
@ -37,7 +36,7 @@ func getDefaultProcessLimits() []string {
rlim := unix.Rlimit{Cur: oldMaxSize, Max: oldMaxSize}
oldrlim := rlim
// Attempt to set file limit and process limit to pid_max in OS
dat, err := ioutil.ReadFile("/proc/sys/kernel/pid_max")
dat, err := os.ReadFile("/proc/sys/kernel/pid_max")
if err == nil {
val := strings.TrimSuffix(string(dat), "\n")
max, err := strconv.ParseUint(val, 10, 64)

View File

@ -3,7 +3,6 @@ package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"testing"
@ -12,7 +11,7 @@ import (
)
func prepareProbeBinary(t *testing.T, expectedOutput string) (path string) {
f, err := ioutil.TempFile("", "conmon-")
f, err := os.CreateTemp("", "conmon-")
require.Nil(t, err)
defer func() { require.Nil(t, f.Close()) }()

View File

@ -4,7 +4,7 @@
package config
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
@ -53,7 +53,7 @@ func defaultLogDriver() string {
func useSystemd() bool {
systemdOnce.Do(func() {
dat, err := ioutil.ReadFile("/proc/1/comm")
dat, err := os.ReadFile("/proc/1/comm")
if err == nil {
val := strings.TrimSuffix(string(dat), "\n")
usesSystemd = (val == "systemd")
@ -68,13 +68,13 @@ func useJournald() bool {
return
}
for _, root := range []string{"/run/log/journal", "/var/log/journal"} {
dirs, err := ioutil.ReadDir(root)
dirs, err := os.ReadDir(root)
if err != nil {
continue
}
for _, d := range dirs {
if d.IsDir() {
if _, err := ioutil.ReadDir(filepath.Join(root, d.Name())); err == nil {
if _, err := os.ReadDir(filepath.Join(root, d.Name())); err == nil {
usesJournald = true
return
}

View File

@ -82,6 +82,7 @@ type ConfigMap struct {
// the configMap metadata.
//
// revive does not like the name because the package is already called configmaps
//
//nolint:revive
type ConfigMapsDriver interface {
// List lists all configMap ids in the configMaps data store

View File

@ -2,7 +2,6 @@ package configmaps
import (
"bytes"
"io/ioutil"
"os"
"testing"
@ -14,7 +13,7 @@ var drivertype = "file"
var opts map[string]string
func setup() (*ConfigMapManager, string, error) {
testpath, err := ioutil.TempDir("", "cmdata")
testpath, err := os.MkdirTemp("", "cmdata")
if err != nil {
return nil, "", err
}

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"os"
"strings"
"time"
@ -51,7 +51,7 @@ func (s *ConfigMapManager) loadDB() error {
return err
}
byteValue, err := ioutil.ReadAll(file)
byteValue, err := io.ReadAll(file)
if err != nil {
return err
}
@ -176,7 +176,7 @@ func (s *ConfigMapManager) store(entry *ConfigMap) error {
if err != nil {
return err
}
err = ioutil.WriteFile(s.configMapDBPath, marshalled, 0o600)
err = os.WriteFile(s.configMapDBPath, marshalled, 0o600)
if err != nil {
return err
}
@ -202,7 +202,7 @@ func (s *ConfigMapManager) delete(nameOrID string) error {
if err != nil {
return err
}
err = ioutil.WriteFile(s.configMapDBPath, marshalled, 0o600)
err = os.WriteFile(s.configMapDBPath, marshalled, 0o600)
if err != nil {
return err
}

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"os"
"path/filepath"
"sort"
@ -96,7 +96,7 @@ func (d *Driver) Store(id string, data []byte) error {
if err != nil {
return err
}
err = ioutil.WriteFile(d.configMapsDataFilePath, marshalled, 0o600)
err = os.WriteFile(d.configMapsDataFilePath, marshalled, 0o600)
if err != nil {
return err
}
@ -120,7 +120,7 @@ func (d *Driver) Delete(id string) error {
if err != nil {
return err
}
err = ioutil.WriteFile(d.configMapsDataFilePath, marshalled, 0o600)
err = os.WriteFile(d.configMapsDataFilePath, marshalled, 0o600)
if err != nil {
return err
}
@ -145,7 +145,7 @@ func (d *Driver) getAllData() (map[string][]byte, error) {
}
defer file.Close()
byteValue, err := ioutil.ReadAll(file)
byteValue, err := io.ReadAll(file)
if err != nil {
return nil, err
}

View File

@ -1,7 +1,6 @@
package filedriver
import (
"io/ioutil"
"os"
"testing"
@ -9,7 +8,7 @@ import (
)
func setup() (*Driver, error) {
tmppath, err := ioutil.TempDir("", "configmapsdata")
tmppath, err := os.MkdirTemp("", "configmapsdata")
if err != nil {
return nil, err
}

View File

@ -3,14 +3,14 @@ package download
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
// FromURL downloads the specified source to a file in tmpdir (OS defaults if
// empty).
func FromURL(tmpdir, source string) (string, error) {
tmp, err := ioutil.TempFile(tmpdir, "")
tmp, err := os.CreateTemp(tmpdir, "")
if err != nil {
return "", fmt.Errorf("creating temporary download file: %w", err)
}

View File

@ -38,6 +38,7 @@ func ComputeUntilTimestamp(filterValues []string) (time.Time, error) {
// background.
//
// revive does not like the name because the package is already called filters
//
//nolint:revive
func FiltersFromRequest(r *http.Request) ([]string, error) {
var (

View File

@ -90,8 +90,8 @@ func (m *Manager) namedHooks() (hooks []*namedHook) {
// extensionStageHooks. This takes precedence over their inclusion in
// the OCI configuration. For example:
//
// manager, err := New(ctx, []string{DefaultDir}, []string{"poststop"})
// extensionStageHooks, err := manager.Hooks(config, annotations, hasBindMounts)
// manager, err := New(ctx, []string{DefaultDir}, []string{"poststop"})
// extensionStageHooks, err := manager.Hooks(config, annotations, hasBindMounts)
//
// will have any matching post-stop hooks in extensionStageHooks and
// will not insert them into config.Hooks.Poststop.

View File

@ -3,7 +3,7 @@ package hooks
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"testing"
@ -31,7 +31,7 @@ func TestGoodNew(t *testing.T) {
if i == 0 {
extraStages = ", \"poststart\", \"poststop\""
}
err := ioutil.WriteFile(jsonPath, []byte(fmt.Sprintf("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"%s\", \"timeout\": %d}, \"when\": {\"always\": true}, \"stages\": [\"prestart\"%s]}", path, i+1, extraStages)), 0o644)
err := os.WriteFile(jsonPath, []byte(fmt.Sprintf("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"%s\", \"timeout\": %d}, \"when\": {\"always\": true}, \"stages\": [\"prestart\"%s]}", path, i+1, extraStages)), 0o644)
if err != nil {
t.Fatal(err)
}
@ -90,7 +90,7 @@ func TestBadNew(t *testing.T) {
dir := t.TempDir()
jsonPath := filepath.Join(dir, "a.json")
err := ioutil.WriteFile(jsonPath, []byte("{\"version\": \"-1\"}"), 0o644)
err := os.WriteFile(jsonPath, []byte("{\"version\": \"-1\"}"), 0o644)
if err != nil {
t.Fatal(err)
}

View File

@ -15,16 +15,16 @@ import (
// first is written after the watchers are established and the second
// when this function exits. The expected usage is:
//
// ctx, cancel := context.WithCancel(context.Background())
// sync := make(chan error, 2)
// go m.Monitor(ctx, sync)
// err := <-sync // block until writers are established
// if err != nil {
// return err // failed to establish watchers
// }
// // do stuff
// cancel()
// err = <-sync // block until monitor finishes
// ctx, cancel := context.WithCancel(context.Background())
// sync := make(chan error, 2)
// go m.Monitor(ctx, sync)
// err := <-sync // block until writers are established
// if err != nil {
// return err // failed to establish watchers
// }
// // do stuff
// cancel()
// err = <-sync // block until monitor finishes
func (m *Manager) Monitor(ctx context.Context, sync chan<- error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {

View File

@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -33,7 +32,7 @@ func TestMonitorOneDirGood(t *testing.T) {
jsonPath := filepath.Join(dir, "a.json")
t.Run("good-addition", func(t *testing.T) {
err = ioutil.WriteFile(jsonPath, []byte(fmt.Sprintf("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"%s\"}, \"when\": {\"always\": true}, \"stages\": [\"prestart\", \"poststart\", \"poststop\"]}", path)), 0o644)
err = os.WriteFile(jsonPath, []byte(fmt.Sprintf("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"%s\"}, \"when\": {\"always\": true}, \"stages\": [\"prestart\", \"poststart\", \"poststop\"]}", path)), 0o644)
if err != nil {
t.Fatal(err)
}
@ -83,7 +82,7 @@ func TestMonitorOneDirGood(t *testing.T) {
})
t.Run("bad-addition", func(t *testing.T) {
err = ioutil.WriteFile(jsonPath, []byte("{\"version\": \"-1\"}"), 0o644)
err = os.WriteFile(jsonPath, []byte("{\"version\": \"-1\"}"), 0o644)
if err != nil {
t.Fatal(err)
}
@ -137,7 +136,7 @@ func TestMonitorTwoDirGood(t *testing.T) {
}
t.Run("good-fallback-addition", func(t *testing.T) {
err = ioutil.WriteFile(fallbackPath, fallbackJSON, 0o644)
err = os.WriteFile(fallbackPath, fallbackJSON, 0o644)
if err != nil {
t.Fatal(err)
}
@ -166,7 +165,7 @@ func TestMonitorTwoDirGood(t *testing.T) {
}
t.Run("good-primary-override", func(t *testing.T) {
err = ioutil.WriteFile(primaryPath, primaryJSON, 0o644)
err = os.WriteFile(primaryPath, primaryJSON, 0o644)
if err != nil {
t.Fatal(err)
}
@ -199,7 +198,7 @@ func TestMonitorTwoDirGood(t *testing.T) {
})
t.Run("good-fallback-restore", func(t *testing.T) {
err = ioutil.WriteFile(fallbackPath, fallbackJSON, 0o644)
err = os.WriteFile(fallbackPath, fallbackJSON, 0o644)
if err != nil {
t.Fatal(err)
}
@ -217,7 +216,7 @@ func TestMonitorTwoDirGood(t *testing.T) {
primaryPath2 := filepath.Join(primaryDir, "0a.json") // 0a because it will be before a.json alphabetically
t.Run("bad-primary-new-addition", func(t *testing.T) {
err = ioutil.WriteFile(primaryPath2, []byte("{\"version\": \"-1\"}"), 0o644)
err = os.WriteFile(primaryPath2, []byte("{\"version\": \"-1\"}"), 0o644)
if err != nil {
t.Fatal(err)
}
@ -236,7 +235,7 @@ func TestMonitorTwoDirGood(t *testing.T) {
})
t.Run("bad-primary-same-addition", func(t *testing.T) {
err = ioutil.WriteFile(primaryPath, []byte("{\"version\": \"-1\"}"), 0o644)
err = os.WriteFile(primaryPath, []byte("{\"version\": \"-1\"}"), 0o644)
if err != nil {
t.Fatal(err)
}
@ -269,7 +268,7 @@ func TestMonitorTwoDirGood(t *testing.T) {
})
t.Run("good-non-json-addition", func(t *testing.T) {
err = ioutil.WriteFile(filepath.Join(fallbackDir, "README"), []byte("Hello"), 0o644)
err = os.WriteFile(filepath.Join(fallbackDir, "README"), []byte("Hello"), 0o644)
if err != nil {
t.Fatal(err)
}

View File

@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
@ -31,7 +30,7 @@ func Read(path string, extensionStages []string) (*current.Hook, error) {
if !strings.HasSuffix(path, ".json") {
return nil, ErrNoJSONSuffix
}
content, err := ioutil.ReadFile(path)
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
@ -64,7 +63,7 @@ func read(content []byte) (hook *current.Hook, err error) {
// clobbering any previous entries with the same filenames.
func ReadDir(path string, extensionStages []string, hooks map[string]*current.Hook) error {
logrus.Debugf("reading hooks from %s", path)
files, err := ioutil.ReadDir(path)
files, err := os.ReadDir(path)
if err != nil {
return err
}

View File

@ -3,7 +3,6 @@ package hooks
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -33,7 +32,7 @@ func TestGoodFile(t *testing.T) {
dir := t.TempDir()
jsonPath := filepath.Join(dir, "hook.json")
err := ioutil.WriteFile(jsonPath, []byte(fmt.Sprintf("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"%s\"}, \"when\": {\"always\": true}, \"stages\": [\"prestart\"]}", path)), 0o644)
err := os.WriteFile(jsonPath, []byte(fmt.Sprintf("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"%s\"}, \"when\": {\"always\": true}, \"stages\": [\"prestart\"]}", path)), 0o644)
if err != nil {
t.Fatal(err)
}
@ -59,7 +58,7 @@ func TestBadFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "hook.json")
err := ioutil.WriteFile(path, []byte("{\"version\": \"1.0.0\", \"hook\": \"not-a-string\"}"), 0o644)
err := os.WriteFile(path, []byte("{\"version\": \"1.0.0\", \"hook\": \"not-a-string\"}"), 0o644)
if err != nil {
t.Fatal(err)
}
@ -116,13 +115,13 @@ func TestInvalidCurrentJSON(t *testing.T) {
func TestGoodDir(t *testing.T) {
dir := t.TempDir()
err := ioutil.WriteFile(filepath.Join(dir, "README"), []byte("not a hook"), 0o644)
err := os.WriteFile(filepath.Join(dir, "README"), []byte("not a hook"), 0o644)
if err != nil {
t.Fatal(err)
}
jsonPath := filepath.Join(dir, "a.json")
err = ioutil.WriteFile(jsonPath, []byte(fmt.Sprintf("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"%s\"}, \"when\": {\"always\": true}, \"stages\": [\"prestart\"]}", path)), 0o644)
err = os.WriteFile(jsonPath, []byte(fmt.Sprintf("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"%s\"}, \"when\": {\"always\": true}, \"stages\": [\"prestart\"]}", path)), 0o644)
if err != nil {
t.Fatal(err)
}
@ -164,7 +163,7 @@ func TestBadDir(t *testing.T) {
dir := t.TempDir()
jsonPath := filepath.Join(dir, "a.json")
err := ioutil.WriteFile(jsonPath, []byte("{\"version\": \"-1\"}"), 0o644)
err := os.WriteFile(jsonPath, []byte("{\"version\": \"-1\"}"), 0o644)
if err != nil {
t.Fatal(err)
}
@ -181,7 +180,7 @@ func TestHookExecutableDoesNotExit(t *testing.T) {
dir := t.TempDir()
jsonPath := filepath.Join(dir, "hook.json")
err := ioutil.WriteFile(jsonPath, []byte("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"/does/not/exist\"}, \"when\": {\"always\": true}, \"stages\": [\"prestart\"]}"), 0o644)
err := os.WriteFile(jsonPath, []byte("{\"version\": \"1.0.0\", \"hook\": {\"path\": \"/does/not/exist\"}, \"when\": {\"always\": true}, \"stages\": [\"prestart\"]}"), 0o644)
if err != nil {
t.Fatal(err)
}

View File

@ -10,6 +10,7 @@ import (
)
// TODO: change name to MachineMarker since package is already called machine
//
//nolint:revive
type MachineMarker struct {
Enabled bool
@ -57,6 +58,7 @@ func IsPodmanMachine() bool {
}
// TODO: change name to HostType since package is already called machine
//
//nolint:revive
func MachineHostType() string {
return GetMachineMarker().Type

View File

@ -1,7 +1,6 @@
package manifests
import (
"io/ioutil"
"os"
"reflect"
"testing"
@ -39,7 +38,7 @@ func TestFromBlob(t *testing.T) {
ociFixture,
dockerFixture,
} {
bytes, err := ioutil.ReadFile(version)
bytes, err := os.ReadFile(version)
if err != nil {
t.Fatalf("error loading %s: %v", version, err)
}
@ -64,7 +63,7 @@ func TestFromBlob(t *testing.T) {
}
func TestAddInstance(t *testing.T) {
manifestBytes, err := ioutil.ReadFile("testdata/fedora-minimal.schema2.json")
manifestBytes, err := os.ReadFile("testdata/fedora-minimal.schema2.json")
if err != nil {
t.Fatalf("error loading testdata/fedora-minimal.schema2.json: %v", err)
}
@ -77,7 +76,7 @@ func TestAddInstance(t *testing.T) {
ociFixture,
dockerFixture,
} {
bytes, err := ioutil.ReadFile(version)
bytes, err := os.ReadFile(version)
if err != nil {
t.Fatalf("error loading %s: %v", version, err)
}
@ -98,7 +97,7 @@ func TestAddInstance(t *testing.T) {
}
func TestRemove(t *testing.T) {
bytes, err := ioutil.ReadFile(ociFixture)
bytes, err := os.ReadFile(ociFixture)
if err != nil {
t.Fatalf("error loading blob: %v", err)
}
@ -131,7 +130,7 @@ func TestRemove(t *testing.T) {
}
func testString(t *testing.T, values []string, set func(List, digest.Digest, string) error, get func(List, digest.Digest) (string, error)) {
bytes, err := ioutil.ReadFile(ociFixture)
bytes, err := os.ReadFile(ociFixture)
if err != nil {
t.Fatalf("error loading blob: %v", err)
}
@ -162,7 +161,7 @@ func testString(t *testing.T, values []string, set func(List, digest.Digest, str
}
func testStringSlice(t *testing.T, values [][]string, set func(List, digest.Digest, []string) error, get func(List, digest.Digest) ([]string, error)) {
bytes, err := ioutil.ReadFile(ociFixture)
bytes, err := os.ReadFile(ociFixture)
if err != nil {
t.Fatalf("error loading blob: %v", err)
}
@ -193,7 +192,7 @@ func testStringSlice(t *testing.T, values [][]string, set func(List, digest.Dige
}
func testMap(t *testing.T, values []map[string]string, set func(List, *digest.Digest, map[string]string) error, get func(List, *digest.Digest) (map[string]string, error)) {
bytes, err := ioutil.ReadFile(ociFixture)
bytes, err := os.ReadFile(ociFixture)
if err != nil {
t.Fatalf("error loading blob: %v", err)
}
@ -332,7 +331,7 @@ func TestSerialize(t *testing.T) {
ociFixture,
dockerFixture,
} {
bytes, err := ioutil.ReadFile(version)
bytes, err := os.ReadFile(version)
if err != nil {
t.Fatalf("error loading %s: %v", version, err)
}

View File

@ -103,10 +103,11 @@ func ValidateVolumeOpts(options []string) ([]string, error) {
// Device parses device mapping string to a src, dest & permissions string
// Valid values for device looklike:
// '/dev/sdc"
// '/dev/sdc:/dev/xvdc"
// '/dev/sdc:/dev/xvdc:rwm"
// '/dev/sdc:rm"
//
// '/dev/sdc"
// '/dev/sdc:/dev/xvdc"
// '/dev/sdc:/dev/xvdc:rwm"
// '/dev/sdc:rm"
func Device(device string) (src, dest, permissions string, err error) {
permissions = "rwm"
arr := strings.Split(device, ":")

View File

@ -13,37 +13,37 @@ import (
//
// Examples
//
// "" => [""]
// "lowercase" => ["lowercase"]
// "Class" => ["Class"]
// "MyClass" => ["My", "Class"]
// "MyC" => ["My", "C"]
// "HTML" => ["HTML"]
// "PDFLoader" => ["PDF", "Loader"]
// "AString" => ["A", "String"]
// "SimpleXMLParser" => ["Simple", "XML", "Parser"]
// "vimRPCPlugin" => ["vim", "RPC", "Plugin"]
// "GL11Version" => ["GL", "11", "Version"]
// "99Bottles" => ["99", "Bottles"]
// "May5" => ["May", "5"]
// "BFG9000" => ["BFG", "9000"]
// "BöseÜberraschung" => ["Böse", "Überraschung"]
// "Two spaces" => ["Two", " ", "spaces"]
// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"]
// "" => [""]
// "lowercase" => ["lowercase"]
// "Class" => ["Class"]
// "MyClass" => ["My", "Class"]
// "MyC" => ["My", "C"]
// "HTML" => ["HTML"]
// "PDFLoader" => ["PDF", "Loader"]
// "AString" => ["A", "String"]
// "SimpleXMLParser" => ["Simple", "XML", "Parser"]
// "vimRPCPlugin" => ["vim", "RPC", "Plugin"]
// "GL11Version" => ["GL", "11", "Version"]
// "99Bottles" => ["99", "Bottles"]
// "May5" => ["May", "5"]
// "BFG9000" => ["BFG", "9000"]
// "BöseÜberraschung" => ["Böse", "Überraschung"]
// "Two spaces" => ["Two", " ", "spaces"]
// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"]
//
// Splitting rules
//
// 1) If string is not valid UTF-8, return it without splitting as
// 1. If string is not valid UTF-8, return it without splitting as
// single item array.
// 2) Assign all unicode characters into one of 4 sets: lower case
// 2. Assign all unicode characters into one of 4 sets: lower case
// letters, upper case letters, numbers, and all other characters.
// 3) Iterate through characters of string, introducing splits
// 3. Iterate through characters of string, introducing splits
// between adjacent characters that belong to different sets.
// 4) Iterate through array of split strings, and if a given string
// 4. Iterate through array of split strings, and if a given string
// is upper case:
// if subsequent string is lower case:
// move last character of upper case string to beginning of
// lower case string
// if subsequent string is lower case:
// move last character of upper case string to beginning of
// lower case string
func Split(src string) (entries []string) {
// don't split invalid utf8
if !utf8.ValidString(src) {

View File

@ -4,6 +4,7 @@ Package report provides helper structs/methods/funcs for formatting output
To format output for an array of structs:
ExamplePodman:
headers := report.Headers(struct {
ID string
}{}, nil)
@ -24,6 +25,7 @@ ExamplePodman:
// fa85da03b40141899f3af3de6d27852b
ExampleUser:
headers := report.Headers(struct {
CID string
}{}, map[string]string{"CID":"ID"})
@ -55,19 +57,18 @@ Helpers:
Template Functions:
The following template functions are added to the template when parsed:
- join strings.Join, {{join .Field separator}}
- json encode field as JSON {{ json .Field }}
- lower strings.ToLower {{ .Field | lower }}
- pad add spaces as prefix and suffix {{ pad . 2 2 }}
- split strings.Split {{ .Field | split }}
- title strings.Title {{ .Field | title }}
- truncate limit field length {{ truncate . 10 }}
- upper strings.ToUpper {{ .Field | upper }}
- join strings.Join, {{join .Field separator}}
- json encode field as JSON {{ json .Field }}
- lower strings.ToLower {{ .Field | lower }}
- pad add spaces as prefix and suffix {{ pad . 2 2 }}
- split strings.Split {{ .Field | split }}
- title strings.Title {{ .Field | title }}
- truncate limit field length {{ truncate . 10 }}
- upper strings.ToUpper {{ .Field | upper }}
report.Funcs() may be used to add additional template functions.
Adding an existing function will replace that function for the life of that template.
Note: Your code should not ignore errors
*/
package report

View File

@ -51,11 +51,11 @@ type Formatter struct {
// Parse parses golang template returning a formatter
//
// - OriginPodman implies text is a template from podman code. Output will
// be filtered through a tabwriter.
// - OriginPodman implies text is a template from podman code. Output will
// be filtered through a tabwriter.
//
// - OriginUser implies text is a template from a user. If template includes
// keyword "table" output will be filtered through a tabwriter.
// - OriginUser implies text is a template from a user. If template includes
// keyword "table" output will be filtered through a tabwriter.
func (f *Formatter) Parse(origin Origin, text string) (*Formatter, error) {
f.Origin = origin

View File

@ -88,10 +88,11 @@ func truncateWithLength(source string, length int) string {
// Array of map is returned to support range templates
// Note: unexported fields can be supported by adding field to overrides
// Note: It is left to the developer to write out said headers
// Podman commands use the general rules of:
// 1) unchanged --format includes headers
// 2) --format '{{.ID}" # no headers
// 3) --format 'table {{.ID}}' # includes headers
//
// Podman commands use the general rules of:
// 1) unchanged --format includes headers
// 2) --format '{{.ID}" # no headers
// 3) --format 'table {{.ID}}' # includes headers
func Headers(object interface{}, overrides map[string]string) []map[string]string {
value := reflect.ValueOf(object)
if value.Kind() == reflect.Ptr {

View File

@ -5,9 +5,10 @@ import "regexp"
var jsonRegex = regexp.MustCompile(`^\s*(json|{{\s*json\s*(\.)?\s*}})\s*$`)
// JSONFormat test CLI --format string to be a JSON request
// if report.IsJSON(cmd.Flag("format").Value.String()) {
// ... process JSON and output
// }
//
// if report.IsJSON(cmd.Flag("format").Value.String()) {
// ... process JSON and output
// }
func IsJSON(s string) bool {
return jsonRegex.MatchString(s)
}

View File

@ -7,7 +7,6 @@ package main
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
@ -29,7 +28,7 @@ func main() {
panic(err)
}
if err := ioutil.WriteFile(f, b, 0o644); err != nil {
if err := os.WriteFile(f, b, 0o644); err != nil {
panic(err)
}
}

View File

@ -8,14 +8,14 @@
package seccomp
import (
"io/ioutil"
"os"
"testing"
"github.com/opencontainers/runtime-tools/generate"
)
func TestLoadProfile(t *testing.T) {
f, err := ioutil.ReadFile("fixtures/example.json")
f, err := os.ReadFile("fixtures/example.json")
if err != nil {
t.Fatal(err)
}
@ -29,7 +29,7 @@ func TestLoadProfile(t *testing.T) {
}
func TestLoadDefaultProfile(t *testing.T) {
f, err := ioutil.ReadFile("seccomp.json")
f, err := os.ReadFile("seccomp.json")
if err != nil {
t.Fatal(err)
}

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"os"
"path/filepath"
"sort"
@ -96,7 +96,7 @@ func (d *Driver) Store(id string, data []byte) error {
if err != nil {
return err
}
err = ioutil.WriteFile(d.secretsDataFilePath, marshalled, 0o600)
err = os.WriteFile(d.secretsDataFilePath, marshalled, 0o600)
if err != nil {
return err
}
@ -120,7 +120,7 @@ func (d *Driver) Delete(id string) error {
if err != nil {
return err
}
err = ioutil.WriteFile(d.secretsDataFilePath, marshalled, 0o600)
err = os.WriteFile(d.secretsDataFilePath, marshalled, 0o600)
if err != nil {
return err
}
@ -145,7 +145,7 @@ func (d *Driver) getAllData() (map[string][]byte, error) {
}
defer file.Close()
byteValue, err := ioutil.ReadAll(file)
byteValue, err := io.ReadAll(file)
if err != nil {
return nil, err
}

View File

@ -1,7 +1,6 @@
package filedriver
import (
"io/ioutil"
"os"
"testing"
@ -9,7 +8,7 @@ import (
)
func setup() (*Driver, error) {
tmppath, err := ioutil.TempDir("", "secretsdata")
tmppath, err := os.MkdirTemp("", "secretsdata")
if err != nil {
return nil, err
}

View File

@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
@ -60,7 +59,7 @@ func defaultDriverConfig() *driverConfig {
continue
}
cfg.Root = path
bs, err := ioutil.ReadFile(filepath.Join(path, ".gpg-id"))
bs, err := os.ReadFile(filepath.Join(path, ".gpg-id"))
if err != nil {
continue
}
@ -76,7 +75,7 @@ func (cfg *driverConfig) findGpgID() {
path := cfg.Root
for len(path) > 1 {
if _, err := os.Stat(filepath.Join(path, ".gpg-id")); err == nil {
bs, err := ioutil.ReadFile(filepath.Join(path, ".gpg-id"))
bs, err := os.ReadFile(filepath.Join(path, ".gpg-id"))
if err != nil {
continue
}
@ -106,7 +105,7 @@ func NewDriver(opts map[string]string) (*Driver, error) {
// List returns all secret IDs
func (d *Driver) List() (secrets []string, err error) {
files, err := ioutil.ReadDir(d.Root)
files, err := os.ReadDir(d.Root)
if err != nil {
return nil, fmt.Errorf("failed to read secret directory: %w", err)
}
@ -168,7 +167,7 @@ func (d *Driver) gpg(ctx context.Context, in io.Reader, out io.Writer, args ...s
cmd.Env = os.Environ()
cmd.Stdin = in
cmd.Stdout = out
cmd.Stderr = ioutil.Discard
cmd.Stderr = io.Discard
return cmd.Run()
}

View File

@ -3,7 +3,6 @@ package passdriver
import (
"context"
"fmt"
"io/ioutil"
"os"
"testing"
@ -13,9 +12,9 @@ import (
const gpgTestID = "testing@passdriver"
func setupDriver(t *testing.T) (driver *Driver, cleanup func()) {
base, err := ioutil.TempDir(os.TempDir(), "pass-test")
base, err := os.MkdirTemp(os.TempDir(), "pass-test")
require.NoError(t, err)
gpghomedir, err := ioutil.TempDir(os.TempDir(), "gpg-dir")
gpghomedir, err := os.MkdirTemp(os.TempDir(), "gpg-dir")
require.NoError(t, err)
driver, err = NewDriver(map[string]string{

View File

@ -56,6 +56,7 @@ var secretNameRegexp = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`)
// SecretsManager holds information on handling secrets
//
// revive does not like the name because the package is already called secrets
//
//nolint:revive
type SecretsManager struct {
// secretsPath is the path to the db file where secrets are stored
@ -90,6 +91,7 @@ type Secret struct {
// Currently only the unencrypted filedriver is implemented.
//
// revive does not like the name because the package is already called secrets
//
//nolint:revive
type SecretsDriver interface {
// List lists all secret ids in the secrets data store

View File

@ -2,7 +2,6 @@ package secrets
import (
"bytes"
"io/ioutil"
"os"
"testing"
@ -14,7 +13,7 @@ var drivertype = "file"
var opts map[string]string
func setup() (*SecretsManager, string, error) {
testpath, err := ioutil.TempDir("", "secretsdata")
testpath, err := os.MkdirTemp("", "secretsdata")
if err != nil {
return nil, "", err
}

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"os"
"strings"
"time"
@ -51,7 +51,7 @@ func (s *SecretsManager) loadDB() error {
return err
}
byteValue, err := ioutil.ReadAll(file)
byteValue, err := io.ReadAll(file)
if err != nil {
return err
}
@ -176,7 +176,7 @@ func (s *SecretsManager) store(entry *Secret) error {
if err != nil {
return err
}
err = ioutil.WriteFile(s.secretsDBPath, marshalled, 0o600)
err = os.WriteFile(s.secretsDBPath, marshalled, 0o600)
if err != nil {
return err
}
@ -202,7 +202,7 @@ func (s *SecretsManager) delete(nameOrID string) error {
if err != nil {
return err
}
err = ioutil.WriteFile(s.secretsDBPath, marshalled, 0o600)
err = os.WriteFile(s.secretsDBPath, marshalled, 0o600)
if err != nil {
return err
}

View File

@ -2,7 +2,6 @@ package shelldriver
import (
"fmt"
"io/ioutil"
"os"
"testing"
@ -10,7 +9,7 @@ import (
)
func setupDriver(t *testing.T) (driver *Driver, cleanup func()) {
base, err := ioutil.TempDir(os.TempDir(), "external-driver-test")
base, err := os.MkdirTemp(os.TempDir(), "external-driver-test")
require.NoError(t, err)
driver, err = NewDriver(map[string]string{
"delete": fmt.Sprintf("rm %s/${SECRET_ID}", base),

View File

@ -1,7 +1,6 @@
package ssh
import (
"io/ioutil"
"net/url"
"os"
"testing"
@ -65,7 +64,7 @@ func TestDial(t *testing.T) {
}
func TestScp(t *testing.T) {
f, err := ioutil.TempFile("", "")
f, err := os.CreateTemp("", "")
require.Nil(t, err)
defer os.Remove(f.Name())

View File

@ -3,7 +3,6 @@ package ssh
import (
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"os"
@ -106,7 +105,7 @@ func ReadPassword(prompt string) (pw []byte, err error) {
}
func PublicKey(path string, passphrase []byte) (ssh.Signer, error) {
key, err := ioutil.ReadFile(path)
key, err := os.ReadFile(path)
if err != nil {
return nil, err
}

View File

@ -4,7 +4,6 @@ import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
@ -42,7 +41,7 @@ func (s subscriptionData) saveTo(dir string) error {
if err := os.MkdirAll(filepath.Dir(path), s.dirMode); err != nil {
return err
}
return ioutil.WriteFile(path, s.data, s.mode)
return os.WriteFile(path, s.data, s.mode)
}
func readAll(root, prefix string, parentMode os.FileMode) ([]subscriptionData, error) {
@ -50,7 +49,7 @@ func readAll(root, prefix string, parentMode os.FileMode) ([]subscriptionData, e
data := []subscriptionData{}
files, err := ioutil.ReadDir(path)
files, err := os.ReadDir(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return data, nil
@ -90,7 +89,7 @@ func readFileOrDir(root, name string, parentMode os.FileMode) ([]subscriptionDat
}
return dirData, nil
}
bytes, err := ioutil.ReadFile(path)
bytes, err := os.ReadFile(path)
if err != nil {
return nil, err
}
@ -153,7 +152,9 @@ func getMountsMap(path string) (string, string, error) { //nolint
// containerRunDir: Private data for storing subscriptions on the host mounted in container.
// mountFile: Additional mount points required for the container.
// mountPoint: Container image mountpoint, or the directory from the hosts perspective that
// corresponds to `/` in the container.
//
// corresponds to `/` in the container.
//
// uid: to assign to content created for subscriptions
// gid: to assign to content created for subscriptions
// rootless: indicates whether container is running in rootless mode
@ -268,7 +269,7 @@ func addSubscriptionsFromMountsFile(filePath, mountLabel, containerRunDir string
if err := os.MkdirAll(filepath.Dir(ctrDirOrFileOnHost), s.dirMode); err != nil {
return nil, err
}
if err := ioutil.WriteFile(ctrDirOrFileOnHost, s.data, s.mode); err != nil {
if err := os.WriteFile(ctrDirOrFileOnHost, s.data, s.mode); err != nil {
return nil, fmt.Errorf("saving data to container filesystem: %w", err)
}
}
@ -305,10 +306,10 @@ func addSubscriptionsFromMountsFile(filePath, mountLabel, containerRunDir string
// (i.e: be FIPs compliant).
// It should only be called if /etc/system-fips exists on host.
// It primarily does two things:
// - creates /run/secrets/system-fips in the container root filesystem, and adds it to the `mounts` slice.
// - If `/etc/crypto-policies/back-ends` already exists inside of the container, it creates
// `/usr/share/crypto-policies/back-ends/FIPS` inside the container as well.
// It is done from within the container to ensure to avoid policy incompatibility between the container and host.
// - creates /run/secrets/system-fips in the container root filesystem, and adds it to the `mounts` slice.
// - If `/etc/crypto-policies/back-ends` already exists inside of the container, it creates
// `/usr/share/crypto-policies/back-ends/FIPS` inside the container as well.
// It is done from within the container to ensure to avoid policy incompatibility between the container and host.
func addFIPSModeSubscription(mounts *[]rspec.Mount, containerRunDir, mountPoint, mountLabel string, uid, gid int) error {
subscriptionsDir := "/run/secrets"
ctrDirOnHost := filepath.Join(containerRunDir, subscriptionsDir)

View File

@ -8,7 +8,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"runtime"
"testing"
@ -102,14 +101,14 @@ func makeManifest(layer, config []byte) v1.Manifest {
}
}
func makeImage(t *testing.T, arch, os string) (ref types.ImageReference, dir string, layer, config, manifest []byte) {
func makeImage(t *testing.T, arch, osStr string) (ref types.ImageReference, dir string, layer, config, manifest []byte) {
ctx := context.TODO()
dir, err := ioutil.TempDir("", "supplemented")
dir, err := os.MkdirTemp("", "supplemented")
assert.Nilf(t, err, "error creating temporary directory")
layerBytes := makeLayer(t)
cb := makeConfig(arch, os, layer)
cb := makeConfig(arch, osStr, layer)
configBytes, err := json.Marshal(&cb)
assert.Nilf(t, err, "error encoding image configuration")
m := makeManifest(layerBytes, configBytes)
@ -171,11 +170,11 @@ func TestSupplemented(t *testing.T) {
digest3, err := manifest.Digest(manifest3)
assert.Nilf(t, err, "error digesting manifest")
multidir, err := ioutil.TempDir("", "supplemented")
multidir, err := os.MkdirTemp("", "supplemented")
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(multidir)
destDir, err := ioutil.TempDir("", "supplemented")
destDir, err := os.MkdirTemp("", "supplemented")
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(destDir)
@ -351,7 +350,7 @@ func TestSupplemented(t *testing.T) {
}
rc, _, err := src.GetBlob(ctx, bi, none.NoCache)
assert.Nilf(t, err, "error reading blob 'dir:%s'[%s][%d]", multidir, test.label, i)
_, err = io.Copy(ioutil.Discard, rc)
_, err = io.Copy(io.Discard, rc)
assert.Nilf(t, err, "error discarding blob 'dir:%s'[%s][%d]", multidir, test.label, i)
rc.Close()
}

View File

@ -3,7 +3,6 @@ package sysinfo
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
@ -210,12 +209,12 @@ func checkCgroupCpusetInfo(cgMounts map[string]string, quiet bool) cgroupCpusetI
return cgroupCpusetInfo{}
}
cpus, err := ioutil.ReadFile(path.Join(mountPoint, "cpuset.cpus"))
cpus, err := os.ReadFile(path.Join(mountPoint, "cpuset.cpus"))
if err != nil {
return cgroupCpusetInfo{}
}
mems, err := ioutil.ReadFile(path.Join(mountPoint, "cpuset.mems"))
mems, err := os.ReadFile(path.Join(mountPoint, "cpuset.mems"))
if err != nil {
return cgroupCpusetInfo{}
}
@ -255,7 +254,7 @@ func cgroupEnabled(mountPoint, name string) bool {
}
func readProcBool(file string) bool {
val, err := ioutil.ReadFile(file)
val, err := os.ReadFile(file)
if err != nil {
return false
}

View File

@ -2,7 +2,6 @@ package sysinfo
import (
"errors"
"io/ioutil"
"os"
"path"
"path/filepath"
@ -13,19 +12,19 @@ import (
)
func TestReadProcBool(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "test-sysinfo-proc")
tmpDir, err := os.MkdirTemp("", "test-sysinfo-proc")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
procFile := filepath.Join(tmpDir, "read-proc-bool")
err = ioutil.WriteFile(procFile, []byte("1"), 0o644)
err = os.WriteFile(procFile, []byte("1"), 0o644)
require.NoError(t, err)
if !readProcBool(procFile) {
t.Fatal("expected proc bool to be true, got false")
}
if err := ioutil.WriteFile(procFile, []byte("0"), 0o644); err != nil {
if err := os.WriteFile(procFile, []byte("0"), 0o644); err != nil {
t.Fatal(err)
}
if readProcBool(procFile) {
@ -38,7 +37,7 @@ func TestReadProcBool(t *testing.T) {
}
func TestCgroupEnabled(t *testing.T) {
cgroupDir, err := ioutil.TempDir("", "cgroup-test")
cgroupDir, err := os.MkdirTemp("", "cgroup-test")
require.NoError(t, err)
defer os.RemoveAll(cgroupDir)
@ -46,7 +45,7 @@ func TestCgroupEnabled(t *testing.T) {
t.Fatal("cgroupEnabled should be false")
}
err = ioutil.WriteFile(path.Join(cgroupDir, "test"), []byte{}, 0o644)
err = os.WriteFile(path.Join(cgroupDir, "test"), []byte{}, 0o644)
require.NoError(t, err)
if !cgroupEnabled(cgroupDir, "test") {

View File

@ -103,8 +103,10 @@ func GetTimestamp(value string, reference time.Time) (string, error) {
// if the incoming nanosecond portion is longer or shorter than 9 digits it is
// converted to nanoseconds. The expectation is that the seconds and
// seconds will be used to create a time variable. For example:
// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0)
// if err == nil since := time.Unix(seconds, nanoseconds)
//
// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0)
// if err == nil since := time.Unix(seconds, nanoseconds)
//
// returns seconds as def(aultSeconds) if value == ""
func ParseTimestamps(value string, def int64) (secs, nanoSecs int64, err error) {
if value == "" {