diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index d19efbbe..631255aa 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -23,7 +23,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.18 + go-version: 1.19 - name: goreleaser uses: goreleaser/goreleaser-action@v2 diff --git a/.travis.yml b/.travis.yml index 26d8c508..683221fb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,7 @@ vm: language: go go: -- 1.18.x +- 1.19.x addons: apt: @@ -32,7 +32,7 @@ jobs: - name: "Run all tests from all other packages" env: TEST_SUITE=non_srv_pkg_tests - name: "Compile with older Go release" - go: 1.17.x + go: 1.18.x env: TEST_SUITE=build_only script: ./scripts/runTestsOnTravis.sh $TEST_SUITE @@ -43,4 +43,4 @@ deploy: script: curl -sL http://git.io/goreleaser | bash on: tags: true - condition: ($TRAVIS_GO_VERSION =~ 1.18) && ($TEST_SUITE = "compile") + condition: ($TRAVIS_GO_VERSION =~ 1.19) && ($TEST_SUITE = "compile") diff --git a/conf/parse.go b/conf/parse.go index afb6f6e8..d1e29819 100644 --- a/conf/parse.go +++ b/conf/parse.go @@ -27,7 +27,6 @@ package conf import ( "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -72,7 +71,7 @@ func Parse(data string) (map[string]interface{}, error) { // ParseFile is a helper to open file, etc. and parse the contents. func ParseFile(fp string) (map[string]interface{}, error) { - data, err := ioutil.ReadFile(fp) + data, err := os.ReadFile(fp) if err != nil { return nil, fmt.Errorf("error opening config file: %v", err) } @@ -86,7 +85,7 @@ func ParseFile(fp string) (map[string]interface{}, error) { // ParseFileWithChecks is equivalent to ParseFile but runs in pedantic mode. func ParseFileWithChecks(fp string) (map[string]interface{}, error) { - data, err := ioutil.ReadFile(fp) + data, err := os.ReadFile(fp) if err != nil { return nil, err } diff --git a/docker/Dockerfile.nightly b/docker/Dockerfile.nightly index ba08ba8f..13fa7d54 100644 --- a/docker/Dockerfile.nightly +++ b/docker/Dockerfile.nightly @@ -1,4 +1,4 @@ -FROM golang:1.18-alpine AS builder +FROM golang:1.19-alpine AS builder ARG VERSION="nightly" diff --git a/logger/log_test.go b/logger/log_test.go index f9638892..e289e19a 100644 --- a/logger/log_test.go +++ b/logger/log_test.go @@ -17,7 +17,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -115,7 +114,7 @@ func TestFileLogger(t *testing.T) { defer logger.Close() logger.Noticef("foo") - buf, err := ioutil.ReadFile(file.Name()) + buf, err := os.ReadFile(file.Name()) if err != nil { t.Fatalf("Could not read logfile: %v", err) } @@ -134,7 +133,7 @@ func TestFileLogger(t *testing.T) { defer logger.Close() logger.Errorf("foo") - buf, err = ioutil.ReadFile(file.Name()) + buf, err = os.ReadFile(file.Name()) if err != nil { t.Fatalf("Could not read logfile: %v", err) } @@ -191,7 +190,7 @@ func TestFileLoggerSizeLimit(t *testing.T) { logger.Noticef("This is a line in the log file") } - files, err := ioutil.ReadDir(tmpDir) + files, err := os.ReadDir(tmpDir) if err != nil { t.Fatalf("Error reading logs dir: %v", err) } @@ -202,7 +201,7 @@ func TestFileLoggerSizeLimit(t *testing.T) { if err := logger.Close(); err != nil { t.Fatalf("Error closing log: %v", err) } - content, err := ioutil.ReadFile(file.Name()) + content, err := os.ReadFile(file.Name()) if err != nil { t.Fatalf("Error loading latest log: %v", err) } @@ -224,7 +223,7 @@ func TestFileLoggerSizeLimit(t *testing.T) { for i := 0; i < 50; i++ { logger.Noticef("This is line %d in the log file", i+1) } - files, err = ioutil.ReadDir(tmpDir) + files, err = os.ReadDir(tmpDir) if err != nil { t.Fatalf("Error reading logs dir: %v", err) } @@ -235,7 +234,7 @@ func TestFileLoggerSizeLimit(t *testing.T) { // Now set a limit that is below current size logger.SetSizeLimit(1000) // Should have triggered rotation - files, err = ioutil.ReadDir(tmpDir) + files, err = os.ReadDir(tmpDir) if err != nil { t.Fatalf("Error reading logs dir: %v", err) } @@ -246,7 +245,7 @@ func TestFileLoggerSizeLimit(t *testing.T) { t.Fatalf("Error closing log: %v", err) } lastBackup = files[len(files)-1] - content, err = ioutil.ReadFile(file.Name()) + content, err = os.ReadFile(file.Name()) if err != nil { t.Fatalf("Error loading latest log: %v", err) } @@ -277,12 +276,12 @@ func TestFileLoggerSizeLimit(t *testing.T) { // Close logger.Close() - files, err = ioutil.ReadDir(tmpDir) + files, err = os.ReadDir(tmpDir) if err != nil { t.Fatalf("Error reading logs dir: %v", err) } lastBackup = files[len(files)-1] - content, err = ioutil.ReadFile(filepath.Join(tmpDir, lastBackup.Name())) + content, err = os.ReadFile(filepath.Join(tmpDir, lastBackup.Name())) if err != nil { t.Fatalf("Error reading backup file: %v", err) } @@ -331,7 +330,7 @@ func createDir(t *testing.T, prefix string) string { if err := os.MkdirAll(tempRoot, 0700); err != nil { t.Fatal(err) } - dir, err := ioutil.TempDir(tempRoot, prefix) + dir, err := os.MkdirTemp(tempRoot, prefix) if err != nil { t.Fatal(err) } @@ -340,7 +339,7 @@ func createDir(t *testing.T, prefix string) string { func createFileAtDir(t *testing.T, dir, prefix string) *os.File { t.Helper() - f, err := ioutil.TempFile(dir, prefix) + f, err := os.CreateTemp(dir, prefix) if err != nil { t.Fatal(err) } diff --git a/server/accounts.go b/server/accounts.go index e9a814f8..a7081f25 100644 --- a/server/accounts.go +++ b/server/accounts.go @@ -20,7 +20,7 @@ import ( "fmt" "hash/fnv" "hash/maphash" - "io/ioutil" + "io" "math" "math/rand" "net/http" @@ -1326,7 +1326,10 @@ func (a *Account) sendBackendErrorTrackingLatency(si *serviceImport, reason rsiR // received the response. // TODO(dlc) - holding locks for RTTs may be too much long term. Should revisit. func (a *Account) sendTrackingLatency(si *serviceImport, responder *client) bool { - if si.rc == nil { + a.mu.RLock() + rc := si.rc + a.mu.RUnlock() + if rc == nil { return true } @@ -3598,7 +3601,7 @@ func (ur *URLAccResolver) Fetch(name string) (string, error) { return _EMPTY_, fmt.Errorf("could not fetch <%q>: %v", redactURLString(url), resp.Status) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return _EMPTY_, err } diff --git a/server/dirstore.go b/server/dirstore.go index 9bb499fd..cabd4a19 100644 --- a/server/dirstore.go +++ b/server/dirstore.go @@ -20,7 +20,6 @@ import ( "crypto/sha256" "errors" "fmt" - "io/ioutil" "math" "os" "path/filepath" @@ -146,8 +145,8 @@ const ( // // limit defines how many files are allowed at any given time. Set to math.MaxInt64 to disable. // evictOnLimit determines the behavior once limit is reached. -// true - Evict based on lru strategy -// false - return an error +// * true - Evict based on lru strategy +// * false - return an error func NewExpiringDirJWTStore(dirPath string, shard bool, create bool, delete deleteType, expireCheck time.Duration, limit int64, evictOnLimit bool, ttl time.Duration, changeNotification JWTChanged, _ ...dirJWTStoreOption) (*DirJWTStore, error) { fullPath, err := newDir(dirPath, create) @@ -175,7 +174,7 @@ func NewExpiringDirJWTStore(dirPath string, shard bool, create bool, delete dele theStore.Lock() err = filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error { if strings.HasSuffix(path, fileExtension) { - if theJwt, err := ioutil.ReadFile(path); err == nil { + if theJwt, err := os.ReadFile(path); err == nil { hash := sha256.Sum256(theJwt) _, file := filepath.Split(path) theStore.expiration.track(strings.TrimSuffix(file, fileExtension), &hash, string(theJwt)) @@ -241,7 +240,7 @@ func (store *DirJWTStore) Pack(maxJWTs int) (string, error) { return nil // only include indexed files } } - jwtBytes, err := ioutil.ReadFile(path) + jwtBytes, err := os.ReadFile(path) if err != nil { return err } @@ -285,7 +284,7 @@ func (store *DirJWTStore) PackWalk(maxJWTs int, cb func(partialPackMsg string)) } } store.Unlock() - jwtBytes, err := ioutil.ReadFile(path) + jwtBytes, err := os.ReadFile(path) if err != nil { return err } @@ -351,7 +350,7 @@ func (store *DirJWTStore) Reload() error { store.Unlock() return filepath.Walk(store.directory, func(path string, info os.FileInfo, err error) error { if strings.HasSuffix(path, fileExtension) { - if theJwt, err := ioutil.ReadFile(path); err == nil { + if theJwt, err := os.ReadFile(path); err == nil { hash := sha256.Sum256(theJwt) _, file := filepath.Split(path) pkey := strings.TrimSuffix(file, fileExtension) @@ -394,7 +393,7 @@ func (store *DirJWTStore) load(publicKey string) (string, error) { defer store.Unlock() if path := store.pathForKey(publicKey); path == _EMPTY_ { return _EMPTY_, fmt.Errorf("invalid public key") - } else if data, err := ioutil.ReadFile(path); err != nil { + } else if data, err := os.ReadFile(path); err != nil { return _EMPTY_, err } else { if store.expiration != nil { @@ -432,7 +431,7 @@ func (store *DirJWTStore) write(path string, publicKey string, theJWT string) (b } } } - if err := ioutil.WriteFile(path, []byte(theJWT), defaultFilePerms); err != nil { + if err := os.WriteFile(path, []byte(theJWT), defaultFilePerms); err != nil { return false, err } else if store.expiration != nil { store.expiration.track(publicKey, newHash, theJWT) @@ -514,7 +513,7 @@ func (store *DirJWTStore) saveIfNewer(publicKey string, theJWT string) error { if _, err := os.Stat(path); err == nil { if newJWT, err := jwt.DecodeGeneric(theJWT); err != nil { return err - } else if existing, err := ioutil.ReadFile(path); err != nil { + } else if existing, err := os.ReadFile(path); err != nil { return err } else if existingJWT, err := jwt.DecodeGeneric(string(existing)); err != nil { // skip if it can't be decoded diff --git a/server/dirstore_test.go b/server/dirstore_test.go index e5bceb57..2e7a1a6c 100644 --- a/server/dirstore_test.go +++ b/server/dirstore_test.go @@ -17,7 +17,6 @@ import ( "bytes" "crypto/sha256" "fmt" - "io/ioutil" "math" "math/rand" "os" @@ -393,7 +392,7 @@ func createTestAccount(t *testing.T, dirStore *DirJWTStore, expSec int, accKey n func assertStoreSize(t *testing.T, dirStore *DirJWTStore, length int) { t.Helper() - f, err := ioutil.ReadDir(dirStore.directory) + f, err := os.ReadDir(dirStore.directory) require_NoError(t, err) require_Len(t, len(f), length) dirStore.Lock() @@ -429,7 +428,7 @@ func TestExpiration(t *testing.T) { failAt := time.Now().Add(4 * time.Second) for time.Now().Before(failAt) { time.Sleep(100 * time.Millisecond) - f, err := ioutil.ReadDir(dir) + f, err := os.ReadDir(dir) require_NoError(t, err) if len(f) == 1 { lh := dirStore.Hash() @@ -678,7 +677,7 @@ func TestReload(t *testing.T) { jwt, err := account.Encode(accKey) require_NoError(t, err) file := fmt.Sprintf("%s/%s.jwt", dir, pKey) - err = ioutil.WriteFile(file, []byte(jwt), 0644) + err = os.WriteFile(file, []byte(jwt), 0644) require_NoError(t, err) return file } @@ -737,7 +736,7 @@ func TestExpirationUpdate(t *testing.T) { h = nh time.Sleep(1500 * time.Millisecond) - f, err := ioutil.ReadDir(dir) + f, err := os.ReadDir(dir) require_NoError(t, err) require_Len(t, len(f), 1) @@ -747,7 +746,7 @@ func TestExpirationUpdate(t *testing.T) { h = nh time.Sleep(1500 * time.Millisecond) - f, err = ioutil.ReadDir(dir) + f, err = os.ReadDir(dir) require_NoError(t, err) require_Len(t, len(f), 1) @@ -757,7 +756,7 @@ func TestExpirationUpdate(t *testing.T) { h = nh time.Sleep(1500 * time.Millisecond) - f, err = ioutil.ReadDir(dir) + f, err = os.ReadDir(dir) require_NoError(t, err) require_Len(t, len(f), 1) @@ -767,7 +766,7 @@ func TestExpirationUpdate(t *testing.T) { h = nh time.Sleep(1500 * time.Millisecond) - f, err = ioutil.ReadDir(dir) + f, err = os.ReadDir(dir) require_NoError(t, err) require_Len(t, len(f), 0) @@ -781,7 +780,7 @@ func TestTTL(t *testing.T) { dir := createDir(t, "jwtstore_test") require_OneJWT := func() { t.Helper() - f, err := ioutil.ReadDir(dir) + f, err := os.ReadDir(dir) require_NoError(t, err) require_Len(t, len(f), 1) } @@ -805,7 +804,7 @@ func TestTTL(t *testing.T) { // observe expiration for i := 0; i < 40; i++ { time.Sleep(50 * time.Millisecond) - f, err := ioutil.ReadDir(dir) + f, err := os.ReadDir(dir) require_NoError(t, err) if len(f) == 0 { return @@ -844,7 +843,7 @@ func TestRemove(t *testing.T) { dir := createDir(t, "jwtstore_test") require_OneJWT := func() { t.Helper() - f, err := ioutil.ReadDir(dir) + f, err := os.ReadDir(dir) require_NoError(t, err) require_Len(t, len(f), 1) } diff --git a/server/errors_gen.go b/server/errors_gen.go index ade67e4e..bbe50a51 100644 --- a/server/errors_gen.go +++ b/server/errors_gen.go @@ -6,7 +6,6 @@ package main import ( "encoding/json" "fmt" - "io/ioutil" "log" "os" "os/exec" @@ -34,7 +33,7 @@ const ( {{- else }} // {{ .Constant }} {{ .Description | print }} {{- end }} - {{ .Constant }} ErrorIdentifier = {{ .ErrCode }} + {{ .Constant }} ErrorIdentifier = {{ .ErrCode }} {{ end }} ) @@ -229,7 +228,7 @@ func main() { p, err := t.Parse(templ) panicIfErr(err) - tf, err := ioutil.TempFile("", "") + tf, err := os.CreateTemp("", "") panicIfErr(err) defer tf.Close() diff --git a/server/filestore.go b/server/filestore.go index 59788092..fa4ece03 100644 --- a/server/filestore.go +++ b/server/filestore.go @@ -26,7 +26,6 @@ import ( "fmt" "hash" "io" - "io/ioutil" "net" "os" "path/filepath" @@ -274,7 +273,7 @@ func newFileStoreWithCreated(fcfg FileStoreConfig, cfg StreamConfig, created tim } else if stat == nil || !stat.IsDir() { return nil, fmt.Errorf("storage directory is not a directory") } - tmpfile, err := ioutil.TempFile(fcfg.StoreDir, "_test_") + tmpfile, err := os.CreateTemp(fcfg.StoreDir, "_test_") if err != nil { return nil, fmt.Errorf("storage directory is not writable") } @@ -488,7 +487,7 @@ func (fs *fileStore) writeStreamMeta() error { if _, err := os.Stat(keyFile); err != nil && !os.IsNotExist(err) { return err } - if err := ioutil.WriteFile(keyFile, encrypted, defaultFilePerms); err != nil { + if err := os.WriteFile(keyFile, encrypted, defaultFilePerms); err != nil { return err } } @@ -508,14 +507,14 @@ func (fs *fileStore) writeStreamMeta() error { b = fs.aek.Seal(nonce, nonce, b, nil) } - if err := ioutil.WriteFile(meta, b, defaultFilePerms); err != nil { + if err := os.WriteFile(meta, b, defaultFilePerms); err != nil { return err } fs.hh.Reset() fs.hh.Write(b) checksum := hex.EncodeToString(fs.hh.Sum(nil)) sum := filepath.Join(fs.fcfg.StoreDir, JetStreamMetaFileSum) - if err := ioutil.WriteFile(sum, []byte(checksum), defaultFilePerms); err != nil { + if err := os.WriteFile(sum, []byte(checksum), defaultFilePerms); err != nil { return err } return nil @@ -599,7 +598,7 @@ func (fs *fileStore) recoverMsgBlock(fi os.FileInfo, index uint64) (*msgBlock, e // Check if encryption is enabled. if fs.prf != nil { - ekey, err := ioutil.ReadFile(filepath.Join(mdir, fmt.Sprintf(keyScan, mb.index))) + ekey, err := os.ReadFile(filepath.Join(mdir, fmt.Sprintf(keyScan, mb.index))) if err != nil { // We do not seem to have keys even though we should. Could be a plaintext conversion. // Create the keys and we will double check below. @@ -649,15 +648,15 @@ func (fs *fileStore) recoverMsgBlock(fi os.FileInfo, index uint64) (*msgBlock, e // Undo cache from above for later. mb.cache = nil mb.bek.XORKeyStream(buf, buf) - if err := ioutil.WriteFile(mb.mfn, buf, defaultFilePerms); err != nil { + if err := os.WriteFile(mb.mfn, buf, defaultFilePerms); err != nil { return nil, err } - if buf, err = ioutil.ReadFile(mb.ifn); err == nil && len(buf) > 0 { + if buf, err = os.ReadFile(mb.ifn); err == nil && len(buf) > 0 { if err := checkHeader(buf); err != nil { return nil, err } buf = mb.aek.Seal(buf[:0], mb.nonce, buf, nil) - if err := ioutil.WriteFile(mb.ifn, buf, defaultFilePerms); err != nil { + if err := os.WriteFile(mb.ifn, buf, defaultFilePerms); err != nil { return nil, err } } @@ -963,7 +962,7 @@ func (fs *fileStore) recoverMsgs() error { } mdir := filepath.Join(fs.fcfg.StoreDir, msgDir) - fis, err := ioutil.ReadDir(mdir) + fis, err := os.ReadDir(mdir) if err != nil { return errNotReadable } @@ -973,7 +972,11 @@ func (fs *fileStore) recoverMsgs() error { for _, fi := range fis { var index uint64 if n, err := fmt.Sscanf(fi.Name(), blkScan, &index); err == nil && n == 1 { - if mb, err := fs.recoverMsgBlock(fi, index); err == nil && mb != nil { + finfo, err := fi.Info() + if err != nil { + return err + } + if mb, err := fs.recoverMsgBlock(finfo, index); err == nil && mb != nil { if fs.state.FirstSeq == 0 || mb.first.seq < fs.state.FirstSeq { fs.state.FirstSeq = mb.first.seq fs.state.FirstTime = time.Unix(0, mb.first.ts).UTC() @@ -1687,7 +1690,7 @@ func (fs *fileStore) genEncryptionKeysForBlock(mb *msgBlock) error { if _, err := os.Stat(keyFile); err != nil && !os.IsNotExist(err) { return err } - if err := ioutil.WriteFile(keyFile, encrypted, defaultFilePerms); err != nil { + if err := os.WriteFile(keyFile, encrypted, defaultFilePerms); err != nil { return err } mb.kfn = keyFile @@ -2250,7 +2253,7 @@ func (mb *msgBlock) compact() { // We will write to a new file and mv/rename it in case of failure. mfn := filepath.Join(filepath.Join(mb.fs.fcfg.StoreDir, msgDir), fmt.Sprintf(newScan, mb.index)) - if err := ioutil.WriteFile(mfn, nbuf, defaultFilePerms); err != nil { + if err := os.WriteFile(mfn, nbuf, defaultFilePerms); err != nil { os.Remove(mfn) return } @@ -3368,7 +3371,7 @@ func (mb *msgBlock) flushPendingMsgsLocked() (*LostStreamData, error) { return fsLostData, mb.werr } -// Lock should be held. +// Lock should be held. func (mb *msgBlock) clearLoading() { mb.loading = false } @@ -4042,7 +4045,7 @@ func (mb *msgBlock) writeIndexInfoLocked() error { // readIndexInfo will read in the index information for the message block. func (mb *msgBlock) readIndexInfo() error { - buf, err := ioutil.ReadFile(mb.ifn) + buf, err := os.ReadFile(mb.ifn) if err != nil { return err } @@ -4513,7 +4516,7 @@ func (fs *fileStore) Compact(seq uint64) (uint64, error) { smb.bek = bek smb.bek.XORKeyStream(nbuf, nbuf) } - if err = ioutil.WriteFile(smb.mfn, nbuf, defaultFilePerms); err != nil { + if err = os.WriteFile(smb.mfn, nbuf, defaultFilePerms); err != nil { goto SKIP } smb.clearCacheAndOffset() @@ -4678,7 +4681,7 @@ func (mb *msgBlock) closeAndKeepIndex() { mb.mfd.Truncate(0) } else { // We were closed, so just write out an empty file. - ioutil.WriteFile(mb.mfn, nil, defaultFilePerms) + os.WriteFile(mb.mfn, nil, defaultFilePerms) } // Make sure to write the index file so we can remember last seq and ts. mb.writeIndexInfoLocked() @@ -4847,7 +4850,7 @@ func (mb *msgBlock) readPerSubjectInfo() error { minFileSize = 24 ) - buf, err := ioutil.ReadFile(mb.sfn) + buf, err := os.ReadFile(mb.sfn) if err != nil || len(buf) < minFileSize || checkHeader(buf) != nil { return mb.generatePerSubjectInfo() @@ -4926,7 +4929,7 @@ func (mb *msgBlock) writePerSubjectInfo() error { // Now copy over checksum from the block itself, this allows us to know if we are in sync. b.Write(mb.lchk[:]) - return ioutil.WriteFile(mb.sfn, b.Bytes(), defaultFilePerms) + return os.WriteFile(mb.sfn, b.Bytes(), defaultFilePerms) } // Close the message block. @@ -5122,7 +5125,7 @@ func (fs *fileStore) streamSnapshot(w io.WriteCloser, state *StreamState, includ mb.writeIndexInfo() } mb.mu.Lock() - buf, err := ioutil.ReadFile(mb.ifn) + buf, err := os.ReadFile(mb.ifn) if err != nil { mb.mu.Unlock() writeErr(fmt.Sprintf("Could not read message block [%d] index file: %v", mb.index, err)) @@ -5161,7 +5164,7 @@ func (fs *fileStore) streamSnapshot(w io.WriteCloser, state *StreamState, includ } // Make sure we snapshot the per subject info. mb.writePerSubjectInfo() - buf, err = ioutil.ReadFile(mb.sfn) + buf, err = os.ReadFile(mb.sfn) // If not there that is ok and not fatal. if err == nil && writeFile(msgPre+fmt.Sprintf(fssScan, mb.index), buf) != nil { mb.mu.Unlock() @@ -5333,7 +5336,7 @@ func (fs *fileStore) ConsumerStore(name string, cfg *ConsumerConfig) (ConsumerSt // Check for encryption. if o.prf != nil { - if ekey, err := ioutil.ReadFile(filepath.Join(odir, JetStreamMetaFileKey)); err == nil { + if ekey, err := os.ReadFile(filepath.Join(odir, JetStreamMetaFileKey)); err == nil { // Recover key encryption key. rb, err := fs.prf([]byte(fs.cfg.Name + tsep + o.name)) if err != nil { @@ -5380,9 +5383,9 @@ func (fs *fileStore) ConsumerStore(name string, cfg *ConsumerConfig) (ConsumerSt return nil, err } // Redo the state file as well here if we have one and we can tell it was plaintext. - if buf, err := ioutil.ReadFile(o.ifn); err == nil { + if buf, err := os.ReadFile(o.ifn); err == nil { if _, err := decodeConsumerState(buf); err == nil { - if err := ioutil.WriteFile(o.ifn, o.encryptState(buf), defaultFilePerms); err != nil { + if err := os.WriteFile(o.ifn, o.encryptState(buf), defaultFilePerms); err != nil { if didCreate { os.RemoveAll(odir) } @@ -5774,7 +5777,7 @@ func (o *consumerFileStore) writeState(buf []byte) error { // Lock not held here but we do limit number of outstanding calls that could block OS threads. <-dios - err := ioutil.WriteFile(ifn, buf, defaultFilePerms) + err := os.WriteFile(ifn, buf, defaultFilePerms) dios <- struct{}{} o.mu.Lock() @@ -5814,7 +5817,7 @@ func (cfs *consumerFileStore) writeConsumerMeta() error { if _, err := os.Stat(keyFile); err != nil && !os.IsNotExist(err) { return err } - if err := ioutil.WriteFile(keyFile, encrypted, defaultFilePerms); err != nil { + if err := os.WriteFile(keyFile, encrypted, defaultFilePerms); err != nil { return err } } @@ -5830,14 +5833,14 @@ func (cfs *consumerFileStore) writeConsumerMeta() error { b = cfs.aek.Seal(nonce, nonce, b, nil) } - if err := ioutil.WriteFile(meta, b, defaultFilePerms); err != nil { + if err := os.WriteFile(meta, b, defaultFilePerms); err != nil { return err } cfs.hh.Reset() cfs.hh.Write(b) checksum := hex.EncodeToString(cfs.hh.Sum(nil)) sum := filepath.Join(cfs.odir, JetStreamMetaFileSum) - if err := ioutil.WriteFile(sum, []byte(checksum), defaultFilePerms); err != nil { + if err := os.WriteFile(sum, []byte(checksum), defaultFilePerms); err != nil { return err } return nil @@ -5909,7 +5912,7 @@ func (o *consumerFileStore) State() (*ConsumerState, error) { } // Read the state in here from disk.. - buf, err := ioutil.ReadFile(o.ifn) + buf, err := os.ReadFile(o.ifn) if err != nil && !os.IsNotExist(err) { return nil, err } @@ -6089,7 +6092,7 @@ func (o *consumerFileStore) Stop() error { if len(buf) > 0 { o.waitOnFlusher() <-dios - err = ioutil.WriteFile(ifn, buf, defaultFilePerms) + err = os.WriteFile(ifn, buf, defaultFilePerms) dios <- struct{}{} } return err @@ -6203,7 +6206,7 @@ func (ts *templateFileStore) Store(t *streamTemplate) error { if err != nil { return err } - if err := ioutil.WriteFile(meta, b, defaultFilePerms); err != nil { + if err := os.WriteFile(meta, b, defaultFilePerms); err != nil { return err } // FIXME(dlc) - Do checksum @@ -6211,7 +6214,7 @@ func (ts *templateFileStore) Store(t *streamTemplate) error { ts.hh.Write(b) checksum := hex.EncodeToString(ts.hh.Sum(nil)) sum := filepath.Join(dir, JetStreamMetaFileSum) - if err := ioutil.WriteFile(sum, []byte(checksum), defaultFilePerms); err != nil { + if err := os.WriteFile(sum, []byte(checksum), defaultFilePerms); err != nil { return err } return nil diff --git a/server/filestore_test.go b/server/filestore_test.go index 43b1a7fd..5eef89a3 100644 --- a/server/filestore_test.go +++ b/server/filestore_test.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math/bits" "math/rand" "os" @@ -1242,7 +1241,7 @@ func TestFileStoreBitRot(t *testing.T) { // Now twiddle some bits. fs.mu.Lock() lmb := fs.lmb - contents, _ := ioutil.ReadFile(lmb.mfn) + contents, _ := os.ReadFile(lmb.mfn) var index int for { index = rand.Intn(len(contents)) @@ -1253,7 +1252,7 @@ func TestFileStoreBitRot(t *testing.T) { break } } - ioutil.WriteFile(lmb.mfn, contents, 0644) + os.WriteFile(lmb.mfn, contents, 0644) fs.mu.Unlock() ld := fs.checkMsgs() @@ -1421,7 +1420,7 @@ func TestFileStoreMeta(t *testing.T) { t.Fatalf("Expected metafile's checksum %q to exist", metasum) } - buf, err := ioutil.ReadFile(metafile) + buf, err := os.ReadFile(metafile) if err != nil { t.Fatalf("Error reading metafile: %v", err) } @@ -1432,7 +1431,7 @@ func TestFileStoreMeta(t *testing.T) { if !reflect.DeepEqual(mconfig, mconfig2) { t.Fatalf("Stream configs not equal, got %+v vs %+v", mconfig2, mconfig) } - checksum, err := ioutil.ReadFile(metasum) + checksum, err := os.ReadFile(metasum) if err != nil { t.Fatalf("Error reading metafile checksum: %v", err) } @@ -1466,7 +1465,7 @@ func TestFileStoreMeta(t *testing.T) { t.Fatalf("Expected consumer metafile's checksum %q to exist", ometasum) } - buf, err = ioutil.ReadFile(ometafile) + buf, err = os.ReadFile(ometafile) if err != nil { t.Fatalf("Error reading consumer metafile: %v", err) } @@ -1478,7 +1477,7 @@ func TestFileStoreMeta(t *testing.T) { if !reflect.DeepEqual(oconfig2, oconfig) { t.Fatalf("Consumer configs not equal, got %+v vs %+v", oconfig2, oconfig) } - checksum, err = ioutil.ReadFile(ometasum) + checksum, err = os.ReadFile(ometasum) if err != nil { t.Fatalf("Error reading consumer metafile checksum: %v", err) @@ -1808,7 +1807,7 @@ func TestFileStoreSnapshot(t *testing.T) { if err != nil { t.Fatalf("Error creating snapshot") } - snapshot, err := ioutil.ReadAll(r.Reader) + snapshot, err := io.ReadAll(r.Reader) if err != nil { t.Fatalf("Error reading snapshot") } @@ -2843,7 +2842,7 @@ func TestFileStoreStreamDeleteDirNotEmpty(t *testing.T) { g := filepath.Join(storeDir, "g") ready <- true for i := 0; i < 100; i++ { - ioutil.WriteFile(g, []byte("OK"), defaultFilePerms) + os.WriteFile(g, []byte("OK"), defaultFilePerms) } }() @@ -2928,7 +2927,7 @@ func TestFileStoreStreamIndexBug(t *testing.T) { dir := createDir(t, "js-bad-idx-") defer removeDir(t, dir) fn := filepath.Join(dir, "1.idx") - ioutil.WriteFile(fn, badIdxBytes, 0644) + os.WriteFile(fn, badIdxBytes, 0644) mb := &msgBlock{index: 1, ifn: fn} if err := mb.readIndexInfo(); err == nil || !strings.Contains(err.Error(), "short index") { t.Fatalf("Expected error during readIndexInfo(): %v", err) diff --git a/server/gateway.go b/server/gateway.go index 8e4939d8..98439ac1 100644 --- a/server/gateway.go +++ b/server/gateway.go @@ -3096,7 +3096,7 @@ func (c *client) gatewaySwitchAccountToSendAllSubs(e *insie, accName string) { // If `client` is nil, the mapping is stored in the client's account's gwReplyMapping // structure. Account lock will be explicitly acquired. // This is a server receiver because we use a timer interval that is avail in -/// Server.gateway object. +// Server.gateway object. func (s *Server) trackGWReply(c *client, acc *Account, reply, routedReply []byte) { var l sync.Locker var g *gwReplyMapping diff --git a/server/jetstream.go b/server/jetstream.go index b0b068dd..0c4b613c 100644 --- a/server/jetstream.go +++ b/server/jetstream.go @@ -21,7 +21,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "math" "os" "path/filepath" @@ -266,14 +265,14 @@ func (s *Server) decryptMeta(ekey, buf []byte, acc, context string) ([]byte, err // Check to make sure directory has the jetstream directory. // We will have it properly configured here now regardless, so need to look inside. func (s *Server) checkStoreDir(cfg *JetStreamConfig) error { - fis, _ := ioutil.ReadDir(cfg.StoreDir) + fis, _ := os.ReadDir(cfg.StoreDir) // If we have nothing underneath us, could be just starting new, but if we see this we can check. if len(fis) != 0 { return nil } // Let's check the directory above. If it has us 'jetstream' but also other stuff that we can // identify as accounts then we can fix. - fis, _ = ioutil.ReadDir(filepath.Dir(cfg.StoreDir)) + fis, _ = os.ReadDir(filepath.Dir(cfg.StoreDir)) // If just one that is us 'jetstream' and all is ok. if len(fis) == 1 { return nil @@ -342,7 +341,7 @@ func (s *Server) enableJetStream(cfg JetStreamConfig) error { if stat == nil || !stat.IsDir() { return fmt.Errorf("storage directory is not a directory") } - tmpfile, err := ioutil.TempFile(cfg.StoreDir, "_test_") + tmpfile, err := os.CreateTemp(cfg.StoreDir, "_test_") if err != nil { return fmt.Errorf("storage directory is not writable") } @@ -707,7 +706,7 @@ func (s *Server) configAllJetStreamAccounts() error { // Now walk all the storage we have and resolve any accounts that we did not process already. // This is important in resolver/operator models. - fis, _ := ioutil.ReadDir(js.config.StoreDir) + fis, _ := os.ReadDir(js.config.StoreDir) for _, fi := range fis { if accName := fi.Name(); accName != _EMPTY_ { // Only load up ones not already loaded since they are processed above. @@ -1067,11 +1066,11 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro if err != nil { return err } - fis, _ := ioutil.ReadDir(tdir) + fis, _ := os.ReadDir(tdir) for _, fi := range fis { metafile := filepath.Join(tdir, fi.Name(), JetStreamMetaFile) metasum := filepath.Join(tdir, fi.Name(), JetStreamMetaFileSum) - buf, err := ioutil.ReadFile(metafile) + buf, err := os.ReadFile(metafile) if err != nil { s.Warnf(" Error reading StreamTemplate metafile %q: %v", metasum, err) continue @@ -1080,7 +1079,7 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro s.Warnf(" Missing StreamTemplate checksum for %q", metasum) continue } - sum, err := ioutil.ReadFile(metasum) + sum, err := os.ReadFile(metasum) if err != nil { s.Warnf(" Error reading StreamTemplate checksum %q: %v", metasum, err) continue @@ -1113,7 +1112,7 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro var consumers []*ce // Now recover the streams. - fis, _ := ioutil.ReadDir(sdir) + fis, _ := os.ReadDir(sdir) for _, fi := range fis { mdir := filepath.Join(sdir, fi.Name()) key := sha256.Sum256([]byte(fi.Name())) @@ -1127,7 +1126,7 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro s.Warnf(" Missing stream metafile for %q", metafile) continue } - buf, err := ioutil.ReadFile(metafile) + buf, err := os.ReadFile(metafile) if err != nil { s.Warnf(" Error reading metafile %q: %v", metafile, err) continue @@ -1136,7 +1135,7 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro s.Warnf(" Missing stream checksum file %q", metasum) continue } - sum, err := ioutil.ReadFile(metasum) + sum, err := os.ReadFile(metasum) if err != nil { s.Warnf(" Error reading Stream metafile checksum %q: %v", metasum, err) continue @@ -1149,7 +1148,7 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro } // Check if we are encrypted. - if key, err := ioutil.ReadFile(filepath.Join(mdir, JetStreamMetaFileKey)); err == nil { + if key, err := os.ReadFile(filepath.Join(mdir, JetStreamMetaFileKey)); err == nil { s.Debugf(" Stream metafile is encrypted, reading encrypted keyfile") if len(key) != metaKeySize { s.Warnf(" Bad stream encryption key length of %d", len(key)) @@ -1222,7 +1221,7 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro } for _, e := range consumers { - ofis, _ := ioutil.ReadDir(e.odir) + ofis, _ := os.ReadDir(e.odir) if len(ofis) > 0 { s.Noticef(" Recovering %d consumers for stream - '%s > %s'", len(ofis), e.mset.accName(), e.mset.name()) } @@ -1233,7 +1232,7 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro s.Warnf(" Missing consumer metafile %q", metafile) continue } - buf, err := ioutil.ReadFile(metafile) + buf, err := os.ReadFile(metafile) if err != nil { s.Warnf(" Error reading consumer metafile %q: %v", metafile, err) continue @@ -1244,7 +1243,7 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) erro } // Check if we are encrypted. - if key, err := ioutil.ReadFile(filepath.Join(e.odir, ofi.Name(), JetStreamMetaFileKey)); err == nil { + if key, err := os.ReadFile(filepath.Join(e.odir, ofi.Name(), JetStreamMetaFileKey)); err == nil { s.Debugf(" Consumer metafile is encrypted, reading encrypted keyfile") // Decode the buffer before proceeding. if buf, err = s.decryptMeta(key, buf, a.Name, e.mset.name()+tsep+ofi.Name()); err != nil { diff --git a/server/jetstream_api.go b/server/jetstream_api.go index f9c4198e..93234533 100644 --- a/server/jetstream_api.go +++ b/server/jetstream_api.go @@ -18,7 +18,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -3090,7 +3089,7 @@ func (s *Server) processStreamRestore(ci *ClientInfo, acc *Account, cfg *StreamC } } - tfile, err := ioutil.TempFile(snapDir, "js-restore-") + tfile, err := os.CreateTemp(snapDir, "js-restore-") if err != nil { resp.Error = NewJSTempStorageFailedError() s.sendAPIErrResponse(ci, acc, subject, reply, msg, s.jsonResponse(&resp)) diff --git a/server/jetstream_helpers_test.go b/server/jetstream_helpers_test.go index 8c69e8c4..7a995252 100644 --- a/server/jetstream_helpers_test.go +++ b/server/jetstream_helpers_test.go @@ -20,9 +20,9 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "math/rand" "net" + "os" "strings" "testing" "time" @@ -712,7 +712,7 @@ func createJetStreamClusterAndModHook(t *testing.T, tmpl string, clusterName, sn func (c *cluster) addInNewServer() *Server { c.t.Helper() sn := fmt.Sprintf("S-%d", len(c.servers)+1) - storeDir, _ := ioutil.TempDir(tempRoot, JetStreamStoreDir) + storeDir, _ := os.MkdirTemp(tempRoot, JetStreamStoreDir) seedRoute := fmt.Sprintf("nats-route://127.0.0.1:%d", c.opts[0].Cluster.Port) conf := fmt.Sprintf(jsClusterTempl, sn, storeDir, c.name, -1, seedRoute) s, o := RunServerWithConfig(createConfFile(c.t, []byte(conf))) @@ -1333,14 +1333,14 @@ func (c *cluster) removeJetStream(s *Server) { } } cf := c.opts[index].ConfigFile - cb, _ := ioutil.ReadFile(cf) + cb, _ := os.ReadFile(cf) var sb strings.Builder for _, l := range strings.Split(string(cb), "\n") { if !strings.HasPrefix(strings.TrimSpace(l), "jetstream") { sb.WriteString(l + "\n") } } - if err := ioutil.WriteFile(cf, []byte(sb.String()), 0644); err != nil { + if err := os.WriteFile(cf, []byte(sb.String()), 0644); err != nil { c.t.Fatalf("Error writing updated config file: %v", err) } if err := s.Reload(); err != nil { diff --git a/server/jetstream_leafnode_test.go b/server/jetstream_leafnode_test.go index 64005041..2cf40072 100644 --- a/server/jetstream_leafnode_test.go +++ b/server/jetstream_leafnode_test.go @@ -18,7 +18,6 @@ package server import ( "fmt" - "io/ioutil" "os" "strings" "testing" @@ -891,7 +890,7 @@ leafnodes: { require_True(t, err == nats.ErrNoResponders) // Add in default domain and restart server - require_NoError(t, ioutil.WriteFile(confHub, []byte(fmt.Sprintf(tmplHub, + require_NoError(t, os.WriteFile(confHub, []byte(fmt.Sprintf(tmplHub, sHub.opts.Port, "disabled", "disabled", @@ -914,7 +913,7 @@ leafnodes: { sdHub := createDir(t, JetStreamStoreDir) defer os.RemoveAll(sdHub) jsEnabled := fmt.Sprintf(`{ domain: "%s", store_dir: '%s', max_mem: 100Mb, max_file: 100Mb }`, domain, sdHub) - require_NoError(t, ioutil.WriteFile(confHub, []byte(fmt.Sprintf(tmplHub, + require_NoError(t, os.WriteFile(confHub, []byte(fmt.Sprintf(tmplHub, sHubUpd1.opts.Port, "disabled", jsEnabled, @@ -935,7 +934,7 @@ leafnodes: { // Enable jetstream in account A of hub // This is a mis config, as you can't have it both ways, local jetstream but default to another one - require_NoError(t, ioutil.WriteFile(confHub, []byte(fmt.Sprintf(tmplHub, + require_NoError(t, os.WriteFile(confHub, []byte(fmt.Sprintf(tmplHub, sHubUpd2.opts.Port, "enabled", jsEnabled, @@ -1052,7 +1051,7 @@ leafnodes: { require_True(t, err == nats.ErrNoResponders) // Add in default domain and restart server - require_NoError(t, ioutil.WriteFile(confHub, []byte(fmt.Sprintf(tmplHub, + require_NoError(t, os.WriteFile(confHub, []byte(fmt.Sprintf(tmplHub, sHub.opts.Port, ojwt, syspub, syspub, sysJwt, aPub, aJwt, sHub.opts.LeafNode.Port, fmt.Sprintf(`default_js_domain: {%s:"%s"}`, aPub, domain))), 0664)) diff --git a/server/jetstream_test.go b/server/jetstream_test.go index 373e81f6..b5116ca8 100644 --- a/server/jetstream_test.go +++ b/server/jetstream_test.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "math/rand" "net/http" @@ -93,7 +92,7 @@ func RunBasicJetStreamServer() *Server { opts := DefaultTestOptions opts.Port = -1 opts.JetStream = true - tdir, _ := ioutil.TempDir(tempRoot, "jstests-storedir-") + tdir, _ := os.MkdirTemp(tempRoot, "jstests-storedir-") opts.StoreDir = tdir return RunServer(&opts) } @@ -4129,7 +4128,7 @@ func TestJetStreamSnapshots(t *testing.T) { t.Fatalf("Error getting snapshot: %v", err) } zr := sr.Reader - snapshot, err := ioutil.ReadAll(zr) + snapshot, err := io.ReadAll(zr) if err != nil { t.Fatalf("Error reading snapshot") } @@ -9679,7 +9678,7 @@ func TestJetStreamMultipleAccountsBasics(t *testing.T) { }, } `) - if err := ioutil.WriteFile(conf, newConf, 0600); err != nil { + if err := os.WriteFile(conf, newConf, 0600); err != nil { t.Fatalf("Error rewriting server's config file: %v", err) } if err := s.Reload(); err != nil { @@ -9813,7 +9812,7 @@ func TestJetStreamStoreDirectoryFix(t *testing.T) { // Now move stuff up from the jetstream directory etc. jssd := filepath.Join(sd, JetStreamStoreDir) - fis, _ := ioutil.ReadDir(jssd) + fis, _ := os.ReadDir(jssd) // This will be accounts, move them up one directory. for _, fi := range fis { os.Rename(filepath.Join(jssd, fi.Name()), filepath.Join(sd, fi.Name())) @@ -11524,7 +11523,7 @@ func TestJetStreamConfigReloadWithGlobalAccount(t *testing.T) { t.Fatalf("Expected %d msgs after restart, got %d", toSend, si.State.Msgs) } - if err := ioutil.WriteFile(conf, []byte(fmt.Sprintf(template, "pwd2")), 0666); err != nil { + if err := os.WriteFile(conf, []byte(fmt.Sprintf(template, "pwd2")), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } @@ -12640,7 +12639,7 @@ func TestJetStreamServerEncryption(t *testing.T) { // Make sure we can not find any plaintext strings in the target file. checkFor := func(fn string, strs ...string) { t.Helper() - data, err := ioutil.ReadFile(fn) + data, err := os.ReadFile(fn) if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -12669,7 +12668,7 @@ func TestJetStreamServerEncryption(t *testing.T) { checkKeyFile(filepath.Join(sdir, "obs", "dlc", JetStreamMetaFileKey)) checkFor(filepath.Join(sdir, "obs", "dlc", JetStreamMetaFile), "TEST", "dlc", "foo", "bar", "baz", "max_msgs", "ack_policy") // Load and see if we can parse the consumer state. - state, err := ioutil.ReadFile(filepath.Join(sdir, "obs", "dlc", "o.dat")) + state, err := os.ReadFile(filepath.Join(sdir, "obs", "dlc", "o.dat")) if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -12733,7 +12732,7 @@ func TestJetStreamServerEncryption(t *testing.T) { if err != nil { t.Fatalf("Error getting snapshot: %v", err) } - snapshot, err := ioutil.ReadAll(sr.Reader) + snapshot, err := io.ReadAll(sr.Reader) if err != nil { t.Fatalf("Error reading snapshot") } @@ -15008,11 +15007,11 @@ func TestJetStreamPullConsumerCrossAccountsAndLeafNodes(t *testing.T) { } // This test is to explicitly test for all combinations of pull consumer behavior. -// 1. Long poll, will be used to emulate push. A request is only invalidated when batch is filled, it expires, or we lose interest. -// 2. Batch 1, will return no messages or a message. Works today. -// 3. Conditional wait, or one shot. This is what the clients do when the do a fetch(). -// They expect to wait up to a given time for any messages but will return once they have any to deliver, so parital fills. -// 4. Try, which never waits at all ever. +// 1. Long poll, will be used to emulate push. A request is only invalidated when batch is filled, it expires, or we lose interest. +// 2. Batch 1, will return no messages or a message. Works today. +// 3. Conditional wait, or one shot. This is what the clients do when the do a fetch(). +// They expect to wait up to a given time for any messages but will return once they have any to deliver, so parital fills. +// 4. Try, which never waits at all ever. func TestJetStreamPullConsumersOneShotBehavior(t *testing.T) { s := RunBasicJetStreamServer() if config := s.JetStreamConfig(); config != nil { @@ -15858,7 +15857,7 @@ func TestJetStreamStorageReservedBytes(t *testing.T) { opts.JetStream = true opts.JetStreamMaxMemory = systemLimit opts.JetStreamMaxStore = systemLimit - tdir, _ := ioutil.TempDir(tempRoot, "jstests-storedir-") + tdir, _ := os.MkdirTemp(tempRoot, "jstests-storedir-") opts.StoreDir = tdir opts.HTTPPort = -1 s := RunServer(&opts) @@ -16376,7 +16375,7 @@ func TestJetStreamRemoveExternalSource(t *testing.T) { lu, err := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", ho.LeafNode.Port)) require_NoError(t, err) - tdir, _ := ioutil.TempDir(tempRoot, "jstests-storedir-") + tdir, _ := os.MkdirTemp(tempRoot, "jstests-storedir-") defer removeDir(t, tdir) lo1 := DefaultTestOptions lo1.Port = 4111 //-1 @@ -16388,7 +16387,7 @@ func TestJetStreamRemoveExternalSource(t *testing.T) { l1 := RunServer(&lo1) defer l1.Shutdown() - tdir, _ = ioutil.TempDir(tempRoot, "jstests-storedir-") + tdir, _ = os.MkdirTemp(tempRoot, "jstests-storedir-") defer removeDir(t, tdir) lo2 := DefaultTestOptions lo2.Port = 2111 //-1 diff --git a/server/jwt.go b/server/jwt.go index 5ab89791..4c97ed21 100644 --- a/server/jwt.go +++ b/server/jwt.go @@ -15,8 +15,8 @@ package server import ( "fmt" - "io/ioutil" "net" + "os" "strings" "time" @@ -34,7 +34,7 @@ func ReadOperatorJWT(jwtfile string) (*jwt.OperatorClaims, error) { } func readOperatorJWT(jwtfile string) (string, *jwt.OperatorClaims, error) { - contents, err := ioutil.ReadFile(jwtfile) + contents, err := os.ReadFile(jwtfile) if err != nil { // Check to see if the JWT has been inlined. if !strings.HasPrefix(jwtfile, jwtPrefix) { diff --git a/server/jwt_test.go b/server/jwt_test.go index 48e8a99e..561b7e95 100644 --- a/server/jwt_test.go +++ b/server/jwt_test.go @@ -20,7 +20,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -3158,7 +3157,7 @@ func TestJWTExpiredUserCredentialsRenewal(t *testing.T) { conf := createFile(t, "") fName := conf.Name() conf.Close() - if err := ioutil.WriteFile(fName, content, 0666); err != nil { + if err := os.WriteFile(fName, content, 0666); err != nil { removeFile(t, fName) t.Fatalf("Error writing conf file: %v", err) } @@ -3243,7 +3242,7 @@ func TestJWTExpiredUserCredentialsRenewal(t *testing.T) { if err != nil { t.Fatalf("Error encoding credentials: %v", err) } - if err := ioutil.WriteFile(chainedFile, creds, 0666); err != nil { + if err := os.WriteFile(chainedFile, creds, 0666); err != nil { t.Fatalf("Error writing conf file: %v", err) } @@ -3317,7 +3316,7 @@ func require_JWTPresent(t *testing.T, dir string, pub string) { func require_JWTEqual(t *testing.T, dir string, pub string, jwt string) { t.Helper() - content, err := ioutil.ReadFile(filepath.Join(dir, pub+".jwt")) + content, err := os.ReadFile(filepath.Join(dir, pub+".jwt")) require_NoError(t, err) require_Equal(t, string(content), jwt) } @@ -3326,7 +3325,7 @@ func createDir(t testing.TB, prefix string) string { t.Helper() err := os.MkdirAll(tempRoot, 0700) require_NoError(t, err) - dir, err := ioutil.TempDir(tempRoot, prefix) + dir, err := os.MkdirTemp(tempRoot, prefix) require_NoError(t, err) return dir } @@ -3340,7 +3339,7 @@ func createFile(t *testing.T, prefix string) *os.File { func createFileAtDir(t *testing.T, dir, prefix string) *os.File { t.Helper() - f, err := ioutil.TempFile(dir, prefix) + f, err := os.CreateTemp(dir, prefix) require_NoError(t, err) return f } @@ -3361,7 +3360,7 @@ func removeFile(t *testing.T, p string) { func writeJWT(t *testing.T, dir string, pub string, jwt string) { t.Helper() - err := ioutil.WriteFile(filepath.Join(dir, pub+".jwt"), []byte(jwt), 0644) + err := os.WriteFile(filepath.Join(dir, pub+".jwt"), []byte(jwt), 0644) require_NoError(t, err) } diff --git a/server/leafnode.go b/server/leafnode.go index 69afdd0b..0170ac2f 100644 --- a/server/leafnode.go +++ b/server/leafnode.go @@ -20,11 +20,11 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "math/rand" "net" "net/http" "net/url" + "os" "reflect" "regexp" "runtime" @@ -142,7 +142,7 @@ func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) { } s.mu.Unlock() if creds != _EMPTY_ { - contents, err := ioutil.ReadFile(creds) + contents, err := os.ReadFile(creds) defer wipeSlice(contents) if err != nil { s.Errorf("Error reading LeafNode Remote Credentials file %q: %v", creds, err) @@ -710,7 +710,7 @@ func (c *client) sendLeafConnect(clusterName string, tlsRequired, headers bool) // Check for credentials first, that will take precedence.. if creds := c.leaf.remote.Credentials; creds != _EMPTY_ { c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials) - contents, err := ioutil.ReadFile(creds) + contents, err := os.ReadFile(creds) if err != nil { c.Errorf("%v", err) return err diff --git a/server/log_test.go b/server/log_test.go index d41fba4b..e32c3556 100644 --- a/server/log_test.go +++ b/server/log_test.go @@ -15,7 +15,6 @@ package server import ( "bytes" - "io/ioutil" "os" "runtime" "strings" @@ -109,7 +108,7 @@ func TestReOpenLogFile(t *testing.T) { expectedStr := "This is a Notice" s.Noticef(expectedStr) // Check content of log - buf, err := ioutil.ReadFile(s.opts.LogFile) + buf, err := os.ReadFile(s.opts.LogFile) if err != nil { t.Fatalf("Error reading file: %v", err) } @@ -123,7 +122,7 @@ func TestReOpenLogFile(t *testing.T) { // Now re-open LogFile s.ReOpenLogFile() // Content should indicate that we have re-opened the log - buf, err = ioutil.ReadFile(s.opts.LogFile) + buf, err = os.ReadFile(s.opts.LogFile) if err != nil { t.Fatalf("Error reading file: %v", err) } @@ -132,7 +131,7 @@ func TestReOpenLogFile(t *testing.T) { } // Make sure we can append to the log s.Noticef("New message") - buf, err = ioutil.ReadFile(s.opts.LogFile) + buf, err = os.ReadFile(s.opts.LogFile) if err != nil { t.Fatalf("Error reading file: %v", err) } @@ -163,7 +162,7 @@ func TestFileLoggerSizeLimitAndReopen(t *testing.T) { s.ReOpenLogFile() // Content should indicate that we have re-opened the log - buf, err := ioutil.ReadFile(s.opts.LogFile) + buf, err := os.ReadFile(s.opts.LogFile) if err != nil { t.Fatalf("Error reading file: %v", err) } @@ -182,7 +181,7 @@ func TestFileLoggerSizeLimitAndReopen(t *testing.T) { } s.Noticef(string(txt)) - buf, err = ioutil.ReadFile(s.opts.LogFile) + buf, err = os.ReadFile(s.opts.LogFile) if err != nil { t.Fatalf("Error reading file: %v", err) } diff --git a/server/monitor_test.go b/server/monitor_test.go index 71f10951..d6f756f0 100644 --- a/server/monitor_test.go +++ b/server/monitor_test.go @@ -19,11 +19,12 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "math/rand" "net" "net/http" "net/url" + "os" "reflect" "runtime" "sort" @@ -158,7 +159,7 @@ func readBodyEx(t *testing.T, url string, status int, content string) []byte { if ct != content { stackFatalf(t, "Expected %s content-type, got %s\n", content, ct) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { stackFatalf(t, "Got an error reading the body: %v\n", err) } @@ -1672,7 +1673,7 @@ func TestHandleRoot(t *testing.T) { t.Fatalf("Expected a %d response, got %d\n", http.StatusOK, resp.StatusCode) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Expected no error reading body: Got %v\n", err) } @@ -2010,7 +2011,7 @@ func TestConcurrentMonitoring(t *testing.T) { ech <- fmt.Sprintf("Expected application/json content-type, got %s\n", ct) return } - if _, err := ioutil.ReadAll(resp.Body); err != nil { + if _, err := io.ReadAll(resp.Body); err != nil { ech <- fmt.Sprintf("Got an error reading the body: %v\n", err) return } @@ -2404,7 +2405,7 @@ func Benchmark_VarzHttp(b *testing.B) { b.Fatalf("Expected no error: Got %v\n", err) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { b.Fatalf("Got an error reading the body: %v\n", err) } @@ -3595,7 +3596,7 @@ func TestMonitorOpJWT(t *testing.T) { sa, _ := RunServerWithConfig(conf) defer sa.Shutdown() - theJWT, err := ioutil.ReadFile("../test/configs/nkeys/op.jwt") + theJWT, err := os.ReadFile("../test/configs/nkeys/op.jwt") require_NoError(t, err) theJWT = []byte(strings.Split(string(theJWT), "\n")[1]) claim, err := jwt.DecodeOperatorClaims(string(theJWT)) diff --git a/server/mqtt.go b/server/mqtt.go index e86558a2..f4d733c0 100644 --- a/server/mqtt.go +++ b/server/mqtt.go @@ -3831,11 +3831,11 @@ func mqttFilterToNATSSubject(filter []byte) ([]byte, error) { // - '/' is the topic level separator. // // Conversion that occurs: -// - '/' is replaced with '/.' if it is the first character in mt -// - '/' is replaced with './' if the last or next character in mt is '/' -// For instance, foo//bar would become foo./.bar -// - '/' is replaced with '.' for all other conditions (foo/bar -> foo.bar) -// - '.' and ' ' cause an error to be returned. +// - '/' is replaced with '/.' if it is the first character in mt +// - '/' is replaced with './' if the last or next character in mt is '/' +// For instance, foo//bar would become foo./.bar +// - '/' is replaced with '.' for all other conditions (foo/bar -> foo.bar) +// - '.' and ' ' cause an error to be returned. // // If there is no need to convert anything (say "foo" remains "foo"), then // the no memory is allocated and the returned slice is the original `mt`. diff --git a/server/norace_test.go b/server/norace_test.go index e14ef24b..a20ca45b 100644 --- a/server/norace_test.go +++ b/server/norace_test.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math/rand" "net" "net/http" @@ -2902,13 +2901,13 @@ func TestNoRaceCompressedConnz(t *testing.T) { t.Fatalf("Unexpected error: %v", err) } defer zr.Close() - buf, err = ioutil.ReadAll(zr) + buf, err = io.ReadAll(zr) if err != nil && err != io.ErrUnexpectedEOF { t.Fatalf("Unexpected error: %v", err) } case "snappy", "s2": sr := s2.NewReader(bytes.NewReader(buf)) - buf, err = ioutil.ReadAll(sr) + buf, err = io.ReadAll(sr) if err != nil && err != io.ErrUnexpectedEOF { t.Fatalf("Unexpected error: %v", err) } @@ -4210,7 +4209,7 @@ func TestNoRaceJetStreamClusterHealthz(t *testing.T) { resp, err := http.Get(url) require_NoError(t, err) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require_NoError(t, err) var hs HealthStatus err = json.Unmarshal(body, &hs) @@ -5183,10 +5182,19 @@ func TestNoRaceJetStreamClusterInterestPullConsumerStreamLimitBug(t *testing.T) for i := 0; i < 100; i++ { go func() { defer wg.Done() - nc, js := jsClientConnect(t, c.randomServer()) + nc := natsConnect(t, c.randomServer().ClientURL()) defer nc.Close() - sub, err := js.PullSubscribe("foo", "dur") + js, err := nc.JetStream(nats.MaxWait(time.Second)) + require_NoError(t, err) + + var sub *nats.Subscription + for j := 0; j < 5; j++ { + sub, err = js.PullSubscribe("foo", "dur") + if err == nil { + break + } + } require_NoError(t, err) for { diff --git a/server/ocsp.go b/server/ocsp.go index 7511aa7b..fa8b2113 100644 --- a/server/ocsp.go +++ b/server/ocsp.go @@ -21,7 +21,7 @@ import ( "encoding/base64" "encoding/pem" "fmt" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -129,7 +129,7 @@ func (oc *OCSPMonitor) getLocalStatus() ([]byte, *ocsp.Response, error) { key := fmt.Sprintf("%x", sha256.Sum256(oc.Leaf.Raw)) oc.mu.Lock() - raw, err := ioutil.ReadFile(filepath.Join(storeDir, defaultOCSPStoreDir, key)) + raw, err := os.ReadFile(filepath.Join(storeDir, defaultOCSPStoreDir, key)) oc.mu.Unlock() if err != nil { return nil, nil, err @@ -168,7 +168,7 @@ func (oc *OCSPMonitor) getRemoteStatus() ([]byte, *ocsp.Response, error) { return nil, fmt.Errorf("non-ok http status: %d", resp.StatusCode) } - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } // Request documentation: @@ -734,7 +734,7 @@ func hasOCSPStatusRequest(cert *x509.Certificate) bool { // new path, in an attempt to avoid corrupting existing data. func (oc *OCSPMonitor) writeOCSPStatus(storeDir, file string, data []byte) error { storeDir = filepath.Join(storeDir, defaultOCSPStoreDir) - tmp, err := ioutil.TempFile(storeDir, "tmp-cert-status") + tmp, err := os.CreateTemp(storeDir, "tmp-cert-status") if err != nil { return err } @@ -760,7 +760,7 @@ func (oc *OCSPMonitor) writeOCSPStatus(storeDir, file string, data []byte) error } func parseCertPEM(name string) ([]*x509.Certificate, error) { - data, err := ioutil.ReadFile(name) + data, err := os.ReadFile(name) if err != nil { return nil, err } diff --git a/server/opts.go b/server/opts.go index 0753464f..c6ec7531 100644 --- a/server/opts.go +++ b/server/opts.go @@ -20,7 +20,6 @@ import ( "errors" "flag" "fmt" - "io/ioutil" "math" "net" "net/url" @@ -2981,10 +2980,10 @@ func parseAccount(v map[string]interface{}, errors, warnings *[]error) (string, // Parse an export stream or service. // e.g. -// {stream: "public.>"} # No accounts means public. -// {stream: "synadia.private.>", accounts: [cncf, natsio]} -// {service: "pub.request"} # No accounts means public. -// {service: "pub.special.request", accounts: [nats.io]} +// {stream: "public.>"} # No accounts means public. +// {stream: "synadia.private.>", accounts: [cncf, natsio]} +// {service: "pub.request"} # No accounts means public. +// {service: "pub.special.request", accounts: [nats.io]} func parseExportStreamOrService(v interface{}, errors, warnings *[]error) (*export, *export, error) { var ( curStream *export @@ -3249,9 +3248,9 @@ func parseServiceLatency(root token, v interface{}) (l *serviceLatency, retErr e // Parse an import stream or service. // e.g. -// {stream: {account: "synadia", subject:"public.synadia"}, prefix: "imports.synadia"} -// {stream: {account: "synadia", subject:"synadia.private.*"}} -// {service: {account: "synadia", subject: "pub.special.request"}, to: "synadia.request"} +// {stream: {account: "synadia", subject:"public.synadia"}, prefix: "imports.synadia"} +// {stream: {account: "synadia", subject:"synadia.private.*"}} +// {service: {account: "synadia", subject: "pub.special.request"}, to: "synadia.request"} func parseImportStreamOrService(v interface{}, errors, warnings *[]error) (*importStream, *importService, error) { var ( curStream *importStream @@ -4260,7 +4259,7 @@ func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) { } // Add in CAs if applicable. if tc.CaFile != "" { - rootPEM, err := ioutil.ReadFile(tc.CaFile) + rootPEM, err := os.ReadFile(tc.CaFile) if err != nil || rootPEM == nil { return nil, err } @@ -4970,7 +4969,7 @@ func processSignal(signal string) error { // 2. If such a file exists and can be read, return its contents. // 3. Otherwise, return the original "pidStr" string. func maybeReadPidFile(pidStr string) string { - if b, err := ioutil.ReadFile(pidStr); err == nil { + if b, err := os.ReadFile(pidStr); err == nil { return string(b) } return pidStr diff --git a/server/opts_test.go b/server/opts_test.go index f612e94a..1a78aaad 100644 --- a/server/opts_test.go +++ b/server/opts_test.go @@ -19,7 +19,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "net/url" "os" "reflect" @@ -1134,7 +1133,7 @@ func TestBadNkeyConfig(t *testing.T) { authorization { users = [ {nkey: "Ufoo"}] }` - if err := ioutil.WriteFile(confFileName, []byte(content), 0666); err != nil { + if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } if _, err := ProcessConfigFile(confFileName); err == nil { @@ -1151,7 +1150,7 @@ func TestNkeyWithPassConfig(t *testing.T) { {nkey: "UDKTV7HZVYJFJN64LLMYQBUR6MTNNYCDC3LAZH4VHURW3GZLL3FULBXV", pass: "foo"} ] }` - if err := ioutil.WriteFile(confFileName, []byte(content), 0666); err != nil { + if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } if _, err := ProcessConfigFile(confFileName); err == nil { @@ -1168,7 +1167,7 @@ func TestTokenWithUserPass(t *testing.T) { pass: password token: $2a$11$whatever }` - if err := ioutil.WriteFile(confFileName, []byte(content), 0666); err != nil { + if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } _, err := ProcessConfigFile(confFileName) @@ -1190,7 +1189,7 @@ func TestTokenWithUsers(t *testing.T) { {user: test, password: test} ] }` - if err := ioutil.WriteFile(confFileName, []byte(content), 0666); err != nil { + if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } _, err := ProcessConfigFile(confFileName) @@ -1205,7 +1204,7 @@ func TestTokenWithUsers(t *testing.T) { func TestParseWriteDeadline(t *testing.T) { confFile := "test.conf" defer removeFile(t, confFile) - if err := ioutil.WriteFile(confFile, []byte("write_deadline: \"1x\""), 0666); err != nil { + if err := os.WriteFile(confFile, []byte("write_deadline: \"1x\""), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } _, err := ProcessConfigFile(confFile) @@ -1216,7 +1215,7 @@ func TestParseWriteDeadline(t *testing.T) { t.Fatalf("Expected error related to parsing, got %v", err) } removeFile(t, confFile) - if err := ioutil.WriteFile(confFile, []byte("write_deadline: \"1s\""), 0666); err != nil { + if err := os.WriteFile(confFile, []byte("write_deadline: \"1s\""), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } opts, err := ProcessConfigFile(confFile) @@ -1234,7 +1233,7 @@ func TestParseWriteDeadline(t *testing.T) { os.Stdout = oldStdout }() os.Stdout = w - if err := ioutil.WriteFile(confFile, []byte("write_deadline: 2"), 0666); err != nil { + if err := os.WriteFile(confFile, []byte("write_deadline: 2"), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } opts, err = ProcessConfigFile(confFile) @@ -2109,7 +2108,7 @@ func TestParsingGateways(t *testing.T) { ` file := "server_config_gateways.conf" defer removeFile(t, file) - if err := ioutil.WriteFile(file, []byte(content), 0600); err != nil { + if err := os.WriteFile(file, []byte(content), 0600); err != nil { t.Fatalf("Error writing config file: %v", err) } opts, err := ProcessConfigFile(file) @@ -2363,7 +2362,7 @@ func TestParsingGatewaysErrors(t *testing.T) { t.Run(test.name, func(t *testing.T) { file := fmt.Sprintf("server_config_gateways_%s.conf", test.name) defer removeFile(t, file) - if err := ioutil.WriteFile(file, []byte(test.content), 0600); err != nil { + if err := os.WriteFile(file, []byte(test.content), 0600); err != nil { t.Fatalf("Error writing config file: %v", err) } _, err := ProcessConfigFile(file) @@ -2570,7 +2569,7 @@ func TestLargeMaxControlLine(t *testing.T) { content := ` max_control_line = 3000000000 ` - if err := ioutil.WriteFile(confFileName, []byte(content), 0666); err != nil { + if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } if _, err := ProcessConfigFile(confFileName); err == nil { diff --git a/server/pse/pse_linux.go b/server/pse/pse_linux.go index aa986d03..77eb8f6a 100644 --- a/server/pse/pse_linux.go +++ b/server/pse/pse_linux.go @@ -16,7 +16,6 @@ package pse import ( "bytes" "fmt" - "io/ioutil" "os" "sync/atomic" "syscall" @@ -48,7 +47,7 @@ func init() { // Sampling function to keep pcpu relevant. func periodic() { - contents, err := ioutil.ReadFile(procStatFile) + contents, err := os.ReadFile(procStatFile) if err != nil { return } @@ -88,7 +87,7 @@ func periodic() { // ProcUsage returns CPU usage func ProcUsage(pcpu *float64, rss, vss *int64) error { - contents, err := ioutil.ReadFile(procStatFile) + contents, err := os.ReadFile(procStatFile) if err != nil { return err } diff --git a/server/raft.go b/server/raft.go index 0ac62ee8..419f580a 100644 --- a/server/raft.go +++ b/server/raft.go @@ -20,7 +20,6 @@ import ( "errors" "fmt" "hash" - "io/ioutil" "math" "math/rand" "net" @@ -330,7 +329,7 @@ func (s *Server) bootstrapRaftNode(cfg *RaftConfig, knownPeers []string, allPeer } else if stat == nil || !stat.IsDir() { return fmt.Errorf("raft: storage directory is not a directory") } - tmpfile, err := ioutil.TempFile(cfg.Store, "_test_") + tmpfile, err := os.CreateTemp(cfg.Store, "_test_") if err != nil { return fmt.Errorf("raft: storage directory is not writable") } @@ -964,7 +963,7 @@ func (n *raft) InstallSnapshot(data []byte) error { sn := fmt.Sprintf(snapFileT, snap.lastTerm, snap.lastIndex) sfile := filepath.Join(snapDir, sn) - if err := ioutil.WriteFile(sfile, n.encodeSnapshot(snap), 0640); err != nil { + if err := os.WriteFile(sfile, n.encodeSnapshot(snap), 0640); err != nil { n.Unlock() // We could set write err here, but if this is a temporary situation, too many open files etc. // we want to retry and snapshots are not fatal. @@ -982,7 +981,7 @@ func (n *raft) InstallSnapshot(data []byte) error { n.Unlock() - psnaps, _ := ioutil.ReadDir(snapDir) + psnaps, _ := os.ReadDir(snapDir) // Remove any old snapshots. for _, fi := range psnaps { pn := fi.Name() @@ -1018,7 +1017,7 @@ func termAndIndexFromSnapFile(sn string) (term, index uint64, err error) { func (n *raft) setupLastSnapshot() { snapDir := filepath.Join(n.sd, snapshotsDir) - psnaps, err := ioutil.ReadDir(snapDir) + psnaps, err := os.ReadDir(snapDir) if err != nil { return } @@ -1085,7 +1084,7 @@ func (n *raft) loadLastSnapshot() (*snapshot, error) { if n.snapfile == _EMPTY_ { return nil, errNoSnapAvailable } - buf, err := ioutil.ReadFile(n.snapfile) + buf, err := os.ReadFile(n.snapfile) if err != nil { n.warn("Error reading snapshot: %v", err) os.Remove(n.snapfile) @@ -3234,14 +3233,14 @@ func writePeerState(sd string, ps *peerState) error { if _, err := os.Stat(psf); err != nil && !os.IsNotExist(err) { return err } - if err := ioutil.WriteFile(psf, encodePeerState(ps), 0640); err != nil { + if err := os.WriteFile(psf, encodePeerState(ps), 0640); err != nil { return err } return nil } func readPeerState(sd string) (ps *peerState, err error) { - buf, err := ioutil.ReadFile(filepath.Join(sd, peerStateFile)) + buf, err := os.ReadFile(filepath.Join(sd, peerStateFile)) if err != nil { return nil, err } @@ -3254,7 +3253,7 @@ const termVoteLen = idLen + 8 // readTermVote will read the largest term and who we voted from to stable storage. // Lock should be held. func (n *raft) readTermVote() (term uint64, voted string, err error) { - buf, err := ioutil.ReadFile(filepath.Join(n.sd, termVoteFile)) + buf, err := os.ReadFile(filepath.Join(n.sd, termVoteFile)) if err != nil { return 0, noVote, err } @@ -3317,7 +3316,7 @@ func (n *raft) fileWriter() { copy(buf[0:], n.wtv) n.RUnlock() <-dios - err := ioutil.WriteFile(tvf, buf[:], 0640) + err := os.WriteFile(tvf, buf[:], 0640) dios <- struct{}{} if err != nil { n.setWriteErr(err) @@ -3328,7 +3327,7 @@ func (n *raft) fileWriter() { buf := copyBytes(n.wps) n.RUnlock() <-dios - err := ioutil.WriteFile(psf, buf, 0640) + err := os.WriteFile(psf, buf, 0640) dios <- struct{}{} if err != nil { n.setWriteErr(err) diff --git a/server/reload_test.go b/server/reload_test.go index 7be0b6d2..bd9da248 100644 --- a/server/reload_test.go +++ b/server/reload_test.go @@ -20,7 +20,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "log" "net" "net/http" @@ -41,7 +40,7 @@ import ( func newServerWithConfig(t *testing.T, configFile string) (*Server, *Options, string) { t.Helper() - content, err := ioutil.ReadFile(configFile) + content, err := os.ReadFile(configFile) if err != nil { t.Fatalf("Error loading file: %v", err) } @@ -70,7 +69,7 @@ func createConfFile(t *testing.T, content []byte) string { conf := createFile(t, "") fName := conf.Name() conf.Close() - if err := ioutil.WriteFile(fName, content, 0666); err != nil { + if err := os.WriteFile(fName, content, 0666); err != nil { removeFile(t, fName) t.Fatalf("Error writing conf file: %v", err) } @@ -79,7 +78,7 @@ func createConfFile(t *testing.T, content []byte) string { func runReloadServerWithConfig(t *testing.T, configFile string) (*Server, *Options, string) { t.Helper() - content, err := ioutil.ReadFile(configFile) + content, err := os.ReadFile(configFile) if err != nil { t.Fatalf("Error loading file: %v", err) } @@ -97,7 +96,7 @@ func runReloadServerWithContent(t *testing.T, content []byte) (*Server, *Options func changeCurrentConfigContent(t *testing.T, curConfig, newConfig string) { t.Helper() - content, err := ioutil.ReadFile(newConfig) + content, err := os.ReadFile(newConfig) if err != nil { t.Fatalf("Error loading file: %v", err) } @@ -106,7 +105,7 @@ func changeCurrentConfigContent(t *testing.T, curConfig, newConfig string) { func changeCurrentConfigContentWithNewContent(t *testing.T, curConfig string, content []byte) { t.Helper() - if err := ioutil.WriteFile(curConfig, content, 0666); err != nil { + if err := os.WriteFile(curConfig, content, 0666); err != nil { t.Fatalf("Error writing config: %v", err) } } @@ -266,7 +265,7 @@ func TestConfigReload(t *testing.T) { } platformConf := filepath.Join(dir, "platform.conf") defer removeFile(t, platformConf) - if err := ioutil.WriteFile(platformConf, content, 0666); err != nil { + if err := os.WriteFile(platformConf, content, 0666); err != nil { t.Fatalf("Unable to write config file: %v", err) } @@ -1627,7 +1626,7 @@ func TestConfigReloadClusterRemoveSolicitedRoutes(t *testing.T) { func reloadUpdateConfig(t *testing.T, s *Server, conf, content string) { t.Helper() - if err := ioutil.WriteFile(conf, []byte(content), 0666); err != nil { + if err := os.WriteFile(conf, []byte(content), 0666); err != nil { t.Fatalf("Error creating config file: %v", err) } if err := s.Reload(); err != nil { @@ -1787,7 +1786,7 @@ func TestConfigReloadMaxSubsUnsupported(t *testing.T) { defer removeFile(t, conf) defer s.Shutdown() - if err := ioutil.WriteFile(conf, []byte(`max_subs: 10`), 0666); err != nil { + if err := os.WriteFile(conf, []byte(`max_subs: 10`), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } if err := s.Reload(); err == nil { @@ -4138,7 +4137,7 @@ func TestLoggingReload(t *testing.T) { check := func(filename string, valid func([]byte) bool) { t.Helper() - log, err := ioutil.ReadFile(filename) + log, err := os.ReadFile(filename) if err != nil { t.Fatalf("Error reading log file %s: %v\n", filename, err) } diff --git a/server/server.go b/server/server.go index 3ac0b660..83525ac0 100644 --- a/server/server.go +++ b/server/server.go @@ -22,7 +22,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "log" "math/rand" "net" @@ -1098,7 +1097,7 @@ func (s *Server) isRunning() bool { func (s *Server) logPid() error { pidStr := strconv.Itoa(os.Getpid()) - return ioutil.WriteFile(s.getOpts().PidFile, []byte(pidStr), 0660) + return os.WriteFile(s.getOpts().PidFile, []byte(pidStr), 0660) } // numReservedAccounts will return the number of reserved accounts configured in the server. @@ -3327,7 +3326,7 @@ func (s *Server) logPorts() { s.Errorf("Error marshaling ports file: %v", err) return } - if err := ioutil.WriteFile(portsFile, data, 0666); err != nil { + if err := os.WriteFile(portsFile, data, 0666); err != nil { s.Errorf("Error writing ports file (%s): %v", portsFile, err) return } diff --git a/server/server_test.go b/server/server_test.go index 22900e64..5021e868 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -22,7 +22,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "net" "net/url" "os" @@ -1625,7 +1624,7 @@ func TestConnectErrorReports(t *testing.T) { checkContent := func(t *testing.T, txt string, attempt int, shouldBeThere bool) { t.Helper() checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { - content, err := ioutil.ReadFile(log) + content, err := os.ReadFile(log) if err != nil { return fmt.Errorf("Error reading log file: %v", err) } @@ -1673,7 +1672,7 @@ func TestConnectErrorReports(t *testing.T) { checkLeafContent := func(t *testing.T, txt, host string, attempt int, shouldBeThere bool) { t.Helper() checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { - content, err := ioutil.ReadFile(log) + content, err := os.ReadFile(log) if err != nil { return fmt.Errorf("Error reading log file: %v", err) } @@ -1789,7 +1788,7 @@ func TestReconnectErrorReports(t *testing.T) { checkContent := func(t *testing.T, txt string, attempt int, shouldBeThere bool) { t.Helper() checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { - content, err := ioutil.ReadFile(log) + content, err := os.ReadFile(log) if err != nil { return fmt.Errorf("Error reading log file: %v", err) } @@ -1852,7 +1851,7 @@ func TestReconnectErrorReports(t *testing.T) { checkLeafContent := func(t *testing.T, txt, host string, attempt int, shouldBeThere bool) { t.Helper() checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { - content, err := ioutil.ReadFile(log) + content, err := os.ReadFile(log) if err != nil { return fmt.Errorf("Error reading log file: %v", err) } @@ -1960,7 +1959,7 @@ func TestServerLogsConfigurationFile(t *testing.T) { s := RunServer(o) s.Shutdown() - log, err := ioutil.ReadFile(file.Name()) + log, err := os.ReadFile(file.Name()) if err != nil { t.Fatalf("Error reading log file: %v", err) } diff --git a/server/signal_test.go b/server/signal_test.go index 1f359755..bc3ba113 100644 --- a/server/signal_test.go +++ b/server/signal_test.go @@ -19,7 +19,6 @@ package server import ( "errors" "fmt" - "io/ioutil" "os" "os/exec" "strings" @@ -52,7 +51,7 @@ func TestSignalToReOpenLogFile(t *testing.T) { // Add a trace expectedStr := "This is a Notice" s.Noticef(expectedStr) - buf, err := ioutil.ReadFile(logFile) + buf, err := os.ReadFile(logFile) if err != nil { t.Fatalf("Error reading file: %v", err) } @@ -67,7 +66,7 @@ func TestSignalToReOpenLogFile(t *testing.T) { syscall.Kill(syscall.Getpid(), syscall.SIGUSR1) // Wait a bit for action to be performed time.Sleep(500 * time.Millisecond) - buf, err = ioutil.ReadFile(logFile) + buf, err = os.ReadFile(logFile) if err != nil { t.Fatalf("Error reading file: %v", err) } diff --git a/server/stream.go b/server/stream.go index 6f4f43b7..c3f93cf6 100644 --- a/server/stream.go +++ b/server/stream.go @@ -20,7 +20,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "math/rand" "os" @@ -4541,7 +4540,7 @@ func (a *Account) RestoreStream(ncfg *StreamConfig, r io.Reader) (*stream, error return nil, fmt.Errorf("could not create snapshots directory - %v", err) } } - sdir, err := ioutil.TempDir(sd, "snap-") + sdir, err := os.MkdirTemp(sd, "snap-") if err != nil { return nil, err } @@ -4594,7 +4593,7 @@ func (a *Account) RestoreStream(ncfg *StreamConfig, r io.Reader) (*stream, error // Check metadata. // The cfg passed in will be the new identity for the stream. var fcfg FileStreamInfo - b, err := ioutil.ReadFile(filepath.Join(sdir, JetStreamMetaFile)) + b, err := os.ReadFile(filepath.Join(sdir, JetStreamMetaFile)) if err != nil { return nil, err } @@ -4649,7 +4648,7 @@ func (a *Account) RestoreStream(ncfg *StreamConfig, r io.Reader) (*stream, error // Now do consumers. odir := filepath.Join(ndir, consumerDir) - ofis, _ := ioutil.ReadDir(odir) + ofis, _ := os.ReadDir(odir) for _, ofi := range ofis { metafile := filepath.Join(odir, ofi.Name(), JetStreamMetaFile) metasum := filepath.Join(odir, ofi.Name(), JetStreamMetaFileSum) @@ -4657,7 +4656,7 @@ func (a *Account) RestoreStream(ncfg *StreamConfig, r io.Reader) (*stream, error mset.stop(true, false) return nil, fmt.Errorf("error restoring consumer [%q]: %v", ofi.Name(), err) } - buf, err := ioutil.ReadFile(metafile) + buf, err := os.ReadFile(metafile) if err != nil { mset.stop(true, false) return nil, fmt.Errorf("error restoring consumer [%q]: %v", ofi.Name(), err) diff --git a/server/websocket.go b/server/websocket.go index 12400969..a884b49b 100644 --- a/server/websocket.go +++ b/server/websocket.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" mrand "math/rand" "net" @@ -406,7 +405,7 @@ func (r *wsReadInfo) decompress() ([]byte, error) { d.(flate.Resetter).Reset(r, nil) } // This will do the decompression. - b, err := ioutil.ReadAll(d) + b, err := io.ReadAll(d) decompressorPool.Put(d) // Now reset the compressed buffers list. r.cbufs = nil @@ -858,7 +857,7 @@ func wsPMCExtensionSupport(header http.Header, checkPMCOnly bool) (bool, bool) { return false, false } -// Send an HTTP error with the given `status`` to the given http response writer `w`. +// Send an HTTP error with the given `status` to the given http response writer `w`. // Return an error created based on the `reason` string. func wsReturnHTTPError(w http.ResponseWriter, r *http.Request, status int, reason string) error { err := fmt.Errorf("%s - websocket handshake error: %s", r.RemoteAddr, reason) diff --git a/server/websocket_test.go b/server/websocket_test.go index f3ea54e0..cffbf22a 100644 --- a/server/websocket_test.go +++ b/server/websocket_test.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math/rand" "net" "net/http" @@ -2014,7 +2013,7 @@ func testWSReadFrame(t testing.TB, br *bufio.Reader) []byte { buf = append(buf, 0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff) dbr := bytes.NewBuffer(buf) d := flate.NewReader(dbr) - uncompressed, err := ioutil.ReadAll(d) + uncompressed, err := io.ReadAll(d) if err != nil { t.Fatalf("Error reading frame: %v", err) } @@ -3127,7 +3126,7 @@ func TestWSCompressionFrameSizeLimit(t *testing.T) { buf = append(buf, 0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff) dbr := bytes.NewBuffer(buf) d := flate.NewReader(dbr) - uncompressed, err := ioutil.ReadAll(d) + uncompressed, err := io.ReadAll(d) if err != nil { t.Fatalf("Error reading frame: %v", err) } diff --git a/test/client_auth_test.go b/test/client_auth_test.go index 80db5d7b..a5185a99 100644 --- a/test/client_auth_test.go +++ b/test/client_auth_test.go @@ -15,7 +15,7 @@ package test import ( "fmt" - "io/ioutil" + "os" "testing" "github.com/nats-io/nats.go" @@ -73,7 +73,7 @@ func TestTokenInConfig(t *testing.T) { token: ` + testToken + ` timeout: 5 }` - if err := ioutil.WriteFile(confFileName, []byte(content), 0666); err != nil { + if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { t.Fatalf("Error writing config file: %v", err) } s, opts := RunServerWithConfig(confFileName) diff --git a/test/cluster_tls_test.go b/test/cluster_tls_test.go index b19c46ee..b5ab06a1 100644 --- a/test/cluster_tls_test.go +++ b/test/cluster_tls_test.go @@ -15,7 +15,7 @@ package test import ( "fmt" - "io/ioutil" + "os" "strings" "testing" "time" @@ -151,7 +151,7 @@ func TestClusterTLSInsecure(t *testing.T) { srvB.SetLogger(wl, false, false) // Need to add "insecure: true" and reload - if err := ioutil.WriteFile(confB, + if err := os.WriteFile(confB, []byte(fmt.Sprintf(bConfigTemplate, "insecure: true", optsA.Cluster.Host, optsA.Cluster.Port)), 0666); err != nil { t.Fatalf("Error rewriting file: %v", err) diff --git a/test/leafnode_test.go b/test/leafnode_test.go index b0b1c8b5..688007c9 100644 --- a/test/leafnode_test.go +++ b/test/leafnode_test.go @@ -19,7 +19,6 @@ import ( "crypto/x509" "encoding/json" "fmt" - "io/ioutil" "math/rand" "net" "net/url" @@ -3594,7 +3593,7 @@ func TestClusterTLSMixedIPAndDNS(t *testing.T) { remote := &server.RemoteLeafOpts{URLs: []*url.URL{rurl}} remote.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} pool := x509.NewCertPool() - rootPEM, err := ioutil.ReadFile("./configs/certs/ca.pem") + rootPEM, err := os.ReadFile("./configs/certs/ca.pem") if err != nil || rootPEM == nil { t.Fatalf("Error loading or parsing rootCA file: %v", err) } diff --git a/test/monitor_test.go b/test/monitor_test.go index d103b68c..91d2f4f0 100644 --- a/test/monitor_test.go +++ b/test/monitor_test.go @@ -18,9 +18,10 @@ import ( "crypto/x509" "encoding/json" "fmt" - "io/ioutil" + "io" "net" "net/http" + "os" "strings" "sync" "sync/atomic" @@ -178,7 +179,7 @@ func TestVarz(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } @@ -204,7 +205,7 @@ func TestVarz(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err = ioutil.ReadAll(resp.Body) + body, err = io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } @@ -256,7 +257,7 @@ func TestConnz(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } @@ -288,7 +289,7 @@ func TestConnz(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err = ioutil.ReadAll(resp.Body) + body, err = io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } @@ -370,7 +371,7 @@ func TestTLSConnz(t *testing.T) { url := fmt.Sprintf("https://127.0.0.1:%d/", opts.HTTPSPort) tlsConfig := &tls.Config{} - caCert, err := ioutil.ReadFile(rootCAFile) + caCert, err := os.ReadFile(rootCAFile) if err != nil { t.Fatalf("Got error reading RootCA file: %s", err) } @@ -394,7 +395,7 @@ func TestTLSConnz(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) @@ -477,7 +478,7 @@ func TestConnzWithSubs(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } @@ -523,7 +524,7 @@ func TestConnzWithAuth(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } @@ -584,7 +585,7 @@ func TestConnzWithAccounts(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } @@ -702,7 +703,7 @@ func TestConnzWithOffsetAndLimit(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } @@ -741,7 +742,7 @@ func TestSubsz(t *testing.T) { t.Fatalf("Expected a 200 response, got %d\n", resp.StatusCode) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("Got an error reading the body: %v\n", err) } diff --git a/test/norace_test.go b/test/norace_test.go index b26dc266..07b17fec 100644 --- a/test/norace_test.go +++ b/test/norace_test.go @@ -20,10 +20,10 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "math/rand" "net" "net/url" + "os" "regexp" "runtime" "strconv" @@ -103,7 +103,7 @@ func TestNoRaceRouteSendSubs(t *testing.T) { "nats://%s:%d" ] `, optsA.Cluster.Host, optsA.Cluster.Port) - if err := ioutil.WriteFile(cfb, []byte(fmt.Sprintf(template, routes)), 0600); err != nil { + if err := os.WriteFile(cfb, []byte(fmt.Sprintf(template, routes)), 0600); err != nil { t.Fatalf("Error rewriting B's config file: %v", err) } if err := srvB.Reload(); err != nil { @@ -220,7 +220,7 @@ func TestNoRaceRouteSendSubs(t *testing.T) { // Otherwise, on test shutdown the client close // will cause the server to try to send unsubs and // this can delay the test. - if err := ioutil.WriteFile(cfb, []byte(fmt.Sprintf(template, "")), 0600); err != nil { + if err := os.WriteFile(cfb, []byte(fmt.Sprintf(template, "")), 0600); err != nil { t.Fatalf("Error rewriting B's config file: %v", err) } if err := srvB.Reload(); err != nil { diff --git a/test/ocsp_test.go b/test/ocsp_test.go index 694dd305..cb77733c 100644 --- a/test/ocsp_test.go +++ b/test/ocsp_test.go @@ -22,7 +22,7 @@ import ( "encoding/base64" "encoding/pem" "fmt" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -641,7 +641,7 @@ func TestOCSPReloadRotateTLSCertWithNoURL(t *testing.T) { timeout: 5 } ` - if err := ioutil.WriteFile(conf, []byte(content), 0666); err != nil { + if err := os.WriteFile(conf, []byte(content), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } // Reload show warning because of cert missing OCSP Url so cannot be used @@ -753,7 +753,7 @@ func TestOCSPReloadRotateTLSCertDisableMustStaple(t *testing.T) { } found := false for _, file := range files { - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { t.Error(err) } @@ -779,7 +779,7 @@ func TestOCSPReloadRotateTLSCertDisableMustStaple(t *testing.T) { } ` content = fmt.Sprintf(updatedContent, storeDir) - if err := ioutil.WriteFile(conf, []byte(content), 0666); err != nil { + if err := os.WriteFile(conf, []byte(content), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } if err := s.Reload(); err != nil { @@ -808,7 +808,7 @@ func TestOCSPReloadRotateTLSCertDisableMustStaple(t *testing.T) { // Re-enable OCSP Stapling content = fmt.Sprintf(originalContent, storeDir) - if err := ioutil.WriteFile(conf, []byte(content), 0666); err != nil { + if err := os.WriteFile(conf, []byte(content), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } if err := s.Reload(); err != nil { @@ -852,7 +852,7 @@ func TestOCSPReloadRotateTLSCertDisableMustStaple(t *testing.T) { } found = false for _, file := range files { - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { t.Error(err) } @@ -938,7 +938,7 @@ func TestOCSPReloadRotateTLSCertEnableMustStaple(t *testing.T) { timeout: 5 } ` - if err := ioutil.WriteFile(conf, []byte(content), 0666); err != nil { + if err := os.WriteFile(conf, []byte(content), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } if err := s.Reload(); err != nil { @@ -1223,7 +1223,7 @@ func TestOCSPCluster(t *testing.T) { } ` srvConfA = fmt.Sprintf(srvConfA, storeDirA) - if err := ioutil.WriteFile(sconfA, []byte(srvConfA), 0666); err != nil { + if err := os.WriteFile(sconfA, []byte(srvConfA), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } if err := srvA.Reload(); err != nil { @@ -1483,7 +1483,7 @@ func TestOCSPLeaf(t *testing.T) { } ` srvConfA = fmt.Sprintf(srvConfA, storeDirA) - if err := ioutil.WriteFile(sconfA, []byte(srvConfA), 0666); err != nil { + if err := os.WriteFile(sconfA, []byte(srvConfA), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } if err := srvA.Reload(); err != nil { @@ -1775,7 +1775,7 @@ func TestOCSPGateway(t *testing.T) { ` srvConfA = fmt.Sprintf(srvConfA, storeDirA) - if err := ioutil.WriteFile(sconfA, []byte(srvConfA), 0666); err != nil { + if err := os.WriteFile(sconfA, []byte(srvConfA), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } if err := srvA.Reload(); err != nil { @@ -2240,7 +2240,7 @@ func TestOCSPCustomConfigReloadDisable(t *testing.T) { timeout: 5 } ` - if err := ioutil.WriteFile(conf, []byte(content), 0666); err != nil { + if err := os.WriteFile(conf, []byte(content), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } if err := s.Reload(); err != nil { @@ -2342,7 +2342,7 @@ func TestOCSPCustomConfigReloadEnable(t *testing.T) { timeout: 5 } ` - if err := ioutil.WriteFile(conf, []byte(content), 0666); err != nil { + if err := os.WriteFile(conf, []byte(content), 0666); err != nil { t.Fatalf("Error writing config: %v", err) } if err := s.Reload(); err != nil { @@ -2400,7 +2400,7 @@ func newOCSPResponderDesignated(t *testing.T, issuerCertPEM, respCertPEM, respKe fmt.Fprintf(rw, "%s %d", key, n) case "POST": - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { http.Error(rw, err.Error(), http.StatusBadRequest) return @@ -2496,7 +2496,7 @@ func setOCSPStatus(t *testing.T, ocspURL, certPEM string, status int) { } defer resp.Body.Close() - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("failed to read OCSP HTTP response body: %s", err) } @@ -2531,7 +2531,7 @@ func parseKeyPEM(t *testing.T, keyPEM string) *rsa.PrivateKey { func parsePEM(t *testing.T, pemPath string) *pem.Block { t.Helper() - data, err := ioutil.ReadFile(pemPath) + data, err := os.ReadFile(pemPath) if err != nil { t.Fatal(err) } diff --git a/test/operator_test.go b/test/operator_test.go index c094e41e..200ec245 100644 --- a/test/operator_test.go +++ b/test/operator_test.go @@ -16,7 +16,7 @@ package test import ( "bytes" "fmt" - "io/ioutil" + "os" "strings" "testing" "time" @@ -416,12 +416,12 @@ func TestReloadDoesNotWipeAccountsWithOperatorMode(t *testing.T) { s2.Shutdown() // Now change config and do reload which will do an auth change. - b, err := ioutil.ReadFile(conf) + b, err := os.ReadFile(conf) if err != nil { t.Fatal(err) } newConf := bytes.Replace(b, []byte("2.2"), []byte("3.3"), 1) - err = ioutil.WriteFile(conf, newConf, 0644) + err = os.WriteFile(conf, newConf, 0644) if err != nil { t.Fatal(err) } @@ -505,7 +505,7 @@ func TestReloadDoesUpdateAccountsWithMemoryResolver(t *testing.T) { accJWT2, accKP2 := createAccountForConfig(t) accPub2, _ := accKP2.PublicKey() contents = strings.Replace(fmt.Sprintf(cf, "", sysPub, sysPub, sysJWT, accPub2, accJWT2), "\n\t", "\n", -1) - err = ioutil.WriteFile(conf, []byte(contents), 0644) + err = os.WriteFile(conf, []byte(contents), 0644) if err != nil { t.Fatal(err) } @@ -580,7 +580,7 @@ func TestReloadFailsWithBadAccountsWithMemoryResolver(t *testing.T) { // Now add in bogus account for second item and make sure reload fails. contents = strings.Replace(fmt.Sprintf(cf, "", sysPub, sysPub, sysJWT, "foo", "bar"), "\n\t", "\n", -1) - err = ioutil.WriteFile(conf, []byte(contents), 0644) + err = os.WriteFile(conf, []byte(contents), 0644) if err != nil { t.Fatal(err) } @@ -594,7 +594,7 @@ func TestReloadFailsWithBadAccountsWithMemoryResolver(t *testing.T) { accPub, _ := accKP.PublicKey() contents = strings.Replace(fmt.Sprintf(cf, "", sysPub, sysPub, sysJWT, accPub, accJWT), "\n\t", "\n", -1) - err = ioutil.WriteFile(conf, []byte(contents), 0644) + err = os.WriteFile(conf, []byte(contents), 0644) if err != nil { t.Fatal(err) } diff --git a/test/pid_test.go b/test/pid_test.go index 62f4aa7b..dd714cb3 100644 --- a/test/pid_test.go +++ b/test/pid_test.go @@ -15,7 +15,6 @@ package test import ( "fmt" - "io/ioutil" "os" "testing" ) @@ -33,7 +32,7 @@ func TestPidFile(t *testing.T) { s := RunServer(&opts) s.Shutdown() - buf, err := ioutil.ReadFile(opts.PidFile) + buf, err := os.ReadFile(opts.PidFile) if err != nil { t.Fatalf("Could not read pid_file: %v", err) } diff --git a/test/ports_test.go b/test/ports_test.go index 55c27339..f58b159f 100644 --- a/test/ports_test.go +++ b/test/ports_test.go @@ -17,7 +17,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -35,7 +34,7 @@ func waitForFile(path string, dur time.Duration) ([]byte, error) { time.Sleep(25 * time.Millisecond) continue } else { - return ioutil.ReadFile(path) + return os.ReadFile(path) } } return nil, errors.New("Timeout") @@ -138,7 +137,7 @@ func TestPortsFileReload(t *testing.T) { `, dirA) config = strings.Replace(config, "\\", "/", -1) confPath := filepath.Join(tempDir, fmt.Sprintf("%d.conf", os.Getpid())) - if err := ioutil.WriteFile(confPath, []byte(config), 0666); err != nil { + if err := os.WriteFile(confPath, []byte(config), 0666); err != nil { t.Fatalf("Error writing ports file (%s): %v", confPath, err) } @@ -179,7 +178,7 @@ func TestPortsFileReload(t *testing.T) { port: -1 `, dirB) config = strings.Replace(config, "\\", "/", -1) - if err := ioutil.WriteFile(confPath, []byte(config), 0666); err != nil { + if err := os.WriteFile(confPath, []byte(config), 0666); err != nil { t.Fatalf("Error writing ports file (%s): %v", confPath, err) } diff --git a/test/route_discovery_test.go b/test/route_discovery_test.go index dde99d81..d51d3c23 100644 --- a/test/route_discovery_test.go +++ b/test/route_discovery_test.go @@ -17,7 +17,7 @@ import ( "bufio" "encoding/json" "fmt" - "io/ioutil" + "io" "net" "net/http" "runtime" @@ -528,7 +528,7 @@ func readHTTPRoutez(t *testing.T, url string) *server.Routez { if resp.StatusCode != 200 { stackFatalf(t, "Expected a 200 response, got %d\n", resp.StatusCode) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { stackFatalf(t, "Got an error reading the body: %v\n", err) } diff --git a/test/routes_test.go b/test/routes_test.go index 982ba398..856329f9 100644 --- a/test/routes_test.go +++ b/test/routes_test.go @@ -16,8 +16,9 @@ package test import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net" + "os" "runtime" "strconv" "sync" @@ -450,11 +451,11 @@ func TestMultipleRoutesSameId(t *testing.T) { // We should only receive on one route, not both. // Check both manually. route1.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) - buf, _ := ioutil.ReadAll(route1) + buf, _ := io.ReadAll(route1) route1.SetReadDeadline(time.Time{}) if len(buf) <= 0 { route2.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) - buf, _ = ioutil.ReadAll(route2) + buf, _ = io.ReadAll(route2) route2.SetReadDeadline(time.Time{}) if len(buf) <= 0 { t.Fatal("Expected to get one message on a route, received none.") @@ -1103,7 +1104,7 @@ func createConfFile(t *testing.T, content []byte) string { conf := createFile(t, "") fName := conf.Name() conf.Close() - if err := ioutil.WriteFile(fName, content, 0666); err != nil { + if err := os.WriteFile(fName, content, 0666); err != nil { removeFile(t, fName) t.Fatalf("Error writing conf file: %v", err) } diff --git a/test/service_latency_test.go b/test/service_latency_test.go index c2dbc6d3..6da77acd 100644 --- a/test/service_latency_test.go +++ b/test/service_latency_test.go @@ -16,9 +16,9 @@ package test import ( "encoding/json" "fmt" - "io/ioutil" "math/rand" "net/http" + "os" "path/filepath" "strings" "sync" @@ -1492,7 +1492,7 @@ func TestServiceLatencyRequestorSharesConfig(t *testing.T) { system_account: SYS `) - if err := ioutil.WriteFile(conf, newConf, 0600); err != nil { + if err := os.WriteFile(conf, newConf, 0600); err != nil { t.Fatalf("Error rewriting server's config file: %v", err) } if err := srv.Reload(); err != nil { diff --git a/test/test.go b/test/test.go index 1534cf32..b54f988d 100644 --- a/test/test.go +++ b/test/test.go @@ -19,7 +19,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "os" "path/filepath" @@ -644,7 +643,7 @@ func createDir(t *testing.T, prefix string) string { if err := os.MkdirAll(tempRoot, 0700); err != nil { t.Fatal(err) } - dir, err := ioutil.TempDir(tempRoot, prefix) + dir, err := os.MkdirTemp(tempRoot, prefix) if err != nil { t.Fatal(err) } @@ -661,7 +660,7 @@ func createFile(t *testing.T, prefix string) *os.File { func createFileAtDir(t *testing.T, dir, prefix string) *os.File { t.Helper() - f, err := ioutil.TempFile(dir, prefix) + f, err := os.CreateTemp(dir, prefix) if err != nil { t.Fatal(err) } diff --git a/test/tls_test.go b/test/tls_test.go index ac17e722..0e6ec3ac 100644 --- a/test/tls_test.go +++ b/test/tls_test.go @@ -19,9 +19,9 @@ import ( "crypto/x509" "errors" "fmt" - "io/ioutil" "net" "net/url" + "os" "strings" "sync" "testing" @@ -91,7 +91,7 @@ func TestTLSClientCertificate(t *testing.T) { } // Load in root CA for server verification - rootPEM, err := ioutil.ReadFile("./configs/certs/ca.pem") + rootPEM, err := os.ReadFile("./configs/certs/ca.pem") if err != nil || rootPEM == nil { t.Fatalf("failed to read root certificate") } @@ -1840,7 +1840,7 @@ func TestTLSPinnedCertsClient(t *testing.T) { t.Fatalf("Expected error trying to connect without a certificate in pinned_certs") } - ioutil.WriteFile(confFileName, []byte(fmt.Sprintf(tmpl, "bf6f821f09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")), 0660) + os.WriteFile(confFileName, []byte(fmt.Sprintf(tmpl, "bf6f821f09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")), 0660) if err := srv.Reload(); err != nil { t.Fatalf("on Reload got %v", err) } @@ -1963,7 +1963,7 @@ func TestTLSPinnedCertsRoute(t *testing.T) { checkClusterFormed(t, srvSeed, srv) // this change will result in the server being and remaining disconnected - ioutil.WriteFile(confSrv, []byte(fmt.Sprintf(tmplSrv, o.Cluster.Port, "aaaaaaaa09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")), 0660) + os.WriteFile(confSrv, []byte(fmt.Sprintf(tmplSrv, o.Cluster.Port, "aaaaaaaa09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")), 0660) if err := srv.Reload(); err != nil { t.Fatalf("on Reload got %v", err) }