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.

341 lines
12 KiB

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