file.go 9.7 KB

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