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.

617 lines
16 KiB

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