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.

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