2020-02-23 08:48:26 +00:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2024-05-31 06:45:34 +00:00
|
|
|
"os/user"
|
2023-08-01 17:01:54 +00:00
|
|
|
"path/filepath"
|
2024-05-31 06:45:34 +00:00
|
|
|
"strconv"
|
2022-09-01 17:20:32 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
2020-02-23 08:48:26 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func SetFileModeForPath(name string, mode os.FileMode) error {
|
|
|
|
return os.Chmod(name, mode)
|
|
|
|
}
|
|
|
|
|
2024-05-31 06:45:34 +00:00
|
|
|
func SetFileGroupForPath(name string, group string) error {
|
|
|
|
// Try to use as group id
|
|
|
|
gid, err := strconv.Atoi(group)
|
|
|
|
if err == nil {
|
|
|
|
return os.Chown(name, -1, gid)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, it must be a group name
|
|
|
|
g, err := user.LookupGroup(group)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
gid, err = strconv.Atoi(g.Gid)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return os.Chown(name, -1, gid)
|
|
|
|
}
|
|
|
|
|
2020-02-23 08:48:26 +00:00
|
|
|
func SetFileModeForFile(file *os.File, mode os.FileMode) error {
|
|
|
|
return file.Chmod(mode)
|
|
|
|
}
|
2022-09-01 17:20:32 +00:00
|
|
|
|
|
|
|
// ReadFile reads from a file
|
|
|
|
func ReadFile(path string) (string, error) {
|
|
|
|
if path == "" {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
for start := time.Now(); time.Since(start) < 4*time.Minute; {
|
|
|
|
vpnBytes, err := os.ReadFile(path)
|
|
|
|
if err == nil {
|
|
|
|
return strings.TrimSpace(string(vpnBytes)), nil
|
|
|
|
} else if os.IsNotExist(err) {
|
|
|
|
logrus.Infof("Waiting for %s to be available\n", path)
|
|
|
|
time.Sleep(2 * time.Second)
|
|
|
|
} else {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", errors.New("Timeout while trying to read the file")
|
|
|
|
}
|
2023-08-01 17:01:54 +00:00
|
|
|
|
|
|
|
// AtomicWrite firsts writes data to a temp file, then renames to the destination file.
|
|
|
|
// This ensures that the destination file is never partially written.
|
|
|
|
func AtomicWrite(fileName string, data []byte, perm os.FileMode) error {
|
|
|
|
f, err := os.CreateTemp(filepath.Dir(fileName), filepath.Base(fileName)+".tmp")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
tmpName := f.Name()
|
2023-08-02 22:17:41 +00:00
|
|
|
defer os.Remove(tmpName)
|
2023-08-01 17:01:54 +00:00
|
|
|
if _, err := f.Write(data); err != nil {
|
|
|
|
f.Close()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := f.Chmod(perm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := f.Sync(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := f.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return os.Rename(tmpName, fileName)
|
|
|
|
}
|