file.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package filesys
  2. import (
  3. "context"
  4. "io"
  5. "os"
  6. "sort"
  7. "sync"
  8. "time"
  9. "github.com/seaweedfs/fuse"
  10. "github.com/seaweedfs/fuse/fs"
  11. "github.com/chrislusf/seaweedfs/weed/filer"
  12. "github.com/chrislusf/seaweedfs/weed/glog"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. "github.com/chrislusf/seaweedfs/weed/util"
  15. )
  16. const blockSize = 512
  17. var _ = fs.Node(&File{})
  18. var _ = fs.NodeOpener(&File{})
  19. var _ = fs.NodeFsyncer(&File{})
  20. var _ = fs.NodeSetattrer(&File{})
  21. var _ = fs.NodeGetxattrer(&File{})
  22. var _ = fs.NodeSetxattrer(&File{})
  23. var _ = fs.NodeRemovexattrer(&File{})
  24. var _ = fs.NodeListxattrer(&File{})
  25. var _ = fs.NodeForgetter(&File{})
  26. type File struct {
  27. Name string
  28. dir *Dir
  29. wfs *WFS
  30. entry *filer.Entry
  31. entryLock sync.RWMutex
  32. entryViewCache []filer.VisibleInterval
  33. isOpen int
  34. reader io.ReaderAt
  35. dirtyMetadata bool
  36. }
  37. func (file *File) fullpath() util.FullPath {
  38. return util.NewFullPath(file.dir.FullPath(), file.Name)
  39. }
  40. func (file *File) Attr(ctx context.Context, attr *fuse.Attr) (err error) {
  41. glog.V(4).Infof("file Attr %s, open:%v existing:%v", file.fullpath(), file.isOpen, attr)
  42. entry := file.getEntry()
  43. if file.isOpen <= 0 || entry == nil {
  44. if entry, err = file.maybeLoadEntry(ctx); err != nil {
  45. return err
  46. }
  47. }
  48. // attr.Inode = file.fullpath().AsInode()
  49. attr.Valid = time.Second
  50. attr.Mode = os.FileMode(entry.Attr.Mode)
  51. attr.Size = filer.FileSize2(entry)
  52. if file.isOpen > 0 {
  53. attr.Size = entry.Attr.FileSize
  54. glog.V(4).Infof("file Attr %s, open:%v, size: %d", file.fullpath(), file.isOpen, attr.Size)
  55. }
  56. attr.Crtime = entry.Attr.Crtime
  57. attr.Mtime = entry.Attr.Mtime
  58. attr.Gid = entry.Attr.Gid
  59. attr.Uid = entry.Attr.Uid
  60. attr.Blocks = attr.Size/blockSize + 1
  61. attr.BlockSize = uint32(file.wfs.option.ChunkSizeLimit)
  62. if entry.HardLinkCounter > 0 {
  63. attr.Nlink = uint32(entry.HardLinkCounter)
  64. }
  65. return nil
  66. }
  67. func (file *File) Getxattr(ctx context.Context, req *fuse.GetxattrRequest, resp *fuse.GetxattrResponse) error {
  68. glog.V(4).Infof("file Getxattr %s", file.fullpath())
  69. entry, err := file.maybeLoadEntry(ctx)
  70. if err != nil {
  71. return err
  72. }
  73. return getxattr(entry, req, resp)
  74. }
  75. func (file *File) Open(ctx context.Context, req *fuse.OpenRequest, resp *fuse.OpenResponse) (fs.Handle, error) {
  76. glog.V(4).Infof("file %v open %+v", file.fullpath(), req)
  77. handle := file.wfs.AcquireHandle(file, req.Uid, req.Gid)
  78. resp.Handle = fuse.HandleID(handle.handle)
  79. glog.V(4).Infof("%v file open handle id = %d", file.fullpath(), handle.handle)
  80. return handle, nil
  81. }
  82. func (file *File) Setattr(ctx context.Context, req *fuse.SetattrRequest, resp *fuse.SetattrResponse) error {
  83. glog.V(4).Infof("%v file setattr %+v", file.fullpath(), req)
  84. entry, err := file.maybeLoadEntry(ctx)
  85. if err != nil {
  86. return err
  87. }
  88. if file.isOpen > 0 {
  89. file.wfs.handlesLock.Lock()
  90. fileHandle := file.wfs.handles[file.fullpath().AsInode()]
  91. file.wfs.handlesLock.Unlock()
  92. if fileHandle != nil {
  93. fileHandle.Lock()
  94. defer fileHandle.Unlock()
  95. }
  96. }
  97. if req.Valid.Size() {
  98. glog.V(4).Infof("%v file setattr set size=%v chunks=%d", file.fullpath(), req.Size, len(entry.Chunks))
  99. if req.Size < filer.FileSize2(entry) {
  100. // fmt.Printf("truncate %v \n", fullPath)
  101. var chunks []*filer_pb.FileChunk
  102. var truncatedChunks []*filer_pb.FileChunk
  103. for _, chunk := range entry.Chunks {
  104. int64Size := int64(chunk.Size)
  105. if chunk.Offset+int64Size > int64(req.Size) {
  106. // this chunk is truncated
  107. int64Size = int64(req.Size) - chunk.Offset
  108. if int64Size > 0 {
  109. chunks = append(chunks, chunk)
  110. glog.V(4).Infof("truncated chunk %+v from %d to %d\n", chunk.GetFileIdString(), chunk.Size, int64Size)
  111. chunk.Size = uint64(int64Size)
  112. } else {
  113. glog.V(4).Infof("truncated whole chunk %+v\n", chunk.GetFileIdString())
  114. truncatedChunks = append(truncatedChunks, chunk)
  115. }
  116. }
  117. }
  118. entry.Chunks = chunks
  119. file.entryViewCache, _ = filer.NonOverlappingVisibleIntervals(file.wfs.LookupFn(), chunks)
  120. file.reader = nil
  121. }
  122. entry.Attr.FileSize = req.Size
  123. file.dirtyMetadata = true
  124. }
  125. if req.Valid.Mode() {
  126. entry.Attr.Mode = req.Mode
  127. file.dirtyMetadata = true
  128. }
  129. if req.Valid.Uid() {
  130. entry.Attr.Uid = req.Uid
  131. file.dirtyMetadata = true
  132. }
  133. if req.Valid.Gid() {
  134. entry.Attr.Gid = req.Gid
  135. file.dirtyMetadata = true
  136. }
  137. if req.Valid.Crtime() {
  138. entry.Attr.Crtime = req.Crtime
  139. file.dirtyMetadata = true
  140. }
  141. if req.Valid.Mtime() {
  142. entry.Attr.Mtime = req.Mtime
  143. file.dirtyMetadata = true
  144. }
  145. if req.Valid.Handle() {
  146. // fmt.Printf("file handle => %d\n", req.Handle)
  147. }
  148. if file.isOpen > 0 {
  149. return nil
  150. }
  151. if !file.dirtyMetadata {
  152. return nil
  153. }
  154. return file.saveEntry(entry)
  155. }
  156. func (file *File) Setxattr(ctx context.Context, req *fuse.SetxattrRequest) error {
  157. glog.V(4).Infof("file Setxattr %s: %s", file.fullpath(), req.Name)
  158. entry, err := file.maybeLoadEntry(ctx)
  159. if err != nil {
  160. return err
  161. }
  162. if err := setxattr(entry, req); err != nil {
  163. return err
  164. }
  165. return file.saveEntry(entry)
  166. }
  167. func (file *File) Removexattr(ctx context.Context, req *fuse.RemovexattrRequest) error {
  168. glog.V(4).Infof("file Removexattr %s: %s", file.fullpath(), req.Name)
  169. entry, err := file.maybeLoadEntry(ctx)
  170. if err != nil {
  171. return err
  172. }
  173. if err := removexattr(entry, req); err != nil {
  174. return err
  175. }
  176. return file.saveEntry(entry)
  177. }
  178. func (file *File) Listxattr(ctx context.Context, req *fuse.ListxattrRequest, resp *fuse.ListxattrResponse) error {
  179. glog.V(4).Infof("file Listxattr %s", file.fullpath())
  180. entry, err := file.maybeLoadEntry(ctx)
  181. if err != nil {
  182. return err
  183. }
  184. if err := listxattr(entry, req, resp); err != nil {
  185. return err
  186. }
  187. return nil
  188. }
  189. func (file *File) Fsync(ctx context.Context, req *fuse.FsyncRequest) error {
  190. // fsync works at OS level
  191. // write the file chunks to the filerGrpcAddress
  192. glog.V(4).Infof("%s/%s fsync file %+v", file.dir.FullPath(), file.Name, req)
  193. return nil
  194. }
  195. func (file *File) Forget() {
  196. t := util.NewFullPath(file.dir.FullPath(), file.Name)
  197. glog.V(4).Infof("Forget file %s", t)
  198. file.wfs.fsNodeCache.DeleteFsNode(t)
  199. }
  200. func (file *File) maybeLoadEntry(ctx context.Context) (entry *filer.Entry, err error) {
  201. entry = file.getEntry()
  202. if file.isOpen > 0 {
  203. return entry, nil
  204. }
  205. if entry != nil {
  206. if len(entry.HardLinkId) == 0 {
  207. // only always reload hard link
  208. return entry, nil
  209. }
  210. }
  211. entry, err = file.wfs.maybeLoadEntry(file.dir.FullPath(), file.Name)
  212. if err != nil {
  213. glog.V(3).Infof("maybeLoadEntry file %s/%s: %v", file.dir.FullPath(), file.Name, err)
  214. return entry, err
  215. }
  216. if entry != nil {
  217. file.setEntry(entry)
  218. } else {
  219. glog.Warningf("maybeLoadEntry not found entry %s/%s: %v", file.dir.FullPath(), file.Name, err)
  220. }
  221. return entry, nil
  222. }
  223. func lessThan(a, b *filer_pb.FileChunk) bool {
  224. if a.Mtime == b.Mtime {
  225. return a.Fid.FileKey < b.Fid.FileKey
  226. }
  227. return a.Mtime < b.Mtime
  228. }
  229. func (file *File) addChunks(chunks []*filer_pb.FileChunk) {
  230. // find the earliest incoming chunk
  231. newChunks := chunks
  232. earliestChunk := newChunks[0]
  233. for i := 1; i < len(newChunks); i++ {
  234. if lessThan(earliestChunk, newChunks[i]) {
  235. earliestChunk = newChunks[i]
  236. }
  237. }
  238. entry := file.getEntry()
  239. if entry == nil {
  240. return
  241. }
  242. // pick out-of-order chunks from existing chunks
  243. for _, chunk := range entry.Chunks {
  244. if lessThan(earliestChunk, chunk) {
  245. chunks = append(chunks, chunk)
  246. }
  247. }
  248. // sort incoming chunks
  249. sort.Slice(chunks, func(i, j int) bool {
  250. return lessThan(chunks[i], chunks[j])
  251. })
  252. // add to entry view cache
  253. for _, chunk := range chunks {
  254. file.entryViewCache = filer.MergeIntoVisibles(file.entryViewCache, chunk)
  255. }
  256. file.reader = nil
  257. glog.V(4).Infof("%s existing %d chunks adds %d more", file.fullpath(), len(entry.Chunks), len(chunks))
  258. entry.Chunks = append(entry.Chunks, newChunks...)
  259. }
  260. func (file *File) setEntry(entry *filer.Entry) {
  261. file.entryLock.Lock()
  262. defer file.entryLock.Unlock()
  263. file.entry = entry
  264. file.entryViewCache, _ = filer.NonOverlappingVisibleIntervals(file.wfs.LookupFn(), entry.Chunks)
  265. file.reader = nil
  266. }
  267. func (file *File) clearEntry() {
  268. file.entryLock.Lock()
  269. defer file.entryLock.Unlock()
  270. file.entry = nil
  271. file.entryViewCache = nil
  272. file.reader = nil
  273. }
  274. func (file *File) saveEntry(entry *filer.Entry) error {
  275. return file.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  276. pbEntry := entry.ToProtoEntry()
  277. file.wfs.mapPbIdFromLocalToFiler(pbEntry)
  278. defer file.wfs.mapPbIdFromFilerToLocal(pbEntry)
  279. request := &filer_pb.UpdateEntryRequest{
  280. Directory: file.dir.FullPath(),
  281. Entry: pbEntry,
  282. Signatures: []int32{file.wfs.signature},
  283. }
  284. glog.V(4).Infof("save file entry: %v", request)
  285. _, err := client.UpdateEntry(context.Background(), request)
  286. if err != nil {
  287. glog.Errorf("UpdateEntry file %s/%s: %v", file.dir.FullPath(), file.Name, err)
  288. return fuse.EIO
  289. }
  290. file.wfs.metaCache.UpdateEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
  291. return nil
  292. })
  293. }
  294. func (file *File) getEntry() *filer.Entry {
  295. file.entryLock.RLock()
  296. defer file.entryLock.RUnlock()
  297. return file.entry
  298. }