filestorage.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. // WriteStream uses the relative path of the storage combined with the provided path
  157. // to write a new file or overwrite an existing file.
  158. //
  159. // It takes advantage of flock() based locking to improve safety. The returned `io.WriteCloser`
  160. // must be closed.
  161. func (fs *FileStorage) WriteStream(path string) (io.WriteCloser, error) {
  162. f, err := fs.prepare(path)
  163. if err != nil {
  164. return nil, errors.Wrap(err, "Failed to prepare path")
  165. }
  166. w, err := fileutil.NewLockedFileWriter(f)
  167. if err != nil {
  168. return nil, fmt.Errorf("failed to load file writer for: %s - %w", f, err)
  169. }
  170. return w, nil
  171. }
  172. // Remove uses the relative path of the storage combined with the provided path to
  173. // remove a file from storage permanently.
  174. func (fs *FileStorage) Remove(path string) error {
  175. f := gopath.Join(fs.baseDir, path)
  176. err := os.Remove(f)
  177. if err != nil {
  178. if os.IsNotExist(err) {
  179. return DoesNotExistError
  180. }
  181. return errors.Wrap(err, "Failed to remove file")
  182. }
  183. return nil
  184. }
  185. // Exists uses the relative path of the storage combined with the provided path to
  186. // determine if the file exists.
  187. func (fs *FileStorage) Exists(path string) (bool, error) {
  188. f := gopath.Join(fs.baseDir, path)
  189. return fileutil.FileExists(f)
  190. }
  191. // prepare checks to see if the directory being written to should be created before writing
  192. // the file, and then returns the correct full path.
  193. func (fs *FileStorage) prepare(path string) (string, error) {
  194. f := gopath.Join(fs.baseDir, path)
  195. dir := filepath.Dir(f)
  196. if _, e := os.Stat(dir); e != nil && os.IsNotExist(e) {
  197. err := os.MkdirAll(dir, os.ModePerm)
  198. if err != nil {
  199. return "", err
  200. }
  201. }
  202. return f, nil
  203. }
  204. // FilesToStorageInfo maps a []fs.FileInfo to []*storage.StorageInfo
  205. func FilesToStorageInfo(fileInfo []gofs.FileInfo) []*StorageInfo {
  206. var stats []*StorageInfo
  207. for _, info := range fileInfo {
  208. if info.IsDir() {
  209. continue
  210. }
  211. stats = append(stats, FileToStorageInfo(info))
  212. }
  213. return stats
  214. }
  215. // FileToStorageInfo maps a fs.FileInfo to *storage.StorageInfo
  216. func FileToStorageInfo(fileInfo gofs.FileInfo) *StorageInfo {
  217. return &StorageInfo{
  218. Name: fileInfo.Name(),
  219. Size: fileInfo.Size(),
  220. ModTime: fileInfo.ModTime(),
  221. }
  222. }
  223. // DirFilesToStorageInfo maps a []fs.FileInfo to []*storage.StorageInfo
  224. // but only returning StorageInfo for directories
  225. func DirFilesToStorageInfo(fileInfo []gofs.FileInfo, relativePath string, basePath string) []*StorageInfo {
  226. var stats []*StorageInfo
  227. for _, info := range fileInfo {
  228. if info.IsDir() {
  229. stats = append(stats, &StorageInfo{
  230. Name: filepath.Join(relativePath, info.Name()),
  231. Size: info.Size(),
  232. ModTime: info.ModTime(),
  233. })
  234. } else if info.Mode()&os.ModeSymlink == os.ModeSymlink {
  235. targetPath, err := os.Readlink(filepath.Join(basePath, relativePath, info.Name()))
  236. if err != nil {
  237. 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)
  238. continue
  239. }
  240. if targetInfo, err := os.Stat(targetPath); err == nil {
  241. if targetInfo.IsDir() {
  242. stats = append(stats, &StorageInfo{
  243. // The Name added here is the path not readlink-ed
  244. Name: filepath.Join(relativePath, info.Name()),
  245. Size: info.Size(),
  246. ModTime: info.ModTime(),
  247. })
  248. }
  249. } else if errors.Is(err, os.ErrNotExist) {
  250. continue
  251. } else {
  252. log.Warnf("Converting files to storage info failed to stat target (%s) of symlink (%s): %s", targetPath, info.Name(), err)
  253. continue
  254. }
  255. }
  256. }
  257. return stats
  258. }