command_volume_fix_replication.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  7. "github.com/chrislusf/seaweedfs/weed/storage/types"
  8. "io"
  9. "path/filepath"
  10. "sort"
  11. "github.com/chrislusf/seaweedfs/weed/operation"
  12. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  13. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  14. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  15. )
  16. func init() {
  17. Commands = append(Commands, &commandVolumeFixReplication{})
  18. }
  19. type commandVolumeFixReplication struct {
  20. collectionPattern *string
  21. }
  22. func (c *commandVolumeFixReplication) Name() string {
  23. return "volume.fix.replication"
  24. }
  25. func (c *commandVolumeFixReplication) Help() string {
  26. return `add replicas to volumes that are missing replicas
  27. This command finds all over-replicated volumes. If found, it will purge the oldest copies and stop.
  28. This command also finds all under-replicated volumes, and finds volume servers with free slots.
  29. If the free slots satisfy the replication requirement, the volume content is copied over and mounted.
  30. volume.fix.replication -n # do not take action
  31. volume.fix.replication # actually deleting or copying the volume files and mount the volume
  32. volume.fix.replication -collectionPattern=important* # fix any collections with prefix "important"
  33. Note:
  34. * each time this will only add back one replica for each volume id that is under replicated.
  35. If there are multiple replicas are missing, e.g. replica count is > 2, you may need to run this multiple times.
  36. * do not run this too quickly within seconds, since the new volume replica may take a few seconds
  37. to register itself to the master.
  38. `
  39. }
  40. func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  41. if err = commandEnv.confirmIsLocked(); err != nil {
  42. return
  43. }
  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. if err = volFixReplicationCommand.Parse(args); err != nil {
  48. return nil
  49. }
  50. takeAction := !*skipChange
  51. // collect topology information
  52. topologyInfo, _, err := collectTopologyInfo(commandEnv)
  53. if err != nil {
  54. return err
  55. }
  56. // find all volumes that needs replication
  57. // collect all data nodes
  58. volumeReplicas, allLocations := collectVolumeReplicaLocations(topologyInfo)
  59. if len(allLocations) == 0 {
  60. return fmt.Errorf("no data nodes at all")
  61. }
  62. // find all under replicated volumes
  63. var underReplicatedVolumeIds, overReplicatedVolumeIds []uint32
  64. for vid, replicas := range volumeReplicas {
  65. replica := replicas[0]
  66. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  67. if replicaPlacement.GetCopyCount() > len(replicas) {
  68. underReplicatedVolumeIds = append(underReplicatedVolumeIds, vid)
  69. } else if replicaPlacement.GetCopyCount() < len(replicas) {
  70. overReplicatedVolumeIds = append(overReplicatedVolumeIds, vid)
  71. fmt.Fprintf(writer, "volume %d replication %s, but over replicated %+d\n", replica.info.Id, replicaPlacement, len(replicas))
  72. }
  73. }
  74. if len(overReplicatedVolumeIds) > 0 {
  75. return c.fixOverReplicatedVolumes(commandEnv, writer, takeAction, overReplicatedVolumeIds, volumeReplicas, allLocations)
  76. }
  77. if len(underReplicatedVolumeIds) == 0 {
  78. return nil
  79. }
  80. // find the most under populated data nodes
  81. return c.fixUnderReplicatedVolumes(commandEnv, writer, takeAction, underReplicatedVolumeIds, volumeReplicas, allLocations)
  82. }
  83. func collectVolumeReplicaLocations(topologyInfo *master_pb.TopologyInfo) (map[uint32][]*VolumeReplica, []location) {
  84. volumeReplicas := make(map[uint32][]*VolumeReplica)
  85. var allLocations []location
  86. eachDataNode(topologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  87. loc := newLocation(dc, string(rack), dn)
  88. for _, diskInfo := range dn.DiskInfos {
  89. for _, v := range diskInfo.VolumeInfos {
  90. volumeReplicas[v.Id] = append(volumeReplicas[v.Id], &VolumeReplica{
  91. location: &loc,
  92. info: v,
  93. })
  94. }
  95. }
  96. allLocations = append(allLocations, loc)
  97. })
  98. return volumeReplicas, allLocations
  99. }
  100. func (c *commandVolumeFixReplication) fixOverReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, takeAction bool, overReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location) error {
  101. for _, vid := range overReplicatedVolumeIds {
  102. replicas := volumeReplicas[vid]
  103. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replicas[0].info.ReplicaPlacement))
  104. replica := pickOneReplicaToDelete(replicas, replicaPlacement)
  105. // check collection name pattern
  106. if *c.collectionPattern != "" {
  107. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  108. if err != nil {
  109. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  110. }
  111. if !matched {
  112. break
  113. }
  114. }
  115. fmt.Fprintf(writer, "deleting volume %d from %s ...\n", replica.info.Id, replica.location.dataNode.Id)
  116. if !takeAction {
  117. break
  118. }
  119. if err := deleteVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(replica.info.Id), replica.location.dataNode.Id); err != nil {
  120. return fmt.Errorf("deleting volume %d from %s : %v", replica.info.Id, replica.location.dataNode.Id, err)
  121. }
  122. }
  123. return nil
  124. }
  125. func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, takeAction bool, underReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location) error {
  126. for _, vid := range underReplicatedVolumeIds {
  127. replicas := volumeReplicas[vid]
  128. replica := pickOneReplicaToCopyFrom(replicas)
  129. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  130. foundNewLocation := false
  131. hasSkippedCollection := false
  132. keepDataNodesSorted(allLocations, types.ToDiskType(replica.info.DiskType))
  133. fn := capacityByFreeVolumeCount(types.ToDiskType(replica.info.DiskType))
  134. for _, dst := range allLocations {
  135. // check whether data nodes satisfy the constraints
  136. if fn(dst.dataNode) > 0 && satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
  137. // check collection name pattern
  138. if *c.collectionPattern != "" {
  139. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  140. if err != nil {
  141. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  142. }
  143. if !matched {
  144. hasSkippedCollection = true
  145. break
  146. }
  147. }
  148. // ask the volume server to replicate the volume
  149. foundNewLocation = true
  150. fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
  151. if !takeAction {
  152. break
  153. }
  154. err := operation.WithVolumeServerClient(dst.dataNode.Id, commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  155. _, replicateErr := volumeServerClient.VolumeCopy(context.Background(), &volume_server_pb.VolumeCopyRequest{
  156. VolumeId: replica.info.Id,
  157. SourceDataNode: replica.location.dataNode.Id,
  158. })
  159. if replicateErr != nil {
  160. return fmt.Errorf("copying from %s => %s : %v", replica.location.dataNode.Id, dst.dataNode.Id, replicateErr)
  161. }
  162. return nil
  163. })
  164. if err != nil {
  165. return err
  166. }
  167. // adjust free volume count
  168. dst.dataNode.DiskInfos[replica.info.DiskType].FreeVolumeCount--
  169. break
  170. }
  171. }
  172. if !foundNewLocation && !hasSkippedCollection {
  173. fmt.Fprintf(writer, "failed to place volume %d replica as %s, existing:%+v\n", replica.info.Id, replicaPlacement, len(replicas))
  174. }
  175. }
  176. return nil
  177. }
  178. func keepDataNodesSorted(dataNodes []location, diskType types.DiskType) {
  179. fn := capacityByFreeVolumeCount(diskType)
  180. sort.Slice(dataNodes, func(i, j int) bool {
  181. return fn(dataNodes[i].dataNode) > fn(dataNodes[j].dataNode)
  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. }