diff --git a/discovery/cached/disk/cached_discovery.go b/discovery/cached/disk/cached_discovery.go index d3082d1e..50b6d410 100644 --- a/discovery/cached/disk/cached_discovery.go +++ b/discovery/cached/disk/cached_discovery.go @@ -18,7 +18,7 @@ package disk import ( "errors" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -157,7 +157,7 @@ func (d *CachedDiscoveryClient) getCachedFile(filename string) ([]byte, error) { } // the cache is present and its valid. Try to read and use it. - cachedBytes, err := ioutil.ReadAll(file) + cachedBytes, err := io.ReadAll(file) if err != nil { return nil, err } @@ -179,7 +179,7 @@ func (d *CachedDiscoveryClient) writeCachedFile(filename string, obj runtime.Obj return err } - f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename)+".") + f, err := os.CreateTemp(filepath.Dir(filename), filepath.Base(filename)+".") if err != nil { return err } diff --git a/discovery/cached/disk/cached_discovery_test.go b/discovery/cached/disk/cached_discovery_test.go index a8e6da06..f7fabab5 100644 --- a/discovery/cached/disk/cached_discovery_test.go +++ b/discovery/cached/disk/cached_discovery_test.go @@ -17,7 +17,6 @@ limitations under the License. package disk import ( - "io/ioutil" "os" "path/filepath" "strings" @@ -42,7 +41,7 @@ import ( func TestCachedDiscoveryClient_Fresh(t *testing.T) { assert := assert.New(t) - d, err := ioutil.TempDir("", "") + d, err := os.MkdirTemp("", "") assert.NoError(err) defer os.RemoveAll(d) @@ -86,7 +85,7 @@ func TestCachedDiscoveryClient_Fresh(t *testing.T) { func TestNewCachedDiscoveryClient_TTL(t *testing.T) { assert := assert.New(t) - d, err := ioutil.TempDir("", "") + d, err := os.MkdirTemp("", "") assert.NoError(err) defer os.RemoveAll(d) @@ -104,7 +103,7 @@ func TestNewCachedDiscoveryClient_TTL(t *testing.T) { func TestNewCachedDiscoveryClient_PathPerm(t *testing.T) { assert := assert.New(t) - d, err := ioutil.TempDir("", "") + d, err := os.MkdirTemp("", "") assert.NoError(err) os.RemoveAll(d) defer os.RemoveAll(d) @@ -131,13 +130,13 @@ func TestNewCachedDiscoveryClient_PathPerm(t *testing.T) { // successive calls func TestOpenAPIDiskCache(t *testing.T) { // Create discovery cache dir (unused) - discoCache, err := ioutil.TempDir("", "") + discoCache, err := os.MkdirTemp("", "") require.NoError(t, err) os.RemoveAll(discoCache) defer os.RemoveAll(discoCache) // Create http cache dir - httpCache, err := ioutil.TempDir("", "") + httpCache, err := os.MkdirTemp("", "") require.NoError(t, err) os.RemoveAll(httpCache) defer os.RemoveAll(httpCache) diff --git a/discovery/cached/disk/round_tripper_test.go b/discovery/cached/disk/round_tripper_test.go index 5f1626c9..fb8c5a06 100644 --- a/discovery/cached/disk/round_tripper_test.go +++ b/discovery/cached/disk/round_tripper_test.go @@ -19,7 +19,7 @@ package disk import ( "bytes" "crypto/sha256" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -43,7 +43,7 @@ func (rt *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) } func BenchmarkDiskCache(b *testing.B) { - cacheDir, err := ioutil.TempDir("", "cache-rt") + cacheDir, err := os.MkdirTemp("", "cache-rt") if err != nil { b.Fatal(err) } @@ -57,7 +57,7 @@ func BenchmarkDiskCache(b *testing.B) { }) k := "localhost:8080/apis/batch/v1.json" - v, err := ioutil.ReadFile("../../testdata/apis/batch/v1.json") + v, err := os.ReadFile("../../testdata/apis/batch/v1.json") if err != nil { b.Fatal(err) } @@ -73,7 +73,7 @@ func BenchmarkDiskCache(b *testing.B) { func TestCacheRoundTripper(t *testing.T) { rt := &testRoundTripper{} - cacheDir, err := ioutil.TempDir("", "cache-rt") + cacheDir, err := os.MkdirTemp("", "cache-rt") defer os.RemoveAll(cacheDir) if err != nil { t.Fatal(err) @@ -87,14 +87,14 @@ func TestCacheRoundTripper(t *testing.T) { } rt.Response = &http.Response{ Header: http.Header{"ETag": []string{`"123456"`}}, - Body: ioutil.NopCloser(bytes.NewReader([]byte("Content"))), + Body: io.NopCloser(bytes.NewReader([]byte("Content"))), StatusCode: http.StatusOK, } resp, err := cache.RoundTrip(req) if err != nil { t.Fatal(err) } - content, err := ioutil.ReadAll(resp.Body) + content, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } @@ -109,7 +109,7 @@ func TestCacheRoundTripper(t *testing.T) { } rt.Response = &http.Response{ StatusCode: http.StatusNotModified, - Body: ioutil.NopCloser(bytes.NewReader([]byte("Other Content"))), + Body: io.NopCloser(bytes.NewReader([]byte("Other Content"))), } resp, err = cache.RoundTrip(req) @@ -118,7 +118,7 @@ func TestCacheRoundTripper(t *testing.T) { } // Read body and make sure we have the initial content - content, err = ioutil.ReadAll(resp.Body) + content, err = io.ReadAll(resp.Body) resp.Body.Close() if err != nil { t.Fatal(err) @@ -132,7 +132,7 @@ func TestCacheRoundTripperPathPerm(t *testing.T) { assert := assert.New(t) rt := &testRoundTripper{} - cacheDir, err := ioutil.TempDir("", "cache-rt") + cacheDir, err := os.MkdirTemp("", "cache-rt") os.RemoveAll(cacheDir) defer os.RemoveAll(cacheDir) @@ -148,14 +148,14 @@ func TestCacheRoundTripperPathPerm(t *testing.T) { } rt.Response = &http.Response{ Header: http.Header{"ETag": []string{`"123456"`}}, - Body: ioutil.NopCloser(bytes.NewReader([]byte("Content"))), + Body: io.NopCloser(bytes.NewReader([]byte("Content"))), StatusCode: http.StatusOK, } resp, err := cache.RoundTrip(req) if err != nil { t.Fatal(err) } - content, err := ioutil.ReadAll(resp.Body) + content, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } @@ -182,7 +182,7 @@ func TestSumDiskCache(t *testing.T) { // Ensure that we'll return a cache miss if the backing file doesn't exist. t.Run("NoSuchKey", func(t *testing.T) { - cacheDir, err := ioutil.TempDir("", "cache-test") + cacheDir, err := os.MkdirTemp("", "cache-test") if err != nil { t.Fatal(err) } @@ -199,7 +199,7 @@ func TestSumDiskCache(t *testing.T) { // Ensure that we'll return a cache miss if the backing file is empty. t.Run("EmptyFile", func(t *testing.T) { - cacheDir, err := ioutil.TempDir("", "cache-test") + cacheDir, err := os.MkdirTemp("", "cache-test") if err != nil { t.Fatal(err) } @@ -223,7 +223,7 @@ func TestSumDiskCache(t *testing.T) { // Ensure that we'll return a cache miss if the backing has an invalid // checksum. t.Run("InvalidChecksum", func(t *testing.T) { - cacheDir, err := ioutil.TempDir("", "cache-test") + cacheDir, err := os.MkdirTemp("", "cache-test") if err != nil { t.Fatal(err) } @@ -258,7 +258,7 @@ func TestSumDiskCache(t *testing.T) { // This should cause httpcache to fall back to its underlying transport and // to subsequently cache the new value, overwriting the corrupt one. t.Run("OverwriteExistingKey", func(t *testing.T) { - cacheDir, err := ioutil.TempDir("", "cache-test") + cacheDir, err := os.MkdirTemp("", "cache-test") if err != nil { t.Fatal(err) } @@ -290,7 +290,7 @@ func TestSumDiskCache(t *testing.T) { // Ensure that deleting a key does in fact delete it. t.Run("DeleteKey", func(t *testing.T) { - cacheDir, err := ioutil.TempDir("", "cache-test") + cacheDir, err := os.MkdirTemp("", "cache-test") if err != nil { t.Fatal(err) } diff --git a/discovery/helper_blackbox_test.go b/discovery/helper_blackbox_test.go index c40421a6..d9481ec2 100644 --- a/discovery/helper_blackbox_test.go +++ b/discovery/helper_blackbox_test.go @@ -21,7 +21,6 @@ import ( "encoding/json" "errors" "io" - "io/ioutil" "net/http" "strings" "testing" @@ -41,7 +40,7 @@ func objBody(object interface{}) io.ReadCloser { if err != nil { panic(err) } - return ioutil.NopCloser(bytes.NewReader([]byte(output))) + return io.NopCloser(bytes.NewReader([]byte(output))) } func TestServerSupportsVersion(t *testing.T) { diff --git a/dynamic/client_test.go b/dynamic/client_test.go index 979d7fe3..46a8f827 100644 --- a/dynamic/client_test.go +++ b/dynamic/client_test.go @@ -20,7 +20,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "reflect" @@ -405,7 +405,7 @@ func TestCreate(t *testing.T) { } w.Header().Set("Content-Type", runtime.ContentTypeJSON) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { t.Errorf("Create(%q) unexpected error reading body: %v", tc.name, err) w.WriteHeader(http.StatusInternalServerError) @@ -487,7 +487,7 @@ func TestUpdate(t *testing.T) { } w.Header().Set("Content-Type", runtime.ContentTypeJSON) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { t.Errorf("Update(%q) unexpected error reading body: %v", tc.name, err) w.WriteHeader(http.StatusInternalServerError) @@ -645,7 +645,7 @@ func TestPatch(t *testing.T) { t.Errorf("Patch(%q) got Content-Type %s. wanted %s", tc.name, content, types.StrategicMergePatchType) } - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { t.Errorf("Patch(%q) unexpected error reading body: %v", tc.name, err) w.WriteHeader(http.StatusInternalServerError) diff --git a/kubernetes/typed/core/v1/fake/fake_pod_expansion.go b/kubernetes/typed/core/v1/fake/fake_pod_expansion.go index 31f71b0e..c814cadb 100644 --- a/kubernetes/typed/core/v1/fake/fake_pod_expansion.go +++ b/kubernetes/typed/core/v1/fake/fake_pod_expansion.go @@ -19,7 +19,7 @@ package fake import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "strings" @@ -68,7 +68,7 @@ func (c *FakePods) GetLogs(name string, opts *v1.PodLogOptions) *restclient.Requ Client: fakerest.CreateHTTPClient(func(request *http.Request) (*http.Response, error) { resp := &http.Response{ StatusCode: http.StatusOK, - Body: ioutil.NopCloser(strings.NewReader("fake logs")), + Body: io.NopCloser(strings.NewReader("fake logs")), } return resp, nil }), diff --git a/kubernetes_test/timeout_test.go b/kubernetes_test/timeout_test.go index eb3c5f3e..ce3d8134 100644 --- a/kubernetes_test/timeout_test.go +++ b/kubernetes_test/timeout_test.go @@ -19,7 +19,7 @@ package kubernetes_test import ( "bytes" "context" - "io/ioutil" + "io" "net/http" "testing" @@ -41,7 +41,7 @@ func TestListTimeout(t *testing.T) { if req.URL.Query().Get("timeout") != "21s" { t.Fatal(spew.Sdump(req.URL.Query())) } - return &http.Response{StatusCode: http.StatusNotFound, Body: ioutil.NopCloser(&bytes.Buffer{})}, nil + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(&bytes.Buffer{})}, nil }), } clientConfig := &rest.Config{ diff --git a/metadata/metadata_test.go b/metadata/metadata_test.go index d82a1758..5e34f008 100644 --- a/metadata/metadata_test.go +++ b/metadata/metadata_test.go @@ -19,7 +19,7 @@ package metadata import ( "context" "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" "reflect" @@ -245,7 +245,7 @@ func TestClient(t *testing.T) { t.Fatal(req.URL.String()) } defer req.Body.Close() - buf, err := ioutil.ReadAll(req.Body) + buf, err := io.ReadAll(req.Body) if err != nil { t.Fatal(err) } @@ -272,7 +272,7 @@ func TestClient(t *testing.T) { t.Fatal(req.URL.String()) } defer req.Body.Close() - buf, err := ioutil.ReadAll(req.Body) + buf, err := io.ReadAll(req.Body) if err != nil { t.Fatal(err) } diff --git a/plugin/pkg/client/auth/exec/exec_test.go b/plugin/pkg/client/auth/exec/exec_test.go index 1f4097ec..b56dd23b 100644 --- a/plugin/pkg/client/auth/exec/exec_test.go +++ b/plugin/pkg/client/auth/exec/exec_test.go @@ -27,7 +27,7 @@ import ( "encoding/json" "encoding/pem" "fmt" - "io/ioutil" + "io" "math/big" "net/http" "net/http/httptest" @@ -888,7 +888,7 @@ func TestRoundTripper(t *testing.T) { } a.environ = environ a.now = now - a.stderr = ioutil.Discard + a.stderr = io.Discard tc := &transport.Config{} if err := a.UpdateTransportConfig(tc); err != nil { @@ -1051,7 +1051,7 @@ func TestTLSCredentials(t *testing.T) { return []string{"TEST_OUTPUT=" + string(data)} } a.now = func() time.Time { return now } - a.stderr = ioutil.Discard + a.stderr = io.Discard // We're not interested in server's cert, this test is about client cert. tc := &transport.Config{TLS: transport.TLSConfig{Insecure: true}} @@ -1134,7 +1134,7 @@ func TestConcurrentUpdateTransportConfig(t *testing.T) { } a.environ = environ a.now = now - a.stderr = ioutil.Discard + a.stderr = io.Discard stopCh := make(chan struct{}) defer close(stopCh) diff --git a/plugin/pkg/client/auth/oidc/oidc.go b/plugin/pkg/client/auth/oidc/oidc.go index 8fc37692..70e8b57b 100644 --- a/plugin/pkg/client/auth/oidc/oidc.go +++ b/plugin/pkg/client/auth/oidc/oidc.go @@ -22,7 +22,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "strings" "sync" @@ -301,7 +301,7 @@ func tokenEndpoint(client *http.Client, issuer string) (string, error) { } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return "", err } diff --git a/rest/config.go b/rest/config.go index 4909dc53..d61ca203 100644 --- a/rest/config.go +++ b/rest/config.go @@ -20,7 +20,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "net" "net/http" "net/url" @@ -519,7 +518,7 @@ func InClusterConfig() (*Config, error) { return nil, ErrNotInCluster } - token, err := ioutil.ReadFile(tokenFile) + token, err := os.ReadFile(tokenFile) if err != nil { return nil, err } @@ -585,7 +584,7 @@ func dataFromSliceOrFile(data []byte, file string) ([]byte, error) { return data, nil } if len(file) > 0 { - fileData, err := ioutil.ReadFile(file) + fileData, err := os.ReadFile(file) if err != nil { return []byte{}, err } diff --git a/rest/request.go b/rest/request.go index dba933f7..f2573ad7 100644 --- a/rest/request.go +++ b/rest/request.go @@ -22,10 +22,10 @@ import ( "encoding/hex" "fmt" "io" - "io/ioutil" "mime" "net/http" "net/url" + "os" "path" "reflect" "strconv" @@ -437,7 +437,7 @@ func (r *Request) Body(obj interface{}) *Request { } switch t := obj.(type) { case string: - data, err := ioutil.ReadFile(t) + data, err := os.ReadFile(t) if err != nil { r.err = err return r @@ -745,7 +745,7 @@ func (r *Request) Stream(ctx context.Context) (io.ReadCloser, error) { return nil, err } if r.body != nil { - req.Body = ioutil.NopCloser(r.body) + req.Body = io.NopCloser(r.body) } resp, err := client.Do(req) updateURLMetrics(ctx, r, resp, err) @@ -937,7 +937,7 @@ func (r *Request) Do(ctx context.Context) Result { func (r *Request) DoRaw(ctx context.Context) ([]byte, error) { var result Result err := r.request(ctx, func(req *http.Request, resp *http.Response) { - result.body, result.err = ioutil.ReadAll(resp.Body) + result.body, result.err = io.ReadAll(resp.Body) glogBody("Response Body", result.body) if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent { result.err = r.transformUnstructuredResponseError(resp, req, result.body) @@ -956,7 +956,7 @@ func (r *Request) DoRaw(ctx context.Context) ([]byte, error) { func (r *Request) transformResponse(resp *http.Response, req *http.Request) Result { var body []byte if resp.Body != nil { - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) switch err.(type) { case nil: body = data @@ -1098,7 +1098,7 @@ const maxUnstructuredResponseTextBytes = 2048 // TODO: introduce transformation of generic http.Client.Do() errors that separates 4. func (r *Request) transformUnstructuredResponseError(resp *http.Response, req *http.Request, body []byte) error { if body == nil && resp.Body != nil { - if data, err := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: maxUnstructuredResponseTextBytes}); err == nil { + if data, err := io.ReadAll(&io.LimitedReader{R: resp.Body, N: maxUnstructuredResponseTextBytes}); err == nil { body = data } } diff --git a/rest/request_test.go b/rest/request_test.go index ddde5f76..669675e0 100644 --- a/rest/request_test.go +++ b/rest/request_test.go @@ -23,7 +23,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -88,7 +87,7 @@ func TestRequestSetsHeaders(t *testing.T) { } return &http.Response{ StatusCode: http.StatusForbidden, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + Body: io.NopCloser(bytes.NewReader([]byte{})), }, nil }) config := defaultContentConfig() @@ -303,7 +302,7 @@ func TestRequestBody(t *testing.T) { } // test error set when failing to read file - f, err := ioutil.TempFile("", "test") + f, err := os.CreateTemp("", "test") if err != nil { t.Fatalf("unable to create temp file") } @@ -360,7 +359,7 @@ func TestTransformResponse(t *testing.T) { Response: &http.Response{ StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), + Body: io.NopCloser(bytes.NewReader(invalid)), }, Error: true, ErrFn: func(err error) bool { @@ -371,7 +370,7 @@ func TestTransformResponse(t *testing.T) { Response: &http.Response{ StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"text/any"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), + Body: io.NopCloser(bytes.NewReader(invalid)), }, Error: true, ErrFn: func(err error) bool { @@ -379,13 +378,13 @@ func TestTransformResponse(t *testing.T) { }, }, {Response: &http.Response{StatusCode: http.StatusForbidden}, Error: true}, - {Response: &http.Response{StatusCode: http.StatusOK, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid}, - {Response: &http.Response{StatusCode: http.StatusOK, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid}, + {Response: &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(invalid))}, Data: invalid}, + {Response: &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(invalid))}, Data: invalid}, } for i, test := range testCases { r := NewRequestWithClient(uri, "", defaultContentConfig(), nil) if test.Response.Body == nil { - test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) + test.Response.Body = io.NopCloser(bytes.NewReader([]byte{})) } result := r.transformResponse(test.Response, &http.Request{}) response, created, err := result.body, result.statusCode == http.StatusCreated, result.err @@ -458,7 +457,7 @@ func TestTransformResponseNegotiate(t *testing.T) { Response: &http.Response{ StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), + Body: io.NopCloser(bytes.NewReader(invalid)), }, Called: true, ExpectContentType: "application/json", @@ -472,7 +471,7 @@ func TestTransformResponseNegotiate(t *testing.T) { Response: &http.Response{ StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/protobuf"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), + Body: io.NopCloser(bytes.NewReader(invalid)), }, Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), @@ -502,7 +501,7 @@ func TestTransformResponseNegotiate(t *testing.T) { Response: &http.Response{ StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/any"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), + Body: io.NopCloser(bytes.NewReader(invalid)), }, Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), Called: true, @@ -513,7 +512,7 @@ func TestTransformResponseNegotiate(t *testing.T) { ContentType: "text/any", Response: &http.Response{ StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), + Body: io.NopCloser(bytes.NewReader(invalid)), }, Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), Called: true, @@ -525,7 +524,7 @@ func TestTransformResponseNegotiate(t *testing.T) { Response: &http.Response{ StatusCode: http.StatusNotFound, Header: http.Header{"Content-Type": []string{"application/unrecognized"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), + Body: io.NopCloser(bytes.NewReader(invalid)), }, Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), @@ -549,7 +548,7 @@ func TestTransformResponseNegotiate(t *testing.T) { contentConfig.Negotiator = negotiator r := NewRequestWithClient(uri, "", contentConfig, nil) if test.Response.Body == nil { - test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) + test.Response.Body = io.NopCloser(bytes.NewReader([]byte{})) } result := r.transformResponse(test.Response, &http.Request{}) _, err := result.body, result.err @@ -601,7 +600,7 @@ func TestTransformUnstructuredError(t *testing.T) { }, Res: &http.Response{ StatusCode: http.StatusConflict, - Body: ioutil.NopCloser(bytes.NewReader(nil)), + Body: io.NopCloser(bytes.NewReader(nil)), }, ErrFn: apierrors.IsAlreadyExists, }, @@ -613,7 +612,7 @@ func TestTransformUnstructuredError(t *testing.T) { }, Res: &http.Response{ StatusCode: http.StatusConflict, - Body: ioutil.NopCloser(bytes.NewReader(nil)), + Body: io.NopCloser(bytes.NewReader(nil)), }, ErrFn: apierrors.IsConflict, }, @@ -623,7 +622,7 @@ func TestTransformUnstructuredError(t *testing.T) { Req: &http.Request{}, Res: &http.Response{ StatusCode: http.StatusNotFound, - Body: ioutil.NopCloser(bytes.NewReader(nil)), + Body: io.NopCloser(bytes.NewReader(nil)), }, ErrFn: apierrors.IsNotFound, }, @@ -631,14 +630,14 @@ func TestTransformUnstructuredError(t *testing.T) { Req: &http.Request{}, Res: &http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader(nil)), + Body: io.NopCloser(bytes.NewReader(nil)), }, ErrFn: apierrors.IsBadRequest, }, { // status in response overrides transformed result Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","status":"Failure","code":404}`)))}, + Res: &http.Response{StatusCode: http.StatusBadRequest, Body: io.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","status":"Failure","code":404}`)))}, ErrFn: apierrors.IsBadRequest, Transformed: &apierrors.StatusError{ ErrStatus: metav1.Status{Status: metav1.StatusFailure, Code: http.StatusNotFound}, @@ -647,20 +646,20 @@ func TestTransformUnstructuredError(t *testing.T) { { // successful status is ignored Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","status":"Success","code":404}`)))}, + Res: &http.Response{StatusCode: http.StatusBadRequest, Body: io.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","status":"Success","code":404}`)))}, ErrFn: apierrors.IsBadRequest, }, { // empty object does not change result Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{}`)))}, + Res: &http.Response{StatusCode: http.StatusBadRequest, Body: io.NopCloser(bytes.NewReader([]byte(`{}`)))}, ErrFn: apierrors.IsBadRequest, }, { // we default apiVersion for backwards compatibility with old clients // TODO: potentially remove in 1.7 Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","status":"Failure","code":404}`)))}, + Res: &http.Response{StatusCode: http.StatusBadRequest, Body: io.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","status":"Failure","code":404}`)))}, ErrFn: apierrors.IsBadRequest, Transformed: &apierrors.StatusError{ ErrStatus: metav1.Status{Status: metav1.StatusFailure, Code: http.StatusNotFound}, @@ -669,7 +668,7 @@ func TestTransformUnstructuredError(t *testing.T) { { // we do not default kind Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"status":"Failure","code":404}`)))}, + Res: &http.Response{StatusCode: http.StatusBadRequest, Body: io.NopCloser(bytes.NewReader([]byte(`{"status":"Failure","code":404}`)))}, ErrFn: apierrors.IsBadRequest, }, } @@ -773,7 +772,7 @@ func TestRequestWatch(t *testing.T) { serverReturns: []responseErr{ {response: &http.Response{ StatusCode: http.StatusForbidden, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + Body: io.NopCloser(bytes.NewReader([]byte{})), }, err: nil}, }, attemptsExpected: 1, @@ -816,7 +815,7 @@ func TestRequestWatch(t *testing.T) { serverReturns: []responseErr{ {response: &http.Response{ StatusCode: http.StatusForbidden, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + Body: io.NopCloser(bytes.NewReader([]byte{})), }, err: nil}, }, attemptsExpected: 1, @@ -836,7 +835,7 @@ func TestRequestWatch(t *testing.T) { serverReturns: []responseErr{ {response: &http.Response{ StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + Body: io.NopCloser(bytes.NewReader([]byte{})), }, err: nil}, }, attemptsExpected: 1, @@ -856,7 +855,7 @@ func TestRequestWatch(t *testing.T) { serverReturns: []responseErr{ {response: &http.Response{ StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &metav1.Status{ + Body: io.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &metav1.Status{ Status: metav1.StatusFailure, Reason: metav1.StatusReasonUnauthorized, })))), @@ -1088,7 +1087,7 @@ func TestRequestStream(t *testing.T) { serverReturns: []responseErr{ {response: &http.Response{ StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &metav1.Status{ + Body: io.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &metav1.Status{ Status: metav1.StatusFailure, Reason: metav1.StatusReasonUnauthorized, })))), @@ -1107,7 +1106,7 @@ func TestRequestStream(t *testing.T) { serverReturns: []responseErr{ {response: &http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"a container name must be specified for pod kube-dns-v20-mz5cv, choose one of: [kubedns dnsmasq healthz]","reason":"BadRequest","code":400}`))), + Body: io.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"a container name must be specified for pod kube-dns-v20-mz5cv, choose one of: [kubedns dnsmasq healthz]","reason":"BadRequest","code":400}`))), }, err: nil}, }, attemptsExpected: 1, @@ -1188,7 +1187,7 @@ func TestRequestStream(t *testing.T) { {response: retryAfterResponse(), err: nil}, {response: &http.Response{ StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + Body: io.NopCloser(bytes.NewReader([]byte{})), }, err: nil}, }, }, @@ -1427,7 +1426,7 @@ func TestConnectionResetByPeerIsRetried(t *testing.T) { if count >= 3 { return &http.Response{ StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + Body: io.NopCloser(bytes.NewReader([]byte{})), }, nil } return nil, &net.OpError{Err: syscall.ECONNRESET} @@ -1455,7 +1454,7 @@ func TestCheckRetryHandles429And5xx(t *testing.T) { count := 0 ch := make(chan struct{}) testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - data, err := ioutil.ReadAll(req.Body) + data, err := io.ReadAll(req.Body) if err != nil { t.Fatalf("unable to read request body: %v", err) } @@ -1607,7 +1606,7 @@ func TestDoRequestNewWayFile(t *testing.T) { t.Errorf("unexpected error: %v", err) } - file, err := ioutil.TempFile("", "foo") + file, err := os.CreateTemp("", "foo") if err != nil { t.Errorf("unexpected error: %v", err) } @@ -1779,7 +1778,7 @@ func TestBody(t *testing.T) { obj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} bodyExpected, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), obj) - f, err := ioutil.TempFile("", "test_body") + f, err := os.CreateTemp("", "test_body") if err != nil { t.Fatalf("TempFile error: %v", err) } @@ -2449,7 +2448,7 @@ func TestRequestWithRetry(t *testing.T) { }{ { name: "server returns retry-after response, request body is not io.Seeker, retry goes ahead", - body: ioutil.NopCloser(bytes.NewReader([]byte{})), + body: io.NopCloser(bytes.NewReader([]byte{})), serverReturns: responseErr{response: retryAfterResponse(), err: nil}, errExpected: nil, transformFuncInvokedExpected: 1, @@ -2473,7 +2472,7 @@ func TestRequestWithRetry(t *testing.T) { }, { name: "server returns retryable err, request body is not io.Seek, retry goes ahead", - body: ioutil.NopCloser(bytes.NewReader([]byte{})), + body: io.NopCloser(bytes.NewReader([]byte{})), serverReturns: responseErr{response: nil, err: io.ErrUnexpectedEOF}, errExpected: io.ErrUnexpectedEOF, transformFuncInvokedExpected: 0, @@ -2773,7 +2772,7 @@ func testRequestWithRetry(t *testing.T, key string, doFunc func(ctx context.Cont resp := test.serverReturns[attempts].response if resp != nil { - responseRecorder.delegated = ioutil.NopCloser(bytes.NewReader([]byte{})) + responseRecorder.delegated = io.NopCloser(bytes.NewReader([]byte{})) resp.Body = responseRecorder } return resp, test.serverReturns[attempts].err @@ -3054,7 +3053,7 @@ func testRetryWithRateLimiterBackoffAndMetrics(t *testing.T, key string, doFunc interceptor.Do() resp := test.serverReturns[attempts].response if resp != nil { - resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) + resp.Body = io.NopCloser(bytes.NewReader([]byte{})) } return resp, test.serverReturns[attempts].err }) @@ -3190,7 +3189,7 @@ func testWithRetryInvokeOrder(t *testing.T, key string, doFunc func(ctx context. interceptor.Do() resp := test.serverReturns[attempts].response if resp != nil { - resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) + resp.Body = io.NopCloser(bytes.NewReader([]byte{})) } return resp, test.serverReturns[attempts].err }) @@ -3365,7 +3364,7 @@ func testWithWrapPreviousError(t *testing.T, doFunc func(ctx context.Context, r resp := test.serverReturns[attempts].response if resp != nil { - resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) + resp.Body = io.NopCloser(bytes.NewReader([]byte{})) } return resp, test.serverReturns[attempts].err }) @@ -3665,12 +3664,12 @@ func TestRequestBodyResetOrder(t *testing.T) { }() // read the request body. - ioutil.ReadAll(req.Body) + io.ReadAll(req.Body) // first attempt, we send a retry-after if attempts == 0 { resp := retryAfterResponse() - respBodyTracker.ReadCloser = ioutil.NopCloser(bytes.NewReader([]byte{})) + respBodyTracker.ReadCloser = io.NopCloser(bytes.NewReader([]byte{})) resp.Body = respBodyTracker return resp, nil } diff --git a/rest/watch/encoder_test.go b/rest/watch/encoder_test.go index b56ce432..da182b1b 100644 --- a/rest/watch/encoder_test.go +++ b/rest/watch/encoder_test.go @@ -18,7 +18,7 @@ package versioned_test import ( "bytes" - "io/ioutil" + "io" "testing" "k8s.io/api/core/v1" @@ -70,7 +70,7 @@ func TestEncodeDecodeRoundTrip(t *testing.T) { continue } - rc := ioutil.NopCloser(buf) + rc := io.NopCloser(buf) decoder := restclientwatch.NewDecoder(streaming.NewDecoder(rc, getDecoder()), getDecoder()) event, obj, err := decoder.Decode() if err != nil { diff --git a/rest/with_retry.go b/rest/with_retry.go index bdcc6f3a..b04e3e9e 100644 --- a/rest/with_retry.go +++ b/rest/with_retry.go @@ -20,7 +20,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "net/url" "time" @@ -345,7 +344,7 @@ func readAndCloseResponseBody(resp *http.Response) { defer resp.Body.Close() if resp.ContentLength <= maxBodySlurpSize { - io.Copy(ioutil.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize}) + io.Copy(io.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize}) } } diff --git a/scale/client_test.go b/scale/client_test.go index c5386cea..058bf3c1 100644 --- a/scale/client_test.go +++ b/scale/client_test.go @@ -22,7 +22,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "testing" @@ -46,7 +45,7 @@ import ( ) func bytesBody(bodyBytes []byte) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader(bodyBytes)) + return io.NopCloser(bytes.NewReader(bodyBytes)) } func defaultHeaders() http.Header { @@ -184,7 +183,7 @@ func fakeScaleClient(t *testing.T) (ScalesGetter, []schema.GroupResource) { return &http.Response{StatusCode: http.StatusOK, Header: defaultHeaders(), Body: bytesBody(res)}, nil case "PUT": decoder := codecs.UniversalDeserializer() - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) if err != nil { return nil, err } @@ -201,7 +200,7 @@ func fakeScaleClient(t *testing.T) (ScalesGetter, []schema.GroupResource) { } return &http.Response{StatusCode: http.StatusOK, Header: defaultHeaders(), Body: bytesBody(res)}, nil case "PATCH": - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) if err != nil { return nil, err } diff --git a/tools/auth/clientauth.go b/tools/auth/clientauth.go index ac30271f..c810e69e 100644 --- a/tools/auth/clientauth.go +++ b/tools/auth/clientauth.go @@ -65,7 +65,6 @@ package auth // TODO: need a way to rotate Tokens. Therefore, need a way for client object to be reset when the authcfg is updated. import ( "encoding/json" - "io/ioutil" "os" restclient "k8s.io/client-go/rest" @@ -90,7 +89,7 @@ func LoadFromFile(path string) (*Info, error) { if _, err := os.Stat(path); os.IsNotExist(err) { return nil, err } - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return nil, err } diff --git a/tools/auth/clientauth_test.go b/tools/auth/clientauth_test.go index 11f7369d..0e4fd299 100644 --- a/tools/auth/clientauth_test.go +++ b/tools/auth/clientauth_test.go @@ -17,7 +17,6 @@ limitations under the License. package auth_test import ( - "io/ioutil" "os" "reflect" "testing" @@ -42,7 +41,7 @@ func TestLoadFromFile(t *testing.T) { } for _, loadAuthInfoTest := range loadAuthInfoTests { tt := loadAuthInfoTest - aifile, err := ioutil.TempFile("", "testAuthInfo") + aifile, err := os.CreateTemp("", "testAuthInfo") if err != nil { t.Errorf("Unexpected error: %v", err) } diff --git a/tools/clientcmd/api/helpers.go b/tools/clientcmd/api/helpers.go index d677d651..1b4fefdb 100644 --- a/tools/clientcmd/api/helpers.go +++ b/tools/clientcmd/api/helpers.go @@ -20,7 +20,6 @@ import ( "encoding/base64" "errors" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -152,7 +151,7 @@ func FlattenContent(path *string, contents *[]byte, baseDir string) error { var err error absPath := ResolvePath(*path, baseDir) - *contents, err = ioutil.ReadFile(absPath) + *contents, err = os.ReadFile(absPath) if err != nil { return err } diff --git a/tools/clientcmd/api/helpers_test.go b/tools/clientcmd/api/helpers_test.go index 67231710..12aab343 100644 --- a/tools/clientcmd/api/helpers_test.go +++ b/tools/clientcmd/api/helpers_test.go @@ -18,7 +18,6 @@ package api import ( "fmt" - "io/ioutil" "os" "reflect" "testing" @@ -27,13 +26,13 @@ import ( ) func newMergedConfig(certFile, certContent, keyFile, keyContent, caFile, caContent string, t *testing.T) Config { - if err := ioutil.WriteFile(certFile, []byte(certContent), 0644); err != nil { + if err := os.WriteFile(certFile, []byte(certContent), 0644); err != nil { t.Errorf("unexpected error: %v", err) } - if err := ioutil.WriteFile(keyFile, []byte(keyContent), 0600); err != nil { + if err := os.WriteFile(keyFile, []byte(keyContent), 0600); err != nil { t.Errorf("unexpected error: %v", err) } - if err := ioutil.WriteFile(caFile, []byte(caContent), 0644); err != nil { + if err := os.WriteFile(caFile, []byte(caContent), 0644); err != nil { t.Errorf("unexpected error: %v", err) } @@ -52,11 +51,11 @@ func newMergedConfig(certFile, certContent, keyFile, keyContent, caFile, caConte } func TestMinifySuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") + certFile, _ := os.CreateTemp("", "") defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") + keyFile, _ := os.CreateTemp("", "") defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") + caFile, _ := os.CreateTemp("", "") defer os.Remove(caFile.Name()) mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) @@ -88,11 +87,11 @@ func TestMinifySuccess(t *testing.T) { } func TestMinifyMissingContext(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") + certFile, _ := os.CreateTemp("", "") defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") + keyFile, _ := os.CreateTemp("", "") defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") + caFile, _ := os.CreateTemp("", "") defer os.Remove(caFile.Name()) mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) @@ -106,11 +105,11 @@ func TestMinifyMissingContext(t *testing.T) { } func TestMinifyMissingCluster(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") + certFile, _ := os.CreateTemp("", "") defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") + keyFile, _ := os.CreateTemp("", "") defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") + caFile, _ := os.CreateTemp("", "") defer os.Remove(caFile.Name()) mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) @@ -124,11 +123,11 @@ func TestMinifyMissingCluster(t *testing.T) { } func TestMinifyMissingAuthInfo(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") + certFile, _ := os.CreateTemp("", "") defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") + keyFile, _ := os.CreateTemp("", "") defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") + caFile, _ := os.CreateTemp("", "") defer os.Remove(caFile.Name()) mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) @@ -142,11 +141,11 @@ func TestMinifyMissingAuthInfo(t *testing.T) { } func TestFlattenSuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") + certFile, _ := os.CreateTemp("", "") defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") + keyFile, _ := os.CreateTemp("", "") defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") + caFile, _ := os.CreateTemp("", "") defer os.Remove(caFile.Name()) certData := "cert" @@ -207,11 +206,11 @@ func TestFlattenSuccess(t *testing.T) { } func Example_minifyAndShorten() { - certFile, _ := ioutil.TempFile("", "") + certFile, _ := os.CreateTemp("", "") defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") + keyFile, _ := os.CreateTemp("", "") defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") + caFile, _ := os.CreateTemp("", "") defer os.Remove(caFile.Name()) certData := "cert" @@ -247,11 +246,11 @@ func Example_minifyAndShorten() { } func TestShortenSuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") + certFile, _ := os.CreateTemp("", "") defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") + keyFile, _ := os.CreateTemp("", "") defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") + caFile, _ := os.CreateTemp("", "") defer os.Remove(caFile.Name()) certData := "cert" diff --git a/tools/clientcmd/auth_loaders.go b/tools/clientcmd/auth_loaders.go index 5153a95a..ce951e88 100644 --- a/tools/clientcmd/auth_loaders.go +++ b/tools/clientcmd/auth_loaders.go @@ -20,7 +20,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "golang.org/x/term" @@ -59,7 +58,7 @@ func (a *PromptingAuthLoader) LoadAuth(path string) (*clientauth.Info, error) { if err != nil { return &auth, err } - err = ioutil.WriteFile(path, data, 0600) + err = os.WriteFile(path, data, 0600) return &auth, err } authPtr, err := clientauth.LoadFromFile(path) diff --git a/tools/clientcmd/client_config.go b/tools/clientcmd/client_config.go index cc37c9fb..6f06e2db 100644 --- a/tools/clientcmd/client_config.go +++ b/tools/clientcmd/client_config.go @@ -19,7 +19,6 @@ package clientcmd import ( "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -246,7 +245,7 @@ func (config *DirectClientConfig) getUserIdentificationPartialConfig(configAuthI mergedConfig.BearerToken = configAuthInfo.Token mergedConfig.BearerTokenFile = configAuthInfo.TokenFile } else if len(configAuthInfo.TokenFile) > 0 { - tokenBytes, err := ioutil.ReadFile(configAuthInfo.TokenFile) + tokenBytes, err := os.ReadFile(configAuthInfo.TokenFile) if err != nil { return nil, err } @@ -586,7 +585,7 @@ func (config *inClusterClientConfig) Namespace() (string, bool, error) { } // Fall back to the namespace associated with the service account token, if available - if data, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil { + if data, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil { if ns := strings.TrimSpace(string(data)); len(ns) > 0 { return ns, false, nil } diff --git a/tools/clientcmd/client_config_test.go b/tools/clientcmd/client_config_test.go index 6af32458..d539873f 100644 --- a/tools/clientcmd/client_config_test.go +++ b/tools/clientcmd/client_config_test.go @@ -17,7 +17,6 @@ limitations under the License. package clientcmd import ( - "io/ioutil" "os" "reflect" "strings" @@ -158,7 +157,7 @@ func TestInsecureOverridesCA(t *testing.T) { } func TestCAOverridesCAData(t *testing.T) { - file, err := ioutil.TempFile("", "my.ca") + file, err := os.CreateTemp("", "my.ca") if err != nil { t.Fatalf("could not create tempfile: %v", err) } @@ -293,7 +292,7 @@ func TestModifyContext(t *testing.T) { "clean": true, } - tempPath, err := ioutil.TempFile("", "testclientcmd-") + tempPath, err := os.CreateTemp("", "testclientcmd-") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -478,13 +477,13 @@ func TestBasicAuthData(t *testing.T) { func TestBasicTokenFile(t *testing.T) { token := "exampletoken" - f, err := ioutil.TempFile("", "tokenfile") + f, err := os.CreateTemp("", "tokenfile") if err != nil { t.Errorf("Unexpected error: %v", err) return } defer os.Remove(f.Name()) - if err := ioutil.WriteFile(f.Name(), []byte(token), 0644); err != nil { + if err := os.WriteFile(f.Name(), []byte(token), 0644); err != nil { t.Errorf("Unexpected error: %v", err) return } @@ -514,13 +513,13 @@ func TestBasicTokenFile(t *testing.T) { func TestPrecedenceTokenFile(t *testing.T) { token := "exampletoken" - f, err := ioutil.TempFile("", "tokenfile") + f, err := os.CreateTemp("", "tokenfile") if err != nil { t.Errorf("Unexpected error: %v", err) return } defer os.Remove(f.Name()) - if err := ioutil.WriteFile(f.Name(), []byte(token), 0644); err != nil { + if err := os.WriteFile(f.Name(), []byte(token), 0644); err != nil { t.Errorf("Unexpected error: %v", err) return } @@ -904,12 +903,12 @@ users: command: foo-command provideClusterInfo: true ` - tmpfile, err := ioutil.TempFile("", "kubeconfig") + tmpfile, err := os.CreateTemp("", "kubeconfig") if err != nil { t.Error(err) } defer os.Remove(tmpfile.Name()) - if err := ioutil.WriteFile(tmpfile.Name(), []byte(content), 0666); err != nil { + if err := os.WriteFile(tmpfile.Name(), []byte(content), 0666); err != nil { t.Error(err) } config, err := BuildConfigFromFlags("", tmpfile.Name()) diff --git a/tools/clientcmd/loader.go b/tools/clientcmd/loader.go index 4e301332..44de1d41 100644 --- a/tools/clientcmd/loader.go +++ b/tools/clientcmd/loader.go @@ -18,7 +18,6 @@ package clientcmd import ( "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -283,12 +282,12 @@ func (rules *ClientConfigLoadingRules) Migrate() error { return fmt.Errorf("cannot migrate %v to %v because it is a directory", source, destination) } - data, err := ioutil.ReadFile(source) + data, err := os.ReadFile(source) if err != nil { return err } // destination is created with mode 0666 before umask - err = ioutil.WriteFile(destination, data, 0666) + err = os.WriteFile(destination, data, 0666) if err != nil { return err } @@ -363,7 +362,7 @@ func (rules *ClientConfigLoadingRules) IsDefaultConfig(config *restclient.Config // LoadFromFile takes a filename and deserializes the contents into Config object func LoadFromFile(filename string) (*clientcmdapi.Config, error) { - kubeconfigBytes, err := ioutil.ReadFile(filename) + kubeconfigBytes, err := os.ReadFile(filename) if err != nil { return nil, err } @@ -429,7 +428,7 @@ func WriteToFile(config clientcmdapi.Config, filename string) error { } } - if err := ioutil.WriteFile(filename, content, 0600); err != nil { + if err := os.WriteFile(filename, content, 0600); err != nil { return err } return nil diff --git a/tools/clientcmd/loader_test.go b/tools/clientcmd/loader_test.go index bebc7fea..3c496b7a 100644 --- a/tools/clientcmd/loader_test.go +++ b/tools/clientcmd/loader_test.go @@ -19,7 +19,6 @@ package clientcmd import ( "bytes" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -132,10 +131,10 @@ func TestToleratingMissingFiles(t *testing.T) { } func TestErrorReadingFile(t *testing.T) { - commandLineFile, _ := ioutil.TempFile("", "") + commandLineFile, _ := os.CreateTemp("", "") defer os.Remove(commandLineFile.Name()) - if err := ioutil.WriteFile(commandLineFile.Name(), []byte("bogus value"), 0644); err != nil { + if err := os.WriteFile(commandLineFile.Name(), []byte("bogus value"), 0644); err != nil { t.Fatalf("Error creating tempfile: %v", err) } @@ -153,7 +152,7 @@ func TestErrorReadingFile(t *testing.T) { } func TestErrorReadingNonFile(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "") + tmpdir, err := os.MkdirTemp("", "") if err != nil { t.Fatalf("Couldn't create tmpdir") } @@ -173,9 +172,9 @@ func TestErrorReadingNonFile(t *testing.T) { } func TestConflictingCurrentContext(t *testing.T) { - commandLineFile, _ := ioutil.TempFile("", "") + commandLineFile, _ := os.CreateTemp("", "") defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") + envVarFile, _ := os.CreateTemp("", "") defer os.Remove(envVarFile.Name()) mockCommandLineConfig := clientcmdapi.Config{ @@ -254,7 +253,7 @@ users: null } func TestLoadingEmptyMaps(t *testing.T) { - configFile, _ := ioutil.TempFile("", "") + configFile, _ := os.CreateTemp("", "") defer os.Remove(configFile.Name()) mockConfig := clientcmdapi.Config{ @@ -280,10 +279,10 @@ func TestLoadingEmptyMaps(t *testing.T) { } func TestDuplicateClusterName(t *testing.T) { - configFile, _ := ioutil.TempFile("", "") + configFile, _ := os.CreateTemp("", "") defer os.Remove(configFile.Name()) - err := ioutil.WriteFile(configFile.Name(), []byte(` + err := os.WriteFile(configFile.Name(), []byte(` kind: Config apiVersion: v1 clusters: @@ -322,10 +321,10 @@ users: } func TestDuplicateContextName(t *testing.T) { - configFile, _ := ioutil.TempFile("", "") + configFile, _ := os.CreateTemp("", "") defer os.Remove(configFile.Name()) - err := ioutil.WriteFile(configFile.Name(), []byte(` + err := os.WriteFile(configFile.Name(), []byte(` kind: Config apiVersion: v1 clusters: @@ -364,10 +363,10 @@ users: } func TestDuplicateUserName(t *testing.T) { - configFile, _ := ioutil.TempFile("", "") + configFile, _ := os.CreateTemp("", "") defer os.Remove(configFile.Name()) - err := ioutil.WriteFile(configFile.Name(), []byte(` + err := os.WriteFile(configFile.Name(), []byte(` kind: Config apiVersion: v1 clusters: @@ -404,10 +403,10 @@ users: } func TestDuplicateExtensionName(t *testing.T) { - configFile, _ := ioutil.TempFile("", "") + configFile, _ := os.CreateTemp("", "") defer os.Remove(configFile.Name()) - err := ioutil.WriteFile(configFile.Name(), []byte(` + err := os.WriteFile(configFile.Name(), []byte(` kind: Config apiVersion: v1 clusters: @@ -472,14 +471,14 @@ func TestResolveRelativePaths(t *testing.T) { }, } - configDir1, _ := ioutil.TempDir("", "") + configDir1, _ := os.MkdirTemp("", "") defer os.RemoveAll(configDir1) configFile1 := path.Join(configDir1, ".kubeconfig") configDir1, _ = filepath.Abs(configDir1) - configDir2, _ := ioutil.TempDir("", "") + configDir2, _ := os.MkdirTemp("", "") defer os.RemoveAll(configDir2) - configDir2, _ = ioutil.TempDir(configDir2, "") + configDir2, _ = os.MkdirTemp(configDir2, "") configFile2 := path.Join(configDir2, ".kubeconfig") configDir2, _ = filepath.Abs(configDir2) @@ -560,9 +559,9 @@ func TestResolveRelativePaths(t *testing.T) { } func TestMigratingFile(t *testing.T) { - sourceFile, _ := ioutil.TempFile("", "") + sourceFile, _ := os.CreateTemp("", "") defer os.Remove(sourceFile.Name()) - destinationFile, _ := ioutil.TempFile("", "") + destinationFile, _ := os.CreateTemp("", "") // delete the file so that we'll write to it os.Remove(destinationFile.Name()) @@ -579,11 +578,11 @@ func TestMigratingFile(t *testing.T) { // the load should have recreated this file defer os.Remove(destinationFile.Name()) - sourceContent, err := ioutil.ReadFile(sourceFile.Name()) + sourceContent, err := os.ReadFile(sourceFile.Name()) if err != nil { t.Errorf("unexpected error %v", err) } - destinationContent, err := ioutil.ReadFile(destinationFile.Name()) + destinationContent, err := os.ReadFile(destinationFile.Name()) if err != nil { t.Errorf("unexpected error %v", err) } @@ -594,9 +593,9 @@ func TestMigratingFile(t *testing.T) { } func TestMigratingFileLeaveExistingFileAlone(t *testing.T) { - sourceFile, _ := ioutil.TempFile("", "") + sourceFile, _ := os.CreateTemp("", "") defer os.Remove(sourceFile.Name()) - destinationFile, _ := ioutil.TempFile("", "") + destinationFile, _ := os.CreateTemp("", "") defer os.Remove(destinationFile.Name()) WriteToFile(testConfigAlfa, sourceFile.Name()) @@ -609,7 +608,7 @@ func TestMigratingFileLeaveExistingFileAlone(t *testing.T) { t.Errorf("unexpected error %v", err) } - destinationContent, err := ioutil.ReadFile(destinationFile.Name()) + destinationContent, err := os.ReadFile(destinationFile.Name()) if err != nil { t.Errorf("unexpected error %v", err) } @@ -621,7 +620,7 @@ func TestMigratingFileLeaveExistingFileAlone(t *testing.T) { func TestMigratingFileSourceMissingSkip(t *testing.T) { sourceFilename := "some-missing-file" - destinationFile, _ := ioutil.TempFile("", "") + destinationFile, _ := os.CreateTemp("", "") // delete the file so that we'll write to it os.Remove(destinationFile.Name()) @@ -639,7 +638,7 @@ func TestMigratingFileSourceMissingSkip(t *testing.T) { } func TestFileLocking(t *testing.T) { - f, _ := ioutil.TempFile("", "") + f, _ := os.CreateTemp("", "") defer os.Remove(f.Name()) err := lockFile(f.Name()) @@ -655,9 +654,9 @@ func TestFileLocking(t *testing.T) { } func Example_noMergingOnExplicitPaths() { - commandLineFile, _ := ioutil.TempFile("", "") + commandLineFile, _ := os.CreateTemp("", "") defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") + envVarFile, _ := os.CreateTemp("", "") defer os.Remove(envVarFile.Name()) WriteToFile(testConfigAlfa, commandLineFile.Name()) @@ -704,9 +703,9 @@ func Example_noMergingOnExplicitPaths() { } func Example_mergingSomeWithConflict() { - commandLineFile, _ := ioutil.TempFile("", "") + commandLineFile, _ := os.CreateTemp("", "") defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") + envVarFile, _ := os.CreateTemp("", "") defer os.Remove(envVarFile.Name()) WriteToFile(testConfigAlfa, commandLineFile.Name()) @@ -759,13 +758,13 @@ func Example_mergingSomeWithConflict() { } func Example_mergingEverythingNoConflicts() { - commandLineFile, _ := ioutil.TempFile("", "") + commandLineFile, _ := os.CreateTemp("", "") defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") + envVarFile, _ := os.CreateTemp("", "") defer os.Remove(envVarFile.Name()) - currentDirFile, _ := ioutil.TempFile("", "") + currentDirFile, _ := os.CreateTemp("", "") defer os.Remove(currentDirFile.Name()) - homeDirFile, _ := ioutil.TempFile("", "") + homeDirFile, _ := os.CreateTemp("", "") defer os.Remove(homeDirFile.Name()) WriteToFile(testConfigAlfa, commandLineFile.Name()) diff --git a/tools/clientcmd/main_test.go b/tools/clientcmd/main_test.go index 43a429b4..0c56d19c 100644 --- a/tools/clientcmd/main_test.go +++ b/tools/clientcmd/main_test.go @@ -17,14 +17,13 @@ limitations under the License. package clientcmd import ( - "io/ioutil" "os" "path/filepath" "testing" ) func TestMain(m *testing.M) { - tmp, err := ioutil.TempDir("", "testkubeconfig") + tmp, err := os.MkdirTemp("", "testkubeconfig") if err != nil { panic(err) } diff --git a/tools/clientcmd/validation_test.go b/tools/clientcmd/validation_test.go index f0065e3c..7b8e2fd5 100644 --- a/tools/clientcmd/validation_test.go +++ b/tools/clientcmd/validation_test.go @@ -19,7 +19,6 @@ package clientcmd import ( "errors" "fmt" - "io/ioutil" "os" "strings" "testing" @@ -296,7 +295,7 @@ func TestValidateCleanClusterInfo(t *testing.T) { } func TestValidateCleanWithCAClusterInfo(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") + tempFile, _ := os.CreateTemp("", "") defer os.Remove(tempFile.Name()) config := clientcmdapi.NewConfig() @@ -339,7 +338,7 @@ func TestValidateCertFilesNotFoundAuthInfo(t *testing.T) { } func TestValidateCertDataOverridesFiles(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") + tempFile, _ := os.CreateTemp("", "") defer os.Remove(tempFile.Name()) config := clientcmdapi.NewConfig() @@ -359,7 +358,7 @@ func TestValidateCertDataOverridesFiles(t *testing.T) { } func TestValidateCleanCertFilesAuthInfo(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") + tempFile, _ := os.CreateTemp("", "") defer os.Remove(tempFile.Name()) config := clientcmdapi.NewConfig() diff --git a/tools/portforward/portforward.go b/tools/portforward/portforward.go index 9e4da91c..f4c1984d 100644 --- a/tools/portforward/portforward.go +++ b/tools/portforward/portforward.go @@ -20,7 +20,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/http" "sort" @@ -351,7 +350,7 @@ func (pf *PortForwarder) handleConnection(conn net.Conn, port ForwardedPort) { errorChan := make(chan error) go func() { - message, err := ioutil.ReadAll(errorStream) + message, err := io.ReadAll(errorStream) switch { case err != nil: errorChan <- fmt.Errorf("error reading from error stream for port %d -> %d: %v", port.Local, port.Remote, err) diff --git a/tools/remotecommand/errorstream.go b/tools/remotecommand/errorstream.go index 360276b6..e60dd7cd 100644 --- a/tools/remotecommand/errorstream.go +++ b/tools/remotecommand/errorstream.go @@ -19,7 +19,6 @@ package remotecommand import ( "fmt" "io" - "io/ioutil" "k8s.io/apimachinery/pkg/util/runtime" ) @@ -39,7 +38,7 @@ func watchErrorStream(errorStream io.Reader, d errorStreamDecoder) chan error { go func() { defer runtime.HandleCrash() - message, err := ioutil.ReadAll(errorStream) + message, err := io.ReadAll(errorStream) switch { case err != nil && err != io.EOF: errorChan <- fmt.Errorf("error reading from error stream: %s", err) diff --git a/tools/remotecommand/remotecommand_test.go b/tools/remotecommand/remotecommand_test.go index d5485af8..7eec4565 100644 --- a/tools/remotecommand/remotecommand_test.go +++ b/tools/remotecommand/remotecommand_test.go @@ -20,7 +20,6 @@ import ( "encoding/json" "errors" "io" - "io/ioutil" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -72,7 +71,7 @@ func fakeMassiveDataAttacher(stdin io.Reader, stdout, stderr io.WriteCloser, tty } go func() { - io.Copy(ioutil.Discard, stdin) + io.Copy(io.Discard, stdin) copyDone <- struct{}{} }() diff --git a/tools/remotecommand/v1.go b/tools/remotecommand/v1.go index ff0fbd2d..53509c30 100644 --- a/tools/remotecommand/v1.go +++ b/tools/remotecommand/v1.go @@ -19,7 +19,6 @@ package remotecommand import ( "fmt" "io" - "io/ioutil" "net/http" "k8s.io/api/core/v1" @@ -111,7 +110,7 @@ func (p *streamProtocolV1) stream(conn streamCreator) error { // always read from errorStream go func() { - message, err := ioutil.ReadAll(p.errorStream) + message, err := io.ReadAll(p.errorStream) if err != nil && err != io.EOF { errorChan <- fmt.Errorf("Error reading from error stream: %s", err) return diff --git a/tools/remotecommand/v2.go b/tools/remotecommand/v2.go index 2f5561c9..d54612f4 100644 --- a/tools/remotecommand/v2.go +++ b/tools/remotecommand/v2.go @@ -19,7 +19,6 @@ package remotecommand import ( "fmt" "io" - "io/ioutil" "net/http" "sync" @@ -126,7 +125,7 @@ func (p *streamProtocolV2) copyStdin() { // this "copy" doesn't actually read anything - it's just here to wait for // the server to close remoteStdin. - if _, err := io.Copy(ioutil.Discard, p.remoteStdin); err != nil { + if _, err := io.Copy(io.Discard, p.remoteStdin); err != nil { runtime.HandleError(err) } }() @@ -145,7 +144,7 @@ func (p *streamProtocolV2) copyStdout(wg *sync.WaitGroup) { // make sure, packet in queue can be consumed. // block in queue may lead to deadlock in conn.server // issue: https://github.com/kubernetes/kubernetes/issues/96339 - defer io.Copy(ioutil.Discard, p.remoteStdout) + defer io.Copy(io.Discard, p.remoteStdout) if _, err := io.Copy(p.Stdout, p.remoteStdout); err != nil { runtime.HandleError(err) @@ -162,7 +161,7 @@ func (p *streamProtocolV2) copyStderr(wg *sync.WaitGroup) { go func() { defer runtime.HandleCrash() defer wg.Done() - defer io.Copy(ioutil.Discard, p.remoteStderr) + defer io.Copy(io.Discard, p.remoteStderr) if _, err := io.Copy(p.Stderr, p.remoteStderr); err != nil { runtime.HandleError(err) diff --git a/transport/token_source.go b/transport/token_source.go index 68a0a704..8e312800 100644 --- a/transport/token_source.go +++ b/transport/token_source.go @@ -18,8 +18,8 @@ package transport import ( "fmt" - "io/ioutil" "net/http" + "os" "strings" "sync" "time" @@ -132,7 +132,7 @@ type fileTokenSource struct { var _ = oauth2.TokenSource(&fileTokenSource{}) func (ts *fileTokenSource) Token() (*oauth2.Token, error) { - tokb, err := ioutil.ReadFile(ts.path) + tokb, err := os.ReadFile(ts.path) if err != nil { return nil, fmt.Errorf("failed to read token file %q: %v", ts.path, err) } diff --git a/transport/transport.go b/transport/transport.go index b4a7bfa6..8ba7056d 100644 --- a/transport/transport.go +++ b/transport/transport.go @@ -22,8 +22,8 @@ import ( "crypto/x509" "encoding/pem" "fmt" - "io/ioutil" "net/http" + "os" "sync" "time" @@ -170,7 +170,7 @@ func dataFromSliceOrFile(data []byte, file string) ([]byte, error) { return data, nil } if len(file) > 0 { - fileData, err := ioutil.ReadFile(file) + fileData, err := os.ReadFile(file) if err != nil { return []byte{}, err } diff --git a/util/cert/cert.go b/util/cert/cert.go index 75143ec0..7196cf89 100644 --- a/util/cert/cert.go +++ b/util/cert/cert.go @@ -25,9 +25,9 @@ import ( "crypto/x509/pkix" "encoding/pem" "fmt" - "io/ioutil" "math/big" "net" + "os" "path/filepath" "strings" "time" @@ -101,9 +101,9 @@ func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, a certFixturePath := filepath.Join(fixtureDirectory, baseName+".crt") keyFixturePath := filepath.Join(fixtureDirectory, baseName+".key") if len(fixtureDirectory) > 0 { - cert, err := ioutil.ReadFile(certFixturePath) + cert, err := os.ReadFile(certFixturePath) if err == nil { - key, err := ioutil.ReadFile(keyFixturePath) + key, err := os.ReadFile(keyFixturePath) if err == nil { return cert, key, nil } @@ -188,10 +188,10 @@ func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, a } if len(fixtureDirectory) > 0 { - if err := ioutil.WriteFile(certFixturePath, certBuffer.Bytes(), 0644); err != nil { + if err := os.WriteFile(certFixturePath, certBuffer.Bytes(), 0644); err != nil { return nil, nil, fmt.Errorf("failed to write cert fixture to %s: %v", certFixturePath, err) } - if err := ioutil.WriteFile(keyFixturePath, keyBuffer.Bytes(), 0644); err != nil { + if err := os.WriteFile(keyFixturePath, keyBuffer.Bytes(), 0644); err != nil { return nil, nil, fmt.Errorf("failed to write key fixture to %s: %v", certFixturePath, err) } } diff --git a/util/cert/csr_test.go b/util/cert/csr_test.go index e81f25e9..594f6aab 100644 --- a/util/cert/csr_test.go +++ b/util/cert/csr_test.go @@ -20,8 +20,8 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/pem" - "io/ioutil" "net" + "os" "testing" "k8s.io/client-go/util/keyutil" @@ -36,7 +36,7 @@ func TestMakeCSR(t *testing.T) { dnsSANs := []string{"localhost"} ipSANs := []net.IP{netutils.ParseIPSloppy("127.0.0.1")} - keyData, err := ioutil.ReadFile(keyFile) + keyData, err := os.ReadFile(keyFile) if err != nil { t.Fatal(err) } diff --git a/util/cert/io.go b/util/cert/io.go index 35fde68a..a70e5132 100644 --- a/util/cert/io.go +++ b/util/cert/io.go @@ -19,7 +19,6 @@ package cert import ( "crypto/x509" "fmt" - "io/ioutil" "os" "path/filepath" ) @@ -66,13 +65,13 @@ func WriteCert(certPath string, data []byte) error { if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil { return err } - return ioutil.WriteFile(certPath, data, os.FileMode(0644)) + return os.WriteFile(certPath, data, os.FileMode(0644)) } // NewPool returns an x509.CertPool containing the certificates in the given PEM-encoded file. // Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates func NewPool(filename string) (*x509.CertPool, error) { - pemBlock, err := ioutil.ReadFile(filename) + pemBlock, err := os.ReadFile(filename) if err != nil { return nil, err } @@ -101,7 +100,7 @@ func NewPoolFromBytes(pemBlock []byte) (*x509.CertPool, error) { // CertsFromFile returns the x509.Certificates contained in the given PEM-encoded file. // Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates func CertsFromFile(file string) ([]*x509.Certificate, error) { - pemBlock, err := ioutil.ReadFile(file) + pemBlock, err := os.ReadFile(file) if err != nil { return nil, err } diff --git a/util/certificate/certificate_store_test.go b/util/certificate/certificate_store_test.go index 6d59f9dc..3d6abaa4 100644 --- a/util/certificate/certificate_store_test.go +++ b/util/certificate/certificate_store_test.go @@ -18,14 +18,13 @@ package certificate import ( "bytes" - "io/ioutil" "os" "path/filepath" "testing" ) func TestUpdateSymlinkExistingFileError(t *testing.T) { - dir, err := ioutil.TempDir("", "k8s-test-update-symlink") + dir, err := os.MkdirTemp("", "k8s-test-update-symlink") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -35,7 +34,7 @@ func TestUpdateSymlinkExistingFileError(t *testing.T) { } }() pairFile := filepath.Join(dir, "kubelet-current.pem") - if err := ioutil.WriteFile(pairFile, nil, 0600); err != nil { + if err := os.WriteFile(pairFile, nil, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", pairFile, err) } @@ -49,7 +48,7 @@ func TestUpdateSymlinkExistingFileError(t *testing.T) { } func TestUpdateSymlinkNewFileNotExist(t *testing.T) { - dir, err := ioutil.TempDir("", "k8s-test-update-symlink") + dir, err := os.MkdirTemp("", "k8s-test-update-symlink") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -59,7 +58,7 @@ func TestUpdateSymlinkNewFileNotExist(t *testing.T) { } }() oldPairFile := filepath.Join(dir, "kubelet-oldpair.pem") - if err := ioutil.WriteFile(oldPairFile, nil, 0600); err != nil { + if err := os.WriteFile(oldPairFile, nil, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", oldPairFile, err) } @@ -89,7 +88,7 @@ func TestUpdateSymlinkNewFileNotExist(t *testing.T) { } func TestUpdateSymlinkNoSymlink(t *testing.T) { - dir, err := ioutil.TempDir("", "k8s-test-update-symlink") + dir, err := os.MkdirTemp("", "k8s-test-update-symlink") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -99,7 +98,7 @@ func TestUpdateSymlinkNoSymlink(t *testing.T) { } }() pairFile := filepath.Join(dir, "kubelet-newfile.pem") - if err := ioutil.WriteFile(pairFile, nil, 0600); err != nil { + if err := os.WriteFile(pairFile, nil, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", pairFile, err) } @@ -124,7 +123,7 @@ func TestUpdateSymlinkNoSymlink(t *testing.T) { func TestUpdateSymlinkReplaceExistingSymlink(t *testing.T) { prefix := "kubelet" - dir, err := ioutil.TempDir("", "k8s-test-update-symlink") + dir, err := os.MkdirTemp("", "k8s-test-update-symlink") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -134,11 +133,11 @@ func TestUpdateSymlinkReplaceExistingSymlink(t *testing.T) { } }() oldPairFile := filepath.Join(dir, prefix+"-oldfile.pem") - if err := ioutil.WriteFile(oldPairFile, nil, 0600); err != nil { + if err := os.WriteFile(oldPairFile, nil, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", oldPairFile, err) } newPairFile := filepath.Join(dir, prefix+"-newfile.pem") - if err := ioutil.WriteFile(newPairFile, nil, 0600); err != nil { + if err := os.WriteFile(newPairFile, nil, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", newPairFile, err) } currentPairFile := filepath.Join(dir, prefix+"-current.pem") @@ -178,7 +177,7 @@ func TestUpdateSymlinkReplaceExistingSymlink(t *testing.T) { } func TestLoadFile(t *testing.T) { - dir, err := ioutil.TempDir("", "k8s-test-load-cert-key-blocks") + dir, err := os.MkdirTemp("", "k8s-test-load-cert-key-blocks") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -199,7 +198,7 @@ func TestLoadFile(t *testing.T) { } for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { - if err := ioutil.WriteFile(pairFile, tt.data, 0600); err != nil { + if err := os.WriteFile(pairFile, tt.data, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", pairFile, err) } cert, err := loadFile(pairFile) @@ -218,7 +217,7 @@ func TestLoadFile(t *testing.T) { func TestUpdateNoRotation(t *testing.T) { prefix := "kubelet-server" - dir, err := ioutil.TempDir("", "k8s-test-certstore-current") + dir, err := os.MkdirTemp("", "k8s-test-certstore-current") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -228,11 +227,11 @@ func TestUpdateNoRotation(t *testing.T) { } }() keyFile := filepath.Join(dir, "kubelet.key") - if err := ioutil.WriteFile(keyFile, storeCertData.keyPEM, 0600); err != nil { + if err := os.WriteFile(keyFile, storeCertData.keyPEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", keyFile, err) } certFile := filepath.Join(dir, "kubelet.crt") - if err := ioutil.WriteFile(certFile, storeCertData.certificatePEM, 0600); err != nil { + if err := os.WriteFile(certFile, storeCertData.certificatePEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", certFile, err) } @@ -252,7 +251,7 @@ func TestUpdateNoRotation(t *testing.T) { func TestUpdateRotation(t *testing.T) { prefix := "kubelet-server" - dir, err := ioutil.TempDir("", "k8s-test-certstore-current") + dir, err := os.MkdirTemp("", "k8s-test-certstore-current") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -262,11 +261,11 @@ func TestUpdateRotation(t *testing.T) { } }() keyFile := filepath.Join(dir, "kubelet.key") - if err := ioutil.WriteFile(keyFile, storeCertData.keyPEM, 0600); err != nil { + if err := os.WriteFile(keyFile, storeCertData.keyPEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", keyFile, err) } certFile := filepath.Join(dir, "kubelet.crt") - if err := ioutil.WriteFile(certFile, storeCertData.certificatePEM, 0600); err != nil { + if err := os.WriteFile(certFile, storeCertData.certificatePEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", certFile, err) } @@ -286,7 +285,7 @@ func TestUpdateRotation(t *testing.T) { func TestUpdateTwoCerts(t *testing.T) { prefix := "kubelet-server" - dir, err := ioutil.TempDir("", "k8s-test-certstore-current") + dir, err := os.MkdirTemp("", "k8s-test-certstore-current") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -296,11 +295,11 @@ func TestUpdateTwoCerts(t *testing.T) { } }() keyFile := filepath.Join(dir, "kubelet.key") - if err := ioutil.WriteFile(keyFile, storeTwoCertsData.keyPEM, 0600); err != nil { + if err := os.WriteFile(keyFile, storeTwoCertsData.keyPEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", keyFile, err) } certFile := filepath.Join(dir, "kubelet.crt") - if err := ioutil.WriteFile(certFile, storeTwoCertsData.certificatePEM, 0600); err != nil { + if err := os.WriteFile(certFile, storeTwoCertsData.certificatePEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", certFile, err) } @@ -323,7 +322,7 @@ func TestUpdateTwoCerts(t *testing.T) { func TestUpdateWithBadCertKeyData(t *testing.T) { prefix := "kubelet-server" - dir, err := ioutil.TempDir("", "k8s-test-certstore-current") + dir, err := os.MkdirTemp("", "k8s-test-certstore-current") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -333,11 +332,11 @@ func TestUpdateWithBadCertKeyData(t *testing.T) { } }() keyFile := filepath.Join(dir, "kubelet.key") - if err := ioutil.WriteFile(keyFile, storeCertData.keyPEM, 0600); err != nil { + if err := os.WriteFile(keyFile, storeCertData.keyPEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", keyFile, err) } certFile := filepath.Join(dir, "kubelet.crt") - if err := ioutil.WriteFile(certFile, storeCertData.certificatePEM, 0600); err != nil { + if err := os.WriteFile(certFile, storeCertData.certificatePEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", certFile, err) } @@ -357,7 +356,7 @@ func TestUpdateWithBadCertKeyData(t *testing.T) { func TestCurrentPairFile(t *testing.T) { prefix := "kubelet-server" - dir, err := ioutil.TempDir("", "k8s-test-certstore-current") + dir, err := os.MkdirTemp("", "k8s-test-certstore-current") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -369,7 +368,7 @@ func TestCurrentPairFile(t *testing.T) { pairFile := filepath.Join(dir, prefix+"-pair.pem") data := append(storeCertData.certificatePEM, []byte("\n")...) data = append(data, storeCertData.keyPEM...) - if err := ioutil.WriteFile(pairFile, data, 0600); err != nil { + if err := os.WriteFile(pairFile, data, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", pairFile, err) } currentFile := filepath.Join(dir, prefix+"-current.pem") @@ -396,7 +395,7 @@ func TestCurrentPairFile(t *testing.T) { func TestCurrentCertKeyFiles(t *testing.T) { prefix := "kubelet-server" - dir, err := ioutil.TempDir("", "k8s-test-certstore-current") + dir, err := os.MkdirTemp("", "k8s-test-certstore-current") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -406,11 +405,11 @@ func TestCurrentCertKeyFiles(t *testing.T) { } }() certFile := filepath.Join(dir, "kubelet.crt") - if err := ioutil.WriteFile(certFile, storeCertData.certificatePEM, 0600); err != nil { + if err := os.WriteFile(certFile, storeCertData.certificatePEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", certFile, err) } keyFile := filepath.Join(dir, "kubelet.key") - if err := ioutil.WriteFile(keyFile, storeCertData.keyPEM, 0600); err != nil { + if err := os.WriteFile(keyFile, storeCertData.keyPEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", keyFile, err) } @@ -433,7 +432,7 @@ func TestCurrentCertKeyFiles(t *testing.T) { func TestCurrentTwoCerts(t *testing.T) { prefix := "kubelet-server" - dir, err := ioutil.TempDir("", "k8s-test-certstore-current") + dir, err := os.MkdirTemp("", "k8s-test-certstore-current") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } @@ -443,11 +442,11 @@ func TestCurrentTwoCerts(t *testing.T) { } }() certFile := filepath.Join(dir, "kubelet.crt") - if err := ioutil.WriteFile(certFile, storeTwoCertsData.certificatePEM, 0600); err != nil { + if err := os.WriteFile(certFile, storeTwoCertsData.certificatePEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", certFile, err) } keyFile := filepath.Join(dir, "kubelet.key") - if err := ioutil.WriteFile(keyFile, storeTwoCertsData.keyPEM, 0600); err != nil { + if err := os.WriteFile(keyFile, storeTwoCertsData.keyPEM, 0600); err != nil { t.Fatalf("Unable to create the file %q: %v", keyFile, err) } @@ -472,7 +471,7 @@ func TestCurrentTwoCerts(t *testing.T) { } func TestCurrentNoFiles(t *testing.T) { - dir, err := ioutil.TempDir("", "k8s-test-certstore-current") + dir, err := os.MkdirTemp("", "k8s-test-certstore-current") if err != nil { t.Fatalf("Unable to create the test directory %q: %v", dir, err) } diff --git a/util/keyutil/key.go b/util/keyutil/key.go index 83c2c625..ecd3e471 100644 --- a/util/keyutil/key.go +++ b/util/keyutil/key.go @@ -26,7 +26,6 @@ import ( "crypto/x509" "encoding/pem" "fmt" - "io/ioutil" "os" "path/filepath" ) @@ -69,13 +68,13 @@ func WriteKey(keyPath string, data []byte) error { if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil { return err } - return ioutil.WriteFile(keyPath, data, os.FileMode(0600)) + return os.WriteFile(keyPath, data, os.FileMode(0600)) } // LoadOrGenerateKeyFile looks for a key in the file at the given path. If it // can't find one, it will generate a new key and store it there. func LoadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error) { - loadedData, err := ioutil.ReadFile(keyPath) + loadedData, err := os.ReadFile(keyPath) // Call verifyKeyData to ensure the file wasn't empty/corrupt. if err == nil && verifyKeyData(loadedData) { return loadedData, false, err @@ -122,7 +121,7 @@ func MarshalPrivateKeyToPEM(privateKey crypto.PrivateKey) ([]byte, error) { // PrivateKeyFromFile returns the private key in rsa.PrivateKey or ecdsa.PrivateKey format from a given PEM-encoded file. // Returns an error if the file could not be read or if the private key could not be parsed. func PrivateKeyFromFile(file string) (interface{}, error) { - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { return nil, err } @@ -136,7 +135,7 @@ func PrivateKeyFromFile(file string) (interface{}, error) { // PublicKeysFromFile returns the public keys in rsa.PublicKey or ecdsa.PublicKey format from a given PEM-encoded file. // Reads public keys from both public and private key files. func PublicKeysFromFile(file string) ([]interface{}, error) { - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { return nil, err } diff --git a/util/keyutil/key_test.go b/util/keyutil/key_test.go index f3974de0..ee57c1f3 100644 --- a/util/keyutil/key_test.go +++ b/util/keyutil/key_test.go @@ -17,7 +17,6 @@ limitations under the License. package keyutil import ( - "io/ioutil" "os" "testing" ) @@ -115,7 +114,7 @@ q2bbtE7r1JMK+/sQA5sNAp+7Vdc3psr1OaNzyTyuhTECyRdFKXm63cMnGg== ) func TestReadPrivateKey(t *testing.T) { - f, err := ioutil.TempFile("", "") + f, err := os.CreateTemp("", "") if err != nil { t.Fatalf("error creating tmpfile: %v", err) } @@ -125,21 +124,21 @@ func TestReadPrivateKey(t *testing.T) { t.Fatalf("Expected error reading key from empty file, got none") } - if err := ioutil.WriteFile(f.Name(), []byte(rsaPrivateKey), os.FileMode(0600)); err != nil { + if err := os.WriteFile(f.Name(), []byte(rsaPrivateKey), os.FileMode(0600)); err != nil { t.Fatalf("error writing private key to tmpfile: %v", err) } if _, err := PrivateKeyFromFile(f.Name()); err != nil { t.Fatalf("error reading private RSA key: %v", err) } - if err := ioutil.WriteFile(f.Name(), []byte(ecdsaPrivateKey), os.FileMode(0600)); err != nil { + if err := os.WriteFile(f.Name(), []byte(ecdsaPrivateKey), os.FileMode(0600)); err != nil { t.Fatalf("error writing private key to tmpfile: %v", err) } if _, err := PrivateKeyFromFile(f.Name()); err != nil { t.Fatalf("error reading private ECDSA key: %v", err) } - if err := ioutil.WriteFile(f.Name(), []byte(ecdsaPrivateKeyWithParams), os.FileMode(0600)); err != nil { + if err := os.WriteFile(f.Name(), []byte(ecdsaPrivateKeyWithParams), os.FileMode(0600)); err != nil { t.Fatalf("error writing private key to tmpfile: %v", err) } if _, err := PrivateKeyFromFile(f.Name()); err != nil { @@ -148,7 +147,7 @@ func TestReadPrivateKey(t *testing.T) { } func TestReadPublicKeys(t *testing.T) { - f, err := ioutil.TempFile("", "") + f, err := os.CreateTemp("", "") if err != nil { t.Fatalf("error creating tmpfile: %v", err) } @@ -158,7 +157,7 @@ func TestReadPublicKeys(t *testing.T) { t.Fatalf("Expected error reading keys from empty file, got none") } - if err := ioutil.WriteFile(f.Name(), []byte(rsaPublicKey), os.FileMode(0600)); err != nil { + if err := os.WriteFile(f.Name(), []byte(rsaPublicKey), os.FileMode(0600)); err != nil { t.Fatalf("error writing public key to tmpfile: %v", err) } if keys, err := PublicKeysFromFile(f.Name()); err != nil { @@ -167,7 +166,7 @@ func TestReadPublicKeys(t *testing.T) { t.Fatalf("expected 1 key, got %d", len(keys)) } - if err := ioutil.WriteFile(f.Name(), []byte(ecdsaPublicKey), os.FileMode(0600)); err != nil { + if err := os.WriteFile(f.Name(), []byte(ecdsaPublicKey), os.FileMode(0600)); err != nil { t.Fatalf("error writing public key to tmpfile: %v", err) } if keys, err := PublicKeysFromFile(f.Name()); err != nil { @@ -176,7 +175,7 @@ func TestReadPublicKeys(t *testing.T) { t.Fatalf("expected 1 key, got %d", len(keys)) } - if err := ioutil.WriteFile(f.Name(), []byte(rsaPublicKey+"\n"+ecdsaPublicKey), os.FileMode(0600)); err != nil { + if err := os.WriteFile(f.Name(), []byte(rsaPublicKey+"\n"+ecdsaPublicKey), os.FileMode(0600)); err != nil { t.Fatalf("error writing public key to tmpfile: %v", err) } if keys, err := PublicKeysFromFile(f.Name()); err != nil { @@ -185,7 +184,7 @@ func TestReadPublicKeys(t *testing.T) { t.Fatalf("expected 2 keys, got %d", len(keys)) } - if err := ioutil.WriteFile(f.Name(), []byte(certificate), os.FileMode(0600)); err != nil { + if err := os.WriteFile(f.Name(), []byte(certificate), os.FileMode(0600)); err != nil { t.Fatalf("error writing certificate to tmpfile: %v", err) } if keys, err := PublicKeysFromFile(f.Name()); err != nil { diff --git a/util/testing/fake_handler.go b/util/testing/fake_handler.go index 6790cfd8..712a6464 100644 --- a/util/testing/fake_handler.go +++ b/util/testing/fake_handler.go @@ -17,7 +17,7 @@ limitations under the License. package testing import ( - "io/ioutil" + "io" "net/http" "net/url" "reflect" @@ -83,7 +83,7 @@ func (f *FakeHandler) ServeHTTP(response http.ResponseWriter, request *http.Requ response.WriteHeader(f.StatusCode) response.Write([]byte(f.ResponseBody)) - bodyReceived, err := ioutil.ReadAll(request.Body) + bodyReceived, err := io.ReadAll(request.Body) if err != nil && f.T != nil { f.T.Logf("Received read error: %v", err) } diff --git a/util/testing/fake_openapi_handler.go b/util/testing/fake_openapi_handler.go index 9c0c0443..e9a07acf 100644 --- a/util/testing/fake_openapi_handler.go +++ b/util/testing/fake_openapi_handler.go @@ -18,8 +18,8 @@ package testing import ( "encoding/json" + "io" "io/fs" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -71,7 +71,7 @@ func NewFakeOpenAPIV3Server(specsPath string) (*FakeOpenAPIServer, error) { } defer file.Close() - vals, err := ioutil.ReadAll(file) + vals, err := io.ReadAll(file) if err != nil { panic(err) } diff --git a/util/testing/tmpdir.go b/util/testing/tmpdir.go index 6e476f2c..73c1edb8 100644 --- a/util/testing/tmpdir.go +++ b/util/testing/tmpdir.go @@ -17,7 +17,6 @@ limitations under the License. package testing import ( - "io/ioutil" "os" ) @@ -26,7 +25,7 @@ import ( // deleted with a call to "os.RemoveAll(...)". // In case of error, it'll return an empty string and the error. func MkTmpdir(prefix string) (string, error) { - tmpDir, err := ioutil.TempDir(os.TempDir(), prefix) + tmpDir, err := os.MkdirTemp(os.TempDir(), prefix) if err != nil { return "", err }