2020-05-04 20:46:48 +00:00
|
|
|
// +build linux
|
|
|
|
|
|
|
|
package fscommon
|
|
|
|
|
|
|
|
import (
|
2021-04-14 18:11:13 +00:00
|
|
|
"bytes"
|
2020-08-10 17:43:49 +00:00
|
|
|
"os"
|
2020-05-04 20:46:48 +00:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2020-08-10 17:43:49 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"golang.org/x/sys/unix"
|
2020-05-04 20:46:48 +00:00
|
|
|
)
|
|
|
|
|
2021-04-14 18:11:13 +00:00
|
|
|
// WriteFile writes data to a cgroup file in dir.
|
|
|
|
// It is supposed to be used for cgroup files only.
|
2020-05-04 20:46:48 +00:00
|
|
|
func WriteFile(dir, file, data string) error {
|
2021-04-14 18:11:13 +00:00
|
|
|
fd, err := OpenFile(dir, file, unix.O_WRONLY)
|
2020-05-04 20:46:48 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-04-14 18:11:13 +00:00
|
|
|
defer fd.Close()
|
|
|
|
if err := retryingWriteFile(fd, data); err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to write %q", data)
|
2020-05-04 20:46:48 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-04-14 18:11:13 +00:00
|
|
|
// ReadFile reads data from a cgroup file in dir.
|
|
|
|
// It is supposed to be used for cgroup files only.
|
2020-05-04 20:46:48 +00:00
|
|
|
func ReadFile(dir, file string) (string, error) {
|
2021-04-14 18:11:13 +00:00
|
|
|
fd, err := OpenFile(dir, file, unix.O_RDONLY)
|
2020-05-04 20:46:48 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2021-04-14 18:11:13 +00:00
|
|
|
defer fd.Close()
|
|
|
|
var buf bytes.Buffer
|
|
|
|
|
|
|
|
_, err = buf.ReadFrom(fd)
|
|
|
|
return buf.String(), err
|
2020-05-04 20:46:48 +00:00
|
|
|
}
|
2020-08-10 17:43:49 +00:00
|
|
|
|
2021-04-14 18:11:13 +00:00
|
|
|
func retryingWriteFile(fd *os.File, data string) error {
|
2020-08-10 17:43:49 +00:00
|
|
|
for {
|
2021-04-14 18:11:13 +00:00
|
|
|
_, err := fd.Write([]byte(data))
|
2020-08-10 17:43:49 +00:00
|
|
|
if errors.Is(err, unix.EINTR) {
|
2021-04-14 18:11:13 +00:00
|
|
|
logrus.Infof("interrupted while writing %s to %s", data, fd.Name())
|
2020-08-10 17:43:49 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|