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.

263 lines
8.1 KiB

6 years ago
6 years ago
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "sync"
  8. "time"
  9. "github.com/chrislusf/seaweedfs/weed/operation"
  10. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  11. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  12. "github.com/chrislusf/seaweedfs/weed/storage/erasure_coding"
  13. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  14. "github.com/chrislusf/seaweedfs/weed/wdclient"
  15. "google.golang.org/grpc"
  16. )
  17. func init() {
  18. Commands = append(Commands, &commandEcEncode{})
  19. }
  20. type commandEcEncode struct {
  21. }
  22. func (c *commandEcEncode) Name() string {
  23. return "ec.encode"
  24. }
  25. func (c *commandEcEncode) Help() string {
  26. return `apply erasure coding to a volume
  27. ec.encode [-collection=""] [-fullPercent=95] [-quietFor=1h]
  28. ec.encode [-collection=""] [-volumeId=<volume_id>]
  29. This command will:
  30. 1. freeze one volume
  31. 2. apply erasure coding to the volume
  32. 3. move the encoded shards to multiple volume servers
  33. The erasure coding is 10.4. So ideally you have more than 14 volume servers, and you can afford
  34. to lose 4 volume servers.
  35. If the number of volumes are not high, the worst case is that you only have 4 volume servers,
  36. and the shards are spread as 4,4,3,3, respectively. You can afford to lose one volume server.
  37. If you only have less than 4 volume servers, with erasure coding, at least you can afford to
  38. have 4 corrupted shard files.
  39. `
  40. }
  41. func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  42. encodeCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  43. volumeId := encodeCommand.Int("volumeId", 0, "the volume id")
  44. collection := encodeCommand.String("collection", "", "the collection name")
  45. fullPercentage := encodeCommand.Float64("fullPercent", 95, "the volume reaches the percentage of max volume size")
  46. quietPeriod := encodeCommand.Duration("quietFor", time.Hour, "select volumes without no writes for this period")
  47. if err = encodeCommand.Parse(args); err != nil {
  48. return nil
  49. }
  50. ctx := context.Background()
  51. vid := needle.VolumeId(*volumeId)
  52. // volumeId is provided
  53. if vid != 0 {
  54. return doEcEncode(ctx, commandEnv, *collection, vid)
  55. }
  56. // apply to all volumes in the collection
  57. volumeIds, err := collectVolumeIdsForEcEncode(ctx, commandEnv, *collection, *fullPercentage, *quietPeriod)
  58. if err != nil {
  59. return err
  60. }
  61. fmt.Printf("ec encode volumes: %v\n", volumeIds)
  62. for _, vid := range volumeIds {
  63. if err = doEcEncode(ctx, commandEnv, *collection, vid); err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }
  69. func doEcEncode(ctx context.Context, commandEnv *CommandEnv, collection string, vid needle.VolumeId) (err error) {
  70. // find volume location
  71. locations := commandEnv.MasterClient.GetLocations(uint32(vid))
  72. if len(locations) == 0 {
  73. return fmt.Errorf("volume %d not found", vid)
  74. }
  75. // generate ec shards
  76. err = generateEcShards(ctx, commandEnv.option.GrpcDialOption, needle.VolumeId(vid), collection, locations[0].Url)
  77. if err != nil {
  78. return fmt.Errorf("generate ec shards for volume %d on %s: %v", vid, locations[0].Url, err)
  79. }
  80. // balance the ec shards to current cluster
  81. err = spreadEcShards(ctx, commandEnv, vid, collection, locations)
  82. if err != nil {
  83. return fmt.Errorf("spread ec shards for volume %d from %s: %v", vid, locations[0].Url, err)
  84. }
  85. return nil
  86. }
  87. func generateEcShards(ctx context.Context, grpcDialOption grpc.DialOption, volumeId needle.VolumeId, collection string, sourceVolumeServer string) error {
  88. err := operation.WithVolumeServerClient(sourceVolumeServer, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  89. _, genErr := volumeServerClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
  90. VolumeId: uint32(volumeId),
  91. Collection: collection,
  92. })
  93. return genErr
  94. })
  95. return err
  96. }
  97. func spreadEcShards(ctx context.Context, commandEnv *CommandEnv, volumeId needle.VolumeId, collection string, existingLocations []wdclient.Location) (err error) {
  98. allEcNodes, totalFreeEcSlots, err := collectEcNodes(ctx, commandEnv, "")
  99. if err != nil {
  100. return err
  101. }
  102. if totalFreeEcSlots < erasure_coding.TotalShardsCount {
  103. return fmt.Errorf("not enough free ec shard slots. only %d left", totalFreeEcSlots)
  104. }
  105. allocatedDataNodes := allEcNodes
  106. if len(allocatedDataNodes) > erasure_coding.TotalShardsCount {
  107. allocatedDataNodes = allocatedDataNodes[:erasure_coding.TotalShardsCount]
  108. }
  109. // calculate how many shards to allocate for these servers
  110. allocated := balancedEcDistribution(allocatedDataNodes)
  111. // ask the data nodes to copy from the source volume server
  112. copiedShardIds, err := parallelCopyEcShardsFromSource(ctx, commandEnv.option.GrpcDialOption, allocatedDataNodes, allocated, volumeId, collection, existingLocations[0])
  113. if err != nil {
  114. return err
  115. }
  116. // unmount the to be deleted shards
  117. err = unmountEcShards(ctx, commandEnv.option.GrpcDialOption, volumeId, existingLocations[0].Url, copiedShardIds)
  118. if err != nil {
  119. return err
  120. }
  121. // ask the source volume server to clean up copied ec shards
  122. err = sourceServerDeleteEcShards(ctx, commandEnv.option.GrpcDialOption, collection, volumeId, existingLocations[0].Url, copiedShardIds)
  123. if err != nil {
  124. return fmt.Errorf("source delete copied ecShards %s %d.%v: %v", existingLocations[0].Url, volumeId, copiedShardIds, err)
  125. }
  126. // ask the source volume server to delete the original volume
  127. for _, location := range existingLocations {
  128. err = deleteVolume(ctx, commandEnv.option.GrpcDialOption, volumeId, location.Url)
  129. if err != nil {
  130. return fmt.Errorf("deleteVolume %s volume %d: %v", location.Url, volumeId, err)
  131. }
  132. }
  133. return err
  134. }
  135. func parallelCopyEcShardsFromSource(ctx context.Context, grpcDialOption grpc.DialOption,
  136. targetServers []*EcNode, allocated []int,
  137. volumeId needle.VolumeId, collection string, existingLocation wdclient.Location) (actuallyCopied []uint32, err error) {
  138. // parallelize
  139. shardIdChan := make(chan []uint32, len(targetServers))
  140. var wg sync.WaitGroup
  141. startFromShardId := uint32(0)
  142. for i, server := range targetServers {
  143. if allocated[i] <= 0 {
  144. continue
  145. }
  146. wg.Add(1)
  147. go func(server *EcNode, startFromShardId uint32, shardCount int) {
  148. defer wg.Done()
  149. copiedShardIds, copyErr := oneServerCopyAndMountEcShardsFromSource(ctx, grpcDialOption, server,
  150. startFromShardId, shardCount, volumeId, collection, existingLocation.Url)
  151. if copyErr != nil {
  152. err = copyErr
  153. } else {
  154. shardIdChan <- copiedShardIds
  155. server.addEcVolumeShards(volumeId, collection, copiedShardIds)
  156. }
  157. }(server, startFromShardId, allocated[i])
  158. startFromShardId += uint32(allocated[i])
  159. }
  160. wg.Wait()
  161. close(shardIdChan)
  162. if err != nil {
  163. return nil, err
  164. }
  165. for shardIds := range shardIdChan {
  166. actuallyCopied = append(actuallyCopied, shardIds...)
  167. }
  168. return
  169. }
  170. func balancedEcDistribution(servers []*EcNode) (allocated []int) {
  171. allocated = make([]int, len(servers))
  172. allocatedCount := 0
  173. for allocatedCount < erasure_coding.TotalShardsCount {
  174. for i, server := range servers {
  175. if server.freeEcSlot-allocated[i] > 0 {
  176. allocated[i] += 1
  177. allocatedCount += 1
  178. }
  179. if allocatedCount >= erasure_coding.TotalShardsCount {
  180. break
  181. }
  182. }
  183. }
  184. return allocated
  185. }
  186. func collectVolumeIdsForEcEncode(ctx context.Context, commandEnv *CommandEnv, selectedCollection string, fullPercentage float64, quietPeriod time.Duration) (vids []needle.VolumeId, err error) {
  187. var resp *master_pb.VolumeListResponse
  188. err = commandEnv.MasterClient.WithClient(ctx, func(client master_pb.SeaweedClient) error {
  189. resp, err = client.VolumeList(ctx, &master_pb.VolumeListRequest{})
  190. return err
  191. })
  192. if err != nil {
  193. return
  194. }
  195. quietSeconds := int64(quietPeriod / time.Second)
  196. nowUnixSeconds := time.Now().Unix()
  197. fmt.Printf("ec encode volumes quiet for: %d seconds\n", quietSeconds)
  198. vidMap := make(map[uint32]bool)
  199. eachDataNode(resp.TopologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  200. for _, v := range dn.VolumeInfos {
  201. if v.Collection == selectedCollection && v.ModifiedAtSecond+quietSeconds < nowUnixSeconds {
  202. if float64(v.Size) > fullPercentage/100*float64(resp.VolumeSizeLimitMb)*1024*1024 {
  203. vidMap[v.Id] = true
  204. }
  205. }
  206. }
  207. })
  208. for vid, _ := range vidMap {
  209. vids = append(vids, needle.VolumeId(vid))
  210. }
  211. return
  212. }