Skip to content

Find, verify, and analyze leaked credentials

Support fatal errors in job reports (#1562)

Miccaha07b6664f82c
diff --git a/go.mod b/go.mod
index f2b78234e..faff10cde 100644
--- a/go.mod
+++ b/go.mod
@@ -34,6 +34,7 @@ require (
github.com/go-sql-driver/mysql v1.7.1
github.com/gobwas/glob v0.2.3
github.com/golang-jwt/jwt v3.2.2+incompatible
+ github.com/golang/mock v1.4.3
github.com/google/go-cmp v0.5.9
github.com/google/go-containerregistry v0.15.2
github.com/google/go-github/v42 v42.0.0
@@ -56,6 +57,7 @@ require (
github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502
github.com/xanzy/go-gitlab v0.88.0
go.mongodb.org/mongo-driver v1.12.0
+ go.uber.org/mock v0.2.0
go.uber.org/zap v1.24.0
golang.org/x/crypto v0.11.0
golang.org/x/exp v0.0.0-20221018205818-5c77f4b2bbd7
diff --git a/go.sum b/go.sum
index 62f9da20c..118550109 100644
--- a/go.sum
+++ b/go.sum
@@ -486,6 +486,8 @@ go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A=
go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4=
+go.uber.org/mock v0.2.0 h1:TaP3xedm7JaAgScZO7tlvlKrqT0p7I6OsdGB5YNSMDU=
+go.uber.org/mock v0.2.0/go.mod h1:J0y0rp9L3xiff1+ZBfKxlC1fz2+aO16tw0tsDOixfuM=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
diff --git a/pkg/sources/errors.go b/pkg/sources/errors.go
index 01e464e44..3ec62a74d 100644
--- a/pkg/sources/errors.go
+++ b/pkg/sources/errors.go
@@ -1,6 +1,7 @@
package sources
import (
+ "errors"
"fmt"
"sync"
)
@@ -32,5 +33,13 @@ func (s *ScanErrors) Count() uint64 {
}
func (s *ScanErrors) String() string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
return fmt.Sprintf("%v", s.errors)
}
+
+func (s *ScanErrors) Errors() error {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return errors.Join(s.errors...)
+}
diff --git a/pkg/sources/job_progress.go b/pkg/sources/job_progress.go
new file mode 100644
index 000000000..50605485d
--- /dev/null
+++ b/pkg/sources/job_progress.go
@@ -0,0 +1,272 @@
+package sources
+
+//go:generate mockgen --source=./job_progress.go --destination=mock_job_progress_test.go --package=sources
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+type JobProgressHook interface {
+ // Start and End marks the overall start and end time for this job.
+ Start(JobProgressRef, time.Time)
+ End(JobProgressRef, time.Time)
+ // StartEnumerating and EndEnumerating marks the start and end time for
+ // calling the source's Enumerate method. If the source does not
+ // support enumeration these methods will never be called.
+ StartEnumerating(JobProgressRef, time.Time)
+ EndEnumerating(JobProgressRef, time.Time)
+ // StartUnitChunking and EndUnitChunking marks the start and end time
+ // for calling the source's ChunkUnit method for a given unit. If the
+ // source does not support enumeration these methods will never be
+ // called.
+ StartUnitChunking(JobProgressRef, SourceUnit, time.Time)
+ EndUnitChunking(JobProgressRef, SourceUnit, time.Time)
+ // ReportError is called when any general error is encountered, usually
+ // from enumeration.
+ ReportError(JobProgressRef, error)
+ // ReportUnit is called when a unit has been enumerated. If the source
+ // does not support enumeration this method will never be called.
+ ReportUnit(JobProgressRef, SourceUnit)
+ // ReportChunk is called when a chunk has been produced for the given
+ // unit. The unit will be nil if the source does not support
+ // enumeration.
+ ReportChunk(JobProgressRef, SourceUnit, *Chunk)
+ // Finish marks the job as done.
+ Finish(JobProgressRef)
+}
+
+// JobProgressRef is a wrapper of a JobProgress for read-only access to its state.
+type JobProgressRef struct {
+ SourceID int64
+ JobID int64
+ jobProgress *JobProgress
+}
+
+// Snapshot returns a snapshot of the job's current metrics.
+func (r *JobProgressRef) Snapshot() JobProgressMetrics {
+ if r.jobProgress == nil {
+ return JobProgressMetrics{}
+ }
+ return r.jobProgress.Snapshot()
+}
+
+// Done returns a channel that will block until the job has completed.
+func (r *JobProgressRef) Done() <-chan struct{} {
+ if r.jobProgress == nil {
+ // Return a closed channel so it does not block.
+ ch := make(chan struct{})
+ close(ch)
+ return ch
+ }
+ return r.jobProgress.Done()
+}
+
+// Fatal is a wrapper around error to differentiate non-fatal errors from fatal
+// ones. A fatal error is typically from a finished context or any error
+// returned from a source's Init, Chunks, Enumerate, or ChunkUnit methods.
+type Fatal struct{ error }
+
+func (f Fatal) Error() string { return fmt.Sprintf("fatal: %s", f.error.Error()) }
+func (f Fatal) Unwrap() error { return f.error }
+
+// ChunkError is a custom error type for errors encountered during chunking of
+// a specific unit.
+type ChunkError struct {
+ unit SourceUnit
+ err error
+}
+
+func (f ChunkError) Error() string {
+ return fmt.Sprintf("error chunking unit %q: %s", f.unit.SourceUnitID(), f.err.Error())
+}
+func (f ChunkError) Unwrap() error { return f.err }
+
+// JobProgress aggregates information about a run of a Source.
+type JobProgress struct {
+ // Unique identifiers for this job.
+ SourceID int64
+ JobID int64
+ // Tracks whether the job is finished or not.
+ ctx context.Context
+ cancel context.CancelFunc
+ // Metrics.
+ metrics JobProgressMetrics
+ metricsLock sync.Mutex
+ // Coarse grained hooks for adding extra functionality when events trigger.
+ hooks []JobProgressHook
+}
+
+// JobProgressMetrics tracks the metrics of a job.
+type JobProgressMetrics struct {
+ StartTime time.Time
+ EndTime time.Time
+ TotalUnits uint64
+ FinishedUnits uint64
+ TotalChunks uint64
+ Errors []error
+ DoneEnumerating bool
+}
+
+// WithHooks adds hooks to be called when an event triggers.
+func WithHooks(hooks ...JobProgressHook) func(*JobProgress) {
+ return func(jp *JobProgress) { jp.hooks = append(jp.hooks, hooks...) }
+}
+
+// NewJobProgress creates a new job report for the given source and job ID.
+func NewJobProgress(sourceID, jobID int64, opts ...func(*JobProgress)) *JobProgress {
+ ctx, cancel := context.WithCancel(context.Background())
+ jp := &JobProgress{
+ SourceID: sourceID,
+ JobID: jobID,
+ ctx: ctx,
+ cancel: cancel,
+ }
+ for _, opt := range opts {
+ opt(jp)
+ }
+ return jp
+}
+
+// executeHooks is a helper method to execute all the hooks for the given
+// closure.
+func (jp *JobProgress) executeHooks(todo func(hook JobProgressHook)) {
+ for _, hook := range jp.hooks {
+ // TODO: Non-blocking?
+ todo(hook)
+ }
+}
+
+// TODO: Comment all this mess. They are mostly implementing JobProgressHook but
+// without the JobProgressRef parameter.
+func (jp *JobProgress) Start(start time.Time) {
+ jp.metricsLock.Lock()
+ jp.metrics.StartTime = start
+ jp.metricsLock.Unlock()
+
+ jp.executeHooks(func(hook JobProgressHook) { hook.Start(jp.Ref(), start) })
+}
+func (jp *JobProgress) End(end time.Time) {
+ jp.metricsLock.Lock()
+ jp.metrics.EndTime = end
+ jp.metricsLock.Unlock()
+
+ jp.executeHooks(func(hook JobProgressHook) { hook.End(jp.Ref(), end) })
+}
+func (jp *JobProgress) Finish() {
+ jp.cancel()
+ jp.executeHooks(func(hook JobProgressHook) { hook.Finish(jp.Ref()) })
+}
+func (jp *JobProgress) Done() <-chan struct{} { return jp.ctx.Done() }
+func (jp *JobProgress) ReportUnit(unit SourceUnit) {
+ atomic.AddUint64(&jp.metrics.TotalUnits, 1)
+ jp.executeHooks(func(hook JobProgressHook) { hook.ReportUnit(jp.Ref(), unit) })
+}
+func (jp *JobProgress) ReportChunk(unit SourceUnit, chunk *Chunk) {
+ atomic.AddUint64(&jp.metrics.TotalChunks, 1)
+ jp.executeHooks(func(hook JobProgressHook) { hook.ReportChunk(jp.Ref(), unit, chunk) })
+}
+func (jp *JobProgress) StartUnitChunking(unit SourceUnit, start time.Time) {
+ // TODO: Record time.
+ jp.executeHooks(func(hook JobProgressHook) { hook.StartUnitChunking(jp.Ref(), unit, start) })
+}
+func (jp *JobProgress) EndUnitChunking(unit SourceUnit, end time.Time) {
+ // TODO: Record time.
+ atomic.AddUint64(&jp.metrics.FinishedUnits, 1)
+ jp.executeHooks(func(hook JobProgressHook) { hook.EndUnitChunking(jp.Ref(), unit, end) })
+}
+func (jp *JobProgress) StartEnumerating(start time.Time) {
+ // TODO: Record time.
+ jp.executeHooks(func(hook JobProgressHook) { hook.StartEnumerating(jp.Ref(), start) })
+}
+func (jp *JobProgress) EndEnumerating(end time.Time) {
+ jp.metricsLock.Lock()
+ // TODO: Record time.
+ jp.metrics.DoneEnumerating = true
+ jp.metricsLock.Unlock()
+
+ jp.executeHooks(func(hook JobProgressHook) { hook.EndEnumerating(jp.Ref(), end) })
+}
+
+// Snapshot safely gets the job's current metrics.
+func (jp *JobProgress) Snapshot() JobProgressMetrics {
+ jp.metricsLock.Lock()
+ defer jp.metricsLock.Unlock()
+ return jp.metrics
+}
+
+// ReportError adds a non-nil error to the aggregate of errors
+// encountered during scanning.
+func (jp *JobProgress) ReportError(err error) {
+ if err == nil {
+ return
+ }
+ jp.metricsLock.Lock()
+ jp.metrics.Errors = append(jp.metrics.Errors, err)
+ jp.metricsLock.Unlock()
+
+ jp.executeHooks(func(hook JobProgressHook) { hook.ReportError(jp.Ref(), err) })
+}
+
+// Ref provides a read-only reference to the JobProgress.
+func (jp *JobProgress) Ref() JobProgressRef {
+ return JobProgressRef{
+ SourceID: jp.SourceID,
+ JobID: jp.JobID,
+ jobProgress: jp,
+ }
+}
+
+// EnumerationErrors joins all errors encountered during initialization or
+// enumeration.
+func (m JobProgressMetrics) EnumerationError() error {
+ return errors.Join(m.Errors...)
+}
+
+// ChunkErrors joins all errors encountered during chunking.
+func (m JobProgressMetrics) ChunkError() error {
+ var aggregate []error
+ for _, err := range m.Errors {
+ var chunkErr ChunkError
+ if ok := errors.As(err, &chunkErr); ok {
+ aggregate = append(aggregate, err)
+ }
+ }
+ return errors.Join(aggregate...)
+}
+
+// FatalError returns the first Fatal error, if any, encountered in the scan.
+func (m JobProgressMetrics) FatalError() error {
+ for _, err := range m.Errors {
+ var fatalErr Fatal
+ if found := errors.As(err, &fatalErr); found {
+ return fatalErr
+ }
+ }
+ return nil
+}
+
+// FatalErrors returns all of the encountered fatal errors joined together.
+func (m JobProgressMetrics) FatalErrors() error {
+ var aggregate []error
+ for _, err := range m.Errors {
+ var fatalErr Fatal
+ if found := errors.As(err, &fatalErr); found {
+ aggregate = append(aggregate, fatalErr)
+ }
+ }
+ return errors.Join(aggregate...)
+}
+
+func (m JobProgressMetrics) PercentComplete() int {
+ num := m.FinishedUnits
+ den := m.TotalUnits
+ if num == 0 && den == 0 {
+ return 0
+ }
+ return int(num * 100 / den)
+}
diff --git a/pkg/sources/job_progress_test.go b/pkg/sources/job_progress_test.go
new file mode 100644
index 000000000..fd1c2972c
--- /dev/null
+++ b/pkg/sources/job_progress_test.go
@@ -0,0 +1,117 @@
+package sources
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "go.uber.org/mock/gomock"
+)
+
+func TestJobProgressFatalErrors(t *testing.T) {
+ var jp JobProgress
+
+ // Add a non-fatal error.
+ jp.ReportError(fmt.Errorf("oh no"))
+ assert.Greater(t, len(jp.Snapshot().Errors), 0)
+ assert.NoError(t, jp.Snapshot().FatalError())
+ assert.NoError(t, jp.Snapshot().ChunkError())
+
+ // Add a fatal error and make sure we can test comparison.
+ err := fmt.Errorf("fatal error")
+ jp.ReportError(Fatal{err})
+ assert.Greater(t, len(jp.Snapshot().Errors), 0)
+ assert.Error(t, jp.Snapshot().FatalError())
+ assert.NoError(t, jp.Snapshot().ChunkError())
+ assert.True(t, errors.Is(jp.Snapshot().FatalError(), err))
+
+ // Add another fatal error and test we still return the first.
+ jp.ReportError(Fatal{fmt.Errorf("second fatal error")})
+ assert.Greater(t, len(jp.Snapshot().Errors), 0)
+ assert.Error(t, jp.Snapshot().FatalError())
+ assert.NoError(t, jp.Snapshot().ChunkError())
+ assert.True(t, errors.Is(jp.Snapshot().FatalError(), err))
+}
+
+func TestJobProgressRef(t *testing.T) {
+ jp := NewJobProgress(123, 456)
+ ref := jp.Ref()
+ assert.Equal(t, int64(123), ref.SourceID)
+ assert.Equal(t, int64(456), ref.JobID)
+
+ // Test Done() blocks until Finish() is called.
+ select {
+ case <-jp.Done():
+ assert.FailNow(t, "job should not be finished")
+ default:
+ }
+
+ jp.Finish()
+ select {
+ case <-jp.Done():
+ default:
+ assert.FailNow(t, "job should be finished")
+ }
+}
+
+func TestJobProgressHook(t *testing.T) {
+ ctrl := gomock.NewController(t)
+ defer ctrl.Finish()
+
+ hook := NewMockJobProgressHook(ctrl)
+ jp := NewJobProgress(123, 456, WithHooks(hook))
+
+ // Start(JobProgressRef, time.Time)
+ // End(JobProgressRef, time.Time)
+ // StartEnumerating(JobProgressRef, time.Time)
+ // EndEnumerating(JobProgressRef, time.Time)
+ // StartUnitChunking(JobProgressRef, SourceUnit, time.Time)
+ // EndUnitChunking(JobProgressRef, SourceUnit, time.Time)
+ // ReportError(JobProgressRef, error)
+ // ReportUnit(JobProgressRef, SourceUnit)
+ // ReportChunk(JobProgressRef, SourceUnit, *Chunk)
+ // Finish(JobProgressRef)
+
+ startTime := time.Now()
+ endTime := time.Now().Add(10 * time.Second)
+ startEnum := time.Now().Add(20 * time.Second)
+ endEnum := time.Now().Add(30 * time.Second)
+ startChunk := time.Now().Add(40 * time.Second)
+ endChunk := time.Now().Add(50 * time.Second)
+ reportErr := fmt.Errorf("reporting error")
+ reportUnit := CommonSourceUnit{"reporting unit"}
+ reportChunk := &Chunk{Data: []byte("reporting chunk")}
+
+ hook.EXPECT().Start(gomock.Any(), startTime)
+ hook.EXPECT().End(gomock.Any(), endTime)
+ hook.EXPECT().StartEnumerating(gomock.Any(), startEnum)
+ hook.EXPECT().EndEnumerating(gomock.Any(), endEnum)
+ hook.EXPECT().StartUnitChunking(gomock.Any(), reportUnit, startChunk)
+ hook.EXPECT().EndUnitChunking(gomock.Any(), reportUnit, endChunk)
+ hook.EXPECT().ReportError(gomock.Any(), reportErr)
+ hook.EXPECT().ReportUnit(gomock.Any(), reportUnit)
+ hook.EXPECT().ReportChunk(gomock.Any(), reportUnit, reportChunk)
+ hook.EXPECT().Finish(gomock.Any())
+
+ jp.Start(startTime)
+ jp.End(endTime)
+ jp.StartEnumerating(startEnum)
+ jp.EndEnumerating(endEnum)
+ jp.StartUnitChunking(reportUnit, startChunk)
+ jp.EndUnitChunking(reportUnit, endChunk)
+ jp.ReportError(reportErr)
+ jp.ReportUnit(reportUnit)
+ jp.ReportChunk(reportUnit, reportChunk)
+ jp.Finish()
+}
+
+func TestJobProgressDone(t *testing.T) {
+ ref := JobProgressRef{}
+ select {
+ case <-ref.Done():
+ default:
+ assert.FailNow(t, "done should not block for a nil job")
+ }
+}
diff --git a/pkg/sources/job_report.go b/pkg/sources/job_report.go
deleted file mode 100644
index 01a7734c3..000000000
--- a/pkg/sources/job_report.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package sources
-
-import (
- "errors"
- "sync"
- "time"
-)
-
-// JobReport aggregates information about a run of a Source.
-type JobReport struct {
- SourceID int64
- JobID int64
- StartTime time.Time
- EndTime time.Time
- TotalChunks uint64
- errors []error
- errorsLock sync.Mutex
-}
-
-// AddError adds a non-nil error to the aggregate of errors encountered during
-// scanning.
-func (jr *JobReport) AddError(err error) {
- if err == nil {
- return
- }
- jr.errorsLock.Lock()
- defer jr.errorsLock.Unlock()
- jr.errors = append(jr.errors, err)
-}
-
-// Errors joins all aggregated errors into one. If there were no errors, nil is
-// returned. errors.Is can be used to check for specific errors.
-func (jr *JobReport) Errors() error {
- jr.errorsLock.Lock()
- defer jr.errorsLock.Unlock()
- return errors.Join(jr.errors...)
-}
diff --git a/pkg/sources/mock_job_progress_test.go b/pkg/sources/mock_job_progress_test.go
new file mode 100644
index 000000000..de3e608fc
--- /dev/null
+++ b/pkg/sources/mock_job_progress_test.go
@@ -0,0 +1,155 @@
+// Code generated by MockGen. DO NOT EDIT.
+// Source: ./job_progress.go
+
+// Package sources is a generated GoMock package.
+package sources
+
+import (
+ reflect "reflect"
+ time "time"
+
+ gomock "go.uber.org/mock/gomock"
+)
+
+// MockJobProgressHook is a mock of JobProgressHook interface.
+type MockJobProgressHook struct {
+ ctrl *gomock.Controller
+ recorder *MockJobProgressHookMockRecorder
+}
+
+// MockJobProgressHookMockRecorder is the mock recorder for MockJobProgressHook.
+type MockJobProgressHookMockRecorder struct {
+ mock *MockJobProgressHook
+}
+
+// NewMockJobProgressHook creates a new mock instance.
+func NewMockJobProgressHook(ctrl *gomock.Controller) *MockJobProgressHook {
+ mock := &MockJobProgressHook{ctrl: ctrl}
+ mock.recorder = &MockJobProgressHookMockRecorder{mock}
+ return mock
+}
+
+// EXPECT returns an object that allows the caller to indicate expected use.
+func (m *MockJobProgressHook) EXPECT() *MockJobProgressHookMockRecorder {
+ return m.recorder
+}
+
+// End mocks base method.
+func (m *MockJobProgressHook) End(arg0 JobProgressRef, arg1 time.Time) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "End", arg0, arg1)
+}
+
+// End indicates an expected call of End.
+func (mr *MockJobProgressHookMockRecorder) End(arg0, arg1 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "End", reflect.TypeOf((*MockJobProgressHook)(nil).End), arg0, arg1)
+}
+
+// EndEnumerating mocks base method.
+func (m *MockJobProgressHook) EndEnumerating(arg0 JobProgressRef, arg1 time.Time) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "EndEnumerating", arg0, arg1)
+}
+
+// EndEnumerating indicates an expected call of EndEnumerating.
+func (mr *MockJobProgressHookMockRecorder) EndEnumerating(arg0, arg1 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EndEnumerating", reflect.TypeOf((*MockJobProgressHook)(nil).EndEnumerating), arg0, arg1)
+}
+
+// EndUnitChunking mocks base method.
+func (m *MockJobProgressHook) EndUnitChunking(arg0 JobProgressRef, arg1 SourceUnit, arg2 time.Time) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "EndUnitChunking", arg0, arg1, arg2)
+}
+
+// EndUnitChunking indicates an expected call of EndUnitChunking.
+func (mr *MockJobProgressHookMockRecorder) EndUnitChunking(arg0, arg1, arg2 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EndUnitChunking", reflect.TypeOf((*MockJobProgressHook)(nil).EndUnitChunking), arg0, arg1, arg2)
+}
+
+// Finish mocks base method.
+func (m *MockJobProgressHook) Finish(arg0 JobProgressRef) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "Finish", arg0)
+}
+
+// Finish indicates an expected call of Finish.
+func (mr *MockJobProgressHookMockRecorder) Finish(arg0 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Finish", reflect.TypeOf((*MockJobProgressHook)(nil).Finish), arg0)
+}
+
+// ReportChunk mocks base method.
+func (m *MockJobProgressHook) ReportChunk(arg0 JobProgressRef, arg1 SourceUnit, arg2 *Chunk) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "ReportChunk", arg0, arg1, arg2)
+}
+
+// ReportChunk indicates an expected call of ReportChunk.
+func (mr *MockJobProgressHookMockRecorder) ReportChunk(arg0, arg1, arg2 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportChunk", reflect.TypeOf((*MockJobProgressHook)(nil).ReportChunk), arg0, arg1, arg2)
+}
+
+// ReportError mocks base method.
+func (m *MockJobProgressHook) ReportError(arg0 JobProgressRef, arg1 error) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "ReportError", arg0, arg1)
+}
+
+// ReportError indicates an expected call of ReportError.
+func (mr *MockJobProgressHookMockRecorder) ReportError(arg0, arg1 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportError", reflect.TypeOf((*MockJobProgressHook)(nil).ReportError), arg0, arg1)
+}
+
+// ReportUnit mocks base method.
+func (m *MockJobProgressHook) ReportUnit(arg0 JobProgressRef, arg1 SourceUnit) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "ReportUnit", arg0, arg1)
+}
+
+// ReportUnit indicates an expected call of ReportUnit.
+func (mr *MockJobProgressHookMockRecorder) ReportUnit(arg0, arg1 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportUnit", reflect.TypeOf((*MockJobProgressHook)(nil).ReportUnit), arg0, arg1)
+}
+
+// Start mocks base method.
+func (m *MockJobProgressHook) Start(arg0 JobProgressRef, arg1 time.Time) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "Start", arg0, arg1)
+}
+
+// Start indicates an expected call of Start.
+func (mr *MockJobProgressHookMockRecorder) Start(arg0, arg1 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockJobProgressHook)(nil).Start), arg0, arg1)
+}
+
+// StartEnumerating mocks base method.
+func (m *MockJobProgressHook) StartEnumerating(arg0 JobProgressRef, arg1 time.Time) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "StartEnumerating", arg0, arg1)
+}
+
+// StartEnumerating indicates an expected call of StartEnumerating.
+func (mr *MockJobProgressHookMockRecorder) StartEnumerating(arg0, arg1 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartEnumerating", reflect.TypeOf((*MockJobProgressHook)(nil).StartEnumerating), arg0, arg1)
+}
+
+// StartUnitChunking mocks base method.
+func (m *MockJobProgressHook) StartUnitChunking(arg0 JobProgressRef, arg1 SourceUnit, arg2 time.Time) {
+ m.ctrl.T.Helper()
+ m.ctrl.Call(m, "StartUnitChunking", arg0, arg1, arg2)
+}
+
+// StartUnitChunking indicates an expected call of StartUnitChunking.
+func (mr *MockJobProgressHookMockRecorder) StartUnitChunking(arg0, arg1, arg2 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartUnitChunking", reflect.TypeOf((*MockJobProgressHook)(nil).StartUnitChunking), arg0, arg1, arg2)
+}
diff --git a/pkg/sources/source_manager.go b/pkg/sources/source_manager.go
index f061c66b6..890099478 100644
--- a/pkg/sources/source_manager.go
+++ b/pkg/sources/source_manager.go
@@ -1,7 +1,6 @@
package sources
import (
- "errors"
"fmt"
"sync"
"sync/atomic"
@@ -23,14 +22,11 @@ type handle int64
type SourceInitFunc func(ctx context.Context, sourceID int64, jobID int64) (Source, error)
type SourceManager struct {
- api apiClient
+ api apiClient
+ hooks []JobProgressHook
// Map of handle to source initializer.
handles map[handle]SourceInitFunc
handlesLock sync.Mutex
- // Map of handle to job reports.
- // TODO: Manage culling and flushing to the API.
- report map[handle]*JobReport
- reportLock sync.Mutex
// Pool limiting the amount of concurrent sources running.
pool errgroup.Group
concurrentUnits int
@@ -39,8 +35,7 @@ type SourceManager struct {
// Downstream chunks channel to be scanned.
outputChunks chan *Chunk
// Set when Wait() returns.
- done bool
- doneErr error
+ done bool
}
// apiClient is an interface for optionally communicating with an external API.
@@ -51,11 +46,18 @@ type apiClient interface {
GetJobID(ctx context.Context, id int64) (int64, error)
}
-// WithAPI adds an API client to the manager for tracking jobs and progress.
+// WithAPI adds an API client to the manager for tracking jobs and progress. If
+// the API is also a JobProgressHook, it will be added to the list of event hooks.
func WithAPI(api apiClient) func(*SourceManager) {
return func(mgr *SourceManager) { mgr.api = api }
}
+func WithReportHook(hook JobProgressHook) func(*SourceManager) {
+ return func(mgr *SourceManager) {
+ mgr.hooks = append(mgr.hooks, hook)
+ }
+}
+
// WithConcurrency limits the concurrent number of sources a manager can run.
func WithConcurrency(concurrency int) func(*SourceManager) {
return func(mgr *SourceManager) { mgr.pool.SetLimit(concurrency) }
@@ -84,7 +86,6 @@ func NewManager(opts ...func(*SourceManager)) *SourceManager {
// Default to the headless API. Can be overwritten by the WithAPI option.
api: &headlessAPI{},
handles: make(map[handle]SourceInitFunc),
- report: make(map[handle]*JobReport),
outputChunks: make(chan *Chunk),
}
for _, opt := range opts {
@@ -114,52 +115,44 @@ func (s *SourceManager) Enroll(ctx context.Context, name string, kind sourcespb.
}
// Run blocks until a resource is available to run the source, then
-// synchronously runs it.
-func (s *SourceManager) Run(ctx context.Context, handle handle) error {
- // Do preflight checks before waiting on the pool.
- if err := s.preflightChecks(ctx, handle); err != nil {
- return err
+// synchronously runs it. The first fatal error, if any, will be returned.
+func (s *SourceManager) Run(ctx context.Context, handle handle) (JobProgressRef, error) {
+ report, err := s.asyncRun(ctx, handle)
+ if err != nil {
+ return report, err
}
- ch := make(chan error)
- s.pool.Go(func() error {
- defer common.Recover(ctx)
- report, err := s.run(ctx, handle)
- if report != nil {
- s.reportLock.Lock()
- s.report[handle] = report
- s.reportLock.Unlock()
- }
- if err != nil {
- ch <- err
- return nil
- }
- ch <- report.Errors()
- return nil
- })
- return <-ch
+ <-report.Done()
+ return report, report.Snapshot().FatalError()
}
// ScheduleRun blocks until a resource is available to run the source, then
-// asynchronously runs it. Error information is stored and returned by Wait().
-func (s *SourceManager) ScheduleRun(ctx context.Context, handle handle) error {
+// asynchronously runs it. Error information is stored and accessible via the
+// JobProgressRef as it becomes available.
+func (s *SourceManager) ScheduleRun(ctx context.Context, handle handle) (JobProgressRef, error) {
+ return s.asyncRun(ctx, handle)
+}
+
+// asyncRun is a helper method to asynchronously run the Source. It calls out
+// to the API to get a job ID for this run, creates a report, then waits for an
+// available goroutine to asynchronously run it.
+func (s *SourceManager) asyncRun(ctx context.Context, handle handle) (JobProgressRef, error) {
// Do preflight checks before waiting on the pool.
if err := s.preflightChecks(ctx, handle); err != nil {
- return err
+ return JobProgressRef{}, err
}
+ // Get a Job ID.
+ jobID, err := s.api.GetJobID(ctx, int64(handle))
+ if err != nil {
+ return JobProgressRef{SourceID: int64(handle)}, err
+ }
+ // Start a report for this job.
+ report := NewJobProgress(int64(handle), jobID, WithHooks(s.hooks...))
s.pool.Go(func() error {
defer common.Recover(ctx)
- // The error is already saved in the report, so we can ignore
- // it here.
- report, _ := s.run(ctx, handle)
- if report != nil {
- s.reportLock.Lock()
- s.report[handle] = report
- s.reportLock.Unlock()
- }
+ _ = s.run(ctx, handle, jobID, report)
return nil
})
- // TODO: Maybe wait for a signal here that initialization was successful?
- return nil
+ return report.Ref(), nil
}
// Chunks returns the read only channel of all the chunks produced by all of
@@ -168,13 +161,14 @@ func (s *SourceManager) Chunks() <-chan *Chunk {
return s.outputChunks
}
-// Wait blocks until all running sources are completed and returns an error if
-// any of the sources had fatal errors. It also closes the channel returned by
-// Chunks(). The manager should not be reused after calling this method.
-func (s *SourceManager) Wait() error {
+// Wait blocks until all running sources are completed and closes the channel
+// returned by Chunks(). The manager should not be reused after calling this
+// method. This current implementation is not thread safe and should only be
+// called by one thread.
+func (s *SourceManager) Wait() {
// Check if the manager has been Waited.
if s.done {
- return s.doneErr
+ return
}
defer close(s.outputChunks)
defer func() { s.done = true }()
@@ -182,26 +176,6 @@ func (s *SourceManager) Wait() error {
// We are only using the errgroup for limiting concurrency.
// TODO: Maybe switch to using a semaphore.Weighted.
_ = s.pool.Wait()
-
- // Aggregate all errors from all job reports.
- // TODO: This should probably only be the fatal errors. We'll also need
- // to rewrite this for when the reports start getting culled.
- s.reportLock.Lock()
- defer s.reportLock.Unlock()
- errs := make([]error, 0, len(s.report))
- for _, report := range s.report {
- errs = append(errs, report.Errors())
- }
- s.doneErr = errors.Join(errs...)
- return s.doneErr
-}
-
-// Report retrieves a scan report for a given handle. If no report exists or
-// the Source has not finished, nil will be returned.
-func (s *SourceManager) Report(handle handle) *JobReport {
- s.reportLock.Lock()
- defer s.reportLock.Unlock()
- return s.report[handle]
}
// preflightChecks is a helper method to check the Manager or the context isn't
@@ -219,40 +193,25 @@ func (s *SourceManager) preflightChecks(ctx context.Context, handle handle) erro
}
// run is a helper method to sychronously run the source. It does not check for
-// acquired resources. Possible return values are:
-//
-// - *JobReport, nil
-// Successfully ran the source, but the report could have errors.
-//
-// - *JobReport, error
-// There was an error calling Init or Chunks. This sort of error indicates
-// a fatal error and is also recorded in the report.
-//
-// - nil, error:
-// There was an error from the API or the handle is invalid. The latter of
-// which should never happen due to the preflightChecks.
-func (s *SourceManager) run(ctx context.Context, handle handle) (*JobReport, error) {
- jobID, err := s.api.GetJobID(ctx, int64(handle))
- if err != nil {
- return nil, err
- }
+// acquired resources. An error is returned if there was a fatal error during
+// the run. This information is also recorded in the JobProgress.
+func (s *SourceManager) run(ctx context.Context, handle handle, jobID int64, report *JobProgress) error {
+ defer report.Finish()
+ report.Start(time.Now())
+ defer func() { report.End(time.Now()) }()
+
+ // Initialize the source.
initFunc, ok := s.getInitFunc(handle)
if !ok {
- return nil, fmt.Errorf("unrecognized handle")
+ // Shouldn't happen due to preflight checks.
+ err := fmt.Errorf("unrecognized handle")
+ report.ReportError(Fatal{err})
+ return Fatal{err}
}
- // Create a report for this run.
- report := &JobReport{
- SourceID: int64(handle),
- JobID: jobID,
- StartTime: time.Now(),
- }
- defer func() { report.EndTime = time.Now() }()
-
- // Initialize the source.
- source, err := initFunc(ctx, jobID, int64(handle))
+ source, err := initFunc(ctx, int64(handle), jobID)
if err != nil {
- report.AddError(err)
- return report, err
+ report.ReportError(Fatal{err})
+ return Fatal{err}
}
// Check for the preferred method of tracking source units.
if enumChunker, ok := source.(SourceUnitEnumChunker); ok && s.useSourceUnits {
@@ -263,7 +222,7 @@ func (s *SourceManager) run(ctx context.Context, handle handle) (*JobReport, err
// runWithoutUnits is a helper method to run a Source. It has coarse-grained
// job reporting.
-func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, source Source, report *JobReport) (*JobReport, error) {
+func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, source Source, report *JobProgress) error {
// Introspect on the chunks we get from the Chunks method.
ch := make(chan *Chunk)
var wg sync.WaitGroup
@@ -272,7 +231,7 @@ func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, sour
go func() {
defer wg.Done()
for chunk := range ch {
- atomic.AddUint64(&report.TotalChunks, 1)
+ report.ReportChunk(nil, chunk)
_ = common.CancellableWrite(ctx, s.outputChunks, chunk)
}
}()
@@ -283,25 +242,38 @@ func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, sour
defer wg.Wait()
defer close(ch)
if err := source.Chunks(ctx, ch); err != nil {
- report.AddError(err)
- return report, err
+ report.ReportError(Fatal{err})
+ return Fatal{err}
}
- return report, nil
+ return nil
}
// runWithUnits is a helper method to run a Source that is also a
// SourceUnitEnumChunker. This allows better introspection of what is getting
// scanned and any errors encountered.
-func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, source SourceUnitEnumChunker, report *JobReport) (*JobReport, error) {
- reporter := &mgrUnitReporter{
+func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, source SourceUnitEnumChunker, report *JobProgress) error {
+ unitReporter := &mgrUnitReporter{
unitCh: make(chan SourceUnit),
+ report: report,
+ }
+ // Create a function that will save the first error encountered (if
+ // any) and discard the rest.
+ fatalErr := make(chan error, 1)
+ catchFirstFatal := func(err error) {
+ select {
+ case fatalErr <- err:
+ default:
+ }
}
// Produce units.
go func() {
// TODO: Catch panics and add to report.
- defer close(reporter.unitCh)
- if err := source.Enumerate(ctx, reporter); err != nil {
- report.AddError(err)
+ report.StartEnumerating(time.Now())
+ defer func() { report.EndEnumerating(time.Now()) }()
+ defer close(unitReporter.unitCh)
+ if err := source.Enumerate(ctx, unitReporter); err != nil {
+ report.ReportError(Fatal{err})
+ catchFirstFatal(Fatal{err})
}
}()
var wg sync.WaitGroup
@@ -311,18 +283,21 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, source
// Negative values indicated no limit.
unitPool.SetLimit(s.concurrentUnits)
}
- for unit := range reporter.unitCh {
- reporter := &mgrChunkReporter{
- unitID: unit.SourceUnitID(),
+ for unit := range unitReporter.unitCh {
+ unit := unit
+ chunkReporter := &mgrChunkReporter{
+ unit: unit,
chunkCh: make(chan *Chunk),
+ report: report,
}
- unit := unit
// Consume units and produce chunks.
unitPool.Go(func() error {
+ report.StartUnitChunking(unit, time.Now())
// TODO: Catch panics and add to report.
- defer close(reporter.chunkCh)
- if err := source.ChunkUnit(ctx, unit, reporter); err != nil {
- report.AddError(err)
+ defer close(chunkReporter.chunkCh)
+ if err := source.ChunkUnit(ctx, unit, chunkReporter); err != nil {
+ report.ReportError(Fatal{err})
+ catchFirstFatal(Fatal{err})
}
return nil
})
@@ -330,16 +305,20 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, source
wg.Add(1)
go func() {
defer wg.Done()
- for chunk := range reporter.chunkCh {
- // TODO: Introspect on the chunks we got from this unit.
- atomic.AddUint64(&report.TotalChunks, 1)
+ defer func() { report.EndUnitChunking(unit, time.Now()) }()
+ for chunk := range chunkReporter.chunkCh {
+ report.ReportChunk(chunkReporter.unit, chunk)
_ = common.CancellableWrite(ctx, s.outputChunks, chunk)
}
}()
}
wg.Wait()
- // TODO: Return fatal errors.
- return report, nil
+ select {
+ case err := <-fatalErr:
+ return err
+ default:
+ return nil
+ }
}
// getInitFunc is a helper method for safe concurrent access to the
@@ -368,9 +347,8 @@ func (api *headlessAPI) GetJobID(ctx context.Context, id int64) (int64, error) {
// mgrUnitReporter implements the UnitReporter interface.
type mgrUnitReporter struct {
- unitCh chan SourceUnit
- unitErrs []error
- unitErrsLock sync.Mutex
+ unitCh chan SourceUnit
+ report *JobProgress
}
func (s *mgrUnitReporter) UnitOk(ctx context.Context, unit SourceUnit) error {
@@ -378,18 +356,15 @@ func (s *mgrUnitReporter) UnitOk(ctx context.Context, unit SourceUnit) error {
}
func (s *mgrUnitReporter) UnitErr(ctx context.Context, err error) error {
- s.unitErrsLock.Lock()
- defer s.unitErrsLock.Unlock()
- s.unitErrs = append(s.unitErrs, err)
+ s.report.ReportError(err)
return nil
}
// mgrChunkReporter implements the ChunkReporter interface.
type mgrChunkReporter struct {
- unitID string
- chunkCh chan *Chunk
- chunkErrs []error
- chunkErrsLock sync.Mutex
+ unit SourceUnit
+ chunkCh chan *Chunk
+ report *JobProgress
}
func (s *mgrChunkReporter) ChunkOk(ctx context.Context, chunk Chunk) error {
@@ -397,8 +372,6 @@ func (s *mgrChunkReporter) ChunkOk(ctx context.Context, chunk Chunk) error {
}
func (s *mgrChunkReporter) ChunkErr(ctx context.Context, err error) error {
- s.chunkErrsLock.Lock()
- defer s.chunkErrsLock.Unlock()
- s.chunkErrs = append(s.chunkErrs, err)
+ s.report.ReportError(ChunkError{s.unit, err})
return nil
}
diff --git a/pkg/sources/source_manager_test.go b/pkg/sources/source_manager_test.go
index a06a05866..4f7db5f1e 100644
--- a/pkg/sources/source_manager_test.go
+++ b/pkg/sources/source_manager_test.go
@@ -102,7 +102,7 @@ func TestSourceManagerRun(t *testing.T) {
t.Fatalf("unexpected error enrolling source: %v", err)
}
for i := 0; i < 3; i++ {
- if err := mgr.Run(context.Background(), handle); err != nil {
+ if _, err := mgr.Run(context.Background(), handle); err != nil {
t.Fatalf("unexpected error running source: %v", err)
}
chunk, err := tryRead(mgr.Chunks())
@@ -127,20 +127,18 @@ func TestSourceManagerWait(t *testing.T) {
t.Fatalf("unexpected error enrolling source: %v", err)
}
// Asynchronously run the source.
- if err := mgr.ScheduleRun(context.Background(), handle); err != nil {
+ if _, err := mgr.ScheduleRun(context.Background(), handle); err != nil {
t.Fatalf("unexpected error scheduling run: %v", err)
}
// Read the 1 chunk we're expecting so Waiting completes.
<-mgr.Chunks()
// Wait for all resources to complete.
- if err := mgr.Wait(); err != nil {
- t.Fatalf("unexpected error waiting: %v", err)
- }
+ mgr.Wait()
// Enroll and run should return an error now.
if _, err := enrollDummy(mgr, &counterChunker{count: 1}); err == nil {
t.Fatalf("expected enroll to fail")
}
- if err := mgr.ScheduleRun(context.Background(), handle); err == nil {
+ if _, err := mgr.ScheduleRun(context.Background(), handle); err == nil {
t.Fatalf("expected scheduling run to fail")
}
}
@@ -152,15 +150,17 @@ func TestSourceManagerError(t *testing.T) {
t.Fatalf("unexpected error enrolling source: %v", err)
}
// A synchronous run should fail.
- if err := mgr.Run(context.Background(), handle); err == nil {
+ if _, err := mgr.Run(context.Background(), handle); err == nil {
t.Fatalf("expected run to fail")
}
// Scheduling a run should not fail, but the error should surface in
// Wait().
- if err := mgr.ScheduleRun(context.Background(), handle); err != nil {
+ ref, err := mgr.ScheduleRun(context.Background(), handle)
+ if err != nil {
t.Fatalf("unexpected error scheduling run: %v", err)
}
- if err := mgr.Wait(); err == nil {
+ <-ref.Done()
+ if err := ref.Snapshot().FatalError(); err == nil {
t.Fatalf("expected wait to fail")
}
}
@@ -177,18 +177,15 @@ func TestSourceManagerReport(t *testing.T) {
t.Fatalf("unexpected error enrolling source: %v", err)
}
// Synchronously run the source.
- if err := mgr.Run(context.Background(), handle); err != nil {
+ ref, err := mgr.Run(context.Background(), handle)
+ if err != nil {
t.Fatalf("unexpected error running source: %v", err)
}
- report := mgr.Report(handle)
- if report == nil {
- t.Fatalf("expected a report")
- }
- if err := report.Errors(); err != nil {
- t.Fatalf("unexpected error in report: %v", err)
+ if errs := ref.Snapshot().Errors; len(errs) > 0 {
+ t.Fatalf("unexpected errors in report: %v", errs)
}
- if report.TotalChunks != 4 {
- t.Fatalf("expected report to have 4 chunks, got: %d", report.TotalChunks)
+ if count := ref.Snapshot().TotalChunks; count != 4 {
+ t.Fatalf("expected report to have 4 chunks, got: %d", count)
}
}
}