1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
24 "git.curoverse.com/arvados.git/sdk/go/keepclient"
25 "github.com/sirupsen/logrus"
28 // Balancer compares the contents of keepstore servers with the
29 // collections stored in Arvados, and issues pull/trash requests
30 // needed to get (closer to) the optimal data layout.
32 // In the optimal data layout: every data block referenced by a
33 // collection is replicated at least as many times as desired by the
34 // collection; there are no unreferenced data blocks older than
35 // BlobSignatureTTL; and all N existing replicas of a given data block
36 // are in the N best positions in rendezvous probe order.
37 type Balancer struct {
38 Logger logrus.FieldLogger
39 Dumper logrus.FieldLogger
45 KeepServices map[string]*KeepService
46 DefaultReplication int
51 mountsByClass map[string]map[*KeepMount]bool
53 serviceRoots map[string]string
60 // Run performs a balance operation using the given config and
61 // runOptions, and returns RunOptions suitable for passing to a
62 // subsequent balance operation.
64 // Run should only be called once on a given Balancer object.
68 // runOptions, err = (&Balancer{}).Run(config, runOptions)
69 func (bal *Balancer) Run(config Config, runOptions RunOptions) (nextRunOptions RunOptions, err error) {
70 nextRunOptions = runOptions
72 defer bal.time("sweep", "wall clock time to run one full sweep")()
75 if bal.LostBlocksFile != "" {
76 tmpfn := bal.LostBlocksFile + ".tmp"
77 lbFile, err = os.OpenFile(tmpfn, os.O_CREATE|os.O_WRONLY, 0777)
82 err = syscall.Flock(int(lbFile.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
87 // Remove the tempfile only if we didn't get
88 // as far as successfully renaming it.
93 bal.lostBlocks = lbFile
95 bal.lostBlocks = ioutil.Discard
98 if len(config.KeepServiceList.Items) > 0 {
99 err = bal.SetKeepServices(config.KeepServiceList)
101 err = bal.DiscoverKeepServices(&config.Client, config.KeepServiceTypes)
107 for _, srv := range bal.KeepServices {
108 err = srv.discoverMounts(&config.Client)
115 if err = bal.CheckSanityEarly(&config.Client); err != nil {
118 rs := bal.rendezvousState()
119 if runOptions.CommitTrash && rs != runOptions.SafeRendezvousState {
120 if runOptions.SafeRendezvousState != "" {
121 bal.logf("notice: KeepServices list has changed since last run")
123 bal.logf("clearing existing trash lists, in case the new rendezvous order differs from previous run")
124 if err = bal.ClearTrashLists(&config.Client); err != nil {
127 // The current rendezvous state becomes "safe" (i.e.,
128 // OK to compute changes for that state without
129 // clearing existing trash lists) only now, after we
130 // succeed in clearing existing trash lists.
131 nextRunOptions.SafeRendezvousState = rs
133 if err = bal.GetCurrentState(&config.Client, config.CollectionBatchSize, config.CollectionBuffers); err != nil {
136 bal.ComputeChangeSets()
137 bal.PrintStatistics()
138 if err = bal.CheckSanityLate(); err != nil {
146 err = os.Rename(bal.LostBlocksFile+".tmp", bal.LostBlocksFile)
152 if runOptions.CommitPulls {
153 err = bal.CommitPulls(&config.Client)
155 // Skip trash if we can't pull. (Too cautious?)
159 if runOptions.CommitTrash {
160 err = bal.CommitTrash(&config.Client)
165 // SetKeepServices sets the list of KeepServices to operate on.
166 func (bal *Balancer) SetKeepServices(srvList arvados.KeepServiceList) error {
167 bal.KeepServices = make(map[string]*KeepService)
168 for _, srv := range srvList.Items {
169 bal.KeepServices[srv.UUID] = &KeepService{
171 ChangeSet: &ChangeSet{},
177 // DiscoverKeepServices sets the list of KeepServices by calling the
178 // API to get a list of all services, and selecting the ones whose
179 // ServiceType is in okTypes.
180 func (bal *Balancer) DiscoverKeepServices(c *arvados.Client, okTypes []string) error {
181 bal.KeepServices = make(map[string]*KeepService)
182 ok := make(map[string]bool)
183 for _, t := range okTypes {
186 return c.EachKeepService(func(srv arvados.KeepService) error {
187 if ok[srv.ServiceType] {
188 bal.KeepServices[srv.UUID] = &KeepService{
190 ChangeSet: &ChangeSet{},
193 bal.logf("skipping %v with service type %q", srv.UUID, srv.ServiceType)
199 func (bal *Balancer) cleanupMounts() {
200 rwdev := map[string]*KeepService{}
201 for _, srv := range bal.KeepServices {
202 for _, mnt := range srv.mounts {
203 if !mnt.ReadOnly && mnt.DeviceID != "" {
204 rwdev[mnt.DeviceID] = srv
208 // Drop the readonly mounts whose device is mounted RW
210 for _, srv := range bal.KeepServices {
211 var dedup []*KeepMount
212 for _, mnt := range srv.mounts {
213 if mnt.ReadOnly && rwdev[mnt.DeviceID] != nil {
214 bal.logf("skipping srv %s readonly mount %q because same device %q is mounted read-write on srv %s", srv, mnt.UUID, mnt.DeviceID, rwdev[mnt.DeviceID])
216 dedup = append(dedup, mnt)
221 for _, srv := range bal.KeepServices {
222 for _, mnt := range srv.mounts {
223 if mnt.Replication <= 0 {
224 log.Printf("%s: mount %s reports replication=%d, using replication=1", srv, mnt.UUID, mnt.Replication)
231 // CheckSanityEarly checks for configuration and runtime errors that
232 // can be detected before GetCurrentState() and ComputeChangeSets()
235 // If it returns an error, it is pointless to run GetCurrentState or
236 // ComputeChangeSets: after doing so, the statistics would be
237 // meaningless and it would be dangerous to run any Commit methods.
238 func (bal *Balancer) CheckSanityEarly(c *arvados.Client) error {
239 u, err := c.CurrentUser()
241 return fmt.Errorf("CurrentUser(): %v", err)
243 if !u.IsActive || !u.IsAdmin {
244 return fmt.Errorf("current user (%s) is not an active admin user", u.UUID)
246 for _, srv := range bal.KeepServices {
247 if srv.ServiceType == "proxy" {
248 return fmt.Errorf("config error: %s: proxy servers cannot be balanced", srv)
252 var checkPage arvados.CollectionList
253 if err = c.RequestAndDecode(&checkPage, "GET", "arvados/v1/collections", nil, arvados.ResourceListParams{
257 IncludeOldVersions: true,
258 Filters: []arvados.Filter{{
265 } else if n := checkPage.ItemsAvailable; n > 0 {
266 return fmt.Errorf("%d collections exist with null modified_at; cannot fetch reliably", n)
272 // rendezvousState returns a fingerprint (e.g., a sorted list of
273 // UUID+host+port) of the current set of keep services.
274 func (bal *Balancer) rendezvousState() string {
275 srvs := make([]string, 0, len(bal.KeepServices))
276 for _, srv := range bal.KeepServices {
277 srvs = append(srvs, srv.String())
280 return strings.Join(srvs, "; ")
283 // ClearTrashLists sends an empty trash list to each keep
284 // service. Calling this before GetCurrentState avoids races.
286 // When a block appears in an index, we assume that replica will still
287 // exist after we delete other replicas on other servers. However,
288 // it's possible that a previous rebalancing operation made different
289 // decisions (e.g., servers were added/removed, and rendezvous order
290 // changed). In this case, the replica might already be on that
291 // server's trash list, and it might be deleted before we send a
292 // replacement trash list.
294 // We avoid this problem if we clear all trash lists before getting
295 // indexes. (We also assume there is only one rebalancing process
296 // running at a time.)
297 func (bal *Balancer) ClearTrashLists(c *arvados.Client) error {
298 for _, srv := range bal.KeepServices {
299 srv.ChangeSet = &ChangeSet{}
301 return bal.CommitTrash(c)
304 // GetCurrentState determines the current replication state, and the
305 // desired replication level, for every block that is either
306 // retrievable or referenced.
308 // It determines the current replication state by reading the block index
309 // from every known Keep service.
311 // It determines the desired replication level by retrieving all
312 // collection manifests in the database (API server).
314 // It encodes the resulting information in BlockStateMap.
315 func (bal *Balancer) GetCurrentState(c *arvados.Client, pageSize, bufs int) error {
316 defer bal.time("get_state", "wall clock time to get current state")()
317 bal.BlockStateMap = NewBlockStateMap()
319 dd, err := c.DiscoveryDocument()
323 bal.DefaultReplication = dd.DefaultCollectionReplication
324 bal.MinMtime = time.Now().UnixNano() - dd.BlobSignatureTTL*1e9
326 errs := make(chan error, 1)
327 wg := sync.WaitGroup{}
329 // When a device is mounted more than once, we will get its
330 // index only once, and call AddReplicas on all of the mounts.
331 // equivMount keys are the mounts that will be indexed, and
332 // each value is a list of mounts to apply the received index
334 equivMount := map[*KeepMount][]*KeepMount{}
335 // deviceMount maps each device ID to the one mount that will
336 // be indexed for that device.
337 deviceMount := map[string]*KeepMount{}
338 for _, srv := range bal.KeepServices {
339 for _, mnt := range srv.mounts {
340 equiv := deviceMount[mnt.DeviceID]
343 if mnt.DeviceID != "" {
344 deviceMount[mnt.DeviceID] = equiv
347 equivMount[equiv] = append(equivMount[equiv], mnt)
351 // Start one goroutine for each (non-redundant) mount:
352 // retrieve the index, and add the returned blocks to
354 for _, mounts := range equivMount {
356 go func(mounts []*KeepMount) {
358 bal.logf("mount %s: retrieve index from %s", mounts[0], mounts[0].KeepService)
359 idx, err := mounts[0].KeepService.IndexMount(c, mounts[0].UUID, "")
362 case errs <- fmt.Errorf("%s: retrieve index: %v", mounts[0], err):
368 // Some other goroutine encountered an
369 // error -- any further effort here
373 for _, mount := range mounts {
374 bal.logf("%s: add %d entries to map", mount, len(idx))
375 bal.BlockStateMap.AddReplicas(mount, idx)
376 bal.logf("%s: added %d entries to map at %dx (%d replicas)", mount, len(idx), mount.Replication, len(idx)*mount.Replication)
378 bal.logf("mount %s: index done", mounts[0])
382 // collQ buffers incoming collections so we can start fetching
383 // the next page without waiting for the current page to
384 // finish processing.
385 collQ := make(chan arvados.Collection, bufs)
387 // Start a goroutine to process collections. (We could use a
388 // worker pool here, but even with a single worker we already
389 // process collections much faster than we can retrieve them.)
393 for coll := range collQ {
394 err := bal.addCollection(coll)
395 if err != nil || len(errs) > 0 {
408 // Start a goroutine to retrieve all collections from the
409 // Arvados database and send them to collQ for processing.
413 err = EachCollection(c, pageSize,
414 func(coll arvados.Collection) error {
417 // some other GetCurrentState
418 // error happened: no point
421 return fmt.Errorf("")
424 }, func(done, total int) {
425 bal.logf("collections: %d/%d", done, total)
443 func (bal *Balancer) addCollection(coll arvados.Collection) error {
444 blkids, err := coll.SizedDigests()
446 return fmt.Errorf("%v: %v", coll.UUID, err)
448 repl := bal.DefaultReplication
449 if coll.ReplicationDesired != nil {
450 repl = *coll.ReplicationDesired
452 debugf("%v: %d block x%d", coll.UUID, len(blkids), repl)
453 bal.BlockStateMap.IncreaseDesired(coll.StorageClassesDesired, repl, blkids)
457 // ComputeChangeSets compares, for each known block, the current and
458 // desired replication states. If it is possible to get closer to the
459 // desired state by copying or deleting blocks, it adds those changes
460 // to the relevant KeepServices' ChangeSets.
462 // It does not actually apply any of the computed changes.
463 func (bal *Balancer) ComputeChangeSets() {
464 // This just calls balanceBlock() once for each block, using a
465 // pool of worker goroutines.
466 defer bal.time("changeset_compute", "wall clock time to compute changesets")()
467 bal.setupLookupTables()
469 type balanceTask struct {
470 blkid arvados.SizedDigest
473 workers := runtime.GOMAXPROCS(-1)
474 todo := make(chan balanceTask, workers)
476 bal.BlockStateMap.Apply(func(blkid arvados.SizedDigest, blk *BlockState) {
484 results := make(chan balanceResult, workers)
486 var wg sync.WaitGroup
487 for i := 0; i < workers; i++ {
490 for work := range todo {
491 results <- bal.balanceBlock(work.blkid, work.blk)
499 bal.collectStatistics(results)
502 func (bal *Balancer) setupLookupTables() {
503 bal.serviceRoots = make(map[string]string)
504 bal.classes = defaultClasses
505 bal.mountsByClass = map[string]map[*KeepMount]bool{"default": {}}
507 for _, srv := range bal.KeepServices {
508 bal.serviceRoots[srv.UUID] = srv.UUID
509 for _, mnt := range srv.mounts {
512 // All mounts on a read-only service are
513 // effectively read-only.
514 mnt.ReadOnly = mnt.ReadOnly || srv.ReadOnly
516 if len(mnt.StorageClasses) == 0 {
517 bal.mountsByClass["default"][mnt] = true
520 for _, class := range mnt.StorageClasses {
521 if mbc := bal.mountsByClass[class]; mbc == nil {
522 bal.classes = append(bal.classes, class)
523 bal.mountsByClass[class] = map[*KeepMount]bool{mnt: true}
530 // Consider classes in lexicographic order to avoid flapping
531 // between balancing runs. The outcome of the "prefer a mount
532 // we're already planning to use for a different storage
533 // class" case in balanceBlock depends on the order classes
535 sort.Strings(bal.classes)
545 var changeName = map[int]string{
548 changeTrash: "trash",
552 type balanceResult struct {
554 blkid arvados.SizedDigest
557 classState map[string]balancedBlockState
560 // balanceBlock compares current state to desired state for a single
561 // block, and makes the appropriate ChangeSet calls.
562 func (bal *Balancer) balanceBlock(blkid arvados.SizedDigest, blk *BlockState) balanceResult {
563 debugf("balanceBlock: %v %+v", blkid, blk)
566 mnt *KeepMount // never nil
567 repl *Replica // replica already stored here (or nil)
568 want bool // we should pull/leave a replica here
571 // Build a list of all slots (one per mounted volume).
572 slots := make([]slot, 0, bal.mounts)
573 for _, srv := range bal.KeepServices {
574 for _, mnt := range srv.mounts {
576 for r := range blk.Replicas {
577 if blk.Replicas[r].KeepMount == mnt {
578 repl = &blk.Replicas[r]
581 // Initial value of "want" is "have, and can't
582 // delete". These untrashable replicas get
583 // prioritized when sorting slots: otherwise,
584 // non-optimal readonly copies would cause us
586 slots = append(slots, slot{
589 want: repl != nil && mnt.ReadOnly,
594 uuids := keepclient.NewRootSorter(bal.serviceRoots, string(blkid[:32])).GetSortedRoots()
595 srvRendezvous := make(map[*KeepService]int, len(uuids))
596 for i, uuid := range uuids {
597 srv := bal.KeepServices[uuid]
598 srvRendezvous[srv] = i
601 // Below we set underreplicated=true if we find any storage
602 // class that's currently underreplicated -- in that case we
603 // won't want to trash any replicas.
604 underreplicated := false
606 classState := make(map[string]balancedBlockState, len(bal.classes))
607 unsafeToDelete := make(map[int64]bool, len(slots))
608 for _, class := range bal.classes {
609 desired := blk.Desired[class]
611 countedDev := map[string]bool{}
613 for _, slot := range slots {
614 if slot.repl != nil && bal.mountsByClass[class][slot.mnt] && !countedDev[slot.mnt.DeviceID] {
615 have += slot.mnt.Replication
616 if slot.mnt.DeviceID != "" {
617 countedDev[slot.mnt.DeviceID] = true
621 classState[class] = balancedBlockState{
623 surplus: have - desired,
630 // Sort the slots by desirability.
631 sort.Slice(slots, func(i, j int) bool {
632 si, sj := slots[i], slots[j]
633 if classi, classj := bal.mountsByClass[class][si.mnt], bal.mountsByClass[class][sj.mnt]; classi != classj {
634 // Prefer a mount that satisfies the
636 return bal.mountsByClass[class][si.mnt]
637 } else if si.want != sj.want {
638 // Prefer a mount that will have a
639 // replica no matter what we do here
640 // -- either because it already has an
641 // untrashable replica, or because we
642 // already need it to satisfy a
643 // different storage class.
645 } else if orderi, orderj := srvRendezvous[si.mnt.KeepService], srvRendezvous[sj.mnt.KeepService]; orderi != orderj {
646 // Prefer a better rendezvous
648 return orderi < orderj
649 } else if repli, replj := si.repl != nil, sj.repl != nil; repli != replj {
650 // Prefer a mount that already has a
654 // If pull/trash turns out to be
655 // needed, distribute the
656 // new/remaining replicas uniformly
657 // across qualifying mounts on a given
659 return rendezvousLess(si.mnt.DeviceID, sj.mnt.DeviceID, blkid)
663 // Servers/mounts/devices (with or without existing
664 // replicas) that are part of the best achievable
665 // layout for this storage class.
666 wantSrv := map[*KeepService]bool{}
667 wantMnt := map[*KeepMount]bool{}
668 wantDev := map[string]bool{}
669 // Positions (with existing replicas) that have been
670 // protected (via unsafeToDelete) to ensure we don't
671 // reduce replication below desired level when
672 // trashing replicas that aren't optimal positions for
673 // any storage class.
674 protMnt := map[*KeepMount]bool{}
675 // Replication planned so far (corresponds to wantMnt).
677 // Protected replication (corresponds to protMnt).
680 // trySlot tries using a slot to meet requirements,
681 // and returns true if all requirements are met.
682 trySlot := func(i int) bool {
684 if wantMnt[slot.mnt] || wantDev[slot.mnt.DeviceID] {
685 // Already allocated a replica to this
686 // backend device, possibly on a
690 if replProt < desired && slot.repl != nil && !protMnt[slot.mnt] {
691 unsafeToDelete[slot.repl.Mtime] = true
692 protMnt[slot.mnt] = true
693 replProt += slot.mnt.Replication
695 if replWant < desired && (slot.repl != nil || !slot.mnt.ReadOnly) {
697 wantSrv[slot.mnt.KeepService] = true
698 wantMnt[slot.mnt] = true
699 if slot.mnt.DeviceID != "" {
700 wantDev[slot.mnt.DeviceID] = true
702 replWant += slot.mnt.Replication
704 return replProt >= desired && replWant >= desired
707 // First try to achieve desired replication without
708 // using the same server twice.
710 for i := 0; i < len(slots) && !done; i++ {
711 if !wantSrv[slots[i].mnt.KeepService] {
716 // If that didn't suffice, do another pass without the
717 // "distinct services" restriction. (Achieving the
718 // desired volume replication on fewer than the
719 // desired number of services is better than
720 // underreplicating.)
721 for i := 0; i < len(slots) && !done; i++ {
725 if !underreplicated {
727 for _, slot := range slots {
728 if slot.repl == nil || !bal.mountsByClass[class][slot.mnt] {
731 if safe += slot.mnt.Replication; safe >= desired {
735 underreplicated = safe < desired
738 // set the unachievable flag if there aren't enough
739 // slots offering the relevant storage class. (This is
740 // as easy as checking slots[desired] because we
741 // already sorted the qualifying slots to the front.)
742 if desired >= len(slots) || !bal.mountsByClass[class][slots[desired].mnt] {
743 cs := classState[class]
744 cs.unachievable = true
745 classState[class] = cs
748 // Avoid deleting wanted replicas from devices that
749 // are mounted on multiple servers -- even if they
750 // haven't already been added to unsafeToDelete
751 // because the servers report different Mtimes.
752 for _, slot := range slots {
753 if slot.repl != nil && wantDev[slot.mnt.DeviceID] {
754 unsafeToDelete[slot.repl.Mtime] = true
759 // TODO: If multiple replicas are trashable, prefer the oldest
760 // replica that doesn't have a timestamp collision with
763 countedDev := map[string]bool{}
765 for _, slot := range slots {
766 if countedDev[slot.mnt.DeviceID] {
770 want += slot.mnt.Replication
772 if slot.repl != nil {
773 have += slot.mnt.Replication
775 if slot.mnt.DeviceID != "" {
776 countedDev[slot.mnt.DeviceID] = true
781 for _, slot := range slots {
782 // TODO: request a Touch if Mtime is duplicated.
785 case !underreplicated && !slot.want && slot.repl != nil && slot.repl.Mtime < bal.MinMtime && !unsafeToDelete[slot.repl.Mtime]:
786 slot.mnt.KeepService.AddTrash(Trash{
788 Mtime: slot.repl.Mtime,
792 case len(blk.Replicas) > 0 && slot.repl == nil && slot.want && !slot.mnt.ReadOnly:
793 slot.mnt.KeepService.AddPull(Pull{
795 From: blk.Replicas[0].KeepMount.KeepService,
799 case slot.repl != nil:
804 if bal.Dumper != nil {
806 if slot.repl != nil {
807 mtime = slot.repl.Mtime
809 srv := slot.mnt.KeepService
810 changes = append(changes, fmt.Sprintf("%s:%d/%s=%s,%d", srv.ServiceHost, srv.ServicePort, slot.mnt.UUID, changeName[change], mtime))
813 if bal.Dumper != nil {
814 bal.Dumper.Printf("%s refs=%d have=%d want=%v %v %v", blkid, blk.RefCount, have, want, blk.Desired, changes)
816 return balanceResult{
821 classState: classState,
825 type blocksNBytes struct {
831 func (bb blocksNBytes) String() string {
832 return fmt.Sprintf("%d replicas (%d blocks, %d bytes)", bb.replicas, bb.blocks, bb.bytes)
835 type balancerStats struct {
840 underrep blocksNBytes
841 unachievable blocksNBytes
842 justright blocksNBytes
848 classStats map[string]replicationStats
850 // collectionBytes / collectionBlockBytes = deduplication ratio
851 collectionBytes int64 // sum(bytes in referenced blocks) across all collections
852 collectionBlockBytes int64 // sum(block size) across all blocks referenced by collections
853 collectionBlockRefs int64 // sum(number of blocks referenced) across all collections
854 collectionBlocks int64 // number of blocks referenced by any collection
857 func (s *balancerStats) dedupByteRatio() float64 {
858 if s.collectionBlockBytes == 0 {
861 return float64(s.collectionBytes) / float64(s.collectionBlockBytes)
864 func (s *balancerStats) dedupBlockRatio() float64 {
865 if s.collectionBlocks == 0 {
868 return float64(s.collectionBlockRefs) / float64(s.collectionBlocks)
871 type replicationStats struct {
875 unachievable blocksNBytes
878 type balancedBlockState struct {
884 func (bal *Balancer) collectStatistics(results <-chan balanceResult) {
886 s.replHistogram = make([]int, 2)
887 s.classStats = make(map[string]replicationStats, len(bal.classes))
888 for result := range results {
889 surplus := result.have - result.want
890 bytes := result.blkid.Size()
892 if rc := int64(result.blk.RefCount); rc > 0 {
893 s.collectionBytes += rc * bytes
894 s.collectionBlockBytes += bytes
895 s.collectionBlockRefs += rc
899 for class, state := range result.classState {
900 cs := s.classStats[class]
901 if state.unachievable {
902 cs.unachievable.blocks++
903 cs.unachievable.bytes += bytes
905 if state.desired > 0 {
906 cs.desired.replicas += state.desired
908 cs.desired.bytes += bytes * int64(state.desired)
910 if state.surplus > 0 {
911 cs.surplus.replicas += state.surplus
913 cs.surplus.bytes += bytes * int64(state.surplus)
914 } else if state.surplus < 0 {
915 cs.short.replicas += -state.surplus
917 cs.short.bytes += bytes * int64(-state.surplus)
919 s.classStats[class] = cs
923 case result.have == 0 && result.want > 0:
924 s.lost.replicas -= surplus
926 s.lost.bytes += bytes * int64(-surplus)
927 fmt.Fprintf(bal.lostBlocks, "%s\n", strings.SplitN(string(result.blkid), "+", 2)[0])
929 s.underrep.replicas -= surplus
931 s.underrep.bytes += bytes * int64(-surplus)
932 case surplus > 0 && result.want == 0:
933 counter := &s.garbage
934 for _, r := range result.blk.Replicas {
935 if r.Mtime >= bal.MinMtime {
940 counter.replicas += surplus
942 counter.bytes += bytes * int64(surplus)
944 s.overrep.replicas += surplus
946 s.overrep.bytes += bytes * int64(result.have-result.want)
948 s.justright.replicas += result.want
950 s.justright.bytes += bytes * int64(result.want)
954 s.desired.replicas += result.want
956 s.desired.bytes += bytes * int64(result.want)
959 s.current.replicas += result.have
961 s.current.bytes += bytes * int64(result.have)
964 for len(s.replHistogram) <= result.have {
965 s.replHistogram = append(s.replHistogram, 0)
967 s.replHistogram[result.have]++
969 for _, srv := range bal.KeepServices {
970 s.pulls += len(srv.ChangeSet.Pulls)
971 s.trashes += len(srv.ChangeSet.Trashes)
974 bal.Metrics.UpdateStats(s)
977 // PrintStatistics writes statistics about the computed changes to
978 // bal.Logger. It should not be called until ComputeChangeSets has
980 func (bal *Balancer) PrintStatistics() {
982 bal.logf("%s lost (0=have<want)", bal.stats.lost)
983 bal.logf("%s underreplicated (0<have<want)", bal.stats.underrep)
984 bal.logf("%s just right (have=want)", bal.stats.justright)
985 bal.logf("%s overreplicated (have>want>0)", bal.stats.overrep)
986 bal.logf("%s unreferenced (have>want=0, new)", bal.stats.unref)
987 bal.logf("%s garbage (have>want=0, old)", bal.stats.garbage)
988 for _, class := range bal.classes {
989 cs := bal.stats.classStats[class]
991 bal.logf("storage class %q: %s desired", class, cs.desired)
992 bal.logf("storage class %q: %s short", class, cs.short)
993 bal.logf("storage class %q: %s surplus", class, cs.surplus)
994 bal.logf("storage class %q: %s unachievable", class, cs.unachievable)
997 bal.logf("%s total commitment (excluding unreferenced)", bal.stats.desired)
998 bal.logf("%s total usage", bal.stats.current)
1000 for _, srv := range bal.KeepServices {
1001 bal.logf("%s: %v\n", srv, srv.ChangeSet)
1004 bal.printHistogram(60)
1008 func (bal *Balancer) printHistogram(hashColumns int) {
1009 bal.logf("Replication level distribution (counting N replicas on a single server as N):")
1011 for _, count := range bal.stats.replHistogram {
1012 if maxCount < count {
1016 hashes := strings.Repeat("#", hashColumns)
1017 countWidth := 1 + int(math.Log10(float64(maxCount+1)))
1018 scaleCount := 10 * float64(hashColumns) / math.Floor(1+10*math.Log10(float64(maxCount+1)))
1019 for repl, count := range bal.stats.replHistogram {
1020 nHashes := int(scaleCount * math.Log10(float64(count+1)))
1021 bal.logf("%2d: %*d %s", repl, countWidth, count, hashes[:nHashes])
1025 // CheckSanityLate checks for configuration and runtime errors after
1026 // GetCurrentState() and ComputeChangeSets() have finished.
1028 // If it returns an error, it is dangerous to run any Commit methods.
1029 func (bal *Balancer) CheckSanityLate() error {
1030 if bal.errors != nil {
1031 for _, err := range bal.errors {
1032 bal.logf("deferred error: %v", err)
1034 return fmt.Errorf("cannot proceed safely after deferred errors")
1037 if bal.collScanned == 0 {
1038 return fmt.Errorf("received zero collections")
1042 bal.BlockStateMap.Apply(func(_ arvados.SizedDigest, blk *BlockState) {
1043 for _, desired := range blk.Desired {
1051 return fmt.Errorf("zero blocks have desired replication>0")
1054 if dr := bal.DefaultReplication; dr < 1 {
1055 return fmt.Errorf("Default replication (%d) is less than 1", dr)
1058 // TODO: no two services have identical indexes
1059 // TODO: no collisions (same md5, different size)
1063 // CommitPulls sends the computed lists of pull requests to the
1064 // keepstore servers. This has the effect of increasing replication of
1065 // existing blocks that are either underreplicated or poorly
1066 // distributed according to rendezvous hashing.
1067 func (bal *Balancer) CommitPulls(c *arvados.Client) error {
1068 defer bal.time("send_pull_lists", "wall clock time to send pull lists")()
1069 return bal.commitAsync(c, "send pull list",
1070 func(srv *KeepService) error {
1071 return srv.CommitPulls(c)
1075 // CommitTrash sends the computed lists of trash requests to the
1076 // keepstore servers. This has the effect of deleting blocks that are
1077 // overreplicated or unreferenced.
1078 func (bal *Balancer) CommitTrash(c *arvados.Client) error {
1079 defer bal.time("send_trash_lists", "wall clock time to send trash lists")()
1080 return bal.commitAsync(c, "send trash list",
1081 func(srv *KeepService) error {
1082 return srv.CommitTrash(c)
1086 func (bal *Balancer) commitAsync(c *arvados.Client, label string, f func(srv *KeepService) error) error {
1087 errs := make(chan error)
1088 for _, srv := range bal.KeepServices {
1089 go func(srv *KeepService) {
1091 defer func() { errs <- err }()
1092 label := fmt.Sprintf("%s: %v", srv, label)
1095 err = fmt.Errorf("%s: %v", label, err)
1100 for range bal.KeepServices {
1101 if err := <-errs; err != nil {
1110 func (bal *Balancer) logf(f string, args ...interface{}) {
1111 if bal.Logger != nil {
1112 bal.Logger.Printf(f, args...)
1116 func (bal *Balancer) time(name, help string) func() {
1117 observer := bal.Metrics.DurationObserver(name+"_seconds", help)
1119 bal.Logger.Printf("%s: start", name)
1121 dur := time.Since(t0)
1122 observer.Observe(dur.Seconds())
1123 bal.Logger.Printf("%s: took %vs", name, dur.Seconds())
1127 // Rendezvous hash sort function. Less efficient than sorting on
1128 // precomputed rendezvous hashes, but also rarely used.
1129 func rendezvousLess(i, j string, blkid arvados.SizedDigest) bool {
1130 a := md5.Sum([]byte(string(blkid[:32]) + i))
1131 b := md5.Sum([]byte(string(blkid[:32]) + j))
1132 return bytes.Compare(a[:], b[:]) < 0