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.

246 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
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. filerSource := &source.FilerSource{}
  64. filerSource.DoInitialize(
  65. filerAddress,
  66. pb.ServerToGrpcAddress(filerAddress),
  67. "/", // does not matter
  68. *remoteSyncOptions.readChunkFromFiler,
  69. )
  70. fmt.Printf("synchronize %s to remote storage...\n", dir)
  71. util.RetryForever("filer.remote.sync "+dir, func() error {
  72. return followUpdatesAndUploadToRemote(&remoteSyncOptions, filerSource, dir)
  73. }, func(err error) bool {
  74. if err != nil {
  75. glog.Errorf("synchronize %s: %v", dir, err)
  76. }
  77. return true
  78. })
  79. return true
  80. }
  81. func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *source.FilerSource, mountedDir string) error {
  82. // read filer remote storage mount mappings
  83. _, _, remoteStorageMountLocation, remoteStorage, detectErr := filer.DetectMountInfo(option.grpcDialOption, *option.filerAddress, mountedDir)
  84. if detectErr != nil {
  85. return fmt.Errorf("read mount info: %v", detectErr)
  86. }
  87. dirHash := util.HashStringToLong(mountedDir)
  88. // 1. specified by timeAgo
  89. // 2. last offset timestamp for this directory
  90. // 3. directory creation time
  91. var lastOffsetTs time.Time
  92. if *option.timeAgo == 0 {
  93. mountedDirEntry, err := filer_pb.GetEntry(option, util.FullPath(mountedDir))
  94. if err != nil {
  95. return fmt.Errorf("lookup %s: %v", mountedDir, err)
  96. }
  97. lastOffsetTsNs, err := getOffset(option.grpcDialOption, *option.filerAddress, RemoteSyncKeyPrefix, int32(dirHash))
  98. if mountedDirEntry != nil {
  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()
  107. }
  108. } else {
  109. lastOffsetTs = time.Now().Add(-*option.timeAgo)
  110. }
  111. client, err := remote_storage.GetRemoteStorage(remoteStorage)
  112. if err != nil {
  113. return err
  114. }
  115. eachEntryFunc := func(resp *filer_pb.SubscribeMetadataResponse) error {
  116. message := resp.EventNotification
  117. if message.OldEntry == nil && message.NewEntry == nil {
  118. return nil
  119. }
  120. if message.OldEntry == nil && message.NewEntry != nil {
  121. if !filer.HasData(message.NewEntry) {
  122. return nil
  123. }
  124. glog.V(2).Infof("create: %+v", resp)
  125. if !shouldSendToRemote(message.NewEntry) {
  126. glog.V(2).Infof("skipping creating: %+v", resp)
  127. return nil
  128. }
  129. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  130. if message.NewEntry.IsDirectory {
  131. glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
  132. return client.WriteDirectory(dest, message.NewEntry)
  133. }
  134. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  135. reader := filer.NewFileReader(filerSource, message.NewEntry)
  136. remoteEntry, writeErr := client.WriteFile(dest, message.NewEntry, reader)
  137. if writeErr != nil {
  138. return writeErr
  139. }
  140. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  141. }
  142. if message.OldEntry != nil && message.NewEntry == nil {
  143. glog.V(2).Infof("delete: %+v", resp)
  144. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  145. if message.OldEntry.IsDirectory {
  146. glog.V(0).Infof("rmdir %s", remote_storage.FormatLocation(dest))
  147. return client.RemoveDirectory(dest)
  148. }
  149. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(dest))
  150. return client.DeleteFile(dest)
  151. }
  152. if message.OldEntry != nil && message.NewEntry != nil {
  153. oldDest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  154. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  155. if !shouldSendToRemote(message.NewEntry) {
  156. glog.V(2).Infof("skipping updating: %+v", resp)
  157. return nil
  158. }
  159. if message.NewEntry.IsDirectory {
  160. return client.WriteDirectory(dest, message.NewEntry)
  161. }
  162. if resp.Directory == message.NewParentPath && message.OldEntry.Name == message.NewEntry.Name {
  163. if filer.IsSameData(message.OldEntry, message.NewEntry) {
  164. glog.V(2).Infof("update meta: %+v", resp)
  165. return client.UpdateFileMetadata(dest, message.OldEntry, message.NewEntry)
  166. }
  167. }
  168. glog.V(2).Infof("update: %+v", resp)
  169. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
  170. if err := client.DeleteFile(oldDest); err != nil {
  171. return err
  172. }
  173. reader := filer.NewFileReader(filerSource, message.NewEntry)
  174. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  175. remoteEntry, writeErr := client.WriteFile(dest, message.NewEntry, reader)
  176. if writeErr != nil {
  177. return writeErr
  178. }
  179. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  180. }
  181. return nil
  182. }
  183. processEventFnWithOffset := pb.AddOffsetFunc(eachEntryFunc, 3*time.Second, func(counter int64, lastTsNs int64) error {
  184. lastTime := time.Unix(0, lastTsNs)
  185. glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, lastTime, float64(counter)/float64(3))
  186. return setOffset(option.grpcDialOption, *option.filerAddress, RemoteSyncKeyPrefix, int32(dirHash), lastTsNs)
  187. })
  188. return pb.FollowMetadata(*option.filerAddress, option.grpcDialOption,
  189. "filer.remote.sync", mountedDir, lastOffsetTs.UnixNano(), 0, processEventFnWithOffset, false)
  190. }
  191. func toRemoteStorageLocation(mountDir, sourcePath util.FullPath, remoteMountLocation *remote_pb.RemoteStorageLocation) *remote_pb.RemoteStorageLocation {
  192. source := string(sourcePath[len(mountDir):])
  193. dest := util.FullPath(remoteMountLocation.Path).Child(source)
  194. return &remote_pb.RemoteStorageLocation{
  195. Name: remoteMountLocation.Name,
  196. Bucket: remoteMountLocation.Bucket,
  197. Path: string(dest),
  198. }
  199. }
  200. func shouldSendToRemote(entry *filer_pb.Entry) bool {
  201. if entry.RemoteEntry == nil {
  202. return true
  203. }
  204. if entry.RemoteEntry.LastLocalSyncTsNs/1e9 < entry.Attributes.Mtime {
  205. return true
  206. }
  207. return false
  208. }
  209. func updateLocalEntry(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.Entry, remoteEntry *filer_pb.RemoteEntry) error {
  210. entry.RemoteEntry = remoteEntry
  211. return filerClient.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  212. _, err := client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
  213. Directory: dir,
  214. Entry: entry,
  215. })
  216. return err
  217. })
  218. }