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.

336 lines
11 KiB

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