Merge branch 'main' into docker-tar-identification-from-filesystem-2
This commit is contained in:
@@ -88,7 +88,7 @@ func startSqlServer() error {
|
||||
return nil
|
||||
case <-time.After(30 * time.Second):
|
||||
stopSqlServer()
|
||||
return errors.New("timeout waiting for mysql database to be ready")
|
||||
return errors.New("timeout waiting for sql server database to be ready")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"regexp"
|
||||
|
||||
mssql "github.com/denisenkom/go-mssqldb"
|
||||
"github.com/denisenkom/go-mssqldb/msdsn"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
|
||||
|
||||
@@ -49,9 +50,15 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
|
||||
|
||||
if verify {
|
||||
verified, err := ping(paramsUnsafe)
|
||||
if err != nil {
|
||||
|
||||
detected.Verified = verified
|
||||
|
||||
if mssqlErr, isMssqlErr := err.(mssql.Error); isMssqlErr && mssqlErr.Number == 18456 {
|
||||
// Login failed
|
||||
// Number taken from https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors?view=sql-server-ver16
|
||||
// Nothing to do; determinate failure to verify
|
||||
} else {
|
||||
detected.Verified = verified
|
||||
detected.VerificationError = err
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//go:build detectors && integration
|
||||
// +build detectors,integration
|
||||
|
||||
package sqlserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
|
||||
)
|
||||
|
||||
func TestSQLServerIntegration_FromChunk(t *testing.T) {
|
||||
type args struct {
|
||||
ctx context.Context
|
||||
data []byte
|
||||
verify bool
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
s Scanner
|
||||
args args
|
||||
want []detectors.Result
|
||||
wantErr bool
|
||||
wantVerificationErr bool
|
||||
}{
|
||||
{
|
||||
name: "found, verified",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte("Server=localhost;Initial Catalog=master;User ID=sa;Password=P@ssw0rd!;Persist Security Info=true;MultipleActiveResultSets=true;"),
|
||||
verify: true,
|
||||
},
|
||||
want: []detectors.Result{
|
||||
{
|
||||
DetectorType: detectorspb.DetectorType_SQLServer,
|
||||
Raw: []byte("P@ssw0rd!"),
|
||||
RawV2: []byte("sqlserver://sa:P%40ssw0rd%21@localhost?database=master&disableRetry=false"),
|
||||
Redacted: "sqlserver://sa:********@localhost?database=master&disableRetry=false",
|
||||
Verified: true,
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "found, unverified",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte("Server=localhost;User ID=sa;Password=123"),
|
||||
verify: true,
|
||||
},
|
||||
want: []detectors.Result{
|
||||
{
|
||||
DetectorType: detectorspb.DetectorType_SQLServer,
|
||||
Raw: []byte("123"),
|
||||
RawV2: []byte("sqlserver://sa:123@localhost?disableRetry=false"),
|
||||
Redacted: "sqlserver://sa:********@localhost?disableRetry=false",
|
||||
Verified: false,
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "not found, in XML, missing password param (pwd is not valid)",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte(`<add name="Sample2" value="SERVER=server_name;DATABASE=database_name;user=user_name;pwd=plaintextpassword;encrypt=true;Timeout=120;MultipleActiveResultSets=True;" />`),
|
||||
verify: true,
|
||||
},
|
||||
want: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "found, verified, in XML",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte(`<add name="test db" value="SERVER=localhost;DATABASE=master;user=sa;password=P@ssw0rd!;encrypt=true;Timeout=120;MultipleActiveResultSets=True;" />`),
|
||||
verify: true,
|
||||
},
|
||||
want: []detectors.Result{
|
||||
{
|
||||
DetectorType: detectorspb.DetectorType_SQLServer,
|
||||
Redacted: "sqlserver://sa:********@localhost?database=master&disableRetry=false",
|
||||
Raw: []byte("P@ssw0rd!"),
|
||||
RawV2: []byte("sqlserver://sa:P%40ssw0rd%21@localhost?database=master&disableRetry=false"),
|
||||
Verified: true,
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "found, unreachable host",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte("Server=unreachablehost;Initial Catalog=master;User ID=sa;Password=P@ssw0rd!;Persist Security Info=true;MultipleActiveResultSets=true;"),
|
||||
verify: true,
|
||||
},
|
||||
want: []detectors.Result{
|
||||
{
|
||||
DetectorType: detectorspb.DetectorType_SQLServer,
|
||||
Raw: []byte("P@ssw0rd!"),
|
||||
RawV2: []byte("sqlserver://sa:P%40ssw0rd%21@unreachablehost?database=master&disableRetry=false"),
|
||||
Redacted: "sqlserver://sa:********@unreachablehost?database=master&disableRetry=false",
|
||||
Verified: false,
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
wantVerificationErr: true,
|
||||
},
|
||||
{
|
||||
name: "not found",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte("You cannot find the secret within"),
|
||||
verify: true,
|
||||
},
|
||||
want: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
if err := startSqlServer(); err != nil {
|
||||
t.Fatalf("could not start sql server for integration testing: %v", err)
|
||||
}
|
||||
defer stopSqlServer()
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := Scanner{}
|
||||
got, err := s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("SQLServer.FromData() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
for i := range got {
|
||||
if len(got[i].Raw) == 0 {
|
||||
t.Fatalf("no raw secret present: \n %+v", got[i])
|
||||
}
|
||||
if (got[i].VerificationError != nil) != tt.wantVerificationErr {
|
||||
t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError)
|
||||
}
|
||||
}
|
||||
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "VerificationError")
|
||||
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
|
||||
t.Errorf("SQLServer.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var sqlServerDockerHash string
|
||||
|
||||
func dockerLogLine(hash string, needle string) chan struct{} {
|
||||
ch := make(chan struct{}, 1)
|
||||
go func() {
|
||||
for {
|
||||
out, err := exec.Command("docker", "logs", hash).CombinedOutput()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if strings.Contains(string(out), needle) {
|
||||
ch <- struct{}{}
|
||||
return
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
func startSqlServer() error {
|
||||
cmd := exec.Command(
|
||||
"docker", "run", "--rm", "-p", "1433:1433",
|
||||
"-e", "ACCEPT_EULA=1",
|
||||
"-e", "MSSQL_SA_PASSWORD=P@ssw0rd!",
|
||||
"-d", "mcr.microsoft.com/azure-sql-edge",
|
||||
)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sqlServerDockerHash = string(bytes.TrimSpace(out))
|
||||
select {
|
||||
case <-dockerLogLine(sqlServerDockerHash, "EdgeTelemetry starting up"):
|
||||
return nil
|
||||
case <-time.After(30 * time.Second):
|
||||
stopSqlServer()
|
||||
return errors.New("timeout waiting for sql server database to be ready")
|
||||
}
|
||||
}
|
||||
|
||||
func stopSqlServer() {
|
||||
exec.Command("docker", "kill", sqlServerDockerHash).Run()
|
||||
}
|
||||
+111
-36
@@ -273,6 +273,65 @@ func (s *Source) Init(aCtx context.Context, name string, jobID, sourceID int64,
|
||||
return nil
|
||||
}
|
||||
|
||||
// Validate is used by enterprise CLI to validate the Github config file.
|
||||
func (s *Source) Validate(ctx context.Context) []error {
|
||||
var (
|
||||
errs []error
|
||||
ghClient *github.Client
|
||||
err error
|
||||
)
|
||||
apiEndpoint := s.conn.Endpoint
|
||||
|
||||
switch cred := s.conn.GetCredential().(type) {
|
||||
case *sourcespb.GitHub_BasicAuth:
|
||||
s.httpClient.Transport = &github.BasicAuthTransport{
|
||||
Username: cred.BasicAuth.Username,
|
||||
Password: cred.BasicAuth.Password,
|
||||
}
|
||||
ghClient, err = createGitHubClient(s.httpClient, apiEndpoint)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("error creating GitHub client: %+v", err))
|
||||
}
|
||||
case *sourcespb.GitHub_Unauthenticated:
|
||||
ghClient, err = createGitHubClient(s.httpClient, apiEndpoint)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("error creating GitHub client: %+v", err))
|
||||
}
|
||||
case *sourcespb.GitHub_Token:
|
||||
s.githubToken = cred.Token
|
||||
|
||||
ts := oauth2.StaticTokenSource(
|
||||
&oauth2.Token{AccessToken: s.githubToken},
|
||||
)
|
||||
s.httpClient.Transport = &oauth2.Transport{
|
||||
Base: s.httpClient.Transport,
|
||||
Source: oauth2.ReuseTokenSource(nil, ts),
|
||||
}
|
||||
|
||||
ghClient, err = createGitHubClient(s.httpClient, apiEndpoint)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("error creating GitHub client: %+v", err))
|
||||
}
|
||||
default:
|
||||
errs = append(errs, errors.Errorf("Invalid configuration given for source. Name: %s, Type: %s", s.name, s.Type()))
|
||||
}
|
||||
|
||||
// Run a simple query to check if the client is actually valid
|
||||
if ghClient != nil {
|
||||
err = checkGitHubConnection(ctx, ghClient)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
return errs
|
||||
}
|
||||
|
||||
func checkGitHubConnection(ctx context.Context, client *github.Client) error {
|
||||
_, _, err := client.Users.Get(ctx, "")
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Source) visibilityOf(ctx context.Context, repoURL string) (visibility source_metadatapb.Visibility) {
|
||||
s.mu.Lock()
|
||||
visibility, ok := s.publicMap[repoURL]
|
||||
@@ -357,6 +416,11 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err
|
||||
apiEndpoint = "https://api.github.com"
|
||||
}
|
||||
|
||||
// Reset consumption and rate limit metrics on each run.
|
||||
githubNumRateLimitEncountered.WithLabelValues(s.name).Set(0)
|
||||
githubSecondsSpentRateLimited.WithLabelValues(s.name).Set(0)
|
||||
githubReposScanned.WithLabelValues(s.name).Set(0)
|
||||
|
||||
installationClient, err := s.enumerate(ctx, apiEndpoint)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -392,6 +456,7 @@ func (s *Source) enumerate(ctx context.Context, apiEndpoint string) (*github.Cli
|
||||
}
|
||||
|
||||
s.repos = s.filteredRepoCache.Values()
|
||||
githubReposEnumerated.WithLabelValues(s.name).Set(float64(len(s.repos)))
|
||||
s.log.Info("Completed enumeration", "num_repos", len(s.repos), "num_orgs", s.orgsCache.Count(), "num_members", len(s.memberCache))
|
||||
|
||||
// We must sort the repos so we can resume later if necessary.
|
||||
@@ -722,6 +787,8 @@ func (s *Source) scan(ctx context.Context, installationClient *github.Client, ch
|
||||
return nil
|
||||
}
|
||||
|
||||
githubReposScanned.WithLabelValues(s.name).Inc()
|
||||
|
||||
if err = s.scanComments(ctx, repoURL, chunksChan); err != nil {
|
||||
scanErrs.Add(fmt.Errorf("error scanning comments in repo %s: %w", repoURL, err))
|
||||
return nil
|
||||
@@ -751,6 +818,8 @@ func (s *Source) handleRateLimit(errIn error, res *github.Response) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
githubNumRateLimitEncountered.WithLabelValues(s.name).Inc()
|
||||
|
||||
if res != nil {
|
||||
knownWait := true
|
||||
remaining, err := strconv.Atoi(res.Header.Get("x-ratelimit-remaining"))
|
||||
@@ -768,6 +837,7 @@ func (s *Source) handleRateLimit(errIn error, res *github.Response) bool {
|
||||
duration := time.Duration(waitTime+1) * time.Second
|
||||
s.log.V(2).Info("rate limited", "resumeTime", time.Now().Add(duration).String())
|
||||
time.Sleep(duration)
|
||||
githubSecondsSpentRateLimited.WithLabelValues(s.name).Add(duration.Seconds())
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -988,46 +1058,51 @@ func (s *Source) scanComments(ctx context.Context, repoPath string, chunksChan c
|
||||
|
||||
trimmedURL := removeURLAndSplit(repoURL.String())
|
||||
if repoURL.Host == "gist.github.com" && s.includeGistComments {
|
||||
s.log.Info("scanning github gist comments", "repository", repoPath)
|
||||
// GitHub Gist URL.
|
||||
var gistId string
|
||||
if len(trimmedURL) == 2 {
|
||||
// https://gist.github.com/<id>
|
||||
gistId = trimmedURL[1]
|
||||
} else if len(trimmedURL) == 3 {
|
||||
// https://gist.github.com/<owner>/<id>
|
||||
gistId = trimmedURL[2]
|
||||
} else {
|
||||
return fmt.Errorf("failed to parse Gist URL: '%s'", repoURL.String())
|
||||
}
|
||||
|
||||
options := &github.ListOptions{
|
||||
PerPage: defaultPagination,
|
||||
Page: initialPage,
|
||||
}
|
||||
for {
|
||||
comments, resp, err := s.apiClient.Gists.ListComments(ctx, gistId, options)
|
||||
if s.handleRateLimit(err, resp) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = s.chunkGistComments(ctx, repoURL.String(), comments, chunksChan)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options.Page++
|
||||
if len(comments) < options.PerPage {
|
||||
break
|
||||
}
|
||||
}
|
||||
return s.processGistComments(ctx, repoPath, trimmedURL, repoURL, chunksChan)
|
||||
}
|
||||
return s.processRepoComments(ctx, repoPath, trimmedURL, repoURL, chunksChan)
|
||||
}
|
||||
|
||||
func (s *Source) processGistComments(ctx context.Context, repoPath string, trimmedURL []string, repoURL *url.URL, chunksChan chan *sources.Chunk) error {
|
||||
s.log.Info("scanning github gist comments", "repository", repoPath)
|
||||
// GitHub Gist URL.
|
||||
gistID, err := extractGistID(trimmedURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := &github.ListOptions{
|
||||
PerPage: defaultPagination,
|
||||
Page: initialPage,
|
||||
}
|
||||
for {
|
||||
comments, resp, err := s.apiClient.Gists.ListComments(ctx, gistID, options)
|
||||
if s.handleRateLimit(err, resp) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = s.chunkGistComments(ctx, repoURL.String(), comments, chunksChan); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options.Page++
|
||||
if len(comments) < options.PerPage {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func extractGistID(url []string) (string, error) {
|
||||
if len(url) < 2 || len(url) > 3 {
|
||||
return "", fmt.Errorf("failed to parse Gist URL: length of trimmedURL should be 2 or 3")
|
||||
}
|
||||
return url[len(url)-1], nil
|
||||
}
|
||||
|
||||
// Note: these can't be consts because the address is needed when using with the GitHub library.
|
||||
var (
|
||||
// sortType defines the criteria for sorting comments.
|
||||
|
||||
@@ -743,3 +743,22 @@ func TestProcessRepoComments(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetGistID(t *testing.T) {
|
||||
tests := []struct {
|
||||
trimmedURL []string
|
||||
expected string
|
||||
err bool
|
||||
}{
|
||||
{[]string{"https://gist.github.com", "12345"}, "12345", false},
|
||||
{[]string{"https://gist.github.com", "owner", "12345"}, "12345", false},
|
||||
{[]string{"https://gist.github.com"}, "", true},
|
||||
{[]string{"https://gist.github.com", "owner", "12345", "extra"}, "", true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got, err := extractGistID(tt.trimmedURL)
|
||||
assert.Equal(t, tt.err, err != nil)
|
||||
assert.Equal(t, tt.expected, got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package github
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
|
||||
)
|
||||
|
||||
var (
|
||||
githubNumRateLimitEncountered = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: common.MetricsNamespace,
|
||||
Subsystem: common.MetricsSubsystem,
|
||||
Name: "github_num_rate_limit_encountered",
|
||||
Help: "Total number of times Github Rate Limit was encountered",
|
||||
},
|
||||
[]string{"source_name"})
|
||||
|
||||
githubSecondsSpentRateLimited = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: common.MetricsNamespace,
|
||||
Subsystem: common.MetricsSubsystem,
|
||||
Name: "github_seconds_spent_rate_limited",
|
||||
Help: "Total number of seconds spent idle due to GitHub rate limits.",
|
||||
},
|
||||
[]string{"source_name"})
|
||||
|
||||
githubReposEnumerated = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: common.MetricsNamespace,
|
||||
Subsystem: common.MetricsSubsystem,
|
||||
Name: "github_repos_enumerated",
|
||||
Help: "Total number of GitHub repositories enumerated.",
|
||||
},
|
||||
[]string{"source_name"})
|
||||
|
||||
githubReposScanned = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: common.MetricsNamespace,
|
||||
Subsystem: common.MetricsSubsystem,
|
||||
Name: "github_repos_scanned",
|
||||
Help: "Total number of GitHub repositories scanned.",
|
||||
},
|
||||
[]string{"source_name"})
|
||||
)
|
||||
@@ -52,7 +52,7 @@ func TestSource_Chunks(t *testing.T) {
|
||||
Secret: s3secret,
|
||||
},
|
||||
},
|
||||
Buckets: []string{"thog-tmp-test"},
|
||||
Buckets: []string{"truffletestbucket-s3-tests"},
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
@@ -77,7 +77,10 @@ func TestSource_Chunks(t *testing.T) {
|
||||
return
|
||||
}
|
||||
chunksCh := make(chan *sources.Chunk)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
err = s.Chunks(ctx, chunksCh)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("Source.Chunks() error = %v, wantErr %v", err, tt.wantErr)
|
||||
@@ -90,6 +93,7 @@ func TestSource_Chunks(t *testing.T) {
|
||||
if diff := pretty.Compare(gotChunk.Data, wantData); diff != "" {
|
||||
t.Errorf("%s: Source.Chunks() diff: (-got +want)\n%s", tt.name, diff)
|
||||
}
|
||||
wg.Wait()
|
||||
assert.Equal(t, "", s.GetProgress().EncodedResumeInfo)
|
||||
assert.Equal(t, int64(100), s.GetProgress().PercentComplete)
|
||||
})
|
||||
|
||||
@@ -6,10 +6,11 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
// handle uniquely identifies a Source given to the manager to manage. If the
|
||||
@@ -19,7 +20,7 @@ type handle int64
|
||||
|
||||
// SourceInitFunc is a function that takes a source and job ID and returns an
|
||||
// initialized Source.
|
||||
type SourceInitFunc func(ctx context.Context, sourceID int64, jobID int64) (Source, error)
|
||||
type SourceInitFunc func(ctx context.Context, jobID, sourceID int64) (Source, error)
|
||||
|
||||
// sourceInfo is an aggregate struct to store source information provided on
|
||||
// initialization.
|
||||
@@ -228,7 +229,7 @@ func (s *SourceManager) run(ctx context.Context, handle handle, jobID int64, rep
|
||||
report.ReportError(Fatal{err})
|
||||
return Fatal{err}
|
||||
}
|
||||
source, err := sourceInfo.initFunc(ctx, int64(handle), jobID)
|
||||
source, err := sourceInfo.initFunc(ctx, jobID, int64(handle))
|
||||
if err != nil {
|
||||
report.ReportError(Fatal{err})
|
||||
return Fatal{err}
|
||||
@@ -255,6 +256,7 @@ func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, sour
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for chunk := range ch {
|
||||
chunk.JobID = source.JobID()
|
||||
report.ReportChunk(nil, chunk)
|
||||
s.outputChunks <- chunk
|
||||
}
|
||||
@@ -334,6 +336,9 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, source
|
||||
defer wg.Done()
|
||||
defer func() { report.EndUnitChunking(unit, time.Now()) }()
|
||||
for chunk := range chunkReporter.chunkCh {
|
||||
if src, ok := source.(Source); ok {
|
||||
chunk.JobID = src.JobID()
|
||||
}
|
||||
s.outputChunks <- chunk
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -245,3 +245,42 @@ func TestSourceManagerContextCancelled(t *testing.T) {
|
||||
report := ref.Snapshot()
|
||||
assert.Error(t, report.FatalError())
|
||||
}
|
||||
|
||||
type DummyAPI struct {
|
||||
registerSource func(context.Context, string, sourcespb.SourceType) (int64, error)
|
||||
getJobID func(context.Context, int64) (int64, error)
|
||||
}
|
||||
|
||||
func (api DummyAPI) RegisterSource(ctx context.Context, name string, kind sourcespb.SourceType) (int64, error) {
|
||||
return api.registerSource(ctx, name, kind)
|
||||
}
|
||||
|
||||
func (api DummyAPI) GetJobID(ctx context.Context, id int64) (int64, error) {
|
||||
return api.getJobID(ctx, id)
|
||||
}
|
||||
|
||||
func TestSourceManagerJobAndSourceIDs(t *testing.T) {
|
||||
mgr := NewManager(WithAPI(DummyAPI{
|
||||
registerSource: func(context.Context, string, sourcespb.SourceType) (int64, error) {
|
||||
return 1337, nil
|
||||
},
|
||||
getJobID: func(context.Context, int64) (int64, error) {
|
||||
return 9001, nil
|
||||
},
|
||||
}))
|
||||
var (
|
||||
initializedJobID int64
|
||||
initializedSourceID int64
|
||||
)
|
||||
handle, err := mgr.Enroll(context.Background(), "dummy", 1337,
|
||||
func(ctx context.Context, jobID, sourceID int64) (Source, error) {
|
||||
initializedJobID = jobID
|
||||
initializedSourceID = sourceID
|
||||
return nil, fmt.Errorf("ignore")
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, _ = mgr.Run(context.Background(), handle)
|
||||
assert.Equal(t, int64(1337), initializedSourceID)
|
||||
assert.Equal(t, int64(9001), initializedJobID)
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ type Chunk struct {
|
||||
SourceName string
|
||||
// SourceID is the ID of the source that the Chunk originated from.
|
||||
SourceID int64
|
||||
// JobID is the ID of the job that the Chunk originated from.
|
||||
JobID int64
|
||||
// SourceType is the type of Source that produced the chunk.
|
||||
SourceType sourcespb.SourceType
|
||||
// SourceMetadata holds the context of where the Chunk was found.
|
||||
@@ -286,7 +288,7 @@ type Progress struct {
|
||||
// Validator is an interface for validating a source. Sources can optionally implement this interface to validate
|
||||
// their configuration.
|
||||
type Validator interface {
|
||||
Validate() []error
|
||||
Validate(ctx context.Context) []error
|
||||
}
|
||||
|
||||
// SetProgressComplete sets job progress information for a running job based on the highest level objects in the source.
|
||||
|
||||
@@ -60,7 +60,7 @@ func NewSyslog(sourceType sourcespb.SourceType, jobID, sourceID int64, sourceNam
|
||||
}
|
||||
|
||||
// Validate validates the configuration of the source.
|
||||
func (s *Source) Validate() []error {
|
||||
func (s *Source) Validate(ctx context.Context) []error {
|
||||
var errors []error
|
||||
|
||||
if s.conn.TlsCert != nilString || s.conn.TlsKey != nilString {
|
||||
|
||||
Reference in New Issue
Block a user