command_volume_fix_replication.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  7. "github.com/chrislusf/seaweedfs/weed/storage/types"
  8. "io"
  9. "path/filepath"
  10. "sort"
  11. "github.com/chrislusf/seaweedfs/weed/operation"
  12. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  13. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  14. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  15. )
  16. func init() {
  17. Commands = append(Commands, &commandVolumeFixReplication{})
  18. }
  19. type commandVolumeFixReplication struct {
  20. collectionPattern *string
  21. }
  22. func (c *commandVolumeFixReplication) Name() string {
  23. return "volume.fix.replication"
  24. }
  25. func (c *commandVolumeFixReplication) Help() string {
  26. return `add replicas to volumes that are missing replicas
  27. This command finds all over-replicated volumes. If found, it will purge the oldest copies and stop.
  28. This command also finds all under-replicated volumes, and finds volume servers with free slots.
  29. If the free slots satisfy the replication requirement, the volume content is copied over and mounted.
  30. volume.fix.replication -n # do not take action
  31. volume.fix.replication # actually deleting or copying the volume files and mount the volume
  32. volume.fix.replication -collectionPattern=important* # fix any collections with prefix "important"
  33. Note:
  34. * each time this will only add back one replica for each volume id that is under replicated.
  35. If there are multiple replicas are missing, e.g. replica count is > 2, you may need to run this multiple times.
  36. * do not run this too quickly within seconds, since the new volume replica may take a few seconds
  37. to register itself to the master.
  38. `
  39. }
  40. func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  41. if err = commandEnv.confirmIsLocked(); err != nil {
  42. return
  43. }
  44. volFixReplicationCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  45. c.collectionPattern = volFixReplicationCommand.String("collectionPattern", "", "match with wildcard characters '*' and '?'")
  46. skipChange := volFixReplicationCommand.Bool("n", false, "skip the changes")
  47. retryCount := volFixReplicationCommand.Int("retry", 0, "how many times to retry")
  48. if err = volFixReplicationCommand.Parse(args); err != nil {
  49. return nil
  50. }
  51. takeAction := !*skipChange
  52. // collect topology information
  53. topologyInfo, _, err := collectTopologyInfo(commandEnv)
  54. if err != nil {
  55. return err
  56. }
  57. // find all volumes that needs replication
  58. // collect all data nodes
  59. volumeReplicas, allLocations := collectVolumeReplicaLocations(topologyInfo)
  60. if len(allLocations) == 0 {
  61. return fmt.Errorf("no data nodes at all")
  62. }
  63. // find all under replicated volumes
  64. var underReplicatedVolumeIds, overReplicatedVolumeIds []uint32
  65. for vid, replicas := range volumeReplicas {
  66. replica := replicas[0]
  67. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  68. if replicaPlacement.GetCopyCount() > len(replicas) {
  69. underReplicatedVolumeIds = append(underReplicatedVolumeIds, vid)
  70. } else if replicaPlacement.GetCopyCount() < len(replicas) {
  71. overReplicatedVolumeIds = append(overReplicatedVolumeIds, vid)
  72. fmt.Fprintf(writer, "volume %d replication %s, but over replicated %+d\n", replica.info.Id, replicaPlacement, len(replicas))
  73. }
  74. }
  75. if len(overReplicatedVolumeIds) > 0 {
  76. return c.fixOverReplicatedVolumes(commandEnv, writer, takeAction, overReplicatedVolumeIds, volumeReplicas, allLocations)
  77. }
  78. if len(underReplicatedVolumeIds) == 0 {
  79. return nil
  80. }
  81. // find the most under populated data nodes
  82. return c.fixUnderReplicatedVolumes(commandEnv, writer, takeAction, underReplicatedVolumeIds, volumeReplicas, allLocations, *retryCount)
  83. }
  84. func collectVolumeReplicaLocations(topologyInfo *master_pb.TopologyInfo) (map[uint32][]*VolumeReplica, []location) {
  85. volumeReplicas := make(map[uint32][]*VolumeReplica)
  86. var allLocations []location
  87. eachDataNode(topologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  88. loc := newLocation(dc, string(rack), dn)
  89. for _, diskInfo := range dn.DiskInfos {
  90. for _, v := range diskInfo.VolumeInfos {
  91. volumeReplicas[v.Id] = append(volumeReplicas[v.Id], &VolumeReplica{
  92. location: &loc,
  93. info: v,
  94. })
  95. }
  96. }
  97. allLocations = append(allLocations, loc)
  98. })
  99. return volumeReplicas, allLocations
  100. }
  101. func (c *commandVolumeFixReplication) fixOverReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, takeAction bool, overReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location) error {
  102. for _, vid := range overReplicatedVolumeIds {
  103. replicas := volumeReplicas[vid]
  104. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replicas[0].info.ReplicaPlacement))
  105. replica := pickOneReplicaToDelete(replicas, replicaPlacement)
  106. // check collection name pattern
  107. if *c.collectionPattern != "" {
  108. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  109. if err != nil {
  110. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  111. }
  112. if !matched {
  113. break
  114. }
  115. }
  116. fmt.Fprintf(writer, "deleting volume %d from %s ...\n", replica.info.Id, replica.location.dataNode.Id)
  117. if !takeAction {
  118. break
  119. }
  120. if err := deleteVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(replica.info.Id), replica.location.dataNode.Id); err != nil {
  121. return fmt.Errorf("deleting volume %d from %s : %v", replica.info.Id, replica.location.dataNode.Id, err)
  122. }
  123. }
  124. return nil
  125. }
  126. func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, takeAction bool, underReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, retryCount int) (err error) {
  127. for _, vid := range underReplicatedVolumeIds {
  128. for i:=0;i<retryCount+1;i++{
  129. if err = c.fixOneUnderReplicatedVolume(commandEnv, writer, takeAction, volumeReplicas, vid, allLocations); err == nil {
  130. continue
  131. }
  132. }
  133. }
  134. return
  135. }
  136. func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *CommandEnv, writer io.Writer, takeAction bool, volumeReplicas map[uint32][]*VolumeReplica, vid uint32, allLocations []location) error {
  137. replicas := volumeReplicas[vid]
  138. replica := pickOneReplicaToCopyFrom(replicas)
  139. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  140. foundNewLocation := false
  141. hasSkippedCollection := false
  142. keepDataNodesSorted(allLocations, types.ToDiskType(replica.info.DiskType))
  143. fn := capacityByFreeVolumeCount(types.ToDiskType(replica.info.DiskType))
  144. for _, dst := range allLocations {
  145. // check whether data nodes satisfy the constraints
  146. if fn(dst.dataNode) > 0 && satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
  147. // check collection name pattern
  148. if *c.collectionPattern != "" {
  149. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  150. if err != nil {
  151. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  152. }
  153. if !matched {
  154. hasSkippedCollection = true
  155. break
  156. }
  157. }
  158. // ask the volume server to replicate the volume
  159. foundNewLocation = true
  160. fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
  161. if !takeAction {
  162. break
  163. }
  164. err := operation.WithVolumeServerClient(dst.dataNode.Id, commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  165. _, replicateErr := volumeServerClient.VolumeCopy(context.Background(), &volume_server_pb.VolumeCopyRequest{
  166. VolumeId: replica.info.Id,
  167. SourceDataNode: replica.location.dataNode.Id,
  168. })
  169. if replicateErr != nil {
  170. return fmt.Errorf("copying from %s => %s : %v", replica.location.dataNode.Id, dst.dataNode.Id, replicateErr)
  171. }
  172. return nil
  173. })
  174. if err != nil {
  175. return err
  176. }
  177. // adjust free volume count
  178. dst.dataNode.DiskInfos[replica.info.DiskType].FreeVolumeCount--
  179. break
  180. }
  181. }
  182. if !foundNewLocation && !hasSkippedCollection {
  183. fmt.Fprintf(writer, "failed to place volume %d replica as %s, existing:%+v\n", replica.info.Id, replicaPlacement, len(replicas))
  184. }
  185. return nil
  186. }
  187. func keepDataNodesSorted(dataNodes []location, diskType types.DiskType) {
  188. fn := capacityByFreeVolumeCount(diskType)
  189. sort.Slice(dataNodes, func(i, j int) bool {
  190. return fn(dataNodes[i].dataNode) > fn(dataNodes[j].dataNode)
  191. })
  192. }
  193. /*
  194. if on an existing data node {
  195. return false
  196. }
  197. if different from existing dcs {
  198. if lack on different dcs {
  199. return true
  200. }else{
  201. return false
  202. }
  203. }
  204. if not on primary dc {
  205. return false
  206. }
  207. if different from existing racks {
  208. if lack on different racks {
  209. return true
  210. }else{
  211. return false
  212. }
  213. }
  214. if not on primary rack {
  215. return false
  216. }
  217. if lacks on same rack {
  218. return true
  219. } else {
  220. return false
  221. }
  222. */
  223. func satisfyReplicaPlacement(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica, possibleLocation location) bool {
  224. existingDataCenters, _, existingDataNodes := countReplicas(replicas)
  225. if _, found := existingDataNodes[possibleLocation.String()]; found {
  226. // avoid duplicated volume on the same data node
  227. return false
  228. }
  229. primaryDataCenters, _ := findTopKeys(existingDataCenters)
  230. // ensure data center count is within limit
  231. if _, found := existingDataCenters[possibleLocation.DataCenter()]; !found {
  232. // different from existing dcs
  233. if len(existingDataCenters) < replicaPlacement.DiffDataCenterCount+1 {
  234. // lack on different dcs
  235. return true
  236. } else {
  237. // adding this would go over the different dcs limit
  238. return false
  239. }
  240. }
  241. // now this is same as one of the existing data center
  242. if !isAmong(possibleLocation.DataCenter(), primaryDataCenters) {
  243. // not on one of the primary dcs
  244. return false
  245. }
  246. // now this is one of the primary dcs
  247. primaryDcRacks := make(map[string]int)
  248. for _, replica := range replicas {
  249. if replica.location.DataCenter() != possibleLocation.DataCenter() {
  250. continue
  251. }
  252. primaryDcRacks[replica.location.Rack()] += 1
  253. }
  254. primaryRacks, _ := findTopKeys(primaryDcRacks)
  255. sameRackCount := primaryDcRacks[possibleLocation.Rack()]
  256. // ensure rack count is within limit
  257. if _, found := primaryDcRacks[possibleLocation.Rack()]; !found {
  258. // different from existing racks
  259. if len(primaryDcRacks) < replicaPlacement.DiffRackCount+1 {
  260. // lack on different racks
  261. return true
  262. } else {
  263. // adding this would go over the different racks limit
  264. return false
  265. }
  266. }
  267. // now this is same as one of the existing racks
  268. if !isAmong(possibleLocation.Rack(), primaryRacks) {
  269. // not on the primary rack
  270. return false
  271. }
  272. // now this is on the primary rack
  273. // different from existing data nodes
  274. if sameRackCount < replicaPlacement.SameRackCount+1 {
  275. // lack on same rack
  276. return true
  277. } else {
  278. // adding this would go over the same data node limit
  279. return false
  280. }
  281. }
  282. func findTopKeys(m map[string]int) (topKeys []string, max int) {
  283. for k, c := range m {
  284. if max < c {
  285. topKeys = topKeys[:0]
  286. topKeys = append(topKeys, k)
  287. max = c
  288. } else if max == c {
  289. topKeys = append(topKeys, k)
  290. }
  291. }
  292. return
  293. }
  294. func isAmong(key string, keys []string) bool {
  295. for _, k := range keys {
  296. if k == key {
  297. return true
  298. }
  299. }
  300. return false
  301. }
  302. type VolumeReplica struct {
  303. location *location
  304. info *master_pb.VolumeInformationMessage
  305. }
  306. type location struct {
  307. dc string
  308. rack string
  309. dataNode *master_pb.DataNodeInfo
  310. }
  311. func newLocation(dc, rack string, dataNode *master_pb.DataNodeInfo) location {
  312. return location{
  313. dc: dc,
  314. rack: rack,
  315. dataNode: dataNode,
  316. }
  317. }
  318. func (l location) String() string {
  319. return fmt.Sprintf("%s %s %s", l.dc, l.rack, l.dataNode.Id)
  320. }
  321. func (l location) Rack() string {
  322. return fmt.Sprintf("%s %s", l.dc, l.rack)
  323. }
  324. func (l location) DataCenter() string {
  325. return l.dc
  326. }
  327. func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
  328. mostRecent := replicas[0]
  329. for _, replica := range replicas {
  330. if replica.info.ModifiedAtSecond > mostRecent.info.ModifiedAtSecond {
  331. mostRecent = replica
  332. }
  333. }
  334. return mostRecent
  335. }
  336. func countReplicas(replicas []*VolumeReplica) (diffDc, diffRack, diffNode map[string]int) {
  337. diffDc = make(map[string]int)
  338. diffRack = make(map[string]int)
  339. diffNode = make(map[string]int)
  340. for _, replica := range replicas {
  341. diffDc[replica.location.DataCenter()] += 1
  342. diffRack[replica.location.Rack()] += 1
  343. diffNode[replica.location.String()] += 1
  344. }
  345. return
  346. }
  347. func pickOneReplicaToDelete(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
  348. sort.Slice(replicas, func(i, j int) bool {
  349. a, b := replicas[i], replicas[j]
  350. if a.info.CompactRevision != b.info.CompactRevision {
  351. return a.info.CompactRevision < b.info.CompactRevision
  352. }
  353. if a.info.ModifiedAtSecond != b.info.ModifiedAtSecond {
  354. return a.info.ModifiedAtSecond < b.info.ModifiedAtSecond
  355. }
  356. if a.info.Size != b.info.Size {
  357. return a.info.Size < b.info.Size
  358. }
  359. return false
  360. })
  361. return replicas[0]
  362. }