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.

287 lines
8.7 KiB

5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "sync"
  8. "time"
  9. "google.golang.org/grpc"
  10. "github.com/chrislusf/seaweedfs/weed/operation"
  11. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  12. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  13. "github.com/chrislusf/seaweedfs/weed/storage/erasure_coding"
  14. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  15. "github.com/chrislusf/seaweedfs/weed/wdclient"
  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. vid := needle.VolumeId(*volumeId)
  51. // volumeId is provided
  52. if vid != 0 {
  53. return doEcEncode(commandEnv, *collection, vid)
  54. }
  55. // apply to all volumes in the collection
  56. volumeIds, err := collectVolumeIdsForEcEncode(commandEnv, *collection, *fullPercentage, *quietPeriod)
  57. if err != nil {
  58. return err
  59. }
  60. fmt.Printf("ec encode volumes: %v\n", volumeIds)
  61. for _, vid := range volumeIds {
  62. if err = doEcEncode(commandEnv, *collection, vid); err != nil {
  63. return err
  64. }
  65. }
  66. return nil
  67. }
  68. func doEcEncode(commandEnv *CommandEnv, collection string, vid needle.VolumeId) (err error) {
  69. // find volume location
  70. locations, found := commandEnv.MasterClient.GetLocations(uint32(vid))
  71. if !found {
  72. return fmt.Errorf("volume %d not found", vid)
  73. }
  74. // fmt.Printf("found ec %d shards on %v\n", vid, locations)
  75. // mark the volume as readonly
  76. err = markVolumeReadonly(commandEnv.option.GrpcDialOption, needle.VolumeId(vid), locations)
  77. if err != nil {
  78. return fmt.Errorf("mark volume %d as readonly on %s: %v", vid, locations[0].Url, err)
  79. }
  80. // generate ec shards
  81. err = generateEcShards(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(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(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(context.Background(), &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(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(context.Background(), &volume_server_pb.VolumeEcShardsGenerateRequest{
  109. VolumeId: uint32(volumeId),
  110. Collection: collection,
  111. })
  112. return genErr
  113. })
  114. return err
  115. }
  116. func spreadEcShards(commandEnv *CommandEnv, volumeId needle.VolumeId, collection string, existingLocations []wdclient.Location) (err error) {
  117. allEcNodes, totalFreeEcSlots, err := collectEcNodes(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. allocatedEcIds := balancedEcDistribution(allocatedDataNodes)
  130. // ask the data nodes to copy from the source volume server
  131. copiedShardIds, err := parallelCopyEcShardsFromSource(commandEnv.option.GrpcDialOption, allocatedDataNodes, allocatedEcIds, volumeId, collection, existingLocations[0])
  132. if err != nil {
  133. return err
  134. }
  135. // unmount the to be deleted shards
  136. err = unmountEcShards(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(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(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(grpcDialOption grpc.DialOption, targetServers []*EcNode, allocatedEcIds [][]uint32, volumeId needle.VolumeId, collection string, existingLocation wdclient.Location) (actuallyCopied []uint32, err error) {
  155. // parallelize
  156. shardIdChan := make(chan []uint32, len(targetServers))
  157. var wg sync.WaitGroup
  158. for i, server := range targetServers {
  159. if len(allocatedEcIds[i]) <= 0 {
  160. continue
  161. }
  162. wg.Add(1)
  163. go func(server *EcNode, allocatedEcShardIds []uint32) {
  164. defer wg.Done()
  165. copiedShardIds, copyErr := oneServerCopyAndMountEcShardsFromSource(grpcDialOption, server,
  166. allocatedEcShardIds, volumeId, collection, existingLocation.Url)
  167. if copyErr != nil {
  168. err = copyErr
  169. } else {
  170. shardIdChan <- copiedShardIds
  171. server.addEcVolumeShards(volumeId, collection, copiedShardIds)
  172. }
  173. }(server, allocatedEcIds[i])
  174. }
  175. wg.Wait()
  176. close(shardIdChan)
  177. if err != nil {
  178. return nil, err
  179. }
  180. for shardIds := range shardIdChan {
  181. actuallyCopied = append(actuallyCopied, shardIds...)
  182. }
  183. return
  184. }
  185. func balancedEcDistribution(servers []*EcNode) (allocated [][]uint32) {
  186. allocated = make([][]uint32, len(servers))
  187. allocatedShardIdIndex := uint32(0)
  188. serverIndex := 0
  189. for allocatedShardIdIndex < erasure_coding.TotalShardsCount {
  190. if servers[serverIndex].freeEcSlot > 0 {
  191. allocated[serverIndex] = append(allocated[serverIndex], allocatedShardIdIndex)
  192. allocatedShardIdIndex++
  193. }
  194. serverIndex++
  195. if serverIndex >= len(servers) {
  196. serverIndex = 0
  197. }
  198. }
  199. return allocated
  200. }
  201. func collectVolumeIdsForEcEncode(commandEnv *CommandEnv, selectedCollection string, fullPercentage float64, quietPeriod time.Duration) (vids []needle.VolumeId, err error) {
  202. var resp *master_pb.VolumeListResponse
  203. err = commandEnv.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {
  204. resp, err = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
  205. return err
  206. })
  207. if err != nil {
  208. return
  209. }
  210. quietSeconds := int64(quietPeriod / time.Second)
  211. nowUnixSeconds := time.Now().Unix()
  212. fmt.Printf("ec encode volumes quiet for: %d seconds\n", quietSeconds)
  213. vidMap := make(map[uint32]bool)
  214. eachDataNode(resp.TopologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  215. for _, v := range dn.VolumeInfos {
  216. if v.Collection == selectedCollection && v.ModifiedAtSecond+quietSeconds < nowUnixSeconds {
  217. if float64(v.Size) > fullPercentage/100*float64(resp.VolumeSizeLimitMb)*1024*1024 {
  218. vidMap[v.Id] = true
  219. }
  220. }
  221. }
  222. })
  223. for vid := range vidMap {
  224. vids = append(vids, needle.VolumeId(vid))
  225. }
  226. return
  227. }