filestorage.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package storage
  2. import (
  3. "fmt"
  4. "io"
  5. gofs "io/fs"
  6. "os"
  7. gopath "path"
  8. "path/filepath"
  9. "github.com/opencost/opencost/core/pkg/log"
  10. "github.com/opencost/opencost/core/pkg/util/fileutil"
  11. "github.com/pkg/errors"
  12. )
  13. // FileStorage leverages the file system to write data to disk.
  14. type FileStorage struct {
  15. baseDir string
  16. }
  17. // NewFileStorage returns a new storage API which leverages the file system.
  18. func NewFileStorage(baseDir string) Storage {
  19. return &FileStorage{baseDir}
  20. }
  21. // String returns the base directory for the file storage.
  22. func (fs *FileStorage) String() string {
  23. return fs.baseDir
  24. }
  25. // StorageType returns a string identifier for the type of storage used by the implementation.
  26. func (fs *FileStorage) StorageType() StorageType {
  27. return StorageTypeFile
  28. }
  29. // FullPath returns the storage working path combined with the path provided
  30. func (fs *FileStorage) FullPath(path string) string {
  31. return gopath.Join(fs.baseDir, path)
  32. }
  33. // Stat returns the StorageStats for the specific path.
  34. func (fs *FileStorage) Stat(path string) (*StorageInfo, error) {
  35. f := gopath.Join(fs.baseDir, path)
  36. st, err := os.Stat(f)
  37. if err != nil {
  38. if os.IsNotExist(err) {
  39. return nil, DoesNotExistError
  40. }
  41. return nil, errors.Wrap(err, "Failed to stat file")
  42. }
  43. return FileToStorageInfo(st), nil
  44. }
  45. // List uses the relative path of the storage combined with the provided path to return
  46. // storage information for the files.
  47. func (fs *FileStorage) List(path string) ([]*StorageInfo, error) {
  48. p := gopath.Join(fs.baseDir, path)
  49. // Read files in the backup path
  50. entries, err := os.ReadDir(p)
  51. if err != nil {
  52. if os.IsNotExist(err) {
  53. return []*StorageInfo{}, nil
  54. }
  55. return nil, err
  56. }
  57. files := make([]gofs.FileInfo, 0, len(entries))
  58. for _, entry := range entries {
  59. info, err := entry.Info()
  60. if err != nil {
  61. return nil, err
  62. }
  63. files = append(files, info)
  64. }
  65. return FilesToStorageInfo(files), nil
  66. }
  67. func (fs *FileStorage) ListDirectories(path string) ([]*StorageInfo, error) {
  68. p := gopath.Join(fs.baseDir, path)
  69. // Read files in the backup path
  70. entries, err := os.ReadDir(p)
  71. if err != nil {
  72. if os.IsNotExist(err) {
  73. return []*StorageInfo{}, nil
  74. }
  75. return nil, err
  76. }
  77. files := make([]gofs.FileInfo, 0, len(entries))
  78. for _, entry := range entries {
  79. info, err := entry.Info()
  80. if err != nil {
  81. return nil, err
  82. }
  83. files = append(files, info)
  84. }
  85. return DirFilesToStorageInfo(files, path, fs.baseDir), nil
  86. }
  87. // Read uses the relative path of the storage combined with the provided path to
  88. // read the contents.
  89. //
  90. // It takes advantage of flock() based locking to improve safety.
  91. func (fs *FileStorage) Read(path string) ([]byte, error) {
  92. f := filepath.Join(fs.baseDir, path)
  93. b, err := fileutil.ReadLocked(f)
  94. if err != nil {
  95. if errors.Is(err, os.ErrNotExist) {
  96. return nil, DoesNotExistError
  97. }
  98. return nil, fmt.Errorf("reading %s: %w", f, err)
  99. }
  100. return b, nil
  101. }
  102. // ReadStream returns a streaming reader for the specified file path.
  103. func (fs *FileStorage) ReadStream(path string) (io.ReadCloser, error) {
  104. f := filepath.Join(fs.baseDir, path)
  105. file, err := os.Open(f)
  106. if err != nil {
  107. if errors.Is(err, os.ErrNotExist) {
  108. return nil, DoesNotExistError
  109. }
  110. return nil, fmt.Errorf("opening %s: %w", f, err)
  111. }
  112. return file, nil
  113. }
  114. // ReadToLocalFile streams the specified file at path to destPath on the local file system.
  115. //
  116. // For FileStorage, this is implemented as a local file copy.
  117. func (fs *FileStorage) ReadToLocalFile(path, destPath string) error {
  118. src := filepath.Join(fs.baseDir, path)
  119. in, err := os.Open(src)
  120. if err != nil {
  121. if os.IsNotExist(err) {
  122. return DoesNotExistError
  123. }
  124. return fmt.Errorf("reading %s: %w", src, err)
  125. }
  126. defer in.Close()
  127. if err := os.MkdirAll(filepath.Dir(destPath), os.ModePerm); err != nil {
  128. return fmt.Errorf("creating destination directory: %w", err)
  129. }
  130. out, err := os.Create(destPath)
  131. if err != nil {
  132. return fmt.Errorf("creating destination file %s: %w", destPath, err)
  133. }
  134. defer out.Close()
  135. // Use 1 MB buffer for file copy operations
  136. buf := make([]byte, 1024*1024)
  137. if _, err := io.CopyBuffer(out, in, buf); err != nil {
  138. return fmt.Errorf("streaming %s to %s: %w", src, destPath, err)
  139. }
  140. return nil
  141. }
  142. // Write uses the relative path of the storage combined with the provided path
  143. // to write a new file or overwrite an existing file.
  144. //
  145. // It takes advantage of flock() based locking to improve safety.
  146. func (fs *FileStorage) Write(path string, data []byte) error {
  147. f, err := fs.prepare(path)
  148. if err != nil {
  149. return errors.Wrap(err, "Failed to prepare path")
  150. }
  151. if _, err := fileutil.WriteLocked(f, data); err != nil {
  152. return fmt.Errorf("writing %s: %w", f, err)
  153. }
  154. return nil
  155. }
  156. // Remove uses the relative path of the storage combined with the provided path to
  157. // remove a file from storage permanently.
  158. func (fs *FileStorage) Remove(path string) error {
  159. f := gopath.Join(fs.baseDir, path)
  160. err := os.Remove(f)
  161. if err != nil {
  162. if os.IsNotExist(err) {
  163. return DoesNotExistError
  164. }
  165. return errors.Wrap(err, "Failed to remove file")
  166. }
  167. return nil
  168. }
  169. // Exists uses the relative path of the storage combined with the provided path to
  170. // determine if the file exists.
  171. func (fs *FileStorage) Exists(path string) (bool, error) {
  172. f := gopath.Join(fs.baseDir, path)
  173. return fileutil.FileExists(f)
  174. }
  175. // prepare checks to see if the directory being written to should be created before writing
  176. // the file, and then returns the correct full path.
  177. func (fs *FileStorage) prepare(path string) (string, error) {
  178. f := gopath.Join(fs.baseDir, path)
  179. dir := filepath.Dir(f)
  180. if _, e := os.Stat(dir); e != nil && os.IsNotExist(e) {
  181. err := os.MkdirAll(dir, os.ModePerm)
  182. if err != nil {
  183. return "", err
  184. }
  185. }
  186. return f, nil
  187. }
  188. // FilesToStorageInfo maps a []fs.FileInfo to []*storage.StorageInfo
  189. func FilesToStorageInfo(fileInfo []gofs.FileInfo) []*StorageInfo {
  190. var stats []*StorageInfo
  191. for _, info := range fileInfo {
  192. if info.IsDir() {
  193. continue
  194. }
  195. stats = append(stats, FileToStorageInfo(info))
  196. }
  197. return stats
  198. }
  199. // FileToStorageInfo maps a fs.FileInfo to *storage.StorageInfo
  200. func FileToStorageInfo(fileInfo gofs.FileInfo) *StorageInfo {
  201. return &StorageInfo{
  202. Name: fileInfo.Name(),
  203. Size: fileInfo.Size(),
  204. ModTime: fileInfo.ModTime(),
  205. }
  206. }
  207. // DirFilesToStorageInfo maps a []fs.FileInfo to []*storage.StorageInfo
  208. // but only returning StorageInfo for directories
  209. func DirFilesToStorageInfo(fileInfo []gofs.FileInfo, relativePath string, basePath string) []*StorageInfo {
  210. var stats []*StorageInfo
  211. for _, info := range fileInfo {
  212. if info.IsDir() {
  213. stats = append(stats, &StorageInfo{
  214. Name: filepath.Join(relativePath, info.Name()),
  215. Size: info.Size(),
  216. ModTime: info.ModTime(),
  217. })
  218. } else if info.Mode()&os.ModeSymlink == os.ModeSymlink {
  219. targetPath, err := os.Readlink(filepath.Join(basePath, relativePath, info.Name()))
  220. if err != nil {
  221. log.Warnf("Converting files to storage info failed on supposed symlink that failed to be Readlink-ed (%s): %s", filepath.Join(basePath, relativePath, info.Name()), err)
  222. continue
  223. }
  224. if targetInfo, err := os.Stat(targetPath); err == nil {
  225. if targetInfo.IsDir() {
  226. stats = append(stats, &StorageInfo{
  227. // The Name added here is the path not readlink-ed
  228. Name: filepath.Join(relativePath, info.Name()),
  229. Size: info.Size(),
  230. ModTime: info.ModTime(),
  231. })
  232. }
  233. } else if errors.Is(err, os.ErrNotExist) {
  234. continue
  235. } else {
  236. log.Warnf("Converting files to storage info failed to stat target (%s) of symlink (%s): %s", targetPath, info.Name(), err)
  237. continue
  238. }
  239. }
  240. }
  241. return stats
  242. }