Backport of Use safeio to write server metadata file into release/1.17.x (#20106)

* backport of commit 0956e061b6

* backport of commit ed9709a578

---------

Co-authored-by: cskh <hui.kang@hashicorp.com>
pull/20230/head
hc-github-team-consul-core 2024-01-05 14:16:14 -06:00 committed by GitHub
parent 5208cdde66
commit ab2666afb7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 1 deletions

View File

@ -31,6 +31,7 @@ import (
"github.com/hashicorp/hcp-scada-provider/capability"
"github.com/hashicorp/raft"
"github.com/hashicorp/serf/serf"
"github.com/rboyer/safeio"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"google.golang.org/grpc"
@ -4668,6 +4669,14 @@ func (a *Agent) persistServerMetadata() {
continue
}
// Use safeio.File to ensure the file is written to disk atomically
if sf, ok := f.(*safeio.File); ok {
if err := sf.Commit(); err != nil {
sf.Close()
a.logger.Error("failed to commit server metadata", "error", err)
continue
}
}
f.Close()
case <-a.shutdownCh:
return

View File

@ -8,6 +8,8 @@ import (
"io"
"os"
"time"
"github.com/rboyer/safeio"
)
// ServerMetadataFile is the name of the file on disk that server metadata
@ -31,7 +33,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, 0600)
return safeio.OpenFile(filename, 0600)
}
type ServerMetadataReadFunc func(filename string) (*ServerMetadata, error)