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.

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