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.

418 lines
13 KiB

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