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.

252 lines
7.2 KiB

3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
  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]struct{}
  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]struct{}),
  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. ma.setActive(address, true)
  53. go ma.subscribeToOneFiler(ma.filer, ma.self, address)
  54. } else {
  55. ma.setActive(address, false)
  56. }
  57. }
  58. func (ma *MetaAggregator) setActive(address pb.ServerAddress, isActive bool) {
  59. ma.peerStatuesLock.Lock()
  60. defer ma.peerStatuesLock.Unlock()
  61. if isActive {
  62. ma.peerStatues[address] = struct{}{}
  63. } else {
  64. delete(ma.peerStatues, address)
  65. }
  66. }
  67. func (ma *MetaAggregator) isActive(address pb.ServerAddress)(isActive bool) {
  68. ma.peerStatuesLock.Lock()
  69. defer ma.peerStatuesLock.Unlock()
  70. _, isActive = ma.peerStatues[address]
  71. return
  72. }
  73. func (ma *MetaAggregator) subscribeToOneFiler(f *Filer, self pb.ServerAddress, peer pb.ServerAddress) {
  74. /*
  75. Each filer reads the "filer.store.id", which is the store's signature when filer starts.
  76. When reading from other filers' local meta changes:
  77. * if the received change does not contain signature from self, apply the change to current filer store.
  78. Upon connecting to other filers, need to remember their signature and their offsets.
  79. */
  80. var maybeReplicateMetadataChange func(*filer_pb.SubscribeMetadataResponse)
  81. lastPersistTime := time.Now()
  82. lastTsNs := time.Now().Add(-LogFlushInterval).UnixNano()
  83. peerSignature, err := ma.readFilerStoreSignature(peer)
  84. for err != nil {
  85. glog.V(0).Infof("connecting to peer filer %s: %v", peer, err)
  86. time.Sleep(1357 * time.Millisecond)
  87. peerSignature, err = ma.readFilerStoreSignature(peer)
  88. }
  89. // when filer store is not shared by multiple filers
  90. if peerSignature != f.Signature {
  91. lastTsNs = 0
  92. if prevTsNs, err := ma.readOffset(f, peer, peerSignature); err == nil {
  93. lastTsNs = prevTsNs
  94. }
  95. glog.V(0).Infof("follow peer: %v, last %v (%d)", peer, time.Unix(0, lastTsNs), lastTsNs)
  96. var counter int64
  97. var synced bool
  98. maybeReplicateMetadataChange = func(event *filer_pb.SubscribeMetadataResponse) {
  99. if err := Replay(f.Store, event); err != nil {
  100. glog.Errorf("failed to reply metadata change from %v: %v", peer, err)
  101. return
  102. }
  103. counter++
  104. if lastPersistTime.Add(time.Minute).Before(time.Now()) {
  105. if err := ma.updateOffset(f, peer, peerSignature, event.TsNs); err == nil {
  106. if event.TsNs < time.Now().Add(-2*time.Minute).UnixNano() {
  107. glog.V(0).Infof("sync with %s progressed to: %v %0.2f/sec", peer, time.Unix(0, event.TsNs), float64(counter)/60.0)
  108. } else if !synced {
  109. synced = true
  110. glog.V(0).Infof("synced with %s", peer)
  111. }
  112. lastPersistTime = time.Now()
  113. counter = 0
  114. } else {
  115. glog.V(0).Infof("failed to update offset for %v: %v", peer, err)
  116. }
  117. }
  118. }
  119. }
  120. processEventFn := func(event *filer_pb.SubscribeMetadataResponse) error {
  121. data, err := proto.Marshal(event)
  122. if err != nil {
  123. glog.Errorf("failed to marshal subscribed filer_pb.SubscribeMetadataResponse %+v: %v", event, err)
  124. return err
  125. }
  126. dir := event.Directory
  127. // println("received meta change", dir, "size", len(data))
  128. ma.MetaLogBuffer.AddToBuffer([]byte(dir), data, event.TsNs)
  129. if maybeReplicateMetadataChange != nil {
  130. maybeReplicateMetadataChange(event)
  131. }
  132. return nil
  133. }
  134. for {
  135. glog.V(4).Infof("subscribing remote %s meta change: %v", peer, time.Unix(0, lastTsNs))
  136. err := pb.WithFilerClient(peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  137. ctx, cancel := context.WithCancel(context.Background())
  138. defer cancel()
  139. stream, err := client.SubscribeLocalMetadata(ctx, &filer_pb.SubscribeMetadataRequest{
  140. ClientName: "filer:" + string(self),
  141. PathPrefix: "/",
  142. SinceNs: lastTsNs,
  143. })
  144. if err != nil {
  145. return fmt.Errorf("subscribe: %v", err)
  146. }
  147. for {
  148. resp, listenErr := stream.Recv()
  149. if listenErr == io.EOF {
  150. return nil
  151. }
  152. if listenErr != nil {
  153. return listenErr
  154. }
  155. if err := processEventFn(resp); err != nil {
  156. return fmt.Errorf("process %v: %v", resp, err)
  157. }
  158. lastTsNs = resp.TsNs
  159. f.onMetadataChangeEvent(resp)
  160. }
  161. })
  162. if !ma.isActive(peer) {
  163. glog.V(0).Infof("stop subscribing remote %s meta change", peer)
  164. return
  165. }
  166. if err != nil {
  167. glog.V(0).Infof("subscribing remote %s meta change: %v", peer, err)
  168. time.Sleep(1733 * time.Millisecond)
  169. }
  170. }
  171. }
  172. func (ma *MetaAggregator) readFilerStoreSignature(peer pb.ServerAddress) (sig int32, err error) {
  173. err = pb.WithFilerClient(peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  174. resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
  175. if err != nil {
  176. return err
  177. }
  178. sig = resp.Signature
  179. return nil
  180. })
  181. return
  182. }
  183. const (
  184. MetaOffsetPrefix = "Meta"
  185. )
  186. func (ma *MetaAggregator) readOffset(f *Filer, peer pb.ServerAddress, peerSignature int32) (lastTsNs int64, err error) {
  187. key := []byte(MetaOffsetPrefix + "xxxx")
  188. util.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))
  189. value, err := f.Store.KvGet(context.Background(), key)
  190. if err == ErrKvNotFound {
  191. glog.Warningf("readOffset %s not found", peer)
  192. return 0, nil
  193. }
  194. if err != nil {
  195. return 0, fmt.Errorf("readOffset %s : %v", peer, err)
  196. }
  197. lastTsNs = int64(util.BytesToUint64(value))
  198. glog.V(0).Infof("readOffset %s : %d", peer, lastTsNs)
  199. return
  200. }
  201. func (ma *MetaAggregator) updateOffset(f *Filer, peer pb.ServerAddress, peerSignature int32, lastTsNs int64) (err error) {
  202. key := []byte(MetaOffsetPrefix + "xxxx")
  203. util.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))
  204. value := make([]byte, 8)
  205. util.Uint64toBytes(value, uint64(lastTsNs))
  206. err = f.Store.KvPut(context.Background(), key, value)
  207. if err != nil {
  208. return fmt.Errorf("updateOffset %s : %v", peer, err)
  209. }
  210. glog.V(4).Infof("updateOffset %s : %d", peer, lastTsNs)
  211. return
  212. }