Skip to content

Commit

Permalink
use new os.ReadDir instead of the deprecated ioutil.ReadDir
Browse files Browse the repository at this point in the history
Replace occurrences of the old and deprecated ioutil.ReadDir
with the new and more efficient os.ReadDir.

I also replaced some usages of the ioutil package along the way
as the whole module is deprecated as of Go 1.16.

Signed-off-by: Antonio Cardace <[email protected]>
  • Loading branch information
acardace committed Jun 4, 2021
1 parent 9f49ed7 commit 604d35f
Show file tree
Hide file tree
Showing 16 changed files with 45 additions and 49 deletions.
11 changes: 5 additions & 6 deletions pkg/cloud-init/cloud-init.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -196,7 +195,7 @@ func resolveConfigDriveSecrets(vmi *v1.VirtualMachineInstance, secretSourceDir s
}

baseDir := filepath.Join(secretSourceDir, secretName+"-access-cred")
files, err := ioutil.ReadDir(baseDir)
files, err := os.ReadDir(baseDir)
if err != nil {
return keys, err
}
Expand Down Expand Up @@ -268,7 +267,7 @@ func findCloudInitConfigDriveSecretVolume(volumes []v1.Volume) *v1.Volume {
func readFileFromDir(basedir, secretFile string) (string, error) {
userDataSecretFile := filepath.Join(basedir, secretFile)
// #nosec No risk for path injection: basedir & secretFile are static strings
userDataSecret, err := ioutil.ReadFile(userDataSecretFile)
userDataSecret, err := os.ReadFile(userDataSecretFile)
if err != nil {
log.Log.V(2).Reason(err).
Errorf("could not read secret data from source: %s", userDataSecretFile)
Expand Down Expand Up @@ -526,20 +525,20 @@ func GenerateLocalData(vmiName string, namespace string, data *CloudInitData) er
return err
}

err = ioutil.WriteFile(userFile, userData, 0600)
err = os.WriteFile(userFile, userData, 0600)
if err != nil {
return err
}
defer os.Remove(userFile)

err = ioutil.WriteFile(metaFile, metaData, 0600)
err = os.WriteFile(metaFile, metaData, 0600)
if err != nil {
return err
}
defer os.Remove(metaFile)

if len(networkData) > 0 {
err = ioutil.WriteFile(networkFile, networkData, 0600)
err = os.WriteFile(networkFile, networkData, 0600)
if err != nil {
return err
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
package config

import (
"io/ioutil"
"os"
"os/exec"
"path/filepath"
)
Expand Down Expand Up @@ -88,7 +88,7 @@ func setIsoCreationFunction(isoFunc isoCreationFunc) {

func getFilesLayout(dirPath string) ([]string, error) {
var filesPath []string
files, err := ioutil.ReadDir(dirPath)
files, err := os.ReadDir(dirPath)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/config/sysprep.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ package config

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"

Expand Down Expand Up @@ -50,7 +50,7 @@ func sysprepVolumeHasContents(sysprepVolume *v1.SysprepSource) bool {
const sysprepFileName = "autounattend.xml"

func validateAutounattendPresence(dirPath string) error {
files, err := ioutil.ReadDir(dirPath)
files, err := os.ReadDir(dirPath)
if err != nil {
return fmt.Errorf("Error validating %s presence: %w", sysprepFileName, err)
}
Expand Down
3 changes: 1 addition & 2 deletions pkg/container-disk/container-disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ package containerdisk

import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
Expand Down Expand Up @@ -193,7 +192,7 @@ func GetImage(root string, imagePath string) (string, error) {
}
}
} else {
files, err := ioutil.ReadDir(fallbackPath)
files, err := os.ReadDir(fallbackPath)
if err != nil {
return "", fmt.Errorf("Failed to check %s for disks: %v", fallbackPath, err)
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/hooks/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
Expand Down Expand Up @@ -89,7 +89,7 @@ func (m *Manager) collectSideCarSockets(numberOfRequestedHookSidecars uint, time
timeoutCh := time.After(timeout)

for uint(len(processedSockets)) < numberOfRequestedHookSidecars {
sockets, err := ioutil.ReadDir(m.hookSocketSharedDirectory)
sockets, err := os.ReadDir(m.hookSocketSharedDirectory)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/inotify-informer/inotify.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ package inotifyinformer

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
Expand Down Expand Up @@ -164,7 +164,7 @@ func (d *DirectoryListWatcher) List(options v1.ListOptions) (runtime.Object, err
return nil, err
}

files, err := ioutil.ReadDir(d.fileDir)
files, err := os.ReadDir(d.fileDir)
if err != nil {
d.Stop()
return nil, err
Expand Down
5 changes: 2 additions & 3 deletions pkg/virt-handler/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ package cache
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
Expand Down Expand Up @@ -107,7 +106,7 @@ func InitializeGhostRecordCache(directoryPath string) error {
return err
}

files, err := ioutil.ReadDir(ghostRecordDir)
files, err := os.ReadDir(ghostRecordDir)
if err != nil {
return err
}
Expand All @@ -118,7 +117,7 @@ func InitializeGhostRecordCache(directoryPath string) error {
}
recordPath := filepath.Join(ghostRecordDir, file.Name())
// #nosec no risk for path injection. Used only for testing and using static location
fileBytes, err := ioutil.ReadFile(recordPath)
fileBytes, err := os.ReadFile(recordPath)
if err != nil {
log.Log.Reason(err).Errorf("Unable to read ghost record file at path %s", recordPath)
continue
Expand Down
5 changes: 2 additions & 3 deletions pkg/virt-handler/cmd-client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ package cmdclient
import (
"fmt"
"io"
"io/ioutil"
"net"
"net/rpc"
"os"
Expand Down Expand Up @@ -130,7 +129,7 @@ func ListAllSockets() ([]string, error) {
return socketFiles, nil
}

files, err := ioutil.ReadDir(socketsDir)
files, err := os.ReadDir(socketsDir)
if err != nil {
return nil, err
}
Expand All @@ -147,7 +146,7 @@ func ListAllSockets() ([]string, error) {
}

podsDir := podsBaseDir
dirs, err := ioutil.ReadDir(podsDir)
dirs, err := os.ReadDir(podsDir)
if err != nil {
return nil, err
}
Expand Down
7 changes: 3 additions & 4 deletions pkg/virt-handler/container-disk/mount.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package container_disk
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -125,7 +124,7 @@ func (m *mounter) getMountTargetRecord(vmi *v1.VirtualMachineInstance) (*vmiMoun
if exists {
record := vmiMountTargetRecord{}
// #nosec No risk for path injection. Using static base and cleaned filename
bytes, err := ioutil.ReadFile(recordFile)
bytes, err := os.ReadFile(recordFile)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -172,7 +171,7 @@ func (m *mounter) setMountTargetRecord(vmi *v1.VirtualMachineInstance, record *v
return err
}

err = ioutil.WriteFile(recordFile, bytes, 0600)
err = os.WriteFile(recordFile, bytes, 0600)
if err != nil {
return err
}
Expand Down Expand Up @@ -278,7 +277,7 @@ func (m *mounter) Mount(vmi *v1.VirtualMachineInstance, verify bool) error {
func (m *mounter) legacyUnmount(vmi *v1.VirtualMachineInstance) error {
mountDir := containerdisk.GetLegacyVolumeMountDirOnHost(vmi)

files, err := ioutil.ReadDir(mountDir)
files, err := os.ReadDir(mountDir)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to list container disk mounts: %v", err)
}
Expand Down
3 changes: 1 addition & 2 deletions pkg/virt-handler/device-manager/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
Expand Down Expand Up @@ -75,7 +74,7 @@ func (h *DeviceUtilsHandler) GetDeviceNumaNode(basepath string, pciAddress strin
numaNode = -1
numaNodePath := filepath.Join(basepath, pciAddress, "numa_node")
// #nosec No risk for path injection. Reading static path of NUMA node info
numaNodeStr, err := ioutil.ReadFile(numaNodePath)
numaNodeStr, err := os.ReadFile(numaNodePath)
if err != nil {
log.DefaultLogger().Reason(err).Errorf("failed to read numa_node %s for device %s", numaNodePath, pciAddress)
return
Expand Down
7 changes: 3 additions & 4 deletions pkg/virt-handler/device-manager/mediated_device.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ package device_manager

import (
"fmt"
"io/ioutil"
"net"
"os"
"path"
Expand Down Expand Up @@ -302,9 +301,9 @@ func discoverPermittedHostMediatedDevices(supportedMdevsMap map[string]string) m
initHandler()

mdevsMap := make(map[string][]*MDEV)
files, err := ioutil.ReadDir(mdevBasePath)
files, err := os.ReadDir(mdevBasePath)
for _, info := range files {
if info.Mode()&os.ModeSymlink == 0 {
if info.Type()&os.ModeSymlink == 0 {
continue
}
mdevTypeName, err := getMdevTypeName(info.Name())
Expand Down Expand Up @@ -415,7 +414,7 @@ func (dpi *MediatedDevicePlugin) healthCheck() error {

func getMdevTypeName(mdevUUID string) (string, error) {
// #nosec No risk for path injection. Path is composed from static base "mdevBasePath" and static components
rawName, err := ioutil.ReadFile(filepath.Join(mdevBasePath, mdevUUID, "mdev_type/name"))
rawName, err := os.ReadFile(filepath.Join(mdevBasePath, mdevUUID, "mdev_type/name"))
if err != nil {
if os.IsNotExist(err) {
originFile, err := os.Readlink(filepath.Join(mdevBasePath, mdevUUID, "mdev_type"))
Expand Down
6 changes: 3 additions & 3 deletions pkg/virt-handler/node-labeller/cpu_plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ package nodelabeller
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"

Expand Down Expand Up @@ -130,7 +130,7 @@ func (n *NodeLabeller) loadHostCapabilities() error {

//loadCPUInfo load info about all cpu models
func (n *NodeLabeller) loadCPUInfo() error {
files, err := ioutil.ReadDir(filepath.Join(n.volumePath, "cpu_map"))
files, err := os.ReadDir(filepath.Join(n.volumePath, "cpu_map"))
if err != nil {
return err
}
Expand Down Expand Up @@ -189,7 +189,7 @@ func getPathCPUFeatures(volumePath string, name string) string {
//GetStructureFromXMLFile load data from xml file and unmarshals them into given structure
//Given structure has to be pointer
func (n *NodeLabeller) getStructureFromXMLFile(path string, structure interface{}) error {
rawFile, err := ioutil.ReadFile(path)
rawFile, err := os.ReadFile(path)
if err != nil {
return err
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
Expand Down Expand Up @@ -503,7 +503,7 @@ func (l *AccessCredentialManager) watchSecrets(vmi *v1.VirtualMachineInstance) {
}

secretDir := getSecretDir(secretName)
files, err := ioutil.ReadDir(secretDir)
files, err := os.ReadDir(secretDir)
if err != nil {
// if reading failed, reset reload to true so this change will be retried again
reload = true
Expand All @@ -529,7 +529,7 @@ func (l *AccessCredentialManager) watchSecrets(vmi *v1.VirtualMachineInstance) {
continue
}

pubKeyBytes, err := ioutil.ReadFile(filepath.Join(secretDir, file.Name()))
pubKeyBytes, err := os.ReadFile(filepath.Join(secretDir, file.Name()))
if err != nil {
// if reading failed, reset reload to true so this change will be retried again
reload = true
Expand All @@ -552,7 +552,7 @@ func (l *AccessCredentialManager) watchSecrets(vmi *v1.VirtualMachineInstance) {
continue
}

passwordBytes, err := ioutil.ReadFile(filepath.Join(secretDir, file.Name()))
passwordBytes, err := os.ReadFile(filepath.Join(secretDir, file.Name()))
if err != nil {
// if reading failed, reset reload to true so this change will be retried again
reload = true
Expand Down
12 changes: 8 additions & 4 deletions pkg/watchdog/watchdog.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ package watchdog

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -50,7 +49,7 @@ func WatchdogFileGetUID(baseDir string, vmi *v1.VirtualMachineInstance) string {

filePath := WatchdogFileFromNamespaceName(baseDir, namespace, domain)
// #nosec No risk for path injection. Using static path and base path of "virtShareDir"
b, err := ioutil.ReadFile(filePath)
b, err := os.ReadFile(filePath)
if err != nil {
return ""
}
Expand Down Expand Up @@ -150,13 +149,18 @@ func getExpiredDomains(timeoutSeconds int, virtShareDir string, timeNow time.Tim
return domains, nil
}

files, err := ioutil.ReadDir(fileDir)
files, err := os.ReadDir(fileDir)
if err != nil {
return nil, err
}
now := timeNow.UTC().Unix()
for _, file := range files {
if isExpired(now, timeoutSeconds, file) == true {
fileInfo, err := file.Info()
if err != nil {
return nil, err
}

if isExpired(now, timeoutSeconds, fileInfo) == true {
key := file.Name()
namespace, name, err := splitFileNamespaceName(key)
if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions tools/crd-validation-generator/validation-generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"sort"
"strings"
Expand All @@ -20,7 +19,7 @@ func main() {

flag.Parse()

files, err := ioutil.ReadDir(*dirname)
files, err := os.ReadDir(*dirname)
if err != nil {
panic(fmt.Errorf("Error occurred reading directory, %v", err))
}
Expand Down
Loading

0 comments on commit 604d35f

Please sign in to comment.