| 51 | } |
| 52 | |
| 53 | func (a *File) Close() error { |
| 54 | cleanup := true |
| 55 | defer func() { |
| 56 | if cleanup { |
| 57 | _ = os.Remove(a.Name()) |
| 58 | } |
| 59 | }() |
| 60 | |
| 61 | merr := multierror.New() |
| 62 | merr.Add(a.Sync()) |
| 63 | merr.Add(a.File.Close()) |
| 64 | if err := merr.Err(); err != nil { |
| 65 | return err |
| 66 | } |
| 67 | |
| 68 | if err := os.Rename(a.Name(), a.finalPath); err != nil { |
| 69 | return err |
| 70 | } |
| 71 | |
| 72 | cleanup = false |
| 73 | // After writing the file and calling fsync on it, fsync the containing directory |
| 74 | // to ensure the directory entry is persisted to disk. |
| 75 | // |
| 76 | // From https://man7.org/linux/man-pages/man2/fsync.2.html |
| 77 | // > Calling fsync() does not necessarily ensure that the entry in the |
| 78 | // > directory containing the file has also reached disk. For that an |
| 79 | // > explicit fsync() on a file descriptor for the directory is also |
| 80 | // > needed. |
| 81 | dir, err := os.Open(filepath.Dir(a.finalPath)) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | |
| 86 | merr.Add(dir.Sync()) |
| 87 | merr.Add(dir.Close()) |
| 88 | return merr.Err() |
| 89 | } |
| 90 | |
| 91 | // CreateFile safely writes the contents of data to filePath, ensuring that all data |
| 92 | // has been fsynced as well as the containing directory of the file. |