1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.curoverse.com/arvados.git/sdk/go/arvados"
20 "git.curoverse.com/arvados.git/sdk/go/keepclient"
21 "github.com/sirupsen/logrus"
24 // Balancer compares the contents of keepstore servers with the
25 // collections stored in Arvados, and issues pull/trash requests
26 // needed to get (closer to) the optimal data layout.
28 // In the optimal data layout: every data block referenced by a
29 // collection is replicated at least as many times as desired by the
30 // collection; there are no unreferenced data blocks older than
31 // BlobSignatureTTL; and all N existing replicas of a given data block
32 // are in the N best positions in rendezvous probe order.
33 type Balancer struct {
34 Logger logrus.FieldLogger
35 Dumper logrus.FieldLogger
39 KeepServices map[string]*KeepService
40 DefaultReplication int
45 mountsByClass map[string]map[*KeepMount]bool
47 serviceRoots map[string]string
53 // Run performs a balance operation using the given config and
54 // runOptions, and returns RunOptions suitable for passing to a
55 // subsequent balance operation.
57 // Run should only be called once on a given Balancer object.
61 // runOptions, err = (&Balancer{}).Run(config, runOptions)
62 func (bal *Balancer) Run(config Config, runOptions RunOptions) (nextRunOptions RunOptions, err error) {
63 nextRunOptions = runOptions
65 defer bal.time("sweep", "wall clock time to run one full sweep")()
67 if len(config.KeepServiceList.Items) > 0 {
68 err = bal.SetKeepServices(config.KeepServiceList)
70 err = bal.DiscoverKeepServices(&config.Client, config.KeepServiceTypes)
76 for _, srv := range bal.KeepServices {
77 err = srv.discoverMounts(&config.Client)
84 if err = bal.CheckSanityEarly(&config.Client); err != nil {
87 rs := bal.rendezvousState()
88 if runOptions.CommitTrash && rs != runOptions.SafeRendezvousState {
89 if runOptions.SafeRendezvousState != "" {
90 bal.logf("notice: KeepServices list has changed since last run")
92 bal.logf("clearing existing trash lists, in case the new rendezvous order differs from previous run")
93 if err = bal.ClearTrashLists(&config.Client); err != nil {
96 // The current rendezvous state becomes "safe" (i.e.,
97 // OK to compute changes for that state without
98 // clearing existing trash lists) only now, after we
99 // succeed in clearing existing trash lists.
100 nextRunOptions.SafeRendezvousState = rs
102 if err = bal.GetCurrentState(&config.Client, config.CollectionBatchSize, config.CollectionBuffers); err != nil {
105 bal.ComputeChangeSets()
106 bal.PrintStatistics()
107 if err = bal.CheckSanityLate(); err != nil {
110 if runOptions.CommitPulls {
111 err = bal.CommitPulls(&config.Client)
113 // Skip trash if we can't pull. (Too cautious?)
117 if runOptions.CommitTrash {
118 err = bal.CommitTrash(&config.Client)
123 // SetKeepServices sets the list of KeepServices to operate on.
124 func (bal *Balancer) SetKeepServices(srvList arvados.KeepServiceList) error {
125 bal.KeepServices = make(map[string]*KeepService)
126 for _, srv := range srvList.Items {
127 bal.KeepServices[srv.UUID] = &KeepService{
129 ChangeSet: &ChangeSet{},
135 // DiscoverKeepServices sets the list of KeepServices by calling the
136 // API to get a list of all services, and selecting the ones whose
137 // ServiceType is in okTypes.
138 func (bal *Balancer) DiscoverKeepServices(c *arvados.Client, okTypes []string) error {
139 bal.KeepServices = make(map[string]*KeepService)
140 ok := make(map[string]bool)
141 for _, t := range okTypes {
144 return c.EachKeepService(func(srv arvados.KeepService) error {
145 if ok[srv.ServiceType] {
146 bal.KeepServices[srv.UUID] = &KeepService{
148 ChangeSet: &ChangeSet{},
151 bal.logf("skipping %v with service type %q", srv.UUID, srv.ServiceType)
157 func (bal *Balancer) cleanupMounts() {
158 rwdev := map[string]*KeepService{}
159 for _, srv := range bal.KeepServices {
160 for _, mnt := range srv.mounts {
161 if !mnt.ReadOnly && mnt.DeviceID != "" {
162 rwdev[mnt.DeviceID] = srv
166 // Drop the readonly mounts whose device is mounted RW
168 for _, srv := range bal.KeepServices {
169 var dedup []*KeepMount
170 for _, mnt := range srv.mounts {
171 if mnt.ReadOnly && rwdev[mnt.DeviceID] != nil {
172 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])
174 dedup = append(dedup, mnt)
179 for _, srv := range bal.KeepServices {
180 for _, mnt := range srv.mounts {
181 if mnt.Replication <= 0 {
182 log.Printf("%s: mount %s reports replication=%d, using replication=1", srv, mnt.UUID, mnt.Replication)
189 // CheckSanityEarly checks for configuration and runtime errors that
190 // can be detected before GetCurrentState() and ComputeChangeSets()
193 // If it returns an error, it is pointless to run GetCurrentState or
194 // ComputeChangeSets: after doing so, the statistics would be
195 // meaningless and it would be dangerous to run any Commit methods.
196 func (bal *Balancer) CheckSanityEarly(c *arvados.Client) error {
197 u, err := c.CurrentUser()
199 return fmt.Errorf("CurrentUser(): %v", err)
201 if !u.IsActive || !u.IsAdmin {
202 return fmt.Errorf("current user (%s) is not an active admin user", u.UUID)
204 for _, srv := range bal.KeepServices {
205 if srv.ServiceType == "proxy" {
206 return fmt.Errorf("config error: %s: proxy servers cannot be balanced", srv)
210 var checkPage arvados.CollectionList
211 if err = c.RequestAndDecode(&checkPage, "GET", "arvados/v1/collections", nil, arvados.ResourceListParams{
215 IncludeOldVersions: true,
216 Filters: []arvados.Filter{{
223 } else if n := checkPage.ItemsAvailable; n > 0 {
224 return fmt.Errorf("%d collections exist with null modified_at; cannot fetch reliably", n)
230 // rendezvousState returns a fingerprint (e.g., a sorted list of
231 // UUID+host+port) of the current set of keep services.
232 func (bal *Balancer) rendezvousState() string {
233 srvs := make([]string, 0, len(bal.KeepServices))
234 for _, srv := range bal.KeepServices {
235 srvs = append(srvs, srv.String())
238 return strings.Join(srvs, "; ")
241 // ClearTrashLists sends an empty trash list to each keep
242 // service. Calling this before GetCurrentState avoids races.
244 // When a block appears in an index, we assume that replica will still
245 // exist after we delete other replicas on other servers. However,
246 // it's possible that a previous rebalancing operation made different
247 // decisions (e.g., servers were added/removed, and rendezvous order
248 // changed). In this case, the replica might already be on that
249 // server's trash list, and it might be deleted before we send a
250 // replacement trash list.
252 // We avoid this problem if we clear all trash lists before getting
253 // indexes. (We also assume there is only one rebalancing process
254 // running at a time.)
255 func (bal *Balancer) ClearTrashLists(c *arvados.Client) error {
256 for _, srv := range bal.KeepServices {
257 srv.ChangeSet = &ChangeSet{}
259 return bal.CommitTrash(c)
262 // GetCurrentState determines the current replication state, and the
263 // desired replication level, for every block that is either
264 // retrievable or referenced.
266 // It determines the current replication state by reading the block index
267 // from every known Keep service.
269 // It determines the desired replication level by retrieving all
270 // collection manifests in the database (API server).
272 // It encodes the resulting information in BlockStateMap.
273 func (bal *Balancer) GetCurrentState(c *arvados.Client, pageSize, bufs int) error {
274 defer bal.time("get_state", "wall clock time to get current state")()
275 bal.BlockStateMap = NewBlockStateMap()
277 dd, err := c.DiscoveryDocument()
281 bal.DefaultReplication = dd.DefaultCollectionReplication
282 bal.MinMtime = time.Now().UnixNano() - dd.BlobSignatureTTL*1e9
284 errs := make(chan error, 1)
285 wg := sync.WaitGroup{}
287 // When a device is mounted more than once, we will get its
288 // index only once, and call AddReplicas on all of the mounts.
289 // equivMount keys are the mounts that will be indexed, and
290 // each value is a list of mounts to apply the received index
292 equivMount := map[*KeepMount][]*KeepMount{}
293 // deviceMount maps each device ID to the one mount that will
294 // be indexed for that device.
295 deviceMount := map[string]*KeepMount{}
296 for _, srv := range bal.KeepServices {
297 for _, mnt := range srv.mounts {
298 equiv := deviceMount[mnt.DeviceID]
301 if mnt.DeviceID != "" {
302 deviceMount[mnt.DeviceID] = equiv
305 equivMount[equiv] = append(equivMount[equiv], mnt)
309 // Start one goroutine for each (non-redundant) mount:
310 // retrieve the index, and add the returned blocks to
312 for _, mounts := range equivMount {
314 go func(mounts []*KeepMount) {
316 bal.logf("mount %s: retrieve index from %s", mounts[0], mounts[0].KeepService)
317 idx, err := mounts[0].KeepService.IndexMount(c, mounts[0].UUID, "")
320 case errs <- fmt.Errorf("%s: retrieve index: %v", mounts[0], err):
326 // Some other goroutine encountered an
327 // error -- any further effort here
331 for _, mount := range mounts {
332 bal.logf("%s: add %d entries to map", mount, len(idx))
333 bal.BlockStateMap.AddReplicas(mount, idx)
334 bal.logf("%s: added %d entries to map at %dx (%d replicas)", mount, len(idx), mount.Replication, len(idx)*mount.Replication)
336 bal.logf("mount %s: index done", mounts[0])
340 // collQ buffers incoming collections so we can start fetching
341 // the next page without waiting for the current page to
342 // finish processing.
343 collQ := make(chan arvados.Collection, bufs)
345 // Start a goroutine to process collections. (We could use a
346 // worker pool here, but even with a single worker we already
347 // process collections much faster than we can retrieve them.)
351 for coll := range collQ {
352 err := bal.addCollection(coll)
353 if err != nil || len(errs) > 0 {
366 // Start a goroutine to retrieve all collections from the
367 // Arvados database and send them to collQ for processing.
371 err = EachCollection(c, pageSize,
372 func(coll arvados.Collection) error {
375 // some other GetCurrentState
376 // error happened: no point
379 return fmt.Errorf("")
382 }, func(done, total int) {
383 bal.logf("collections: %d/%d", done, total)
401 func (bal *Balancer) addCollection(coll arvados.Collection) error {
402 blkids, err := coll.SizedDigests()
404 return fmt.Errorf("%v: %v", coll.UUID, err)
406 repl := bal.DefaultReplication
407 if coll.ReplicationDesired != nil {
408 repl = *coll.ReplicationDesired
410 debugf("%v: %d block x%d", coll.UUID, len(blkids), repl)
411 bal.BlockStateMap.IncreaseDesired(coll.StorageClassesDesired, repl, blkids)
415 // ComputeChangeSets compares, for each known block, the current and
416 // desired replication states. If it is possible to get closer to the
417 // desired state by copying or deleting blocks, it adds those changes
418 // to the relevant KeepServices' ChangeSets.
420 // It does not actually apply any of the computed changes.
421 func (bal *Balancer) ComputeChangeSets() {
422 // This just calls balanceBlock() once for each block, using a
423 // pool of worker goroutines.
424 defer bal.time("changeset_compute", "wall clock time to compute changesets")()
425 bal.setupLookupTables()
427 type balanceTask struct {
428 blkid arvados.SizedDigest
431 workers := runtime.GOMAXPROCS(-1)
432 todo := make(chan balanceTask, workers)
434 bal.BlockStateMap.Apply(func(blkid arvados.SizedDigest, blk *BlockState) {
442 results := make(chan balanceResult, workers)
444 var wg sync.WaitGroup
445 for i := 0; i < workers; i++ {
448 for work := range todo {
449 results <- bal.balanceBlock(work.blkid, work.blk)
457 bal.collectStatistics(results)
460 func (bal *Balancer) setupLookupTables() {
461 bal.serviceRoots = make(map[string]string)
462 bal.classes = defaultClasses
463 bal.mountsByClass = map[string]map[*KeepMount]bool{"default": {}}
465 for _, srv := range bal.KeepServices {
466 bal.serviceRoots[srv.UUID] = srv.UUID
467 for _, mnt := range srv.mounts {
470 // All mounts on a read-only service are
471 // effectively read-only.
472 mnt.ReadOnly = mnt.ReadOnly || srv.ReadOnly
474 if len(mnt.StorageClasses) == 0 {
475 bal.mountsByClass["default"][mnt] = true
478 for _, class := range mnt.StorageClasses {
479 if mbc := bal.mountsByClass[class]; mbc == nil {
480 bal.classes = append(bal.classes, class)
481 bal.mountsByClass[class] = map[*KeepMount]bool{mnt: true}
488 // Consider classes in lexicographic order to avoid flapping
489 // between balancing runs. The outcome of the "prefer a mount
490 // we're already planning to use for a different storage
491 // class" case in balanceBlock depends on the order classes
493 sort.Strings(bal.classes)
503 var changeName = map[int]string{
506 changeTrash: "trash",
510 type balanceResult struct {
512 blkid arvados.SizedDigest
515 classState map[string]balancedBlockState
518 // balanceBlock compares current state to desired state for a single
519 // block, and makes the appropriate ChangeSet calls.
520 func (bal *Balancer) balanceBlock(blkid arvados.SizedDigest, blk *BlockState) balanceResult {
521 debugf("balanceBlock: %v %+v", blkid, blk)
524 mnt *KeepMount // never nil
525 repl *Replica // replica already stored here (or nil)
526 want bool // we should pull/leave a replica here
529 // Build a list of all slots (one per mounted volume).
530 slots := make([]slot, 0, bal.mounts)
531 for _, srv := range bal.KeepServices {
532 for _, mnt := range srv.mounts {
534 for r := range blk.Replicas {
535 if blk.Replicas[r].KeepMount == mnt {
536 repl = &blk.Replicas[r]
539 // Initial value of "want" is "have, and can't
540 // delete". These untrashable replicas get
541 // prioritized when sorting slots: otherwise,
542 // non-optimal readonly copies would cause us
544 slots = append(slots, slot{
547 want: repl != nil && mnt.ReadOnly,
552 uuids := keepclient.NewRootSorter(bal.serviceRoots, string(blkid[:32])).GetSortedRoots()
553 srvRendezvous := make(map[*KeepService]int, len(uuids))
554 for i, uuid := range uuids {
555 srv := bal.KeepServices[uuid]
556 srvRendezvous[srv] = i
559 // Below we set underreplicated=true if we find any storage
560 // class that's currently underreplicated -- in that case we
561 // won't want to trash any replicas.
562 underreplicated := false
564 classState := make(map[string]balancedBlockState, len(bal.classes))
565 unsafeToDelete := make(map[int64]bool, len(slots))
566 for _, class := range bal.classes {
567 desired := blk.Desired[class]
569 countedDev := map[string]bool{}
571 for _, slot := range slots {
572 if slot.repl != nil && bal.mountsByClass[class][slot.mnt] && !countedDev[slot.mnt.DeviceID] {
573 have += slot.mnt.Replication
574 if slot.mnt.DeviceID != "" {
575 countedDev[slot.mnt.DeviceID] = true
579 classState[class] = balancedBlockState{
581 surplus: have - desired,
588 // Sort the slots by desirability.
589 sort.Slice(slots, func(i, j int) bool {
590 si, sj := slots[i], slots[j]
591 if classi, classj := bal.mountsByClass[class][si.mnt], bal.mountsByClass[class][sj.mnt]; classi != classj {
592 // Prefer a mount that satisfies the
594 return bal.mountsByClass[class][si.mnt]
595 } else if si.want != sj.want {
596 // Prefer a mount that will have a
597 // replica no matter what we do here
598 // -- either because it already has an
599 // untrashable replica, or because we
600 // already need it to satisfy a
601 // different storage class.
603 } else if orderi, orderj := srvRendezvous[si.mnt.KeepService], srvRendezvous[sj.mnt.KeepService]; orderi != orderj {
604 // Prefer a better rendezvous
606 return orderi < orderj
607 } else if repli, replj := si.repl != nil, sj.repl != nil; repli != replj {
608 // Prefer a mount that already has a
612 // If pull/trash turns out to be
613 // needed, distribute the
614 // new/remaining replicas uniformly
615 // across qualifying mounts on a given
617 return rendezvousLess(si.mnt.DeviceID, sj.mnt.DeviceID, blkid)
621 // Servers/mounts/devices (with or without existing
622 // replicas) that are part of the best achievable
623 // layout for this storage class.
624 wantSrv := map[*KeepService]bool{}
625 wantMnt := map[*KeepMount]bool{}
626 wantDev := map[string]bool{}
627 // Positions (with existing replicas) that have been
628 // protected (via unsafeToDelete) to ensure we don't
629 // reduce replication below desired level when
630 // trashing replicas that aren't optimal positions for
631 // any storage class.
632 protMnt := map[*KeepMount]bool{}
633 // Replication planned so far (corresponds to wantMnt).
635 // Protected replication (corresponds to protMnt).
638 // trySlot tries using a slot to meet requirements,
639 // and returns true if all requirements are met.
640 trySlot := func(i int) bool {
642 if wantMnt[slot.mnt] || wantDev[slot.mnt.DeviceID] {
643 // Already allocated a replica to this
644 // backend device, possibly on a
648 if replProt < desired && slot.repl != nil && !protMnt[slot.mnt] {
649 unsafeToDelete[slot.repl.Mtime] = true
650 protMnt[slot.mnt] = true
651 replProt += slot.mnt.Replication
653 if replWant < desired && (slot.repl != nil || !slot.mnt.ReadOnly) {
655 wantSrv[slot.mnt.KeepService] = true
656 wantMnt[slot.mnt] = true
657 if slot.mnt.DeviceID != "" {
658 wantDev[slot.mnt.DeviceID] = true
660 replWant += slot.mnt.Replication
662 return replProt >= desired && replWant >= desired
665 // First try to achieve desired replication without
666 // using the same server twice.
668 for i := 0; i < len(slots) && !done; i++ {
669 if !wantSrv[slots[i].mnt.KeepService] {
674 // If that didn't suffice, do another pass without the
675 // "distinct services" restriction. (Achieving the
676 // desired volume replication on fewer than the
677 // desired number of services is better than
678 // underreplicating.)
679 for i := 0; i < len(slots) && !done; i++ {
683 if !underreplicated {
685 for _, slot := range slots {
686 if slot.repl == nil || !bal.mountsByClass[class][slot.mnt] {
689 if safe += slot.mnt.Replication; safe >= desired {
693 underreplicated = safe < desired
696 // set the unachievable flag if there aren't enough
697 // slots offering the relevant storage class. (This is
698 // as easy as checking slots[desired] because we
699 // already sorted the qualifying slots to the front.)
700 if desired >= len(slots) || !bal.mountsByClass[class][slots[desired].mnt] {
701 cs := classState[class]
702 cs.unachievable = true
703 classState[class] = cs
706 // Avoid deleting wanted replicas from devices that
707 // are mounted on multiple servers -- even if they
708 // haven't already been added to unsafeToDelete
709 // because the servers report different Mtimes.
710 for _, slot := range slots {
711 if slot.repl != nil && wantDev[slot.mnt.DeviceID] {
712 unsafeToDelete[slot.repl.Mtime] = true
717 // TODO: If multiple replicas are trashable, prefer the oldest
718 // replica that doesn't have a timestamp collision with
721 countedDev := map[string]bool{}
723 for _, slot := range slots {
724 if countedDev[slot.mnt.DeviceID] {
728 want += slot.mnt.Replication
730 if slot.repl != nil {
731 have += slot.mnt.Replication
733 if slot.mnt.DeviceID != "" {
734 countedDev[slot.mnt.DeviceID] = true
739 for _, slot := range slots {
740 // TODO: request a Touch if Mtime is duplicated.
743 case !underreplicated && !slot.want && slot.repl != nil && slot.repl.Mtime < bal.MinMtime && !unsafeToDelete[slot.repl.Mtime]:
744 slot.mnt.KeepService.AddTrash(Trash{
746 Mtime: slot.repl.Mtime,
750 case len(blk.Replicas) > 0 && slot.repl == nil && slot.want && !slot.mnt.ReadOnly:
751 slot.mnt.KeepService.AddPull(Pull{
753 From: blk.Replicas[0].KeepMount.KeepService,
757 case slot.repl != nil:
762 if bal.Dumper != nil {
764 if slot.repl != nil {
765 mtime = slot.repl.Mtime
767 srv := slot.mnt.KeepService
768 changes = append(changes, fmt.Sprintf("%s:%d/%s=%s,%d", srv.ServiceHost, srv.ServicePort, slot.mnt.UUID, changeName[change], mtime))
771 if bal.Dumper != nil {
772 bal.Dumper.Printf("%s refs=%d have=%d want=%v %v %v", blkid, blk.RefCount, have, want, blk.Desired, changes)
774 return balanceResult{
779 classState: classState,
783 type blocksNBytes struct {
789 func (bb blocksNBytes) String() string {
790 return fmt.Sprintf("%d replicas (%d blocks, %d bytes)", bb.replicas, bb.blocks, bb.bytes)
793 type balancerStats struct {
798 underrep blocksNBytes
799 unachievable blocksNBytes
800 justright blocksNBytes
806 classStats map[string]replicationStats
808 // collectionBytes / collectionBlockBytes = deduplication ratio
809 collectionBytes int64 // sum(bytes in referenced blocks) across all collections
810 collectionBlockBytes int64 // sum(block size) across all blocks referenced by collections
811 collectionBlockRefs int64 // sum(number of blocks referenced) across all collections
812 collectionBlocks int64 // number of blocks referenced by any collection
815 func (s *balancerStats) dedupByteRatio() float64 {
816 if s.collectionBlockBytes == 0 {
819 return float64(s.collectionBytes) / float64(s.collectionBlockBytes)
822 func (s *balancerStats) dedupBlockRatio() float64 {
823 if s.collectionBlocks == 0 {
826 return float64(s.collectionBlockRefs) / float64(s.collectionBlocks)
829 type replicationStats struct {
833 unachievable blocksNBytes
836 type balancedBlockState struct {
842 func (bal *Balancer) collectStatistics(results <-chan balanceResult) {
844 s.replHistogram = make([]int, 2)
845 s.classStats = make(map[string]replicationStats, len(bal.classes))
846 for result := range results {
847 surplus := result.have - result.want
848 bytes := result.blkid.Size()
850 if rc := int64(result.blk.RefCount); rc > 0 {
851 s.collectionBytes += rc * bytes
852 s.collectionBlockBytes += bytes
853 s.collectionBlockRefs += rc
857 for class, state := range result.classState {
858 cs := s.classStats[class]
859 if state.unachievable {
860 cs.unachievable.blocks++
861 cs.unachievable.bytes += bytes
863 if state.desired > 0 {
864 cs.desired.replicas += state.desired
866 cs.desired.bytes += bytes * int64(state.desired)
868 if state.surplus > 0 {
869 cs.surplus.replicas += state.surplus
871 cs.surplus.bytes += bytes * int64(state.surplus)
872 } else if state.surplus < 0 {
873 cs.short.replicas += -state.surplus
875 cs.short.bytes += bytes * int64(-state.surplus)
877 s.classStats[class] = cs
881 case result.have == 0 && result.want > 0:
882 s.lost.replicas -= surplus
884 s.lost.bytes += bytes * int64(-surplus)
886 s.underrep.replicas -= surplus
888 s.underrep.bytes += bytes * int64(-surplus)
889 case surplus > 0 && result.want == 0:
890 counter := &s.garbage
891 for _, r := range result.blk.Replicas {
892 if r.Mtime >= bal.MinMtime {
897 counter.replicas += surplus
899 counter.bytes += bytes * int64(surplus)
901 s.overrep.replicas += surplus
903 s.overrep.bytes += bytes * int64(result.have-result.want)
905 s.justright.replicas += result.want
907 s.justright.bytes += bytes * int64(result.want)
911 s.desired.replicas += result.want
913 s.desired.bytes += bytes * int64(result.want)
916 s.current.replicas += result.have
918 s.current.bytes += bytes * int64(result.have)
921 for len(s.replHistogram) <= result.have {
922 s.replHistogram = append(s.replHistogram, 0)
924 s.replHistogram[result.have]++
926 for _, srv := range bal.KeepServices {
927 s.pulls += len(srv.ChangeSet.Pulls)
928 s.trashes += len(srv.ChangeSet.Trashes)
931 bal.Metrics.UpdateStats(s)
934 // PrintStatistics writes statistics about the computed changes to
935 // bal.Logger. It should not be called until ComputeChangeSets has
937 func (bal *Balancer) PrintStatistics() {
939 bal.logf("%s lost (0=have<want)", bal.stats.lost)
940 bal.logf("%s underreplicated (0<have<want)", bal.stats.underrep)
941 bal.logf("%s just right (have=want)", bal.stats.justright)
942 bal.logf("%s overreplicated (have>want>0)", bal.stats.overrep)
943 bal.logf("%s unreferenced (have>want=0, new)", bal.stats.unref)
944 bal.logf("%s garbage (have>want=0, old)", bal.stats.garbage)
945 for _, class := range bal.classes {
946 cs := bal.stats.classStats[class]
948 bal.logf("storage class %q: %s desired", class, cs.desired)
949 bal.logf("storage class %q: %s short", class, cs.short)
950 bal.logf("storage class %q: %s surplus", class, cs.surplus)
951 bal.logf("storage class %q: %s unachievable", class, cs.unachievable)
954 bal.logf("%s total commitment (excluding unreferenced)", bal.stats.desired)
955 bal.logf("%s total usage", bal.stats.current)
957 for _, srv := range bal.KeepServices {
958 bal.logf("%s: %v\n", srv, srv.ChangeSet)
961 bal.printHistogram(60)
965 func (bal *Balancer) printHistogram(hashColumns int) {
966 bal.logf("Replication level distribution (counting N replicas on a single server as N):")
968 for _, count := range bal.stats.replHistogram {
969 if maxCount < count {
973 hashes := strings.Repeat("#", hashColumns)
974 countWidth := 1 + int(math.Log10(float64(maxCount+1)))
975 scaleCount := 10 * float64(hashColumns) / math.Floor(1+10*math.Log10(float64(maxCount+1)))
976 for repl, count := range bal.stats.replHistogram {
977 nHashes := int(scaleCount * math.Log10(float64(count+1)))
978 bal.logf("%2d: %*d %s", repl, countWidth, count, hashes[:nHashes])
982 // CheckSanityLate checks for configuration and runtime errors after
983 // GetCurrentState() and ComputeChangeSets() have finished.
985 // If it returns an error, it is dangerous to run any Commit methods.
986 func (bal *Balancer) CheckSanityLate() error {
987 if bal.errors != nil {
988 for _, err := range bal.errors {
989 bal.logf("deferred error: %v", err)
991 return fmt.Errorf("cannot proceed safely after deferred errors")
994 if bal.collScanned == 0 {
995 return fmt.Errorf("received zero collections")
999 bal.BlockStateMap.Apply(func(_ arvados.SizedDigest, blk *BlockState) {
1000 for _, desired := range blk.Desired {
1008 return fmt.Errorf("zero blocks have desired replication>0")
1011 if dr := bal.DefaultReplication; dr < 1 {
1012 return fmt.Errorf("Default replication (%d) is less than 1", dr)
1015 // TODO: no two services have identical indexes
1016 // TODO: no collisions (same md5, different size)
1020 // CommitPulls sends the computed lists of pull requests to the
1021 // keepstore servers. This has the effect of increasing replication of
1022 // existing blocks that are either underreplicated or poorly
1023 // distributed according to rendezvous hashing.
1024 func (bal *Balancer) CommitPulls(c *arvados.Client) error {
1025 defer bal.time("send_pull_lists", "wall clock time to send pull lists")()
1026 return bal.commitAsync(c, "send pull list",
1027 func(srv *KeepService) error {
1028 return srv.CommitPulls(c)
1032 // CommitTrash sends the computed lists of trash requests to the
1033 // keepstore servers. This has the effect of deleting blocks that are
1034 // overreplicated or unreferenced.
1035 func (bal *Balancer) CommitTrash(c *arvados.Client) error {
1036 defer bal.time("send_trash_lists", "wall clock time to send trash lists")()
1037 return bal.commitAsync(c, "send trash list",
1038 func(srv *KeepService) error {
1039 return srv.CommitTrash(c)
1043 func (bal *Balancer) commitAsync(c *arvados.Client, label string, f func(srv *KeepService) error) error {
1044 errs := make(chan error)
1045 for _, srv := range bal.KeepServices {
1046 go func(srv *KeepService) {
1048 defer func() { errs <- err }()
1049 label := fmt.Sprintf("%s: %v", srv, label)
1052 err = fmt.Errorf("%s: %v", label, err)
1057 for range bal.KeepServices {
1058 if err := <-errs; err != nil {
1067 func (bal *Balancer) logf(f string, args ...interface{}) {
1068 if bal.Logger != nil {
1069 bal.Logger.Printf(f, args...)
1073 func (bal *Balancer) time(name, help string) func() {
1074 observer := bal.Metrics.DurationObserver(name+"_seconds", help)
1076 bal.Logger.Printf("%s: start", name)
1078 dur := time.Since(t0)
1079 observer.Observe(dur.Seconds())
1080 bal.Logger.Printf("%s: took %vs", name, dur.Seconds())
1084 // Rendezvous hash sort function. Less efficient than sorting on
1085 // precomputed rendezvous hashes, but also rarely used.
1086 func rendezvousLess(i, j string, blkid arvados.SizedDigest) bool {
1087 a := md5.Sum([]byte(string(blkid[:32]) + i))
1088 b := md5.Sum([]byte(string(blkid[:32]) + j))
1089 return bytes.Compare(a[:], b[:]) < 0