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.

256 lines
8.3 KiB

5 years ago
5 months ago
4 years ago
4 years ago
4 months ago
6 years ago
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "time"
  8. "github.com/seaweedfs/seaweedfs/weed/glog"
  9. "github.com/seaweedfs/seaweedfs/weed/pb"
  10. "google.golang.org/grpc"
  11. "github.com/seaweedfs/seaweedfs/weed/operation"
  12. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
  15. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  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. (optionally) re-balance encoded shards across 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. Re-balancing algorithm:
  40. ` + ecBalanceAlgorithmDescription
  41. }
  42. func (c *commandEcEncode) HasTag(CommandTag) bool {
  43. return false
  44. }
  45. func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  46. encodeCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  47. volumeId := encodeCommand.Int("volumeId", 0, "the volume id")
  48. collection := encodeCommand.String("collection", "", "the collection name")
  49. fullPercentage := encodeCommand.Float64("fullPercent", 95, "the volume reaches the percentage of max volume size")
  50. quietPeriod := encodeCommand.Duration("quietFor", time.Hour, "select volumes without no writes for this period")
  51. maxParallelization := encodeCommand.Int("maxParallelization", 10, "run up to X tasks in parallel, whenever possible")
  52. forceChanges := encodeCommand.Bool("force", false, "force the encoding even if the cluster has less than recommended 4 nodes")
  53. shardReplicaPlacement := encodeCommand.String("shardReplicaPlacement", "", "replica placement for EC shards, or master default if empty")
  54. applyBalancing := encodeCommand.Bool("rebalance", false, "re-balance EC shards after creation")
  55. if err = encodeCommand.Parse(args); err != nil {
  56. return nil
  57. }
  58. if err = commandEnv.confirmIsLocked(args); err != nil {
  59. return
  60. }
  61. rp, err := parseReplicaPlacementArg(commandEnv, *shardReplicaPlacement)
  62. if err != nil {
  63. return err
  64. }
  65. // collect topology information
  66. topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
  67. if err != nil {
  68. return err
  69. }
  70. if !*forceChanges {
  71. var nodeCount int
  72. eachDataNode(topologyInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
  73. nodeCount++
  74. })
  75. if nodeCount < erasure_coding.ParityShardsCount {
  76. glog.V(0).Infof("skip erasure coding with %d nodes, less than recommended %d nodes", nodeCount, erasure_coding.ParityShardsCount)
  77. return nil
  78. }
  79. }
  80. var collections []string
  81. var volumeIds []needle.VolumeId
  82. if vid := needle.VolumeId(*volumeId); vid != 0 {
  83. // volumeId is provided
  84. volumeIds = append(volumeIds, vid)
  85. collections = collectCollectionsForVolumeIds(topologyInfo, volumeIds)
  86. } else {
  87. // apply to all volumes for the given collection
  88. volumeIds, err = collectVolumeIdsForEcEncode(commandEnv, *collection, *fullPercentage, *quietPeriod)
  89. if err != nil {
  90. return err
  91. }
  92. collections = append(collections, *collection)
  93. }
  94. // encode all requested volumes...
  95. for _, vid := range volumeIds {
  96. if err = doEcEncode(commandEnv, *collection, vid, *maxParallelization); err != nil {
  97. return fmt.Errorf("ec encode for volume %d: %v", vid, err)
  98. }
  99. }
  100. // ...then re-balance ec shards.
  101. if err := EcBalance(commandEnv, collections, "", rp, *maxParallelization, *applyBalancing); err != nil {
  102. return fmt.Errorf("re-balance ec shards for collection(s) %v: %v", collections, err)
  103. }
  104. return nil
  105. }
  106. func doEcEncode(commandEnv *CommandEnv, collection string, vid needle.VolumeId, maxParallelization int) error {
  107. var ewg *ErrorWaitGroup
  108. if !commandEnv.isLocked() {
  109. return fmt.Errorf("lock is lost")
  110. }
  111. // find volume location
  112. locations, found := commandEnv.MasterClient.GetLocationsClone(uint32(vid))
  113. if !found {
  114. return fmt.Errorf("volume %d not found", vid)
  115. }
  116. target := locations[0]
  117. // mark the volume as readonly
  118. ewg = NewErrorWaitGroup(maxParallelization)
  119. for _, location := range locations {
  120. ewg.Add(func() error {
  121. if err := markVolumeReplicaWritable(commandEnv.option.GrpcDialOption, vid, location, false, false); err != nil {
  122. return fmt.Errorf("mark volume %d as readonly on %s: %v", vid, location.Url, err)
  123. }
  124. return nil
  125. })
  126. }
  127. if err := ewg.Wait(); err != nil {
  128. return err
  129. }
  130. // generate ec shards
  131. if err := generateEcShards(commandEnv.option.GrpcDialOption, vid, collection, target.ServerAddress()); err != nil {
  132. return fmt.Errorf("generate ec shards for volume %d on %s: %v", vid, target.Url, err)
  133. }
  134. // ask the source volume server to delete the original volume
  135. ewg = NewErrorWaitGroup(maxParallelization)
  136. for _, location := range locations {
  137. ewg.Add(func() error {
  138. if err := deleteVolume(commandEnv.option.GrpcDialOption, vid, location.ServerAddress(), false); err != nil {
  139. return fmt.Errorf("deleteVolume %s volume %d: %v", location.Url, vid, err)
  140. }
  141. fmt.Printf("deleted volume %d from %s\n", vid, location.Url)
  142. return nil
  143. })
  144. }
  145. if err := ewg.Wait(); err != nil {
  146. return err
  147. }
  148. // mount all ec shards for the converted volume
  149. shardIds := make([]uint32, erasure_coding.TotalShardsCount)
  150. for i := range shardIds {
  151. shardIds[i] = uint32(i)
  152. }
  153. if err := mountEcShards(commandEnv.option.GrpcDialOption, collection, vid, target.ServerAddress(), shardIds); err != nil {
  154. return fmt.Errorf("mount ec shards for volume %d on %s: %v", vid, target.Url, err)
  155. }
  156. return nil
  157. }
  158. func generateEcShards(grpcDialOption grpc.DialOption, volumeId needle.VolumeId, collection string, sourceVolumeServer pb.ServerAddress) error {
  159. fmt.Printf("generateEcShards %s %d on %s ...\n", collection, volumeId, sourceVolumeServer)
  160. err := operation.WithVolumeServerClient(false, sourceVolumeServer, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  161. _, genErr := volumeServerClient.VolumeEcShardsGenerate(context.Background(), &volume_server_pb.VolumeEcShardsGenerateRequest{
  162. VolumeId: uint32(volumeId),
  163. Collection: collection,
  164. })
  165. return genErr
  166. })
  167. return err
  168. }
  169. func collectVolumeIdsForEcEncode(commandEnv *CommandEnv, selectedCollection string, fullPercentage float64, quietPeriod time.Duration) (vids []needle.VolumeId, err error) {
  170. // collect topology information
  171. topologyInfo, volumeSizeLimitMb, err := collectTopologyInfo(commandEnv, 0)
  172. if err != nil {
  173. return
  174. }
  175. quietSeconds := int64(quietPeriod / time.Second)
  176. nowUnixSeconds := time.Now().Unix()
  177. fmt.Printf("collect volumes quiet for: %d seconds and %.1f%% full\n", quietSeconds, fullPercentage)
  178. vidMap := make(map[uint32]bool)
  179. eachDataNode(topologyInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
  180. for _, diskInfo := range dn.DiskInfos {
  181. for _, v := range diskInfo.VolumeInfos {
  182. // ignore remote volumes
  183. if v.RemoteStorageName != "" && v.RemoteStorageKey != "" {
  184. continue
  185. }
  186. if v.Collection == selectedCollection && v.ModifiedAtSecond+quietSeconds < nowUnixSeconds {
  187. if float64(v.Size) > fullPercentage/100*float64(volumeSizeLimitMb)*1024*1024 {
  188. if good, found := vidMap[v.Id]; found {
  189. if good {
  190. if diskInfo.FreeVolumeCount < 2 {
  191. glog.V(0).Infof("skip %s %d on %s, no free disk", v.Collection, v.Id, dn.Id)
  192. vidMap[v.Id] = false
  193. }
  194. }
  195. } else {
  196. if diskInfo.FreeVolumeCount < 2 {
  197. glog.V(0).Infof("skip %s %d on %s, no free disk", v.Collection, v.Id, dn.Id)
  198. vidMap[v.Id] = false
  199. } else {
  200. vidMap[v.Id] = true
  201. }
  202. }
  203. }
  204. }
  205. }
  206. }
  207. })
  208. for vid, good := range vidMap {
  209. if good {
  210. vids = append(vids, needle.VolumeId(vid))
  211. }
  212. }
  213. return
  214. }