Skip to content

Commit

Permalink
migrations: Use atomic file operations for subgid and subuid files
Browse files Browse the repository at this point in the history
Signed-off-by: Evan Maddock <[email protected]>
  • Loading branch information
EbonJaeger committed May 29, 2024
1 parent 5bbd39f commit edf6acd
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions core/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,16 @@
package core

import (
"errors"
"fmt"
"github.com/BurntSushi/toml"
"github.com/DataDrake/waterlog"
"io/ioutil"
"os"
gouser "os/user"
"path/filepath"
"strconv"

"github.com/BurntSushi/toml"
"github.com/DataDrake/waterlog"
)

// Migration contains the information about a migration, including where it is on the system and its requested system modifications
Expand Down Expand Up @@ -170,27 +172,33 @@ func (m *Migration) addSubIds(context *Context, task *AddSubIds) {
m.createSubGidFile(context, task, users)
}

func createFileIfNotExists(path string) (created bool) {
if _, err := os.Stat(path); err == nil {
waterlog.Debugf("\t%s already exists, skipping", path)

return false
}
func createFileIfNotExists(path string) (bool, error) {
fh, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)

fh, err := os.Create(path)
if err != nil {
waterlog.Warnf("\tUnable to create %s due to error: %s\n", path, err)
if errors.Is(err, os.ErrExist) {
waterlog.Debugf("\t%s already exists, skipping", path)
// The file already existing isn't an error mode for us,
// so don't propagate the error.
return false, nil
}

return false
return false, err
}

fh.Close()

return true
return true, nil
}

func (m *Migration) createSubUidFile(context *Context, task *AddSubIds, users []User) {
if !createFileIfNotExists("/etc/subuid") {
created, err := createFileIfNotExists("/etc/subuid")

if !created {
if err != nil {
waterlog.Warnf("\tUnable to create /etc/subuid due to error: %s\n", err)
}

return
}

Expand All @@ -205,7 +213,13 @@ func (m *Migration) createSubUidFile(context *Context, task *AddSubIds, users []
}

func (m *Migration) createSubGidFile(context *Context, task *AddSubIds, users []User) {
if !createFileIfNotExists("/etc/subgid") {
created, err := createFileIfNotExists("/etc/subgid")

if !created {
if err != nil {
waterlog.Warnf("\tUnable to create /etc/subgid due to error: %s\n", err)
}

return
}

Expand Down

0 comments on commit edf6acd

Please sign in to comment.