Skip to content

Commit

Permalink
chore: Solve Checkmarx race condition alert (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
TeodorSAP authored Jul 9, 2024
1 parent 91c348d commit a0ee5a3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
2 changes: 2 additions & 0 deletions receiver/dummyreceiver/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dummyreceiver

import (
"context"
"sync"
"time"

"go.opentelemetry.io/collector/component"
Expand All @@ -28,6 +29,7 @@ func createMetricsReceiver(_ context.Context, params receiver.Settings, baseCfg
config: baseCfg.(*Config),
nextConsumer: consumer,
settings: &params,
wg: &sync.WaitGroup{},
}, nil
}

Expand Down
46 changes: 27 additions & 19 deletions receiver/dummyreceiver/metrics_receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
"sync"
"time"

"go.opentelemetry.io/collector/component"
Expand All @@ -19,6 +20,7 @@ type dummyReceiver struct {
settings *receiver.Settings

cancel context.CancelFunc
wg *sync.WaitGroup
}

func (r *dummyReceiver) Start(_ context.Context, _ component.Host) error { //nolint:contextcheck // Create a new context as specified in the interface documentation
Expand All @@ -32,29 +34,34 @@ func (r *dummyReceiver) Start(_ context.Context, _ component.Host) error { //nol

}

r.wg.Add(1)
go r.startGenerating(ctx, interval) //nolint:contextcheck // Non-inherited new context

return nil
}

func (r *dummyReceiver) startGenerating(ctx context.Context, interval time.Duration) {
defer r.wg.Done()

ticker := time.NewTicker(interval)
defer ticker.Stop()

go func() {
defer ticker.Stop()
for {
select {
case <-ticker.C:
md, err := r.generateMetric()
if err != nil {
r.settings.Logger.Error("Failed to generate metric", zap.Error(err))
continue
}
err = r.nextConsumer.ConsumeMetrics(ctx, md)
if err != nil {
r.settings.Logger.Error("next consumer failed", zap.Error(err))
}
case <-ctx.Done():
return
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
md, err := r.generateMetric()
if err != nil {
r.settings.Logger.Error("Failed to generate metric", zap.Error(err))
continue
}
err = r.nextConsumer.ConsumeMetrics(ctx, md)
if err != nil {
r.settings.Logger.Error("next consumer failed", zap.Error(err))
}
}
}()

return nil
}
}

func (r *dummyReceiver) generateMetric() (pmetric.Metrics, error) {
Expand Down Expand Up @@ -90,5 +97,6 @@ func (r *dummyReceiver) Shutdown(_ context.Context) error {
if r.cancel != nil {
r.cancel()
}
r.wg.Wait()
return nil
}

0 comments on commit a0ee5a3

Please sign in to comment.