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.

282 lines
9.5 KiB

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