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.

286 lines
9.2 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package shell
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/glog"
  6. "github.com/chrislusf/seaweedfs/weed/pb"
  7. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  8. "github.com/chrislusf/seaweedfs/weed/storage/types"
  9. "github.com/chrislusf/seaweedfs/weed/wdclient"
  10. "io"
  11. "path/filepath"
  12. "sync"
  13. "time"
  14. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  15. )
  16. func init() {
  17. Commands = append(Commands, &commandVolumeTierMove{})
  18. }
  19. type volumeTierMoveJob struct {
  20. src pb.ServerAddress
  21. vid needle.VolumeId
  22. }
  23. type commandVolumeTierMove struct {
  24. activeServers sync.Map
  25. queues map[pb.ServerAddress]chan volumeTierMoveJob
  26. //activeServers map[pb.ServerAddress]struct{}
  27. //activeServersLock sync.Mutex
  28. //activeServersCond *sync.Cond
  29. }
  30. func (c *commandVolumeTierMove) Name() string {
  31. return "volume.tier.move"
  32. }
  33. func (c *commandVolumeTierMove) Help() string {
  34. return `change a volume from one disk type to another
  35. volume.tier.move -fromDiskType=hdd -toDiskType=ssd [-collectionPattern=""] [-fullPercent=95] [-quietFor=1h] [-parallelLimit=4]
  36. Even if the volume is replicated, only one replica will be changed and the rest replicas will be dropped.
  37. So "volume.fix.replication" and "volume.balance" should be followed.
  38. `
  39. }
  40. func (c *commandVolumeTierMove) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  41. tierCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  42. collectionPattern := tierCommand.String("collectionPattern", "", "match with wildcard characters '*' and '?'")
  43. fullPercentage := tierCommand.Float64("fullPercent", 95, "the volume reaches the percentage of max volume size")
  44. quietPeriod := tierCommand.Duration("quietFor", 24*time.Hour, "select volumes without no writes for this period")
  45. source := tierCommand.String("fromDiskType", "", "the source disk type")
  46. target := tierCommand.String("toDiskType", "", "the target disk type")
  47. parallelLimit := tierCommand.Int("parallelLimit", 0, "limit the number of parallel copying jobs")
  48. applyChange := tierCommand.Bool("force", false, "actually apply the changes")
  49. if err = tierCommand.Parse(args); err != nil {
  50. return nil
  51. }
  52. infoAboutSimulationMode(writer, *applyChange, "-force")
  53. if err = commandEnv.confirmIsLocked(args); err != nil {
  54. return
  55. }
  56. fromDiskType := types.ToDiskType(*source)
  57. toDiskType := types.ToDiskType(*target)
  58. if fromDiskType == toDiskType {
  59. return fmt.Errorf("source tier %s is the same as target tier %s", fromDiskType, toDiskType)
  60. }
  61. // collect topology information
  62. topologyInfo, volumeSizeLimitMb, err := collectTopologyInfo(commandEnv, 0)
  63. if err != nil {
  64. return err
  65. }
  66. // collect all volumes that should change
  67. volumeIds, err := collectVolumeIdsForTierChange(commandEnv, topologyInfo, volumeSizeLimitMb, fromDiskType, *collectionPattern, *fullPercentage, *quietPeriod)
  68. if err != nil {
  69. return err
  70. }
  71. fmt.Printf("tier move volumes: %v\n", volumeIds)
  72. _, allLocations := collectVolumeReplicaLocations(topologyInfo)
  73. allLocations = filterLocationsByDiskType(allLocations, toDiskType)
  74. keepDataNodesSorted(allLocations, toDiskType)
  75. if len(allLocations) > 0 && *parallelLimit > 0 && *parallelLimit < len(allLocations) {
  76. allLocations = allLocations[:*parallelLimit]
  77. }
  78. wg := sync.WaitGroup{}
  79. bufferLen := len(allLocations)
  80. c.queues = make(map[pb.ServerAddress]chan volumeTierMoveJob)
  81. for _, dst := range allLocations {
  82. destServerAddress := pb.NewServerAddressFromDataNode(dst.dataNode)
  83. c.queues[destServerAddress] = make(chan volumeTierMoveJob, bufferLen)
  84. wg.Add(1)
  85. go func(dst location, jobs <-chan volumeTierMoveJob, applyChanges bool) {
  86. defer wg.Done()
  87. for job := range jobs {
  88. fmt.Fprintf(writer, "moving volume %d from %s to %s with disk type %s ...\n", job.vid, job.src, dst.dataNode.Id, toDiskType.ReadableString())
  89. locations, found := commandEnv.MasterClient.GetLocations(uint32(job.vid))
  90. if !found {
  91. fmt.Printf("volume %d not found", job.vid)
  92. continue
  93. }
  94. unlock := c.Lock(job.src)
  95. if applyChanges {
  96. if err := c.doMoveOneVolume(commandEnv, writer, job.vid, toDiskType, locations, job.src, dst); err != nil {
  97. fmt.Fprintf(writer, "move volume %d %s => %s: %v\n", job.vid, job.src, dst.dataNode.Id, err)
  98. }
  99. }
  100. unlock()
  101. }
  102. }(dst, c.queues[destServerAddress], *applyChange)
  103. }
  104. for _, vid := range volumeIds {
  105. if err = c.doVolumeTierMove(commandEnv, writer, vid, toDiskType, allLocations); err != nil {
  106. fmt.Printf("tier move volume %d: %v\n", vid, err)
  107. }
  108. allLocations = rotateDataNodes(allLocations)
  109. }
  110. for key, _ := range c.queues {
  111. close(c.queues[key])
  112. }
  113. wg.Wait()
  114. return nil
  115. }
  116. func (c *commandVolumeTierMove) Lock(key pb.ServerAddress) func() {
  117. value, _ := c.activeServers.LoadOrStore(key, &sync.Mutex{})
  118. mtx := value.(*sync.Mutex)
  119. mtx.Lock()
  120. return func() { mtx.Unlock() }
  121. }
  122. func filterLocationsByDiskType(dataNodes []location, diskType types.DiskType) (ret []location) {
  123. for _, loc := range dataNodes {
  124. _, found := loc.dataNode.DiskInfos[string(diskType)]
  125. if found {
  126. ret = append(ret, loc)
  127. }
  128. }
  129. return
  130. }
  131. func rotateDataNodes(dataNodes []location) []location {
  132. if len(dataNodes) > 0 {
  133. return append(dataNodes[1:], dataNodes[0])
  134. } else {
  135. return dataNodes
  136. }
  137. }
  138. func isOneOf(server string, locations []wdclient.Location) bool {
  139. for _, loc := range locations {
  140. if server == loc.Url {
  141. return true
  142. }
  143. }
  144. return false
  145. }
  146. func (c *commandVolumeTierMove) doVolumeTierMove(commandEnv *CommandEnv, writer io.Writer, vid needle.VolumeId, toDiskType types.DiskType, allLocations []location) (err error) {
  147. // find volume location
  148. locations, found := commandEnv.MasterClient.GetLocations(uint32(vid))
  149. if !found {
  150. return fmt.Errorf("volume %d not found", vid)
  151. }
  152. // find one server with the most empty volume slots with target disk type
  153. hasFoundTarget := false
  154. fn := capacityByFreeVolumeCount(toDiskType)
  155. for _, dst := range allLocations {
  156. if fn(dst.dataNode) > 0 && !hasFoundTarget {
  157. // ask the volume server to replicate the volume
  158. if isOneOf(dst.dataNode.Id, locations) {
  159. continue
  160. }
  161. var sourceVolumeServer pb.ServerAddress
  162. for _, loc := range locations {
  163. if loc.Url != dst.dataNode.Id {
  164. sourceVolumeServer = loc.ServerAddress()
  165. }
  166. }
  167. if sourceVolumeServer == "" {
  168. continue
  169. }
  170. hasFoundTarget = true
  171. // adjust volume count
  172. dst.dataNode.DiskInfos[string(toDiskType)].VolumeCount++
  173. destServerAddress := pb.NewServerAddressFromDataNode(dst.dataNode)
  174. c.queues[destServerAddress] <- volumeTierMoveJob{sourceVolumeServer, vid}
  175. }
  176. }
  177. if !hasFoundTarget {
  178. fmt.Fprintf(writer, "can not find disk type %s for volume %d\n", toDiskType.ReadableString(), vid)
  179. }
  180. return nil
  181. }
  182. func (c *commandVolumeTierMove) doMoveOneVolume(commandEnv *CommandEnv, writer io.Writer, vid needle.VolumeId, toDiskType types.DiskType, locations []wdclient.Location, sourceVolumeServer pb.ServerAddress, dst location) (err error) {
  183. // mark all replicas as read only
  184. if err = markVolumeReplicasWritable(commandEnv.option.GrpcDialOption, vid, locations, false); err != nil {
  185. return fmt.Errorf("mark volume %d as readonly on %s: %v", vid, locations[0].Url, err)
  186. }
  187. if err = LiveMoveVolume(commandEnv.option.GrpcDialOption, writer, vid, sourceVolumeServer, pb.NewServerAddressFromDataNode(dst.dataNode), 5*time.Second, toDiskType.ReadableString(), true); err != nil {
  188. // mark all replicas as writable
  189. if err = markVolumeReplicasWritable(commandEnv.option.GrpcDialOption, vid, locations, true); err != nil {
  190. glog.Errorf("mark volume %d as writable on %s: %v", vid, locations[0].Url, err)
  191. }
  192. return fmt.Errorf("move volume %d %s => %s : %v", vid, locations[0].Url, dst.dataNode.Id, err)
  193. }
  194. // remove the remaining replicas
  195. for _, loc := range locations {
  196. if loc.Url != dst.dataNode.Id && loc.ServerAddress() != sourceVolumeServer {
  197. if err = deleteVolume(commandEnv.option.GrpcDialOption, vid, loc.ServerAddress()); err != nil {
  198. fmt.Fprintf(writer, "failed to delete volume %d on %s: %v\n", vid, loc.Url, err)
  199. }
  200. // reduce volume count? Not really necessary since they are "more" full and will not be a candidate to move to
  201. }
  202. }
  203. return nil
  204. }
  205. func collectVolumeIdsForTierChange(commandEnv *CommandEnv, topologyInfo *master_pb.TopologyInfo, volumeSizeLimitMb uint64, sourceTier types.DiskType, collectionPattern string, fullPercentage float64, quietPeriod time.Duration) (vids []needle.VolumeId, err error) {
  206. quietSeconds := int64(quietPeriod / time.Second)
  207. nowUnixSeconds := time.Now().Unix()
  208. fmt.Printf("collect %s volumes quiet for: %d seconds\n", sourceTier, quietSeconds)
  209. vidMap := make(map[uint32]bool)
  210. eachDataNode(topologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  211. for _, diskInfo := range dn.DiskInfos {
  212. for _, v := range diskInfo.VolumeInfos {
  213. // check collection name pattern
  214. if collectionPattern != "" {
  215. matched, err := filepath.Match(collectionPattern, v.Collection)
  216. if err != nil {
  217. return
  218. }
  219. if !matched {
  220. continue
  221. }
  222. }
  223. if v.ModifiedAtSecond+quietSeconds < nowUnixSeconds && types.ToDiskType(v.DiskType) == sourceTier {
  224. if float64(v.Size) > fullPercentage/100*float64(volumeSizeLimitMb)*1024*1024 {
  225. vidMap[v.Id] = true
  226. }
  227. }
  228. }
  229. }
  230. })
  231. for vid := range vidMap {
  232. vids = append(vids, needle.VolumeId(vid))
  233. }
  234. return
  235. }