Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix errors reported by gocritic and enable #1509

Merged
merged 1 commit into from
Aug 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ linters:
- misspell
- scopelint
- unconvert
- gocritic

issues:
# Excluding configuration per-path, per-linter, per-text and per-source
Expand Down
10 changes: 2 additions & 8 deletions cmd/pdatagen/internal/base_structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,10 +450,7 @@ func (ms *messageStruct) generateStruct(sb *strings.Builder) {
}
sb.WriteString(newLine)
sb.WriteString(os.Expand(messageCopyToFooterTemplate, func(name string) string {
switch name {
default:
panic(name)
}
panic(name)
}))
}

Expand Down Expand Up @@ -500,10 +497,7 @@ func (ms *messageStruct) generateTestValueHelpers(sb *strings.Builder) {
}
sb.WriteString(newLine)
sb.WriteString(os.Expand(messageFillTestFooterTemplate, func(name string) string {
switch name {
default:
panic(name)
}
panic(name)
}))
}

Expand Down
8 changes: 5 additions & 3 deletions exporter/opencensusexporter/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ func (f *Factory) OCAgentOptions(logger *zap.Logger, ocac *Config) ([]ocagent.Ex
}
}
}
if ocac.TLSSetting.CAFile != "" {
switch {
case ocac.TLSSetting.CAFile != "":
creds, err := credentials.NewClientTLSFromFile(ocac.TLSSetting.CAFile, "")
if err != nil {
return nil, &ocExporterError{
Expand All @@ -96,16 +97,17 @@ func (f *Factory) OCAgentOptions(logger *zap.Logger, ocac *Config) ([]ocagent.Ex
}
}
opts = append(opts, ocagent.WithTLSCredentials(creds))
} else if !ocac.TLSSetting.Insecure {
case !ocac.TLSSetting.Insecure:
tlsConf, err := ocac.TLSSetting.LoadTLSConfig()
if err != nil {
return nil, fmt.Errorf("OpenCensus exporter failed to load TLS config: %w", err)
}
creds := credentials.NewTLS(tlsConf)
opts = append(opts, ocagent.WithTLSCredentials(creds))
} else {
default:
opts = append(opts, ocagent.WithInsecure())
}

if len(ocac.Headers) > 0 {
opts = append(opts, ocagent.WithHeaders(ocac.Headers))
}
Expand Down
3 changes: 1 addition & 2 deletions exporter/otlpexporter/otlp.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,7 @@ func shouldRetry(code codes.Code) bool {
func getThrottleDuration(status *status.Status) time.Duration {
// See if throttling information is available.
for _, detail := range status.Details() {
switch t := detail.(type) {
case *errdetails.RetryInfo:
if t, ok := detail.(*errdetails.RetryInfo); ok {
if t.RetryDelay.Seconds > 0 || t.RetryDelay.Nanos > 0 {
// We are throttled. Wait before retrying as requested by the server.
return time.Duration(t.RetryDelay.Seconds)*time.Second + time.Duration(t.RetryDelay.Nanos)*time.Nanosecond
Expand Down
4 changes: 1 addition & 3 deletions internal/processor/attraction/attraction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -762,9 +762,7 @@ func TestValidConfiguration(t *testing.T) {
require.NoError(t, err)

av := pdata.NewAttributeValueInt(123)
compiledRegex, err := regexp.Compile(`^\/api\/v1\/document\/(?P<documentId>.*)\/update$`)
require.NoError(t, err)

compiledRegex := regexp.MustCompile(`^\/api\/v1\/document\/(?P<documentId>.*)\/update$`)
assert.Equal(t, []attributeAction{
{Key: "one", Action: DELETE},
{Key: "two", Action: INSERT,
Expand Down
10 changes: 4 additions & 6 deletions processor/memorylimiter/memorylimiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,13 +177,11 @@ func (ml *memoryLimiter) readMemStats(ms *runtime.MemStats) {
// a misconfiguration is possible check for that here.
if ms.Alloc >= ml.ballastSize {
ms.Alloc -= ml.ballastSize
} else {
} else if !ml.configMismatchedLogged {
// This indicates misconfiguration. Log it once.
if !ml.configMismatchedLogged {
ml.configMismatchedLogged = true
ml.logger.Warn(typeStr + " is likely incorrectly configured. " + ballastSizeMibKey +
" must be set equal to --mem-ballast-size-mib command line option.")
}
ml.configMismatchedLogged = true
ml.logger.Warn(typeStr + " is likely incorrectly configured. " + ballastSizeMibKey +
" must be set equal to --mem-ballast-size-mib command line option.")
}
}

Expand Down
19 changes: 9 additions & 10 deletions processor/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,17 +135,16 @@ func MetricViews(level telemetry.Level) []*view.View {

// ServiceNameForNode gets the service name for a specified node.
func ServiceNameForNode(node *commonpb.Node) string {
var serviceName string
if node == nil {
serviceName = "<nil-batch-node>"
} else if node.ServiceInfo == nil {
serviceName = "<nil-service-info>"
} else if node.ServiceInfo.Name == "" {
serviceName = "<empty-service-info-name>"
} else {
serviceName = node.ServiceInfo.Name
switch {
case node == nil:
return "<nil-batch-node>"
case node.ServiceInfo == nil:
return "<nil-service-info>"
case node.ServiceInfo.Name == "":
return "<empty-service-info-name>"
default:
return node.ServiceInfo.Name
}
return serviceName
}

// ServiceNameForResource gets the service name for a specified Resource.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ func hash(key []byte, seed uint32) (hash uint32) {
remainingBytes += uint32(key[iByte])
remainingBytes *= c1
remainingBytes = (remainingBytes << r1) | (remainingBytes >> (32 - r1))
remainingBytes = remainingBytes * c2
remainingBytes *= c2
hash ^= remainingBytes
}

Expand Down
7 changes: 4 additions & 3 deletions receiver/fluentforwardreceiver/conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,19 +353,20 @@ func (pfe *PackedForwardEventLogRecords) DecodeMsg(dc *msgp.Reader) error {
// determine if it is gzipped by peeking and just ignoring options, but
// this seems simpler for now.
var entriesRaw []byte
if entriesType == msgp.StrType {
switch entriesType {
case msgp.StrType:
var entriesStr string
entriesStr, err = dc.ReadString()
if err != nil {
return msgp.WrapError(err, "EntriesRaw")
}
entriesRaw = []byte(entriesStr)
} else if entriesType == msgp.BinType {
case msgp.BinType:
entriesRaw, err = dc.ReadBytes(nil)
if err != nil {
return msgp.WrapError(err, "EntriesRaw")
}
} else {
default:
return msgp.WrapError(fmt.Errorf("invalid type %d", entriesType), "EntriesRaw")
}

Expand Down
2 changes: 1 addition & 1 deletion receiver/prometheusreceiver/internal/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func extractLogData(keyvals []interface{}) *logData {
msg := ""

other := make([]interface{}, 0, len(keyvals))
for i := 0; i < len(keyvals); i = i + 2 {
for i := 0; i < len(keyvals); i += 2 {
key := keyvals[i]
val := keyvals[i+1]

Expand Down
7 changes: 4 additions & 3 deletions receiver/prometheusreceiver/internal/metricfamily.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,16 +155,17 @@ func (mf *metricFamily) Add(metricName string, ls labels.Labels, t int64, v floa
case metricspb.MetricDescriptor_CUMULATIVE_DISTRIBUTION:
fallthrough
case metricspb.MetricDescriptor_SUMMARY:
if strings.HasSuffix(metricName, metricsSuffixSum) {
switch {
case strings.HasSuffix(metricName, metricsSuffixSum):
// always use the timestamp from sum (count is ok too), because the startTs from quantiles won't be reliable
// in cases like remote server restart
mg.ts = t
mg.sum = v
mg.hasSum = true
} else if strings.HasSuffix(metricName, metricsSuffixCount) {
case strings.HasSuffix(metricName, metricsSuffixCount):
mg.count = v
mg.hasCount = true
} else {
default:
boundary, err := getBoundary(mf.mtype, ls)
if err != nil {
mf.droppedTimeseries++
Expand Down
16 changes: 9 additions & 7 deletions receiver/prometheusreceiver/internal/metricsbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,12 @@ func newMetricBuilder(mc MetadataCache, useStartTimeMetric bool, logger *zap.Log
// AddDataPoint is for feeding prometheus data complexValue in its processing order
func (b *metricBuilder) AddDataPoint(ls labels.Labels, t int64, v float64) error {
metricName := ls.Get(model.MetricNameLabel)
if metricName == "" {
switch {
case metricName == "":
b.numTimeseries++
b.droppedTimeseries++
return errMetricNameNotFound
} else if isInternalMetric(metricName) {
case isInternalMetric(metricName):
b.hasInternalMetric = true
lm := ls.Map()
delete(lm, model.MetricNameLabel)
Expand All @@ -103,7 +104,7 @@ func (b *metricBuilder) AddDataPoint(ls labels.Labels, t int64, v float64) error
b.scrapeLatencyMs = v * 1000
}
return nil
} else if b.useStartTimeMetric && metricName == startTimeMetricName {
case b.useStartTimeMetric && metricName == startTimeMetricName:
b.startTime = v
}

Expand Down Expand Up @@ -192,12 +193,13 @@ func normalizeMetricName(name string) string {

func getBoundary(metricType metricspb.MetricDescriptor_Type, labels labels.Labels) (float64, error) {
labelName := ""
if metricType == metricspb.MetricDescriptor_CUMULATIVE_DISTRIBUTION ||
metricType == metricspb.MetricDescriptor_GAUGE_DISTRIBUTION {
switch metricType {
case metricspb.MetricDescriptor_CUMULATIVE_DISTRIBUTION,
metricspb.MetricDescriptor_GAUGE_DISTRIBUTION:
labelName = model.BucketLabel
} else if metricType == metricspb.MetricDescriptor_SUMMARY {
case metricspb.MetricDescriptor_SUMMARY:
labelName = model.QuantileLabel
} else {
default:
return 0, errNoBoundaryLabel
}

Expand Down
2 changes: 1 addition & 1 deletion testbed/testbed/mock_backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func WaitFor(t *testing.T, cond func() bool, errMsg ...interface{}) bool {

// Increase waiting interval exponentially up to 500 ms.
if waitInterval < time.Millisecond*500 {
waitInterval = waitInterval * 2
waitInterval *= 2
}

if cond() {
Expand Down
6 changes: 3 additions & 3 deletions testbed/testbed/results.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (r *PerformanceResults) Add(testName string, result interface{}) {
testResult.errorCause,
),
)
r.totalDuration = r.totalDuration + testResult.duration
r.totalDuration += testResult.duration
}

// CorrectnessResults implements the TestResultsSummary interface with fields suitable for reporting data translation
Expand Down Expand Up @@ -183,8 +183,8 @@ func (r *CorrectnessResults) Add(testName string, result interface{}) {
),
)
r.perTestResults = append(r.perTestResults, testResult)
r.totalAssertionFailures = r.totalAssertionFailures + testResult.assertionFailureCount
r.totalDuration = r.totalDuration + testResult.duration
r.totalAssertionFailures += testResult.assertionFailureCount
r.totalDuration += testResult.duration
}

func (r *CorrectnessResults) Save() {
Expand Down
2 changes: 1 addition & 1 deletion testbed/testbed/test_case.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ func (tc *TestCase) WaitForN(cond func() bool, duration time.Duration, errMsg ..

// Increase waiting interval exponentially up to 500 ms.
if waitInterval < time.Millisecond*500 {
waitInterval = waitInterval * 2
waitInterval *= 2
}

if time.Since(startTime) > duration {
Expand Down
2 changes: 1 addition & 1 deletion testutil/testutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ func WaitFor(t *testing.T, cond func() bool, errMsg ...interface{}) bool {

// Increase waiting interval exponentially up to 500 ms.
if waitInterval < time.Millisecond*500 {
waitInterval = waitInterval * 2
waitInterval *= 2
}

if cond() {
Expand Down