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.

562 lines
18 KiB

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