Initial implementation to make progress increment monotically.

This commit is contained in:
Ahrav Dutta
2022-09-17 15:59:04 -07:00
parent 59d6d29c02
commit d9f296e7d3
4 changed files with 85 additions and 52 deletions
+9 -7
View File
@@ -394,15 +394,16 @@ func (s *Source) scan(ctx context.Context, installationClient *github.Client, ch
s.repos = reposToScan
var scanErrs []error
for i, repoURL := range s.repos {
i, repoURL := i, repoURL
repoCnt := len(s.repos)
for _, repoURL := range s.repos {
repoURL := repoURL
s.jobPool.Go(func() error {
if common.IsDone(ctx) {
return nil
}
// TODO: set progress complete is being called concurrently with i
s.setProgressCompleteWithRepo(i, progressIndexOffset, repoURL)
cnt := s.Counter.Inc()
s.setProgressCompleteWithRepo(cnt, progressIndexOffset, repoURL)
// Ensure the repo is removed from the resume info after being scanned.
defer func(s *Source, repoURL string) {
s.resumeInfoMutex.Lock()
@@ -415,7 +416,7 @@ func (s *Source) scan(ctx context.Context, installationClient *github.Client, ch
return nil
}
s.log.WithField("repo", repoURL).Debugf("attempting to clone repo %d/%d", i+1, len(s.repos))
s.log.WithField("repo", repoURL).Debugf("attempting to clone repo #%d of %d", cnt, repoCnt)
var path string
var repo *gogit.Repository
var err error
@@ -435,12 +436,13 @@ func (s *Source) scan(ctx context.Context, installationClient *github.Client, ch
git.ScanOptionHeadCommit(s.conn.Head),
)
log.Debugf("Starting to scan repo #%d of %d: %s", cnt, repoCnt, repo)
if err = s.git.ScanRepo(ctx, repo, path, scanOptions, chunksChan); err != nil {
log.WithError(err).Errorf("unable to scan repo, continuing")
return nil
}
atomic.AddUint64(&scanned, 1)
log.Debugf("scanned %d/%d repos", scanned, len(s.repos))
log.Debugf("scanned %d/%d repos", scanned, repoCnt)
return nil
})
@@ -448,7 +450,7 @@ func (s *Source) scan(ctx context.Context, installationClient *github.Client, ch
_ = s.jobPool.Wait()
if len(scanErrs) == 0 {
s.SetProgressComplete(len(s.repos), len(s.repos), "Completed Github scan", "")
s.SetProgressComplete(repoCnt, repoCnt, "Completed Github scan", "")
}
return scanErrs
+40 -38
View File
@@ -8,6 +8,9 @@ import (
"sort"
"strings"
"sync"
"sync/atomic"
"golang.org/x/sync/errgroup"
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
@@ -44,6 +47,7 @@ type Source struct {
resumeInfoMutex sync.Mutex
jobSem *semaphore.Weighted
sources.Progress
jobPool *errgroup.Group
}
// Ensure the Source satisfies the interface at compile time.
@@ -71,7 +75,8 @@ func (s *Source) Init(aCtx context.Context, name string, jobId, sourceId int64,
s.sourceId = sourceId
s.jobId = jobId
s.verify = verify
s.jobSem = semaphore.NewWeighted(int64(concurrency))
s.jobPool = &errgroup.Group{}
s.jobPool.SetLimit(concurrency)
var conn sourcespb.GitLab
err := anypb.UnmarshalTo(connection, &conn, proto.UnmarshalOptions{})
@@ -265,34 +270,30 @@ func (s *Source) getRepos() ([]string, []error) {
}
func (s *Source) scanRepos(ctx context.Context, chunksChan chan *sources.Chunk) []error {
wg := sync.WaitGroup{}
var errs []error
var errsMut sync.Mutex
var scanned uint64
// If there is resume information available, limit this scan to only the repos that still need scanning.
reposToScan, progressIndexOffset := sources.FilterReposToResume(s.repos, s.GetProgress().EncodedResumeInfo)
s.repos = reposToScan
log.Debugf("Found %v total repos to scan", len(s.repos))
for i, repo := range s.repos {
if common.IsDone(ctx) {
// We are returning nil instead of the scanErrors slice here because
// we don't want to mark this scan as errored if we cancelled it.
return nil
}
if err := s.jobSem.Acquire(ctx, 1); err != nil {
log.WithError(err).Debug("could not acquire semaphore")
continue
}
wg.Add(1)
go func(ctx context.Context, repoURL string, i int) {
defer s.jobSem.Release(1)
defer wg.Done()
var scanErrs []error
repoCnt := len(s.repos)
for _, repoURL := range s.repos {
repoURL := repoURL
s.jobPool.Go(func() error {
if common.IsDone(ctx) {
// We are returning nil instead of the scanErrors slice here because
// we don't want to mark this scan as errored if we cancelled it.
return nil
}
if len(repoURL) == 0 {
return
return nil
}
s.setProgressCompleteWithRepo(i, progressIndexOffset, repoURL)
// Ensure the repo is removed from the resume info after being scanned.
cnt := s.Counter.Inc()
s.setProgressCompleteWithRepo(cnt, progressIndexOffset, repoURL)
// Ensure the repoURL is removed from the resume info after being scanned.
defer func(s *Source) {
s.resumeInfoMutex.Lock()
defer s.resumeInfoMutex.Unlock()
@@ -305,7 +306,7 @@ func (s *Source) scanRepos(ctx context.Context, chunksChan chan *sources.Chunk)
if s.authMethod == "UNAUTHENTICATED" {
path, repo, err = git.CloneRepoUsingUnauthenticated(repoURL)
} else {
// If a username is not provided we need to use a default one in order to clone a private repo.
// If a username is not provided we need to use a default one in order to clone a private repoURL.
// Not setting "placeholder" as s.user on purpose in case any downstream services rely on a "" value for s.user.
user := s.user
if user == "" {
@@ -315,28 +316,29 @@ func (s *Source) scanRepos(ctx context.Context, chunksChan chan *sources.Chunk)
}
defer os.RemoveAll(path)
if err != nil {
errsMut.Lock()
errs = append(errs, err)
errsMut.Unlock()
return
scanErrs = append(scanErrs, err)
return nil
}
log.Debugf("Starting to scan repo %d/%d: %s", i+1, len(s.repos), repoURL)
log.Debugf("Starting to scan repoURL #%d of %d: %s", cnt, repoCnt, repo)
err = s.git.ScanRepo(ctx, repo, path, git.NewScanOptions(), chunksChan)
if err != nil {
errsMut.Lock()
errs = append(errs, err)
errsMut.Unlock()
return
scanErrs = append(scanErrs, err)
return nil
}
log.Debugf("Completed scanning repo %d/%d: %s", i+1, len(s.repos), repoURL)
}(ctx, repo, i)
}
wg.Wait()
if len(errs) == 0 {
s.SetProgressComplete(len(s.repos), len(s.repos), fmt.Sprintf("Completed scanning source %s", s.name), "")
atomic.AddUint64(&scanned, 1)
log.Debugf("scanned %d/%d repos", scanned, repoCnt)
log.Debugf("Completed scanning repoURL # %d of %d: %s", cnt, repoCnt, repo)
return nil
})
}
return errs
_ = s.jobPool.Wait()
if len(scanErrs) == 0 {
s.SetProgressComplete(repoCnt, repoCnt, fmt.Sprintf("Completed scanning source %s", s.name), "")
}
return scanErrs
}
// Chunks emits chunks of bytes over a channel.
+8 -3
View File
@@ -135,12 +135,15 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err
return errors.Errorf("invalid configuration given for %s source", s.name)
}
for i, bucket := range bucketsToScan {
numBuckets := len(bucketsToScan)
log.Debugf("Found %v total buckets to scan", numBuckets)
for _, bucket := range bucketsToScan {
if common.IsDone(ctx) {
return nil
}
s.SetProgressComplete(i, len(bucketsToScan), fmt.Sprintf("Bucket: %s", bucket), "")
cnt := s.Counter.Inc()
s.SetProgressComplete(cnt, len(bucketsToScan), fmt.Sprintf("Bucket: %s", bucket), "")
s.log.Debugf("Scanning bucket: %s", bucket)
region, err := s3manager.GetBucketRegionWithClient(context.Background(), client, bucket)
@@ -161,6 +164,7 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err
// pf := "public"
errorCount := sync.Map{}
log.Debugf("Starting to scan bucket #%d of %d: %s", cnt, numBuckets, bucket)
err = regionalClient.ListObjectsV2PagesWithContext(
ctx, &s3.ListObjectsV2Input{Bucket: &bucket},
func(page *s3.ListObjectsV2Output, last bool) bool {
@@ -172,8 +176,9 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err
s.log.WithError(err).Errorf("could not list objects in s3 bucket: %s", bucket)
return errors.WrapPrefix(err, fmt.Sprintf("could not list objects in s3 bucket: %s", bucket), 0)
}
log.Debugf("scanned %d/%d buckets", cnt, numBuckets)
}
s.SetProgressComplete(len(bucketsToScan), len(bucketsToScan), fmt.Sprintf("Completed scanning source %s", s.name), "")
s.SetProgressComplete(numBuckets, numBuckets, fmt.Sprintf("Completed scanning source %s", s.name), "")
return nil
}
+28 -4
View File
@@ -104,14 +104,36 @@ func NewConfig(opts ...func(*Config)) Config {
return *c
}
// Counter is a simple monotonically-increasing counter for tracking progress.
type Counter struct {
count uint32
mu sync.Mutex
}
// Inc increments the counter.
func (c *Counter) Inc() int {
c.mu.Lock()
defer c.mu.Unlock()
c.count++
return int(c.count)
}
// Get returns the current count.
func (c *Counter) Get() uint32 {
c.mu.Lock()
defer c.mu.Unlock()
return c.count
}
// Progress is used to update job completion progress across sources.
type Progress struct {
mut sync.Mutex
Counter Counter
SectionsCompleted int32
SectionsRemaining int32
PercentComplete int64
Message string
EncodedResumeInfo string
SectionsCompleted int32
SectionsRemaining int32
mut sync.Mutex
}
// SetProgressComplete sets job progress information for a running job based on the highest level objects in the source.
@@ -119,10 +141,12 @@ type Progress struct {
// scope should be the len(scopedItems)
// message is the public facing user information about the current progress
// encodedResumeInfo is an optional string representing any information necessary to resume the job if interrupted
func (p *Progress) SetProgressComplete(i, scope int, message, encodedResumeInfo string) {
func (p *Progress) SetProgressComplete(_, scope int, message, encodedResumeInfo string) {
p.mut.Lock()
defer p.mut.Unlock()
i := p.Counter.Get()
p.Message = message
p.EncodedResumeInfo = encodedResumeInfo
p.SectionsCompleted = int32(i)