remote_storage.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package remote_storage
  2. import (
  3. "fmt"
  4. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  5. "io"
  6. "strings"
  7. "sync"
  8. )
  9. func ParseLocation(remote string) (loc *filer_pb.RemoteStorageLocation) {
  10. loc = &filer_pb.RemoteStorageLocation{}
  11. if strings.HasSuffix(string(remote), "/") {
  12. remote = remote[:len(remote)-1]
  13. }
  14. parts := strings.SplitN(string(remote), "/", 3)
  15. if len(parts) >= 1 {
  16. loc.Name = parts[0]
  17. }
  18. if len(parts) >= 2 {
  19. loc.Bucket = parts[1]
  20. }
  21. loc.Path = string(remote[len(loc.Name)+1+len(loc.Bucket):])
  22. if loc.Path == "" {
  23. loc.Path = "/"
  24. }
  25. return
  26. }
  27. type VisitFunc func(dir string, name string, isDirectory bool, remoteEntry *filer_pb.RemoteEntry) error
  28. type RemoteStorageClient interface {
  29. Traverse(loc *filer_pb.RemoteStorageLocation, visitFn VisitFunc) error
  30. ReadFile(loc *filer_pb.RemoteStorageLocation, offset int64, size int64) (data []byte, err error)
  31. WriteFile(loc *filer_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (remoteEntry *filer_pb.RemoteEntry, err error)
  32. UpdateFileMetadata(loc *filer_pb.RemoteStorageLocation, entry *filer_pb.Entry) (err error)
  33. DeleteFile(loc *filer_pb.RemoteStorageLocation) (err error)
  34. }
  35. type RemoteStorageClientMaker interface {
  36. Make(remoteConf *filer_pb.RemoteConf) (RemoteStorageClient, error)
  37. }
  38. var (
  39. RemoteStorageClientMakers = make(map[string]RemoteStorageClientMaker)
  40. remoteStorageClients = make(map[string]RemoteStorageClient)
  41. remoteStorageClientsLock sync.Mutex
  42. )
  43. func makeRemoteStorageClient(remoteConf *filer_pb.RemoteConf) (RemoteStorageClient, error) {
  44. maker, found := RemoteStorageClientMakers[remoteConf.Type]
  45. if !found {
  46. return nil, fmt.Errorf("remote storage type %s not found", remoteConf.Type)
  47. }
  48. return maker.Make(remoteConf)
  49. }
  50. func GetRemoteStorage(remoteConf *filer_pb.RemoteConf) (RemoteStorageClient, error) {
  51. remoteStorageClientsLock.Lock()
  52. defer remoteStorageClientsLock.Unlock()
  53. existingRemoteStorageClient, found := remoteStorageClients[remoteConf.Name]
  54. if found {
  55. return existingRemoteStorageClient, nil
  56. }
  57. newRemoteStorageClient, err := makeRemoteStorageClient(remoteConf)
  58. if err != nil {
  59. return nil, fmt.Errorf("make remote storage client %s: %v", remoteConf.Name, err)
  60. }
  61. remoteStorageClients[remoteConf.Name] = newRemoteStorageClient
  62. return newRemoteStorageClient, nil
  63. }