Use safeio to write server metadata file (#20101)

* Use safeio to write server metadata file

* guard the conversion
This commit is contained in:
cskh 2024-01-05 14:46:19 -05:00 committed by GitHub
parent d2f6a25c28
commit 15b40f36f3
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)