From f714c9284c5f9f8411749953e4d9052468ead989 Mon Sep 17 00:00:00 2001 From: CrazyMax Date: Fri, 3 Dec 2021 14:09:44 +0100 Subject: [PATCH] Go 1.17 Signed-off-by: CrazyMax --- .circleci/config.yml | 5 +- Dockerfile | 3 +- agent/exec/dockerapi/controller_test.go | 5 +- agent/storage_test.go | 5 +- agent/testutils/fakes.go | 3 +- ca/certificates.go | 9 ++-- ca/certificates_test.go | 43 ++++++++-------- ca/config_test.go | 33 ++++++------ ca/external.go | 3 +- ca/keyreadwriter.go | 17 +++---- ca/keyreadwriter_test.go | 47 +++++++++-------- ca/server_test.go | 3 +- ca/testutils/cautils.go | 11 ++-- ca/transport_test.go | 7 ++- cmd/external-ca-example/main.go | 3 +- cmd/swarm-rafttool/common.go | 3 +- cmd/swarm-rafttool/common_test.go | 5 +- cmd/swarmctl/config/create.go | 6 +-- cmd/swarmctl/secret/create.go | 6 +-- cmd/swarmd/defaults/defaults_unix.go | 1 + cmd/swarmd/defaults/defaults_windows.go | 1 + cmd/swarmd/main.go | 2 +- integration/integration_test.go | 9 ++-- integration/node.go | 9 ++-- ioutils/ioutils.go | 3 +- ioutils/ioutils_test.go | 7 ++- .../cnmallocator/drivers_unsupported.go | 1 + manager/controlapi/ca_rotation_test.go | 7 ++- manager/controlapi/node_test.go | 6 +-- manager/controlapi/server_test.go | 3 +- manager/deks_test.go | 41 ++++++++------- manager/dirty_test.go | 5 +- manager/dispatcher/dispatcher_test.go | 4 +- manager/manager.go | 6 +-- manager/manager_test.go | 15 +++--- ...rchestrator_controlapi_integration_test.go | 3 +- manager/scheduler/topology_test.go | 3 +- manager/state/raft/membership/cluster_test.go | 6 +-- manager/state/raft/raft_test.go | 6 +-- manager/state/raft/storage/snapwrap.go | 3 +- manager/state/raft/storage/snapwrap_test.go | 21 ++++---- manager/state/raft/storage/storage.go | 4 +- manager/state/raft/storage/storage_test.go | 9 ++-- manager/state/raft/storage/walwrap.go | 5 +- manager/state/raft/storage/walwrap_test.go | 17 +++---- manager/state/raft/storage_test.go | 31 ++++++----- manager/state/raft/testutils/testutils.go | 3 +- manager/watchapi/server_test.go | 8 +-- node/node.go | 9 ++-- node/node_test.go | 51 +++++++++---------- xnet/xnet_unix.go | 1 + xnet/xnet_windows.go | 1 + 52 files changed, 246 insertions(+), 272 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 467f61e2ca..a47c4229d3 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -11,7 +11,8 @@ jobs: # Needed to install go OS: linux ARCH: amd64 - GOVERSION: 1.13 + GOVERSION: 1.17 + GO111MODULE: off # Needed to install protoc PROTOC_VERSION: 3.6.1 @@ -29,7 +30,7 @@ jobs: # /dev/shm in the container is tmpfs although files in /dev/shm are not executable. # If we specify TMPDIR=/dev/shm, /dev/shm will be used by our tests, which call - # ioutil.TempDir/ioutil.TempFile, to write temporary files. + # os.MkdirTemp/os.CreateTemp, to write temporary files. # We can also specify GOTMPDIR=/tmp or some other non-tmpfs directory # (see https://golang.org/doc/go1.10#goroot) - this is the directory in which the # go tool itself will put temporarily compiled test executables, etc. diff --git a/Dockerfile b/Dockerfile index 58dc21e720..6611c52c34 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # NOTE(dperny): for some reason, alpine was giving me trouble -ARG GO_VERSION=1.13.15 +ARG GO_VERSION=1.17.2 ARG DEBIAN_FRONTEND=noninteractive ARG BASE_DEBIAN_DISTRO="buster" ARG GOLANG_IMAGE="golang:${GO_VERSION}-${BASE_DEBIAN_DISTRO}" @@ -16,6 +16,7 @@ RUN curl --silent --show-error --location --output protoc.zip \ && unzip -d /usr/local protoc.zip include/\* bin/\* \ && rm -f protoc.zip +ENV GO111MODULE=off WORKDIR /go/src/github.com/docker/swarmkit/ # install the dependencies from `make setup` diff --git a/agent/exec/dockerapi/controller_test.go b/agent/exec/dockerapi/controller_test.go index 00a0914085..b08e6910ad 100644 --- a/agent/exec/dockerapi/controller_test.go +++ b/agent/exec/dockerapi/controller_test.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "reflect" "runtime" "testing" @@ -38,7 +37,7 @@ func TestControllerPrepare(t *testing.T) { client.ImagePullFn = func(_ context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) { if refStr == config.image() { - return ioutil.NopCloser(bytes.NewBuffer([]byte{})), nil + return io.NopCloser(bytes.NewBuffer([]byte{})), nil } panic("unexpected call of ImagePull") } @@ -68,7 +67,7 @@ func TestControllerPrepareAlreadyPrepared(t *testing.T) { client.ImagePullFn = func(_ context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) { if refStr == config.image() { - return ioutil.NopCloser(bytes.NewBuffer([]byte{})), nil + return io.NopCloser(bytes.NewBuffer([]byte{})), nil } panic("unexpected call of ImagePull") } diff --git a/agent/storage_test.go b/agent/storage_test.go index a488701db4..90f603b160 100644 --- a/agent/storage_test.go +++ b/agent/storage_test.go @@ -1,7 +1,6 @@ package agent import ( - "io/ioutil" "math/rand" "os" "path/filepath" @@ -176,11 +175,11 @@ func genTaskStatus() *api.TaskStatus { // tests. func storageTestEnv(t *testing.T) (*bolt.DB, func()) { var cleanup []func() - dir, err := ioutil.TempDir("", "agent-TestStorage-") + dir, err := os.MkdirTemp("", "agent-TestStorage-") assert.NoError(t, err) dbpath := filepath.Join(dir, "tasks.db") - assert.NoError(t, os.MkdirAll(dir, 0777)) + assert.NoError(t, os.MkdirAll(dir, 0o777)) cleanup = append(cleanup, func() { os.RemoveAll(dir) }) db, err := bolt.Open(dbpath, 0666, nil) diff --git a/agent/testutils/fakes.go b/agent/testutils/fakes.go index 0b01d1a890..1717c79630 100644 --- a/agent/testutils/fakes.go +++ b/agent/testutils/fakes.go @@ -2,7 +2,6 @@ package testutils import ( "context" - "io/ioutil" "net" "os" "path/filepath" @@ -235,7 +234,7 @@ func NewMockDispatcher(t *testing.T, secConfig *ca.SecurityConfig, local bool) ( cleanup func() ) if local { - tempDir, err := ioutil.TempDir("", "local-dispatcher-socket") + tempDir, err := os.MkdirTemp("", "local-dispatcher-socket") require.NoError(t, err) addr = filepath.Join(tempDir, "socket") l, err = net.Listen("unix", addr) diff --git a/ca/certificates.go b/ca/certificates.go index dd0297ab4f..2598057902 100644 --- a/ca/certificates.go +++ b/ca/certificates.go @@ -14,7 +14,6 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "os" "path/filepath" "time" @@ -687,7 +686,7 @@ func ensureCertKeyMatch(cert *x509.Certificate, key crypto.PublicKey) error { // CA certificate, and returns the PEM-encoded Certificate if so func GetLocalRootCA(paths CertPaths) (RootCA, error) { // Check if we have a Certificate file - cert, err := ioutil.ReadFile(paths.Cert) + cert, err := os.ReadFile(paths.Cert) if err != nil { if os.IsNotExist(err) { err = ErrNoLocalRootCA @@ -697,7 +696,7 @@ func GetLocalRootCA(paths CertPaths) (RootCA, error) { } signingCert := cert - key, err := ioutil.ReadFile(paths.Key) + key, err := os.ReadFile(paths.Key) if err != nil { if !os.IsNotExist(err) { return RootCA{}, err @@ -910,13 +909,13 @@ func readCertValidity(kr KeyReader) (time.Time, time.Time, error) { // SaveRootCA saves a RootCA object to disk func SaveRootCA(rootCA RootCA, paths CertPaths) error { // Make sure the necessary dirs exist and they are writable - err := os.MkdirAll(filepath.Dir(paths.Cert), 0755) + err := os.MkdirAll(filepath.Dir(paths.Cert), 0o755) if err != nil { return err } // If the root certificate got returned successfully, save the rootCA to disk. - return ioutils.AtomicWriteFile(paths.Cert, rootCA.Certs, 0644) + return ioutils.AtomicWriteFile(paths.Cert, rootCA.Certs, 0o644) } // GenerateNewCSR returns a newly generated key and CSR signed with said key diff --git a/ca/certificates_test.go b/ca/certificates_test.go index 9feb479bff..4d1fd77f9d 100644 --- a/ca/certificates_test.go +++ b/ca/certificates_test.go @@ -11,7 +11,6 @@ import ( "encoding/hex" "encoding/pem" "fmt" - "io/ioutil" "net" "os" "sync" @@ -79,7 +78,7 @@ func TestMain(m *testing.M) { } func TestCreateRootCASaveRootCA(t *testing.T) { - tempBaseDir, err := ioutil.TempDir("", "swarm-ca-test-") + tempBaseDir, err := os.MkdirTemp("", "swarm-ca-test-") assert.NoError(t, err) defer os.RemoveAll(tempBaseDir) @@ -100,7 +99,7 @@ func TestCreateRootCASaveRootCA(t *testing.T) { assert.True(t, os.IsNotExist(err)) // ensure that the cert that was written is already normalized - written, err := ioutil.ReadFile(paths.RootCA.Cert) + written, err := os.ReadFile(paths.RootCA.Cert) assert.NoError(t, err) assert.Equal(t, written, ca.NormalizePEMs(written)) } @@ -118,7 +117,7 @@ func TestCreateRootCAExpiry(t *testing.T) { } func TestGetLocalRootCA(t *testing.T) { - tempBaseDir, err := ioutil.TempDir("", "swarm-ca-test-") + tempBaseDir, err := os.MkdirTemp("", "swarm-ca-test-") assert.NoError(t, err) defer os.RemoveAll(tempBaseDir) @@ -144,7 +143,7 @@ func TestGetLocalRootCA(t *testing.T) { assert.Equal(t, err, ca.ErrNoValidSigner) // write private key and assert we can load it and sign - assert.NoError(t, ioutil.WriteFile(paths.RootCA.Key, s.Key, os.FileMode(0600))) + assert.NoError(t, os.WriteFile(paths.RootCA.Key, s.Key, os.FileMode(0o600))) rootCA3, err := ca.GetLocalRootCA(paths.RootCA) assert.NoError(t, err) assert.Equal(t, rootCA.Certs, rootCA3.Certs) @@ -160,30 +159,30 @@ func TestGetLocalRootCA(t *testing.T) { Type: "EC PRIVATE KEY", Bytes: privKeyBytes, }) - assert.NoError(t, ioutil.WriteFile(paths.RootCA.Key, privKeyPem, os.FileMode(0600))) + assert.NoError(t, os.WriteFile(paths.RootCA.Key, privKeyPem, os.FileMode(0o600))) _, err = ca.GetLocalRootCA(paths.RootCA) assert.EqualError(t, err, "certificate key mismatch") } func TestGetLocalRootCAInvalidCert(t *testing.T) { - tempBaseDir, err := ioutil.TempDir("", "swarm-ca-test-") + tempBaseDir, err := os.MkdirTemp("", "swarm-ca-test-") assert.NoError(t, err) defer os.RemoveAll(tempBaseDir) paths := ca.NewConfigPaths(tempBaseDir) // Write some garbage to the CA cert - require.NoError(t, ioutil.WriteFile(paths.RootCA.Cert, []byte(`-----BEGIN CERTIFICATE-----\n + require.NoError(t, os.WriteFile(paths.RootCA.Cert, []byte(`-----BEGIN CERTIFICATE-----\n some random garbage\n ------END CERTIFICATE-----`), 0644)) +-----END CERTIFICATE-----`), 0o644)) _, err = ca.GetLocalRootCA(paths.RootCA) require.Error(t, err) } func TestGetLocalRootCAInvalidKey(t *testing.T) { - tempBaseDir, err := ioutil.TempDir("", "swarm-ca-test-") + tempBaseDir, err := os.MkdirTemp("", "swarm-ca-test-") assert.NoError(t, err) defer os.RemoveAll(tempBaseDir) @@ -194,9 +193,9 @@ func TestGetLocalRootCAInvalidKey(t *testing.T) { require.NoError(t, ca.SaveRootCA(rootCA, paths.RootCA)) // Write some garbage to the root key - this will cause the loading to fail - require.NoError(t, ioutil.WriteFile(paths.RootCA.Key, []byte(`-----BEGIN PRIVATE KEY-----\n + require.NoError(t, os.WriteFile(paths.RootCA.Key, []byte(`-----BEGIN PRIVATE KEY-----\n some random garbage\n ------END PRIVATE KEY-----`), 0600)) +-----END PRIVATE KEY-----`), 0o600)) _, err = ca.GetLocalRootCA(paths.RootCA) require.Error(t, err) @@ -261,7 +260,7 @@ func TestGetRemoteCA(t *testing.T) { // update the test CA to include a multi-certificate bundle as the root - the digest // we use to verify with must be the digest of the whole bundle - tmpDir, err := ioutil.TempDir("", "GetRemoteCA") + tmpDir, err := os.MkdirTemp("", "GetRemoteCA") require.NoError(t, err) defer os.RemoveAll(tmpDir) paths := ca.NewConfigPaths(tmpDir) @@ -338,7 +337,7 @@ func testRequestAndSaveNewCertificates(t *testing.T, tc *cautils.TestCA) (*ca.Is require.False(t, perms.GroupWrite()) require.False(t, perms.OtherWrite()) - certs, err := ioutil.ReadFile(tc.Paths.Node.Cert) + certs, err := os.ReadFile(tc.Paths.Node.Cert) require.NoError(t, err) require.Equal(t, certs, ca.NormalizePEMs(certs)) @@ -374,7 +373,7 @@ func TestRequestAndSaveNewCertificatesWithIntermediates(t *testing.T) { CrossSignedCACert: concat([]byte(" "), cautils.ECDSACertChain[1]), }, } - tempdir, err := ioutil.TempDir("", "test-request-and-save-new-certificates") + tempdir, err := os.MkdirTemp("", "test-request-and-save-new-certificates") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -453,7 +452,7 @@ func TestRequestAndSaveNewCertificatesWithKEKUpdate(t *testing.T) { // returns the issuer of the issued certificate and the parsed certs of the issued certificate func testIssueAndSaveNewCertificates(t *testing.T, rca *ca.RootCA) { - tempdir, err := ioutil.TempDir("", "test-issue-and-save-new-certificates") + tempdir, err := os.MkdirTemp("", "test-issue-and-save-new-certificates") require.NoError(t, err) defer os.RemoveAll(tempdir) paths := ca.NewConfigPaths(tempdir) @@ -485,7 +484,7 @@ func testIssueAndSaveNewCertificates(t *testing.T, rca *ca.RootCA) { require.False(t, perms.GroupWrite()) require.False(t, perms.OtherWrite()) - certBytes, err := ioutil.ReadFile(paths.Node.Cert) + certBytes, err := os.ReadFile(paths.Node.Cert) require.NoError(t, err) parsed := checkLeafCert(t, certBytes, issuer.Subject.CommonName, "CN", role, "org", additionalNames...) if len(rca.Intermediates) > 0 { @@ -926,7 +925,7 @@ func TestNewRootCA(t *testing.T) { } func TestNewRootCABundle(t *testing.T) { - tempBaseDir, err := ioutil.TempDir("", "swarm-ca-test-") + tempBaseDir, err := os.MkdirTemp("", "swarm-ca-test-") assert.NoError(t, err) defer os.RemoveAll(tempBaseDir) @@ -944,7 +943,7 @@ func TestNewRootCABundle(t *testing.T) { // Overwrite the bytes of the second Root CA with the bundle, creating a valid 2 cert bundle bundle := append(firstRootCA.Certs, secondRootCA.Certs...) - err = ioutil.WriteFile(paths.RootCA.Cert, bundle, 0644) + err = os.WriteFile(paths.RootCA.Cert, bundle, 0o644) assert.NoError(t, err) newRootCA, err := ca.NewRootCA(bundle, firstRootCA.Certs, s.Key, ca.DefaultNodeCertExpiration, nil) @@ -957,7 +956,7 @@ func TestNewRootCABundle(t *testing.T) { _, _, err = newRootCA.IssueAndSaveNewCertificates(kw, "CN", "OU", "ORG") assert.NoError(t, err) - certBytes, err := ioutil.ReadFile(paths.Node.Cert) + certBytes, err := os.ReadFile(paths.Node.Cert) assert.NoError(t, err) assert.Len(t, checkLeafCert(t, certBytes, "rootCN1", "CN", "OU", "ORG"), 1) } @@ -1189,7 +1188,7 @@ func TestNewRootCAInvalidCertAndKeys(t *testing.T) { } func TestRootCAWithCrossSignedIntermediates(t *testing.T) { - tempdir, err := ioutil.TempDir("", "swarm-ca-test-") + tempdir, err := os.MkdirTemp("", "swarm-ca-test-") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -1485,7 +1484,7 @@ func TestRootCACrossSignCACertificate(t *testing.T) { }, } - tempdir, err := ioutil.TempDir("", "cross-sign-cert") + tempdir, err := os.MkdirTemp("", "cross-sign-cert") require.NoError(t, err) defer os.RemoveAll(tempdir) paths := ca.NewConfigPaths(tempdir) diff --git a/ca/config_test.go b/ca/config_test.go index 804b96dbb3..8b27ea3195 100644 --- a/ca/config_test.go +++ b/ca/config_test.go @@ -6,7 +6,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -234,7 +233,7 @@ func TestLoadSecurityConfigExpiredCert(t *testing.T) { // A cert that is not yet valid is not valid even if expiry is allowed invalidCert := cautils.ReDateCert(t, certBytes, tc.RootCA.Certs, s.Key, now.Add(time.Hour), now.Add(time.Hour*2)) - require.NoError(t, ioutil.WriteFile(tc.Paths.Node.Cert, invalidCert, 0700)) + require.NoError(t, os.WriteFile(tc.Paths.Node.Cert, invalidCert, 0o700)) _, _, err = ca.LoadSecurityConfig(tc.Context, tc.RootCA, krw, false) require.Error(t, err) @@ -246,7 +245,7 @@ func TestLoadSecurityConfigExpiredCert(t *testing.T) { // a cert that is expired is not valid if expiry is not allowed invalidCert = cautils.ReDateCert(t, certBytes, tc.RootCA.Certs, s.Key, now.Add(-2*time.Minute), now.Add(-1*time.Minute)) - require.NoError(t, ioutil.WriteFile(tc.Paths.Node.Cert, invalidCert, 0700)) + require.NoError(t, os.WriteFile(tc.Paths.Node.Cert, invalidCert, 0o700)) _, _, err = ca.LoadSecurityConfig(tc.Context, tc.RootCA, krw, false) require.Error(t, err) @@ -266,9 +265,9 @@ func TestLoadSecurityConfigInvalidCert(t *testing.T) { defer tc.Stop() // Write some garbage to the cert - ioutil.WriteFile(tc.Paths.Node.Cert, []byte(`-----BEGIN CERTIFICATE-----\n + os.WriteFile(tc.Paths.Node.Cert, []byte(`-----BEGIN CERTIFICATE-----\n some random garbage\n ------END CERTIFICATE-----`), 0644) +-----END CERTIFICATE-----`), 0o644) krw := ca.NewKeyReadWriter(tc.Paths.Node, nil, nil) @@ -284,9 +283,9 @@ func TestLoadSecurityConfigInvalidKey(t *testing.T) { defer tc.Stop() // Write some garbage to the Key - ioutil.WriteFile(tc.Paths.Node.Key, []byte(`-----BEGIN PRIVATE KEY-----\n + os.WriteFile(tc.Paths.Node.Key, []byte(`-----BEGIN PRIVATE KEY-----\n some random garbage\n ------END PRIVATE KEY-----`), 0644) +-----END PRIVATE KEY-----`), 0o644) krw := ca.NewKeyReadWriter(tc.Paths.Node, nil, nil) @@ -314,7 +313,7 @@ func TestLoadSecurityConfigIntermediates(t *testing.T) { if cautils.External { return // this doesn't require any servers at all } - tempdir, err := ioutil.TempDir("", "test-load-config-with-intermediates") + tempdir, err := os.MkdirTemp("", "test-load-config-with-intermediates") require.NoError(t, err) defer os.RemoveAll(tempdir) paths := ca.NewConfigPaths(tempdir) @@ -354,7 +353,7 @@ func TestLoadSecurityConfigKeyFormat(t *testing.T) { if cautils.External { return // this doesn't require any servers at all } - tempdir, err := ioutil.TempDir("", "test-load-config") + tempdir, err := os.MkdirTemp("", "test-load-config") require.NoError(t, err) defer os.RemoveAll(tempdir) paths := ca.NewConfigPaths(tempdir) @@ -440,7 +439,7 @@ func TestSecurityConfigUpdateRootCA(t *testing.T) { rootCA, err := ca.NewRootCA(cert, cert, key, ca.DefaultNodeCertExpiration, nil) require.NoError(t, err) - tempdir, err := ioutil.TempDir("", "test-security-config-update") + tempdir, err := os.MkdirTemp("", "test-security-config-update") require.NoError(t, err) defer os.RemoveAll(tempdir) configPaths := ca.NewConfigPaths(tempdir) @@ -535,7 +534,7 @@ func TestSecurityConfigUpdateRootCAUpdateConsistentWithTLSCertificates(t *testin if cautils.External { return // we don't care about external CAs at all } - tempdir, err := ioutil.TempDir("", "") + tempdir, err := os.MkdirTemp("", "") require.NoError(t, err) krw := ca.NewKeyReadWriter(ca.NewConfigPaths(tempdir).Node, nil, nil) @@ -628,7 +627,7 @@ func TestSecurityConfigWatch(t *testing.T) { // root certificate. If it validates against the current TLS credentials, it will be used to download // new ones, (only if the new certificate indicates that it's a worker, though). func TestRenewTLSConfigUpdatesRootOnUnknownAuthError(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-renew-tls-config-now-downloads-root") + tempdir, err := os.MkdirTemp("", "test-renew-tls-config-now-downloads-root") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -746,13 +745,13 @@ func TestRenewTLSConfigUpdatesRootOnUnknownAuthError(t *testing.T) { if testCase.expectedRoot != nil { // only rotate if we are a worker, and if the new cert validates against the old TLS creds require.NoError(t, err) - downloadedRoot, err := ioutil.ReadFile(paths.RootCA.Cert) + downloadedRoot, err := os.ReadFile(paths.RootCA.Cert) require.NoError(t, err) require.Equal(t, testCase.expectedRoot, downloadedRoot) } else { require.Error(t, err) require.IsType(t, x509.UnknownAuthorityError{}, err) - _, err = ioutil.ReadFile(paths.RootCA.Cert) // we didn't download a file + _, err = os.ReadFile(paths.RootCA.Cert) // we didn't download a file require.Error(t, err) } } @@ -761,7 +760,7 @@ func TestRenewTLSConfigUpdatesRootOnUnknownAuthError(t *testing.T) { // If we get a not unknown authority error when trying to renew the TLS certificate, just return the // error and do not attempt to download the root certificate. func TestRenewTLSConfigUpdatesRootNonUnknownAuthError(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-renew-tls-config-now-downloads-root") + tempdir, err := os.MkdirTemp("", "test-renew-tls-config-now-downloads-root") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -822,7 +821,7 @@ func TestRenewTLSConfigUpdateRootCARace(t *testing.T) { secConfig, err := tc.WriteNewNodeConfig(ca.ManagerRole) require.NoError(t, err) - leafCert, err := ioutil.ReadFile(paths.Node.Cert) + leafCert, err := os.ReadFile(paths.Node.Cert) require.NoError(t, err) for i := 0; i < 5; i++ { @@ -853,7 +852,7 @@ func TestRenewTLSConfigUpdateRootCARace(t *testing.T) { <-done1 <-done2 - newCert, err := ioutil.ReadFile(paths.Node.Cert) + newCert, err := os.ReadFile(paths.Node.Cert) require.NoError(t, err) require.NotEqual(t, newCert, leafCert) diff --git a/ca/external.go b/ca/external.go index 6b81204595..e455a6dbf7 100644 --- a/ca/external.go +++ b/ca/external.go @@ -10,7 +10,6 @@ import ( "encoding/json" "encoding/pem" "io" - "io/ioutil" "net/http" "sync" "time" @@ -193,7 +192,7 @@ func makeExternalSignRequest(ctx context.Context, client *http.Client, url strin defer resp.Body.Close() b := io.LimitReader(resp.Body, CertificateMaxSize) - body, err := ioutil.ReadAll(b) + body, err := io.ReadAll(b) if err != nil { return nil, recoverableErr{err: errors.Wrap(err, "unable to read CSR response body")} } diff --git a/ca/keyreadwriter.go b/ca/keyreadwriter.go index 0911440976..4e66d7e056 100644 --- a/ca/keyreadwriter.go +++ b/ca/keyreadwriter.go @@ -3,7 +3,6 @@ package ca import ( "crypto/x509" "encoding/pem" - "io/ioutil" "os" "path/filepath" "strconv" @@ -20,9 +19,9 @@ import ( const ( // keyPerms are the permissions used to write the TLS keys - keyPerms = 0600 + keyPerms = 0o600 // certPerms are the permissions used to write TLS certificates - certPerms = 0644 + certPerms = 0o644 // versionHeader is the TLS PEM key header that contains the KEK version versionHeader = "kek-version" ) @@ -157,14 +156,14 @@ func (k *KeyReadWriter) SetKeyFormatter(kf keyutils.Formatter) { // location than two possible key locations. func (k *KeyReadWriter) Migrate() error { tmpPaths := k.genTempPaths() - keyBytes, err := ioutil.ReadFile(tmpPaths.Key) + keyBytes, err := os.ReadFile(tmpPaths.Key) if err != nil { return nil // no key? no migration } // it does exist - no need to decrypt, because previous versions of swarmkit // which supported this temporary key did not support encrypting TLS keys - cert, err := ioutil.ReadFile(k.paths.Cert) + cert, err := os.ReadFile(k.paths.Cert) if err != nil { return os.RemoveAll(tmpPaths.Key) // no cert? no migration } @@ -202,7 +201,7 @@ func (k *KeyReadWriter) Read() ([]byte, []byte, error) { } keyBytes := pem.EncodeToMemory(keyBlock) - cert, err := ioutil.ReadFile(k.paths.Cert) + cert, err := os.ReadFile(k.paths.Cert) // The cert is written to a temporary file first, then the key, and then // the cert gets renamed - so, if interrupted, it's possible to end up with // a cert that only exists in the temporary location. @@ -219,7 +218,7 @@ func (k *KeyReadWriter) Read() ([]byte, []byte, error) { if err != nil { var tempErr error tmpPaths := k.genTempPaths() - cert, tempErr = ioutil.ReadFile(tmpPaths.Cert) + cert, tempErr = os.ReadFile(tmpPaths.Cert) if tempErr != nil { return nil, nil, err // return the original error } @@ -308,7 +307,7 @@ func (k *KeyReadWriter) Write(certBytes, plaintextKeyBytes []byte, kekData *KEKD defer k.mu.Unlock() // current assumption is that the cert and key will be in the same directory - if err := os.MkdirAll(filepath.Dir(k.paths.Key), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(k.paths.Key), 0o755); err != nil { return err } @@ -353,7 +352,7 @@ func (k *KeyReadWriter) Target() string { } func (k *KeyReadWriter) readKeyblock() (*pem.Block, error) { - key, err := ioutil.ReadFile(k.paths.Key) + key, err := os.ReadFile(k.paths.Key) if err != nil { return nil, err } diff --git a/ca/keyreadwriter_test.go b/ca/keyreadwriter_test.go index b28ee2c244..4eba19e1c8 100644 --- a/ca/keyreadwriter_test.go +++ b/ca/keyreadwriter_test.go @@ -3,7 +3,6 @@ package ca_test import ( "encoding/pem" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -23,7 +22,7 @@ func TestKeyReadWriter(t *testing.T) { expectedKey := key - tempdir, err := ioutil.TempDir("", "KeyReadWriter") + tempdir, err := os.MkdirTemp("", "KeyReadWriter") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -59,7 +58,7 @@ func TestKeyReadWriter(t *testing.T) { expectedKey = pem.EncodeToMemory(keyBlock) // write a version, but that's not what we'd expect back once we read keyBlock.Headers["kek-version"] = "8" - require.NoError(t, ioutil.WriteFile(path.Node.Key, pem.EncodeToMemory(keyBlock), 0600)) + require.NoError(t, os.WriteFile(path.Node.Key, pem.EncodeToMemory(keyBlock), 0o600)) // if a kek is provided, we can still read unencrypted keys, and read // the provided version @@ -131,7 +130,7 @@ func TestKeyReadWriterWithPemHeaderManager(t *testing.T) { keyBlock.Headers = map[string]string{"hello": "world"} key = pem.EncodeToMemory(keyBlock) - tempdir, err := ioutil.TempDir("", "KeyReadWriter") + tempdir, err := os.MkdirTemp("", "KeyReadWriter") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -207,7 +206,7 @@ func TestKeyReadWriterViewAndUpdateHeaders(t *testing.T) { cert, key, err := testutils.CreateRootCertAndKey("cn") require.NoError(t, err) - tempdir, err := ioutil.TempDir("", "KeyReadWriter") + tempdir, err := os.MkdirTemp("", "KeyReadWriter") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -218,8 +217,8 @@ func TestKeyReadWriterViewAndUpdateHeaders(t *testing.T) { require.NotNil(t, keyBlock) keyBlock.Headers = map[string]string{"hello": "world"} key = pem.EncodeToMemory(keyBlock) - require.NoError(t, ioutil.WriteFile(path.Node.Cert, cert, 0644)) - require.NoError(t, ioutil.WriteFile(path.Node.Key, key, 0600)) + require.NoError(t, os.WriteFile(path.Node.Cert, cert, 0o644)) + require.NoError(t, os.WriteFile(path.Node.Key, key, 0o600)) // if the update headers callback function fails, updating headers fails k := ca.NewKeyReadWriter(path.Node, nil, nil) @@ -273,7 +272,7 @@ func TestKeyReadWriterViewAndRotateKEK(t *testing.T) { cert, key, err := testutils.CreateRootCertAndKey("cn") require.NoError(t, err) - tempdir, err := ioutil.TempDir("", "KeyReadWriter") + tempdir, err := os.MkdirTemp("", "KeyReadWriter") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -332,7 +331,7 @@ func TestTwoPhaseReadWrite(t *testing.T) { cert2, key2, err := testutils.CreateRootCertAndKey("cn") require.NoError(t, err) - tempdir, err := ioutil.TempDir("", "KeyReadWriter") + tempdir, err := os.MkdirTemp("", "KeyReadWriter") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -341,12 +340,12 @@ func TestTwoPhaseReadWrite(t *testing.T) { // put a directory in the location where the cert goes, so we can't actually move // the cert from the temporary location to the final location. - require.NoError(t, os.Mkdir(filepath.Join(path.Node.Cert), 0755)) + require.NoError(t, os.Mkdir(filepath.Join(path.Node.Cert), 0o755)) require.Error(t, krw.Write(cert2, key2, nil)) // the temp cert file should exist tempCertPath := filepath.Join(filepath.Dir(path.Node.Cert), "."+filepath.Base(path.Node.Cert)) - readCert, err := ioutil.ReadFile(tempCertPath) + readCert, err := os.ReadFile(tempCertPath) require.NoError(t, err) require.Equal(t, cert2, readCert) @@ -361,8 +360,8 @@ func TestTwoPhaseReadWrite(t *testing.T) { require.True(t, os.IsNotExist(err)) // If the cert in the proper location doesn't match the key, the temp location is checked - require.NoError(t, ioutil.WriteFile(tempCertPath, cert2, 0644)) - require.NoError(t, ioutil.WriteFile(path.Node.Cert, cert1, 0644)) + require.NoError(t, os.WriteFile(tempCertPath, cert2, 0o644)) + require.NoError(t, os.WriteFile(path.Node.Cert, cert1, 0o644)) readCert, readKey, err = krw.Read() require.NoError(t, err) require.Equal(t, cert2, readCert) @@ -374,7 +373,7 @@ func TestTwoPhaseReadWrite(t *testing.T) { // If the cert in the temp location also doesn't match, the failure matching the // correctly-located cert is returned require.NoError(t, os.Remove(path.Node.Cert)) - require.NoError(t, ioutil.WriteFile(tempCertPath, cert1, 0644)) // mismatching cert + require.NoError(t, os.WriteFile(tempCertPath, cert1, 0o644)) // mismatching cert _, _, err = krw.Read() require.True(t, os.IsNotExist(err)) // the cert should have been removed @@ -386,7 +385,7 @@ func TestKeyReadWriterMigrate(t *testing.T) { cert, key, err := testutils.CreateRootCertAndKey("cn") require.NoError(t, err) - tempdir, err := ioutil.TempDir("", "KeyReadWriter") + tempdir, err := os.MkdirTemp("", "KeyReadWriter") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -394,8 +393,8 @@ func TestKeyReadWriterMigrate(t *testing.T) { // if the key exists in an old location, migrate it from there. tempKeyPath := filepath.Join(filepath.Dir(path.Node.Key), "."+filepath.Base(path.Node.Key)) - require.NoError(t, ioutil.WriteFile(path.Node.Cert, cert, 0644)) - require.NoError(t, ioutil.WriteFile(tempKeyPath, key, 0600)) + require.NoError(t, os.WriteFile(path.Node.Cert, cert, 0o644)) + require.NoError(t, os.WriteFile(tempKeyPath, key, 0o600)) krw := ca.NewKeyReadWriter(path.Node, nil, nil) require.NoError(t, krw.Migrate()) @@ -405,10 +404,10 @@ func TestKeyReadWriterMigrate(t *testing.T) { require.NoError(t, err) // migrate does not affect any existing files - dirList, err := ioutil.ReadDir(filepath.Dir(path.Node.Key)) + dirList, err := os.ReadDir(filepath.Dir(path.Node.Key)) require.NoError(t, err) require.NoError(t, krw.Migrate()) - dirList2, err := ioutil.ReadDir(filepath.Dir(path.Node.Key)) + dirList2, err := os.ReadDir(filepath.Dir(path.Node.Key)) require.NoError(t, err) require.Equal(t, dirList, dirList2) _, _, err = krw.Read() @@ -442,7 +441,7 @@ func testKeyReadWriterDowngradeKeyCase(t *testing.T, tc downgradeTestCase) error key = pem.EncodeToMemory(block) } - tempdir, err := ioutil.TempDir("", "KeyReadWriterDowngrade") + tempdir, err := os.MkdirTemp("", "KeyReadWriterDowngrade") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -455,8 +454,8 @@ func testKeyReadWriterDowngradeKeyCase(t *testing.T, tc downgradeTestCase) error block.Headers["kek-version"] = "5" key = pem.EncodeToMemory(block) - require.NoError(t, ioutil.WriteFile(path.Node.Cert, cert, 0644)) - require.NoError(t, ioutil.WriteFile(path.Node.Key, key, 0600)) + require.NoError(t, os.WriteFile(path.Node.Cert, cert, 0o644)) + require.NoError(t, os.WriteFile(path.Node.Key, key, 0o600)) // if the update headers callback function fails, updating headers fails k := ca.NewKeyReadWriter(path.Node, kek, nil) @@ -465,7 +464,7 @@ func testKeyReadWriterDowngradeKeyCase(t *testing.T, tc downgradeTestCase) error } // read the key directly from fs so we can check if key - key, err = ioutil.ReadFile(path.Node.Key) + key, err = os.ReadFile(path.Node.Key) require.NoError(t, err) keyBlock, _ := pem.Decode(key) @@ -528,7 +527,7 @@ func TestKeyReadWriterReadNonFIPS(t *testing.T) { key, err = pkcs8.ConvertToECPrivateKeyPEM(key) require.NoError(t, err) - tempdir, err := ioutil.TempDir("", "KeyReadWriter") + tempdir, err := os.MkdirTemp("", "KeyReadWriter") require.NoError(t, err) defer os.RemoveAll(tempdir) diff --git a/ca/server_test.go b/ca/server_test.go index 4b74d29a32..0d0d880bdb 100644 --- a/ca/server_test.go +++ b/ca/server_test.go @@ -6,7 +6,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -1171,7 +1170,7 @@ func TestRootRotationReconciliationRace(t *testing.T) { t: t, } - tempDir, err := ioutil.TempDir("", "competing-ca-server") + tempDir, err := os.MkdirTemp("", "competing-ca-server") require.NoError(t, err) defer os.RemoveAll(tempDir) diff --git a/ca/testutils/cautils.go b/ca/testutils/cautils.go index 2f0ceaefa9..9927b84c68 100644 --- a/ca/testutils/cautils.go +++ b/ca/testutils/cautils.go @@ -7,7 +7,6 @@ import ( "crypto/tls" "crypto/x509" "encoding/pem" - "io/ioutil" "net" "os" "strings" @@ -102,7 +101,7 @@ var External bool // NewTestCA is a helper method that creates a TestCA and a bunch of default // connections and security configs. func NewTestCA(t *testing.T, krwGenerators ...func(ca.CertPaths) *ca.KeyReadWriter) *TestCA { - tempdir, err := ioutil.TempDir("", "swarm-ca-test-") + tempdir, err := os.MkdirTemp("", "swarm-ca-test-") if t != nil { require.NoError(t, err) } @@ -122,7 +121,7 @@ func NewTestCA(t *testing.T, krwGenerators ...func(ca.CertPaths) *ca.KeyReadWrit // NewFIPSTestCA is a helper method that creates a mandatory fips TestCA and a bunch of default // connections and security configs. func NewFIPSTestCA(t *testing.T) *TestCA { - tempdir, err := ioutil.TempDir("", "swarm-ca-test-") + tempdir, err := os.MkdirTemp("", "swarm-ca-test-") if t != nil { require.NoError(t, err) } @@ -175,7 +174,7 @@ func newTestCA(t *testing.T, tempBaseDir string, apiRootCA api.RootCA, krwGenera } // Write the root certificate to disk, using decent permissions - err = ioutils.AtomicWriteFile(paths.RootCA.Cert, apiRootCA.CACert, 0644) + err = ioutils.AtomicWriteFile(paths.RootCA.Cert, apiRootCA.CACert, 0o644) if t != nil { require.NoError(t, err) } @@ -369,10 +368,10 @@ func genSecurityConfig(s *store.MemoryStore, rootCA ca.RootCA, krw *ca.KeyReadWr // If we were instructed to persist the files if tmpDir != "" { paths := ca.NewConfigPaths(tmpDir) - if err := ioutil.WriteFile(paths.Node.Cert, certChain, 0644); err != nil { + if err := os.WriteFile(paths.Node.Cert, certChain, 0o644); err != nil { return nil, nil, err } - if err := ioutil.WriteFile(paths.Node.Key, key, 0600); err != nil { + if err := os.WriteFile(paths.Node.Key, key, 0o600); err != nil { return nil, nil, err } } diff --git a/ca/transport_test.go b/ca/transport_test.go index f523fe81a0..24eb264282 100644 --- a/ca/transport_test.go +++ b/ca/transport_test.go @@ -2,7 +2,6 @@ package ca import ( "crypto/tls" - "io/ioutil" "os" "testing" @@ -11,7 +10,7 @@ import ( ) func TestNewMutableTLS(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-transport") + tempdir, err := os.MkdirTemp("", "test-transport") require.NoError(t, err) defer os.RemoveAll(tempdir) paths := NewConfigPaths(tempdir) @@ -32,7 +31,7 @@ func TestNewMutableTLS(t *testing.T) { } func TestGetAndValidateCertificateSubject(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-transport") + tempdir, err := os.MkdirTemp("", "test-transport") require.NoError(t, err) defer os.RemoveAll(tempdir) paths := NewConfigPaths(tempdir) @@ -52,7 +51,7 @@ func TestGetAndValidateCertificateSubject(t *testing.T) { } func TestLoadNewTLSConfig(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-transport") + tempdir, err := os.MkdirTemp("", "test-transport") require.NoError(t, err) defer os.RemoveAll(tempdir) paths := NewConfigPaths(tempdir) diff --git a/cmd/external-ca-example/main.go b/cmd/external-ca-example/main.go index f40c22707a..9753878cb9 100644 --- a/cmd/external-ca-example/main.go +++ b/cmd/external-ca-example/main.go @@ -1,7 +1,6 @@ package main import ( - "io/ioutil" "os" "os/signal" "path/filepath" @@ -42,7 +41,7 @@ func main() { // And copy the Root CA certificate into the node config path for its // CA. - ioutil.WriteFile(nodeConfigPaths.RootCA.Cert, rootCA.Certs, os.FileMode(0644)) + os.WriteFile(nodeConfigPaths.RootCA.Cert, rootCA.Certs, os.FileMode(0o644)) server, err := testutils.NewExternalSigningServer(rootCA, "ca") if err != nil { diff --git a/cmd/swarm-rafttool/common.go b/cmd/swarm-rafttool/common.go index dddb6e2428..aa921c92c1 100644 --- a/cmd/swarm-rafttool/common.go +++ b/cmd/swarm-rafttool/common.go @@ -3,7 +3,6 @@ package main import ( "context" "errors" - "io/ioutil" "os" "path/filepath" @@ -55,7 +54,7 @@ func getKRW(swarmdir, unlockKey string) (*ca.KeyReadWriter, error) { func moveDirAside(dirname string) error { if fileutil.Exist(dirname) { - tempdir, err := ioutil.TempDir(filepath.Dir(dirname), filepath.Base(dirname)) + tempdir, err := os.MkdirTemp(filepath.Dir(dirname), filepath.Base(dirname)) if err != nil { return err } diff --git a/cmd/swarm-rafttool/common_test.go b/cmd/swarm-rafttool/common_test.go index 606110ad20..bc2636aca6 100644 --- a/cmd/swarm-rafttool/common_test.go +++ b/cmd/swarm-rafttool/common_test.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -23,7 +22,7 @@ import ( func writeFakeRaftData(t *testing.T, stateDir string, snapshot *raftpb.Snapshot, wf storage.WALFactory, sf storage.SnapFactory) { snapDir := filepath.Join(stateDir, "raft", "snap-v3-encrypted") walDir := filepath.Join(stateDir, "raft", "wal-v3-encrypted") - require.NoError(t, os.MkdirAll(snapDir, 0755)) + require.NoError(t, os.MkdirAll(snapDir, 0o755)) wsn := walpb.Snapshot{} if snapshot != nil { @@ -50,7 +49,7 @@ func writeFakeRaftData(t *testing.T, stateDir string, snapshot *raftpb.Snapshot, } func TestDecrypt(t *testing.T) { - tempdir, err := ioutil.TempDir("", "rafttool") + tempdir, err := os.MkdirTemp("", "rafttool") require.NoError(t, err) defer os.RemoveAll(tempdir) diff --git a/cmd/swarmctl/config/create.go b/cmd/swarmctl/config/create.go index f7ea6c2b46..da862f5e18 100644 --- a/cmd/swarmctl/config/create.go +++ b/cmd/swarmctl/config/create.go @@ -3,7 +3,7 @@ package config import ( "errors" "fmt" - "io/ioutil" + "io" "os" "github.com/docker/swarmkit/api" @@ -31,12 +31,12 @@ var createCmd = &cobra.Command{ if err != nil { return err } - configData, err = ioutil.ReadFile(filename) + configData, err = os.ReadFile(filename) if err != nil { return fmt.Errorf("Error reading from file '%s': %s", filename, err.Error()) } } else { - configData, err = ioutil.ReadAll(os.Stdin) + configData, err = io.ReadAll(os.Stdin) if err != nil { return fmt.Errorf("Error reading content from STDIN: %s", err.Error()) } diff --git a/cmd/swarmctl/secret/create.go b/cmd/swarmctl/secret/create.go index ad799a48be..69ac1ced0a 100644 --- a/cmd/swarmctl/secret/create.go +++ b/cmd/swarmctl/secret/create.go @@ -3,7 +3,7 @@ package secret import ( "errors" "fmt" - "io/ioutil" + "io" "os" "github.com/docker/swarmkit/api" @@ -36,12 +36,12 @@ var createCmd = &cobra.Command{ if err != nil { return err } - secretData, err = ioutil.ReadFile(filename) + secretData, err = os.ReadFile(filename) if err != nil { return fmt.Errorf("Error reading from file '%s': %s", filename, err.Error()) } } else if driver == "" { - secretData, err = ioutil.ReadAll(os.Stdin) + secretData, err = io.ReadAll(os.Stdin) if err != nil { return fmt.Errorf("Error reading content from STDIN: %s", err.Error()) } diff --git a/cmd/swarmd/defaults/defaults_unix.go b/cmd/swarmd/defaults/defaults_unix.go index 7da63aa83e..270775a214 100644 --- a/cmd/swarmd/defaults/defaults_unix.go +++ b/cmd/swarmd/defaults/defaults_unix.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package defaults diff --git a/cmd/swarmd/defaults/defaults_windows.go b/cmd/swarmd/defaults/defaults_windows.go index 9a12725fe3..1921b15258 100644 --- a/cmd/swarmd/defaults/defaults_windows.go +++ b/cmd/swarmd/defaults/defaults_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package defaults diff --git a/cmd/swarmd/main.go b/cmd/swarmd/main.go index 6efa41c29d..89fcc573a2 100644 --- a/cmd/swarmd/main.go +++ b/cmd/swarmd/main.go @@ -167,7 +167,7 @@ var ( ctx, cancel := context.WithCancel(ctx) defer cancel() - if err := os.MkdirAll(stateDir, 0700); err != nil { + if err := os.MkdirAll(stateDir, 0o700); err != nil { return err } diff --git a/integration/integration_test.go b/integration/integration_test.go index 4c3011575c..30cb0e7d59 100644 --- a/integration/integration_test.go +++ b/integration/integration_test.go @@ -5,7 +5,6 @@ import ( "context" "flag" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -577,7 +576,7 @@ func TestForceNewCluster(t *testing.T) { // generate an expired certificate managerCertFile := filepath.Join(leader.stateDir, "certificates", "swarm-node.crt") - certBytes, err := ioutil.ReadFile(managerCertFile) + certBytes, err := os.ReadFile(managerCertFile) require.NoError(t, err) now := time.Now() // we don't want it too expired, because it can't have expired before the root CA cert is valid @@ -588,13 +587,13 @@ func TestForceNewCluster(t *testing.T) { // restart node with an expired certificate while forcing a new cluster - it should start without error and the certificate should be renewed nodeID := leader.node.NodeID() require.NoError(t, leader.Pause(true)) - require.NoError(t, ioutil.WriteFile(managerCertFile, expiredCertPEM, 0644)) + require.NoError(t, os.WriteFile(managerCertFile, expiredCertPEM, 0o644)) require.NoError(t, cl.StartNode(nodeID)) pollClusterReady(t, cl, numWorker, numManager) pollServiceReady(t, cl, sid, 2) err = testutils.PollFuncWithTimeout(nil, func() error { - certBytes, err := ioutil.ReadFile(managerCertFile) + certBytes, err := os.ReadFile(managerCertFile) if err != nil { return err } @@ -611,7 +610,7 @@ func TestForceNewCluster(t *testing.T) { // restart node with an expired certificate without forcing a new cluster - it should error on start require.NoError(t, leader.Pause(true)) - require.NoError(t, ioutil.WriteFile(managerCertFile, expiredCertPEM, 0644)) + require.NoError(t, os.WriteFile(managerCertFile, expiredCertPEM, 0o644)) require.Error(t, cl.StartNode(nodeID)) } diff --git a/integration/node.go b/integration/node.go index 263c3b7eec..3f3d703d11 100644 --- a/integration/node.go +++ b/integration/node.go @@ -3,7 +3,6 @@ package integration import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -33,15 +32,15 @@ func generateCerts(tmpDir string, rootCA *ca.RootCA, nodeID, role, org string, w return err } certDir := filepath.Join(tmpDir, "certificates") - if err := os.MkdirAll(certDir, 0700); err != nil { + if err := os.MkdirAll(certDir, 0o700); err != nil { return err } certPaths := ca.NewConfigPaths(certDir) - if err := ioutil.WriteFile(certPaths.RootCA.Cert, signer.Cert, 0644); err != nil { + if err := os.WriteFile(certPaths.RootCA.Cert, signer.Cert, 0o644); err != nil { return err } if writeKey { - if err := ioutil.WriteFile(certPaths.RootCA.Key, signer.Key, 0600); err != nil { + if err := os.WriteFile(certPaths.RootCA.Key, signer.Key, 0o600); err != nil { return err } } @@ -55,7 +54,7 @@ func generateCerts(tmpDir string, rootCA *ca.RootCA, nodeID, role, org string, w // It uses TestExecutor as executor. If lateBind is set, the remote API port is not // bound. If rootCA is set, this root is used to bootstrap the node's TLS certs. func newTestNode(joinAddr, joinToken string, lateBind bool, fips bool) (*testNode, error) { - tmpDir, err := ioutil.TempDir("", "swarmkit-integration-") + tmpDir, err := os.MkdirTemp("", "swarmkit-integration-") if err != nil { return nil, err } diff --git a/ioutils/ioutils.go b/ioutils/ioutils.go index 25e2a7803a..f9520e91d2 100644 --- a/ioutils/ioutils.go +++ b/ioutils/ioutils.go @@ -2,7 +2,6 @@ package ioutils import ( "io" - "io/ioutil" "os" "path/filepath" ) @@ -11,7 +10,7 @@ import ( // AtomicWriteFile atomically writes data to a file specified by filename. func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error { - f, err := ioutil.TempFile(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) + f, err := os.CreateTemp(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) if err != nil { return err } diff --git a/ioutils/ioutils_test.go b/ioutils/ioutils_test.go index 56a69c4ec6..21eee72b06 100644 --- a/ioutils/ioutils_test.go +++ b/ioutils/ioutils_test.go @@ -2,25 +2,24 @@ package ioutils import ( "bytes" - "io/ioutil" "os" "path/filepath" "testing" ) func TestAtomicWriteToFile(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "atomic-writers-test") + tmpDir, err := os.MkdirTemp("", "atomic-writers-test") if err != nil { t.Fatalf("Error when creating temporary directory: %s", err) } defer os.RemoveAll(tmpDir) expected := []byte("barbaz") - if err := AtomicWriteFile(filepath.Join(tmpDir, "foo"), expected, 0600); err != nil { + if err := AtomicWriteFile(filepath.Join(tmpDir, "foo"), expected, 0o600); err != nil { t.Fatalf("Error writing to file: %v", err) } - actual, err := ioutil.ReadFile(filepath.Join(tmpDir, "foo")) + actual, err := os.ReadFile(filepath.Join(tmpDir, "foo")) if err != nil { t.Fatalf("Error reading from file: %v", err) } diff --git a/manager/allocator/cnmallocator/drivers_unsupported.go b/manager/allocator/cnmallocator/drivers_unsupported.go index f9de277e38..120971be52 100644 --- a/manager/allocator/cnmallocator/drivers_unsupported.go +++ b/manager/allocator/cnmallocator/drivers_unsupported.go @@ -1,3 +1,4 @@ +//go:build !linux && !darwin && !windows // +build !linux,!darwin,!windows package cnmallocator diff --git a/manager/controlapi/ca_rotation_test.go b/manager/controlapi/ca_rotation_test.go index 638e7507ac..cd21c657d2 100644 --- a/manager/controlapi/ca_rotation_test.go +++ b/manager/controlapi/ca_rotation_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/x509" "encoding/pem" - "io/ioutil" "os" "testing" "time" @@ -57,7 +56,7 @@ func uglifyOnePEM(pemBytes []byte) []byte { } func getSecurityConfig(t *testing.T, localRootCA *ca.RootCA, cluster *api.Cluster) *ca.SecurityConfig { - tempdir, err := ioutil.TempDir("", "test-validate-CA") + tempdir, err := os.MkdirTemp("", "test-validate-CA") require.NoError(t, err) defer os.RemoveAll(tempdir) paths := ca.NewConfigPaths(tempdir) @@ -93,7 +92,7 @@ func TestValidateCAConfigInvalidValues(t *testing.T) { } // set up 2 external CAs that can be contacted for signing - tempdir, err := ioutil.TempDir("", "test-validate-CA") + tempdir, err := os.MkdirTemp("", "test-validate-CA") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -385,7 +384,7 @@ func TestValidateCAConfigValidValues(t *testing.T) { initialExternalRootCA.CAKey = nil // set up 2 external CAs that can be contacted for signing - tempdir, err := ioutil.TempDir("", "test-validate-CA") + tempdir, err := os.MkdirTemp("", "test-validate-CA") require.NoError(t, err) defer os.RemoveAll(tempdir) diff --git a/manager/controlapi/node_test.go b/manager/controlapi/node_test.go index 735dce3703..186750cf62 100644 --- a/manager/controlapi/node_test.go +++ b/manager/controlapi/node_test.go @@ -3,7 +3,7 @@ package controlapi import ( "context" "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/swarmkit/api" @@ -451,8 +451,8 @@ func TestRemoveNodes(t *testing.T) { } func init() { - grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard)) - logrus.SetOutput(ioutil.Discard) + grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard)) + logrus.SetOutput(io.Discard) } func getMap(t *testing.T, nodes []*api.Node) map[uint64]*api.ManagerStatus { diff --git a/manager/controlapi/server_test.go b/manager/controlapi/server_test.go index 3f4ea2547d..5a23a4d7d4 100644 --- a/manager/controlapi/server_test.go +++ b/manager/controlapi/server_test.go @@ -2,7 +2,6 @@ package controlapi import ( "context" - "io/ioutil" "net" "os" "testing" @@ -51,7 +50,7 @@ func newTestServer(t *testing.T) *testServer { ts.Server = NewServer(ts.Store, nil, securityConfig, nil, nil) assert.NotNil(t, ts.Server) - temp, err := ioutil.TempFile("", "test-socket") + temp, err := os.CreateTemp("", "test-socket") assert.NoError(t, err) assert.NoError(t, temp.Close()) assert.NoError(t, os.Remove(temp.Name())) diff --git a/manager/deks_test.go b/manager/deks_test.go index 63fdaf9141..6c790c6d37 100644 --- a/manager/deks_test.go +++ b/manager/deks_test.go @@ -4,7 +4,6 @@ import ( "encoding/base64" "encoding/pem" "fmt" - "io/ioutil" "os" "testing" @@ -136,7 +135,7 @@ func TestRaftDEKMarshalUnmarshal(t *testing.T) { // NewRaftDEKManager creates a key if one doesn't exist func TestNewRaftDEKManager(t *testing.T) { - tempDir, err := ioutil.TempDir("", "manager-new-dek-manager-") + tempDir, err := os.MkdirTemp("", "manager-new-dek-manager-") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -148,14 +147,14 @@ func TestNewRaftDEKManager(t *testing.T) { krw := ca.NewKeyReadWriter(paths.Node, nil, nil) require.NoError(t, krw.Write(cert, key, nil)) - keyBytes, err := ioutil.ReadFile(paths.Node.Key) + keyBytes, err := os.ReadFile(paths.Node.Key) require.NoError(t, err) require.NotContains(t, string(keyBytes), pemHeaderRaftDEK) // headers are not written dekManager, err := NewRaftDEKManager(krw, fips) // this should create a new DEK and write it to the file require.NoError(t, err) - keyBytes, err = ioutil.ReadFile(paths.Node.Key) + keyBytes, err = os.ReadFile(paths.Node.Key) require.NoError(t, err) require.Contains(t, string(keyBytes), pemHeaderRaftDEK) // header is written now @@ -174,7 +173,7 @@ func TestNewRaftDEKManager(t *testing.T) { dekManager, err = NewRaftDEKManager(krw, fips) // this should not have created a new dek require.NoError(t, err) - keyBytes2, err := ioutil.ReadFile(paths.Node.Key) + keyBytes2, err := os.ReadFile(paths.Node.Key) require.NoError(t, err) require.Equal(t, keyBytes, keyBytes2) @@ -189,7 +188,7 @@ func TestNewRaftDEKManager(t *testing.T) { // NeedsRotation flag are there, it does not remove the NeedsRotation flag, because that indicates // that we basically need to do 2 rotations. func TestRaftDEKManagerNeedsRotateGetKeys(t *testing.T) { - tempDir, err := ioutil.TempDir("", "manager-maybe-get-data-") + tempDir, err := os.MkdirTemp("", "manager-maybe-get-data-") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -271,7 +270,7 @@ func TestRaftDEKManagerNeedsRotateGetKeys(t *testing.T) { } { // clear the directory require.NoError(t, os.RemoveAll(tempDir)) - os.Mkdir(tempDir, 0777) + os.Mkdir(tempDir, 0o777) testcase.dekData.FIPS = fips krw := ca.NewKeyReadWriter(paths.Node, nil, testcase.dekData) if testcase.keyOnDisk { @@ -302,7 +301,7 @@ func TestRaftDEKManagerNeedsRotateGetKeys(t *testing.T) { } func TestRaftDEKManagerUpdateKeys(t *testing.T) { - tempDir, err := ioutil.TempDir("", "manager-update-keys-") + tempDir, err := os.MkdirTemp("", "manager-update-keys-") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -345,7 +344,7 @@ func TestRaftDEKManagerUpdateKeys(t *testing.T) { h, _ = krw.GetCurrentState() require.Nil(t, h) - keyBytes, err := ioutil.ReadFile(paths.Node.Key) + keyBytes, err := os.ReadFile(paths.Node.Key) require.NoError(t, err) keyBlock, _ := pem.Decode(keyBytes) require.NotNil(t, keyBlock) @@ -357,7 +356,7 @@ func TestRaftDEKManagerUpdateKeys(t *testing.T) { } func TestRaftDEKManagerMaybeUpdateKEK(t *testing.T) { - tempDir, err := ioutil.TempDir("", "manager-maybe-update-kek-") + tempDir, err := os.MkdirTemp("", "manager-maybe-update-kek-") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -377,14 +376,14 @@ func TestRaftDEKManagerMaybeUpdateKEK(t *testing.T) { dekManager, err := NewRaftDEKManager(krw, fips) require.NoError(t, err) - keyBytes, err := ioutil.ReadFile(paths.Node.Key) + keyBytes, err := os.ReadFile(paths.Node.Key) require.NoError(t, err) _, _, err = dekManager.MaybeUpdateKEK(ca.KEKData{KEK: []byte("locked now")}) require.Error(t, err) require.False(t, dekManager.NeedsRotation()) - keyBytes2, err := ioutil.ReadFile(paths.Node.Key) + keyBytes2, err := os.ReadFile(paths.Node.Key) require.NoError(t, err) require.Equal(t, keyBytes, keyBytes2) @@ -402,7 +401,7 @@ func TestRaftDEKManagerMaybeUpdateKEK(t *testing.T) { require.Equal(t, fips, dekData.FIPS) require.NotNil(t, <-dekManager.RotationNotify()) // we are notified of a new pending key - keyBytes2, err = ioutil.ReadFile(paths.Node.Key) + keyBytes2, err = os.ReadFile(paths.Node.Key) require.NoError(t, err) require.NotEqual(t, keyBytes, keyBytes2) keyBytes = keyBytes2 @@ -424,7 +423,7 @@ func TestRaftDEKManagerMaybeUpdateKEK(t *testing.T) { require.True(t, dekData.NeedsRotation) require.Equal(t, fips, dekData.FIPS) - keyBytes2, err = ioutil.ReadFile(paths.Node.Key) + keyBytes2, err = os.ReadFile(paths.Node.Key) require.NoError(t, err) require.Equal(t, keyBytes, keyBytes2, string(keyBytes), string(keyBytes2)) @@ -441,7 +440,7 @@ func TestRaftDEKManagerMaybeUpdateKEK(t *testing.T) { require.True(t, dekData.NeedsRotation) require.Equal(t, fips, dekData.FIPS) - keyBytes2, err = ioutil.ReadFile(paths.Node.Key) + keyBytes2, err = os.ReadFile(paths.Node.Key) require.NoError(t, err) require.Equal(t, keyBytes, keyBytes2) @@ -455,7 +454,7 @@ func TestRaftDEKManagerMaybeUpdateKEK(t *testing.T) { dekManager, err = NewRaftDEKManager(krw, fips) require.NoError(t, err) - keyBytes, err = ioutil.ReadFile(paths.Node.Key) + keyBytes, err = os.ReadFile(paths.Node.Key) require.NoError(t, err) updated, unlockedToLocked, err = dekManager.MaybeUpdateKEK(ca.KEKData{Version: 2}) @@ -465,7 +464,7 @@ func TestRaftDEKManagerMaybeUpdateKEK(t *testing.T) { require.Equal(t, keys, dekManager.GetKeys()) require.False(t, dekManager.NeedsRotation()) - keyBytes2, err = ioutil.ReadFile(paths.Node.Key) + keyBytes2, err = os.ReadFile(paths.Node.Key) require.NoError(t, err) require.NotEqual(t, keyBytes, keyBytes2) @@ -518,13 +517,13 @@ O0T3aXuZGYNyh//KqAoA3erCmh6HauMz84Y= realKEK, err := base64.RawStdEncoding.DecodeString("fDg9YejLnMjU+FpulWR62oJLzVpkD2j7VQuP5xiK9QA") require.NoError(t, err) - tempdir, err := ioutil.TempDir("", "KeyReadWriter-false-positive-decryption") + tempdir, err := os.MkdirTemp("", "KeyReadWriter-false-positive-decryption") require.NoError(t, err) defer os.RemoveAll(tempdir) path := ca.NewConfigPaths(tempdir) - require.NoError(t, ioutil.WriteFile(path.Node.Key, badKey, 0600)) - require.NoError(t, ioutil.WriteFile(path.Node.Cert, matchingCert, 0644)) + require.NoError(t, os.WriteFile(path.Node.Key, badKey, 0o600)) + require.NoError(t, os.WriteFile(path.Node.Cert, matchingCert, 0o644)) krw := ca.NewKeyReadWriter(path.Node, wrongKEK, RaftDEKData{}) _, _, err = krw.Read() @@ -542,7 +541,7 @@ O0T3aXuZGYNyh//KqAoA3erCmh6HauMz84Y= // If FIPS is enabled, the raft DEK will be encrypted using fernet, and not NACL secretbox. func TestRaftDEKsFIPSEnabledUsesFernet(t *testing.T) { - tempDir, err := ioutil.TempDir("", "manager-dek-fips") + tempDir, err := os.MkdirTemp("", "manager-dek-fips") require.NoError(t, err) defer os.RemoveAll(tempDir) diff --git a/manager/dirty_test.go b/manager/dirty_test.go index 3f6468f8b2..7b0ab129b4 100644 --- a/manager/dirty_test.go +++ b/manager/dirty_test.go @@ -2,7 +2,6 @@ package manager import ( "context" - "io/ioutil" "os" "testing" @@ -18,14 +17,14 @@ import ( func TestIsStateDirty(t *testing.T) { ctx := context.Background() - temp, err := ioutil.TempFile("", "test-socket") + temp, err := os.CreateTemp("", "test-socket") assert.NoError(t, err) assert.NoError(t, temp.Close()) assert.NoError(t, os.Remove(temp.Name())) defer os.RemoveAll(temp.Name()) - stateDir, err := ioutil.TempDir("", "test-raft") + stateDir, err := os.MkdirTemp("", "test-raft") assert.NoError(t, err) defer os.RemoveAll(stateDir) diff --git a/manager/dispatcher/dispatcher_test.go b/manager/dispatcher/dispatcher_test.go index 1cde296375..94ec446160 100644 --- a/manager/dispatcher/dispatcher_test.go +++ b/manager/dispatcher/dispatcher_test.go @@ -6,7 +6,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/http/httptest" @@ -426,7 +426,7 @@ func TestAssignmentsSecretDriver(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc(drivers.SecretsProviderAPI, func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) var request drivers.SecretsProviderRequest assert.NoError(t, err) assert.NoError(t, json.Unmarshal(body, &request)) diff --git a/manager/manager.go b/manager/manager.go index 8713f20c67..59895b1399 100644 --- a/manager/manager.go +++ b/manager/manager.go @@ -204,13 +204,13 @@ func (l *closeOnceListener) Close() error { // New creates a Manager which has not started to accept requests yet. func New(config *Config) (*Manager, error) { - err := os.MkdirAll(config.StateDir, 0700) + err := os.MkdirAll(config.StateDir, 0o700) if err != nil { return nil, errors.Wrap(err, "failed to create state directory") } raftStateDir := filepath.Join(config.StateDir, "raft") - err = os.MkdirAll(raftStateDir, 0700) + err = os.MkdirAll(raftStateDir, 0o700) if err != nil { return nil, errors.Wrap(err, "failed to create raft state directory") } @@ -332,7 +332,7 @@ func (m *Manager) BindControl(addr string) error { // don't create a socket directory if we're on windows. we used named pipe if runtime.GOOS != "windows" { - err := os.MkdirAll(filepath.Dir(addr), 0700) + err := os.MkdirAll(filepath.Dir(addr), 0o700) if err != nil { return errors.Wrap(err, "failed to create socket directory") } diff --git a/manager/manager_test.go b/manager/manager_test.go index dd921f4d7e..985407ad47 100644 --- a/manager/manager_test.go +++ b/manager/manager_test.go @@ -7,7 +7,6 @@ import ( "encoding/pem" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -29,14 +28,14 @@ import ( ) func TestManager(t *testing.T) { - temp, err := ioutil.TempFile("", "test-socket") + temp, err := os.CreateTemp("", "test-socket") require.NoError(t, err) require.NoError(t, temp.Close()) require.NoError(t, os.Remove(temp.Name())) defer os.RemoveAll(temp.Name()) - stateDir, err := ioutil.TempDir("", "test-raft") + stateDir, err := os.MkdirTemp("", "test-raft") require.NoError(t, err) defer os.RemoveAll(stateDir) @@ -221,14 +220,14 @@ func TestManager(t *testing.T) { // Tests locking and unlocking the manager and key rotations func TestManagerLockUnlock(t *testing.T) { - temp, err := ioutil.TempFile("", "test-manager-lock") + temp, err := os.CreateTemp("", "test-manager-lock") require.NoError(t, err) require.NoError(t, temp.Close()) require.NoError(t, os.Remove(temp.Name())) defer os.RemoveAll(temp.Name()) - stateDir, err := ioutil.TempDir("", "test-raft") + stateDir, err := os.MkdirTemp("", "test-raft") require.NoError(t, err) defer os.RemoveAll(stateDir) @@ -289,7 +288,7 @@ func TestManagerLockUnlock(t *testing.T) { require.Nil(t, cluster.UnlockKeys) // tls key is unencrypted, but there is a DEK - unencryptedKey, err := ioutil.ReadFile(tc.Paths.Node.Key) + unencryptedKey, err := os.ReadFile(tc.Paths.Node.Key) require.NoError(t, err) keyBlock, _ := pem.Decode(unencryptedKey) require.NotNil(t, keyBlock) @@ -330,7 +329,7 @@ func TestManagerLockUnlock(t *testing.T) { // this should update the TLS key, rotate the DEK, and finish snapshotting var encryptedKey []byte require.NoError(t, testutils.PollFuncWithTimeout(nil, func() error { - encryptedKey, err = ioutil.ReadFile(tc.Paths.Node.Key) + encryptedKey, err = os.ReadFile(tc.Paths.Node.Key) require.NoError(t, err) // this should never error due to atomic writes if bytes.Equal(unencryptedKey, encryptedKey) { @@ -394,7 +393,7 @@ func TestManagerLockUnlock(t *testing.T) { // this should update the TLS key var unlockedKey []byte require.NoError(t, testutils.PollFuncWithTimeout(nil, func() error { - unlockedKey, err = ioutil.ReadFile(tc.Paths.Node.Key) + unlockedKey, err = os.ReadFile(tc.Paths.Node.Key) if err != nil { return err } diff --git a/manager/orchestrator/jobs/orchestrator_controlapi_integration_test.go b/manager/orchestrator/jobs/orchestrator_controlapi_integration_test.go index 4815c9635a..48a92596f6 100644 --- a/manager/orchestrator/jobs/orchestrator_controlapi_integration_test.go +++ b/manager/orchestrator/jobs/orchestrator_controlapi_integration_test.go @@ -5,7 +5,6 @@ import ( . "github.com/onsi/gomega" "context" - "io/ioutil" "net" "os" "time" @@ -58,7 +57,7 @@ var _ = Describe("Integration between the controlapi and jobs orchestrator", fun server = controlapi.NewServer(s, nil, nil, nil, nil) // we need a temporary unix socket to server on - temp, err := ioutil.TempFile("", "test-socket") + temp, err := os.CreateTemp("", "test-socket") // this is probably to make sure that the socket can be created // successfully. Expect(err).ToNot(HaveOccurred()) diff --git a/manager/scheduler/topology_test.go b/manager/scheduler/topology_test.go index a9859321a3..6b31202273 100644 --- a/manager/scheduler/topology_test.go +++ b/manager/scheduler/topology_test.go @@ -1,8 +1,9 @@ package scheduler import ( - "github.com/docker/swarmkit/api" "testing" + + "github.com/docker/swarmkit/api" ) func TestIsInTopology(t *testing.T) { diff --git a/manager/state/raft/membership/cluster_test.go b/manager/state/raft/membership/cluster_test.go index 0781fc8677..6e5e503471 100644 --- a/manager/state/raft/membership/cluster_test.go +++ b/manager/state/raft/membership/cluster_test.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "os" "testing" "time" @@ -25,8 +25,8 @@ import ( var tc *cautils.TestCA func init() { - grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard)) - logrus.SetOutput(ioutil.Discard) + grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard)) + logrus.SetOutput(io.Discard) } func TestMain(m *testing.M) { diff --git a/manager/state/raft/raft_test.go b/manager/state/raft/raft_test.go index a7fbfb636a..c1b003b1e3 100644 --- a/manager/state/raft/raft_test.go +++ b/manager/state/raft/raft_test.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "math/rand" "net" "os" @@ -41,8 +41,8 @@ const ( func init() { store.WedgeTimeout = 3 * time.Second - grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard)) - logrus.SetOutput(ioutil.Discard) + grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard)) + logrus.SetOutput(io.Discard) } var tc *cautils.TestCA diff --git a/manager/state/raft/storage/snapwrap.go b/manager/state/raft/storage/snapwrap.go index 641f7e16b1..6152351a80 100644 --- a/manager/state/raft/storage/snapwrap.go +++ b/manager/state/raft/storage/snapwrap.go @@ -1,7 +1,6 @@ package storage import ( - "io/ioutil" "os" "path/filepath" "sort" @@ -140,7 +139,7 @@ func MigrateSnapshot(oldDir, newDir string, oldFactory, newFactory SnapFactory) // ListSnapshots lists all the snapshot files in a particular directory and returns // the snapshot files in reverse lexical order (newest first) func ListSnapshots(dirpath string) ([]string, error) { - dirents, err := ioutil.ReadDir(dirpath) + dirents, err := os.ReadDir(dirpath) if err != nil { return nil, err } diff --git a/manager/state/raft/storage/snapwrap_test.go b/manager/state/raft/storage/snapwrap_test.go index 01e10ed4d4..87988678dc 100644 --- a/manager/state/raft/storage/snapwrap_test.go +++ b/manager/state/raft/storage/snapwrap_test.go @@ -2,7 +2,6 @@ package storage import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -40,7 +39,7 @@ func getSnapshotFile(t *testing.T, tempdir string) string { // Snapshotter can read snapshots that are wrapped, but not encrypted func TestSnapshotterLoadNotEncryptedSnapshot(t *testing.T) { - tempdir, err := ioutil.TempDir("", "snapwrap") + tempdir, err := os.MkdirTemp("", "snapwrap") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -66,7 +65,7 @@ func TestSnapshotterLoadNotEncryptedSnapshot(t *testing.T) { // If there is no decrypter for a snapshot, decrypting fails func TestSnapshotterLoadNoDecrypter(t *testing.T) { - tempdir, err := ioutil.TempDir("", "snapwrap") + tempdir, err := os.MkdirTemp("", "snapwrap") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -92,7 +91,7 @@ func TestSnapshotterLoadNoDecrypter(t *testing.T) { // If decrypting a snapshot fails, the error is propagated func TestSnapshotterLoadDecryptingFail(t *testing.T) { - tempdir, err := ioutil.TempDir("", "snapwrap") + tempdir, err := os.MkdirTemp("", "snapwrap") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -122,7 +121,7 @@ func TestSnapshotterLoadDecryptingFail(t *testing.T) { // The snapshot data (but not metadata or anything else) is encryptd before being // passed to the wrapped Snapshotter. func TestSnapshotterSavesSnapshotWithEncryption(t *testing.T) { - tempdir, err := ioutil.TempDir("", "snapwrap") + tempdir, err := os.MkdirTemp("", "snapwrap") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -143,7 +142,7 @@ func TestSnapshotterSavesSnapshotWithEncryption(t *testing.T) { // If an encrypter is passed to Snapshotter, but encrypting the data fails, the // error is propagated up func TestSnapshotterSavesSnapshotEncryptionFails(t *testing.T) { - tempdir, err := ioutil.TempDir("", "snapwrap") + tempdir, err := os.MkdirTemp("", "snapwrap") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -164,7 +163,7 @@ func TestSnapshotterSavesSnapshotEncryptionFails(t *testing.T) { // Snapshotter can read what it wrote so long as it has the same decrypter func TestSaveAndLoad(t *testing.T) { crypter := &meowCrypter{} - tempdir, err := ioutil.TempDir("", "waltests") + tempdir, err := os.MkdirTemp("", "waltests") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -184,14 +183,14 @@ func TestMigrateSnapshot(t *testing.T) { dirs = make([]string, 3) ) - tempDir, err := ioutil.TempDir("", "test-migrate") + tempDir, err := os.MkdirTemp("", "test-migrate") require.NoError(t, err) defer os.RemoveAll(tempDir) for i := range dirs { dirs[i] = filepath.Join(tempDir, fmt.Sprintf("snapDir%d", i)) } - require.NoError(t, os.Mkdir(dirs[0], 0755)) + require.NoError(t, os.Mkdir(dirs[0], 0o755)) require.NoError(t, OriginalSnap.New(dirs[0]).SaveSnap(fakeSnapshotData)) // original to new @@ -220,14 +219,14 @@ func TestMigrateSnapshot(t *testing.T) { for _, dir := range dirs { require.NoError(t, os.RemoveAll(dir)) } - require.NoError(t, os.Mkdir(dirs[0], 0755)) + require.NoError(t, os.Mkdir(dirs[0], 0o755)) oldDir = dirs[0] newDir = dirs[1] err = MigrateSnapshot(oldDir, newDir, OriginalSnap, c) require.NoError(t, err) - subdirs, err := ioutil.ReadDir(tempDir) + subdirs, err := os.ReadDir(tempDir) require.NoError(t, err) require.Len(t, subdirs, 1) } diff --git a/manager/state/raft/storage/storage.go b/manager/state/raft/storage/storage.go index 64d821894e..49050b1823 100644 --- a/manager/state/raft/storage/storage.go +++ b/manager/state/raft/storage/storage.go @@ -83,7 +83,7 @@ func (e *EncryptedRaftLogger) BootstrapFromDisk(ctx context.Context, oldEncrypti } } // ensure the new directory exists - if err := os.MkdirAll(snapDir, 0700); err != nil { + if err := os.MkdirAll(snapDir, 0o700); err != nil { return nil, WALData{}, errors.Wrap(err, "failed to create snapshot directory") } @@ -147,7 +147,7 @@ func (e *EncryptedRaftLogger) BootstrapNew(metadata []byte) error { walFactory := NewWALFactory(encrypter, decrypter) for _, dirpath := range []string{filepath.Dir(e.walDir()), e.snapDir()} { - if err := os.MkdirAll(dirpath, 0700); err != nil { + if err := os.MkdirAll(dirpath, 0o700); err != nil { return errors.Wrapf(err, "failed to create %s", dirpath) } } diff --git a/manager/state/raft/storage/storage_test.go b/manager/state/raft/storage/storage_test.go index 2811f6e7d4..5b1e321ff3 100644 --- a/manager/state/raft/storage/storage_test.go +++ b/manager/state/raft/storage/storage_test.go @@ -2,7 +2,6 @@ package storage import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -15,7 +14,7 @@ import ( ) func TestBootstrapFromDisk(t *testing.T) { - tempdir, err := ioutil.TempDir("", "raft-storage") + tempdir, err := os.MkdirTemp("", "raft-storage") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -95,7 +94,7 @@ func TestBootstrapFromDisk(t *testing.T) { // Ensure that we can change encoding and not have a race condition func TestRaftLoggerRace(t *testing.T) { - tempdir, err := ioutil.TempDir("", "raft-storage") + tempdir, err := os.MkdirTemp("", "raft-storage") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -142,7 +141,7 @@ func TestRaftLoggerRace(t *testing.T) { func TestMigrateToV3EncryptedForm(t *testing.T) { t.Parallel() - tempdir, err := ioutil.TempDir("", "raft-storage") + tempdir, err := os.MkdirTemp("", "raft-storage") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -151,7 +150,7 @@ func TestMigrateToV3EncryptedForm(t *testing.T) { writeDataTo := func(suffix string, snapshot raftpb.Snapshot, walFactory WALFactory, snapFactory SnapFactory) []raftpb.Entry { snapDir := filepath.Join(tempdir, "snap"+suffix) walDir := filepath.Join(tempdir, "wal"+suffix) - require.NoError(t, os.MkdirAll(snapDir, 0755)) + require.NoError(t, os.MkdirAll(snapDir, 0o755)) require.NoError(t, snapFactory.New(snapDir).SaveSnap(snapshot)) _, entries, _ := makeWALData(snapshot.Metadata.Index, snapshot.Metadata.Term) diff --git a/manager/state/raft/storage/walwrap.go b/manager/state/raft/storage/walwrap.go index d1155975bf..42549a641f 100644 --- a/manager/state/raft/storage/walwrap.go +++ b/manager/state/raft/storage/walwrap.go @@ -3,7 +3,6 @@ package storage import ( "context" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -203,7 +202,7 @@ func MigrateWALs(ctx context.Context, oldDir, newDir string, oldFactory, newFact } oldReader.Close() - if err := os.MkdirAll(filepath.Dir(newDir), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(newDir), 0o700); err != nil { return errors.Wrap(err, "could not create parent directory") } @@ -237,7 +236,7 @@ func MigrateWALs(ctx context.Context, oldDir, newDir string, oldFactory, newFact // ListWALs lists all the wals in a directory and returns the list in lexical // order (oldest first) func ListWALs(dirpath string) ([]string, error) { - dirents, err := ioutil.ReadDir(dirpath) + dirents, err := os.ReadDir(dirpath) if err != nil { return nil, err } diff --git a/manager/state/raft/storage/walwrap_test.go b/manager/state/raft/storage/walwrap_test.go index ffe4d39107..23d69c7097 100644 --- a/manager/state/raft/storage/walwrap_test.go +++ b/manager/state/raft/storage/walwrap_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -38,7 +37,7 @@ func makeWALData(index uint64, term uint64) ([]byte, []raftpb.Entry, walpb.Snaps } func createWithWAL(t *testing.T, w WALFactory, metadata []byte, startSnap walpb.Snapshot, entries []raftpb.Entry) string { - walDir, err := ioutil.TempDir("", "waltests") + walDir, err := os.MkdirTemp("", "waltests") require.NoError(t, err) require.NoError(t, os.RemoveAll(walDir)) @@ -161,7 +160,7 @@ func TestSave(t *testing.T) { func TestSaveEncryptionFails(t *testing.T) { metadata, entries, snapshot := makeWALData(1, 1) - tempdir, err := ioutil.TempDir("", "waltests") + tempdir, err := os.MkdirTemp("", "waltests") require.NoError(t, err) os.RemoveAll(tempdir) defer os.RemoveAll(tempdir) @@ -197,7 +196,7 @@ func TestCreateOpenInvalidDirFails(t *testing.T) { _, err := c.Create("/not/existing/directory", []byte("metadata")) require.Error(t, err) - tempDir, err := ioutil.TempDir("", "test-migrate") + tempDir, err := os.MkdirTemp("", "test-migrate") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -230,14 +229,14 @@ func TestReadRepairWAL(t *testing.T) { defer os.RemoveAll(tempdir) // there should only be one WAL file in there - corrupt it - files, err := ioutil.ReadDir(tempdir) + files, err := os.ReadDir(tempdir) require.NoError(t, err) require.Len(t, files, 1) fName := filepath.Join(tempdir, files[0].Name()) - fileContents, err := ioutil.ReadFile(fName) + fileContents, err := os.ReadFile(fName) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(fName, fileContents[:200], files[0].Mode())) + require.NoError(t, os.WriteFile(fName, fileContents[:200], files[0].Mode())) ogWAL, err := OriginalWAL.Open(tempdir, snapshot) require.NoError(t, err) @@ -261,7 +260,7 @@ func TestMigrateWALs(t *testing.T) { dirs = make([]string, 2) ) - tempDir, err := ioutil.TempDir("", "test-migrate") + tempDir, err := os.MkdirTemp("", "test-migrate") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -313,7 +312,7 @@ func TestMigrateWALs(t *testing.T) { err = MigrateWALs(context.Background(), oldDir, newDir, OriginalWAL, c, walpb.Snapshot{}) require.Error(t, err) - subdirs, err := ioutil.ReadDir(tempDir) + subdirs, err := os.ReadDir(tempDir) require.NoError(t, err) require.Empty(t, subdirs) } diff --git a/manager/state/raft/storage_test.go b/manager/state/raft/storage_test.go index 516eab4498..664906324a 100644 --- a/manager/state/raft/storage_test.go +++ b/manager/state/raft/storage_test.go @@ -3,7 +3,6 @@ package raft_test import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -41,7 +40,7 @@ func TestRaftSnapshot(t *testing.T) { // None of the nodes should have snapshot files yet for _, node := range nodes { - dirents, err := ioutil.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) assert.NoError(t, err) assert.Len(t, dirents, 0) } @@ -60,7 +59,7 @@ func TestRaftSnapshot(t *testing.T) { // All nodes should now have a snapshot file for nodeID, node := range nodes { assert.NoError(t, testutils.PollFunc(clockSource, func() error { - dirents, err := ioutil.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) if err != nil { return err } @@ -77,7 +76,7 @@ func TestRaftSnapshot(t *testing.T) { // It should get a copy of the snapshot assert.NoError(t, testutils.PollFunc(clockSource, func() error { - dirents, err := ioutil.ReadDir(filepath.Join(nodes[4].StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(nodes[4].StateDir, "snap-v3-encrypted")) if err != nil { return err } @@ -113,7 +112,7 @@ func TestRaftSnapshot(t *testing.T) { // All nodes should have a snapshot under a *different* name for nodeID, node := range nodes { assert.NoError(t, testutils.PollFunc(clockSource, func() error { - dirents, err := ioutil.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) if err != nil { return err } @@ -158,7 +157,7 @@ func TestRaftSnapshotRestart(t *testing.T) { // Remaining nodes shouldn't have snapshot files yet for _, node := range []*raftutils.TestNode{nodes[1], nodes[2]} { - dirents, err := ioutil.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) assert.NoError(t, err) assert.Len(t, dirents, 0) } @@ -171,7 +170,7 @@ func TestRaftSnapshotRestart(t *testing.T) { // Remaining nodes should now have a snapshot file for nodeIdx, node := range []*raftutils.TestNode{nodes[1], nodes[2]} { assert.NoError(t, testutils.PollFunc(clockSource, func() error { - dirents, err := ioutil.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) if err != nil { return err } @@ -193,7 +192,7 @@ func TestRaftSnapshotRestart(t *testing.T) { // New node should get a copy of the snapshot assert.NoError(t, testutils.PollFunc(clockSource, func() error { - dirents, err := ioutil.ReadDir(filepath.Join(nodes[5].StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(nodes[5].StateDir, "snap-v3-encrypted")) if err != nil { return err } @@ -203,7 +202,7 @@ func TestRaftSnapshotRestart(t *testing.T) { return nil })) - dirents, err := ioutil.ReadDir(filepath.Join(nodes[5].StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(nodes[5].StateDir, "snap-v3-encrypted")) assert.NoError(t, err) assert.Len(t, dirents, 1) raftutils.CheckValuesOnNodes(t, clockSource, map[uint64]*raftutils.TestNode{1: nodes[1], 2: nodes[2]}, nodeIDs[:5], values[:5]) @@ -287,7 +286,7 @@ func TestRaftSnapshotForceNewCluster(t *testing.T) { // Nodes shouldn't have snapshot files yet for _, node := range nodes { - dirents, err := ioutil.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) assert.NoError(t, err) assert.Len(t, dirents, 0) } @@ -299,7 +298,7 @@ func TestRaftSnapshotForceNewCluster(t *testing.T) { // Nodes should now have a snapshot file for nodeIdx, node := range nodes { assert.NoError(t, testutils.PollFunc(clockSource, func() error { - dirents, err := ioutil.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) if err != nil { return err } @@ -350,7 +349,7 @@ func TestGCWAL(t *testing.T) { // Snapshot should have been triggered just as the WAL rotated, so // both WAL files should be preserved assert.NoError(t, testutils.PollFunc(clockSource, func() error { - dirents, err := ioutil.ReadDir(filepath.Join(nodes[1].StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(nodes[1].StateDir, "snap-v3-encrypted")) if err != nil { return err } @@ -358,7 +357,7 @@ func TestGCWAL(t *testing.T) { return fmt.Errorf("expected 1 snapshot, found %d", len(dirents)) } - dirents, err = ioutil.ReadDir(filepath.Join(nodes[1].StateDir, "wal-v3-encrypted")) + dirents, err = os.ReadDir(filepath.Join(nodes[1].StateDir, "wal-v3-encrypted")) if err != nil { return err } @@ -390,7 +389,7 @@ func TestGCWAL(t *testing.T) { // This time only one WAL file should be saved. assert.NoError(t, testutils.PollFunc(clockSource, func() error { - dirents, err := ioutil.ReadDir(filepath.Join(nodes[1].StateDir, "snap-v3-encrypted")) + dirents, err := os.ReadDir(filepath.Join(nodes[1].StateDir, "snap-v3-encrypted")) if err != nil { return err } @@ -399,7 +398,7 @@ func TestGCWAL(t *testing.T) { return fmt.Errorf("expected 1 snapshot, found %d", len(dirents)) } - dirents, err = ioutil.ReadDir(filepath.Join(nodes[1].StateDir, "wal-v3-encrypted")) + dirents, err = os.ReadDir(filepath.Join(nodes[1].StateDir, "wal-v3-encrypted")) if err != nil { return err } @@ -591,7 +590,7 @@ func TestRaftEncryptionKeyRotationWait(t *testing.T) { // break snapshotting, and ensure that key rotation never finishes tempSnapDir := filepath.Join(nodes[1].StateDir, "snap-backup") require.NoError(t, os.Rename(snapDir, tempSnapDir)) - require.NoError(t, ioutil.WriteFile(snapDir, []byte("this is no longer a directory"), 0644)) + require.NoError(t, os.WriteFile(snapDir, []byte("this is no longer a directory"), 0o644)) nodes[1].KeyRotator.QueuePendingKey([]byte("key3")) nodes[1].KeyRotator.RotationNotify() <- struct{}{} diff --git a/manager/state/raft/testutils/testutils.go b/manager/state/raft/testutils/testutils.go index c6169d90c9..1bd3fab9b4 100644 --- a/manager/state/raft/testutils/testutils.go +++ b/manager/state/raft/testutils/testutils.go @@ -2,7 +2,6 @@ package testutils import ( "context" - "io/ioutil" "net" "os" "reflect" @@ -271,7 +270,7 @@ func NewNode(t *testing.T, clockSource *fakeclock.FakeClock, tc *cautils.TestCA, cfg := raft.DefaultNodeConfig() - stateDir, err := ioutil.TempDir("", t.Name()) + stateDir, err := os.MkdirTemp("", t.Name()) require.NoError(t, err, "can't create temporary state directory") keyRotator := NewSimpleKeyRotator(raft.EncryptionKeys{CurrentDEK: []byte("current")}) diff --git a/manager/watchapi/server_test.go b/manager/watchapi/server_test.go index 753a0b3cfa..7f24643edc 100644 --- a/manager/watchapi/server_test.go +++ b/manager/watchapi/server_test.go @@ -2,7 +2,7 @@ package watchapi import ( "context" - "io/ioutil" + "io" "net" "os" "testing" @@ -52,7 +52,7 @@ func newTestServer(t *testing.T) *testServer { require.NoError(t, ts.Server.Start(context.Background())) - temp, err := ioutil.TempFile("", "test-socket") + temp, err := os.CreateTemp("", "test-socket") assert.NoError(t, err) assert.NoError(t, temp.Close()) assert.NoError(t, os.Remove(temp.Name())) @@ -101,6 +101,6 @@ func createNode(t *testing.T, ts *testServer, id string, role api.NodeRole, memb } func init() { - grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard)) - logrus.SetOutput(ioutil.Discard) + grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard)) + logrus.SetOutput(io.Discard) } diff --git a/node/node.go b/node/node.go index c4ce906e34..c467a6c8d6 100644 --- a/node/node.go +++ b/node/node.go @@ -5,7 +5,6 @@ import ( "context" "crypto/tls" "encoding/json" - "io/ioutil" "math" "net" "os" @@ -195,11 +194,11 @@ func (n *Node) RemoteAPIAddr() (string, error) { // New returns new Node instance. func New(c *Config) (*Node, error) { - if err := os.MkdirAll(c.StateDir, 0700); err != nil { + if err := os.MkdirAll(c.StateDir, 0o700); err != nil { return nil, err } stateFile := filepath.Join(c.StateDir, stateFilename) - dt, err := ioutil.ReadFile(stateFile) + dt, err := os.ReadFile(stateFile) var p []api.Peer if err != nil && !os.IsNotExist(err) { return nil, err @@ -337,7 +336,7 @@ func (n *Node) run(ctx context.Context) (err error) { // database if it doesn't already exist, and if it does already exist, no // error will be returned, so we use this regardless of whether this node // is new or not. - if err := os.MkdirAll(filepath.Dir(taskDBPath), 0777); err != nil { + if err := os.MkdirAll(filepath.Dir(taskDBPath), 0o777); err != nil { return err } @@ -1248,7 +1247,7 @@ func (s *persistentRemotes) save() error { return err } s.lastSavedState = remotes - return ioutils.AtomicWriteFile(s.storePath, dt, 0600) + return ioutils.AtomicWriteFile(s.storePath, dt, 0o600) } // WaitSelect waits until at least one remote becomes available and then selects one. diff --git a/node/node_test.go b/node/node_test.go index 6f6bd25c67..73eacc4d57 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -6,7 +6,6 @@ import ( "crypto/x509" "encoding/pem" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -36,7 +35,7 @@ func getLoggingContext(t *testing.T) context.Context { // If AutoLockManagers is enabled, the TLS key is encrypted with a randomly generated lock key. func TestLoadSecurityConfigNewNode(t *testing.T) { for _, autoLockManagers := range []bool{true, false} { - tempdir, err := ioutil.TempDir("", "test-new-node") + tempdir, err := os.MkdirTemp("", "test-new-node") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -65,7 +64,7 @@ func TestLoadSecurityConfigNewNode(t *testing.T) { // If there's only a root CA on disk (no TLS certs), and no join addr, we create a new CA // and a new set of TLS certs. Similarly if there's only a TLS cert and key, and no CA. func TestLoadSecurityConfigPartialCertsOnDisk(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-new-node") + tempdir, err := os.MkdirTemp("", "test-new-node") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -111,7 +110,7 @@ func TestLoadSecurityConfigPartialCertsOnDisk(t *testing.T) { // If there are CAs and TLS certs on disk, it tries to load and fails if there // are any errors, even if a join token is provided. func TestLoadSecurityConfigLoadFromDisk(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-load-node-tls") + tempdir, err := os.MkdirTemp("", "test-load-node-tls") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -188,7 +187,7 @@ func TestLoadSecurityConfigLoadFromDisk(t *testing.T) { // join server. If there is a CA, it is just loaded from disk. The TLS key and // cert are also downloaded. func TestLoadSecurityConfigDownloadAllCerts(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-join-node") + tempdir, err := os.MkdirTemp("", "test-join-node") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -227,13 +226,13 @@ func TestLoadSecurityConfigDownloadAllCerts(t *testing.T) { // know if it gets replaced require.NoError(t, os.Remove(paths.Node.Cert)) require.NoError(t, os.Remove(paths.Node.Key)) - certBytes, err := ioutil.ReadFile(paths.RootCA.Cert) + certBytes, err := os.ReadFile(paths.RootCA.Cert) require.NoError(t, err) pemBlock, _ := pem.Decode(certBytes) require.NotNil(t, pemBlock) pemBlock.Headers["marked"] = "true" certBytes = pem.EncodeToMemory(pemBlock) - require.NoError(t, ioutil.WriteFile(paths.RootCA.Cert, certBytes, 0644)) + require.NoError(t, os.WriteFile(paths.RootCA.Cert, certBytes, 0o644)) // also make sure the new set gets downloaded and written to disk with a passphrase // by updating the memory store with manager autolock on and an unlock key @@ -265,7 +264,7 @@ func TestLoadSecurityConfigDownloadAllCerts(t *testing.T) { cancel() // make sure the CA cert has not been replaced - readCertBytes, err := ioutil.ReadFile(paths.RootCA.Cert) + readCertBytes, err := os.ReadFile(paths.RootCA.Cert) require.NoError(t, err) require.Equal(t, certBytes, readCertBytes) @@ -279,7 +278,7 @@ func TestLoadSecurityConfigDownloadAllCerts(t *testing.T) { // If there is nothing on disk and no join addr, and FIPS is enabled, we create a cluster whose // ID starts with 'FIPS.' func TestLoadSecurityConfigNodeFIPSCreateCluster(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-security-config-fips-new-cluster") + tempdir, err := os.MkdirTemp("", "test-security-config-fips-new-cluster") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -305,7 +304,7 @@ func TestLoadSecurityConfigNodeFIPSCreateCluster(t *testing.T) { // If FIPS is enabled and there is a join address, the cluster ID is whatever the CA set // the cluster ID to. func TestLoadSecurityConfigNodeFIPSJoinCluster(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-security-config-fips-join-cluster") + tempdir, err := os.MkdirTemp("", "test-security-config-fips-join-cluster") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -344,7 +343,7 @@ func TestLoadSecurityConfigNodeFIPSJoinCluster(t *testing.T) { // If the certificate specifies that the cluster requires FIPS mode, loading the security // config will fail if the node is not FIPS enabled. func TestLoadSecurityConfigRespectsFIPSCert(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-security-config-fips-cert-on-disk") + tempdir, err := os.MkdirTemp("", "test-security-config-fips-cert-on-disk") require.NoError(t, err) defer os.RemoveAll(tempdir) @@ -352,7 +351,7 @@ func TestLoadSecurityConfigRespectsFIPSCert(t *testing.T) { defer tc.Stop() certDir := filepath.Join(tempdir, "certificates") - require.NoError(t, os.Mkdir(certDir, 0700)) + require.NoError(t, os.Mkdir(certDir, 0o700)) paths := ca.NewConfigPaths(certDir) // copy certs and keys from the test CA using a hard link @@ -383,12 +382,12 @@ func TestLoadSecurityConfigRespectsFIPSCert(t *testing.T) { // the cluster requires fips, then loading the security config will fail. However, if // there are already certs on disk, it will load them and ignore the join token. func TestLoadSecurityConfigNonFIPSNodeJoinCluster(t *testing.T) { - tempdir, err := ioutil.TempDir("", "test-security-config-nonfips-join-cluster") + tempdir, err := os.MkdirTemp("", "test-security-config-nonfips-join-cluster") require.NoError(t, err) defer os.RemoveAll(tempdir) certDir := filepath.Join(tempdir, "certificates") - require.NoError(t, os.Mkdir(certDir, 0700)) + require.NoError(t, os.Mkdir(certDir, 0o700)) paths := ca.NewConfigPaths(certDir) tc := cautils.NewTestCA(t) @@ -433,7 +432,7 @@ func TestLoadSecurityConfigNonFIPSNodeJoinCluster(t *testing.T) { } func TestManagerRespectsDispatcherRootCAUpdate(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "manager-root-ca-update") + tmpDir, err := os.MkdirTemp("", "manager-root-ca-update") require.NoError(t, err) defer os.RemoveAll(tmpDir) @@ -481,7 +480,7 @@ func TestManagerRespectsDispatcherRootCAUpdate(t *testing.T) { // the node root CA certificates have changed now time.Sleep(250 * time.Millisecond) certPath := filepath.Join(tmpDir, certDirectory, "swarm-root-ca.crt") - caCerts, err := ioutil.ReadFile(certPath) + caCerts, err := os.ReadFile(certPath) require.NoError(t, err) require.NotEqual(t, currentCACerts, caCerts) @@ -489,7 +488,7 @@ func TestManagerRespectsDispatcherRootCAUpdate(t *testing.T) { } func TestAgentRespectsDispatcherRootCAUpdate(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "manager-root-ca-update") + tmpDir, err := os.MkdirTemp("", "manager-root-ca-update") require.NoError(t, err) defer os.RemoveAll(tmpDir) @@ -526,7 +525,7 @@ func TestAgentRespectsDispatcherRootCAUpdate(t *testing.T) { require.FailNow(t, "node did not ready in time") } - currentCACerts, err := ioutil.ReadFile(paths.RootCA.Cert) + currentCACerts, err := os.ReadFile(paths.RootCA.Cert) require.NoError(t, err) parsedCerts, err := helpers.ParseCertificatesPEM(currentCACerts) require.NoError(t, err) @@ -538,7 +537,7 @@ func TestAgentRespectsDispatcherRootCAUpdate(t *testing.T) { } require.NoError(t, testutils.PollFuncWithTimeout(nil, func() error { - caCerts, err := ioutil.ReadFile(paths.RootCA.Cert) + caCerts, err := os.ReadFile(paths.RootCA.Cert) require.NoError(t, err) if bytes.Equal(currentCACerts, caCerts) { return errors.New("new certificates have not been replaced yet") @@ -557,7 +556,7 @@ func TestAgentRespectsDispatcherRootCAUpdate(t *testing.T) { } func TestCertRenewals(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "no-top-level-role") + tmpDir, err := os.MkdirTemp("", "no-top-level-role") require.NoError(t, err) defer os.RemoveAll(tmpDir) @@ -581,7 +580,7 @@ func TestCertRenewals(t *testing.T) { require.FailNow(t, "node did not ready in time") } - currentNodeCert, err := ioutil.ReadFile(paths.Node.Cert) + currentNodeCert, err := os.ReadFile(paths.Node.Cert) require.NoError(t, err) // Fake an update from the dispatcher. Make sure the Role field is @@ -597,7 +596,7 @@ func TestCertRenewals(t *testing.T) { time.Sleep(500 * time.Millisecond) - nodeCert, err := ioutil.ReadFile(paths.Node.Cert) + nodeCert, err := os.ReadFile(paths.Node.Cert) require.NoError(t, err) if !bytes.Equal(currentNodeCert, nodeCert) { t.Fatal("Certificate should not have been renewed") @@ -615,7 +614,7 @@ func TestCertRenewals(t *testing.T) { } require.NoError(t, testutils.PollFuncWithTimeout(nil, func() error { - nodeCert, err := ioutil.ReadFile(paths.Node.Cert) + nodeCert, err := os.ReadFile(paths.Node.Cert) require.NoError(t, err) if bytes.Equal(currentNodeCert, nodeCert) { return errors.New("certificate has not been replaced yet") @@ -628,7 +627,7 @@ func TestCertRenewals(t *testing.T) { } func TestManagerFailedStartup(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "manager-root-ca-update") + tmpDir, err := os.MkdirTemp("", "manager-root-ca-update") require.NoError(t, err) defer os.RemoveAll(tmpDir) @@ -670,7 +669,7 @@ func TestManagerFailedStartup(t *testing.T) { // TestFIPSConfiguration ensures that new keys will be stored in PKCS8 format. func TestFIPSConfiguration(t *testing.T) { ctx := getLoggingContext(t) - tmpDir, err := ioutil.TempDir("", "fips") + tmpDir, err := os.MkdirTemp("", "fips") require.NoError(t, err) defer os.RemoveAll(tmpDir) @@ -697,7 +696,7 @@ func TestFIPSConfiguration(t *testing.T) { require.FailNow(t, "node did not ready in time") } - nodeKey, err := ioutil.ReadFile(paths.Node.Key) + nodeKey, err := os.ReadFile(paths.Node.Key) require.NoError(t, err) pemBlock, _ := pem.Decode(nodeKey) require.NotNil(t, pemBlock) diff --git a/xnet/xnet_unix.go b/xnet/xnet_unix.go index 7dc7732345..4086ed5021 100644 --- a/xnet/xnet_unix.go +++ b/xnet/xnet_unix.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package xnet diff --git a/xnet/xnet_windows.go b/xnet/xnet_windows.go index 38385a7e3a..3f5e4d04d7 100644 --- a/xnet/xnet_windows.go +++ b/xnet/xnet_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package xnet