meta_aggregator.go 7.5 KB

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