webdav_server.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. }