1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/keepclient"
26 "github.com/jmoiron/sqlx"
27 "github.com/sirupsen/logrus"
30 // Balancer compares the contents of keepstore servers with the
31 // collections stored in Arvados, and issues pull/trash requests
32 // needed to get (closer to) the optimal data layout.
34 // In the optimal data layout: every data block referenced by a
35 // collection is replicated at least as many times as desired by the
36 // collection; there are no unreferenced data blocks older than
37 // BlobSignatureTTL; and all N existing replicas of a given data block
38 // are in the N best positions in rendezvous probe order.
39 type Balancer struct {
41 Logger logrus.FieldLogger
42 Dumper logrus.FieldLogger
48 KeepServices map[string]*KeepService
49 DefaultReplication int
54 mountsByClass map[string]map[*KeepMount]bool
56 serviceRoots map[string]string
63 // Run performs a balance operation using the given config and
64 // runOptions, and returns RunOptions suitable for passing to a
65 // subsequent balance operation.
67 // Run should only be called once on a given Balancer object.
71 // runOptions, err = (&Balancer{}).Run(config, runOptions)
72 func (bal *Balancer) Run(client *arvados.Client, cluster *arvados.Cluster, runOptions RunOptions) (nextRunOptions RunOptions, err error) {
73 nextRunOptions = runOptions
75 defer bal.time("sweep", "wall clock time to run one full sweep")()
77 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(cluster.Collections.BalanceTimeout.Duration()))
81 if bal.LostBlocksFile != "" {
82 tmpfn := bal.LostBlocksFile + ".tmp"
83 lbFile, err = os.OpenFile(tmpfn, os.O_CREATE|os.O_WRONLY, 0777)
88 err = syscall.Flock(int(lbFile.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
93 // Remove the tempfile only if we didn't get
94 // as far as successfully renaming it.
99 bal.lostBlocks = lbFile
101 bal.lostBlocks = ioutil.Discard
104 err = bal.DiscoverKeepServices(client)
109 for _, srv := range bal.KeepServices {
110 err = srv.discoverMounts(client)
117 if err = bal.CheckSanityEarly(client); err != nil {
121 // On a big site, indexing and sending trash/pull lists can
122 // take much longer than the usual 5 minute client
123 // timeout. From here on, we rely on the context deadline
124 // instead, aborting the entire operation if any part takes
128 rs := bal.rendezvousState()
129 if runOptions.CommitTrash && rs != runOptions.SafeRendezvousState {
130 if runOptions.SafeRendezvousState != "" {
131 bal.logf("notice: KeepServices list has changed since last run")
133 bal.logf("clearing existing trash lists, in case the new rendezvous order differs from previous run")
134 if err = bal.ClearTrashLists(ctx, client); err != nil {
137 // The current rendezvous state becomes "safe" (i.e.,
138 // OK to compute changes for that state without
139 // clearing existing trash lists) only now, after we
140 // succeed in clearing existing trash lists.
141 nextRunOptions.SafeRendezvousState = rs
144 if err = bal.GetCurrentState(ctx, client, cluster.Collections.BalanceCollectionBatch, cluster.Collections.BalanceCollectionBuffers); err != nil {
147 bal.ComputeChangeSets()
148 bal.PrintStatistics()
149 if err = bal.CheckSanityLate(); err != nil {
157 err = os.Rename(bal.LostBlocksFile+".tmp", bal.LostBlocksFile)
163 if runOptions.CommitPulls {
164 err = bal.CommitPulls(ctx, client)
166 // Skip trash if we can't pull. (Too cautious?)
170 if runOptions.CommitTrash {
171 err = bal.CommitTrash(ctx, client)
176 err = bal.updateCollections(ctx, client, cluster)
180 // SetKeepServices sets the list of KeepServices to operate on.
181 func (bal *Balancer) SetKeepServices(srvList arvados.KeepServiceList) error {
182 bal.KeepServices = make(map[string]*KeepService)
183 for _, srv := range srvList.Items {
184 bal.KeepServices[srv.UUID] = &KeepService{
186 ChangeSet: &ChangeSet{},
192 // DiscoverKeepServices sets the list of KeepServices by calling the
193 // API to get a list of all services, and selecting the ones whose
194 // ServiceType is "disk"
195 func (bal *Balancer) DiscoverKeepServices(c *arvados.Client) error {
196 bal.KeepServices = make(map[string]*KeepService)
197 return c.EachKeepService(func(srv arvados.KeepService) error {
198 if srv.ServiceType == "disk" {
199 bal.KeepServices[srv.UUID] = &KeepService{
201 ChangeSet: &ChangeSet{},
204 bal.logf("skipping %v with service type %q", srv.UUID, srv.ServiceType)
210 func (bal *Balancer) cleanupMounts() {
211 rwdev := map[string]*KeepService{}
212 for _, srv := range bal.KeepServices {
213 for _, mnt := range srv.mounts {
214 if !mnt.ReadOnly && mnt.DeviceID != "" {
215 rwdev[mnt.DeviceID] = srv
219 // Drop the readonly mounts whose device is mounted RW
221 for _, srv := range bal.KeepServices {
222 var dedup []*KeepMount
223 for _, mnt := range srv.mounts {
224 if mnt.ReadOnly && rwdev[mnt.DeviceID] != nil {
225 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])
227 dedup = append(dedup, mnt)
232 for _, srv := range bal.KeepServices {
233 for _, mnt := range srv.mounts {
234 if mnt.Replication <= 0 {
235 log.Printf("%s: mount %s reports replication=%d, using replication=1", srv, mnt.UUID, mnt.Replication)
242 // CheckSanityEarly checks for configuration and runtime errors that
243 // can be detected before GetCurrentState() and ComputeChangeSets()
246 // If it returns an error, it is pointless to run GetCurrentState or
247 // ComputeChangeSets: after doing so, the statistics would be
248 // meaningless and it would be dangerous to run any Commit methods.
249 func (bal *Balancer) CheckSanityEarly(c *arvados.Client) error {
250 u, err := c.CurrentUser()
252 return fmt.Errorf("CurrentUser(): %v", err)
254 if !u.IsActive || !u.IsAdmin {
255 return fmt.Errorf("current user (%s) is not an active admin user", u.UUID)
257 for _, srv := range bal.KeepServices {
258 if srv.ServiceType == "proxy" {
259 return fmt.Errorf("config error: %s: proxy servers cannot be balanced", srv)
263 var checkPage arvados.CollectionList
264 if err = c.RequestAndDecode(&checkPage, "GET", "arvados/v1/collections", nil, arvados.ResourceListParams{
268 IncludeOldVersions: true,
269 Filters: []arvados.Filter{{
276 } else if n := checkPage.ItemsAvailable; n > 0 {
277 return fmt.Errorf("%d collections exist with null modified_at; cannot fetch reliably", n)
283 // rendezvousState returns a fingerprint (e.g., a sorted list of
284 // UUID+host+port) of the current set of keep services.
285 func (bal *Balancer) rendezvousState() string {
286 srvs := make([]string, 0, len(bal.KeepServices))
287 for _, srv := range bal.KeepServices {
288 srvs = append(srvs, srv.String())
291 return strings.Join(srvs, "; ")
294 // ClearTrashLists sends an empty trash list to each keep
295 // service. Calling this before GetCurrentState avoids races.
297 // When a block appears in an index, we assume that replica will still
298 // exist after we delete other replicas on other servers. However,
299 // it's possible that a previous rebalancing operation made different
300 // decisions (e.g., servers were added/removed, and rendezvous order
301 // changed). In this case, the replica might already be on that
302 // server's trash list, and it might be deleted before we send a
303 // replacement trash list.
305 // We avoid this problem if we clear all trash lists before getting
306 // indexes. (We also assume there is only one rebalancing process
307 // running at a time.)
308 func (bal *Balancer) ClearTrashLists(ctx context.Context, c *arvados.Client) error {
309 for _, srv := range bal.KeepServices {
310 srv.ChangeSet = &ChangeSet{}
312 return bal.CommitTrash(ctx, c)
315 // GetCurrentState determines the current replication state, and the
316 // desired replication level, for every block that is either
317 // retrievable or referenced.
319 // It determines the current replication state by reading the block index
320 // from every known Keep service.
322 // It determines the desired replication level by retrieving all
323 // collection manifests in the database (API server).
325 // It encodes the resulting information in BlockStateMap.
326 func (bal *Balancer) GetCurrentState(ctx context.Context, c *arvados.Client, pageSize, bufs int) error {
327 ctx, cancel := context.WithCancel(ctx)
330 defer bal.time("get_state", "wall clock time to get current state")()
331 bal.BlockStateMap = NewBlockStateMap()
333 dd, err := c.DiscoveryDocument()
337 bal.DefaultReplication = dd.DefaultCollectionReplication
338 bal.MinMtime = time.Now().UnixNano() - dd.BlobSignatureTTL*1e9
340 errs := make(chan error, 1)
341 wg := sync.WaitGroup{}
343 // When a device is mounted more than once, we will get its
344 // index only once, and call AddReplicas on all of the mounts.
345 // equivMount keys are the mounts that will be indexed, and
346 // each value is a list of mounts to apply the received index
348 equivMount := map[*KeepMount][]*KeepMount{}
349 // deviceMount maps each device ID to the one mount that will
350 // be indexed for that device.
351 deviceMount := map[string]*KeepMount{}
352 for _, srv := range bal.KeepServices {
353 for _, mnt := range srv.mounts {
354 equiv := deviceMount[mnt.DeviceID]
357 if mnt.DeviceID != "" {
358 deviceMount[mnt.DeviceID] = equiv
361 equivMount[equiv] = append(equivMount[equiv], mnt)
365 // Start one goroutine for each (non-redundant) mount:
366 // retrieve the index, and add the returned blocks to
368 for _, mounts := range equivMount {
370 go func(mounts []*KeepMount) {
372 bal.logf("mount %s: retrieve index from %s", mounts[0], mounts[0].KeepService)
373 idx, err := mounts[0].KeepService.IndexMount(ctx, c, mounts[0].UUID, "")
376 case errs <- fmt.Errorf("%s: retrieve index: %v", mounts[0], err):
383 // Some other goroutine encountered an
384 // error -- any further effort here
388 for _, mount := range mounts {
389 bal.logf("%s: add %d entries to map", mount, len(idx))
390 bal.BlockStateMap.AddReplicas(mount, idx)
391 bal.logf("%s: added %d entries to map at %dx (%d replicas)", mount, len(idx), mount.Replication, len(idx)*mount.Replication)
393 bal.logf("mount %s: index done", mounts[0])
397 // collQ buffers incoming collections so we can start fetching
398 // the next page without waiting for the current page to
399 // finish processing.
400 collQ := make(chan arvados.Collection, bufs)
402 // Start a goroutine to process collections. (We could use a
403 // worker pool here, but even with a single worker we already
404 // process collections much faster than we can retrieve them.)
408 for coll := range collQ {
409 err := bal.addCollection(coll)
410 if err != nil || len(errs) > 0 {
424 // Start a goroutine to retrieve all collections from the
425 // Arvados database and send them to collQ for processing.
429 err = EachCollection(ctx, bal.DB, c,
430 func(coll arvados.Collection) error {
433 // some other GetCurrentState
434 // error happened: no point
437 return fmt.Errorf("")
440 }, func(done, total int) {
441 bal.logf("collections: %d/%d", done, total)
460 func (bal *Balancer) addCollection(coll arvados.Collection) error {
461 blkids, err := coll.SizedDigests()
463 return fmt.Errorf("%v: %v", coll.UUID, err)
465 repl := bal.DefaultReplication
466 if coll.ReplicationDesired != nil {
467 repl = *coll.ReplicationDesired
469 bal.Logger.Debugf("%v: %d blocks x%d", coll.UUID, len(blkids), repl)
470 // Pass pdh to IncreaseDesired only if LostBlocksFile is being
471 // written -- otherwise it's just a waste of memory.
473 if bal.LostBlocksFile != "" {
474 pdh = coll.PortableDataHash
476 bal.BlockStateMap.IncreaseDesired(pdh, coll.StorageClassesDesired, repl, blkids)
480 // ComputeChangeSets compares, for each known block, the current and
481 // desired replication states. If it is possible to get closer to the
482 // desired state by copying or deleting blocks, it adds those changes
483 // to the relevant KeepServices' ChangeSets.
485 // It does not actually apply any of the computed changes.
486 func (bal *Balancer) ComputeChangeSets() {
487 // This just calls balanceBlock() once for each block, using a
488 // pool of worker goroutines.
489 defer bal.time("changeset_compute", "wall clock time to compute changesets")()
490 bal.setupLookupTables()
492 type balanceTask struct {
493 blkid arvados.SizedDigest
496 workers := runtime.GOMAXPROCS(-1)
497 todo := make(chan balanceTask, workers)
499 bal.BlockStateMap.Apply(func(blkid arvados.SizedDigest, blk *BlockState) {
507 results := make(chan balanceResult, workers)
509 var wg sync.WaitGroup
510 for i := 0; i < workers; i++ {
513 for work := range todo {
514 results <- bal.balanceBlock(work.blkid, work.blk)
522 bal.collectStatistics(results)
525 func (bal *Balancer) setupLookupTables() {
526 bal.serviceRoots = make(map[string]string)
527 bal.classes = defaultClasses
528 bal.mountsByClass = map[string]map[*KeepMount]bool{"default": {}}
530 for _, srv := range bal.KeepServices {
531 bal.serviceRoots[srv.UUID] = srv.UUID
532 for _, mnt := range srv.mounts {
535 // All mounts on a read-only service are
536 // effectively read-only.
537 mnt.ReadOnly = mnt.ReadOnly || srv.ReadOnly
539 if len(mnt.StorageClasses) == 0 {
540 bal.mountsByClass["default"][mnt] = true
543 for class := range mnt.StorageClasses {
544 if mbc := bal.mountsByClass[class]; mbc == nil {
545 bal.classes = append(bal.classes, class)
546 bal.mountsByClass[class] = map[*KeepMount]bool{mnt: true}
553 // Consider classes in lexicographic order to avoid flapping
554 // between balancing runs. The outcome of the "prefer a mount
555 // we're already planning to use for a different storage
556 // class" case in balanceBlock depends on the order classes
558 sort.Strings(bal.classes)
568 var changeName = map[int]string{
571 changeTrash: "trash",
575 type balancedBlockState struct {
582 type balanceResult struct {
584 blkid arvados.SizedDigest
586 blockState balancedBlockState
587 classState map[string]balancedBlockState
591 mnt *KeepMount // never nil
592 repl *Replica // replica already stored here (or nil)
593 want bool // we should pull/leave a replica here
596 // balanceBlock compares current state to desired state for a single
597 // block, and makes the appropriate ChangeSet calls.
598 func (bal *Balancer) balanceBlock(blkid arvados.SizedDigest, blk *BlockState) balanceResult {
599 bal.Logger.Debugf("balanceBlock: %v %+v", blkid, blk)
601 // Build a list of all slots (one per mounted volume).
602 slots := make([]slot, 0, bal.mounts)
603 for _, srv := range bal.KeepServices {
604 for _, mnt := range srv.mounts {
606 for r := range blk.Replicas {
607 if blk.Replicas[r].KeepMount == mnt {
608 repl = &blk.Replicas[r]
611 // Initial value of "want" is "have, and can't
612 // delete". These untrashable replicas get
613 // prioritized when sorting slots: otherwise,
614 // non-optimal readonly copies would cause us
616 slots = append(slots, slot{
619 want: repl != nil && mnt.ReadOnly,
624 uuids := keepclient.NewRootSorter(bal.serviceRoots, string(blkid[:32])).GetSortedRoots()
625 srvRendezvous := make(map[*KeepService]int, len(uuids))
626 for i, uuid := range uuids {
627 srv := bal.KeepServices[uuid]
628 srvRendezvous[srv] = i
631 // Below we set underreplicated=true if we find any storage
632 // class that's currently underreplicated -- in that case we
633 // won't want to trash any replicas.
634 underreplicated := false
636 unsafeToDelete := make(map[int64]bool, len(slots))
637 for _, class := range bal.classes {
638 desired := blk.Desired[class]
643 // Sort the slots by desirability.
644 sort.Slice(slots, func(i, j int) bool {
645 si, sj := slots[i], slots[j]
646 if classi, classj := bal.mountsByClass[class][si.mnt], bal.mountsByClass[class][sj.mnt]; classi != classj {
647 // Prefer a mount that satisfies the
649 return bal.mountsByClass[class][si.mnt]
650 } else if si.want != sj.want {
651 // Prefer a mount that will have a
652 // replica no matter what we do here
653 // -- either because it already has an
654 // untrashable replica, or because we
655 // already need it to satisfy a
656 // different storage class.
658 } else if orderi, orderj := srvRendezvous[si.mnt.KeepService], srvRendezvous[sj.mnt.KeepService]; orderi != orderj {
659 // Prefer a better rendezvous
661 return orderi < orderj
662 } else if repli, replj := si.repl != nil, sj.repl != nil; repli != replj {
663 // Prefer a mount that already has a
667 // If pull/trash turns out to be
668 // needed, distribute the
669 // new/remaining replicas uniformly
670 // across qualifying mounts on a given
672 return rendezvousLess(si.mnt.DeviceID, sj.mnt.DeviceID, blkid)
676 // Servers/mounts/devices (with or without existing
677 // replicas) that are part of the best achievable
678 // layout for this storage class.
679 wantSrv := map[*KeepService]bool{}
680 wantMnt := map[*KeepMount]bool{}
681 wantDev := map[string]bool{}
682 // Positions (with existing replicas) that have been
683 // protected (via unsafeToDelete) to ensure we don't
684 // reduce replication below desired level when
685 // trashing replicas that aren't optimal positions for
686 // any storage class.
687 protMnt := map[*KeepMount]bool{}
688 // Replication planned so far (corresponds to wantMnt).
690 // Protected replication (corresponds to protMnt).
693 // trySlot tries using a slot to meet requirements,
694 // and returns true if all requirements are met.
695 trySlot := func(i int) bool {
697 if wantMnt[slot.mnt] || wantDev[slot.mnt.DeviceID] {
698 // Already allocated a replica to this
699 // backend device, possibly on a
703 if replProt < desired && slot.repl != nil && !protMnt[slot.mnt] {
704 unsafeToDelete[slot.repl.Mtime] = true
705 protMnt[slot.mnt] = true
706 replProt += slot.mnt.Replication
708 if replWant < desired && (slot.repl != nil || !slot.mnt.ReadOnly) {
710 wantSrv[slot.mnt.KeepService] = true
711 wantMnt[slot.mnt] = true
712 if slot.mnt.DeviceID != "" {
713 wantDev[slot.mnt.DeviceID] = true
715 replWant += slot.mnt.Replication
717 return replProt >= desired && replWant >= desired
720 // First try to achieve desired replication without
721 // using the same server twice.
723 for i := 0; i < len(slots) && !done; i++ {
724 if !wantSrv[slots[i].mnt.KeepService] {
729 // If that didn't suffice, do another pass without the
730 // "distinct services" restriction. (Achieving the
731 // desired volume replication on fewer than the
732 // desired number of services is better than
733 // underreplicating.)
734 for i := 0; i < len(slots) && !done; i++ {
738 if !underreplicated {
740 for _, slot := range slots {
741 if slot.repl == nil || !bal.mountsByClass[class][slot.mnt] {
744 if safe += slot.mnt.Replication; safe >= desired {
748 underreplicated = safe < desired
751 // Avoid deleting wanted replicas from devices that
752 // are mounted on multiple servers -- even if they
753 // haven't already been added to unsafeToDelete
754 // because the servers report different Mtimes.
755 for _, slot := range slots {
756 if slot.repl != nil && wantDev[slot.mnt.DeviceID] {
757 unsafeToDelete[slot.repl.Mtime] = true
762 // TODO: If multiple replicas are trashable, prefer the oldest
763 // replica that doesn't have a timestamp collision with
766 for i, slot := range slots {
767 // Don't trash (1) any replicas of an underreplicated
768 // block, even if they're in the wrong positions, or
769 // (2) any replicas whose Mtimes are identical to
770 // needed replicas (in case we're really seeing the
771 // same copy via different mounts).
772 if slot.repl != nil && (underreplicated || unsafeToDelete[slot.repl.Mtime]) {
777 classState := make(map[string]balancedBlockState, len(bal.classes))
778 for _, class := range bal.classes {
779 classState[class] = computeBlockState(slots, bal.mountsByClass[class], len(blk.Replicas), blk.Desired[class])
781 blockState := computeBlockState(slots, nil, len(blk.Replicas), 0)
785 for _, slot := range slots {
786 // TODO: request a Touch if Mtime is duplicated.
789 case !slot.want && slot.repl != nil && slot.repl.Mtime < bal.MinMtime:
790 slot.mnt.KeepService.AddTrash(Trash{
792 Mtime: slot.repl.Mtime,
796 case slot.repl == nil && slot.want && len(blk.Replicas) == 0:
799 case slot.repl == nil && slot.want && !slot.mnt.ReadOnly:
800 slot.mnt.KeepService.AddPull(Pull{
802 From: blk.Replicas[0].KeepMount.KeepService,
806 case slot.repl != nil:
811 if bal.Dumper != nil {
813 if slot.repl != nil {
814 mtime = slot.repl.Mtime
816 srv := slot.mnt.KeepService
817 changes = append(changes, fmt.Sprintf("%s:%d/%s=%s,%d", srv.ServiceHost, srv.ServicePort, slot.mnt.UUID, changeName[change], mtime))
820 if bal.Dumper != nil {
821 bal.Dumper.Printf("%s refs=%d needed=%d unneeded=%d pulling=%v %v %v", blkid, blk.RefCount, blockState.needed, blockState.unneeded, blockState.pulling, blk.Desired, changes)
823 return balanceResult{
827 blockState: blockState,
828 classState: classState,
832 func computeBlockState(slots []slot, onlyCount map[*KeepMount]bool, have, needRepl int) (bbs balancedBlockState) {
834 countedDev := map[string]bool{}
835 for _, slot := range slots {
836 if onlyCount != nil && !onlyCount[slot.mnt] {
839 if countedDev[slot.mnt.DeviceID] {
843 case slot.repl != nil && slot.want:
845 repl += slot.mnt.Replication
846 case slot.repl != nil && !slot.want:
848 repl += slot.mnt.Replication
849 case slot.repl == nil && slot.want && have > 0:
851 repl += slot.mnt.Replication
853 if slot.mnt.DeviceID != "" {
854 countedDev[slot.mnt.DeviceID] = true
858 bbs.unachievable = true
863 type blocksNBytes struct {
869 func (bb blocksNBytes) String() string {
870 return fmt.Sprintf("%d replicas (%d blocks, %d bytes)", bb.replicas, bb.blocks, bb.bytes)
873 type replicationStats struct {
875 unneeded blocksNBytes
877 unachievable blocksNBytes
880 type balancerStats struct {
885 underrep blocksNBytes
886 unachievable blocksNBytes
887 justright blocksNBytes
893 classStats map[string]replicationStats
895 // collectionBytes / collectionBlockBytes = deduplication ratio
896 collectionBytes int64 // sum(bytes in referenced blocks) across all collections
897 collectionBlockBytes int64 // sum(block size) across all blocks referenced by collections
898 collectionBlockRefs int64 // sum(number of blocks referenced) across all collections
899 collectionBlocks int64 // number of blocks referenced by any collection
902 func (s *balancerStats) dedupByteRatio() float64 {
903 if s.collectionBlockBytes == 0 {
906 return float64(s.collectionBytes) / float64(s.collectionBlockBytes)
909 func (s *balancerStats) dedupBlockRatio() float64 {
910 if s.collectionBlocks == 0 {
913 return float64(s.collectionBlockRefs) / float64(s.collectionBlocks)
916 func (bal *Balancer) collectStatistics(results <-chan balanceResult) {
918 s.replHistogram = make([]int, 2)
919 s.classStats = make(map[string]replicationStats, len(bal.classes))
920 for result := range results {
921 bytes := result.blkid.Size()
923 if rc := int64(result.blk.RefCount); rc > 0 {
924 s.collectionBytes += rc * bytes
925 s.collectionBlockBytes += bytes
926 s.collectionBlockRefs += rc
930 for class, state := range result.classState {
931 cs := s.classStats[class]
932 if state.unachievable {
933 cs.unachievable.replicas++
934 cs.unachievable.blocks++
935 cs.unachievable.bytes += bytes
937 if state.needed > 0 {
938 cs.needed.replicas += state.needed
940 cs.needed.bytes += bytes * int64(state.needed)
942 if state.unneeded > 0 {
943 cs.unneeded.replicas += state.unneeded
945 cs.unneeded.bytes += bytes * int64(state.unneeded)
947 if state.pulling > 0 {
948 cs.pulling.replicas += state.pulling
950 cs.pulling.bytes += bytes * int64(state.pulling)
952 s.classStats[class] = cs
955 bs := result.blockState
960 s.lost.bytes += bytes
961 fmt.Fprintf(bal.lostBlocks, "%s", strings.SplitN(string(result.blkid), "+", 2)[0])
962 for pdh := range result.blk.Refs {
963 fmt.Fprintf(bal.lostBlocks, " %s", pdh)
965 fmt.Fprint(bal.lostBlocks, "\n")
967 s.underrep.replicas += bs.pulling
969 s.underrep.bytes += bytes * int64(bs.pulling)
970 case bs.unachievable:
971 s.underrep.replicas++
973 s.underrep.bytes += bytes
974 case bs.unneeded > 0 && bs.needed == 0:
975 // Count as "garbage" if all replicas are old
976 // enough to trash, otherwise count as
978 counter := &s.garbage
979 for _, r := range result.blk.Replicas {
980 if r.Mtime >= bal.MinMtime {
985 counter.replicas += bs.unneeded
987 counter.bytes += bytes * int64(bs.unneeded)
988 case bs.unneeded > 0:
989 s.overrep.replicas += bs.unneeded
991 s.overrep.bytes += bytes * int64(bs.unneeded)
993 s.justright.replicas += bs.needed
995 s.justright.bytes += bytes * int64(bs.needed)
999 s.desired.replicas += bs.needed
1001 s.desired.bytes += bytes * int64(bs.needed)
1003 if bs.needed+bs.unneeded > 0 {
1004 s.current.replicas += bs.needed + bs.unneeded
1006 s.current.bytes += bytes * int64(bs.needed+bs.unneeded)
1009 for len(s.replHistogram) <= bs.needed+bs.unneeded {
1010 s.replHistogram = append(s.replHistogram, 0)
1012 s.replHistogram[bs.needed+bs.unneeded]++
1014 for _, srv := range bal.KeepServices {
1015 s.pulls += len(srv.ChangeSet.Pulls)
1016 s.trashes += len(srv.ChangeSet.Trashes)
1019 bal.Metrics.UpdateStats(s)
1022 // PrintStatistics writes statistics about the computed changes to
1023 // bal.Logger. It should not be called until ComputeChangeSets has
1025 func (bal *Balancer) PrintStatistics() {
1027 bal.logf("%s lost (0=have<want)", bal.stats.lost)
1028 bal.logf("%s underreplicated (0<have<want)", bal.stats.underrep)
1029 bal.logf("%s just right (have=want)", bal.stats.justright)
1030 bal.logf("%s overreplicated (have>want>0)", bal.stats.overrep)
1031 bal.logf("%s unreferenced (have>want=0, new)", bal.stats.unref)
1032 bal.logf("%s garbage (have>want=0, old)", bal.stats.garbage)
1033 for _, class := range bal.classes {
1034 cs := bal.stats.classStats[class]
1036 bal.logf("storage class %q: %s needed", class, cs.needed)
1037 bal.logf("storage class %q: %s unneeded", class, cs.unneeded)
1038 bal.logf("storage class %q: %s pulling", class, cs.pulling)
1039 bal.logf("storage class %q: %s unachievable", class, cs.unachievable)
1042 bal.logf("%s total commitment (excluding unreferenced)", bal.stats.desired)
1043 bal.logf("%s total usage", bal.stats.current)
1045 for _, srv := range bal.KeepServices {
1046 bal.logf("%s: %v\n", srv, srv.ChangeSet)
1049 bal.printHistogram(60)
1053 func (bal *Balancer) printHistogram(hashColumns int) {
1054 bal.logf("Replication level distribution:")
1056 for _, count := range bal.stats.replHistogram {
1057 if maxCount < count {
1061 hashes := strings.Repeat("#", hashColumns)
1062 countWidth := 1 + int(math.Log10(float64(maxCount+1)))
1063 scaleCount := 10 * float64(hashColumns) / math.Floor(1+10*math.Log10(float64(maxCount+1)))
1064 for repl, count := range bal.stats.replHistogram {
1065 nHashes := int(scaleCount * math.Log10(float64(count+1)))
1066 bal.logf("%2d: %*d %s", repl, countWidth, count, hashes[:nHashes])
1070 // CheckSanityLate checks for configuration and runtime errors after
1071 // GetCurrentState() and ComputeChangeSets() have finished.
1073 // If it returns an error, it is dangerous to run any Commit methods.
1074 func (bal *Balancer) CheckSanityLate() error {
1075 if bal.errors != nil {
1076 for _, err := range bal.errors {
1077 bal.logf("deferred error: %v", err)
1079 return fmt.Errorf("cannot proceed safely after deferred errors")
1082 if bal.collScanned == 0 {
1083 return fmt.Errorf("received zero collections")
1087 bal.BlockStateMap.Apply(func(_ arvados.SizedDigest, blk *BlockState) {
1088 for _, desired := range blk.Desired {
1096 return fmt.Errorf("zero blocks have desired replication>0")
1099 if dr := bal.DefaultReplication; dr < 1 {
1100 return fmt.Errorf("Default replication (%d) is less than 1", dr)
1103 // TODO: no two services have identical indexes
1104 // TODO: no collisions (same md5, different size)
1108 // CommitPulls sends the computed lists of pull requests to the
1109 // keepstore servers. This has the effect of increasing replication of
1110 // existing blocks that are either underreplicated or poorly
1111 // distributed according to rendezvous hashing.
1112 func (bal *Balancer) CommitPulls(ctx context.Context, c *arvados.Client) error {
1113 defer bal.time("send_pull_lists", "wall clock time to send pull lists")()
1114 return bal.commitAsync(c, "send pull list",
1115 func(srv *KeepService) error {
1116 return srv.CommitPulls(ctx, c)
1120 // CommitTrash sends the computed lists of trash requests to the
1121 // keepstore servers. This has the effect of deleting blocks that are
1122 // overreplicated or unreferenced.
1123 func (bal *Balancer) CommitTrash(ctx context.Context, c *arvados.Client) error {
1124 defer bal.time("send_trash_lists", "wall clock time to send trash lists")()
1125 return bal.commitAsync(c, "send trash list",
1126 func(srv *KeepService) error {
1127 return srv.CommitTrash(ctx, c)
1131 func (bal *Balancer) commitAsync(c *arvados.Client, label string, f func(srv *KeepService) error) error {
1132 errs := make(chan error)
1133 for _, srv := range bal.KeepServices {
1134 go func(srv *KeepService) {
1136 defer func() { errs <- err }()
1137 label := fmt.Sprintf("%s: %v", srv, label)
1140 err = fmt.Errorf("%s: %v", label, err)
1145 for range bal.KeepServices {
1146 if err := <-errs; err != nil {
1155 func (bal *Balancer) logf(f string, args ...interface{}) {
1156 if bal.Logger != nil {
1157 bal.Logger.Printf(f, args...)
1161 func (bal *Balancer) time(name, help string) func() {
1162 observer := bal.Metrics.DurationObserver(name+"_seconds", help)
1164 bal.Logger.Printf("%s: start", name)
1166 dur := time.Since(t0)
1167 observer.Observe(dur.Seconds())
1168 bal.Logger.Printf("%s: took %vs", name, dur.Seconds())
1172 // Rendezvous hash sort function. Less efficient than sorting on
1173 // precomputed rendezvous hashes, but also rarely used.
1174 func rendezvousLess(i, j string, blkid arvados.SizedDigest) bool {
1175 a := md5.Sum([]byte(string(blkid[:32]) + i))
1176 b := md5.Sum([]byte(string(blkid[:32]) + j))
1177 return bytes.Compare(a[:], b[:]) < 0