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.

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