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.

638 lines
20 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
3 years ago
4 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
2 years ago
4 years ago
4 years ago
4 years ago
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "path/filepath"
  8. "strconv"
  9. "time"
  10. "github.com/seaweedfs/seaweedfs/weed/pb"
  11. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  12. "github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
  13. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  14. "golang.org/x/exp/slices"
  15. "google.golang.org/grpc"
  16. "github.com/seaweedfs/seaweedfs/weed/operation"
  17. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  18. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  19. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  20. )
  21. func init() {
  22. Commands = append(Commands, &commandVolumeFixReplication{})
  23. }
  24. type commandVolumeFixReplication struct {
  25. collectionPattern *string
  26. }
  27. func (c *commandVolumeFixReplication) Name() string {
  28. return "volume.fix.replication"
  29. }
  30. func (c *commandVolumeFixReplication) Help() string {
  31. return `add or remove replicas to volumes that are missing replicas or over-replicated
  32. This command finds all over-replicated volumes. If found, it will purge the oldest copies and stop.
  33. This command also finds all under-replicated volumes, and finds volume servers with free slots.
  34. If the free slots satisfy the replication requirement, the volume content is copied over and mounted.
  35. volume.fix.replication -n # do not take action
  36. volume.fix.replication # actually deleting or copying the volume files and mount the volume
  37. volume.fix.replication -collectionPattern=important* # fix any collections with prefix "important"
  38. Note:
  39. * each time this will only add back one replica for each volume id that is under replicated.
  40. If there are multiple replicas are missing, e.g. replica count is > 2, you may need to run this multiple times.
  41. * do not run this too quickly within seconds, since the new volume replica may take a few seconds
  42. to register itself to the master.
  43. `
  44. }
  45. func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  46. volFixReplicationCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  47. c.collectionPattern = volFixReplicationCommand.String("collectionPattern", "", "match with wildcard characters '*' and '?'")
  48. skipChange := volFixReplicationCommand.Bool("n", false, "skip the changes")
  49. doDelete := volFixReplicationCommand.Bool("doDelete", true, "Also delete over-replicated volumes besides fixing under-replication")
  50. doCheck := volFixReplicationCommand.Bool("doCheck", true, "Also check synchronization before deleting")
  51. retryCount := volFixReplicationCommand.Int("retry", 5, "how many times to retry")
  52. volumesPerStep := volFixReplicationCommand.Int("volumesPerStep", 0, "how many volumes to fix in one cycle")
  53. if err = volFixReplicationCommand.Parse(args); err != nil {
  54. return nil
  55. }
  56. if err = commandEnv.confirmIsLocked(args); err != nil {
  57. return
  58. }
  59. takeAction := !*skipChange
  60. underReplicatedVolumeIdsCount := 1
  61. for underReplicatedVolumeIdsCount > 0 {
  62. fixedVolumeReplicas := map[string]int{}
  63. // collect topology information
  64. topologyInfo, _, err := collectTopologyInfo(commandEnv, 15*time.Second)
  65. if err != nil {
  66. return err
  67. }
  68. // find all volumes that needs replication
  69. // collect all data nodes
  70. volumeReplicas, allLocations := collectVolumeReplicaLocations(topologyInfo)
  71. if len(allLocations) == 0 {
  72. return fmt.Errorf("no data nodes at all")
  73. }
  74. // find all under replicated volumes
  75. var underReplicatedVolumeIds, overReplicatedVolumeIds, misplacedVolumeIds []uint32
  76. for vid, replicas := range volumeReplicas {
  77. replica := replicas[0]
  78. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  79. switch {
  80. case replicaPlacement.GetCopyCount() > len(replicas) || !satisfyReplicaCurrentLocation(replicaPlacement, replicas):
  81. underReplicatedVolumeIds = append(underReplicatedVolumeIds, vid)
  82. case isMisplaced(replicas, replicaPlacement):
  83. misplacedVolumeIds = append(misplacedVolumeIds, vid)
  84. fmt.Fprintf(writer, "volume %d replication %s is not well placed %s\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id)
  85. case replicaPlacement.GetCopyCount() < len(replicas):
  86. overReplicatedVolumeIds = append(overReplicatedVolumeIds, vid)
  87. fmt.Fprintf(writer, "volume %d replication %s, but over replicated %+d\n", replica.info.Id, replicaPlacement, len(replicas))
  88. }
  89. }
  90. if !commandEnv.isLocked() {
  91. return fmt.Errorf("lock is lost")
  92. }
  93. if len(overReplicatedVolumeIds) > 0 && *doDelete {
  94. if err := c.deleteOneVolume(commandEnv, writer, takeAction, *doCheck, overReplicatedVolumeIds, volumeReplicas, allLocations, pickOneReplicaToDelete); err != nil {
  95. return err
  96. }
  97. }
  98. if len(misplacedVolumeIds) > 0 && *doDelete {
  99. if err := c.deleteOneVolume(commandEnv, writer, takeAction, *doCheck, misplacedVolumeIds, volumeReplicas, allLocations, pickOneMisplacedVolume); err != nil {
  100. return err
  101. }
  102. }
  103. underReplicatedVolumeIdsCount = len(underReplicatedVolumeIds)
  104. if underReplicatedVolumeIdsCount > 0 {
  105. // find the most under populated data nodes
  106. fixedVolumeReplicas, err = c.fixUnderReplicatedVolumes(commandEnv, writer, takeAction, underReplicatedVolumeIds, volumeReplicas, allLocations, *retryCount, *volumesPerStep)
  107. if err != nil {
  108. return err
  109. }
  110. }
  111. if *skipChange {
  112. break
  113. }
  114. // check that the topology has been updated
  115. if len(fixedVolumeReplicas) > 0 {
  116. fixedVolumes := make([]string, 0, len(fixedVolumeReplicas))
  117. for k, _ := range fixedVolumeReplicas {
  118. fixedVolumes = append(fixedVolumes, k)
  119. }
  120. volumeIdLocations, err := lookupVolumeIds(commandEnv, fixedVolumes)
  121. if err != nil {
  122. return err
  123. }
  124. for _, volumeIdLocation := range volumeIdLocations {
  125. volumeId := volumeIdLocation.VolumeOrFileId
  126. volumeIdLocationCount := len(volumeIdLocation.Locations)
  127. i := 0
  128. for fixedVolumeReplicas[volumeId] >= volumeIdLocationCount {
  129. fmt.Fprintf(writer, "the number of locations for volume %s has not increased yet, let's wait\n", volumeId)
  130. time.Sleep(time.Duration(i+1) * time.Second * 7)
  131. volumeLocIds, err := lookupVolumeIds(commandEnv, []string{volumeId})
  132. if err != nil {
  133. return err
  134. }
  135. volumeIdLocationCount = len(volumeLocIds[0].Locations)
  136. if *retryCount <= i {
  137. return fmt.Errorf("replicas volume %s mismatch in topology", volumeId)
  138. }
  139. i += 1
  140. }
  141. }
  142. }
  143. }
  144. return nil
  145. }
  146. func collectVolumeReplicaLocations(topologyInfo *master_pb.TopologyInfo) (map[uint32][]*VolumeReplica, []location) {
  147. volumeReplicas := make(map[uint32][]*VolumeReplica)
  148. var allLocations []location
  149. eachDataNode(topologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
  150. loc := newLocation(dc, string(rack), dn)
  151. for _, diskInfo := range dn.DiskInfos {
  152. for _, v := range diskInfo.VolumeInfos {
  153. volumeReplicas[v.Id] = append(volumeReplicas[v.Id], &VolumeReplica{
  154. location: &loc,
  155. info: v,
  156. })
  157. }
  158. }
  159. allLocations = append(allLocations, loc)
  160. })
  161. return volumeReplicas, allLocations
  162. }
  163. type SelectOneVolumeFunc func(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica
  164. func checkOneVolume(a *VolumeReplica, b *VolumeReplica, writer io.Writer, grpcDialOption grpc.DialOption) (err error) {
  165. aDB, bDB := needle_map.NewMemDb(), needle_map.NewMemDb()
  166. defer func() {
  167. aDB.Close()
  168. bDB.Close()
  169. }()
  170. // read index db
  171. readIndexDbCutoffFrom := uint64(time.Now().UnixNano())
  172. if err = readIndexDatabase(aDB, a.info.Collection, a.info.Id, pb.NewServerAddressFromDataNode(a.location.dataNode), false, writer, grpcDialOption); err != nil {
  173. return fmt.Errorf("readIndexDatabase %s volume %d: %v", a.location.dataNode, a.info.Id, err)
  174. }
  175. if err := readIndexDatabase(bDB, b.info.Collection, b.info.Id, pb.NewServerAddressFromDataNode(b.location.dataNode), false, writer, grpcDialOption); err != nil {
  176. return fmt.Errorf("readIndexDatabase %s volume %d: %v", b.location.dataNode, b.info.Id, err)
  177. }
  178. if _, err = doVolumeCheckDisk(aDB, bDB, a, b, false, writer, true, false, float64(1), readIndexDbCutoffFrom, grpcDialOption); err != nil {
  179. return fmt.Errorf("doVolumeCheckDisk source:%s target:%s volume %d: %v", a.location.dataNode.Id, b.location.dataNode.Id, a.info.Id, err)
  180. }
  181. return
  182. }
  183. func (c *commandVolumeFixReplication) deleteOneVolume(commandEnv *CommandEnv, writer io.Writer, takeAction bool, doCheck bool, overReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, selectOneVolumeFn SelectOneVolumeFunc) error {
  184. for _, vid := range overReplicatedVolumeIds {
  185. replicas := volumeReplicas[vid]
  186. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replicas[0].info.ReplicaPlacement))
  187. replica := selectOneVolumeFn(replicas, replicaPlacement)
  188. // check collection name pattern
  189. if *c.collectionPattern != "" {
  190. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  191. if err != nil {
  192. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  193. }
  194. if !matched {
  195. break
  196. }
  197. }
  198. collectionIsMismatch := false
  199. for _, volumeReplica := range replicas {
  200. if volumeReplica.info.Collection != replica.info.Collection {
  201. fmt.Fprintf(writer, "skip delete volume %d as collection %s is mismatch: %s\n", replica.info.Id, replica.info.Collection, volumeReplica.info.Collection)
  202. collectionIsMismatch = true
  203. }
  204. }
  205. if collectionIsMismatch {
  206. continue
  207. }
  208. fmt.Fprintf(writer, "deleting volume %d from %s ...\n", replica.info.Id, replica.location.dataNode.Id)
  209. if !takeAction {
  210. break
  211. }
  212. if doCheck {
  213. for _, replicaB := range replicas {
  214. if replicaB.location.dataNode == replica.location.dataNode {
  215. continue
  216. }
  217. if err := checkOneVolume(replica, replicaB, writer, commandEnv.option.GrpcDialOption); err != nil {
  218. return fmt.Errorf("sync volume %d on %s and %s: %v\n", replica.info.Id, replica.location.dataNode.Id, replicaB.location.dataNode.Id, err)
  219. }
  220. }
  221. }
  222. if err := deleteVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(replica.info.Id),
  223. pb.NewServerAddressFromDataNode(replica.location.dataNode), false); err != nil {
  224. return fmt.Errorf("deleting volume %d from %s : %v", replica.info.Id, replica.location.dataNode.Id, err)
  225. }
  226. }
  227. return nil
  228. }
  229. 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) {
  230. fixedVolumes = map[string]int{}
  231. if len(underReplicatedVolumeIds) > volumesPerStep && volumesPerStep > 0 {
  232. underReplicatedVolumeIds = underReplicatedVolumeIds[0:volumesPerStep]
  233. }
  234. for _, vid := range underReplicatedVolumeIds {
  235. for i := 0; i < retryCount+1; i++ {
  236. if err = c.fixOneUnderReplicatedVolume(commandEnv, writer, takeAction, volumeReplicas, vid, allLocations); err == nil {
  237. if takeAction {
  238. fixedVolumes[strconv.FormatUint(uint64(vid), 10)] = len(volumeReplicas[vid])
  239. }
  240. break
  241. } else {
  242. fmt.Fprintf(writer, "fixing under replicated volume %d: %v\n", vid, err)
  243. }
  244. }
  245. }
  246. return fixedVolumes, nil
  247. }
  248. func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *CommandEnv, writer io.Writer, takeAction bool, volumeReplicas map[uint32][]*VolumeReplica, vid uint32, allLocations []location) error {
  249. replicas := volumeReplicas[vid]
  250. replica := pickOneReplicaToCopyFrom(replicas)
  251. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
  252. foundNewLocation := false
  253. hasSkippedCollection := false
  254. keepDataNodesSorted(allLocations, types.ToDiskType(replica.info.DiskType))
  255. fn := capacityByFreeVolumeCount(types.ToDiskType(replica.info.DiskType))
  256. for _, dst := range allLocations {
  257. // check whether data nodes satisfy the constraints
  258. if fn(dst.dataNode) > 0 && satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
  259. // check collection name pattern
  260. if *c.collectionPattern != "" {
  261. matched, err := filepath.Match(*c.collectionPattern, replica.info.Collection)
  262. if err != nil {
  263. return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
  264. }
  265. if !matched {
  266. hasSkippedCollection = true
  267. break
  268. }
  269. }
  270. // ask the volume server to replicate the volume
  271. foundNewLocation = true
  272. fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
  273. if !takeAction {
  274. // adjust volume count
  275. addVolumeCount(dst.dataNode.DiskInfos[replica.info.DiskType], 1)
  276. break
  277. }
  278. err := operation.WithVolumeServerClient(false, pb.NewServerAddressFromDataNode(dst.dataNode), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  279. stream, replicateErr := volumeServerClient.VolumeCopy(context.Background(), &volume_server_pb.VolumeCopyRequest{
  280. VolumeId: replica.info.Id,
  281. SourceDataNode: string(pb.NewServerAddressFromDataNode(replica.location.dataNode)),
  282. })
  283. if replicateErr != nil {
  284. return fmt.Errorf("copying from %s => %s : %v", replica.location.dataNode.Id, dst.dataNode.Id, replicateErr)
  285. }
  286. for {
  287. resp, recvErr := stream.Recv()
  288. if recvErr != nil {
  289. if recvErr == io.EOF {
  290. break
  291. } else {
  292. return recvErr
  293. }
  294. }
  295. if resp.ProcessedBytes > 0 {
  296. fmt.Fprintf(writer, "volume %d processed %d bytes\n", replica.info.Id, resp.ProcessedBytes)
  297. }
  298. }
  299. return nil
  300. })
  301. if err != nil {
  302. return err
  303. }
  304. // adjust volume count
  305. addVolumeCount(dst.dataNode.DiskInfos[replica.info.DiskType], 1)
  306. break
  307. }
  308. }
  309. if !foundNewLocation && !hasSkippedCollection {
  310. fmt.Fprintf(writer, "failed to place volume %d replica as %s, existing:%+v\n", replica.info.Id, replicaPlacement, len(replicas))
  311. }
  312. return nil
  313. }
  314. func addVolumeCount(info *master_pb.DiskInfo, count int) {
  315. if info == nil {
  316. return
  317. }
  318. info.VolumeCount += int64(count)
  319. info.FreeVolumeCount -= int64(count)
  320. }
  321. func keepDataNodesSorted(dataNodes []location, diskType types.DiskType) {
  322. fn := capacityByFreeVolumeCount(diskType)
  323. slices.SortFunc(dataNodes, func(a, b location) int {
  324. return int(fn(b.dataNode) - fn(a.dataNode))
  325. })
  326. }
  327. func satisfyReplicaCurrentLocation(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica) bool {
  328. existingDataCenters, existingRacks, _ := countReplicas(replicas)
  329. if replicaPlacement.DiffDataCenterCount+1 > len(existingDataCenters) {
  330. return false
  331. }
  332. if replicaPlacement.DiffRackCount+1 > len(existingRacks) {
  333. return false
  334. }
  335. if replicaPlacement.SameRackCount > 0 {
  336. foundSatisfyRack := false
  337. for _, rackCount := range existingRacks {
  338. if rackCount >= replicaPlacement.SameRackCount+1 {
  339. foundSatisfyRack = true
  340. }
  341. }
  342. return foundSatisfyRack
  343. }
  344. return true
  345. }
  346. /*
  347. if on an existing data node {
  348. return false
  349. }
  350. if different from existing dcs {
  351. if lack on different dcs {
  352. return true
  353. }else{
  354. return false
  355. }
  356. }
  357. if not on primary dc {
  358. return false
  359. }
  360. if different from existing racks {
  361. if lack on different racks {
  362. return true
  363. }else{
  364. return false
  365. }
  366. }
  367. if not on primary rack {
  368. return false
  369. }
  370. if lacks on same rack {
  371. return true
  372. } else {
  373. return false
  374. }
  375. */
  376. func satisfyReplicaPlacement(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica, possibleLocation location) bool {
  377. existingDataCenters, _, existingDataNodes := countReplicas(replicas)
  378. if _, found := existingDataNodes[possibleLocation.String()]; found {
  379. // avoid duplicated volume on the same data node
  380. return false
  381. }
  382. primaryDataCenters, _ := findTopKeys(existingDataCenters)
  383. // ensure data center count is within limit
  384. if _, found := existingDataCenters[possibleLocation.DataCenter()]; !found {
  385. // different from existing dcs
  386. if len(existingDataCenters) < replicaPlacement.DiffDataCenterCount+1 {
  387. // lack on different dcs
  388. return true
  389. } else {
  390. // adding this would go over the different dcs limit
  391. return false
  392. }
  393. }
  394. // now this is same as one of the existing data center
  395. if !isAmong(possibleLocation.DataCenter(), primaryDataCenters) {
  396. // not on one of the primary dcs
  397. return false
  398. }
  399. // now this is one of the primary dcs
  400. primaryDcRacks := make(map[string]int)
  401. for _, replica := range replicas {
  402. if replica.location.DataCenter() != possibleLocation.DataCenter() {
  403. continue
  404. }
  405. primaryDcRacks[replica.location.Rack()] += 1
  406. }
  407. primaryRacks, _ := findTopKeys(primaryDcRacks)
  408. sameRackCount := primaryDcRacks[possibleLocation.Rack()]
  409. // ensure rack count is within limit
  410. if _, found := primaryDcRacks[possibleLocation.Rack()]; !found {
  411. // different from existing racks
  412. if len(primaryDcRacks) < replicaPlacement.DiffRackCount+1 {
  413. // lack on different racks
  414. return true
  415. } else {
  416. // adding this would go over the different racks limit
  417. return false
  418. }
  419. }
  420. // now this is same as one of the existing racks
  421. if !isAmong(possibleLocation.Rack(), primaryRacks) {
  422. // not on the primary rack
  423. return false
  424. }
  425. // now this is on the primary rack
  426. // different from existing data nodes
  427. if sameRackCount < replicaPlacement.SameRackCount+1 {
  428. // lack on same rack
  429. return true
  430. } else {
  431. // adding this would go over the same data node limit
  432. return false
  433. }
  434. }
  435. func findTopKeys(m map[string]int) (topKeys []string, max int) {
  436. for k, c := range m {
  437. if max < c {
  438. topKeys = topKeys[:0]
  439. topKeys = append(topKeys, k)
  440. max = c
  441. } else if max == c {
  442. topKeys = append(topKeys, k)
  443. }
  444. }
  445. return
  446. }
  447. func isAmong(key string, keys []string) bool {
  448. for _, k := range keys {
  449. if k == key {
  450. return true
  451. }
  452. }
  453. return false
  454. }
  455. type VolumeReplica struct {
  456. location *location
  457. info *master_pb.VolumeInformationMessage
  458. }
  459. type location struct {
  460. dc string
  461. rack string
  462. dataNode *master_pb.DataNodeInfo
  463. }
  464. func newLocation(dc, rack string, dataNode *master_pb.DataNodeInfo) location {
  465. return location{
  466. dc: dc,
  467. rack: rack,
  468. dataNode: dataNode,
  469. }
  470. }
  471. func (l location) String() string {
  472. return fmt.Sprintf("%s %s %s", l.dc, l.rack, l.dataNode.Id)
  473. }
  474. func (l location) Rack() string {
  475. return fmt.Sprintf("%s %s", l.dc, l.rack)
  476. }
  477. func (l location) DataCenter() string {
  478. return l.dc
  479. }
  480. func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
  481. mostRecent := replicas[0]
  482. for _, replica := range replicas {
  483. if replica.info.ModifiedAtSecond > mostRecent.info.ModifiedAtSecond {
  484. mostRecent = replica
  485. }
  486. }
  487. return mostRecent
  488. }
  489. func countReplicas(replicas []*VolumeReplica) (diffDc, diffRack, diffNode map[string]int) {
  490. diffDc = make(map[string]int)
  491. diffRack = make(map[string]int)
  492. diffNode = make(map[string]int)
  493. for _, replica := range replicas {
  494. diffDc[replica.location.DataCenter()] += 1
  495. diffRack[replica.location.Rack()] += 1
  496. diffNode[replica.location.String()] += 1
  497. }
  498. return
  499. }
  500. func pickOneReplicaToDelete(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
  501. slices.SortFunc(replicas, func(a, b *VolumeReplica) int {
  502. if a.info.Size != b.info.Size {
  503. return int(a.info.Size - b.info.Size)
  504. }
  505. if a.info.ModifiedAtSecond != b.info.ModifiedAtSecond {
  506. return int(a.info.ModifiedAtSecond - b.info.ModifiedAtSecond)
  507. }
  508. if a.info.CompactRevision != b.info.CompactRevision {
  509. return int(a.info.CompactRevision - b.info.CompactRevision)
  510. }
  511. return 0
  512. })
  513. return replicas[0]
  514. }
  515. // check and fix misplaced volumes
  516. func isMisplaced(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) bool {
  517. for i := 0; i < len(replicas); i++ {
  518. others := otherThan(replicas, i)
  519. if !satisfyReplicaPlacement(replicaPlacement, others, *replicas[i].location) {
  520. return true
  521. }
  522. }
  523. return false
  524. }
  525. func otherThan(replicas []*VolumeReplica, index int) (others []*VolumeReplica) {
  526. for i := 0; i < len(replicas); i++ {
  527. if index != i {
  528. others = append(others, replicas[i])
  529. }
  530. }
  531. return
  532. }
  533. func pickOneMisplacedVolume(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) (toDelete *VolumeReplica) {
  534. var deletionCandidates []*VolumeReplica
  535. for i := 0; i < len(replicas); i++ {
  536. others := otherThan(replicas, i)
  537. if !isMisplaced(others, replicaPlacement) {
  538. deletionCandidates = append(deletionCandidates, replicas[i])
  539. }
  540. }
  541. if len(deletionCandidates) > 0 {
  542. return pickOneReplicaToDelete(deletionCandidates, replicaPlacement)
  543. }
  544. return pickOneReplicaToDelete(replicas, replicaPlacement)
  545. }