Skip to content

Commit

Permalink
chore: enable early-return from revive
Browse files Browse the repository at this point in the history
Signed-off-by: Matthieu MOREL <[email protected]>
  • Loading branch information
mmorel-35 committed Jan 9, 2025
1 parent a1830b3 commit 5b8a767
Show file tree
Hide file tree
Showing 17 changed files with 79 additions and 85 deletions.
5 changes: 5 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ linters-settings:
- name: context-keys-type
# Importing with `.` makes the programs much harder to understand
- name: dot-imports
- name: early-return
arguments:
- "preserveScope"
# Empty blocks make code less readable and could be a symptom of a bug or unfinished refactoring.
- name: empty-block
# for better readability, variables of type `error` must be named with the prefix `err`.
Expand All @@ -111,6 +114,8 @@ linters-settings:
- name: redefines-builtin-id
# redundant else-blocks that can be eliminated from the code.
- name: superfluous-else
arguments:
- "preserveScope"
# prevent confusing name for variables when using `time` package
- name: time-naming
# warns when an exported function or method returns a value of an un-exported type.
Expand Down
5 changes: 2 additions & 3 deletions confmap/provider/aesprovider/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,12 @@ func TestAESCredentialProvider(t *testing.T) {

p := NewFactory().Create(confmap.ProviderSettings{})
retrieved, err := p.Retrieve(context.Background(), tt.configValue, nil)
if tt.expectedError == "" {
require.NoError(t, err)
} else {
if tt.expectedError != "" {
require.Error(t, err)
require.Equal(t, tt.expectedError, err.Error())
return
}
require.NoError(t, err)
require.NotNil(t, retrieved)
stringValue, err := retrieved.AsString()
require.NoError(t, err)
Expand Down
5 changes: 2 additions & 3 deletions exporter/datasetexporter/datasetexporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,11 @@ func updateWithPrefixedValues(target map[string]any, prefix string, separator st
// now the last value wins
// Should the first value win?
_, found := target[prefix]
if found && len(suffix) > 0 {
prefix += suffix
} else {
if !found || len(suffix) == 0 {
target[prefix] = source
break
}
prefix += suffix
}
}

Expand Down
7 changes: 3 additions & 4 deletions exporter/prometheusexporter/accumulator.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,15 +261,14 @@ func (a *lastValueAccumulator) accumulateHistogram(metric pmetric.Metric, il pco
zap.String("pp_timestamp", pp.Timestamp().String()),
zap.String("ip_timestamp", ip.Timestamp().String()),
).Warn("Misaligned starting timestamps")
if ip.StartTimestamp().AsTime().After(pp.Timestamp().AsTime()) {
a.logger.Debug("treating it like reset")
ip.CopyTo(m.Histogram().DataPoints().AppendEmpty())
} else {
if !ip.StartTimestamp().AsTime().After(pp.Timestamp().AsTime()) {
a.logger.With(
zap.String("metric_name", metric.Name()),
).Warn("Dropped misaligned histogram datapoint")
continue
}
a.logger.Debug("treating it like reset")
ip.CopyTo(m.Histogram().DataPoints().AppendEmpty())
} else {
a.logger.Debug("Accumulate another histogram datapoint")
accumulateHistogramValues(pp, ip, m.Histogram().DataPoints().AppendEmpty())
Expand Down
7 changes: 3 additions & 4 deletions exporter/signalfxexporter/internal/correlation/correlation.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,11 @@ func (cor *Tracker) ProcessTraces(ctx context.Context, traces ptrace.Traces) err
res := traces.ResourceSpans().At(0).Resource()
hostID, ok := splunk.ResourceToHostID(res)

if ok {
cor.log.Info("Detected host resource ID for correlation", zap.Any("hostID", hostID))
} else {
if !ok {
cor.log.Warn("Unable to determine host resource ID for correlation syncing")
return
}
}
cor.log.Info("Detected host resource ID for correlation", zap.Any("hostID", hostID))

hostDimension := string(hostID.Key)

Expand Down
5 changes: 2 additions & 3 deletions internal/aws/metrics/metric_calculator.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,10 @@ func NewFloat64DeltaCalculator() MetricCalculator {

func calculateDelta(prev *MetricValue, val any, _ time.Time) (any, bool) {
var deltaValue float64
if prev != nil {
deltaValue = val.(float64) - prev.RawValue.(float64)
} else {
if prev == nil {
return deltaValue, false
}
deltaValue = val.(float64) - prev.RawValue.(float64)
return deltaValue, true
}

Expand Down
5 changes: 2 additions & 3 deletions internal/sqlquery/scraper.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,10 @@ func (s *Scraper) ScrapeMetrics(ctx context.Context) (pmetric.Metrics, error) {
out := pmetric.NewMetrics()
rows, err := s.Client.QueryRows(ctx)
if err != nil {
if errors.Is(err, ErrNullValueWarning) {
s.Logger.Warn("problems encountered getting metric rows", zap.Error(err))
} else {
if !errors.Is(err, ErrNullValueWarning) {
return out, fmt.Errorf("Scraper: %w", err)
}
s.Logger.Warn("problems encountered getting metric rows", zap.Error(err))
}
ts := pcommon.NewTimestampFromTime(time.Now())
rms := out.ResourceMetrics()
Expand Down
6 changes: 3 additions & 3 deletions pkg/stanza/entry/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,11 @@ func (entry *Entry) readToStringMap(field FieldInterface, dest *map[string]strin
case map[string]any:
newDest := make(map[string]string)
for k, v := range m {
if vStr, ok := v.(string); ok {
newDest[k] = vStr
} else {
vStr, ok := v.(string)
if !ok {
return fmt.Errorf("can not cast map members '%s' of type '%s' to string", k, v)
}
newDest[k] = vStr
}
*dest = newDest
case map[any]any:
Expand Down
17 changes: 8 additions & 9 deletions receiver/awscontainerinsightreceiver/internal/stores/podstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,17 @@ func (p *PodStore) Decorate(ctx context.Context, metric CIMetric, kubernetesBlob
}

// If the entry is not a placeholder, decorate the pod
if entry.pod.Name != "" {
p.decorateCPU(metric, &entry.pod)
p.decorateMem(metric, &entry.pod)
p.addStatus(metric, &entry.pod)
addContainerCount(metric, &entry.pod)
addContainerID(&entry.pod, metric, kubernetesBlob, p.logger)
p.addPodOwnersAndPodName(metric, &entry.pod, kubernetesBlob)
addLabels(&entry.pod, kubernetesBlob)
} else {
if entry.pod.Name == "" {
p.logger.Warn("no pod information is found in podstore for pod " + podKey)
return false
}
p.decorateCPU(metric, &entry.pod)
p.decorateMem(metric, &entry.pod)
p.addStatus(metric, &entry.pod)
addContainerCount(metric, &entry.pod)
addContainerID(&entry.pod, metric, kubernetesBlob, p.logger)
p.addPodOwnersAndPodName(metric, &entry.pod, kubernetesBlob)
addLabels(&entry.pod, kubernetesBlob)
}
return true
}
Expand Down
6 changes: 3 additions & 3 deletions receiver/awss3receiver/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,11 @@ func newEncodingExtensions(encodingsConfig []Encoding, host component.Host) (enc
encodings := make(encodingExtensions, 0)
extensions := host.GetExtensions()
for _, configItem := range encodingsConfig {
if e, ok := extensions[configItem.Extension]; ok {
encodings = append(encodings, encodingExtension{extension: e, suffix: configItem.Suffix})
} else {
e, ok := extensions[configItem.Extension]
if !ok {
return nil, fmt.Errorf("extension %q not found", configItem.Extension)
}
encodings = append(encodings, encodingExtension{extension: e, suffix: configItem.Suffix})
}
return encodings, nil
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,11 @@ func (r azureResourceMetricsUnmarshaler) UnmarshalMetrics(event *eventhub.Event)
}

var startTimestamp pcommon.Timestamp
if azureMetric.TimeGrain == "PT1M" {
startTimestamp = pcommon.NewTimestampFromTime(nanos.AsTime().Add(-time.Minute))
} else {
if azureMetric.TimeGrain != "PT1M" {
r.logger.Warn("Unhandled Time Grain", zap.String("timegrain", azureMetric.TimeGrain))
continue
}
startTimestamp = pcommon.NewTimestampFromTime(nanos.AsTime().Add(-time.Minute))

metricTotal := metrics.AppendEmpty()
metricTotal.SetName(strings.ToLower(fmt.Sprintf("%s_%s", strings.ReplaceAll(azureMetric.MetricName, " ", "_"), "Total")))
Expand Down
5 changes: 2 additions & 3 deletions receiver/cloudfoundryreceiver/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,11 @@ type authorizationProvider struct {

func (ap *authorizationProvider) Do(request *http.Request) (*http.Response, error) {
token, err := ap.authTokenProvider.ProvideToken()
if err == nil {
request.Header.Set("Authorization", token)
} else {
if err != nil {
ap.logger.Error("fetching authentication token", zap.Error(err))
return nil, errors.New("obtaining authentication token for the request")
}
request.Header.Set("Authorization", token)

return ap.client.Do(request)
}
12 changes: 6 additions & 6 deletions receiver/kubeletstatsreceiver/internal/kubelet/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ var supportedLabels = map[MetadataLabel]bool{
func ValidateMetadataLabelsConfig(labels []MetadataLabel) error {
labelsFound := map[MetadataLabel]bool{}
for _, label := range labels {
if _, supported := supportedLabels[label]; supported {
if _, duplicate := labelsFound[label]; duplicate {
return fmt.Errorf("duplicate metadata label: %q", label)
}
labelsFound[label] = true
} else {
_, supported := supportedLabels[label]
if !supported {
return fmt.Errorf("label %q is not supported", label)
}
if _, duplicate := labelsFound[label]; duplicate {
return fmt.Errorf("duplicate metadata label: %q", label)
}
labelsFound[label] = true
}
return nil
}
Expand Down
6 changes: 3 additions & 3 deletions receiver/prometheusreceiver/internal/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,13 +198,13 @@ func (t *transaction) getOrCreateMetricFamily(key resourceKey, scope scopeID, mn
if _, ok := t.mc.GetMetadata(mn); !ok {
fn = normalizeMetricName(mn)
}
if mf, ok := t.families[key][scope][fn]; ok && mf.includesMetric(mn) {
curMf = mf
} else {
mf, ok := t.families[key][scope][fn]
if !ok || !mf.includesMetric(mn) {
curMf = newMetricFamily(mn, t.mc, t.logger)
t.families[key][scope][curMf.name] = curMf
return curMf, false
}
curMf = mf
}
return curMf, true
}
Expand Down
9 changes: 4 additions & 5 deletions receiver/saphanareceiver/queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,12 @@ func (q *queryStat) collectStat(s *sapHanaScraper, m *monitoringQuery, now pcomm
return fmt.Errorf("unable to parse metric for key %s: %w", q.key, err)
}

if q.addMetricFunction != nil {
if err = q.addMetricFunction(mb, now, val, row); err != nil {
return fmt.Errorf("failed to record metric for key %s: %w", q.key, err)
}
} else {
if q.addMetricFunction == nil {
return errors.New("incorrectly configured query, addMetricFunction must be provided")
}
if err = q.addMetricFunction(mb, now, val, row); err != nil {
return fmt.Errorf("failed to record metric for key %s: %w", q.key, err)
}
}
return nil
}
Expand Down
49 changes: 24 additions & 25 deletions receiver/solacereceiver/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,35 +265,34 @@ flowControlLoop:
}

forwardErr := s.nextConsumer.ConsumeTraces(ctx, traces)
if forwardErr != nil {
if !consumererror.IsPermanent(forwardErr) {
s.settings.Logger.Info("Encountered temporary error while forwarding traces to next receiver, will allow redelivery", zap.Error(forwardErr))
// handle flow control metrics
if flowControlCount == 0 {
s.telemetryBuilder.SolacereceiverReceiverFlowControlStatus.Record(ctx, int64(flowControlStateControlled), metric.WithAttributeSet(s.metricAttrs))
}
flowControlCount++
s.telemetryBuilder.SolacereceiverReceiverFlowControlRecentRetries.Record(ctx, flowControlCount, metric.WithAttributeSet(s.metricAttrs))
// Backpressure scenario. For now, we are only delayed retry, eventually we may need to handle this
delayTimer := time.NewTimer(s.config.Flow.DelayedRetry.Delay)
select {
case <-delayTimer.C:
continue flowControlLoop
case <-ctx.Done():
s.settings.Logger.Info("Context was cancelled while attempting redelivery, exiting")
disposition = nil // do not make any network requests, we are shutting down
return errors.New("delayed retry interrupted by shutdown request")
}
} else { // error is permanent, we want to accept the message and increment the number of dropped messages
s.settings.Logger.Warn("Encountered permanent error while forwarding traces to next receiver, will swallow trace", zap.Error(forwardErr))
s.telemetryBuilder.SolacereceiverDroppedSpanMessages.Add(ctx, 1, metric.WithAttributeSet(s.metricAttrs))
break flowControlLoop
}
} else {
if forwardErr == nil {
// no forward error
s.telemetryBuilder.SolacereceiverReportedSpans.Add(ctx, int64(spanCount), metric.WithAttributeSet(s.metricAttrs))
break flowControlLoop
}
if !consumererror.IsPermanent(forwardErr) {
s.settings.Logger.Info("Encountered temporary error while forwarding traces to next receiver, will allow redelivery", zap.Error(forwardErr))
// handle flow control metrics
if flowControlCount == 0 {
s.telemetryBuilder.SolacereceiverReceiverFlowControlStatus.Record(ctx, int64(flowControlStateControlled), metric.WithAttributeSet(s.metricAttrs))
}
flowControlCount++
s.telemetryBuilder.SolacereceiverReceiverFlowControlRecentRetries.Record(ctx, flowControlCount, metric.WithAttributeSet(s.metricAttrs))
// Backpressure scenario. For now, we are only delayed retry, eventually we may need to handle this
delayTimer := time.NewTimer(s.config.Flow.DelayedRetry.Delay)
select {
case <-delayTimer.C:
continue flowControlLoop
case <-ctx.Done():
s.settings.Logger.Info("Context was cancelled while attempting redelivery, exiting")
disposition = nil // do not make any network requests, we are shutting down
return errors.New("delayed retry interrupted by shutdown request")
}
} else { // error is permanent, we want to accept the message and increment the number of dropped messages
s.settings.Logger.Warn("Encountered permanent error while forwarding traces to next receiver, will swallow trace", zap.Error(forwardErr))
s.telemetryBuilder.SolacereceiverDroppedSpanMessages.Add(ctx, 1, metric.WithAttributeSet(s.metricAttrs))
break flowControlLoop
}
}
// Make sure to clear the stats no matter what, unless we were interrupted in which case we should preserve the last state
if flowControlCount != 0 {
Expand Down
10 changes: 5 additions & 5 deletions testbed/testbed/child_process_collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,12 +334,12 @@ func (cp *childProcessCollector) WatchResourceConsumption() error {
for start := time.Now(); time.Since(start) < time.Minute; {
cp.fetchRAMUsage()
cp.fetchCPUUsage()
if err := cp.checkAllowedResourceUsage(); err != nil {
log.Printf("Allowed usage of resources is too high before test starts wait for one second : %v", err)
time.Sleep(time.Second)
} else {
err := cp.checkAllowedResourceUsage();

Check failure on line 337 in testbed/testbed/child_process_collector.go

View workflow job for this annotation

GitHub Actions / lint-matrix (windows, other)

File is not properly formatted (gci)

Check failure on line 337 in testbed/testbed/child_process_collector.go

View workflow job for this annotation

GitHub Actions / lint-matrix (linux, other)

File is not properly formatted (gci)
if err == nil {
break
}
}

Check failure on line 340 in testbed/testbed/child_process_collector.go

View workflow job for this annotation

GitHub Actions / lint-matrix (windows, other)

File is not properly formatted (gci)

Check failure on line 340 in testbed/testbed/child_process_collector.go

View workflow job for this annotation

GitHub Actions / lint-matrix (linux, other)

File is not properly formatted (gci)
log.Printf("Allowed usage of resources is too high before test starts wait for one second : %v", err)
time.Sleep(time.Second)
}

remainingFailures := cp.resourceSpec.MaxConsecutiveFailures
Expand Down

0 comments on commit 5b8a767

Please sign in to comment.