topology.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. package topology
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math/rand"
  7. "sync"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/pb"
  10. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  11. hashicorpRaft "github.com/hashicorp/raft"
  12. "github.com/seaweedfs/raft"
  13. "github.com/seaweedfs/seaweedfs/weed/glog"
  14. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  15. "github.com/seaweedfs/seaweedfs/weed/sequence"
  16. "github.com/seaweedfs/seaweedfs/weed/storage"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  18. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  19. "github.com/seaweedfs/seaweedfs/weed/util"
  20. )
  21. type Topology struct {
  22. vacuumLockCounter int64
  23. NodeImpl
  24. collectionMap *util.ConcurrentReadMap
  25. ecShardMap map[needle.VolumeId]*EcShardLocations
  26. ecShardMapLock sync.RWMutex
  27. pulse int64
  28. volumeSizeLimit uint64
  29. replicationAsMin bool
  30. Sequence sequence.Sequencer
  31. chanFullVolumes chan storage.VolumeInfo
  32. chanCrowdedVolumes chan storage.VolumeInfo
  33. Configuration *Configuration
  34. RaftServer raft.Server
  35. RaftServerAccessLock sync.RWMutex
  36. HashicorpRaft *hashicorpRaft.Raft
  37. UuidAccessLock sync.RWMutex
  38. UuidMap map[string][]string
  39. }
  40. func NewTopology(id string, seq sequence.Sequencer, volumeSizeLimit uint64, pulse int, replicationAsMin bool) *Topology {
  41. t := &Topology{}
  42. t.id = NodeId(id)
  43. t.nodeType = "Topology"
  44. t.NodeImpl.value = t
  45. t.diskUsages = newDiskUsages()
  46. t.children = make(map[NodeId]Node)
  47. t.collectionMap = util.NewConcurrentReadMap()
  48. t.ecShardMap = make(map[needle.VolumeId]*EcShardLocations)
  49. t.pulse = int64(pulse)
  50. t.volumeSizeLimit = volumeSizeLimit
  51. t.replicationAsMin = replicationAsMin
  52. t.Sequence = seq
  53. t.chanFullVolumes = make(chan storage.VolumeInfo)
  54. t.chanCrowdedVolumes = make(chan storage.VolumeInfo)
  55. t.Configuration = &Configuration{}
  56. return t
  57. }
  58. func (t *Topology) IsLeader() bool {
  59. t.RaftServerAccessLock.RLock()
  60. defer t.RaftServerAccessLock.RUnlock()
  61. if t.RaftServer != nil {
  62. if t.RaftServer.State() == raft.Leader {
  63. return true
  64. }
  65. if leader, err := t.Leader(); err == nil {
  66. if pb.ServerAddress(t.RaftServer.Name()) == leader {
  67. return true
  68. }
  69. }
  70. } else if t.HashicorpRaft != nil {
  71. if t.HashicorpRaft.State() == hashicorpRaft.Leader {
  72. return true
  73. }
  74. }
  75. return false
  76. }
  77. func (t *Topology) Leader() (l pb.ServerAddress, err error) {
  78. for count := 0; count < 3; count++ {
  79. l, err = t.MaybeLeader()
  80. if err != nil {
  81. return
  82. }
  83. if l != "" {
  84. break
  85. }
  86. time.Sleep(time.Duration(5+count) * time.Second)
  87. }
  88. return
  89. }
  90. func (t *Topology) MaybeLeader() (l pb.ServerAddress, err error) {
  91. t.RaftServerAccessLock.RLock()
  92. defer t.RaftServerAccessLock.RUnlock()
  93. if t.RaftServer != nil {
  94. l = pb.ServerAddress(t.RaftServer.Leader())
  95. } else if t.HashicorpRaft != nil {
  96. l = pb.ServerAddress(t.HashicorpRaft.Leader())
  97. } else {
  98. err = errors.New("Raft Server not ready yet!")
  99. }
  100. return
  101. }
  102. func (t *Topology) Lookup(collection string, vid needle.VolumeId) (dataNodes []*DataNode) {
  103. // maybe an issue if lots of collections?
  104. if collection == "" {
  105. for _, c := range t.collectionMap.Items() {
  106. if list := c.(*Collection).Lookup(vid); list != nil {
  107. return list
  108. }
  109. }
  110. } else {
  111. if c, ok := t.collectionMap.Find(collection); ok {
  112. return c.(*Collection).Lookup(vid)
  113. }
  114. }
  115. if locations, found := t.LookupEcShards(vid); found {
  116. for _, loc := range locations.Locations {
  117. dataNodes = append(dataNodes, loc...)
  118. }
  119. return dataNodes
  120. }
  121. return nil
  122. }
  123. func (t *Topology) NextVolumeId() (needle.VolumeId, error) {
  124. vid := t.GetMaxVolumeId()
  125. next := vid.Next()
  126. t.RaftServerAccessLock.RLock()
  127. defer t.RaftServerAccessLock.RUnlock()
  128. if t.RaftServer != nil {
  129. if _, err := t.RaftServer.Do(NewMaxVolumeIdCommand(next)); err != nil {
  130. return 0, err
  131. }
  132. } else if t.HashicorpRaft != nil {
  133. b, err := json.Marshal(NewMaxVolumeIdCommand(next))
  134. if err != nil {
  135. return 0, fmt.Errorf("failed marshal NewMaxVolumeIdCommand: %+v", err)
  136. }
  137. if future := t.HashicorpRaft.Apply(b, time.Second); future.Error() != nil {
  138. return 0, future.Error()
  139. }
  140. }
  141. return next, nil
  142. }
  143. // deprecated
  144. func (t *Topology) HasWritableVolume(option *VolumeGrowOption) bool {
  145. vl := t.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl, option.DiskType)
  146. active, _ := vl.GetActiveVolumeCount(option)
  147. return active > 0
  148. }
  149. func (t *Topology) PickForWrite(count uint64, option *VolumeGrowOption) (string, uint64, *VolumeLocationList, error) {
  150. vid, count, datanodes, err := t.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl, option.DiskType).PickForWrite(count, option)
  151. if err != nil {
  152. return "", 0, nil, 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)
  153. }
  154. if datanodes.Length() == 0 {
  155. return "", 0, nil, fmt.Errorf("no writable volumes available for collection:%s replication:%s ttl:%s", option.Collection, option.ReplicaPlacement.String(), option.Ttl.String())
  156. }
  157. fileId := t.Sequence.NextFileId(count)
  158. return needle.NewFileId(*vid, fileId, rand.Uint32()).String(), count, datanodes, nil
  159. }
  160. func (t *Topology) GetVolumeLayout(collectionName string, rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType types.DiskType) *VolumeLayout {
  161. return t.collectionMap.Get(collectionName, func() interface{} {
  162. return NewCollection(collectionName, t.volumeSizeLimit, t.replicationAsMin)
  163. }).(*Collection).GetOrCreateVolumeLayout(rp, ttl, diskType)
  164. }
  165. func (t *Topology) ListCollections(includeNormalVolumes, includeEcVolumes bool) (ret []string) {
  166. mapOfCollections := make(map[string]bool)
  167. for _, c := range t.collectionMap.Items() {
  168. mapOfCollections[c.(*Collection).Name] = true
  169. }
  170. if includeEcVolumes {
  171. t.ecShardMapLock.RLock()
  172. for _, ecVolumeLocation := range t.ecShardMap {
  173. mapOfCollections[ecVolumeLocation.Collection] = true
  174. }
  175. t.ecShardMapLock.RUnlock()
  176. }
  177. for k := range mapOfCollections {
  178. ret = append(ret, k)
  179. }
  180. return ret
  181. }
  182. func (t *Topology) FindCollection(collectionName string) (*Collection, bool) {
  183. c, hasCollection := t.collectionMap.Find(collectionName)
  184. if !hasCollection {
  185. return nil, false
  186. }
  187. return c.(*Collection), hasCollection
  188. }
  189. func (t *Topology) DeleteCollection(collectionName string) {
  190. t.collectionMap.Delete(collectionName)
  191. }
  192. func (t *Topology) DeleteLayout(collectionName string, rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType types.DiskType) {
  193. collection, found := t.FindCollection(collectionName)
  194. if !found {
  195. return
  196. }
  197. collection.DeleteVolumeLayout(rp, ttl, diskType)
  198. if len(collection.storageType2VolumeLayout.Items()) == 0 {
  199. t.DeleteCollection(collectionName)
  200. }
  201. }
  202. func (t *Topology) RegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
  203. diskType := types.ToDiskType(v.DiskType)
  204. vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
  205. vl.RegisterVolume(&v, dn)
  206. vl.EnsureCorrectWritables(&v)
  207. }
  208. func (t *Topology) UnRegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
  209. glog.Infof("removing volume info: %+v from %v", v, dn.id)
  210. diskType := types.ToDiskType(v.DiskType)
  211. volumeLayout := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
  212. volumeLayout.UnRegisterVolume(&v, dn)
  213. if volumeLayout.isEmpty() {
  214. t.DeleteLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
  215. }
  216. }
  217. func (t *Topology) GetOrCreateDataCenter(dcName string) *DataCenter {
  218. t.Lock()
  219. defer t.Unlock()
  220. for _, c := range t.children {
  221. dc := c.(*DataCenter)
  222. if string(dc.Id()) == dcName {
  223. return dc
  224. }
  225. }
  226. dc := NewDataCenter(dcName)
  227. t.doLinkChildNode(dc)
  228. return dc
  229. }
  230. func (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformationMessage, dn *DataNode) (newVolumes, deletedVolumes []storage.VolumeInfo) {
  231. // convert into in memory struct storage.VolumeInfo
  232. var volumeInfos []storage.VolumeInfo
  233. for _, v := range volumes {
  234. if vi, err := storage.NewVolumeInfo(v); err == nil {
  235. volumeInfos = append(volumeInfos, vi)
  236. } else {
  237. glog.V(0).Infof("Fail to convert joined volume information: %v", err)
  238. }
  239. }
  240. // find out the delta volumes
  241. var changedVolumes []storage.VolumeInfo
  242. newVolumes, deletedVolumes, changedVolumes = dn.UpdateVolumes(volumeInfos)
  243. for _, v := range newVolumes {
  244. t.RegisterVolumeLayout(v, dn)
  245. }
  246. for _, v := range deletedVolumes {
  247. t.UnRegisterVolumeLayout(v, dn)
  248. }
  249. for _, v := range changedVolumes {
  250. diskType := types.ToDiskType(v.DiskType)
  251. vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
  252. vl.EnsureCorrectWritables(&v)
  253. }
  254. return
  255. }
  256. func (t *Topology) IncrementalSyncDataNodeRegistration(newVolumes, deletedVolumes []*master_pb.VolumeShortInformationMessage, dn *DataNode) {
  257. var newVis, oldVis []storage.VolumeInfo
  258. for _, v := range newVolumes {
  259. vi, err := storage.NewVolumeInfoFromShort(v)
  260. if err != nil {
  261. glog.V(0).Infof("NewVolumeInfoFromShort %v: %v", v, err)
  262. continue
  263. }
  264. newVis = append(newVis, vi)
  265. }
  266. for _, v := range deletedVolumes {
  267. vi, err := storage.NewVolumeInfoFromShort(v)
  268. if err != nil {
  269. glog.V(0).Infof("NewVolumeInfoFromShort %v: %v", v, err)
  270. continue
  271. }
  272. oldVis = append(oldVis, vi)
  273. }
  274. dn.DeltaUpdateVolumes(newVis, oldVis)
  275. for _, vi := range newVis {
  276. t.RegisterVolumeLayout(vi, dn)
  277. }
  278. for _, vi := range oldVis {
  279. t.UnRegisterVolumeLayout(vi, dn)
  280. }
  281. return
  282. }
  283. func (t *Topology) DataNodeRegistration(dcName, rackName string, dn *DataNode) {
  284. if dn.Parent() != nil {
  285. return
  286. }
  287. // registration to topo
  288. dc := t.GetOrCreateDataCenter(dcName)
  289. rack := dc.GetOrCreateRack(rackName)
  290. rack.LinkChildNode(dn)
  291. glog.Infof("[%s] reLink To topo ", dn.Id())
  292. }