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.

343 lines
13 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 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. filerA := pb.ServerAddress(*syncOptions.filerA)
  84. filerB := pb.ServerAddress(*syncOptions.filerB)
  85. go func() {
  86. for {
  87. err := doSubscribeFilerMetaChanges(grpcDialOption, filerA, *syncOptions.aPath, *syncOptions.aProxyByFiler, filerB,
  88. *syncOptions.bPath, *syncOptions.bReplication, *syncOptions.bCollection, *syncOptions.bTtlSec, *syncOptions.bProxyByFiler, *syncOptions.bDiskType, *syncOptions.bDebug)
  89. if err != nil {
  90. glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err)
  91. time.Sleep(1747 * time.Millisecond)
  92. }
  93. }
  94. }()
  95. if !*syncOptions.isActivePassive {
  96. go func() {
  97. for {
  98. err := doSubscribeFilerMetaChanges(grpcDialOption, filerB, *syncOptions.bPath, *syncOptions.bProxyByFiler, filerA,
  99. *syncOptions.aPath, *syncOptions.aReplication, *syncOptions.aCollection, *syncOptions.aTtlSec, *syncOptions.aProxyByFiler, *syncOptions.aDiskType, *syncOptions.aDebug)
  100. if err != nil {
  101. glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err)
  102. time.Sleep(2147 * time.Millisecond)
  103. }
  104. }
  105. }()
  106. }
  107. select {}
  108. return true
  109. }
  110. func doSubscribeFilerMetaChanges(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourcePath string, sourceReadChunkFromFiler bool, targetFiler pb.ServerAddress, targetPath string,
  111. replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool) error {
  112. // read source filer signature
  113. sourceFilerSignature, sourceErr := replication.ReadFilerSignature(grpcDialOption, sourceFiler)
  114. if sourceErr != nil {
  115. return sourceErr
  116. }
  117. // read target filer signature
  118. targetFilerSignature, targetErr := replication.ReadFilerSignature(grpcDialOption, targetFiler)
  119. if targetErr != nil {
  120. return targetErr
  121. }
  122. // if first time, start from now
  123. // if has previously synced, resume from that point of time
  124. sourceFilerOffsetTsNs, err := getOffset(grpcDialOption, targetFiler, SyncKeyPrefix, sourceFilerSignature)
  125. if err != nil {
  126. return err
  127. }
  128. glog.V(0).Infof("start sync %s(%d) => %s(%d) from %v(%d)", sourceFiler, sourceFilerSignature, targetFiler, targetFilerSignature, time.Unix(0, sourceFilerOffsetTsNs), sourceFilerOffsetTsNs)
  129. // create filer sink
  130. filerSource := &source.FilerSource{}
  131. filerSource.DoInitialize(sourceFiler.ToHttpAddress(), sourceFiler.ToGrpcAddress(), sourcePath, sourceReadChunkFromFiler)
  132. filerSink := &filersink.FilerSink{}
  133. filerSink.DoInitialize(targetFiler.ToHttpAddress(), targetFiler.ToGrpcAddress(), targetPath, replicationStr, collection, ttlSec, diskType, grpcDialOption, sinkWriteChunkByFiler)
  134. filerSink.SetSourceFiler(filerSource)
  135. persistEventFn := genProcessFunction(sourcePath, targetPath, filerSink, debug)
  136. processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
  137. message := resp.EventNotification
  138. for _, sig := range message.Signatures {
  139. if sig == targetFilerSignature && targetFilerSignature != 0 {
  140. fmt.Printf("%s skipping %s change to %v\n", targetFiler, sourceFiler, message)
  141. return nil
  142. }
  143. }
  144. return persistEventFn(resp)
  145. }
  146. processEventFnWithOffset := pb.AddOffsetFunc(processEventFn, 3*time.Second, func(counter int64, lastTsNs int64) error {
  147. glog.V(0).Infof("sync %s to %s progressed to %v %0.2f/sec", sourceFiler, targetFiler, time.Unix(0, lastTsNs), float64(counter)/float64(3))
  148. return setOffset(grpcDialOption, targetFiler, SyncKeyPrefix, sourceFilerSignature, lastTsNs)
  149. })
  150. return pb.FollowMetadata(sourceFiler, grpcDialOption, "syncTo_"+string(targetFiler),
  151. sourcePath, nil, sourceFilerOffsetTsNs, targetFilerSignature, processEventFnWithOffset, false)
  152. }
  153. const (
  154. SyncKeyPrefix = "sync."
  155. )
  156. func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) {
  157. readErr = pb.WithFilerClient(filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  158. syncKey := []byte(signaturePrefix + "____")
  159. util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
  160. resp, err := client.KvGet(context.Background(), &filer_pb.KvGetRequest{Key: syncKey})
  161. if err != nil {
  162. return err
  163. }
  164. if len(resp.Error) != 0 {
  165. return errors.New(resp.Error)
  166. }
  167. if len(resp.Value) < 8 {
  168. return nil
  169. }
  170. lastOffsetTsNs = int64(util.BytesToUint64(resp.Value))
  171. return nil
  172. })
  173. return
  174. }
  175. func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, offsetTsNs int64) error {
  176. return pb.WithFilerClient(filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  177. syncKey := []byte(signaturePrefix + "____")
  178. util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
  179. valueBuf := make([]byte, 8)
  180. util.Uint64toBytes(valueBuf, uint64(offsetTsNs))
  181. resp, err := client.KvPut(context.Background(), &filer_pb.KvPutRequest{
  182. Key: syncKey,
  183. Value: valueBuf,
  184. })
  185. if err != nil {
  186. return err
  187. }
  188. if len(resp.Error) != 0 {
  189. return errors.New(resp.Error)
  190. }
  191. return nil
  192. })
  193. }
  194. func genProcessFunction(sourcePath string, targetPath string, dataSink sink.ReplicationSink, debug bool) func(resp *filer_pb.SubscribeMetadataResponse) error {
  195. // process function
  196. processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
  197. message := resp.EventNotification
  198. var sourceOldKey, sourceNewKey util.FullPath
  199. if message.OldEntry != nil {
  200. sourceOldKey = util.FullPath(resp.Directory).Child(message.OldEntry.Name)
  201. }
  202. if message.NewEntry != nil {
  203. sourceNewKey = util.FullPath(message.NewParentPath).Child(message.NewEntry.Name)
  204. }
  205. if debug {
  206. glog.V(0).Infof("received %v", resp)
  207. }
  208. if !strings.HasPrefix(resp.Directory, sourcePath) {
  209. return nil
  210. }
  211. // handle deletions
  212. if message.OldEntry != nil && message.NewEntry == nil {
  213. if !strings.HasPrefix(string(sourceOldKey), sourcePath) {
  214. return nil
  215. }
  216. key := buildKey(dataSink, message, targetPath, sourceOldKey, sourcePath)
  217. return dataSink.DeleteEntry(key, message.OldEntry.IsDirectory, message.DeleteChunks, message.Signatures)
  218. }
  219. // handle new entries
  220. if message.OldEntry == nil && message.NewEntry != nil {
  221. if !strings.HasPrefix(string(sourceNewKey), sourcePath) {
  222. return nil
  223. }
  224. key := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  225. return dataSink.CreateEntry(key, message.NewEntry, message.Signatures)
  226. }
  227. // this is something special?
  228. if message.OldEntry == nil && message.NewEntry == nil {
  229. return nil
  230. }
  231. // handle updates
  232. if strings.HasPrefix(string(sourceOldKey), sourcePath) {
  233. // old key is in the watched directory
  234. if strings.HasPrefix(string(sourceNewKey), sourcePath) {
  235. // new key is also in the watched directory
  236. if !dataSink.IsIncremental() {
  237. oldKey := util.Join(targetPath, string(sourceOldKey)[len(sourcePath):])
  238. message.NewParentPath = util.Join(targetPath, message.NewParentPath[len(sourcePath):])
  239. foundExisting, err := dataSink.UpdateEntry(string(oldKey), message.OldEntry, message.NewParentPath, message.NewEntry, message.DeleteChunks, message.Signatures)
  240. if foundExisting {
  241. return err
  242. }
  243. // not able to find old entry
  244. if err = dataSink.DeleteEntry(string(oldKey), message.OldEntry.IsDirectory, false, message.Signatures); err != nil {
  245. return fmt.Errorf("delete old entry %v: %v", oldKey, err)
  246. }
  247. }
  248. // create the new entry
  249. newKey := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  250. return dataSink.CreateEntry(newKey, message.NewEntry, message.Signatures)
  251. } else {
  252. // new key is outside of the watched directory
  253. if !dataSink.IsIncremental() {
  254. key := buildKey(dataSink, message, targetPath, sourceOldKey, sourcePath)
  255. return dataSink.DeleteEntry(key, message.OldEntry.IsDirectory, message.DeleteChunks, message.Signatures)
  256. }
  257. }
  258. } else {
  259. // old key is outside of the watched directory
  260. if strings.HasPrefix(string(sourceNewKey), sourcePath) {
  261. // new key is in the watched directory
  262. key := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  263. return dataSink.CreateEntry(key, message.NewEntry, message.Signatures)
  264. } else {
  265. // new key is also outside of the watched directory
  266. // skip
  267. }
  268. }
  269. return nil
  270. }
  271. return processEventFn
  272. }
  273. func buildKey(dataSink sink.ReplicationSink, message *filer_pb.EventNotification, targetPath string, sourceKey util.FullPath, sourcePath string) (key string) {
  274. if !dataSink.IsIncremental() {
  275. key = util.Join(targetPath, string(sourceKey)[len(sourcePath):])
  276. } else {
  277. var mTime int64
  278. if message.NewEntry != nil {
  279. mTime = message.NewEntry.Attributes.Mtime
  280. } else if message.OldEntry != nil {
  281. mTime = message.OldEntry.Attributes.Mtime
  282. }
  283. dateKey := time.Unix(mTime, 0).Format("2006-01-02")
  284. key = util.Join(targetPath, dateKey, string(sourceKey)[len(sourcePath):])
  285. }
  286. return escapeKey(key)
  287. }