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.

566 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. dir, name := util.FullPath(fullFilePath).DirAndName()
  210. return filer_pb.Remove(fs, dir, name, true, false, false)
  211. }
  212. func (fs *WebDavFileSystem) RemoveAll(ctx context.Context, name string) error {
  213. glog.V(2).Infof("WebDavFileSystem.RemoveAll %v", name)
  214. return fs.removeAll(ctx, name)
  215. }
  216. func (fs *WebDavFileSystem) Rename(ctx context.Context, oldName, newName string) error {
  217. glog.V(2).Infof("WebDavFileSystem.Rename %v to %v", oldName, newName)
  218. var err error
  219. if oldName, err = clearName(oldName); err != nil {
  220. return err
  221. }
  222. if newName, err = clearName(newName); err != nil {
  223. return err
  224. }
  225. of, err := fs.stat(ctx, oldName)
  226. if err != nil {
  227. return os.ErrExist
  228. }
  229. if of.IsDir() {
  230. if strings.HasSuffix(oldName, "/") {
  231. oldName = strings.TrimRight(oldName, "/")
  232. }
  233. if strings.HasSuffix(newName, "/") {
  234. newName = strings.TrimRight(newName, "/")
  235. }
  236. }
  237. _, err = fs.stat(ctx, newName)
  238. if err == nil {
  239. return os.ErrExist
  240. }
  241. oldDir, oldBaseName := util.FullPath(oldName).DirAndName()
  242. newDir, newBaseName := util.FullPath(newName).DirAndName()
  243. return fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  244. request := &filer_pb.AtomicRenameEntryRequest{
  245. OldDirectory: oldDir,
  246. OldName: oldBaseName,
  247. NewDirectory: newDir,
  248. NewName: newBaseName,
  249. }
  250. _, err := client.AtomicRenameEntry(ctx, request)
  251. if err != nil {
  252. return fmt.Errorf("renaming %s/%s => %s/%s: %v", oldDir, oldBaseName, newDir, newBaseName, err)
  253. }
  254. return nil
  255. })
  256. }
  257. func (fs *WebDavFileSystem) stat(ctx context.Context, fullFilePath string) (os.FileInfo, error) {
  258. var err error
  259. if fullFilePath, err = clearName(fullFilePath); err != nil {
  260. return nil, err
  261. }
  262. fullpath := util.FullPath(fullFilePath)
  263. var fi FileInfo
  264. entry, err := filer_pb.GetEntry(fs, fullpath)
  265. if entry == nil {
  266. return nil, os.ErrNotExist
  267. }
  268. if err != nil {
  269. return nil, err
  270. }
  271. fi.size = int64(filer2.TotalSize(entry.GetChunks()))
  272. fi.name = string(fullpath)
  273. fi.mode = os.FileMode(entry.Attributes.FileMode)
  274. fi.modifiledTime = time.Unix(entry.Attributes.Mtime, 0)
  275. fi.isDirectory = entry.IsDirectory
  276. if fi.name == "/" {
  277. fi.modifiledTime = time.Now()
  278. fi.isDirectory = true
  279. }
  280. return &fi, nil
  281. }
  282. func (fs *WebDavFileSystem) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  283. glog.V(2).Infof("WebDavFileSystem.Stat %v", name)
  284. return fs.stat(ctx, name)
  285. }
  286. func (f *WebDavFile) Write(buf []byte) (int, error) {
  287. glog.V(2).Infof("WebDavFileSystem.Write %v", f.name)
  288. dir, _ := util.FullPath(f.name).DirAndName()
  289. var err error
  290. ctx := context.Background()
  291. if f.entry == nil {
  292. f.entry, err = filer_pb.GetEntry(f.fs, util.FullPath(f.name))
  293. }
  294. if f.entry == nil {
  295. return 0, err
  296. }
  297. if err != nil {
  298. return 0, err
  299. }
  300. var fileId, host string
  301. var auth security.EncodedJwt
  302. var collection, replication string
  303. if err = f.fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  304. request := &filer_pb.AssignVolumeRequest{
  305. Count: 1,
  306. Replication: "",
  307. Collection: f.fs.option.Collection,
  308. ParentPath: dir,
  309. }
  310. resp, err := client.AssignVolume(ctx, request)
  311. if err != nil {
  312. glog.V(0).Infof("assign volume failure %v: %v", request, err)
  313. return err
  314. }
  315. if resp.Error != "" {
  316. return fmt.Errorf("assign volume failure %v: %v", request, resp.Error)
  317. }
  318. fileId, host, auth = resp.FileId, resp.Url, security.EncodedJwt(resp.Auth)
  319. collection, replication = resp.Collection, resp.Replication
  320. return nil
  321. }); err != nil {
  322. return 0, fmt.Errorf("filerGrpcAddress assign volume: %v", err)
  323. }
  324. fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
  325. uploadResult, err := operation.UploadData(fileUrl, f.name, f.fs.option.Cipher, buf, false, "", nil, auth)
  326. if err != nil {
  327. glog.V(0).Infof("upload data %v to %s: %v", f.name, fileUrl, err)
  328. return 0, fmt.Errorf("upload data: %v", err)
  329. }
  330. if uploadResult.Error != "" {
  331. glog.V(0).Infof("upload failure %v to %s: %v", f.name, fileUrl, err)
  332. return 0, fmt.Errorf("upload result: %v", uploadResult.Error)
  333. }
  334. chunk := &filer_pb.FileChunk{
  335. FileId: fileId,
  336. Offset: f.off,
  337. Size: uint64(len(buf)),
  338. Mtime: time.Now().UnixNano(),
  339. ETag: uploadResult.ETag,
  340. CipherKey: uploadResult.CipherKey,
  341. IsGzipped: uploadResult.Gzip > 0,
  342. }
  343. f.entry.Chunks = append(f.entry.Chunks, chunk)
  344. err = f.fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  345. f.entry.Attributes.Mtime = time.Now().Unix()
  346. f.entry.Attributes.Collection = collection
  347. f.entry.Attributes.Replication = replication
  348. request := &filer_pb.UpdateEntryRequest{
  349. Directory: dir,
  350. Entry: f.entry,
  351. }
  352. if _, err := client.UpdateEntry(ctx, request); err != nil {
  353. return fmt.Errorf("update %s: %v", f.name, err)
  354. }
  355. return nil
  356. })
  357. if err == nil {
  358. glog.V(3).Infof("WebDavFileSystem.Write %v: written [%d,%d)", f.name, f.off, f.off+int64(len(buf)))
  359. f.off += int64(len(buf))
  360. }
  361. return len(buf), err
  362. }
  363. func (f *WebDavFile) Close() error {
  364. glog.V(2).Infof("WebDavFileSystem.Close %v", f.name)
  365. if f.entry != nil {
  366. f.entry = nil
  367. f.entryViewCache = nil
  368. }
  369. return nil
  370. }
  371. func (f *WebDavFile) Read(p []byte) (readSize int, err error) {
  372. glog.V(2).Infof("WebDavFileSystem.Read %v", f.name)
  373. if f.entry == nil {
  374. f.entry, err = filer_pb.GetEntry(f.fs, util.FullPath(f.name))
  375. }
  376. if f.entry == nil {
  377. return 0, err
  378. }
  379. if err != nil {
  380. return 0, err
  381. }
  382. if len(f.entry.Chunks) == 0 {
  383. return 0, io.EOF
  384. }
  385. if f.entryViewCache == nil {
  386. f.entryViewCache = filer2.NonOverlappingVisibleIntervals(f.entry.Chunks)
  387. f.reader = nil
  388. }
  389. if f.reader == nil {
  390. chunkViews := filer2.ViewFromVisibleIntervals(f.entryViewCache, 0, math.MaxInt64)
  391. f.reader = filer2.NewChunkStreamReaderFromClient(f.fs, chunkViews)
  392. }
  393. f.reader.Seek(f.off, io.SeekStart)
  394. readSize, err = f.reader.Read(p)
  395. glog.V(3).Infof("WebDavFileSystem.Read %v: [%d,%d)", f.name, f.off, f.off+int64(readSize))
  396. f.off += int64(readSize)
  397. if err != nil {
  398. glog.Errorf("file read %s: %v", f.name, err)
  399. }
  400. return
  401. }
  402. func (f *WebDavFile) Readdir(count int) (ret []os.FileInfo, err error) {
  403. glog.V(2).Infof("WebDavFileSystem.Readdir %v count %d", f.name, count)
  404. dir, _ := util.FullPath(f.name).DirAndName()
  405. err = filer_pb.ReadDirAllEntries(f.fs, util.FullPath(dir), "", func(entry *filer_pb.Entry, isLast bool) {
  406. fi := FileInfo{
  407. size: int64(filer2.TotalSize(entry.GetChunks())),
  408. name: entry.Name,
  409. mode: os.FileMode(entry.Attributes.FileMode),
  410. modifiledTime: time.Unix(entry.Attributes.Mtime, 0),
  411. isDirectory: entry.IsDirectory,
  412. }
  413. if !strings.HasSuffix(fi.name, "/") && fi.IsDir() {
  414. fi.name += "/"
  415. }
  416. glog.V(4).Infof("entry: %v", fi.name)
  417. ret = append(ret, &fi)
  418. })
  419. old := f.off
  420. if old >= int64(len(ret)) {
  421. if count > 0 {
  422. return nil, io.EOF
  423. }
  424. return nil, nil
  425. }
  426. if count > 0 {
  427. f.off += int64(count)
  428. if f.off > int64(len(ret)) {
  429. f.off = int64(len(ret))
  430. }
  431. } else {
  432. f.off = int64(len(ret))
  433. old = 0
  434. }
  435. return ret[old:f.off], nil
  436. }
  437. func (f *WebDavFile) Seek(offset int64, whence int) (int64, error) {
  438. glog.V(2).Infof("WebDavFile.Seek %v %v %v", f.name, offset, whence)
  439. ctx := context.Background()
  440. var err error
  441. switch whence {
  442. case 0:
  443. f.off = 0
  444. case 2:
  445. if fi, err := f.fs.stat(ctx, f.name); err != nil {
  446. return 0, err
  447. } else {
  448. f.off = fi.Size()
  449. }
  450. }
  451. f.off += offset
  452. return f.off, err
  453. }
  454. func (f *WebDavFile) Stat() (os.FileInfo, error) {
  455. glog.V(2).Infof("WebDavFile.Stat %v", f.name)
  456. ctx := context.Background()
  457. return f.fs.stat(ctx, f.name)
  458. }