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.

649 lines
21 KiB

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