filer_remote_sync_dir.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package command
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  6. "os"
  7. "strings"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/filer"
  10. "github.com/seaweedfs/seaweedfs/weed/glog"
  11. "github.com/seaweedfs/seaweedfs/weed/pb"
  12. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/remote_storage"
  15. "github.com/seaweedfs/seaweedfs/weed/replication/source"
  16. "github.com/seaweedfs/seaweedfs/weed/util"
  17. "google.golang.org/grpc"
  18. "google.golang.org/protobuf/proto"
  19. )
  20. func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *source.FilerSource, mountedDir string) error {
  21. // read filer remote storage mount mappings
  22. _, _, remoteStorageMountLocation, remoteStorage, detectErr := filer.DetectMountInfo(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir)
  23. if detectErr != nil {
  24. return fmt.Errorf("read mount info: %v", detectErr)
  25. }
  26. eachEntryFunc, err := makeEventProcessor(remoteStorage, mountedDir, remoteStorageMountLocation, filerSource)
  27. if err != nil {
  28. return err
  29. }
  30. processor := NewMetadataProcessor(eachEntryFunc, 128)
  31. var lastLogTsNs = time.Now().UnixNano()
  32. processEventFnWithOffset := pb.AddOffsetFunc(func(resp *filer_pb.SubscribeMetadataResponse) error {
  33. if resp.EventNotification.NewEntry != nil {
  34. if *option.storageClass == "" {
  35. if _, ok := resp.EventNotification.NewEntry.Extended[s3_constants.AmzStorageClass]; ok {
  36. delete(resp.EventNotification.NewEntry.Extended, s3_constants.AmzStorageClass)
  37. }
  38. } else {
  39. resp.EventNotification.NewEntry.Extended[s3_constants.AmzStorageClass] = []byte(*option.storageClass)
  40. }
  41. }
  42. processor.AddSyncJob(resp)
  43. return nil
  44. }, 3*time.Second, func(counter int64, lastTsNs int64) error {
  45. if processor.processedTsWatermark == 0 {
  46. return nil
  47. }
  48. // use processor.processedTsWatermark instead of the lastTsNs from the most recent job
  49. now := time.Now().UnixNano()
  50. glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, time.Unix(0, processor.processedTsWatermark), float64(counter)/(float64(now-lastLogTsNs)/1e9))
  51. lastLogTsNs = now
  52. return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, processor.processedTsWatermark)
  53. })
  54. lastOffsetTs := collectLastSyncOffset(option, option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, *option.timeAgo)
  55. option.clientEpoch++
  56. return pb.FollowMetadata(pb.ServerAddress(*option.filerAddress), option.grpcDialOption, "filer.remote.sync", option.clientId, option.clientEpoch,
  57. mountedDir, []string{filer.DirectoryEtcRemote}, lastOffsetTs.UnixNano(), 0, 0, processEventFnWithOffset, pb.TrivialOnError)
  58. }
  59. func makeEventProcessor(remoteStorage *remote_pb.RemoteConf, mountedDir string, remoteStorageMountLocation *remote_pb.RemoteStorageLocation, filerSource *source.FilerSource) (pb.ProcessMetadataFunc, error) {
  60. client, err := remote_storage.GetRemoteStorage(remoteStorage)
  61. if err != nil {
  62. return nil, err
  63. }
  64. handleEtcRemoteChanges := func(resp *filer_pb.SubscribeMetadataResponse) error {
  65. message := resp.EventNotification
  66. if message.NewEntry == nil {
  67. return nil
  68. }
  69. if message.NewEntry.Name == filer.REMOTE_STORAGE_MOUNT_FILE {
  70. mappings, readErr := filer.UnmarshalRemoteStorageMappings(message.NewEntry.Content)
  71. if readErr != nil {
  72. return fmt.Errorf("unmarshal mappings: %v", readErr)
  73. }
  74. if remoteLoc, found := mappings.Mappings[mountedDir]; found {
  75. if remoteStorageMountLocation.Bucket != remoteLoc.Bucket || remoteStorageMountLocation.Path != remoteLoc.Path {
  76. glog.Fatalf("Unexpected mount changes %+v => %+v", remoteStorageMountLocation, remoteLoc)
  77. }
  78. } else {
  79. glog.V(0).Infof("unmounted %s exiting ...", mountedDir)
  80. os.Exit(0)
  81. }
  82. }
  83. if message.NewEntry.Name == remoteStorage.Name+filer.REMOTE_STORAGE_CONF_SUFFIX {
  84. conf := &remote_pb.RemoteConf{}
  85. if err := proto.Unmarshal(message.NewEntry.Content, conf); err != nil {
  86. return fmt.Errorf("unmarshal %s/%s: %v", filer.DirectoryEtcRemote, message.NewEntry.Name, err)
  87. }
  88. remoteStorage = conf
  89. if newClient, err := remote_storage.GetRemoteStorage(remoteStorage); err == nil {
  90. client = newClient
  91. } else {
  92. return err
  93. }
  94. }
  95. return nil
  96. }
  97. eachEntryFunc := func(resp *filer_pb.SubscribeMetadataResponse) error {
  98. message := resp.EventNotification
  99. if strings.HasPrefix(resp.Directory, filer.DirectoryEtcRemote) {
  100. return handleEtcRemoteChanges(resp)
  101. }
  102. if filer_pb.IsEmpty(resp) {
  103. return nil
  104. }
  105. if filer_pb.IsCreate(resp) {
  106. if isMultipartUploadFile(message.NewParentPath, message.NewEntry.Name) {
  107. return nil
  108. }
  109. if !filer.HasData(message.NewEntry) {
  110. return nil
  111. }
  112. glog.V(2).Infof("create: %+v", resp)
  113. if !shouldSendToRemote(message.NewEntry) {
  114. glog.V(2).Infof("skipping creating: %+v", resp)
  115. return nil
  116. }
  117. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  118. if message.NewEntry.IsDirectory {
  119. glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
  120. return client.WriteDirectory(dest, message.NewEntry)
  121. }
  122. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  123. remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewEntry, dest)
  124. if writeErr != nil {
  125. return writeErr
  126. }
  127. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  128. }
  129. if filer_pb.IsDelete(resp) {
  130. glog.V(2).Infof("delete: %+v", resp)
  131. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  132. if message.OldEntry.IsDirectory {
  133. glog.V(0).Infof("rmdir %s", remote_storage.FormatLocation(dest))
  134. return client.RemoveDirectory(dest)
  135. }
  136. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(dest))
  137. return client.DeleteFile(dest)
  138. }
  139. if message.OldEntry != nil && message.NewEntry != nil {
  140. oldDest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  141. dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  142. if !shouldSendToRemote(message.NewEntry) {
  143. glog.V(2).Infof("skipping updating: %+v", resp)
  144. return nil
  145. }
  146. if message.NewEntry.IsDirectory {
  147. return client.WriteDirectory(dest, message.NewEntry)
  148. }
  149. if resp.Directory == message.NewParentPath && message.OldEntry.Name == message.NewEntry.Name {
  150. if filer.IsSameData(message.OldEntry, message.NewEntry) {
  151. glog.V(2).Infof("update meta: %+v", resp)
  152. return client.UpdateFileMetadata(dest, message.OldEntry, message.NewEntry)
  153. }
  154. }
  155. glog.V(2).Infof("update: %+v", resp)
  156. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
  157. if err := client.DeleteFile(oldDest); err != nil {
  158. if isMultipartUploadFile(resp.Directory, message.OldEntry.Name) {
  159. return nil
  160. }
  161. }
  162. remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewEntry, dest)
  163. if writeErr != nil {
  164. return writeErr
  165. }
  166. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  167. }
  168. return nil
  169. }
  170. return eachEntryFunc, nil
  171. }
  172. func retriedWriteFile(client remote_storage.RemoteStorageClient, filerSource *source.FilerSource, newEntry *filer_pb.Entry, dest *remote_pb.RemoteStorageLocation) (remoteEntry *filer_pb.RemoteEntry, err error) {
  173. var writeErr error
  174. err = util.Retry("writeFile", func() error {
  175. reader := filer.NewFileReader(filerSource, newEntry)
  176. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  177. remoteEntry, writeErr = client.WriteFile(dest, newEntry, reader)
  178. if writeErr != nil {
  179. return writeErr
  180. }
  181. return nil
  182. })
  183. if err != nil {
  184. glog.Errorf("write to %s: %v", dest, err)
  185. }
  186. return
  187. }
  188. func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, mountedDir string, timeAgo time.Duration) time.Time {
  189. // 1. specified by timeAgo
  190. // 2. last offset timestamp for this directory
  191. // 3. directory creation time
  192. var lastOffsetTs time.Time
  193. if timeAgo == 0 {
  194. mountedDirEntry, err := filer_pb.GetEntry(filerClient, util.FullPath(mountedDir))
  195. if err != nil {
  196. glog.V(0).Infof("get mounted directory %s: %v", mountedDir, err)
  197. return time.Now()
  198. }
  199. lastOffsetTsNs, err := remote_storage.GetSyncOffset(grpcDialOption, filerAddress, mountedDir)
  200. if mountedDirEntry != nil {
  201. if err == nil && mountedDirEntry.Attributes.Crtime < lastOffsetTsNs/1000000 {
  202. lastOffsetTs = time.Unix(0, lastOffsetTsNs)
  203. glog.V(0).Infof("resume from %v", lastOffsetTs)
  204. } else {
  205. lastOffsetTs = time.Unix(mountedDirEntry.Attributes.Crtime, 0)
  206. }
  207. } else {
  208. lastOffsetTs = time.Now()
  209. }
  210. } else {
  211. lastOffsetTs = time.Now().Add(-timeAgo)
  212. }
  213. return lastOffsetTs
  214. }
  215. func toRemoteStorageLocation(mountDir, sourcePath util.FullPath, remoteMountLocation *remote_pb.RemoteStorageLocation) *remote_pb.RemoteStorageLocation {
  216. source := string(sourcePath[len(mountDir):])
  217. dest := util.FullPath(remoteMountLocation.Path).Child(source)
  218. return &remote_pb.RemoteStorageLocation{
  219. Name: remoteMountLocation.Name,
  220. Bucket: remoteMountLocation.Bucket,
  221. Path: string(dest),
  222. }
  223. }
  224. func shouldSendToRemote(entry *filer_pb.Entry) bool {
  225. if entry.RemoteEntry == nil {
  226. return true
  227. }
  228. if entry.RemoteEntry.RemoteMtime < entry.Attributes.Mtime {
  229. return true
  230. }
  231. return false
  232. }
  233. func updateLocalEntry(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.Entry, remoteEntry *filer_pb.RemoteEntry) error {
  234. remoteEntry.LastLocalSyncTsNs = time.Now().UnixNano()
  235. entry.RemoteEntry = remoteEntry
  236. return filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  237. _, err := client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
  238. Directory: dir,
  239. Entry: entry,
  240. })
  241. return err
  242. })
  243. }
  244. func isMultipartUploadFile(dir string, name string) bool {
  245. return strings.HasPrefix(dir, "/buckets/") &&
  246. strings.Contains(dir, "/"+s3_constants.MultipartUploadsFolder+"/") &&
  247. strings.HasSuffix(name, ".part")
  248. }