Skip to content

Find, verify, and analyze leaked credentials

Show progress inside S3 buckets (#5330)

Shahzad Haiderb170a2800f02
diff --git a/pkg/feature/feature.go b/pkg/feature/feature.go
index 65f83c869..efe2f86d5 100644
--- a/pkg/feature/feature.go
+++ b/pkg/feature/feature.go
@@ -54,6 +54,7 @@ var (
ResendDetectorEnabled atomic.Bool
WeightsAndBiasesV2DetectorEnabled atomic.Bool
HumioAPITokenDetectorEnabled atomic.Bool
+ EnableS3UnitProgress atomic.Bool // count each S3 bucket during a unit scan to report progress inside it
)
type AtomicString struct {
diff --git a/pkg/sources/job_progress.go b/pkg/sources/job_progress.go
index a175987bf..88d6f3a1d 100644
--- a/pkg/sources/job_progress.go
+++ b/pkg/sources/job_progress.go
@@ -74,6 +74,15 @@ func (r *JobProgressRef) Err() error {
return r.jobProgress.Err()
}
+// UnitProgress returns the progress the source last reported inside the unit
+// with the provided ID, and whether it reported any.
+func (r *JobProgressRef) UnitProgress(unitID string) (UnitProgress, bool) {
+ if r.jobProgress == nil {
+ return UnitProgress{}, false
+ }
+ return r.jobProgress.UnitProgress(unitID)
+}
+
// Done returns a channel that will block until the job has completed.
func (r *JobProgressRef) Done() <-chan struct{} {
if r.jobProgress == nil {
@@ -336,6 +345,19 @@ func (jp *JobProgress) Snapshot() JobProgressMetrics {
return metrics
}
+// UnitProgress safely gets the progress the source last reported inside the
+// unit with the provided ID.
+func (jp *JobProgress) UnitProgress(unitID string) (UnitProgress, bool) {
+ jp.metricsLock.Lock()
+ progress := jp.progress
+ jp.metricsLock.Unlock()
+
+ if progress == nil {
+ return UnitProgress{}, false
+ }
+ return progress.GetUnitProgressFor(unitID)
+}
+
// ReportError adds a non-nil error to the aggregate of errors
// encountered during scanning.
func (jp *JobProgress) ReportError(err error) {
diff --git a/pkg/sources/job_progress_test.go b/pkg/sources/job_progress_test.go
index c56c85de3..9058c4a72 100644
--- a/pkg/sources/job_progress_test.go
+++ b/pkg/sources/job_progress_test.go
@@ -223,3 +223,26 @@ func TestJobProgressErrorsFor(t *testing.T) {
assert.Equal(t, 1, len(metrics.ErrorsFor(CommonSourceUnit{ID: "bar"})))
assert.Equal(t, 0, len(metrics.ErrorsFor(CommonSourceUnit{ID: "baz"})))
}
+
+func TestJobProgressRefUnitProgress(t *testing.T) {
+ var progress Progress
+ jp := NewJobProgress(123, 456, "source name")
+ jp.TrackProgress(&progress)
+ ref := jp.Ref()
+
+ _, ok := ref.UnitProgress("unit")
+ assert.False(t, ok)
+
+ want := UnitProgress{State: UnitProgressCounting, ItemsDone: 3, BytesDone: 300}
+ progress.SetUnitProgressFor("unit", want)
+ got, ok := ref.UnitProgress("unit")
+ assert.True(t, ok)
+ assert.Equal(t, want, got)
+
+ // A ref to no job, or to a job whose source reports no progress, has none to give.
+ _, ok = (&JobProgressRef{}).UnitProgress("unit")
+ assert.False(t, ok)
+ untracked := NewJobProgress(123, 456, "source name").Ref()
+ _, ok = untracked.UnitProgress("unit")
+ assert.False(t, ok)
+}
diff --git a/pkg/sources/s3/progress.go b/pkg/sources/s3/progress.go
new file mode 100644
index 000000000..870277e64
--- /dev/null
+++ b/pkg/sources/s3/progress.go
@@ -0,0 +1,152 @@
+package s3
+
+import (
+ "sync"
+
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/common"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/sources"
+)
+
+// unitProgress tracks how far a unit scan has got through its bucket and publishes it on the source's
+// Progress under the unit's ID. Each ChunkUnit call has its own, so buckets scanned at the same time
+// never mix their counts.
+type unitProgress struct {
+ unitID string
+ progress *sources.Progress
+
+ mu sync.Mutex
+ current sources.UnitProgress
+ finished bool
+}
+
+func newUnitProgress(unitID string, progress *sources.Progress) *unitProgress {
+ return &unitProgress{unitID: unitID, progress: progress}
+}
+
+// update applies f and publishes the result. Publishing under the lock keeps an older value from
+// replacing a newer one. Nothing changes once the unit has finished.
+func (p *unitProgress) update(f func(current *sources.UnitProgress)) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.finished {
+ return
+ }
+ f(&p.current)
+ p.progress.SetUnitProgressFor(p.unitID, p.current)
+}
+
+// objectDone records that the scan is finished with an object it downloads, whether or not the
+// download worked. It does nothing on a nil receiver, which is how a legacy scan runs.
+func (p *unitProgress) objectDone(size int64) {
+ if p == nil {
+ return
+ }
+ p.update(func(current *sources.UnitProgress) {
+ current.ItemsDone++
+ current.BytesDone += uint64(max(size, 0))
+ })
+}
+
+// counted adds a listed page to the totals. Objects an earlier run finished count as done too.
+func (p *unitProgress) counted(items, bytes, resumedItems, resumedBytes uint64) {
+ p.update(func(current *sources.UnitProgress) {
+ current.ItemsTotal += items
+ current.BytesTotal += bytes
+ current.ItemsDone += resumedItems
+ current.BytesDone += resumedBytes
+ current.ResumedBytes += resumedBytes
+ })
+}
+
+func (p *unitProgress) setState(state sources.UnitProgressState) {
+ p.update(func(current *sources.UnitProgress) { current.State = state })
+}
+
+// finish settles the totals once the scan of the bucket has ended. scannedWholeBucket means the scan
+// listed the bucket from the start to the end, so it has seen every object there is.
+func (p *unitProgress) finish(scannedWholeBucket bool) {
+ p.update(func(current *sources.UnitProgress) {
+ switch {
+ case current.State == sources.UnitProgressReady:
+ // Objects added during the scan can take the done count past the total.
+ current.ItemsTotal = max(current.ItemsTotal, current.ItemsDone)
+ current.BytesTotal = max(current.BytesTotal, current.BytesDone)
+ case scannedWholeBucket:
+ // The count pass did not get to the end, but the scan did, so what it did is the total.
+ current.ItemsTotal = current.ItemsDone
+ current.BytesTotal = current.BytesDone
+ current.State = sources.UnitProgressReady
+ default:
+ current.State = sources.UnitProgressUnavailable
+ }
+ p.finished = true
+ })
+}
+
+// startCount runs the count pass alongside the scan. It returns a function that stops the count and
+// waits for it to exit, so nothing is counted after the unit finishes.
+func (s *Source) startCount(
+ ctx context.Context,
+ client *s3.Client,
+ bucket string,
+ startAfter *string,
+ progress *unitProgress,
+) func() {
+ countCtx, cancel := context.WithCancel(ctx)
+ done := make(chan struct{})
+
+ progress.setState(sources.UnitProgressCounting)
+ go func() {
+ defer close(done)
+ defer common.Recover(countCtx)
+ s.countBucket(countCtx, client, bucket, startAfter, progress)
+ }()
+
+ return func() {
+ cancel()
+ <-done
+ }
+}
+
+// countBucket lists the whole bucket once to add up the objects the scan downloads and their size,
+// since S3 has no API that reports either. Keys at or before startAfter were finished by an earlier
+// run, so they count as done too. Nothing is kept per object.
+func (s *Source) countBucket(
+ ctx context.Context,
+ client *s3.Client,
+ bucket string,
+ startAfter *string,
+ progress *unitProgress,
+) {
+ paginator := s3.NewListObjectsV2Paginator(client, &s3.ListObjectsV2Input{Bucket: &bucket})
+ for paginator.HasMorePages() {
+ page, err := paginator.NextPage(ctx)
+ if err != nil {
+ // A cancelled count means the unit has finished, and finish settles the totals.
+ if ctx.Err() == nil {
+ ctx.Logger().V(2).Info("could not count objects for progress", "bucket", bucket, "err", err)
+ progress.setState(sources.UnitProgressUnavailable)
+ }
+ return
+ }
+
+ var items, bytes, resumedItems, resumedBytes uint64
+ for _, obj := range page.Contents {
+ if s.skipReason(obj) != "" {
+ continue
+ }
+ size := uint64(max(*obj.Size, 0))
+ items++
+ bytes += size
+ if startAfter != nil && *obj.Key <= *startAfter {
+ resumedItems++
+ resumedBytes += size
+ }
+ }
+ progress.counted(items, bytes, resumedItems, resumedBytes)
+ }
+ progress.setState(sources.UnitProgressReady)
+}
diff --git a/pkg/sources/s3/progress_test.go b/pkg/sources/s3/progress_test.go
new file mode 100644
index 000000000..96f63b821
--- /dev/null
+++ b/pkg/sources/s3/progress_test.go
@@ -0,0 +1,344 @@
+package s3
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/anypb"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/feature"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/sources"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/sourcestest"
+)
+
+func TestUnitProgress_CountThenScan(t *testing.T) {
+ var progress sources.Progress
+ p := newUnitProgress("unit", &progress)
+
+ p.setState(sources.UnitProgressCounting)
+ p.counted(4, 4000, 1, 1000)
+
+ got, ok := progress.GetUnitProgressFor("unit")
+ require.True(t, ok)
+ assert.Equal(t, sources.UnitProgress{
+ State: sources.UnitProgressCounting,
+ ItemsDone: 1,
+ ItemsTotal: 4,
+ BytesDone: 1000,
+ BytesTotal: 4000,
+ ResumedBytes: 1000,
+ }, got)
+ assert.Zero(t, got.Percent(), "no percent while the total is still being counted")
+
+ p.setState(sources.UnitProgressReady)
+ p.objectDone(1000)
+
+ got, _ = progress.GetUnitProgressFor("unit")
+ assert.EqualValues(t, 2, got.ItemsDone)
+ assert.EqualValues(t, 2000, got.BytesDone)
+ assert.EqualValues(t, 50, got.Percent())
+}
+
+func TestUnitProgress_Finish(t *testing.T) {
+ tests := []struct {
+ name string
+ state sources.UnitProgressState
+ itemsTotal uint64
+ itemsDone uint64
+ scannedWholeBucket bool
+ wantState sources.UnitProgressState
+ wantItemsTotal uint64
+ }{
+ {
+ name: "counted, and objects added during the scan",
+ state: sources.UnitProgressReady, itemsTotal: 4, itemsDone: 5, scannedWholeBucket: true,
+ wantState: sources.UnitProgressReady, wantItemsTotal: 5,
+ },
+ {
+ name: "counted, and the scan listing broke off",
+ state: sources.UnitProgressReady, itemsTotal: 4, itemsDone: 2,
+ wantState: sources.UnitProgressReady, wantItemsTotal: 4,
+ },
+ {
+ name: "scan listed the whole bucket before the count finished",
+ state: sources.UnitProgressCounting, itemsTotal: 1, itemsDone: 3, scannedWholeBucket: true,
+ wantState: sources.UnitProgressReady, wantItemsTotal: 3,
+ },
+ {
+ name: "count failed but the scan listed the whole bucket",
+ state: sources.UnitProgressUnavailable, itemsTotal: 1, itemsDone: 3, scannedWholeBucket: true,
+ wantState: sources.UnitProgressReady, wantItemsTotal: 3,
+ },
+ {
+ name: "resumed scan finished before the count",
+ state: sources.UnitProgressCounting, itemsTotal: 1, itemsDone: 3,
+ wantState: sources.UnitProgressUnavailable, wantItemsTotal: 1,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var progress sources.Progress
+ p := newUnitProgress("unit", &progress)
+ p.setState(tt.state)
+ p.counted(tt.itemsTotal, tt.itemsTotal*100, 0, 0)
+ for range tt.itemsDone {
+ p.objectDone(100)
+ }
+
+ p.finish(tt.scannedWholeBucket)
+
+ got, _ := progress.GetUnitProgressFor("unit")
+ assert.Equal(t, tt.wantState, got.State)
+ assert.Equal(t, tt.wantItemsTotal, got.ItemsTotal)
+ assert.Equal(t, tt.wantItemsTotal*100, got.BytesTotal)
+ assert.Equal(t, tt.itemsDone, got.ItemsDone)
+ })
+ }
+}
+
+func TestUnitProgress_IgnoresUpdatesAfterFinish(t *testing.T) {
+ var progress sources.Progress
+ p := newUnitProgress("unit", &progress)
+ p.objectDone(100)
+ p.finish(true)
+ want, _ := progress.GetUnitProgressFor("unit")
+
+ p.objectDone(100)
+ p.counted(5, 500, 0, 0)
+ p.setState(sources.UnitProgressUnavailable)
+
+ got, _ := progress.GetUnitProgressFor("unit")
+ assert.Equal(t, want, got)
+}
+
+func TestUnitProgress_NilIsANoOp(t *testing.T) {
+ var p *unitProgress
+ assert.NotPanics(t, func() { p.objectDone(100) })
+}
+
+// fakeBucket is a bucket served by fakeS3.
+type fakeBucket struct {
+ objects map[string]string
+ // countDelay holds back listings that start from the beginning of the bucket, which only the count
+ // makes when the scan is resumed, so a test can make the scan finish first.
+ countDelay time.Duration
+}
+
+// fakeS3 serves the parts of the S3 API a unit scan uses, path style, two keys per page.
+type fakeS3 struct {
+ buckets map[string]fakeBucket
+ getDelay time.Duration
+ listCalls atomic.Int32
+}
+
+func (f *fakeS3) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ name, key, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/")
+ bucket, ok := f.buckets[name]
+ if !ok {
+ http.Error(w, "no such bucket", http.StatusNotFound)
+ return
+ }
+
+ if key == "" {
+ f.list(w, r, name, bucket)
+ return
+ }
+
+ if !sleep(r, f.getDelay) {
+ return
+ }
+ body, ok := bucket.objects[key]
+ if !ok {
+ http.Error(w, "no such key", http.StatusNotFound)
+ return
+ }
+ _, _ = w.Write([]byte(body))
+}
+
+func (f *fakeS3) list(w http.ResponseWriter, r *http.Request, name string, bucket fakeBucket) {
+ f.listCalls.Add(1)
+ const pageSize = 2
+
+ query := r.URL.Query()
+ after := query.Get("continuation-token")
+ if after == "" {
+ after = query.Get("start-after")
+ if after == "" && !sleep(r, bucket.countDelay) {
+ return
+ }
+ }
+
+ keys := make([]string, 0, len(bucket.objects))
+ for key := range bucket.objects {
+ if key > after {
+ keys = append(keys, key)
+ }
+ }
+ slices.Sort(keys)
+ truncated := len(keys) > pageSize
+ if truncated {
+ keys = keys[:pageSize]
+ }
+
+ var b strings.Builder
+ fmt.Fprintf(&b, `<?xml version="1.0" encoding="UTF-8"?><ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`+
+ `<Name>%s</Name><KeyCount>%d</KeyCount><MaxKeys>1000</MaxKeys><IsTruncated>%t</IsTruncated>`, name, len(keys), truncated)
+ for _, key := range keys {
+ fmt.Fprintf(&b, `<Contents><Key>%s</Key><LastModified>2024-01-01T00:00:00.000Z</LastModified><Size>%d</Size>`+
+ `<StorageClass>STANDARD</StorageClass></Contents>`, key, len(bucket.objects[key]))
+ }
+ if truncated {
+ fmt.Fprintf(&b, `<NextContinuationToken>%s</NextContinuationToken>`, keys[len(keys)-1])
+ }
+ b.WriteString(`</ListBucketResult>`)
+
+ w.Header().Set("Content-Type", "application/xml")
+ _, _ = w.Write([]byte(b.String()))
+}
+
+// sleep waits for d unless the request is cancelled first, and reports whether it waited the whole time.
+func sleep(r *http.Request, d time.Duration) bool {
+ if d == 0 {
+ return true
+ }
+ select {
+ case <-time.After(d):
+ return true
+ case <-r.Context().Done():
+ return false
+ }
+}
+
+// newFakeS3Source starts fake as an S3-compatible endpoint and returns a source initialized against it.
+func newFakeS3Source(t *testing.T, fake *fakeS3) *Source {
+ t.Helper()
+ server := httptest.NewServer(fake)
+ t.Cleanup(server.Close)
+
+ conn, err := anypb.New(&sourcespb.S3{
+ Credential: &sourcespb.S3_Unauthenticated{},
+ Endpoint: server.URL,
+ })
+ require.NoError(t, err)
+
+ s := &Source{}
+ require.NoError(t, s.Init(context.Background(), "s3 test source", 0, 0, false, conn, 1))
+ return s
+}
+
+func enableUnitProgress(t *testing.T) {
+ t.Helper()
+ feature.EnableS3UnitProgress.Store(true)
+ t.Cleanup(func() { feature.EnableS3UnitProgress.Store(false) })
+}
+
+// testObjects are three objects of 10, 20 and 30 bytes, and one the scan skips as empty.
+func testObjects() map[string]string {
+ return map[string]string{
+ "a.txt": strings.Repeat("a", 10),
+ "b.txt": strings.Repeat("b", 20),
+ "c.txt": strings.Repeat("c", 30),
+ "empty.txt": "",
+ }
+}
+
+func TestSource_ChunkUnit_UnitProgress(t *testing.T) {
+ enableUnitProgress(t)
+ fake := &fakeS3{buckets: map[string]fakeBucket{"bucket": {objects: testObjects()}}}
+ s := newFakeS3Source(t, fake)
+
+ unit := S3SourceUnit{Bucket: "bucket"}
+ reporter := sourcestest.TestReporter{}
+ require.NoError(t, s.ChunkUnit(context.Background(), unit, &reporter))
+
+ unitID, _ := unit.SourceUnitID()
+ got, ok := s.GetUnitProgressFor(unitID)
+ require.True(t, ok)
+ assert.Equal(t, sources.UnitProgress{
+ State: sources.UnitProgressReady,
+ ItemsDone: 3,
+ ItemsTotal: 3,
+ BytesDone: 60,
+ BytesTotal: 60,
+ }, got)
+ assert.EqualValues(t, 99, got.Percent())
+ assert.NotEmpty(t, reporter.Chunks)
+}
+
+func TestSource_ChunkUnit_ResumedUnitProgress(t *testing.T) {
+ enableUnitProgress(t)
+ // Slow downloads let the count finish first.
+ fake := &fakeS3{buckets: map[string]fakeBucket{"bucket": {objects: testObjects()}}, getDelay: 200 * time.Millisecond}
+ s := newFakeS3Source(t, fake)
+
+ unit := S3SourceUnit{Bucket: "bucket"}
+ unitID, _ := unit.SourceUnitID()
+ s.SetEncodedResumeInfoFor(unitID, "a.txt")
+
+ require.NoError(t, s.ChunkUnit(context.Background(), unit, &sourcestest.TestReporter{}))
+
+ got, _ := s.GetUnitProgressFor(unitID)
+ assert.Equal(t, sources.UnitProgress{
+ State: sources.UnitProgressReady,
+ ItemsDone: 3,
+ ItemsTotal: 3,
+ BytesDone: 60,
+ BytesTotal: 60,
+ ResumedBytes: 10,
+ }, got, "the object an earlier run finished counts as done")
+}
+
+// With one progress shared by every bucket, a count cut short in one bucket left the others at 0%.
+// Each unit now has its own, so one bucket's count cannot affect another's.
+func TestSource_ChunkUnit_UnitsDoNotShareProgress(t *testing.T) {
+ enableUnitProgress(t)
+ fake := &fakeS3{buckets: map[string]fakeBucket{
+ "resumed": {objects: testObjects(), countDelay: 10 * time.Second},
+ "fresh": {objects: testObjects()},
+ }}
+ s := newFakeS3Source(t, fake)
+
+ // The resumed scan finishes long before its count, which is cancelled.
+ resumed := S3SourceUnit{Bucket: "resumed"}
+ resumedID, _ := resumed.SourceUnitID()
+ s.SetEncodedResumeInfoFor(resumedID, "a.txt")
+ require.NoError(t, s.ChunkUnit(context.Background(), resumed, &sourcestest.TestReporter{}))
+
+ fresh := S3SourceUnit{Bucket: "fresh"}
+ require.NoError(t, s.ChunkUnit(context.Background(), fresh, &sourcestest.TestReporter{}))
+
+ got, _ := s.GetUnitProgressFor(resumedID)
+ assert.Equal(t, sources.UnitProgressUnavailable, got.State, "a resumed bucket with no count has no total")
+ assert.EqualValues(t, 2, got.ItemsDone)
+ assert.Zero(t, got.Percent())
+
+ freshID, _ := fresh.SourceUnitID()
+ got, _ = s.GetUnitProgressFor(freshID)
+ assert.Equal(t, sources.UnitProgressReady, got.State)
+ assert.EqualValues(t, 60, got.BytesTotal)
+ assert.EqualValues(t, 99, got.Percent())
+}
+
+func TestSource_ChunkUnit_NoUnitProgressUnlessEnabled(t *testing.T) {
+ fake := &fakeS3{buckets: map[string]fakeBucket{"bucket": {objects: testObjects()}}}
+ s := newFakeS3Source(t, fake)
+
+ unit := S3SourceUnit{Bucket: "bucket"}
+ require.NoError(t, s.ChunkUnit(context.Background(), unit, &sourcestest.TestReporter{}))
+
+ unitID, _ := unit.SourceUnitID()
+ _, ok := s.GetUnitProgressFor(unitID)
+ assert.False(t, ok)
+ assert.EqualValues(t, 2, fake.listCalls.Load(), "only the scan lists the bucket")
+}
diff --git a/pkg/sources/s3/s3.go b/pkg/sources/s3/s3.go
index d4de282f4..1165b28f0 100644
--- a/pkg/sources/s3/s3.go
+++ b/pkg/sources/s3/s3.go
@@ -26,6 +26,7 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/feature"
"github.com/trufflesecurity/trufflehog/v3/pkg/handlers"
"github.com/trufflesecurity/trufflehog/v3/pkg/log"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/source_metadatapb"
@@ -306,9 +307,10 @@ type pageMetadata struct {
// processingState tracks the state of concurrent S3 object processing.
type processingState struct {
- errorCount *sync.Map // Thread-safe map tracking errors per prefix
- objectCount *uint64 // Total number of objects processed
- filteredCount *uint64 // Total number of objects excluded by the object filter
+ errorCount *sync.Map // Thread-safe map tracking errors per prefix
+ objectCount *uint64 // Total number of objects processed
+ filteredCount *uint64 // Total number of objects excluded by the object filter
+ progress *unitProgress // Progress inside the unit, nil for a legacy scan
}
// resumePosition tracks where to restart scanning S3 buckets and objects after an interruption.
@@ -419,7 +421,7 @@ func (s *Source) scanBuckets(
)
}
- objectCount := s.scanBucket(ctx, client, role, bucket, sources.ChanReporter{Ch: chunksChan}, startAfter, checkpointer)
+ objectCount := s.scanBucket(ctx, client, role, bucket, sources.ChanReporter{Ch: chunksChan}, startAfter, checkpointer, nil)
*totalObjectCount += objectCount
}
@@ -439,6 +441,7 @@ func (s *Source) scanBucket(
reporter sources.ChunkReporter,
startAfter *string,
checkpointer *Checkpointer,
+ progress *unitProgress,
) uint64 {
s.metricsCollector.RecordBucketForRole(role)
@@ -457,6 +460,16 @@ func (s *Source) scanBucket(
return 0
}
+ // scannedWholeBucket is set once the listing below has gone from the start of the bucket to the end.
+ var scannedWholeBucket bool
+ if progress != nil {
+ stopCount := s.startCount(ctx, regionalClient, bucket, startAfter, progress)
+ defer func() {
+ stopCount()
+ progress.finish(scannedWholeBucket)
+ }()
+ }
+
errorCount := sync.Map{}
input := &s3.ListObjectsV2Input{Bucket: &bucket}
@@ -467,6 +480,7 @@ func (s *Source) scanBucket(
pageNumber := 1
paginator := s3.NewListObjectsV2Paginator(regionalClient, input)
var objectCount, filteredCount uint64
+ listFailed := false
for paginator.HasMorePages() {
output, err := paginator.NextPage(ctx)
if err != nil {
@@ -483,6 +497,7 @@ func (s *Source) scanBucket(
ctx.Logger().Error(err, "could not list objects in bucket")
}
s.metricsCollector.RecordBucketListError(bucket, role)
+ listFailed = true
break
}
pageMetadata := pageMetadata{
@@ -496,11 +511,13 @@ func (s *Source) scanBucket(
errorCount: &errorCount,
objectCount: &objectCount,
filteredCount: &filteredCount,
+ progress: progress,
}
s.pageChunker(ctx, pageMetadata, processingState, reporter, checkpointer)
pageNumber++
}
+ scannedWholeBucket = startAfter == nil && !listFailed && ctx.Err() == nil
// A filter that excludes everything otherwise looks exactly like a clean scan
// of an empty bucket, so say so rather than finishing silently.
@@ -561,6 +578,35 @@ func (s *Source) getRegionalClientForBucket(
return regionalClient, nil
}
+// Reasons the scan skips an object without downloading it. They are also the reason label on the
+// skipped objects metric.
+const (
+ skipReasonObjectFilter = "object_filter"
+ skipReasonStorageClass = "storage_class"
+ skipReasonSizeLimit = "size_limit"
+ skipReasonEmptyFile = "empty_file"
+ skipReasonIncompatibleExtension = "incompatible_extension"
+)
+
+// skipReason returns why the scan skips an object without downloading it, or "" if it downloads it.
+// The count pass uses it too, so the progress total holds exactly the objects the scan downloads.
+func (s *Source) skipReason(obj s3types.Object) string {
+ switch {
+ case !s.objectFilter.shouldInclude(*obj.Key):
+ return skipReasonObjectFilter
+ case obj.StorageClass == s3types.ObjectStorageClassGlacier || obj.StorageClass == s3types.ObjectStorageClassGlacierIr:
+ return skipReasonStorageClass
+ case *obj.Size > s.maxObjectSize:
+ return skipReasonSizeLimit
+ case *obj.Size == 0:
+ return skipReasonEmptyFile
+ case common.SkipFile(*obj.Key):
+ return skipReasonIncompatibleExtension
+ default:
+ return ""
+ }
+}
+
// pageChunker emits chunks onto the given channel from a page.
func (s *Source) pageChunker(
ctx context.Context,
@@ -577,53 +623,16 @@ func (s *Source) pageChunker(
return
}
- // Skip objects excluded by the configured prefixes or extensions.
- if !s.objectFilter.shouldInclude(*obj.Key) {
- atomic.AddUint64(state.filteredCount, 1)
- octx.Logger().V(5).Info("Skipping filtered object")
- s.metricsCollector.RecordObjectSkipped(metadata.bucket, "object_filter", float64(*obj.Size))
- if err := checkpointer.UpdateObjectCompletion(octx, objIdx, metadata.bucket, metadata.role, metadata.page.Contents); err != nil {
- octx.Logger().Error(err, "could not update progress for filtered object")
+ // Skip objects the scan never downloads: filtered, Glacier, too large, empty or of an
+ // incompatible extension. They are left out of the unit's progress on both sides.
+ if reason := s.skipReason(obj); reason != "" {
+ if reason == skipReasonObjectFilter {
+ atomic.AddUint64(state.filteredCount, 1)
}
- continue
- }
-
- // Skip GLACIER and GLACIER_IR objects.
- if obj.StorageClass == s3types.ObjectStorageClassGlacier || obj.StorageClass == s3types.ObjectStorageClassGlacierIr {
- octx.Logger().V(5).Info("Skipping object in storage class", "storage_class", obj.StorageClass)
- s.metricsCollector.RecordObjectSkipped(metadata.bucket, "storage_class", float64(*obj.Size))
+ octx.Logger().V(5).Info("Skipping object", "reason", reason)
+ s.metricsCollector.RecordObjectSkipped(metadata.bucket, reason, float64(*obj.Size))
if err := checkpointer.UpdateObjectCompletion(octx, objIdx, metadata.bucket, metadata.role, metadata.page.Contents); err != nil {
- octx.Logger().Error(err, "could not update progress for glacier object")
- }
- continue
- }
-
- // Ignore large files.
- if *obj.Size > s.maxObjectSize {
- octx.Logger().V(5).Info("Skipping large file", "max_object_size", s.maxObjectSize)
- s.metricsCollector.RecordObjectSkipped(metadata.bucket, "size_limit", float64(*obj.Size))
- if err := checkpointer.UpdateObjectCompletion(octx, objIdx, metadata.bucket, metadata.role, metadata.page.Contents); err != nil {
- octx.Logger().Error(err, "could not update progress for large file")
- }
- continue
- }
-
- // File empty file.
- if *obj.Size == 0 {
- octx.Logger().V(5).Info("Skipping empty file")
- s.metricsCollector.RecordObjectSkipped(metadata.bucket, "empty_file", 0)
- if err := checkpointer.UpdateObjectCompletion(octx, objIdx, metadata.bucket, metadata.role, metadata.page.Contents); err != nil {
- octx.Logger().Error(err, "could not update progress for empty file")
- }
- continue
- }
-
- // Skip incompatible extensions.
- if common.SkipFile(*obj.Key) {
- octx.Logger().V(5).Info("Skipping file with incompatible extension")
- s.metricsCollector.RecordObjectSkipped(metadata.bucket, "incompatible_extension", float64(*obj.Size))
- if err := checkpointer.UpdateObjectCompletion(octx, objIdx, metadata.bucket, metadata.role, metadata.page.Contents); err != nil {
- octx.Logger().Error(err, "could not update progress for incompatible file")
+ octx.Logger().Error(err, "could not update progress for skipped object", "reason", reason)
}
continue
}
@@ -633,6 +642,7 @@ func (s *Source) pageChunker(
if common.IsDone(octx) {
return octx.Err()
}
+ defer state.progress.objectDone(*obj.Size)
if strings.HasSuffix(*obj.Key, "/") {
octx.Logger().V(5).Info("Skipping directory")
@@ -888,7 +898,13 @@ func (s *Source) ChunkUnit(ctx context.Context, unit sources.SourceUnit, reporte
startAfterPtr = &startAfter
}
defer s.ClearEncodedResumeInfoFor(unitID)
- s.scanBucket(ctx, defaultClient, s3unit.Role, s3unit.Bucket, reporter, startAfterPtr, checkpointer)
+
+ // Counting the bucket costs an extra listing of it, so it only runs where something reads the result.
+ var progress *unitProgress
+ if feature.EnableS3UnitProgress.Load() {
+ progress = newUnitProgress(unitID, &s.Progress)
+ }
+ s.scanBucket(ctx, defaultClient, s3unit.Role, s3unit.Bucket, reporter, startAfterPtr, checkpointer, progress)
return nil
}
diff --git a/pkg/sources/s3/s3_integration_test.go b/pkg/sources/s3/s3_integration_test.go
index 002864ce8..43aa1fc0c 100644
--- a/pkg/sources/s3/s3_integration_test.go
+++ b/pkg/sources/s3/s3_integration_test.go
@@ -644,3 +644,34 @@ func TestSourceChunksResumptionWithRole(t *testing.T) {
assert.Equal(t, 9638, count, "Should have processed all remaining data on resume")
assert.Less(t, count, sourceTotalChunkCount, "Should have processed less than total chunks on resume")
}
+
+func TestSource_ChunkUnit_ReportsUnitProgress(t *testing.T) {
+ enableUnitProgress(t)
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
+ defer cancel()
+
+ conn, err := anypb.New(&sourcespb.S3{
+ Credential: &sourcespb.S3_Unauthenticated{},
+ Buckets: []string{"truffletestbucket"},
+ })
+ require.NoError(t, err)
+
+ s := Source{}
+ require.NoError(t, s.Init(ctx, "test percent", 0, 0, false, conn, 1))
+
+ reporter := sourcestest.TestReporter{}
+ require.NoError(t, s.Enumerate(ctx, &reporter))
+ require.Len(t, reporter.Units, 1)
+ require.NoError(t, s.ChunkUnit(ctx, reporter.Units[0], &reporter))
+
+ unitID, _ := reporter.Units[0].SourceUnitID()
+ progress, ok := s.GetUnitProgressFor(unitID)
+ require.True(t, ok)
+ assert.Equal(t, sources.UnitProgressReady, progress.State)
+ assert.Positive(t, progress.ItemsTotal)
+ assert.Equal(t, progress.ItemsTotal, progress.ItemsDone)
+ assert.Equal(t, progress.BytesTotal, progress.BytesDone)
+ assert.EqualValues(t, 99, progress.Percent())
+ assert.Empty(t, s.GetEncodedResumeInfoFor(unitID))
+}
diff --git a/pkg/sources/s3/s3_test.go b/pkg/sources/s3/s3_test.go
index e57b7cc90..5f5ecb640 100644
--- a/pkg/sources/s3/s3_test.go
+++ b/pkg/sources/s3/s3_test.go
@@ -531,3 +531,120 @@ func TestSource_PageChunker_FilteredObjectsAdvanceCheckpoint(t *testing.T) {
assert.Equal(t, "test-bucket", resumeInfo.CurrentBucket)
assert.Equal(t, *page.Contents[objectCount-1].Key, resumeInfo.StartAfter)
}
+
+func TestSource_PageChunker_UnitScanLeavesSkippedObjectsOutOfProgress(t *testing.T) {
+ ctx := context.Background()
+
+ conn, err := anypb.New(&sourcespb.S3{
+ Credential: &sourcespb.S3_Unauthenticated{},
+ ExcludePrefixes: []string{"archive/"},
+ MaxObjectSize: 1024,
+ })
+ require.NoError(t, err)
+
+ s := Source{}
+ require.NoError(t, s.Init(ctx, "s3 test source", 0, 0, false, conn, 1))
+ s.SetEncodedResumeInfoFor("test-bucket", "earlier-key")
+
+ filteredKey, glacierKey, oversizeKey, emptyKey, imageKey := "archive/a.txt", "cold.txt", "huge.txt", "none.txt", "photo.jpg"
+ size, oversize, empty := int64(512), int64(4096), int64(0)
+ page := &awss3.ListObjectsV2Output{Contents: []s3types.Object{
+ {Key: &filteredKey, Size: &size},
+ {Key: &glacierKey, Size: &size, StorageClass: s3types.ObjectStorageClassGlacier},
+ {Key: &oversizeKey, Size: &oversize},
+ {Key: &emptyKey, Size: &empty},
+ {Key: &imageKey, Size: &size},
+ }}
+
+ // No object is downloaded, so pageChunker needs no client.
+ var scanned, filtered uint64
+ s.pageChunker(
+ ctx,
+ pageMetadata{bucket: "test-bucket", pageNumber: 1, page: page},
+ processingState{
+ errorCount: &sync.Map{},
+ objectCount: &scanned,
+ filteredCount: &filtered,
+ progress: newUnitProgress("test-bucket", &s.Progress),
+ },
+ sources.ChanReporter{Ch: make(chan *sources.Chunk, len(page.Contents))},
+ NewCheckpointer(ctx, &s.Progress, true),
+ )
+
+ _, reported := s.GetUnitProgressFor("test-bucket")
+ assert.False(t, reported, "skipped objects are in neither the total nor the done count")
+ assert.EqualValues(t, 1, filtered)
+ // Skipped objects still advance the checkpoint to the last key of the page.
+ assert.Equal(t, *page.Contents[len(page.Contents)-1].Key, s.GetEncodedResumeInfoFor("test-bucket"))
+}
+
+func TestSource_PageChunker_LegacyScanLeavesProgressUntouched(t *testing.T) {
+ ctx := context.Background()
+
+ conn, err := anypb.New(&sourcespb.S3{
+ Credential: &sourcespb.S3_Unauthenticated{},
+ ExcludePrefixes: []string{"archive/"},
+ })
+ require.NoError(t, err)
+
+ s := Source{}
+ require.NoError(t, s.Init(ctx, "s3 test source", 0, 0, false, conn, 1))
+ s.SetProgressComplete(0, 1, "Bucket: test-bucket", "")
+
+ key, size := "archive/key.txt", int64(1024)
+ page := &awss3.ListObjectsV2Output{Contents: []s3types.Object{{Key: &key, Size: &size}}}
+
+ var scanned, filtered uint64
+ s.pageChunker(
+ ctx,
+ pageMetadata{bucket: "test-bucket", pageNumber: 1, page: page},
+ processingState{errorCount: &sync.Map{}, objectCount: &scanned, filteredCount: &filtered},
+ sources.ChanReporter{Ch: make(chan *sources.Chunk, 1)},
+ NewCheckpointer(ctx, &s.Progress, false),
+ )
+
+ _, reported := s.GetUnitProgressFor("test-bucket")
+ assert.False(t, reported)
+ assert.EqualValues(t, 1, s.GetProgress().SectionsRemaining)
+ assert.Equal(t, "Bucket: test-bucket", s.GetProgress().Message)
+}
+
+func TestSource_SkipReason(t *testing.T) {
+ filter, err := newObjectFilter(nil, []string{"archive/"}, nil, nil)
+ require.NoError(t, err)
+ s := Source{maxObjectSize: 1024, objectFilter: filter}
+
+ key, filteredKey, imageKey := "keep/obj.txt", "archive/obj.txt", "keep/photo.jpg"
+ size, oversize, empty := int64(512), int64(2048), int64(0)
+
+ tests := []struct {
+ name string
+ obj s3types.Object
+ want string
+ }{
+ {name: "standard object", obj: s3types.Object{Key: &key, Size: &size}, want: ""},
+ {name: "at the size limit", obj: s3types.Object{Key: &key, Size: &s.maxObjectSize}, want: ""},
+ {name: "over the size limit", obj: s3types.Object{Key: &key, Size: &oversize}, want: skipReasonSizeLimit},
+ {
+ name: "glacier",
+ obj: s3types.Object{Key: &key, Size: &size, StorageClass: s3types.ObjectStorageClassGlacier},
+ want: skipReasonStorageClass,
+ },
+ {
+ name: "glacier instant retrieval",
+ obj: s3types.Object{Key: &key, Size: &size, StorageClass: s3types.ObjectStorageClassGlacierIr},
+ want: skipReasonStorageClass,
+ },
+ {name: "empty", obj: s3types.Object{Key: &key, Size: &empty}, want: skipReasonEmptyFile},
+ {name: "incompatible extension", obj: s3types.Object{Key: &imageKey, Size: &size}, want: skipReasonIncompatibleExtension},
+ {name: "filtered", obj: s3types.Object{Key: &filteredKey, Size: &size}, want: skipReasonObjectFilter},
+ // The filter is checked first, matching the reason the skipped objects metric has always recorded.
+ {name: "filtered and over the size limit", obj: s3types.Object{Key: &filteredKey, Size: &oversize}, want: skipReasonObjectFilter},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.want, s.skipReason(tt.obj))
+ })
+ }
+}
diff --git a/pkg/sources/sources.go b/pkg/sources/sources.go
index 3ec246245..c738c1ef8 100644
--- a/pkg/sources/sources.go
+++ b/pkg/sources/sources.go
@@ -510,6 +510,8 @@ type Progress struct {
EncodedResumeInfo string
SectionsCompleted int32
SectionsRemaining int32
+ // unitProgressByID is used for progress inside a unit (see below)
+ unitProgressByID map[string]UnitProgress
}
// Validator is an interface for validating a source. Sources can optionally implement this interface to validate
@@ -635,3 +637,71 @@ func unmarshalEncodedResumeInfo(data string) map[string]string {
}
// -/sub-unit-resumption-----------------------------------------------------------
+
+// -unit-progress------------------------------------------------------------------
+//
+// The following methods let a Source report how far it has got inside a unit,
+// for units large enough that counting finished units reads as no progress.
+// They are kept apart from EncodedResumeInfo, so reporting progress never
+// changes where a resumed scan starts.
+//
+// Usage:
+// - id should be the SourceUnit ID
+//
+
+// UnitProgressState says whether the totals in a UnitProgress are final.
+type UnitProgressState string
+
+const (
+ // UnitProgressCounting means the source is still finding out how much the
+ // unit holds, so the totals are only a lower bound.
+ UnitProgressCounting UnitProgressState = "counting"
+ // UnitProgressReady means the totals are final.
+ UnitProgressReady UnitProgressState = "ready"
+ // UnitProgressUnavailable means the source could not find out how much the
+ // unit holds, so only the done counts mean anything.
+ UnitProgressUnavailable UnitProgressState = "unavailable"
+)
+
+// UnitProgress is how far a Source has got through one unit. Items are
+// whatever the source scans one at a time, such as objects or files.
+type UnitProgress struct {
+ State UnitProgressState `json:"state"`
+ ItemsDone uint64 `json:"items_done"`
+ ItemsTotal uint64 `json:"items_total"`
+ BytesDone uint64 `json:"bytes_done"`
+ BytesTotal uint64 `json:"bytes_total"`
+ // ResumedBytes is the part of BytesDone that an earlier run of the unit
+ // finished, so a scan rate can leave it out.
+ ResumedBytes uint64 `json:"resumed_bytes"`
+}
+
+// Percent returns the share of bytes done once the totals are final, and 0
+// before. It is capped at 99, because only the unit finishing makes it complete.
+func (u UnitProgress) Percent() int64 {
+ if u.State != UnitProgressReady || u.BytesTotal == 0 {
+ return 0
+ }
+ return int64(min(u.BytesDone*100/u.BytesTotal, 99))
+}
+
+// SetUnitProgressFor records the progress of the unit with the provided ID.
+func (p *Progress) SetUnitProgressFor(id string, progress UnitProgress) {
+ p.mut.Lock()
+ defer p.mut.Unlock()
+ if p.unitProgressByID == nil {
+ p.unitProgressByID = make(map[string]UnitProgress)
+ }
+ p.unitProgressByID[id] = progress
+}
+
+// GetUnitProgressFor returns the progress last recorded for the unit with the
+// provided ID, and whether any was recorded.
+func (p *Progress) GetUnitProgressFor(id string) (UnitProgress, bool) {
+ p.mut.Lock()
+ defer p.mut.Unlock()
+ progress, ok := p.unitProgressByID[id]
+ return progress, ok
+}
+
+// -/unit-progress-----------------------------------------------------------------
diff --git a/pkg/sources/sources_test.go b/pkg/sources/sources_test.go
index 6db3fccbc..fc6fd22b4 100644
--- a/pkg/sources/sources_test.go
+++ b/pkg/sources/sources_test.go
@@ -14,3 +14,65 @@ func TestChunkSize(t *testing.T) {
t.Parallel()
assert.Equal(t, unsafe.Sizeof(Chunk{}), uintptr(104), "Chunk struct size exceeds 104 bytes")
}
+
+func TestProgress_UnitProgressKeepsResumeInfo(t *testing.T) {
+ t.Parallel()
+ var p Progress
+ p.SetEncodedResumeInfoFor("unit", "key")
+ resumeInfo := p.EncodedResumeInfo
+
+ want := UnitProgress{State: UnitProgressReady, ItemsDone: 1, ItemsTotal: 2, BytesDone: 10, BytesTotal: 20}
+ p.SetUnitProgressFor("unit", want)
+
+ got, ok := p.GetUnitProgressFor("unit")
+ assert.True(t, ok)
+ assert.Equal(t, want, got)
+ assert.Equal(t, resumeInfo, p.EncodedResumeInfo)
+ assert.Equal(t, "key", p.GetEncodedResumeInfoFor("unit"))
+
+ _, ok = p.GetUnitProgressFor("other unit")
+ assert.False(t, ok)
+}
+
+func TestUnitProgress_Percent(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ name string
+ progress UnitProgress
+ want int64
+ }{
+ {name: "nothing reported", progress: UnitProgress{}, want: 0},
+ {
+ name: "still counting",
+ progress: UnitProgress{State: UnitProgressCounting, BytesDone: 500, BytesTotal: 1000},
+ want: 0,
+ },
+ {
+ name: "count unavailable",
+ progress: UnitProgress{State: UnitProgressUnavailable, BytesDone: 500, BytesTotal: 1000},
+ want: 0,
+ },
+ {name: "empty total", progress: UnitProgress{State: UnitProgressReady}, want: 0},
+ {
+ name: "partial rounds down",
+ progress: UnitProgress{State: UnitProgressReady, BytesDone: 1999, BytesTotal: 3000},
+ want: 66,
+ },
+ {
+ name: "all done caps at 99",
+ progress: UnitProgress{State: UnitProgressReady, BytesDone: 1000, BytesTotal: 1000},
+ want: 99,
+ },
+ {
+ name: "done past total caps at 99",
+ progress: UnitProgress{State: UnitProgressReady, BytesDone: 1200, BytesTotal: 1000},
+ want: 99,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.want, tt.progress.Percent())
+ })
+ }
+}