meta_aggregator.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package filer
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/util"
  6. "io"
  7. "sync"
  8. "time"
  9. "github.com/golang/protobuf/proto"
  10. "google.golang.org/grpc"
  11. "github.com/chrislusf/seaweedfs/weed/glog"
  12. "github.com/chrislusf/seaweedfs/weed/pb"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. "github.com/chrislusf/seaweedfs/weed/util/log_buffer"
  15. )
  16. type MetaAggregator struct {
  17. filers []string
  18. grpcDialOption grpc.DialOption
  19. MetaLogBuffer *log_buffer.LogBuffer
  20. // notifying clients
  21. ListenersLock sync.Mutex
  22. ListenersCond *sync.Cond
  23. }
  24. // MetaAggregator only aggregates data "on the fly". The logs are not re-persisted to disk.
  25. // The old data comes from what each LocalMetadata persisted on disk.
  26. func NewMetaAggregator(filers []string, grpcDialOption grpc.DialOption) *MetaAggregator {
  27. t := &MetaAggregator{
  28. filers: filers,
  29. grpcDialOption: grpcDialOption,
  30. }
  31. t.ListenersCond = sync.NewCond(&t.ListenersLock)
  32. t.MetaLogBuffer = log_buffer.NewLogBuffer(LogFlushInterval, nil, func() {
  33. t.ListenersCond.Broadcast()
  34. })
  35. return t
  36. }
  37. func (ma *MetaAggregator) StartLoopSubscribe(f *Filer, self string) {
  38. for _, filer := range ma.filers {
  39. go ma.subscribeToOneFiler(f, self, filer)
  40. }
  41. }
  42. func (ma *MetaAggregator) subscribeToOneFiler(f *Filer, self string, peer string) {
  43. /*
  44. Each filer reads the "filer.store.id", which is the store's signature when filer starts.
  45. When reading from other filers' local meta changes:
  46. * if the received change does not contain signature from self, apply the change to current filer store.
  47. Upon connecting to other filers, need to remember their signature and their offsets.
  48. */
  49. var maybeReplicateMetadataChange func(*filer_pb.SubscribeMetadataResponse)
  50. lastPersistTime := time.Now()
  51. lastTsNs := time.Now().Add(-LogFlushInterval).UnixNano()
  52. peerSignature, err := ma.readFilerStoreSignature(peer)
  53. for err != nil {
  54. glog.V(0).Infof("connecting to peer filer %s: %v", peer, err)
  55. time.Sleep(1357 * time.Millisecond)
  56. peerSignature, err = ma.readFilerStoreSignature(peer)
  57. }
  58. // when filer store is not shared by multiple filers
  59. if peerSignature != f.Signature {
  60. if prevTsNs, err := ma.readOffset(f, peer, peerSignature); err == nil {
  61. lastTsNs = prevTsNs
  62. }
  63. glog.V(0).Infof("follow peer: %v, last %v (%d)", peer, time.Unix(0, lastTsNs), lastTsNs)
  64. var counter int64
  65. var synced bool
  66. maybeReplicateMetadataChange = func(event *filer_pb.SubscribeMetadataResponse) {
  67. if err := Replay(f.Store, event); err != nil {
  68. glog.Errorf("failed to reply metadata change from %v: %v", peer, err)
  69. return
  70. }
  71. counter++
  72. if lastPersistTime.Add(time.Minute).Before(time.Now()) {
  73. if err := ma.updateOffset(f, peer, peerSignature, event.TsNs); err == nil {
  74. if event.TsNs < time.Now().Add(-2*time.Minute).UnixNano() {
  75. glog.V(0).Infof("sync with %s progressed to: %v %0.2f/sec", peer, time.Unix(0, event.TsNs), float64(counter)/60.0)
  76. } else if !synced {
  77. synced = true
  78. glog.V(0).Infof("synced with %s", peer)
  79. }
  80. lastPersistTime = time.Now()
  81. counter = 0
  82. } else {
  83. glog.V(0).Infof("failed to update offset for %v: %v", peer, err)
  84. }
  85. }
  86. }
  87. }
  88. processEventFn := func(event *filer_pb.SubscribeMetadataResponse) error {
  89. data, err := proto.Marshal(event)
  90. if err != nil {
  91. glog.Errorf("failed to marshal subscribed filer_pb.SubscribeMetadataResponse %+v: %v", event, err)
  92. return err
  93. }
  94. dir := event.Directory
  95. // println("received meta change", dir, "size", len(data))
  96. ma.MetaLogBuffer.AddToBuffer([]byte(dir), data, 0)
  97. if maybeReplicateMetadataChange != nil {
  98. maybeReplicateMetadataChange(event)
  99. }
  100. return nil
  101. }
  102. for {
  103. err := pb.WithFilerClient(peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  104. ctx, cancel := context.WithCancel(context.Background())
  105. defer cancel()
  106. stream, err := client.SubscribeLocalMetadata(ctx, &filer_pb.SubscribeMetadataRequest{
  107. ClientName: "filer:" + self,
  108. PathPrefix: "/",
  109. SinceNs: lastTsNs,
  110. })
  111. if err != nil {
  112. return fmt.Errorf("subscribe: %v", err)
  113. }
  114. for {
  115. resp, listenErr := stream.Recv()
  116. if listenErr == io.EOF {
  117. return nil
  118. }
  119. if listenErr != nil {
  120. return listenErr
  121. }
  122. if err := processEventFn(resp); err != nil {
  123. return fmt.Errorf("process %v: %v", resp, err)
  124. }
  125. lastTsNs = resp.TsNs
  126. f.onMetadataChangeEvent(resp)
  127. }
  128. })
  129. if err != nil {
  130. glog.V(0).Infof("subscribing remote %s meta change: %v", peer, err)
  131. time.Sleep(1733 * time.Millisecond)
  132. }
  133. }
  134. }
  135. func (ma *MetaAggregator) readFilerStoreSignature(peer string) (sig int32, err error) {
  136. err = pb.WithFilerClient(peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  137. resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
  138. if err != nil {
  139. return err
  140. }
  141. sig = resp.Signature
  142. return nil
  143. })
  144. return
  145. }
  146. const (
  147. MetaOffsetPrefix = "Meta"
  148. )
  149. func (ma *MetaAggregator) readOffset(f *Filer, peer string, peerSignature int32) (lastTsNs int64, err error) {
  150. key := []byte(MetaOffsetPrefix + "xxxx")
  151. util.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))
  152. value, err := f.Store.KvGet(context.Background(), key)
  153. if err == ErrKvNotFound {
  154. glog.Warningf("readOffset %s not found", peer)
  155. return 0, nil
  156. }
  157. if err != nil {
  158. return 0, fmt.Errorf("readOffset %s : %v", peer, err)
  159. }
  160. lastTsNs = int64(util.BytesToUint64(value))
  161. glog.V(0).Infof("readOffset %s : %d", peer, lastTsNs)
  162. return
  163. }
  164. func (ma *MetaAggregator) updateOffset(f *Filer, peer string, peerSignature int32, lastTsNs int64) (err error) {
  165. key := []byte(MetaOffsetPrefix + "xxxx")
  166. util.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))
  167. value := make([]byte, 8)
  168. util.Uint64toBytes(value, uint64(lastTsNs))
  169. err = f.Store.KvPut(context.Background(), key, value)
  170. if err != nil {
  171. return fmt.Errorf("updateOffset %s : %v", peer, err)
  172. }
  173. glog.V(4).Infof("updateOffset %s : %d", peer, lastTsNs)
  174. return
  175. }