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.

270 lines
9.4 KiB

6 years ago
3 years ago
6 years ago
3 years ago
  1. package topology
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  6. "math/rand"
  7. "sync"
  8. "google.golang.org/grpc"
  9. "github.com/seaweedfs/seaweedfs/weed/glog"
  10. "github.com/seaweedfs/seaweedfs/weed/storage"
  11. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  12. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  13. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  14. "github.com/seaweedfs/seaweedfs/weed/util"
  15. )
  16. /*
  17. This package is created to resolve these replica placement issues:
  18. 1. growth factor for each replica level, e.g., add 10 volumes for 1 copy, 20 volumes for 2 copies, 30 volumes for 3 copies
  19. 2. in time of tight storage, how to reduce replica level
  20. 3. optimizing for hot data on faster disk, cold data on cheaper storage,
  21. 4. volume allocation for each bucket
  22. */
  23. type VolumeGrowRequest struct {
  24. Option *VolumeGrowOption
  25. Count int
  26. ErrCh chan error
  27. }
  28. type VolumeGrowOption struct {
  29. Collection string `json:"collection,omitempty"`
  30. ReplicaPlacement *super_block.ReplicaPlacement `json:"replication,omitempty"`
  31. Ttl *needle.TTL `json:"ttl,omitempty"`
  32. DiskType types.DiskType `json:"disk,omitempty"`
  33. Preallocate int64 `json:"preallocate,omitempty"`
  34. DataCenter string `json:"dataCenter,omitempty"`
  35. Rack string `json:"rack,omitempty"`
  36. DataNode string `json:"dataNode,omitempty"`
  37. MemoryMapMaxSizeMb uint32 `json:"memoryMapMaxSizeMb,omitempty"`
  38. }
  39. type VolumeGrowth struct {
  40. accessLock sync.Mutex
  41. }
  42. func (o *VolumeGrowOption) String() string {
  43. blob, _ := json.Marshal(o)
  44. return string(blob)
  45. }
  46. func (o *VolumeGrowOption) Threshold() float64 {
  47. v := util.GetViper()
  48. return v.GetFloat64("master.volume_growth.threshold")
  49. }
  50. func NewDefaultVolumeGrowth() *VolumeGrowth {
  51. return &VolumeGrowth{}
  52. }
  53. // one replication type may need rp.GetCopyCount() actual volumes
  54. // given copyCount, how many logical volumes to create
  55. func (vg *VolumeGrowth) findVolumeCount(copyCount int) (count int) {
  56. v := util.GetViper()
  57. switch copyCount {
  58. case 1:
  59. count = v.GetInt("master.volume_growth.copy_1")
  60. case 2:
  61. count = v.GetInt("master.volume_growth.copy_2")
  62. case 3:
  63. count = v.GetInt("master.volume_growth.copy_3")
  64. default:
  65. count = v.GetInt("master.volume_growth.copy_other")
  66. }
  67. return
  68. }
  69. func (vg *VolumeGrowth) AutomaticGrowByType(option *VolumeGrowOption, grpcDialOption grpc.DialOption, topo *Topology, targetCount int) (result []*master_pb.VolumeLocation, err error) {
  70. if targetCount == 0 {
  71. targetCount = vg.findVolumeCount(option.ReplicaPlacement.GetCopyCount())
  72. }
  73. result, err = vg.GrowByCountAndType(grpcDialOption, targetCount, option, topo)
  74. if len(result) > 0 && len(result)%option.ReplicaPlacement.GetCopyCount() == 0 {
  75. return result, nil
  76. }
  77. return result, err
  78. }
  79. func (vg *VolumeGrowth) GrowByCountAndType(grpcDialOption grpc.DialOption, targetCount int, option *VolumeGrowOption, topo *Topology) (result []*master_pb.VolumeLocation, err error) {
  80. vg.accessLock.Lock()
  81. defer vg.accessLock.Unlock()
  82. for i := 0; i < targetCount; i++ {
  83. if res, e := vg.findAndGrow(grpcDialOption, topo, option); e == nil {
  84. result = append(result, res...)
  85. } else {
  86. glog.V(0).Infof("create %d volume, created %d: %v", targetCount, len(result), e)
  87. return result, e
  88. }
  89. }
  90. return
  91. }
  92. func (vg *VolumeGrowth) findAndGrow(grpcDialOption grpc.DialOption, topo *Topology, option *VolumeGrowOption) (result []*master_pb.VolumeLocation, err error) {
  93. servers, e := vg.findEmptySlotsForOneVolume(topo, option)
  94. if e != nil {
  95. return nil, e
  96. }
  97. vid, raftErr := topo.NextVolumeId()
  98. if raftErr != nil {
  99. return nil, raftErr
  100. }
  101. if err = vg.grow(grpcDialOption, topo, vid, option, servers...); err == nil {
  102. for _, server := range servers {
  103. result = append(result, &master_pb.VolumeLocation{
  104. Url: server.Url(),
  105. PublicUrl: server.PublicUrl,
  106. DataCenter: server.GetDataCenterId(),
  107. NewVids: []uint32{uint32(vid)},
  108. })
  109. }
  110. }
  111. return
  112. }
  113. // 1. find the main data node
  114. // 1.1 collect all data nodes that have 1 slots
  115. // 2.2 collect all racks that have rp.SameRackCount+1
  116. // 2.2 collect all data centers that have DiffRackCount+rp.SameRackCount+1
  117. // 2. find rest data nodes
  118. func (vg *VolumeGrowth) findEmptySlotsForOneVolume(topo *Topology, option *VolumeGrowOption) (servers []*DataNode, err error) {
  119. //find main datacenter and other data centers
  120. rp := option.ReplicaPlacement
  121. mainDataCenter, otherDataCenters, dc_err := topo.PickNodesByWeight(rp.DiffDataCenterCount+1, option, func(node Node) error {
  122. if option.DataCenter != "" && node.IsDataCenter() && node.Id() != NodeId(option.DataCenter) {
  123. return fmt.Errorf("Not matching preferred data center:%s", option.DataCenter)
  124. }
  125. if len(node.Children()) < rp.DiffRackCount+1 {
  126. return fmt.Errorf("Only has %d racks, not enough for %d.", len(node.Children()), rp.DiffRackCount+1)
  127. }
  128. if node.AvailableSpaceFor(option) < int64(rp.DiffRackCount+rp.SameRackCount+1) {
  129. return fmt.Errorf("Free:%d < Expected:%d", node.AvailableSpaceFor(option), rp.DiffRackCount+rp.SameRackCount+1)
  130. }
  131. possibleRacksCount := 0
  132. for _, rack := range node.Children() {
  133. possibleDataNodesCount := 0
  134. for _, n := range rack.Children() {
  135. if n.AvailableSpaceFor(option) >= 1 {
  136. possibleDataNodesCount++
  137. }
  138. }
  139. if possibleDataNodesCount >= rp.SameRackCount+1 {
  140. possibleRacksCount++
  141. }
  142. }
  143. if possibleRacksCount < rp.DiffRackCount+1 {
  144. return fmt.Errorf("Only has %d racks with more than %d free data nodes, not enough for %d.", possibleRacksCount, rp.SameRackCount+1, rp.DiffRackCount+1)
  145. }
  146. return nil
  147. })
  148. if dc_err != nil {
  149. return nil, dc_err
  150. }
  151. //find main rack and other racks
  152. mainRack, otherRacks, rackErr := mainDataCenter.(*DataCenter).PickNodesByWeight(rp.DiffRackCount+1, option, func(node Node) error {
  153. if option.Rack != "" && node.IsRack() && node.Id() != NodeId(option.Rack) {
  154. return fmt.Errorf("Not matching preferred rack:%s", option.Rack)
  155. }
  156. if node.AvailableSpaceFor(option) < int64(rp.SameRackCount+1) {
  157. return fmt.Errorf("Free:%d < Expected:%d", node.AvailableSpaceFor(option), rp.SameRackCount+1)
  158. }
  159. if len(node.Children()) < rp.SameRackCount+1 {
  160. // a bit faster way to test free racks
  161. return fmt.Errorf("Only has %d data nodes, not enough for %d.", len(node.Children()), rp.SameRackCount+1)
  162. }
  163. possibleDataNodesCount := 0
  164. for _, n := range node.Children() {
  165. if n.AvailableSpaceFor(option) >= 1 {
  166. possibleDataNodesCount++
  167. }
  168. }
  169. if possibleDataNodesCount < rp.SameRackCount+1 {
  170. return fmt.Errorf("Only has %d data nodes with a slot, not enough for %d.", possibleDataNodesCount, rp.SameRackCount+1)
  171. }
  172. return nil
  173. })
  174. if rackErr != nil {
  175. return nil, rackErr
  176. }
  177. //find main server and other servers
  178. mainServer, otherServers, serverErr := mainRack.(*Rack).PickNodesByWeight(rp.SameRackCount+1, option, func(node Node) error {
  179. if option.DataNode != "" && node.IsDataNode() && node.Id() != NodeId(option.DataNode) {
  180. return fmt.Errorf("Not matching preferred data node:%s", option.DataNode)
  181. }
  182. if node.AvailableSpaceFor(option) < 1 {
  183. return fmt.Errorf("Free:%d < Expected:%d", node.AvailableSpaceFor(option), 1)
  184. }
  185. return nil
  186. })
  187. if serverErr != nil {
  188. return nil, serverErr
  189. }
  190. servers = append(servers, mainServer.(*DataNode))
  191. for _, server := range otherServers {
  192. servers = append(servers, server.(*DataNode))
  193. }
  194. for _, rack := range otherRacks {
  195. r := rand.Int63n(rack.AvailableSpaceFor(option))
  196. if server, e := rack.ReserveOneVolume(r, option); e == nil {
  197. servers = append(servers, server)
  198. } else {
  199. return servers, e
  200. }
  201. }
  202. for _, datacenter := range otherDataCenters {
  203. r := rand.Int63n(datacenter.AvailableSpaceFor(option))
  204. if server, e := datacenter.ReserveOneVolume(r, option); e == nil {
  205. servers = append(servers, server)
  206. } else {
  207. return servers, e
  208. }
  209. }
  210. return
  211. }
  212. func (vg *VolumeGrowth) grow(grpcDialOption grpc.DialOption, topo *Topology, vid needle.VolumeId, option *VolumeGrowOption, servers ...*DataNode) (growErr error) {
  213. var createdVolumes []storage.VolumeInfo
  214. for _, server := range servers {
  215. if err := AllocateVolume(server, grpcDialOption, vid, option); err == nil {
  216. createdVolumes = append(createdVolumes, storage.VolumeInfo{
  217. Id: vid,
  218. Size: 0,
  219. Collection: option.Collection,
  220. ReplicaPlacement: option.ReplicaPlacement,
  221. Ttl: option.Ttl,
  222. Version: needle.CurrentVersion,
  223. DiskType: option.DiskType.String(),
  224. })
  225. glog.V(0).Infof("Created Volume %d on %s", vid, server.NodeImpl.String())
  226. } else {
  227. glog.Warningf("Failed to assign volume %d on %s: %v", vid, server.NodeImpl.String(), err)
  228. growErr = fmt.Errorf("failed to assign volume %d on %s: %v", vid, server.NodeImpl.String(), err)
  229. break
  230. }
  231. }
  232. if growErr == nil {
  233. for i, vi := range createdVolumes {
  234. server := servers[i]
  235. server.AddOrUpdateVolume(vi)
  236. topo.RegisterVolumeLayout(vi, server)
  237. glog.V(0).Infof("Registered Volume %d on %s", vid, server.NodeImpl.String())
  238. }
  239. } else {
  240. // cleaning up created volume replicas
  241. for i, vi := range createdVolumes {
  242. server := servers[i]
  243. if err := DeleteVolume(server, grpcDialOption, vi.Id); err != nil {
  244. glog.Warningf("Failed to clean up volume %d on %s", vid, server.NodeImpl.String())
  245. }
  246. }
  247. }
  248. return growErr
  249. }