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.

340 lines
13 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
  1. package command
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  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/replication"
  10. "github.com/chrislusf/seaweedfs/weed/replication/sink"
  11. "github.com/chrislusf/seaweedfs/weed/replication/sink/filersink"
  12. "github.com/chrislusf/seaweedfs/weed/replication/source"
  13. "github.com/chrislusf/seaweedfs/weed/security"
  14. "github.com/chrislusf/seaweedfs/weed/util"
  15. "github.com/chrislusf/seaweedfs/weed/util/grace"
  16. "google.golang.org/grpc"
  17. "strings"
  18. "time"
  19. )
  20. type SyncOptions struct {
  21. isActivePassive *bool
  22. filerA *string
  23. filerB *string
  24. aPath *string
  25. bPath *string
  26. aReplication *string
  27. bReplication *string
  28. aCollection *string
  29. bCollection *string
  30. aTtlSec *int
  31. bTtlSec *int
  32. aDiskType *string
  33. bDiskType *string
  34. aDebug *bool
  35. bDebug *bool
  36. aProxyByFiler *bool
  37. bProxyByFiler *bool
  38. }
  39. var (
  40. syncOptions SyncOptions
  41. syncCpuProfile *string
  42. syncMemProfile *string
  43. )
  44. func init() {
  45. cmdFilerSynchronize.Run = runFilerSynchronize // break init cycle
  46. syncOptions.isActivePassive = cmdFilerSynchronize.Flag.Bool("isActivePassive", false, "one directional follow from A to B if true")
  47. syncOptions.filerA = cmdFilerSynchronize.Flag.String("a", "", "filer A in one SeaweedFS cluster")
  48. syncOptions.filerB = cmdFilerSynchronize.Flag.String("b", "", "filer B in the other SeaweedFS cluster")
  49. syncOptions.aPath = cmdFilerSynchronize.Flag.String("a.path", "/", "directory to sync on filer A")
  50. syncOptions.bPath = cmdFilerSynchronize.Flag.String("b.path", "/", "directory to sync on filer B")
  51. syncOptions.aReplication = cmdFilerSynchronize.Flag.String("a.replication", "", "replication on filer A")
  52. syncOptions.bReplication = cmdFilerSynchronize.Flag.String("b.replication", "", "replication on filer B")
  53. syncOptions.aCollection = cmdFilerSynchronize.Flag.String("a.collection", "", "collection on filer A")
  54. syncOptions.bCollection = cmdFilerSynchronize.Flag.String("b.collection", "", "collection on filer B")
  55. syncOptions.aTtlSec = cmdFilerSynchronize.Flag.Int("a.ttlSec", 0, "ttl in seconds on filer A")
  56. syncOptions.bTtlSec = cmdFilerSynchronize.Flag.Int("b.ttlSec", 0, "ttl in seconds on filer B")
  57. syncOptions.aDiskType = cmdFilerSynchronize.Flag.String("a.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag on filer A")
  58. syncOptions.bDiskType = cmdFilerSynchronize.Flag.String("b.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag on filer B")
  59. syncOptions.aProxyByFiler = cmdFilerSynchronize.Flag.Bool("a.filerProxy", false, "read and write file chunks by filer A instead of volume servers")
  60. syncOptions.bProxyByFiler = cmdFilerSynchronize.Flag.Bool("b.filerProxy", false, "read and write file chunks by filer B instead of volume servers")
  61. syncOptions.aDebug = cmdFilerSynchronize.Flag.Bool("a.debug", false, "debug mode to print out filer A received files")
  62. syncOptions.bDebug = cmdFilerSynchronize.Flag.Bool("b.debug", false, "debug mode to print out filer B received files")
  63. syncCpuProfile = cmdFilerSynchronize.Flag.String("cpuprofile", "", "cpu profile output file")
  64. syncMemProfile = cmdFilerSynchronize.Flag.String("memprofile", "", "memory profile output file")
  65. }
  66. var cmdFilerSynchronize = &Command{
  67. UsageLine: "filer.sync -a=<oneFilerHost>:<oneFilerPort> -b=<otherFilerHost>:<otherFilerPort>",
  68. Short: "resumable continuous synchronization between two active-active or active-passive SeaweedFS clusters",
  69. Long: `resumable continuous synchronization for file changes between two active-active or active-passive filers
  70. filer.sync listens on filer notifications. If any file is updated, it will fetch the updated content,
  71. and write to the other destination. Different from filer.replicate:
  72. * filer.sync only works between two filers.
  73. * filer.sync does not need any special message queue setup.
  74. * filer.sync supports both active-active and active-passive modes.
  75. If restarted, the synchronization will resume from the previous checkpoints, persisted every minute.
  76. A fresh sync will start from the earliest metadata logs.
  77. `,
  78. }
  79. func runFilerSynchronize(cmd *Command, args []string) bool {
  80. util.LoadConfiguration("security", false)
  81. grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
  82. grace.SetupProfiling(*syncCpuProfile, *syncMemProfile)
  83. go func() {
  84. for {
  85. err := doSubscribeFilerMetaChanges(grpcDialOption, *syncOptions.filerA, *syncOptions.aPath, *syncOptions.aProxyByFiler, *syncOptions.filerB,
  86. *syncOptions.bPath, *syncOptions.bReplication, *syncOptions.bCollection, *syncOptions.bTtlSec, *syncOptions.bProxyByFiler, *syncOptions.bDiskType, *syncOptions.bDebug)
  87. if err != nil {
  88. glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err)
  89. time.Sleep(1747 * time.Millisecond)
  90. }
  91. }
  92. }()
  93. if !*syncOptions.isActivePassive {
  94. go func() {
  95. for {
  96. err := doSubscribeFilerMetaChanges(grpcDialOption, *syncOptions.filerB, *syncOptions.bPath, *syncOptions.bProxyByFiler, *syncOptions.filerA,
  97. *syncOptions.aPath, *syncOptions.aReplication, *syncOptions.aCollection, *syncOptions.aTtlSec, *syncOptions.aProxyByFiler, *syncOptions.aDiskType, *syncOptions.aDebug)
  98. if err != nil {
  99. glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err)
  100. time.Sleep(2147 * time.Millisecond)
  101. }
  102. }
  103. }()
  104. }
  105. select {}
  106. return true
  107. }
  108. func doSubscribeFilerMetaChanges(grpcDialOption grpc.DialOption, sourceFiler, sourcePath string, sourceReadChunkFromFiler bool, targetFiler, targetPath string,
  109. replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool) error {
  110. // read source filer signature
  111. sourceFilerSignature, sourceErr := replication.ReadFilerSignature(grpcDialOption, sourceFiler)
  112. if sourceErr != nil {
  113. return sourceErr
  114. }
  115. // read target filer signature
  116. targetFilerSignature, targetErr := replication.ReadFilerSignature(grpcDialOption, targetFiler)
  117. if targetErr != nil {
  118. return targetErr
  119. }
  120. // if first time, start from now
  121. // if has previously synced, resume from that point of time
  122. sourceFilerOffsetTsNs, err := getOffset(grpcDialOption, targetFiler, SyncKeyPrefix, sourceFilerSignature)
  123. if err != nil {
  124. return err
  125. }
  126. glog.V(0).Infof("start sync %s(%d) => %s(%d) from %v(%d)", sourceFiler, sourceFilerSignature, targetFiler, targetFilerSignature, time.Unix(0, sourceFilerOffsetTsNs), sourceFilerOffsetTsNs)
  127. // create filer sink
  128. filerSource := &source.FilerSource{}
  129. filerSource.DoInitialize(sourceFiler, pb.ServerToGrpcAddress(sourceFiler), sourcePath, sourceReadChunkFromFiler)
  130. filerSink := &filersink.FilerSink{}
  131. filerSink.DoInitialize(targetFiler, pb.ServerToGrpcAddress(targetFiler), targetPath, replicationStr, collection, ttlSec, diskType, grpcDialOption, sinkWriteChunkByFiler)
  132. filerSink.SetSourceFiler(filerSource)
  133. persistEventFn := genProcessFunction(sourcePath, targetPath, filerSink, debug)
  134. processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
  135. message := resp.EventNotification
  136. for _, sig := range message.Signatures {
  137. if sig == targetFilerSignature && targetFilerSignature != 0 {
  138. fmt.Printf("%s skipping %s change to %v\n", targetFiler, sourceFiler, message)
  139. return nil
  140. }
  141. }
  142. return persistEventFn(resp)
  143. }
  144. processEventFnWithOffset := pb.AddOffsetFunc(processEventFn, 3*time.Second, func(counter int64, lastTsNs int64) error {
  145. glog.V(0).Infof("sync %s to %s progressed to %v %0.2f/sec", sourceFiler, targetFiler, time.Unix(0, lastTsNs), float64(counter)/float64(3))
  146. return setOffset(grpcDialOption, targetFiler, SyncKeyPrefix, sourceFilerSignature, lastTsNs)
  147. })
  148. return pb.FollowMetadata(sourceFiler, grpcDialOption, "syncTo_"+targetFiler, sourcePath, nil, sourceFilerOffsetTsNs, targetFilerSignature, processEventFnWithOffset, false)
  149. }
  150. const (
  151. SyncKeyPrefix = "sync."
  152. )
  153. func getOffset(grpcDialOption grpc.DialOption, filer string, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) {
  154. readErr = pb.WithFilerClient(filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  155. syncKey := []byte(signaturePrefix + "____")
  156. util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
  157. resp, err := client.KvGet(context.Background(), &filer_pb.KvGetRequest{Key: syncKey})
  158. if err != nil {
  159. return err
  160. }
  161. if len(resp.Error) != 0 {
  162. return errors.New(resp.Error)
  163. }
  164. if len(resp.Value) < 8 {
  165. return nil
  166. }
  167. lastOffsetTsNs = int64(util.BytesToUint64(resp.Value))
  168. return nil
  169. })
  170. return
  171. }
  172. func setOffset(grpcDialOption grpc.DialOption, filer string, signaturePrefix string, signature int32, offsetTsNs int64) error {
  173. return pb.WithFilerClient(filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  174. syncKey := []byte(signaturePrefix + "____")
  175. util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
  176. valueBuf := make([]byte, 8)
  177. util.Uint64toBytes(valueBuf, uint64(offsetTsNs))
  178. resp, err := client.KvPut(context.Background(), &filer_pb.KvPutRequest{
  179. Key: syncKey,
  180. Value: valueBuf,
  181. })
  182. if err != nil {
  183. return err
  184. }
  185. if len(resp.Error) != 0 {
  186. return errors.New(resp.Error)
  187. }
  188. return nil
  189. })
  190. }
  191. func genProcessFunction(sourcePath string, targetPath string, dataSink sink.ReplicationSink, debug bool) func(resp *filer_pb.SubscribeMetadataResponse) error {
  192. // process function
  193. processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
  194. message := resp.EventNotification
  195. var sourceOldKey, sourceNewKey util.FullPath
  196. if message.OldEntry != nil {
  197. sourceOldKey = util.FullPath(resp.Directory).Child(message.OldEntry.Name)
  198. }
  199. if message.NewEntry != nil {
  200. sourceNewKey = util.FullPath(message.NewParentPath).Child(message.NewEntry.Name)
  201. }
  202. if debug {
  203. glog.V(0).Infof("received %v", resp)
  204. }
  205. if !strings.HasPrefix(resp.Directory, sourcePath) {
  206. return nil
  207. }
  208. // handle deletions
  209. if message.OldEntry != nil && message.NewEntry == nil {
  210. if !strings.HasPrefix(string(sourceOldKey), sourcePath) {
  211. return nil
  212. }
  213. key := buildKey(dataSink, message, targetPath, sourceOldKey, sourcePath)
  214. return dataSink.DeleteEntry(key, message.OldEntry.IsDirectory, message.DeleteChunks, message.Signatures)
  215. }
  216. // handle new entries
  217. if message.OldEntry == nil && message.NewEntry != nil {
  218. if !strings.HasPrefix(string(sourceNewKey), sourcePath) {
  219. return nil
  220. }
  221. key := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  222. return dataSink.CreateEntry(key, message.NewEntry, message.Signatures)
  223. }
  224. // this is something special?
  225. if message.OldEntry == nil && message.NewEntry == nil {
  226. return nil
  227. }
  228. // handle updates
  229. if strings.HasPrefix(string(sourceOldKey), sourcePath) {
  230. // old key is in the watched directory
  231. if strings.HasPrefix(string(sourceNewKey), sourcePath) {
  232. // new key is also in the watched directory
  233. if !dataSink.IsIncremental() {
  234. oldKey := util.Join(targetPath, string(sourceOldKey)[len(sourcePath):])
  235. message.NewParentPath = util.Join(targetPath, message.NewParentPath[len(sourcePath):])
  236. foundExisting, err := dataSink.UpdateEntry(string(oldKey), message.OldEntry, message.NewParentPath, message.NewEntry, message.DeleteChunks, message.Signatures)
  237. if foundExisting {
  238. return err
  239. }
  240. // not able to find old entry
  241. if err = dataSink.DeleteEntry(string(oldKey), message.OldEntry.IsDirectory, false, message.Signatures); err != nil {
  242. return fmt.Errorf("delete old entry %v: %v", oldKey, err)
  243. }
  244. }
  245. // create the new entry
  246. newKey := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  247. return dataSink.CreateEntry(newKey, message.NewEntry, message.Signatures)
  248. } else {
  249. // new key is outside of the watched directory
  250. if !dataSink.IsIncremental() {
  251. key := buildKey(dataSink, message, targetPath, sourceOldKey, sourcePath)
  252. return dataSink.DeleteEntry(key, message.OldEntry.IsDirectory, message.DeleteChunks, message.Signatures)
  253. }
  254. }
  255. } else {
  256. // old key is outside of the watched directory
  257. if strings.HasPrefix(string(sourceNewKey), sourcePath) {
  258. // new key is in the watched directory
  259. key := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  260. return dataSink.CreateEntry(key, message.NewEntry, message.Signatures)
  261. } else {
  262. // new key is also outside of the watched directory
  263. // skip
  264. }
  265. }
  266. return nil
  267. }
  268. return processEventFn
  269. }
  270. func buildKey(dataSink sink.ReplicationSink, message *filer_pb.EventNotification, targetPath string, sourceKey util.FullPath, sourcePath string) (key string) {
  271. if !dataSink.IsIncremental() {
  272. key = util.Join(targetPath, string(sourceKey)[len(sourcePath):])
  273. } else {
  274. var mTime int64
  275. if message.NewEntry != nil {
  276. mTime = message.NewEntry.Attributes.Mtime
  277. } else if message.OldEntry != nil {
  278. mTime = message.OldEntry.Attributes.Mtime
  279. }
  280. dateKey := time.Unix(mTime, 0).Format("2006-01-02")
  281. key = util.Join(targetPath, dateKey, string(sourceKey)[len(sourcePath):])
  282. }
  283. return escapeKey(key)
  284. }