package utils
import (
"fmt"
"os"
"path"
)
const (
DirPerm = 0700
FilePerm = 0600
)
type FakeFilesystem struct {
RootDir string
Dirs []string
Files map[string][]byte
Symlinks map[string]string
}
func (fs *FakeFilesystem) Use() func() {
tmpDir, err := os.MkdirTemp("", "k8s-rdma-shared-dev-plugin-")
if err != nil {
panic(fmt.Errorf("error creating fake root dir: %s", err.Error()))
}
fs.RootDir = tmpDir
for _, dir := range fs.Dirs {
osErr := os.MkdirAll(path.Join(fs.RootDir, dir), DirPerm)
if osErr != nil {
panic(fmt.Errorf("error creating fake directory: %s", osErr.Error()))
}
}
for filename, body := range fs.Files {
ioErr := os.WriteFile(path.Join(fs.RootDir, filename), body, FilePerm)
if ioErr != nil {
panic(fmt.Errorf("error creating fake file: %s", ioErr.Error()))
}
}
for link, target := range fs.Symlinks {
osErr := os.Symlink(target, path.Join(fs.RootDir, link))
if osErr != nil {
panic(fmt.Errorf("error creating fake symlink: %s", osErr.Error()))
}
}
err = os.MkdirAll(path.Join(fs.RootDir, "usr/share/hwdata"), DirPerm)
if err != nil {
panic(fmt.Errorf("error creating fake directory: %s", err.Error()))
}
pciData, err := os.ReadFile("/usr/share/hwdata/pci.ids")
if err != nil {
panic(fmt.Errorf("error reading file: %s", err.Error()))
}
err = os.WriteFile(path.Join(fs.RootDir, "usr/share/hwdata/pci.ids"), pciData, FilePerm)
if err != nil {
panic(fmt.Errorf("error creating fake file: %s", err.Error()))
}
sysNetDevices = path.Join(fs.RootDir, "/sys/class/net")
return func() {
err := os.RemoveAll(fs.RootDir)
if err != nil {
panic(fmt.Errorf("error tearing down fake filesystem: %s", err.Error()))
}
}
}