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)
86 defer os.Remove(tmpfn)
87 bal.lostBlocks = lbFile
89 bal.lostBlocks = ioutil.Discard
92 if len(config.KeepServiceList.Items) > 0 {
93 err = bal.SetKeepServices(config.KeepServiceList)
95 err = bal.DiscoverKeepServices(&config.Client, config.KeepServiceTypes)
101 for _, srv := range bal.KeepServices {
102 err = srv.discoverMounts(&config.Client)
109 if err = bal.CheckSanityEarly(&config.Client); err != nil {
112 rs := bal.rendezvousState()
113 if runOptions.CommitTrash && rs != runOptions.SafeRendezvousState {
114 if runOptions.SafeRendezvousState != "" {
115 bal.logf("notice: KeepServices list has changed since last run")
117 bal.logf("clearing existing trash lists, in case the new rendezvous order differs from previous run")
118 if err = bal.ClearTrashLists(&config.Client); err != nil {
121 // The current rendezvous state becomes "safe" (i.e.,
122 // OK to compute changes for that state without
123 // clearing existing trash lists) only now, after we
124 // succeed in clearing existing trash lists.
125 nextRunOptions.SafeRendezvousState = rs
127 if err = bal.GetCurrentState(&config.Client, config.CollectionBatchSize, config.CollectionBuffers); err != nil {
130 bal.ComputeChangeSets()
131 bal.PrintStatistics()
132 if err = bal.CheckSanityLate(); err != nil {
140 err = os.Rename(bal.LostBlocksFile+".tmp", bal.LostBlocksFile)
149 if runOptions.CommitPulls {
150 err = bal.CommitPulls(&config.Client)
152 // Skip trash if we can't pull. (Too cautious?)
156 if runOptions.CommitTrash {
157 err = bal.CommitTrash(&config.Client)
162 // SetKeepServices sets the list of KeepServices to operate on.
163 func (bal *Balancer) SetKeepServices(srvList arvados.KeepServiceList) error {
164 bal.KeepServices = make(map[string]*KeepService)
165 for _, srv := range srvList.Items {
166 bal.KeepServices[srv.UUID] = &KeepService{
168 ChangeSet: &ChangeSet{},
174 // DiscoverKeepServices sets the list of KeepServices by calling the
175 // API to get a list of all services, and selecting the ones whose
176 // ServiceType is in okTypes.
177 func (bal *Balancer) DiscoverKeepServices(c *arvados.Client, okTypes []string) error {
178 bal.KeepServices = make(map[string]*KeepService)
179 ok := make(map[string]bool)
180 for _, t := range okTypes {
183 return c.EachKeepService(func(srv arvados.KeepService) error {
184 if ok[srv.ServiceType] {
185 bal.KeepServices[srv.UUID] = &KeepService{
187 ChangeSet: &ChangeSet{},
190 bal.logf("skipping %v with service type %q", srv.UUID, srv.ServiceType)
196 func (bal *Balancer) cleanupMounts() {
197 rwdev := map[string]*KeepService{}
198 for _, srv := range bal.KeepServices {
199 for _, mnt := range srv.mounts {
200 if !mnt.ReadOnly && mnt.DeviceID != "" {
201 rwdev[mnt.DeviceID] = srv
205 // Drop the readonly mounts whose device is mounted RW
207 for _, srv := range bal.KeepServices {
208 var dedup []*KeepMount
209 for _, mnt := range srv.mounts {
210 if mnt.ReadOnly && rwdev[mnt.DeviceID] != nil {
211 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])
213 dedup = append(dedup, mnt)
218 for _, srv := range bal.KeepServices {
219 for _, mnt := range srv.mounts {
220 if mnt.Replication <= 0 {
221 log.Printf("%s: mount %s reports replication=%d, using replication=1", srv, mnt.UUID, mnt.Replication)
228 // CheckSanityEarly checks for configuration and runtime errors that
229 // can be detected before GetCurrentState() and ComputeChangeSets()
232 // If it returns an error, it is pointless to run GetCurrentState or
233 // ComputeChangeSets: after doing so, the statistics would be
234 // meaningless and it would be dangerous to run any Commit methods.
235 func (bal *Balancer) CheckSanityEarly(c *arvados.Client) error {
236 u, err := c.CurrentUser()
238 return fmt.Errorf("CurrentUser(): %v", err)
240 if !u.IsActive || !u.IsAdmin {
241 return fmt.Errorf("current user (%s) is not an active admin user", u.UUID)
243 for _, srv := range bal.KeepServices {
244 if srv.ServiceType == "proxy" {
245 return fmt.Errorf("config error: %s: proxy servers cannot be balanced", srv)
249 var checkPage arvados.CollectionList
250 if err = c.RequestAndDecode(&checkPage, "GET", "arvados/v1/collections", nil, arvados.ResourceListParams{
254 IncludeOldVersions: true,
255 Filters: []arvados.Filter{{
262 } else if n := checkPage.ItemsAvailable; n > 0 {
263 return fmt.Errorf("%d collections exist with null modified_at; cannot fetch reliably", n)
269 // rendezvousState returns a fingerprint (e.g., a sorted list of
270 // UUID+host+port) of the current set of keep services.
271 func (bal *Balancer) rendezvousState() string {
272 srvs := make([]string, 0, len(bal.KeepServices))
273 for _, srv := range bal.KeepServices {
274 srvs = append(srvs, srv.String())
277 return strings.Join(srvs, "; ")
280 // ClearTrashLists sends an empty trash list to each keep
281 // service. Calling this before GetCurrentState avoids races.
283 // When a block appears in an index, we assume that replica will still
284 // exist after we delete other replicas on other servers. However,
285 // it's possible that a previous rebalancing operation made different
286 // decisions (e.g., servers were added/removed, and rendezvous order
287 // changed). In this case, the replica might already be on that
288 // server's trash list, and it might be deleted before we send a
289 // replacement trash list.
291 // We avoid this problem if we clear all trash lists before getting
292 // indexes. (We also assume there is only one rebalancing process
293 // running at a time.)
294 func (bal *Balancer) ClearTrashLists(c *arvados.Client) error {
295 for _, srv := range bal.KeepServices {
296 srv.ChangeSet = &ChangeSet{}
298 return bal.CommitTrash(c)
301 // GetCurrentState determines the current replication state, and the
302 // desired replication level, for every block that is either
303 // retrievable or referenced.
305 // It determines the current replication state by reading the block index
306 // from every known Keep service.
308 // It determines the desired replication level by retrieving all
309 // collection manifests in the database (API server).
311 // It encodes the resulting information in BlockStateMap.
312 func (bal *Balancer) GetCurrentState(c *arvados.Client, pageSize, bufs int) error {
313 defer bal.time("get_state", "wall clock time to get current state")()
314 bal.BlockStateMap = NewBlockStateMap()
316 dd, err := c.DiscoveryDocument()
320 bal.DefaultReplication = dd.DefaultCollectionReplication
321 bal.MinMtime = time.Now().UnixNano() - dd.BlobSignatureTTL*1e9
323 errs := make(chan error, 1)
324 wg := sync.WaitGroup{}
326 // When a device is mounted more than once, we will get its
327 // index only once, and call AddReplicas on all of the mounts.
328 // equivMount keys are the mounts that will be indexed, and
329 // each value is a list of mounts to apply the received index
331 equivMount := map[*KeepMount][]*KeepMount{}
332 // deviceMount maps each device ID to the one mount that will
333 // be indexed for that device.
334 deviceMount := map[string]*KeepMount{}
335 for _, srv := range bal.KeepServices {
336 for _, mnt := range srv.mounts {
337 equiv := deviceMount[mnt.DeviceID]
340 if mnt.DeviceID != "" {
341 deviceMount[mnt.DeviceID] = equiv
344 equivMount[equiv] = append(equivMount[equiv], mnt)
348 // Start one goroutine for each (non-redundant) mount:
349 // retrieve the index, and add the returned blocks to
351 for _, mounts := range equivMount {
353 go func(mounts []*KeepMount) {
355 bal.logf("mount %s: retrieve index from %s", mounts[0], mounts[0].KeepService)
356 idx, err := mounts[0].KeepService.IndexMount(c, mounts[0].UUID, "")
359 case errs <- fmt.Errorf("%s: retrieve index: %v", mounts[0], err):
365 // Some other goroutine encountered an
366 // error -- any further effort here
370 for _, mount := range mounts {
371 bal.logf("%s: add %d entries to map", mount, len(idx))
372 bal.BlockStateMap.AddReplicas(mount, idx)
373 bal.logf("%s: added %d entries to map at %dx (%d replicas)", mount, len(idx), mount.Replication, len(idx)*mount.Replication)
375 bal.logf("mount %s: index done", mounts[0])
379 // collQ buffers incoming collections so we can start fetching
380 // the next page without waiting for the current page to
381 // finish processing.
382 collQ := make(chan arvados.Collection, bufs)
384 // Start a goroutine to process collections. (We could use a
385 // worker pool here, but even with a single worker we already
386 // process collections much faster than we can retrieve them.)
390 for coll := range collQ {
391 err := bal.addCollection(coll)
392 if err != nil || len(errs) > 0 {
405 // Start a goroutine to retrieve all collections from the
406 // Arvados database and send them to collQ for processing.
410 err = EachCollection(c, pageSize,
411 func(coll arvados.Collection) error {
414 // some other GetCurrentState
415 // error happened: no point
418 return fmt.Errorf("")
421 }, func(done, total int) {
422 bal.logf("collections: %d/%d", done, total)
440 func (bal *Balancer) addCollection(coll arvados.Collection) error {
441 blkids, err := coll.SizedDigests()
443 return fmt.Errorf("%v: %v", coll.UUID, err)
445 repl := bal.DefaultReplication
446 if coll.ReplicationDesired != nil {
447 repl = *coll.ReplicationDesired
449 debugf("%v: %d block x%d", coll.UUID, len(blkids), repl)
450 bal.BlockStateMap.IncreaseDesired(coll.StorageClassesDesired, repl, blkids)
454 // ComputeChangeSets compares, for each known block, the current and
455 // desired replication states. If it is possible to get closer to the
456 // desired state by copying or deleting blocks, it adds those changes
457 // to the relevant KeepServices' ChangeSets.
459 // It does not actually apply any of the computed changes.
460 func (bal *Balancer) ComputeChangeSets() {
461 // This just calls balanceBlock() once for each block, using a
462 // pool of worker goroutines.
463 defer bal.time("changeset_compute", "wall clock time to compute changesets")()
464 bal.setupLookupTables()
466 type balanceTask struct {
467 blkid arvados.SizedDigest
470 workers := runtime.GOMAXPROCS(-1)
471 todo := make(chan balanceTask, workers)
473 bal.BlockStateMap.Apply(func(blkid arvados.SizedDigest, blk *BlockState) {
481 results := make(chan balanceResult, workers)
483 var wg sync.WaitGroup
484 for i := 0; i < workers; i++ {
487 for work := range todo {
488 results <- bal.balanceBlock(work.blkid, work.blk)
496 bal.collectStatistics(results)
499 func (bal *Balancer) setupLookupTables() {
500 bal.serviceRoots = make(map[string]string)
501 bal.classes = defaultClasses
502 bal.mountsByClass = map[string]map[*KeepMount]bool{"default": {}}
504 for _, srv := range bal.KeepServices {
505 bal.serviceRoots[srv.UUID] = srv.UUID
506 for _, mnt := range srv.mounts {
509 // All mounts on a read-only service are
510 // effectively read-only.
511 mnt.ReadOnly = mnt.ReadOnly || srv.ReadOnly
513 if len(mnt.StorageClasses) == 0 {
514 bal.mountsByClass["default"][mnt] = true
517 for _, class := range mnt.StorageClasses {
518 if mbc := bal.mountsByClass[class]; mbc == nil {
519 bal.classes = append(bal.classes, class)
520 bal.mountsByClass[class] = map[*KeepMount]bool{mnt: true}
527 // Consider classes in lexicographic order to avoid flapping
528 // between balancing runs. The outcome of the "prefer a mount
529 // we're already planning to use for a different storage
530 // class" case in balanceBlock depends on the order classes
532 sort.Strings(bal.classes)
542 var changeName = map[int]string{
545 changeTrash: "trash",
549 type balanceResult struct {
551 blkid arvados.SizedDigest
554 classState map[string]balancedBlockState
557 // balanceBlock compares current state to desired state for a single
558 // block, and makes the appropriate ChangeSet calls.
559 func (bal *Balancer) balanceBlock(blkid arvados.SizedDigest, blk *BlockState) balanceResult {
560 debugf("balanceBlock: %v %+v", blkid, blk)
563 mnt *KeepMount // never nil
564 repl *Replica // replica already stored here (or nil)
565 want bool // we should pull/leave a replica here
568 // Build a list of all slots (one per mounted volume).
569 slots := make([]slot, 0, bal.mounts)
570 for _, srv := range bal.KeepServices {
571 for _, mnt := range srv.mounts {
573 for r := range blk.Replicas {
574 if blk.Replicas[r].KeepMount == mnt {
575 repl = &blk.Replicas[r]
578 // Initial value of "want" is "have, and can't
579 // delete". These untrashable replicas get
580 // prioritized when sorting slots: otherwise,
581 // non-optimal readonly copies would cause us
583 slots = append(slots, slot{
586 want: repl != nil && mnt.ReadOnly,
591 uuids := keepclient.NewRootSorter(bal.serviceRoots, string(blkid[:32])).GetSortedRoots()
592 srvRendezvous := make(map[*KeepService]int, len(uuids))
593 for i, uuid := range uuids {
594 srv := bal.KeepServices[uuid]
595 srvRendezvous[srv] = i
598 // Below we set underreplicated=true if we find any storage
599 // class that's currently underreplicated -- in that case we
600 // won't want to trash any replicas.
601 underreplicated := false
603 classState := make(map[string]balancedBlockState, len(bal.classes))
604 unsafeToDelete := make(map[int64]bool, len(slots))
605 for _, class := range bal.classes {
606 desired := blk.Desired[class]
608 countedDev := map[string]bool{}
610 for _, slot := range slots {
611 if slot.repl != nil && bal.mountsByClass[class][slot.mnt] && !countedDev[slot.mnt.DeviceID] {
612 have += slot.mnt.Replication
613 if slot.mnt.DeviceID != "" {
614 countedDev[slot.mnt.DeviceID] = true
618 classState[class] = balancedBlockState{
620 surplus: have - desired,
627 // Sort the slots by desirability.
628 sort.Slice(slots, func(i, j int) bool {
629 si, sj := slots[i], slots[j]
630 if classi, classj := bal.mountsByClass[class][si.mnt], bal.mountsByClass[class][sj.mnt]; classi != classj {
631 // Prefer a mount that satisfies the
633 return bal.mountsByClass[class][si.mnt]
634 } else if si.want != sj.want {
635 // Prefer a mount that will have a
636 // replica no matter what we do here
637 // -- either because it already has an
638 // untrashable replica, or because we
639 // already need it to satisfy a
640 // different storage class.
642 } else if orderi, orderj := srvRendezvous[si.mnt.KeepService], srvRendezvous[sj.mnt.KeepService]; orderi != orderj {
643 // Prefer a better rendezvous
645 return orderi < orderj
646 } else if repli, replj := si.repl != nil, sj.repl != nil; repli != replj {
647 // Prefer a mount that already has a
651 // If pull/trash turns out to be
652 // needed, distribute the
653 // new/remaining replicas uniformly
654 // across qualifying mounts on a given
656 return rendezvousLess(si.mnt.DeviceID, sj.mnt.DeviceID, blkid)
660 // Servers/mounts/devices (with or without existing
661 // replicas) that are part of the best achievable
662 // layout for this storage class.
663 wantSrv := map[*KeepService]bool{}
664 wantMnt := map[*KeepMount]bool{}
665 wantDev := map[string]bool{}
666 // Positions (with existing replicas) that have been
667 // protected (via unsafeToDelete) to ensure we don't
668 // reduce replication below desired level when
669 // trashing replicas that aren't optimal positions for
670 // any storage class.
671 protMnt := map[*KeepMount]bool{}
672 // Replication planned so far (corresponds to wantMnt).
674 // Protected replication (corresponds to protMnt).
677 // trySlot tries using a slot to meet requirements,
678 // and returns true if all requirements are met.
679 trySlot := func(i int) bool {
681 if wantMnt[slot.mnt] || wantDev[slot.mnt.DeviceID] {
682 // Already allocated a replica to this
683 // backend device, possibly on a
687 if replProt < desired && slot.repl != nil && !protMnt[slot.mnt] {
688 unsafeToDelete[slot.repl.Mtime] = true
689 protMnt[slot.mnt] = true
690 replProt += slot.mnt.Replication
692 if replWant < desired && (slot.repl != nil || !slot.mnt.ReadOnly) {
694 wantSrv[slot.mnt.KeepService] = true
695 wantMnt[slot.mnt] = true
696 if slot.mnt.DeviceID != "" {
697 wantDev[slot.mnt.DeviceID] = true
699 replWant += slot.mnt.Replication
701 return replProt >= desired && replWant >= desired
704 // First try to achieve desired replication without
705 // using the same server twice.
707 for i := 0; i < len(slots) && !done; i++ {
708 if !wantSrv[slots[i].mnt.KeepService] {
713 // If that didn't suffice, do another pass without the
714 // "distinct services" restriction. (Achieving the
715 // desired volume replication on fewer than the
716 // desired number of services is better than
717 // underreplicating.)
718 for i := 0; i < len(slots) && !done; i++ {
722 if !underreplicated {
724 for _, slot := range slots {
725 if slot.repl == nil || !bal.mountsByClass[class][slot.mnt] {
728 if safe += slot.mnt.Replication; safe >= desired {
732 underreplicated = safe < desired
735 // set the unachievable flag if there aren't enough
736 // slots offering the relevant storage class. (This is
737 // as easy as checking slots[desired] because we
738 // already sorted the qualifying slots to the front.)
739 if desired >= len(slots) || !bal.mountsByClass[class][slots[desired].mnt] {
740 cs := classState[class]
741 cs.unachievable = true
742 classState[class] = cs
745 // Avoid deleting wanted replicas from devices that
746 // are mounted on multiple servers -- even if they
747 // haven't already been added to unsafeToDelete
748 // because the servers report different Mtimes.
749 for _, slot := range slots {
750 if slot.repl != nil && wantDev[slot.mnt.DeviceID] {
751 unsafeToDelete[slot.repl.Mtime] = true
756 // TODO: If multiple replicas are trashable, prefer the oldest
757 // replica that doesn't have a timestamp collision with
760 countedDev := map[string]bool{}
762 for _, slot := range slots {
763 if countedDev[slot.mnt.DeviceID] {
767 want += slot.mnt.Replication
769 if slot.repl != nil {
770 have += slot.mnt.Replication
772 if slot.mnt.DeviceID != "" {
773 countedDev[slot.mnt.DeviceID] = true
778 for _, slot := range slots {
779 // TODO: request a Touch if Mtime is duplicated.
782 case !underreplicated && !slot.want && slot.repl != nil && slot.repl.Mtime < bal.MinMtime && !unsafeToDelete[slot.repl.Mtime]:
783 slot.mnt.KeepService.AddTrash(Trash{
785 Mtime: slot.repl.Mtime,
789 case len(blk.Replicas) > 0 && slot.repl == nil && slot.want && !slot.mnt.ReadOnly:
790 slot.mnt.KeepService.AddPull(Pull{
792 From: blk.Replicas[0].KeepMount.KeepService,
796 case slot.repl != nil:
801 if bal.Dumper != nil {
803 if slot.repl != nil {
804 mtime = slot.repl.Mtime
806 srv := slot.mnt.KeepService
807 changes = append(changes, fmt.Sprintf("%s:%d/%s=%s,%d", srv.ServiceHost, srv.ServicePort, slot.mnt.UUID, changeName[change], mtime))
810 if bal.Dumper != nil {
811 bal.Dumper.Printf("%s refs=%d have=%d want=%v %v %v", blkid, blk.RefCount, have, want, blk.Desired, changes)
813 return balanceResult{
818 classState: classState,
822 type blocksNBytes struct {
828 func (bb blocksNBytes) String() string {
829 return fmt.Sprintf("%d replicas (%d blocks, %d bytes)", bb.replicas, bb.blocks, bb.bytes)
832 type balancerStats struct {
837 underrep blocksNBytes
838 unachievable blocksNBytes
839 justright blocksNBytes
845 classStats map[string]replicationStats
847 // collectionBytes / collectionBlockBytes = deduplication ratio
848 collectionBytes int64 // sum(bytes in referenced blocks) across all collections
849 collectionBlockBytes int64 // sum(block size) across all blocks referenced by collections
850 collectionBlockRefs int64 // sum(number of blocks referenced) across all collections
851 collectionBlocks int64 // number of blocks referenced by any collection
854 func (s *balancerStats) dedupByteRatio() float64 {
855 if s.collectionBlockBytes == 0 {
858 return float64(s.collectionBytes) / float64(s.collectionBlockBytes)
861 func (s *balancerStats) dedupBlockRatio() float64 {
862 if s.collectionBlocks == 0 {
865 return float64(s.collectionBlockRefs) / float64(s.collectionBlocks)
868 type replicationStats struct {
872 unachievable blocksNBytes
875 type balancedBlockState struct {
881 func (bal *Balancer) collectStatistics(results <-chan balanceResult) {
883 s.replHistogram = make([]int, 2)
884 s.classStats = make(map[string]replicationStats, len(bal.classes))
885 for result := range results {
886 surplus := result.have - result.want
887 bytes := result.blkid.Size()
889 if rc := int64(result.blk.RefCount); rc > 0 {
890 s.collectionBytes += rc * bytes
891 s.collectionBlockBytes += bytes
892 s.collectionBlockRefs += rc
896 for class, state := range result.classState {
897 cs := s.classStats[class]
898 if state.unachievable {
899 cs.unachievable.blocks++
900 cs.unachievable.bytes += bytes
902 if state.desired > 0 {
903 cs.desired.replicas += state.desired
905 cs.desired.bytes += bytes * int64(state.desired)
907 if state.surplus > 0 {
908 cs.surplus.replicas += state.surplus
910 cs.surplus.bytes += bytes * int64(state.surplus)
911 } else if state.surplus < 0 {
912 cs.short.replicas += -state.surplus
914 cs.short.bytes += bytes * int64(-state.surplus)
916 s.classStats[class] = cs
920 case result.have == 0 && result.want > 0:
921 s.lost.replicas -= surplus
923 s.lost.bytes += bytes * int64(-surplus)
924 fmt.Fprintf(bal.lostBlocks, "%s\n", strings.SplitN(string(result.blkid), "+", 2)[0])
926 s.underrep.replicas -= surplus
928 s.underrep.bytes += bytes * int64(-surplus)
929 case surplus > 0 && result.want == 0:
930 counter := &s.garbage
931 for _, r := range result.blk.Replicas {
932 if r.Mtime >= bal.MinMtime {
937 counter.replicas += surplus
939 counter.bytes += bytes * int64(surplus)
941 s.overrep.replicas += surplus
943 s.overrep.bytes += bytes * int64(result.have-result.want)
945 s.justright.replicas += result.want
947 s.justright.bytes += bytes * int64(result.want)
951 s.desired.replicas += result.want
953 s.desired.bytes += bytes * int64(result.want)
956 s.current.replicas += result.have
958 s.current.bytes += bytes * int64(result.have)
961 for len(s.replHistogram) <= result.have {
962 s.replHistogram = append(s.replHistogram, 0)
964 s.replHistogram[result.have]++
966 for _, srv := range bal.KeepServices {
967 s.pulls += len(srv.ChangeSet.Pulls)
968 s.trashes += len(srv.ChangeSet.Trashes)
971 bal.Metrics.UpdateStats(s)
974 // PrintStatistics writes statistics about the computed changes to
975 // bal.Logger. It should not be called until ComputeChangeSets has
977 func (bal *Balancer) PrintStatistics() {
979 bal.logf("%s lost (0=have<want)", bal.stats.lost)
980 bal.logf("%s underreplicated (0<have<want)", bal.stats.underrep)
981 bal.logf("%s just right (have=want)", bal.stats.justright)
982 bal.logf("%s overreplicated (have>want>0)", bal.stats.overrep)
983 bal.logf("%s unreferenced (have>want=0, new)", bal.stats.unref)
984 bal.logf("%s garbage (have>want=0, old)", bal.stats.garbage)
985 for _, class := range bal.classes {
986 cs := bal.stats.classStats[class]
988 bal.logf("storage class %q: %s desired", class, cs.desired)
989 bal.logf("storage class %q: %s short", class, cs.short)
990 bal.logf("storage class %q: %s surplus", class, cs.surplus)
991 bal.logf("storage class %q: %s unachievable", class, cs.unachievable)
994 bal.logf("%s total commitment (excluding unreferenced)", bal.stats.desired)
995 bal.logf("%s total usage", bal.stats.current)
997 for _, srv := range bal.KeepServices {
998 bal.logf("%s: %v\n", srv, srv.ChangeSet)
1001 bal.printHistogram(60)
1005 func (bal *Balancer) printHistogram(hashColumns int) {
1006 bal.logf("Replication level distribution (counting N replicas on a single server as N):")
1008 for _, count := range bal.stats.replHistogram {
1009 if maxCount < count {
1013 hashes := strings.Repeat("#", hashColumns)
1014 countWidth := 1 + int(math.Log10(float64(maxCount+1)))
1015 scaleCount := 10 * float64(hashColumns) / math.Floor(1+10*math.Log10(float64(maxCount+1)))
1016 for repl, count := range bal.stats.replHistogram {
1017 nHashes := int(scaleCount * math.Log10(float64(count+1)))
1018 bal.logf("%2d: %*d %s", repl, countWidth, count, hashes[:nHashes])
1022 // CheckSanityLate checks for configuration and runtime errors after
1023 // GetCurrentState() and ComputeChangeSets() have finished.
1025 // If it returns an error, it is dangerous to run any Commit methods.
1026 func (bal *Balancer) CheckSanityLate() error {
1027 if bal.errors != nil {
1028 for _, err := range bal.errors {
1029 bal.logf("deferred error: %v", err)
1031 return fmt.Errorf("cannot proceed safely after deferred errors")
1034 if bal.collScanned == 0 {
1035 return fmt.Errorf("received zero collections")
1039 bal.BlockStateMap.Apply(func(_ arvados.SizedDigest, blk *BlockState) {
1040 for _, desired := range blk.Desired {
1048 return fmt.Errorf("zero blocks have desired replication>0")
1051 if dr := bal.DefaultReplication; dr < 1 {
1052 return fmt.Errorf("Default replication (%d) is less than 1", dr)
1055 // TODO: no two services have identical indexes
1056 // TODO: no collisions (same md5, different size)
1060 // CommitPulls sends the computed lists of pull requests to the
1061 // keepstore servers. This has the effect of increasing replication of
1062 // existing blocks that are either underreplicated or poorly
1063 // distributed according to rendezvous hashing.
1064 func (bal *Balancer) CommitPulls(c *arvados.Client) error {
1065 defer bal.time("send_pull_lists", "wall clock time to send pull lists")()
1066 return bal.commitAsync(c, "send pull list",
1067 func(srv *KeepService) error {
1068 return srv.CommitPulls(c)
1072 // CommitTrash sends the computed lists of trash requests to the
1073 // keepstore servers. This has the effect of deleting blocks that are
1074 // overreplicated or unreferenced.
1075 func (bal *Balancer) CommitTrash(c *arvados.Client) error {
1076 defer bal.time("send_trash_lists", "wall clock time to send trash lists")()
1077 return bal.commitAsync(c, "send trash list",
1078 func(srv *KeepService) error {
1079 return srv.CommitTrash(c)
1083 func (bal *Balancer) commitAsync(c *arvados.Client, label string, f func(srv *KeepService) error) error {
1084 errs := make(chan error)
1085 for _, srv := range bal.KeepServices {
1086 go func(srv *KeepService) {
1088 defer func() { errs <- err }()
1089 label := fmt.Sprintf("%s: %v", srv, label)
1092 err = fmt.Errorf("%s: %v", label, err)
1097 for range bal.KeepServices {
1098 if err := <-errs; err != nil {
1107 func (bal *Balancer) logf(f string, args ...interface{}) {
1108 if bal.Logger != nil {
1109 bal.Logger.Printf(f, args...)
1113 func (bal *Balancer) time(name, help string) func() {
1114 observer := bal.Metrics.DurationObserver(name+"_seconds", help)
1116 bal.Logger.Printf("%s: start", name)
1118 dur := time.Since(t0)
1119 observer.Observe(dur.Seconds())
1120 bal.Logger.Printf("%s: took %vs", name, dur.Seconds())
1124 // Rendezvous hash sort function. Less efficient than sorting on
1125 // precomputed rendezvous hashes, but also rarely used.
1126 func rendezvousLess(i, j string, blkid arvados.SizedDigest) bool {
1127 a := md5.Sum([]byte(string(blkid[:32]) + i))
1128 b := md5.Sum([]byte(string(blkid[:32]) + j))
1129 return bytes.Compare(a[:], b[:]) < 0