From fcf1e247b349f8ee92b2e3b9f684fcc5c3cd7b54 Mon Sep 17 00:00:00 2001 From: Milan Lenco Date: Fri, 3 Feb 2023 11:09:11 +0100 Subject: [PATCH] io/ioutil is deprecated As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. Since we are bombarded with Yetus complains about ioutil in all our PRs, it is worth getting rid of it. Signed-off-by: Milan Lenco --- pkg/edgeview/src/basics.go | 15 ++-- pkg/edgeview/src/copyfile.go | 7 +- pkg/edgeview/src/log-search.go | 17 +++-- pkg/edgeview/src/multiinst.go | 4 +- pkg/edgeview/src/network.go | 40 +++++------ pkg/edgeview/src/policy.go | 3 +- pkg/edgeview/src/pubsub.go | 6 +- pkg/edgeview/src/system.go | 71 +++++++++++-------- pkg/edgeview/src/websocket.go | 3 +- pkg/newlog/cmd/newlogd.go | 19 ++--- pkg/pillar/agentlog/eveversion.go | 6 +- pkg/pillar/cas/containerd.go | 13 ++-- pkg/pillar/cipher/handlecipher.go | 4 +- pkg/pillar/cmd/client/client.go | 11 ++- pkg/pillar/cmd/diag/diag.go | 5 +- pkg/pillar/cmd/domainmgr/domainmgr.go | 3 +- pkg/pillar/cmd/domainmgr/domainmgr_test.go | 3 +- pkg/pillar/cmd/domainmgr/processes.go | 6 +- pkg/pillar/cmd/downloader/dirs.go | 3 +- pkg/pillar/cmd/hardwaremodel/hardwaremodel.go | 6 +- pkg/pillar/cmd/ledmanager/ledmanager.go | 13 ++-- pkg/pillar/cmd/loguploader/loguploader.go | 7 +- pkg/pillar/cmd/nim/controllerdns.go | 9 ++- pkg/pillar/cmd/nim/nim.go | 4 +- pkg/pillar/cmd/nodeagent/nodeagent.go | 5 +- pkg/pillar/cmd/pbuf/pbuf.go | 3 +- pkg/pillar/cmd/tpmmgr/tpmmgr.go | 49 +++++++------ pkg/pillar/cmd/tpmmgr/tpmmgr_test.go | 11 ++- .../applydefaultconfigitem.go | 3 +- .../upgradeconverter/convertglobalconfig.go | 6 +- pkg/pillar/cmd/upgradeconverter/oldvolumes.go | 3 +- .../cmd/upgradeconverter/parseconfig.go | 4 +- .../upgradeconverter/renameverifiedfiles.go | 5 +- .../upgradeconverter/upgradeconverter_test.go | 11 ++- pkg/pillar/cmd/verifier/verifier.go | 3 +- pkg/pillar/cmd/volumemgr/artifact.go | 4 +- .../cmd/volumemgr/initialvolumestatus.go | 5 +- .../cmd/wstunnelclient/wstunnelclient.go | 4 +- pkg/pillar/cmd/zedagent/attesttask.go | 13 ++-- pkg/pillar/cmd/zedagent/handleconfig.go | 7 +- pkg/pillar/cmd/zedagent/handlemetrics.go | 6 +- pkg/pillar/cmd/zedagent/parseconfig.go | 3 +- pkg/pillar/cmd/zedagent/parseedgeview.go | 5 +- pkg/pillar/cmd/zedrouter/dnsmasq.go | 7 +- pkg/pillar/cmd/zedrouter/probe.go | 4 +- pkg/pillar/cmd/zedrouter/server.go | 9 ++- pkg/pillar/conntester/zedcloud.go | 4 +- pkg/pillar/containerd/containerd.go | 7 +- pkg/pillar/containerd/containerd_test.go | 5 +- pkg/pillar/containerd/logging.go | 3 +- pkg/pillar/containerd/oci.go | 9 ++- pkg/pillar/containerd/oci_test.go | 33 +++++---- pkg/pillar/diskmetrics/usage.go | 2 +- pkg/pillar/dpcmanager/wwan.go | 8 +-- .../dpcreconciler/genericitems/dhcpcd.go | 3 +- pkg/pillar/dpcreconciler/genericitems/ssh.go | 5 +- pkg/pillar/dpcreconciler/linuxitems/wlan.go | 3 +- pkg/pillar/evetpm/keys.go | 6 +- pkg/pillar/evetpm/tpm.go | 5 +- pkg/pillar/hardware/model.go | 7 +- pkg/pillar/hypervisor/kvm.go | 15 ++-- pkg/pillar/hypervisor/kvm_test.go | 23 +++--- pkg/pillar/hypervisor/null.go | 5 +- pkg/pillar/hypervisor/null_test.go | 3 +- pkg/pillar/hypervisor/xen.go | 5 +- pkg/pillar/pidfile/pidfile.go | 5 +- pkg/pillar/pubsub/checkmaxsize_test.go | 3 +- pkg/pillar/pubsub/large.go | 3 +- pkg/pillar/pubsub/large_test.go | 5 +- pkg/pillar/pubsub/restarted_test.go | 3 +- pkg/pillar/pubsub/socketdriver/publish.go | 9 ++- .../pubsub/socketdriver/recovery_test.go | 5 +- pkg/pillar/pubsub/socketdriver/subscribe.go | 11 ++- pkg/pillar/pubsub/unsubscribe_test.go | 3 +- pkg/pillar/sriov/sriov.go | 3 +- pkg/pillar/ssh/ssh.go | 3 +- .../testprograms/testverifier/testverifier.go | 25 ++++--- pkg/pillar/tgt/tgt.go | 15 ++-- pkg/pillar/types/assignableadapters.go | 3 +- pkg/pillar/types/ifnametopci.go | 5 +- pkg/pillar/types/memory.go | 4 +- pkg/pillar/utils/file/copy.go | 11 +-- pkg/pillar/utils/file/file.go | 3 +- pkg/pillar/utils/file/move.go | 10 +-- pkg/pillar/vault/key.go | 3 +- pkg/pillar/vault/vault.go | 3 +- pkg/pillar/watch/watchconfigstatus.go | 4 +- pkg/pillar/zboot/zboot.go | 7 +- pkg/pillar/zedbox/zedbox.go | 3 +- pkg/pillar/zedcloud/authen.go | 7 +- pkg/pillar/zedcloud/send.go | 3 +- pkg/pillar/zedcloud/tls.go | 13 ++-- pkg/pillar/zedcloud/wstunnelclient.go | 3 +- pkg/pillar/zfs/zfs.go | 5 +- 94 files changed, 368 insertions(+), 411 deletions(-) diff --git a/pkg/edgeview/src/basics.go b/pkg/edgeview/src/basics.go index 684a1498920..f7235f9d299 100644 --- a/pkg/edgeview/src/basics.go +++ b/pkg/edgeview/src/basics.go @@ -10,7 +10,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "os" "os/exec" @@ -201,7 +200,7 @@ func getAddrFromJWT(token string, isServer bool, instID int) (string, string, er var uuidStr string if isServer { - retbytes, err := ioutil.ReadFile("/persist/status/uuid") + retbytes, err := os.ReadFile("/persist/status/uuid") if err == nil { uuidStr = strings.TrimSuffix(string(retbytes), "\n") } @@ -322,7 +321,7 @@ func getBasics() { } if basics.uuid == "" { - retbytes, err := ioutil.ReadFile("/persist/status/uuid") + retbytes, err := os.ReadFile("/persist/status/uuid") if err == nil { basics.uuid = string(retbytes) } @@ -335,7 +334,7 @@ func getBasics() { } if basics.server == "" { - retbytes, err := ioutil.ReadFile("/config/server") + retbytes, err := os.ReadFile("/config/server") if err == nil { server := string(retbytes) basics.server = strings.TrimSuffix(server, "\n") @@ -361,14 +360,14 @@ func getBasics() { } if basics.release == "" { - retbytes, err := ioutil.ReadFile("/run/eve-release") + retbytes, err := os.ReadFile("/run/eve-release") if err == nil { basics.release = string(retbytes) } } if basics.partition == "" { - retbytes, err := ioutil.ReadFile("/run/eve.id") + retbytes, err := os.ReadFile("/run/eve.id") if err == nil { basics.partition = string(retbytes) } @@ -459,7 +458,7 @@ func runPipeCmds(prog1 string, arg1 []string, prog2 string, arg2 []string) (stri c1.Wait() }() c2.Wait() - out, err := ioutil.ReadAll(&b2) + out, err := io.ReadAll(&b2) if err != nil { reOpenPipe(true) return "", err @@ -517,7 +516,7 @@ func getFileTimeStr(t1 time.Time) string { } func listJSONFiles(path string) ([]string, error) { - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { return nil, err } diff --git a/pkg/edgeview/src/copyfile.go b/pkg/edgeview/src/copyfile.go index e220b53ceca..15277fb00c7 100644 --- a/pkg/edgeview/src/copyfile.go +++ b/pkg/edgeview/src/copyfile.go @@ -9,7 +9,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -323,13 +322,15 @@ func untarLogfile(downloadedFile string) { } logSaveDir := fileCopyDir + fileStr[0] fmt.Printf("\n log files saved at %s\n\n", logSaveDir) - files, err := ioutil.ReadDir(logSaveDir) + files, err := os.ReadDir(logSaveDir) if err != nil { fmt.Printf("read %s error, %v\n", logSaveDir, err) return } for _, f := range files { - fmt.Printf("file: %s, size %d\n", f.Name(), f.Size()) + if info, err := f.Info(); err == nil { + fmt.Printf("file: %s, size %d\n", f.Name(), info.Size()) + } } unpackLogfiles(fileCopyDir+fileStr[0], files) diff --git a/pkg/edgeview/src/log-search.go b/pkg/edgeview/src/log-search.go index b6323a0ac29..ea564664ffc 100644 --- a/pkg/edgeview/src/log-search.go +++ b/pkg/edgeview/src/log-search.go @@ -9,7 +9,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "sort" "strconv" @@ -110,7 +109,7 @@ func runLogSearch(cmds cmdOpt) { func walkLogDirs(t1, t2, now int64) []logfiletime { var getfiles []logfiletime - files, err := ioutil.ReadDir("/persist/newlog") + files, err := os.ReadDir("/persist/newlog") if err != nil { fmt.Printf("read /persist/newlog error %v\n", err) return getfiles @@ -130,13 +129,17 @@ func walkLogDirs(t1, t2, now int64) []logfiletime { if strings.Contains(dir.Name(), "appUpload") && querytype == "dev" { continue } - files1, err := ioutil.ReadDir("/persist/newlog/" + dir.Name()) + files1, err := os.ReadDir("/persist/newlog/" + dir.Name()) if err != nil { continue } var groupfiles []string for _, f := range files1 { - if f.ModTime().Unix() > t1 || f.ModTime().Unix() < t2 { + info, err := f.Info() + if err != nil { + continue + } + if info.ModTime().Unix() > t1 || info.ModTime().Unix() < t2 { continue } groupfiles = append(groupfiles, f.Name()) @@ -178,7 +181,7 @@ func walkLogDirs(t1, t2, now int64) []logfiletime { } func searchLiveLogs(pattern string, now int64, typeStr string, idx *int, logjson bool) { - files, err := ioutil.ReadDir("/persist/newlog/collect") + files, err := os.ReadDir("/persist/newlog/collect") if err != nil { fmt.Printf("read /persist/newlog/collect error %v\n", err) return @@ -194,7 +197,7 @@ func searchLiveLogs(pattern string, now int64, typeStr string, idx *int, logjson } func searchCurrentLogs(pattern, path, typeStr string, now int64, idx *int, logjson bool) { - contents, err := ioutil.ReadFile(path) + contents, err := os.ReadFile(path) if err != nil { fmt.Printf("read %s file error: %v\n", path, err) } @@ -301,7 +304,7 @@ func getTimeSec(timeline string, now int64) (int64, int64) { // uncompress the gzip log files and pack them into a single // json text file for device and each app logs -func unpackLogfiles(path string, files []os.FileInfo) { +func unpackLogfiles(path string, files []os.DirEntry) { sfnames := make(map[string][]string) for _, f := range files { if strings.HasPrefix(f.Name(), "dev.log.") { diff --git a/pkg/edgeview/src/multiinst.go b/pkg/edgeview/src/multiinst.go index a116fc8603d..10be5208ece 100644 --- a/pkg/edgeview/src/multiinst.go +++ b/pkg/edgeview/src/multiinst.go @@ -6,7 +6,7 @@ package main import ( "bytes" "encoding/json" - "io/ioutil" + "io" "net/http" "github.com/lf-edge/eve/pkg/pillar/pubsub" @@ -68,7 +68,7 @@ func evStatsHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "POST": var localStats evLocalStats - content, err := ioutil.ReadAll(r.Body) + content, err := io.ReadAll(r.Body) if err != nil { log.Errorf("stats server read error: %v", err) return diff --git a/pkg/edgeview/src/network.go b/pkg/edgeview/src/network.go index fff17c7b9ae..be9da5b9298 100644 --- a/pkg/edgeview/src/network.go +++ b/pkg/edgeview/src/network.go @@ -8,7 +8,7 @@ import ( "crypto/tls" "encoding/json" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/url" @@ -78,7 +78,7 @@ func runNetwork(netw string) { intfStat = getAllIntfs() } if opt == "ping" || opt == "trace" { - retbytes, err := ioutil.ReadFile("/config/server") + retbytes, err := os.ReadFile("/config/server") if err != nil { continue } @@ -161,7 +161,7 @@ func doAppNet(status, appstr string, isSummary bool) string { for _, item := range appStatus.UnderlayNetworkList { niUUID := item.Network.String() - retbytes, err := ioutil.ReadFile("/run/zedrouter/NetworkInstanceStatus/" + niUUID + ".json") + retbytes, err := os.ReadFile("/run/zedrouter/NetworkInstanceStatus/" + niUUID + ".json") if err != nil { continue } @@ -198,7 +198,7 @@ func doAppNet(status, appstr string, isSummary bool) string { if !strings.HasPrefix(l, "dhcp-hosts.") { continue } - retbytes, err := ioutil.ReadFile(l) + retbytes, err := os.ReadFile(l) if err == nil { if strings.Contains(string(retbytes), item.Mac) { fmt.Printf("%s\n", l) @@ -208,7 +208,7 @@ func doAppNet(status, appstr string, isSummary bool) string { } } - retbytes, err := ioutil.ReadFile("/run/zedrouter/dnsmasq.leases/" + item.Bridge) + retbytes, err := os.ReadFile("/run/zedrouter/dnsmasq.leases/" + item.Bridge) if err == nil { printColor("\n - dnsmasq lease files\n", colorGREEN) lines := strings.Split(string(retbytes), "\n") @@ -251,7 +251,7 @@ func doAppNet(status, appstr string, isSummary bool) string { } appUUIDStr := appStatus.UUIDandVersion.UUID.String() - retbytes, err := ioutil.ReadFile("/run/domainmgr/DomainStatus/" + appUUIDStr + ".json") + retbytes, err := os.ReadFile("/run/domainmgr/DomainStatus/" + appUUIDStr + ".json") if err == nil { printColor("\n - domain status:", colorGREEN) var domainS types.DomainStatus @@ -297,7 +297,7 @@ func getAppNetTable(ipaddr string, niStatus *types.NetworkInstanceStatus) { // getVifStats - in 'doAppNet' func getVifStats(vifStr string) { - retbytes, err := ioutil.ReadFile("/run/zedrouter/NetworkMetrics/global.json") + retbytes, err := os.ReadFile("/run/zedrouter/NetworkMetrics/global.json") if err != nil { return } @@ -401,7 +401,7 @@ func getPortCfg(opt string, isPrint bool) []string { if isPrint { fmt.Printf("\n - device port configure:\n") } - outbytes, err := ioutil.ReadFile("/run/zedagent/DevicePortConfig/zedagent.json") + outbytes, err := os.ReadFile("/run/zedagent/DevicePortConfig/zedagent.json") if err != nil { return mgmtIntf } @@ -447,7 +447,7 @@ func getAllAppIPs() []appIPvnc { var allAppIPs []appIPvnc for _, s := range jfiles { - retbytes1, err := ioutil.ReadFile(s) + retbytes1, err := os.ReadFile(s) if err != nil { continue } @@ -455,7 +455,7 @@ func getAllAppIPs() []appIPvnc { appIPs, appUUID := getAppIPs(status) var oneAppIPs []appIPvnc if len(appIPs) > 0 { - retbytes1, err := ioutil.ReadFile("/run/zedagent/AppInstanceConfig/" + appUUID.String() + ".json") + retbytes1, err := os.ReadFile("/run/zedagent/AppInstanceConfig/" + appUUID.String() + ".json") if err != nil { log.Errorf("getAllAppIPs: run appinstcfg %v", err) continue @@ -502,7 +502,7 @@ func getConnectivity() { fmt.Printf(" override.json:\n") } for _, f := range jfiles { - retbytes1, err := ioutil.ReadFile(f) + retbytes1, err := os.ReadFile(f) if err != nil { fmt.Printf("error: %v\n", err) } else { @@ -511,7 +511,7 @@ func getConnectivity() { } } - retbytes, err := ioutil.ReadFile("/persist/status/nim/DevicePortConfigList/global.json") + retbytes, err := os.ReadFile("/persist/status/nim/DevicePortConfigList/global.json") if err != nil { return } @@ -651,7 +651,7 @@ func getTables(rules string) []string { } func getMetricsMap(path string, stats *urlStats, isPrint bool) { - retbytes, err := ioutil.ReadFile(path + "global.json") + retbytes, err := os.ReadFile(path + "global.json") if err != nil { return } @@ -745,7 +745,7 @@ func showAppDetail(substring string) { return } for _, s := range jfiles { - retbytes1, err := ioutil.ReadFile(s) + retbytes1, err := os.ReadFile(s) if err != nil { continue } @@ -834,7 +834,7 @@ func getProxy(needPrint bool) (string, int, [][]byte) { proxyIP := "" proxyPort := 0 proxyPEM := [][]byte{} - retbytes, err := ioutil.ReadFile("/run/zedagent/DevicePortConfig/zedagent.json") + retbytes, err := os.ReadFile("/run/zedagent/DevicePortConfig/zedagent.json") if err != nil { return proxyIP, proxyPort, proxyPEM } @@ -886,7 +886,7 @@ func httpsclient(server string, ipaddr net.IP) { } defer resp.Body.Close() - htmlData, err := ioutil.ReadAll(resp.Body) + htmlData, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("%v\n", err) return @@ -1169,7 +1169,7 @@ func runWireless() { args := []string{"wlan0"} _, _ = runCmd(prog, args, true) - retbytes, err := ioutil.ReadFile("/run/wlan/wpa_supplicant.conf") + retbytes, err := os.ReadFile("/run/wlan/wpa_supplicant.conf") if err == nil { printTitle(" wpa_supplicant.conf:", colorCYAN, false) lines := strings.Split(string(retbytes), "\n") @@ -1189,7 +1189,7 @@ func runWireless() { } printTitle("\n wwan config", colorCYAN, false) - retbytes, err = ioutil.ReadFile("/run/wwan/config.json") + retbytes, err = os.ReadFile("/run/wwan/config.json") if err != nil { return } @@ -1201,7 +1201,7 @@ func runWireless() { fmt.Printf("%+v\n", wwancfg) printTitle("\n wwan metrics", colorCYAN, false) - retbytes, err = ioutil.ReadFile("/run/wwan/metrics.json") + retbytes, err = os.ReadFile("/run/wwan/metrics.json") if err == nil { prettyJSON, err := formatJSON(retbytes) if err == nil { @@ -1210,7 +1210,7 @@ func runWireless() { } printTitle("\n wwan status", colorCYAN, false) - retbytes, err = ioutil.ReadFile("/run/wwan/status.json") + retbytes, err = os.ReadFile("/run/wwan/status.json") if err == nil { prettyJSON, err := formatJSON(retbytes) if err == nil { diff --git a/pkg/edgeview/src/policy.go b/pkg/edgeview/src/policy.go index 4bbd98b8f5f..e57b327830f 100644 --- a/pkg/edgeview/src/policy.go +++ b/pkg/edgeview/src/policy.go @@ -7,7 +7,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "os" "strconv" "strings" @@ -34,7 +33,7 @@ var ( func initPolicy() error { _, err := os.Stat(types.EdgeviewCfgFile) if err == nil { - data, err := ioutil.ReadFile(types.EdgeviewCfgFile) + data, err := os.ReadFile(types.EdgeviewCfgFile) if err != nil { log.Errorf("can not read policy file: %v", err) return err diff --git a/pkg/edgeview/src/pubsub.go b/pkg/edgeview/src/pubsub.go index d36956ad0be..76c656a6b22 100644 --- a/pkg/edgeview/src/pubsub.go +++ b/pkg/edgeview/src/pubsub.go @@ -7,7 +7,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "os" "strings" ) @@ -53,7 +53,7 @@ func runPubsub(pubStr string) { printColor("\n pubsub in: "+sdir, colorBLUE) if subdir != "" { - files, err := ioutil.ReadDir(sdir + pubsubdir) + files, err := os.ReadDir(sdir + pubsubdir) if err != nil { continue } @@ -105,7 +105,7 @@ func pubsubSvs(startDir, pubsubDir, subDir string) { printpath = newdir + path } fmt.Printf(" service: %s\n", paths[len(paths)-1]) - retData, err := ioutil.ReadFile(f) + retData, err := os.ReadFile(f) if err != nil { continue } diff --git a/pkg/edgeview/src/system.go b/pkg/edgeview/src/system.go index 080820261b9..fb6e859e87b 100644 --- a/pkg/edgeview/src/system.go +++ b/pkg/edgeview/src/system.go @@ -15,7 +15,6 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -107,7 +106,7 @@ func runSystem(cmds cmdOpt, sysOpt string) { // getLogStats - in 'runSystem' func getLogStats() { - retData1, err := ioutil.ReadFile("/run/newlogd/NewlogMetrics/global.json") + retData1, err := os.ReadFile("/run/newlogd/NewlogMetrics/global.json") if err == nil { prettyJSON, err := formatJSON(retData1) if err == nil { @@ -126,7 +125,7 @@ func getLogStats() { printColor(" log file directories:\n", colorCYAN) for _, d := range logdirectory { - files, err := ioutil.ReadDir(d) + files, err := os.ReadDir(d) if err != nil { continue } @@ -315,7 +314,7 @@ func getVolume() { } for _, line := range jfiles { - retbytes, err := ioutil.ReadFile(line) + retbytes, err := os.ReadFile(line) if err != nil { continue } @@ -339,7 +338,7 @@ func getVolume() { if foundfile == "" { continue } - retbytes, err := ioutil.ReadFile(foundfile) + retbytes, err := os.ReadFile(foundfile) if err != nil { continue } @@ -348,7 +347,7 @@ func getVolume() { fmt.Printf(" name: %s, ID %s, RefCount: %d \n", vol1.DisplayName, vol1.VolumeID.String(), vol1.RefCount) printColor("\n content tree config: "+vol1.ContentID.String(), colorBLUE) - retbytes, err = ioutil.ReadFile("/run/zedagent/ContentTreeConfig/" + vol1.ContentID.String() + ".json") + retbytes, err = os.ReadFile("/run/zedagent/ContentTreeConfig/" + vol1.ContentID.String() + ".json") var cont types.ContentTreeConfig _ = json.Unmarshal(retbytes, &cont) fmt.Printf(" url: %s, format: %s, sha: %s\n", cont.RelativeURL, cont.Format, cont.ContentSha256) @@ -366,10 +365,10 @@ func getSysApp() { return } for _, s := range jfiles { - retbytes, _ := ioutil.ReadFile(s) + retbytes, _ := os.ReadFile(s) status := strings.TrimSuffix(string(retbytes), "\n") appuuid := doAppNet(status, "", true) - retbytes, err := ioutil.ReadFile("/run/domainmgr/DomainMetric/" + appuuid + ".json") + retbytes, err := os.ReadFile("/run/domainmgr/DomainMetric/" + appuuid + ".json") if err == nil { var metric types.DomainMetric _ = json.Unmarshal(retbytes, &metric) @@ -377,7 +376,7 @@ func getSysApp() { metric.CPUTotalNs, metric.UsedMemory, metric.AvailableMemory) } - retbytes, err = ioutil.ReadFile("/run/zedmanager/DomainConfig/" + appuuid + ".json") + retbytes, err = os.ReadFile("/run/zedmanager/DomainConfig/" + appuuid + ".json") if err != nil { continue } @@ -397,7 +396,7 @@ func getDataStore() { printColor(" - DataStore:", colorCYAN) for _, l := range jfiles { - retbytes1, err := ioutil.ReadFile(l) + retbytes1, err := os.ReadFile(l) if err != nil { continue } @@ -436,7 +435,7 @@ func getHW() { } func getLastReboot() { - files, err := ioutil.ReadDir("/persist/log") + files, err := os.ReadDir("/persist/log") if err != nil { fmt.Printf("failed to get to /persist/log\n") return @@ -444,7 +443,12 @@ func getLastReboot() { now := time.Now().Unix() for _, l := range files { - if now-l.ModTime().Unix() > 2592000 { // if files are older then 30 days + info, err := l.Info() + if err != nil { + fmt.Printf("failed to get file '%s' info: %v\n", l.Name(), err) + continue + } + if now-info.ModTime().Unix() > 2592000 { // if files are older then 30 days continue } var rebootFile string @@ -463,14 +467,19 @@ func getLastReboot() { } } - files, err = ioutil.ReadDir("/persist/newlog/panicStacks") + files, err = os.ReadDir("/persist/newlog/panicStacks") if err != nil { fmt.Printf("failed to get to /persist/newlog/panicStacks\n") return } for _, l := range files { - if now-l.ModTime().Unix() > 2592000 { // if files are older then 30 days + info, err := l.Info() + if err != nil { + fmt.Printf("failed to get file '%s' info: %v\n", l.Name(), err) + continue + } + if now-info.ModTime().Unix() > 2592000 { // if files are older then 30 days continue } if strings.Contains(l.Name(), "pillar-panic-stack.") { @@ -479,7 +488,7 @@ func getLastReboot() { if n < 1 { continue } - retbytes, err := ioutil.ReadFile("/persist/newlog/panicStacks/" + fields[n-1]) + retbytes, err := os.ReadFile("/persist/newlog/panicStacks/" + fields[n-1]) if err != nil { break } @@ -524,11 +533,13 @@ func runPCI() { func getCipher() { path := "/persist/certs" - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err == nil { printColor(" - /persist/certs:\n", colorCYAN) for _, f := range files { - fmt.Printf("file: %s, size %d\n", path+f.Name(), f.Size()) + if info, err := f.Info(); err == nil { + fmt.Printf("file: %s, size %d\n", path+f.Name(), info.Size()) + } } } @@ -540,7 +551,7 @@ func getCipher() { } printColor(" - Additional CA-Certificates:\n", colorCYAN) - files, err = ioutil.ReadDir("/etc/ssl/certs") + files, err = os.ReadDir("/etc/ssl/certs") if err == nil { for _, f := range files { if !strings.Contains(f.Name(), "/usr/local/share") { @@ -554,7 +565,7 @@ func getCipher() { if err == nil { printColor("\n - DataStore Config:", colorCYAN) for _, l := range jfiles { - retbytes1, err := ioutil.ReadFile(l) + retbytes1, err := os.ReadFile(l) if err != nil { continue } @@ -575,7 +586,7 @@ func getCipher() { if err == nil { printColor("\n - Domainmgr CipherBlock:", colorCYAN) for _, l := range jfiles { - retbytes1, err := ioutil.ReadFile(l) + retbytes1, err := os.ReadFile(l) if err != nil { continue } @@ -595,7 +606,7 @@ func getCipher() { if err == nil { printColor("\n - TPMmgr Edgenode Certs:", colorCYAN) for _, l := range jfiles { - retbytes1, err := ioutil.ReadFile(l) + retbytes1, err := os.ReadFile(l) if err != nil { continue } @@ -612,7 +623,7 @@ func getCipher() { if err == nil { printColor("\n - Cipher Context:", colorCYAN) for _, l := range jfiles { - retbytes1, err := ioutil.ReadFile(l) + retbytes1, err := os.ReadFile(l) if err != nil { continue } @@ -629,7 +640,7 @@ func getCipher() { if err == nil { printColor("\n - Controller Certs:", colorCYAN) for _, l := range jfiles { - retbytes1, err := ioutil.ReadFile(l) + retbytes1, err := os.ReadFile(l) if err != nil { continue } @@ -694,7 +705,7 @@ func runConfigItems() { func getConfigItems() types.ConfigItemValueMap { var cfgItem types.ConfigItemValueMap - retbytes, err := ioutil.ReadFile("/persist/status/zedagent/ConfigItemValueMap/global.json") + retbytes, err := os.ReadFile("/persist/status/zedagent/ConfigItemValueMap/global.json") if err != nil { return cfgItem } @@ -892,7 +903,7 @@ func runLs(opt string) { } if fi.IsDir() { - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { fmt.Printf("read dir failed. %v\n", err) return @@ -914,7 +925,9 @@ func runLs(opt string) { continue } } - dispAFile(file) + if info, err := file.Info(); err == nil { + dispAFile(info) + } } } else { dispAFile(fi) @@ -928,7 +941,7 @@ func readAFile(path string, extraline int) { return } - buf, err := ioutil.ReadAll(f) + buf, err := io.ReadAll(f) if err != nil { fmt.Printf("%v\n", err) return @@ -1227,7 +1240,7 @@ func gzipTechSuppFile(ifileName string) (string, error) { } reader := bufio.NewReader(ifile) - content, _ := ioutil.ReadAll(reader) + content, _ := io.ReadAll(reader) tmpfiles := strings.Split(ifileName, "-tmp-") if len(tmpfiles) != 2 { @@ -1272,7 +1285,7 @@ func getDevInfo() types.EdgeNodeInfo { jfiles, err := listJSONFiles("/persist/status/zedagent/EdgeNodeInfo") if err == nil { for _, l := range jfiles { - retbytes1, err := ioutil.ReadFile(l) + retbytes1, err := os.ReadFile(l) if err != nil { continue } diff --git a/pkg/edgeview/src/websocket.go b/pkg/edgeview/src/websocket.go index 5c9995aeca5..f4418eb127a 100644 --- a/pkg/edgeview/src/websocket.go +++ b/pkg/edgeview/src/websocket.go @@ -11,7 +11,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -150,7 +149,7 @@ func tlsDial(isServer bool, pIP string, pport int, src []net.IP, idx int) (*webs _, err0 := os.Stat(serverCertFile) if err0 == nil { caCertPool := x509.NewCertPool() - caCert, err := ioutil.ReadFile(serverCertFile) + caCert, err := os.ReadFile(serverCertFile) if err != nil { log.Errorf("can not read server cert file, %v", err) return nil, err diff --git a/pkg/newlog/cmd/newlogd.go b/pkg/newlog/cmd/newlogd.go index 0457ff60c6c..8824dfce41f 100644 --- a/pkg/newlog/cmd/newlogd.go +++ b/pkg/newlog/cmd/newlogd.go @@ -11,7 +11,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "net" "os" "path" @@ -686,7 +685,7 @@ func getSourceFromMsg(msg string) (string, string, string) { } func startTmpfile(dirname, filename string, isApp bool) *os.File { - tmpFile, err := ioutil.TempFile(dirname, filename) + tmpFile, err := os.CreateTemp(dirname, filename) if err != nil { log.Fatal(err) } @@ -1152,7 +1151,7 @@ func (w *countingWriter) Write(p []byte) (n int, err error) { func prepareGzipToOutTempFile(gzipDirName string, fHdr fileChanInfo, now time.Time) (*gzip.Writer, *countingWriter, *os.File) { // open output file - oTmpFile, err := ioutil.TempFile(gzipDirName, tmpPrefix) + oTmpFile, err := os.CreateTemp(gzipDirName, tmpPrefix) if err != nil { log.Fatal("prepareGzipToOutTempFile: create tmp file failed ", err) } @@ -1250,7 +1249,7 @@ func getAppuuidFromLogfile(tmplogfileInfo fileChanInfo) string { // at bootup, move the collected log files from previous life func findMovePrevLogFiles(movefile chan fileChanInfo) string { - files, err := ioutil.ReadDir(collectDir) + files, err := os.ReadDir(collectDir) if err != nil { log.Fatal("findMovePrevLogFiles: read dir ", err) } @@ -1271,8 +1270,9 @@ func findMovePrevLogFiles(movefile chan fileChanInfo) string { prevLogFile := collectDir + "/" + f.Name() fileinfo.tmpfile = prevLogFile fileinfo.isApp = isApp - fileinfo.inputSize = int32(f.Size()) - + if info, err := f.Info(); err == nil { + fileinfo.inputSize = int32(info.Size()) + } movefile <- fileinfo } } @@ -1379,7 +1379,7 @@ func getEveInfo() { } func cleanGzipTempfiles(dir string) { - gfiles, err := ioutil.ReadDir(dir) + gfiles, err := os.ReadDir(dir) if err == nil { for _, f := range gfiles { if !f.IsDir() && strings.HasPrefix(f.Name(), tmpPrefix) && len(f.Name()) > len(tmpPrefix) { @@ -1497,7 +1497,7 @@ func cleanPanicFileDir() { return } - files, err := ioutil.ReadDir(panicFileDir) + files, err := os.ReadDir(panicFileDir) if err != nil { log.Error(err) return @@ -1627,7 +1627,8 @@ func getSyslogMsg(loggerChan chan inputEntry) { } // listenDevLog() - substitute /dev/log with our AF_UNIX socket and open it -// for listening +// +// for listening func listenDevLog() (*net.UnixConn, error) { UnixPath := "/dev/log" os.Remove(UnixPath) diff --git a/pkg/pillar/agentlog/eveversion.go b/pkg/pillar/agentlog/eveversion.go index 6f662c8b36b..fefdd877e43 100644 --- a/pkg/pillar/agentlog/eveversion.go +++ b/pkg/pillar/agentlog/eveversion.go @@ -6,7 +6,7 @@ package agentlog import ( "fmt" "github.com/lf-edge/eve/pkg/pillar/types" - "io/ioutil" + "os" "strings" ) @@ -28,7 +28,7 @@ func EveVersion() string { } func readEveVersion(fileName string) string { - version, err := ioutil.ReadFile(fileName) + version, err := os.ReadFile(fileName) if err != nil { // Note: can be called from log hook hence no log calls. fmt.Printf("readEveVersion: Error reading EVE version from file %s", fileName) @@ -51,7 +51,7 @@ func EveCurrentPartition() string { } func readCurrentPartition(fileName string) string { - curpart, err := ioutil.ReadFile(fileName) + curpart, err := os.ReadFile(fileName) if err != nil { fmt.Printf("readCurrentPartition: Error reading current partition from file %s", fileName) diff --git a/pkg/pillar/cas/containerd.go b/pkg/pillar/cas/containerd.go index dda07fcab8f..a76a8b92e80 100644 --- a/pkg/pillar/cas/containerd.go +++ b/pkg/pillar/cas/containerd.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "runtime" @@ -282,7 +281,7 @@ func (c *containerdCAS) IngestBlob(ctx context.Context, blobs ...types.BlobStatu switch { case blob.IsIndex(): // read it in so we can process it - data, err := ioutil.ReadAll(contentReader) + data, err := io.ReadAll(contentReader) if err != nil { err = fmt.Errorf("IngestBlob(%s): could not read data at %s: %+s", blob.Sha256, blobFile, err.Error()) @@ -301,7 +300,7 @@ func (c *containerdCAS) IngestBlob(ctx context.Context, blobs ...types.BlobStatu indexHash = sha case blob.IsManifest(): // read it in so we can process it - data, err := ioutil.ReadAll(contentReader) + data, err := io.ReadAll(contentReader) if err != nil { err = fmt.Errorf("IngestBlob(%s): could not read data at %s: %+s", blob.Sha256, blobFile, err.Error()) @@ -690,7 +689,7 @@ func (c *containerdCAS) PrepareContainerRootDir(rootPath, reference, rootBlobSha logrus.Errorf(err.Error()) return err } - if err := ioutil.WriteFile(filepath.Join(rootPath, imageConfigFilename), []byte(clientImageSpecJSON), 0666); err != nil { + if err := os.WriteFile(filepath.Join(rootPath, imageConfigFilename), []byte(clientImageSpecJSON), 0666); err != nil { err = fmt.Errorf("PrepareContainerRootDir: Exception while writing image info to %v/%v. %v", rootPath, imageConfigFilename, err) logrus.Errorf(err.Error()) @@ -928,7 +927,7 @@ func getImageConfig(c *containerdCAS, reference string) (*ocispec.Image, error) logrus.Errorf(err.Error()) return nil, err } - blobData, err := ioutil.ReadAll(blobReader) + blobData, err := io.ReadAll(blobReader) if err != nil { err = fmt.Errorf("getImageConfig: could not read blobdata %s for reference %s: %+s", imageParentHash, reference, err.Error()) @@ -960,7 +959,7 @@ func getImageConfig(c *containerdCAS, reference string) (*ocispec.Image, error) return nil, err } //Step 3.1.3: Read the manifest data - blobData, err = ioutil.ReadAll(blobReader) + blobData, err = io.ReadAll(blobReader) if err != nil { err = fmt.Errorf("getImageConfig: could not parsr manifestBlob %s for reference %s: %+s", m.Digest.String(), reference, err.Error()) @@ -987,7 +986,7 @@ func getImageConfig(c *containerdCAS, reference string) (*ocispec.Image, error) logrus.Errorf(err.Error()) return nil, err } - blobData, err = ioutil.ReadAll(blobReader) + blobData, err = io.ReadAll(blobReader) if err != nil { err = fmt.Errorf("getImageConfig: could not read config blobdata %s for reference %s: %+s", configHash, reference, err.Error()) diff --git a/pkg/pillar/cipher/handlecipher.go b/pkg/pillar/cipher/handlecipher.go index 768e18601a3..6e079176460 100644 --- a/pkg/pillar/cipher/handlecipher.go +++ b/pkg/pillar/cipher/handlecipher.go @@ -11,7 +11,7 @@ import ( "encoding/pem" "errors" "fmt" - "io/ioutil" + "os" zconfig "github.com/lf-edge/eve/api/go/config" zcommon "github.com/lf-edge/eve/api/go/evecommon" @@ -82,7 +82,7 @@ func getDeviceCert(ctx *DecryptCipherContext, return []byte{}, errors.New(errStr) } // TBD:XXX as of now, only one - certBytes, err := ioutil.ReadFile(types.DeviceCertName) + certBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { errStr := fmt.Sprintf("getDeviceCert failed while reading device certificate: %v", err) diff --git a/pkg/pillar/cmd/client/client.go b/pkg/pillar/cmd/client/client.go index 29f956ea45a..a80772c6a0b 100644 --- a/pkg/pillar/cmd/client/client.go +++ b/pkg/pillar/cmd/client/client.go @@ -9,7 +9,6 @@ import ( "encoding/base64" "flag" "fmt" - "io/ioutil" "mime" "net/http" "os" @@ -221,7 +220,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar ticker := flextimer.NewExpTicker(time.Second, maxDelay, 0.0) - server, err := ioutil.ReadFile(types.ServerFileName) + server, err := os.ReadFile(types.ServerFileName) if err != nil { log.Fatal(err) } @@ -244,7 +243,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar log.Fatal(err) } // Load device text cert for upload - deviceCertPem, err = ioutil.ReadFile(types.DeviceCertName) + deviceCertPem, err = os.ReadFile(types.DeviceCertName) if err != nil { log.Fatal(err) } @@ -357,7 +356,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar case <-ticker.C: // Check in case /config/server changes while running - nserver, err := ioutil.ReadFile(types.ServerFileName) + nserver, err := os.ReadFile(types.ServerFileName) if err != nil { log.Error(err) } else if len(nserver) != 0 && string(server) != string(nserver) { @@ -439,7 +438,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar } if doWrite { b := []byte(fmt.Sprintf("%s\n", devUUID)) - err = ioutil.WriteFile(uuidFileName, b, 0644) + err = os.WriteFile(uuidFileName, b, 0644) if err != nil { log.Errorf("WriteFile %s failed: %v", uuidFileName, err) @@ -465,7 +464,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar // Write/update file for ledmanager // Note that no CRLF b := []byte(hardwaremodel) - err = ioutil.WriteFile(hardwaremodelFileName, b, 0644) + err = os.WriteFile(hardwaremodelFileName, b, 0644) if err != nil { log.Errorf("WriteFile %s failed: %v", hardwaremodelFileName, err) diff --git a/pkg/pillar/cmd/diag/diag.go b/pkg/pillar/cmd/diag/diag.go index 17dbea26b39..dd3b7c86173 100644 --- a/pkg/pillar/cmd/diag/diag.go +++ b/pkg/pillar/cmd/diag/diag.go @@ -12,7 +12,6 @@ import ( "encoding/base64" "flag" "fmt" - "io/ioutil" "net" "net/http" "os" @@ -164,7 +163,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar } log.Functionf("processed GlobalConfig") - server, err := ioutil.ReadFile(types.ServerFileName) + server, err := os.ReadFile(types.ServerFileName) if err != nil { log.Fatal(err) } @@ -340,7 +339,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar ctx.usingOnboardCert = false } // Check in case /config/server changes while running - nserver, err := ioutil.ReadFile(types.ServerFileName) + nserver, err := os.ReadFile(types.ServerFileName) if err != nil { log.Error(err) } else if len(nserver) != 0 && string(server) != string(nserver) { diff --git a/pkg/pillar/cmd/domainmgr/domainmgr.go b/pkg/pillar/cmd/domainmgr/domainmgr.go index 6b1213819e9..ed675ba095c 100644 --- a/pkg/pillar/cmd/domainmgr/domainmgr.go +++ b/pkg/pillar/cmd/domainmgr/domainmgr.go @@ -13,7 +13,6 @@ import ( "errors" "flag" "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -2658,7 +2657,7 @@ func createCloudInitISO(ctx *domainContext, fileName := cloudInitISOFileLocation(ctx, config.UUIDandVersion.UUID) - dir, err := ioutil.TempDir("", "cloud-init") + dir, err := os.MkdirTemp("", "cloud-init") if err != nil { log.Fatalf("createCloudInitISO failed %s", err) } diff --git a/pkg/pillar/cmd/domainmgr/domainmgr_test.go b/pkg/pillar/cmd/domainmgr/domainmgr_test.go index c39bdba9b0a..b491adc7854 100644 --- a/pkg/pillar/cmd/domainmgr/domainmgr_test.go +++ b/pkg/pillar/cmd/domainmgr/domainmgr_test.go @@ -11,7 +11,6 @@ package domainmgr import ( "encoding/base64" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -402,7 +401,7 @@ func TestHandleMimeMultipart(t *testing.T) { expectFail: true, }, } - dir, err := ioutil.TempDir("", "domainmgr_test") + dir, err := os.MkdirTemp("", "domainmgr_test") assert.Nil(t, err) if err != nil { return diff --git a/pkg/pillar/cmd/domainmgr/processes.go b/pkg/pillar/cmd/domainmgr/processes.go index 3ebe2fa9e2a..cd7632b1168 100644 --- a/pkg/pillar/cmd/domainmgr/processes.go +++ b/pkg/pillar/cmd/domainmgr/processes.go @@ -8,7 +8,7 @@ package domainmgr import ( "fmt" - "io/ioutil" + "os" "path" "strconv" "strings" @@ -99,7 +99,7 @@ func getWatchedPids() (map[int32]bool, error) { func getWatchedPidsFromDir(wDirname string, pDirname string) (map[int32]bool, error) { pids := make(map[int32]bool) - locations, err := ioutil.ReadDir(wDirname) + locations, err := os.ReadDir(wDirname) if err != nil { return pids, err } @@ -119,7 +119,7 @@ func getWatchedPidsFromDir(wDirname string, pDirname string) (map[int32]bool, er } pidFile := path.Join(pDirname, location.Name()) - pidBytes, err := ioutil.ReadFile(pidFile) + pidBytes, err := os.ReadFile(pidFile) if err != nil { log.Errorf("pidFile %s read error %v", pidFile, err) continue diff --git a/pkg/pillar/cmd/downloader/dirs.go b/pkg/pillar/cmd/downloader/dirs.go index bdee03c44c6..0c1f7f406ea 100644 --- a/pkg/pillar/cmd/downloader/dirs.go +++ b/pkg/pillar/cmd/downloader/dirs.go @@ -4,7 +4,6 @@ package downloader import ( - "io/ioutil" "os" "path" "path/filepath" @@ -38,7 +37,7 @@ func createDownloadDirs() { func clearInProgressDownloadDirs(ctx *downloaderContext) { // get files dirName := getPendingDir() - files, err := ioutil.ReadDir(dirName) + files, err := os.ReadDir(dirName) if err != nil { if os.IsNotExist(err) { return diff --git a/pkg/pillar/cmd/hardwaremodel/hardwaremodel.go b/pkg/pillar/cmd/hardwaremodel/hardwaremodel.go index 47bf20e773c..e35fe9544ad 100644 --- a/pkg/pillar/cmd/hardwaremodel/hardwaremodel.go +++ b/pkg/pillar/cmd/hardwaremodel/hardwaremodel.go @@ -6,7 +6,7 @@ package hardwaremodel import ( "flag" "fmt" - "io/ioutil" + "os" "github.com/lf-edge/eve/pkg/pillar/agentbase" "github.com/lf-edge/eve/pkg/pillar/base" @@ -57,14 +57,14 @@ func Run(_ *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, arg model := hardware.GetHardwareModelNoOverride(log) if *state.cPtr { b := []byte(fmt.Sprintf("%s", model)) - err := ioutil.WriteFile(outputFile, b, 0644) + err := os.WriteFile(outputFile, b, 0644) if err != nil { log.Fatal("WriteFile", err, outputFile) } } else { b := []byte(fmt.Sprintf("%s\n", model)) - err := ioutil.WriteFile(outputFile, b, 0644) + err := os.WriteFile(outputFile, b, 0644) if err != nil { log.Fatal("WriteFile", err, outputFile) } diff --git a/pkg/pillar/cmd/ledmanager/ledmanager.go b/pkg/pillar/cmd/ledmanager/ledmanager.go index 9ca8f37b8de..905db595080 100644 --- a/pkg/pillar/cmd/ledmanager/ledmanager.go +++ b/pkg/pillar/cmd/ledmanager/ledmanager.go @@ -14,7 +14,6 @@ package ledmanager import ( "flag" "fmt" - "io/ioutil" "os" "regexp" "strings" @@ -537,9 +536,9 @@ var diskRepeatCount int // Based on time for 200ms // InitDellCmd prepares "Cloud LED" on Dell IoT gateways by enabling GPIO endpoint func InitDellCmd(ledName string) { - err := ioutil.WriteFile("/sys/class/gpio/export", []byte("346"), 0644) + err := os.WriteFile("/sys/class/gpio/export", []byte("346"), 0644) if err == nil { - if err = ioutil.WriteFile("/sys/class/gpio/gpio346/direction", []byte("out"), 0644); err == nil { + if err = os.WriteFile("/sys/class/gpio/gpio346/direction", []byte("out"), 0644); err == nil { log.Functionf("Enabled Dell Cloud LED") return } @@ -645,7 +644,7 @@ func InitLedCmd(ledName string) { log.Functionf("InitLedCmd(%s)", ledName) triggerFilename := fmt.Sprintf("/sys/class/leds/%s/trigger", ledName) b := []byte("none") - err := ioutil.WriteFile(triggerFilename, b, 0644) + err := os.WriteFile(triggerFilename, b, 0644) if err != nil { log.Error(err, triggerFilename) } @@ -752,7 +751,7 @@ func doLedAction(ledName string, turnon bool) { } else { brightnessFilename = fmt.Sprintf("/sys/class/leds/%s/brightness", ledName) } - err := ioutil.WriteFile(brightnessFilename, b, 0644) + err := os.WriteFile(brightnessFilename, b, 0644) if err != nil { log.Trace(err, brightnessFilename) } @@ -769,7 +768,7 @@ func doLedBlink(ledName string) { } else { brightnessFilename = fmt.Sprintf("/sys/class/leds/%s/brightness", ledName) } - err := ioutil.WriteFile(brightnessFilename, b, 0644) + err := os.WriteFile(brightnessFilename, b, 0644) if err != nil { if printOnce { log.Error(err, brightnessFilename) @@ -781,7 +780,7 @@ func doLedBlink(ledName string) { } time.Sleep(200 * time.Millisecond) b = []byte("0") - err = ioutil.WriteFile(brightnessFilename, b, 0644) + err = os.WriteFile(brightnessFilename, b, 0644) if err != nil { log.Trace(err, brightnessFilename) } diff --git a/pkg/pillar/cmd/loguploader/loguploader.go b/pkg/pillar/cmd/loguploader/loguploader.go index 4dd0e562467..0ede5402c15 100644 --- a/pkg/pillar/cmd/loguploader/loguploader.go +++ b/pkg/pillar/cmd/loguploader/loguploader.go @@ -7,7 +7,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "math/rand" "net/http" "os" @@ -393,7 +392,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar func sendCtxInit(ctx *loguploaderContext) { //get server name - bytes, err := ioutil.ReadFile(types.ServerFileName) + bytes, err := os.ReadFile(types.ServerFileName) if err != nil { log.Fatalf("sendCtxInit: Failed to read ServerFileName(%s). Err: %s", types.ServerFileName, err) @@ -565,7 +564,7 @@ func doFetchSend(ctx *loguploaderContext, zipDir string, iter *int) int { log.Tracef("doFetchSend: can't stats %s", zipDir) return 0 } - files, err := ioutil.ReadDir(zipDir) + files, err := os.ReadDir(zipDir) if err != nil { log.Fatal("doFetchSend: read dir failed", err) } @@ -933,7 +932,7 @@ func handle4xxlogfile(ctx *loguploaderContext, fName string, isApp bool) { } dstFile = failSendDir + "/" + fName - files, err := ioutil.ReadDir(failSendDir) + files, err := os.ReadDir(failSendDir) if err != nil { log.Fatal("handle4xxlogfile: read dir ", err) } diff --git a/pkg/pillar/cmd/nim/controllerdns.go b/pkg/pillar/cmd/nim/controllerdns.go index ee0ac331814..62feb73df8b 100644 --- a/pkg/pillar/cmd/nim/controllerdns.go +++ b/pkg/pillar/cmd/nim/controllerdns.go @@ -6,7 +6,6 @@ package nim import ( "bytes" "fmt" - "io/ioutil" "net" "os" "time" @@ -31,9 +30,9 @@ func (n *nim) queryControllerDNS() { var ipaddrCached string if _, err := os.Stat(etcHostFileName); err == nil { - etchosts, err = ioutil.ReadFile(etcHostFileName) + etchosts, err = os.ReadFile(etcHostFileName) if err == nil { - controllerServer, _ = ioutil.ReadFile(types.ServerFileName) + controllerServer, _ = os.ReadFile(types.ServerFileName) controllerServer = bytes.TrimSuffix(controllerServer, []byte("\n")) if bytes.Contains(controllerServer, []byte(":")) { serverport := bytes.Split(controllerServer, []byte(":")) @@ -94,7 +93,7 @@ func (n *nim) controllerDNSCache(etchosts, controllerServer []byte, ipaddrCached } var nameServers []string - dnsServer, _ := ioutil.ReadFile(resolvFileName) + dnsServer, _ := os.ReadFile(resolvFileName) dnsRes := bytes.Split(dnsServer, []byte("\n")) for _, d := range dnsRes { d1 := bytes.Split(d, []byte("nameserver ")) @@ -158,7 +157,7 @@ func (n *nim) controllerDNSCache(etchosts, controllerServer []byte, ipaddrCached } ipaddrCached = "" - err := ioutil.WriteFile(tmpHostFileName, newhosts, 0644) + err := os.WriteFile(tmpHostFileName, newhosts, 0644) if err == nil { if err := os.Rename(tmpHostFileName, etcHostFileName); err != nil { n.Log.Errorf("can not rename /etc/hosts file %v", err) diff --git a/pkg/pillar/cmd/nim/nim.go b/pkg/pillar/cmd/nim/nim.go index 7fc0f90237d..d05cb00cddb 100644 --- a/pkg/pillar/cmd/nim/nim.go +++ b/pkg/pillar/cmd/nim/nim.go @@ -8,7 +8,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "os" "path" "path/filepath" "strings" @@ -825,7 +825,7 @@ func (n *nim) isDeviceOnboarded() bool { } func (n *nim) listPublishedDPCs(directory string) (dpcFilePaths []string) { - locations, err := ioutil.ReadDir(directory) + locations, err := os.ReadDir(directory) if err != nil { // Directory might not exist return diff --git a/pkg/pillar/cmd/nodeagent/nodeagent.go b/pkg/pillar/cmd/nodeagent/nodeagent.go index 8fedb8cb590..3530d955643 100644 --- a/pkg/pillar/cmd/nodeagent/nodeagent.go +++ b/pkg/pillar/cmd/nodeagent/nodeagent.go @@ -20,7 +20,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "os" "strconv" "strings" @@ -208,7 +207,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar fileToRead := "/persist/fault-injection/readfile" if _, err := os.Stat(fileToRead); err == nil { log.Warnf("Reading %s", fileToRead) - content, err := ioutil.ReadFile(fileToRead) + content, err := os.ReadFile(fileToRead) if err != nil { log.Error(err) } else { @@ -668,7 +667,7 @@ func incrementRestartCounter() uint32 { } } b := []byte(fmt.Sprintf("%d", restartCounter+1)) - err := ioutil.WriteFile(restartCounterFile, b, 0644) + err := os.WriteFile(restartCounterFile, b, 0644) if err != nil { log.Errorf("incrementRestartCounter write: %s", err) } diff --git a/pkg/pillar/cmd/pbuf/pbuf.go b/pkg/pillar/cmd/pbuf/pbuf.go index eb83b98798e..6921c32def2 100644 --- a/pkg/pillar/cmd/pbuf/pbuf.go +++ b/pkg/pillar/cmd/pbuf/pbuf.go @@ -5,7 +5,6 @@ package pbuf import ( "flag" - "io/ioutil" "os" zauth "github.com/lf-edge/eve/api/go/auth" @@ -44,7 +43,7 @@ func Run(_ *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, arg for _, arg := range state.args { log.Noticef("Handling %s type %s", arg, *state.typePtr) - buf, err := ioutil.ReadFile(arg) + buf, err := os.ReadFile(arg) if err != nil { log.Errorf("Read failed: %s", err) continue diff --git a/pkg/pillar/cmd/tpmmgr/tpmmgr.go b/pkg/pillar/cmd/tpmmgr/tpmmgr.go index aece36bc9f4..51a4213027b 100644 --- a/pkg/pillar/cmd/tpmmgr/tpmmgr.go +++ b/pkg/pillar/cmd/tpmmgr/tpmmgr.go @@ -17,7 +17,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "math/big" "os" "reflect" @@ -286,7 +285,7 @@ func writeDeviceCert() error { log.Tracef("NVUndefineSpace failed: %v", err) } - deviceCertBytes, err := ioutil.ReadFile(types.DeviceCertName) + deviceCertBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { log.Errorf("Failed to read device cert file: %v", err) return err @@ -332,7 +331,7 @@ func readDeviceCert() error { return err } - err = ioutil.WriteFile(types.DeviceCertName, deviceCertBytes, 0644) + err = os.WriteFile(types.DeviceCertName, deviceCertBytes, 0644) if err != nil { log.Errorf("Writing to device cert file failed: %v", err) return err @@ -351,7 +350,7 @@ func genCredentials() error { return err } //Write uuid to credentials file for faster access - err = ioutil.WriteFile(etpm.TpmCredentialsFileName, []byte(id.String()), 0644) + err = os.WriteFile(etpm.TpmCredentialsFileName, []byte(id.String()), 0644) if err != nil { log.Errorf("Writing to credentials file failed: %v", err) return err @@ -380,7 +379,7 @@ func writeCredentials() error { log.Tracef("NVUndefineSpace failed: %v", err) } - tpmCredentialBytes, err := ioutil.ReadFile(etpm.TpmCredentialsFileName) + tpmCredentialBytes, err := os.ReadFile(etpm.TpmCredentialsFileName) if err != nil { log.Errorf("Failed to read credentials file: %v", err) return err @@ -425,7 +424,7 @@ func readCredentials() error { return err } - err = ioutil.WriteFile(etpm.TpmCredentialsFileName, tpmCredentialBytes, 0644) + err = os.WriteFile(etpm.TpmCredentialsFileName, tpmCredentialBytes, 0644) if err != nil { log.Errorf("Writing to credentials file failed: %v", err) return err @@ -550,7 +549,7 @@ func testEcdhAES() error { } //read public key from ecdh certificate - certBytes, err := ioutil.ReadFile(ecdhCertFile) + certBytes, err := os.ReadFile(ecdhCertFile) if err != nil { fmt.Printf("error in reading ecdh cert file: %v", err) return err @@ -665,7 +664,7 @@ func createEkCertOnTpm() error { } defer rw.Close() - deviceCertBytes, err := ioutil.ReadFile(types.DeviceCertName) + deviceCertBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { return err } @@ -710,7 +709,7 @@ func createEkCertOnTpm() error { return fmt.Errorf("empty bytes after encoding to PEM") } - err = ioutil.WriteFile(EkCertFile, certBytes, 0644) + err = os.WriteFile(EkCertFile, certBytes, 0644) if err != nil { return err } @@ -800,7 +799,7 @@ func createDeviceCertOnTpm(pubkey crypto.PublicKey) error { return fmt.Errorf("empty bytes after encoding to PEM") } - err = ioutil.WriteFile(types.DeviceCertName, certBytes, 0644) + err = os.WriteFile(types.DeviceCertName, certBytes, 0644) if err != nil { return err } @@ -859,10 +858,10 @@ func createDeviceCertSoft() error { } func writeDeviceCertToFile(certBytes, keyBytes []byte) error { - if err := ioutil.WriteFile(types.DeviceKeyName, keyBytes, 0600); err != nil { + if err := os.WriteFile(types.DeviceKeyName, keyBytes, 0600); err != nil { return err } - return ioutil.WriteFile(types.DeviceCertName, certBytes, 0644) + return os.WriteFile(types.DeviceCertName, certBytes, 0644) } func createOtherKeys(override bool) error { @@ -919,7 +918,7 @@ func createQuoteCertOnTpm() error { } defer rw.Close() - deviceCertBytes, err := ioutil.ReadFile(types.DeviceCertName) + deviceCertBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { return err } @@ -964,7 +963,7 @@ func createQuoteCertOnTpm() error { return fmt.Errorf("empty bytes after encoding to PEM") } - err = ioutil.WriteFile(quoteCertFile, certBytes, 0644) + err = os.WriteFile(quoteCertFile, certBytes, 0644) if err != nil { return err } @@ -1014,7 +1013,7 @@ func createQuoteCertSoft() error { return fmt.Errorf("Failed to generate software ECDSA key pair: %v", err) } - deviceCertBytes, err := ioutil.ReadFile(types.DeviceCertName) + deviceCertBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { return fmt.Errorf("Failed to read device cert file: %v", err) } @@ -1068,17 +1067,17 @@ func createQuoteCertSoft() error { } func writeQuoteCertToFile(certBytes, keyBytes []byte) error { - if err := ioutil.WriteFile(quoteKeyFile, keyBytes, 0644); err != nil { + if err := os.WriteFile(quoteKeyFile, keyBytes, 0644); err != nil { return err } - if err := ioutil.WriteFile(quoteCertFile, certBytes, 0644); err != nil { + if err := os.WriteFile(quoteCertFile, certBytes, 0644); err != nil { return err } return nil } func getQuoteCert(certPath string) ([]byte, error) { - certBytes, err := ioutil.ReadFile(certPath) + certBytes, err := os.ReadFile(certPath) if err != nil { return nil, fmt.Errorf("Failed to read Quote certificate: %v", err) } @@ -1113,7 +1112,7 @@ func createEcdhCertOnTpm() error { } defer rw.Close() - deviceCertBytes, err := ioutil.ReadFile(types.DeviceCertName) + deviceCertBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { return err } @@ -1158,7 +1157,7 @@ func createEcdhCertOnTpm() error { return fmt.Errorf("empty bytes after encoding to PEM") } - err = ioutil.WriteFile(ecdhCertFile, certBytes, 0644) + err = os.WriteFile(ecdhCertFile, certBytes, 0644) if err != nil { return err } @@ -1208,7 +1207,7 @@ func createEcdhCertSoft() error { return fmt.Errorf("Failed to generate software ECDSA key pair: %v", err) } - deviceCertBytes, err := ioutil.ReadFile(types.DeviceCertName) + deviceCertBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { return fmt.Errorf("Failed to read device cert file: %v", err) } @@ -1262,10 +1261,10 @@ func createEcdhCertSoft() error { } func writeEcdhCertToFile(certBytes, keyBytes []byte) error { - if err := ioutil.WriteFile(etpm.EcdhKeyFile, keyBytes, 0644); err != nil { + if err := os.WriteFile(etpm.EcdhKeyFile, keyBytes, 0644); err != nil { return err } - return ioutil.WriteFile(ecdhCertFile, certBytes, 0644) + return os.WriteFile(ecdhCertFile, certBytes, 0644) } func publishEdgeNodeCert(ctx *tpmMgrContext, config types.EdgeNodeCert) { @@ -1277,7 +1276,7 @@ func publishEdgeNodeCert(ctx *tpmMgrContext, config types.EdgeNodeCert) { } func readEdgeNodeCert(certPath string) ([]byte, error) { - certBytes, err := ioutil.ReadFile(certPath) + certBytes, err := os.ReadFile(certPath) if err != nil { return nil, fmt.Errorf("readEdgeNodeCert failed with error: %v", err) } @@ -1365,7 +1364,7 @@ func saveTpmInfo(filename string) error { return err } - return ioutil.WriteFile(filename, []byte(info), 0600) + return os.WriteFile(filename, []byte(info), 0600) } // Create required directories, if not already created diff --git a/pkg/pillar/cmd/tpmmgr/tpmmgr_test.go b/pkg/pillar/cmd/tpmmgr/tpmmgr_test.go index 0e1bb046cfb..f61905b5df4 100644 --- a/pkg/pillar/cmd/tpmmgr/tpmmgr_test.go +++ b/pkg/pillar/cmd/tpmmgr/tpmmgr_test.go @@ -9,7 +9,6 @@ import ( "crypto/x509" "encoding/pem" "fmt" - "io/ioutil" "os" "reflect" "testing" @@ -113,13 +112,13 @@ func TestSoftEcdh(t *testing.T) { ecdhKeyFile := testEcdhKeyFile etpm.SetECDHPrivateKeyFile(ecdhKeyFile) - err := ioutil.WriteFile(ecdhCertFile, []byte(ecdhCertPem), 0644) + err := os.WriteFile(ecdhCertFile, []byte(ecdhCertPem), 0644) if err != nil { t.Errorf("Failed to create test certificate file: %v", err) } defer os.Remove(ecdhCertFile) - err = ioutil.WriteFile(ecdhKeyFile, []byte(ecdhKeyPem), 0644) + err = os.WriteFile(ecdhKeyFile, []byte(ecdhKeyPem), 0644) if err != nil { t.Errorf("Failed to create test key file: %v", err) } @@ -132,19 +131,19 @@ func TestSoftEcdh(t *testing.T) { // Test ECDH key exchange and a symmetric cipher based on ECDH, with software based keys func TestGetPrivateKeyFromFile(t *testing.T) { - err := ioutil.WriteFile(testEcdhKeyFile, []byte(ecdhKeyPem), 0644) + err := os.WriteFile(testEcdhKeyFile, []byte(ecdhKeyPem), 0644) if err != nil { t.Errorf("Failed to create test ecdh key file: %v", err) } defer os.Remove(testEcdhKeyFile) - err = ioutil.WriteFile(testDeviceKeyFile, []byte(deviceKeyPem), 0644) + err = os.WriteFile(testDeviceKeyFile, []byte(deviceKeyPem), 0644) if err != nil { t.Errorf("Failed to create test device key file: %v", err) } defer os.Remove(testDeviceKeyFile) - err = ioutil.WriteFile(testEcdhKeyLegacyFile, []byte(ecdhKeyPemLegacy), 0644) + err = os.WriteFile(testEcdhKeyLegacyFile, []byte(ecdhKeyPemLegacy), 0644) if err != nil { t.Errorf("Failed to create test ecdh legacy key file: %v", err) } diff --git a/pkg/pillar/cmd/upgradeconverter/applydefaultconfigitem.go b/pkg/pillar/cmd/upgradeconverter/applydefaultconfigitem.go index 38c7bba7476..36c6e0dacdf 100644 --- a/pkg/pillar/cmd/upgradeconverter/applydefaultconfigitem.go +++ b/pkg/pillar/cmd/upgradeconverter/applydefaultconfigitem.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "strings" @@ -192,7 +191,7 @@ func parseFile(filename string) (*types.ConfigItemValueMap, error) { return nil, fmt.Errorf("Failed to open file %s. Err: %s", filename, err) } - byteValue, err := ioutil.ReadAll(file) + byteValue, err := io.ReadAll(file) if err != nil { return nil, fmt.Errorf("***Failed to read file %s. Err: %s", filename, err) diff --git a/pkg/pillar/cmd/upgradeconverter/convertglobalconfig.go b/pkg/pillar/cmd/upgradeconverter/convertglobalconfig.go index 342e4ba1f37..753846973b4 100644 --- a/pkg/pillar/cmd/upgradeconverter/convertglobalconfig.go +++ b/pkg/pillar/cmd/upgradeconverter/convertglobalconfig.go @@ -5,7 +5,7 @@ package upgradeconverter import ( "encoding/json" - "io/ioutil" + "io" "os" "github.com/lf-edge/eve/pkg/pillar/types" @@ -97,7 +97,7 @@ func convertGlobalConfig(ctxPtr *ucContext) error { if err != nil { log.Fatalf("Failed to marshall new global config err %s", err) } - err = ioutil.WriteFile(newGlobalConfigFile, data, 0644) + err = os.WriteFile(newGlobalConfigFile, data, 0644) if err != nil { log.Fatalf("Failed to Save NewConfig. err %s", err) } @@ -114,7 +114,7 @@ func newConfigFromOld(globalConfigFile string) *types.ConfigItemValueMap { return types.DefaultConfigItemValueMap() } - byteValue, err := ioutil.ReadAll(file) + byteValue, err := io.ReadAll(file) if err != nil { log.Errorf("***Failed to read file %s. Err: %s", globalConfigFile, err) diff --git a/pkg/pillar/cmd/upgradeconverter/oldvolumes.go b/pkg/pillar/cmd/upgradeconverter/oldvolumes.go index 5cb3125254d..2ff2c18beb2 100644 --- a/pkg/pillar/cmd/upgradeconverter/oldvolumes.go +++ b/pkg/pillar/cmd/upgradeconverter/oldvolumes.go @@ -6,7 +6,6 @@ package upgradeconverter // Look for old VM and OCI volumes in /persist import ( - "io/ioutil" "os" "time" @@ -29,7 +28,7 @@ func scanDir(dirName string, isContainer bool) []oldVolume { log.Tracef("scanDir(%s)", dirName) var old []oldVolume - locations, err := ioutil.ReadDir(dirName) + locations, err := os.ReadDir(dirName) if err != nil { log.Errorf("scanDir: read directory '%s' failed: %v", dirName, err) diff --git a/pkg/pillar/cmd/upgradeconverter/parseconfig.go b/pkg/pillar/cmd/upgradeconverter/parseconfig.go index be7960e1518..e299e758d4e 100644 --- a/pkg/pillar/cmd/upgradeconverter/parseconfig.go +++ b/pkg/pillar/cmd/upgradeconverter/parseconfig.go @@ -7,7 +7,7 @@ package upgradeconverter // app instances and their drives and the volumes import ( - "io/ioutil" + "os" zauth "github.com/lf-edge/eve/api/go/auth" zconfig "github.com/lf-edge/eve/api/go/config" @@ -62,7 +62,7 @@ func parseConfig(checkpointFile string) (parseResult, error) { } func readSavedProtoMessage(filename string) (*zconfig.EdgeDevConfig, error) { - contents, err := ioutil.ReadFile(filename) + contents, err := os.ReadFile(filename) if err != nil { log.Errorln("readSavedProtoMessage", err) return nil, err diff --git a/pkg/pillar/cmd/upgradeconverter/renameverifiedfiles.go b/pkg/pillar/cmd/upgradeconverter/renameverifiedfiles.go index 3af0449ea44..69cc8ce9484 100644 --- a/pkg/pillar/cmd/upgradeconverter/renameverifiedfiles.go +++ b/pkg/pillar/cmd/upgradeconverter/renameverifiedfiles.go @@ -4,7 +4,6 @@ package upgradeconverter import ( - "io/ioutil" "os" "strings" @@ -46,7 +45,7 @@ func renameFiles(srcDir string, dstDir string, noFlag bool) { return } } - locations, err := ioutil.ReadDir(srcDir) + locations, err := os.ReadDir(srcDir) if err != nil { // Some old directories might not exist if !os.IsNotExist(err) { @@ -60,7 +59,7 @@ func renameFiles(srcDir string, dstDir string, noFlag bool) { dstFile := dstDir + "/" + sha // Find single file in srcDir innerDir := srcDir + "/" + location.Name() - files, err := ioutil.ReadDir(innerDir) + files, err := os.ReadDir(innerDir) if err != nil { log.Errorf("renameFiles: read directory '%s' failed: %v", innerDir, err) diff --git a/pkg/pillar/cmd/upgradeconverter/upgradeconverter_test.go b/pkg/pillar/cmd/upgradeconverter/upgradeconverter_test.go index 681dc66f07a..9bc56ae1c39 100644 --- a/pkg/pillar/cmd/upgradeconverter/upgradeconverter_test.go +++ b/pkg/pillar/cmd/upgradeconverter/upgradeconverter_test.go @@ -6,7 +6,6 @@ package upgradeconverter import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -73,7 +72,7 @@ func createJSONFile(config interface{}, file string) { log.Fatalf("createJSONFile: failed to marshall. err %s\n config: %+v", err, config) } - err = ioutil.WriteFile(file, configJSON, 0644) + err = os.WriteFile(file, configJSON, 0644) if err != nil { log.Fatalf("createJSONFile: failed to write file err %s", err) } @@ -82,7 +81,7 @@ func createJSONFile(config interface{}, file string) { func configItemValueMapFromFile(file string) *types.ConfigItemValueMap { var newConfig types.ConfigItemValueMap - cfgJSON, err := ioutil.ReadFile(file) + cfgJSON, err := os.ReadFile(file) if err != nil { log.Errorf("***configItemValueMapFromFile - Failed to read from %s. "+ "Err: %s", file, err) @@ -107,15 +106,15 @@ func ucContextForTest() *ucContext { //log.SetLevel(log.TraceLevel) var err error ctxPtr := &ucContext{} - ctxPtr.persistDir, err = ioutil.TempDir("", "PersistDir") + ctxPtr.persistDir, err = os.MkdirTemp("", "PersistDir") if err != nil { log.Fatalf("Failed to create persistDir. err: %s", err) } - ctxPtr.persistConfigDir, err = ioutil.TempDir("", "PersistConfigDir") + ctxPtr.persistConfigDir, err = os.MkdirTemp("", "PersistConfigDir") if err != nil { log.Fatalf("Failed to create persistConfigDir. err: %s", err) } - ctxPtr.persistStatusDir, err = ioutil.TempDir("", "PersistStatusDir") + ctxPtr.persistStatusDir, err = os.MkdirTemp("", "PersistStatusDir") if err != nil { log.Fatalf("Failed to create persistStatusDir. err: %s", err) } diff --git a/pkg/pillar/cmd/verifier/verifier.go b/pkg/pillar/cmd/verifier/verifier.go index 7396f2a1a2b..5a7dcdd137e 100644 --- a/pkg/pillar/cmd/verifier/verifier.go +++ b/pkg/pillar/cmd/verifier/verifier.go @@ -14,7 +14,6 @@ package verifier import ( "flag" "fmt" - "io/ioutil" "os" "path" "strings" @@ -629,7 +628,7 @@ func populateInitialStatusFromVerified(ctx *verifierContext, log.Functionf("populateInitialStatusFromVerified(%s, %s)", objDirname, parentDirname) - locations, err := ioutil.ReadDir(objDirname) + locations, err := os.ReadDir(objDirname) if err != nil { log.Fatal(err) diff --git a/pkg/pillar/cmd/volumemgr/artifact.go b/pkg/pillar/cmd/volumemgr/artifact.go index 1f1125a4230..307e3e25f1c 100644 --- a/pkg/pillar/cmd/volumemgr/artifact.go +++ b/pkg/pillar/cmd/volumemgr/artifact.go @@ -7,7 +7,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "strings" "time" @@ -113,7 +113,7 @@ func createManifestsForBareBlob(artifact *registry.Artifact) ([]*types.BlobStatu } defer reader.Close() - configBytes, err := ioutil.ReadAll(reader) + configBytes, err := io.ReadAll(reader) if err != nil { return nil, fmt.Errorf("getManifestsForBlob: Exception while reading config bytes: %s", err.Error()) diff --git a/pkg/pillar/cmd/volumemgr/initialvolumestatus.go b/pkg/pillar/cmd/volumemgr/initialvolumestatus.go index 11ce27a97fd..4585a7f56e2 100644 --- a/pkg/pillar/cmd/volumemgr/initialvolumestatus.go +++ b/pkg/pillar/cmd/volumemgr/initialvolumestatus.go @@ -9,7 +9,6 @@ package volumemgr import ( "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -27,7 +26,7 @@ import ( func populateExistingVolumesFormatObjects(_ *volumemgrContext, dirName string) { log.Functionf("populateExistingVolumesFormatObjects(%s)", dirName) - locations, err := ioutil.ReadDir(dirName) + locations, err := os.ReadDir(dirName) if err != nil { log.Errorf("populateExistingVolumesFormatObjects: read directory '%s' failed: %v", dirName, err) @@ -70,7 +69,7 @@ func populateExistingVolumesFormatDatasets(_ *volumemgrContext, dataset string) // Others have their delete handler. func gcObjects(ctx *volumemgrContext, dirName string) { log.Tracef("gcObjects(%s)", dirName) - locationsFileInfo, err := ioutil.ReadDir(dirName) + locationsFileInfo, err := os.ReadDir(dirName) if err != nil { log.Errorf("gcObjects: read directory '%s' failed: %v", dirName, err) diff --git a/pkg/pillar/cmd/wstunnelclient/wstunnelclient.go b/pkg/pillar/cmd/wstunnelclient/wstunnelclient.go index 61d86687449..e0c3518f0ef 100644 --- a/pkg/pillar/cmd/wstunnelclient/wstunnelclient.go +++ b/pkg/pillar/cmd/wstunnelclient/wstunnelclient.go @@ -6,7 +6,7 @@ package wstunnelclient import ( "flag" "fmt" - "io/ioutil" + "os" "strings" "time" @@ -146,7 +146,7 @@ func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, ar wscCtx.subAppInstanceConfig = subAppInstanceConfig //get server name - bytes, err := ioutil.ReadFile(types.ServerFileName) + bytes, err := os.ReadFile(types.ServerFileName) if err != nil { log.Fatal(err) } diff --git a/pkg/pillar/cmd/zedagent/attesttask.go b/pkg/pillar/cmd/zedagent/attesttask.go index 64a15345201..30f9ce237f2 100644 --- a/pkg/pillar/cmd/zedagent/attesttask.go +++ b/pkg/pillar/cmd/zedagent/attesttask.go @@ -9,6 +9,10 @@ import ( "bytes" "encoding/json" "fmt" + "os" + "reflect" + "strings" + eventlog "github.com/cshari-zededa/eve-tpm2-tools/eventlog" "github.com/lf-edge/eve/api/go/attest" "github.com/lf-edge/eve/pkg/pillar/agentlog" @@ -19,9 +23,6 @@ import ( "github.com/lf-edge/eve/pkg/pillar/vault" "github.com/lf-edge/eve/pkg/pillar/zedcloud" "google.golang.org/protobuf/proto" - "io/ioutil" - "reflect" - "strings" ) const ( @@ -211,7 +212,7 @@ func encodeVersions(quoteMsg *attest.ZAttestQuote) error { quoteMsg.Versions = make([]*attest.AttestVersionInfo, 0) eveVersion := new(attest.AttestVersionInfo) eveVersion.VersionType = attest.AttestVersionType_ATTEST_VERSION_TYPE_EVE - eveRelease, err := ioutil.ReadFile(types.EveVersionFile) + eveRelease, err := os.ReadFile(types.EveVersionFile) if err != nil { return err } @@ -860,7 +861,7 @@ func storeIntegrityToken(token []byte) { if len(token) == 0 { log.Warnf("[ATTEST] Received empty integrity token") } - err := ioutil.WriteFile(types.ITokenFile, token, 644) + err := os.WriteFile(types.ITokenFile, token, 644) if err != nil { log.Fatalf("Failed to store integrity token, err: %v", err) } @@ -868,7 +869,7 @@ func storeIntegrityToken(token []byte) { // helper to get IntegrityToken func readIntegrityToken() ([]byte, error) { - return ioutil.ReadFile(types.ITokenFile) + return os.ReadFile(types.ITokenFile) } // trigger restart event in attesation FSM diff --git a/pkg/pillar/cmd/zedagent/handleconfig.go b/pkg/pillar/cmd/zedagent/handleconfig.go index 2b0b12e69de..0f51418a406 100644 --- a/pkg/pillar/cmd/zedagent/handleconfig.go +++ b/pkg/pillar/cmd/zedagent/handleconfig.go @@ -6,7 +6,6 @@ package zedagent import ( "bytes" "fmt" - "io/ioutil" "net" "net/http" "net/url" @@ -222,7 +221,7 @@ func maybeLoadBootstrapConfig(getconfigCtx *getconfigContext) { } // Load file content. - contents, err := ioutil.ReadFile(types.BootstrapConfFileName) + contents, err := os.ReadFile(types.BootstrapConfFileName) if err != nil { log.Errorf("Failed to read bootstrap config: %v", err) indicateInvalidBootstrapConfig(getconfigCtx) @@ -307,7 +306,7 @@ func indicateInvalidBootstrapConfig(getconfigCtx *getconfigContext) { func initZedcloudContext(networkSendTimeout uint32, agentMetrics *zedcloud.AgentMetrics) *zedcloud.ZedCloudContext { // get the server name - bytes, err := ioutil.ReadFile(types.ServerFileName) + bytes, err := os.ReadFile(types.ServerFileName) if err != nil { log.Fatal(err) } @@ -756,7 +755,7 @@ func readSavedConfig(staleTime uint32, log.Errorln(errStr) return nil, info.ModTime(), nil } - contents, err := ioutil.ReadFile(filename) + contents, err := os.ReadFile(filename) if err != nil { log.Errorln("readSavedConfig", err) return nil, info.ModTime(), err diff --git a/pkg/pillar/cmd/zedagent/handlemetrics.go b/pkg/pillar/cmd/zedagent/handlemetrics.go index f8f7dcf3f9d..0138f0eb986 100644 --- a/pkg/pillar/cmd/zedagent/handlemetrics.go +++ b/pkg/pillar/cmd/zedagent/handlemetrics.go @@ -10,8 +10,8 @@ import ( "crypto/sha256" "encoding/hex" "fmt" - "io/ioutil" "net/http" + "os" "runtime" "strings" "time" @@ -941,7 +941,7 @@ func getSecurityInfo(ctx *zedagentContext) *info.SecurityInfo { si := new(info.SecurityInfo) // Deterime sha of the root CA cert used for object signing and // encryption - caCert1, err := ioutil.ReadFile(types.RootCertFileName) + caCert1, err := os.ReadFile(types.RootCertFileName) if err != nil { log.Error(err) } else { @@ -952,7 +952,7 @@ func getSecurityInfo(ctx *zedagentContext) *info.SecurityInfo { // Add the sha of the root CAs used for TLS // Note that we have the sha in a logical symlink so we // just read that file. - line, err := ioutil.ReadFile(types.V2TLSCertShaFilename) + line, err := os.ReadFile(types.V2TLSCertShaFilename) if err != nil { log.Error(err) } else { diff --git a/pkg/pillar/cmd/zedagent/parseconfig.go b/pkg/pillar/cmd/zedagent/parseconfig.go index 11b8558f303..84cd4dfcf01 100644 --- a/pkg/pillar/cmd/zedagent/parseconfig.go +++ b/pkg/pillar/cmd/zedagent/parseconfig.go @@ -10,7 +10,6 @@ import ( "errors" "fmt" "hash" - "io/ioutil" "net" "os" "sort" @@ -2546,7 +2545,7 @@ func readDeviceOpsCmdConfig(op types.DeviceOperation) *types.DeviceOpsCmd { } log.Tracef("readDeviceOpsCmdConfig - reading %s", fileName) - b, err := ioutil.ReadFile(fileName) + b, err := os.ReadFile(fileName) if err == nil { cfg := types.DeviceOpsCmd{} err = json.Unmarshal(b, &cfg) diff --git a/pkg/pillar/cmd/zedagent/parseedgeview.go b/pkg/pillar/cmd/zedagent/parseedgeview.go index fae25656c0d..86899db467f 100644 --- a/pkg/pillar/cmd/zedagent/parseedgeview.go +++ b/pkg/pillar/cmd/zedagent/parseedgeview.go @@ -8,7 +8,6 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "os" "strconv" "strings" @@ -89,7 +88,7 @@ func parseEvConfig(ctx *getconfigContext, config *zconfig.EdgeDevConfig) { } func verifyJWT(params []string) error { - certBytes, err := ioutil.ReadFile(types.ServerSigningCertFileName) + certBytes, err := os.ReadFile(types.ServerSigningCertFileName) if err != nil { log.Errorf("can not read signing cert: %v", err) return err @@ -167,7 +166,7 @@ func addEvFiles(evConfig types.EdgeviewConfig, params []string) error { } // create jwt token file - f, err := ioutil.TempFile(types.EdgeviewPath, "Edgeview-Config") + f, err := os.CreateTemp(types.EdgeviewPath, "Edgeview-Config") if err != nil { log.Errorf("file create failed: %v", err) return err diff --git a/pkg/pillar/cmd/zedrouter/dnsmasq.go b/pkg/pillar/cmd/zedrouter/dnsmasq.go index 335668a88ba..385d86fdc19 100644 --- a/pkg/pillar/cmd/zedrouter/dnsmasq.go +++ b/pkg/pillar/cmd/zedrouter/dnsmasq.go @@ -9,7 +9,6 @@ import ( "bufio" "fmt" "io" - "io/ioutil" "net" "os" "strconv" @@ -58,7 +57,7 @@ func dnsmasqLeasePath(bridgeName string) string { func dnsmasqBridgeNames() []string { var bridgeNames []string - locations, err := ioutil.ReadDir(dnsmasqLeaseDir) + locations, err := os.ReadDir(dnsmasqLeaseDir) if err != nil { log.Error(err) return bridgeNames @@ -392,7 +391,7 @@ func deleteDnsmasqConfiglet(bridgeName string) { } func RemoveDirContent(dir string) error { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return err } @@ -434,7 +433,7 @@ func stopDnsmasq(bridgeName string, printOnError bool, delConfiglet bool) { log.Functionf("stopDnsmasq(%s)\n", bridgeName) pidfile := fmt.Sprintf("/run/dnsmasq.%s.pid", bridgeName) - pidByte, err := ioutil.ReadFile(pidfile) + pidByte, err := os.ReadFile(pidfile) if err != nil { log.Errorf("stopDnsmasq: pid file read error %v\n", err) return diff --git a/pkg/pillar/cmd/zedrouter/probe.go b/pkg/pillar/cmd/zedrouter/probe.go index 7d410f5fd4e..d292816d495 100644 --- a/pkg/pillar/cmd/zedrouter/probe.go +++ b/pkg/pillar/cmd/zedrouter/probe.go @@ -9,8 +9,8 @@ import ( "context" "crypto/tls" "fmt" - "io/ioutil" "net" + "os" "strings" "sync" "time" @@ -596,7 +596,7 @@ func infoUpCount(info types.ProbeInfo) int { func getSystemURL() string { var remoteURL string if serverNameAndPort == "" { - server, err := ioutil.ReadFile(types.ServerFileName) + server, err := os.ReadFile(types.ServerFileName) if err == nil { serverNameAndPort = strings.TrimSpace(string(server)) } diff --git a/pkg/pillar/cmd/zedrouter/server.go b/pkg/pillar/cmd/zedrouter/server.go index 06cbc2fe7ec..d02dc295732 100644 --- a/pkg/pillar/cmd/zedrouter/server.go +++ b/pkg/pillar/cmd/zedrouter/server.go @@ -15,7 +15,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" stdlog "log" "net" "net/http" @@ -688,9 +687,9 @@ func (hdl appInstMetaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) return } - kubeConfig, err := ioutil.ReadAll(io.LimitReader(r.Body, AppInstMetadataResponseSizeLimitInBytes)) + kubeConfig, err := io.ReadAll(io.LimitReader(r.Body, AppInstMetadataResponseSizeLimitInBytes)) if err != nil { - msg := fmt.Sprintf("appInstMetaHandler: ioutil read failed: %v", err) + msg := fmt.Sprintf("appInstMetaHandler: ReadAll failed: %v", err) log.Errorf(msg) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return @@ -809,9 +808,9 @@ func (hdl signerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } // One larger to make sure we detect too large below. - payload, err := ioutil.ReadAll(io.LimitReader(r.Body, SignerMaxSize+1)) + payload, err := io.ReadAll(io.LimitReader(r.Body, SignerMaxSize+1)) if err != nil { - msg := fmt.Sprintf("signerHandler: ioutil read failed: %v", err) + msg := fmt.Sprintf("signerHandler: ReadAll failed: %v", err) log.Errorf(msg) http.Error(w, msg, http.StatusInternalServerError) return diff --git a/pkg/pillar/conntester/zedcloud.go b/pkg/pillar/conntester/zedcloud.go index 5fb9cbafb35..ac59985cda8 100644 --- a/pkg/pillar/conntester/zedcloud.go +++ b/pkg/pillar/conntester/zedcloud.go @@ -7,7 +7,7 @@ import ( "crypto/tls" "errors" "fmt" - "io/ioutil" + "os" "strings" "time" @@ -49,7 +49,7 @@ func (t *ZedcloudConnectivityTester) TestConnectivity(dns types.DeviceNetworkSta t.Log.Tracef("TestConnectivity() requiredSuccessCount %d, iteration %d", requiredSuccessCount, t.iteration) - server, err := ioutil.ReadFile(types.ServerFileName) + server, err := os.ReadFile(types.ServerFileName) if err != nil { t.Log.Fatal(err) } diff --git a/pkg/pillar/containerd/containerd.go b/pkg/pillar/containerd/containerd.go index eddb4cf87d8..640b48bc0be 100644 --- a/pkg/pillar/containerd/containerd.go +++ b/pkg/pillar/containerd/containerd.go @@ -9,7 +9,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math/rand" "os" "os/exec" @@ -775,7 +774,7 @@ func prepareProcess(pid int, VifList []types.VifInfo) error { func getSavedImageInfo(containerPath string) (ocispec.Image, error) { var image ocispec.Image - data, err := ioutil.ReadFile(filepath.Join(containerPath, imageConfigFilename)) + data, err := os.ReadFile(filepath.Join(containerPath, imageConfigFilename)) if err != nil { return image, err } @@ -840,7 +839,7 @@ func newServiceCtxWithLease(ctrdClient *containerd.Client, namespace string) (co func SaveSnapshotID(oldRootpath, newRootpath string) error { snapshotID := filepath.Base(oldRootpath) filename := filepath.Join(newRootpath, snapshotIDFile) - if err := ioutil.WriteFile(filename, []byte(snapshotID), 0644); err != nil { + if err := os.WriteFile(filename, []byte(snapshotID), 0644); err != nil { err = fmt.Errorf("SaveSnapshotID: Save snapshotID %s failed: %s", snapshotID, err) logrus.Error(err.Error()) return err @@ -856,7 +855,7 @@ func SaveSnapshotID(oldRootpath, newRootpath string) error { func GetSnapshotID(rootpath string) string { filename := filepath.Join(rootpath, snapshotIDFile) if _, err := os.Stat(filename); err == nil { - cont, err := ioutil.ReadFile(filename) + cont, err := os.ReadFile(filename) if err == nil { snapshotID := string(cont) logrus.Infof("GetSnapshotID read %s from %s", diff --git a/pkg/pillar/containerd/containerd_test.go b/pkg/pillar/containerd/containerd_test.go index 3d23978146c..8e8faf1c619 100644 --- a/pkg/pillar/containerd/containerd_test.go +++ b/pkg/pillar/containerd/containerd_test.go @@ -11,7 +11,6 @@ package containerd import ( "fmt" uuid "github.com/satori/go.uuid" - "io/ioutil" "os" "path" "path/filepath" @@ -66,7 +65,7 @@ func TestSaveSnapshotID(t *testing.T) { } else { snapshotIDFile := path.Join(tt.args.newRootpath, snapshotIDFile) expectedSnapshotID := snapshotID - snapshotID, err := ioutil.ReadFile(snapshotIDFile) + snapshotID, err := os.ReadFile(snapshotIDFile) if err != nil { t.Errorf("TestSaveSnapshotID: exception while reading %s file %s %v", snapshotIDFile, snapshotIDFile, err) @@ -89,7 +88,7 @@ func TestGetSnapshotID(t *testing.T) { } filename := filepath.Join(newTempRootPath, snapshotIDFile) - if err := ioutil.WriteFile(filename, []byte(snapshotID), 0644); err != nil { + if err := os.WriteFile(filename, []byte(snapshotID), 0644); err != nil { t.Errorf("TestGetSnapshotID: exception while saving %s: %s", filename, err.Error()) } type args struct { diff --git a/pkg/pillar/containerd/logging.go b/pkg/pillar/containerd/logging.go index 51a7e553fba..d7c69aa34ba 100644 --- a/pkg/pillar/containerd/logging.go +++ b/pkg/pillar/containerd/logging.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "os" "path/filepath" @@ -80,7 +79,7 @@ func (f *nullLog) Path(n string) string { // Open a log file for the named service. func (f *nullLog) Open(n string) (io.WriteCloser, error) { - return nullWriterCloser{ioutil.Discard}, nil + return nullWriterCloser{io.Discard}, nil } // Dump copies logs to the console. diff --git a/pkg/pillar/containerd/oci.go b/pkg/pillar/containerd/oci.go index 69e7847549f..3124cd0fb23 100644 --- a/pkg/pillar/containerd/oci.go +++ b/pkg/pillar/containerd/oci.go @@ -13,7 +13,6 @@ package containerd import ( "encoding/json" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -132,7 +131,7 @@ func (s *ociSpec) AddLoader(volume string) error { // inside UpdateFromVolume for the next boot on restart of app // create mountpoints manifest - if err := ioutil.WriteFile(filepath.Join(volumeRoot, "mountPoints"), + if err := os.WriteFile(filepath.Join(volumeRoot, "mountPoints"), []byte(s.Annotations[eveOCIMountPointsLabel]), 0644); err != nil { return err } @@ -152,7 +151,7 @@ func (s *ociSpec) AddLoader(volume string) error { envContent = envContent + fmt.Sprintf("export %s\n", e) } } - if err := ioutil.WriteFile(filepath.Join(volumeRoot, "environment"), []byte(envContent), 0644); err != nil { + if err := os.WriteFile(filepath.Join(volumeRoot, "environment"), []byte(envContent), 0644); err != nil { return err } @@ -163,13 +162,13 @@ func (s *ociSpec) AddLoader(volume string) error { execpathQuoted = append(execpathQuoted, fmt.Sprintf("\"%s\"", s)) } execpath := strings.Join(execpathQuoted, " ") - if err := ioutil.WriteFile(filepath.Join(volumeRoot, "cmdline"), + if err := os.WriteFile(filepath.Join(volumeRoot, "cmdline"), []byte(execpath), 0644); err != nil { return err } ug := fmt.Sprintf("%d %d", s.Process.User.UID, s.Process.User.GID) - if err := ioutil.WriteFile(filepath.Join(volumeRoot, "ug"), + if err := os.WriteFile(filepath.Join(volumeRoot, "ug"), []byte(ug), 0644); err != nil { return err } diff --git a/pkg/pillar/containerd/oci_test.go b/pkg/pillar/containerd/oci_test.go index 2dc8586ac19..4b26b8c8574 100644 --- a/pkg/pillar/containerd/oci_test.go +++ b/pkg/pillar/containerd/oci_test.go @@ -6,7 +6,6 @@ package containerd import ( "encoding/json" "fmt" - "io/ioutil" "log" "os" "path" @@ -363,21 +362,21 @@ func TestOciSpec(t *testing.T) { t.Errorf("failed to create default OCI spec %v", err) } - tmpfile, err := ioutil.TempFile("/tmp", "oci_spec*.json") + tmpfile, err := os.CreateTemp("/tmp", "oci_spec*.json") if err != nil { t.Errorf("failed to create tmpfile %v", err) } else { defer os.Remove(tmpfile.Name()) } - tmpdir, err := ioutil.TempDir("/tmp", "volume") + tmpdir, err := os.MkdirTemp("/tmp", "volume") if err != nil { t.Errorf("failed to create tmpdir %v", err) } else { defer os.RemoveAll(tmpdir) } - if ioutil.WriteFile(tmpdir+"/image-config.json", []byte(imageConfig), 0777) != nil { + if os.WriteFile(tmpdir+"/image-config.json", []byte(imageConfig), 0777) != nil { t.Errorf("failed to write to temp file %s", tmpdir+"/image-config.json") } @@ -475,7 +474,7 @@ func TestCreateMountPointExecEnvFiles(t *testing.T) { ] }` //create a temp dir to hold resulting files - dir, _ := ioutil.TempDir("/tmp", "podfiles") + dir, _ := os.MkdirTemp("/tmp", "podfiles") rootDir := path.Join(dir, "runx") rootFsDir := path.Join(rootDir, "rootfs") podPath := path.Join(dir, imageConfigFilename) @@ -488,11 +487,11 @@ func TestCreateMountPointExecEnvFiles(t *testing.T) { } // now create a fake pod file... - if err := ioutil.WriteFile(podPath, []byte(content), 0644); err != nil { + if err := os.WriteFile(podPath, []byte(content), 0644); err != nil { t.Errorf("failed to write to a pod file %v", err) } // ...and a loader runtime spec - if err := ioutil.WriteFile(rsPath, []byte(loaderRuntimeSpec), 0644); err != nil { + if err := os.WriteFile(rsPath, []byte(loaderRuntimeSpec), 0644); err != nil { t.Errorf("failed to write to a runtime spec file %v", err) } @@ -515,7 +514,7 @@ func TestCreateMountPointExecEnvFiles(t *testing.T) { execpathStr := "\"/bin/sh\"" cmdlineFile := path.Join(rootDir, "cmdline") - cmdline, err := ioutil.ReadFile(cmdlineFile) + cmdline, err := os.ReadFile(cmdlineFile) if err != nil { t.Errorf("createMountPointExecEnvFiles failed to create cmdline file %s %v", cmdlineFile, err) } @@ -525,7 +524,7 @@ func TestCreateMountPointExecEnvFiles(t *testing.T) { mountFile := path.Join(rootDir, "mountPoints") mountExpected := "" - mounts, err := ioutil.ReadFile(mountFile) + mounts, err := os.ReadFile(mountFile) if err != nil { t.Errorf("createMountPointExecEnvFiles failed to create mountPoints file %s %v", mountFile, err) } @@ -534,7 +533,7 @@ func TestCreateMountPointExecEnvFiles(t *testing.T) { } envFile := path.Join(rootDir, "environment") - envActual, err := ioutil.ReadFile(envFile) + envActual, err := os.ReadFile(envFile) // start with WORKDIR envExpect := "export WORKDIR=\"/data\"\nexport PATH=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n" if err != nil { @@ -632,11 +631,11 @@ func TestPrepareMount(t *testing.T) { } filename := filepath.Join(oldTempRootPath, imageConfigFilename) - if err := ioutil.WriteFile(filename, []byte(imageConfig), 0644); err != nil { + if err := os.WriteFile(filename, []byte(imageConfig), 0644); err != nil { t.Errorf("TestPrepareMount: exception while saving %s: %s", filename, err.Error()) } filename = filepath.Join(oldTempRootPath, "tmp", ociRuntimeSpecFilename) - if err := ioutil.WriteFile(filename, []byte(loaderRuntimeSpec), 0644); err != nil { + if err := os.WriteFile(filename, []byte(loaderRuntimeSpec), 0644); err != nil { t.Errorf("TestPrepareMount: exception while saving %s: %s", filename, err.Error()) } @@ -698,7 +697,7 @@ func TestPrepareMount(t *testing.T) { } else { cmdlineFile := path.Join(tt.args.containerPath, "cmdline") expectedCmdLine := "\"/start.sh\"" - cmdline, err := ioutil.ReadFile(cmdlineFile) + cmdline, err := os.ReadFile(cmdlineFile) if err != nil { t.Errorf("TestPrepareMount: exception while reading cmdline file %s %v", cmdlineFile, err) } @@ -709,7 +708,7 @@ func TestPrepareMount(t *testing.T) { mountFile := path.Join(tt.args.containerPath, "mountPoints") expectedMounts := "" - mounts, err := ioutil.ReadFile(mountFile) + mounts, err := os.ReadFile(mountFile) if err != nil { t.Errorf("TestPrepareMount: exception while reading mountPoints file %s %v", mountFile, err) } @@ -722,7 +721,7 @@ func TestPrepareMount(t *testing.T) { expectedEnv := "export WORKDIR=\"/\"\n" + "export PATH=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n" + "export ENV1=\"VAL1\"\n" - env, err := ioutil.ReadFile(envFile) + env, err := os.ReadFile(envFile) if err != nil { t.Errorf("TestPrepareMount: exception while reading environment file %s %v", envFile, err) } @@ -813,13 +812,13 @@ func TestAddLoader(t *testing.T) { spec1 := deepCopy(specTemplate).(ociSpec) spec2 := deepCopy(specTemplate).(ociSpec) - tmpdir, err := ioutil.TempDir("/tmp", "volume") + tmpdir, err := os.MkdirTemp("/tmp", "volume") if err != nil { log.Fatalf("failed to create tmpdir %v", err) } else { defer os.RemoveAll(tmpdir) } - if err := ioutil.WriteFile(filepath.Join(tmpdir, ociRuntimeSpecFilename), []byte(loaderRuntimeSpec), 0666); err != nil { + if err := os.WriteFile(filepath.Join(tmpdir, ociRuntimeSpecFilename), []byte(loaderRuntimeSpec), 0666); err != nil { log.Fatalf("failed to create tmpfile %v", err) } diff --git a/pkg/pillar/diskmetrics/usage.go b/pkg/pillar/diskmetrics/usage.go index 3b813545c6d..7ac8e085690 100644 --- a/pkg/pillar/diskmetrics/usage.go +++ b/pkg/pillar/diskmetrics/usage.go @@ -19,7 +19,7 @@ import ( ) // SizeFromDir performs a du -s equivalent operation. -// Didn't use ioutil.ReadDir and filepath.Walk because they sort (quick_sort) all files per directory +// Didn't use os.ReadDir and filepath.Walk because they sort (quick_sort) all files per directory // which is an unnecessary costly operation. func SizeFromDir(log *base.LogObject, dirname string) (uint64, error) { var totalUsed uint64 diff --git a/pkg/pillar/dpcmanager/wwan.go b/pkg/pillar/dpcmanager/wwan.go index 9ea0f65f747..50d88371280 100644 --- a/pkg/pillar/dpcmanager/wwan.go +++ b/pkg/pillar/dpcmanager/wwan.go @@ -7,7 +7,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "os" "reflect" "strings" @@ -75,7 +75,7 @@ func (w *wwanWatcher) LoadStatus() (status types.WwanStatus, err error) { return status, err } defer statusFile.Close() - statusBytes, err := ioutil.ReadAll(statusFile) + statusBytes, err := io.ReadAll(statusFile) if err != nil { w.Log.Errorf("Failed to read file %s: %v", devicenetwork.WwanStatusPath, err) return status, err @@ -95,7 +95,7 @@ func (w *wwanWatcher) LoadMetrics() (metrics types.WwanMetrics, err error) { return metrics, err } defer metricsFile.Close() - metricsBytes, err := ioutil.ReadAll(metricsFile) + metricsBytes, err := io.ReadAll(metricsFile) if err != nil { w.Log.Errorf("Failed to read file %s: %v", devicenetwork.WwanMetricsPath, err) return metrics, err @@ -116,7 +116,7 @@ func (w *wwanWatcher) LoadLocationInfo() (locInfo types.WwanLocationInfo, err er return locInfo, err } defer locFile.Close() - locBytes, err := ioutil.ReadAll(locFile) + locBytes, err := io.ReadAll(locFile) if err != nil { w.Log.Errorf("Failed to read file %s: %v", filepath, err) return locInfo, err diff --git a/pkg/pillar/dpcreconciler/genericitems/dhcpcd.go b/pkg/pillar/dpcreconciler/genericitems/dhcpcd.go index 04580ed45c3..f7fc975604f 100644 --- a/pkg/pillar/dpcreconciler/genericitems/dhcpcd.go +++ b/pkg/pillar/dpcreconciler/genericitems/dhcpcd.go @@ -7,7 +7,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "net" "os" "os/exec" @@ -396,7 +395,7 @@ func (c *DhcpcdConfigurator) statAndRead(filename string) (string, time.Time) { // File doesn't exist return "", time.Time{} } - content, err := ioutil.ReadFile(filename) + content, err := os.ReadFile(filename) if err != nil { return "", fi.ModTime() } diff --git a/pkg/pillar/dpcreconciler/genericitems/ssh.go b/pkg/pillar/dpcreconciler/genericitems/ssh.go index b4877b51282..ee8979e94fa 100644 --- a/pkg/pillar/dpcreconciler/genericitems/ssh.go +++ b/pkg/pillar/dpcreconciler/genericitems/ssh.go @@ -6,7 +6,6 @@ package genericitems import ( "context" "fmt" - "io/ioutil" "os" "github.com/lf-edge/eve/libs/depgraph" @@ -81,9 +80,9 @@ func (c *SSHAuthKeysConfigurator) Delete(ctx context.Context, item depgraph.Item func (c *SSHAuthKeysConfigurator) writeSSHAuthKeys(keys string) error { c.Log.Functionf("writeSSHAuthKeys: %s", keys) - tmpfile, err := ioutil.TempFile(runDir, "ak") + tmpfile, err := os.CreateTemp(runDir, "ak") if err != nil { - err = fmt.Errorf("ioutil.TempFile(%s) failed: %v", runDir, err) + err = fmt.Errorf("os.CreateTemp(%s) failed: %v", runDir, err) c.Log.Error(err) return err } diff --git a/pkg/pillar/dpcreconciler/linuxitems/wlan.go b/pkg/pillar/dpcreconciler/linuxitems/wlan.go index f986e77a3a7..cd351137e80 100644 --- a/pkg/pillar/dpcreconciler/linuxitems/wlan.go +++ b/pkg/pillar/dpcreconciler/linuxitems/wlan.go @@ -6,7 +6,6 @@ package linuxitems import ( "context" "fmt" - "io/ioutil" "os" "reflect" "strings" @@ -121,7 +120,7 @@ func (c *WlanConfigurator) installWifiConfig(config []WifiConfig) error { return err } } - tmpfile, err := ioutil.TempFile(devicenetwork.RunWlanDir, devicenetwork.WpaTempname) + tmpfile, err := os.CreateTemp(devicenetwork.RunWlanDir, devicenetwork.WpaTempname) if err != nil { err = fmt.Errorf("failed to create temporary file %s/%s: %v", devicenetwork.RunWlanDir, devicenetwork.WpaTempname, err) diff --git a/pkg/pillar/evetpm/keys.go b/pkg/pillar/evetpm/keys.go index ac968e5af13..55fdf22c0bb 100644 --- a/pkg/pillar/evetpm/keys.go +++ b/pkg/pillar/evetpm/keys.go @@ -10,7 +10,7 @@ import ( "encoding/pem" "errors" "fmt" - "io/ioutil" + "os" "strings" "github.com/lf-edge/eve/pkg/pillar/types" @@ -34,7 +34,7 @@ func SetECDHPrivateKeyFile(filename string) { // GetPrivateKeyFromFile reads a private key file on a device with no TPM func GetPrivateKeyFromFile(keyFile string) (*ecdsa.PrivateKey, error) { - keyPEMBlock, err := ioutil.ReadFile(keyFile) + keyPEMBlock, err := os.ReadFile(keyFile) if err != nil { return nil, err } @@ -77,7 +77,7 @@ func GetPrivateKeyFromFile(keyFile string) (*ecdsa.PrivateKey, error) { // GetPublicKeyFromCert gets public key from a X.509 cert func GetPublicKeyFromCert(certFile string) (crypto.PublicKey, error) { //read public key from ecdh certificate - certBytes, err := ioutil.ReadFile(certFile) + certBytes, err := os.ReadFile(certFile) if err != nil { fmt.Printf("error in reading ecdh cert file: %v", err) return nil, err diff --git a/pkg/pillar/evetpm/tpm.go b/pkg/pillar/evetpm/tpm.go index ded6f577770..45fd8e96d73 100644 --- a/pkg/pillar/evetpm/tpm.go +++ b/pkg/pillar/evetpm/tpm.go @@ -12,7 +12,6 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "math/big" "os" "unsafe" @@ -147,7 +146,7 @@ func (s TpmPrivateKey) Public() crypto.PublicKey { ecdsaPublicKey := myDevicePublicKey.(*ecdsa.PublicKey) return ecdsaPublicKey } - clientCertBytes, err := ioutil.ReadFile(types.DeviceCertName) + clientCertBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { return nil } @@ -169,7 +168,7 @@ func (s TpmPrivateKey) Sign(r io.Reader, digest []byte, opts crypto.SignerOpts) // ReadOwnerCrdl returns credential specific to this device func ReadOwnerCrdl() (string, error) { - tpmOwnerPasswdBytes, err := ioutil.ReadFile(TpmCredentialsFileName) + tpmOwnerPasswdBytes, err := os.ReadFile(TpmCredentialsFileName) if err != nil { return "", err } diff --git a/pkg/pillar/hardware/model.go b/pkg/pillar/hardware/model.go index 43b8fbab651..59b9ae188c0 100644 --- a/pkg/pillar/hardware/model.go +++ b/pkg/pillar/hardware/model.go @@ -18,7 +18,6 @@ package hardware import ( "bytes" - "io/ioutil" "os" "regexp" "strings" @@ -101,7 +100,7 @@ func getOverride(log *base.LogObject, filename string) string { if _, err := os.Stat(filename); err != nil { return "" } - contents, err := ioutil.ReadFile(filename) + contents, err := os.ReadFile(filename) if err != nil { log.Errorf("getOverride(%s) failed: %s\n", filename, err) return "" @@ -114,7 +113,7 @@ const controlChars = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x func GetCompatible(log *base.LogObject) string { compatible := "" if _, err := os.Stat(compatibleFile); err == nil { - contents, err := ioutil.ReadFile(compatibleFile) + contents, err := os.ReadFile(compatibleFile) if err != nil { log.Errorf("GetCompatible(%s) failed %s\n", compatibleFile, err) @@ -128,7 +127,7 @@ func GetCompatible(log *base.LogObject) string { func getCPUSerial(log *base.LogObject) string { serial := "" if _, err := os.Stat(cpuInfoFile); err == nil { - contents, err := ioutil.ReadFile(cpuInfoFile) + contents, err := os.ReadFile(cpuInfoFile) if err != nil { log.Errorf("getCPUSerial(%s) failed %s\n", cpuInfoFile, err) diff --git a/pkg/pillar/hypervisor/kvm.go b/pkg/pillar/hypervisor/kvm.go index 8d82ca3d647..f37fbd7c910 100644 --- a/pkg/pillar/hypervisor/kvm.go +++ b/pkg/pillar/hypervisor/kvm.go @@ -5,7 +5,6 @@ package hypervisor import ( "fmt" - "io/ioutil" "os" "runtime" "strings" @@ -655,7 +654,7 @@ func (ctx kvmContext) CreateDomConfig(domainName string, config types.DomainConf pciPTContext.Xvga = true } vendorFile := sysfsPciDevices + pa.pciLong + "/vendor" - if vendor, err := ioutil.ReadFile(vendorFile); err == nil { + if vendor, err := os.ReadFile(vendorFile); err == nil { // check for Intel vendor if strings.TrimSpace(strings.TrimSuffix(string(vendor), "\n")) == "0x8086" { if pciPTContext.Xvga { @@ -868,20 +867,20 @@ func (ctx kvmContext) PCIReserve(long string) error { } //map vfio-pci as the driver_override for the device - if err := ioutil.WriteFile(overrideFile, []byte("vfio-pci"), 0644); err != nil { + if err := os.WriteFile(overrideFile, []byte("vfio-pci"), 0644); err != nil { return logError("driver_override failure for PCI device %s: %v", long, err) } //Unbind the current driver, whatever it is, if there is one if _, err := os.Stat(unbindFile); err == nil { - if err := ioutil.WriteFile(unbindFile, []byte(long), 0644); err != nil { + if err := os.WriteFile(unbindFile, []byte(long), 0644); err != nil { return logError("unbind failure for PCI device %s: %v", long, err) } } - if err := ioutil.WriteFile(sysfsPciDriversProbe, []byte(long), 0644); err != nil { + if err := os.WriteFile(sysfsPciDriversProbe, []byte(long), 0644); err != nil { return logError("drivers_probe failure for PCI device %s: %v", long, err) } @@ -896,14 +895,14 @@ func (ctx kvmContext) PCIRelease(long string) error { unbindFile := sysfsPciDevices + long + "/driver/unbind" //Write Empty string, to clear driver_override for the device - if err := ioutil.WriteFile(overrideFile, []byte("\n"), 0644); err != nil { + if err := os.WriteFile(overrideFile, []byte("\n"), 0644); err != nil { logrus.Fatalf("driver_override failure for PCI device %s: %v", long, err) } //Unbind vfio-pci, if unbind file is present if _, err := os.Stat(unbindFile); err == nil { - if err := ioutil.WriteFile(unbindFile, []byte(long), 0644); err != nil { + if err := os.WriteFile(unbindFile, []byte(long), 0644); err != nil { logrus.Fatalf("unbind failure for PCI device %s: %v", long, err) } @@ -911,7 +910,7 @@ func (ctx kvmContext) PCIRelease(long string) error { //Write PCI DDDD:BB:DD.FF to /sys/bus/pci/drivers_probe, //as a best-effort to bring back original driver - if err := ioutil.WriteFile(sysfsPciDriversProbe, []byte(long), 0644); err != nil { + if err := os.WriteFile(sysfsPciDriversProbe, []byte(long), 0644); err != nil { logrus.Fatalf("drivers_probe failure for PCI device %s: %v", long, err) } diff --git a/pkg/pillar/hypervisor/kvm_test.go b/pkg/pillar/hypervisor/kvm_test.go index 09cd98d1ff2..8cdd669713a 100644 --- a/pkg/pillar/hypervisor/kvm_test.go +++ b/pkg/pillar/hypervisor/kvm_test.go @@ -1,7 +1,6 @@ package hypervisor import ( - "io/ioutil" "os" "os/exec" "testing" @@ -86,7 +85,7 @@ func TestCreateDomConfigOnlyCom1(t *testing.T) { }, }, } - conf, err := ioutil.TempFile("/tmp", "config") + conf, err := os.CreateTemp("/tmp", "config") if err != nil { t.Errorf("Can't create config file for a domain %v", err) } else { @@ -100,7 +99,7 @@ func TestCreateDomConfigOnlyCom1(t *testing.T) { } defer os.Truncate(conf.Name(), 0) - result, err := ioutil.ReadFile(conf.Name()) + result, err := os.ReadFile(conf.Name()) if err != nil { t.Errorf("reading conf file failed %v", err) } @@ -362,7 +361,7 @@ func TestCreateDomConfigOnlyCom1(t *testing.T) { } defer os.Truncate(conf.Name(), 0) - result, err := ioutil.ReadFile(conf.Name()) + result, err := os.ReadFile(conf.Name()) if err != nil { t.Errorf("reading conf file failed %v", err) } @@ -624,7 +623,7 @@ func TestCreateDomConfigOnlyCom1(t *testing.T) { } defer os.Truncate(conf.Name(), 0) - result, err := ioutil.ReadFile(conf.Name()) + result, err := os.ReadFile(conf.Name()) if err != nil { t.Errorf("reading conf file failed %v", err) } @@ -928,7 +927,7 @@ func TestCreateDomConfig(t *testing.T) { }, }, } - conf, err := ioutil.TempFile("/tmp", "config") + conf, err := os.CreateTemp("/tmp", "config") if err != nil { t.Errorf("Can't create config file for a domain %v", err) } else { @@ -942,7 +941,7 @@ func TestCreateDomConfig(t *testing.T) { } defer os.Truncate(conf.Name(), 0) - result, err := ioutil.ReadFile(conf.Name()) + result, err := os.ReadFile(conf.Name()) if err != nil { t.Errorf("reading conf file failed %v", err) } @@ -1237,7 +1236,7 @@ func TestCreateDomConfig(t *testing.T) { } defer os.Truncate(conf.Name(), 0) - result, err := ioutil.ReadFile(conf.Name()) + result, err := os.ReadFile(conf.Name()) if err != nil { t.Errorf("reading conf file failed %v", err) } @@ -1552,7 +1551,7 @@ func TestCreateDomConfig(t *testing.T) { config.IoAdapterList = config.IoAdapterList[:len(config.IoAdapterList)-1] defer os.Truncate(conf.Name(), 0) - result, err := ioutil.ReadFile(conf.Name()) + result, err := os.ReadFile(conf.Name()) if err != nil { t.Errorf("reading conf file failed %v", err) } @@ -1861,7 +1860,7 @@ func TestCreateDomConfig(t *testing.T) { } defer os.Truncate(conf.Name(), 0) - result, err := ioutil.ReadFile(conf.Name()) + result, err := os.ReadFile(conf.Name()) if err != nil { t.Errorf("reading conf file failed %v", err) } @@ -2162,13 +2161,13 @@ func TestCreateDom(t *testing.T) { } os.RemoveAll(kvmStateDir) - conf, err := ioutil.TempFile("/tmp/", "config") + conf, err := os.CreateTemp("/tmp/", "config") if err != nil { t.Errorf("Can't create config file for a domain %v", err) } else { defer os.Remove(conf.Name()) } - ioutil.WriteFile(conf.Name(), []byte(`# This file is automatically generated by domainmgr + os.WriteFile(conf.Name(), []byte(`# This file is automatically generated by domainmgr [msg] timestamp = "on" diff --git a/pkg/pillar/hypervisor/null.go b/pkg/pillar/hypervisor/null.go index bf43c4737f8..663507fd49a 100644 --- a/pkg/pillar/hypervisor/null.go +++ b/pkg/pillar/hypervisor/null.go @@ -6,7 +6,6 @@ package hypervisor import ( "fmt" "github.com/lf-edge/eve/pkg/pillar/types" - "io/ioutil" "os" "github.com/sirupsen/logrus" @@ -43,7 +42,7 @@ func newNull() Hypervisor { doms: map[string]*domState{}, domCounter: 0, PCI: map[string]bool{}} - if dir, err := ioutil.TempDir("", "null_domains"); err == nil { + if dir, err := os.MkdirTemp("", "null_domains"); err == nil { res.tempDir = dir } return res @@ -77,7 +76,7 @@ func (ctx nullContext) Create(domainName string, cfgFilename string, config *typ return 0, fmt.Errorf("Null Domain create failed to create domain descriptor %v\n", err) } - configContent, err := ioutil.ReadFile(cfgFilename) + configContent, err := os.ReadFile(cfgFilename) if err != nil { return 0, fmt.Errorf("Null Domain create failed to read cfgFilename %s %v\n", cfgFilename, err) } diff --git a/pkg/pillar/hypervisor/null_test.go b/pkg/pillar/hypervisor/null_test.go index bca588add51..9b572f748cf 100644 --- a/pkg/pillar/hypervisor/null_test.go +++ b/pkg/pillar/hypervisor/null_test.go @@ -6,7 +6,6 @@ package hypervisor import ( "fmt" "github.com/lf-edge/eve/pkg/pillar/types" - "io/ioutil" "os" "testing" ) @@ -49,7 +48,7 @@ func TestPCIAssignments(t *testing.T) { func TestBasicNullDomainWorkflow(t *testing.T) { // t.Logf("Running test case") - conf, err := ioutil.TempFile("", "config") + conf, err := os.CreateTemp("", "config") if err != nil { t.Errorf("Can't create config file for a domain %v", err) } else { diff --git a/pkg/pillar/hypervisor/xen.go b/pkg/pillar/hypervisor/xen.go index bb529e28a2f..78be16b5a0a 100644 --- a/pkg/pillar/hypervisor/xen.go +++ b/pkg/pillar/hypervisor/xen.go @@ -6,7 +6,6 @@ package hypervisor import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -544,7 +543,7 @@ func (ctx xenContext) Info(domainName string) (int, types.SwState, error) { // first we ask for the task status effectiveDomainID, effectiveDomainState, err := ctx.ctrdContext.Info(domainName) if err != nil || effectiveDomainState != types.RUNNING { - status, err := ioutil.ReadFile(ctx.getTaskStateFilePath(domainName)) + status, err := os.ReadFile(ctx.getTaskStateFilePath(domainName)) if err != nil { status = []byte("file not read") } @@ -555,7 +554,7 @@ func (ctx xenContext) Info(domainName string) (int, types.SwState, error) { } // if task is alive, we augment task status with finer grained details from xl info - status, err := ioutil.ReadFile(ctx.getTaskStateFilePath(domainName)) + status, err := os.ReadFile(ctx.getTaskStateFilePath(domainName)) if err != nil { logrus.Errorf("couldn't read task status file: %v", err) status = []byte("running") // assigning default state as we weren't able to read status file diff --git a/pkg/pillar/pidfile/pidfile.go b/pkg/pillar/pidfile/pidfile.go index 78212be3ad6..8e20c82cd2e 100644 --- a/pkg/pillar/pidfile/pidfile.go +++ b/pkg/pillar/pidfile/pidfile.go @@ -7,7 +7,6 @@ package pidfile import ( "fmt" - "io/ioutil" "os" "strconv" "syscall" @@ -23,7 +22,7 @@ func writeMyPid(filename string) error { pid := os.Getpid() pidStr := fmt.Sprintf("%d", pid) b := []byte(pidStr) - return ioutil.WriteFile(filename, b, 0644) + return os.WriteFile(filename, b, 0644) } // CheckProcessExists returns true if agent process is running @@ -35,7 +34,7 @@ func CheckProcessExists(log *base.LogObject, agentName string) (bool, string) { } log.Functionf("CheckProcessExists: found %s\n", filename) // Check if process still exists - b, err := ioutil.ReadFile(filename) + b, err := os.ReadFile(filename) if err != nil { log.Fatalf("CheckProcessExists: %s", err) } diff --git a/pkg/pillar/pubsub/checkmaxsize_test.go b/pkg/pillar/pubsub/checkmaxsize_test.go index ec7703f8b64..fa11f07382d 100644 --- a/pkg/pillar/pubsub/checkmaxsize_test.go +++ b/pkg/pillar/pubsub/checkmaxsize_test.go @@ -4,7 +4,6 @@ package pubsub_test import ( - "io/ioutil" "os" "testing" "time" @@ -23,7 +22,7 @@ type largeItem struct { func TestCheckMaxSize(t *testing.T) { // Run in a unique directory - rootPath, err := ioutil.TempDir("", "checkmaxsize_test") + rootPath, err := os.MkdirTemp("", "checkmaxsize_test") if err != nil { t.Fatalf("TempDir failed: %s", err) } diff --git a/pkg/pillar/pubsub/large.go b/pkg/pillar/pubsub/large.go index f5b33edd852..f29b00920ea 100644 --- a/pkg/pillar/pubsub/large.go +++ b/pkg/pillar/pubsub/large.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "strings" @@ -142,7 +141,7 @@ func writeRemoveTree(log *base.LogObject, dirname, nk, err) return out, err } - tmpfile, err := ioutil.TempFile(dirname, nk) + tmpfile, err := os.CreateTemp(dirname, nk) if err != nil { err := fmt.Errorf("writeRemoveTree: TempFile failed for %s %s: %v", dirname, nk, err) diff --git a/pkg/pillar/pubsub/large_test.go b/pkg/pillar/pubsub/large_test.go index c03378f18f9..efd22d0659d 100644 --- a/pkg/pillar/pubsub/large_test.go +++ b/pkg/pillar/pubsub/large_test.go @@ -5,7 +5,6 @@ package pubsub import ( "encoding/json" - "io/ioutil" "os" "reflect" "strings" @@ -28,7 +27,7 @@ func TestRemoveAndAddLarge(t *testing.T) { logger := logrus.StandardLogger() log := base.NewSourceLogObject(logger, "test", 1234) // Run in a unique directory - rootPath, err := ioutil.TempDir("", "remove_large_test") + rootPath, err := os.MkdirTemp("", "remove_large_test") if err != nil { t.Fatalf("TempDir failed: %s", err) } @@ -121,7 +120,7 @@ func TestRemoveAndAddLargeWithArray(t *testing.T) { logger := logrus.StandardLogger() log := base.NewSourceLogObject(logger, "test", 1234) // Run in a unique directory - rootPath, err := ioutil.TempDir("", "remove_large_test_with_array") + rootPath, err := os.MkdirTemp("", "remove_large_test_with_array") if err != nil { t.Fatalf("TempDir failed: %s", err) } diff --git a/pkg/pillar/pubsub/restarted_test.go b/pkg/pillar/pubsub/restarted_test.go index 757893f5059..081d434e2ec 100644 --- a/pkg/pillar/pubsub/restarted_test.go +++ b/pkg/pillar/pubsub/restarted_test.go @@ -5,7 +5,6 @@ package pubsub_test import ( "fmt" - "io/ioutil" "os" "testing" "time" @@ -19,7 +18,7 @@ import ( func TestRestarted(t *testing.T) { // Run in a unique directory - rootPath, err := ioutil.TempDir("", "restarted_test") + rootPath, err := os.MkdirTemp("", "restarted_test") if err != nil { t.Fatalf("TempDir failed: %s", err) } diff --git a/pkg/pillar/pubsub/socketdriver/publish.go b/pkg/pillar/pubsub/socketdriver/publish.go index 5016a3ed32d..50fd570917b 100644 --- a/pkg/pillar/pubsub/socketdriver/publish.go +++ b/pkg/pillar/pubsub/socketdriver/publish.go @@ -7,7 +7,6 @@ import ( "encoding/base64" "errors" "fmt" - "io/ioutil" "net" "os" "strconv" @@ -104,7 +103,7 @@ func (s *Publisher) Load() (map[string][]byte, int, error) { s.log.Tracef("Load(%s)\n", s.name) - files, err := ioutil.ReadDir(dirName) + files, err := os.ReadDir(dirName) if err != nil { // Drive on? s.log.Error(err) @@ -114,7 +113,7 @@ func (s *Publisher) Load() (map[string][]byte, int, error) { if !strings.HasSuffix(file.Name(), ".json") { if file.Name() == "restarted" { statusFile := dirName + "/" + file.Name() - sb, err := ioutil.ReadFile(statusFile) + sb, err := os.ReadFile(statusFile) if err != nil { s.log.Errorf("Load: %s for %s\n", err, statusFile) continue @@ -142,7 +141,7 @@ func (s *Publisher) Load() (map[string][]byte, int, error) { s.log.Tracef("Load found key %s file %s\n", key, statusFile) - sb, err := ioutil.ReadFile(statusFile) + sb, err := os.ReadFile(statusFile) if err != nil { s.log.Errorf("Load: %s for %s\n", err, statusFile) continue @@ -184,7 +183,7 @@ func (s *Publisher) Load() (map[string][]byte, int, error) { func (s *Publisher) recoverFromBackup(key string) ([]byte, error) { origFileName := s.dirName + "/" + key + ".json" backupFileName := origFileName + ".bak" - bakData, err := ioutil.ReadFile(backupFileName) + bakData, err := os.ReadFile(backupFileName) if err != nil { err = fmt.Errorf("failed to read backup file %s: %w", backupFileName, err) return nil, err diff --git a/pkg/pillar/pubsub/socketdriver/recovery_test.go b/pkg/pillar/pubsub/socketdriver/recovery_test.go index 31b17fe7349..39fdee1f4d6 100644 --- a/pkg/pillar/pubsub/socketdriver/recovery_test.go +++ b/pkg/pillar/pubsub/socketdriver/recovery_test.go @@ -4,7 +4,6 @@ package socketdriver_test import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -32,7 +31,7 @@ func (mockPubSub) DetermineDiffs(pubsub.LocalCollection) []string { func TestRecovery(t *testing.T) { // Run in a unique directory. - rootPath, err := ioutil.TempDir("", "recovery_test") + rootPath, err := os.MkdirTemp("", "recovery_test") if err != nil { t.Fatalf("TempDir failed: %s", err) } @@ -107,7 +106,7 @@ func TestRecovery(t *testing.T) { assert.Equal(t, items["global"], []byte(`{"field":"abcdef"}`)) // Simulate reboot and the persisted file getting emptied. - err = ioutil.WriteFile(filePath, nil, file.Mode()) + err = os.WriteFile(filePath, nil, file.Mode()) if err != nil { t.Fatal(err) } diff --git a/pkg/pillar/pubsub/socketdriver/subscribe.go b/pkg/pillar/pubsub/socketdriver/subscribe.go index b975b461ced..7bf75a56760 100644 --- a/pkg/pillar/pubsub/socketdriver/subscribe.go +++ b/pkg/pillar/pubsub/socketdriver/subscribe.go @@ -7,7 +7,6 @@ import ( "encoding/base64" "errors" "fmt" - "io/ioutil" "net" "os" "path" @@ -48,7 +47,7 @@ func (s *Subscriber) Load() (map[string][]byte, int, error) { s.log.Tracef("Load(%s)\n", s.name) - files, err := ioutil.ReadDir(dirName) + files, err := os.ReadDir(dirName) if err != nil { // Drive on? s.log.Error(err) @@ -58,7 +57,7 @@ func (s *Subscriber) Load() (map[string][]byte, int, error) { if !strings.HasSuffix(file.Name(), ".json") { if file.Name() == "restarted" { statusFile := dirName + "/" + file.Name() - sb, err := ioutil.ReadFile(statusFile) + sb, err := os.ReadFile(statusFile) if err != nil { s.log.Errorf("Load: %s for %s\n", err, statusFile) continue @@ -86,7 +85,7 @@ func (s *Subscriber) Load() (map[string][]byte, int, error) { s.log.Tracef("Load found key %s file %s\n", key, statusFile) - sb, err := ioutil.ReadFile(statusFile) + sb, err := os.ReadFile(statusFile) if err != nil { s.log.Errorf("Load: %s for %s\n", err, statusFile) continue @@ -432,7 +431,7 @@ func (s *Subscriber) translate(in <-chan string, out chan<- pubsub.Change) { out <- pubsub.Change{Operation: pubsub.Sync} case operation == "M" && fileName == "restarted": statusFile := path.Join(statusDirName, fileName) - cb, err := ioutil.ReadFile(statusFile) + cb, err := os.ReadFile(statusFile) if err != nil { s.log.Errorf("%s for %s\n", err, statusFile) continue @@ -461,7 +460,7 @@ func (s *Subscriber) translate(in <-chan string, out chan<- pubsub.Change) { name[0]) case operation == "M": statusFile := path.Join(statusDirName, fileName) - cb, err := ioutil.ReadFile(statusFile) + cb, err := os.ReadFile(statusFile) if err != nil { s.log.Errorf("%s for %s\n", err, statusFile) continue diff --git a/pkg/pillar/pubsub/unsubscribe_test.go b/pkg/pillar/pubsub/unsubscribe_test.go index e41cdf21c15..cbee2dfd9b6 100644 --- a/pkg/pillar/pubsub/unsubscribe_test.go +++ b/pkg/pillar/pubsub/unsubscribe_test.go @@ -4,7 +4,6 @@ package pubsub_test import ( - "io/ioutil" "os" "runtime" "testing" @@ -26,7 +25,7 @@ type context struct { func TestUnsubscribe(t *testing.T) { // Run in a unique directory - rootPath, err := ioutil.TempDir("", "unsubscribe_test") + rootPath, err := os.MkdirTemp("", "unsubscribe_test") if err != nil { t.Fatalf("TempDir failed: %s", err) } diff --git a/pkg/pillar/sriov/sriov.go b/pkg/pillar/sriov/sriov.go index 07bf15deb77..8e13c0828ac 100644 --- a/pkg/pillar/sriov/sriov.go +++ b/pkg/pillar/sriov/sriov.go @@ -6,7 +6,6 @@ package sriov import ( "context" "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -80,7 +79,7 @@ func GetVf(device string) (*VFList, error) { //nolint:gocyclo } if devInfo.IsDir() && (os.IsNotExist(err) || physfnInfo.Mode()&os.ModeSymlink == 0) { - devices, err := ioutil.ReadDir(devPath) + devices, err := os.ReadDir(devPath) if err != nil { return nil, fmt.Errorf("vfInfo failed. Cannot obtain list of %s directory. Error %w", devPath, err) } diff --git a/pkg/pillar/ssh/ssh.go b/pkg/pillar/ssh/ssh.go index fc4052c31ca..073d270e5da 100644 --- a/pkg/pillar/ssh/ssh.go +++ b/pkg/pillar/ssh/ssh.go @@ -11,7 +11,6 @@ package ssh import ( - "io/ioutil" "os" "github.com/lf-edge/eve/pkg/pillar/base" @@ -25,7 +24,7 @@ const ( func UpdateSshAuthorizedKeys(log *base.LogObject, authorizedKeys string) { log.Functionf("UpdateSshAuthorizedKeys: %s", authorizedKeys) - tmpfile, err := ioutil.TempFile(runDir, "ak") + tmpfile, err := os.CreateTemp(runDir, "ak") if err != nil { log.Errorln("TempFile ", err) return diff --git a/pkg/pillar/testprograms/testverifier/testverifier.go b/pkg/pillar/testprograms/testverifier/testverifier.go index a6bac4f3c3a..fd65090444b 100644 --- a/pkg/pillar/testprograms/testverifier/testverifier.go +++ b/pkg/pillar/testprograms/testverifier/testverifier.go @@ -28,7 +28,6 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "log" "math/big" "os" @@ -108,9 +107,9 @@ func main() { //then this config file will be updated //read disk image from local file and compute sha256 of the image... - diskImage, err := ioutil.ReadFile(localImageDirname + "/cirros-0.3.5-x86_64-disk.img") + diskImage, err := os.ReadFile(localImageDirname + "/cirros-0.3.5-x86_64-disk.img") - //diskImage, err := ioutil.ReadFile("/var/tmp/zedmanager/downloads/verified/e137062a4dfbb4c225971b67781bc52183d14517170e16a3841d16f962ae7470/http:__download.cirros-cloud.net_0.3.5_cirros-0.3.5-x86_64-disk.img.e137062a4dfbb4c225971b67781bc52183d14517170e16a3841d16f962ae7470") + //diskImage, err := os.ReadFile("/var/tmp/zedmanager/downloads/verified/e137062a4dfbb4c225971b67781bc52183d14517170e16a3841d16f962ae7470/http:__download.cirros-cloud.net_0.3.5_cirros-0.3.5-x86_64-disk.img.e137062a4dfbb4c225971b67781bc52183d14517170e16a3841d16f962ae7470") if err != nil { fmt.Println(err) } @@ -127,14 +126,14 @@ func main() { if err != nil { fmt.Println("err: ", err) } - serverPrivateKey, err = ioutil.ReadFile(localBaseDirname + "/server_private_key") + serverPrivateKey, err = os.ReadFile(localBaseDirname + "/server_private_key") if err != nil { fmt.Println(err) } } else { - serverPrivateKey, err = ioutil.ReadFile(localCertificateDirname + "/server.key.pem") - err = ioutil.WriteFile(localBaseDirname+"/server_private_key", serverPrivateKey, 0644) + serverPrivateKey, err = os.ReadFile(localCertificateDirname + "/server.key.pem") + err = os.WriteFile(localBaseDirname+"/server_private_key", serverPrivateKey, 0644) if err != nil { fmt.Println(err) } @@ -240,7 +239,7 @@ func UpdateConfigFile(config VerifierConfig, configDirname string) { } //fmt.Println(b) - err = ioutil.WriteFile(configDirname+"/testCf.json", b, 0644) + err = os.WriteFile(configDirname+"/testCf.json", b, 0644) if err != nil { log.Fatal(err) } @@ -252,7 +251,7 @@ func urlToSafename(url string, sha string) string { } func InvokeDeviceCodeForVerification(configDirname, imageDirname, certificateDirname, rootCertFileName string, signature []byte) { configFile := configDirname + "/testCf.json" - cb, err := ioutil.ReadFile(configFile) + cb, err := os.ReadFile(configFile) if err != nil { log.Printf("%s for %s\n", err, configFile) } @@ -268,7 +267,7 @@ func InvokeDeviceCodeForVerification(configDirname, imageDirname, certificateDir //and signature verification... serverCertName := config.SignatureKey - serverCertificate, err := ioutil.ReadFile(certificateDirname + "/" + serverCertName) + serverCertificate, err := os.ReadFile(certificateDirname + "/" + serverCertName) if err != nil { fmt.Println(err) } @@ -290,7 +289,7 @@ func InvokeDeviceCodeForVerification(configDirname, imageDirname, certificateDir roots := x509.NewCertPool() //read the root cerificates from /usr/local/etc/zededa... - rootCertificate, err := ioutil.ReadFile(rootCertFileName) + rootCertificate, err := os.ReadFile(rootCertFileName) if err != nil { fmt.Println(err) } @@ -304,7 +303,7 @@ func InvokeDeviceCodeForVerification(configDirname, imageDirname, certificateDir for c := 0; c < length; c++ { fmt.Println(certificateNameInChain[c]) - certNameFromChain, err := ioutil.ReadFile(certificateDirname + "/" + certificateNameInChain[c]) + certNameFromChain, err := os.ReadFile(certificateDirname + "/" + certificateNameInChain[c]) if err != nil { fmt.Println(err) } @@ -327,9 +326,9 @@ func InvokeDeviceCodeForVerification(configDirname, imageDirname, certificateDir //and compute sha256 of the image... destinationImgDir := imageDirname + "/" + imgSha + "/" + safeName - diskImg, err := ioutil.ReadFile(destinationImgDir) + diskImg, err := os.ReadFile(destinationImgDir) - //diskImage, err := ioutil.ReadFile("/var/tmp/zedmanager/downloads/verified/e137062a4dfbb4c225971b67781bc52183d14517170e16a3841d16f962ae7470/http:__download.cirros-cloud.net_0.3.5_cirros-0.3.5-x86_64-disk.img.e137062a4dfbb4c225971b67781bc52183d14517170e16a3841d16f962ae7470") + //diskImage, err := os.ReadFile("/var/tmp/zedmanager/downloads/verified/e137062a4dfbb4c225971b67781bc52183d14517170e16a3841d16f962ae7470/http:__download.cirros-cloud.net_0.3.5_cirros-0.3.5-x86_64-disk.img.e137062a4dfbb4c225971b67781bc52183d14517170e16a3841d16f962ae7470") if err != nil { fmt.Println(err) } diff --git a/pkg/pillar/tgt/tgt.go b/pkg/pillar/tgt/tgt.go index 038aceb90fb..b0a2a96eb84 100644 --- a/pkg/pillar/tgt/tgt.go +++ b/pkg/pillar/tgt/tgt.go @@ -7,7 +7,6 @@ package tgt import ( "fmt" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -70,19 +69,19 @@ func TargetCreateIBlock(dev, tgtName, serial string) error { return fmt.Errorf("error waitForFile: %v", err) } controlCommand := fmt.Sprintf("udev_path=%s", dev) - if err := ioutil.WriteFile(filepath.Join(targetRoot, "control"), []byte(controlCommand), 0660); err != nil { + if err := os.WriteFile(filepath.Join(targetRoot, "control"), []byte(controlCommand), 0660); err != nil { return fmt.Errorf("error set control: %v", err) } - if err := ioutil.WriteFile(filepath.Join(targetRoot, "wwn", "vpd_unit_serial"), []byte(serial), 0660); err != nil { + if err := os.WriteFile(filepath.Join(targetRoot, "wwn", "vpd_unit_serial"), []byte(serial), 0660); err != nil { return fmt.Errorf("error set vpd_unit_serial: %v", err) } if err := waitForFile(filepath.Join(targetRoot, "enable")); err != nil { return fmt.Errorf("error waitForFile: %v", err) } - if err := ioutil.WriteFile(filepath.Join(targetRoot, "enable"), []byte("1"), 0660); err != nil { + if err := os.WriteFile(filepath.Join(targetRoot, "enable"), []byte("1"), 0660); err != nil { return fmt.Errorf("error set enable: %v", err) } - if err := ioutil.WriteFile(filepath.Join(targetRoot, "attrib", "emulate_tpu"), []byte("1"), 0660); err != nil { + if err := os.WriteFile(filepath.Join(targetRoot, "attrib", "emulate_tpu"), []byte("1"), 0660); err != nil { return fmt.Errorf("error set emulate_tpu: %v", err) } return nil @@ -111,13 +110,13 @@ func VHostCreateIBlock(tgtName, wwn string) error { return fmt.Errorf("cannot create vhost: %v", err) } controlCommand := "scsi_host_id=1,scsi_channel_id=0,scsi_target_id=0,scsi_lun_id=0" - if err := ioutil.WriteFile(filepath.Join(targetRoot, "control"), []byte(controlCommand), 0660); err != nil { + if err := os.WriteFile(filepath.Join(targetRoot, "control"), []byte(controlCommand), 0660); err != nil { return fmt.Errorf("error set control: %v", err) } if err := waitForFile(filepath.Join(vhostRoot, "nexus")); err != nil { return fmt.Errorf("error waitForFile: %v", err) } - if err := ioutil.WriteFile(filepath.Join(vhostRoot, "nexus"), []byte(wwn), 0660); err != nil { + if err := os.WriteFile(filepath.Join(vhostRoot, "nexus"), []byte(wwn), 0660); err != nil { return fmt.Errorf("error set nexus: %v", err) } if _, err := os.Stat(filepath.Join(vhostLun, "iblock")); os.IsNotExist(err) { @@ -132,7 +131,7 @@ func VHostCreateIBlock(tgtName, wwn string) error { func GetSerialTarget(tgtName string) (string, error) { targetRoot := filepath.Join(iBlockPath, tgtName) //it returns something like "T10 VPD Unit Serial Number: 5001405043a8fbf4" - serial, err := ioutil.ReadFile(filepath.Join(targetRoot, "wwn", "vpd_unit_serial")) + serial, err := os.ReadFile(filepath.Join(targetRoot, "wwn", "vpd_unit_serial")) if err != nil { return "", fmt.Errorf("GetSerialTarget for %s: %s", targetRoot, err) } diff --git a/pkg/pillar/types/assignableadapters.go b/pkg/pillar/types/assignableadapters.go index 7d1d8b2a914..17b0f27e58d 100644 --- a/pkg/pillar/types/assignableadapters.go +++ b/pkg/pillar/types/assignableadapters.go @@ -13,7 +13,6 @@ package types import ( "fmt" - "io/ioutil" "os" "reflect" "strings" @@ -496,7 +495,7 @@ func getDeviceNameFromPciID(pciID string) (string, error) { // e.g., ls /sys/bus/pci/devices//nvme/ // -> nvme0 deviceName := "" - nvmePath, err := ioutil.ReadDir(sysfsPciDevices + pciID + "/nvme") + nvmePath, err := os.ReadDir(sysfsPciDevices + pciID + "/nvme") if err != nil { return "", err } diff --git a/pkg/pillar/types/ifnametopci.go b/pkg/pillar/types/ifnametopci.go index 4fa357460e4..dc9450f4f16 100644 --- a/pkg/pillar/types/ifnametopci.go +++ b/pkg/pillar/types/ifnametopci.go @@ -9,7 +9,6 @@ package types import ( "errors" "fmt" - "io/ioutil" "os" "path" "regexp" @@ -175,7 +174,7 @@ func PciLongToIfname(log *base.LogObject, long string) (bool, string) { return false, "" } devPath := pciPath + "/" + long + "/net" - locations, err := ioutil.ReadDir(devPath) + locations, err := os.ReadDir(devPath) if err != nil { log.Errorf("Dir %s is missing", devPath) return false, "" @@ -288,7 +287,7 @@ func PCIIsBootVga(log *base.LogObject, long string) (bool, error) { log.Functionf("PCIIsBootVga %s", long) bootVgaFile := pciPath + "/" + long + "/boot_vga" - if isBoot, err := ioutil.ReadFile(bootVgaFile); err != nil { + if isBoot, err := os.ReadFile(bootVgaFile); err != nil { return false, err } else { return strings.TrimSpace(strings.TrimSuffix(string(isBoot), "\n")) == "1", err diff --git a/pkg/pillar/types/memory.go b/pkg/pillar/types/memory.go index 1e5d27bd2b7..accaff85140 100644 --- a/pkg/pillar/types/memory.go +++ b/pkg/pillar/types/memory.go @@ -4,7 +4,7 @@ package types import ( - "io/ioutil" + "os" "strconv" "strings" ) @@ -34,7 +34,7 @@ func GetZFSArcMaxSizeInBytes() (uint64, error) { } func readUint64File(filename string) (uint64, error) { - dataBytes, err := ioutil.ReadFile(filename) + dataBytes, err := os.ReadFile(filename) if err != nil { return 0, err } diff --git a/pkg/pillar/utils/file/copy.go b/pkg/pillar/utils/file/copy.go index 4ef6b0edc39..c93e671baa7 100644 --- a/pkg/pillar/utils/file/copy.go +++ b/pkg/pillar/utils/file/copy.go @@ -26,7 +26,6 @@ package utils import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" ) @@ -103,7 +102,7 @@ func CopyDir(src string, dst string) (err error) { return } - entries, err := ioutil.ReadDir(src) + entries, err := os.ReadDir(src) if err != nil { return } @@ -111,7 +110,11 @@ func CopyDir(src string, dst string) (err error) { for _, entry := range entries { srcPath := filepath.Join(src, entry.Name()) dstPath := filepath.Join(dst, entry.Name()) - + var info os.FileInfo + info, err = entry.Info() + if err != nil { + return fmt.Errorf("failed to get file '%s' info: %v", entry.Name(), err) + } if entry.IsDir() { err = CopyDir(srcPath, dstPath) if err != nil { @@ -119,7 +122,7 @@ func CopyDir(src string, dst string) (err error) { } } else { // Skip symlinks. - if entry.Mode()&os.ModeSymlink != 0 { + if info.Mode()&os.ModeSymlink != 0 { continue } diff --git a/pkg/pillar/utils/file/file.go b/pkg/pillar/utils/file/file.go index 124c6ed3bd4..38f3fa9fab8 100644 --- a/pkg/pillar/utils/file/file.go +++ b/pkg/pillar/utils/file/file.go @@ -7,7 +7,6 @@ import ( "bufio" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -104,7 +103,7 @@ func WriteRenameWithBackup(fileName string, b []byte) error { func writeRename(fileName string, b []byte, withBackup bool) error { dirName := filepath.Dir(fileName) // Do atomic rename to avoid partially written files - tmpfile, err := ioutil.TempFile(dirName, "tmp") + tmpfile, err := os.CreateTemp(dirName, "tmp") if err != nil { errStr := fmt.Sprintf("WriteRename(%s): %s", fileName, err) diff --git a/pkg/pillar/utils/file/move.go b/pkg/pillar/utils/file/move.go index 642d93c5626..cdccae548e2 100644 --- a/pkg/pillar/utils/file/move.go +++ b/pkg/pillar/utils/file/move.go @@ -5,7 +5,6 @@ package utils import ( "fmt" - "io/ioutil" "os" "path/filepath" "syscall" @@ -40,7 +39,7 @@ func MoveDir(log *base.LogObject, src string, dst string) error { return fmt.Errorf("error creating dst directory: %v", err) } - entries, err := ioutil.ReadDir(src) + entries, err := os.ReadDir(src) if err != nil { return fmt.Errorf("error read dst directory: %v", err) } @@ -52,14 +51,17 @@ func MoveDir(log *base.LogObject, src string, dst string) error { for _, entry := range entries { srcPath := filepath.Join(src, entry.Name()) dstPath := filepath.Join(dst, entry.Name()) - + info, err := entry.Info() + if err != nil { + return fmt.Errorf("failed to get file '%s' info: %v", entry.Name(), err) + } if entry.IsDir() { err = MoveDir(log, srcPath, dstPath) if err != nil { return err } } else { - if entry.Mode()&os.ModeSymlink != 0 { + if info.Mode()&os.ModeSymlink != 0 { link, err := os.Readlink(srcPath) if err != nil { return fmt.Errorf("error readlink file: %v", err) diff --git a/pkg/pillar/vault/key.go b/pkg/pillar/vault/key.go index 331d1911c89..2737a3559bf 100644 --- a/pkg/pillar/vault/key.go +++ b/pkg/pillar/vault/key.go @@ -6,7 +6,6 @@ package vault import ( "errors" "fmt" - "io/ioutil" "os" "github.com/lf-edge/eve/pkg/pillar/base" @@ -79,7 +78,7 @@ func stageKey(log *base.LogObject, cloudKeyOnlyMode, useSealedKey, tpmKeyOnlyMod unstageKey(log, keyDirName, keyFileName) return nil, err } - if err := ioutil.WriteFile(keyFileName, vaultKey, 0700); err != nil { + if err := os.WriteFile(keyFileName, vaultKey, 0700); err != nil { unstageKey(log, keyDirName, keyFileName) return nil, fmt.Errorf("error creating keyFile: %v", err) } diff --git a/pkg/pillar/vault/vault.go b/pkg/pillar/vault/vault.go index dc6658e223a..be235e1a342 100644 --- a/pkg/pillar/vault/vault.go +++ b/pkg/pillar/vault/vault.go @@ -6,7 +6,6 @@ package vault import ( "bytes" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -36,7 +35,7 @@ func GetOperationalInfo(log *base.LogObject) (info.DataSecAtRestStatus, string) // ReadPersistType returns the persist filesystem func ReadPersistType() types.PersistType { persistFsType := "" - pBytes, err := ioutil.ReadFile(evePersistTypeFile) + pBytes, err := os.ReadFile(evePersistTypeFile) if err == nil { persistFsType = strings.TrimSpace(string(pBytes)) } diff --git a/pkg/pillar/watch/watchconfigstatus.go b/pkg/pillar/watch/watchconfigstatus.go index 26653d914c1..05e51b96300 100644 --- a/pkg/pillar/watch/watchconfigstatus.go +++ b/pkg/pillar/watch/watchconfigstatus.go @@ -12,7 +12,7 @@ package watch import ( - "io/ioutil" + "os" "path" "strings" "time" @@ -30,7 +30,7 @@ func watchReadDir(log *base.LogObject, configDir string, fileChanges chan<- stri foundRestart := false foundRestarted := false - files, err := ioutil.ReadDir(configDir) + files, err := os.ReadDir(configDir) if err != nil { log.Fatalf("***watchReadDir - Failed to read Directory %s . err: %s", configDir, err) diff --git a/pkg/pillar/zboot/zboot.go b/pkg/pillar/zboot/zboot.go index 68de5752dca..81bb1e5b748 100644 --- a/pkg/pillar/zboot/zboot.go +++ b/pkg/pillar/zboot/zboot.go @@ -9,7 +9,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "os/exec" "strings" @@ -485,7 +484,7 @@ func getVersion(log *base.LogObject, part string, verFilename string) (string, e if part == GetCurrentPartition() { filename := verFilename - version, err := ioutil.ReadFile(filename) + version, err := os.ReadFile(filename) if err != nil { log.Errorln(err) return "", err @@ -497,7 +496,7 @@ func getVersion(log *base.LogObject, part string, verFilename string) (string, e } else { verFilename = otherPartVersionFile devname := GetPartitionDevname(part) - target, err := ioutil.TempDir("/run/baseosmgr", "tmpmnt") + target, err := os.MkdirTemp("/run/baseosmgr", "tmpmnt") if err != nil { log.Errorln(err) return "", err @@ -536,7 +535,7 @@ func getVersion(log *base.LogObject, part string, verFilename string) (string, e }() filename := fmt.Sprintf("%s/%s", target, verFilename) - version, err := ioutil.ReadFile(filename) + version, err := os.ReadFile(filename) if err != nil { log.Warn(err) return "", err diff --git a/pkg/pillar/zedbox/zedbox.go b/pkg/pillar/zedbox/zedbox.go index c3489ab2a97..e22dbae8cf6 100644 --- a/pkg/pillar/zedbox/zedbox.go +++ b/pkg/pillar/zedbox/zedbox.go @@ -7,7 +7,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -235,7 +234,7 @@ func startAgentAndDone(sep entrypoint, agentName string, srvPs *pubsub.PubSub, retval := sep.f(srvPs, srvLogger, srvLog, cmdArgs) ret := strconv.Itoa(retval) - if err := ioutil.WriteFile(fmt.Sprintf("/run/%s.done", agentName), + if err := os.WriteFile(fmt.Sprintf("/run/%s.done", agentName), []byte(ret), 0700); err != nil { log.Fatalf("Error write done file: %v", err) } diff --git a/pkg/pillar/zedcloud/authen.go b/pkg/pillar/zedcloud/authen.go index 305cec1502c..0e7eac09d83 100644 --- a/pkg/pillar/zedcloud/authen.go +++ b/pkg/pillar/zedcloud/authen.go @@ -18,7 +18,6 @@ import ( "encoding/pem" "errors" "fmt" - "io/ioutil" "math/big" "mime" "net/http" @@ -166,7 +165,7 @@ func VerifyAuthContainer(ctx *ZedCloudContext, sm *zauth.AuthContainer) (types.S } func loadSavedServerSigningCert(ctx *ZedCloudContext) error { - certBytes, err := ioutil.ReadFile(types.ServerSigningCertFileName) + certBytes, err := os.ReadFile(types.ServerSigningCertFileName) if err != nil { ctx.log.Errorf("loadSavedServerSigningCert: can not read in server cert file, %v\n", err) return err @@ -300,7 +299,7 @@ func getMyDevCert(ctx *ZedCloudContext, isOnboard bool) (tls.Certificate, error) return cert, err } - onboardCertpem, err := ioutil.ReadFile(types.OnboardCertName) + onboardCertpem, err := os.ReadFile(types.OnboardCertName) if err != nil { ctx.log.Tracef("getMyDevCert: get onboard certbytes error %v\n", err) return cert, err @@ -537,7 +536,7 @@ func verifySignature(log *base.LogObject, certByte []byte, interm *x509.CertPool // Get the root certificate from file signingRoots := x509.NewCertPool() - caCert, err := ioutil.ReadFile(types.RootCertFileName) + caCert, err := os.ReadFile(types.RootCertFileName) if err != nil { errStr := fmt.Sprintf("root certificate read fail, %v", err) log.Errorln("verifySignature: " + errStr) diff --git a/pkg/pillar/zedcloud/send.go b/pkg/pillar/zedcloud/send.go index 7ca774a3c02..27d01e926f0 100644 --- a/pkg/pillar/zedcloud/send.go +++ b/pkg/pillar/zedcloud/send.go @@ -14,7 +14,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime" "net" "net/http" @@ -1086,7 +1085,7 @@ func SendLocal(ctx *ZedCloudContext, destURL string, intf string, ipSrc net.IP, return nil, nil, errors.New(errStr) } - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) if err != nil { resp.Body.Close() resp.Body = nil diff --git a/pkg/pillar/zedcloud/tls.go b/pkg/pillar/zedcloud/tls.go index 9c7f72e6612..94f7fed3380 100644 --- a/pkg/pillar/zedcloud/tls.go +++ b/pkg/pillar/zedcloud/tls.go @@ -14,7 +14,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strconv" @@ -36,7 +35,7 @@ func GetClientCert() (tls.Certificate, error) { } // TPM capable device, return TPM bcased certificate - deviceCertBytes, err := ioutil.ReadFile(types.DeviceCertName) + deviceCertBytes, err := os.ReadFile(types.DeviceCertName) if err != nil { return tls.Certificate{}, err } @@ -92,7 +91,7 @@ func GetTlsConfig(dns *types.DeviceNetworkStatus, clientCert *tls.Certificate, c if ctx != nil && ctx.V2API { log := ctx.log // Load the well-known CAs - line, err := ioutil.ReadFile(types.V2TLSCertShaFilename) + line, err := os.ReadFile(types.V2TLSCertShaFilename) if err != nil { return nil, err } @@ -103,7 +102,7 @@ func GetTlsConfig(dns *types.DeviceNetworkStatus, clientCert *tls.Certificate, c return nil, errors.New(errStr) } v2RootFilename := types.CertificateDirname + "/" + sha - caCert, err := ioutil.ReadFile(v2RootFilename) + caCert, err := os.ReadFile(v2RootFilename) if err != nil { return nil, err } @@ -135,7 +134,7 @@ func GetTlsConfig(dns *types.DeviceNetworkStatus, clientCert *tls.Certificate, c } // Also append the v1's private signed root-cert - caCert1, err := ioutil.ReadFile(types.RootCertFileName) + caCert1, err := os.ReadFile(types.RootCertFileName) if err != nil { return nil, err } @@ -251,7 +250,7 @@ func UpdateTLSProxyCerts(ctx *ZedCloudContext) bool { // previous certs we have are different, lets rebuild from beginning caCertPool = x509.NewCertPool() - line, err := ioutil.ReadFile(types.V2TLSCertShaFilename) + line, err := os.ReadFile(types.V2TLSCertShaFilename) if err != nil { errStr := fmt.Sprintf("Failed to read V2TLSCertShaFilename") log.Errorf(errStr) @@ -264,7 +263,7 @@ func UpdateTLSProxyCerts(ctx *ZedCloudContext) bool { return false } v2RootFilename := types.CertificateDirname + "/" + sha - caCert, err := ioutil.ReadFile(v2RootFilename) + caCert, err := os.ReadFile(v2RootFilename) if err != nil { errStr := fmt.Sprintf("Failed to read v2RootFilename") log.Errorf(errStr) diff --git a/pkg/pillar/zedcloud/wstunnelclient.go b/pkg/pillar/zedcloud/wstunnelclient.go index 347bca580dd..c8ea79dd39a 100644 --- a/pkg/pillar/zedcloud/wstunnelclient.go +++ b/pkg/pillar/zedcloud/wstunnelclient.go @@ -8,7 +8,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -249,7 +248,7 @@ func (wsc *WSConnection) handleRequests() { // SetReadLimit on the websocket. We have to do this because we want to handle // the request in a goroutine (see "go process..Request" calls below) and the // websocket doesn't allow us to have multiple goroutines reading... - request, err := ioutil.ReadAll(reader) + request, err := io.ReadAll(reader) if err != nil { log.Tracef("[id=%d] WS cannot read request message Error: %s", id, err.Error()) break diff --git a/pkg/pillar/zfs/zfs.go b/pkg/pillar/zfs/zfs.go index 96e7b83693d..d1b898bb649 100644 --- a/pkg/pillar/zfs/zfs.go +++ b/pkg/pillar/zfs/zfs.go @@ -5,7 +5,6 @@ package zfs import ( "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -400,7 +399,7 @@ func ReplaceVDev(log *base.LogObject, pool, oldVdev, newVdev string) (string, er // GetZfsVersion return zfs kernel module version func GetZfsVersion() (string, error) { - dataBytes, err := ioutil.ReadFile("/hostfs/sys/module/zfs/version") + dataBytes, err := os.ReadFile("/hostfs/sys/module/zfs/version") if err != nil { return "", err } @@ -684,7 +683,7 @@ func GetDatasetUsageStat(datasetName string) (*types.UsageStat, error) { // GetZVolSectorSize return hw_sector_size for zvol func GetZVolSectorSize(zVolName string) (uint64, error) { - dataBytes, err := ioutil.ReadFile( + dataBytes, err := os.ReadFile( fmt.Sprintf("/sys/block/%s/queue/hw_sector_size", filepath.Base(zVolName))) if err != nil {