command_ec_encode.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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, found := commandEnv.MasterClient.GetLocations(uint32(vid))
  72. if !found {
  73. return fmt.Errorf("volume %d not found", vid)
  74. }
  75. // mark the volume as readonly
  76. err = markVolumeReadonly(ctx, commandEnv.option.GrpcDialOption, needle.VolumeId(vid), locations)
  77. if err != nil {
  78. return fmt.Errorf("generate ec shards for volume %d on %s: %v", vid, locations[0].Url, err)
  79. }
  80. // generate ec shards
  81. err = generateEcShards(ctx, commandEnv.option.GrpcDialOption, needle.VolumeId(vid), collection, locations[0].Url)
  82. if err != nil {
  83. return fmt.Errorf("generate ec shards for volume %d on %s: %v", vid, locations[0].Url, err)
  84. }
  85. // balance the ec shards to current cluster
  86. err = spreadEcShards(ctx, commandEnv, vid, collection, locations)
  87. if err != nil {
  88. return fmt.Errorf("spread ec shards for volume %d from %s: %v", vid, locations[0].Url, err)
  89. }
  90. return nil
  91. }
  92. func markVolumeReadonly(ctx context.Context, grpcDialOption grpc.DialOption, volumeId needle.VolumeId, locations []wdclient.Location) error {
  93. for _, location := range locations {
  94. err := operation.WithVolumeServerClient(location.Url, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  95. _, markErr := volumeServerClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{
  96. VolumeId: uint32(volumeId),
  97. })
  98. return markErr
  99. })
  100. if err != nil {
  101. return err
  102. }
  103. }
  104. return nil
  105. }
  106. func generateEcShards(ctx context.Context, grpcDialOption grpc.DialOption, volumeId needle.VolumeId, collection string, sourceVolumeServer string) error {
  107. err := operation.WithVolumeServerClient(sourceVolumeServer, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  108. _, genErr := volumeServerClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
  109. VolumeId: uint32(volumeId),
  110. Collection: collection,
  111. })
  112. return genErr
  113. })
  114. return err
  115. }
  116. func spreadEcShards(ctx context.Context, commandEnv *CommandEnv, volumeId needle.VolumeId, collection string, existingLocations []wdclient.Location) (err error) {
  117. allEcNodes, totalFreeEcSlots, err := collectEcNodes(ctx, commandEnv, "")
  118. if err != nil {
  119. return err
  120. }
  121. if totalFreeEcSlots < erasure_coding.TotalShardsCount {
  122. return fmt.Errorf("not enough free ec shard slots. only %d left", totalFreeEcSlots)
  123. }
  124. allocatedDataNodes := allEcNodes
  125. if len(allocatedDataNodes) > erasure_coding.TotalShardsCount {
  126. allocatedDataNodes = allocatedDataNodes[:erasure_coding.TotalShardsCount]
  127. }
  128. // calculate how many shards to allocate for these servers
  129. allocated := balancedEcDistribution(allocatedDataNodes)
  130. // ask the data nodes to copy from the source volume server
  131. copiedShardIds, err := parallelCopyEcShardsFromSource(ctx, commandEnv.option.GrpcDialOption, allocatedDataNodes, allocated, volumeId, collection, existingLocations[0])
  132. if err != nil {
  133. return err
  134. }
  135. // unmount the to be deleted shards
  136. err = unmountEcShards(ctx, commandEnv.option.GrpcDialOption, volumeId, existingLocations[0].Url, copiedShardIds)
  137. if err != nil {
  138. return err
  139. }
  140. // ask the source volume server to clean up copied ec shards
  141. err = sourceServerDeleteEcShards(ctx, commandEnv.option.GrpcDialOption, collection, volumeId, existingLocations[0].Url, copiedShardIds)
  142. if err != nil {
  143. return fmt.Errorf("source delete copied ecShards %s %d.%v: %v", existingLocations[0].Url, volumeId, copiedShardIds, err)
  144. }
  145. // ask the source volume server to delete the original volume
  146. for _, location := range existingLocations {
  147. err = deleteVolume(ctx, commandEnv.option.GrpcDialOption, volumeId, location.Url)
  148. if err != nil {
  149. return fmt.Errorf("deleteVolume %s volume %d: %v", location.Url, volumeId, err)
  150. }
  151. }
  152. return err
  153. }
  154. func parallelCopyEcShardsFromSource(ctx context.Context, grpcDialOption grpc.DialOption,
  155. targetServers []*EcNode, allocated []int,
  156. volumeId needle.VolumeId, collection string, existingLocation wdclient.Location) (actuallyCopied []uint32, err error) {
  157. // parallelize
  158. shardIdChan := make(chan []uint32, len(targetServers))
  159. var wg sync.WaitGroup
  160. startFromShardId := uint32(0)
  161. for i, server := range targetServers {
  162. if allocated[i] <= 0 {
  163. continue
  164. }
  165. wg.Add(1)
  166. go func(server *EcNode, startFromShardId uint32, shardCount int) {
  167. defer wg.Done()
  168. copiedShardIds, copyErr := oneServerCopyAndMountEcShardsFromSource(ctx, grpcDialOption, server,
  169. startFromShardId, shardCount, volumeId, collection, existingLocation.Url)
  170. if copyErr != nil {
  171. err = copyErr
  172. } else {
  173. shardIdChan <- copiedShardIds
  174. server.addEcVolumeShards(volumeId, collection, copiedShardIds)
  175. }
  176. }(server, startFromShardId, allocated[i])
  177. startFromShardId += uint32(allocated[i])
  178. }
  179. wg.Wait()
  180. close(shardIdChan)
  181. if err != nil {
  182. return nil, err
  183. }
  184. for shardIds := range shardIdChan {
  185. actuallyCopied = append(actuallyCopied, shardIds...)
  186. }
  187. return
  188. }
  189. func balancedEcDistribution(servers []*EcNode) (allocated []int) {
  190. allocated = make([]int, len(servers))
  191. allocatedCount := 0
  192. for allocatedCount < erasure_coding.TotalShardsCount {
  193. for i, server := range servers {
  194. if server.freeEcSlot-allocated[i] > 0 {
  195. allocated[i] += 1
  196. allocatedCount += 1
  197. }
  198. if allocatedCount >= erasure_coding.TotalShardsCount {
  199. break
  200. }
  201. }
  202. }
  203. return allocated
  204. }
  205. func collectVolumeIdsForEcEncode(ctx context.Context, commandEnv *CommandEnv, selectedCollection string, fullPercentage float64, quietPeriod time.Duration) (vids []needle.VolumeId, err error) {
  206. var resp *master_pb.VolumeListResponse
  207. err = commandEnv.MasterClient.WithClient(ctx, func(client master_pb.SeaweedClient) error {
  208. resp, err = client.VolumeList(ctx, &master_pb.VolumeListRequest{})
  209. return err
  210. })
  211. if err != nil {
  212. return
  213. }
  214. quietSeconds := int64(quietPeriod / time.Second)
  215. nowUnixSeconds := time.Now().Unix()
  216. fmt.Printf("ec encode volumes quiet for: %d seconds\n", quietSeconds)
  217. vidMap := make(map[uint32]bool)
  218. eachDataNode(resp.TopologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  219. for _, v := range dn.VolumeInfos {
  220. if v.Collection == selectedCollection && v.ModifiedAtSecond+quietSeconds < nowUnixSeconds {
  221. if float64(v.Size) > fullPercentage/100*float64(resp.VolumeSizeLimitMb)*1024*1024 {
  222. vidMap[v.Id] = true
  223. }
  224. }
  225. }
  226. })
  227. for vid, _ := range vidMap {
  228. vids = append(vids, needle.VolumeId(vid))
  229. }
  230. return
  231. }