io/ioutil has already been deprecated in golang 1.16, so replace all ioutil with io and os

This commit is contained in:
ahrtr 2021-10-30 06:41:02 +08:00
parent 2d0fa78f2f
commit fe95aa614c
96 changed files with 250 additions and 297 deletions

View File

@ -19,7 +19,6 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"os/signal" "os/signal"
@ -123,7 +122,7 @@ func saveResults(resultsDir string) error {
return fmt.Errorf("failed to find absolute path for %v: %w", resultsTarball, err) return fmt.Errorf("failed to find absolute path for %v: %w", resultsTarball, err)
} }
err = ioutil.WriteFile(doneFile, []byte(resultsTarball), os.FileMode(0777)) err = os.WriteFile(doneFile, []byte(resultsTarball), os.FileMode(0777))
if err != nil { if err != nil {
return fmt.Errorf("writing donefile: %w", err) return fmt.Errorf("writing donefile: %w", err)
} }

View File

@ -21,7 +21,6 @@ import (
"compress/gzip" "compress/gzip"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"reflect" "reflect"
@ -30,7 +29,7 @@ import (
) )
func TestTar(t *testing.T) { func TestTar(t *testing.T) {
tmp, err := ioutil.TempDir("", "testtar") tmp, err := os.MkdirTemp("", "testtar")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -39,13 +38,13 @@ func TestTar(t *testing.T) {
if err := os.Mkdir(filepath.Join(tmp, "subdir"), os.FileMode(0755)); err != nil { if err := os.Mkdir(filepath.Join(tmp, "subdir"), os.FileMode(0755)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(filepath.Join(tmp, "file1"), []byte(`file1 data`), os.FileMode(0644)); err != nil { if err := os.WriteFile(filepath.Join(tmp, "file1"), []byte(`file1 data`), os.FileMode(0644)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(filepath.Join(tmp, "file2"), []byte(`file2 data`), os.FileMode(0644)); err != nil { if err := os.WriteFile(filepath.Join(tmp, "file2"), []byte(`file2 data`), os.FileMode(0644)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(filepath.Join(tmp, "subdir", "file4"), []byte(`file4 data`), os.FileMode(0644)); err != nil { if err := os.WriteFile(filepath.Join(tmp, "subdir", "file4"), []byte(`file4 data`), os.FileMode(0644)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -138,7 +137,7 @@ func readAllTar(tarPath string) (map[string]string, error) {
return nil, err return nil, err
} }
b, err := ioutil.ReadAll(tr) b, err := io.ReadAll(tr)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -18,7 +18,6 @@ package apimachinery
import ( import (
"crypto/x509" "crypto/x509"
"io/ioutil"
"os" "os"
"k8s.io/client-go/util/cert" "k8s.io/client-go/util/cert"
@ -36,7 +35,7 @@ type certContext struct {
// Setup the server cert. For example, user apiservers and admission webhooks // Setup the server cert. For example, user apiservers and admission webhooks
// can use the cert to prove their identify to the kube-apiserver // can use the cert to prove their identify to the kube-apiserver
func setupServerCert(namespaceName, serviceName string) *certContext { func setupServerCert(namespaceName, serviceName string) *certContext {
certDir, err := ioutil.TempDir("", "test-e2e-server-cert") certDir, err := os.MkdirTemp("", "test-e2e-server-cert")
if err != nil { if err != nil {
framework.Failf("Failed to create a temp dir for cert generation %v", err) framework.Failf("Failed to create a temp dir for cert generation %v", err)
} }
@ -49,11 +48,11 @@ func setupServerCert(namespaceName, serviceName string) *certContext {
if err != nil { if err != nil {
framework.Failf("Failed to create CA cert for apiserver %v", err) framework.Failf("Failed to create CA cert for apiserver %v", err)
} }
caCertFile, err := ioutil.TempFile(certDir, "ca.crt") caCertFile, err := os.CreateTemp(certDir, "ca.crt")
if err != nil { if err != nil {
framework.Failf("Failed to create a temp file for ca cert generation %v", err) framework.Failf("Failed to create a temp file for ca cert generation %v", err)
} }
if err := ioutil.WriteFile(caCertFile.Name(), utils.EncodeCertPEM(signingCert), 0644); err != nil { if err := os.WriteFile(caCertFile.Name(), utils.EncodeCertPEM(signingCert), 0644); err != nil {
framework.Failf("Failed to write CA cert %v", err) framework.Failf("Failed to write CA cert %v", err)
} }
key, err := utils.NewPrivateKey() key, err := utils.NewPrivateKey()
@ -71,22 +70,22 @@ func setupServerCert(namespaceName, serviceName string) *certContext {
if err != nil { if err != nil {
framework.Failf("Failed to create cert%v", err) framework.Failf("Failed to create cert%v", err)
} }
certFile, err := ioutil.TempFile(certDir, "server.crt") certFile, err := os.CreateTemp(certDir, "server.crt")
if err != nil { if err != nil {
framework.Failf("Failed to create a temp file for cert generation %v", err) framework.Failf("Failed to create a temp file for cert generation %v", err)
} }
keyFile, err := ioutil.TempFile(certDir, "server.key") keyFile, err := os.CreateTemp(certDir, "server.key")
if err != nil { if err != nil {
framework.Failf("Failed to create a temp file for key generation %v", err) framework.Failf("Failed to create a temp file for key generation %v", err)
} }
if err = ioutil.WriteFile(certFile.Name(), utils.EncodeCertPEM(signedCert), 0600); err != nil { if err = os.WriteFile(certFile.Name(), utils.EncodeCertPEM(signedCert), 0600); err != nil {
framework.Failf("Failed to write cert file %v", err) framework.Failf("Failed to write cert file %v", err)
} }
privateKeyPEM, err := keyutil.MarshalPrivateKeyToPEM(key) privateKeyPEM, err := keyutil.MarshalPrivateKeyToPEM(key)
if err != nil { if err != nil {
framework.Failf("Failed to marshal key %v", err) framework.Failf("Failed to marshal key %v", err)
} }
if err = ioutil.WriteFile(keyFile.Name(), privateKeyPEM, 0644); err != nil { if err = os.WriteFile(keyFile.Name(), privateKeyPEM, 0644); err != nil {
framework.Failf("Failed to write key file %v", err) framework.Failf("Failed to write key file %v", err)
} }
return &certContext{ return &certContext{

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"regexp" "regexp"
"strings" "strings"
@ -662,7 +662,7 @@ func waitForOpenAPISchema(c k8sclientset.Interface, pred func(*spec.Swagger) (bo
spec = etagSpec spec = etagSpec
} else if resp.StatusCode != http.StatusOK { } else if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf("unexpected response: %d", resp.StatusCode) return false, fmt.Errorf("unexpected response: %d", resp.StatusCode)
} else if bs, err := ioutil.ReadAll(resp.Body); err != nil { } else if bs, err := io.ReadAll(resp.Body); err != nil {
return false, err return false, err
} else if err := json.Unmarshal(bs, spec); err != nil { } else if err := json.Unmarshal(bs, spec); err != nil {
return false, err return false, err

View File

@ -17,7 +17,7 @@ limitations under the License.
package apimachinery package apimachinery
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
@ -100,7 +100,7 @@ func newRequest(f *framework.Framework, timeout string) *http.Request {
} }
func readBody(response *http.Response) string { func readBody(response *http.Response) string {
raw, err := ioutil.ReadAll(response.Body) raw, err := io.ReadAll(response.Body)
framework.ExpectNoError(err) framework.ExpectNoError(err)
return string(raw) return string(raw)

View File

@ -19,7 +19,7 @@ package autoscaling
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"math" "math"
"net/http" "net/http"
"os" "os"
@ -1101,7 +1101,7 @@ func getCluster(apiVersion string) (string, error) {
return "", err return "", err
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -19,7 +19,7 @@ package node
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "os"
"path" "path"
"time" "time"
@ -291,7 +291,7 @@ while true; do sleep 1; done
}` }`
// we might be told to use a different docker config JSON. // we might be told to use a different docker config JSON.
if framework.TestContext.DockerConfigFile != "" { if framework.TestContext.DockerConfigFile != "" {
contents, err := ioutil.ReadFile(framework.TestContext.DockerConfigFile) contents, err := os.ReadFile(framework.TestContext.DockerConfigFile)
framework.ExpectNoError(err) framework.ExpectNoError(err)
auth = string(contents) auth = string(contents)
} }

View File

@ -20,7 +20,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path" "path"
@ -298,7 +297,7 @@ func logClusterImageSources() {
outputBytes, _ := json.MarshalIndent(images, "", " ") outputBytes, _ := json.MarshalIndent(images, "", " ")
filePath := filepath.Join(framework.TestContext.ReportDir, "images.json") filePath := filepath.Join(framework.TestContext.ReportDir, "images.json")
if err := ioutil.WriteFile(filePath, outputBytes, 0644); err != nil { if err := os.WriteFile(filePath, outputBytes, 0644); err != nil {
framework.Logf("cluster images sources, could not write to %q: %v", filePath, err) framework.Logf("cluster images sources, could not write to %q: %v", filePath, err)
} }
} }

View File

@ -24,8 +24,8 @@ package framework
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"math/rand" "math/rand"
"os"
"path" "path"
"strings" "strings"
"sync" "sync"
@ -328,7 +328,7 @@ func printSummaries(summaries []TestDataSummary, testBaseName string) {
} else { } else {
// TODO: learn to extract test name and append it to the kind instead of timestamp. // TODO: learn to extract test name and append it to the kind instead of timestamp.
filePath := path.Join(TestContext.ReportDir, summaries[i].SummaryKind()+"_"+testBaseName+"_"+now.Format(time.RFC3339)+".txt") filePath := path.Join(TestContext.ReportDir, summaries[i].SummaryKind()+"_"+testBaseName+"_"+now.Format(time.RFC3339)+".txt")
if err := ioutil.WriteFile(filePath, []byte(summaries[i].PrintHumanReadable()), 0644); err != nil { if err := os.WriteFile(filePath, []byte(summaries[i].PrintHumanReadable()), 0644); err != nil {
Logf("Failed to write file %v with test performance data: %v", filePath, err) Logf("Failed to write file %v with test performance data: %v", filePath, err)
} }
} }
@ -345,7 +345,7 @@ func printSummaries(summaries []TestDataSummary, testBaseName string) {
// TODO: learn to extract test name and append it to the kind instead of timestamp. // TODO: learn to extract test name and append it to the kind instead of timestamp.
filePath := path.Join(TestContext.ReportDir, summaries[i].SummaryKind()+"_"+testBaseName+"_"+now.Format(time.RFC3339)+".json") filePath := path.Join(TestContext.ReportDir, summaries[i].SummaryKind()+"_"+testBaseName+"_"+now.Format(time.RFC3339)+".json")
Logf("Writing to %s", filePath) Logf("Writing to %s", filePath)
if err := ioutil.WriteFile(filePath, []byte(summaries[i].PrintJSON()), 0644); err != nil { if err := os.WriteFile(filePath, []byte(summaries[i].PrintJSON()), 0644); err != nil {
Logf("Failed to write file %v with test performance data: %v", filePath, err) Logf("Failed to write file %v with test performance data: %v", filePath, err)
} }
} }

View File

@ -26,10 +26,11 @@ import (
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil" "io"
"math/big" "math/big"
"net" "net"
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv" "strconv"
@ -178,7 +179,7 @@ func SimpleGET(c *http.Client, url, host string) (string, error) {
return "", err return "", err
} }
defer res.Body.Close() defer res.Body.Close()
rawBody, err := ioutil.ReadAll(res.Body) rawBody, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -533,7 +534,7 @@ func ingressToManifest(ing *networkingv1.Ingress, path string) error {
return fmt.Errorf("failed to marshal ingress %v to YAML: %v", ing, err) return fmt.Errorf("failed to marshal ingress %v to YAML: %v", ing, err)
} }
if err := ioutil.WriteFile(path, serialized, 0600); err != nil { if err := os.WriteFile(path, serialized, 0600); err != nil {
return fmt.Errorf("error in writing ingress to file: %s", err) return fmt.Errorf("error in writing ingress to file: %s", err)
} }
return nil return nil

View File

@ -17,7 +17,6 @@ limitations under the License.
package ingress package ingress
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -28,7 +27,7 @@ import (
func TestIngressToManifest(t *testing.T) { func TestIngressToManifest(t *testing.T) {
ing := &networkingv1.Ingress{} ing := &networkingv1.Ingress{}
// Create a temp dir. // Create a temp dir.
tmpDir, err := ioutil.TempDir("", "kubemci") tmpDir, err := os.MkdirTemp("", "kubemci")
if err != nil { if err != nil {
t.Fatalf("unexpected error in creating temp dir: %s", err) t.Fatalf("unexpected error in creating temp dir: %s", err)
} }

View File

@ -20,7 +20,7 @@ import (
"crypto/tls" "crypto/tls"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"regexp" "regexp"
"strconv" "strconv"
@ -117,7 +117,7 @@ func decodeConfigz(resp *http.Response) (*kubeletconfig.KubeletConfiguration, er
configz := configzWrapper{} configz := configzWrapper{}
kubeCfg := kubeletconfig.KubeletConfiguration{} kubeCfg := kubeletconfig.KubeletConfiguration{}
contentsBytes, err := ioutil.ReadAll(resp.Body) contentsBytes, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -18,7 +18,7 @@ package manifest
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"time" "time"
@ -115,7 +115,7 @@ func DaemonSetFromURL(url string) (*appsv1.DaemonSet, error) {
} }
defer response.Body.Close() defer response.Body.Close()
data, err := ioutil.ReadAll(response.Body) data, err := io.ReadAll(response.Body)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to read html response body: %v", err) return nil, fmt.Errorf("Failed to read html response body: %v", err)
} }

View File

@ -19,7 +19,7 @@ package metrics
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"sort" "sort"
"strconv" "strconv"
@ -73,7 +73,7 @@ func GrabKubeletMetricsWithoutProxy(nodeName, path string) (KubeletMetrics, erro
return KubeletMetrics{}, err return KubeletMetrics{}, err
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return KubeletMetrics{}, err return KubeletMetrics{}, err
} }

View File

@ -21,7 +21,7 @@ import (
"crypto/tls" "crypto/tls"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"strconv" "strconv"
@ -1005,7 +1005,7 @@ func PokeHTTP(host string, port int, path string, params *HTTPPokeParams) HTTPPo
ret.Code = resp.StatusCode ret.Code = resp.StatusCode
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
ret.Status = HTTPError ret.Status = HTTPError
ret.Error = fmt.Errorf("error reading HTTP body: %v", err) ret.Error = fmt.Errorf("error reading HTTP body: %v", err)

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"regexp" "regexp"
@ -116,7 +116,7 @@ func (d *Dialer) DialContainerPort(ctx context.Context, addr Addr) (conn net.Con
} }
errorStream.Close() errorStream.Close()
go func() { go func() {
message, err := ioutil.ReadAll(errorStream) message, err := io.ReadAll(errorStream)
switch { switch {
case err != nil: case err != nil:
klog.ErrorS(err, "error reading from error stream") klog.ErrorS(err, "error reading from error stream")

View File

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
@ -102,7 +101,7 @@ func GetSigner(provider string) (ssh.Signer, error) {
} }
func makePrivateKeySignerFromFile(key string) (ssh.Signer, error) { func makePrivateKeySignerFromFile(key string) (ssh.Signer, error) {
buffer, err := ioutil.ReadFile(key) buffer, err := os.ReadFile(key)
if err != nil { if err != nil {
return nil, fmt.Errorf("error reading SSH key %s: '%v'", key, err) return nil, fmt.Errorf("error reading SSH key %s: '%v'", key, err)
} }

View File

@ -22,7 +22,6 @@ import (
"errors" "errors"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"math" "math"
"os" "os"
"sort" "sort"
@ -449,7 +448,7 @@ func AfterReadingAllFlags(t *TestContextType) {
if len(t.Host) == 0 && len(t.KubeConfig) == 0 { if len(t.Host) == 0 && len(t.KubeConfig) == 0 {
// Check if we can use the in-cluster config // Check if we can use the in-cluster config
if clusterConfig, err := restclient.InClusterConfig(); err == nil { if clusterConfig, err := restclient.InClusterConfig(); err == nil {
if tempFile, err := ioutil.TempFile(os.TempDir(), "kubeconfig-"); err == nil { if tempFile, err := os.CreateTemp(os.TempDir(), "kubeconfig-"); err == nil {
kubeConfig := createKubeConfig(clusterConfig) kubeConfig := createKubeConfig(clusterConfig)
clientcmd.WriteToFile(*kubeConfig, tempFile.Name()) clientcmd.WriteToFile(*kubeConfig, tempFile.Name())
t.KubeConfig = tempFile.Name() t.KubeConfig = tempFile.Name()

View File

@ -29,7 +29,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/fs" "io/fs"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -122,7 +121,7 @@ func (r RootFileSource) ReadTestFile(filePath string) ([]byte, error) {
} else { } else {
fullPath = filepath.Join(r.Root, filePath) fullPath = filepath.Join(r.Root, filePath)
} }
data, err := ioutil.ReadFile(fullPath) data, err := os.ReadFile(fullPath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
// Not an error (yet), some other provider may have the file. // Not an error (yet), some other provider may have the file.
return nil, nil return nil, nil

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"reflect" "reflect"
"time" "time"
@ -89,7 +89,7 @@ func testAgent(f *framework.Framework, kubeClient clientset.Interface) {
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
framework.Failf("Stackdriver Metadata API returned error status: %s", resp.Status) framework.Failf("Stackdriver Metadata API returned error status: %s", resp.Status)
} }
metadataAPIResponse, err := ioutil.ReadAll(resp.Body) metadataAPIResponse, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
framework.Failf("Failed to read response from Stackdriver Metadata API: %s", err) framework.Failf("Failed to read response from Stackdriver Metadata API: %s", err)
} }

View File

@ -24,7 +24,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"net" "net"
"net/http" "net/http"
@ -280,7 +279,7 @@ var _ = SIGDescribe("Kubectl client", func() {
} }
framework.Logf("%s modified at %s (current time: %s)", path, info.ModTime(), time.Now()) framework.Logf("%s modified at %s (current time: %s)", path, info.ModTime(), time.Now())
data, readError := ioutil.ReadFile(path) data, readError := os.ReadFile(path)
if readError != nil { if readError != nil {
framework.Logf("%s error: %v", path, readError) framework.Logf("%s error: %v", path, readError)
} else { } else {
@ -691,11 +690,11 @@ var _ = SIGDescribe("Kubectl client", func() {
// Build a kubeconfig file that will make use of the injected ca and token, // Build a kubeconfig file that will make use of the injected ca and token,
// but point at the DNS host and the default namespace // but point at the DNS host and the default namespace
tmpDir, err := ioutil.TempDir("", "icc-override") tmpDir, err := os.MkdirTemp("", "icc-override")
overrideKubeconfigName := "icc-override.kubeconfig" overrideKubeconfigName := "icc-override.kubeconfig"
framework.ExpectNoError(err) framework.ExpectNoError(err)
defer func() { os.Remove(tmpDir) }() defer func() { os.Remove(tmpDir) }()
framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, overrideKubeconfigName), []byte(` framework.ExpectNoError(os.WriteFile(filepath.Join(tmpDir, overrideKubeconfigName), []byte(`
kind: Config kind: Config
apiVersion: v1 apiVersion: v1
clusters: clusters:
@ -719,14 +718,14 @@ users:
framework.Logf("copying override kubeconfig to the %s pod", simplePodName) framework.Logf("copying override kubeconfig to the %s pod", simplePodName)
framework.RunKubectlOrDie(ns, "cp", filepath.Join(tmpDir, overrideKubeconfigName), ns+"/"+simplePodName+":/tmp/") framework.RunKubectlOrDie(ns, "cp", filepath.Join(tmpDir, overrideKubeconfigName), ns+"/"+simplePodName+":/tmp/")
framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, "invalid-configmap-with-namespace.yaml"), []byte(` framework.ExpectNoError(os.WriteFile(filepath.Join(tmpDir, "invalid-configmap-with-namespace.yaml"), []byte(`
kind: ConfigMap kind: ConfigMap
apiVersion: v1 apiVersion: v1
metadata: metadata:
name: "configmap with namespace and invalid name" name: "configmap with namespace and invalid name"
namespace: configmap-namespace namespace: configmap-namespace
`), os.FileMode(0755))) `), os.FileMode(0755)))
framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, "invalid-configmap-without-namespace.yaml"), []byte(` framework.ExpectNoError(os.WriteFile(filepath.Join(tmpDir, "invalid-configmap-without-namespace.yaml"), []byte(`
kind: ConfigMap kind: ConfigMap
apiVersion: v1 apiVersion: v1
metadata: metadata:
@ -1385,7 +1384,7 @@ metadata:
ginkgo.It("should copy a file from a running Pod", func() { ginkgo.It("should copy a file from a running Pod", func() {
remoteContents := "foobar\n" remoteContents := "foobar\n"
podSource := fmt.Sprintf("%s:/root/foo/bar/foo.bar", busyboxPodName) podSource := fmt.Sprintf("%s:/root/foo/bar/foo.bar", busyboxPodName)
tempDestination, err := ioutil.TempFile(os.TempDir(), "copy-foobar") tempDestination, err := os.CreateTemp(os.TempDir(), "copy-foobar")
if err != nil { if err != nil {
framework.Failf("Failed creating temporary destination file: %v", err) framework.Failf("Failed creating temporary destination file: %v", err)
} }
@ -1393,7 +1392,7 @@ metadata:
ginkgo.By("specifying a remote filepath " + podSource + " on the pod") ginkgo.By("specifying a remote filepath " + podSource + " on the pod")
framework.RunKubectlOrDie(ns, "cp", podSource, tempDestination.Name()) framework.RunKubectlOrDie(ns, "cp", podSource, tempDestination.Name())
ginkgo.By("verifying that the contents of the remote file " + podSource + " have been copied to a local file " + tempDestination.Name()) ginkgo.By("verifying that the contents of the remote file " + podSource + " have been copied to a local file " + tempDestination.Name())
localData, err := ioutil.ReadAll(tempDestination) localData, err := io.ReadAll(tempDestination)
if err != nil { if err != nil {
framework.Failf("Failed reading temporary local file: %v", err) framework.Failf("Failed reading temporary local file: %v", err)
} }
@ -1648,7 +1647,7 @@ metadata:
*/ */
framework.ConformanceIt("should support --unix-socket=/path ", func() { framework.ConformanceIt("should support --unix-socket=/path ", func() {
ginkgo.By("Starting the proxy") ginkgo.By("Starting the proxy")
tmpdir, err := ioutil.TempDir("", "kubectl-proxy-unix") tmpdir, err := os.MkdirTemp("", "kubectl-proxy-unix")
if err != nil { if err != nil {
framework.Failf("Failed to create temporary directory: %v", err) framework.Failf("Failed to create temporary directory: %v", err)
} }
@ -1958,7 +1957,7 @@ func curlTransport(url string, transport *http.Transport) (string, error) {
return "", err return "", err
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -23,7 +23,7 @@ import (
"context" "context"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"os/exec" "os/exec"
"regexp" "regexp"
@ -231,7 +231,7 @@ func doTestConnectSendDisconnect(bindAddress string, f *framework.Framework) {
}() }()
ginkgo.By("Reading data from the local port") ginkgo.By("Reading data from the local port")
fromServer, err := ioutil.ReadAll(conn) fromServer, err := io.ReadAll(conn)
if err != nil { if err != nil {
framework.Failf("Unexpected error reading data from the server: %v", err) framework.Failf("Unexpected error reading data from the server: %v", err)
} }
@ -323,7 +323,7 @@ func doTestMustConnectSendDisconnect(bindAddress string, f *framework.Framework)
fmt.Fprint(conn, "abc") fmt.Fprint(conn, "abc")
ginkgo.By("Reading data from the local port") ginkgo.By("Reading data from the local port")
fromServer, err := ioutil.ReadAll(conn) fromServer, err := io.ReadAll(conn)
if err != nil { if err != nil {
framework.Failf("Unexpected error reading data from the server: %v", err) framework.Failf("Unexpected error reading data from the server: %v", err)
} }

View File

@ -19,7 +19,7 @@ package network
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -175,7 +175,7 @@ func prepareResourceWithReplacedString(inputFile, old, new string) string {
f, err := os.Open(inputFile) f, err := os.Open(inputFile)
framework.ExpectNoError(err, "failed to open file: %s", inputFile) framework.ExpectNoError(err, "failed to open file: %s", inputFile)
defer f.Close() defer f.Close()
data, err := ioutil.ReadAll(f) data, err := io.ReadAll(f)
framework.ExpectNoError(err, "failed to read from file: %s", inputFile) framework.ExpectNoError(err, "failed to read from file: %s", inputFile)
podYaml := strings.Replace(string(data), old, new, 1) podYaml := strings.Replace(string(data), old, new, 1)
return podYaml return podYaml

View File

@ -19,7 +19,7 @@ package scale
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "os"
"sync" "sync"
"time" "time"
@ -316,7 +316,7 @@ func (f *IngressScaleFramework) dumpLatencies() {
formattedData := f.GetFormattedLatencies() formattedData := f.GetFormattedLatencies()
if f.OutputFile != "" { if f.OutputFile != "" {
f.Logger.Infof("Dumping scale test latencies to file %s...", f.OutputFile) f.Logger.Infof("Dumping scale test latencies to file %s...", f.OutputFile)
ioutil.WriteFile(f.OutputFile, []byte(formattedData), 0644) os.WriteFile(f.OutputFile, []byte(formattedData), 0644)
return return
} }
f.Logger.Infof("\n%v", formattedData) f.Logger.Infof("\n%v", formattedData)

View File

@ -20,7 +20,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"time" "time"
@ -123,7 +123,7 @@ func (reporter *ProgressReporter) postProgressToURL(b []byte) {
klog.Errorf("Unexpected response when posting progress update to %v: %v", reporter.progressURL, resp.StatusCode) klog.Errorf("Unexpected response when posting progress update to %v: %v", reporter.progressURL, resp.StatusCode)
if resp.Body != nil { if resp.Body != nil {
defer resp.Body.Close() defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body) respBody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
klog.Errorf("Failed to read response body from posting progress: %v", err) klog.Errorf("Failed to read response body from posting progress: %v", err)
return return

View File

@ -22,7 +22,6 @@ package drivers
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -79,7 +78,7 @@ func createGCESecrets(client clientset.Interface, ns string) {
framework.ExpectNoError(err, "error copying service account key: %s\nstdout: %s\nstderr: %s", err, stdout, stderr) framework.ExpectNoError(err, "error copying service account key: %s\nstdout: %s\nstderr: %s", err, stdout, stderr)
defer shredFile(saFile) defer shredFile(saFile)
// Create Secret with this Service Account // Create Secret with this Service Account
fileBytes, err := ioutil.ReadFile(saFile) fileBytes, err := os.ReadFile(saFile)
framework.ExpectNoError(err, "Failed to read file %v", saFile) framework.ExpectNoError(err, "Failed to read file %v", saFile)
s := &v1.Secret{ s := &v1.Secret{

View File

@ -21,7 +21,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"sync" "sync"
@ -220,7 +219,7 @@ func dial(ctx context.Context, prefix string, dialer httpstream.Dialer, port int
} }
errorStream.Close() errorStream.Close()
go func() { go func() {
message, err := ioutil.ReadAll(errorStream) message, err := io.ReadAll(errorStream)
switch { switch {
case err != nil: case err != nil:
klog.Errorf("%s: error reading from error stream: %v", prefix, err) klog.Errorf("%s: error reading from error stream: %v", prefix, err)

View File

@ -21,7 +21,7 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "os"
"time" "time"
storagev1 "k8s.io/api/storage/v1" storagev1 "k8s.io/api/storage/v1"
@ -182,7 +182,7 @@ func loadDriverDefinition(filename string) (*driverDefinition, error) {
if filename == "" { if filename == "" {
return nil, fmt.Errorf("missing file name") return nil, fmt.Errorf("missing file name")
} }
data, err := ioutil.ReadFile(filename) data, err := os.ReadFile(filename)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -339,7 +339,7 @@ func (d *driverDefinition) GetTimeouts() *framework.TimeoutContext {
} }
func loadSnapshotClass(filename string) (*unstructured.Unstructured, error) { func loadSnapshotClass(filename string) (*unstructured.Unstructured, error) {
data, err := ioutil.ReadFile(filename) data, err := os.ReadFile(filename)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -18,7 +18,7 @@ package e2e
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"path" "path"
"time" "time"
@ -80,7 +80,7 @@ func gatherTestSuiteMetrics() error {
metricsJSON := metricsForE2E.PrintJSON() metricsJSON := metricsForE2E.PrintJSON()
if framework.TestContext.ReportDir != "" { if framework.TestContext.ReportDir != "" {
filePath := path.Join(framework.TestContext.ReportDir, "MetricsForE2ESuite_"+time.Now().Format(time.RFC3339)+".json") filePath := path.Join(framework.TestContext.ReportDir, "MetricsForE2ESuite_"+time.Now().Format(time.RFC3339)+".json")
if err := ioutil.WriteFile(filePath, []byte(metricsJSON), 0644); err != nil { if err := os.WriteFile(filePath, []byte(metricsJSON), 0644); err != nil {
return fmt.Errorf("error writing to %q: %v", filePath, err) return fmt.Errorf("error writing to %q: %v", filePath, err)
} }
} else { } else {

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"path/filepath" "path/filepath"
"sync" "sync"
@ -124,7 +124,7 @@ func (t *CassandraUpgradeTest) listUsers() ([]string, error) {
} }
defer r.Body.Close() defer r.Body.Close()
if r.StatusCode != http.StatusOK { if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body) b, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -146,7 +146,7 @@ func (t *CassandraUpgradeTest) addUser(name string) error {
} }
defer r.Body.Close() defer r.Body.Close()
if r.StatusCode != http.StatusOK { if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body) b, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return err return err
} }

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"path/filepath" "path/filepath"
"sync" "sync"
@ -118,7 +118,7 @@ func (t *EtcdUpgradeTest) listUsers() ([]string, error) {
} }
defer r.Body.Close() defer r.Body.Close()
if r.StatusCode != http.StatusOK { if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body) b, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -139,7 +139,7 @@ func (t *EtcdUpgradeTest) addUser(name string) error {
} }
defer r.Body.Close() defer r.Body.Close()
if r.StatusCode != http.StatusOK { if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body) b, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return err return err
} }

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -187,7 +187,7 @@ func (t *MySQLUpgradeTest) addName(name string) error {
} }
defer r.Body.Close() defer r.Body.Close()
if r.StatusCode != http.StatusOK { if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body) b, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return err return err
} }
@ -205,7 +205,7 @@ func (t *MySQLUpgradeTest) countNames() (int, error) {
} }
defer r.Body.Close() defer r.Body.Close()
if r.StatusCode != http.StatusOK { if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body) b, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return 0, err return 0, err
} }

View File

@ -41,7 +41,6 @@ package windows
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path" "path"
@ -245,7 +244,7 @@ func retrieveCRDManifestFileContents(f *framework.Framework, node v1.Node) strin
func deployGmsaWebhook(f *framework.Framework, deployScriptPath string) (func(), error) { func deployGmsaWebhook(f *framework.Framework, deployScriptPath string) (func(), error) {
cleanUpFunc := func() {} cleanUpFunc := func() {}
tempDir, err := ioutil.TempDir("", "") tempDir, err := os.MkdirTemp("", "")
if err != nil { if err != nil {
return cleanUpFunc, fmt.Errorf("unable to create temp dir: %w", err) return cleanUpFunc, fmt.Errorf("unable to create temp dir: %w", err)
} }
@ -287,7 +286,7 @@ func deployGmsaWebhook(f *framework.Framework, deployScriptPath string) (func(),
func createGmsaCustomResource(ns string, crdManifestContents string) (func(), error) { func createGmsaCustomResource(ns string, crdManifestContents string) (func(), error) {
cleanUpFunc := func() {} cleanUpFunc := func() {}
tempFile, err := ioutil.TempFile("", "") tempFile, err := os.CreateTemp("", "")
if err != nil { if err != nil {
return cleanUpFunc, fmt.Errorf("unable to create temp file: %w", err) return cleanUpFunc, fmt.Errorf("unable to create temp file: %w", err)
} }

View File

@ -19,8 +19,8 @@ package windows
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os"
) )
// downloadFile saves a remote URL to a local temp file, and returns its path. // downloadFile saves a remote URL to a local temp file, and returns its path.
@ -32,7 +32,7 @@ func downloadFile(url string) (string, error) {
} }
defer response.Body.Close() defer response.Body.Close()
tempFile, err := ioutil.TempFile("", "") tempFile, err := os.CreateTemp("", "")
if err != nil { if err != nil {
return "", fmt.Errorf("unable to create temp file: %w", err) return "", fmt.Errorf("unable to create temp file: %w", err)
} }

View File

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"regexp" "regexp"
@ -118,7 +117,7 @@ profile e2e-node-apparmor-test-audit-write flags=(attach_disconnected) {
` `
func loadTestProfiles() error { func loadTestProfiles() error {
f, err := ioutil.TempFile("/tmp", "apparmor") f, err := os.CreateTemp("/tmp", "apparmor")
if err != nil { if err != nil {
return fmt.Errorf("failed to open temp file: %v", err) return fmt.Errorf("failed to open temp file: %v", err)
} }

View File

@ -22,7 +22,7 @@ package e2enode
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "os"
"path" "path"
"sort" "sort"
"strconv" "strconv"
@ -51,7 +51,7 @@ func dumpDataToFile(data interface{}, labels map[string]string, prefix string) {
fileName := path.Join(framework.TestContext.ReportDir, fmt.Sprintf("%s-%s-%s.json", prefix, framework.TestContext.ReportPrefix, testName)) fileName := path.Join(framework.TestContext.ReportDir, fmt.Sprintf("%s-%s-%s.json", prefix, framework.TestContext.ReportPrefix, testName))
labels["timestamp"] = strconv.FormatInt(time.Now().UTC().Unix(), 10) labels["timestamp"] = strconv.FormatInt(time.Now().UTC().Unix(), 10)
framework.Logf("Dumping perf data for test %q to %q.", testName, fileName) framework.Logf("Dumping perf data for test %q to %q.", testName, fileName)
if err := ioutil.WriteFile(fileName, []byte(framework.PrettyPrintJSON(data)), 0644); err != nil { if err := os.WriteFile(fileName, []byte(framework.PrettyPrintJSON(data)), 0644); err != nil {
framework.Logf("Failed to write perf data for test %q to %q: %v", testName, fileName, err) framework.Logf("Failed to write perf data for test %q to %q: %v", testName, fileName, err)
} }
} }

View File

@ -19,7 +19,6 @@ package e2enode
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -306,8 +305,8 @@ func rewriteCheckpointAsV1(dir, name string) error {
// TODO: why `checkpointManager.CreateCheckpoint(name, cpV1)` doesn't seem to work? // TODO: why `checkpointManager.CreateCheckpoint(name, cpV1)` doesn't seem to work?
ckPath := filepath.Join(dir, name) ckPath := filepath.Join(dir, name)
ioutil.WriteFile(filepath.Join("/tmp", name), blob, 0600) os.WriteFile(filepath.Join("/tmp", name), blob, 0600)
return ioutil.WriteFile(ckPath, blob, 0600) return os.WriteFile(ckPath, blob, 0600)
} }
func convertPodDeviceEntriesToV1(entries []checkpoint.PodDevicesEntry) []checkpoint.PodDevicesEntryV1 { func convertPodDeviceEntriesToV1(entries []checkpoint.PodDevicesEntry) []checkpoint.PodDevicesEntryV1 {

View File

@ -27,7 +27,6 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"math/rand" "math/rand"
"os" "os"
@ -260,7 +259,7 @@ func validateSystem() error {
} }
func maskLocksmithdOnCoreos() { func maskLocksmithdOnCoreos() {
data, err := ioutil.ReadFile("/etc/os-release") data, err := os.ReadFile("/etc/os-release")
if err != nil { if err != nil {
// Not all distros contain this file. // Not all distros contain this file.
klog.Infof("Could not read /etc/os-release: %v", err) klog.Infof("Could not read /etc/os-release: %v", err)
@ -350,7 +349,7 @@ func getAPIServerClient() (*clientset.Clientset, error) {
// loadSystemSpecFromFile returns the system spec from the file with the // loadSystemSpecFromFile returns the system spec from the file with the
// filename. // filename.
func loadSystemSpecFromFile(filename string) (*system.SysSpec, error) { func loadSystemSpecFromFile(filename string) (*system.SysSpec, error) {
b, err := ioutil.ReadFile(filename) b, err := os.ReadFile(filename)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -21,7 +21,6 @@ package main
import ( import (
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os/exec" "os/exec"
"regexp" "regexp"
@ -146,7 +145,7 @@ const cmdlineCGroupMemory = `cgroup_enable=memory`
// kernel checks that the kernel has been configured correctly to support the required cgroup features // kernel checks that the kernel has been configured correctly to support the required cgroup features
func kernel() error { func kernel() error {
cmdline, err := ioutil.ReadFile("/proc/cmdline") cmdline, err := os.ReadFile("/proc/cmdline")
if err != nil { if err != nil {
return printError("Kernel Command Line Check %s: Could not check /proc/cmdline", failed) return printError("Kernel Command Line Check %s: Could not check /proc/cmdline", failed)
} }

View File

@ -19,7 +19,6 @@ package gcp
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"strconv" "strconv"
@ -137,7 +136,7 @@ var _ = SIGDescribe("GKE system requirements [NodeConformance][Feature:GKEEnv][N
// getPPID returns the PPID for the pid. // getPPID returns the PPID for the pid.
func getPPID(pid int) (int, error) { func getPPID(pid int) (int, error) {
statusFile := "/proc/" + strconv.Itoa(pid) + "/status" statusFile := "/proc/" + strconv.Itoa(pid) + "/status"
content, err := ioutil.ReadFile(statusFile) content, err := os.ReadFile(statusFile)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -183,7 +182,7 @@ func getCmdToProcessMap() (map[string][]process, error) {
if err != nil { if err != nil {
continue continue
} }
content, err := ioutil.ReadFile("/proc/" + dir + "/cmdline") content, err := os.ReadFile("/proc/" + dir + "/cmdline")
if err != nil || len(content) == 0 { if err != nil || len(content) == 0 {
continue continue
} }

View File

@ -18,7 +18,6 @@ package kubeletconfig
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -49,7 +48,7 @@ func GetCurrentKubeletConfigFromFile() (*kubeletconfig.KubeletConfiguration, err
return nil, err return nil, err
} }
data, err := ioutil.ReadFile(kubeletConfigFilePath) data, err := os.ReadFile(kubeletConfigFilePath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get the kubelet config from the file %q: %w", kubeletConfigFilePath, err) return nil, fmt.Errorf("failed to get the kubelet config from the file %q: %w", kubeletConfigFilePath, err)
} }
@ -87,7 +86,7 @@ func WriteKubeletConfigFile(kubeletConfig *kubeletconfig.KubeletConfiguration) e
return err return err
} }
if err := ioutil.WriteFile(kubeletConfigFilePath, data, 0644); err != nil { if err := os.WriteFile(kubeletConfigFilePath, data, 0644); err != nil {
return fmt.Errorf("failed to write the kubelet file to %q: %w", kubeletConfigFilePath, err) return fmt.Errorf("failed to write the kubelet file to %q: %w", kubeletConfigFilePath, err)
} }

View File

@ -22,7 +22,7 @@ package e2enode
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
@ -73,7 +73,7 @@ var _ = SIGDescribe("Node Container Manager [Serial]", func() {
}) })
func expectFileValToEqual(filePath string, expectedValue, delta int64) error { func expectFileValToEqual(filePath string, expectedValue, delta int64) error {
out, err := ioutil.ReadFile(filePath) out, err := os.ReadFile(filePath)
if err != nil { if err != nil {
return fmt.Errorf("failed to read file %q", filePath) return fmt.Errorf("failed to read file %q", filePath)
} }

View File

@ -18,7 +18,6 @@ package e2enode
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@ -78,7 +77,7 @@ func (R *numaPodResources) String() string {
} }
func getCPUsPerNUMANode(nodeNum int) ([]int, error) { func getCPUsPerNUMANode(nodeNum int) ([]int, error) {
nodeCPUList, err := ioutil.ReadFile(fmt.Sprintf("/sys/devices/system/node/node%d/cpulist", nodeNum)) nodeCPUList, err := os.ReadFile(fmt.Sprintf("/sys/devices/system/node/node%d/cpulist", nodeNum))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -230,7 +229,7 @@ type pciDeviceInfo struct {
func getPCIDeviceInfo(sysPCIDir string) ([]pciDeviceInfo, error) { func getPCIDeviceInfo(sysPCIDir string) ([]pciDeviceInfo, error) {
var pciDevs []pciDeviceInfo var pciDevs []pciDeviceInfo
entries, err := ioutil.ReadDir(sysPCIDir) entries, err := os.ReadDir(sysPCIDir)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -251,7 +250,7 @@ func getPCIDeviceInfo(sysPCIDir string) ([]pciDeviceInfo, error) {
return nil, err return nil, err
} }
content, err := ioutil.ReadFile(filepath.Join(sysPCIDir, entry.Name(), "numa_node")) content, err := os.ReadFile(filepath.Join(sysPCIDir, entry.Name(), "numa_node"))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -20,7 +20,6 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strings" "strings"
"time" "time"
@ -829,7 +828,7 @@ func requireLackOfSRIOVDevices() {
} }
func getOnlineCPUs() (cpuset.CPUSet, error) { func getOnlineCPUs() (cpuset.CPUSet, error) {
onlineCPUList, err := ioutil.ReadFile("/sys/devices/system/cpu/online") onlineCPUList, err := os.ReadFile("/sys/devices/system/cpu/online")
if err != nil { if err != nil {
return cpuset.CPUSet{}, err return cpuset.CPUSet{}, err
} }

View File

@ -20,7 +20,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -71,7 +70,7 @@ func copyKubeletConfigIfExists(kubeletConfigFile, dstDir string) error {
// CreateTestArchive creates the archive package for the node e2e test. // CreateTestArchive creates the archive package for the node e2e test.
func CreateTestArchive(suite TestSuite, systemSpecName, kubeletConfigFile string) (string, error) { func CreateTestArchive(suite TestSuite, systemSpecName, kubeletConfigFile string) (string, error) {
klog.V(2).Infof("Building archive...") klog.V(2).Infof("Building archive...")
tardir, err := ioutil.TempDir("", "node-e2e-archive") tardir, err := os.MkdirTemp("", "node-e2e-archive")
if err != nil { if err != nil {
return "", fmt.Errorf("failed to create temporary directory %v", err) return "", fmt.Errorf("failed to create temporary directory %v", err)
} }

View File

@ -23,7 +23,7 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"log" "log"
"os" "os"
"sort" "sort"
@ -486,7 +486,7 @@ func getPidFromPidFile(pidFile string) (int, error) {
} }
defer file.Close() defer file.Close()
data, err := ioutil.ReadAll(file) data, err := io.ReadAll(file)
if err != nil { if err != nil {
return 0, fmt.Errorf("error reading pid file %s: %v", pidFile, err) return 0, fmt.Errorf("error reading pid file %s: %v", pidFile, err)
} }

View File

@ -24,7 +24,6 @@ import (
"context" "context"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"math/rand" "math/rand"
"net/http" "net/http"
"os" "os"
@ -323,7 +322,7 @@ func prepareGceImages() (*internalImageConfig, error) {
configPath = filepath.Join(*imageConfigDir, *imageConfigFile) configPath = filepath.Join(*imageConfigDir, *imageConfigFile)
} }
imageConfigData, err := ioutil.ReadFile(configPath) imageConfigData, err := os.ReadFile(configPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("Could not read image config file provided: %v", err) return nil, fmt.Errorf("Could not read image config file provided: %v", err)
} }
@ -895,7 +894,7 @@ func parseInstanceMetadata(str string) map[string]string {
if *imageConfigDir != "" { if *imageConfigDir != "" {
metaPath = filepath.Join(*imageConfigDir, metaPath) metaPath = filepath.Join(*imageConfigDir, metaPath)
} }
v, err := ioutil.ReadFile(metaPath) v, err := os.ReadFile(metaPath)
if err != nil { if err != nil {
klog.Fatalf("Failed to read metadata file %q: %v", metaPath, err) klog.Fatalf("Failed to read metadata file %q: %v", metaPath, err)
continue continue

View File

@ -18,7 +18,6 @@ package e2enode
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"time" "time"
@ -81,7 +80,7 @@ var _ = SIGDescribe("Container Runtime Conformance Test", func() {
} }
configFile := filepath.Join(services.KubeletRootDirectory, "config.json") configFile := filepath.Join(services.KubeletRootDirectory, "config.json")
err := ioutil.WriteFile(configFile, []byte(auth), 0644) err := os.WriteFile(configFile, []byte(auth), 0644)
framework.ExpectNoError(err) framework.ExpectNoError(err)
defer os.Remove(configFile) defer os.Remove(configFile)

View File

@ -18,7 +18,6 @@ package services
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"k8s.io/apiserver/pkg/storage/storagebackend" "k8s.io/apiserver/pkg/storage/storagebackend"
@ -76,12 +75,12 @@ func (a *APIServer) Start() error {
o.Authentication.TokenFile.TokenFile = tokenFilePath o.Authentication.TokenFile.TokenFile = tokenFilePath
o.Admission.GenericAdmission.DisablePlugins = []string{"ServiceAccount", "TaintNodesByCondition"} o.Admission.GenericAdmission.DisablePlugins = []string{"ServiceAccount", "TaintNodesByCondition"}
saSigningKeyFile, err := ioutil.TempFile("/tmp", "insecure_test_key") saSigningKeyFile, err := os.CreateTemp("/tmp", "insecure_test_key")
if err != nil { if err != nil {
return fmt.Errorf("create temp file failed: %v", err) return fmt.Errorf("create temp file failed: %v", err)
} }
defer os.RemoveAll(saSigningKeyFile.Name()) defer os.RemoveAll(saSigningKeyFile.Name())
if err = ioutil.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil { if err = os.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
return fmt.Errorf("write file %s failed: %v", saSigningKeyFile.Name(), err) return fmt.Errorf("write file %s failed: %v", saSigningKeyFile.Name(), err)
} }
o.ServiceAccountSigningKeyFile = saSigningKeyFile.Name() o.ServiceAccountSigningKeyFile = saSigningKeyFile.Name()
@ -143,5 +142,5 @@ func getAPIServerHealthCheckURL() string {
func generateTokenFile(tokenFilePath string) error { func generateTokenFile(tokenFilePath string) error {
tokenFile := fmt.Sprintf("%s,kubelet,uid,system:masters\n", framework.TestContext.BearerToken) tokenFile := fmt.Sprintf("%s,kubelet,uid,system:masters\n", framework.TestContext.BearerToken)
return ioutil.WriteFile(tokenFilePath, []byte(tokenFile), 0644) return os.WriteFile(tokenFilePath, []byte(tokenFile), 0644)
} }

View File

@ -19,7 +19,6 @@ package services
import ( import (
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -327,7 +326,7 @@ func writeKubeletConfigFile(internal *kubeletconfig.KubeletConfiguration, path s
return err return err
} }
// write the file // write the file
if err := ioutil.WriteFile(path, data, 0755); err != nil { if err := os.WriteFile(path, data, 0755); err != nil {
return err return err
} }
return nil return nil
@ -339,7 +338,7 @@ func createPodDirectory() (string, error) {
if err != nil { if err != nil {
return "", fmt.Errorf("failed to get current working directory: %v", err) return "", fmt.Errorf("failed to get current working directory: %v", err)
} }
path, err := ioutil.TempDir(cwd, "static-pods") path, err := os.MkdirTemp(cwd, "static-pods")
if err != nil { if err != nil {
return "", fmt.Errorf("failed to create static pod directory: %v", err) return "", fmt.Errorf("failed to create static pod directory: %v", err)
} }
@ -366,7 +365,7 @@ contexts:
name: local-context name: local-context
current-context: local-context`, framework.TestContext.BearerToken, getAPIServerClientURL())) current-context: local-context`, framework.TestContext.BearerToken, getAPIServerClientURL()))
if err := ioutil.WriteFile(path, kubeconfig, 0666); err != nil { if err := os.WriteFile(path, kubeconfig, 0666); err != nil {
return err return err
} }
return nil return nil

View File

@ -18,7 +18,6 @@ package services
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path" "path"
@ -167,7 +166,7 @@ func (e *E2EServices) collectLogFiles() {
if err != nil { if err != nil {
klog.Errorf("failed to get %q from journald: %v, %v", targetFileName, string(out), err) klog.Errorf("failed to get %q from journald: %v, %v", targetFileName, string(out), err)
} else { } else {
if err = ioutil.WriteFile(targetLink, out, 0644); err != nil { if err = os.WriteFile(targetLink, out, 0644); err != nil {
klog.Errorf("failed to write logs to %q: %v", targetLink, err) klog.Errorf("failed to write logs to %q: %v", targetLink, err)
} }
} }

View File

@ -18,7 +18,7 @@ package e2enode
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"strings" "strings"
"time" "time"
@ -434,7 +434,7 @@ func recordSystemCgroupProcesses() {
if IsCgroup2UnifiedMode() { if IsCgroup2UnifiedMode() {
filePattern = "/sys/fs/cgroup/%s/cgroup.procs" filePattern = "/sys/fs/cgroup/%s/cgroup.procs"
} }
pids, err := ioutil.ReadFile(fmt.Sprintf(filePattern, cgroup)) pids, err := os.ReadFile(fmt.Sprintf(filePattern, cgroup))
if err != nil { if err != nil {
framework.Logf("Failed to read processes in cgroup %s: %v", name, err) framework.Logf("Failed to read processes in cgroup %s: %v", name, err)
continue continue
@ -443,7 +443,7 @@ func recordSystemCgroupProcesses() {
framework.Logf("Processes in %s cgroup (%s):", name, cgroup) framework.Logf("Processes in %s cgroup (%s):", name, cgroup)
for _, pid := range strings.Fields(string(pids)) { for _, pid := range strings.Fields(string(pids)) {
path := fmt.Sprintf("/proc/%s/cmdline", pid) path := fmt.Sprintf("/proc/%s/cmdline", pid)
cmd, err := ioutil.ReadFile(path) cmd, err := os.ReadFile(path)
if err != nil { if err != nil {
framework.Logf(" ginkgo.Failed to read %s: %v", path, err) framework.Logf(" ginkgo.Failed to read %s: %v", path, err)
} else { } else {

View File

@ -19,7 +19,7 @@ package e2enode
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "os"
"os/exec" "os/exec"
"regexp" "regexp"
"strconv" "strconv"
@ -478,7 +478,7 @@ func getSRIOVDevicePluginConfigMap(cmFile string) *v1.ConfigMap {
// the SRIOVDP configuration is hw-dependent, so we allow per-test-host customization. // the SRIOVDP configuration is hw-dependent, so we allow per-test-host customization.
framework.Logf("host-local SRIOV Device Plugin Config Map %q", cmFile) framework.Logf("host-local SRIOV Device Plugin Config Map %q", cmFile)
if cmFile != "" { if cmFile != "" {
data, err = ioutil.ReadFile(cmFile) data, err = os.ReadFile(cmFile)
if err != nil { if err != nil {
framework.Failf("unable to load the SRIOV Device Plugin ConfigMap: %v", err) framework.Failf("unable to load the SRIOV Device Plugin ConfigMap: %v", err)
} }

View File

@ -22,7 +22,7 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os/exec" "os/exec"
"regexp" "regexp"
@ -95,7 +95,7 @@ func getNodeSummary() (*stats.Summary, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
contentsBytes, err := ioutil.ReadAll(resp.Body) contentsBytes, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to read /stats/summary: %+v", resp) return nil, fmt.Errorf("failed to read /stats/summary: %+v", resp)
} }

View File

@ -23,7 +23,6 @@ import (
"go/ast" "go/ast"
"go/parser" "go/parser"
"go/token" "go/token"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@ -237,7 +236,7 @@ func importedGlobalVariableDeclaration(localVariables map[string]ast.Expr, impor
continue continue
} }
files, err := ioutil.ReadDir(importDirectory) files, err := os.ReadDir(importDirectory)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed to read import path directory %s with error %s, skipping\n", importDirectory, err) fmt.Fprintf(os.Stderr, "failed to read import path directory %s with error %s, skipping\n", importDirectory, err)
continue continue

View File

@ -22,7 +22,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"path" "path"
@ -1262,7 +1262,7 @@ func testNoPruningCustomFancy(c *testContext) {
func newV1beta1WebhookHandler(t *testing.T, holder *holder, phase string, converted bool) http.Handler { func newV1beta1WebhookHandler(t *testing.T, holder *holder, phase string, converted bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
return return
@ -1360,7 +1360,7 @@ func newV1beta1WebhookHandler(t *testing.T, holder *holder, phase string, conver
func newV1WebhookHandler(t *testing.T, holder *holder, phase string, converted bool) http.Handler { func newV1WebhookHandler(t *testing.T, holder *holder, phase string, converted bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
return return

View File

@ -22,7 +22,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@ -84,13 +84,13 @@ func testWebhookClientAuth(t *testing.T, enableAggregatorRouting bool) {
t.Fatal(err) t.Fatal(err)
} }
kubeConfigFile, err := ioutil.TempFile("", "admission-config.yaml") kubeConfigFile, err := os.CreateTemp("", "admission-config.yaml")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.Remove(kubeConfigFile.Name()) defer os.Remove(kubeConfigFile.Name())
if err := ioutil.WriteFile(kubeConfigFile.Name(), []byte(` if err := os.WriteFile(kubeConfigFile.Name(), []byte(`
apiVersion: v1 apiVersion: v1
kind: Config kind: Config
users: users:
@ -110,13 +110,13 @@ users:
t.Fatal(err) t.Fatal(err)
} }
admissionConfigFile, err := ioutil.TempFile("", "admission-config.yaml") admissionConfigFile, err := os.CreateTemp("", "admission-config.yaml")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.Remove(admissionConfigFile.Name()) defer os.Remove(admissionConfigFile.Name())
if err := ioutil.WriteFile(admissionConfigFile.Name(), []byte(` if err := os.WriteFile(admissionConfigFile.Name(), []byte(`
apiVersion: apiserver.k8s.io/v1alpha1 apiVersion: apiserver.k8s.io/v1alpha1
kind: AdmissionConfiguration kind: AdmissionConfiguration
plugins: plugins:
@ -247,7 +247,7 @@ func newClientAuthWebhookHandler(t *testing.T, recorder *clientAuthRecorder) htt
} }
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
} }

View File

@ -23,7 +23,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
@ -176,7 +176,7 @@ func TestMutatingWebhookDuplicateOwnerReferences(t *testing.T) {
func newDuplicateOwnerReferencesWebhookHandler(t *testing.T) http.Handler { func newDuplicateOwnerReferencesWebhookHandler(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
} }

View File

@ -23,7 +23,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
@ -179,7 +179,7 @@ func validateManagedFieldsAndDecode(managedFields []metav1.ManagedFieldsEntry) e
func newInvalidManagedFieldsWebhookHandler(t *testing.T) http.Handler { func newInvalidManagedFieldsWebhookHandler(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
} }

View File

@ -22,7 +22,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"sync" "sync"
@ -245,7 +245,7 @@ func newLoadBalanceWebhookHandler(recorder *connectionRecorder) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Proto) fmt.Println(r.Proto)
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, err.Error(), 400) http.Error(w, err.Error(), 400)
} }

View File

@ -22,7 +22,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@ -265,7 +265,7 @@ func testWebhookReinvocationPolicy(t *testing.T, watchCache bool) {
defer webhookServer.Close() defer webhookServer.Close()
// prepare audit policy file // prepare audit policy file
policyFile, err := ioutil.TempFile("", "audit-policy.yaml") policyFile, err := os.CreateTemp("", "audit-policy.yaml")
if err != nil { if err != nil {
t.Fatalf("Failed to create audit policy file: %v", err) t.Fatalf("Failed to create audit policy file: %v", err)
} }
@ -278,7 +278,7 @@ func testWebhookReinvocationPolicy(t *testing.T, watchCache bool) {
} }
// prepare audit log file // prepare audit log file
logFile, err := ioutil.TempFile("", "audit.log") logFile, err := os.CreateTemp("", "audit.log")
if err != nil { if err != nil {
t.Fatalf("Failed to create audit log file: %v", err) t.Fatalf("Failed to create audit log file: %v", err)
} }
@ -536,7 +536,7 @@ func newReinvokeWebhookHandler(recorder *invocationRecorder) http.Handler {
} }
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, err.Error(), 400) http.Error(w, err.Error(), 400)
} }

View File

@ -22,7 +22,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"sort" "sort"
@ -413,7 +413,7 @@ func newTimeoutWebhookHandler(recorder *timeoutRecorder) http.Handler {
} }
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, err.Error(), 400) http.Error(w, err.Error(), 400)
} }

View File

@ -22,7 +22,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -117,7 +116,7 @@ func verifyStatusCode(t *testing.T, verb, URL, body string, expectedStatusCode i
t.Fatalf("unexpected error: %v in req: %v", err, req) t.Fatalf("unexpected error: %v in req: %v", err, req)
} }
defer resp.Body.Close() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
if resp.StatusCode != expectedStatusCode { if resp.StatusCode != expectedStatusCode {
t.Errorf("Expected status %v, but got %v", expectedStatusCode, resp.StatusCode) t.Errorf("Expected status %v, but got %v", expectedStatusCode, resp.StatusCode)
t.Errorf("Body: %v", string(b)) t.Errorf("Body: %v", string(b))
@ -2070,7 +2069,7 @@ func expectPartialObjectMetaEventsProtobuf(t *testing.T, r io.Reader, values ...
metav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) metav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
rs := protobuf.NewRawSerializer(scheme, scheme) rs := protobuf.NewRawSerializer(scheme, scheme)
d := streaming.NewDecoder( d := streaming.NewDecoder(
protobuf.LengthDelimitedFramer.NewFrameReader(ioutil.NopCloser(r)), protobuf.LengthDelimitedFramer.NewFrameReader(io.NopCloser(r)),
rs, rs,
) )
ds := metainternalversionscheme.Codecs.UniversalDeserializer() ds := metainternalversionscheme.Codecs.UniversalDeserializer()
@ -2179,7 +2178,7 @@ func expectPartialObjectMetaV1EventsProtobuf(t *testing.T, r io.Reader, values .
metav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) metav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
rs := protobuf.NewRawSerializer(scheme, scheme) rs := protobuf.NewRawSerializer(scheme, scheme)
d := streaming.NewDecoder( d := streaming.NewDecoder(
protobuf.LengthDelimitedFramer.NewFrameReader(ioutil.NopCloser(r)), protobuf.LengthDelimitedFramer.NewFrameReader(io.NopCloser(r)),
rs, rs,
) )
ds := metainternalversionscheme.Codecs.UniversalDeserializer() ds := metainternalversionscheme.Codecs.UniversalDeserializer()

View File

@ -25,7 +25,6 @@ import (
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"path" "path"
@ -204,10 +203,10 @@ func testClientCA(t *testing.T, recreate bool) {
} }
// when we run this the second time, we know which one we are expecting // when we run this the second time, we know which one we are expecting
if err := ioutil.WriteFile(clientCAFilename, clientCA.CACert, 0644); err != nil { if err := os.WriteFile(clientCAFilename, clientCA.CACert, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(frontProxyCAFilename, frontProxyCA.CACert, 0644); err != nil { if err := os.WriteFile(frontProxyCAFilename, frontProxyCA.CACert, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -492,10 +491,10 @@ func testServingCert(t *testing.T, recreate bool) {
} }
} }
if err := ioutil.WriteFile(path.Join(servingCertPath, "apiserver.key"), serverKey, 0644); err != nil { if err := os.WriteFile(path.Join(servingCertPath, "apiserver.key"), serverKey, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(path.Join(servingCertPath, "apiserver.crt"), serverCert, 0644); err != nil { if err := os.WriteFile(path.Join(servingCertPath, "apiserver.crt"), serverCert, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -522,10 +521,10 @@ func TestSNICert(t *testing.T) {
opts.GenericServerRunOptions.MaxRequestBodyBytes = 1024 * 1024 opts.GenericServerRunOptions.MaxRequestBodyBytes = 1024 * 1024
servingCertPath = opts.SecureServing.ServerCert.CertDirectory servingCertPath = opts.SecureServing.ServerCert.CertDirectory
if err := ioutil.WriteFile(path.Join(servingCertPath, "foo.key"), anotherServerKey, 0644); err != nil { if err := os.WriteFile(path.Join(servingCertPath, "foo.key"), anotherServerKey, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(path.Join(servingCertPath, "foo.crt"), anotherServerCert, 0644); err != nil { if err := os.WriteFile(path.Join(servingCertPath, "foo.crt"), anotherServerCert, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -546,10 +545,10 @@ func TestSNICert(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(path.Join(servingCertPath, "foo.key"), serverKey, 0644); err != nil { if err := os.WriteFile(path.Join(servingCertPath, "foo.key"), serverKey, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(path.Join(servingCertPath, "foo.crt"), serverCert, 0644); err != nil { if err := os.WriteFile(path.Join(servingCertPath, "foo.crt"), serverCert, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -19,7 +19,7 @@ package apiserver
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net/http" "net/http"
"reflect" "reflect"
"strings" "strings"
@ -73,7 +73,7 @@ func TestOpenAPIV3SpecRoundTrip(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
defer resp.Body.Close() defer resp.Body.Close()
bs, err := ioutil.ReadAll(resp.Body) bs, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -217,7 +217,7 @@ func TestOpenAPIV3ProtoRoundtrip(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
defer resp.Body.Close() defer resp.Body.Close()
bs, err := ioutil.ReadAll(resp.Body) bs, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -237,7 +237,7 @@ func TestOpenAPIV3ProtoRoundtrip(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
defer protoResp.Body.Close() defer protoResp.Body.Close()
bs, err = ioutil.ReadAll(protoResp.Body) bs, err = io.ReadAll(protoResp.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -20,7 +20,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"reflect" "reflect"
"strings" "strings"
@ -162,7 +161,7 @@ func TestServerSidePrint(t *testing.T) {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }
cacheDir, err := ioutil.TempDir(os.TempDir(), "test-integration-apiserver-print") cacheDir, err := os.MkdirTemp(os.TempDir(), "test-integration-apiserver-print")
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }

View File

@ -19,7 +19,6 @@ package tracing
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os" "os"
"testing" "testing"
@ -61,13 +60,13 @@ func TestAPIServerTracing(t *testing.T) {
defer srv.Stop() defer srv.Stop()
// Write the configuration for tracing to a file // Write the configuration for tracing to a file
tracingConfigFile, err := ioutil.TempFile("", "tracing-config.yaml") tracingConfigFile, err := os.CreateTemp("", "tracing-config.yaml")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.Remove(tracingConfigFile.Name()) defer os.Remove(tracingConfigFile.Name())
if err := ioutil.WriteFile(tracingConfigFile.Name(), []byte(fmt.Sprintf(` if err := os.WriteFile(tracingConfigFile.Name(), []byte(fmt.Sprintf(`
apiVersion: apiserver.config.k8s.io/v1alpha1 apiVersion: apiserver.config.k8s.io/v1alpha1
kind: TracingConfiguration kind: TracingConfiguration
endpoint: %s`, listener.Addr().String())), os.FileMode(0755)); err != nil { endpoint: %s`, listener.Addr().String())), os.FileMode(0755)); err != nil {

View File

@ -30,7 +30,7 @@ import (
"encoding/json" "encoding/json"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@ -87,7 +87,7 @@ func getTestTokenAuth() authenticator.Request {
} }
func getTestWebhookTokenAuth(serverURL string, customDial utilnet.DialFunc) (authenticator.Request, error) { func getTestWebhookTokenAuth(serverURL string, customDial utilnet.DialFunc) (authenticator.Request, error) {
kubecfgFile, err := ioutil.TempFile("", "webhook-kubecfg") kubecfgFile, err := os.CreateTemp("", "webhook-kubecfg")
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -495,7 +495,7 @@ func TestAuthModeAlwaysAllow(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
if _, ok := r.statusCodes[resp.StatusCode]; !ok { if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r) t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode) t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
@ -643,7 +643,7 @@ func TestAliceNotForbiddenOrUnauthorized(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
if _, ok := r.statusCodes[resp.StatusCode]; !ok { if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r) t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode) t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
@ -742,7 +742,7 @@ func TestUnknownUserIsUnauthorized(t *testing.T) {
if resp.StatusCode != http.StatusUnauthorized { if resp.StatusCode != http.StatusUnauthorized {
t.Logf("case %v", r) t.Logf("case %v", r)
t.Errorf("Expected status %v, but got %v", http.StatusUnauthorized, resp.StatusCode) t.Errorf("Expected status %v, but got %v", http.StatusUnauthorized, resp.StatusCode)
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
t.Errorf("Body: %v", string(b)) t.Errorf("Body: %v", string(b))
} }
}() }()
@ -1047,14 +1047,14 @@ func csrPEM(t *testing.T) []byte {
} }
func newAuthorizerWithContents(t *testing.T, contents string) authorizer.Authorizer { func newAuthorizerWithContents(t *testing.T, contents string) authorizer.Authorizer {
f, err := ioutil.TempFile("", "auth_test") f, err := os.CreateTemp("", "auth_test")
if err != nil { if err != nil {
t.Fatalf("unexpected error creating policyfile: %v", err) t.Fatalf("unexpected error creating policyfile: %v", err)
} }
f.Close() f.Close()
defer os.Remove(f.Name()) defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(contents), 0700); err != nil { if err := os.WriteFile(f.Name(), []byte(contents), 0700); err != nil {
t.Fatalf("unexpected error writing policyfile: %v", err) t.Fatalf("unexpected error writing policyfile: %v", err)
} }
@ -1215,7 +1215,7 @@ func TestNamespaceAuthorization(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
if _, ok := r.statusCodes[resp.StatusCode]; !ok { if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r) t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode) t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
@ -1300,7 +1300,7 @@ func TestKindAuthorization(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
if _, ok := r.statusCodes[resp.StatusCode]; !ok { if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r) t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode) t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
@ -1367,7 +1367,7 @@ func TestReadOnlyAuthorization(t *testing.T) {
if _, ok := r.statusCodes[resp.StatusCode]; !ok { if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r) t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode) t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
t.Errorf("Body: %v", string(b)) t.Errorf("Body: %v", string(b))
} }
}() }()

View File

@ -19,7 +19,7 @@ package auth
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"testing" "testing"
"time" "time"
@ -160,7 +160,7 @@ func TestBootstrapTokenAuth(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
if _, ok := test.request.statusCodes[resp.StatusCode]; !ok { if _, ok := test.request.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", test.name) t.Logf("case %v", test.name)
t.Errorf("Expected status one of %v, but got %v", test.request.statusCodes, resp.StatusCode) t.Errorf("Expected status one of %v, but got %v", test.request.statusCodes, resp.StatusCode)

View File

@ -18,7 +18,6 @@ package auth
import ( import (
"context" "context"
"io/ioutil"
"os" "os"
"testing" "testing"
"time" "time"
@ -36,13 +35,13 @@ import (
) )
func TestDynamicClientBuilder(t *testing.T) { func TestDynamicClientBuilder(t *testing.T) {
tmpfile, err := ioutil.TempFile("/tmp", "key") tmpfile, err := os.CreateTemp("/tmp", "key")
if err != nil { if err != nil {
t.Fatalf("create temp file failed: %v", err) t.Fatalf("create temp file failed: %v", err)
} }
defer os.RemoveAll(tmpfile.Name()) defer os.RemoveAll(tmpfile.Name())
if err = ioutil.WriteFile(tmpfile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil { if err = os.WriteFile(tmpfile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
t.Fatalf("write file %s failed: %v", tmpfile.Name(), err) t.Fatalf("write file %s failed: %v", tmpfile.Name(), err)
} }

View File

@ -19,7 +19,7 @@ package auth
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "os"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -55,7 +55,7 @@ func TestNodeAuthorizer(t *testing.T) {
// Enable DynamicKubeletConfig feature so that Node.Spec.ConfigSource can be set // Enable DynamicKubeletConfig feature so that Node.Spec.ConfigSource can be set
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.DynamicKubeletConfig, true)() defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.DynamicKubeletConfig, true)()
tokenFile, err := ioutil.TempFile("", "kubeconfig") tokenFile, err := os.CreateTemp("", "kubeconfig")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -325,7 +325,7 @@ func ValidateWebhookMetrics(t *testing.T, webhookAddr string) {
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
t.Fatalf("Non-200 response trying to scrape metrics from %s: %v", endpoint.String(), resp) t.Fatalf("Non-200 response trying to scrape metrics from %s: %v", endpoint.String(), resp)
} }
data, err := ioutil.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatalf("Unable to read metrics response: %v", err) t.Fatalf("Unable to read metrics response: %v", err)
} }

View File

@ -20,7 +20,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
gopath "path" gopath "path"
@ -623,7 +622,7 @@ func TestRBAC(t *testing.T) {
t.Errorf("case %d, req %d: %s expected %q got %q", i, j, r, statusCode(r.expectedStatus), statusCode(resp.StatusCode)) t.Errorf("case %d, req %d: %s expected %q got %q", i, j, r, statusCode(r.expectedStatus), statusCode(resp.StatusCode))
} }
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
if r.verb == "POST" && (resp.StatusCode/100) == 2 { if r.verb == "POST" && (resp.StatusCode/100) == 2 {
// For successful create operations, extract resourceVersion // For successful create operations, extract resourceVersion

View File

@ -23,7 +23,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"reflect" "reflect"
@ -740,7 +740,7 @@ func TestServiceAccountTokenCreate(t *testing.T) {
t.Errorf("got Cache-Control: %v, want: %v", got, want) t.Errorf("got Cache-Control: %v, want: %v", got, want)
} }
b, err := ioutil.ReadAll(resp.Body) b, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -793,7 +793,7 @@ func TestServiceAccountTokenCreate(t *testing.T) {
t.Errorf("got Cache-Control: %v, want: %v", got, want) t.Errorf("got Cache-Control: %v, want: %v", got, want)
} }
b, err = ioutil.ReadAll(resp.Body) b, err = io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"os" "os"
benchparse "golang.org/x/tools/benchmark/parse" benchparse "golang.org/x/tools/benchmark/parse"
@ -87,7 +86,7 @@ func run() error {
if err := json.Indent(formatted, output.Bytes(), "", " "); err != nil { if err := json.Indent(formatted, output.Bytes(), "", " "); err != nil {
return err return err
} }
return ioutil.WriteFile(os.Args[1], formatted.Bytes(), 0664) return os.WriteFile(os.Args[1], formatted.Bytes(), 0664)
} }
func appendIfMeasured(items []DataItem, benchmark *benchparse.Benchmark, metricType int, metricName string, unit string, value float64) []DataItem { func appendIfMeasured(items []DataItem, benchmark *benchparse.Benchmark, metricType int, metricName string, unit string, value float64) []DataItem {

View File

@ -23,7 +23,6 @@ import (
"crypto/rand" "crypto/rand"
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem" "encoding/pem"
"io/ioutil"
"os" "os"
"path" "path"
"strings" "strings"
@ -99,7 +98,7 @@ func TestCSRDuration(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
caPublicKeyFile := path.Join(s.TmpDir, "test-ca-public-key") caPublicKeyFile := path.Join(s.TmpDir, "test-ca-public-key")
if err := ioutil.WriteFile(caPublicKeyFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCert.Raw}), os.FileMode(0600)); err != nil { if err := os.WriteFile(caPublicKeyFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCert.Raw}), os.FileMode(0600)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
caPrivateKeyBytes, err := keyutil.MarshalPrivateKeyToPEM(caPrivateKey) caPrivateKeyBytes, err := keyutil.MarshalPrivateKeyToPEM(caPrivateKey)
@ -107,7 +106,7 @@ func TestCSRDuration(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
caPrivateKeyFile := path.Join(s.TmpDir, "test-ca-private-key") caPrivateKeyFile := path.Join(s.TmpDir, "test-ca-private-key")
if err := ioutil.WriteFile(caPrivateKeyFile, caPrivateKeyBytes, os.FileMode(0600)); err != nil { if err := os.WriteFile(caPrivateKeyFile, caPrivateKeyBytes, os.FileMode(0600)); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -23,7 +23,6 @@ import (
"crypto/x509" "crypto/x509"
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem" "encoding/pem"
"io/ioutil"
"math" "math"
"math/big" "math/big"
"os" "os"
@ -157,7 +156,7 @@ func writeCACertFiles(t *testing.T, certDir string) (string, *x509.Certificate,
clientCAFilename := path.Join(certDir, "ca.crt") clientCAFilename := path.Join(certDir, "ca.crt")
if err := ioutil.WriteFile(clientCAFilename, utils.EncodeCertPEM(clientSigningCert), 0644); err != nil { if err := os.WriteFile(clientCAFilename, utils.EncodeCertPEM(clientSigningCert), 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -175,7 +174,7 @@ func writeCerts(t *testing.T, clientSigningCert *x509.Certificate, clientSigning
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(path.Join(certDir, "client.key"), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}), 0666); err != nil { if err := os.WriteFile(path.Join(certDir, "client.key"), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}), 0666); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -201,7 +200,7 @@ func writeCerts(t *testing.T, clientSigningCert *x509.Certificate, clientSigning
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(path.Join(certDir, "client.crt"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDERBytes}), 0666); err != nil { if err := os.WriteFile(path.Join(certDir, "client.crt"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDERBytes}), 0666); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -23,7 +23,6 @@ import (
"encoding/base64" "encoding/base64"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -700,7 +699,7 @@ type execPlugin struct {
func newExecPlugin(t *testing.T) *execPlugin { func newExecPlugin(t *testing.T) *execPlugin {
t.Helper() t.Helper()
outputFile, err := ioutil.TempFile("", "kubernetes-client-exec-test-plugin-output-file-*") outputFile, err := os.CreateTemp("", "kubernetes-client-exec-test-plugin-output-file-*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -806,7 +805,7 @@ func TestExecPluginRotationViaInformer(t *testing.T) {
} }
func startTestServer(t *testing.T) (result *kubeapiservertesting.TestServer, clientAuthorizedToken string, clientCertFileName string, clientKeyFileName string) { func startTestServer(t *testing.T) (result *kubeapiservertesting.TestServer, clientAuthorizedToken string, clientCertFileName string, clientKeyFileName string) {
certDir, err := ioutil.TempDir("", "kubernetes-client-exec-test-cert-dir-*") certDir, err := os.MkdirTemp("", "kubernetes-client-exec-test-cert-dir-*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -837,7 +836,7 @@ func startTestServer(t *testing.T) (result *kubeapiservertesting.TestServer, cli
func writeTokenFile(t *testing.T, goodToken string) string { func writeTokenFile(t *testing.T, goodToken string) string {
t.Helper() t.Helper()
tokenFile, err := ioutil.TempFile("", "kubernetes-client-exec-test-token-file-*") tokenFile, err := os.CreateTemp("", "kubernetes-client-exec-test-token-file-*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -855,7 +854,7 @@ func writeTokenFile(t *testing.T, goodToken string) string {
func read(t *testing.T, fileName string) string { func read(t *testing.T, fileName string) string {
t.Helper() t.Helper()
data, err := ioutil.ReadFile(fileName) data, err := os.ReadFile(fileName)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -20,7 +20,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@ -232,7 +231,7 @@ func runTestWithVersion(t *testing.T, version string) {
// prepare audit policy file // prepare audit policy file
auditPolicy := strings.Replace(auditPolicyPattern, "{version}", version, 1) auditPolicy := strings.Replace(auditPolicyPattern, "{version}", version, 1)
policyFile, err := ioutil.TempFile("", "audit-policy.yaml") policyFile, err := os.CreateTemp("", "audit-policy.yaml")
if err != nil { if err != nil {
t.Fatalf("Failed to create audit policy file: %v", err) t.Fatalf("Failed to create audit policy file: %v", err)
} }
@ -245,7 +244,7 @@ func runTestWithVersion(t *testing.T, version string) {
} }
// prepare audit log file // prepare audit log file
logFile, err := ioutil.TempFile("", "audit.log") logFile, err := os.CreateTemp("", "audit.log")
if err != nil { if err != nil {
t.Fatalf("Failed to create audit log file: %v", err) t.Fatalf("Failed to create audit log file: %v", err)
} }

View File

@ -18,7 +18,6 @@ package controlplane
import ( import (
"io" "io"
"io/ioutil"
"net/http" "net/http"
"sync" "sync"
"testing" "testing"
@ -55,7 +54,7 @@ func TestGracefulShutdown(t *testing.T) {
if respErr.err != nil { if respErr.err != nil {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
bs, err := ioutil.ReadAll(respErr.resp.Body) bs, err := io.ReadAll(respErr.resp.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -96,7 +95,7 @@ func TestGracefulShutdown(t *testing.T) {
t.Fatal(respErr.err) t.Fatal(respErr.err)
} }
defer respErr.resp.Body.Close() defer respErr.resp.Body.Close()
bs, err := ioutil.ReadAll(respErr.resp.Body) bs, err := io.ReadAll(respErr.resp.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -21,7 +21,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"path" "path"
@ -126,7 +126,7 @@ func TestEmptyList(t *testing.T) {
t.Fatalf("got status %v instead of 200 OK", resp.StatusCode) t.Fatalf("got status %v instead of 200 OK", resp.StatusCode)
} }
defer resp.Body.Close() defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body) data, _ := io.ReadAll(resp.Body)
decodedData := map[string]interface{}{} decodedData := map[string]interface{}{}
if err := json.Unmarshal(data, &decodedData); err != nil { if err := json.Unmarshal(data, &decodedData); err != nil {
t.Logf("body: %s", string(data)) t.Logf("body: %s", string(data))
@ -214,7 +214,7 @@ func TestStatus(t *testing.T) {
t.Fatalf("got status %v instead of %s", resp.StatusCode, tc.name) t.Fatalf("got status %v instead of %s", resp.StatusCode, tc.name)
} }
defer resp.Body.Close() defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body) data, _ := io.ReadAll(resp.Body)
decodedData := map[string]interface{}{} decodedData := map[string]interface{}{}
if err := json.Unmarshal(data, &decodedData); err != nil { if err := json.Unmarshal(data, &decodedData); err != nil {
t.Logf("body: %s", string(data)) t.Logf("body: %s", string(data))
@ -470,7 +470,7 @@ func TestAutoscalingGroupBackwardCompatibility(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
body := string(b) body := string(b)
if _, ok := r.expectedStatusCodes[resp.StatusCode]; !ok { if _, ok := r.expectedStatusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r) t.Logf("case %v", r)
@ -518,7 +518,7 @@ func TestAppsGroupBackwardCompatibility(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := io.ReadAll(resp.Body)
body := string(b) body := string(b)
if _, ok := r.expectedStatusCodes[resp.StatusCode]; !ok { if _, ok := r.expectedStatusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r) t.Logf("case %v", r)
@ -545,7 +545,7 @@ func TestAccept(t *testing.T) {
t.Fatalf("got status %v instead of 200 OK", resp.StatusCode) t.Fatalf("got status %v instead of 200 OK", resp.StatusCode)
} }
body, _ := ioutil.ReadAll(resp.Body) body, _ := io.ReadAll(resp.Body)
if resp.Header.Get("Content-Type") != "application/json" { if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("unexpected content: %s", body) t.Errorf("unexpected content: %s", body)
} }
@ -562,7 +562,7 @@ func TestAccept(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
body, _ = ioutil.ReadAll(resp.Body) body, _ = io.ReadAll(resp.Body)
if resp.Header.Get("Content-Type") != "application/yaml" { if resp.Header.Get("Content-Type") != "application/yaml" {
t.Errorf("unexpected content: %s", body) t.Errorf("unexpected content: %s", body)
} }
@ -580,7 +580,7 @@ func TestAccept(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
body, _ = ioutil.ReadAll(resp.Body) body, _ = io.ReadAll(resp.Body)
if resp.Header.Get("Content-Type") != "application/json" { if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("unexpected content: %s", body) t.Errorf("unexpected content: %s", body)
} }

View File

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path" "path"
"strconv" "strconv"
@ -173,14 +172,14 @@ func (e *transformTest) getEncryptionOptions() []string {
} }
func (e *transformTest) createEncryptionConfig() (string, error) { func (e *transformTest) createEncryptionConfig() (string, error) {
tempDir, err := ioutil.TempDir("", "secrets-encryption-test") tempDir, err := os.MkdirTemp("", "secrets-encryption-test")
if err != nil { if err != nil {
return "", fmt.Errorf("failed to create temp directory: %v", err) return "", fmt.Errorf("failed to create temp directory: %v", err)
} }
encryptionConfig := path.Join(tempDir, encryptionConfigFileName) encryptionConfig := path.Join(tempDir, encryptionConfigFileName)
if err := ioutil.WriteFile(encryptionConfig, []byte(e.transformerConfig), 0644); err != nil { if err := os.WriteFile(encryptionConfig, []byte(e.transformerConfig), 0644); err != nil {
os.RemoveAll(tempDir) os.RemoveAll(tempDir)
return "", fmt.Errorf("error while writing encryption config: %v", err) return "", fmt.Errorf("error while writing encryption config: %v", err)
} }

View File

@ -19,7 +19,6 @@ package etcd
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -64,7 +63,7 @@ AwEHoUQDQgAEH6cuzP8XuD5wal6wf9M6xDljTOPLX2i8uIp/C/ASqiIGUeeKQtX0
// StartRealAPIServerOrDie starts an API server that is appropriate for use in tests that require one of every resource // StartRealAPIServerOrDie starts an API server that is appropriate for use in tests that require one of every resource
func StartRealAPIServerOrDie(t *testing.T, configFuncs ...func(*options.ServerRunOptions)) *APIServer { func StartRealAPIServerOrDie(t *testing.T, configFuncs ...func(*options.ServerRunOptions)) *APIServer {
certDir, err := ioutil.TempDir("", t.Name()) certDir, err := os.MkdirTemp("", t.Name())
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -79,12 +78,12 @@ func StartRealAPIServerOrDie(t *testing.T, configFuncs ...func(*options.ServerRu
t.Fatal(err) t.Fatal(err)
} }
saSigningKeyFile, err := ioutil.TempFile("/tmp", "insecure_test_key") saSigningKeyFile, err := os.CreateTemp("/tmp", "insecure_test_key")
if err != nil { if err != nil {
t.Fatalf("create temp file failed: %v", err) t.Fatalf("create temp file failed: %v", err)
} }
defer os.RemoveAll(saSigningKeyFile.Name()) defer os.RemoveAll(saSigningKeyFile.Name())
if err = ioutil.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil { if err = os.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
t.Fatalf("write file %s failed: %v", saSigningKeyFile.Name(), err) t.Fatalf("write file %s failed: %v", saSigningKeyFile.Name(), err)
} }

View File

@ -20,7 +20,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -72,7 +71,7 @@ func TestAggregatedAPIServer(t *testing.T) {
// start the wardle server to prove we can aggregate it // start the wardle server to prove we can aggregate it
wardleToKASKubeConfigFile := writeKubeConfigForWardleServerToKASConnection(t, rest.CopyConfig(kubeClientConfig)) wardleToKASKubeConfigFile := writeKubeConfigForWardleServerToKASConnection(t, rest.CopyConfig(kubeClientConfig))
defer os.Remove(wardleToKASKubeConfigFile) defer os.Remove(wardleToKASKubeConfigFile)
wardleCertDir, _ := ioutil.TempDir("", "test-integration-wardle-server") wardleCertDir, _ := os.MkdirTemp("", "test-integration-wardle-server")
defer os.RemoveAll(wardleCertDir) defer os.RemoveAll(wardleCertDir)
listener, wardlePort, err := genericapiserveroptions.CreateListener("tcp", "127.0.0.1:0", net.ListenConfig{}) listener, wardlePort, err := genericapiserveroptions.CreateListener("tcp", "127.0.0.1:0", net.ListenConfig{})
if err != nil { if err != nil {
@ -108,7 +107,7 @@ func TestAggregatedAPIServer(t *testing.T) {
testAPIGroup(t, wardleClient.Discovery().RESTClient()) testAPIGroup(t, wardleClient.Discovery().RESTClient())
testAPIResourceList(t, wardleClient.Discovery().RESTClient()) testAPIResourceList(t, wardleClient.Discovery().RESTClient())
wardleCA, err := ioutil.ReadFile(directWardleClientConfig.CAFile) wardleCA, err := os.ReadFile(directWardleClientConfig.CAFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -158,10 +157,10 @@ func TestAggregatedAPIServer(t *testing.T) {
// now we update the client-ca nd request-header-client-ca-file and the kas will consume it, update the configmap // now we update the client-ca nd request-header-client-ca-file and the kas will consume it, update the configmap
// and then the wardle server will detect and update too. // and then the wardle server will detect and update too.
if err := ioutil.WriteFile(path.Join(testServer.TmpDir, "client-ca.crt"), differentClientCA, 0644); err != nil { if err := os.WriteFile(path.Join(testServer.TmpDir, "client-ca.crt"), differentClientCA, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(path.Join(testServer.TmpDir, "proxy-ca.crt"), differentFrontProxyCA, 0644); err != nil { if err := os.WriteFile(path.Join(testServer.TmpDir, "proxy-ca.crt"), differentFrontProxyCA, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
// wait for it to be picked up. there's a test in certreload_test.go that ensure this works // wait for it to be picked up. there's a test in certreload_test.go that ensure this works
@ -274,7 +273,7 @@ func writeKubeConfigForWardleServerToKASConnection(t *testing.T, kubeClientConfi
} }
adminKubeConfig := createKubeConfig(wardleToKASKubeClientConfig) adminKubeConfig := createKubeConfig(wardleToKASKubeClientConfig)
wardleToKASKubeConfigFile, _ := ioutil.TempFile("", "") wardleToKASKubeConfigFile, _ := os.CreateTemp("", "")
if err := clientcmd.WriteToFile(*adminKubeConfig, wardleToKASKubeConfigFile.Name()); err != nil { if err := clientcmd.WriteToFile(*adminKubeConfig, wardleToKASKubeConfigFile.Name()); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"os" "os"
"os/exec" "os/exec"
@ -104,7 +104,7 @@ func RunCustomEtcd(dataDir string, customFlags []string) (url string, stopFn fun
klog.Infof("starting etcd on %s", customURL) klog.Infof("starting etcd on %s", customURL)
etcdDataDir, err := ioutil.TempDir(os.TempDir(), dataDir) etcdDataDir, err := os.MkdirTemp(os.TempDir(), dataDir)
if err != nil { if err != nil {
return "", nil, fmt.Errorf("unable to make temp etcd data dir %s: %v", dataDir, err) return "", nil, fmt.Errorf("unable to make temp etcd data dir %s: %v", dataDir, err)
} }
@ -139,7 +139,7 @@ func RunCustomEtcd(dataDir string, customFlags []string) (url string, stopFn fun
// Quiet etcd logs for integration tests // Quiet etcd logs for integration tests
// Comment out to get verbose logs if desired // Comment out to get verbose logs if desired
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, os.Stderr)) grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, os.Stderr))
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
return "", nil, fmt.Errorf("failed to run etcd: %v", err) return "", nil, fmt.Errorf("failed to run etcd: %v", err)

View File

@ -18,7 +18,6 @@ package framework
import ( import (
"context" "context"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -58,7 +57,7 @@ type TestServerSetup struct {
// StartTestServer runs a kube-apiserver, optionally calling out to the setup.ModifyServerRunOptions and setup.ModifyServerConfig functions // StartTestServer runs a kube-apiserver, optionally calling out to the setup.ModifyServerRunOptions and setup.ModifyServerConfig functions
func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup) (client.Interface, *rest.Config) { func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup) (client.Interface, *rest.Config) {
certDir, _ := ioutil.TempDir("", "test-integration-"+t.Name()) certDir, _ := os.MkdirTemp("", "test-integration-"+t.Name())
go func() { go func() {
<-stopCh <-stopCh
os.RemoveAll(certDir) os.RemoveAll(certDir)
@ -73,8 +72,8 @@ func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
proxyCACertFile, _ := ioutil.TempFile(certDir, "proxy-ca.crt") proxyCACertFile, _ := os.CreateTemp(certDir, "proxy-ca.crt")
if err := ioutil.WriteFile(proxyCACertFile.Name(), utils.EncodeCertPEM(proxySigningCert), 0644); err != nil { if err := os.WriteFile(proxyCACertFile.Name(), utils.EncodeCertPEM(proxySigningCert), 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
clientSigningKey, err := utils.NewPrivateKey() clientSigningKey, err := utils.NewPrivateKey()
@ -85,8 +84,8 @@ func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
clientCACertFile, _ := ioutil.TempFile(certDir, "client-ca.crt") clientCACertFile, _ := os.CreateTemp(certDir, "client-ca.crt")
if err := ioutil.WriteFile(clientCACertFile.Name(), utils.EncodeCertPEM(clientSigningCert), 0644); err != nil { if err := os.WriteFile(clientCACertFile.Name(), utils.EncodeCertPEM(clientSigningCert), 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -95,12 +94,12 @@ func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup
t.Fatal(err) t.Fatal(err)
} }
saSigningKeyFile, err := ioutil.TempFile("/tmp", "insecure_test_key") saSigningKeyFile, err := os.CreateTemp("/tmp", "insecure_test_key")
if err != nil { if err != nil {
t.Fatalf("create temp file failed: %v", err) t.Fatalf("create temp file failed: %v", err)
} }
defer os.RemoveAll(saSigningKeyFile.Name()) defer os.RemoveAll(saSigningKeyFile.Name())
if err = ioutil.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil { if err = os.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
t.Fatalf("write file %s failed: %v", saSigningKeyFile.Name(), err) t.Fatalf("write file %s failed: %v", saSigningKeyFile.Name(), err)
} }

View File

@ -19,7 +19,6 @@ package ipamperf
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os" "os"
"testing" "testing"
@ -101,7 +100,7 @@ func logResults(allResults []*Results) {
} }
if resultsLogFile != "" { if resultsLogFile != "" {
klog.Infof("Logging results to %s", resultsLogFile) klog.Infof("Logging results to %s", resultsLogFile)
if err := ioutil.WriteFile(resultsLogFile, jStr, os.FileMode(0644)); err != nil { if err := os.WriteFile(resultsLogFile, jStr, os.FileMode(0644)); err != nil {
klog.Errorf("Error logging results to %s: %v", resultsLogFile, err) klog.Errorf("Error logging results to %s: %v", resultsLogFile, err)
} }
} }

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"runtime" "runtime"
@ -51,7 +51,7 @@ func scrapeMetrics(s *httptest.Server) (testutil.Metrics, error) {
return nil, fmt.Errorf("Non-200 response trying to scrape metrics from API Server: %v", resp) return nil, fmt.Errorf("Non-200 response trying to scrape metrics from API Server: %v", resp)
} }
metrics := testutil.NewMetrics() metrics := testutil.NewMetrics()
data, err := ioutil.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, fmt.Errorf("Unable to read response: %v", resp) return nil, fmt.Errorf("Unable to read response: %v", resp)
} }

View File

@ -19,7 +19,7 @@ package scale
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"io/ioutil" "io"
"path" "path"
"strings" "strings"
"testing" "testing"
@ -203,7 +203,7 @@ var (
) )
func setupWithOptions(t *testing.T, instanceOptions *apitesting.TestServerInstanceOptions, flags []string) (client kubernetes.Interface, tearDown func()) { func setupWithOptions(t *testing.T, instanceOptions *apitesting.TestServerInstanceOptions, flags []string) (client kubernetes.Interface, tearDown func()) {
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard)) grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard))
result := apitesting.StartTestServerOrDie(t, instanceOptions, flags, framework.SharedEtcd()) result := apitesting.StartTestServerOrDie(t, instanceOptions, flags, framework.SharedEtcd())
result.ClientConfig.AcceptContentTypes = "" result.ClientConfig.AcceptContentTypes = ""

View File

@ -20,8 +20,8 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"math" "math"
"os"
"strings" "strings"
"sync" "sync"
"testing" "testing"
@ -542,7 +542,7 @@ func BenchmarkPerfScheduling(b *testing.B) {
} }
func loadSchedulerConfig(file string) (*config.KubeSchedulerConfiguration, error) { func loadSchedulerConfig(file string) (*config.KubeSchedulerConfiguration, error) {
data, err := ioutil.ReadFile(file) data, err := os.ReadFile(file)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -940,7 +940,7 @@ func waitUntilPodsScheduled(ctx context.Context, podInformer coreinformers.PodIn
} }
func getSpecFromFile(path *string, spec interface{}) error { func getSpecFromFile(path *string, spec interface{}) error {
bytes, err := ioutil.ReadFile(*path) bytes, err := os.ReadFile(*path)
if err != nil { if err != nil {
return err return err
} }
@ -948,7 +948,7 @@ func getSpecFromFile(path *string, spec interface{}) error {
} }
func getUnstructuredFromFile(path string) (*unstructured.Unstructured, *schema.GroupVersionKind, error) { func getUnstructuredFromFile(path string) (*unstructured.Unstructured, *schema.GroupVersionKind, error) {
bytes, err := ioutil.ReadFile(path) bytes, err := os.ReadFile(path)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }

View File

@ -22,7 +22,6 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"math" "math"
"os" "os"
"path" "path"
@ -178,7 +177,7 @@ func dataItems2JSONFile(dataItems DataItems, namePrefix string) error {
if err := json.Indent(formatted, b, "", " "); err != nil { if err := json.Indent(formatted, b, "", " "); err != nil {
return fmt.Errorf("indenting error: %v", err) return fmt.Errorf("indenting error: %v", err)
} }
return ioutil.WriteFile(destFile, formatted.Bytes(), 0644) return os.WriteFile(destFile, formatted.Bytes(), 0644)
} }
type labelValues struct { type labelValues struct {

View File

@ -21,7 +21,6 @@ import (
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path" "path"
@ -90,7 +89,7 @@ func TestComponentSecureServingAndAuth(t *testing.T) {
// authenticate to apiserver via bearer token // authenticate to apiserver via bearer token
token := "flwqkenfjasasdfmwerasd" // Fake token for testing. token := "flwqkenfjasasdfmwerasd" // Fake token for testing.
tokenFile, err := ioutil.TempFile("", "kubeconfig") tokenFile, err := os.CreateTemp("", "kubeconfig")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -107,7 +106,7 @@ func TestComponentSecureServingAndAuth(t *testing.T) {
defer server.TearDownFn() defer server.TearDownFn()
// create kubeconfig for the apiserver // create kubeconfig for the apiserver
apiserverConfig, err := ioutil.TempFile("", "kubeconfig") apiserverConfig, err := os.CreateTemp("", "kubeconfig")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -133,7 +132,7 @@ users:
apiserverConfig.Close() apiserverConfig.Close()
// create BROKEN kubeconfig for the apiserver // create BROKEN kubeconfig for the apiserver
brokenApiserverConfig, err := ioutil.TempFile("", "kubeconfig") brokenApiserverConfig, err := os.CreateTemp("", "kubeconfig")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -273,7 +272,7 @@ func testComponent(t *testing.T, tester componentTester, kubeconfig, brokenKubec
// read self-signed server cert disk // read self-signed server cert disk
pool := x509.NewCertPool() pool := x509.NewCertPool()
serverCertPath := path.Join(secureOptions.ServerCert.CertDirectory, secureOptions.ServerCert.PairName+".crt") serverCertPath := path.Join(secureOptions.ServerCert.CertDirectory, secureOptions.ServerCert.PairName+".crt")
serverCert, err := ioutil.ReadFile(serverCertPath) serverCert, err := os.ReadFile(serverCertPath)
if err != nil { if err != nil {
t.Fatalf("Failed to read component server cert %q: %v", serverCertPath, err) t.Fatalf("Failed to read component server cert %q: %v", serverCertPath, err)
} }
@ -297,7 +296,7 @@ func testComponent(t *testing.T, tester componentTester, kubeconfig, brokenKubec
t.Fatalf("failed to GET %s from component: %v", tt.path, err) t.Fatalf("failed to GET %s from component: %v", tt.path, err)
} }
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
t.Fatalf("failed to read response body: %v", err) t.Fatalf("failed to read response body: %v", err)
} }
@ -315,7 +314,7 @@ func testComponent(t *testing.T, tester componentTester, kubeconfig, brokenKubec
if err != nil { if err != nil {
t.Fatalf("failed to GET %s from component: %v", tt.path, err) t.Fatalf("failed to GET %s from component: %v", tt.path, err)
} }
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
t.Fatalf("failed to read response body: %v", err) t.Fatalf("failed to read response body: %v", err)
} }
@ -396,7 +395,7 @@ func testComponentWithSecureServing(t *testing.T, tester componentTester, kubeco
// read self-signed server cert disk // read self-signed server cert disk
pool := x509.NewCertPool() pool := x509.NewCertPool()
serverCertPath := path.Join(secureOptions.ServerCert.CertDirectory, secureOptions.ServerCert.PairName+".crt") serverCertPath := path.Join(secureOptions.ServerCert.CertDirectory, secureOptions.ServerCert.PairName+".crt")
serverCert, err := ioutil.ReadFile(serverCertPath) serverCert, err := os.ReadFile(serverCertPath)
if err != nil { if err != nil {
t.Fatalf("Failed to read component server cert %q: %v", serverCertPath, err) t.Fatalf("Failed to read component server cert %q: %v", serverCertPath, err)
} }
@ -420,7 +419,7 @@ func testComponentWithSecureServing(t *testing.T, tester componentTester, kubeco
t.Fatalf("failed to GET %s from component: %v", tt.path, err) t.Fatalf("failed to GET %s from component: %v", tt.path, err)
} }
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
t.Fatalf("failed to read response body: %v", err) t.Fatalf("failed to read response body: %v", err)
} }

View File

@ -21,7 +21,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@ -55,7 +55,7 @@ func NewAdmissionWebhookServer(handler http.Handler) (string, func(), error) {
func AdmissionWebhookHandler(t *testing.T, admit func(*v1beta1.AdmissionReview) error) http.HandlerFunc { func AdmissionWebhookHandler(t *testing.T, admit func(*v1beta1.AdmissionReview) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
return return

View File

@ -17,7 +17,6 @@ limitations under the License.
package harness package harness
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -56,11 +55,11 @@ func (h *Harness) Close() {
} }
} }
// TempDir is a wrapper around ioutil.TempDir for tests. // TempDir is a wrapper around os.MkdirTemp for tests.
// It automatically fails the test if we can't create a temp file, // It automatically fails the test if we can't create a temp file,
// and deletes the temp directory when Close is called on the Harness // and deletes the temp directory when Close is called on the Harness
func (h *Harness) TempDir(baseDir string, prefix string) string { func (h *Harness) TempDir(baseDir string, prefix string) string {
tempDir, err := ioutil.TempDir(baseDir, prefix) tempDir, err := os.MkdirTemp(baseDir, prefix)
if err != nil { if err != nil {
h.Fatalf("unable to create tempdir: %v", err) h.Fatalf("unable to create tempdir: %v", err)
} }

View File

@ -20,7 +20,6 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"regexp" "regexp"
"strings" "strings"
@ -73,7 +72,7 @@ func initReg() RegistryList {
return registry return registry
} }
fileContent, err := ioutil.ReadFile(repoList) fileContent, err := os.ReadFile(repoList)
if err != nil { if err != nil {
panic(fmt.Errorf("Error reading '%v' file contents: %v", repoList, err)) panic(fmt.Errorf("Error reading '%v' file contents: %v", repoList, err))
} }

View File

@ -17,7 +17,7 @@ limitations under the License.
package utils package utils
import ( import (
"io/ioutil" "os"
"k8s.io/klog/v2" "k8s.io/klog/v2"
) )
@ -26,7 +26,7 @@ func MakeTempDirOrDie(prefix string, baseDir string) string {
if baseDir == "" { if baseDir == "" {
baseDir = "/tmp" baseDir = "/tmp"
} }
tempDir, err := ioutil.TempDir(baseDir, prefix) tempDir, err := os.MkdirTemp(baseDir, prefix)
if err != nil { if err != nil {
klog.Fatalf("Can't make a temp rootdir: %v", err) klog.Fatalf("Can't make a temp rootdir: %v", err)
} }