You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

406 lines
9.5 KiB

7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
  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_pb.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. if entry == nil {
  49. return fuse.ENOENT
  50. }
  51. // attr.Inode = file.fullpath().AsInode()
  52. attr.Valid = time.Second
  53. attr.Mode = os.FileMode(entry.Attributes.FileMode)
  54. attr.Size = filer.FileSize(entry)
  55. if file.isOpen > 0 {
  56. attr.Size = entry.Attributes.FileSize
  57. glog.V(4).Infof("file Attr %s, open:%v, size: %d", file.fullpath(), file.isOpen, attr.Size)
  58. }
  59. attr.Crtime = time.Unix(entry.Attributes.Crtime, 0)
  60. attr.Mtime = time.Unix(entry.Attributes.Mtime, 0)
  61. attr.Gid = entry.Attributes.Gid
  62. attr.Uid = entry.Attributes.Uid
  63. attr.Blocks = attr.Size/blockSize + 1
  64. attr.BlockSize = uint32(file.wfs.option.ChunkSizeLimit)
  65. if entry.HardLinkCounter > 0 {
  66. attr.Nlink = uint32(entry.HardLinkCounter)
  67. }
  68. return nil
  69. }
  70. func (file *File) Getxattr(ctx context.Context, req *fuse.GetxattrRequest, resp *fuse.GetxattrResponse) error {
  71. glog.V(4).Infof("file Getxattr %s", file.fullpath())
  72. entry, err := file.maybeLoadEntry(ctx)
  73. if err != nil {
  74. return err
  75. }
  76. return getxattr(entry, req, resp)
  77. }
  78. func (file *File) Open(ctx context.Context, req *fuse.OpenRequest, resp *fuse.OpenResponse) (fs.Handle, error) {
  79. glog.V(4).Infof("file %v open %+v", file.fullpath(), req)
  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. if file.wfs.option.ReadOnly {
  87. return fuse.EPERM
  88. }
  89. glog.V(4).Infof("%v file setattr %+v", file.fullpath(), req)
  90. entry, err := file.maybeLoadEntry(ctx)
  91. if err != nil {
  92. return err
  93. }
  94. if file.isOpen > 0 {
  95. file.wfs.handlesLock.Lock()
  96. fileHandle := file.wfs.handles[file.fullpath().AsInode()]
  97. file.wfs.handlesLock.Unlock()
  98. if fileHandle != nil {
  99. fileHandle.Lock()
  100. defer fileHandle.Unlock()
  101. }
  102. }
  103. if req.Valid.Size() {
  104. glog.V(4).Infof("%v file setattr set size=%v chunks=%d", file.fullpath(), req.Size, len(entry.Chunks))
  105. if req.Size < filer.FileSize(entry) {
  106. // fmt.Printf("truncate %v \n", fullPath)
  107. var chunks []*filer_pb.FileChunk
  108. var truncatedChunks []*filer_pb.FileChunk
  109. for _, chunk := range entry.Chunks {
  110. int64Size := int64(chunk.Size)
  111. if chunk.Offset+int64Size > int64(req.Size) {
  112. // this chunk is truncated
  113. int64Size = int64(req.Size) - chunk.Offset
  114. if int64Size > 0 {
  115. chunks = append(chunks, chunk)
  116. glog.V(4).Infof("truncated chunk %+v from %d to %d\n", chunk.GetFileIdString(), chunk.Size, int64Size)
  117. chunk.Size = uint64(int64Size)
  118. } else {
  119. glog.V(4).Infof("truncated whole chunk %+v\n", chunk.GetFileIdString())
  120. truncatedChunks = append(truncatedChunks, chunk)
  121. }
  122. }
  123. }
  124. entry.Chunks = chunks
  125. file.entryViewCache, _ = filer.NonOverlappingVisibleIntervals(file.wfs.LookupFn(), chunks)
  126. file.setReader(nil)
  127. }
  128. entry.Attributes.FileSize = req.Size
  129. file.dirtyMetadata = true
  130. }
  131. if req.Valid.Mode() {
  132. entry.Attributes.FileMode = uint32(req.Mode)
  133. file.dirtyMetadata = true
  134. }
  135. if req.Valid.Uid() {
  136. entry.Attributes.Uid = req.Uid
  137. file.dirtyMetadata = true
  138. }
  139. if req.Valid.Gid() {
  140. entry.Attributes.Gid = req.Gid
  141. file.dirtyMetadata = true
  142. }
  143. if req.Valid.Crtime() {
  144. entry.Attributes.Crtime = req.Crtime.Unix()
  145. file.dirtyMetadata = true
  146. }
  147. if req.Valid.Mtime() {
  148. entry.Attributes.Mtime = req.Mtime.Unix()
  149. file.dirtyMetadata = true
  150. }
  151. if req.Valid.Handle() {
  152. // fmt.Printf("file handle => %d\n", req.Handle)
  153. }
  154. if file.isOpen > 0 {
  155. return nil
  156. }
  157. if !file.dirtyMetadata {
  158. return nil
  159. }
  160. return file.saveEntry(entry)
  161. }
  162. func (file *File) Setxattr(ctx context.Context, req *fuse.SetxattrRequest) error {
  163. if file.wfs.option.ReadOnly {
  164. return fuse.EPERM
  165. }
  166. glog.V(4).Infof("file Setxattr %s: %s", file.fullpath(), req.Name)
  167. entry, err := file.maybeLoadEntry(ctx)
  168. if err != nil {
  169. return err
  170. }
  171. if err := setxattr(entry, req); err != nil {
  172. return err
  173. }
  174. return file.saveEntry(entry)
  175. }
  176. func (file *File) Removexattr(ctx context.Context, req *fuse.RemovexattrRequest) error {
  177. if file.wfs.option.ReadOnly {
  178. return fuse.EPERM
  179. }
  180. glog.V(4).Infof("file Removexattr %s: %s", file.fullpath(), req.Name)
  181. entry, err := file.maybeLoadEntry(ctx)
  182. if err != nil {
  183. return err
  184. }
  185. if err := removexattr(entry, req); err != nil {
  186. return err
  187. }
  188. return file.saveEntry(entry)
  189. }
  190. func (file *File) Listxattr(ctx context.Context, req *fuse.ListxattrRequest, resp *fuse.ListxattrResponse) error {
  191. glog.V(4).Infof("file Listxattr %s", file.fullpath())
  192. entry, err := file.maybeLoadEntry(ctx)
  193. if err != nil {
  194. return err
  195. }
  196. if err := listxattr(entry, req, resp); err != nil {
  197. return err
  198. }
  199. return nil
  200. }
  201. func (file *File) Fsync(ctx context.Context, req *fuse.FsyncRequest) error {
  202. // fsync works at OS level
  203. // write the file chunks to the filerGrpcAddress
  204. glog.V(4).Infof("%s/%s fsync file %+v", file.dir.FullPath(), file.Name, req)
  205. return nil
  206. }
  207. func (file *File) Forget() {
  208. t := util.NewFullPath(file.dir.FullPath(), file.Name)
  209. glog.V(4).Infof("Forget file %s", t)
  210. file.wfs.fsNodeCache.DeleteFsNode(t)
  211. file.wfs.ReleaseHandle(t, 0)
  212. file.setReader(nil)
  213. }
  214. func (file *File) maybeLoadEntry(ctx context.Context) (entry *filer_pb.Entry, err error) {
  215. entry = file.getEntry()
  216. if file.isOpen > 0 {
  217. return entry, nil
  218. }
  219. if entry != nil {
  220. if len(entry.HardLinkId) == 0 {
  221. // only always reload hard link
  222. return entry, nil
  223. }
  224. }
  225. entry, err = file.wfs.maybeLoadEntry(file.dir.FullPath(), file.Name)
  226. if err != nil {
  227. glog.V(3).Infof("maybeLoadEntry file %s/%s: %v", file.dir.FullPath(), file.Name, err)
  228. return entry, err
  229. }
  230. if entry != nil {
  231. file.setEntry(entry)
  232. } else {
  233. glog.Warningf("maybeLoadEntry not found entry %s/%s: %v", file.dir.FullPath(), file.Name, err)
  234. }
  235. return entry, nil
  236. }
  237. func lessThan(a, b *filer_pb.FileChunk) bool {
  238. if a.Mtime == b.Mtime {
  239. return a.Fid.FileKey < b.Fid.FileKey
  240. }
  241. return a.Mtime < b.Mtime
  242. }
  243. func (file *File) addChunks(chunks []*filer_pb.FileChunk) {
  244. // find the earliest incoming chunk
  245. newChunks := chunks
  246. earliestChunk := newChunks[0]
  247. for i := 1; i < len(newChunks); i++ {
  248. if lessThan(earliestChunk, newChunks[i]) {
  249. earliestChunk = newChunks[i]
  250. }
  251. }
  252. entry := file.getEntry()
  253. if entry == nil {
  254. return
  255. }
  256. // pick out-of-order chunks from existing chunks
  257. for _, chunk := range entry.Chunks {
  258. if lessThan(earliestChunk, chunk) {
  259. chunks = append(chunks, chunk)
  260. }
  261. }
  262. // sort incoming chunks
  263. sort.Slice(chunks, func(i, j int) bool {
  264. return lessThan(chunks[i], chunks[j])
  265. })
  266. // add to entry view cache
  267. for _, chunk := range chunks {
  268. file.entryViewCache = filer.MergeIntoVisibles(file.entryViewCache, chunk)
  269. }
  270. file.setReader(nil)
  271. glog.V(4).Infof("%s existing %d chunks adds %d more", file.fullpath(), len(entry.Chunks), len(chunks))
  272. entry.Chunks = append(entry.Chunks, newChunks...)
  273. }
  274. func (file *File) setReader(reader io.ReaderAt) {
  275. r := file.reader
  276. if r != nil {
  277. if closer, ok := r.(io.Closer); ok {
  278. closer.Close()
  279. }
  280. }
  281. file.reader = reader
  282. }
  283. func (file *File) setEntry(entry *filer_pb.Entry) {
  284. file.entryLock.Lock()
  285. defer file.entryLock.Unlock()
  286. file.entry = entry
  287. file.entryViewCache, _ = filer.NonOverlappingVisibleIntervals(file.wfs.LookupFn(), entry.Chunks)
  288. file.setReader(nil)
  289. }
  290. func (file *File) clearEntry() {
  291. file.entryLock.Lock()
  292. defer file.entryLock.Unlock()
  293. file.entry = nil
  294. file.entryViewCache = nil
  295. file.setReader(nil)
  296. }
  297. func (file *File) saveEntry(entry *filer_pb.Entry) error {
  298. return file.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  299. file.wfs.mapPbIdFromLocalToFiler(entry)
  300. defer file.wfs.mapPbIdFromFilerToLocal(entry)
  301. request := &filer_pb.UpdateEntryRequest{
  302. Directory: file.dir.FullPath(),
  303. Entry: entry,
  304. Signatures: []int32{file.wfs.signature},
  305. }
  306. glog.V(4).Infof("save file entry: %v", request)
  307. _, err := client.UpdateEntry(context.Background(), request)
  308. if err != nil {
  309. glog.Errorf("UpdateEntry file %s/%s: %v", file.dir.FullPath(), file.Name, err)
  310. return fuse.EIO
  311. }
  312. file.wfs.metaCache.UpdateEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
  313. return nil
  314. })
  315. }
  316. func (file *File) getEntry() *filer_pb.Entry {
  317. file.entryLock.RLock()
  318. defer file.entryLock.RUnlock()
  319. return file.entry
  320. }