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.

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