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.

571 lines
18 KiB

3 years ago
6 years ago
4 years ago
6 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/seaweedfs/seaweedfs/weed/pb"
  7. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  8. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  9. "golang.org/x/exp/slices"
  10. "io"
  11. "path/filepath"
  12. "strconv"
  13. "time"
  14. "github.com/seaweedfs/seaweedfs/weed/operation"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  16. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  18. )
  19. func init() {
  20. Commands = append(Commands, &commandVolumeFixReplication{})
  21. }
  22. type commandVolumeFixReplication struct {
  23. collectionPattern *string
  24. }
  25. func (c *commandVolumeFixReplication) Name() string {
  26. return "volume.fix.replication"
  27. }
  28. func (c *commandVolumeFixReplication) Help() string {
  29. return `add or remove replicas to volumes that are missing replicas or over-replicated
  30. This command finds all over-replicated volumes. If found, it will purge the oldest copies and stop.
  31. This command also finds all under-replicated volumes, and finds volume servers with free slots.
  32. If the free slots satisfy the replication requirement, the volume content is copied over and mounted.
  33. volume.fix.replication -n # do not take action
  34. volume.fix.replication # actually deleting or copying the volume files and mount the volume
  35. volume.fix.replication -collectionPattern=important* # fix any collections with prefix "important"
  36. Note:
  37. * each time this will only add back one replica for each volume id that is under replicated.
  38. If there are multiple replicas are missing, e.g. replica count is > 2, you may need to run this multiple times.
  39. * do not run this too quickly within seconds, since the new volume replica may take a few seconds
  40. to register itself to the master.
  41. `
  42. }
  43. func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  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. noDelete := volFixReplicationCommand.Bool("noDelete", false, "Do not delete over-replicated volumes, only fix under-replication")
  48. retryCount := volFixReplicationCommand.Int("retry", 5, "how many times to retry")
  49. volumesPerStep := volFixReplicationCommand.Int("volumesPerStep", 0, "how many volumes to fix in one cycle")
  50. if err = volFixReplicationCommand.Parse(args); err != nil {
  51. return nil
  52. }
  53. if err = commandEnv.confirmIsLocked(args); err != nil {
  54. return
  55. }
  56. takeAction := !*skipChange
  57. doDeletes := !*noDelete
  58. underReplicatedVolumeIdsCount := 1
  59. for underReplicatedVolumeIdsCount > 0 {
  60. fixedVolumeReplicas := map[string]int{}
  61. // collect topology information
  62. topologyInfo, _, err := collectTopologyInfo(commandEnv, 15*time.Second)
  63. if err != nil {
  64. return err
  65. }
  66. // find all volumes that needs replication
  67. // collect all data nodes
  68. volumeReplicas, allLocations := collectVolumeReplicaLocations(topologyInfo)
  69. if len(allLocations) == 0 {
  70. return fmt.Errorf("no data nodes at all")
  71. }
  72. // find all under replicated volumes
  73. var underReplicatedVolumeIds, overReplicatedVolumeIds, misplacedVolumeIds []uint32
  74. for vid, replicas := range volumeReplicas {
  75. replica := replicas[0]
  76. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  77. if replicaPlacement.GetCopyCount() > len(replicas) {
  78. underReplicatedVolumeIds = append(underReplicatedVolumeIds, vid)
  79. } else if replicaPlacement.GetCopyCount() < len(replicas) {
  80. overReplicatedVolumeIds = append(overReplicatedVolumeIds, vid)
  81. fmt.Fprintf(writer, "volume %d replication %s, but over replicated %+d\n", replica.info.Id, replicaPlacement, len(replicas))
  82. } else if isMisplaced(replicas, replicaPlacement) {
  83. misplacedVolumeIds = append(misplacedVolumeIds, vid)
  84. fmt.Fprintf(writer, "volume %d replication %s is not well placed %+v\n", replica.info.Id, replicaPlacement, replicas)
  85. }
  86. }
  87. if !commandEnv.isLocked() {
  88. return fmt.Errorf("lock is lost")
  89. }
  90. if len(overReplicatedVolumeIds) > 0 && doDeletes {
  91. if err := c.deleteOneVolume(commandEnv, writer, takeAction, overReplicatedVolumeIds, volumeReplicas, allLocations, pickOneReplicaToDelete); err != nil {
  92. return err
  93. }
  94. }
  95. if len(misplacedVolumeIds) > 0 && doDeletes {
  96. if err := c.deleteOneVolume(commandEnv, writer, takeAction, misplacedVolumeIds, volumeReplicas, allLocations, pickOneMisplacedVolume); err != nil {
  97. return err
  98. }
  99. }
  100. underReplicatedVolumeIdsCount = len(underReplicatedVolumeIds)
  101. if underReplicatedVolumeIdsCount > 0 {
  102. // find the most under populated data nodes
  103. fixedVolumeReplicas, err = c.fixUnderReplicatedVolumes(commandEnv, writer, takeAction, underReplicatedVolumeIds, volumeReplicas, allLocations, *retryCount, *volumesPerStep)
  104. if err != nil {
  105. return err
  106. }
  107. }
  108. if *skipChange {
  109. break
  110. }
  111. // check that the topology has been updated
  112. if len(fixedVolumeReplicas) > 0 {
  113. fixedVolumes := make([]string, 0, len(fixedVolumeReplicas))
  114. for k, _ := range fixedVolumeReplicas {
  115. fixedVolumes = append(fixedVolumes, k)
  116. }
  117. volumeIdLocations, err := lookupVolumeIds(commandEnv, fixedVolumes)
  118. if err != nil {
  119. return err
  120. }
  121. for _, volumeIdLocation := range volumeIdLocations {
  122. volumeId := volumeIdLocation.VolumeOrFileId
  123. volumeIdLocationCount := len(volumeIdLocation.Locations)
  124. i := 0
  125. for fixedVolumeReplicas[volumeId] >= volumeIdLocationCount {
  126. fmt.Fprintf(writer, "the number of locations for volume %s has not increased yet, let's wait\n", volumeId)
  127. time.Sleep(time.Duration(i+1) * time.Second * 7)
  128. volumeLocIds, err := lookupVolumeIds(commandEnv, []string{volumeId})
  129. if err != nil {
  130. return err
  131. }
  132. volumeIdLocationCount = len(volumeLocIds[0].Locations)
  133. if *retryCount <= i {
  134. return fmt.Errorf("replicas volume %s mismatch in topology", volumeId)
  135. }
  136. i += 1
  137. }
  138. }
  139. }
  140. }
  141. return nil
  142. }
  143. func collectVolumeReplicaLocations(topologyInfo *master_pb.TopologyInfo) (map[uint32][]*VolumeReplica, []location) {
  144. volumeReplicas := make(map[uint32][]*VolumeReplica)
  145. var allLocations []location
  146. eachDataNode(topologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  147. loc := newLocation(dc, string(rack), dn)
  148. for _, diskInfo := range dn.DiskInfos {
  149. for _, v := range diskInfo.VolumeInfos {
  150. volumeReplicas[v.Id] = append(volumeReplicas[v.Id], &VolumeReplica{
  151. location: &loc,
  152. info: v,
  153. })
  154. }
  155. }
  156. allLocations = append(allLocations, loc)
  157. })
  158. return volumeReplicas, allLocations
  159. }
  160. type SelectOneVolumeFunc func(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica
  161. func (c *commandVolumeFixReplication) deleteOneVolume(commandEnv *CommandEnv, writer io.Writer, takeAction bool, overReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, selectOneVolumeFn SelectOneVolumeFunc) error {
  162. for _, vid := range overReplicatedVolumeIds {
  163. replicas := volumeReplicas[vid]
  164. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replicas[0].info.ReplicaPlacement))
  165. replica := selectOneVolumeFn(replicas, replicaPlacement)
  166. // check collection name pattern
  167. if *c.collectionPattern != "" {
  168. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  169. if err != nil {
  170. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  171. }
  172. if !matched {
  173. break
  174. }
  175. }
  176. collectionIsMismatch := false
  177. for _, volumeReplica := range replicas {
  178. if volumeReplica.info.Collection != replica.info.Collection {
  179. fmt.Fprintf(writer, "skip delete volume %d as collection %s is mismatch: %s\n", replica.info.Id, replica.info.Collection, volumeReplica.info.Collection)
  180. collectionIsMismatch = true
  181. }
  182. }
  183. if collectionIsMismatch {
  184. continue
  185. }
  186. fmt.Fprintf(writer, "deleting volume %d from %s ...\n", replica.info.Id, replica.location.dataNode.Id)
  187. if !takeAction {
  188. break
  189. }
  190. if err := deleteVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(replica.info.Id),
  191. pb.NewServerAddressFromDataNode(replica.location.dataNode), false); err != nil {
  192. return fmt.Errorf("deleting volume %d from %s : %v", replica.info.Id, replica.location.dataNode.Id, err)
  193. }
  194. }
  195. return nil
  196. }
  197. func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, takeAction bool, underReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, retryCount int, volumesPerStep int) (fixedVolumes map[string]int, err error) {
  198. fixedVolumes = map[string]int{}
  199. if len(underReplicatedVolumeIds) > volumesPerStep && volumesPerStep > 0 {
  200. underReplicatedVolumeIds = underReplicatedVolumeIds[0:volumesPerStep]
  201. }
  202. for _, vid := range underReplicatedVolumeIds {
  203. for i := 0; i < retryCount+1; i++ {
  204. if err = c.fixOneUnderReplicatedVolume(commandEnv, writer, takeAction, volumeReplicas, vid, allLocations); err == nil {
  205. if takeAction {
  206. fixedVolumes[strconv.FormatUint(uint64(vid), 10)] = len(volumeReplicas[vid])
  207. }
  208. break
  209. }
  210. }
  211. }
  212. return fixedVolumes, nil
  213. }
  214. func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *CommandEnv, writer io.Writer, takeAction bool, volumeReplicas map[uint32][]*VolumeReplica, vid uint32, allLocations []location) error {
  215. replicas := volumeReplicas[vid]
  216. replica := pickOneReplicaToCopyFrom(replicas)
  217. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  218. foundNewLocation := false
  219. hasSkippedCollection := false
  220. keepDataNodesSorted(allLocations, types.ToDiskType(replica.info.DiskType))
  221. fn := capacityByFreeVolumeCount(types.ToDiskType(replica.info.DiskType))
  222. for _, dst := range allLocations {
  223. // check whether data nodes satisfy the constraints
  224. if fn(dst.dataNode) > 0 && satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
  225. // check collection name pattern
  226. if *c.collectionPattern != "" {
  227. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  228. if err != nil {
  229. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  230. }
  231. if !matched {
  232. hasSkippedCollection = true
  233. break
  234. }
  235. }
  236. // ask the volume server to replicate the volume
  237. foundNewLocation = true
  238. fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
  239. if !takeAction {
  240. // adjust free volume count
  241. dst.dataNode.DiskInfos[replica.info.DiskType].FreeVolumeCount--
  242. break
  243. }
  244. err := operation.WithVolumeServerClient(false, pb.NewServerAddressFromDataNode(dst.dataNode), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  245. stream, replicateErr := volumeServerClient.VolumeCopy(context.Background(), &volume_server_pb.VolumeCopyRequest{
  246. VolumeId: replica.info.Id,
  247. SourceDataNode: string(pb.NewServerAddressFromDataNode(replica.location.dataNode)),
  248. })
  249. if replicateErr != nil {
  250. return fmt.Errorf("copying from %s => %s : %v", replica.location.dataNode.Id, dst.dataNode.Id, replicateErr)
  251. }
  252. for {
  253. resp, recvErr := stream.Recv()
  254. if recvErr != nil {
  255. if recvErr == io.EOF {
  256. break
  257. } else {
  258. return recvErr
  259. }
  260. }
  261. if resp.ProcessedBytes > 0 {
  262. fmt.Fprintf(writer, "volume %d processed %d bytes\n", replica.info.Id, resp.ProcessedBytes)
  263. }
  264. }
  265. return nil
  266. })
  267. if err != nil {
  268. return err
  269. }
  270. // adjust free volume count
  271. dst.dataNode.DiskInfos[replica.info.DiskType].FreeVolumeCount--
  272. break
  273. }
  274. }
  275. if !foundNewLocation && !hasSkippedCollection {
  276. fmt.Fprintf(writer, "failed to place volume %d replica as %s, existing:%+v\n", replica.info.Id, replicaPlacement, len(replicas))
  277. }
  278. return nil
  279. }
  280. func keepDataNodesSorted(dataNodes []location, diskType types.DiskType) {
  281. fn := capacityByFreeVolumeCount(diskType)
  282. slices.SortFunc(dataNodes, func(a, b location) bool {
  283. return fn(a.dataNode) > fn(b.dataNode)
  284. })
  285. }
  286. /*
  287. if on an existing data node {
  288. return false
  289. }
  290. if different from existing dcs {
  291. if lack on different dcs {
  292. return true
  293. }else{
  294. return false
  295. }
  296. }
  297. if not on primary dc {
  298. return false
  299. }
  300. if different from existing racks {
  301. if lack on different racks {
  302. return true
  303. }else{
  304. return false
  305. }
  306. }
  307. if not on primary rack {
  308. return false
  309. }
  310. if lacks on same rack {
  311. return true
  312. } else {
  313. return false
  314. }
  315. */
  316. func satisfyReplicaPlacement(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica, possibleLocation location) bool {
  317. existingDataCenters, _, existingDataNodes := countReplicas(replicas)
  318. if _, found := existingDataNodes[possibleLocation.String()]; found {
  319. // avoid duplicated volume on the same data node
  320. return false
  321. }
  322. primaryDataCenters, _ := findTopKeys(existingDataCenters)
  323. // ensure data center count is within limit
  324. if _, found := existingDataCenters[possibleLocation.DataCenter()]; !found {
  325. // different from existing dcs
  326. if len(existingDataCenters) < replicaPlacement.DiffDataCenterCount+1 {
  327. // lack on different dcs
  328. return true
  329. } else {
  330. // adding this would go over the different dcs limit
  331. return false
  332. }
  333. }
  334. // now this is same as one of the existing data center
  335. if !isAmong(possibleLocation.DataCenter(), primaryDataCenters) {
  336. // not on one of the primary dcs
  337. return false
  338. }
  339. // now this is one of the primary dcs
  340. primaryDcRacks := make(map[string]int)
  341. for _, replica := range replicas {
  342. if replica.location.DataCenter() != possibleLocation.DataCenter() {
  343. continue
  344. }
  345. primaryDcRacks[replica.location.Rack()] += 1
  346. }
  347. primaryRacks, _ := findTopKeys(primaryDcRacks)
  348. sameRackCount := primaryDcRacks[possibleLocation.Rack()]
  349. // ensure rack count is within limit
  350. if _, found := primaryDcRacks[possibleLocation.Rack()]; !found {
  351. // different from existing racks
  352. if len(primaryDcRacks) < replicaPlacement.DiffRackCount+1 {
  353. // lack on different racks
  354. return true
  355. } else {
  356. // adding this would go over the different racks limit
  357. return false
  358. }
  359. }
  360. // now this is same as one of the existing racks
  361. if !isAmong(possibleLocation.Rack(), primaryRacks) {
  362. // not on the primary rack
  363. return false
  364. }
  365. // now this is on the primary rack
  366. // different from existing data nodes
  367. if sameRackCount < replicaPlacement.SameRackCount+1 {
  368. // lack on same rack
  369. return true
  370. } else {
  371. // adding this would go over the same data node limit
  372. return false
  373. }
  374. }
  375. func findTopKeys(m map[string]int) (topKeys []string, max int) {
  376. for k, c := range m {
  377. if max < c {
  378. topKeys = topKeys[:0]
  379. topKeys = append(topKeys, k)
  380. max = c
  381. } else if max == c {
  382. topKeys = append(topKeys, k)
  383. }
  384. }
  385. return
  386. }
  387. func isAmong(key string, keys []string) bool {
  388. for _, k := range keys {
  389. if k == key {
  390. return true
  391. }
  392. }
  393. return false
  394. }
  395. type VolumeReplica struct {
  396. location *location
  397. info *master_pb.VolumeInformationMessage
  398. }
  399. type location struct {
  400. dc string
  401. rack string
  402. dataNode *master_pb.DataNodeInfo
  403. }
  404. func newLocation(dc, rack string, dataNode *master_pb.DataNodeInfo) location {
  405. return location{
  406. dc: dc,
  407. rack: rack,
  408. dataNode: dataNode,
  409. }
  410. }
  411. func (l location) String() string {
  412. return fmt.Sprintf("%s %s %s", l.dc, l.rack, l.dataNode.Id)
  413. }
  414. func (l location) Rack() string {
  415. return fmt.Sprintf("%s %s", l.dc, l.rack)
  416. }
  417. func (l location) DataCenter() string {
  418. return l.dc
  419. }
  420. func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
  421. mostRecent := replicas[0]
  422. for _, replica := range replicas {
  423. if replica.info.ModifiedAtSecond > mostRecent.info.ModifiedAtSecond {
  424. mostRecent = replica
  425. }
  426. }
  427. return mostRecent
  428. }
  429. func countReplicas(replicas []*VolumeReplica) (diffDc, diffRack, diffNode map[string]int) {
  430. diffDc = make(map[string]int)
  431. diffRack = make(map[string]int)
  432. diffNode = make(map[string]int)
  433. for _, replica := range replicas {
  434. diffDc[replica.location.DataCenter()] += 1
  435. diffRack[replica.location.Rack()] += 1
  436. diffNode[replica.location.String()] += 1
  437. }
  438. return
  439. }
  440. func pickOneReplicaToDelete(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
  441. slices.SortFunc(replicas, func(a, b *VolumeReplica) bool {
  442. if a.info.Size != b.info.Size {
  443. return a.info.Size < b.info.Size
  444. }
  445. if a.info.ModifiedAtSecond != b.info.ModifiedAtSecond {
  446. return a.info.ModifiedAtSecond < b.info.ModifiedAtSecond
  447. }
  448. if a.info.CompactRevision != b.info.CompactRevision {
  449. return a.info.CompactRevision < b.info.CompactRevision
  450. }
  451. return false
  452. })
  453. return replicas[0]
  454. }
  455. // check and fix misplaced volumes
  456. func isMisplaced(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) bool {
  457. for i := 0; i < len(replicas); i++ {
  458. others := otherThan(replicas, i)
  459. if satisfyReplicaPlacement(replicaPlacement, others, *replicas[i].location) {
  460. return false
  461. }
  462. }
  463. return true
  464. }
  465. func otherThan(replicas []*VolumeReplica, index int) (others []*VolumeReplica) {
  466. for i := 0; i < len(replicas); i++ {
  467. if index != i {
  468. others = append(others, replicas[i])
  469. }
  470. }
  471. return
  472. }
  473. func pickOneMisplacedVolume(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) (toDelete *VolumeReplica) {
  474. var deletionCandidates []*VolumeReplica
  475. for i := 0; i < len(replicas); i++ {
  476. others := otherThan(replicas, i)
  477. if !isMisplaced(others, replicaPlacement) {
  478. deletionCandidates = append(deletionCandidates, replicas[i])
  479. }
  480. }
  481. if len(deletionCandidates) > 0 {
  482. return pickOneReplicaToDelete(deletionCandidates, replicaPlacement)
  483. }
  484. return pickOneReplicaToDelete(replicas, replicaPlacement)
  485. }