Backport of agent: prevent empty server_metadata.json into release/1.15.x (#20018)

backport of commit 9fc0fc3dcc

Co-authored-by: cskh <hui.kang@hashicorp.com>
pull/20104/head
hc-github-team-consul-core 2024-01-05 13:42:14 -06:00 committed by GitHub
parent d88efe9128
commit f616d3b4c3
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())
})
}