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.

290 lines
9.7 KiB

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