command_ec_encode.go 9.7 KB

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