replicator.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package replication
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  8. "github.com/chrislusf/seaweedfs/weed/replication/sink"
  9. "github.com/chrislusf/seaweedfs/weed/replication/source"
  10. "github.com/chrislusf/seaweedfs/weed/util"
  11. )
  12. type Replicator struct {
  13. sink sink.ReplicationSink
  14. source *source.FilerSource
  15. }
  16. func NewReplicator(sourceConfig util.Configuration, configPrefix string, dataSink sink.ReplicationSink) *Replicator {
  17. source := &source.FilerSource{}
  18. source.Initialize(sourceConfig, configPrefix)
  19. dataSink.SetSourceFiler(source)
  20. return &Replicator{
  21. sink: dataSink,
  22. source: source,
  23. }
  24. }
  25. func (r *Replicator) Replicate(ctx context.Context, key string, message *filer_pb.EventNotification) error {
  26. if message.IsFromOtherCluster && r.sink.GetName() == "filer" {
  27. return nil
  28. }
  29. if !strings.HasPrefix(key, r.source.Dir) {
  30. glog.V(4).Infof("skipping %v outside of %v", key, r.source.Dir)
  31. return nil
  32. }
  33. newKey := util.Join(r.sink.GetSinkToDirectory(), key[len(r.source.Dir):])
  34. glog.V(3).Infof("replicate %s => %s", key, newKey)
  35. key = newKey
  36. if message.OldEntry != nil && message.NewEntry == nil {
  37. glog.V(4).Infof("deleting %v", key)
  38. return r.sink.DeleteEntry(key, message.OldEntry.IsDirectory, message.DeleteChunks)
  39. }
  40. if message.OldEntry == nil && message.NewEntry != nil {
  41. glog.V(4).Infof("creating %v", key)
  42. return r.sink.CreateEntry(key, message.NewEntry)
  43. }
  44. if message.OldEntry == nil && message.NewEntry == nil {
  45. glog.V(0).Infof("weird message %+v", message)
  46. return nil
  47. }
  48. foundExisting, err := r.sink.UpdateEntry(key, message.OldEntry, message.NewParentPath, message.NewEntry, message.DeleteChunks)
  49. if foundExisting {
  50. glog.V(4).Infof("updated %v", key)
  51. return err
  52. }
  53. err = r.sink.DeleteEntry(key, message.OldEntry.IsDirectory, false)
  54. if err != nil {
  55. return fmt.Errorf("delete old entry %v: %v", key, err)
  56. }
  57. glog.V(4).Infof("creating missing %v", key)
  58. return r.sink.CreateEntry(key, message.NewEntry)
  59. }