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.

414 lines
12 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 one volume id. If there are multiple replicas
  34. are missing, e.g. multiple volume servers are new, 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. keepDataNodesSorted(allLocations)
  84. return c.fixUnderReplicatedVolumes(commandEnv, writer, takeAction, underReplicatedVolumeIds, volumeReplicas, allLocations)
  85. }
  86. func collectVolumeReplicaLocations(resp *master_pb.VolumeListResponse) (map[uint32][]*VolumeReplica, []location) {
  87. volumeReplicas := make(map[uint32][]*VolumeReplica)
  88. var allLocations []location
  89. eachDataNode(resp.TopologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  90. loc := newLocation(dc, string(rack), dn)
  91. for _, v := range dn.VolumeInfos {
  92. volumeReplicas[v.Id] = append(volumeReplicas[v.Id], &VolumeReplica{
  93. location: &loc,
  94. info: v,
  95. })
  96. }
  97. allLocations = append(allLocations, loc)
  98. })
  99. return volumeReplicas, allLocations
  100. }
  101. func (c *commandVolumeFixReplication) fixOverReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, takeAction bool, overReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location) error {
  102. for _, vid := range overReplicatedVolumeIds {
  103. replicas := volumeReplicas[vid]
  104. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replicas[0].info.ReplicaPlacement))
  105. replica := pickOneReplicaToDelete(replicas, replicaPlacement)
  106. // check collection name pattern
  107. if *c.collectionPattern != "" {
  108. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  109. if err != nil {
  110. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  111. }
  112. if !matched {
  113. break
  114. }
  115. }
  116. fmt.Fprintf(writer, "deleting volume %d from %s ...\n", replica.info.Id, replica.location.dataNode.Id)
  117. if !takeAction {
  118. break
  119. }
  120. if err := deleteVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(replica.info.Id), replica.location.dataNode.Id); err != nil {
  121. return fmt.Errorf("deleting volume %d from %s : %v", replica.info.Id, replica.location.dataNode.Id, err)
  122. }
  123. }
  124. return nil
  125. }
  126. func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, takeAction bool, underReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location) error {
  127. for _, vid := range underReplicatedVolumeIds {
  128. replicas := volumeReplicas[vid]
  129. replica := pickOneReplicaToCopyFrom(replicas)
  130. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  131. foundNewLocation := false
  132. for _, dst := range allLocations {
  133. // check whether data nodes satisfy the constraints
  134. if dst.dataNode.FreeVolumeCount > 0 && satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
  135. // check collection name pattern
  136. if *c.collectionPattern != "" {
  137. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  138. if err != nil {
  139. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  140. }
  141. if !matched {
  142. break
  143. }
  144. }
  145. // ask the volume server to replicate the volume
  146. foundNewLocation = true
  147. fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
  148. if !takeAction {
  149. break
  150. }
  151. err := operation.WithVolumeServerClient(dst.dataNode.Id, commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  152. _, replicateErr := volumeServerClient.VolumeCopy(context.Background(), &volume_server_pb.VolumeCopyRequest{
  153. VolumeId: replica.info.Id,
  154. SourceDataNode: replica.location.dataNode.Id,
  155. })
  156. if replicateErr != nil {
  157. return fmt.Errorf("copying from %s => %s : %v", replica.location.dataNode.Id, dst.dataNode.Id, replicateErr)
  158. }
  159. return nil
  160. })
  161. if err != nil {
  162. return err
  163. }
  164. // adjust free volume count
  165. dst.dataNode.FreeVolumeCount--
  166. keepDataNodesSorted(allLocations)
  167. break
  168. }
  169. }
  170. if !foundNewLocation {
  171. fmt.Fprintf(writer, "failed to place volume %d replica as %s, existing:%+v\n", replica.info.Id, replicaPlacement, len(replicas))
  172. }
  173. }
  174. return nil
  175. }
  176. func keepDataNodesSorted(dataNodes []location) {
  177. sort.Slice(dataNodes, func(i, j int) bool {
  178. return dataNodes[i].dataNode.FreeVolumeCount > dataNodes[j].dataNode.FreeVolumeCount
  179. })
  180. }
  181. /*
  182. if on an existing data node {
  183. return false
  184. }
  185. if different from existing dcs {
  186. if lack on different dcs {
  187. return true
  188. }else{
  189. return false
  190. }
  191. }
  192. if not on primary dc {
  193. return false
  194. }
  195. if different from existing racks {
  196. if lack on different racks {
  197. return true
  198. }else{
  199. return false
  200. }
  201. }
  202. if not on primary rack {
  203. return false
  204. }
  205. if lacks on same rack {
  206. return true
  207. } else {
  208. return false
  209. }
  210. */
  211. func satisfyReplicaPlacement(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica, possibleLocation location) bool {
  212. existingDataCenters, _, existingDataNodes := countReplicas(replicas)
  213. if _, found := existingDataNodes[possibleLocation.String()]; found {
  214. // avoid duplicated volume on the same data node
  215. return false
  216. }
  217. primaryDataCenters, _ := findTopKeys(existingDataCenters)
  218. // ensure data center count is within limit
  219. if _, found := existingDataCenters[possibleLocation.DataCenter()]; !found {
  220. // different from existing dcs
  221. if len(existingDataCenters) < replicaPlacement.DiffDataCenterCount+1 {
  222. // lack on different dcs
  223. return true
  224. } else {
  225. // adding this would go over the different dcs limit
  226. return false
  227. }
  228. }
  229. // now this is same as one of the existing data center
  230. if !isAmong(possibleLocation.DataCenter(), primaryDataCenters) {
  231. // not on one of the primary dcs
  232. return false
  233. }
  234. // now this is one of the primary dcs
  235. primaryDcRacks := make(map[string]int)
  236. for _, replica := range replicas {
  237. if replica.location.DataCenter() != possibleLocation.DataCenter() {
  238. continue
  239. }
  240. primaryDcRacks[replica.location.Rack()] += 1
  241. }
  242. primaryRacks, _ := findTopKeys(primaryDcRacks)
  243. sameRackCount := primaryDcRacks[possibleLocation.Rack()]
  244. // ensure rack count is within limit
  245. if _, found := primaryDcRacks[possibleLocation.Rack()]; !found {
  246. // different from existing racks
  247. if len(primaryDcRacks) < replicaPlacement.DiffRackCount+1 {
  248. // lack on different racks
  249. return true
  250. } else {
  251. // adding this would go over the different racks limit
  252. return false
  253. }
  254. }
  255. // now this is same as one of the existing racks
  256. if !isAmong(possibleLocation.Rack(), primaryRacks) {
  257. // not on the primary rack
  258. return false
  259. }
  260. // now this is on the primary rack
  261. // different from existing data nodes
  262. if sameRackCount < replicaPlacement.SameRackCount+1 {
  263. // lack on same rack
  264. return true
  265. } else {
  266. // adding this would go over the same data node limit
  267. return false
  268. }
  269. }
  270. func findTopKeys(m map[string]int) (topKeys []string, max int) {
  271. for k, c := range m {
  272. if max < c {
  273. topKeys = topKeys[:0]
  274. topKeys = append(topKeys, k)
  275. max = c
  276. } else if max == c {
  277. topKeys = append(topKeys, k)
  278. }
  279. }
  280. return
  281. }
  282. func isAmong(key string, keys []string) bool {
  283. for _, k := range keys {
  284. if k == key {
  285. return true
  286. }
  287. }
  288. return false
  289. }
  290. type VolumeReplica struct {
  291. location *location
  292. info *master_pb.VolumeInformationMessage
  293. }
  294. type location struct {
  295. dc string
  296. rack string
  297. dataNode *master_pb.DataNodeInfo
  298. }
  299. func newLocation(dc, rack string, dataNode *master_pb.DataNodeInfo) location {
  300. return location{
  301. dc: dc,
  302. rack: rack,
  303. dataNode: dataNode,
  304. }
  305. }
  306. func (l location) String() string {
  307. return fmt.Sprintf("%s %s %s", l.dc, l.rack, l.dataNode.Id)
  308. }
  309. func (l location) Rack() string {
  310. return fmt.Sprintf("%s %s", l.dc, l.rack)
  311. }
  312. func (l location) DataCenter() string {
  313. return l.dc
  314. }
  315. func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
  316. mostRecent := replicas[0]
  317. for _, replica := range replicas {
  318. if replica.info.ModifiedAtSecond > mostRecent.info.ModifiedAtSecond {
  319. mostRecent = replica
  320. }
  321. }
  322. return mostRecent
  323. }
  324. func countReplicas(replicas []*VolumeReplica) (diffDc, diffRack, diffNode map[string]int) {
  325. diffDc = make(map[string]int)
  326. diffRack = make(map[string]int)
  327. diffNode = make(map[string]int)
  328. for _, replica := range replicas {
  329. diffDc[replica.location.DataCenter()] += 1
  330. diffRack[replica.location.Rack()] += 1
  331. diffNode[replica.location.String()] += 1
  332. }
  333. return
  334. }
  335. func pickOneReplicaToDelete(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
  336. sort.Slice(replicas, func(i, j int) bool {
  337. a, b := replicas[i], replicas[j]
  338. if a.info.CompactRevision != b.info.CompactRevision {
  339. return a.info.CompactRevision < b.info.CompactRevision
  340. }
  341. if a.info.ModifiedAtSecond != b.info.ModifiedAtSecond {
  342. return a.info.ModifiedAtSecond < b.info.ModifiedAtSecond
  343. }
  344. if a.info.Size != b.info.Size {
  345. return a.info.Size < b.info.Size
  346. }
  347. return false
  348. })
  349. return replicas[0]
  350. }