Skip to content

Commit

Permalink
libnetwork: use atomic write for the backend file
Browse files Browse the repository at this point in the history
It is possible that two processes write at the same time and this could
lead to an invalid value in the file.

I think this fixes a race condition which was observed in the buildah
integration tests.

Signed-off-by: Paul Holzinger <[email protected]>
  • Loading branch information
Luap99 committed Jan 7, 2022
1 parent e6f53e6 commit e3dee00
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions libnetwork/network/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/config"
"github.com/containers/storage"
"github.com/containers/storage/pkg/ioutils"
"github.com/sirupsen/logrus"
)

Expand Down Expand Up @@ -64,13 +65,14 @@ func defaultNetworkBackend(store storage.Store, conf *config.Config) (backend ty
file := filepath.Join(store.GraphRoot(), defaultNetworkBackendFileName)
b, err := ioutil.ReadFile(file)
if err == nil {
if string(b) == string(types.Netavark) {
val := string(b)
if val == string(types.Netavark) {
return types.Netavark, nil
}
if string(b) == string(types.CNI) {
if val == string(types.CNI) {
return types.CNI, nil
}
return "", fmt.Errorf("unknown network backend value in %q", file)
return "", fmt.Errorf("unknown network backend value %q in %q", val, file)
}
// fail for all errors except ENOENT
if !errors.Is(err, os.ErrNotExist) {
Expand All @@ -81,7 +83,8 @@ func defaultNetworkBackend(store storage.Store, conf *config.Config) (backend ty
defer func() {
// only write when there is no error
if err == nil {
if err := ioutil.WriteFile(file, []byte(backend), 0644); err != nil {
// nolint:gocritic
if err := ioutils.AtomicWriteFile(file, []byte(backend), 0644); err != nil {
logrus.Errorf("could not write network backend to file: %v", err)
}
}
Expand Down

0 comments on commit e3dee00

Please sign in to comment.