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.

554 lines
18 KiB

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