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.

469 lines
18 KiB

4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package command
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/seaweedfs/seaweedfs/weed/glog"
  7. "github.com/seaweedfs/seaweedfs/weed/pb"
  8. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  9. "github.com/seaweedfs/seaweedfs/weed/replication"
  10. "github.com/seaweedfs/seaweedfs/weed/replication/sink"
  11. "github.com/seaweedfs/seaweedfs/weed/replication/sink/filersink"
  12. "github.com/seaweedfs/seaweedfs/weed/replication/source"
  13. "github.com/seaweedfs/seaweedfs/weed/security"
  14. statsCollect "github.com/seaweedfs/seaweedfs/weed/stats"
  15. "github.com/seaweedfs/seaweedfs/weed/util"
  16. "github.com/seaweedfs/seaweedfs/weed/util/grace"
  17. "google.golang.org/grpc"
  18. "os"
  19. "strings"
  20. "time"
  21. )
  22. type SyncOptions struct {
  23. isActivePassive *bool
  24. filerA *string
  25. filerB *string
  26. aPath *string
  27. aExcludePaths *string
  28. bPath *string
  29. bExcludePaths *string
  30. aReplication *string
  31. bReplication *string
  32. aCollection *string
  33. bCollection *string
  34. aTtlSec *int
  35. bTtlSec *int
  36. aDiskType *string
  37. bDiskType *string
  38. aDebug *bool
  39. bDebug *bool
  40. aFromTsMs *int64
  41. bFromTsMs *int64
  42. aProxyByFiler *bool
  43. bProxyByFiler *bool
  44. metricsHttpPort *int
  45. concurrency *int
  46. clientId int32
  47. clientEpoch int32
  48. }
  49. const (
  50. SyncKeyPrefix = "sync."
  51. DefaultConcurrencyLimit = 32
  52. )
  53. var (
  54. syncOptions SyncOptions
  55. syncCpuProfile *string
  56. syncMemProfile *string
  57. )
  58. func init() {
  59. cmdFilerSynchronize.Run = runFilerSynchronize // break init cycle
  60. syncOptions.isActivePassive = cmdFilerSynchronize.Flag.Bool("isActivePassive", false, "one directional follow from A to B if true")
  61. syncOptions.filerA = cmdFilerSynchronize.Flag.String("a", "", "filer A in one SeaweedFS cluster")
  62. syncOptions.filerB = cmdFilerSynchronize.Flag.String("b", "", "filer B in the other SeaweedFS cluster")
  63. syncOptions.aPath = cmdFilerSynchronize.Flag.String("a.path", "/", "directory to sync on filer A")
  64. syncOptions.aExcludePaths = cmdFilerSynchronize.Flag.String("a.excludePaths", "", "exclude directories to sync on filer A")
  65. syncOptions.bPath = cmdFilerSynchronize.Flag.String("b.path", "/", "directory to sync on filer B")
  66. syncOptions.bExcludePaths = cmdFilerSynchronize.Flag.String("b.excludePaths", "", "exclude directories to sync on filer B")
  67. syncOptions.aReplication = cmdFilerSynchronize.Flag.String("a.replication", "", "replication on filer A")
  68. syncOptions.bReplication = cmdFilerSynchronize.Flag.String("b.replication", "", "replication on filer B")
  69. syncOptions.aCollection = cmdFilerSynchronize.Flag.String("a.collection", "", "collection on filer A")
  70. syncOptions.bCollection = cmdFilerSynchronize.Flag.String("b.collection", "", "collection on filer B")
  71. syncOptions.aTtlSec = cmdFilerSynchronize.Flag.Int("a.ttlSec", 0, "ttl in seconds on filer A")
  72. syncOptions.bTtlSec = cmdFilerSynchronize.Flag.Int("b.ttlSec", 0, "ttl in seconds on filer B")
  73. syncOptions.aDiskType = cmdFilerSynchronize.Flag.String("a.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag on filer A")
  74. syncOptions.bDiskType = cmdFilerSynchronize.Flag.String("b.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag on filer B")
  75. syncOptions.aProxyByFiler = cmdFilerSynchronize.Flag.Bool("a.filerProxy", false, "read and write file chunks by filer A instead of volume servers")
  76. syncOptions.bProxyByFiler = cmdFilerSynchronize.Flag.Bool("b.filerProxy", false, "read and write file chunks by filer B instead of volume servers")
  77. syncOptions.aDebug = cmdFilerSynchronize.Flag.Bool("a.debug", false, "debug mode to print out filer A received files")
  78. syncOptions.bDebug = cmdFilerSynchronize.Flag.Bool("b.debug", false, "debug mode to print out filer B received files")
  79. syncOptions.aFromTsMs = cmdFilerSynchronize.Flag.Int64("a.fromTsMs", 0, "synchronization from timestamp on filer A. The unit is millisecond")
  80. syncOptions.bFromTsMs = cmdFilerSynchronize.Flag.Int64("b.fromTsMs", 0, "synchronization from timestamp on filer B. The unit is millisecond")
  81. syncOptions.concurrency = cmdFilerSynchronize.Flag.Int("concurrency", DefaultConcurrencyLimit, "The maximum number of files that will be synced concurrently.")
  82. syncCpuProfile = cmdFilerSynchronize.Flag.String("cpuprofile", "", "cpu profile output file")
  83. syncMemProfile = cmdFilerSynchronize.Flag.String("memprofile", "", "memory profile output file")
  84. syncOptions.metricsHttpPort = cmdFilerSynchronize.Flag.Int("metricsPort", 0, "metrics listen port")
  85. syncOptions.clientId = util.RandomInt32()
  86. }
  87. var cmdFilerSynchronize = &Command{
  88. UsageLine: "filer.sync -a=<oneFilerHost>:<oneFilerPort> -b=<otherFilerHost>:<otherFilerPort>",
  89. Short: "resumable continuous synchronization between two active-active or active-passive SeaweedFS clusters",
  90. Long: `resumable continuous synchronization for file changes between two active-active or active-passive filers
  91. filer.sync listens on filer notifications. If any file is updated, it will fetch the updated content,
  92. and write to the other destination. Different from filer.replicate:
  93. * filer.sync only works between two filers.
  94. * filer.sync does not need any special message queue setup.
  95. * filer.sync supports both active-active and active-passive modes.
  96. If restarted, the synchronization will resume from the previous checkpoints, persisted every minute.
  97. A fresh sync will start from the earliest metadata logs.
  98. `,
  99. }
  100. func runFilerSynchronize(cmd *Command, args []string) bool {
  101. util.LoadConfiguration("security", false)
  102. grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
  103. grace.SetupProfiling(*syncCpuProfile, *syncMemProfile)
  104. filerA := pb.ServerAddress(*syncOptions.filerA)
  105. filerB := pb.ServerAddress(*syncOptions.filerB)
  106. // start filer.sync metrics server
  107. go statsCollect.StartMetricsServer(*syncOptions.metricsHttpPort)
  108. // read a filer signature
  109. aFilerSignature, aFilerErr := replication.ReadFilerSignature(grpcDialOption, filerA)
  110. if aFilerErr != nil {
  111. glog.Errorf("get filer 'a' signature %d error from %s to %s: %v", aFilerSignature, *syncOptions.filerA, *syncOptions.filerB, aFilerErr)
  112. return true
  113. }
  114. // read b filer signature
  115. bFilerSignature, bFilerErr := replication.ReadFilerSignature(grpcDialOption, filerB)
  116. if bFilerErr != nil {
  117. glog.Errorf("get filer 'b' signature %d error from %s to %s: %v", bFilerSignature, *syncOptions.filerA, *syncOptions.filerB, bFilerErr)
  118. return true
  119. }
  120. go func() {
  121. // a->b
  122. // set synchronization start timestamp to offset
  123. initOffsetError := initOffsetFromTsMs(grpcDialOption, filerB, aFilerSignature, *syncOptions.bFromTsMs, getSignaturePrefixByPath(*syncOptions.aPath))
  124. if initOffsetError != nil {
  125. glog.Errorf("init offset from timestamp %d error from %s to %s: %v", *syncOptions.bFromTsMs, *syncOptions.filerA, *syncOptions.filerB, initOffsetError)
  126. os.Exit(2)
  127. }
  128. for {
  129. syncOptions.clientEpoch++
  130. err := doSubscribeFilerMetaChanges(
  131. syncOptions.clientId,
  132. syncOptions.clientEpoch,
  133. grpcDialOption,
  134. filerA,
  135. *syncOptions.aPath,
  136. util.StringSplit(*syncOptions.aExcludePaths, ","),
  137. *syncOptions.aProxyByFiler,
  138. filerB,
  139. *syncOptions.bPath,
  140. *syncOptions.bReplication,
  141. *syncOptions.bCollection,
  142. *syncOptions.bTtlSec,
  143. *syncOptions.bProxyByFiler,
  144. *syncOptions.bDiskType,
  145. *syncOptions.bDebug,
  146. *syncOptions.concurrency,
  147. aFilerSignature,
  148. bFilerSignature)
  149. if err != nil {
  150. glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err)
  151. time.Sleep(1747 * time.Millisecond)
  152. }
  153. }
  154. }()
  155. if !*syncOptions.isActivePassive {
  156. // b->a
  157. // set synchronization start timestamp to offset
  158. initOffsetError := initOffsetFromTsMs(grpcDialOption, filerA, bFilerSignature, *syncOptions.aFromTsMs, getSignaturePrefixByPath(*syncOptions.bPath))
  159. if initOffsetError != nil {
  160. glog.Errorf("init offset from timestamp %d error from %s to %s: %v", *syncOptions.aFromTsMs, *syncOptions.filerB, *syncOptions.filerA, initOffsetError)
  161. os.Exit(2)
  162. }
  163. go func() {
  164. for {
  165. syncOptions.clientEpoch++
  166. err := doSubscribeFilerMetaChanges(
  167. syncOptions.clientId,
  168. syncOptions.clientEpoch,
  169. grpcDialOption,
  170. filerB,
  171. *syncOptions.bPath,
  172. util.StringSplit(*syncOptions.bExcludePaths, ","),
  173. *syncOptions.bProxyByFiler,
  174. filerA,
  175. *syncOptions.aPath,
  176. *syncOptions.aReplication,
  177. *syncOptions.aCollection,
  178. *syncOptions.aTtlSec,
  179. *syncOptions.aProxyByFiler,
  180. *syncOptions.aDiskType,
  181. *syncOptions.aDebug,
  182. *syncOptions.concurrency,
  183. bFilerSignature,
  184. aFilerSignature)
  185. if err != nil {
  186. glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err)
  187. time.Sleep(2147 * time.Millisecond)
  188. }
  189. }
  190. }()
  191. }
  192. select {}
  193. return true
  194. }
  195. // initOffsetFromTsMs Initialize offset
  196. func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, sourceFilerSignature int32, fromTsMs int64, signaturePrefix string) error {
  197. if fromTsMs <= 0 {
  198. return nil
  199. }
  200. // convert to nanosecond
  201. fromTsNs := fromTsMs * 1000_000
  202. // If not successful, exit the program.
  203. setOffsetErr := setOffset(grpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, fromTsNs)
  204. if setOffsetErr != nil {
  205. return setOffsetErr
  206. }
  207. glog.Infof("setOffset from timestamp ms success! start offset: %d from %s to %s", fromTsNs, *syncOptions.filerA, *syncOptions.filerB)
  208. return nil
  209. }
  210. func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourcePath string, sourceExcludePaths []string, sourceReadChunkFromFiler bool, targetFiler pb.ServerAddress, targetPath string,
  211. replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool, concurrency int, sourceFilerSignature int32, targetFilerSignature int32) error {
  212. // if first time, start from now
  213. // if has previously synced, resume from that point of time
  214. sourceFilerOffsetTsNs, err := getOffset(grpcDialOption, targetFiler, getSignaturePrefixByPath(sourcePath), sourceFilerSignature)
  215. if err != nil {
  216. return err
  217. }
  218. glog.V(0).Infof("start sync %s(%d) => %s(%d) from %v(%d)", sourceFiler, sourceFilerSignature, targetFiler, targetFilerSignature, time.Unix(0, sourceFilerOffsetTsNs), sourceFilerOffsetTsNs)
  219. // create filer sink
  220. filerSource := &source.FilerSource{}
  221. filerSource.DoInitialize(sourceFiler.ToHttpAddress(), sourceFiler.ToGrpcAddress(), sourcePath, sourceReadChunkFromFiler)
  222. filerSink := &filersink.FilerSink{}
  223. filerSink.DoInitialize(targetFiler.ToHttpAddress(), targetFiler.ToGrpcAddress(), targetPath, replicationStr, collection, ttlSec, diskType, grpcDialOption, sinkWriteChunkByFiler)
  224. filerSink.SetSourceFiler(filerSource)
  225. persistEventFn := genProcessFunction(sourcePath, targetPath, sourceExcludePaths, filerSink, debug)
  226. processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
  227. message := resp.EventNotification
  228. for _, sig := range message.Signatures {
  229. if sig == targetFilerSignature && targetFilerSignature != 0 {
  230. fmt.Printf("%s skipping %s change to %v\n", targetFiler, sourceFiler, message)
  231. return nil
  232. }
  233. }
  234. return persistEventFn(resp)
  235. }
  236. if concurrency < 0 || concurrency > 1024 {
  237. glog.Warningf("invalid concurrency value, using default: %d", DefaultConcurrencyLimit)
  238. concurrency = DefaultConcurrencyLimit
  239. }
  240. processor := NewMetadataProcessor(processEventFn, concurrency)
  241. var lastLogTsNs = time.Now().UnixNano()
  242. var clientName = fmt.Sprintf("syncFrom_%s_To_%s", string(sourceFiler), string(targetFiler))
  243. processEventFnWithOffset := pb.AddOffsetFunc(func(resp *filer_pb.SubscribeMetadataResponse) error {
  244. processor.AddSyncJob(resp)
  245. return nil
  246. }, 3*time.Second, func(counter int64, lastTsNs int64) error {
  247. if processor.processedTsWatermark == 0 {
  248. return nil
  249. }
  250. // use processor.processedTsWatermark instead of the lastTsNs from the most recent job
  251. now := time.Now().UnixNano()
  252. glog.V(0).Infof("sync %s to %s progressed to %v %0.2f/sec", sourceFiler, targetFiler, time.Unix(0, processor.processedTsWatermark), float64(counter)/(float64(now-lastLogTsNs)/1e9))
  253. lastLogTsNs = now
  254. // collect synchronous offset
  255. statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(processor.processedTsWatermark))
  256. return setOffset(grpcDialOption, targetFiler, getSignaturePrefixByPath(sourcePath), sourceFilerSignature, processor.processedTsWatermark)
  257. })
  258. return pb.FollowMetadata(sourceFiler, grpcDialOption, clientName, clientId, clientEpoch,
  259. sourcePath, nil, sourceFilerOffsetTsNs, 0, targetFilerSignature, processEventFnWithOffset, pb.RetryForeverOnError)
  260. }
  261. // When each business is distinguished according to path, and offsets need to be maintained separately.
  262. func getSignaturePrefixByPath(path string) string {
  263. // compatible historical version
  264. if path == "/" {
  265. return SyncKeyPrefix
  266. } else {
  267. return SyncKeyPrefix + path
  268. }
  269. }
  270. func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) {
  271. readErr = pb.WithFilerClient(false, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  272. syncKey := []byte(signaturePrefix + "____")
  273. util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
  274. resp, err := client.KvGet(context.Background(), &filer_pb.KvGetRequest{Key: syncKey})
  275. if err != nil {
  276. return err
  277. }
  278. if len(resp.Error) != 0 {
  279. return errors.New(resp.Error)
  280. }
  281. if len(resp.Value) < 8 {
  282. return nil
  283. }
  284. lastOffsetTsNs = int64(util.BytesToUint64(resp.Value))
  285. return nil
  286. })
  287. return
  288. }
  289. func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, offsetTsNs int64) error {
  290. return pb.WithFilerClient(false, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  291. syncKey := []byte(signaturePrefix + "____")
  292. util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
  293. valueBuf := make([]byte, 8)
  294. util.Uint64toBytes(valueBuf, uint64(offsetTsNs))
  295. resp, err := client.KvPut(context.Background(), &filer_pb.KvPutRequest{
  296. Key: syncKey,
  297. Value: valueBuf,
  298. })
  299. if err != nil {
  300. return err
  301. }
  302. if len(resp.Error) != 0 {
  303. return errors.New(resp.Error)
  304. }
  305. return nil
  306. })
  307. }
  308. func genProcessFunction(sourcePath string, targetPath string, excludePaths []string, dataSink sink.ReplicationSink, debug bool) func(resp *filer_pb.SubscribeMetadataResponse) error {
  309. // process function
  310. processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
  311. message := resp.EventNotification
  312. var sourceOldKey, sourceNewKey util.FullPath
  313. if message.OldEntry != nil {
  314. sourceOldKey = util.FullPath(resp.Directory).Child(message.OldEntry.Name)
  315. }
  316. if message.NewEntry != nil {
  317. sourceNewKey = util.FullPath(message.NewParentPath).Child(message.NewEntry.Name)
  318. }
  319. if debug {
  320. glog.V(0).Infof("received %v", resp)
  321. }
  322. if !strings.HasPrefix(resp.Directory, sourcePath) {
  323. return nil
  324. }
  325. for _, excludePath := range excludePaths {
  326. if strings.HasPrefix(resp.Directory, excludePath) {
  327. return nil
  328. }
  329. }
  330. // handle deletions
  331. if filer_pb.IsDelete(resp) {
  332. if !strings.HasPrefix(string(sourceOldKey), sourcePath) {
  333. return nil
  334. }
  335. key := buildKey(dataSink, message, targetPath, sourceOldKey, sourcePath)
  336. if !dataSink.IsIncremental() {
  337. return dataSink.DeleteEntry(key, message.OldEntry.IsDirectory, message.DeleteChunks, message.Signatures)
  338. }
  339. return nil
  340. }
  341. // handle new entries
  342. if filer_pb.IsCreate(resp) {
  343. if !strings.HasPrefix(string(sourceNewKey), sourcePath) {
  344. return nil
  345. }
  346. key := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  347. return dataSink.CreateEntry(key, message.NewEntry, message.Signatures)
  348. }
  349. // this is something special?
  350. if filer_pb.IsEmpty(resp) {
  351. return nil
  352. }
  353. // handle updates
  354. if strings.HasPrefix(string(sourceOldKey), sourcePath) {
  355. // old key is in the watched directory
  356. if strings.HasPrefix(string(sourceNewKey), sourcePath) {
  357. // new key is also in the watched directory
  358. if !dataSink.IsIncremental() {
  359. oldKey := util.Join(targetPath, string(sourceOldKey)[len(sourcePath):])
  360. message.NewParentPath = util.Join(targetPath, message.NewParentPath[len(sourcePath):])
  361. foundExisting, err := dataSink.UpdateEntry(string(oldKey), message.OldEntry, message.NewParentPath, message.NewEntry, message.DeleteChunks, message.Signatures)
  362. if foundExisting {
  363. return err
  364. }
  365. // not able to find old entry
  366. if err = dataSink.DeleteEntry(string(oldKey), message.OldEntry.IsDirectory, false, message.Signatures); err != nil {
  367. return fmt.Errorf("delete old entry %v: %v", oldKey, err)
  368. }
  369. }
  370. // create the new entry
  371. newKey := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  372. return dataSink.CreateEntry(newKey, message.NewEntry, message.Signatures)
  373. } else {
  374. // new key is outside of the watched directory
  375. if !dataSink.IsIncremental() {
  376. key := buildKey(dataSink, message, targetPath, sourceOldKey, sourcePath)
  377. return dataSink.DeleteEntry(key, message.OldEntry.IsDirectory, message.DeleteChunks, message.Signatures)
  378. }
  379. }
  380. } else {
  381. // old key is outside of the watched directory
  382. if strings.HasPrefix(string(sourceNewKey), sourcePath) {
  383. // new key is in the watched directory
  384. key := buildKey(dataSink, message, targetPath, sourceNewKey, sourcePath)
  385. return dataSink.CreateEntry(key, message.NewEntry, message.Signatures)
  386. } else {
  387. // new key is also outside of the watched directory
  388. // skip
  389. }
  390. }
  391. return nil
  392. }
  393. return processEventFn
  394. }
  395. func buildKey(dataSink sink.ReplicationSink, message *filer_pb.EventNotification, targetPath string, sourceKey util.FullPath, sourcePath string) (key string) {
  396. if !dataSink.IsIncremental() {
  397. key = util.Join(targetPath, string(sourceKey)[len(sourcePath):])
  398. } else {
  399. var mTime int64
  400. if message.NewEntry != nil {
  401. mTime = message.NewEntry.Attributes.Mtime
  402. } else if message.OldEntry != nil {
  403. mTime = message.OldEntry.Attributes.Mtime
  404. }
  405. dateKey := time.Unix(mTime, 0).Format("2006-01-02")
  406. key = util.Join(targetPath, dateKey, string(sourceKey)[len(sourcePath):])
  407. }
  408. return escapeKey(key)
  409. }