topology.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package topology
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math/rand/v2"
  7. "sync"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/pb"
  10. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  11. backoff "github.com/cenkalti/backoff/v4"
  12. hashicorpRaft "github.com/hashicorp/raft"
  13. "github.com/seaweedfs/raft"
  14. "github.com/seaweedfs/seaweedfs/weed/glog"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  16. "github.com/seaweedfs/seaweedfs/weed/sequence"
  17. "github.com/seaweedfs/seaweedfs/weed/stats"
  18. "github.com/seaweedfs/seaweedfs/weed/storage"
  19. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  20. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  21. "github.com/seaweedfs/seaweedfs/weed/util"
  22. )
  23. type Topology struct {
  24. vacuumLockCounter int64
  25. NodeImpl
  26. collectionMap *util.ConcurrentReadMap
  27. ecShardMap map[needle.VolumeId]*EcShardLocations
  28. ecShardMapLock sync.RWMutex
  29. pulse int64
  30. volumeSizeLimit uint64
  31. replicationAsMin bool
  32. isDisableVacuum bool
  33. Sequence sequence.Sequencer
  34. chanFullVolumes chan storage.VolumeInfo
  35. chanCrowdedVolumes chan storage.VolumeInfo
  36. Configuration *Configuration
  37. RaftServer raft.Server
  38. RaftServerAccessLock sync.RWMutex
  39. HashicorpRaft *hashicorpRaft.Raft
  40. barrierLock sync.Mutex
  41. barrierDone bool
  42. UuidAccessLock sync.RWMutex
  43. UuidMap map[string][]string
  44. }
  45. func NewTopology(id string, seq sequence.Sequencer, volumeSizeLimit uint64, pulse int, replicationAsMin bool) *Topology {
  46. t := &Topology{}
  47. t.id = NodeId(id)
  48. t.nodeType = "Topology"
  49. t.NodeImpl.value = t
  50. t.diskUsages = newDiskUsages()
  51. t.children = make(map[NodeId]Node)
  52. t.collectionMap = util.NewConcurrentReadMap()
  53. t.ecShardMap = make(map[needle.VolumeId]*EcShardLocations)
  54. t.pulse = int64(pulse)
  55. t.volumeSizeLimit = volumeSizeLimit
  56. t.replicationAsMin = replicationAsMin
  57. t.Sequence = seq
  58. t.chanFullVolumes = make(chan storage.VolumeInfo)
  59. t.chanCrowdedVolumes = make(chan storage.VolumeInfo)
  60. t.Configuration = &Configuration{}
  61. return t
  62. }
  63. func (t *Topology) IsChildLocked() (bool, error) {
  64. if t.IsLocked() {
  65. return true, errors.New("topology is locked")
  66. }
  67. for _, dcNode := range t.Children() {
  68. if dcNode.IsLocked() {
  69. return true, fmt.Errorf("topology child %s is locked", dcNode.String())
  70. }
  71. for _, rackNode := range dcNode.Children() {
  72. if rackNode.IsLocked() {
  73. return true, fmt.Errorf("dc %s child %s is locked", dcNode.String(), rackNode.String())
  74. }
  75. for _, dataNode := range rackNode.Children() {
  76. if dataNode.IsLocked() {
  77. return true, fmt.Errorf("rack %s child %s is locked", rackNode.String(), dataNode.Id())
  78. }
  79. }
  80. }
  81. }
  82. return false, nil
  83. }
  84. func (t *Topology) IsLeader() bool {
  85. t.RaftServerAccessLock.RLock()
  86. defer t.RaftServerAccessLock.RUnlock()
  87. if t.RaftServer != nil {
  88. if t.RaftServer.State() == raft.Leader {
  89. return true
  90. }
  91. if leader, err := t.Leader(); err == nil {
  92. if pb.ServerAddress(t.RaftServer.Name()) == leader {
  93. return true
  94. }
  95. }
  96. } else if t.HashicorpRaft != nil {
  97. if t.HashicorpRaft.State() == hashicorpRaft.Leader {
  98. return true
  99. }
  100. }
  101. return false
  102. }
  103. func (t *Topology) IsLeaderAndCanRead() bool {
  104. if t.RaftServer != nil {
  105. return t.IsLeader()
  106. } else if t.HashicorpRaft != nil {
  107. return t.IsLeader() && t.DoBarrier()
  108. } else {
  109. return false
  110. }
  111. }
  112. func (t *Topology) DoBarrier() bool {
  113. t.barrierLock.Lock()
  114. defer t.barrierLock.Unlock()
  115. if t.barrierDone {
  116. return true
  117. }
  118. glog.V(0).Infof("raft do barrier")
  119. barrier := t.HashicorpRaft.Barrier(2 * time.Minute)
  120. if err := barrier.Error(); err != nil {
  121. glog.Errorf("failed to wait for barrier, error %s", err)
  122. return false
  123. }
  124. t.barrierDone = true
  125. glog.V(0).Infof("raft do barrier success")
  126. return true
  127. }
  128. func (t *Topology) BarrierReset() {
  129. t.barrierLock.Lock()
  130. defer t.barrierLock.Unlock()
  131. t.barrierDone = false
  132. }
  133. func (t *Topology) Leader() (l pb.ServerAddress, err error) {
  134. exponentialBackoff := backoff.NewExponentialBackOff()
  135. exponentialBackoff.InitialInterval = 100 * time.Millisecond
  136. exponentialBackoff.MaxElapsedTime = 20 * time.Second
  137. leaderNotSelected := errors.New("leader not selected yet")
  138. l, err = backoff.RetryWithData(
  139. func() (l pb.ServerAddress, err error) {
  140. l, err = t.MaybeLeader()
  141. if err == nil && l == "" {
  142. err = leaderNotSelected
  143. }
  144. return l, err
  145. },
  146. exponentialBackoff)
  147. if err == leaderNotSelected {
  148. l = ""
  149. }
  150. return l, err
  151. }
  152. func (t *Topology) MaybeLeader() (l pb.ServerAddress, err error) {
  153. t.RaftServerAccessLock.RLock()
  154. defer t.RaftServerAccessLock.RUnlock()
  155. if t.RaftServer != nil {
  156. l = pb.ServerAddress(t.RaftServer.Leader())
  157. } else if t.HashicorpRaft != nil {
  158. l = pb.ServerAddress(t.HashicorpRaft.Leader())
  159. } else {
  160. err = errors.New("Raft Server not ready yet!")
  161. }
  162. return
  163. }
  164. func (t *Topology) Lookup(collection string, vid needle.VolumeId) (dataNodes []*DataNode) {
  165. // maybe an issue if lots of collections?
  166. if collection == "" {
  167. for _, c := range t.collectionMap.Items() {
  168. if list := c.(*Collection).Lookup(vid); list != nil {
  169. return list
  170. }
  171. }
  172. } else {
  173. if c, ok := t.collectionMap.Find(collection); ok {
  174. return c.(*Collection).Lookup(vid)
  175. }
  176. }
  177. if locations, found := t.LookupEcShards(vid); found {
  178. for _, loc := range locations.Locations {
  179. dataNodes = append(dataNodes, loc...)
  180. }
  181. return dataNodes
  182. }
  183. return nil
  184. }
  185. func (t *Topology) NextVolumeId() (needle.VolumeId, error) {
  186. if !t.IsLeaderAndCanRead() {
  187. return 0, fmt.Errorf("as leader can not read yet")
  188. }
  189. vid := t.GetMaxVolumeId()
  190. next := vid.Next()
  191. t.RaftServerAccessLock.RLock()
  192. defer t.RaftServerAccessLock.RUnlock()
  193. if t.RaftServer != nil {
  194. if _, err := t.RaftServer.Do(NewMaxVolumeIdCommand(next)); err != nil {
  195. return 0, err
  196. }
  197. } else if t.HashicorpRaft != nil {
  198. b, err := json.Marshal(NewMaxVolumeIdCommand(next))
  199. if err != nil {
  200. return 0, fmt.Errorf("failed marshal NewMaxVolumeIdCommand: %+v", err)
  201. }
  202. if future := t.HashicorpRaft.Apply(b, time.Second); future.Error() != nil {
  203. return 0, future.Error()
  204. }
  205. }
  206. return next, nil
  207. }
  208. func (t *Topology) PickForWrite(requestedCount uint64, option *VolumeGrowOption, volumeLayout *VolumeLayout) (fileId string, count uint64, volumeLocationList *VolumeLocationList, shouldGrow bool, err error) {
  209. var vid needle.VolumeId
  210. vid, count, volumeLocationList, shouldGrow, err = volumeLayout.PickForWrite(requestedCount, option)
  211. if err != nil {
  212. return "", 0, nil, shouldGrow, fmt.Errorf("failed to find writable volumes for collection:%s replication:%s ttl:%s error: %v", option.Collection, option.ReplicaPlacement.String(), option.Ttl.String(), err)
  213. }
  214. if volumeLocationList == nil || volumeLocationList.Length() == 0 {
  215. return "", 0, nil, shouldGrow, fmt.Errorf("%s available for collection:%s replication:%s ttl:%s", noWritableVolumes, option.Collection, option.ReplicaPlacement.String(), option.Ttl.String())
  216. }
  217. nextFileId := t.Sequence.NextFileId(requestedCount)
  218. fileId = needle.NewFileId(vid, nextFileId, rand.Uint32()).String()
  219. return fileId, count, volumeLocationList, shouldGrow, nil
  220. }
  221. func (t *Topology) GetVolumeLayout(collectionName string, rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType types.DiskType) *VolumeLayout {
  222. return t.collectionMap.Get(collectionName, func() interface{} {
  223. return NewCollection(collectionName, t.volumeSizeLimit, t.replicationAsMin)
  224. }).(*Collection).GetOrCreateVolumeLayout(rp, ttl, diskType)
  225. }
  226. func (t *Topology) ListCollections(includeNormalVolumes, includeEcVolumes bool) (ret []string) {
  227. mapOfCollections := make(map[string]bool)
  228. for _, c := range t.collectionMap.Items() {
  229. mapOfCollections[c.(*Collection).Name] = true
  230. }
  231. if includeEcVolumes {
  232. t.ecShardMapLock.RLock()
  233. for _, ecVolumeLocation := range t.ecShardMap {
  234. mapOfCollections[ecVolumeLocation.Collection] = true
  235. }
  236. t.ecShardMapLock.RUnlock()
  237. }
  238. for k := range mapOfCollections {
  239. ret = append(ret, k)
  240. }
  241. return ret
  242. }
  243. func (t *Topology) FindCollection(collectionName string) (*Collection, bool) {
  244. c, hasCollection := t.collectionMap.Find(collectionName)
  245. if !hasCollection {
  246. return nil, false
  247. }
  248. return c.(*Collection), hasCollection
  249. }
  250. func (t *Topology) DeleteCollection(collectionName string) {
  251. t.collectionMap.Delete(collectionName)
  252. }
  253. func (t *Topology) DeleteLayout(collectionName string, rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType types.DiskType) {
  254. collection, found := t.FindCollection(collectionName)
  255. if !found {
  256. return
  257. }
  258. collection.DeleteVolumeLayout(rp, ttl, diskType)
  259. if len(collection.storageType2VolumeLayout.Items()) == 0 {
  260. t.DeleteCollection(collectionName)
  261. }
  262. }
  263. func (t *Topology) RegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
  264. diskType := types.ToDiskType(v.DiskType)
  265. vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
  266. vl.RegisterVolume(&v, dn)
  267. vl.EnsureCorrectWritables(&v)
  268. }
  269. func (t *Topology) UnRegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
  270. glog.Infof("removing volume info: %+v from %v", v, dn.id)
  271. if v.ReplicaPlacement.GetCopyCount() > 1 {
  272. stats.MasterReplicaPlacementMismatch.WithLabelValues(v.Collection, v.Id.String()).Set(0)
  273. }
  274. diskType := types.ToDiskType(v.DiskType)
  275. volumeLayout := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
  276. volumeLayout.UnRegisterVolume(&v, dn)
  277. if volumeLayout.isEmpty() {
  278. t.DeleteLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
  279. }
  280. }
  281. func (t *Topology) DataCenterExists(dcName string) bool {
  282. return dcName == "" || t.GetDataCenter(dcName) != nil
  283. }
  284. func (t *Topology) GetDataCenter(dcName string) (dc *DataCenter) {
  285. t.RLock()
  286. defer t.RUnlock()
  287. for _, c := range t.children {
  288. dc = c.(*DataCenter)
  289. if string(dc.Id()) == dcName {
  290. return dc
  291. }
  292. }
  293. return dc
  294. }
  295. func (t *Topology) GetOrCreateDataCenter(dcName string) *DataCenter {
  296. t.Lock()
  297. defer t.Unlock()
  298. for _, c := range t.children {
  299. dc := c.(*DataCenter)
  300. if string(dc.Id()) == dcName {
  301. return dc
  302. }
  303. }
  304. dc := NewDataCenter(dcName)
  305. t.doLinkChildNode(dc)
  306. return dc
  307. }
  308. func (t *Topology) ListDataCenters() (dcs []string) {
  309. t.RLock()
  310. defer t.RUnlock()
  311. for _, c := range t.children {
  312. dcs = append(dcs, string(c.(*DataCenter).Id()))
  313. }
  314. return dcs
  315. }
  316. func (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformationMessage, dn *DataNode) (newVolumes, deletedVolumes []storage.VolumeInfo) {
  317. // convert into in memory struct storage.VolumeInfo
  318. var volumeInfos []storage.VolumeInfo
  319. for _, v := range volumes {
  320. if vi, err := storage.NewVolumeInfo(v); err == nil {
  321. volumeInfos = append(volumeInfos, vi)
  322. } else {
  323. glog.V(0).Infof("Fail to convert joined volume information: %v", err)
  324. }
  325. }
  326. // find out the delta volumes
  327. var changedVolumes []storage.VolumeInfo
  328. newVolumes, deletedVolumes, changedVolumes = dn.UpdateVolumes(volumeInfos)
  329. for _, v := range newVolumes {
  330. t.RegisterVolumeLayout(v, dn)
  331. }
  332. for _, v := range deletedVolumes {
  333. t.UnRegisterVolumeLayout(v, dn)
  334. }
  335. for _, v := range changedVolumes {
  336. diskType := types.ToDiskType(v.DiskType)
  337. vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
  338. vl.EnsureCorrectWritables(&v)
  339. }
  340. return
  341. }
  342. func (t *Topology) IncrementalSyncDataNodeRegistration(newVolumes, deletedVolumes []*master_pb.VolumeShortInformationMessage, dn *DataNode) {
  343. var newVis, oldVis []storage.VolumeInfo
  344. for _, v := range newVolumes {
  345. vi, err := storage.NewVolumeInfoFromShort(v)
  346. if err != nil {
  347. glog.V(0).Infof("NewVolumeInfoFromShort %v: %v", v, err)
  348. continue
  349. }
  350. newVis = append(newVis, vi)
  351. }
  352. for _, v := range deletedVolumes {
  353. vi, err := storage.NewVolumeInfoFromShort(v)
  354. if err != nil {
  355. glog.V(0).Infof("NewVolumeInfoFromShort %v: %v", v, err)
  356. continue
  357. }
  358. oldVis = append(oldVis, vi)
  359. }
  360. dn.DeltaUpdateVolumes(newVis, oldVis)
  361. for _, vi := range newVis {
  362. t.RegisterVolumeLayout(vi, dn)
  363. }
  364. for _, vi := range oldVis {
  365. t.UnRegisterVolumeLayout(vi, dn)
  366. }
  367. return
  368. }
  369. func (t *Topology) DataNodeRegistration(dcName, rackName string, dn *DataNode) {
  370. if dn.Parent() != nil {
  371. return
  372. }
  373. // registration to topo
  374. dc := t.GetOrCreateDataCenter(dcName)
  375. rack := dc.GetOrCreateRack(rackName)
  376. rack.LinkChildNode(dn)
  377. glog.Infof("[%s] reLink To topo ", dn.Id())
  378. }
  379. func (t *Topology) DisableVacuum() {
  380. glog.V(0).Infof("DisableVacuum")
  381. t.isDisableVacuum = true
  382. }
  383. func (t *Topology) EnableVacuum() {
  384. glog.V(0).Infof("EnableVacuum")
  385. t.isDisableVacuum = false
  386. }