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.

290 lines
9.3 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. 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 err := c.doMoveOneVolume(commandEnv, writer, job.vid, toDiskType, locations, job.src, dst, applyChanges); err != nil {
  95. fmt.Fprintf(writer, "move volume %d %s => %s: %v\n", job.vid, job.src, dst.dataNode.Id, err)
  96. }
  97. unlock()
  98. }
  99. }(dst, c.queues[destServerAddress], *applyChange)
  100. }
  101. for _, vid := range volumeIds {
  102. if err = c.doVolumeTierMove(commandEnv, writer, vid, toDiskType, allLocations); err != nil {
  103. fmt.Printf("tier move volume %d: %v\n", vid, err)
  104. }
  105. allLocations = rotateDataNodes(allLocations)
  106. }
  107. for key, _ := range c.queues {
  108. close(c.queues[key])
  109. }
  110. wg.Wait()
  111. return nil
  112. }
  113. func (c *commandVolumeTierMove) Lock(key pb.ServerAddress) func() {
  114. value, _ := c.activeServers.LoadOrStore(key, &sync.Mutex{})
  115. mtx := value.(*sync.Mutex)
  116. mtx.Lock()
  117. return func() { mtx.Unlock() }
  118. }
  119. func filterLocationsByDiskType(dataNodes []location, diskType types.DiskType) (ret []location) {
  120. for _, loc := range dataNodes {
  121. _, found := loc.dataNode.DiskInfos[string(diskType)]
  122. if found {
  123. ret = append(ret, loc)
  124. }
  125. }
  126. return
  127. }
  128. func rotateDataNodes(dataNodes []location) []location {
  129. if len(dataNodes) > 0 {
  130. return append(dataNodes[1:], dataNodes[0])
  131. } else {
  132. return dataNodes
  133. }
  134. }
  135. func isOneOf(server string, locations []wdclient.Location) bool {
  136. for _, loc := range locations {
  137. if server == loc.Url {
  138. return true
  139. }
  140. }
  141. return false
  142. }
  143. func (c *commandVolumeTierMove) doVolumeTierMove(commandEnv *CommandEnv, writer io.Writer, vid needle.VolumeId, toDiskType types.DiskType, allLocations []location) (err error) {
  144. // find volume location
  145. locations, found := commandEnv.MasterClient.GetLocations(uint32(vid))
  146. if !found {
  147. return fmt.Errorf("volume %d not found", vid)
  148. }
  149. // find one server with the most empty volume slots with target disk type
  150. hasFoundTarget := false
  151. fn := capacityByFreeVolumeCount(toDiskType)
  152. for _, dst := range allLocations {
  153. if fn(dst.dataNode) > 0 && !hasFoundTarget {
  154. // ask the volume server to replicate the volume
  155. if isOneOf(dst.dataNode.Id, locations) {
  156. continue
  157. }
  158. var sourceVolumeServer pb.ServerAddress
  159. for _, loc := range locations {
  160. if loc.Url != dst.dataNode.Id {
  161. sourceVolumeServer = loc.ServerAddress()
  162. }
  163. }
  164. if sourceVolumeServer == "" {
  165. continue
  166. }
  167. hasFoundTarget = true
  168. // adjust volume count
  169. dst.dataNode.DiskInfos[string(toDiskType)].VolumeCount++
  170. destServerAddress := pb.NewServerAddressFromDataNode(dst.dataNode)
  171. c.queues[destServerAddress] <- volumeTierMoveJob{sourceVolumeServer, vid}
  172. }
  173. }
  174. if !hasFoundTarget {
  175. fmt.Fprintf(writer, "can not find disk type %s for volume %d\n", toDiskType.ReadableString(), vid)
  176. }
  177. return nil
  178. }
  179. func (c *commandVolumeTierMove) doMoveOneVolume(commandEnv *CommandEnv, writer io.Writer, vid needle.VolumeId, toDiskType types.DiskType, locations []wdclient.Location, sourceVolumeServer pb.ServerAddress, dst location, applyChanges bool) (err error) {
  180. // mark all replicas as read only
  181. if applyChanges {
  182. if err = markVolumeReplicasWritable(commandEnv.option.GrpcDialOption, vid, locations, false); err != nil {
  183. return fmt.Errorf("mark volume %d as readonly on %s: %v", vid, locations[0].Url, err)
  184. }
  185. if err = LiveMoveVolume(commandEnv.option.GrpcDialOption, writer, vid, sourceVolumeServer, pb.NewServerAddressFromDataNode(dst.dataNode), 5*time.Second, toDiskType.ReadableString(), true); err != nil {
  186. // mark all replicas as writable
  187. if err = markVolumeReplicasWritable(commandEnv.option.GrpcDialOption, vid, locations, true); err != nil {
  188. glog.Errorf("mark volume %d as writable on %s: %v", vid, locations[0].Url, err)
  189. }
  190. return fmt.Errorf("move volume %d %s => %s : %v", vid, locations[0].Url, dst.dataNode.Id, err)
  191. }
  192. }
  193. // adjust volume count
  194. dst.dataNode.DiskInfos[string(toDiskType)].VolumeCount++
  195. // remove the remaining replicas
  196. for _, loc := range locations {
  197. if loc.Url != dst.dataNode.Id && loc.ServerAddress() != sourceVolumeServer {
  198. if applyChanges {
  199. if err = deleteVolume(commandEnv.option.GrpcDialOption, vid, loc.ServerAddress()); err != nil {
  200. fmt.Fprintf(writer, "failed to delete volume %d on %s: %v\n", vid, loc.Url, err)
  201. }
  202. }
  203. // reduce volume count? Not really necessary since they are "more" full and will not be a candidate to move to
  204. }
  205. }
  206. return nil
  207. }
  208. 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) {
  209. quietSeconds := int64(quietPeriod / time.Second)
  210. nowUnixSeconds := time.Now().Unix()
  211. fmt.Printf("collect %s volumes quiet for: %d seconds\n", sourceTier, quietSeconds)
  212. vidMap := make(map[uint32]bool)
  213. eachDataNode(topologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  214. for _, diskInfo := range dn.DiskInfos {
  215. for _, v := range diskInfo.VolumeInfos {
  216. // check collection name pattern
  217. if collectionPattern != "" {
  218. matched, err := filepath.Match(collectionPattern, v.Collection)
  219. if err != nil {
  220. return
  221. }
  222. if !matched {
  223. continue
  224. }
  225. }
  226. if v.ModifiedAtSecond+quietSeconds < nowUnixSeconds && types.ToDiskType(v.DiskType) == sourceTier {
  227. if float64(v.Size) > fullPercentage/100*float64(volumeSizeLimitMb)*1024*1024 {
  228. vidMap[v.Id] = true
  229. }
  230. }
  231. }
  232. }
  233. })
  234. for vid := range vidMap {
  235. vids = append(vids, needle.VolumeId(vid))
  236. }
  237. return
  238. }