volume_growth.go 9.4 KB

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