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.

620 lines
15 KiB

5 years ago
5 years ago
3 years ago
3 years ago
4 years ago
2 years ago
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 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
5 years ago
5 years ago
5 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
4 years ago
5 years ago
5 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
5 years ago
4 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
5 years ago
5 years ago
5 years ago
2 years ago
2 years ago
4 years ago
4 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path"
  8. "strings"
  9. "time"
  10. "github.com/seaweedfs/seaweedfs/weed/util/buffered_writer"
  11. "golang.org/x/net/webdav"
  12. "google.golang.org/grpc"
  13. "github.com/seaweedfs/seaweedfs/weed/operation"
  14. "github.com/seaweedfs/seaweedfs/weed/pb"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  16. "github.com/seaweedfs/seaweedfs/weed/util"
  17. "github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
  18. "github.com/seaweedfs/seaweedfs/weed/filer"
  19. "github.com/seaweedfs/seaweedfs/weed/glog"
  20. "github.com/seaweedfs/seaweedfs/weed/security"
  21. )
  22. type WebDavOption struct {
  23. Filer pb.ServerAddress
  24. FilerRootPath string
  25. DomainName string
  26. BucketsPath string
  27. GrpcDialOption grpc.DialOption
  28. Collection string
  29. Replication string
  30. DiskType string
  31. Uid uint32
  32. Gid uint32
  33. Cipher bool
  34. CacheDir string
  35. CacheSizeMB int64
  36. }
  37. type WebDavServer struct {
  38. option *WebDavOption
  39. secret security.SigningKey
  40. filer *filer.Filer
  41. grpcDialOption grpc.DialOption
  42. Handler *webdav.Handler
  43. }
  44. func max(x, y int64) int64 {
  45. if x <= y {
  46. return y
  47. }
  48. return x
  49. }
  50. func NewWebDavServer(option *WebDavOption) (ws *WebDavServer, err error) {
  51. fs, _ := NewWebDavFileSystem(option)
  52. // Fix no set filer.path , accessing "/" returns "//"
  53. if option.FilerRootPath == "/" {
  54. option.FilerRootPath = ""
  55. }
  56. ws = &WebDavServer{
  57. option: option,
  58. grpcDialOption: security.LoadClientTLS(util.GetViper(), "grpc.filer"),
  59. Handler: &webdav.Handler{
  60. FileSystem: fs,
  61. LockSystem: webdav.NewMemLS(),
  62. },
  63. }
  64. return ws, nil
  65. }
  66. // adapted from https://github.com/mattn/davfs/blob/master/plugin/mysql/mysql.go
  67. type WebDavFileSystem struct {
  68. option *WebDavOption
  69. secret security.SigningKey
  70. grpcDialOption grpc.DialOption
  71. chunkCache *chunk_cache.TieredChunkCache
  72. readerCache *filer.ReaderCache
  73. signature int32
  74. }
  75. type FileInfo struct {
  76. name string
  77. size int64
  78. mode os.FileMode
  79. modifiedTime time.Time
  80. isDirectory bool
  81. }
  82. func (fi *FileInfo) Name() string { return fi.name }
  83. func (fi *FileInfo) Size() int64 { return fi.size }
  84. func (fi *FileInfo) Mode() os.FileMode { return fi.mode }
  85. func (fi *FileInfo) ModTime() time.Time { return fi.modifiedTime }
  86. func (fi *FileInfo) IsDir() bool { return fi.isDirectory }
  87. func (fi *FileInfo) Sys() interface{} { return nil }
  88. type WebDavFile struct {
  89. fs *WebDavFileSystem
  90. name string
  91. isDirectory bool
  92. off int64
  93. entry *filer_pb.Entry
  94. visibleIntervals *filer.IntervalList[*filer.VisibleInterval]
  95. reader io.ReaderAt
  96. bufWriter *buffered_writer.BufferedWriteCloser
  97. }
  98. func NewWebDavFileSystem(option *WebDavOption) (webdav.FileSystem, error) {
  99. cacheUniqueId := util.Md5String([]byte("webdav" + string(option.Filer) + util.Version()))[0:8]
  100. cacheDir := path.Join(option.CacheDir, cacheUniqueId)
  101. os.MkdirAll(cacheDir, os.FileMode(0755))
  102. chunkCache := chunk_cache.NewTieredChunkCache(256, cacheDir, option.CacheSizeMB, 1024*1024)
  103. t := &WebDavFileSystem{
  104. option: option,
  105. chunkCache: chunkCache,
  106. signature: util.RandomInt32(),
  107. }
  108. t.readerCache = filer.NewReaderCache(32, chunkCache, filer.LookupFn(t))
  109. return t, nil
  110. }
  111. var _ = filer_pb.FilerClient(&WebDavFileSystem{})
  112. func (fs *WebDavFileSystem) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
  113. return pb.WithGrpcClient(streamingMode, fs.signature, func(grpcConnection *grpc.ClientConn) error {
  114. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  115. return fn(client)
  116. }, fs.option.Filer.ToGrpcAddress(), false, fs.option.GrpcDialOption)
  117. }
  118. func (fs *WebDavFileSystem) AdjustedUrl(location *filer_pb.Location) string {
  119. return location.Url
  120. }
  121. func (fs *WebDavFileSystem) GetDataCenter() string {
  122. return ""
  123. }
  124. func clearName(name string) (string, error) {
  125. slashed := strings.HasSuffix(name, "/")
  126. name = path.Clean(name)
  127. if !strings.HasSuffix(name, "/") && slashed {
  128. name += "/"
  129. }
  130. if !strings.HasPrefix(name, "/") {
  131. return "", os.ErrInvalid
  132. }
  133. return name, nil
  134. }
  135. func (fs *WebDavFileSystem) Mkdir(ctx context.Context, fullDirPath string, perm os.FileMode) error {
  136. glog.V(2).Infof("WebDavFileSystem.Mkdir %v", fullDirPath)
  137. if !strings.HasSuffix(fullDirPath, "/") {
  138. fullDirPath += "/"
  139. }
  140. var err error
  141. if fullDirPath, err = clearName(fullDirPath); err != nil {
  142. return err
  143. }
  144. _, err = fs.stat(ctx, fullDirPath)
  145. if err == nil {
  146. return os.ErrExist
  147. }
  148. return fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  149. dir, name := util.FullPath(fullDirPath).DirAndName()
  150. request := &filer_pb.CreateEntryRequest{
  151. Directory: dir,
  152. Entry: &filer_pb.Entry{
  153. Name: name,
  154. IsDirectory: true,
  155. Attributes: &filer_pb.FuseAttributes{
  156. Mtime: time.Now().Unix(),
  157. Crtime: time.Now().Unix(),
  158. FileMode: uint32(perm | os.ModeDir),
  159. Uid: fs.option.Uid,
  160. Gid: fs.option.Gid,
  161. },
  162. },
  163. Signatures: []int32{fs.signature},
  164. }
  165. glog.V(1).Infof("mkdir: %v", request)
  166. if err := filer_pb.CreateEntry(client, request); err != nil {
  167. return fmt.Errorf("mkdir %s/%s: %v", dir, name, err)
  168. }
  169. return nil
  170. })
  171. }
  172. func (fs *WebDavFileSystem) OpenFile(ctx context.Context, fullFilePath string, flag int, perm os.FileMode) (webdav.File, error) {
  173. // Add filer.path
  174. fullFilePath = fs.option.FilerRootPath + fullFilePath
  175. glog.V(2).Infof("WebDavFileSystem.OpenFile %v %x", fullFilePath, flag)
  176. var err error
  177. if fullFilePath, err = clearName(fullFilePath); err != nil {
  178. return nil, err
  179. }
  180. if flag&os.O_CREATE != 0 {
  181. // file should not have / suffix.
  182. if strings.HasSuffix(fullFilePath, "/") {
  183. return nil, os.ErrInvalid
  184. }
  185. _, err = fs.stat(ctx, fullFilePath)
  186. if err == nil {
  187. if flag&os.O_EXCL != 0 {
  188. return nil, os.ErrExist
  189. }
  190. fs.removeAll(ctx, fullFilePath)
  191. }
  192. dir, name := util.FullPath(fullFilePath).DirAndName()
  193. err = fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  194. if err := filer_pb.CreateEntry(client, &filer_pb.CreateEntryRequest{
  195. Directory: dir,
  196. Entry: &filer_pb.Entry{
  197. Name: name,
  198. IsDirectory: perm&os.ModeDir > 0,
  199. Attributes: &filer_pb.FuseAttributes{
  200. Mtime: time.Now().Unix(),
  201. Crtime: time.Now().Unix(),
  202. FileMode: uint32(perm),
  203. Uid: fs.option.Uid,
  204. Gid: fs.option.Gid,
  205. TtlSec: 0,
  206. },
  207. },
  208. Signatures: []int32{fs.signature},
  209. }); err != nil {
  210. return fmt.Errorf("create %s: %v", fullFilePath, err)
  211. }
  212. return nil
  213. })
  214. if err != nil {
  215. return nil, err
  216. }
  217. return &WebDavFile{
  218. fs: fs,
  219. name: fullFilePath,
  220. isDirectory: false,
  221. bufWriter: buffered_writer.NewBufferedWriteCloser(4 * 1024 * 1024),
  222. }, nil
  223. }
  224. fi, err := fs.stat(ctx, fullFilePath)
  225. if err != nil {
  226. return nil, os.ErrNotExist
  227. }
  228. if !strings.HasSuffix(fullFilePath, "/") && fi.IsDir() {
  229. fullFilePath += "/"
  230. }
  231. return &WebDavFile{
  232. fs: fs,
  233. name: fullFilePath,
  234. isDirectory: false,
  235. bufWriter: buffered_writer.NewBufferedWriteCloser(4 * 1024 * 1024),
  236. }, nil
  237. }
  238. func (fs *WebDavFileSystem) removeAll(ctx context.Context, fullFilePath string) error {
  239. var err error
  240. if fullFilePath, err = clearName(fullFilePath); err != nil {
  241. return err
  242. }
  243. dir, name := util.FullPath(fullFilePath).DirAndName()
  244. return filer_pb.Remove(fs, dir, name, true, false, false, false, []int32{fs.signature})
  245. }
  246. func (fs *WebDavFileSystem) RemoveAll(ctx context.Context, name string) error {
  247. glog.V(2).Infof("WebDavFileSystem.RemoveAll %v", name)
  248. return fs.removeAll(ctx, name)
  249. }
  250. func (fs *WebDavFileSystem) Rename(ctx context.Context, oldName, newName string) error {
  251. glog.V(2).Infof("WebDavFileSystem.Rename %v to %v", oldName, newName)
  252. var err error
  253. if oldName, err = clearName(oldName); err != nil {
  254. return err
  255. }
  256. if newName, err = clearName(newName); err != nil {
  257. return err
  258. }
  259. of, err := fs.stat(ctx, oldName)
  260. if err != nil {
  261. return os.ErrExist
  262. }
  263. if of.IsDir() {
  264. if strings.HasSuffix(oldName, "/") {
  265. oldName = strings.TrimRight(oldName, "/")
  266. }
  267. if strings.HasSuffix(newName, "/") {
  268. newName = strings.TrimRight(newName, "/")
  269. }
  270. }
  271. _, err = fs.stat(ctx, newName)
  272. if err == nil {
  273. return os.ErrExist
  274. }
  275. oldDir, oldBaseName := util.FullPath(oldName).DirAndName()
  276. newDir, newBaseName := util.FullPath(newName).DirAndName()
  277. return fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  278. request := &filer_pb.AtomicRenameEntryRequest{
  279. OldDirectory: oldDir,
  280. OldName: oldBaseName,
  281. NewDirectory: newDir,
  282. NewName: newBaseName,
  283. }
  284. _, err := client.AtomicRenameEntry(ctx, request)
  285. if err != nil {
  286. return fmt.Errorf("renaming %s/%s => %s/%s: %v", oldDir, oldBaseName, newDir, newBaseName, err)
  287. }
  288. return nil
  289. })
  290. }
  291. func (fs *WebDavFileSystem) stat(ctx context.Context, fullFilePath string) (os.FileInfo, error) {
  292. var err error
  293. if fullFilePath, err = clearName(fullFilePath); err != nil {
  294. return nil, err
  295. }
  296. fullpath := util.FullPath(fullFilePath)
  297. var fi FileInfo
  298. entry, err := filer_pb.GetEntry(fs, fullpath)
  299. if entry == nil {
  300. return nil, os.ErrNotExist
  301. }
  302. if err != nil {
  303. return nil, err
  304. }
  305. fi.size = int64(filer.FileSize(entry))
  306. fi.name = string(fullpath)
  307. fi.mode = os.FileMode(entry.Attributes.FileMode)
  308. fi.modifiedTime = time.Unix(entry.Attributes.Mtime, 0)
  309. fi.isDirectory = entry.IsDirectory
  310. if fi.name == "/" {
  311. fi.modifiedTime = time.Now()
  312. fi.isDirectory = true
  313. }
  314. return &fi, nil
  315. }
  316. func (fs *WebDavFileSystem) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  317. // Add filer.path
  318. name = fs.option.FilerRootPath + name
  319. glog.V(2).Infof("WebDavFileSystem.Stat %v", name)
  320. return fs.stat(ctx, name)
  321. }
  322. func (f *WebDavFile) saveDataAsChunk(reader io.Reader, name string, offset int64, tsNs int64) (chunk *filer_pb.FileChunk, err error) {
  323. fileId, uploadResult, flushErr, _ := operation.UploadWithRetry(
  324. f.fs,
  325. &filer_pb.AssignVolumeRequest{
  326. Count: 1,
  327. Replication: f.fs.option.Replication,
  328. Collection: f.fs.option.Collection,
  329. DiskType: f.fs.option.DiskType,
  330. Path: name,
  331. },
  332. &operation.UploadOption{
  333. Filename: f.name,
  334. Cipher: f.fs.option.Cipher,
  335. IsInputCompressed: false,
  336. MimeType: "",
  337. PairMap: nil,
  338. },
  339. func(host, fileId string) string {
  340. return fmt.Sprintf("http://%s/%s", host, fileId)
  341. },
  342. reader,
  343. )
  344. if flushErr != nil {
  345. glog.V(0).Infof("upload data %v: %v", f.name, flushErr)
  346. return nil, fmt.Errorf("upload data: %v", flushErr)
  347. }
  348. if uploadResult.Error != "" {
  349. glog.V(0).Infof("upload failure %v: %v", f.name, flushErr)
  350. return nil, fmt.Errorf("upload result: %v", uploadResult.Error)
  351. }
  352. return uploadResult.ToPbFileChunk(fileId, offset, tsNs), nil
  353. }
  354. func (f *WebDavFile) Write(buf []byte) (int, error) {
  355. glog.V(2).Infof("WebDavFileSystem.Write %v", f.name)
  356. dir, _ := util.FullPath(f.name).DirAndName()
  357. var getErr error
  358. ctx := context.Background()
  359. if f.entry == nil {
  360. f.entry, getErr = filer_pb.GetEntry(f.fs, util.FullPath(f.name))
  361. }
  362. if f.entry == nil {
  363. return 0, getErr
  364. }
  365. if getErr != nil {
  366. return 0, getErr
  367. }
  368. if f.bufWriter.FlushFunc == nil {
  369. f.bufWriter.FlushFunc = func(data []byte, offset int64) (flushErr error) {
  370. var chunk *filer_pb.FileChunk
  371. chunk, flushErr = f.saveDataAsChunk(util.NewBytesReader(data), f.name, offset, time.Now().UnixNano())
  372. if flushErr != nil {
  373. return fmt.Errorf("%s upload result: %v", f.name, flushErr)
  374. }
  375. f.entry.Content = nil
  376. f.entry.Chunks = append(f.entry.GetChunks(), chunk)
  377. return flushErr
  378. }
  379. f.bufWriter.CloseFunc = func() error {
  380. manifestedChunks, manifestErr := filer.MaybeManifestize(f.saveDataAsChunk, f.entry.GetChunks())
  381. if manifestErr != nil {
  382. // not good, but should be ok
  383. glog.V(0).Infof("file %s close MaybeManifestize: %v", f.name, manifestErr)
  384. } else {
  385. f.entry.Chunks = manifestedChunks
  386. }
  387. flushErr := f.fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  388. f.entry.Attributes.Mtime = time.Now().Unix()
  389. request := &filer_pb.UpdateEntryRequest{
  390. Directory: dir,
  391. Entry: f.entry,
  392. Signatures: []int32{f.fs.signature},
  393. }
  394. if _, err := client.UpdateEntry(ctx, request); err != nil {
  395. return fmt.Errorf("update %s: %v", f.name, err)
  396. }
  397. return nil
  398. })
  399. return flushErr
  400. }
  401. }
  402. written, err := f.bufWriter.Write(buf)
  403. if err == nil {
  404. f.entry.Attributes.FileSize = uint64(max(f.off+int64(written), int64(f.entry.Attributes.FileSize)))
  405. glog.V(3).Infof("WebDavFileSystem.Write %v: written [%d,%d)", f.name, f.off, f.off+int64(len(buf)))
  406. f.off += int64(written)
  407. }
  408. return written, err
  409. }
  410. func (f *WebDavFile) Close() error {
  411. glog.V(2).Infof("WebDavFileSystem.Close %v", f.name)
  412. err := f.bufWriter.Close()
  413. if f.entry != nil {
  414. f.entry = nil
  415. f.visibleIntervals = nil
  416. }
  417. return err
  418. }
  419. func (f *WebDavFile) Read(p []byte) (readSize int, err error) {
  420. glog.V(2).Infof("WebDavFileSystem.Read %v", f.name)
  421. if f.entry == nil {
  422. f.entry, err = filer_pb.GetEntry(f.fs, util.FullPath(f.name))
  423. }
  424. if f.entry == nil {
  425. return 0, err
  426. }
  427. if err != nil {
  428. return 0, err
  429. }
  430. fileSize := int64(filer.FileSize(f.entry))
  431. if fileSize == 0 {
  432. return 0, io.EOF
  433. }
  434. if f.visibleIntervals == nil {
  435. f.visibleIntervals, _ = filer.NonOverlappingVisibleIntervals(filer.LookupFn(f.fs), f.entry.GetChunks(), 0, fileSize)
  436. f.reader = nil
  437. }
  438. if f.reader == nil {
  439. chunkViews := filer.ViewFromVisibleIntervals(f.visibleIntervals, 0, fileSize)
  440. f.reader = filer.NewChunkReaderAtFromClient(f.fs.readerCache, chunkViews, fileSize)
  441. }
  442. readSize, err = f.reader.ReadAt(p, f.off)
  443. glog.V(3).Infof("WebDavFileSystem.Read %v: [%d,%d)", f.name, f.off, f.off+int64(readSize))
  444. f.off += int64(readSize)
  445. if err != nil && err != io.EOF {
  446. glog.Errorf("file read %s: %v", f.name, err)
  447. }
  448. return
  449. }
  450. func (f *WebDavFile) Readdir(count int) (ret []os.FileInfo, err error) {
  451. glog.V(2).Infof("WebDavFileSystem.Readdir %v count %d", f.name, count)
  452. dir, _ := util.FullPath(f.name).DirAndName()
  453. err = filer_pb.ReadDirAllEntries(f.fs, util.FullPath(dir), "", func(entry *filer_pb.Entry, isLast bool) error {
  454. fi := FileInfo{
  455. size: int64(filer.FileSize(entry)),
  456. name: entry.Name,
  457. mode: os.FileMode(entry.Attributes.FileMode),
  458. modifiedTime: time.Unix(entry.Attributes.Mtime, 0),
  459. isDirectory: entry.IsDirectory,
  460. }
  461. if !strings.HasSuffix(fi.name, "/") && fi.IsDir() {
  462. fi.name += "/"
  463. }
  464. glog.V(4).Infof("entry: %v", fi.name)
  465. ret = append(ret, &fi)
  466. return nil
  467. })
  468. old := f.off
  469. if old >= int64(len(ret)) {
  470. if count > 0 {
  471. return nil, io.EOF
  472. }
  473. return nil, nil
  474. }
  475. if count > 0 {
  476. f.off += int64(count)
  477. if f.off > int64(len(ret)) {
  478. f.off = int64(len(ret))
  479. }
  480. } else {
  481. f.off = int64(len(ret))
  482. old = 0
  483. }
  484. return ret[old:f.off], nil
  485. }
  486. func (f *WebDavFile) Seek(offset int64, whence int) (int64, error) {
  487. glog.V(2).Infof("WebDavFile.Seek %v %v %v", f.name, offset, whence)
  488. ctx := context.Background()
  489. var err error
  490. switch whence {
  491. case io.SeekStart:
  492. f.off = 0
  493. case io.SeekEnd:
  494. if fi, err := f.fs.stat(ctx, f.name); err != nil {
  495. return 0, err
  496. } else {
  497. f.off = fi.Size()
  498. }
  499. }
  500. f.off += offset
  501. return f.off, err
  502. }
  503. func (f *WebDavFile) Stat() (os.FileInfo, error) {
  504. glog.V(2).Infof("WebDavFile.Stat %v", f.name)
  505. ctx := context.Background()
  506. return f.fs.stat(ctx, f.name)
  507. }