let the repo handle timeouts... better for automating audits anyway

This commit is contained in:
zricethezav committed 2020-01-19 09:26:06 -05:00
1 parent e75693b131
commit 62e74b2b18
3 files changed
+56 -3

No files matched your search

+42 -1
View File
@@ -2,6 +2,7 @@ package audit
import (
"bytes"
"context"
"crypto/md5"
"fmt"
"io"
@@ -39,6 +40,8 @@ type Repo struct {
// for those repo audits.
config config.Config
ctx context.Context
Name string
Manager *manager.Manager
}
@@ -200,10 +203,45 @@ func (repo *Repo) AuditUncommitted() error {
return nil
}
// timeoutReached returns true if the timeout deadline has been met. This function should be used
// at the top of loops and before potentially long running goroutines (like checking inefficient regexes)
func (repo *Repo) timeoutReached() bool {
if repo.ctx.Err() == context.DeadlineExceeded {
return true
}
return false
}
// setupTimeout parses the --timeout option and assigns a context with timeout to the manager
// which will exit early if the timeout has been met.
func (repo *Repo) setupTimeout() error {
if repo.Manager.Opts.Timeout == "" {
return nil
}
timeout, err := time.ParseDuration(repo.Manager.Opts.Timeout)
if err != nil {
return err
}
repo.ctx, _ = context.WithTimeout(context.Background(), timeout)
go func() {
select {
case <-repo.ctx.Done():
log.Warnf("Timeout deadline exceeded: %s", timeout.String())
}
}()
return nil
}
// Audit is responsible for scanning the entire history (default behavior) of a
// git repo. Options that can change the behavior of this function include: --commit, --depth, --branch.
// See options/options.go for an explanation on these options.
func (repo *Repo) Audit() error {
if err := repo.setupTimeout(); err != nil {
return err
}
if repo.Repository == nil {
return fmt.Errorf("%s repo is empty", repo.Name)
}
@@ -247,7 +285,7 @@ func (repo *Repo) Audit() error {
semaphore := make(chan bool, howManyThreads(repo.Manager.Opts.Threads))
wg := sync.WaitGroup{}
err = cIter.ForEach(func(c *object.Commit) error {
if c == nil || c.Hash.String() == repo.Manager.Opts.CommitTo {
if c == nil || c.Hash.String() == repo.Manager.Opts.CommitTo || repo.timeoutReached() {
return storer.ErrStop
}
@@ -274,6 +312,9 @@ func (repo *Repo) Audit() error {
return
}
}()
if repo.timeoutReached() {
return nil
}
start := time.Now()
patch, err := c.Patch(parent)
if err != nil {