1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.curoverse.com/arvados.git/sdk/go/arvados"
21 "git.curoverse.com/arvados.git/sdk/go/keepclient"
24 // CheckConfig returns an error if anything is wrong with the given
25 // config and runOptions.
26 func CheckConfig(config Config, runOptions RunOptions) error {
27 if len(config.KeepServiceList.Items) > 0 && config.KeepServiceTypes != nil {
28 return fmt.Errorf("cannot specify both KeepServiceList and KeepServiceTypes in config")
30 if !runOptions.Once && config.RunPeriod == arvados.Duration(0) {
31 return fmt.Errorf("you must either use the -once flag, or specify RunPeriod in config")
36 // Balancer compares the contents of keepstore servers with the
37 // collections stored in Arvados, and issues pull/trash requests
38 // needed to get (closer to) the optimal data layout.
40 // In the optimal data layout: every data block referenced by a
41 // collection is replicated at least as many times as desired by the
42 // collection; there are no unreferenced data blocks older than
43 // BlobSignatureTTL; and all N existing replicas of a given data block
44 // are in the N best positions in rendezvous probe order.
45 type Balancer struct {
47 KeepServices map[string]*KeepService
48 DefaultReplication int
55 mountsByClass map[string]map[*KeepMount]bool
57 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(config Config, runOptions RunOptions) (nextRunOptions RunOptions, err error) {
73 nextRunOptions = runOptions
75 bal.Dumper = runOptions.Dumper
76 bal.Logger = runOptions.Logger
77 if bal.Logger == nil {
78 bal.Logger = log.New(os.Stderr, "", log.LstdFlags)
81 defer timeMe(bal.Logger, "Run")()
83 if len(config.KeepServiceList.Items) > 0 {
84 err = bal.SetKeepServices(config.KeepServiceList)
86 err = bal.DiscoverKeepServices(&config.Client, config.KeepServiceTypes)
92 for _, srv := range bal.KeepServices {
93 err = srv.discoverMounts(&config.Client)
100 if err = bal.CheckSanityEarly(&config.Client); err != nil {
103 rs := bal.rendezvousState()
104 if runOptions.CommitTrash && rs != runOptions.SafeRendezvousState {
105 if runOptions.SafeRendezvousState != "" {
106 bal.logf("notice: KeepServices list has changed since last run")
108 bal.logf("clearing existing trash lists, in case the new rendezvous order differs from previous run")
109 if err = bal.ClearTrashLists(&config.Client); err != nil {
112 // The current rendezvous state becomes "safe" (i.e.,
113 // OK to compute changes for that state without
114 // clearing existing trash lists) only now, after we
115 // succeed in clearing existing trash lists.
116 nextRunOptions.SafeRendezvousState = rs
118 if err = bal.GetCurrentState(&config.Client, config.CollectionBatchSize, config.CollectionBuffers); err != nil {
121 bal.ComputeChangeSets()
122 bal.PrintStatistics()
123 if err = bal.CheckSanityLate(); err != nil {
126 if runOptions.CommitPulls {
127 err = bal.CommitPulls(&config.Client)
129 // Skip trash if we can't pull. (Too cautious?)
133 if runOptions.CommitTrash {
134 err = bal.CommitTrash(&config.Client)
139 // SetKeepServices sets the list of KeepServices to operate on.
140 func (bal *Balancer) SetKeepServices(srvList arvados.KeepServiceList) error {
141 bal.KeepServices = make(map[string]*KeepService)
142 for _, srv := range srvList.Items {
143 bal.KeepServices[srv.UUID] = &KeepService{
145 ChangeSet: &ChangeSet{},
151 // DiscoverKeepServices sets the list of KeepServices by calling the
152 // API to get a list of all services, and selecting the ones whose
153 // ServiceType is in okTypes.
154 func (bal *Balancer) DiscoverKeepServices(c *arvados.Client, okTypes []string) error {
155 bal.KeepServices = make(map[string]*KeepService)
156 ok := make(map[string]bool)
157 for _, t := range okTypes {
160 return c.EachKeepService(func(srv arvados.KeepService) error {
161 if ok[srv.ServiceType] {
162 bal.KeepServices[srv.UUID] = &KeepService{
164 ChangeSet: &ChangeSet{},
167 bal.logf("skipping %v with service type %q", srv.UUID, srv.ServiceType)
173 func (bal *Balancer) dedupDevices() {
174 rwdev := map[string]*KeepService{}
175 for _, srv := range bal.KeepServices {
176 for _, mnt := range srv.mounts {
177 if !mnt.ReadOnly && mnt.DeviceID != "" {
178 rwdev[mnt.DeviceID] = srv
182 // Drop the readonly mounts whose device is mounted RW
184 for _, srv := range bal.KeepServices {
185 var dedup []*KeepMount
186 for _, mnt := range srv.mounts {
187 if mnt.ReadOnly && rwdev[mnt.DeviceID] != nil {
188 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])
190 dedup = append(dedup, mnt)
197 // CheckSanityEarly checks for configuration and runtime errors that
198 // can be detected before GetCurrentState() and ComputeChangeSets()
201 // If it returns an error, it is pointless to run GetCurrentState or
202 // ComputeChangeSets: after doing so, the statistics would be
203 // meaningless and it would be dangerous to run any Commit methods.
204 func (bal *Balancer) CheckSanityEarly(c *arvados.Client) error {
205 u, err := c.CurrentUser()
207 return fmt.Errorf("CurrentUser(): %v", err)
209 if !u.IsActive || !u.IsAdmin {
210 return fmt.Errorf("current user (%s) is not an active admin user", u.UUID)
212 for _, srv := range bal.KeepServices {
213 if srv.ServiceType == "proxy" {
214 return fmt.Errorf("config error: %s: proxy servers cannot be balanced", srv)
220 // rendezvousState returns a fingerprint (e.g., a sorted list of
221 // UUID+host+port) of the current set of keep services.
222 func (bal *Balancer) rendezvousState() string {
223 srvs := make([]string, 0, len(bal.KeepServices))
224 for _, srv := range bal.KeepServices {
225 srvs = append(srvs, srv.String())
228 return strings.Join(srvs, "; ")
231 // ClearTrashLists sends an empty trash list to each keep
232 // service. Calling this before GetCurrentState avoids races.
234 // When a block appears in an index, we assume that replica will still
235 // exist after we delete other replicas on other servers. However,
236 // it's possible that a previous rebalancing operation made different
237 // decisions (e.g., servers were added/removed, and rendezvous order
238 // changed). In this case, the replica might already be on that
239 // server's trash list, and it might be deleted before we send a
240 // replacement trash list.
242 // We avoid this problem if we clear all trash lists before getting
243 // indexes. (We also assume there is only one rebalancing process
244 // running at a time.)
245 func (bal *Balancer) ClearTrashLists(c *arvados.Client) error {
246 for _, srv := range bal.KeepServices {
247 srv.ChangeSet = &ChangeSet{}
249 return bal.CommitTrash(c)
252 // GetCurrentState determines the current replication state, and the
253 // desired replication level, for every block that is either
254 // retrievable or referenced.
256 // It determines the current replication state by reading the block index
257 // from every known Keep service.
259 // It determines the desired replication level by retrieving all
260 // collection manifests in the database (API server).
262 // It encodes the resulting information in BlockStateMap.
263 func (bal *Balancer) GetCurrentState(c *arvados.Client, pageSize, bufs int) error {
264 defer timeMe(bal.Logger, "GetCurrentState")()
265 bal.BlockStateMap = NewBlockStateMap()
267 dd, err := c.DiscoveryDocument()
271 bal.DefaultReplication = dd.DefaultCollectionReplication
272 bal.MinMtime = time.Now().UnixNano() - dd.BlobSignatureTTL*1e9
274 errs := make(chan error, 2+len(bal.KeepServices))
275 wg := sync.WaitGroup{}
277 // Start one goroutine for each KeepService: retrieve the
278 // index, and add the returned blocks to BlockStateMap.
279 for _, srv := range bal.KeepServices {
281 go func(srv *KeepService) {
283 bal.logf("%s: retrieve indexes", srv)
284 for _, mount := range srv.mounts {
285 bal.logf("%s: retrieve index", mount)
286 idx, err := srv.IndexMount(c, mount.UUID, "")
288 errs <- fmt.Errorf("%s: retrieve index: %v", mount, err)
292 // Some other goroutine encountered an
293 // error -- any further effort here
297 bal.logf("%s: add %d replicas to map", mount, len(idx))
298 bal.BlockStateMap.AddReplicas(mount, idx)
299 bal.logf("%s: done", mount)
301 bal.logf("%s: done", srv)
305 // collQ buffers incoming collections so we can start fetching
306 // the next page without waiting for the current page to
307 // finish processing.
308 collQ := make(chan arvados.Collection, bufs)
310 // Start a goroutine to process collections. (We could use a
311 // worker pool here, but even with a single worker we already
312 // process collections much faster than we can retrieve them.)
316 for coll := range collQ {
317 err := bal.addCollection(coll)
328 // Start a goroutine to retrieve all collections from the
329 // Arvados database and send them to collQ for processing.
333 err = EachCollection(c, pageSize,
334 func(coll arvados.Collection) error {
337 // some other GetCurrentState
338 // error happened: no point
341 return fmt.Errorf("")
344 }, func(done, total int) {
345 bal.logf("collections: %d/%d", done, total)
360 func (bal *Balancer) addCollection(coll arvados.Collection) error {
361 blkids, err := coll.SizedDigests()
364 bal.errors = append(bal.errors, fmt.Errorf("%v: %v", coll.UUID, err))
368 repl := bal.DefaultReplication
369 if coll.ReplicationDesired != nil {
370 repl = *coll.ReplicationDesired
372 debugf("%v: %d block x%d", coll.UUID, len(blkids), repl)
373 bal.BlockStateMap.IncreaseDesired(coll.StorageClassesDesired, repl, blkids)
377 // ComputeChangeSets compares, for each known block, the current and
378 // desired replication states. If it is possible to get closer to the
379 // desired state by copying or deleting blocks, it adds those changes
380 // to the relevant KeepServices' ChangeSets.
382 // It does not actually apply any of the computed changes.
383 func (bal *Balancer) ComputeChangeSets() {
384 // This just calls balanceBlock() once for each block, using a
385 // pool of worker goroutines.
386 defer timeMe(bal.Logger, "ComputeChangeSets")()
387 bal.setupLookupTables()
389 type balanceTask struct {
390 blkid arvados.SizedDigest
393 workers := runtime.GOMAXPROCS(-1)
394 todo := make(chan balanceTask, workers)
396 bal.BlockStateMap.Apply(func(blkid arvados.SizedDigest, blk *BlockState) {
404 results := make(chan balanceResult, workers)
406 var wg sync.WaitGroup
407 for i := 0; i < workers; i++ {
410 for work := range todo {
411 results <- bal.balanceBlock(work.blkid, work.blk)
419 bal.collectStatistics(results)
422 func (bal *Balancer) setupLookupTables() {
423 bal.serviceRoots = make(map[string]string)
424 bal.classes = []string{"default"}
425 bal.mountsByClass = map[string]map[*KeepMount]bool{"default": {}}
427 for _, srv := range bal.KeepServices {
428 bal.serviceRoots[srv.UUID] = srv.UUID
429 for _, mnt := range srv.mounts {
432 // All mounts on a read-only service are
433 // effectively read-only.
434 mnt.ReadOnly = mnt.ReadOnly || srv.ReadOnly
436 if len(mnt.StorageClasses) == 0 {
437 bal.mountsByClass["default"][mnt] = true
440 for _, class := range mnt.StorageClasses {
441 if mbc := bal.mountsByClass[class]; mbc == nil {
442 bal.classes = append(bal.classes, class)
443 bal.mountsByClass[class] = map[*KeepMount]bool{mnt: true}
450 // Consider classes in lexicographic order to avoid flapping
451 // between balancing runs. The outcome of the "prefer a mount
452 // we're already planning to use for a different storage
453 // class" case in balanceBlock depends on the order classes
455 sort.Strings(bal.classes)
465 var changeName = map[int]string{
468 changeTrash: "trash",
472 type balanceResult struct {
474 blkid arvados.SizedDigest
477 classState map[string]balancedBlockState
480 // balanceBlock compares current state to desired state for a single
481 // block, and makes the appropriate ChangeSet calls.
482 func (bal *Balancer) balanceBlock(blkid arvados.SizedDigest, blk *BlockState) balanceResult {
483 debugf("balanceBlock: %v %+v", blkid, blk)
486 mnt *KeepMount // never nil
487 repl *Replica // replica already stored here (or nil)
488 want bool // we should pull/leave a replica here
491 // Build a list of all slots (one per mounted volume).
492 slots := make([]slot, 0, bal.mounts)
493 for _, srv := range bal.KeepServices {
494 for _, mnt := range srv.mounts {
496 for r := range blk.Replicas {
497 if blk.Replicas[r].KeepMount == mnt {
498 repl = &blk.Replicas[r]
501 // Initial value of "want" is "have, and can't
502 // delete". These untrashable replicas get
503 // prioritized when sorting slots: otherwise,
504 // non-optimal readonly copies would cause us
506 slots = append(slots, slot{
509 want: repl != nil && (mnt.ReadOnly || repl.Mtime >= bal.MinMtime),
514 uuids := keepclient.NewRootSorter(bal.serviceRoots, string(blkid[:32])).GetSortedRoots()
515 srvRendezvous := make(map[*KeepService]int, len(uuids))
516 for i, uuid := range uuids {
517 srv := bal.KeepServices[uuid]
518 srvRendezvous[srv] = i
521 // Below we set underreplicated=true if we find any storage
522 // class that's currently underreplicated -- in that case we
523 // won't want to trash any replicas.
524 underreplicated := false
526 classState := make(map[string]balancedBlockState, len(bal.classes))
527 unsafeToDelete := make(map[int64]bool, len(slots))
528 for _, class := range bal.classes {
529 desired := blk.Desired[class]
532 for _, slot := range slots {
533 if slot.repl != nil && bal.mountsByClass[class][slot.mnt] {
537 classState[class] = balancedBlockState{
539 surplus: have - desired,
546 // Sort the slots by desirability.
547 sort.Slice(slots, func(i, j int) bool {
548 si, sj := slots[i], slots[j]
549 if classi, classj := bal.mountsByClass[class][si.mnt], bal.mountsByClass[class][sj.mnt]; classi != classj {
550 // Prefer a mount that satisfies the
552 return bal.mountsByClass[class][si.mnt]
553 } else if wanti, wantj := si.want, si.want; wanti != wantj {
554 // Prefer a mount that will have a
555 // replica no matter what we do here
556 // -- either because it already has an
557 // untrashable replica, or because we
558 // already need it to satisfy a
559 // different storage class.
561 } else if orderi, orderj := srvRendezvous[si.mnt.KeepService], srvRendezvous[sj.mnt.KeepService]; orderi != orderj {
562 // Prefer a better rendezvous
564 return orderi < orderj
565 } else if repli, replj := si.repl != nil, sj.repl != nil; repli != replj {
566 // Prefer a mount that already has a
570 // If pull/trash turns out to be
571 // needed, distribute the
572 // new/remaining replicas uniformly
573 // across qualifying mounts on a given
575 return rendezvousLess(si.mnt.DeviceID, sj.mnt.DeviceID, blkid)
579 // Servers and mounts (with or without existing
580 // replicas) that are part of the best achievable
581 // layout for this storage class.
582 wantSrv := map[*KeepService]bool{}
583 wantMnt := map[*KeepMount]bool{}
584 // Positions (with existing replicas) that have been
585 // protected (via unsafeToDelete) to ensure we don't
586 // reduce replication below desired level when
587 // trashing replicas that aren't optimal positions for
588 // any storage class.
589 protMnt := map[*KeepMount]bool{}
591 // trySlot tries using a slot to meet requirements,
592 // and returns true if all requirements are met.
593 trySlot := func(i int) bool {
595 if len(protMnt) < desired && slot.repl != nil {
596 unsafeToDelete[slot.repl.Mtime] = true
597 protMnt[slot.mnt] = true
599 if len(wantMnt) < desired && (slot.repl != nil || !slot.mnt.ReadOnly) {
601 wantSrv[slot.mnt.KeepService] = true
602 wantMnt[slot.mnt] = true
604 return len(protMnt) >= desired && len(wantMnt) >= desired
607 // First try to achieve desired replication without
608 // using the same server twice.
610 for i := 0; i < len(slots) && !done; i++ {
611 if !wantSrv[slots[i].mnt.KeepService] {
616 // If that didn't suffice, do another pass without the
617 // "distinct services" restriction. (Achieving the
618 // desired volume replication on fewer than the
619 // desired number of services is better than
620 // underreplicating.)
621 for i := 0; i < len(slots) && !done; i++ {
625 if !underreplicated {
627 for _, slot := range slots {
628 if slot.repl == nil || !bal.mountsByClass[class][slot.mnt] {
631 if safe++; safe >= desired {
635 underreplicated = safe < desired
638 // set the unachievable flag if there aren't enough
639 // slots offering the relevant storage class. (This is
640 // as easy as checking slots[desired] because we
641 // already sorted the qualifying slots to the front.)
642 if desired >= len(slots) || !bal.mountsByClass[class][slots[desired].mnt] {
643 cs := classState[class]
644 cs.unachievable = true
645 classState[class] = cs
649 // TODO: If multiple replicas are trashable, prefer the oldest
650 // replica that doesn't have a timestamp collision with
654 for _, slot := range slots {
658 if slot.repl != nil {
664 for _, slot := range slots {
665 // TODO: request a Touch if Mtime is duplicated.
668 case !underreplicated && slot.repl != nil && !slot.want && !unsafeToDelete[slot.repl.Mtime]:
669 slot.mnt.KeepService.AddTrash(Trash{
671 Mtime: slot.repl.Mtime,
675 case len(blk.Replicas) == 0:
677 case slot.repl == nil && slot.want && !slot.mnt.ReadOnly:
678 slot.mnt.KeepService.AddPull(Pull{
680 From: blk.Replicas[0].KeepMount.KeepService,
687 if bal.Dumper != nil {
689 if slot.repl != nil {
690 mtime = slot.repl.Mtime
692 srv := slot.mnt.KeepService
693 changes = append(changes, fmt.Sprintf("%s:%d/%s=%s,%d", srv.ServiceHost, srv.ServicePort, slot.mnt.UUID, changeName[change], mtime))
696 if bal.Dumper != nil {
697 bal.Dumper.Printf("%s have=%d want=%v %s", blkid, have, want, strings.Join(changes, " "))
699 return balanceResult{
704 classState: classState,
708 type blocksNBytes struct {
714 func (bb blocksNBytes) String() string {
715 return fmt.Sprintf("%d replicas (%d blocks, %d bytes)", bb.replicas, bb.blocks, bb.bytes)
718 type balancerStats struct {
723 underrep blocksNBytes
724 unachievable blocksNBytes
725 justright blocksNBytes
731 classStats map[string]replicationStats
734 type replicationStats struct {
738 unachievable blocksNBytes
741 type balancedBlockState struct {
747 func (bal *Balancer) collectStatistics(results <-chan balanceResult) {
749 s.replHistogram = make([]int, 2)
750 s.classStats = make(map[string]replicationStats, len(bal.classes))
751 for result := range results {
752 surplus := result.have - result.want
753 bytes := result.blkid.Size()
755 for class, state := range result.classState {
756 cs := s.classStats[class]
757 if state.unachievable {
758 cs.unachievable.blocks++
759 cs.unachievable.bytes += bytes
761 if state.desired > 0 {
762 cs.desired.replicas += state.desired
764 cs.desired.bytes += bytes * int64(state.desired)
766 if state.surplus > 0 {
767 cs.surplus.replicas += state.surplus
769 cs.surplus.bytes += bytes * int64(state.surplus)
770 } else if state.surplus < 0 {
771 cs.short.replicas += -state.surplus
773 cs.short.bytes += bytes * int64(-state.surplus)
775 s.classStats[class] = cs
779 case result.have == 0 && result.want > 0:
780 s.lost.replicas -= surplus
782 s.lost.bytes += bytes * int64(-surplus)
784 s.underrep.replicas -= surplus
786 s.underrep.bytes += bytes * int64(-surplus)
787 case surplus > 0 && result.want == 0:
788 counter := &s.garbage
789 for _, r := range result.blk.Replicas {
790 if r.Mtime >= bal.MinMtime {
795 counter.replicas += surplus
797 counter.bytes += bytes * int64(surplus)
799 s.overrep.replicas += surplus
801 s.overrep.bytes += bytes * int64(len(result.blk.Replicas)-result.want)
803 s.justright.replicas += result.want
805 s.justright.bytes += bytes * int64(result.want)
809 s.desired.replicas += result.want
811 s.desired.bytes += bytes * int64(result.want)
813 if len(result.blk.Replicas) > 0 {
814 s.current.replicas += len(result.blk.Replicas)
816 s.current.bytes += bytes * int64(len(result.blk.Replicas))
819 for len(s.replHistogram) <= len(result.blk.Replicas) {
820 s.replHistogram = append(s.replHistogram, 0)
822 s.replHistogram[len(result.blk.Replicas)]++
824 for _, srv := range bal.KeepServices {
825 s.pulls += len(srv.ChangeSet.Pulls)
826 s.trashes += len(srv.ChangeSet.Trashes)
831 // PrintStatistics writes statistics about the computed changes to
832 // bal.Logger. It should not be called until ComputeChangeSets has
834 func (bal *Balancer) PrintStatistics() {
836 bal.logf("%s lost (0=have<want)", bal.stats.lost)
837 bal.logf("%s underreplicated (0<have<want)", bal.stats.underrep)
838 bal.logf("%s just right (have=want)", bal.stats.justright)
839 bal.logf("%s overreplicated (have>want>0)", bal.stats.overrep)
840 bal.logf("%s unreferenced (have>want=0, new)", bal.stats.unref)
841 bal.logf("%s garbage (have>want=0, old)", bal.stats.garbage)
842 for _, class := range bal.classes {
843 cs := bal.stats.classStats[class]
845 bal.logf("storage class %q: %s desired", class, cs.desired)
846 bal.logf("storage class %q: %s short", class, cs.short)
847 bal.logf("storage class %q: %s surplus", class, cs.surplus)
848 bal.logf("storage class %q: %s unachievable", class, cs.unachievable)
851 bal.logf("%s total commitment (excluding unreferenced)", bal.stats.desired)
852 bal.logf("%s total usage", bal.stats.current)
854 for _, srv := range bal.KeepServices {
855 bal.logf("%s: %v\n", srv, srv.ChangeSet)
858 bal.printHistogram(60)
862 func (bal *Balancer) printHistogram(hashColumns int) {
863 bal.logf("Replication level distribution (counting N replicas on a single server as N):")
865 for _, count := range bal.stats.replHistogram {
866 if maxCount < count {
870 hashes := strings.Repeat("#", hashColumns)
871 countWidth := 1 + int(math.Log10(float64(maxCount+1)))
872 scaleCount := 10 * float64(hashColumns) / math.Floor(1+10*math.Log10(float64(maxCount+1)))
873 for repl, count := range bal.stats.replHistogram {
874 nHashes := int(scaleCount * math.Log10(float64(count+1)))
875 bal.logf("%2d: %*d %s", repl, countWidth, count, hashes[:nHashes])
879 // CheckSanityLate checks for configuration and runtime errors after
880 // GetCurrentState() and ComputeChangeSets() have finished.
882 // If it returns an error, it is dangerous to run any Commit methods.
883 func (bal *Balancer) CheckSanityLate() error {
884 if bal.errors != nil {
885 for _, err := range bal.errors {
886 bal.logf("deferred error: %v", err)
888 return fmt.Errorf("cannot proceed safely after deferred errors")
891 if bal.collScanned == 0 {
892 return fmt.Errorf("received zero collections")
896 bal.BlockStateMap.Apply(func(_ arvados.SizedDigest, blk *BlockState) {
897 for _, desired := range blk.Desired {
905 return fmt.Errorf("zero blocks have desired replication>0")
908 if dr := bal.DefaultReplication; dr < 1 {
909 return fmt.Errorf("Default replication (%d) is less than 1", dr)
912 // TODO: no two services have identical indexes
913 // TODO: no collisions (same md5, different size)
917 // CommitPulls sends the computed lists of pull requests to the
918 // keepstore servers. This has the effect of increasing replication of
919 // existing blocks that are either underreplicated or poorly
920 // distributed according to rendezvous hashing.
921 func (bal *Balancer) CommitPulls(c *arvados.Client) error {
922 return bal.commitAsync(c, "send pull list",
923 func(srv *KeepService) error {
924 return srv.CommitPulls(c)
928 // CommitTrash sends the computed lists of trash requests to the
929 // keepstore servers. This has the effect of deleting blocks that are
930 // overreplicated or unreferenced.
931 func (bal *Balancer) CommitTrash(c *arvados.Client) error {
932 return bal.commitAsync(c, "send trash list",
933 func(srv *KeepService) error {
934 return srv.CommitTrash(c)
938 func (bal *Balancer) commitAsync(c *arvados.Client, label string, f func(srv *KeepService) error) error {
939 errs := make(chan error)
940 for _, srv := range bal.KeepServices {
941 go func(srv *KeepService) {
943 defer func() { errs <- err }()
944 label := fmt.Sprintf("%s: %v", srv, label)
945 defer timeMe(bal.Logger, label)()
948 err = fmt.Errorf("%s: %v", label, err)
953 for range bal.KeepServices {
954 if err := <-errs; err != nil {
963 func (bal *Balancer) logf(f string, args ...interface{}) {
964 if bal.Logger != nil {
965 bal.Logger.Printf(f, args...)
969 // Rendezvous hash sort function. Less efficient than sorting on
970 // precomputed rendezvous hashes, but also rarely used.
971 func rendezvousLess(i, j string, blkid arvados.SizedDigest) bool {
972 a := md5.Sum([]byte(string(blkid[:32]) + i))
973 b := md5.Sum([]byte(string(blkid[:32]) + j))
974 return bytes.Compare(a[:], b[:]) < 0