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 // Pass pdh to IncreaseDesired only if LostBlocksFile is being
454 // written -- otherwise it's just a waste of memory.
456 if bal.LostBlocksFile != "" {
457 pdh = coll.PortableDataHash
459 bal.BlockStateMap.IncreaseDesired(pdh, coll.StorageClassesDesired, repl, blkids)
463 // ComputeChangeSets compares, for each known block, the current and
464 // desired replication states. If it is possible to get closer to the
465 // desired state by copying or deleting blocks, it adds those changes
466 // to the relevant KeepServices' ChangeSets.
468 // It does not actually apply any of the computed changes.
469 func (bal *Balancer) ComputeChangeSets() {
470 // This just calls balanceBlock() once for each block, using a
471 // pool of worker goroutines.
472 defer bal.time("changeset_compute", "wall clock time to compute changesets")()
473 bal.setupLookupTables()
475 type balanceTask struct {
476 blkid arvados.SizedDigest
479 workers := runtime.GOMAXPROCS(-1)
480 todo := make(chan balanceTask, workers)
482 bal.BlockStateMap.Apply(func(blkid arvados.SizedDigest, blk *BlockState) {
490 results := make(chan balanceResult, workers)
492 var wg sync.WaitGroup
493 for i := 0; i < workers; i++ {
496 for work := range todo {
497 results <- bal.balanceBlock(work.blkid, work.blk)
505 bal.collectStatistics(results)
508 func (bal *Balancer) setupLookupTables() {
509 bal.serviceRoots = make(map[string]string)
510 bal.classes = defaultClasses
511 bal.mountsByClass = map[string]map[*KeepMount]bool{"default": {}}
513 for _, srv := range bal.KeepServices {
514 bal.serviceRoots[srv.UUID] = srv.UUID
515 for _, mnt := range srv.mounts {
518 // All mounts on a read-only service are
519 // effectively read-only.
520 mnt.ReadOnly = mnt.ReadOnly || srv.ReadOnly
522 if len(mnt.StorageClasses) == 0 {
523 bal.mountsByClass["default"][mnt] = true
526 for _, class := range mnt.StorageClasses {
527 if mbc := bal.mountsByClass[class]; mbc == nil {
528 bal.classes = append(bal.classes, class)
529 bal.mountsByClass[class] = map[*KeepMount]bool{mnt: true}
536 // Consider classes in lexicographic order to avoid flapping
537 // between balancing runs. The outcome of the "prefer a mount
538 // we're already planning to use for a different storage
539 // class" case in balanceBlock depends on the order classes
541 sort.Strings(bal.classes)
551 var changeName = map[int]string{
554 changeTrash: "trash",
558 type balanceResult struct {
560 blkid arvados.SizedDigest
563 classState map[string]balancedBlockState
566 // balanceBlock compares current state to desired state for a single
567 // block, and makes the appropriate ChangeSet calls.
568 func (bal *Balancer) balanceBlock(blkid arvados.SizedDigest, blk *BlockState) balanceResult {
569 debugf("balanceBlock: %v %+v", blkid, blk)
572 mnt *KeepMount // never nil
573 repl *Replica // replica already stored here (or nil)
574 want bool // we should pull/leave a replica here
577 // Build a list of all slots (one per mounted volume).
578 slots := make([]slot, 0, bal.mounts)
579 for _, srv := range bal.KeepServices {
580 for _, mnt := range srv.mounts {
582 for r := range blk.Replicas {
583 if blk.Replicas[r].KeepMount == mnt {
584 repl = &blk.Replicas[r]
587 // Initial value of "want" is "have, and can't
588 // delete". These untrashable replicas get
589 // prioritized when sorting slots: otherwise,
590 // non-optimal readonly copies would cause us
592 slots = append(slots, slot{
595 want: repl != nil && mnt.ReadOnly,
600 uuids := keepclient.NewRootSorter(bal.serviceRoots, string(blkid[:32])).GetSortedRoots()
601 srvRendezvous := make(map[*KeepService]int, len(uuids))
602 for i, uuid := range uuids {
603 srv := bal.KeepServices[uuid]
604 srvRendezvous[srv] = i
607 // Below we set underreplicated=true if we find any storage
608 // class that's currently underreplicated -- in that case we
609 // won't want to trash any replicas.
610 underreplicated := false
612 classState := make(map[string]balancedBlockState, len(bal.classes))
613 unsafeToDelete := make(map[int64]bool, len(slots))
614 for _, class := range bal.classes {
615 desired := blk.Desired[class]
617 countedDev := map[string]bool{}
619 for _, slot := range slots {
620 if slot.repl != nil && bal.mountsByClass[class][slot.mnt] && !countedDev[slot.mnt.DeviceID] {
621 have += slot.mnt.Replication
622 if slot.mnt.DeviceID != "" {
623 countedDev[slot.mnt.DeviceID] = true
627 classState[class] = balancedBlockState{
629 surplus: have - desired,
636 // Sort the slots by desirability.
637 sort.Slice(slots, func(i, j int) bool {
638 si, sj := slots[i], slots[j]
639 if classi, classj := bal.mountsByClass[class][si.mnt], bal.mountsByClass[class][sj.mnt]; classi != classj {
640 // Prefer a mount that satisfies the
642 return bal.mountsByClass[class][si.mnt]
643 } else if si.want != sj.want {
644 // Prefer a mount that will have a
645 // replica no matter what we do here
646 // -- either because it already has an
647 // untrashable replica, or because we
648 // already need it to satisfy a
649 // different storage class.
651 } else if orderi, orderj := srvRendezvous[si.mnt.KeepService], srvRendezvous[sj.mnt.KeepService]; orderi != orderj {
652 // Prefer a better rendezvous
654 return orderi < orderj
655 } else if repli, replj := si.repl != nil, sj.repl != nil; repli != replj {
656 // Prefer a mount that already has a
660 // If pull/trash turns out to be
661 // needed, distribute the
662 // new/remaining replicas uniformly
663 // across qualifying mounts on a given
665 return rendezvousLess(si.mnt.DeviceID, sj.mnt.DeviceID, blkid)
669 // Servers/mounts/devices (with or without existing
670 // replicas) that are part of the best achievable
671 // layout for this storage class.
672 wantSrv := map[*KeepService]bool{}
673 wantMnt := map[*KeepMount]bool{}
674 wantDev := map[string]bool{}
675 // Positions (with existing replicas) that have been
676 // protected (via unsafeToDelete) to ensure we don't
677 // reduce replication below desired level when
678 // trashing replicas that aren't optimal positions for
679 // any storage class.
680 protMnt := map[*KeepMount]bool{}
681 // Replication planned so far (corresponds to wantMnt).
683 // Protected replication (corresponds to protMnt).
686 // trySlot tries using a slot to meet requirements,
687 // and returns true if all requirements are met.
688 trySlot := func(i int) bool {
690 if wantMnt[slot.mnt] || wantDev[slot.mnt.DeviceID] {
691 // Already allocated a replica to this
692 // backend device, possibly on a
696 if replProt < desired && slot.repl != nil && !protMnt[slot.mnt] {
697 unsafeToDelete[slot.repl.Mtime] = true
698 protMnt[slot.mnt] = true
699 replProt += slot.mnt.Replication
701 if replWant < desired && (slot.repl != nil || !slot.mnt.ReadOnly) {
703 wantSrv[slot.mnt.KeepService] = true
704 wantMnt[slot.mnt] = true
705 if slot.mnt.DeviceID != "" {
706 wantDev[slot.mnt.DeviceID] = true
708 replWant += slot.mnt.Replication
710 return replProt >= desired && replWant >= desired
713 // First try to achieve desired replication without
714 // using the same server twice.
716 for i := 0; i < len(slots) && !done; i++ {
717 if !wantSrv[slots[i].mnt.KeepService] {
722 // If that didn't suffice, do another pass without the
723 // "distinct services" restriction. (Achieving the
724 // desired volume replication on fewer than the
725 // desired number of services is better than
726 // underreplicating.)
727 for i := 0; i < len(slots) && !done; i++ {
731 if !underreplicated {
733 for _, slot := range slots {
734 if slot.repl == nil || !bal.mountsByClass[class][slot.mnt] {
737 if safe += slot.mnt.Replication; safe >= desired {
741 underreplicated = safe < desired
744 // set the unachievable flag if there aren't enough
745 // slots offering the relevant storage class. (This is
746 // as easy as checking slots[desired] because we
747 // already sorted the qualifying slots to the front.)
748 if desired >= len(slots) || !bal.mountsByClass[class][slots[desired].mnt] {
749 cs := classState[class]
750 cs.unachievable = true
751 classState[class] = cs
754 // Avoid deleting wanted replicas from devices that
755 // are mounted on multiple servers -- even if they
756 // haven't already been added to unsafeToDelete
757 // because the servers report different Mtimes.
758 for _, slot := range slots {
759 if slot.repl != nil && wantDev[slot.mnt.DeviceID] {
760 unsafeToDelete[slot.repl.Mtime] = true
765 // TODO: If multiple replicas are trashable, prefer the oldest
766 // replica that doesn't have a timestamp collision with
769 countedDev := map[string]bool{}
771 for _, slot := range slots {
772 if countedDev[slot.mnt.DeviceID] {
776 want += slot.mnt.Replication
778 if slot.repl != nil {
779 have += slot.mnt.Replication
781 if slot.mnt.DeviceID != "" {
782 countedDev[slot.mnt.DeviceID] = true
787 for _, slot := range slots {
788 // TODO: request a Touch if Mtime is duplicated.
791 case !underreplicated && !slot.want && slot.repl != nil && slot.repl.Mtime < bal.MinMtime && !unsafeToDelete[slot.repl.Mtime]:
792 slot.mnt.KeepService.AddTrash(Trash{
794 Mtime: slot.repl.Mtime,
798 case len(blk.Replicas) > 0 && slot.repl == nil && slot.want && !slot.mnt.ReadOnly:
799 slot.mnt.KeepService.AddPull(Pull{
801 From: blk.Replicas[0].KeepMount.KeepService,
805 case slot.repl != nil:
810 if bal.Dumper != nil {
812 if slot.repl != nil {
813 mtime = slot.repl.Mtime
815 srv := slot.mnt.KeepService
816 changes = append(changes, fmt.Sprintf("%s:%d/%s=%s,%d", srv.ServiceHost, srv.ServicePort, slot.mnt.UUID, changeName[change], mtime))
819 if bal.Dumper != nil {
820 bal.Dumper.Printf("%s refs=%d have=%d want=%v %v %v", blkid, blk.RefCount, have, want, blk.Desired, changes)
822 return balanceResult{
827 classState: classState,
831 type blocksNBytes struct {
837 func (bb blocksNBytes) String() string {
838 return fmt.Sprintf("%d replicas (%d blocks, %d bytes)", bb.replicas, bb.blocks, bb.bytes)
841 type balancerStats struct {
846 underrep blocksNBytes
847 unachievable blocksNBytes
848 justright blocksNBytes
854 classStats map[string]replicationStats
856 // collectionBytes / collectionBlockBytes = deduplication ratio
857 collectionBytes int64 // sum(bytes in referenced blocks) across all collections
858 collectionBlockBytes int64 // sum(block size) across all blocks referenced by collections
859 collectionBlockRefs int64 // sum(number of blocks referenced) across all collections
860 collectionBlocks int64 // number of blocks referenced by any collection
863 func (s *balancerStats) dedupByteRatio() float64 {
864 if s.collectionBlockBytes == 0 {
867 return float64(s.collectionBytes) / float64(s.collectionBlockBytes)
870 func (s *balancerStats) dedupBlockRatio() float64 {
871 if s.collectionBlocks == 0 {
874 return float64(s.collectionBlockRefs) / float64(s.collectionBlocks)
877 type replicationStats struct {
881 unachievable blocksNBytes
884 type balancedBlockState struct {
890 func (bal *Balancer) collectStatistics(results <-chan balanceResult) {
892 s.replHistogram = make([]int, 2)
893 s.classStats = make(map[string]replicationStats, len(bal.classes))
894 for result := range results {
895 surplus := result.have - result.want
896 bytes := result.blkid.Size()
898 if rc := int64(result.blk.RefCount); rc > 0 {
899 s.collectionBytes += rc * bytes
900 s.collectionBlockBytes += bytes
901 s.collectionBlockRefs += rc
905 for class, state := range result.classState {
906 cs := s.classStats[class]
907 if state.unachievable {
908 cs.unachievable.blocks++
909 cs.unachievable.bytes += bytes
911 if state.desired > 0 {
912 cs.desired.replicas += state.desired
914 cs.desired.bytes += bytes * int64(state.desired)
916 if state.surplus > 0 {
917 cs.surplus.replicas += state.surplus
919 cs.surplus.bytes += bytes * int64(state.surplus)
920 } else if state.surplus < 0 {
921 cs.short.replicas += -state.surplus
923 cs.short.bytes += bytes * int64(-state.surplus)
925 s.classStats[class] = cs
929 case result.have == 0 && result.want > 0:
930 s.lost.replicas -= surplus
932 s.lost.bytes += bytes * int64(-surplus)
933 fmt.Fprintf(bal.lostBlocks, "%s", strings.SplitN(string(result.blkid), "+", 2)[0])
934 for pdh := range result.blk.Refs {
935 fmt.Fprintf(bal.lostBlocks, " %s", pdh)
937 fmt.Fprint(bal.lostBlocks, "\n")
939 s.underrep.replicas -= surplus
941 s.underrep.bytes += bytes * int64(-surplus)
942 case surplus > 0 && result.want == 0:
943 counter := &s.garbage
944 for _, r := range result.blk.Replicas {
945 if r.Mtime >= bal.MinMtime {
950 counter.replicas += surplus
952 counter.bytes += bytes * int64(surplus)
954 s.overrep.replicas += surplus
956 s.overrep.bytes += bytes * int64(result.have-result.want)
958 s.justright.replicas += result.want
960 s.justright.bytes += bytes * int64(result.want)
964 s.desired.replicas += result.want
966 s.desired.bytes += bytes * int64(result.want)
969 s.current.replicas += result.have
971 s.current.bytes += bytes * int64(result.have)
974 for len(s.replHistogram) <= result.have {
975 s.replHistogram = append(s.replHistogram, 0)
977 s.replHistogram[result.have]++
979 for _, srv := range bal.KeepServices {
980 s.pulls += len(srv.ChangeSet.Pulls)
981 s.trashes += len(srv.ChangeSet.Trashes)
984 bal.Metrics.UpdateStats(s)
987 // PrintStatistics writes statistics about the computed changes to
988 // bal.Logger. It should not be called until ComputeChangeSets has
990 func (bal *Balancer) PrintStatistics() {
992 bal.logf("%s lost (0=have<want)", bal.stats.lost)
993 bal.logf("%s underreplicated (0<have<want)", bal.stats.underrep)
994 bal.logf("%s just right (have=want)", bal.stats.justright)
995 bal.logf("%s overreplicated (have>want>0)", bal.stats.overrep)
996 bal.logf("%s unreferenced (have>want=0, new)", bal.stats.unref)
997 bal.logf("%s garbage (have>want=0, old)", bal.stats.garbage)
998 for _, class := range bal.classes {
999 cs := bal.stats.classStats[class]
1001 bal.logf("storage class %q: %s desired", class, cs.desired)
1002 bal.logf("storage class %q: %s short", class, cs.short)
1003 bal.logf("storage class %q: %s surplus", class, cs.surplus)
1004 bal.logf("storage class %q: %s unachievable", class, cs.unachievable)
1007 bal.logf("%s total commitment (excluding unreferenced)", bal.stats.desired)
1008 bal.logf("%s total usage", bal.stats.current)
1010 for _, srv := range bal.KeepServices {
1011 bal.logf("%s: %v\n", srv, srv.ChangeSet)
1014 bal.printHistogram(60)
1018 func (bal *Balancer) printHistogram(hashColumns int) {
1019 bal.logf("Replication level distribution (counting N replicas on a single server as N):")
1021 for _, count := range bal.stats.replHistogram {
1022 if maxCount < count {
1026 hashes := strings.Repeat("#", hashColumns)
1027 countWidth := 1 + int(math.Log10(float64(maxCount+1)))
1028 scaleCount := 10 * float64(hashColumns) / math.Floor(1+10*math.Log10(float64(maxCount+1)))
1029 for repl, count := range bal.stats.replHistogram {
1030 nHashes := int(scaleCount * math.Log10(float64(count+1)))
1031 bal.logf("%2d: %*d %s", repl, countWidth, count, hashes[:nHashes])
1035 // CheckSanityLate checks for configuration and runtime errors after
1036 // GetCurrentState() and ComputeChangeSets() have finished.
1038 // If it returns an error, it is dangerous to run any Commit methods.
1039 func (bal *Balancer) CheckSanityLate() error {
1040 if bal.errors != nil {
1041 for _, err := range bal.errors {
1042 bal.logf("deferred error: %v", err)
1044 return fmt.Errorf("cannot proceed safely after deferred errors")
1047 if bal.collScanned == 0 {
1048 return fmt.Errorf("received zero collections")
1052 bal.BlockStateMap.Apply(func(_ arvados.SizedDigest, blk *BlockState) {
1053 for _, desired := range blk.Desired {
1061 return fmt.Errorf("zero blocks have desired replication>0")
1064 if dr := bal.DefaultReplication; dr < 1 {
1065 return fmt.Errorf("Default replication (%d) is less than 1", dr)
1068 // TODO: no two services have identical indexes
1069 // TODO: no collisions (same md5, different size)
1073 // CommitPulls sends the computed lists of pull requests to the
1074 // keepstore servers. This has the effect of increasing replication of
1075 // existing blocks that are either underreplicated or poorly
1076 // distributed according to rendezvous hashing.
1077 func (bal *Balancer) CommitPulls(c *arvados.Client) error {
1078 defer bal.time("send_pull_lists", "wall clock time to send pull lists")()
1079 return bal.commitAsync(c, "send pull list",
1080 func(srv *KeepService) error {
1081 return srv.CommitPulls(c)
1085 // CommitTrash sends the computed lists of trash requests to the
1086 // keepstore servers. This has the effect of deleting blocks that are
1087 // overreplicated or unreferenced.
1088 func (bal *Balancer) CommitTrash(c *arvados.Client) error {
1089 defer bal.time("send_trash_lists", "wall clock time to send trash lists")()
1090 return bal.commitAsync(c, "send trash list",
1091 func(srv *KeepService) error {
1092 return srv.CommitTrash(c)
1096 func (bal *Balancer) commitAsync(c *arvados.Client, label string, f func(srv *KeepService) error) error {
1097 errs := make(chan error)
1098 for _, srv := range bal.KeepServices {
1099 go func(srv *KeepService) {
1101 defer func() { errs <- err }()
1102 label := fmt.Sprintf("%s: %v", srv, label)
1105 err = fmt.Errorf("%s: %v", label, err)
1110 for range bal.KeepServices {
1111 if err := <-errs; err != nil {
1120 func (bal *Balancer) logf(f string, args ...interface{}) {
1121 if bal.Logger != nil {
1122 bal.Logger.Printf(f, args...)
1126 func (bal *Balancer) time(name, help string) func() {
1127 observer := bal.Metrics.DurationObserver(name+"_seconds", help)
1129 bal.Logger.Printf("%s: start", name)
1131 dur := time.Since(t0)
1132 observer.Observe(dur.Seconds())
1133 bal.Logger.Printf("%s: took %vs", name, dur.Seconds())
1137 // Rendezvous hash sort function. Less efficient than sorting on
1138 // precomputed rendezvous hashes, but also rarely used.
1139 func rendezvousLess(i, j string, blkid arvados.SizedDigest) bool {
1140 a := md5.Sum([]byte(string(blkid[:32]) + i))
1141 b := md5.Sum([]byte(string(blkid[:32]) + j))
1142 return bytes.Compare(a[:], b[:]) < 0