agent: prevent empty server_metadata.json (#19935)

This commit is contained in:
cskh 2023-12-19 10:01:56 -05:00 committed by GitHub
parent 4e451f2358
commit cff872749d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 1 deletions

View File

@ -31,7 +31,7 @@ func (md *ServerMetadata) IsLastSeenStale(d time.Duration) bool {
// OpenServerMetadata is a helper function for opening the server metadata file
// with the correct permissions.
func OpenServerMetadata(filename string) (io.WriteCloser, error) {
return os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
return os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0600)
}
type ServerMetadataReadFunc func(filename string) (*ServerMetadata, error)

View File

@ -6,6 +6,7 @@ package consul
import (
"bytes"
"errors"
"os"
"testing"
"time"
@ -66,3 +67,35 @@ func TestWriteServerMetadata(t *testing.T) {
assert.True(t, b.Len() > 0)
})
}
func TestWriteServerMetadata_MultipleTimes(t *testing.T) {
file, err := os.CreateTemp("", "server_metadata.json")
assert.NoError(t, err)
defer os.Remove(file.Name())
// prepare some data in server_metadata.json
_, err = OpenServerMetadata(file.Name())
assert.NoError(t, err)
err = WriteServerMetadata(file)
assert.NoError(t, err)
stat, err := file.Stat()
assert.NoError(t, err)
t.Run("reopen not truncate file", func(t *testing.T) {
_, err = OpenServerMetadata(file.Name())
assert.NoError(t, err)
// file size unchanged
stat2, err := file.Stat()
assert.NoError(t, err)
assert.Equal(t, stat.Size(), stat2.Size())
})
t.Run("write updates the file", func(t *testing.T) {
err = WriteServerMetadata(file)
assert.NoError(t, err)
stat2, err := file.Stat()
assert.NoError(t, err)
assert.Equal(t, stat2.ModTime(), stat2.ModTime())
})
}