command_volume_tier_move.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. if err = commandEnv.confirmIsLocked(args); err != nil {
  53. return
  54. }
  55. fromDiskType := types.ToDiskType(*source)
  56. toDiskType := types.ToDiskType(*target)
  57. if fromDiskType == toDiskType {
  58. return fmt.Errorf("source tier %s is the same as target tier %s", fromDiskType, toDiskType)
  59. }
  60. // collect topology information
  61. topologyInfo, volumeSizeLimitMb, err := collectTopologyInfo(commandEnv, 0)
  62. if err != nil {
  63. return err
  64. }
  65. // collect all volumes that should change
  66. volumeIds, err := collectVolumeIdsForTierChange(commandEnv, topologyInfo, volumeSizeLimitMb, fromDiskType, *collectionPattern, *fullPercentage, *quietPeriod)
  67. if err != nil {
  68. return err
  69. }
  70. fmt.Printf("tier move volumes: %v\n", volumeIds)
  71. _, allLocations := collectVolumeReplicaLocations(topologyInfo)
  72. allLocations = filterLocationsByDiskType(allLocations, toDiskType)
  73. keepDataNodesSorted(allLocations, toDiskType)
  74. if len(allLocations) > 0 && *parallelLimit > 0 && *parallelLimit < len(allLocations) {
  75. allLocations = allLocations[:*parallelLimit]
  76. }
  77. wg := sync.WaitGroup{}
  78. bufferLen := len(allLocations)
  79. c.queues = make(map[pb.ServerAddress]chan volumeTierMoveJob)
  80. for _, dst := range allLocations {
  81. destServerAddress := pb.NewServerAddressFromDataNode(dst.dataNode)
  82. c.queues[destServerAddress] = make(chan volumeTierMoveJob, bufferLen)
  83. wg.Add(1)
  84. go func(dst location, jobs <-chan volumeTierMoveJob, applyChanges bool) {
  85. defer wg.Done()
  86. for job := range jobs {
  87. fmt.Fprintf(writer, "moving volume %d from %s to %s with disk type %s ...\n", job.vid, job.src, dst.dataNode.Id, toDiskType.ReadableString())
  88. locations, found := commandEnv.MasterClient.GetLocations(uint32(job.vid))
  89. if !found {
  90. fmt.Printf("volume %d not found", job.vid)
  91. continue
  92. }
  93. unlock := c.Lock(job.src)
  94. if applyChanges {
  95. if err := c.doMoveOneVolume(commandEnv, writer, job.vid, toDiskType, locations, job.src, dst); err != nil {
  96. fmt.Fprintf(writer, "move volume %d %s => %s: %v\n", job.vid, job.src, dst.dataNode.Id, err)
  97. }
  98. }
  99. unlock()
  100. }
  101. }(dst, c.queues[destServerAddress], *applyChange)
  102. }
  103. for _, vid := range volumeIds {
  104. if err = c.doVolumeTierMove(commandEnv, writer, vid, toDiskType, allLocations); err != nil {
  105. fmt.Printf("tier move volume %d: %v\n", vid, err)
  106. }
  107. allLocations = rotateDataNodes(allLocations)
  108. }
  109. for key, _ := range c.queues {
  110. close(c.queues[key])
  111. }
  112. wg.Wait()
  113. return nil
  114. }
  115. func (c *commandVolumeTierMove) Lock(key pb.ServerAddress) func() {
  116. value, _ := c.activeServers.LoadOrStore(key, &sync.Mutex{})
  117. mtx := value.(*sync.Mutex)
  118. mtx.Lock()
  119. return func() { mtx.Unlock() }
  120. }
  121. func filterLocationsByDiskType(dataNodes []location, diskType types.DiskType) (ret []location) {
  122. for _, loc := range dataNodes {
  123. _, found := loc.dataNode.DiskInfos[string(diskType)]
  124. if found {
  125. ret = append(ret, loc)
  126. }
  127. }
  128. return
  129. }
  130. func rotateDataNodes(dataNodes []location) []location {
  131. if len(dataNodes) > 0 {
  132. return append(dataNodes[1:], dataNodes[0])
  133. } else {
  134. return dataNodes
  135. }
  136. }
  137. func isOneOf(server string, locations []wdclient.Location) bool {
  138. for _, loc := range locations {
  139. if server == loc.Url {
  140. return true
  141. }
  142. }
  143. return false
  144. }
  145. func (c *commandVolumeTierMove) doVolumeTierMove(commandEnv *CommandEnv, writer io.Writer, vid needle.VolumeId, toDiskType types.DiskType, allLocations []location) (err error) {
  146. // find volume location
  147. locations, found := commandEnv.MasterClient.GetLocations(uint32(vid))
  148. if !found {
  149. return fmt.Errorf("volume %d not found", vid)
  150. }
  151. // find one server with the most empty volume slots with target disk type
  152. hasFoundTarget := false
  153. fn := capacityByFreeVolumeCount(toDiskType)
  154. for _, dst := range allLocations {
  155. if fn(dst.dataNode) > 0 && !hasFoundTarget {
  156. // ask the volume server to replicate the volume
  157. if isOneOf(dst.dataNode.Id, locations) {
  158. continue
  159. }
  160. var sourceVolumeServer pb.ServerAddress
  161. for _, loc := range locations {
  162. if loc.Url != dst.dataNode.Id {
  163. sourceVolumeServer = loc.ServerAddress()
  164. }
  165. }
  166. if sourceVolumeServer == "" {
  167. continue
  168. }
  169. hasFoundTarget = true
  170. // adjust volume count
  171. dst.dataNode.DiskInfos[string(toDiskType)].VolumeCount++
  172. destServerAddress := pb.NewServerAddressFromDataNode(dst.dataNode)
  173. c.queues[destServerAddress] <- volumeTierMoveJob{sourceVolumeServer, vid}
  174. }
  175. }
  176. if !hasFoundTarget {
  177. fmt.Fprintf(writer, "can not find disk type %s for volume %d\n", toDiskType.ReadableString(), vid)
  178. }
  179. return nil
  180. }
  181. 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) {
  182. // mark all replicas as read only
  183. if err = markVolumeReplicasWritable(commandEnv.option.GrpcDialOption, vid, locations, false); err != nil {
  184. return fmt.Errorf("mark volume %d as readonly on %s: %v", vid, locations[0].Url, err)
  185. }
  186. if err = LiveMoveVolume(commandEnv.option.GrpcDialOption, writer, vid, sourceVolumeServer, pb.NewServerAddressFromDataNode(dst.dataNode), 5*time.Second, toDiskType.ReadableString(), true); err != nil {
  187. // mark all replicas as writable
  188. if err = markVolumeReplicasWritable(commandEnv.option.GrpcDialOption, vid, locations, true); err != nil {
  189. glog.Errorf("mark volume %d as writable on %s: %v", vid, locations[0].Url, err)
  190. }
  191. return fmt.Errorf("move volume %d %s => %s : %v", vid, locations[0].Url, dst.dataNode.Id, err)
  192. }
  193. // remove the remaining replicas
  194. for _, loc := range locations {
  195. if loc.Url != dst.dataNode.Id && loc.ServerAddress() != sourceVolumeServer {
  196. if err = deleteVolume(commandEnv.option.GrpcDialOption, vid, loc.ServerAddress()); err != nil {
  197. fmt.Fprintf(writer, "failed to delete volume %d on %s: %v\n", vid, loc.Url, err)
  198. }
  199. // reduce volume count? Not really necessary since they are "more" full and will not be a candidate to move to
  200. }
  201. }
  202. return nil
  203. }
  204. 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) {
  205. quietSeconds := int64(quietPeriod / time.Second)
  206. nowUnixSeconds := time.Now().Unix()
  207. fmt.Printf("collect %s volumes quiet for: %d seconds\n", sourceTier, 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. // check collection name pattern
  213. if collectionPattern != "" {
  214. matched, err := filepath.Match(collectionPattern, v.Collection)
  215. if err != nil {
  216. return
  217. }
  218. if !matched {
  219. continue
  220. }
  221. }
  222. if v.ModifiedAtSecond+quietSeconds < nowUnixSeconds && types.ToDiskType(v.DiskType) == sourceTier {
  223. if float64(v.Size) > fullPercentage/100*float64(volumeSizeLimitMb)*1024*1024 {
  224. vidMap[v.Id] = true
  225. }
  226. }
  227. }
  228. }
  229. })
  230. for vid := range vidMap {
  231. vids = append(vids, needle.VolumeId(vid))
  232. }
  233. return
  234. }