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.

616 lines
15 KiB

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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "math"
  8. "os"
  9. "path"
  10. "strings"
  11. "time"
  12. "github.com/chrislusf/seaweedfs/weed/util/buffered_writer"
  13. "golang.org/x/net/webdav"
  14. "google.golang.org/grpc"
  15. "github.com/chrislusf/seaweedfs/weed/operation"
  16. "github.com/chrislusf/seaweedfs/weed/pb"
  17. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  18. "github.com/chrislusf/seaweedfs/weed/util"
  19. "github.com/chrislusf/seaweedfs/weed/util/chunk_cache"
  20. "github.com/chrislusf/seaweedfs/weed/filer"
  21. "github.com/chrislusf/seaweedfs/weed/glog"
  22. "github.com/chrislusf/seaweedfs/weed/security"
  23. )
  24. type WebDavOption struct {
  25. Filer string
  26. FilerGrpcAddress string
  27. DomainName string
  28. BucketsPath string
  29. GrpcDialOption grpc.DialOption
  30. Collection 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 NewWebDavServer(option *WebDavOption) (ws *WebDavServer, err error) {
  45. fs, _ := NewWebDavFileSystem(option)
  46. ws = &WebDavServer{
  47. option: option,
  48. grpcDialOption: security.LoadClientTLS(util.GetViper(), "grpc.filer"),
  49. Handler: &webdav.Handler{
  50. FileSystem: fs,
  51. LockSystem: webdav.NewMemLS(),
  52. },
  53. }
  54. return ws, nil
  55. }
  56. // adapted from https://github.com/mattn/davfs/blob/master/plugin/mysql/mysql.go
  57. type WebDavFileSystem struct {
  58. option *WebDavOption
  59. secret security.SigningKey
  60. filer *filer.Filer
  61. grpcDialOption grpc.DialOption
  62. chunkCache *chunk_cache.TieredChunkCache
  63. signature int32
  64. }
  65. type FileInfo struct {
  66. name string
  67. size int64
  68. mode os.FileMode
  69. modifiledTime time.Time
  70. isDirectory bool
  71. }
  72. func (fi *FileInfo) Name() string { return fi.name }
  73. func (fi *FileInfo) Size() int64 { return fi.size }
  74. func (fi *FileInfo) Mode() os.FileMode { return fi.mode }
  75. func (fi *FileInfo) ModTime() time.Time { return fi.modifiledTime }
  76. func (fi *FileInfo) IsDir() bool { return fi.isDirectory }
  77. func (fi *FileInfo) Sys() interface{} { return nil }
  78. type WebDavFile struct {
  79. fs *WebDavFileSystem
  80. name string
  81. isDirectory bool
  82. off int64
  83. entry *filer_pb.Entry
  84. entryViewCache []filer.VisibleInterval
  85. reader io.ReaderAt
  86. bufWriter *buffered_writer.BufferedWriteCloser
  87. collection string
  88. replication string
  89. }
  90. func NewWebDavFileSystem(option *WebDavOption) (webdav.FileSystem, error) {
  91. cacheUniqueId := util.Md5String([]byte("webdav" + option.FilerGrpcAddress + util.Version()))[0:8]
  92. cacheDir := path.Join(option.CacheDir, cacheUniqueId)
  93. chunkCache := chunk_cache.NewTieredChunkCache(256, cacheDir, option.CacheSizeMB, 1024*1024)
  94. return &WebDavFileSystem{
  95. option: option,
  96. chunkCache: chunkCache,
  97. signature: util.RandomInt32(),
  98. }, nil
  99. }
  100. var _ = filer_pb.FilerClient(&WebDavFileSystem{})
  101. func (fs *WebDavFileSystem) WithFilerClient(fn func(filer_pb.SeaweedFilerClient) error) error {
  102. return pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  103. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  104. return fn(client)
  105. }, fs.option.FilerGrpcAddress, fs.option.GrpcDialOption)
  106. }
  107. func (fs *WebDavFileSystem) AdjustedUrl(location *filer_pb.Location) string {
  108. return location.Url
  109. }
  110. func clearName(name string) (string, error) {
  111. slashed := strings.HasSuffix(name, "/")
  112. name = path.Clean(name)
  113. if !strings.HasSuffix(name, "/") && slashed {
  114. name += "/"
  115. }
  116. if !strings.HasPrefix(name, "/") {
  117. return "", os.ErrInvalid
  118. }
  119. return name, nil
  120. }
  121. func (fs *WebDavFileSystem) Mkdir(ctx context.Context, fullDirPath string, perm os.FileMode) error {
  122. glog.V(2).Infof("WebDavFileSystem.Mkdir %v", fullDirPath)
  123. if !strings.HasSuffix(fullDirPath, "/") {
  124. fullDirPath += "/"
  125. }
  126. var err error
  127. if fullDirPath, err = clearName(fullDirPath); err != nil {
  128. return err
  129. }
  130. _, err = fs.stat(ctx, fullDirPath)
  131. if err == nil {
  132. return os.ErrExist
  133. }
  134. return fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  135. dir, name := util.FullPath(fullDirPath).DirAndName()
  136. request := &filer_pb.CreateEntryRequest{
  137. Directory: dir,
  138. Entry: &filer_pb.Entry{
  139. Name: name,
  140. IsDirectory: true,
  141. Attributes: &filer_pb.FuseAttributes{
  142. Mtime: time.Now().Unix(),
  143. Crtime: time.Now().Unix(),
  144. FileMode: uint32(perm | os.ModeDir),
  145. Uid: fs.option.Uid,
  146. Gid: fs.option.Gid,
  147. },
  148. },
  149. Signatures: []int32{fs.signature},
  150. }
  151. glog.V(1).Infof("mkdir: %v", request)
  152. if err := filer_pb.CreateEntry(client, request); err != nil {
  153. return fmt.Errorf("mkdir %s/%s: %v", dir, name, err)
  154. }
  155. return nil
  156. })
  157. }
  158. func (fs *WebDavFileSystem) OpenFile(ctx context.Context, fullFilePath string, flag int, perm os.FileMode) (webdav.File, error) {
  159. glog.V(2).Infof("WebDavFileSystem.OpenFile %v %x", fullFilePath, flag)
  160. var err error
  161. if fullFilePath, err = clearName(fullFilePath); err != nil {
  162. return nil, err
  163. }
  164. if flag&os.O_CREATE != 0 {
  165. // file should not have / suffix.
  166. if strings.HasSuffix(fullFilePath, "/") {
  167. return nil, os.ErrInvalid
  168. }
  169. _, err = fs.stat(ctx, fullFilePath)
  170. if err == nil {
  171. if flag&os.O_EXCL != 0 {
  172. return nil, os.ErrExist
  173. }
  174. fs.removeAll(ctx, fullFilePath)
  175. }
  176. dir, name := util.FullPath(fullFilePath).DirAndName()
  177. err = fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  178. if err := filer_pb.CreateEntry(client, &filer_pb.CreateEntryRequest{
  179. Directory: dir,
  180. Entry: &filer_pb.Entry{
  181. Name: name,
  182. IsDirectory: perm&os.ModeDir > 0,
  183. Attributes: &filer_pb.FuseAttributes{
  184. Mtime: time.Now().Unix(),
  185. Crtime: time.Now().Unix(),
  186. FileMode: uint32(perm),
  187. Uid: fs.option.Uid,
  188. Gid: fs.option.Gid,
  189. Collection: fs.option.Collection,
  190. Replication: "000",
  191. TtlSec: 0,
  192. },
  193. },
  194. Signatures: []int32{fs.signature},
  195. }); err != nil {
  196. return fmt.Errorf("create %s: %v", fullFilePath, err)
  197. }
  198. return nil
  199. })
  200. if err != nil {
  201. return nil, err
  202. }
  203. return &WebDavFile{
  204. fs: fs,
  205. name: fullFilePath,
  206. isDirectory: false,
  207. bufWriter: buffered_writer.NewBufferedWriteCloser(4 * 1024 * 1024),
  208. }, nil
  209. }
  210. fi, err := fs.stat(ctx, fullFilePath)
  211. if err != nil {
  212. return nil, os.ErrNotExist
  213. }
  214. if !strings.HasSuffix(fullFilePath, "/") && fi.IsDir() {
  215. fullFilePath += "/"
  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. func (fs *WebDavFileSystem) removeAll(ctx context.Context, fullFilePath string) error {
  225. var err error
  226. if fullFilePath, err = clearName(fullFilePath); err != nil {
  227. return err
  228. }
  229. dir, name := util.FullPath(fullFilePath).DirAndName()
  230. return filer_pb.Remove(fs, dir, name, true, false, false, false, []int32{fs.signature})
  231. }
  232. func (fs *WebDavFileSystem) RemoveAll(ctx context.Context, name string) error {
  233. glog.V(2).Infof("WebDavFileSystem.RemoveAll %v", name)
  234. return fs.removeAll(ctx, name)
  235. }
  236. func (fs *WebDavFileSystem) Rename(ctx context.Context, oldName, newName string) error {
  237. glog.V(2).Infof("WebDavFileSystem.Rename %v to %v", oldName, newName)
  238. var err error
  239. if oldName, err = clearName(oldName); err != nil {
  240. return err
  241. }
  242. if newName, err = clearName(newName); err != nil {
  243. return err
  244. }
  245. of, err := fs.stat(ctx, oldName)
  246. if err != nil {
  247. return os.ErrExist
  248. }
  249. if of.IsDir() {
  250. if strings.HasSuffix(oldName, "/") {
  251. oldName = strings.TrimRight(oldName, "/")
  252. }
  253. if strings.HasSuffix(newName, "/") {
  254. newName = strings.TrimRight(newName, "/")
  255. }
  256. }
  257. _, err = fs.stat(ctx, newName)
  258. if err == nil {
  259. return os.ErrExist
  260. }
  261. oldDir, oldBaseName := util.FullPath(oldName).DirAndName()
  262. newDir, newBaseName := util.FullPath(newName).DirAndName()
  263. return fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  264. request := &filer_pb.AtomicRenameEntryRequest{
  265. OldDirectory: oldDir,
  266. OldName: oldBaseName,
  267. NewDirectory: newDir,
  268. NewName: newBaseName,
  269. }
  270. _, err := client.AtomicRenameEntry(ctx, request)
  271. if err != nil {
  272. return fmt.Errorf("renaming %s/%s => %s/%s: %v", oldDir, oldBaseName, newDir, newBaseName, err)
  273. }
  274. return nil
  275. })
  276. }
  277. func (fs *WebDavFileSystem) stat(ctx context.Context, fullFilePath string) (os.FileInfo, error) {
  278. var err error
  279. if fullFilePath, err = clearName(fullFilePath); err != nil {
  280. return nil, err
  281. }
  282. fullpath := util.FullPath(fullFilePath)
  283. var fi FileInfo
  284. entry, err := filer_pb.GetEntry(fs, fullpath)
  285. if entry == nil {
  286. return nil, os.ErrNotExist
  287. }
  288. if err != nil {
  289. return nil, err
  290. }
  291. fi.size = int64(filer.FileSize(entry))
  292. fi.name = string(fullpath)
  293. fi.mode = os.FileMode(entry.Attributes.FileMode)
  294. fi.modifiledTime = time.Unix(entry.Attributes.Mtime, 0)
  295. fi.isDirectory = entry.IsDirectory
  296. if fi.name == "/" {
  297. fi.modifiledTime = time.Now()
  298. fi.isDirectory = true
  299. }
  300. return &fi, nil
  301. }
  302. func (fs *WebDavFileSystem) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  303. glog.V(2).Infof("WebDavFileSystem.Stat %v", name)
  304. return fs.stat(ctx, name)
  305. }
  306. func (f *WebDavFile) saveDataAsChunk(reader io.Reader, name string, offset int64) (chunk *filer_pb.FileChunk, collection, replication string, err error) {
  307. var fileId, host string
  308. var auth security.EncodedJwt
  309. if flushErr := f.fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  310. ctx := context.Background()
  311. request := &filer_pb.AssignVolumeRequest{
  312. Count: 1,
  313. Replication: "",
  314. Collection: f.fs.option.Collection,
  315. Path: name,
  316. }
  317. resp, err := client.AssignVolume(ctx, request)
  318. if err != nil {
  319. glog.V(0).Infof("assign volume failure %v: %v", request, err)
  320. return err
  321. }
  322. if resp.Error != "" {
  323. return fmt.Errorf("assign volume failure %v: %v", request, resp.Error)
  324. }
  325. fileId, host, auth = resp.FileId, resp.Url, security.EncodedJwt(resp.Auth)
  326. f.collection, f.replication = resp.Collection, resp.Replication
  327. return nil
  328. }); flushErr != nil {
  329. return nil, f.collection, f.replication, fmt.Errorf("filerGrpcAddress assign volume: %v", flushErr)
  330. }
  331. fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
  332. uploadResult, flushErr, _ := operation.Upload(fileUrl, f.name, f.fs.option.Cipher, reader, false, "", nil, auth)
  333. if flushErr != nil {
  334. glog.V(0).Infof("upload data %v to %s: %v", f.name, fileUrl, flushErr)
  335. return nil, f.collection, f.replication, fmt.Errorf("upload data: %v", flushErr)
  336. }
  337. if uploadResult.Error != "" {
  338. glog.V(0).Infof("upload failure %v to %s: %v", f.name, fileUrl, flushErr)
  339. return nil, f.collection, f.replication, fmt.Errorf("upload result: %v", uploadResult.Error)
  340. }
  341. return uploadResult.ToPbFileChunk(fileId, offset), f.collection, f.replication, nil
  342. }
  343. func (f *WebDavFile) Write(buf []byte) (int, error) {
  344. glog.V(2).Infof("WebDavFileSystem.Write %v", f.name)
  345. dir, _ := util.FullPath(f.name).DirAndName()
  346. var getErr error
  347. ctx := context.Background()
  348. if f.entry == nil {
  349. f.entry, getErr = filer_pb.GetEntry(f.fs, util.FullPath(f.name))
  350. }
  351. if f.entry == nil {
  352. return 0, getErr
  353. }
  354. if getErr != nil {
  355. return 0, getErr
  356. }
  357. if f.bufWriter.FlushFunc == nil {
  358. f.bufWriter.FlushFunc = func(data []byte, offset int64) (flushErr error) {
  359. var chunk *filer_pb.FileChunk
  360. chunk, f.collection, f.replication, flushErr = f.saveDataAsChunk(bytes.NewReader(data), f.name, offset)
  361. if flushErr != nil {
  362. return fmt.Errorf("%s upload result: %v", f.name, flushErr)
  363. }
  364. f.entry.Content = nil
  365. f.entry.Chunks = append(f.entry.Chunks, chunk)
  366. return flushErr
  367. }
  368. f.bufWriter.CloseFunc = func() error {
  369. manifestedChunks, manifestErr := filer.MaybeManifestize(f.saveDataAsChunk, f.entry.Chunks)
  370. if manifestErr != nil {
  371. // not good, but should be ok
  372. glog.V(0).Infof("file %s close MaybeManifestize: %v", f.name, manifestErr)
  373. } else {
  374. f.entry.Chunks = manifestedChunks
  375. }
  376. flushErr := f.fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  377. f.entry.Attributes.Mtime = time.Now().Unix()
  378. f.entry.Attributes.Collection = f.collection
  379. f.entry.Attributes.Replication = f.replication
  380. request := &filer_pb.UpdateEntryRequest{
  381. Directory: dir,
  382. Entry: f.entry,
  383. Signatures: []int32{f.fs.signature},
  384. }
  385. if _, err := client.UpdateEntry(ctx, request); err != nil {
  386. return fmt.Errorf("update %s: %v", f.name, err)
  387. }
  388. return nil
  389. })
  390. return flushErr
  391. }
  392. }
  393. written, err := f.bufWriter.Write(buf)
  394. if err == nil {
  395. glog.V(3).Infof("WebDavFileSystem.Write %v: written [%d,%d)", f.name, f.off, f.off+int64(len(buf)))
  396. f.off += int64(written)
  397. }
  398. return written, err
  399. }
  400. func (f *WebDavFile) Close() error {
  401. glog.V(2).Infof("WebDavFileSystem.Close %v", f.name)
  402. err := f.bufWriter.Close()
  403. if f.entry != nil {
  404. f.entry = nil
  405. f.entryViewCache = nil
  406. }
  407. return err
  408. }
  409. func (f *WebDavFile) Read(p []byte) (readSize int, err error) {
  410. glog.V(2).Infof("WebDavFileSystem.Read %v", f.name)
  411. if f.entry == nil {
  412. f.entry, err = filer_pb.GetEntry(f.fs, util.FullPath(f.name))
  413. }
  414. if f.entry == nil {
  415. return 0, err
  416. }
  417. if err != nil {
  418. return 0, err
  419. }
  420. fileSize := int64(filer.FileSize(f.entry))
  421. if fileSize == 0 {
  422. return 0, io.EOF
  423. }
  424. if f.entryViewCache == nil {
  425. f.entryViewCache, _ = filer.NonOverlappingVisibleIntervals(filer.LookupFn(f.fs), f.entry.Chunks)
  426. f.reader = nil
  427. }
  428. if f.reader == nil {
  429. chunkViews := filer.ViewFromVisibleIntervals(f.entryViewCache, 0, math.MaxInt64)
  430. f.reader = filer.NewChunkReaderAtFromClient(filer.LookupFn(f.fs), chunkViews, f.fs.chunkCache, fileSize)
  431. }
  432. readSize, err = f.reader.ReadAt(p, f.off)
  433. glog.V(3).Infof("WebDavFileSystem.Read %v: [%d,%d)", f.name, f.off, f.off+int64(readSize))
  434. f.off += int64(readSize)
  435. if err != nil && err != io.EOF {
  436. glog.Errorf("file read %s: %v", f.name, err)
  437. }
  438. return
  439. }
  440. func (f *WebDavFile) Readdir(count int) (ret []os.FileInfo, err error) {
  441. glog.V(2).Infof("WebDavFileSystem.Readdir %v count %d", f.name, count)
  442. dir, _ := util.FullPath(f.name).DirAndName()
  443. err = filer_pb.ReadDirAllEntries(f.fs, util.FullPath(dir), "", func(entry *filer_pb.Entry, isLast bool) error {
  444. fi := FileInfo{
  445. size: int64(filer.FileSize(entry)),
  446. name: entry.Name,
  447. mode: os.FileMode(entry.Attributes.FileMode),
  448. modifiledTime: time.Unix(entry.Attributes.Mtime, 0),
  449. isDirectory: entry.IsDirectory,
  450. }
  451. if !strings.HasSuffix(fi.name, "/") && fi.IsDir() {
  452. fi.name += "/"
  453. }
  454. glog.V(4).Infof("entry: %v", fi.name)
  455. ret = append(ret, &fi)
  456. return nil
  457. })
  458. old := f.off
  459. if old >= int64(len(ret)) {
  460. if count > 0 {
  461. return nil, io.EOF
  462. }
  463. return nil, nil
  464. }
  465. if count > 0 {
  466. f.off += int64(count)
  467. if f.off > int64(len(ret)) {
  468. f.off = int64(len(ret))
  469. }
  470. } else {
  471. f.off = int64(len(ret))
  472. old = 0
  473. }
  474. return ret[old:f.off], nil
  475. }
  476. func (f *WebDavFile) Seek(offset int64, whence int) (int64, error) {
  477. glog.V(2).Infof("WebDavFile.Seek %v %v %v", f.name, offset, whence)
  478. ctx := context.Background()
  479. var err error
  480. switch whence {
  481. case io.SeekStart:
  482. f.off = 0
  483. case io.SeekEnd:
  484. if fi, err := f.fs.stat(ctx, f.name); err != nil {
  485. return 0, err
  486. } else {
  487. f.off = fi.Size()
  488. }
  489. }
  490. f.off += offset
  491. return f.off, err
  492. }
  493. func (f *WebDavFile) Stat() (os.FileInfo, error) {
  494. glog.V(2).Infof("WebDavFile.Stat %v", f.name)
  495. ctx := context.Background()
  496. return f.fs.stat(ctx, f.name)
  497. }