1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.curoverse.com/arvados.git/sdk/go/arvados"
19 "git.curoverse.com/arvados.git/sdk/go/keepclient"
22 // CheckConfig returns an error if anything is wrong with the given
23 // config and runOptions.
24 func CheckConfig(config Config, runOptions RunOptions) error {
25 if len(config.KeepServiceList.Items) > 0 && config.KeepServiceTypes != nil {
26 return fmt.Errorf("cannot specify both KeepServiceList and KeepServiceTypes in config")
28 if !runOptions.Once && config.RunPeriod == arvados.Duration(0) {
29 return fmt.Errorf("you must either use the -once flag, or specify RunPeriod in config")
34 // Balancer compares the contents of keepstore servers with the
35 // collections stored in Arvados, and issues pull/trash requests
36 // needed to get (closer to) the optimal data layout.
38 // In the optimal data layout: every data block referenced by a
39 // collection is replicated at least as many times as desired by the
40 // collection; there are no unreferenced data blocks older than
41 // BlobSignatureTTL; and all N existing replicas of a given data block
42 // are in the N best positions in rendezvous probe order.
43 type Balancer struct {
45 KeepServices map[string]*KeepService
46 DefaultReplication int
52 serviceRoots map[string]string
57 // Run performs a balance operation using the given config and
58 // runOptions, and returns RunOptions suitable for passing to a
59 // subsequent balance operation.
61 // Run should only be called once on a given Balancer object.
65 // runOptions, err = (&Balancer{}).Run(config, runOptions)
66 func (bal *Balancer) Run(config Config, runOptions RunOptions) (nextRunOptions RunOptions, err error) {
67 nextRunOptions = runOptions
69 bal.Dumper = runOptions.Dumper
70 bal.Logger = runOptions.Logger
71 if bal.Logger == nil {
72 bal.Logger = log.New(os.Stderr, "", log.LstdFlags)
75 defer timeMe(bal.Logger, "Run")()
77 if len(config.KeepServiceList.Items) > 0 {
78 err = bal.SetKeepServices(config.KeepServiceList)
80 err = bal.DiscoverKeepServices(&config.Client, config.KeepServiceTypes)
86 if err = bal.CheckSanityEarly(&config.Client); err != nil {
89 rs := bal.rendezvousState()
90 if runOptions.CommitTrash && rs != runOptions.SafeRendezvousState {
91 if runOptions.SafeRendezvousState != "" {
92 bal.logf("notice: KeepServices list has changed since last run")
94 bal.logf("clearing existing trash lists, in case the new rendezvous order differs from previous run")
95 if err = bal.ClearTrashLists(&config.Client); err != nil {
98 // The current rendezvous state becomes "safe" (i.e.,
99 // OK to compute changes for that state without
100 // clearing existing trash lists) only now, after we
101 // succeed in clearing existing trash lists.
102 nextRunOptions.SafeRendezvousState = rs
104 if err = bal.GetCurrentState(&config.Client, config.CollectionBatchSize, config.CollectionBuffers); err != nil {
107 bal.ComputeChangeSets()
108 bal.PrintStatistics()
109 if err = bal.CheckSanityLate(); err != nil {
112 if runOptions.CommitPulls {
113 err = bal.CommitPulls(&config.Client)
115 // Skip trash if we can't pull. (Too cautious?)
119 if runOptions.CommitTrash {
120 err = bal.CommitTrash(&config.Client)
125 // SetKeepServices sets the list of KeepServices to operate on.
126 func (bal *Balancer) SetKeepServices(srvList arvados.KeepServiceList) error {
127 bal.KeepServices = make(map[string]*KeepService)
128 for _, srv := range srvList.Items {
129 bal.KeepServices[srv.UUID] = &KeepService{
131 ChangeSet: &ChangeSet{},
137 // DiscoverKeepServices sets the list of KeepServices by calling the
138 // API to get a list of all services, and selecting the ones whose
139 // ServiceType is in okTypes.
140 func (bal *Balancer) DiscoverKeepServices(c *arvados.Client, okTypes []string) error {
141 bal.KeepServices = make(map[string]*KeepService)
142 ok := make(map[string]bool)
143 for _, t := range okTypes {
146 return c.EachKeepService(func(srv arvados.KeepService) error {
147 if ok[srv.ServiceType] {
148 bal.KeepServices[srv.UUID] = &KeepService{
150 ChangeSet: &ChangeSet{},
153 bal.logf("skipping %v with service type %q", srv.UUID, srv.ServiceType)
159 // CheckSanityEarly checks for configuration and runtime errors that
160 // can be detected before GetCurrentState() and ComputeChangeSets()
163 // If it returns an error, it is pointless to run GetCurrentState or
164 // ComputeChangeSets: after doing so, the statistics would be
165 // meaningless and it would be dangerous to run any Commit methods.
166 func (bal *Balancer) CheckSanityEarly(c *arvados.Client) error {
167 u, err := c.CurrentUser()
169 return fmt.Errorf("CurrentUser(): %v", err)
171 if !u.IsActive || !u.IsAdmin {
172 return fmt.Errorf("current user (%s) is not an active admin user", u.UUID)
174 for _, srv := range bal.KeepServices {
175 if srv.ServiceType == "proxy" {
176 return fmt.Errorf("config error: %s: proxy servers cannot be balanced", srv)
182 // rendezvousState returns a fingerprint (e.g., a sorted list of
183 // UUID+host+port) of the current set of keep services.
184 func (bal *Balancer) rendezvousState() string {
185 srvs := make([]string, 0, len(bal.KeepServices))
186 for _, srv := range bal.KeepServices {
187 srvs = append(srvs, srv.String())
190 return strings.Join(srvs, "; ")
193 // ClearTrashLists sends an empty trash list to each keep
194 // service. Calling this before GetCurrentState avoids races.
196 // When a block appears in an index, we assume that replica will still
197 // exist after we delete other replicas on other servers. However,
198 // it's possible that a previous rebalancing operation made different
199 // decisions (e.g., servers were added/removed, and rendezvous order
200 // changed). In this case, the replica might already be on that
201 // server's trash list, and it might be deleted before we send a
202 // replacement trash list.
204 // We avoid this problem if we clear all trash lists before getting
205 // indexes. (We also assume there is only one rebalancing process
206 // running at a time.)
207 func (bal *Balancer) ClearTrashLists(c *arvados.Client) error {
208 for _, srv := range bal.KeepServices {
209 srv.ChangeSet = &ChangeSet{}
211 return bal.CommitTrash(c)
214 // GetCurrentState determines the current replication state, and the
215 // desired replication level, for every block that is either
216 // retrievable or referenced.
218 // It determines the current replication state by reading the block index
219 // from every known Keep service.
221 // It determines the desired replication level by retrieving all
222 // collection manifests in the database (API server).
224 // It encodes the resulting information in BlockStateMap.
225 func (bal *Balancer) GetCurrentState(c *arvados.Client, pageSize, bufs int) error {
226 defer timeMe(bal.Logger, "GetCurrentState")()
227 bal.BlockStateMap = NewBlockStateMap()
229 dd, err := c.DiscoveryDocument()
233 bal.DefaultReplication = dd.DefaultCollectionReplication
234 bal.MinMtime = time.Now().UnixNano() - dd.BlobSignatureTTL*1e9
236 errs := make(chan error, 2+len(bal.KeepServices))
237 wg := sync.WaitGroup{}
239 // Start one goroutine for each KeepService: retrieve the
240 // index, and add the returned blocks to BlockStateMap.
241 for _, srv := range bal.KeepServices {
243 go func(srv *KeepService) {
245 bal.logf("%s: retrieve index", srv)
246 idx, err := srv.Index(c, "")
248 errs <- fmt.Errorf("%s: %v", srv, err)
252 // Some other goroutine encountered an
253 // error -- any further effort here
257 bal.logf("%s: add %d replicas to map", srv, len(idx))
258 bal.BlockStateMap.AddReplicas(srv, idx)
259 bal.logf("%s: done", srv)
263 // collQ buffers incoming collections so we can start fetching
264 // the next page without waiting for the current page to
265 // finish processing.
266 collQ := make(chan arvados.Collection, bufs)
268 // Start a goroutine to process collections. (We could use a
269 // worker pool here, but even with a single worker we already
270 // process collections much faster than we can retrieve them.)
274 for coll := range collQ {
275 err := bal.addCollection(coll)
286 // Start a goroutine to retrieve all collections from the
287 // Arvados database and send them to collQ for processing.
291 err = EachCollection(c, pageSize,
292 func(coll arvados.Collection) error {
295 // some other GetCurrentState
296 // error happened: no point
299 return fmt.Errorf("")
302 }, func(done, total int) {
303 bal.logf("collections: %d/%d", done, total)
318 func (bal *Balancer) addCollection(coll arvados.Collection) error {
319 blkids, err := coll.SizedDigests()
322 bal.errors = append(bal.errors, fmt.Errorf("%v: %v", coll.UUID, err))
326 repl := bal.DefaultReplication
327 if coll.ReplicationDesired != nil {
328 repl = *coll.ReplicationDesired
330 debugf("%v: %d block x%d", coll.UUID, len(blkids), repl)
331 bal.BlockStateMap.IncreaseDesired(repl, blkids)
335 // ComputeChangeSets compares, for each known block, the current and
336 // desired replication states. If it is possible to get closer to the
337 // desired state by copying or deleting blocks, it adds those changes
338 // to the relevant KeepServices' ChangeSets.
340 // It does not actually apply any of the computed changes.
341 func (bal *Balancer) ComputeChangeSets() {
342 // This just calls balanceBlock() once for each block, using a
343 // pool of worker goroutines.
344 defer timeMe(bal.Logger, "ComputeChangeSets")()
345 bal.setupServiceRoots()
347 type balanceTask struct {
348 blkid arvados.SizedDigest
351 nWorkers := 1 + runtime.NumCPU()
352 todo := make(chan balanceTask, nWorkers)
353 var wg sync.WaitGroup
354 for i := 0; i < nWorkers; i++ {
357 for work := range todo {
358 bal.balanceBlock(work.blkid, work.blk)
363 bal.BlockStateMap.Apply(func(blkid arvados.SizedDigest, blk *BlockState) {
373 func (bal *Balancer) setupServiceRoots() {
374 bal.serviceRoots = make(map[string]string)
375 for _, srv := range bal.KeepServices {
376 bal.serviceRoots[srv.UUID] = srv.UUID
387 var changeName = map[int]string{
390 changeTrash: "trash",
394 // balanceBlock compares current state to desired state for a single
395 // block, and makes the appropriate ChangeSet calls.
396 func (bal *Balancer) balanceBlock(blkid arvados.SizedDigest, blk *BlockState) {
397 debugf("balanceBlock: %v %+v", blkid, blk)
398 uuids := keepclient.NewRootSorter(bal.serviceRoots, string(blkid[:32])).GetSortedRoots()
399 hasRepl := make(map[string]Replica, len(bal.serviceRoots))
400 for _, repl := range blk.Replicas {
401 hasRepl[repl.UUID] = repl
402 // TODO: when multiple copies are on one server, use
403 // the oldest one that doesn't have a timestamp
404 // collision with other replicas.
406 // number of replicas already found in positions better than
407 // the position we're contemplating now.
408 reportedBestRepl := 0
409 // To be safe we assume two replicas with the same Mtime are
410 // in fact the same replica being reported more than
411 // once. len(uniqueBestRepl) is the number of distinct
412 // replicas in the best rendezvous positions we've considered
414 uniqueBestRepl := make(map[int64]bool, len(bal.serviceRoots))
415 // pulls is the number of Pull changes we have already
416 // requested. (For purposes of deciding whether to Pull to
417 // rendezvous position N, we should assume all pulls we have
418 // requested on rendezvous positions M<N will be successful.)
421 for _, uuid := range uuids {
423 srv := bal.KeepServices[uuid]
424 // TODO: request a Touch if Mtime is duplicated.
425 repl, ok := hasRepl[srv.UUID]
427 // This service has a replica. We should
428 // delete it if [1] we already have enough
429 // distinct replicas in better rendezvous
430 // positions and [2] this replica's Mtime is
431 // distinct from all of the better replicas'
434 repl.Mtime < bal.MinMtime &&
435 len(uniqueBestRepl) >= blk.Desired &&
436 !uniqueBestRepl[repl.Mtime] {
445 uniqueBestRepl[repl.Mtime] = true
447 } else if pulls+reportedBestRepl < blk.Desired &&
448 len(blk.Replicas) > 0 &&
450 // This service doesn't have a replica. We
451 // should pull one to this server if we don't
452 // already have enough (existing+requested)
453 // replicas in better rendezvous positions.
456 Source: blk.Replicas[0].KeepService,
461 if bal.Dumper != nil {
462 changes = append(changes, fmt.Sprintf("%s:%d=%s,%d", srv.ServiceHost, srv.ServicePort, changeName[change], repl.Mtime))
465 if bal.Dumper != nil {
466 bal.Dumper.Printf("%s have=%d want=%d %s", blkid, len(blk.Replicas), blk.Desired, strings.Join(changes, " "))
470 type blocksNBytes struct {
476 func (bb blocksNBytes) String() string {
477 return fmt.Sprintf("%d replicas (%d blocks, %d bytes)", bb.replicas, bb.blocks, bb.bytes)
480 type balancerStats struct {
481 lost, overrep, unref, garbage, underrep, justright blocksNBytes
482 desired, current blocksNBytes
487 func (bal *Balancer) getStatistics() (s balancerStats) {
488 s.replHistogram = make([]int, 2)
489 bal.BlockStateMap.Apply(func(blkid arvados.SizedDigest, blk *BlockState) {
490 surplus := len(blk.Replicas) - blk.Desired
491 bytes := blkid.Size()
493 case len(blk.Replicas) == 0 && blk.Desired > 0:
494 s.lost.replicas -= surplus
496 s.lost.bytes += bytes * int64(-surplus)
497 case len(blk.Replicas) < blk.Desired:
498 s.underrep.replicas -= surplus
500 s.underrep.bytes += bytes * int64(-surplus)
501 case len(blk.Replicas) > 0 && blk.Desired == 0:
502 counter := &s.garbage
503 for _, r := range blk.Replicas {
504 if r.Mtime >= bal.MinMtime {
509 counter.replicas += surplus
511 counter.bytes += bytes * int64(surplus)
512 case len(blk.Replicas) > blk.Desired:
513 s.overrep.replicas += surplus
515 s.overrep.bytes += bytes * int64(len(blk.Replicas)-blk.Desired)
517 s.justright.replicas += blk.Desired
519 s.justright.bytes += bytes * int64(blk.Desired)
523 s.desired.replicas += blk.Desired
525 s.desired.bytes += bytes * int64(blk.Desired)
527 if len(blk.Replicas) > 0 {
528 s.current.replicas += len(blk.Replicas)
530 s.current.bytes += bytes * int64(len(blk.Replicas))
533 for len(s.replHistogram) <= len(blk.Replicas) {
534 s.replHistogram = append(s.replHistogram, 0)
536 s.replHistogram[len(blk.Replicas)]++
538 for _, srv := range bal.KeepServices {
539 s.pulls += len(srv.ChangeSet.Pulls)
540 s.trashes += len(srv.ChangeSet.Trashes)
545 // PrintStatistics writes statistics about the computed changes to
546 // bal.Logger. It should not be called until ComputeChangeSets has
548 func (bal *Balancer) PrintStatistics() {
549 s := bal.getStatistics()
551 bal.logf("%s lost (0=have<want)", s.lost)
552 bal.logf("%s underreplicated (0<have<want)", s.underrep)
553 bal.logf("%s just right (have=want)", s.justright)
554 bal.logf("%s overreplicated (have>want>0)", s.overrep)
555 bal.logf("%s unreferenced (have>want=0, new)", s.unref)
556 bal.logf("%s garbage (have>want=0, old)", s.garbage)
558 bal.logf("%s total commitment (excluding unreferenced)", s.desired)
559 bal.logf("%s total usage", s.current)
561 for _, srv := range bal.KeepServices {
562 bal.logf("%s: %v\n", srv, srv.ChangeSet)
565 bal.printHistogram(s, 60)
569 func (bal *Balancer) printHistogram(s balancerStats, hashColumns int) {
570 bal.logf("Replication level distribution (counting N replicas on a single server as N):")
572 for _, count := range s.replHistogram {
573 if maxCount < count {
577 hashes := strings.Repeat("#", hashColumns)
578 countWidth := 1 + int(math.Log10(float64(maxCount+1)))
579 scaleCount := 10 * float64(hashColumns) / math.Floor(1+10*math.Log10(float64(maxCount+1)))
580 for repl, count := range s.replHistogram {
581 nHashes := int(scaleCount * math.Log10(float64(count+1)))
582 bal.logf("%2d: %*d %s", repl, countWidth, count, hashes[:nHashes])
586 // CheckSanityLate checks for configuration and runtime errors after
587 // GetCurrentState() and ComputeChangeSets() have finished.
589 // If it returns an error, it is dangerous to run any Commit methods.
590 func (bal *Balancer) CheckSanityLate() error {
591 if bal.errors != nil {
592 for _, err := range bal.errors {
593 bal.logf("deferred error: %v", err)
595 return fmt.Errorf("cannot proceed safely after deferred errors")
598 if bal.collScanned == 0 {
599 return fmt.Errorf("received zero collections")
603 bal.BlockStateMap.Apply(func(_ arvados.SizedDigest, blk *BlockState) {
609 return fmt.Errorf("zero blocks have desired replication>0")
612 if dr := bal.DefaultReplication; dr < 1 {
613 return fmt.Errorf("Default replication (%d) is less than 1", dr)
616 // TODO: no two services have identical indexes
617 // TODO: no collisions (same md5, different size)
621 // CommitPulls sends the computed lists of pull requests to the
622 // keepstore servers. This has the effect of increasing replication of
623 // existing blocks that are either underreplicated or poorly
624 // distributed according to rendezvous hashing.
625 func (bal *Balancer) CommitPulls(c *arvados.Client) error {
626 return bal.commitAsync(c, "send pull list",
627 func(srv *KeepService) error {
628 return srv.CommitPulls(c)
632 // CommitTrash sends the computed lists of trash requests to the
633 // keepstore servers. This has the effect of deleting blocks that are
634 // overreplicated or unreferenced.
635 func (bal *Balancer) CommitTrash(c *arvados.Client) error {
636 return bal.commitAsync(c, "send trash list",
637 func(srv *KeepService) error {
638 return srv.CommitTrash(c)
642 func (bal *Balancer) commitAsync(c *arvados.Client, label string, f func(srv *KeepService) error) error {
643 errs := make(chan error)
644 for _, srv := range bal.KeepServices {
645 go func(srv *KeepService) {
647 defer func() { errs <- err }()
648 label := fmt.Sprintf("%s: %v", srv, label)
649 defer timeMe(bal.Logger, label)()
652 err = fmt.Errorf("%s: %v", label, err)
657 for range bal.KeepServices {
658 if err := <-errs; err != nil {
667 func (bal *Balancer) logf(f string, args ...interface{}) {
668 if bal.Logger != nil {
669 bal.Logger.Printf(f, args...)