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.

585 lines
14 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
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  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. }
  31. type WebDavServer struct {
  32. option *WebDavOption
  33. secret security.SigningKey
  34. filer *filer2.Filer
  35. grpcDialOption grpc.DialOption
  36. Handler *webdav.Handler
  37. }
  38. func NewWebDavServer(option *WebDavOption) (ws *WebDavServer, err error) {
  39. fs, _ := NewWebDavFileSystem(option)
  40. ws = &WebDavServer{
  41. option: option,
  42. grpcDialOption: security.LoadClientTLS(util.GetViper(), "grpc.filer"),
  43. Handler: &webdav.Handler{
  44. FileSystem: fs,
  45. LockSystem: webdav.NewMemLS(),
  46. },
  47. }
  48. return ws, nil
  49. }
  50. // adapted from https://github.com/mattn/davfs/blob/master/plugin/mysql/mysql.go
  51. type WebDavFileSystem struct {
  52. option *WebDavOption
  53. secret security.SigningKey
  54. filer *filer2.Filer
  55. grpcDialOption grpc.DialOption
  56. }
  57. type FileInfo struct {
  58. name string
  59. size int64
  60. mode os.FileMode
  61. modifiledTime time.Time
  62. isDirectory bool
  63. }
  64. func (fi *FileInfo) Name() string { return fi.name }
  65. func (fi *FileInfo) Size() int64 { return fi.size }
  66. func (fi *FileInfo) Mode() os.FileMode { return fi.mode }
  67. func (fi *FileInfo) ModTime() time.Time { return fi.modifiledTime }
  68. func (fi *FileInfo) IsDir() bool { return fi.isDirectory }
  69. func (fi *FileInfo) Sys() interface{} { return nil }
  70. type WebDavFile struct {
  71. fs *WebDavFileSystem
  72. name string
  73. isDirectory bool
  74. off int64
  75. entry *filer_pb.Entry
  76. entryViewCache []filer2.VisibleInterval
  77. }
  78. func NewWebDavFileSystem(option *WebDavOption) (webdav.FileSystem, error) {
  79. return &WebDavFileSystem{
  80. option: option,
  81. }, nil
  82. }
  83. func (fs *WebDavFileSystem) WithFilerClient(fn func(filer_pb.SeaweedFilerClient) error) error {
  84. return pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  85. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  86. return fn(client)
  87. }, fs.option.FilerGrpcAddress, fs.option.GrpcDialOption)
  88. }
  89. func (fs *WebDavFileSystem) AdjustedUrl(hostAndPort string) string {
  90. return hostAndPort
  91. }
  92. func clearName(name string) (string, error) {
  93. slashed := strings.HasSuffix(name, "/")
  94. name = path.Clean(name)
  95. if !strings.HasSuffix(name, "/") && slashed {
  96. name += "/"
  97. }
  98. if !strings.HasPrefix(name, "/") {
  99. return "", os.ErrInvalid
  100. }
  101. return name, nil
  102. }
  103. func (fs *WebDavFileSystem) Mkdir(ctx context.Context, fullDirPath string, perm os.FileMode) error {
  104. glog.V(2).Infof("WebDavFileSystem.Mkdir %v", fullDirPath)
  105. if !strings.HasSuffix(fullDirPath, "/") {
  106. fullDirPath += "/"
  107. }
  108. var err error
  109. if fullDirPath, err = clearName(fullDirPath); err != nil {
  110. return err
  111. }
  112. _, err = fs.stat(ctx, fullDirPath)
  113. if err == nil {
  114. return os.ErrExist
  115. }
  116. return fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  117. dir, name := filer2.FullPath(fullDirPath).DirAndName()
  118. request := &filer_pb.CreateEntryRequest{
  119. Directory: dir,
  120. Entry: &filer_pb.Entry{
  121. Name: name,
  122. IsDirectory: true,
  123. Attributes: &filer_pb.FuseAttributes{
  124. Mtime: time.Now().Unix(),
  125. Crtime: time.Now().Unix(),
  126. FileMode: uint32(perm | os.ModeDir),
  127. Uid: fs.option.Uid,
  128. Gid: fs.option.Gid,
  129. },
  130. },
  131. }
  132. glog.V(1).Infof("mkdir: %v", request)
  133. if err := filer_pb.CreateEntry(client, request); err != nil {
  134. return fmt.Errorf("mkdir %s/%s: %v", dir, name, err)
  135. }
  136. return nil
  137. })
  138. }
  139. func (fs *WebDavFileSystem) OpenFile(ctx context.Context, fullFilePath string, flag int, perm os.FileMode) (webdav.File, error) {
  140. glog.V(2).Infof("WebDavFileSystem.OpenFile %v %x", fullFilePath, flag)
  141. var err error
  142. if fullFilePath, err = clearName(fullFilePath); err != nil {
  143. return nil, err
  144. }
  145. if flag&os.O_CREATE != 0 {
  146. // file should not have / suffix.
  147. if strings.HasSuffix(fullFilePath, "/") {
  148. return nil, os.ErrInvalid
  149. }
  150. _, err = fs.stat(ctx, fullFilePath)
  151. if err == nil {
  152. if flag&os.O_EXCL != 0 {
  153. return nil, os.ErrExist
  154. }
  155. fs.removeAll(ctx, fullFilePath)
  156. }
  157. dir, name := filer2.FullPath(fullFilePath).DirAndName()
  158. err = fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  159. if err := filer_pb.CreateEntry(client, &filer_pb.CreateEntryRequest{
  160. Directory: dir,
  161. Entry: &filer_pb.Entry{
  162. Name: name,
  163. IsDirectory: perm&os.ModeDir > 0,
  164. Attributes: &filer_pb.FuseAttributes{
  165. Mtime: time.Now().Unix(),
  166. Crtime: time.Now().Unix(),
  167. FileMode: uint32(perm),
  168. Uid: fs.option.Uid,
  169. Gid: fs.option.Gid,
  170. Collection: fs.option.Collection,
  171. Replication: "000",
  172. TtlSec: 0,
  173. },
  174. },
  175. }); err != nil {
  176. return fmt.Errorf("create %s: %v", fullFilePath, err)
  177. }
  178. return nil
  179. })
  180. if err != nil {
  181. return nil, err
  182. }
  183. return &WebDavFile{
  184. fs: fs,
  185. name: fullFilePath,
  186. isDirectory: false,
  187. }, nil
  188. }
  189. fi, err := fs.stat(ctx, fullFilePath)
  190. if err != nil {
  191. return nil, os.ErrNotExist
  192. }
  193. if !strings.HasSuffix(fullFilePath, "/") && fi.IsDir() {
  194. fullFilePath += "/"
  195. }
  196. return &WebDavFile{
  197. fs: fs,
  198. name: fullFilePath,
  199. isDirectory: false,
  200. }, nil
  201. }
  202. func (fs *WebDavFileSystem) removeAll(ctx context.Context, fullFilePath string) error {
  203. var err error
  204. if fullFilePath, err = clearName(fullFilePath); err != nil {
  205. return err
  206. }
  207. fi, err := fs.stat(ctx, fullFilePath)
  208. if err != nil {
  209. return err
  210. }
  211. if fi.IsDir() {
  212. //_, err = fs.db.Exec(`delete from filesystem where fullFilePath like $1 escape '\'`, strings.Replace(fullFilePath, `%`, `\%`, -1)+`%`)
  213. } else {
  214. //_, err = fs.db.Exec(`delete from filesystem where fullFilePath = ?`, fullFilePath)
  215. }
  216. dir, name := filer2.FullPath(fullFilePath).DirAndName()
  217. err = fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  218. request := &filer_pb.DeleteEntryRequest{
  219. Directory: dir,
  220. Name: name,
  221. IsDeleteData: true,
  222. }
  223. glog.V(3).Infof("removing entry: %v", request)
  224. _, err := client.DeleteEntry(ctx, request)
  225. if err != nil {
  226. return fmt.Errorf("remove %s: %v", fullFilePath, err)
  227. }
  228. return nil
  229. })
  230. return err
  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 := filer2.FullPath(oldName).DirAndName()
  262. newDir, newBaseName := filer2.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 := filer2.FullPath(fullFilePath)
  283. var fi FileInfo
  284. entry, err := filer2.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(filer2.TotalSize(entry.GetChunks()))
  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) Write(buf []byte) (int, error) {
  307. glog.V(2).Infof("WebDavFileSystem.Write %v", f.name)
  308. dir, _ := filer2.FullPath(f.name).DirAndName()
  309. var err error
  310. ctx := context.Background()
  311. if f.entry == nil {
  312. f.entry, err = filer2.GetEntry(f.fs, filer2.FullPath(f.name))
  313. }
  314. if f.entry == nil {
  315. return 0, err
  316. }
  317. if err != nil {
  318. return 0, err
  319. }
  320. var fileId, host string
  321. var auth security.EncodedJwt
  322. var collection, replication string
  323. if err = f.fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  324. request := &filer_pb.AssignVolumeRequest{
  325. Count: 1,
  326. Replication: "",
  327. Collection: f.fs.option.Collection,
  328. ParentPath: dir,
  329. }
  330. resp, err := client.AssignVolume(ctx, request)
  331. if err != nil {
  332. glog.V(0).Infof("assign volume failure %v: %v", request, err)
  333. return err
  334. }
  335. if resp.Error != "" {
  336. return fmt.Errorf("assign volume failure %v: %v", request, resp.Error)
  337. }
  338. fileId, host, auth = resp.FileId, resp.Url, security.EncodedJwt(resp.Auth)
  339. collection, replication = resp.Collection, resp.Replication
  340. return nil
  341. }); err != nil {
  342. return 0, fmt.Errorf("filerGrpcAddress assign volume: %v", err)
  343. }
  344. fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
  345. bufReader := bytes.NewReader(buf)
  346. uploadResult, err := operation.Upload(fileUrl, f.name, bufReader, false, "", nil, auth)
  347. if err != nil {
  348. glog.V(0).Infof("upload data %v to %s: %v", f.name, fileUrl, err)
  349. return 0, fmt.Errorf("upload data: %v", err)
  350. }
  351. if uploadResult.Error != "" {
  352. glog.V(0).Infof("upload failure %v to %s: %v", f.name, fileUrl, err)
  353. return 0, fmt.Errorf("upload result: %v", uploadResult.Error)
  354. }
  355. chunk := &filer_pb.FileChunk{
  356. FileId: fileId,
  357. Offset: f.off,
  358. Size: uint64(len(buf)),
  359. Mtime: time.Now().UnixNano(),
  360. ETag: uploadResult.ETag,
  361. }
  362. f.entry.Chunks = append(f.entry.Chunks, chunk)
  363. err = f.fs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  364. f.entry.Attributes.Mtime = time.Now().Unix()
  365. f.entry.Attributes.Collection = collection
  366. f.entry.Attributes.Replication = replication
  367. request := &filer_pb.UpdateEntryRequest{
  368. Directory: dir,
  369. Entry: f.entry,
  370. }
  371. if _, err := client.UpdateEntry(ctx, request); err != nil {
  372. return fmt.Errorf("update %s: %v", f.name, err)
  373. }
  374. return nil
  375. })
  376. if err == nil {
  377. glog.V(3).Infof("WebDavFileSystem.Write %v: written [%d,%d)", f.name, f.off, f.off+int64(len(buf)))
  378. f.off += int64(len(buf))
  379. }
  380. return len(buf), err
  381. }
  382. func (f *WebDavFile) Close() error {
  383. glog.V(2).Infof("WebDavFileSystem.Close %v", f.name)
  384. if f.entry != nil {
  385. f.entry = nil
  386. f.entryViewCache = nil
  387. }
  388. return nil
  389. }
  390. func (f *WebDavFile) Read(p []byte) (readSize int, err error) {
  391. glog.V(2).Infof("WebDavFileSystem.Read %v", f.name)
  392. if f.entry == nil {
  393. f.entry, err = filer2.GetEntry(f.fs, filer2.FullPath(f.name))
  394. }
  395. if f.entry == nil {
  396. return 0, err
  397. }
  398. if err != nil {
  399. return 0, err
  400. }
  401. if len(f.entry.Chunks) == 0 {
  402. return 0, io.EOF
  403. }
  404. if f.entryViewCache == nil {
  405. f.entryViewCache = filer2.NonOverlappingVisibleIntervals(f.entry.Chunks)
  406. }
  407. chunkViews := filer2.ViewFromVisibleIntervals(f.entryViewCache, f.off, len(p))
  408. totalRead, err := filer2.ReadIntoBuffer(f.fs, filer2.FullPath(f.name), p, chunkViews, f.off)
  409. if err != nil {
  410. return 0, err
  411. }
  412. readSize = int(totalRead)
  413. glog.V(3).Infof("WebDavFileSystem.Read %v: [%d,%d)", f.name, f.off, f.off+totalRead)
  414. f.off += totalRead
  415. if readSize == 0 {
  416. return 0, io.EOF
  417. }
  418. return
  419. }
  420. func (f *WebDavFile) Readdir(count int) (ret []os.FileInfo, err error) {
  421. glog.V(2).Infof("WebDavFileSystem.Readdir %v count %d", f.name, count)
  422. dir, _ := filer2.FullPath(f.name).DirAndName()
  423. err = filer2.ReadDirAllEntries(f.fs, filer2.FullPath(dir), "", func(entry *filer_pb.Entry, isLast bool) {
  424. fi := FileInfo{
  425. size: int64(filer2.TotalSize(entry.GetChunks())),
  426. name: entry.Name,
  427. mode: os.FileMode(entry.Attributes.FileMode),
  428. modifiledTime: time.Unix(entry.Attributes.Mtime, 0),
  429. isDirectory: entry.IsDirectory,
  430. }
  431. if !strings.HasSuffix(fi.name, "/") && fi.IsDir() {
  432. fi.name += "/"
  433. }
  434. glog.V(4).Infof("entry: %v", fi.name)
  435. ret = append(ret, &fi)
  436. })
  437. old := f.off
  438. if old >= int64(len(ret)) {
  439. if count > 0 {
  440. return nil, io.EOF
  441. }
  442. return nil, nil
  443. }
  444. if count > 0 {
  445. f.off += int64(count)
  446. if f.off > int64(len(ret)) {
  447. f.off = int64(len(ret))
  448. }
  449. } else {
  450. f.off = int64(len(ret))
  451. old = 0
  452. }
  453. return ret[old:f.off], nil
  454. }
  455. func (f *WebDavFile) Seek(offset int64, whence int) (int64, error) {
  456. glog.V(2).Infof("WebDavFile.Seek %v %v %v", f.name, offset, whence)
  457. ctx := context.Background()
  458. var err error
  459. switch whence {
  460. case 0:
  461. f.off = 0
  462. case 2:
  463. if fi, err := f.fs.stat(ctx, f.name); err != nil {
  464. return 0, err
  465. } else {
  466. f.off = fi.Size()
  467. }
  468. }
  469. f.off += offset
  470. return f.off, err
  471. }
  472. func (f *WebDavFile) Stat() (os.FileInfo, error) {
  473. glog.V(2).Infof("WebDavFile.Stat %v", f.name)
  474. ctx := context.Background()
  475. return f.fs.stat(ctx, f.name)
  476. }