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.

284 lines
9.5 KiB

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