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.

243 lines
9.3 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 mountedDirEntry != nil {
  100. if err == nil && mountedDirEntry.Attributes.Crtime < lastOffsetTsNs/1000000 {
  101. lastOffsetTs = time.Unix(0, lastOffsetTsNs)
  102. glog.V(0).Infof("resume from %v", lastOffsetTs)
  103. } else {
  104. lastOffsetTs = time.Unix(mountedDirEntry.Attributes.Crtime, 0)
  105. }
  106. } else {
  107. lastOffsetTs = time.Now()
  108. }
  109. } else {
  110. lastOffsetTs = time.Now().Add(-*option.timeAgo)
  111. }
  112. client, err := remote_storage.GetRemoteStorage(remoteStorage)
  113. if err != nil {
  114. return err
  115. }
  116. eachEntryFunc := func(resp *filer_pb.SubscribeMetadataResponse) error {
  117. message := resp.EventNotification
  118. if message.OldEntry == nil && message.NewEntry == nil {
  119. return nil
  120. }
  121. if message.OldEntry == nil && message.NewEntry != nil {
  122. if !filer.HasData(message.NewEntry) {
  123. return nil
  124. }
  125. glog.V(2).Infof("create: %+v", resp)
  126. if !shouldSendToRemote(message.NewEntry) {
  127. glog.V(2).Infof("skipping creating: %+v", resp)
  128. return nil
  129. }
  130. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  131. if message.NewEntry.IsDirectory {
  132. glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
  133. return client.WriteDirectory(dest, message.NewEntry)
  134. }
  135. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  136. reader := filer.NewFileReader(filerSource, message.NewEntry)
  137. remoteEntry, writeErr := client.WriteFile(dest, message.NewEntry, reader)
  138. if writeErr != nil {
  139. return writeErr
  140. }
  141. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  142. }
  143. if message.OldEntry != nil && message.NewEntry == nil {
  144. glog.V(2).Infof("delete: %+v", resp)
  145. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  146. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(dest))
  147. return client.DeleteFile(dest)
  148. }
  149. if message.OldEntry != nil && message.NewEntry != nil {
  150. oldDest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  151. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  152. if !shouldSendToRemote(message.NewEntry) {
  153. glog.V(2).Infof("skipping updating: %+v", resp)
  154. return nil
  155. }
  156. if message.NewEntry.IsDirectory {
  157. return client.WriteDirectory(dest, message.NewEntry)
  158. }
  159. if resp.Directory == message.NewParentPath && message.OldEntry.Name == message.NewEntry.Name {
  160. if filer.IsSameData(message.OldEntry, message.NewEntry) {
  161. glog.V(2).Infof("update meta: %+v", resp)
  162. return client.UpdateFileMetadata(dest, message.OldEntry, message.NewEntry)
  163. }
  164. }
  165. glog.V(2).Infof("update: %+v", resp)
  166. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
  167. if err := client.DeleteFile(oldDest); err != nil {
  168. return err
  169. }
  170. reader := filer.NewFileReader(filerSource, message.NewEntry)
  171. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  172. remoteEntry, writeErr := client.WriteFile(dest, message.NewEntry, reader)
  173. if writeErr != nil {
  174. return writeErr
  175. }
  176. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  177. }
  178. return nil
  179. }
  180. processEventFnWithOffset := pb.AddOffsetFunc(eachEntryFunc, 3*time.Second, func(counter int64, lastTsNs int64) error {
  181. lastTime := time.Unix(0, lastTsNs)
  182. glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, lastTime, float64(counter)/float64(3))
  183. return setOffset(option.grpcDialOption, *option.filerAddress, RemoteSyncKeyPrefix, int32(dirHash), lastTsNs)
  184. })
  185. return pb.FollowMetadata(*option.filerAddress, option.grpcDialOption,
  186. "filer.remote.sync", mountedDir, lastOffsetTs.UnixNano(), 0, processEventFnWithOffset, false)
  187. }
  188. func toRemoteStorageLocation(mountDir, sourcePath util.FullPath, remoteMountLocation *remote_pb.RemoteStorageLocation) *remote_pb.RemoteStorageLocation {
  189. source := string(sourcePath[len(mountDir):])
  190. dest := util.FullPath(remoteMountLocation.Path).Child(source)
  191. return &remote_pb.RemoteStorageLocation{
  192. Name: remoteMountLocation.Name,
  193. Bucket: remoteMountLocation.Bucket,
  194. Path: string(dest),
  195. }
  196. }
  197. func shouldSendToRemote(entry *filer_pb.Entry) bool {
  198. if entry.RemoteEntry == nil {
  199. return true
  200. }
  201. if entry.RemoteEntry.LastLocalSyncTsNs/1e9 < entry.Attributes.Mtime {
  202. return true
  203. }
  204. return false
  205. }
  206. func updateLocalEntry(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.Entry, remoteEntry *filer_pb.RemoteEntry) error {
  207. entry.RemoteEntry = remoteEntry
  208. return filerClient.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  209. _, err := client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
  210. Directory: dir,
  211. Entry: entry,
  212. })
  213. return err
  214. })
  215. }