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.

283 lines
11 KiB

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