volume_growth.go 9.4 KB

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