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.

239 lines
9.2 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package command
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "github.com/chrislusf/seaweedfs/weed/pb"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. "github.com/chrislusf/seaweedfs/weed/pb/remote_pb"
  10. "github.com/chrislusf/seaweedfs/weed/remote_storage"
  11. "github.com/chrislusf/seaweedfs/weed/replication/source"
  12. "github.com/chrislusf/seaweedfs/weed/security"
  13. "github.com/chrislusf/seaweedfs/weed/util"
  14. "google.golang.org/grpc"
  15. "time"
  16. )
  17. type RemoteSyncOptions struct {
  18. filerAddress *string
  19. grpcDialOption grpc.DialOption
  20. readChunkFromFiler *bool
  21. debug *bool
  22. timeAgo *time.Duration
  23. dir *string
  24. }
  25. const (
  26. RemoteSyncKeyPrefix = "remote.sync."
  27. )
  28. var _ = filer_pb.FilerClient(&RemoteSyncOptions{})
  29. func (option *RemoteSyncOptions) WithFilerClient(fn func(filer_pb.SeaweedFilerClient) error) error {
  30. return pb.WithFilerClient(*option.filerAddress, option.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  31. return fn(client)
  32. })
  33. }
  34. func (option *RemoteSyncOptions) AdjustedUrl(location *filer_pb.Location) string {
  35. return location.Url
  36. }
  37. var (
  38. remoteSyncOptions RemoteSyncOptions
  39. )
  40. func init() {
  41. cmdFilerRemoteSynchronize.Run = runFilerRemoteSynchronize // break init cycle
  42. remoteSyncOptions.filerAddress = cmdFilerRemoteSynchronize.Flag.String("filer", "localhost:8888", "filer of the SeaweedFS cluster")
  43. remoteSyncOptions.dir = cmdFilerRemoteSynchronize.Flag.String("dir", "/", "a mounted directory on filer")
  44. remoteSyncOptions.readChunkFromFiler = cmdFilerRemoteSynchronize.Flag.Bool("filerProxy", false, "read file chunks from filer instead of volume servers")
  45. remoteSyncOptions.debug = cmdFilerRemoteSynchronize.Flag.Bool("debug", false, "debug mode to print out filer updated remote files")
  46. remoteSyncOptions.timeAgo = cmdFilerRemoteSynchronize.Flag.Duration("timeAgo", 0, "start time before now. \"300ms\", \"1.5h\" or \"2h45m\". Valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\"")
  47. }
  48. var cmdFilerRemoteSynchronize = &Command{
  49. UsageLine: "filer.remote.sync -filer=<filerHost>:<filerPort> -dir=/mount/s3_on_cloud",
  50. Short: "resumable continuously write back updates to remote storage if the directory is mounted to the remote storage",
  51. Long: `resumable continuously write back updates to remote storage if the directory is mounted to the remote storage
  52. filer.remote.sync listens on filer update events.
  53. If any mounted remote file is updated, it will fetch the updated content,
  54. and write to the remote storage.
  55. `,
  56. }
  57. func runFilerRemoteSynchronize(cmd *Command, args []string) bool {
  58. util.LoadConfiguration("security", false)
  59. grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
  60. remoteSyncOptions.grpcDialOption = grpcDialOption
  61. dir := *remoteSyncOptions.dir
  62. filerAddress := *remoteSyncOptions.filerAddress
  63. // read filer remote storage mount mappings
  64. _, _, remoteStorageMountLocation, storageConf, detectErr := filer.DetectMountInfo(grpcDialOption, filerAddress, dir)
  65. if detectErr != nil {
  66. fmt.Printf("read mount info: %v", detectErr)
  67. return false
  68. }
  69. filerSource := &source.FilerSource{}
  70. filerSource.DoInitialize(
  71. filerAddress,
  72. pb.ServerToGrpcAddress(filerAddress),
  73. "/", // does not matter
  74. *remoteSyncOptions.readChunkFromFiler,
  75. )
  76. fmt.Printf("synchronize %s to remote storage...\n", dir)
  77. util.RetryForever("filer.remote.sync "+dir, func() error {
  78. return followUpdatesAndUploadToRemote(&remoteSyncOptions, filerSource, dir, storageConf, remoteStorageMountLocation)
  79. }, func(err error) bool {
  80. if err != nil {
  81. glog.Errorf("synchronize %s: %v", dir, err)
  82. }
  83. return true
  84. })
  85. return true
  86. }
  87. func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *source.FilerSource, mountedDir string, remoteStorage *remote_pb.RemoteConf, remoteStorageMountLocation *remote_pb.RemoteStorageLocation) error {
  88. dirHash := util.HashStringToLong(mountedDir)
  89. // 1. specified by timeAgo
  90. // 2. last offset timestamp for this directory
  91. // 3. directory creation time
  92. var lastOffsetTs time.Time
  93. if *option.timeAgo == 0 {
  94. mountedDirEntry, err := filer_pb.GetEntry(option, util.FullPath(mountedDir))
  95. if err != nil {
  96. return fmt.Errorf("lookup %s: %v", mountedDir, err)
  97. }
  98. lastOffsetTsNs, err := getOffset(option.grpcDialOption, *option.filerAddress, RemoteSyncKeyPrefix, int32(dirHash))
  99. if err == nil && mountedDirEntry.Attributes.Crtime < lastOffsetTsNs/1000000 {
  100. lastOffsetTs = time.Unix(0, lastOffsetTsNs)
  101. glog.V(0).Infof("resume from %v", lastOffsetTs)
  102. } else {
  103. lastOffsetTs = time.Unix(mountedDirEntry.Attributes.Crtime, 0)
  104. }
  105. } else {
  106. lastOffsetTs = time.Now().Add(-*option.timeAgo)
  107. }
  108. client, err := remote_storage.GetRemoteStorage(remoteStorage)
  109. if err != nil {
  110. return err
  111. }
  112. eachEntryFunc := func(resp *filer_pb.SubscribeMetadataResponse) error {
  113. message := resp.EventNotification
  114. if message.OldEntry == nil && message.NewEntry == nil {
  115. return nil
  116. }
  117. if message.OldEntry == nil && message.NewEntry != nil {
  118. if !filer.HasData(message.NewEntry) {
  119. return nil
  120. }
  121. glog.V(2).Infof("create: %+v", resp)
  122. if !shouldSendToRemote(message.NewEntry) {
  123. glog.V(2).Infof("skipping creating: %+v", resp)
  124. return nil
  125. }
  126. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  127. if message.NewEntry.IsDirectory {
  128. glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
  129. return client.WriteDirectory(dest, message.NewEntry)
  130. }
  131. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  132. reader := filer.NewFileReader(filerSource, message.NewEntry)
  133. remoteEntry, writeErr := client.WriteFile(dest, message.NewEntry, reader)
  134. if writeErr != nil {
  135. return writeErr
  136. }
  137. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  138. }
  139. if message.OldEntry != nil && message.NewEntry == nil {
  140. glog.V(2).Infof("delete: %+v", resp)
  141. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  142. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(dest))
  143. return client.DeleteFile(dest)
  144. }
  145. if message.OldEntry != nil && message.NewEntry != nil {
  146. oldDest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  147. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  148. if !shouldSendToRemote(message.NewEntry) {
  149. glog.V(2).Infof("skipping updating: %+v", resp)
  150. return nil
  151. }
  152. if message.NewEntry.IsDirectory {
  153. return client.WriteDirectory(dest, message.NewEntry)
  154. }
  155. if resp.Directory == message.NewParentPath && message.OldEntry.Name == message.NewEntry.Name {
  156. if filer.IsSameData(message.OldEntry, message.NewEntry) {
  157. glog.V(2).Infof("update meta: %+v", resp)
  158. return client.UpdateFileMetadata(dest, message.OldEntry, message.NewEntry)
  159. }
  160. }
  161. glog.V(2).Infof("update: %+v", resp)
  162. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
  163. if err := client.DeleteFile(oldDest); err != nil {
  164. return err
  165. }
  166. reader := filer.NewFileReader(filerSource, message.NewEntry)
  167. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  168. remoteEntry, writeErr := client.WriteFile(dest, message.NewEntry, reader)
  169. if writeErr != nil {
  170. return writeErr
  171. }
  172. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  173. }
  174. return nil
  175. }
  176. processEventFnWithOffset := pb.AddOffsetFunc(eachEntryFunc, 3*time.Second, func(counter int64, lastTsNs int64) error {
  177. lastTime := time.Unix(0, lastTsNs)
  178. glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, lastTime, float64(counter)/float64(3))
  179. return setOffset(option.grpcDialOption, *option.filerAddress, RemoteSyncKeyPrefix, int32(dirHash), lastTsNs)
  180. })
  181. return pb.FollowMetadata(*option.filerAddress, option.grpcDialOption,
  182. "filer.remote.sync", mountedDir, lastOffsetTs.UnixNano(), 0, processEventFnWithOffset, false)
  183. }
  184. func toRemoteStorageLocation(mountDir, sourcePath util.FullPath, remoteMountLocation *remote_pb.RemoteStorageLocation) *remote_pb.RemoteStorageLocation {
  185. source := string(sourcePath[len(mountDir):])
  186. dest := util.FullPath(remoteMountLocation.Path).Child(source)
  187. return &remote_pb.RemoteStorageLocation{
  188. Name: remoteMountLocation.Name,
  189. Bucket: remoteMountLocation.Bucket,
  190. Path: string(dest),
  191. }
  192. }
  193. func shouldSendToRemote(entry *filer_pb.Entry) bool {
  194. if entry.RemoteEntry == nil {
  195. return true
  196. }
  197. if entry.RemoteEntry.LastLocalSyncTsNs/1e9 < entry.Attributes.Mtime {
  198. return true
  199. }
  200. return false
  201. }
  202. func updateLocalEntry(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.Entry, remoteEntry *filer_pb.RemoteEntry) error {
  203. entry.RemoteEntry = remoteEntry
  204. return filerClient.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  205. _, err := client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
  206. Directory: dir,
  207. Entry: entry,
  208. })
  209. return err
  210. })
  211. }