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.

282 lines
8.7 KiB

5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 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. if err = commandEnv.confirmIsLocked(); err != nil {
  43. return
  44. }
  45. encodeCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  46. volumeId := encodeCommand.Int("volumeId", 0, "the volume id")
  47. collection := encodeCommand.String("collection", "", "the collection name")
  48. fullPercentage := encodeCommand.Float64("fullPercent", 95, "the volume reaches the percentage of max volume size")
  49. quietPeriod := encodeCommand.Duration("quietFor", time.Hour, "select volumes without no writes for this period")
  50. parallelCopy := encodeCommand.Bool("parallelCopy", true, "copy shards in parallel")
  51. if err = encodeCommand.Parse(args); err != nil {
  52. return nil
  53. }
  54. vid := needle.VolumeId(*volumeId)
  55. // volumeId is provided
  56. if vid != 0 {
  57. return doEcEncode(commandEnv, *collection, vid, *parallelCopy)
  58. }
  59. // apply to all volumes in the collection
  60. volumeIds, err := collectVolumeIdsForEcEncode(commandEnv, *collection, *fullPercentage, *quietPeriod)
  61. if err != nil {
  62. return err
  63. }
  64. fmt.Printf("ec encode volumes: %v\n", volumeIds)
  65. for _, vid := range volumeIds {
  66. if err = doEcEncode(commandEnv, *collection, vid, *parallelCopy); err != nil {
  67. return err
  68. }
  69. }
  70. return nil
  71. }
  72. func doEcEncode(commandEnv *CommandEnv, collection string, vid needle.VolumeId, parallelCopy bool) (err error) {
  73. // find volume location
  74. locations, found := commandEnv.MasterClient.GetLocations(uint32(vid))
  75. if !found {
  76. return fmt.Errorf("volume %d not found", vid)
  77. }
  78. // fmt.Printf("found ec %d shards on %v\n", vid, locations)
  79. // mark the volume as readonly
  80. err = markVolumeReplicasWritable(commandEnv.option.GrpcDialOption, vid, locations, false)
  81. if err != nil {
  82. return fmt.Errorf("mark volume %d as readonly on %s: %v", vid, locations[0].Url, err)
  83. }
  84. // generate ec shards
  85. err = generateEcShards(commandEnv.option.GrpcDialOption, vid, collection, locations[0].Url)
  86. if err != nil {
  87. return fmt.Errorf("generate ec shards for volume %d on %s: %v", vid, locations[0].Url, err)
  88. }
  89. // balance the ec shards to current cluster
  90. err = spreadEcShards(commandEnv, vid, collection, locations, parallelCopy)
  91. if err != nil {
  92. return fmt.Errorf("spread ec shards for volume %d from %s: %v", vid, locations[0].Url, err)
  93. }
  94. return nil
  95. }
  96. func generateEcShards(grpcDialOption grpc.DialOption, volumeId needle.VolumeId, collection string, sourceVolumeServer string) error {
  97. fmt.Printf("generateEcShards %s %d on %s ...\n", collection, volumeId, sourceVolumeServer)
  98. err := operation.WithVolumeServerClient(sourceVolumeServer, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  99. _, genErr := volumeServerClient.VolumeEcShardsGenerate(context.Background(), &volume_server_pb.VolumeEcShardsGenerateRequest{
  100. VolumeId: uint32(volumeId),
  101. Collection: collection,
  102. })
  103. return genErr
  104. })
  105. return err
  106. }
  107. func spreadEcShards(commandEnv *CommandEnv, volumeId needle.VolumeId, collection string, existingLocations []wdclient.Location, parallelCopy bool) (err error) {
  108. allEcNodes, totalFreeEcSlots, err := collectEcNodes(commandEnv, "")
  109. if err != nil {
  110. return err
  111. }
  112. if totalFreeEcSlots < erasure_coding.TotalShardsCount {
  113. return fmt.Errorf("not enough free ec shard slots. only %d left", totalFreeEcSlots)
  114. }
  115. allocatedDataNodes := allEcNodes
  116. if len(allocatedDataNodes) > erasure_coding.TotalShardsCount {
  117. allocatedDataNodes = allocatedDataNodes[:erasure_coding.TotalShardsCount]
  118. }
  119. // calculate how many shards to allocate for these servers
  120. allocatedEcIds := balancedEcDistribution(allocatedDataNodes)
  121. // ask the data nodes to copy from the source volume server
  122. copiedShardIds, err := parallelCopyEcShardsFromSource(commandEnv.option.GrpcDialOption, allocatedDataNodes, allocatedEcIds, volumeId, collection, existingLocations[0], parallelCopy)
  123. if err != nil {
  124. return err
  125. }
  126. // unmount the to be deleted shards
  127. err = unmountEcShards(commandEnv.option.GrpcDialOption, volumeId, existingLocations[0].Url, copiedShardIds)
  128. if err != nil {
  129. return err
  130. }
  131. // ask the source volume server to clean up copied ec shards
  132. err = sourceServerDeleteEcShards(commandEnv.option.GrpcDialOption, collection, volumeId, existingLocations[0].Url, copiedShardIds)
  133. if err != nil {
  134. return fmt.Errorf("source delete copied ecShards %s %d.%v: %v", existingLocations[0].Url, volumeId, copiedShardIds, err)
  135. }
  136. // ask the source volume server to delete the original volume
  137. for _, location := range existingLocations {
  138. fmt.Printf("delete volume %d from %s\n", volumeId, location.Url)
  139. err = deleteVolume(commandEnv.option.GrpcDialOption, volumeId, location.Url)
  140. if err != nil {
  141. return fmt.Errorf("deleteVolume %s volume %d: %v", location.Url, volumeId, err)
  142. }
  143. }
  144. return err
  145. }
  146. func parallelCopyEcShardsFromSource(grpcDialOption grpc.DialOption, targetServers []*EcNode, allocatedEcIds [][]uint32, volumeId needle.VolumeId, collection string, existingLocation wdclient.Location, parallelCopy bool) (actuallyCopied []uint32, err error) {
  147. fmt.Printf("parallelCopyEcShardsFromSource %d %s\n", volumeId, existingLocation.Url)
  148. var wg sync.WaitGroup
  149. shardIdChan := make(chan []uint32, len(targetServers))
  150. copyFunc := func(server *EcNode, allocatedEcShardIds []uint32) {
  151. defer wg.Done()
  152. copiedShardIds, copyErr := oneServerCopyAndMountEcShardsFromSource(grpcDialOption, server,
  153. allocatedEcShardIds, volumeId, collection, existingLocation.Url)
  154. if copyErr != nil {
  155. err = copyErr
  156. } else {
  157. shardIdChan <- copiedShardIds
  158. server.addEcVolumeShards(volumeId, collection, copiedShardIds)
  159. }
  160. }
  161. // maybe parallelize
  162. for i, server := range targetServers {
  163. if len(allocatedEcIds[i]) <= 0 {
  164. continue
  165. }
  166. wg.Add(1)
  167. if parallelCopy {
  168. go copyFunc(server, allocatedEcIds[i])
  169. } else {
  170. copyFunc(server, allocatedEcIds[i])
  171. }
  172. }
  173. wg.Wait()
  174. close(shardIdChan)
  175. if err != nil {
  176. return nil, err
  177. }
  178. for shardIds := range shardIdChan {
  179. actuallyCopied = append(actuallyCopied, shardIds...)
  180. }
  181. return
  182. }
  183. func balancedEcDistribution(servers []*EcNode) (allocated [][]uint32) {
  184. allocated = make([][]uint32, len(servers))
  185. allocatedShardIdIndex := uint32(0)
  186. serverIndex := 0
  187. for allocatedShardIdIndex < erasure_coding.TotalShardsCount {
  188. if servers[serverIndex].freeEcSlot > 0 {
  189. allocated[serverIndex] = append(allocated[serverIndex], allocatedShardIdIndex)
  190. allocatedShardIdIndex++
  191. }
  192. serverIndex++
  193. if serverIndex >= len(servers) {
  194. serverIndex = 0
  195. }
  196. }
  197. return allocated
  198. }
  199. func collectVolumeIdsForEcEncode(commandEnv *CommandEnv, selectedCollection string, fullPercentage float64, quietPeriod time.Duration) (vids []needle.VolumeId, err error) {
  200. // collect topology information
  201. topologyInfo, volumeSizeLimitMb, err := collectTopologyInfo(commandEnv)
  202. if err != nil {
  203. return
  204. }
  205. quietSeconds := int64(quietPeriod / time.Second)
  206. nowUnixSeconds := time.Now().Unix()
  207. fmt.Printf("collect volumes quiet for: %d seconds\n", quietSeconds)
  208. vidMap := make(map[uint32]bool)
  209. eachDataNode(topologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  210. for _, diskInfo := range dn.DiskInfos {
  211. for _, v := range diskInfo.VolumeInfos {
  212. if v.Collection == selectedCollection && v.ModifiedAtSecond+quietSeconds < nowUnixSeconds {
  213. if float64(v.Size) > fullPercentage/100*float64(volumeSizeLimitMb)*1024*1024 {
  214. vidMap[v.Id] = true
  215. }
  216. }
  217. }
  218. }
  219. })
  220. for vid := range vidMap {
  221. vids = append(vids, needle.VolumeId(vid))
  222. }
  223. return
  224. }