- 
                Notifications
    
You must be signed in to change notification settings  - Fork 78
 
Implement BadgerDB garbage collection #757
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
  File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| /* | ||
| Copyright 2025 The Flux authors | ||
| 
     | 
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
| 
     | 
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
| 
     | 
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
| package database | ||
| 
     | 
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "time" | ||
| 
     | 
||
| "github.com/dgraph-io/badger/v3" | ||
| "github.com/go-logr/logr" | ||
| ctrl "sigs.k8s.io/controller-runtime" | ||
| ) | ||
| 
     | 
||
| // BadgerGarbageCollector implements controller runtime's Runnable | ||
| type BadgerGarbageCollector struct { | ||
| // DiscardRatio must be a float between 0.0 and 1.0, inclusive | ||
| // See badger.DB.RunValueLogGC for more info | ||
| DiscardRatio float64 | ||
| Interval time.Duration | ||
| 
     | 
||
| name string | ||
| db *badger.DB | ||
| log logr.Logger | ||
| } | ||
| 
     | 
||
| // NewBadgerGarbageCollector creates and returns a new BadgerGarbageCollector | ||
| func NewBadgerGarbageCollector(name string, db *badger.DB, interval time.Duration, discardRatio float64) *BadgerGarbageCollector { | ||
| return &BadgerGarbageCollector{ | ||
| DiscardRatio: discardRatio, | ||
| Interval: interval, | ||
| 
     | 
||
| name: name, | ||
| db: db, | ||
| } | ||
| } | ||
| 
     | 
||
| // Start repeatedly runs the BadgerDB garbage collector with a delay inbetween | ||
| // runs. | ||
| // | ||
| // Start blocks until the context is cancelled. The database is expected to | ||
| // already be open and not be closed while this context is active. | ||
| // | ||
| // ctx should be a logr.Logger context. | ||
| func (gc *BadgerGarbageCollector) Start(ctx context.Context) error { | ||
| gc.log = ctrl.LoggerFrom(ctx).WithName(gc.name) | ||
| 
     | 
||
| gc.log.Info("Starting Badger GC") | ||
| timer := time.NewTimer(gc.Interval) | ||
| for { | ||
| select { | ||
| case <-timer.C: | ||
| gc.discardValueLogFiles() | ||
| timer.Reset(gc.Interval) | ||
| case <-ctx.Done(): | ||
| timer.Stop() | ||
| gc.log.Info("Stopped Badger GC") | ||
| return nil | ||
| } | ||
| } | ||
| } | ||
| 
     | 
||
| // upper bound for loop | ||
| const maxDiscards = 1000 | ||
| 
     | 
||
| func (gc *BadgerGarbageCollector) discardValueLogFiles() { | ||
| gc.log.V(1).Info("Running Badger GC") | ||
| for c := 0; c < maxDiscards; c++ { | ||
| err := gc.db.RunValueLogGC(gc.DiscardRatio) | ||
| if errors.Is(err, badger.ErrNoRewrite) { | ||
| // there is no more garbage to discard | ||
| gc.log.V(1).Info("Ran Badger GC", "discarded_vlogs", c) | ||
| return | ||
| } | ||
| if err != nil { | ||
| gc.log.Error(err, "Badger GC Error", "discarded_vlogs", c) | ||
| return | ||
| } | ||
| } | ||
| gc.log.Error(nil, "Warning: Badger GC ran for maximum discards", "discarded_vlogs", maxDiscards) | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| /* | ||
| Copyright 2020 The Flux authors | ||
| 
     | 
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
| 
     | 
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
| 
     | 
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
| package database | ||
| 
     | 
||
| import ( | ||
| "context" | ||
| "os" | ||
| "testing" | ||
| "time" | ||
| 
     | 
||
| "github.com/dgraph-io/badger/v3" | ||
| "github.com/go-logr/logr" | ||
| "github.com/go-logr/logr/testr" | ||
| ) | ||
| 
     | 
||
| func TestBadgerGarbageCollectorDoesStop(t *testing.T) { | ||
| 
         There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Example Successful run (2.3 seconds) Synthetic Failure (sleep for a minute when stopped) (7.3 seconds)  | 
||
| badger, db := createBadgerDatabaseForGC(t) | ||
| ctx, cancel := context.WithCancel( | ||
| logr.NewContext(context.Background(), | ||
| testr.NewWithOptions(t, testr.Options{Verbosity: 1, LogTimestamp: true}))) | ||
| 
     | 
||
| stop := make(chan struct{}) | ||
| go func() { | ||
| gc := NewBadgerGarbageCollector("test-badger-gc", badger, 500*time.Millisecond, 0.01) | ||
| gc.Start(ctx) | ||
| stop <- struct{}{} | ||
| }() | ||
| 
     | 
||
| time.Sleep(time.Second) | ||
| 
     | 
||
| tags := []string{"latest", "v0.0.1", "v0.0.2"} | ||
| fatalIfError(t, db.SetTags(testRepo, tags)) | ||
| _, err := db.Tags(testRepo) | ||
| fatalIfError(t, err) | ||
| t.Log("wrote tags successfully") | ||
| 
     | 
||
| time.Sleep(time.Second) | ||
| 
     | 
||
| cancel() | ||
| t.Log("waiting for GC stop") | ||
| select { | ||
| case <-time.NewTimer(5 * time.Second).C: | ||
| t.Fatalf("GC did not stop") | ||
| case <-stop: | ||
| t.Log("GC Stopped") | ||
| } | ||
| } | ||
| 
     | 
||
| func createBadgerDatabaseForGC(t *testing.T) (*badger.DB, *BadgerDatabase) { | ||
| t.Helper() | ||
| dir, err := os.MkdirTemp(os.TempDir(), t.Name()) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| db, err := badger.Open(badger.DefaultOptions(dir)) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| t.Cleanup(func() { | ||
| db.Close() | ||
| os.RemoveAll(dir) | ||
| }) | ||
| return db, NewBadgerDatabase(db) | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't know if this is a reasonable value of discards, but it felt like the controller could sample, delete, and rewrite 1000 value log files relatively quickly in its own goroutine without impacting the controller-runtime too much.