command_volume_fix_replication.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/seaweedfs/seaweedfs/weed/pb"
  7. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  8. "github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
  9. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  10. "golang.org/x/exp/slices"
  11. "google.golang.org/grpc"
  12. "io"
  13. "path/filepath"
  14. "strconv"
  15. "time"
  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):
  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 free volume count
  275. dst.dataNode.DiskInfos[replica.info.DiskType].FreeVolumeCount--
  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 free volume count
  305. dst.dataNode.DiskInfos[replica.info.DiskType].FreeVolumeCount--
  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 keepDataNodesSorted(dataNodes []location, diskType types.DiskType) {
  315. fn := capacityByFreeVolumeCount(diskType)
  316. slices.SortFunc(dataNodes, func(a, b location) int {
  317. return int(fn(b.dataNode) - fn(a.dataNode))
  318. })
  319. }
  320. /*
  321. if on an existing data node {
  322. return false
  323. }
  324. if different from existing dcs {
  325. if lack on different dcs {
  326. return true
  327. }else{
  328. return false
  329. }
  330. }
  331. if not on primary dc {
  332. return false
  333. }
  334. if different from existing racks {
  335. if lack on different racks {
  336. return true
  337. }else{
  338. return false
  339. }
  340. }
  341. if not on primary rack {
  342. return false
  343. }
  344. if lacks on same rack {
  345. return true
  346. } else {
  347. return false
  348. }
  349. */
  350. func satisfyReplicaPlacement(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica, possibleLocation location) bool {
  351. existingDataCenters, _, existingDataNodes := countReplicas(replicas)
  352. if _, found := existingDataNodes[possibleLocation.String()]; found {
  353. // avoid duplicated volume on the same data node
  354. return false
  355. }
  356. primaryDataCenters, _ := findTopKeys(existingDataCenters)
  357. // ensure data center count is within limit
  358. if _, found := existingDataCenters[possibleLocation.DataCenter()]; !found {
  359. // different from existing dcs
  360. if len(existingDataCenters) < replicaPlacement.DiffDataCenterCount+1 {
  361. // lack on different dcs
  362. return true
  363. } else {
  364. // adding this would go over the different dcs limit
  365. return false
  366. }
  367. }
  368. // now this is same as one of the existing data center
  369. if !isAmong(possibleLocation.DataCenter(), primaryDataCenters) {
  370. // not on one of the primary dcs
  371. return false
  372. }
  373. // now this is one of the primary dcs
  374. primaryDcRacks := make(map[string]int)
  375. for _, replica := range replicas {
  376. if replica.location.DataCenter() != possibleLocation.DataCenter() {
  377. continue
  378. }
  379. primaryDcRacks[replica.location.Rack()] += 1
  380. }
  381. primaryRacks, _ := findTopKeys(primaryDcRacks)
  382. sameRackCount := primaryDcRacks[possibleLocation.Rack()]
  383. // ensure rack count is within limit
  384. if _, found := primaryDcRacks[possibleLocation.Rack()]; !found {
  385. // different from existing racks
  386. if len(primaryDcRacks) < replicaPlacement.DiffRackCount+1 {
  387. // lack on different racks
  388. return true
  389. } else {
  390. // adding this would go over the different racks limit
  391. return false
  392. }
  393. }
  394. // now this is same as one of the existing racks
  395. if !isAmong(possibleLocation.Rack(), primaryRacks) {
  396. // not on the primary rack
  397. return false
  398. }
  399. // now this is on the primary rack
  400. // different from existing data nodes
  401. if sameRackCount < replicaPlacement.SameRackCount+1 {
  402. // lack on same rack
  403. return true
  404. } else {
  405. // adding this would go over the same data node limit
  406. return false
  407. }
  408. }
  409. func findTopKeys(m map[string]int) (topKeys []string, max int) {
  410. for k, c := range m {
  411. if max < c {
  412. topKeys = topKeys[:0]
  413. topKeys = append(topKeys, k)
  414. max = c
  415. } else if max == c {
  416. topKeys = append(topKeys, k)
  417. }
  418. }
  419. return
  420. }
  421. func isAmong(key string, keys []string) bool {
  422. for _, k := range keys {
  423. if k == key {
  424. return true
  425. }
  426. }
  427. return false
  428. }
  429. type VolumeReplica struct {
  430. location *location
  431. info *master_pb.VolumeInformationMessage
  432. }
  433. type location struct {
  434. dc string
  435. rack string
  436. dataNode *master_pb.DataNodeInfo
  437. }
  438. func newLocation(dc, rack string, dataNode *master_pb.DataNodeInfo) location {
  439. return location{
  440. dc: dc,
  441. rack: rack,
  442. dataNode: dataNode,
  443. }
  444. }
  445. func (l location) String() string {
  446. return fmt.Sprintf("%s %s %s", l.dc, l.rack, l.dataNode.Id)
  447. }
  448. func (l location) Rack() string {
  449. return fmt.Sprintf("%s %s", l.dc, l.rack)
  450. }
  451. func (l location) DataCenter() string {
  452. return l.dc
  453. }
  454. func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
  455. mostRecent := replicas[0]
  456. for _, replica := range replicas {
  457. if replica.info.ModifiedAtSecond > mostRecent.info.ModifiedAtSecond {
  458. mostRecent = replica
  459. }
  460. }
  461. return mostRecent
  462. }
  463. func countReplicas(replicas []*VolumeReplica) (diffDc, diffRack, diffNode map[string]int) {
  464. diffDc = make(map[string]int)
  465. diffRack = make(map[string]int)
  466. diffNode = make(map[string]int)
  467. for _, replica := range replicas {
  468. diffDc[replica.location.DataCenter()] += 1
  469. diffRack[replica.location.Rack()] += 1
  470. diffNode[replica.location.String()] += 1
  471. }
  472. return
  473. }
  474. func pickOneReplicaToDelete(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
  475. slices.SortFunc(replicas, func(a, b *VolumeReplica) int {
  476. if a.info.Size != b.info.Size {
  477. return int(a.info.Size - b.info.Size)
  478. }
  479. if a.info.ModifiedAtSecond != b.info.ModifiedAtSecond {
  480. return int(a.info.ModifiedAtSecond - b.info.ModifiedAtSecond)
  481. }
  482. if a.info.CompactRevision != b.info.CompactRevision {
  483. return int(a.info.CompactRevision - b.info.CompactRevision)
  484. }
  485. return 0
  486. })
  487. return replicas[0]
  488. }
  489. // check and fix misplaced volumes
  490. func isMisplaced(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) bool {
  491. for i := 0; i < len(replicas); i++ {
  492. others := otherThan(replicas, i)
  493. if !satisfyReplicaPlacement(replicaPlacement, others, *replicas[i].location) {
  494. return true
  495. }
  496. }
  497. return false
  498. }
  499. func otherThan(replicas []*VolumeReplica, index int) (others []*VolumeReplica) {
  500. for i := 0; i < len(replicas); i++ {
  501. if index != i {
  502. others = append(others, replicas[i])
  503. }
  504. }
  505. return
  506. }
  507. func pickOneMisplacedVolume(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) (toDelete *VolumeReplica) {
  508. var deletionCandidates []*VolumeReplica
  509. for i := 0; i < len(replicas); i++ {
  510. others := otherThan(replicas, i)
  511. if !isMisplaced(others, replicaPlacement) {
  512. deletionCandidates = append(deletionCandidates, replicas[i])
  513. }
  514. }
  515. if len(deletionCandidates) > 0 {
  516. return pickOneReplicaToDelete(deletionCandidates, replicaPlacement)
  517. }
  518. return pickOneReplicaToDelete(replicas, replicaPlacement)
  519. }