Skip to content

Commit

Permalink
fix(metrics-operator): use context with timeout for fetching analysis…
Browse files Browse the repository at this point in the history
… values (keptn#2213)

Signed-off-by: Florian Bacher <florian.bacher@dynatrace.com>
  • Loading branch information
bacherfl authored and StackScribe committed Oct 13, 2023
1 parent 48c4b65 commit dc38b22
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
6 changes: 4 additions & 2 deletions metrics-operator/controllers/analysis/worker_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ type IAnalysisPool interface {
DispatchAndCollect(ctx context.Context) (map[string]metricsapi.ProviderResult, error)
}

const workerPoolTimeout = 2 * time.Minute

type NewWorkersPoolFactory func(ctx context.Context, analysis *metricsapi.Analysis, objectives []metricsapi.Objective, numWorkers int, c client.Client, log logr.Logger, namespace string) (context.Context, IAnalysisPool)

func NewWorkersPool(ctx context.Context, analysis *metricsapi.Analysis, objectives []metricsapi.Objective, numWorkers int, c client.Client, log logr.Logger, namespace string) (context.Context, IAnalysisPool) {
numJobs := len(objectives)
if numJobs <= numWorkers { // do not start useless go routines
numWorkers = numJobs
}
_, cancel := context.WithTimeout(ctx, 10*time.Second)
childCtx, cancel := context.WithTimeout(ctx, workerPoolTimeout)
providerChans := make(map[string]chan metricstypes.ProviderRequest, len(providers.SupportedProviders))

assigner := TaskAssigner{tasks: objectives, numWorkers: numWorkers}
Expand All @@ -49,7 +51,7 @@ func NewWorkersPool(ctx context.Context, analysis *metricsapi.Analysis, objectiv
providers: providerChans,
cancel: cancel,
}
return ctx, WorkersPool{
return childCtx, WorkersPool{
numWorkers: numWorkers,
numJobs: numJobs,
cancel: cancel,
Expand Down
6 changes: 5 additions & 1 deletion metrics-operator/controllers/analysis/worker_pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,13 @@ func TestNewWorkerPool(t *testing.T) {
}

// no objectives to evaluate
_, got := NewWorkersPool(context.TODO(), &analysis, []metricsapi.Objective{}, 4, nil, log, "default")
ctx, got := NewWorkersPool(context.TODO(), &analysis, []metricsapi.Objective{}, 4, nil, log, "default")
require.Equal(t, 0, got.(WorkersPool).numWorkers)
require.Equal(t, 0, got.(WorkersPool).numJobs)
deadline, ok := ctx.Deadline()
require.True(t, ok)
// verify that we get a context with a timeout being set
require.WithinDuration(t, time.Now().Add(workerPoolTimeout), deadline, 1*time.Second)

_, got = NewWorkersPool(context.TODO(), &analysis, objs, 4, nil, log, "default")
//make sure never to create more workers than needed
Expand Down

0 comments on commit dc38b22

Please sign in to comment.