command_volume_fix_replication.go 20 KB

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