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.

364 lines
12 KiB

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