Skip to content

Commit 870b4c5

Browse files
committed
BUG/MINOR: prevent panic and avoid unnecessary file operations
The `WriteOnDiskIfChanged` method eagerly created files and deferred `f.Close()` before confirming if there were changes to write. If the file already existed, `f` remained `nil`, leading to a panic when the function returned without changes. It also redundantly recreated the file later in the flow. This commit moves directory and file creation after the `hasDiff` check, ensuring file operations only occur when necessary. It also correctly scopes `defer f.Close()` immediately after the actual file creation to prevent nil pointer panics and optimize performance.
1 parent 900b5bc commit 870b4c5

1 file changed

Lines changed: 13 additions & 9 deletions

File tree

k8s/gate/haproxy/storage/maps/mapsmanager.go

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -446,22 +446,25 @@ func (m *MapFileState) ApplyDesiredBackends(
446446
// It iterates over the entries in the map file state and checks if there are any differences between the desired state and the current state.
447447
// If there are differences, it writes the desired state to disk in the format "key value\n"
448448
func (m *MapFileState) WriteOnDiskIfChanged() error {
449-
var f *os.File
450-
var err error
451449
dir := filepath.Dir(m.Path.FullPath())
452-
if _, err = os.Stat(dir); os.IsNotExist(err) {
453-
err = os.MkdirAll(dir, 0o755)
454-
if err != nil {
450+
if _, err := os.Stat(dir); os.IsNotExist(err) {
451+
if err := os.MkdirAll(dir, 0o755); err != nil {
455452
return err
456453
}
457454
}
458-
if _, err = os.Stat(m.Path.FullPath()); os.IsNotExist(err) {
459-
f, err = os.Create(m.Path.FullPath())
455+
456+
// The map file must exist on disk even when empty, because the HAProxy
457+
// configuration references it at load time. Create an empty placeholder
458+
// on first sync if it is missing.
459+
if _, err := os.Stat(m.Path.FullPath()); os.IsNotExist(err) {
460+
placeholder, err := os.Create(m.Path.FullPath())
460461
if err != nil {
461462
return err
462463
}
464+
if err := placeholder.Close(); err != nil {
465+
return err
466+
}
463467
}
464-
defer f.Close()
465468

466469
var hasDiff bool
467470
for _, entryValue := range m.Entries {
@@ -482,10 +485,11 @@ func (m *MapFileState) WriteOnDiskIfChanged() error {
482485
logging.LogAttrMapFileContent(m.PrettyString()),
483486
)
484487

485-
f, err = os.Create(m.Path.FullPath())
488+
f, err := os.Create(m.Path.FullPath())
486489
if err != nil {
487490
return err
488491
}
492+
defer f.Close()
489493

490494
orderedEntries := []EntryKey{}
491495
for entryKey := range m.Entries {

0 commit comments

Comments
 (0)