diff --git a/.golangci.yml b/.golangci.yml index 80ce04356957..8692ebe9e1ea 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -87,6 +87,9 @@ linters-settings: gofmt: # simplify code: gofmt with `-s` option, true by default simplify: true + rewrite-rules: + - pattern: interface{} + replacement: any goimports: # put imports beginning with prefix after 3rd-party packages; diff --git a/cmd/configschema/configs.go b/cmd/configschema/configs.go index ab44f581898e..62bd9f00a87a 100644 --- a/cmd/configschema/configs.go +++ b/cmd/configschema/configs.go @@ -26,7 +26,7 @@ type CfgInfo struct { // the component type, e.g. "otlpreceiver.Config" Type component.Type // an instance of the component's configuration struct - CfgInstance interface{} + CfgInstance any } // GetAllCfgInfos accepts a Factories struct, then creates and returns a CfgInfo diff --git a/cmd/configschema/fields.go b/cmd/configschema/fields.go index 92541369f2d8..a2fed157f0cd 100644 --- a/cmd/configschema/fields.go +++ b/cmd/configschema/fields.go @@ -14,12 +14,12 @@ import ( // Field holds attributes and subfields of a config struct. type Field struct { - Name string `yaml:",omitempty"` - Type string `yaml:",omitempty"` - Kind string `yaml:",omitempty"` - Default interface{} `yaml:",omitempty"` - Doc string `yaml:",omitempty"` - Fields []*Field `yaml:",omitempty"` + Name string `yaml:",omitempty"` + Type string `yaml:",omitempty"` + Kind string `yaml:",omitempty"` + Default any `yaml:",omitempty"` + Doc string `yaml:",omitempty"` + Fields []*Field `yaml:",omitempty"` } // ReadFields accepts both a config struct's Value, as well as a DirResolver, diff --git a/cmd/configschema/fields_test.go b/cmd/configschema/fields_test.go index 2644da09fdad..0964edb759d2 100644 --- a/cmd/configschema/fields_test.go +++ b/cmd/configschema/fields_test.go @@ -15,7 +15,7 @@ import ( ) func TestReadFieldsWithDefaults(t *testing.T) { - defaults := map[string]interface{}{ + defaults := map[string]any{ "one": "1", "two": int64(2), "three": uint64(3), @@ -43,7 +43,7 @@ func TestReadFieldsWithDefaults(t *testing.T) { } func TestReadFieldsWithoutDefaults(t *testing.T) { - testReadFields(t, testStruct{}, map[string]interface{}{ + testReadFields(t, testStruct{}, map[string]any{ "one": "", "three": uint64(0), "four": false, @@ -53,7 +53,7 @@ func TestReadFieldsWithoutDefaults(t *testing.T) { }) } -func testReadFields(t *testing.T, s testStruct, defaults map[string]interface{}) { +func testReadFields(t *testing.T, s testStruct, defaults map[string]any) { root, _ := ReadFields( reflect.ValueOf(s), testDR(), diff --git a/cmd/configschema/resolver_test.go b/cmd/configschema/resolver_test.go index 073b995155d7..f74fe4759741 100644 --- a/cmd/configschema/resolver_test.go +++ b/cmd/configschema/resolver_test.go @@ -67,7 +67,7 @@ func TestTypetoProjectPath_External(t *testing.T) { assert.Equal(t, "", dir) } -func testTypeToPackagePath(t *testing.T, v interface{}) string { +func testTypeToPackagePath(t *testing.T, v any) string { packageDir, err := testDR().TypeToPackagePath(reflect.ValueOf(v).Type()) require.NoError(t, err) return packageDir diff --git a/cmd/mdatagen/main.go b/cmd/mdatagen/main.go index 5bf96cd074f1..2d35ff129362 100644 --- a/cmd/mdatagen/main.go +++ b/cmd/mdatagen/main.go @@ -125,7 +125,7 @@ func templatize(tmplFile string, md metadata) *template.Template { template. New(filepath.Base(tmplFile)). Option("missingkey=error"). - Funcs(map[string]interface{}{ + Funcs(map[string]any{ "publicVar": func(s string) (string, error) { return formatIdentifier(s, true) }, diff --git a/confmap/provider/s3provider/provider.go b/confmap/provider/s3provider/provider.go index 17f1bc539114..b11f0cfc1b5a 100644 --- a/confmap/provider/s3provider/provider.go +++ b/confmap/provider/s3provider/provider.go @@ -82,7 +82,7 @@ func (fmp *provider) Retrieve(ctx context.Context, uri string, _ confmap.Watcher // read config from response body dec := yaml.NewDecoder(resp.Body) defer resp.Body.Close() - var conf map[string]interface{} + var conf map[string]any err = dec.Decode(&conf) if err != nil { return nil, err diff --git a/connector/exceptionsconnector/connector_metrics_test.go b/connector/exceptionsconnector/connector_metrics_test.go index 2d9f98872d6f..56907e763b6e 100644 --- a/connector/exceptionsconnector/connector_metrics_test.go +++ b/connector/exceptionsconnector/connector_metrics_test.go @@ -246,8 +246,8 @@ func TestBuildKeyWithDimensions(t *testing.T) { for _, tc := range []struct { name string optionalDims []dimension - resourceAttrMap map[string]interface{} - spanAttrMap map[string]interface{} + resourceAttrMap map[string]any + spanAttrMap map[string]any wantKey string }{ { @@ -273,7 +273,7 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - spanAttrMap: map[string]interface{}{ + spanAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u000099", @@ -283,7 +283,7 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - resourceAttrMap: map[string]interface{}{ + resourceAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u000099", @@ -293,10 +293,10 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - spanAttrMap: map[string]interface{}{ + spanAttrMap: map[string]any{ "foo": 100, }, - resourceAttrMap: map[string]interface{}{ + resourceAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u0000100", diff --git a/connector/routingconnector/internal/common/functions.go b/connector/routingconnector/internal/common/functions.go index 6753ec8a56f8..338172197934 100644 --- a/connector/routingconnector/internal/common/functions.go +++ b/connector/routingconnector/internal/common/functions.go @@ -11,7 +11,7 @@ import ( ) func createRouteFunction[K any](_ ottl.FunctionContext, _ ottl.Arguments) (ottl.ExprFunc[K], error) { - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { return true, nil }, nil } diff --git a/connector/spanmetricsconnector/connector_test.go b/connector/spanmetricsconnector/connector_test.go index 7d75015a07ff..c10078313795 100644 --- a/connector/spanmetricsconnector/connector_test.go +++ b/connector/spanmetricsconnector/connector_test.go @@ -493,8 +493,8 @@ func TestBuildKeyWithDimensions(t *testing.T) { for _, tc := range []struct { name string optionalDims []dimension - resourceAttrMap map[string]interface{} - spanAttrMap map[string]interface{} + resourceAttrMap map[string]any + spanAttrMap map[string]any wantKey string }{ { @@ -520,7 +520,7 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - spanAttrMap: map[string]interface{}{ + spanAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u000099", @@ -530,7 +530,7 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - resourceAttrMap: map[string]interface{}{ + resourceAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u000099", @@ -540,10 +540,10 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - spanAttrMap: map[string]interface{}{ + spanAttrMap: map[string]any{ "foo": 100, }, - resourceAttrMap: map[string]interface{}{ + resourceAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u0000100", diff --git a/exporter/alibabacloudlogserviceexporter/logsdata_to_logservice.go b/exporter/alibabacloudlogserviceexporter/logsdata_to_logservice.go index cd7f48ad9034..29b11ca37457 100644 --- a/exporter/alibabacloudlogserviceexporter/logsdata_to_logservice.go +++ b/exporter/alibabacloudlogserviceexporter/logsdata_to_logservice.go @@ -83,7 +83,7 @@ func resourceToLogContents(resource pcommon.Resource) []*sls.LogContent { } } - fields := map[string]interface{}{} + fields := map[string]any{} attrs.Range(func(k string, v pcommon.Value) bool { if k == conventions.AttributeServiceName || k == conventions.AttributeHostName { return true @@ -144,7 +144,7 @@ func mapLogRecordToLogService(lr plog.LogRecord, Value: proto.String(lr.SeverityText()), }) - fields := map[string]interface{}{} + fields := map[string]any{} lr.Attributes().Range(func(k string, v pcommon.Value) bool { fields[k] = v.AsString() return true diff --git a/exporter/alibabacloudlogserviceexporter/tracedata_to_logservice.go b/exporter/alibabacloudlogserviceexporter/tracedata_to_logservice.go index 16cc8881f19a..df843aa099b0 100644 --- a/exporter/alibabacloudlogserviceexporter/tracedata_to_logservice.go +++ b/exporter/alibabacloudlogserviceexporter/tracedata_to_logservice.go @@ -177,10 +177,10 @@ func statusCodeToShortString(code ptrace.StatusCode) string { } func eventsToString(events ptrace.SpanEventSlice) string { - eventArray := make([]map[string]interface{}, 0, events.Len()) + eventArray := make([]map[string]any, 0, events.Len()) for i := 0; i < events.Len(); i++ { spanEvent := events.At(i) - event := map[string]interface{}{} + event := map[string]any{} event[nameField] = spanEvent.Name() event[timeField] = spanEvent.Timestamp() event[attributeField] = spanEvent.Attributes().AsRaw() @@ -192,10 +192,10 @@ func eventsToString(events ptrace.SpanEventSlice) string { } func spanLinksToString(spanLinkSlice ptrace.SpanLinkSlice) string { - linkArray := make([]map[string]interface{}, 0, spanLinkSlice.Len()) + linkArray := make([]map[string]any, 0, spanLinkSlice.Len()) for i := 0; i < spanLinkSlice.Len(); i++ { spanLink := spanLinkSlice.At(i) - link := map[string]interface{}{} + link := map[string]any{} link[spanIDField] = traceutil.SpanIDToHexOrEmptyString(spanLink.SpanID()) link[traceIDField] = traceutil.TraceIDToHexOrEmptyString(spanLink.TraceID()) link[attributeField] = spanLink.Attributes().AsRaw() diff --git a/exporter/alibabacloudlogserviceexporter/tracedata_to_logservice_test.go b/exporter/alibabacloudlogserviceexporter/tracedata_to_logservice_test.go index b4e6fb0c6a30..88d005199739 100644 --- a/exporter/alibabacloudlogserviceexporter/tracedata_to_logservice_test.go +++ b/exporter/alibabacloudlogserviceexporter/tracedata_to_logservice_test.go @@ -59,7 +59,7 @@ func TestTraceDataToLogService(t *testing.T) { } } -func loadFromJSON(file string, obj interface{}) error { +func loadFromJSON(file string, obj any) error { blob, err := os.ReadFile(file) if err == nil { err = json.Unmarshal(blob, obj) @@ -97,7 +97,7 @@ func fillResource(resource pcommon.Resource) { } func fillHTTPClientSpan(span ptrace.Span) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/users/junit" attributes[conventions.AttributeHTTPStatusCode] = 200 @@ -129,7 +129,7 @@ func fillHTTPClientSpan(span ptrace.Span) { } func fillHTTPServerSpan(span ptrace.Span) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/users/junit" attributes[conventions.AttributeHTTPClientIP] = "192.168.15.32" @@ -151,7 +151,7 @@ func fillHTTPServerSpan(span ptrace.Span) { status.SetMessage("something error") } -func constructSpanAttributes(attributes map[string]interface{}) pcommon.Map { +func constructSpanAttributes(attributes map[string]any) pcommon.Map { attrs := pcommon.NewMap() for key, value := range attributes { if cast, ok := value.(int); ok { diff --git a/exporter/awscloudwatchlogsexporter/exporter.go b/exporter/awscloudwatchlogsexporter/exporter.go index 95040ecab3a4..bd9467b7e981 100644 --- a/exporter/awscloudwatchlogsexporter/exporter.go +++ b/exporter/awscloudwatchlogsexporter/exporter.go @@ -159,18 +159,18 @@ func pushLogsToCWLogs(logger *zap.Logger, ld plog.Logs, config *Config, pusher c } type cwLogBody struct { - Body interface{} `json:"body,omitempty"` - SeverityNumber int32 `json:"severity_number,omitempty"` - SeverityText string `json:"severity_text,omitempty"` - DroppedAttributesCount uint32 `json:"dropped_attributes_count,omitempty"` - Flags uint32 `json:"flags,omitempty"` - TraceID string `json:"trace_id,omitempty"` - SpanID string `json:"span_id,omitempty"` - Attributes map[string]interface{} `json:"attributes,omitempty"` - Resource map[string]interface{} `json:"resource,omitempty"` + Body any `json:"body,omitempty"` + SeverityNumber int32 `json:"severity_number,omitempty"` + SeverityText string `json:"severity_text,omitempty"` + DroppedAttributesCount uint32 `json:"dropped_attributes_count,omitempty"` + Flags uint32 `json:"flags,omitempty"` + TraceID string `json:"trace_id,omitempty"` + SpanID string `json:"span_id,omitempty"` + Attributes map[string]any `json:"attributes,omitempty"` + Resource map[string]any `json:"resource,omitempty"` } -func logToCWLog(resourceAttrs map[string]interface{}, log plog.LogRecord, config *Config) (*cwlogs.Event, error) { +func logToCWLog(resourceAttrs map[string]any, log plog.LogRecord, config *Config) (*cwlogs.Event, error) { // TODO(jbd): Benchmark and improve the allocations. // Evaluate go.elastic.co/fastjson as a replacement for encoding/json. logGroupName := config.LogGroupName @@ -232,11 +232,11 @@ func logToCWLog(resourceAttrs map[string]interface{}, log plog.LogRecord, config }, nil } -func attrsValue(attrs pcommon.Map) map[string]interface{} { +func attrsValue(attrs pcommon.Map) map[string]any { if attrs.Len() == 0 { return nil } - out := make(map[string]interface{}, attrs.Len()) + out := make(map[string]any, attrs.Len()) attrs.Range(func(k string, v pcommon.Value) bool { out[k] = v.AsRaw() return true diff --git a/exporter/awsemfexporter/config.go b/exporter/awsemfexporter/config.go index cbb38e84d2e3..9a93c558bf21 100644 --- a/exporter/awsemfexporter/config.go +++ b/exporter/awsemfexporter/config.go @@ -137,8 +137,8 @@ func (config *Config) Validate() error { } -func newEMFSupportedUnits() map[string]interface{} { - unitIndexer := map[string]interface{}{} +func newEMFSupportedUnits() map[string]any { + unitIndexer := map[string]any{} for _, unit := range []string{"Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent", "Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", diff --git a/exporter/awsemfexporter/datapoint.go b/exporter/awsemfexporter/datapoint.go index 0ac878aaa5e5..54759b047441 100644 --- a/exporter/awsemfexporter/datapoint.go +++ b/exporter/awsemfexporter/datapoint.go @@ -27,7 +27,7 @@ type emfCalculators struct { summary aws.MetricCalculator } -func calculateSummaryDelta(prev *aws.MetricValue, val interface{}, _ time.Time) (interface{}, bool) { +func calculateSummaryDelta(prev *aws.MetricValue, val any, _ time.Time) (any, bool) { metricEntry := val.(summaryMetricEntry) summaryDelta := metricEntry.sum countDelta := metricEntry.count @@ -44,7 +44,7 @@ func calculateSummaryDelta(prev *aws.MetricValue, val interface{}, _ time.Time) // dataPoint represents a processed metric data point type dataPoint struct { name string - value interface{} + value any labels map[string]string timestampMs int64 } @@ -126,7 +126,7 @@ func (dps numberDataPointSlice) CalculateDeltaDatapoints(i int, instrumentationS retained := true if dps.adjustToDelta { - var deltaVal interface{} + var deltaVal any mKey := aws.NewKey(dps.deltaMetricMetadata, labels) deltaVal, retained = calculators.delta.Calculate(mKey, metricVal, metric.Timestamp().AsTime()) @@ -299,7 +299,7 @@ func (dps summaryDataPointSlice) CalculateDeltaDatapoints(i int, instrumentation datapoints := []dataPoint{} if dps.adjustToDelta { - var delta interface{} + var delta any mKey := aws.NewKey(dps.deltaMetricMetadata, labels) delta, retained = calculators.summary.Calculate(mKey, summaryMetricEntry{sum, count}, metric.Timestamp().AsTime()) diff --git a/exporter/awsemfexporter/datapoint_test.go b/exporter/awsemfexporter/datapoint_test.go index 004bcd481cb8..638a98737f2c 100644 --- a/exporter/awsemfexporter/datapoint_test.go +++ b/exporter/awsemfexporter/datapoint_test.go @@ -276,7 +276,7 @@ func TestIsStaleOrNaN_NumberDataPointSlice(t *testing.T) { testCases := []struct { name string metricName string - metricValue interface{} + metricValue any expectedAssert assert.BoolAssertionFunc setFlagsFunc func(point pmetric.NumberDataPoint) pmetric.NumberDataPoint }{ @@ -338,7 +338,7 @@ func TestCalculateDeltaDatapoints_NumberDataPointSlice(t *testing.T) { name string adjustToDelta bool metricName string - metricValue interface{} + metricValue any expectedDatapoint dataPoint expectedRetained bool }{ @@ -784,13 +784,13 @@ func TestCalculateDeltaDatapoints_SummaryDataPointSlice(t *testing.T) { testCases := []struct { name string - summaryMetricValue map[string]interface{} + summaryMetricValue map[string]any expectedDatapoint []dataPoint expectedRetained bool }{ { name: fmt.Sprintf("Detailed summary with 1st delta sum count calculation retainInitialValueOfDeltaMetric=%t", retainInitialValueOfDeltaMetric), - summaryMetricValue: map[string]interface{}{"sum": float64(17.3), "count": uint64(17), "firstQuantile": float64(1), "secondQuantile": float64(5)}, + summaryMetricValue: map[string]any{"sum": float64(17.3), "count": uint64(17), "firstQuantile": float64(1), "secondQuantile": float64(5)}, expectedDatapoint: []dataPoint{ {name: fmt.Sprint("foo", summarySumSuffix), value: float64(17.3), labels: map[string]string{"label1": "value1"}}, {name: fmt.Sprint("foo", summaryCountSuffix), value: uint64(17), labels: map[string]string{"label1": "value1"}}, @@ -801,7 +801,7 @@ func TestCalculateDeltaDatapoints_SummaryDataPointSlice(t *testing.T) { }, { name: "Detailed summary with 2nd delta sum count calculation", - summaryMetricValue: map[string]interface{}{"sum": float64(100), "count": uint64(25), "firstQuantile": float64(1), "secondQuantile": float64(5)}, + summaryMetricValue: map[string]any{"sum": float64(100), "count": uint64(25), "firstQuantile": float64(1), "secondQuantile": float64(5)}, expectedDatapoint: []dataPoint{ {name: fmt.Sprint("foo", summarySumSuffix), value: float64(82.7), labels: map[string]string{"label1": "value1"}}, {name: fmt.Sprint("foo", summaryCountSuffix), value: uint64(8), labels: map[string]string{"label1": "value1"}}, @@ -812,7 +812,7 @@ func TestCalculateDeltaDatapoints_SummaryDataPointSlice(t *testing.T) { }, { name: "Detailed summary with 3rd delta sum count calculation", - summaryMetricValue: map[string]interface{}{"sum": float64(120), "count": uint64(26), "firstQuantile": float64(1), "secondQuantile": float64(5)}, + summaryMetricValue: map[string]any{"sum": float64(120), "count": uint64(26), "firstQuantile": float64(1), "secondQuantile": float64(5)}, expectedDatapoint: []dataPoint{ {name: fmt.Sprint("foo", summarySumSuffix), value: float64(20), labels: map[string]string{"label1": "value1"}}, {name: fmt.Sprint("foo", summaryCountSuffix), value: uint64(1), labels: map[string]string{"label1": "value1"}}, @@ -864,23 +864,23 @@ func TestCalculateDeltaDatapoints_SummaryDataPointSlice(t *testing.T) { func TestIsStaleOrNaN_SummaryDataPointSlice(t *testing.T) { testCases := []struct { name string - summaryMetricValue map[string]interface{} + summaryMetricValue map[string]any expectedBoolAssert assert.BoolAssertionFunc setFlagsFunc func(point pmetric.SummaryDataPoint) pmetric.SummaryDataPoint }{ { name: "summary with no nan values", - summaryMetricValue: map[string]interface{}{"sum": float64(17.3), "count": uint64(17), "firstQuantile": float64(1), "secondQuantile": float64(5)}, + summaryMetricValue: map[string]any{"sum": float64(17.3), "count": uint64(17), "firstQuantile": float64(1), "secondQuantile": float64(5)}, expectedBoolAssert: assert.False, }, { name: "Summary with nan values", - summaryMetricValue: map[string]interface{}{"sum": math.NaN(), "count": uint64(25), "firstQuantile": math.NaN(), "secondQuantile": math.NaN()}, + summaryMetricValue: map[string]any{"sum": math.NaN(), "count": uint64(25), "firstQuantile": math.NaN(), "secondQuantile": math.NaN()}, expectedBoolAssert: assert.True, }, { name: "Summary with set flag func", - summaryMetricValue: map[string]interface{}{"sum": math.NaN(), "count": uint64(25), "firstQuantile": math.NaN(), "secondQuantile": math.NaN()}, + summaryMetricValue: map[string]any{"sum": math.NaN(), "count": uint64(25), "firstQuantile": math.NaN(), "secondQuantile": math.NaN()}, expectedBoolAssert: assert.True, setFlagsFunc: func(point pmetric.SummaryDataPoint) pmetric.SummaryDataPoint { point.SetFlags(pmetric.DefaultDataPointFlags.WithNoRecordedValue(true)) @@ -924,7 +924,7 @@ func TestCreateLabels(t *testing.T) { "c": "C", } labelsMap := pcommon.NewMap() - assert.NoError(t, labelsMap.FromRaw(map[string]interface{}{ + assert.NoError(t, labelsMap.FromRaw(map[string]any{ "a": "A", "b": "B", "c": "C", @@ -950,49 +950,49 @@ func TestGetDataPoints(t *testing.T) { isPrometheusMetrics bool metric pmetric.Metrics expectedDatapointSlice dataPoints - expectedAttributes map[string]interface{} + expectedAttributes map[string]any }{ { name: "Int gauge", isPrometheusMetrics: false, metric: generateTestGaugeMetric("foo", intValueType), expectedDatapointSlice: numberDataPointSlice{normalDeltraMetricMetadata, pmetric.NumberDataPointSlice{}}, - expectedAttributes: map[string]interface{}{"label1": "value1"}, + expectedAttributes: map[string]any{"label1": "value1"}, }, { name: "Double sum", isPrometheusMetrics: false, metric: generateTestSumMetric("foo", doubleValueType), expectedDatapointSlice: numberDataPointSlice{cumulativeDeltaMetricMetadata, pmetric.NumberDataPointSlice{}}, - expectedAttributes: map[string]interface{}{"label1": "value1"}, + expectedAttributes: map[string]any{"label1": "value1"}, }, { name: "Histogram", isPrometheusMetrics: false, metric: generateTestHistogramMetric("foo"), expectedDatapointSlice: histogramDataPointSlice{cumulativeDeltaMetricMetadata, pmetric.HistogramDataPointSlice{}}, - expectedAttributes: map[string]interface{}{"label1": "value1"}, + expectedAttributes: map[string]any{"label1": "value1"}, }, { name: "ExponentialHistogram", isPrometheusMetrics: false, metric: generateTestExponentialHistogramMetric("foo"), expectedDatapointSlice: exponentialHistogramDataPointSlice{cumulativeDeltaMetricMetadata, pmetric.ExponentialHistogramDataPointSlice{}}, - expectedAttributes: map[string]interface{}{"label1": "value1"}, + expectedAttributes: map[string]any{"label1": "value1"}, }, { name: "Summary from SDK", isPrometheusMetrics: false, metric: generateTestSummaryMetric("foo"), expectedDatapointSlice: summaryDataPointSlice{normalDeltraMetricMetadata, pmetric.SummaryDataPointSlice{}}, - expectedAttributes: map[string]interface{}{"label1": "value1"}, + expectedAttributes: map[string]any{"label1": "value1"}, }, { name: "Summary from Prometheus", isPrometheusMetrics: true, metric: generateTestSummaryMetric("foo"), expectedDatapointSlice: summaryDataPointSlice{cumulativeDeltaMetricMetadata, pmetric.SummaryDataPointSlice{}}, - expectedAttributes: map[string]interface{}{"label1": "value1"}, + expectedAttributes: map[string]any{"label1": "value1"}, }, } diff --git a/exporter/awsemfexporter/emf_exporter.go b/exporter/awsemfexporter/emf_exporter.go index b80dcf12c0e0..193a0068db1a 100644 --- a/exporter/awsemfexporter/emf_exporter.go +++ b/exporter/awsemfexporter/emf_exporter.go @@ -93,7 +93,7 @@ func (emf *emfExporter) pushMetricsData(_ context.Context, md pmetric.Metrics) e } emf.config.logger.Info("Start processing resource metrics", zap.Any("labels", labels)) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) defaultLogStream := fmt.Sprintf("otel-stream-%s", emf.collectorID) outputDestination := emf.config.OutputDestination diff --git a/exporter/awsemfexporter/emf_exporter_test.go b/exporter/awsemfexporter/emf_exporter_test.go index c9ae63c56697..3cf6d13ca6e5 100644 --- a/exporter/awsemfexporter/emf_exporter_test.go +++ b/exporter/awsemfexporter/emf_exporter_test.go @@ -168,7 +168,7 @@ func TestConsumeMetricsWithLogGroupStreamValidPlaceholder(t *testing.T) { md := generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]interface{}{ + resourceAttributeMap: map[string]any{ "aws.ecs.cluster.name": "test-cluster-name", "aws.ecs.task.id": "test-task-id", }, @@ -199,7 +199,7 @@ func TestConsumeMetricsWithOnlyLogStreamPlaceholder(t *testing.T) { md := generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]interface{}{ + resourceAttributeMap: map[string]any{ "aws.ecs.cluster.name": "test-cluster-name", "aws.ecs.task.id": "test-task-id", }, @@ -230,7 +230,7 @@ func TestConsumeMetricsWithWrongPlaceholder(t *testing.T) { md := generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]interface{}{ + resourceAttributeMap: map[string]any{ "aws.ecs.cluster.name": "test-cluster-name", "aws.ecs.task.id": "test-task-id", }, diff --git a/exporter/awsemfexporter/grouped_metric.go b/exporter/awsemfexporter/grouped_metric.go index 9c919c6f23c5..c62c723a4a5e 100644 --- a/exporter/awsemfexporter/grouped_metric.go +++ b/exporter/awsemfexporter/grouped_metric.go @@ -22,12 +22,12 @@ type groupedMetric struct { // metricInfo defines value and unit for OT Metrics type metricInfo struct { - value interface{} + value any unit string } // addToGroupedMetric processes OT metrics and adds them into GroupedMetric buckets -func addToGroupedMetric(pmd pmetric.Metric, groupedMetrics map[interface{}]*groupedMetric, metadata cWMetricMetadata, patternReplaceSucceeded bool, logger *zap.Logger, descriptor map[string]MetricDescriptor, config *Config, calculators *emfCalculators) error { +func addToGroupedMetric(pmd pmetric.Metric, groupedMetrics map[any]*groupedMetric, metadata cWMetricMetadata, patternReplaceSucceeded bool, logger *zap.Logger, descriptor map[string]MetricDescriptor, config *Config, calculators *emfCalculators) error { dps := getDataPoints(pmd, metadata, logger) if dps == nil || dps.Len() == 0 { diff --git a/exporter/awsemfexporter/grouped_metric_test.go b/exporter/awsemfexporter/grouped_metric_test.go index 275506d4eeea..a21d5f523771 100644 --- a/exporter/awsemfexporter/grouped_metric_test.go +++ b/exporter/awsemfexporter/grouped_metric_test.go @@ -99,7 +99,7 @@ func TestAddToGroupedMetric(t *testing.T) { emfCalcs := setupEmfCalculators() defer require.NoError(t, shutdownEmfCalculators(emfCalcs)) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) rms := tc.metric.ResourceMetrics() ilms := rms.At(0).ScopeMetrics() metrics := ilms.At(0).Metrics() @@ -132,7 +132,7 @@ func TestAddToGroupedMetric(t *testing.T) { emfCalcs := setupEmfCalculators() defer require.NoError(t, shutdownEmfCalculators(emfCalcs)) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) generateMetrics := []pmetric.Metrics{ generateTestGaugeMetric("int-gauge", intValueType), generateTestGaugeMetric("double-gauge", doubleValueType), @@ -196,7 +196,7 @@ func TestAddToGroupedMetric(t *testing.T) { emfCalcs := setupEmfCalculators() defer require.NoError(t, shutdownEmfCalculators(emfCalcs)) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) generateMetrics := []pmetric.Metrics{ generateTestGaugeMetric("int-gauge", intValueType), generateTestGaugeMetric("double-gauge", doubleValueType), @@ -263,7 +263,7 @@ func TestAddToGroupedMetric(t *testing.T) { t.Run("Add same metric but different log group", func(t *testing.T) { emfCalcs := setupEmfCalculators() defer require.NoError(t, shutdownEmfCalculators(emfCalcs)) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) otelMetrics := generateTestGaugeMetric("int-gauge", "int") ilms := otelMetrics.ResourceMetrics().At(0).ScopeMetrics() metric := ilms.At(0).Metrics().At(0) @@ -319,7 +319,7 @@ func TestAddToGroupedMetric(t *testing.T) { t.Run("Duplicate metric names", func(t *testing.T) { emfCalcs := setupEmfCalculators() defer require.NoError(t, shutdownEmfCalculators(emfCalcs)) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) generateMetrics := []pmetric.Metrics{ generateTestGaugeMetric("foo", "int"), generateTestGaugeMetric("foo", "double"), @@ -369,7 +369,7 @@ func TestAddToGroupedMetric(t *testing.T) { t.Run("Unhandled metric type", func(t *testing.T) { emfCalcs := setupEmfCalculators() defer require.NoError(t, shutdownEmfCalculators(emfCalcs)) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) md := pmetric.NewMetrics() rms := md.ResourceMetrics() metric := rms.AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty() @@ -415,10 +415,10 @@ func TestAddKubernetesWrapper(t *testing.T) { ContainerID: "Container mccontainter the third", } expectedCreatedObj := struct { - ContainerName string `json:"container_name"` - Docker interface{} `json:"docker"` - Host string `json:"host"` - PodID string `json:"pod_id"` + ContainerName string `json:"container_name"` + Docker any `json:"docker"` + Host string `json:"host"` + PodID string `json:"pod_id"` }{ ContainerName: "container mccontainer", Docker: dockerObj, @@ -459,7 +459,7 @@ func BenchmarkAddToGroupedMetric(b *testing.B) { b.ResetTimer() for n := 0; n < b.N; n++ { - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) for i := 0; i < numMetrics; i++ { metadata := generateTestMetricMetadata("namespace", int64(1596151098037), "log-group", "log-stream", "cloudwatch-otel", metrics.At(i).Type()) err := addToGroupedMetric(metrics.At(i), groupedMetrics, metadata, true, logger, nil, testCfg, emfCalcs) diff --git a/exporter/awsemfexporter/metric_translator.go b/exporter/awsemfexporter/metric_translator.go index 8ee0687585d1..fbd601a33725 100644 --- a/exporter/awsemfexporter/metric_translator.go +++ b/exporter/awsemfexporter/metric_translator.go @@ -42,7 +42,7 @@ var fieldPrometheusTypes = map[pmetric.MetricType]string{ type cWMetrics struct { measurements []cWMeasurement timestampMs int64 - fields map[string]interface{} + fields map[string]any } type cWMeasurement struct { @@ -112,7 +112,7 @@ func (mt metricTranslator) Shutdown() error { } // translateOTelToGroupedMetric converts OT metrics to Grouped Metric format. -func (mt metricTranslator) translateOTelToGroupedMetric(rm pmetric.ResourceMetrics, groupedMetrics map[interface{}]*groupedMetric, config *Config) error { +func (mt metricTranslator) translateOTelToGroupedMetric(rm pmetric.ResourceMetrics, groupedMetrics map[any]*groupedMetric, config *Config) error { timestamp := time.Now().UnixNano() / int64(time.Millisecond) var instrumentationScopeName string cWNamespace := getNamespace(rm, config.Namespace) @@ -163,7 +163,7 @@ func translateGroupedMetricToCWMetric(groupedMetric *groupedMetric, config *Conf if isPrometheusMetric { fieldsLength++ } - fields := make(map[string]interface{}, fieldsLength) + fields := make(map[string]any, fieldsLength) // Add labels to fields for k, v := range labels { @@ -363,7 +363,7 @@ func translateCWMetricToEMF(cWMetric *cWMetrics, config *Config) (*cwlogs.Event, } if val, ok := fieldMap[key].(string); ok { - var f interface{} + var f any err := json.Unmarshal([]byte(val), &f) if err != nil { config.logger.Debug( @@ -402,7 +402,7 @@ func translateCWMetricToEMF(cWMetric *cWMetrics, config *Config) (*cwlogs.Event, } */ fieldMap["Version"] = "1" - fieldMap["_aws"] = map[string]interface{}{ + fieldMap["_aws"] = map[string]any{ "CloudWatchMetrics": cWMetric.measurements, "Timestamp": cWMetric.timestampMs, } diff --git a/exporter/awsemfexporter/metric_translator_test.go b/exporter/awsemfexporter/metric_translator_test.go index 16fa3f7e1961..366112d5c338 100644 --- a/exporter/awsemfexporter/metric_translator_test.go +++ b/exporter/awsemfexporter/metric_translator_test.go @@ -348,7 +348,7 @@ func TestTranslateOtToGroupedMetric(t *testing.T) { for _, tc := range testCases { t.Run(tc.testName, func(t *testing.T) { - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) err := translator.translateOTelToGroupedMetric(tc.metric, groupedMetrics, config) assert.Nil(t, err) assert.NotNil(t, groupedMetrics) @@ -380,7 +380,7 @@ func TestTranslateOtToGroupedMetric(t *testing.T) { rm := pmetric.NewResourceMetrics() rm.Resource().Attributes().PutStr(conventions.AttributeServiceName, "myServiceName") rm.Resource().Attributes().PutStr(occonventions.AttributeExporterVersion, "SomeVersion") - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) err := translator.translateOTelToGroupedMetric(rm, groupedMetrics, config) assert.Nil(t, err) assert.Equal(t, 0, len(groupedMetrics)) @@ -439,7 +439,7 @@ func TestTranslateCWMetricToEMF(t *testing.T) { logger: zap.NewNop(), } - fields := map[string]interface{}{ + fields := map[string]any{ oTellibDimensionKey: "cloudwatch-otel", "spanName": "test", "spanCounter": 0, @@ -505,7 +505,7 @@ func TestTranslateGroupedMetricToCWMetric(t *testing.T) { }, }, timestampMs: timestamp, - fields: map[string]interface{}{ + fields: map[string]any{ "label1": "value1", "metric1": 1, }, @@ -550,7 +550,7 @@ func TestTranslateGroupedMetricToCWMetric(t *testing.T) { }, }, timestampMs: timestamp, - fields: map[string]interface{}{ + fields: map[string]any{ "label1": "value1", "metric1": 1, }, @@ -607,7 +607,7 @@ func TestTranslateGroupedMetricToCWMetric(t *testing.T) { }, }, timestampMs: timestamp, - fields: map[string]interface{}{ + fields: map[string]any{ "label1": "value1", "label2": "value2", "metric1": 1, @@ -684,7 +684,7 @@ func TestTranslateGroupedMetricToCWMetric(t *testing.T) { }, }, timestampMs: timestamp, - fields: map[string]interface{}{ + fields: map[string]any{ "label1": "value1", "label2": "value2", "metric1": 1, @@ -717,7 +717,7 @@ func TestTranslateGroupedMetricToCWMetric(t *testing.T) { }, }, timestampMs: timestamp, - fields: map[string]interface{}{ + fields: map[string]any{ "label1": "value1", }, }, @@ -758,7 +758,7 @@ func TestTranslateGroupedMetricToCWMetric(t *testing.T) { }, }, timestampMs: timestamp, - fields: map[string]interface{}{ + fields: map[string]any{ "label1": "value1", "metric1": 1, fieldPrometheusMetricType: "gauge", @@ -1982,7 +1982,7 @@ func BenchmarkTranslateOtToGroupedMetricWithInstrLibrary(b *testing.B) { b.ResetTimer() for n := 0; n < b.N; n++ { - groupedMetric := make(map[interface{}]*groupedMetric) + groupedMetric := make(map[any]*groupedMetric) err := translator.translateOTelToGroupedMetric(rm, groupedMetric, config) assert.Nil(b, err) } @@ -2005,7 +2005,7 @@ func BenchmarkTranslateOtToGroupedMetricWithoutConfigReplacePattern(b *testing.B b.ResetTimer() for n := 0; n < b.N; n++ { - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) err := translator.translateOTelToGroupedMetric(rm, groupedMetrics, config) assert.Nil(b, err) } @@ -2028,7 +2028,7 @@ func BenchmarkTranslateOtToGroupedMetricWithConfigReplaceWithResource(b *testing b.ResetTimer() for n := 0; n < b.N; n++ { - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) err := translator.translateOTelToGroupedMetric(rm, groupedMetrics, config) assert.Nil(b, err) } @@ -2051,7 +2051,7 @@ func BenchmarkTranslateOtToGroupedMetricWithConfigReplaceWithLabel(b *testing.B) b.ResetTimer() for n := 0; n < b.N; n++ { - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) err := translator.translateOTelToGroupedMetric(rm, groupedMetrics, config) assert.Nil(b, err) } @@ -2069,7 +2069,7 @@ func BenchmarkTranslateOtToGroupedMetricWithoutInstrLibrary(b *testing.B) { b.ResetTimer() for n := 0; n < b.N; n++ { - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) err := translator.translateOTelToGroupedMetric(rm, groupedMetrics, config) assert.Nil(b, err) } @@ -2162,7 +2162,7 @@ func BenchmarkTranslateCWMetricToEMF(b *testing.B) { }}, } timestamp := int64(1596151098037) - fields := make(map[string]interface{}) + fields := make(map[string]any) fields[oTellibDimensionKey] = "cloudwatch-otel" fields["spanName"] = "test" fields["spanCounter"] = 0 @@ -2183,8 +2183,8 @@ func BenchmarkTranslateCWMetricToEMF(b *testing.B) { type testMetric struct { metricNames []string metricValues [][]float64 - resourceAttributeMap map[string]interface{} - attributeMap map[string]interface{} + resourceAttributeMap map[string]any + attributeMap map[string]any } type logGroupStreamTest struct { @@ -2214,7 +2214,7 @@ var ( inputMetrics: generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]interface{}{ + resourceAttributeMap: map[string]any{ "ClusterName": "test-cluster", "PodName": "test-pod", }, @@ -2229,7 +2229,7 @@ var ( inputMetrics: generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]interface{}{ + resourceAttributeMap: map[string]any{ "ClusterName": "test-cluster", "PodName": "test-pod", }, @@ -2244,7 +2244,7 @@ var ( inputMetrics: generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - attributeMap: map[string]interface{}{ + attributeMap: map[string]any{ "ClusterName": "test-cluster", "PodName": "test-pod", }, @@ -2259,7 +2259,7 @@ var ( inputMetrics: generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - attributeMap: map[string]interface{}{ + attributeMap: map[string]any{ "ClusterName": "test-cluster", "PodName": "test-pod", }, @@ -2274,10 +2274,10 @@ var ( inputMetrics: generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]interface{}{ + resourceAttributeMap: map[string]any{ "ClusterName": "test-cluster", }, - attributeMap: map[string]interface{}{ + attributeMap: map[string]any{ "PodName": "test-pod", }, }), @@ -2302,7 +2302,7 @@ var ( inputMetrics: generateTestMetrics(testMetric{ metricNames: []string{"metric_1", "metric_2"}, metricValues: [][]float64{{100}, {4}}, - attributeMap: map[string]interface{}{ + attributeMap: map[string]any{ "PodName": "test-pod", }, }), @@ -2328,7 +2328,7 @@ func TestTranslateOtToGroupedMetricForLogGroupAndStream(t *testing.T) { translator := newMetricTranslator(*config) defer require.NoError(t, translator.Shutdown()) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) rm := test.inputMetrics.ResourceMetrics().At(0) err := translator.translateOTelToGroupedMetric(rm, groupedMetrics, config) @@ -2359,7 +2359,7 @@ func TestTranslateOtToGroupedMetricForInitialDeltaValue(t *testing.T) { translator := newMetricTranslator(*config) - groupedMetrics := make(map[interface{}]*groupedMetric) + groupedMetrics := make(map[any]*groupedMetric) rm := test.inputMetrics.ResourceMetrics().At(0) err := translator.translateOTelToGroupedMetric(rm, groupedMetrics, config) diff --git a/exporter/awskinesisexporter/internal/batch/encode_jaeger.go b/exporter/awskinesisexporter/internal/batch/encode_jaeger.go index 6b7685adf88c..42131ee0ea3d 100644 --- a/exporter/awskinesisexporter/internal/batch/encode_jaeger.go +++ b/exporter/awskinesisexporter/internal/batch/encode_jaeger.go @@ -16,7 +16,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/translator/jaeger" ) -func partitionByTraceID(v interface{}) string { +func partitionByTraceID(v any) string { if s, ok := v.(*model.Span); ok && s != nil { return s.TraceID.String() } diff --git a/exporter/awskinesisexporter/internal/key/key.go b/exporter/awskinesisexporter/internal/key/key.go index 3f87bc77a7be..a9293020d667 100644 --- a/exporter/awskinesisexporter/internal/key/key.go +++ b/exporter/awskinesisexporter/internal/key/key.go @@ -9,8 +9,8 @@ import ( // Partition allows for switching our partitioning behavior // when sending data to kinesis. -type Partition func(v interface{}) string +type Partition func(v any) string -func Randomized(_ interface{}) string { +func Randomized(_ any) string { return uuid.NewString() } diff --git a/exporter/awss3exporter/sumo_marshaler.go b/exporter/awss3exporter/sumo_marshaler.go index 1828b136dfb5..9ec2c54e6449 100644 --- a/exporter/awss3exporter/sumo_marshaler.go +++ b/exporter/awss3exporter/sumo_marshaler.go @@ -31,7 +31,7 @@ func newSumoICMarshaler() sumoMarshaler { return sumoMarshaler{} } -func logEntry(buf *bytes.Buffer, format string, a ...interface{}) { +func logEntry(buf *bytes.Buffer, format string, a ...any) { buf.WriteString(fmt.Sprintf(format, a...)) buf.WriteString("\n") } diff --git a/exporter/awsxrayexporter/awsxray_test.go b/exporter/awsxrayexporter/awsxray_test.go index 3f7fc4d6bdf2..f4d5d2875244 100644 --- a/exporter/awsxrayexporter/awsxray_test.go +++ b/exporter/awsxrayexporter/awsxray_test.go @@ -182,7 +182,7 @@ func constructResource() pcommon.Resource { } func constructHTTPClientSpan(traceID pcommon.TraceID) ptrace.Span { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/users/junit" attributes[conventions.AttributeHTTPStatusCode] = 200 @@ -209,7 +209,7 @@ func constructHTTPClientSpan(traceID pcommon.TraceID) ptrace.Span { } func constructHTTPServerSpan(traceID pcommon.TraceID) ptrace.Span { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/users/junit" attributes[conventions.AttributeHTTPClientIP] = "192.168.15.32" @@ -236,7 +236,7 @@ func constructHTTPServerSpan(traceID pcommon.TraceID) ptrace.Span { return span } -func constructSpanAttributes(attributes map[string]interface{}) pcommon.Map { +func constructSpanAttributes(attributes map[string]any) pcommon.Map { attrs := pcommon.NewMap() for key, value := range attributes { if cast, ok := value.(int); ok { diff --git a/exporter/awsxrayexporter/internal/translator/cause_test.go b/exporter/awsxrayexporter/internal/translator/cause_test.go index 0d9d4388ef7f..eabe8147369a 100644 --- a/exporter/awsxrayexporter/internal/translator/cause_test.go +++ b/exporter/awsxrayexporter/internal/translator/cause_test.go @@ -17,7 +17,7 @@ import ( func TestCauseWithExceptions(t *testing.T) { errorMsg := "this is a test" - attributeMap := make(map[string]interface{}) + attributeMap := make(map[string]any) span := constructExceptionServerSpan(attributeMap, ptrace.StatusCodeError) span.Status().SetMessage(errorMsg) @@ -61,7 +61,7 @@ Caused by: java.lang.IllegalArgumentException: bad argument`) func TestMakeCauseAwsSdkSpan(t *testing.T) { errorMsg := "this is a test" - attributeMap := make(map[string]interface{}) + attributeMap := make(map[string]any) attributeMap[conventions.AttributeRPCSystem] = "aws-api" span := constructExceptionServerSpan(attributeMap, ptrace.StatusCodeError) span.Status().SetMessage(errorMsg) @@ -109,7 +109,7 @@ func ExceptionWithoutErrorHelper(t *testing.T, statusCode ptrace.StatusCode) { at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) Caused by: java.lang.IllegalArgumentException: bad argument` - attributeMap := make(map[string]interface{}) + attributeMap := make(map[string]any) span := constructExceptionServerSpan(attributeMap, statusCode) span.Status().SetMessage(errorMsg) @@ -149,7 +149,7 @@ func TestEventWithoutExceptionWithoutError(t *testing.T) { func EventWithoutExceptionWithoutErrorHelper(t *testing.T, statusCode ptrace.StatusCode) { errorMsg := "this is a test" - attributeMap := make(map[string]interface{}) + attributeMap := make(map[string]any) span := constructExceptionServerSpan(attributeMap, statusCode) span.Status().SetMessage(errorMsg) @@ -173,7 +173,7 @@ func EventWithoutExceptionWithoutErrorHelper(t *testing.T, statusCode ptrace.Sta func TestCauseWithStatusMessage(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes[conventions.AttributeHTTPStatusCode] = 500 @@ -198,7 +198,7 @@ func TestCauseWithStatusMessage(t *testing.T) { func TestCauseWithHttpStatusMessage(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes[conventions.AttributeHTTPStatusCode] = 500 @@ -223,7 +223,7 @@ func TestCauseWithHttpStatusMessage(t *testing.T) { func TestCauseWithZeroStatusMessageAndFaultHttpCode(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes[conventions.AttributeHTTPStatusCode] = 500 @@ -247,7 +247,7 @@ func TestCauseWithZeroStatusMessageAndFaultHttpCode(t *testing.T) { func TestNonHttpUnsetCodeSpan(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes["http.status_text"] = errorMsg @@ -270,7 +270,7 @@ func TestNonHttpUnsetCodeSpan(t *testing.T) { func TestNonHttpOkCodeSpan(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes["http.status_text"] = errorMsg @@ -293,7 +293,7 @@ func TestNonHttpOkCodeSpan(t *testing.T) { func TestNonHttpErrCodeSpan(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes["http.status_text"] = errorMsg @@ -316,7 +316,7 @@ func TestNonHttpErrCodeSpan(t *testing.T) { func TestCauseWithZeroStatusMessageAndFaultErrorCode(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes[conventions.AttributeHTTPStatusCode] = 400 @@ -340,7 +340,7 @@ func TestCauseWithZeroStatusMessageAndFaultErrorCode(t *testing.T) { func TestCauseWithClientErrorMessage(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes[conventions.AttributeHTTPStatusCode] = 499 @@ -361,7 +361,7 @@ func TestCauseWithClientErrorMessage(t *testing.T) { func TestCauseWithThrottled(t *testing.T) { errorMsg := "this is a test" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/widgets" attributes[conventions.AttributeHTTPStatusCode] = 429 @@ -380,7 +380,7 @@ func TestCauseWithThrottled(t *testing.T) { assert.NotNil(t, cause) } -func constructExceptionServerSpan(attributes map[string]interface{}, statuscode ptrace.StatusCode) ptrace.Span { +func constructExceptionServerSpan(attributes map[string]any, statuscode ptrace.StatusCode) ptrace.Span { endTime := time.Now().Round(time.Second) startTime := endTime.Add(-90 * time.Second) spanAttributes := constructSpanAttributes(attributes) diff --git a/exporter/awsxrayexporter/internal/translator/http_test.go b/exporter/awsxrayexporter/internal/translator/http_test.go index 957c1c09c113..8d9948eab050 100644 --- a/exporter/awsxrayexporter/internal/translator/http_test.go +++ b/exporter/awsxrayexporter/internal/translator/http_test.go @@ -16,7 +16,7 @@ import ( ) func TestClientSpanWithURLAttribute(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/users/junit" attributes[conventions.AttributeHTTPStatusCode] = 200 @@ -34,7 +34,7 @@ func TestClientSpanWithURLAttribute(t *testing.T) { } func TestClientSpanWithSchemeHostTargetAttributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "api.example.com" @@ -55,7 +55,7 @@ func TestClientSpanWithSchemeHostTargetAttributes(t *testing.T) { } func TestClientSpanWithPeerAttributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "http" attributes[conventions.AttributeNetPeerName] = "kb234.example.com" @@ -80,7 +80,7 @@ func TestClientSpanWithPeerAttributes(t *testing.T) { } func TestClientSpanWithHttpPeerAttributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPClientIP] = "1.2.3.4" attributes[conventions.AttributeNetPeerIP] = "10.8.17.36" span := constructHTTPClientSpan(attributes) @@ -94,7 +94,7 @@ func TestClientSpanWithHttpPeerAttributes(t *testing.T) { } func TestClientSpanWithPeerIp4Attributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "http" attributes[conventions.AttributeNetPeerIP] = "10.8.17.36" @@ -113,7 +113,7 @@ func TestClientSpanWithPeerIp4Attributes(t *testing.T) { } func TestClientSpanWithPeerIp6Attributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeNetPeerIP] = "2001:db8:85a3::8a2e:370:7334" @@ -132,7 +132,7 @@ func TestClientSpanWithPeerIp6Attributes(t *testing.T) { } func TestServerSpanWithURLAttribute(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/users/junit" attributes[conventions.AttributeHTTPClientIP] = "192.168.15.32" @@ -152,7 +152,7 @@ func TestServerSpanWithURLAttribute(t *testing.T) { } func TestServerSpanWithSchemeHostTargetAttributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "api.example.com" @@ -173,7 +173,7 @@ func TestServerSpanWithSchemeHostTargetAttributes(t *testing.T) { } func TestServerSpanWithSchemeServernamePortTargetAttributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPServerName] = "api.example.com" @@ -195,7 +195,7 @@ func TestServerSpanWithSchemeServernamePortTargetAttributes(t *testing.T) { } func TestServerSpanWithSchemeNamePortTargetAttributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "http" attributes[conventions.AttributeHostName] = "kb234.example.com" @@ -219,7 +219,7 @@ func TestServerSpanWithSchemeNamePortTargetAttributes(t *testing.T) { } func TestSpanWithNotEnoughHTTPRequestURLAttributes(t *testing.T) { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "http" attributes[conventions.AttributeHTTPClientIP] = "192.168.15.32" @@ -244,7 +244,7 @@ func TestSpanWithNotEnoughHTTPRequestURLAttributes(t *testing.T) { assert.NotNil(t, filtered) } -func constructHTTPClientSpan(attributes map[string]interface{}) ptrace.Span { +func constructHTTPClientSpan(attributes map[string]any) ptrace.Span { endTime := time.Now().Round(time.Second) startTime := endTime.Add(-90 * time.Second) spanAttributes := constructSpanAttributes(attributes) @@ -267,7 +267,7 @@ func constructHTTPClientSpan(attributes map[string]interface{}) ptrace.Span { return span } -func constructHTTPServerSpan(attributes map[string]interface{}) ptrace.Span { +func constructHTTPServerSpan(attributes map[string]any) ptrace.Span { endTime := time.Now().Round(time.Second) startTime := endTime.Add(-90 * time.Second) spanAttributes := constructSpanAttributes(attributes) diff --git a/exporter/awsxrayexporter/internal/translator/segment.go b/exporter/awsxrayexporter/internal/translator/segment.go index 7d7498e5fa91..d8a9d21dd428 100644 --- a/exporter/awsxrayexporter/internal/translator/segment.go +++ b/exporter/awsxrayexporter/internal/translator/segment.go @@ -369,10 +369,10 @@ func addSpecialAttributes(attributes map[string]pcommon.Value, indexedAttrs []st } func makeXRayAttributes(attributes map[string]pcommon.Value, resource pcommon.Resource, storeResource bool, indexedAttrs []string, indexAllAttrs bool) ( - string, map[string]interface{}, map[string]map[string]interface{}) { + string, map[string]any, map[string]map[string]any) { var ( - annotations = map[string]interface{}{} - metadata = map[string]map[string]interface{}{} + annotations = map[string]any{} + metadata = map[string]map[string]any{} user string ) userid, ok := attributes[conventions.AttributeEnduserID] @@ -385,7 +385,7 @@ func makeXRayAttributes(attributes map[string]pcommon.Value, resource pcommon.Re return user, nil, nil } - defaultMetadata := map[string]interface{}{} + defaultMetadata := map[string]any{} indexedKeys := map[string]bool{} if !indexAllAttrs { @@ -445,7 +445,7 @@ func makeXRayAttributes(attributes map[string]pcommon.Value, resource pcommon.Re } case strings.HasPrefix(key, awsxray.AWSXraySegmentMetadataAttributePrefix) && value.Type() == pcommon.ValueTypeStr: namespace := strings.TrimPrefix(key, awsxray.AWSXraySegmentMetadataAttributePrefix) - var metaVal map[string]interface{} + var metaVal map[string]any err := json.Unmarshal([]byte(value.Str()), &metaVal) switch { case err != nil: @@ -474,7 +474,7 @@ func makeXRayAttributes(attributes map[string]pcommon.Value, resource pcommon.Re return user, annotations, metadata } -func annotationValue(value pcommon.Value) interface{} { +func annotationValue(value pcommon.Value) any { switch value.Type() { case pcommon.ValueTypeStr: return value.Str() diff --git a/exporter/awsxrayexporter/internal/translator/segment_test.go b/exporter/awsxrayexporter/internal/translator/segment_test.go index 284e91c72249..0ceabab1910d 100644 --- a/exporter/awsxrayexporter/internal/translator/segment_test.go +++ b/exporter/awsxrayexporter/internal/translator/segment_test.go @@ -37,7 +37,7 @@ func TestClientSpanWithRpcAwsSdkClientAttributes(t *testing.T) { spanName := "AmazonDynamoDB.getItem" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "dynamodb.us-east-1.amazonaws.com" @@ -70,7 +70,7 @@ func TestClientSpanWithLegacyAwsSdkClientAttributes(t *testing.T) { spanName := "AmazonDynamoDB.getItem" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "dynamodb.us-east-1.amazonaws.com" @@ -102,7 +102,7 @@ func TestClientSpanWithLegacyAwsSdkClientAttributes(t *testing.T) { func TestClientSpanWithPeerService(t *testing.T) { spanName := "AmazonDynamoDB.getItem" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "dynamodb.us-east-1.amazonaws.com" @@ -125,7 +125,7 @@ func TestServerSpanWithInternalServerError(t *testing.T) { errorMessage := "java.lang.NullPointerException" userAgent := "PostmanRuntime/7.21.0" enduser := "go.tester@example.com" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.org/api/locations" attributes[conventions.AttributeHTTPTarget] = "/api/locations" @@ -152,7 +152,7 @@ func TestServerSpanWithThrottle(t *testing.T) { errorMessage := "java.lang.NullPointerException" userAgent := "PostmanRuntime/7.21.0" enduser := "go.tester@example.com" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPURL] = "https://api.example.org/api/locations" attributes[conventions.AttributeHTTPTarget] = "/api/locations" @@ -220,7 +220,7 @@ func TestClientSpanWithDbComponent(t *testing.T) { spanName := "call update_user_preference( ?, ?, ? )" parentSpanID := newSegmentID() enterpriseAppID := "25F2E73B-4769-4C79-9DF3-7EBE85D571EA" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeDBSystem] = "mysql" attributes[conventions.AttributeDBName] = "customers" attributes[conventions.AttributeDBStatement] = spanName @@ -259,7 +259,7 @@ func TestClientSpanWithDbComponent(t *testing.T) { func TestClientSpanWithHttpHost(t *testing.T) { spanName := "GET /" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeNetPeerIP] = "2607:f8b0:4000:80c::2004" @@ -279,7 +279,7 @@ func TestClientSpanWithHttpHost(t *testing.T) { func TestClientSpanWithoutHttpHost(t *testing.T) { spanName := "GET /" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeNetPeerIP] = "2607:f8b0:4000:80c::2004" @@ -298,7 +298,7 @@ func TestClientSpanWithoutHttpHost(t *testing.T) { func TestClientSpanWithRpcHost(t *testing.T) { spanName := "GET /com.foo.AnimalService/GetCats" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeNetPeerIP] = "2607:f8b0:4000:80c::2004" @@ -317,7 +317,7 @@ func TestClientSpanWithRpcHost(t *testing.T) { func TestSpanWithInvalidTraceId(t *testing.T) { spanName := "platformapi.widgets.searchWidgets" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPScheme] = "ipv6" attributes[conventions.AttributeNetPeerIP] = "2607:f8b0:4000:80c::2004" @@ -352,7 +352,7 @@ func TestSpanWithInvalidTraceIdWithoutTimestampValidation(t *testing.T) { spanName := "ABC.payment" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "payment.amazonaws.com" @@ -418,7 +418,7 @@ func TestFixAnnotationKey(t *testing.T) { func TestServerSpanWithNilAttributes(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeError, "OK", attributes) timeEvents := constructTimedEventsWithSentMessageEvent(span.StartTimestamp()) @@ -436,7 +436,7 @@ func TestServerSpanWithNilAttributes(t *testing.T) { func TestSpanWithAttributesDefaultNotIndexed(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes["attr1@1"] = "val1" attributes["attr2@2"] = "val2" resource := constructDefaultResource() @@ -452,18 +452,18 @@ func TestSpanWithAttributesDefaultNotIndexed(t *testing.T) { assert.Equal(t, int64(10), segment.Metadata["default"]["otel.resource.int.key"]) assert.Equal(t, 5.0, segment.Metadata["default"]["otel.resource.double.key"]) assert.Equal(t, true, segment.Metadata["default"]["otel.resource.bool.key"]) - expectedMap := make(map[string]interface{}) + expectedMap := make(map[string]any) expectedMap["key1"] = int64(1) expectedMap["key2"] = "value" assert.Equal(t, expectedMap, segment.Metadata["default"]["otel.resource.map.key"]) - expectedArr := []interface{}{"foo", "bar"} + expectedArr := []any{"foo", "bar"} assert.Equal(t, expectedArr, segment.Metadata["default"]["otel.resource.array.key"]) } func TestSpanWithResourceNotStoredIfSubsegment(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes["attr1@1"] = "val1" attributes["attr2@2"] = "val2" resource := constructDefaultResource() @@ -486,7 +486,7 @@ func TestSpanWithResourceNotStoredIfSubsegment(t *testing.T) { func TestSpanWithAttributesPartlyIndexed(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes["attr1@1"] = "val1" attributes["attr2@2"] = "val2" resource := constructDefaultResource() @@ -503,7 +503,7 @@ func TestSpanWithAttributesPartlyIndexed(t *testing.T) { func TestSpanWithAnnotationsAttribute(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes["attr1@1"] = "val1" attributes["attr2@2"] = "val2" attributes[awsxray.AWSXraySegmentAnnotationsAttribute] = []string{"attr2@2", "not_exist"} @@ -521,7 +521,7 @@ func TestSpanWithAnnotationsAttribute(t *testing.T) { func TestSpanWithAttributesAllIndexed(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes["attr1@1"] = "val1" attributes["attr2@2"] = "val2" resource := constructDefaultResource() @@ -537,7 +537,7 @@ func TestSpanWithAttributesAllIndexed(t *testing.T) { func TestSpanWithAttributesSegmentMetadata(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes["attr1@1"] = "val1" attributes[awsxray.AWSXraySegmentMetadataAttributePrefix+"default"] = "{\"custom_key\": \"custom_value\"}" attributes[awsxray.AWSXraySegmentMetadataAttributePrefix+"http"] = "{\"connection\":{\"reused\":false,\"was_idle\":false}}" @@ -555,7 +555,7 @@ func TestSpanWithAttributesSegmentMetadata(t *testing.T) { assert.Equal(t, "retain-value", segment.Metadata["default"][awsxray.AWSXraySegmentMetadataAttributePrefix+"non-xray-sdk"]) assert.Nil(t, segment.Metadata["default"][awsxray.AWSXraySegmentMetadataAttributePrefix+"default"]) assert.Nil(t, segment.Metadata["default"][awsxray.AWSXraySegmentMetadataAttributePrefix+"http"]) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "reused": false, "was_idle": false, }, segment.Metadata["http"]["connection"]) @@ -564,7 +564,7 @@ func TestSpanWithAttributesSegmentMetadata(t *testing.T) { func TestResourceAttributesCanBeIndexed(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeError, "OK", attributes) @@ -584,19 +584,19 @@ func TestResourceAttributesCanBeIndexed(t *testing.T) { assert.Equal(t, 5.0, segment.Annotations["otel_resource_double_key"]) assert.Equal(t, true, segment.Annotations["otel_resource_bool_key"]) - expectedMap := make(map[string]interface{}) + expectedMap := make(map[string]any) expectedMap["key1"] = int64(1) expectedMap["key2"] = "value" // Maps and arrays are not supported for annotations so still in metadata. assert.Equal(t, expectedMap, segment.Metadata["default"]["otel.resource.map.key"]) - expectedArr := []interface{}{"foo", "bar"} + expectedArr := []any{"foo", "bar"} assert.Equal(t, expectedArr, segment.Metadata["default"]["otel.resource.array.key"]) } func TestResourceAttributesNotIndexedIfSubsegment(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructClientSpan(parentSpanID, spanName, ptrace.StatusCodeError, "OK", attributes) @@ -617,7 +617,7 @@ func TestResourceAttributesNotIndexedIfSubsegment(t *testing.T) { func TestSpanWithSpecialAttributesAsListed(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[awsxray.AWSOperationAttribute] = "aws_operation_val" attributes[conventions.AttributeRPCMethod] = "rpc_method_val" resource := constructDefaultResource() @@ -634,7 +634,7 @@ func TestSpanWithSpecialAttributesAsListed(t *testing.T) { func TestSpanWithSpecialAttributesAsListedAndIndexAll(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[awsxray.AWSOperationAttribute] = "aws_operation_val" attributes[conventions.AttributeRPCMethod] = "rpc_method_val" resource := constructDefaultResource() @@ -650,7 +650,7 @@ func TestSpanWithSpecialAttributesAsListedAndIndexAll(t *testing.T) { func TestSpanWithSpecialAttributesNotListedAndIndexAll(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[awsxray.AWSOperationAttribute] = "val1" attributes[conventions.AttributeRPCMethod] = "val2" resource := constructDefaultResource() @@ -666,7 +666,7 @@ func TestSpanWithSpecialAttributesNotListedAndIndexAll(t *testing.T) { func TestOriginNotAws(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderGCP) @@ -682,7 +682,7 @@ func TestOriginNotAws(t *testing.T) { func TestOriginEc2(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -699,7 +699,7 @@ func TestOriginEc2(t *testing.T) { func TestOriginEcs(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -717,7 +717,7 @@ func TestOriginEcs(t *testing.T) { func TestOriginEcsEc2(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -736,7 +736,7 @@ func TestOriginEcsEc2(t *testing.T) { func TestOriginEcsFargate(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -755,7 +755,7 @@ func TestOriginEcsFargate(t *testing.T) { func TestOriginEb(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -777,7 +777,7 @@ func TestOriginEks(t *testing.T) { containerID := "0123456789A" spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -805,7 +805,7 @@ func TestOriginEks(t *testing.T) { func TestOriginAppRunner(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -821,7 +821,7 @@ func TestOriginAppRunner(t *testing.T) { func TestOriginBlank(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -836,7 +836,7 @@ func TestOriginBlank(t *testing.T) { func TestOriginPrefersInfraService(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() attrs := resource.Attributes() attrs.PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAWS) @@ -856,7 +856,7 @@ func TestOriginPrefersInfraService(t *testing.T) { func TestFilteredAttributesMetadata(t *testing.T) { spanName := "/test" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := pcommon.NewResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeError, "OK", attributes) @@ -885,8 +885,8 @@ func TestFilteredAttributesMetadata(t *testing.T) { assert.Equal(t, int64(123), segment.Metadata["default"]["int_value"]) assert.Equal(t, 456.78, segment.Metadata["default"]["float_value"]) assert.Equal(t, false, segment.Metadata["default"]["bool_value"]) - assert.Equal(t, []interface{}{int64(12), int64(34), int64(56)}, segment.Metadata["default"]["array_value"]) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, []any{int64(12), int64(34), int64(56)}, segment.Metadata["default"]["array_value"]) + assert.Equal(t, map[string]any{ "value1": -987.65, "value2": true, }, segment.Metadata["default"]["map_value"]) @@ -895,7 +895,7 @@ func TestFilteredAttributesMetadata(t *testing.T) { func TestSpanWithSingleDynamoDBTableHasTableName(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeAWSDynamoDBTableNames] = []string{"table1"} resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeError, "OK", attributes) @@ -905,13 +905,13 @@ func TestSpanWithSingleDynamoDBTableHasTableName(t *testing.T) { assert.NotNil(t, segment) assert.Equal(t, "table1", *segment.AWS.TableName) assert.Nil(t, segment.AWS.TableNames) - assert.Equal(t, []interface{}{"table1"}, segment.Metadata["default"][conventions.AttributeAWSDynamoDBTableNames]) + assert.Equal(t, []any{"table1"}, segment.Metadata["default"][conventions.AttributeAWSDynamoDBTableNames]) } func TestSpanWithMultipleDynamoDBTablesHasTableNames(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeAWSDynamoDBTableNames] = []string{"table1", "table2"} resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeError, "OK", attributes) @@ -921,13 +921,13 @@ func TestSpanWithMultipleDynamoDBTablesHasTableNames(t *testing.T) { assert.NotNil(t, segment) assert.Nil(t, segment.AWS.TableName) assert.Equal(t, []string{"table1", "table2"}, segment.AWS.TableNames) - assert.Equal(t, []interface{}{"table1", "table2"}, segment.Metadata["default"][conventions.AttributeAWSDynamoDBTableNames]) + assert.Equal(t, []any{"table1", "table2"}, segment.Metadata["default"][conventions.AttributeAWSDynamoDBTableNames]) } func TestSegmentWithLogGroupsFromConfig(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeError, "OK", attributes) timeEvents := constructTimedEventsWithSentMessageEvent(span.StartTimestamp()) @@ -946,7 +946,7 @@ func TestSegmentWithLogGroupsFromConfig(t *testing.T) { func TestSegmentWith2LogGroupsFromConfig(t *testing.T) { spanName := "/api/locations" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeError, "OK", attributes) timeEvents := constructTimedEventsWithSentMessageEvent(span.StartTimestamp()) @@ -968,7 +968,7 @@ func TestClientSpanWithAwsRemoteServiceName(t *testing.T) { spanName := "ABC.payment" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "payment.amazonaws.com" @@ -996,7 +996,7 @@ func TestAwsSdkSpanWithAwsRemoteServiceName(t *testing.T) { spanName := "DynamoDB.PutItem" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeRPCSystem] = "aws-api" attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" @@ -1024,7 +1024,7 @@ func TestProducerSpanWithAwsRemoteServiceName(t *testing.T) { spanName := "ABC.payment" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "payment.amazonaws.com" @@ -1052,7 +1052,7 @@ func TestConsumerSpanWithAwsRemoteServiceName(t *testing.T) { spanName := "ABC.payment" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "payment.amazonaws.com" @@ -1079,7 +1079,7 @@ func TestServerSpanWithAwsLocalServiceName(t *testing.T) { spanName := "ABC.payment" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "POST" attributes[conventions.AttributeHTTPScheme] = "https" attributes[conventions.AttributeHTTPHost] = "payment.amazonaws.com" @@ -1103,7 +1103,7 @@ func TestServerSpanWithAwsLocalServiceName(t *testing.T) { assert.False(t, strings.Contains(jsonStr, "user")) } -func constructClientSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]interface{}) ptrace.Span { +func constructClientSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]any) ptrace.Span { var ( traceID = newTraceID() spanID = newSegmentID() @@ -1130,7 +1130,7 @@ func constructClientSpan(parentSpanID pcommon.SpanID, name string, code ptrace.S return span } -func constructServerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]interface{}) ptrace.Span { +func constructServerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]any) ptrace.Span { var ( traceID = newTraceID() spanID = newSegmentID() @@ -1157,7 +1157,7 @@ func constructServerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.S return span } -func constructConsumerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]interface{}) ptrace.Span { +func constructConsumerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]any) ptrace.Span { var ( traceID = newTraceID() spanID = newSegmentID() @@ -1184,7 +1184,7 @@ func constructConsumerSpan(parentSpanID pcommon.SpanID, name string, code ptrace return span } -func constructProducerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]interface{}) ptrace.Span { +func constructProducerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]any) ptrace.Span { var ( traceID = newTraceID() spanID = newSegmentID() @@ -1211,7 +1211,7 @@ func constructProducerSpan(parentSpanID pcommon.SpanID, name string, code ptrace return span } -func constructSpanAttributes(attributes map[string]interface{}) pcommon.Map { +func constructSpanAttributes(attributes map[string]any) pcommon.Map { attrs := pcommon.NewMap() for key, value := range attributes { if cast, ok := value.(int); ok { diff --git a/exporter/awsxrayexporter/internal/translator/span_links.go b/exporter/awsxrayexporter/internal/translator/span_links.go index 3f22f586110a..7a262b2fa5b1 100644 --- a/exporter/awsxrayexporter/internal/translator/span_links.go +++ b/exporter/awsxrayexporter/internal/translator/span_links.go @@ -28,7 +28,7 @@ func makeSpanLinks(links ptrace.SpanLinkSlice, skipTimestampValidation bool) ([] spanLinkData.TraceID = &traceID if link.Attributes().Len() > 0 { - spanLinkData.Attributes = make(map[string]interface{}) + spanLinkData.Attributes = make(map[string]any) link.Attributes().Range(func(k string, v pcommon.Value) bool { spanLinkData.Attributes[k] = v.AsRaw() diff --git a/exporter/awsxrayexporter/internal/translator/span_links_test.go b/exporter/awsxrayexporter/internal/translator/span_links_test.go index b16504a143c1..f299bd4f01f9 100644 --- a/exporter/awsxrayexporter/internal/translator/span_links_test.go +++ b/exporter/awsxrayexporter/internal/translator/span_links_test.go @@ -16,7 +16,7 @@ import ( func TestSpanLinkSimple(t *testing.T) { spanName := "ProcessingMessage" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeOk, "OK", attributes) @@ -46,7 +46,7 @@ func TestSpanLinkSimple(t *testing.T) { func TestSpanLinkEmpty(t *testing.T) { spanName := "ProcessingMessage" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeOk, "OK", attributes) @@ -62,7 +62,7 @@ func TestSpanLinkEmpty(t *testing.T) { func TestOldSpanLinkError(t *testing.T) { spanName := "ProcessingMessage" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeOk, "OK", attributes) @@ -88,7 +88,7 @@ func TestOldSpanLinkError(t *testing.T) { func TestTwoSpanLinks(t *testing.T) { spanName := "ProcessingMessage" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeOk, "OK", attributes) @@ -138,7 +138,7 @@ func TestTwoSpanLinks(t *testing.T) { func TestSpanLinkComplexAttributes(t *testing.T) { spanName := "ProcessingMessage" parentSpanID := newSegmentID() - attributes := make(map[string]interface{}) + attributes := make(map[string]any) resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeOk, "OK", attributes) @@ -180,21 +180,21 @@ func TestSpanLinkComplexAttributes(t *testing.T) { assert.Equal(t, int64(112233), segment.Links[0].Attributes["myKey3"]) assert.Equal(t, 3.1415, segment.Links[0].Attributes["myKey4"]) - assert.Equal(t, "apple", segment.Links[0].Attributes["myKey5"].([]interface{})[0]) - assert.Equal(t, "pear", segment.Links[0].Attributes["myKey5"].([]interface{})[1]) - assert.Equal(t, "banana", segment.Links[0].Attributes["myKey5"].([]interface{})[2]) + assert.Equal(t, "apple", segment.Links[0].Attributes["myKey5"].([]any)[0]) + assert.Equal(t, "pear", segment.Links[0].Attributes["myKey5"].([]any)[1]) + assert.Equal(t, "banana", segment.Links[0].Attributes["myKey5"].([]any)[2]) - assert.Equal(t, true, segment.Links[0].Attributes["myKey6"].([]interface{})[0]) - assert.Equal(t, false, segment.Links[0].Attributes["myKey6"].([]interface{})[1]) - assert.Equal(t, false, segment.Links[0].Attributes["myKey6"].([]interface{})[2]) - assert.Equal(t, true, segment.Links[0].Attributes["myKey6"].([]interface{})[0]) + assert.Equal(t, true, segment.Links[0].Attributes["myKey6"].([]any)[0]) + assert.Equal(t, false, segment.Links[0].Attributes["myKey6"].([]any)[1]) + assert.Equal(t, false, segment.Links[0].Attributes["myKey6"].([]any)[2]) + assert.Equal(t, true, segment.Links[0].Attributes["myKey6"].([]any)[0]) - assert.Equal(t, int64(1234), segment.Links[0].Attributes["myKey7"].([]interface{})[0]) - assert.Equal(t, int64(5678), segment.Links[0].Attributes["myKey7"].([]interface{})[1]) - assert.Equal(t, int64(9012), segment.Links[0].Attributes["myKey7"].([]interface{})[2]) + assert.Equal(t, int64(1234), segment.Links[0].Attributes["myKey7"].([]any)[0]) + assert.Equal(t, int64(5678), segment.Links[0].Attributes["myKey7"].([]any)[1]) + assert.Equal(t, int64(9012), segment.Links[0].Attributes["myKey7"].([]any)[2]) - assert.Equal(t, 2.718, segment.Links[0].Attributes["myKey8"].([]interface{})[0]) - assert.Equal(t, 1.618, segment.Links[0].Attributes["myKey8"].([]interface{})[1]) + assert.Equal(t, 2.718, segment.Links[0].Attributes["myKey8"].([]any)[0]) + assert.Equal(t, 1.618, segment.Links[0].Attributes["myKey8"].([]any)[1]) jsonStr, _ := MakeSegmentDocumentString(span, resource, nil, false, nil, false) diff --git a/exporter/awsxrayexporter/internal/translator/sql_test.go b/exporter/awsxrayexporter/internal/translator/sql_test.go index e084be8ae76e..d3af6a2faa0f 100644 --- a/exporter/awsxrayexporter/internal/translator/sql_test.go +++ b/exporter/awsxrayexporter/internal/translator/sql_test.go @@ -77,7 +77,7 @@ func constructSQLSpan(attributes map[string]pcommon.Value) ptrace.Span { startTime := endTime.Add(-90 * time.Second) // constructSpanAttributes() in segment_test accepts a map of interfaces... - interfaceAttributes := make(map[string]interface{}) + interfaceAttributes := make(map[string]any) for k, v := range attributes { interfaceAttributes[k] = v } diff --git a/exporter/awsxrayexporter/internal/translator/writer_pool.go b/exporter/awsxrayexporter/internal/translator/writer_pool.go index 55b788b3132e..b35d5553fdd9 100644 --- a/exporter/awsxrayexporter/internal/translator/writer_pool.go +++ b/exporter/awsxrayexporter/internal/translator/writer_pool.go @@ -24,7 +24,7 @@ type writerPool struct { func newWriterPool(size int) *writerPool { pool := &sync.Pool{ - New: func() interface{} { + New: func() any { var ( buffer = bytes.NewBuffer(make([]byte, 0, size)) encoder = json.NewEncoder(buffer) @@ -43,7 +43,7 @@ func (w *writer) Reset() { w.buffer.Reset() } -func (w *writer) Encode(v interface{}) error { +func (w *writer) Encode(v any) error { return w.encoder.Encode(v) } diff --git a/exporter/awsxrayexporter/internal/translator/writer_pool_test.go b/exporter/awsxrayexporter/internal/translator/writer_pool_test.go index b3f34641202d..f7d9728d389e 100644 --- a/exporter/awsxrayexporter/internal/translator/writer_pool_test.go +++ b/exporter/awsxrayexporter/internal/translator/writer_pool_test.go @@ -65,7 +65,7 @@ func BenchmarkWithPool(b *testing.B) { } func constructWriterPoolSpan() ptrace.Span { - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes[conventions.AttributeHTTPMethod] = "GET" attributes[conventions.AttributeHTTPURL] = "https://api.example.com/users/junit" attributes[conventions.AttributeHTTPClientIP] = "192.168.15.32" diff --git a/exporter/azuredataexplorerexporter/adx_exporter.go b/exporter/azuredataexplorerexporter/adx_exporter.go index bb46a08b8ca5..b9b8ada24dae 100644 --- a/exporter/azuredataexplorerexporter/adx_exporter.go +++ b/exporter/azuredataexplorerexporter/adx_exporter.go @@ -239,8 +239,8 @@ func createQueuedIngestor(config *Config, adxclient *kusto.Client, tablename str return ingestor, err } -func getScopeMap(sc pcommon.InstrumentationScope) map[string]interface{} { - scopeMap := make(map[string]interface{}, 2) +func getScopeMap(sc pcommon.InstrumentationScope) map[string]any { + scopeMap := make(map[string]any, 2) if sc.Name() != "" { scopeMap[scopename] = sc.Name() diff --git a/exporter/azuredataexplorerexporter/e2e_test.go b/exporter/azuredataexplorerexporter/e2e_test.go index 0718c0e04938..7d8ebb729e14 100644 --- a/exporter/azuredataexplorerexporter/e2e_test.go +++ b/exporter/azuredataexplorerexporter/e2e_test.go @@ -255,12 +255,12 @@ func getConfig() (*Config, bool) { }, true } -func createTraces() (ptrace.Traces, string, map[string]interface{}) { +func createTraces() (ptrace.Traces, string, map[string]any) { td := ptrace.NewTraces() span := td.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty() span.SetName(spanName) span.Status().SetMessage("STATUS_MESSAGE") - attrs := map[string]interface{}{ + attrs := map[string]any{ "k0": "v0", "k1": "v1", } @@ -280,10 +280,10 @@ func createTraces() (ptrace.Traces, string, map[string]interface{}) { return td, traceutil.TraceIDToHexOrEmptyString(span.TraceID()), attrs } -func createLogs() (plog.Logs, string, map[string]interface{}) { +func createLogs() (plog.Logs, string, map[string]any) { testLogs := plog.NewLogs() tID := uuid.New().String() - attrs := map[string]interface{}{ + attrs := map[string]any{ "l0": "a0", "l1": "a1", } @@ -305,10 +305,10 @@ func createLogs() (plog.Logs, string, map[string]interface{}) { return testLogs, traceutil.TraceIDToHexOrEmptyString(logRecord.TraceID()), attrs } -func createMetrics() (pmetric.Metrics, map[string]interface{}, string) { +func createMetrics() (pmetric.Metrics, map[string]any, string) { tm := pmetric.NewMetrics() tID := uuid.New().String() - attrs := map[string]interface{}{ + attrs := map[string]any{ "m1": "a0", "m2": "a1", } diff --git a/exporter/azuredataexplorerexporter/logsdata_to_adx.go b/exporter/azuredataexplorerexporter/logsdata_to_adx.go index 6dd240998c5c..8256495dc985 100644 --- a/exporter/azuredataexplorerexporter/logsdata_to_adx.go +++ b/exporter/azuredataexplorerexporter/logsdata_to_adx.go @@ -14,15 +14,15 @@ import ( ) type AdxLog struct { - Timestamp string // The timestamp of the occurrence. Formatted into string as RFC3339Nano - ObservedTimestamp string // The timestamp of logs observed in opentelemetry collector. Formatted into string as RFC3339Nano - TraceID string // TraceId associated to the log - SpanID string // SpanId associated to the log - SeverityText string // The severity level of the log - SeverityNumber int32 // The severity number associated to the log - Body string // The body/Text of the log - ResourceAttributes map[string]interface{} // JSON Resource attributes that can then be parsed. - LogsAttributes map[string]interface{} // JSON attributes that can then be parsed. + Timestamp string // The timestamp of the occurrence. Formatted into string as RFC3339Nano + ObservedTimestamp string // The timestamp of logs observed in opentelemetry collector. Formatted into string as RFC3339Nano + TraceID string // TraceId associated to the log + SpanID string // SpanId associated to the log + SeverityText string // The severity level of the log + SeverityNumber int32 // The severity number associated to the log + Body string // The body/Text of the log + ResourceAttributes map[string]any // JSON Resource attributes that can then be parsed. + LogsAttributes map[string]any // JSON attributes that can then be parsed. } // Convert the plog to the type ADXLog, this matches the scheme in the Log table in the database diff --git a/exporter/azuredataexplorerexporter/logsdata_to_adx_test.go b/exporter/azuredataexplorerexporter/logsdata_to_adx_test.go index 11c7b1e8f936..3828ba27a76f 100644 --- a/exporter/azuredataexplorerexporter/logsdata_to_adx_test.go +++ b/exporter/azuredataexplorerexporter/logsdata_to_adx_test.go @@ -19,7 +19,7 @@ func Test_mapToAdxLog(t *testing.T) { logger := zap.NewNop() epoch, _ := time.Parse("2006-01-02T15:04:05.999999999Z07:00", "1970-01-01T00:00:00.000000000Z") defaultTime := pcommon.NewTimestampFromTime(epoch).AsTime().Format(time.RFC3339Nano) - tmap := make(map[string]interface{}) + tmap := make(map[string]any) tmap["key"] = "value" tmap[hostkey] = testhost @@ -167,8 +167,8 @@ func Test_mapToAdxLog(t *testing.T) { { Timestamp: defaultTime, ObservedTimestamp: defaultTime, - ResourceAttributes: map[string]interface{}{}, - LogsAttributes: map[string]interface{}{}, + ResourceAttributes: map[string]any{}, + LogsAttributes: map[string]any{}, }, }, }, diff --git a/exporter/azuredataexplorerexporter/metricsdata_to_adx.go b/exporter/azuredataexplorerexporter/metricsdata_to_adx.go index 1582fd647285..a21897f393b0 100644 --- a/exporter/azuredataexplorerexporter/metricsdata_to_adx.go +++ b/exporter/azuredataexplorerexporter/metricsdata_to_adx.go @@ -35,22 +35,22 @@ const ( type AdxMetric struct { Timestamp string // The timestamp of the occurrence. A metric is measured at a point of time. Formatted into string as RFC3339Nano // Including name, the Metric object is defined by the following properties: - MetricName string // Name of the metric field - MetricType string // The data point type (e.g. Sum, Gauge, Histogram ExponentialHistogram, Summary) - MetricUnit string // The metric stream’s unit - MetricDescription string // The metric stream’s description - MetricValue float64 // the value of the metric - MetricAttributes map[string]interface{} // JSON attributes that can then be parsed. Extrinsic properties + MetricName string // Name of the metric field + MetricType string // The data point type (e.g. Sum, Gauge, Histogram ExponentialHistogram, Summary) + MetricUnit string // The metric stream’s unit + MetricDescription string // The metric stream’s description + MetricValue float64 // the value of the metric + MetricAttributes map[string]any // JSON attributes that can then be parsed. Extrinsic properties // Additional properties - Host string // The hostname for analysis of the metric. Extracted from https://opentelemetry.io/docs/reference/specification/resource/semantic_conventions/host/ - ResourceAttributes map[string]interface{} // The originating Resource attributes. Refer https://opentelemetry.io/docs/reference/specification/resource/sdk/ + Host string // The hostname for analysis of the metric. Extracted from https://opentelemetry.io/docs/reference/specification/resource/semantic_conventions/host/ + ResourceAttributes map[string]any // The originating Resource attributes. Refer https://opentelemetry.io/docs/reference/specification/resource/sdk/ } /* Convert the pMetric to the type ADXMetric , this matches the scheme in the OTELMetric table in the database */ -func mapToAdxMetric(res pcommon.Resource, md pmetric.Metric, scopeattrs map[string]interface{}, logger *zap.Logger) []*AdxMetric { +func mapToAdxMetric(res pcommon.Resource, md pmetric.Metric, scopeattrs map[string]any, logger *zap.Logger) []*AdxMetric { logger.Debug("Entering processing of toAdxMetric function") // default to collectors host name. Ignore the error here. This should not cause the failure of the process host, err := os.Hostname() @@ -134,7 +134,7 @@ func mapToAdxMetric(res pcommon.Resource, md pmetric.Metric, scopeattrs map[stri // now create buckets for each bound. for bi := 0; bi < bounds.Len(); bi++ { customMap := - copyMap(map[string]interface{}{"le": float64ToDimValue(bounds.At(bi))}, dataPoint.Attributes().AsRaw()) + copyMap(map[string]any{"le": float64ToDimValue(bounds.At(bi))}, dataPoint.Attributes().AsRaw()) value += counts.At(bi) vMap := pcommon.NewMap() @@ -152,7 +152,7 @@ func mapToAdxMetric(res pcommon.Resource, md pmetric.Metric, scopeattrs map[stri { // Add the LE field for the bucket's bound customMap := - copyMap(map[string]interface{}{ + copyMap(map[string]any{ "le": float64ToDimValue(math.Inf(1)), }, dataPoint.Attributes().AsRaw()) vMap := pcommon.NewMap() @@ -214,7 +214,7 @@ func mapToAdxMetric(res pcommon.Resource, md pmetric.Metric, scopeattrs map[stri for bi := 0; bi < dataPoint.QuantileValues().Len(); bi++ { dp := dataPoint.QuantileValues().At(bi) quantileName := fmt.Sprintf("%s_%s", md.Name(), strconv.FormatFloat(dp.Quantile(), 'f', -1, 64)) - metricQuantile := map[string]interface{}{ + metricQuantile := map[string]any{ "qt": float64ToDimValue(dp.Quantile()), quantileName: sanitizeFloat(dp.Value()).(float64), } @@ -261,15 +261,15 @@ func rawMetricsToAdxMetrics(_ context.Context, metrics pmetric.Metrics, logger * return transformedAdxMetrics } -func copyMap(toAttrib map[string]interface{}, fromAttrib map[string]interface{}) map[string]interface{} { +func copyMap(toAttrib map[string]any, fromAttrib map[string]any) map[string]any { for k, v := range fromAttrib { toAttrib[k] = v } return toAttrib } -func cloneMap(fields map[string]interface{}) map[string]interface{} { - newFields := make(map[string]interface{}, len(fields)) +func cloneMap(fields map[string]any) map[string]any { + newFields := make(map[string]any, len(fields)) return copyMap(newFields, fields) } @@ -277,7 +277,7 @@ func float64ToDimValue(f float64) string { return strconv.FormatFloat(f, 'g', -1, 64) } -func sanitizeFloat(value float64) interface{} { +func sanitizeFloat(value float64) any { if math.IsNaN(value) { return math.NaN() } diff --git a/exporter/azuredataexplorerexporter/metricsdata_to_adx_test.go b/exporter/azuredataexplorerexporter/metricsdata_to_adx_test.go index 9d07534df6ae..5afa9781713e 100644 --- a/exporter/azuredataexplorerexporter/metricsdata_to_adx_test.go +++ b/exporter/azuredataexplorerexporter/metricsdata_to_adx_test.go @@ -34,12 +34,12 @@ var distributionCounts = []uint64{4, 2, 3, 5} func Test_rawMetricsToAdxMetrics(t *testing.T) { t.Parallel() // Resource map - rmap := make(map[string]interface{}) + rmap := make(map[string]any) rmap["key"] = "value" rmap[hostkey] = testhost // Metric map , with scopes - mmap := make(map[string]interface{}) + mmap := make(map[string]any) mmap[scopename] = "SN" mmap[scopeversion] = "SV" @@ -175,10 +175,10 @@ func Test_rawMetricsToAdxMetrics(t *testing.T) { func Test_mapToAdxMetric(t *testing.T) { t.Parallel() - rmap := make(map[string]interface{}) + rmap := make(map[string]any) rmap["key"] = "value" rmap[hostkey] = testhost - mmap := make(map[string]interface{}) + mmap := make(map[string]any) tests := []struct { name string // name of the test @@ -548,7 +548,7 @@ func Test_mapToAdxMetric(t *testing.T) { t.Run(tt.name, func(t *testing.T) { res := tt.resourceFn() md := tt.metricDataFn() - emptyscopemap := make(map[string]interface{}, 2) + emptyscopemap := make(map[string]any, 2) actualMetrics := mapToAdxMetric(res, md, emptyscopemap, zap.NewNop()) encoder := json.NewEncoder(io.Discard) for i, expectedMetric := range tt.expectedAdxMetrics { @@ -578,12 +578,12 @@ func newDummyResource() pcommon.Resource { return res } -func newMapFromAttr(jsonStr string) map[string]interface{} { - dynamic := make(map[string]interface{}) +func newMapFromAttr(jsonStr string) map[string]any { + dynamic := make(map[string]any) err := json.Unmarshal([]byte(jsonStr), &dynamic) // If there is a failure , send the error back in a map if err != nil { - return map[string]interface{}{"err": err.Error()} + return map[string]any{"err": err.Error()} } return dynamic } diff --git a/exporter/azuredataexplorerexporter/tracesdata_to_adx.go b/exporter/azuredataexplorerexporter/tracesdata_to_adx.go index 3189f0aed4d2..7f72f5e8742d 100644 --- a/exporter/azuredataexplorerexporter/tracesdata_to_adx.go +++ b/exporter/azuredataexplorerexporter/tracesdata_to_adx.go @@ -13,32 +13,32 @@ import ( ) type AdxTrace struct { - TraceID string // TraceID associated to the Trace - SpanID string // SpanID associated to the Trace - ParentID string // ParentID associated to the Trace - SpanName string // The SpanName of the Trace - SpanStatus string // The SpanStatus Code associated to the Trace - SpanStatusMessage string // The SpanStatusMessage associated to the Trace - SpanKind string // The SpanKind of the Trace - StartTime string // The start time of the occurrence. Formatted into string as RFC3339Nano - EndTime string // The end time of the occurrence. Formatted into string as RFC3339Nano - ResourceAttributes map[string]interface{} // JSON Resource attributes that can then be parsed. - TraceAttributes map[string]interface{} // JSON attributes that can then be parsed. - Events []*Event // Array containing the events in a span - Links []*Link // Array containing the link in a span + TraceID string // TraceID associated to the Trace + SpanID string // SpanID associated to the Trace + ParentID string // ParentID associated to the Trace + SpanName string // The SpanName of the Trace + SpanStatus string // The SpanStatus Code associated to the Trace + SpanStatusMessage string // The SpanStatusMessage associated to the Trace + SpanKind string // The SpanKind of the Trace + StartTime string // The start time of the occurrence. Formatted into string as RFC3339Nano + EndTime string // The end time of the occurrence. Formatted into string as RFC3339Nano + ResourceAttributes map[string]any // JSON Resource attributes that can then be parsed. + TraceAttributes map[string]any // JSON attributes that can then be parsed. + Events []*Event // Array containing the events in a span + Links []*Link // Array containing the link in a span } type Event struct { EventName string Timestamp string - EventAttributes map[string]interface{} + EventAttributes map[string]any } type Link struct { TraceID string SpanID string TraceState string - SpanLinkAttributes map[string]interface{} + SpanLinkAttributes map[string]any } type Status struct { diff --git a/exporter/azuredataexplorerexporter/tracesdata_to_adx_test.go b/exporter/azuredataexplorerexporter/tracesdata_to_adx_test.go index 337723424894..9b5a9e119c07 100644 --- a/exporter/azuredataexplorerexporter/tracesdata_to_adx_test.go +++ b/exporter/azuredataexplorerexporter/tracesdata_to_adx_test.go @@ -16,7 +16,7 @@ import ( func Test_mapToAdxTrace(t *testing.T) { epoch, _ := time.Parse("2006-01-02T15:04:05.999999999Z07:00", "1970-01-01T00:00:00.000000000Z") defaultTime := pcommon.NewTimestampFromTime(epoch).AsTime().Format(time.RFC3339Nano) - tmap := make(map[string]interface{}) + tmap := make(map[string]any) tmap["key"] = "value" tmap[hostkey] = testhost diff --git a/exporter/azuremonitorexporter/conventions_test.go b/exporter/azuremonitorexporter/conventions_test.go index 141c078d3cc2..58486ddbbec6 100644 --- a/exporter/azuremonitorexporter/conventions_test.go +++ b/exporter/azuremonitorexporter/conventions_test.go @@ -12,7 +12,7 @@ import ( ) func TestHTTPAttributeMapping(t *testing.T) { - httpAttributeValues := map[string]interface{}{ + httpAttributeValues := map[string]any{ conventions.AttributeHTTPMethod: conventions.AttributeHTTPMethod, conventions.AttributeHTTPURL: conventions.AttributeHTTPURL, conventions.AttributeHTTPTarget: conventions.AttributeHTTPTarget, @@ -63,7 +63,7 @@ func TestHTTPAttributeMapping(t *testing.T) { } func TestRPCPAttributeMapping(t *testing.T) { - rpcAttributeValues := map[string]interface{}{ + rpcAttributeValues := map[string]any{ conventions.AttributeRPCSystem: conventions.AttributeRPCSystem, conventions.AttributeRPCService: conventions.AttributeRPCService, conventions.AttributeRPCMethod: conventions.AttributeRPCMethod, @@ -85,7 +85,7 @@ func TestRPCPAttributeMapping(t *testing.T) { } func TestDatabaseAttributeMapping(t *testing.T) { - databaseAttributeValues := map[string]interface{}{ + databaseAttributeValues := map[string]any{ conventions.AttributeDBSystem: conventions.AttributeDBSystem, conventions.AttributeDBConnectionString: conventions.AttributeDBConnectionString, conventions.AttributeDBUser: conventions.AttributeDBUser, @@ -121,7 +121,7 @@ func TestDatabaseAttributeMapping(t *testing.T) { } func TestMessagingAttributeMapping(t *testing.T) { - messagingAttributeValues := map[string]interface{}{ + messagingAttributeValues := map[string]any{ conventions.AttributeMessagingSystem: conventions.AttributeMessagingSystem, conventions.AttributeMessagingDestination: conventions.AttributeMessagingDestination, conventions.AttributeMessagingDestinationKind: conventions.AttributeMessagingDestinationKind, diff --git a/exporter/azuremonitorexporter/trace_to_envelope_test.go b/exporter/azuremonitorexporter/trace_to_envelope_test.go index 441449963605..f16051f75471 100644 --- a/exporter/azuremonitorexporter/trace_to_envelope_test.go +++ b/exporter/azuremonitorexporter/trace_to_envelope_test.go @@ -67,21 +67,21 @@ var ( defaultMessagingStatusCodeAsString = strconv.FormatInt(defaultRPCStatusCode, 10) // Required attribute for any HTTP Span - requiredHTTPAttributes = map[string]interface{}{ + requiredHTTPAttributes = map[string]any{ conventions.AttributeHTTPMethod: defaultHTTPMethod, } // Required attribute for any RPC Span - requiredRPCAttributes = map[string]interface{}{ + requiredRPCAttributes = map[string]any{ conventions.AttributeRPCSystem: defaultRPCSystem, } - requiredDatabaseAttributes = map[string]interface{}{ + requiredDatabaseAttributes = map[string]any{ conventions.AttributeDBSystem: defaultDBSystem, conventions.AttributeDBName: defaultDBName, } - requiredMessagingAttributes = map[string]interface{}{ + requiredMessagingAttributes = map[string]any{ conventions.AttributeMessagingSystem: defaultMessagingSystem, conventions.AttributeMessagingDestination: defaultMessagingDestination, } @@ -494,14 +494,14 @@ func TestUnspecifiedSpanToInProcRemoteDependencyData(t *testing.T) { func TestSpanWithEventsToEnvelopes(t *testing.T) { span := getDefaultRPCClientSpan() - spanEvent := getSpanEvent("foo", map[string]interface{}{"bar": "baz"}) + spanEvent := getSpanEvent("foo", map[string]any{"bar": "baz"}) spanEvent.CopyTo(span.Events().AppendEmpty()) exceptionType := "foo" exceptionMessage := "bar" exceptionStackTrace := "baz" - exceptionEvent := getSpanEvent("exception", map[string]interface{}{ + exceptionEvent := getSpanEvent("exception", map[string]any{ conventions.AttributeExceptionType: exceptionType, conventions.AttributeExceptionMessage: exceptionMessage, conventions.AttributeExceptionStacktrace: exceptionStackTrace, @@ -747,7 +747,7 @@ func assertAttributesCopiedToPropertiesOrMeasurements( /* The remainder of these methods are for building up test assets */ -func getSpan(spanName string, spanKind ptrace.SpanKind, initialAttributes map[string]interface{}) ptrace.Span { +func getSpan(spanName string, spanKind ptrace.SpanKind, initialAttributes map[string]any) ptrace.Span { span := ptrace.NewSpan() span.SetTraceID(defaultTraceID) span.SetSpanID(defaultSpanID) @@ -762,7 +762,7 @@ func getSpan(spanName string, spanKind ptrace.SpanKind, initialAttributes map[st } // Returns a default span event -func getSpanEvent(name string, initialAttributes map[string]interface{}) ptrace.SpanEvent { +func getSpanEvent(name string, initialAttributes map[string]any) ptrace.SpanEvent { spanEvent := ptrace.NewSpanEvent() spanEvent.SetName(name) spanEvent.SetTimestamp(defaultSpanEventTime) @@ -772,27 +772,27 @@ func getSpanEvent(name string, initialAttributes map[string]interface{}) ptrace. } // Returns a default server span -func getServerSpan(spanName string, initialAttributes map[string]interface{}) ptrace.Span { +func getServerSpan(spanName string, initialAttributes map[string]any) ptrace.Span { return getSpan(spanName, ptrace.SpanKindServer, initialAttributes) } // Returns a default client span -func getClientSpan(spanName string, initialAttributes map[string]interface{}) ptrace.Span { +func getClientSpan(spanName string, initialAttributes map[string]any) ptrace.Span { return getSpan(spanName, ptrace.SpanKindClient, initialAttributes) } // Returns a default consumer span -func getConsumerSpan(spanName string, initialAttributes map[string]interface{}) ptrace.Span { +func getConsumerSpan(spanName string, initialAttributes map[string]any) ptrace.Span { return getSpan(spanName, ptrace.SpanKindConsumer, initialAttributes) } // Returns a default producer span -func getProducerSpan(spanName string, initialAttributes map[string]interface{}) ptrace.Span { +func getProducerSpan(spanName string, initialAttributes map[string]any) ptrace.Span { return getSpan(spanName, ptrace.SpanKindProducer, initialAttributes) } // Returns a default internal span -func getInternalSpan(spanName string, initialAttributes map[string]interface{}) ptrace.Span { +func getInternalSpan(spanName string, initialAttributes map[string]any) ptrace.Span { return getSpan(spanName, ptrace.SpanKindInternal, initialAttributes) } @@ -841,7 +841,7 @@ func getDefaultMessagingProducerSpan() ptrace.Span { func getDefaultInternalSpan() ptrace.Span { return getInternalSpan( defaultInternalSpanName, - map[string]interface{}{}) + map[string]any{}) } // Returns a default Resource diff --git a/exporter/azuremonitorexporter/traceexporter_test.go b/exporter/azuremonitorexporter/traceexporter_test.go index 61cc761b25c8..aa0ae5aedab2 100644 --- a/exporter/azuremonitorexporter/traceexporter_test.go +++ b/exporter/azuremonitorexporter/traceexporter_test.go @@ -73,10 +73,10 @@ func TestExporterTraceDataCallbackSingleSpanWithSpanEvents(t *testing.T) { ilss := rs.ScopeSpans().AppendEmpty() scope.CopyTo(ilss.Scope()) - spanEvent1 := getSpanEvent("foo", map[string]interface{}{"foo": "bar"}) + spanEvent1 := getSpanEvent("foo", map[string]any{"foo": "bar"}) spanEvent1.CopyTo(span.Events().AppendEmpty()) - spanEvent2 := getSpanEvent("bar", map[string]interface{}{"bar": "baz"}) + spanEvent2 := getSpanEvent("bar", map[string]any{"bar": "baz"}) spanEvent2.CopyTo(span.Events().AppendEmpty()) span.CopyTo(ilss.Spans().AppendEmpty()) diff --git a/exporter/carbonexporter/metricdata_to_plaintext_test.go b/exporter/carbonexporter/metricdata_to_plaintext_test.go index fe4fe5e82a86..1fb08ccd9637 100644 --- a/exporter/carbonexporter/metricdata_to_plaintext_test.go +++ b/exporter/carbonexporter/metricdata_to_plaintext_test.go @@ -232,7 +232,7 @@ func TestToPlaintext(t *testing.T) { ms.At(0).SetEmptyHistogram().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative) dp := ms.At(0).SetEmptyHistogram().DataPoints().AppendEmpty() dp.SetTimestamp(pcommon.NewTimestampFromTime(tsUnix)) - assert.NoError(t, dp.Attributes().FromRaw(map[string]interface{}{"k0": "v0", "k1": "v1"})) + assert.NoError(t, dp.Attributes().FromRaw(map[string]any{"k0": "v0", "k1": "v1"})) dp.SetCount(distributionCount) dp.SetSum(distributionSum) dp.ExplicitBounds().FromRaw(distributionBounds) @@ -255,7 +255,7 @@ func TestToPlaintext(t *testing.T) { ms.AppendEmpty().SetName("summary") dp := ms.At(0).SetEmptySummary().DataPoints().AppendEmpty() dp.SetTimestamp(pcommon.NewTimestampFromTime(tsUnix)) - assert.NoError(t, dp.Attributes().FromRaw(map[string]interface{}{"k0": "v0", "k1": "v1"})) + assert.NoError(t, dp.Attributes().FromRaw(map[string]any{"k0": "v0", "k1": "v1"})) dp.SetCount(summaryCount) dp.SetSum(summarySum) for i := range summaryQuantiles { diff --git a/exporter/datadogexporter/config_test.go b/exporter/datadogexporter/config_test.go index 9bdabdfd2ba7..2d6ae5005230 100644 --- a/exporter/datadogexporter/config_test.go +++ b/exporter/datadogexporter/config_test.go @@ -130,9 +130,9 @@ func TestUnmarshal(t *testing.T) { }{ { name: "invalid cumulative monotonic mode", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "metrics": map[string]interface{}{ - "sums": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "metrics": map[string]any{ + "sums": map[string]any{ "cumulative_monotonic_mode": "invalid_mode", }, }, @@ -141,8 +141,8 @@ func TestUnmarshal(t *testing.T) { }, { name: "invalid host metadata hostname source", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "host_metadata": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "host_metadata": map[string]any{ "hostname_source": "invalid_source", }, }), @@ -150,9 +150,9 @@ func TestUnmarshal(t *testing.T) { }, { name: "invalid summary mode", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "metrics": map[string]interface{}{ - "summaries": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "metrics": map[string]any{ + "summaries": map[string]any{ "mode": "invalid_mode", }, }, @@ -161,8 +161,8 @@ func TestUnmarshal(t *testing.T) { }, { name: "metrics::send_monotonic_counter custom error", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "metrics": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "metrics": map[string]any{ "send_monotonic_counter": true, }, }), @@ -170,29 +170,29 @@ func TestUnmarshal(t *testing.T) { }, { name: "tags custom error", - configMap: confmap.NewFromStringMap(map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ "tags": []string{}, }), err: "\"tags\" was removed in favor of \"host_metadata::tags\". See https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/9099", }, { name: "send_metadata custom error", - configMap: confmap.NewFromStringMap(map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ "send_metadata": false, }), err: "\"send_metadata\" was removed in favor of \"host_metadata::enabled\". See https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/9099", }, { name: "use_resource_metadata custom error", - configMap: confmap.NewFromStringMap(map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ "use_resource_metadata": false, }), err: "\"use_resource_metadata\" was removed in favor of \"host_metadata::hostname_source\". See https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/9099", }, { name: "metrics::report_quantiles custom error", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "metrics": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "metrics": map[string]any{ "report_quantiles": true, }, }), @@ -200,8 +200,8 @@ func TestUnmarshal(t *testing.T) { }, { name: "instrumentation_library_metadata_as_tags custom error", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "metrics": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "metrics": map[string]any{ "instrumentation_library_metadata_as_tags": true, }, }), @@ -209,8 +209,8 @@ func TestUnmarshal(t *testing.T) { }, { name: "Empty metric endpoint", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "metrics": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "metrics": map[string]any{ "endpoint": "", }, }), @@ -218,8 +218,8 @@ func TestUnmarshal(t *testing.T) { }, { name: "Empty trace endpoint", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "traces": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "traces": map[string]any{ "endpoint": "", }, }), @@ -227,8 +227,8 @@ func TestUnmarshal(t *testing.T) { }, { name: "Empty log endpoint", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "logs": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "logs": map[string]any{ "endpoint": "", }, }), @@ -236,9 +236,9 @@ func TestUnmarshal(t *testing.T) { }, { name: "invalid initial cumulative monotonic value mode", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "metrics": map[string]interface{}{ - "sums": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "metrics": map[string]any{ + "sums": map[string]any{ "initial_cumulative_monotonic_value": "invalid_mode", }, }, @@ -247,9 +247,9 @@ func TestUnmarshal(t *testing.T) { }, { name: "initial cumulative monotonic value mode set with raw_value", - configMap: confmap.NewFromStringMap(map[string]interface{}{ - "metrics": map[string]interface{}{ - "sums": map[string]interface{}{ + configMap: confmap.NewFromStringMap(map[string]any{ + "metrics": map[string]any{ + "sums": map[string]any{ "cumulative_monotonic_mode": "raw_value", "initial_cumulative_monotonic_value": "drop", }, diff --git a/exporter/datadogexporter/internal/hostmetadata/internal/gohai/processes.go b/exporter/datadogexporter/internal/hostmetadata/internal/gohai/processes.go index b6283bc7e83e..2d2fb9803179 100644 --- a/exporter/datadogexporter/internal/hostmetadata/internal/gohai/processes.go +++ b/exporter/datadogexporter/internal/hostmetadata/internal/gohai/processes.go @@ -20,8 +20,8 @@ func NewProcessesPayload(hostname string, logger *zap.Logger) *gohai.ProcessesPa return nil } - processesPayload := map[string]interface{}{ - "snaps": []interface{}{proc}, + processesPayload := map[string]any{ + "snaps": []any{proc}, } return &gohai.ProcessesPayload{ Processes: processesPayload, diff --git a/exporter/datadogexporter/internal/logs/sender_test.go b/exporter/datadogexporter/internal/logs/sender_test.go index b07906109233..fe95e1360162 100644 --- a/exporter/datadogexporter/internal/logs/sender_test.go +++ b/exporter/datadogexporter/internal/logs/sender_test.go @@ -35,7 +35,7 @@ func TestSubmitLogs(t *testing.T) { Hostname: datadog.PtrString("hostname"), Message: "log 1", Service: datadog.PtrString("server"), - UnparsedObject: map[string]interface{}{ + UnparsedObject: map[string]any{ "ddsource": "golang", "ddtags": "tag1:true", "hostname": "hostname", @@ -48,7 +48,7 @@ func TestSubmitLogs(t *testing.T) { Hostname: datadog.PtrString("hostname"), Message: "log 2", Service: datadog.PtrString("server"), - UnparsedObject: map[string]interface{}{ + UnparsedObject: map[string]any{ "ddsource": "golang", "ddtags": "tag1:true", "hostname": "hostname", @@ -75,7 +75,7 @@ func TestSubmitLogs(t *testing.T) { Hostname: datadog.PtrString("hostname"), Message: "log 1", Service: datadog.PtrString("server"), - UnparsedObject: map[string]interface{}{ + UnparsedObject: map[string]any{ "ddsource": "golang", "ddtags": "tag1:true", "hostname": "hostname", @@ -88,7 +88,7 @@ func TestSubmitLogs(t *testing.T) { Hostname: datadog.PtrString("hostname"), Message: "log 2", Service: datadog.PtrString("server"), - UnparsedObject: map[string]interface{}{ + UnparsedObject: map[string]any{ "ddsource": "golang", "ddtags": "tag2:true", "hostname": "hostname", @@ -118,7 +118,7 @@ func TestSubmitLogs(t *testing.T) { Hostname: datadog.PtrString("hostname"), Message: "log 1", Service: datadog.PtrString("server"), - UnparsedObject: map[string]interface{}{ + UnparsedObject: map[string]any{ "ddsource": "golang", "ddtags": "tag1:true", "hostname": "hostname", @@ -131,7 +131,7 @@ func TestSubmitLogs(t *testing.T) { Hostname: datadog.PtrString("hostname"), Message: "log 2", Service: datadog.PtrString("server"), - UnparsedObject: map[string]interface{}{ + UnparsedObject: map[string]any{ "ddsource": "golang", "ddtags": "tag1:true", "hostname": "hostname", @@ -144,7 +144,7 @@ func TestSubmitLogs(t *testing.T) { Hostname: datadog.PtrString("hostname"), Message: "log 3", Service: datadog.PtrString("server"), - UnparsedObject: map[string]interface{}{ + UnparsedObject: map[string]any{ "ddsource": "golang", "ddtags": "tag2:true", "hostname": "hostname", @@ -157,7 +157,7 @@ func TestSubmitLogs(t *testing.T) { Hostname: datadog.PtrString("hostname"), Message: "log 4", Service: datadog.PtrString("server"), - UnparsedObject: map[string]interface{}{ + UnparsedObject: map[string]any{ "ddsource": "golang", "ddtags": "tag2:true", "hostname": "hostname", diff --git a/exporter/datadogexporter/internal/testutil/logs.go b/exporter/datadogexporter/internal/testutil/logs.go index a074d5ce37d8..83799437bd7a 100644 --- a/exporter/datadogexporter/internal/testutil/logs.go +++ b/exporter/datadogexporter/internal/testutil/logs.go @@ -13,7 +13,7 @@ import ( ) // JSONLogs is the type for the array of processed JSON log data from each request -type JSONLogs []map[string]interface{} +type JSONLogs []map[string]any // HasDDTag returns true if every log has the given ddtags func (jsonLogs *JSONLogs) HasDDTag(ddtags string) bool { diff --git a/exporter/datadogexporter/internal/testutil/test_utils_test.go b/exporter/datadogexporter/internal/testutil/test_utils_test.go index f2eecd2fcd32..2ddd68a0803d 100644 --- a/exporter/datadogexporter/internal/testutil/test_utils_test.go +++ b/exporter/datadogexporter/internal/testutil/test_utils_test.go @@ -38,16 +38,16 @@ func TestNewGaugeMetrics(t *testing.T) { require.Equal(t, all.Len(), 2) require.Equal(t, all.At(0).Name(), "metric1") require.Equal(t, all.At(0).Gauge().DataPoints().At(0).DoubleValue(), float64(1)) - require.EqualValues(t, all.At(0).Gauge().DataPoints().At(0).Attributes().AsRaw(), map[string]interface{}{ + require.EqualValues(t, all.At(0).Gauge().DataPoints().At(0).Attributes().AsRaw(), map[string]any{ "a": "b", "c": "d", "e": "f", }) require.Equal(t, all.At(1).Name(), "metric2") require.Equal(t, all.At(1).Gauge().DataPoints().At(0).DoubleValue(), float64(2)) - require.EqualValues(t, all.At(1).Gauge().DataPoints().At(0).Attributes().AsRaw(), map[string]interface{}{ + require.EqualValues(t, all.At(1).Gauge().DataPoints().At(0).Attributes().AsRaw(), map[string]any{ "x": "y", "z": "q", "w": "e", }) require.Equal(t, all.At(1).Gauge().DataPoints().At(1).DoubleValue(), float64(3)) - require.EqualValues(t, all.At(1).Gauge().DataPoints().At(1).Attributes().AsRaw(), map[string]interface{}{ + require.EqualValues(t, all.At(1).Gauge().DataPoints().At(1).Attributes().AsRaw(), map[string]any{ "w": "n", }) } diff --git a/exporter/datadogexporter/metrics_exporter_test.go b/exporter/datadogexporter/metrics_exporter_test.go index 484b58f22b56..8dcf3d792a47 100644 --- a/exporter/datadogexporter/metrics_exporter_test.go +++ b/exporter/datadogexporter/metrics_exporter_test.go @@ -99,7 +99,7 @@ func Test_metricsExporter_PushMetricsData(t *testing.T) { source source.Source hostTags []string histogramMode HistogramMode - expectedSeries map[string]interface{} + expectedSeries map[string]any expectedSketchPayload *gogen.SketchPayload expectedErr error expectedStats []*pb.ClientStatsPayload @@ -122,49 +122,49 @@ func Test_metricsExporter_PushMetricsData(t *testing.T) { }, histogramMode: HistogramModeCounters, hostTags: []string{"key1:value1", "key2:value2"}, - expectedSeries: map[string]interface{}{ - "series": []interface{}{ - map[string]interface{}{ + expectedSeries: map[string]any{ + "series": []any{ + map[string]any{ "metric": "int.gauge", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(222)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(222)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.system.filesystem.utilization", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(333)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(333)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "double.histogram.bucket", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(2)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(2)}}, "type": float64(datadogV2.METRICINTAKETYPE_COUNT), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"lower_bound:-inf", "upper_bound:0", "env:dev"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"lower_bound:-inf", "upper_bound:0", "env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "double.histogram.bucket", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(18)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(18)}}, "type": float64(datadogV2.METRICINTAKETYPE_COUNT), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"lower_bound:0", "upper_bound:inf", "env:dev"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"lower_bound:0", "upper_bound:inf", "env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "system.disk.in_use", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(333)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(333)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.datadog_exporter.metrics.running", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(1)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(1)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"version:latest", "command:otelcol"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"version:latest", "command:otelcol"}, }, }, }, @@ -177,35 +177,35 @@ func Test_metricsExporter_PushMetricsData(t *testing.T) { }, histogramMode: HistogramModeDistributions, hostTags: []string{"key1:value1", "key2:value2"}, - expectedSeries: map[string]interface{}{ - "series": []interface{}{ - map[string]interface{}{ + expectedSeries: map[string]any{ + "series": []any{ + map[string]any{ "metric": "int.gauge", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(222)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(222)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.system.filesystem.utilization", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(333)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(333)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "system.disk.in_use", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(333)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(333)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.datadog_exporter.metrics.running", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(1)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(1)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"version:latest", "command:otelcol"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"version:latest", "command:otelcol"}, }, }, }, @@ -236,49 +236,49 @@ func Test_metricsExporter_PushMetricsData(t *testing.T) { }, histogramMode: HistogramModeCounters, hostTags: []string{"key1:value1", "key2:value2"}, - expectedSeries: map[string]interface{}{ - "series": []interface{}{ - map[string]interface{}{ + expectedSeries: map[string]any{ + "series": []any{ + map[string]any{ "metric": "int.gauge", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(222)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(222)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev", "key1:value1", "key2:value2"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.system.filesystem.utilization", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(333)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(333)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev", "key1:value1", "key2:value2"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "double.histogram.bucket", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(2)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(2)}}, "type": float64(datadogV2.METRICINTAKETYPE_COUNT), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"lower_bound:-inf", "upper_bound:0", "env:dev", "key1:value1", "key2:value2"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"lower_bound:-inf", "upper_bound:0", "env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "double.histogram.bucket", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(18)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(18)}}, "type": float64(datadogV2.METRICINTAKETYPE_COUNT), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"lower_bound:0", "upper_bound:inf", "env:dev", "key1:value1", "key2:value2"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"lower_bound:0", "upper_bound:inf", "env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "system.disk.in_use", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(333)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(333)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"env:dev", "key1:value1", "key2:value2"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.datadog_exporter.metrics.running", - "points": []interface{}{map[string]interface{}{"timestamp": float64(0), "value": float64(1)}}, + "points": []any{map[string]any{"timestamp": float64(0), "value": float64(1)}}, "type": float64(datadogV2.METRICINTAKETYPE_GAUGE), - "resources": []interface{}{map[string]interface{}{"name": "test-host", "type": "host"}}, - "tags": []interface{}{"version:latest", "command:otelcol", "key1:value1", "key2:value2"}, + "resources": []any{map[string]any{"name": "test-host", "type": "host"}}, + "tags": []any{"version:latest", "command:otelcol", "key1:value1", "key2:value2"}, }, }, }, @@ -338,7 +338,7 @@ func Test_metricsExporter_PushMetricsData(t *testing.T) { reader, err := gzip.NewReader(buf) assert.NoError(t, err) dec := json.NewDecoder(reader) - var actual map[string]interface{} + var actual map[string]any assert.NoError(t, dec.Decode(&actual)) assert.EqualValues(t, tt.expectedSeries, actual) } @@ -427,7 +427,7 @@ func Test_metricsExporter_PushMetricsData_Zorkian(t *testing.T) { source source.Source hostTags []string histogramMode HistogramMode - expectedSeries map[string]interface{} + expectedSeries map[string]any expectedSketchPayload *gogen.SketchPayload expectedErr error expectedStats []*pb.ClientStatsPayload @@ -450,49 +450,49 @@ func Test_metricsExporter_PushMetricsData_Zorkian(t *testing.T) { }, histogramMode: HistogramModeCounters, hostTags: []string{"key1:value1", "key2:value2"}, - expectedSeries: map[string]interface{}{ - "series": []interface{}{ - map[string]interface{}{ + expectedSeries: map[string]any{ + "series": []any{ + map[string]any{ "metric": "int.gauge", - "points": []interface{}{[]interface{}{float64(0), float64(222)}}, + "points": []any{[]any{float64(0), float64(222)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.system.filesystem.utilization", - "points": []interface{}{[]interface{}{float64(0), float64(333)}}, + "points": []any{[]any{float64(0), float64(333)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "double.histogram.bucket", - "points": []interface{}{[]interface{}{float64(0), float64(2)}}, + "points": []any{[]any{float64(0), float64(2)}}, "type": "count", "host": "test-host", - "tags": []interface{}{"lower_bound:-inf", "upper_bound:0", "env:dev"}, + "tags": []any{"lower_bound:-inf", "upper_bound:0", "env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "double.histogram.bucket", - "points": []interface{}{[]interface{}{float64(0), float64(18)}}, + "points": []any{[]any{float64(0), float64(18)}}, "type": "count", "host": "test-host", - "tags": []interface{}{"lower_bound:0", "upper_bound:inf", "env:dev"}, + "tags": []any{"lower_bound:0", "upper_bound:inf", "env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "system.disk.in_use", - "points": []interface{}{[]interface{}{float64(0), float64(333)}}, + "points": []any{[]any{float64(0), float64(333)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.datadog_exporter.metrics.running", - "points": []interface{}{[]interface{}{float64(0), float64(1)}}, + "points": []any{[]any{float64(0), float64(1)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"version:latest", "command:otelcol"}, + "tags": []any{"version:latest", "command:otelcol"}, }, }, }, @@ -505,35 +505,35 @@ func Test_metricsExporter_PushMetricsData_Zorkian(t *testing.T) { }, histogramMode: HistogramModeDistributions, hostTags: []string{"key1:value1", "key2:value2"}, - expectedSeries: map[string]interface{}{ - "series": []interface{}{ - map[string]interface{}{ + expectedSeries: map[string]any{ + "series": []any{ + map[string]any{ "metric": "int.gauge", - "points": []interface{}{[]interface{}{float64(0), float64(222)}}, + "points": []any{[]any{float64(0), float64(222)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.system.filesystem.utilization", - "points": []interface{}{[]interface{}{float64(0), float64(333)}}, + "points": []any{[]any{float64(0), float64(333)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "system.disk.in_use", - "points": []interface{}{[]interface{}{float64(0), float64(333)}}, + "points": []any{[]any{float64(0), float64(333)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.datadog_exporter.metrics.running", - "points": []interface{}{[]interface{}{float64(0), float64(1)}}, + "points": []any{[]any{float64(0), float64(1)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"version:latest", "command:otelcol"}, + "tags": []any{"version:latest", "command:otelcol"}, }, }, }, @@ -564,49 +564,49 @@ func Test_metricsExporter_PushMetricsData_Zorkian(t *testing.T) { }, histogramMode: HistogramModeCounters, hostTags: []string{"key1:value1", "key2:value2"}, - expectedSeries: map[string]interface{}{ - "series": []interface{}{ - map[string]interface{}{ + expectedSeries: map[string]any{ + "series": []any{ + map[string]any{ "metric": "int.gauge", - "points": []interface{}{[]interface{}{float64(0), float64(222)}}, + "points": []any{[]any{float64(0), float64(222)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev", "key1:value1", "key2:value2"}, + "tags": []any{"env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.system.filesystem.utilization", - "points": []interface{}{[]interface{}{float64(0), float64(333)}}, + "points": []any{[]any{float64(0), float64(333)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev", "key1:value1", "key2:value2"}, + "tags": []any{"env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "double.histogram.bucket", - "points": []interface{}{[]interface{}{float64(0), float64(2)}}, + "points": []any{[]any{float64(0), float64(2)}}, "type": "count", "host": "test-host", - "tags": []interface{}{"lower_bound:-inf", "upper_bound:0", "env:dev", "key1:value1", "key2:value2"}, + "tags": []any{"lower_bound:-inf", "upper_bound:0", "env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "double.histogram.bucket", - "points": []interface{}{[]interface{}{float64(0), float64(18)}}, + "points": []any{[]any{float64(0), float64(18)}}, "type": "count", "host": "test-host", - "tags": []interface{}{"lower_bound:0", "upper_bound:inf", "env:dev", "key1:value1", "key2:value2"}, + "tags": []any{"lower_bound:0", "upper_bound:inf", "env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "system.disk.in_use", - "points": []interface{}{[]interface{}{float64(0), float64(333)}}, + "points": []any{[]any{float64(0), float64(333)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev", "key1:value1", "key2:value2"}, + "tags": []any{"env:dev", "key1:value1", "key2:value2"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.datadog_exporter.metrics.running", - "points": []interface{}{[]interface{}{float64(0), float64(1)}}, + "points": []any{[]any{float64(0), float64(1)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"version:latest", "command:otelcol", "key1:value1", "key2:value2"}, + "tags": []any{"version:latest", "command:otelcol", "key1:value1", "key2:value2"}, }, }, }, @@ -621,35 +621,35 @@ func Test_metricsExporter_PushMetricsData_Zorkian(t *testing.T) { }, histogramMode: HistogramModeDistributions, hostTags: []string{"key1:value1", "key2:value2"}, - expectedSeries: map[string]interface{}{ - "series": []interface{}{ - map[string]interface{}{ + expectedSeries: map[string]any{ + "series": []any{ + map[string]any{ "metric": "int.gauge", - "points": []interface{}{[]interface{}{float64(0), float64(222)}}, + "points": []any{[]any{float64(0), float64(222)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.system.filesystem.utilization", - "points": []interface{}{[]interface{}{float64(0), float64(333)}}, + "points": []any{[]any{float64(0), float64(333)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "system.disk.in_use", - "points": []interface{}{[]interface{}{float64(0), float64(333)}}, + "points": []any{[]any{float64(0), float64(333)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"env:dev"}, + "tags": []any{"env:dev"}, }, - map[string]interface{}{ + map[string]any{ "metric": "otel.datadog_exporter.metrics.running", - "points": []interface{}{[]interface{}{float64(0), float64(1)}}, + "points": []any{[]any{float64(0), float64(1)}}, "type": "gauge", "host": "test-host", - "tags": []interface{}{"version:latest", "command:otelcol"}, + "tags": []any{"version:latest", "command:otelcol"}, }, }, }, @@ -721,7 +721,7 @@ func Test_metricsExporter_PushMetricsData_Zorkian(t *testing.T) { assert.Equal(t, "application/json", seriesRecorder.Header.Get("Content-Type")) assert.Equal(t, "otelcol/latest", seriesRecorder.Header.Get("User-Agent")) assert.NoError(t, err) - var actual map[string]interface{} + var actual map[string]any assert.NoError(t, json.Unmarshal(seriesRecorder.ByteBody, &actual)) assert.EqualValues(t, tt.expectedSeries, actual) } diff --git a/exporter/datadogexporter/traces_exporter_test.go b/exporter/datadogexporter/traces_exporter_test.go index 73de0d506d88..4d177a0f34cf 100644 --- a/exporter/datadogexporter/traces_exporter_test.go +++ b/exporter/datadogexporter/traces_exporter_test.go @@ -38,59 +38,59 @@ func TestMain(m *testing.M) { type testlogger struct{} // Trace implements Logger. -func (testlogger) Trace(_ ...interface{}) {} +func (testlogger) Trace(_ ...any) {} // Tracef implements Logger. -func (testlogger) Tracef(_ string, _ ...interface{}) {} +func (testlogger) Tracef(_ string, _ ...any) {} // Debug implements Logger. -func (testlogger) Debug(v ...interface{}) { fmt.Println("DEBUG", fmt.Sprint(v...)) } +func (testlogger) Debug(v ...any) { fmt.Println("DEBUG", fmt.Sprint(v...)) } // Debugf implements Logger. -func (testlogger) Debugf(format string, params ...interface{}) { +func (testlogger) Debugf(format string, params ...any) { fmt.Println("DEBUG", fmt.Sprintf(format, params...)) } // Info implements Logger. -func (testlogger) Info(v ...interface{}) { fmt.Println("INFO", fmt.Sprint(v...)) } +func (testlogger) Info(v ...any) { fmt.Println("INFO", fmt.Sprint(v...)) } // Infof implements Logger. -func (testlogger) Infof(format string, params ...interface{}) { +func (testlogger) Infof(format string, params ...any) { fmt.Println("INFO", fmt.Sprintf(format, params...)) } // Warn implements Logger. -func (testlogger) Warn(v ...interface{}) error { +func (testlogger) Warn(v ...any) error { fmt.Println("WARN", fmt.Sprint(v...)) return nil } // Warnf implements Logger. -func (testlogger) Warnf(format string, params ...interface{}) error { +func (testlogger) Warnf(format string, params ...any) error { fmt.Println("WARN", fmt.Sprintf(format, params...)) return nil } // Error implements Logger. -func (testlogger) Error(v ...interface{}) error { +func (testlogger) Error(v ...any) error { fmt.Println("ERROR", fmt.Sprint(v...)) return nil } // Errorf implements Logger. -func (testlogger) Errorf(format string, params ...interface{}) error { +func (testlogger) Errorf(format string, params ...any) error { fmt.Println("ERROR", fmt.Sprintf(format, params...)) return nil } // Critical implements Logger. -func (testlogger) Critical(v ...interface{}) error { +func (testlogger) Critical(v ...any) error { fmt.Println("CRITICAL", fmt.Sprint(v...)) return nil } // Criticalf implements Logger. -func (testlogger) Criticalf(format string, params ...interface{}) error { +func (testlogger) Criticalf(format string, params ...any) error { fmt.Println("CRITICAL", fmt.Sprintf(format, params...)) return nil } @@ -176,24 +176,24 @@ func TestTracesSource(t *testing.T) { return *p.Series[0].Resources[0].Name, p.Series[0].Tags } for _, tt := range []struct { - attrs map[string]interface{} + attrs map[string]any host string tags []string }{ { - attrs: map[string]interface{}{}, + attrs: map[string]any{}, host: "fallbackHostname", tags: []string{"version:latest", "command:otelcol"}, }, { - attrs: map[string]interface{}{ + attrs: map[string]any{ attributes.AttributeDatadogHostname: "customName", }, host: "customName", tags: []string{"version:latest", "command:otelcol"}, }, { - attrs: map[string]interface{}{ + attrs: map[string]any{ semconv.AttributeCloudProvider: semconv.AttributeCloudProviderAWS, semconv.AttributeCloudPlatform: semconv.AttributeCloudPlatformAWSECS, semconv.AttributeAWSECSTaskARN: "example-task-ARN", @@ -340,11 +340,11 @@ func simpleTraces() ptrace.Traces { return genTraces([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4}, nil) } -func simpleTracesWithAttributes(attrs map[string]interface{}) ptrace.Traces { +func simpleTracesWithAttributes(attrs map[string]any) ptrace.Traces { return genTraces([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4}, attrs) } -func genTraces(traceID pcommon.TraceID, attrs map[string]interface{}) ptrace.Traces { +func genTraces(traceID pcommon.TraceID, attrs map[string]any) ptrace.Traces { traces := ptrace.NewTraces() rspans := traces.ResourceSpans().AppendEmpty() span := rspans.ScopeSpans().AppendEmpty().Spans().AppendEmpty() diff --git a/exporter/datadogexporter/zaplogger.go b/exporter/datadogexporter/zaplogger.go index 6e9daf23e925..bd9e09ae1e85 100644 --- a/exporter/datadogexporter/zaplogger.go +++ b/exporter/datadogexporter/zaplogger.go @@ -13,63 +13,63 @@ import ( type zaplogger struct{ logger *zap.Logger } // Trace implements Logger. -func (z *zaplogger) Trace(_ ...interface{}) { /* N/A */ } +func (z *zaplogger) Trace(_ ...any) { /* N/A */ } // Tracef implements Logger. -func (z *zaplogger) Tracef(_ string, _ ...interface{}) { /* N/A */ } +func (z *zaplogger) Tracef(_ string, _ ...any) { /* N/A */ } // Debug implements Logger. -func (z *zaplogger) Debug(v ...interface{}) { +func (z *zaplogger) Debug(v ...any) { z.logger.Debug(fmt.Sprint(v...)) } // Debugf implements Logger. -func (z *zaplogger) Debugf(format string, params ...interface{}) { +func (z *zaplogger) Debugf(format string, params ...any) { z.logger.Debug(fmt.Sprintf(format, params...)) } // Info implements Logger. -func (z *zaplogger) Info(v ...interface{}) { +func (z *zaplogger) Info(v ...any) { z.logger.Info(fmt.Sprint(v...)) } // Infof implements Logger. -func (z *zaplogger) Infof(format string, params ...interface{}) { +func (z *zaplogger) Infof(format string, params ...any) { z.logger.Info(fmt.Sprintf(format, params...)) } // Warn implements Logger. -func (z *zaplogger) Warn(v ...interface{}) error { +func (z *zaplogger) Warn(v ...any) error { z.logger.Warn(fmt.Sprint(v...)) return nil } // Warnf implements Logger. -func (z *zaplogger) Warnf(format string, params ...interface{}) error { +func (z *zaplogger) Warnf(format string, params ...any) error { z.logger.Warn(fmt.Sprintf(format, params...)) return nil } // Error implements Logger. -func (z *zaplogger) Error(v ...interface{}) error { +func (z *zaplogger) Error(v ...any) error { z.logger.Error(fmt.Sprint(v...)) return nil } // Errorf implements Logger. -func (z *zaplogger) Errorf(format string, params ...interface{}) error { +func (z *zaplogger) Errorf(format string, params ...any) error { z.logger.Error(fmt.Sprintf(format, params...)) return nil } // Critical implements Logger. -func (z *zaplogger) Critical(v ...interface{}) error { +func (z *zaplogger) Critical(v ...any) error { z.logger.Error(fmt.Sprint(v...), zap.Bool("critical", true)) return nil } // Criticalf implements Logger. -func (z *zaplogger) Criticalf(format string, params ...interface{}) error { +func (z *zaplogger) Criticalf(format string, params ...any) error { z.logger.Error(fmt.Sprintf(format, params...), zap.Bool("critical", true)) return nil } diff --git a/exporter/datasetexporter/config_test.go b/exporter/datasetexporter/config_test.go index 44470519ad53..af99f0cf7f93 100644 --- a/exporter/datasetexporter/config_test.go +++ b/exporter/datasetexporter/config_test.go @@ -16,7 +16,7 @@ import ( func TestConfigUnmarshalUnknownAttributes(t *testing.T) { f := NewFactory() config := f.CreateDefaultConfig().(*Config) - configMap := confmap.NewFromStringMap(map[string]interface{}{ + configMap := confmap.NewFromStringMap(map[string]any{ "dataset_url": "https://example.com", "api_key": "secret", "unknown_attribute": "some value", @@ -32,7 +32,7 @@ func TestConfigUnmarshalUnknownAttributes(t *testing.T) { func TestConfigUseDefaults(t *testing.T) { f := NewFactory() config := f.CreateDefaultConfig().(*Config) - configMap := confmap.NewFromStringMap(map[string]interface{}{ + configMap := confmap.NewFromStringMap(map[string]any{ "dataset_url": "https://example.com", "api_key": "secret", }) @@ -148,7 +148,7 @@ func TestConfigString(t *testing.T) { func TestConfigUseProvidedExportResourceInfoValue(t *testing.T) { f := NewFactory() config := f.CreateDefaultConfig().(*Config) - configMap := confmap.NewFromStringMap(map[string]interface{}{ + configMap := confmap.NewFromStringMap(map[string]any{ "dataset_url": "https://example.com", "api_key": "secret", "logs": map[string]any{ @@ -163,7 +163,7 @@ func TestConfigUseProvidedExportResourceInfoValue(t *testing.T) { func TestConfigUseProvidedExportScopeInfoValue(t *testing.T) { f := NewFactory() config := f.CreateDefaultConfig().(*Config) - configMap := confmap.NewFromStringMap(map[string]interface{}{ + configMap := confmap.NewFromStringMap(map[string]any{ "dataset_url": "https://example.com", "api_key": "secret", "logs": map[string]any{ diff --git a/exporter/datasetexporter/datasetexporter.go b/exporter/datasetexporter/datasetexporter.go index 62e401e4228c..4767c588d4c4 100644 --- a/exporter/datasetexporter/datasetexporter.go +++ b/exporter/datasetexporter/datasetexporter.go @@ -86,21 +86,21 @@ func buildKey(prefix string, separator string, key string, depth int) string { return res } -func updateWithPrefixedValuesMap(target map[string]interface{}, prefix string, separator string, suffix string, source map[string]interface{}, depth int) { +func updateWithPrefixedValuesMap(target map[string]any, prefix string, separator string, suffix string, source map[string]any, depth int) { for k, v := range source { key := buildKey(prefix, separator, k, depth) updateWithPrefixedValues(target, key, separator, suffix, v, depth+1) } } -func updateWithPrefixedValuesArray(target map[string]interface{}, prefix string, separator string, suffix string, source []interface{}, depth int) { +func updateWithPrefixedValuesArray(target map[string]any, prefix string, separator string, suffix string, source []any, depth int) { for i, v := range source { key := buildKey(prefix, separator, strconv.FormatInt(int64(i), 10), depth) updateWithPrefixedValues(target, key, separator, suffix, v, depth+1) } } -func updateWithPrefixedValues(target map[string]interface{}, prefix string, separator string, suffix string, source interface{}, depth int) { +func updateWithPrefixedValues(target map[string]any, prefix string, separator string, suffix string, source any, depth int) { setValue := func() { for { // now the last value wins @@ -122,9 +122,9 @@ func updateWithPrefixedValues(target map[string]interface{}, prefix string, sepa } switch st.Kind() { case reflect.Map: - updateWithPrefixedValuesMap(target, prefix, separator, suffix, source.(map[string]interface{}), depth) + updateWithPrefixedValuesMap(target, prefix, separator, suffix, source.(map[string]any), depth) case reflect.Array, reflect.Slice: - updateWithPrefixedValuesArray(target, prefix, separator, suffix, source.([]interface{}), depth) + updateWithPrefixedValuesArray(target, prefix, separator, suffix, source.([]any), depth) default: setValue() } @@ -132,7 +132,7 @@ func updateWithPrefixedValues(target map[string]interface{}, prefix string, sepa func inferServerHost( resource pcommon.Resource, - attrs map[string]interface{}, + attrs map[string]any, serverHost string, ) string { // first use value from the attribute serverHost diff --git a/exporter/datasetexporter/logs_exporter.go b/exporter/datasetexporter/logs_exporter.go index f2a43f75d347..8ff1a98892e1 100644 --- a/exporter/datasetexporter/logs_exporter.go +++ b/exporter/datasetexporter/logs_exporter.go @@ -58,7 +58,7 @@ func createLogsExporter(ctx context.Context, set exporter.CreateSettings, config ) } -func buildBody(settings LogsSettings, attrs map[string]interface{}, value pcommon.Value) string { +func buildBody(settings LogsSettings, attrs map[string]any, value pcommon.Value) string { // The message / body is stored as part of the "message" field on the DataSet event. message := value.AsString() @@ -169,7 +169,7 @@ func buildEventFromLog( serverHost string, logSettings LogsSettings, ) *add_events.EventBundle { - attrs := make(map[string]interface{}) + attrs := make(map[string]any) event := add_events.Event{} observedTs := log.ObservedTimestamp().AsTime() @@ -231,7 +231,7 @@ func buildEventFromLog( return &add_events.EventBundle{ Event: &event, Thread: &add_events.Thread{Id: "TL", Name: "logs"}, - Log: &add_events.Log{Id: "LL", Attrs: map[string]interface{}{}}, + Log: &add_events.Log{Id: "LL", Attrs: map[string]any{}}, } } diff --git a/exporter/datasetexporter/logs_exporter_stress_test.go b/exporter/datasetexporter/logs_exporter_stress_test.go index 8f1fb045c2ef..60384308e380 100644 --- a/exporter/datasetexporter/logs_exporter_stress_test.go +++ b/exporter/datasetexporter/logs_exporter_stress_test.go @@ -63,7 +63,7 @@ func TestConsumeLogsManyLogsShouldSucceed(t *testing.T) { } wasSuccessful.Store(true) - payload, err := json.Marshal(map[string]interface{}{ + payload, err := json.Marshal(map[string]any{ "status": "success", "bytesCharged": 42, }) diff --git a/exporter/datasetexporter/logs_exporter_test.go b/exporter/datasetexporter/logs_exporter_test.go index a0a7f62f3929..49eb45b47740 100644 --- a/exporter/datasetexporter/logs_exporter_test.go +++ b/exporter/datasetexporter/logs_exporter_test.go @@ -106,7 +106,7 @@ func TestBuildBody(t *testing.T) { for _, tt := range tests { t.Run(tt.valueType, func(*testing.T) { - attrs := make(map[string]interface{}) + attrs := make(map[string]any) msg := buildBody(settings, attrs, tt.body) assert.Equal(t, tt.message, msg, tt.valueType) @@ -127,10 +127,10 @@ func TestBuildBodyMap(t *testing.T) { if assert.NoError(t, err) { settings := newDefaultLogsSettings() settings.DecomposeComplexMessageField = true - attrs := make(map[string]interface{}) + attrs := make(map[string]any) msg := buildBody(settings, attrs, m) - expectedAttrs := make(map[string]interface{}) + expectedAttrs := make(map[string]any) expectedAttrs["body.map.scalar"] = "scalar-value" expectedAttrs["body.map.map.m1"] = "v1" expectedAttrs["body.map.map.m2"] = "v2" @@ -152,7 +152,7 @@ var testLThread = &add_events.Thread{ var testLLog = &add_events.Log{ Id: "LL", - Attrs: map[string]interface{}{}, + Attrs: map[string]any{}, } var testServerHost = "foo" @@ -163,7 +163,7 @@ var testLEventRaw = &add_events.Event{ Sev: 3, Ts: "1581452773000000789", ServerHost: testServerHost, - Attrs: map[string]interface{}{ + Attrs: map[string]any{ "app": "server", "instance_num": int64(1), "dropped_attributes_count": uint32(1), @@ -179,7 +179,7 @@ var testLEventRawWithScopeInfo = &add_events.Event{ Sev: 3, Ts: "1581452773000000789", ServerHost: testServerHost, - Attrs: map[string]interface{}{ + Attrs: map[string]any{ "app": "server", "instance_num": int64(1), "dropped_attributes_count": uint32(1), @@ -195,7 +195,7 @@ var testLEventReq = &add_events.Event{ Log: testLEventRaw.Log, Sev: testLEventRaw.Sev, Ts: testLEventRaw.Ts, - Attrs: map[string]interface{}{ + Attrs: map[string]any{ add_events.AttrOrigServerHost: testServerHost, "app": "server", "instance_num": float64(1), @@ -790,7 +790,7 @@ func TestConsumeLogsShouldSucceed(t *testing.T) { assert.NoError(t, err, "Error reading request: %v", err) wasSuccessful.Store(true) - payload, err := json.Marshal(map[string]interface{}{ + payload, err := json.Marshal(map[string]any{ "status": "success", "bytesCharged": 42, }) @@ -895,7 +895,7 @@ func TestConsumeLogsShouldSucceed(t *testing.T) { Log: testLEventReq.Log, Sev: testLEventReq.Sev, Ts: testLEventReq.Ts, - Attrs: map[string]interface{}{ + Attrs: map[string]any{ add_events.AttrOrigServerHost: testServerHost, "app": "server", "instance_num": float64(1), @@ -913,7 +913,7 @@ func TestConsumeLogsShouldSucceed(t *testing.T) { Log: testLEventReq.Log, Sev: testLEventReq.Sev, Ts: testLEventReq.Ts, - Attrs: map[string]interface{}{ + Attrs: map[string]any{ add_events.AttrOrigServerHost: "serverHostFromAttribute", "app": "server", "instance_num": float64(1), @@ -932,7 +932,7 @@ func TestConsumeLogsShouldSucceed(t *testing.T) { Log: testLEventReq.Log, Sev: testLEventReq.Sev, Ts: testLEventReq.Ts, - Attrs: map[string]interface{}{ + Attrs: map[string]any{ add_events.AttrOrigServerHost: "serverHostFromResourceServer", "app": "server", "instance_num": float64(1), @@ -952,7 +952,7 @@ func TestConsumeLogsShouldSucceed(t *testing.T) { Log: testLEventReq.Log, Sev: testLEventReq.Sev, Ts: testLEventReq.Ts, - Attrs: map[string]interface{}{ + Attrs: map[string]any{ add_events.AttrOrigServerHost: "serverHostFromResourceHost", "app": "server", "instance_num": float64(1), @@ -971,7 +971,7 @@ func TestConsumeLogsShouldSucceed(t *testing.T) { Log: testLEventReq.Log, Sev: testLEventReq.Sev, Ts: testLEventReq.Ts, - Attrs: map[string]interface{}{ + Attrs: map[string]any{ add_events.AttrOrigServerHost: testServerHost, "app": "server", "instance_num": float64(1), diff --git a/exporter/datasetexporter/traces_exporter.go b/exporter/datasetexporter/traces_exporter.go index 01429477846b..5ee1024e591c 100644 --- a/exporter/datasetexporter/traces_exporter.go +++ b/exporter/datasetexporter/traces_exporter.go @@ -46,7 +46,7 @@ func buildEventFromSpan( span := bundle.span resource := bundle.resource - attrs := make(map[string]interface{}) + attrs := make(map[string]any) event := add_events.Event{ Sev: int(plog.SeverityNumberInfo), Ts: fmt.Sprintf("%d", span.StartTimestamp().AsTime().UnixNano()), @@ -84,7 +84,7 @@ func buildEventFromSpan( return &add_events.EventBundle{ Event: &event, Thread: &add_events.Thread{Id: "TT", Name: "traces"}, - Log: &add_events.Log{Id: "LT", Attrs: map[string]interface{}{}}, + Log: &add_events.Log{Id: "LT", Attrs: map[string]any{}}, } } @@ -98,7 +98,7 @@ const ( Process = ResourceType("process") ) -func updateResource(attrs map[string]interface{}, resource map[string]any) { +func updateResource(attrs map[string]any, resource map[string]any) { // first detect, whether there is key service.name // if it's there, we are done name, found := resource["service.name"] diff --git a/exporter/datasetexporter/traces_exporter_test.go b/exporter/datasetexporter/traces_exporter_test.go index 4f268ff7bb41..c265856b28bf 100644 --- a/exporter/datasetexporter/traces_exporter_test.go +++ b/exporter/datasetexporter/traces_exporter_test.go @@ -46,7 +46,7 @@ func generateTEvent1Raw() *add_events.Event { Sev: 9, Ts: "1581452772000000321", ServerHost: "foo", - Attrs: map[string]interface{}{ + Attrs: map[string]any{ "sca:schemVer": 1, "sca:schema": "tracing", "sca:type": "span", @@ -75,7 +75,7 @@ func generateTEvent2Raw() *add_events.Event { Sev: 9, Ts: "1581452772000000321", ServerHost: "foo", - Attrs: map[string]interface{}{ + Attrs: map[string]any{ "sca:schemVer": 1, "sca:schema": "tracing", "sca:type": "span", @@ -105,7 +105,7 @@ func generateTEvent3Raw() *add_events.Event { Sev: 9, Ts: "1581452772000000321", ServerHost: "valServerHost", - Attrs: map[string]interface{}{ + Attrs: map[string]any{ "sca:schemVer": 1, "sca:schema": "tracing", "sca:type": "span", @@ -136,7 +136,7 @@ var testTThread = &add_events.Thread{ var testTLog = &add_events.Log{ Id: "LT", - Attrs: map[string]interface{}{}, + Attrs: map[string]any{}, } func TestBuildEventFromSpanOne(t *testing.T) { @@ -173,7 +173,7 @@ func TestBuildEventsFromSpanAttributesCollision(t *testing.T) { Log: "LT", Sev: 9, Ts: "0", - Attrs: map[string]interface{}{ + Attrs: map[string]any{ "sca:schemVer": 1, "sca:schema": "tracing", "sca:type": "span", @@ -229,7 +229,7 @@ func TestBuildEventsFromSpanAttributesDifferentTypes(t *testing.T) { Log: "LT", Sev: 9, Ts: "0", - Attrs: map[string]interface{}{ + Attrs: map[string]any{ "sca:schemVer": 1, "sca:schema": "tracing", "sca:type": "span", @@ -617,7 +617,7 @@ func generateSimpleEvent( serviceName string, serverHost string, ) *add_events.Event { - attrs := map[string]interface{}{ + attrs := map[string]any{ "sca:schemVer": 1, "sca:schema": "tracing", "sca:type": "span", @@ -729,38 +729,38 @@ func TestUpdateResource(t *testing.T) { tests := []struct { name string resource map[string]any - expected map[string]interface{} + expected map[string]any }{ { name: "with_service.name", resource: map[string]any{"service.name": "foo"}, - expected: map[string]interface{}{resourceName: "foo", resourceType: string(Service)}, + expected: map[string]any{resourceName: "foo", resourceType: string(Service)}, }, { name: "without_service.name", resource: map[string]any{"service.bar": "foo"}, - expected: map[string]interface{}{resourceName: "", resourceType: string(Service)}, + expected: map[string]any{resourceName: "", resourceType: string(Service)}, }, { name: "with_process.pid", resource: map[string]any{"process.pid": "bar"}, - expected: map[string]interface{}{resourceName: "bar", resourceType: string(Process)}, + expected: map[string]any{resourceName: "bar", resourceType: string(Process)}, }, { name: "prefer_service", resource: map[string]any{"service.bar": "foo", "process.pid": "bar"}, - expected: map[string]interface{}{resourceName: "", resourceType: string(Service)}, + expected: map[string]any{resourceName: "", resourceType: string(Service)}, }, { name: "empty", resource: map[string]any{}, - expected: map[string]interface{}{resourceName: "", resourceType: string(Process)}, + expected: map[string]any{resourceName: "", resourceType: string(Process)}, }, } for _, tt := range tests { t.Run(tt.name, func(*testing.T) { - attrs := make(map[string]interface{}) + attrs := make(map[string]any) updateResource(attrs, tt.resource) assert.Equal(t, tt.expected, attrs, tt.name) diff --git a/exporter/elasticsearchexporter/internal/objmodel/objmodel_test.go b/exporter/elasticsearchexporter/internal/objmodel/objmodel_test.go index f33aaa740754..320a769f6419 100644 --- a/exporter/elasticsearchexporter/internal/objmodel/objmodel_test.go +++ b/exporter/elasticsearchexporter/internal/objmodel/objmodel_test.go @@ -269,33 +269,33 @@ func TestValue_FromAttribute(t *testing.T) { func TestDocument_Serialize_Flat(t *testing.T) { tests := map[string]struct { - attrs map[string]interface{} + attrs map[string]any want string }{ "no nesting with multiple fields": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a": "test", "b": 1, }, want: `{"a":"test","b":1}`, }, "shared prefix": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a.str": "test", "a.i": 1, }, want: `{"a.i":1,"a.str":"test"}`, }, "multiple namespaces with dot": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a.str": "test", "b.i": 1, }, want: `{"a.str":"test","b.i":1}`, }, "nested maps": { - attrs: map[string]interface{}{ - "a": map[string]interface{}{ + attrs: map[string]any{ + "a": map[string]any{ "str": "test", "i": 1, }, @@ -303,8 +303,8 @@ func TestDocument_Serialize_Flat(t *testing.T) { want: `{"a.i":1,"a.str":"test"}`, }, "multi-level nested namespace maps": { - attrs: map[string]interface{}{ - "a": map[string]interface{}{ + attrs: map[string]any{ + "a": map[string]any{ "b.str": "test", "i": 1, }, @@ -330,33 +330,33 @@ func TestDocument_Serialize_Flat(t *testing.T) { func TestDocument_Serialize_Dedot(t *testing.T) { tests := map[string]struct { - attrs map[string]interface{} + attrs map[string]any want string }{ "no nesting with multiple fields": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a": "test", "b": 1, }, want: `{"a":"test","b":1}`, }, "shared prefix": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a.str": "test", "a.i": 1, }, want: `{"a":{"i":1,"str":"test"}}`, }, "multiple namespaces": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a.str": "test", "b.i": 1, }, want: `{"a":{"str":"test"},"b":{"i":1}}`, }, "nested maps": { - attrs: map[string]interface{}{ - "a": map[string]interface{}{ + attrs: map[string]any{ + "a": map[string]any{ "str": "test", "i": 1, }, @@ -364,8 +364,8 @@ func TestDocument_Serialize_Dedot(t *testing.T) { want: `{"a":{"i":1,"str":"test"}}`, }, "multi-level nested namespace maps": { - attrs: map[string]interface{}{ - "a": map[string]interface{}{ + attrs: map[string]any{ + "a": map[string]any{ "b.c.str": "test", "i": 1, }, diff --git a/exporter/elasticsearchexporter/logs_exporter_test.go b/exporter/elasticsearchexporter/logs_exporter_test.go index dd7d80e6b2e7..48fa8a06cc0b 100644 --- a/exporter/elasticsearchexporter/logs_exporter_test.go +++ b/exporter/elasticsearchexporter/logs_exporter_test.go @@ -181,11 +181,11 @@ func TestExporter_PushEvent(t *testing.T) { data, err := docs[0].Action.MarshalJSON() assert.Nil(t, err) - jsonVal := map[string]interface{}{} + jsonVal := map[string]any{} err = json.Unmarshal(data, &jsonVal) assert.Nil(t, err) - create := jsonVal["create"].(map[string]interface{}) + create := jsonVal["create"].(map[string]any) expected := fmt.Sprintf("%s%s%s", prefix, index, suffix) assert.Equal(t, expected, create["_index"].(string)) diff --git a/exporter/elasticsearchexporter/model.go b/exporter/elasticsearchexporter/model.go index 9e9e43bc663b..74737b7d1b32 100644 --- a/exporter/elasticsearchexporter/model.go +++ b/exporter/elasticsearchexporter/model.go @@ -91,10 +91,10 @@ func (m *encodeModel) encodeSpan(resource pcommon.Resource, span ptrace.Span, sc } func spanLinksToString(spanLinkSlice ptrace.SpanLinkSlice) string { - linkArray := make([]map[string]interface{}, 0, spanLinkSlice.Len()) + linkArray := make([]map[string]any, 0, spanLinkSlice.Len()) for i := 0; i < spanLinkSlice.Len(); i++ { spanLink := spanLinkSlice.At(i) - link := map[string]interface{}{} + link := map[string]any{} link[spanIDField] = traceutil.SpanIDToHexOrEmptyString(spanLink.SpanID()) link[traceIDField] = traceutil.TraceIDToHexOrEmptyString(spanLink.TraceID()) link[attributeField] = spanLink.Attributes().AsRaw() diff --git a/exporter/elasticsearchexporter/traces_exporter_test.go b/exporter/elasticsearchexporter/traces_exporter_test.go index 70113b95365d..7c40be6b4d61 100644 --- a/exporter/elasticsearchexporter/traces_exporter_test.go +++ b/exporter/elasticsearchexporter/traces_exporter_test.go @@ -170,11 +170,11 @@ func TestExporter_PushTraceRecord(t *testing.T) { data, err := docs[0].Action.MarshalJSON() assert.Nil(t, err) - jsonVal := map[string]interface{}{} + jsonVal := map[string]any{} err = json.Unmarshal(data, &jsonVal) assert.Nil(t, err) - create := jsonVal["create"].(map[string]interface{}) + create := jsonVal["create"].(map[string]any) expected := fmt.Sprintf("%s%s%s", prefix, index, suffix) assert.Equal(t, expected, create["_index"].(string)) diff --git a/exporter/elasticsearchexporter/utils_test.go b/exporter/elasticsearchexporter/utils_test.go index b632e45d7b06..3309d9fb9a26 100644 --- a/exporter/elasticsearchexporter/utils_test.go +++ b/exporter/elasticsearchexporter/utils_test.go @@ -130,8 +130,8 @@ func newESTestServer(t *testing.T, bulkHandler bulkHandler) *httptest.Server { w.Header().Add("X-Elastic-Product", "Elasticsearch") enc := json.NewEncoder(w) - return enc.Encode(map[string]interface{}{ - "version": map[string]interface{}{ + return enc.Encode(map[string]any{ + "version": map[string]any{ "number": currentESVersion, }, }) diff --git a/exporter/influxdbexporter/logger.go b/exporter/influxdbexporter/logger.go index 2ff318bf0829..c052366d7359 100644 --- a/exporter/influxdbexporter/logger.go +++ b/exporter/influxdbexporter/logger.go @@ -20,6 +20,6 @@ func newZapInfluxLogger(logger *zap.Logger) common.Logger { } } -func (l zapInfluxLogger) Debug(msg string, kv ...interface{}) { +func (l zapInfluxLogger) Debug(msg string, kv ...any) { l.SugaredLogger.Debugw(msg, kv...) } diff --git a/exporter/influxdbexporter/writer.go b/exporter/influxdbexporter/writer.go index f996ca664041..5bd9df809d95 100644 --- a/exporter/influxdbexporter/writer.go +++ b/exporter/influxdbexporter/writer.go @@ -47,7 +47,7 @@ func newInfluxHTTPWriter(logger common.Logger, config *Config, telemetrySettings return &influxHTTPWriter{ encoderPool: sync.Pool{ - New: func() interface{} { + New: func() any { e := new(lineprotocol.Encoder) e.SetLax(false) e.SetPrecision(lineprotocol.Nanosecond) @@ -137,7 +137,7 @@ func newInfluxHTTPWriterBatch(w *influxHTTPWriter) *influxHTTPWriterBatch { // EnqueuePoint emits a set of line protocol attributes (metrics, tags, fields, timestamp) // to the internal line protocol buffer. // If the buffer is full, it will be flushed by calling WriteBatch. -func (b *influxHTTPWriterBatch) EnqueuePoint(ctx context.Context, measurement string, tags map[string]string, fields map[string]interface{}, ts time.Time, _ common.InfluxMetricValueType) error { +func (b *influxHTTPWriterBatch) EnqueuePoint(ctx context.Context, measurement string, tags map[string]string, fields map[string]any, ts time.Time, _ common.InfluxMetricValueType) error { if b.encoder == nil { b.encoder = b.encoderPool.Get().(*lineprotocol.Encoder) } @@ -234,7 +234,7 @@ func (b *influxHTTPWriterBatch) optimizeTags(m map[string]string) []tag { return tags } -func (b *influxHTTPWriterBatch) convertFields(m map[string]interface{}) (fields map[string]lineprotocol.Value) { +func (b *influxHTTPWriterBatch) convertFields(m map[string]any) (fields map[string]lineprotocol.Value) { fields = make(map[string]lineprotocol.Value, len(m)) for k, v := range m { if k == "" { diff --git a/exporter/influxdbexporter/writer_test.go b/exporter/influxdbexporter/writer_test.go index ff64a462d5a3..2cb240a25602 100644 --- a/exporter/influxdbexporter/writer_test.go +++ b/exporter/influxdbexporter/writer_test.go @@ -115,7 +115,7 @@ func Test_influxHTTPWriterBatch_maxPayload(t *testing.T) { batch := &influxHTTPWriterBatch{ influxHTTPWriter: &influxHTTPWriter{ encoderPool: sync.Pool{ - New: func() interface{} { + New: func() any { e := new(lineprotocol.Encoder) e.SetLax(false) e.SetPrecision(lineprotocol.Nanosecond) @@ -130,9 +130,9 @@ func Test_influxHTTPWriterBatch_maxPayload(t *testing.T) { }, } - err := batch.EnqueuePoint(context.Background(), "m", map[string]string{"k": "v"}, map[string]interface{}{"f": int64(1)}, time.Unix(1, 0), 0) + err := batch.EnqueuePoint(context.Background(), "m", map[string]string{"k": "v"}, map[string]any{"f": int64(1)}, time.Unix(1, 0), 0) require.NoError(t, err) - err = batch.EnqueuePoint(context.Background(), "m", map[string]string{"k": "v"}, map[string]interface{}{"f": int64(2)}, time.Unix(2, 0), 0) + err = batch.EnqueuePoint(context.Background(), "m", map[string]string{"k": "v"}, map[string]any{"f": int64(2)}, time.Unix(2, 0), 0) require.NoError(t, err) err = batch.WriteBatch(context.Background()) require.NoError(t, err) @@ -175,7 +175,7 @@ func Test_influxHTTPWriterBatch_EnqueuePoint_emptyTagValue(t *testing.T) { context.Background(), "m", map[string]string{"k": "v", "empty": ""}, - map[string]interface{}{"f": int64(1)}, + map[string]any{"f": int64(1)}, nowTime, common.InfluxMetricValueTypeUntyped) require.NoError(t, err) diff --git a/exporter/kafkaexporter/marshaler_test.go b/exporter/kafkaexporter/marshaler_test.go index 458fb99ed6cc..a94811c554cd 100644 --- a/exporter/kafkaexporter/marshaler_test.go +++ b/exporter/kafkaexporter/marshaler_test.go @@ -97,15 +97,15 @@ func TestOTLPTracesJsonMarshaling(t *testing.T) { // Since marshaling json is not guaranteed to be in order // within a string, using a map to compare that the expected values are there - otlpJSON := map[string]interface{}{ - "resourceSpans": []interface{}{ - map[string]interface{}{ - "resource": map[string]interface{}{}, - "scopeSpans": []interface{}{ - map[string]interface{}{ - "scope": map[string]interface{}{}, - "spans": []interface{}{ - map[string]interface{}{ + otlpJSON := map[string]any{ + "resourceSpans": []any{ + map[string]any{ + "resource": map[string]any{}, + "scopeSpans": []any{ + map[string]any{ + "scope": map[string]any{}, + "spans": []any{ + map[string]any{ "traceId": "0102030405060708090a0b0c0d0e0f10", "spanId": "0001020304050607", "parentSpanId": "08090a0b0c0d0e00", @@ -113,7 +113,7 @@ func TestOTLPTracesJsonMarshaling(t *testing.T) { "kind": float64(ptrace.SpanKindServer), "startTimeUnixNano": fmt.Sprint(now.UnixNano()), "endTimeUnixNano": fmt.Sprint(now.Add(time.Second).UnixNano()), - "status": map[string]interface{}{}, + "status": map[string]any{}, }, }, "schemaUrl": conventions.SchemaURL, @@ -124,8 +124,8 @@ func TestOTLPTracesJsonMarshaling(t *testing.T) { }, } - zipkinJSON := []interface{}{ - map[string]interface{}{ + zipkinJSON := []any{ + map[string]any{ "traceId": "0102030405060708090a0b0c0d0e0f10", "id": "0001020304050607", "parentId": "08090a0b0c0d0e00", @@ -133,17 +133,17 @@ func TestOTLPTracesJsonMarshaling(t *testing.T) { "timestamp": float64(time.Second.Microseconds()), "duration": float64(time.Second.Microseconds()), "kind": string(zipkin.Server), - "localEndpoint": map[string]interface{}{"serviceName": "otlpresourcenoservicename"}, + "localEndpoint": map[string]any{"serviceName": "otlpresourcenoservicename"}, }, } tests := []struct { encoding string - expectedJSON interface{} - unmarshaled interface{} + expectedJSON any + unmarshaled any }{ - {encoding: "otlp_json", expectedJSON: otlpJSON, unmarshaled: map[string]interface{}{}}, - {encoding: "zipkin_json", expectedJSON: zipkinJSON, unmarshaled: []map[string]interface{}{}}, + {encoding: "otlp_json", expectedJSON: otlpJSON, unmarshaled: map[string]any{}}, + {encoding: "zipkin_json", expectedJSON: zipkinJSON, unmarshaled: []map[string]any{}}, } for _, test := range tests { diff --git a/exporter/kafkaexporter/raw_marshaler.go b/exporter/kafkaexporter/raw_marshaler.go index 4f53714106ca..166be57f3e06 100644 --- a/exporter/kafkaexporter/raw_marshaler.go +++ b/exporter/kafkaexporter/raw_marshaler.go @@ -71,7 +71,7 @@ func (r rawMarshaler) logBodyAsBytes(value pcommon.Value) ([]byte, error) { } } -func (r rawMarshaler) interfaceAsBytes(value interface{}) ([]byte, error) { +func (r rawMarshaler) interfaceAsBytes(value any) ([]byte, error) { if value == nil { return []byte{}, nil } diff --git a/exporter/loadbalancingexporter/resolver_k8s_handler.go b/exporter/loadbalancingexporter/resolver_k8s_handler.go index f879f22f4213..d93cc2d94a88 100644 --- a/exporter/loadbalancingexporter/resolver_k8s_handler.go +++ b/exporter/loadbalancingexporter/resolver_k8s_handler.go @@ -21,7 +21,7 @@ type handler struct { logger *zap.Logger } -func (h handler) OnAdd(obj interface{}, _ bool) { +func (h handler) OnAdd(obj any, _ bool) { var endpoints []string switch object := obj.(type) { @@ -43,7 +43,7 @@ func (h handler) OnAdd(obj interface{}, _ bool) { } } -func (h handler) OnUpdate(oldObj, newObj interface{}) { +func (h handler) OnUpdate(oldObj, newObj any) { switch oldEps := oldObj.(type) { case *corev1.Endpoints: epRemove := convertToEndpoints(oldEps) @@ -76,7 +76,7 @@ func (h handler) OnUpdate(oldObj, newObj interface{}) { } } -func (h handler) OnDelete(obj interface{}) { +func (h handler) OnDelete(obj any) { var endpoints []string switch object := obj.(type) { case *cache.DeletedFinalStateUnknown: diff --git a/exporter/logicmonitorexporter/internal/logs/sender_test.go b/exporter/logicmonitorexporter/internal/logs/sender_test.go index b32b0c732cab..67f7355a6355 100644 --- a/exporter/logicmonitorexporter/internal/logs/sender_test.go +++ b/exporter/logicmonitorexporter/internal/logs/sender_test.go @@ -42,7 +42,7 @@ func TestSendLogs(t *testing.T) { sender, err := NewSender(ctx, ts.URL, ts.Client(), authParams, zap.NewNop()) assert.NoError(t, err) - logInput := translator.ConvertToLMLogInput("test msg", utils.NewTimestampFromTime(time.Now()).String(), map[string]interface{}{"system.hostname": "test"}, map[string]interface{}{"cloud.provider": "aws"}) + logInput := translator.ConvertToLMLogInput("test msg", utils.NewTimestampFromTime(time.Now()).String(), map[string]any{"system.hostname": "test"}, map[string]any{"cloud.provider": "aws"}) err = sender.SendLogs(ctx, []model.LogInput{logInput}) cancel() assert.NoError(t, err) @@ -64,7 +64,7 @@ func TestSendLogs(t *testing.T) { sender, err := NewSender(ctx, ts.URL, ts.Client(), authParams, zap.NewNop()) assert.NoError(t, err) - logInput := translator.ConvertToLMLogInput("test msg", utils.NewTimestampFromTime(time.Now()).String(), map[string]interface{}{"system.hostname": "test"}, map[string]interface{}{"cloud.provider": "aws"}) + logInput := translator.ConvertToLMLogInput("test msg", utils.NewTimestampFromTime(time.Now()).String(), map[string]any{"system.hostname": "test"}, map[string]any{"cloud.provider": "aws"}) err = sender.SendLogs(ctx, []model.LogInput{logInput}) cancel() assert.Error(t, err) @@ -87,7 +87,7 @@ func TestSendLogs(t *testing.T) { sender, err := NewSender(ctx, ts.URL, ts.Client(), authParams, zap.NewNop()) assert.NoError(t, err) - logInput := translator.ConvertToLMLogInput("test msg", utils.NewTimestampFromTime(time.Now()).String(), map[string]interface{}{"system.hostname": "test"}, map[string]interface{}{"cloud.provider": "aws"}) + logInput := translator.ConvertToLMLogInput("test msg", utils.NewTimestampFromTime(time.Now()).String(), map[string]any{"system.hostname": "test"}, map[string]any{"cloud.provider": "aws"}) err = sender.SendLogs(ctx, []model.LogInput{logInput}) cancel() assert.Error(t, err) diff --git a/exporter/logicmonitorexporter/logs_exporter.go b/exporter/logicmonitorexporter/logs_exporter.go index 381758cc0b38..d79b500d8c95 100644 --- a/exporter/logicmonitorexporter/logs_exporter.go +++ b/exporter/logicmonitorexporter/logs_exporter.go @@ -72,8 +72,8 @@ func (e *logExporter) PushLogData(ctx context.Context, lg plog.Logs) error { libraryLog := libraryLogs.At(j) logs := libraryLog.LogRecords() for k := 0; k < logs.Len(); k++ { - logMetadataMap := make(map[string]interface{}) - resourceMapperMap := make(map[string]interface{}) + logMetadataMap := make(map[string]any) + resourceMapperMap := make(map[string]any) log := logs.At(k) log.Attributes().Range(func(key string, value pcommon.Value) bool { diff --git a/exporter/logzioexporter/exporter_test.go b/exporter/logzioexporter/exporter_test.go index cbcd489c7bcd..d37e138bf77f 100644 --- a/exporter/logzioexporter/exporter_test.go +++ b/exporter/logzioexporter/exporter_test.go @@ -293,7 +293,7 @@ func TestPushLogsData(tester *testing.T) { res.Attributes().PutStr(conventions.AttributeHostName, testHost) err := testLogsExporter(ld, tester, &cfg) require.NoError(tester, err) - var jsonLog map[string]interface{} + var jsonLog map[string]any decoded, _ := gUnzipData(recordedRequests) requests := strings.Split(string(decoded), "\n") assert.NoError(tester, json.Unmarshal([]byte(requests[0]), &jsonLog)) diff --git a/exporter/logzioexporter/jsonlog.go b/exporter/logzioexporter/jsonlog.go index ec824cf41170..54a9341ef268 100644 --- a/exporter/logzioexporter/jsonlog.go +++ b/exporter/logzioexporter/jsonlog.go @@ -11,8 +11,8 @@ import ( ) // convertLogRecordToJSON Takes `plog.LogRecord` and `pcommon.Resource` input, outputs byte array that represents the log record as json string -func convertLogRecordToJSON(log plog.LogRecord, resource pcommon.Resource) map[string]interface{} { - jsonLog := map[string]interface{}{} +func convertLogRecordToJSON(log plog.LogRecord, resource pcommon.Resource) map[string]any { + jsonLog := map[string]any{} if spanID := log.SpanID(); !spanID.IsEmpty() { jsonLog["spanID"] = hex.EncodeToString(spanID[:]) } diff --git a/exporter/logzioexporter/jsonlog_test.go b/exporter/logzioexporter/jsonlog_test.go index 5ec6e9bf2328..c95fb7059ac9 100644 --- a/exporter/logzioexporter/jsonlog_test.go +++ b/exporter/logzioexporter/jsonlog_test.go @@ -37,13 +37,13 @@ func TestConvertLogRecordToJSON(t *testing.T) { type convertLogRecordToJSONTest struct { log plog.LogRecord resource pcommon.Resource - expected map[string]interface{} + expected map[string]any } var convertLogRecordToJSONTests = []convertLogRecordToJSONTest{ {generateLogRecordWithNestedBody(), pcommon.NewResource(), - map[string]interface{}{ + map[string]any{ "23": float64(45), "app": "server", "foo": "bar", @@ -51,14 +51,14 @@ func TestConvertLogRecordToJSON(t *testing.T) { "level": "Info", "message": "hello there", "@timestamp": TestLogTimeUnixMilli, - "nested": map[string]interface{}{"number": float64(499), "string": "v1"}, + "nested": map[string]any{"number": float64(499), "string": "v1"}, "spanID": "0102040800000000", "traceID": "08040201000000000000000000000000", }, }, {generateLogRecordWithMultiTypeValues(), pcommon.NewResource(), - map[string]interface{}{ + map[string]any{ "bool": true, "customer": "acme", "env": "dev", @@ -101,8 +101,8 @@ func TestSetTimeStamp(t *testing.T) { require.NoError(t, err) err = exporter.Shutdown(ctx) require.NoError(t, err) - var jsonLog map[string]interface{} - var jsonLogNoTimestamp map[string]interface{} + var jsonLog map[string]any + var jsonLogNoTimestamp map[string]any decoded, _ := gUnzipData(recordedRequests) requests := strings.Split(string(decoded), "\n") require.NoError(t, json.Unmarshal([]byte(requests[0]), &jsonLog)) diff --git a/exporter/logzioexporter/logger.go b/exporter/logzioexporter/logger.go index 3f4bacbf1a65..810e494d5a34 100644 --- a/exporter/logzioexporter/logger.go +++ b/exporter/logzioexporter/logger.go @@ -20,9 +20,9 @@ type hclog2ZapLogger struct { name string } -func (l *hclog2ZapLogger) Log(_ hclog.Level, _ string, _ ...interface{}) {} +func (l *hclog2ZapLogger) Log(_ hclog.Level, _ string, _ ...any) {} -func (l *hclog2ZapLogger) ImpliedArgs() []interface{} { +func (l *hclog2ZapLogger) ImpliedArgs() []any { return nil } @@ -35,25 +35,25 @@ func (l *hclog2ZapLogger) StandardWriter(_ *hclog.StandardLoggerOptions) io.Writ } // Trace implementation. -func (l *hclog2ZapLogger) Trace(_ string, _ ...interface{}) {} +func (l *hclog2ZapLogger) Trace(_ string, _ ...any) {} // Debug implementation. -func (l *hclog2ZapLogger) Debug(msg string, args ...interface{}) { +func (l *hclog2ZapLogger) Debug(msg string, args ...any) { l.Zap.Debug(msg, argsToFields(args...)...) } // Info implementation. -func (l *hclog2ZapLogger) Info(msg string, args ...interface{}) { +func (l *hclog2ZapLogger) Info(msg string, args ...any) { l.Zap.Info(msg, argsToFields(args...)...) } // Warn implementation. -func (l *hclog2ZapLogger) Warn(msg string, args ...interface{}) { +func (l *hclog2ZapLogger) Warn(msg string, args ...any) { l.Zap.Warn(msg, argsToFields(args...)...) } // Error implementation. -func (l *hclog2ZapLogger) Error(msg string, args ...interface{}) { +func (l *hclog2ZapLogger) Error(msg string, args ...any) { l.Zap.Error(msg, argsToFields(args...)...) } @@ -73,7 +73,7 @@ func (l *hclog2ZapLogger) IsWarn() bool { return false } func (l *hclog2ZapLogger) IsError() bool { return false } // With implementation. -func (l *hclog2ZapLogger) With(args ...interface{}) hclog.Logger { +func (l *hclog2ZapLogger) With(args ...any) hclog.Logger { return &hclog2ZapLogger{Zap: l.Zap.With(argsToFields(args...)...)} } @@ -105,7 +105,7 @@ func (l *hclog2ZapLogger) StandardLogger(_ *hclog.StandardLoggerOptions) *log.Lo return log.New(io.Discard, "", 0) } -func argsToFields(args ...interface{}) []zapcore.Field { +func argsToFields(args ...any) []zapcore.Field { var fields []zapcore.Field for i := 0; i < len(args); i += 2 { fields = append(fields, zap.String(args[i].(string), fmt.Sprintf("%v", args[i+1]))) diff --git a/exporter/logzioexporter/logziospan.go b/exporter/logzioexporter/logziospan.go index 58c82b68e97b..7bc485fd1409 100644 --- a/exporter/logzioexporter/logziospan.go +++ b/exporter/logzioexporter/logziospan.go @@ -18,20 +18,20 @@ const ( // logzioSpan is same as esSpan with a few different json field names and an addition on type field. type logzioSpan struct { - TraceID dbmodel.TraceID `json:"traceID"` - OperationName string `json:"operationName,omitempty"` - SpanID dbmodel.SpanID `json:"spanID"` - References []dbmodel.Reference `json:"references"` - Flags uint32 `json:"flags,omitempty"` - StartTime uint64 `json:"startTime"` - StartTimeMillis uint64 `json:"startTimeMillis"` - Timestamp uint64 `json:"@timestamp"` - Duration uint64 `json:"duration"` - Tags []dbmodel.KeyValue `json:"JaegerTags,omitempty"` - Tag map[string]interface{} `json:"JaegerTag,omitempty"` - Logs []dbmodel.Log `json:"logs"` - Process dbmodel.Process `json:"process,omitempty"` - Type string `json:"type"` + TraceID dbmodel.TraceID `json:"traceID"` + OperationName string `json:"operationName,omitempty"` + SpanID dbmodel.SpanID `json:"spanID"` + References []dbmodel.Reference `json:"references"` + Flags uint32 `json:"flags,omitempty"` + StartTime uint64 `json:"startTime"` + StartTimeMillis uint64 `json:"startTimeMillis"` + Timestamp uint64 `json:"@timestamp"` + Duration uint64 `json:"duration"` + Tags []dbmodel.KeyValue `json:"JaegerTags,omitempty"` + Tag map[string]any `json:"JaegerTag,omitempty"` + Logs []dbmodel.Log `json:"logs"` + Process dbmodel.Process `json:"process,omitempty"` + Type string `json:"type"` } func getTagsValues(tags []model.KeyValue) []string { diff --git a/exporter/logzioexporter/logziospan_test.go b/exporter/logzioexporter/logziospan_test.go index 49836f5020f0..5a8f15ec412a 100644 --- a/exporter/logzioexporter/logziospan_test.go +++ b/exporter/logzioexporter/logziospan_test.go @@ -27,7 +27,7 @@ func TestTransformToLogzioSpanBytes(tester *testing.T) { if err != nil { tester.Fatalf(err.Error()) } - m := make(map[string]interface{}) + m := make(map[string]any) err = json.Unmarshal(newSpan, &m) if err != nil { tester.Fatalf(err.Error()) diff --git a/exporter/lokiexporter/exporter_test.go b/exporter/lokiexporter/exporter_test.go index 4f184b01a6ba..6473f7f9cabe 100644 --- a/exporter/lokiexporter/exporter_test.go +++ b/exporter/lokiexporter/exporter_test.go @@ -27,19 +27,19 @@ import ( func TestPushLogData(t *testing.T) { testCases := []struct { desc string - hints map[string]interface{} - attrs map[string]interface{} - res map[string]interface{} + hints map[string]any + attrs map[string]any + res map[string]any expectedLabel string expectedLine string }{ { desc: "with attribute to label and regular attribute", - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", "http.status": 200, }, - hints: map[string]interface{}{ + hints: map[string]any{ "loki.attribute.labels": "host.name", }, expectedLabel: `{exporter="OTLP", host_name="guarana"}`, @@ -47,11 +47,11 @@ func TestPushLogData(t *testing.T) { }, { desc: "with resource to label and regular resource", - res: map[string]interface{}{ + res: map[string]any{ "host.name": "guarana", "region.az": "eu-west-1a", }, - hints: map[string]interface{}{ + hints: map[string]any{ "loki.resource.labels": "host.name", }, expectedLabel: `{exporter="OTLP", host_name="guarana"}`, diff --git a/exporter/opensearchexporter/config_test.go b/exporter/opensearchexporter/config_test.go index 4a6f27ff8e03..6ce3c8ddc3bd 100644 --- a/exporter/opensearchexporter/config_test.go +++ b/exporter/opensearchexporter/config_test.go @@ -81,7 +81,7 @@ func TestLoadConfig(t *testing.T) { config.Dataset = "" config.Namespace = "eu" }), - configValidateAssert: func(t assert.TestingT, err error, i ...interface{}) bool { + configValidateAssert: func(t assert.TestingT, err error, i ...any) bool { return assert.ErrorContains(t, err, errDatasetNoValue.Error()) }, }, @@ -92,7 +92,7 @@ func TestLoadConfig(t *testing.T) { config.Dataset = "ngnix" config.Namespace = "" }), - configValidateAssert: func(t assert.TestingT, err error, i ...interface{}) bool { + configValidateAssert: func(t assert.TestingT, err error, i ...any) bool { return assert.ErrorContains(t, err, errNamespaceNoValue.Error()) }, }, @@ -102,7 +102,7 @@ func TestLoadConfig(t *testing.T) { config.Endpoint = sampleEndpoint config.BulkAction = "delete" }), - configValidateAssert: func(t assert.TestingT, err error, i ...interface{}) bool { + configValidateAssert: func(t assert.TestingT, err error, i ...any) bool { return assert.ErrorContains(t, err, errBulkActionInvalid.Error()) }, }, diff --git a/exporter/opensearchexporter/internal/objmodel/objmodel_test.go b/exporter/opensearchexporter/internal/objmodel/objmodel_test.go index f33aaa740754..320a769f6419 100644 --- a/exporter/opensearchexporter/internal/objmodel/objmodel_test.go +++ b/exporter/opensearchexporter/internal/objmodel/objmodel_test.go @@ -269,33 +269,33 @@ func TestValue_FromAttribute(t *testing.T) { func TestDocument_Serialize_Flat(t *testing.T) { tests := map[string]struct { - attrs map[string]interface{} + attrs map[string]any want string }{ "no nesting with multiple fields": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a": "test", "b": 1, }, want: `{"a":"test","b":1}`, }, "shared prefix": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a.str": "test", "a.i": 1, }, want: `{"a.i":1,"a.str":"test"}`, }, "multiple namespaces with dot": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a.str": "test", "b.i": 1, }, want: `{"a.str":"test","b.i":1}`, }, "nested maps": { - attrs: map[string]interface{}{ - "a": map[string]interface{}{ + attrs: map[string]any{ + "a": map[string]any{ "str": "test", "i": 1, }, @@ -303,8 +303,8 @@ func TestDocument_Serialize_Flat(t *testing.T) { want: `{"a.i":1,"a.str":"test"}`, }, "multi-level nested namespace maps": { - attrs: map[string]interface{}{ - "a": map[string]interface{}{ + attrs: map[string]any{ + "a": map[string]any{ "b.str": "test", "i": 1, }, @@ -330,33 +330,33 @@ func TestDocument_Serialize_Flat(t *testing.T) { func TestDocument_Serialize_Dedot(t *testing.T) { tests := map[string]struct { - attrs map[string]interface{} + attrs map[string]any want string }{ "no nesting with multiple fields": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a": "test", "b": 1, }, want: `{"a":"test","b":1}`, }, "shared prefix": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a.str": "test", "a.i": 1, }, want: `{"a":{"i":1,"str":"test"}}`, }, "multiple namespaces": { - attrs: map[string]interface{}{ + attrs: map[string]any{ "a.str": "test", "b.i": 1, }, want: `{"a":{"str":"test"},"b":{"i":1}}`, }, "nested maps": { - attrs: map[string]interface{}{ - "a": map[string]interface{}{ + attrs: map[string]any{ + "a": map[string]any{ "str": "test", "i": 1, }, @@ -364,8 +364,8 @@ func TestDocument_Serialize_Dedot(t *testing.T) { want: `{"a":{"i":1,"str":"test"}}`, }, "multi-level nested namespace maps": { - attrs: map[string]interface{}{ - "a": map[string]interface{}{ + attrs: map[string]any{ + "a": map[string]any{ "b.c.str": "test", "i": 1, }, diff --git a/exporter/prometheusexporter/accumulator.go b/exporter/prometheusexporter/accumulator.go index c8a8be7af1c8..62fb29692ef7 100644 --- a/exporter/prometheusexporter/accumulator.go +++ b/exporter/prometheusexporter/accumulator.go @@ -271,7 +271,7 @@ func (a *lastValueAccumulator) Collect() ([]pmetric.Metric, []pcommon.Map) { var resourceAttrs []pcommon.Map expirationTime := time.Now().Add(-a.metricExpiration) - a.registeredMetrics.Range(func(key, value interface{}) bool { + a.registeredMetrics.Range(func(key, value any) bool { v := value.(*accumulatedValue) if expirationTime.After(v.updated) { a.logger.Debug(fmt.Sprintf("metric expired: %s", v.value.Name())) diff --git a/exporter/prometheusexporter/log.go b/exporter/prometheusexporter/log.go index 1b859332ae96..7f8c5c5ee275 100644 --- a/exporter/prometheusexporter/log.go +++ b/exporter/prometheusexporter/log.go @@ -19,6 +19,6 @@ func newPromLogger(zapLog *zap.Logger) *promLogger { } } -func (l *promLogger) Println(v ...interface{}) { +func (l *promLogger) Println(v ...any) { l.realLog.Error(fmt.Sprintln(v...)) } diff --git a/exporter/pulsarexporter/marshaler_test.go b/exporter/pulsarexporter/marshaler_test.go index 455a6a5b66b7..318dd7b580b7 100644 --- a/exporter/pulsarexporter/marshaler_test.go +++ b/exporter/pulsarexporter/marshaler_test.go @@ -102,15 +102,15 @@ func TestOTLPTracesJsonMarshaling(t *testing.T) { // Since marshaling json is not guaranteed to be in order // within a string, using a map to compare that the expected values are there - expectedJSON := map[string]interface{}{ - "resourceSpans": []interface{}{ - map[string]interface{}{ - "resource": map[string]interface{}{}, - "scopeSpans": []interface{}{ - map[string]interface{}{ - "scope": map[string]interface{}{}, - "spans": []interface{}{ - map[string]interface{}{ + expectedJSON := map[string]any{ + "resourceSpans": []any{ + map[string]any{ + "resource": map[string]any{}, + "scopeSpans": []any{ + map[string]any{ + "scope": map[string]any{}, + "spans": []any{ + map[string]any{ "traceId": "", "spanId": "0001020304050607", "parentSpanId": "08090a0b0c0d0e00", @@ -118,7 +118,7 @@ func TestOTLPTracesJsonMarshaling(t *testing.T) { "kind": float64(ptrace.SpanKindInternal), "startTimeUnixNano": fmt.Sprint(now.UnixNano()), "endTimeUnixNano": fmt.Sprint(now.Add(time.Second).UnixNano()), - "status": map[string]interface{}{}, + "status": map[string]any{}, }, }, "schemaUrl": conventions.SchemaURL, @@ -129,7 +129,7 @@ func TestOTLPTracesJsonMarshaling(t *testing.T) { }, } - var final map[string]interface{} + var final map[string]any err = json.Unmarshal(payload, &final) require.NoError(t, err, "Must not error marshaling expected data") diff --git a/exporter/sentryexporter/sentry_exporter_test.go b/exporter/sentryexporter/sentry_exporter_test.go index 7526d3fa0073..0506e88c379e 100644 --- a/exporter/sentryexporter/sentry_exporter_test.go +++ b/exporter/sentryexporter/sentry_exporter_test.go @@ -205,7 +205,7 @@ func TestSpanEventToSentryEvent(t *testing.T) { Timestamp: sampleSentrySpanForEvent.EndTime, Transaction: sampleSentrySpanForEvent.Description, Contexts: map[string]sentry.Context{}, - Extra: map[string]interface{}{}, + Extra: map[string]any{}, Modules: map[string]string{}, StartTime: unixNanoToTime(123), } @@ -357,7 +357,7 @@ type SpanDescriptorsCase struct { testName string // input name string - attrs map[string]interface{} + attrs map[string]any spanKind ptrace.SpanKind // output op string @@ -369,7 +369,7 @@ func TestGenerateSpanDescriptors(t *testing.T) { { testName: "http-client", name: "/api/users/{user_id}", - attrs: map[string]interface{}{ + attrs: map[string]any{ conventions.AttributeHTTPMethod: "GET", }, spanKind: ptrace.SpanKindClient, @@ -379,7 +379,7 @@ func TestGenerateSpanDescriptors(t *testing.T) { { testName: "http-server", name: "/api/users/{user_id}", - attrs: map[string]interface{}{ + attrs: map[string]any{ conventions.AttributeHTTPMethod: "POST", }, spanKind: ptrace.SpanKindServer, @@ -389,7 +389,7 @@ func TestGenerateSpanDescriptors(t *testing.T) { { testName: "db-call-without-statement", name: "SET mykey 'Val'", - attrs: map[string]interface{}{ + attrs: map[string]any{ conventions.AttributeDBSystem: "redis", }, spanKind: ptrace.SpanKindClient, @@ -399,7 +399,7 @@ func TestGenerateSpanDescriptors(t *testing.T) { { testName: "db-call-with-statement", name: "mysql call", - attrs: map[string]interface{}{ + attrs: map[string]any{ conventions.AttributeDBSystem: "sqlite", conventions.AttributeDBStatement: "SELECT * FROM table", }, @@ -410,7 +410,7 @@ func TestGenerateSpanDescriptors(t *testing.T) { { testName: "rpc", name: "grpc.test.EchoService/Echo", - attrs: map[string]interface{}{ + attrs: map[string]any{ conventions.AttributeRPCService: "EchoService", }, spanKind: ptrace.SpanKindClient, @@ -420,7 +420,7 @@ func TestGenerateSpanDescriptors(t *testing.T) { { testName: "message-system", name: "message-destination", - attrs: map[string]interface{}{ + attrs: map[string]any{ "messaging.system": "kafka", }, spanKind: ptrace.SpanKindProducer, @@ -430,7 +430,7 @@ func TestGenerateSpanDescriptors(t *testing.T) { { testName: "faas", name: "message-destination", - attrs: map[string]interface{}{ + attrs: map[string]any{ "faas.trigger": "pubsub", }, spanKind: ptrace.SpanKindServer, diff --git a/exporter/signalfxexporter/config.go b/exporter/signalfxexporter/config.go index 77c097aceba3..b8d14217d7a6 100644 --- a/exporter/signalfxexporter/config.go +++ b/exporter/signalfxexporter/config.go @@ -236,7 +236,7 @@ func setDefaultExcludes(cfg *Config) error { func loadConfig(bytes []byte) (Config, error) { var cfg Config - var data map[string]interface{} + var data map[string]any if err := yaml.Unmarshal(bytes, &data); err != nil { return cfg, err } diff --git a/exporter/signalfxexporter/config_test.go b/exporter/signalfxexporter/config_test.go index 0069879d6029..2646ee12cbef 100644 --- a/exporter/signalfxexporter/config_test.go +++ b/exporter/signalfxexporter/config_test.go @@ -186,14 +186,14 @@ func TestLoadConfig(t *testing.T) { }, { MetricName: "metric4", - Dimensions: map[string]interface{}{ + Dimensions: map[string]any{ "dimension_key": "dimension_val", }, }, { MetricName: "metric5", - Dimensions: map[string]interface{}{ - "dimension_key": []interface{}{"dimension_val1", "dimension_val2"}, + Dimensions: map[string]any{ + "dimension_key": []any{"dimension_val1", "dimension_val2"}, }, }, { @@ -204,7 +204,7 @@ func TestLoadConfig(t *testing.T) { }, { MetricName: "cpu.utilization", - Dimensions: map[string]interface{}{ + Dimensions: map[string]any{ "container_name": "/^[A-Z][A-Z]$/", }, }, @@ -545,7 +545,7 @@ func TestUnmarshalExcludeMetrics(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - require.NoError(t, tt.cfg.Unmarshal(confmap.NewFromStringMap(map[string]interface{}{}))) + require.NoError(t, tt.cfg.Unmarshal(confmap.NewFromStringMap(map[string]any{}))) assert.Len(t, tt.cfg.ExcludeMetrics, tt.excludeMetricsLen) }) } diff --git a/exporter/signalfxexporter/exporter.go b/exporter/signalfxexporter/exporter.go index ede1c2ba583e..2f35031623ec 100644 --- a/exporter/signalfxexporter/exporter.go +++ b/exporter/signalfxexporter/exporter.go @@ -167,7 +167,7 @@ func (se *signalfxExporter) start(ctx context.Context, host component.Host) (err } func newGzipPool() sync.Pool { - return sync.Pool{New: func() interface{} { + return sync.Pool{New: func() any { return gzip.NewWriter(nil) }} } diff --git a/exporter/signalfxexporter/exporter_test.go b/exporter/signalfxexporter/exporter_test.go index 50820d63eebd..5d66060a0681 100644 --- a/exporter/signalfxexporter/exporter_test.go +++ b/exporter/signalfxexporter/exporter_test.go @@ -196,7 +196,7 @@ func TestConsumeMetrics(t *testing.T) { sfxClientBase: sfxClientBase{ ingestURL: serverURL, client: client, - zippers: sync.Pool{New: func() interface{} { + zippers: sync.Pool{New: func() any { return gzip.NewWriter(nil) }}, }, @@ -736,7 +736,7 @@ func TestConsumeMetadata(t *testing.T) { metadata []*metadata.MetadataUpdate } type fields struct { - payLoad map[string]interface{} + payLoad map[string]any } tests := []struct { name string @@ -751,8 +751,8 @@ func TestConsumeMetadata(t *testing.T) { { name: "Test property updates", fields: fields{ - map[string]interface{}{ - "customProperties": map[string]interface{}{ + map[string]any{ + "customProperties": map[string]any{ "prop.erty1": "val1", "property2": nil, "prop.erty3": "val33", @@ -811,12 +811,12 @@ func TestConsumeMetadata(t *testing.T) { { name: "Test tag updates", fields: fields{ - map[string]interface{}{ - "customProperties": map[string]interface{}{}, - "tags": []interface{}{ + map[string]any{ + "customProperties": map[string]any{}, + "tags": []any{ "tag.1", }, - "tagsToRemove": []interface{}{ + "tagsToRemove": []any{ "tag/2", }, }, @@ -853,16 +853,16 @@ func TestConsumeMetadata(t *testing.T) { { name: "Test quick successive updates", fields: fields{ - map[string]interface{}{ - "customProperties": map[string]interface{}{ + map[string]any{ + "customProperties": map[string]any{ "property1": nil, "property2": "val2", "property3": nil, }, - "tags": []interface{}{ + "tags": []any{ "tag/2", }, - "tagsToRemove": []interface{}{ + "tagsToRemove": []any{ "tag.1", }, }, @@ -923,8 +923,8 @@ func TestConsumeMetadata(t *testing.T) { { name: "Test updates on dimensions with nonalphanumeric characters (other than the default allow list)", fields: fields{ - map[string]interface{}{ - "customProperties": map[string]interface{}{ + map[string]any{ + "customProperties": map[string]any{ "prop.erty1": "val1", "property2": nil, "prop.erty3": "val33", @@ -1012,7 +1012,7 @@ func TestConsumeMetadata(t *testing.T) { assert.Equal(t, tt.expectedDimensionKey, dimPair[0]) assert.Equal(t, tt.expectedDimensionValue, dimPair[1]) - p := map[string]interface{}{ + p := map[string]any{ "customProperties": map[string]*string{}, "tags": []string{}, "tagsToRemove": []string{}, @@ -1098,7 +1098,7 @@ func BenchmarkExporterConsumeData(b *testing.B) { client: &http.Client{ Timeout: 1 * time.Second, }, - zippers: sync.Pool{New: func() interface{} { + zippers: sync.Pool{New: func() any { return gzip.NewWriter(nil) }}, }, diff --git a/exporter/signalfxexporter/factory_test.go b/exporter/signalfxexporter/factory_test.go index d40d48b7a5dd..c9db6217cd8b 100644 --- a/exporter/signalfxexporter/factory_test.go +++ b/exporter/signalfxexporter/factory_test.go @@ -615,7 +615,7 @@ func getMetrics(metrics []map[string]string) pmetric.Metrics { return md } -func testReadJSON(f string, v interface{}) error { +func testReadJSON(f string, v any) error { bytes, err := os.ReadFile(f) if err != nil { return err diff --git a/exporter/signalfxexporter/internal/apm/log/log.go b/exporter/signalfxexporter/internal/apm/log/log.go index 1e65e416b6e8..0924d8ce955a 100644 --- a/exporter/signalfxexporter/internal/apm/log/log.go +++ b/exporter/signalfxexporter/internal/apm/log/log.go @@ -5,7 +5,7 @@ package log // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/signalfxexporter/internal/apm/log" // Fields is a map that is used to populated logging context. -type Fields map[string]interface{} +type Fields map[string]any type nilLogger struct { } diff --git a/exporter/signalfxexporter/internal/dimensions/dimclient.go b/exporter/signalfxexporter/internal/dimensions/dimclient.go index e209fc24a776..98ca7c6b102c 100644 --- a/exporter/signalfxexporter/internal/dimensions/dimclient.go +++ b/exporter/signalfxexporter/internal/dimensions/dimclient.go @@ -304,7 +304,7 @@ func (dc *DimensionClient) makePatchRequest(dim *DimensionUpdate) (*http.Request } } - json, err := json.Marshal(map[string]interface{}{ + json, err := json.Marshal(map[string]any{ "customProperties": dim.Properties, "tags": tagsToAdd, "tagsToRemove": tagsToRemove, diff --git a/exporter/signalfxexporter/internal/translation/converter_test.go b/exporter/signalfxexporter/internal/translation/converter_test.go index 90f8db83d5d6..f2f8457c7457 100644 --- a/exporter/signalfxexporter/internal/translation/converter_test.go +++ b/exporter/signalfxexporter/internal/translation/converter_test.go @@ -39,12 +39,12 @@ var ( func Test_MetricDataToSignalFxV2(t *testing.T) { logger := zap.NewNop() - labelMap := map[string]interface{}{ + labelMap := map[string]any{ "k0": "v0", "k1": "v1", } - longLabelMap := map[string]interface{}{ + longLabelMap := map[string]any{ fmt.Sprintf("l%sng_key", strings.Repeat("o", 128)): "v0", "k0": "v0", "k1": fmt.Sprintf("l%sng_value", strings.Repeat("o", 256)), @@ -68,7 +68,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { assert.NoError(t, doublePtWithLabels.Attributes().FromRaw(longLabelMap)) } - differentLabelMap := map[string]interface{}{ + differentLabelMap := map[string]any{ "k00": "v00", "k11": "v11", } @@ -232,7 +232,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { doubleSFxDataPoint( "gauge_double_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(map[string]interface{}{ + maps.MergeRawMaps(map[string]any{ "k_n0": "vn0", "k_n1": "vn1", "k_r0": "vr0", @@ -241,7 +241,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { int64SFxDataPoint( "gauge_int_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(map[string]interface{}{ + maps.MergeRawMaps(map[string]any{ "k_n0": "vn0", "k_n1": "vn1", "k_r0": "vr0", @@ -295,7 +295,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { int64SFxDataPoint( "gauge_int_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(map[string]interface{}{ + maps.MergeRawMaps(map[string]any{ "k_n0": "vn0", "k_n1": "vn1", "k_r0": "vr0", @@ -304,7 +304,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { int64SFxDataPoint( "gauge_int_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(map[string]interface{}{ + maps.MergeRawMaps(map[string]any{ "k_n0": "vn0", "k_n1": "vn1", "k_r0": "vr0", @@ -338,12 +338,12 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { doubleSFxDataPoint( "gauge_double_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(map[string]interface{}{ + maps.MergeRawMaps(map[string]any{ "k_n0": "vn0", "k_n1": "vn1", "k_r0": "vr0", "k_r1": "vr1", - }, map[string]interface{}{ + }, map[string]any{ "k0": "v0", "k2": "v2", })), @@ -372,7 +372,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { doubleSFxDataPoint( "gauge_double_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(labelMap, map[string]interface{}{ + maps.MergeRawMaps(labelMap, map[string]any{ "cloud_account_id": "efgh", "cloud_provider": conventions.AttributeCloudProviderAWS, "cloud_region": "us-east", @@ -405,7 +405,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { doubleSFxDataPoint( "gauge_double_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(labelMap, map[string]interface{}{ + maps.MergeRawMaps(labelMap, map[string]any{ "cloud_provider": conventions.AttributeCloudProviderAWS, "cloud_account_id": "efgh", "cloud_region": "us-east", @@ -438,7 +438,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { doubleSFxDataPoint( "gauge_double_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(labelMap, map[string]interface{}{ + maps.MergeRawMaps(labelMap, map[string]any{ "host_id": "abcd", "cloud_provider": conventions.AttributeCloudProviderGCP, "k_r0": "vr0", @@ -469,7 +469,7 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { doubleSFxDataPoint( "gauge_double_with_dims", &sfxMetricTypeGauge, - maps.MergeRawMaps(labelMap, map[string]interface{}{ + maps.MergeRawMaps(labelMap, map[string]any{ "gcp_id": "efgh_abcd", "k_r0": "vr0", "k_r1": "vr1", @@ -520,14 +520,14 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { }, { MetricName: "gauge_int_with_dims", - Dimensions: map[string]interface{}{ - "k0": []interface{}{"v1"}, + Dimensions: map[string]any{ + "k0": []any{"v1"}, }, }, { MetricName: "cumulative_double_with_dims", - Dimensions: map[string]interface{}{ - "k0": []interface{}{"v0"}, + Dimensions: map[string]any{ + "k0": []any{"v0"}, }, }, }, @@ -578,14 +578,14 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { }, { MetricName: "gauge_int_with_dims", - Dimensions: map[string]interface{}{ - "k0": []interface{}{"v1"}, + Dimensions: map[string]any{ + "k0": []any{"v1"}, }, }, { MetricName: "cumulative_double_with_dims", - Dimensions: map[string]interface{}{ - "k0": []interface{}{"v0"}, + Dimensions: map[string]any{ + "k0": []any{"v0"}, }, }, }, @@ -619,27 +619,27 @@ func Test_MetricDataToSignalFxV2(t *testing.T) { func Test_MetricDataToSignalFxV2WithHistogramBuckets(t *testing.T) { logger := zap.NewNop() - labelMap := map[string]interface{}{ + labelMap := map[string]any{ "k0": "v0", "k1": "v1", } - labelMapBucket1 := map[string]interface{}{ + labelMapBucket1 := map[string]any{ "k0": "v0", "k1": "v1", "le": "1", } - labelMapBucket2 := map[string]interface{}{ + labelMapBucket2 := map[string]any{ "k0": "v0", "k1": "v1", "le": "2", } - labelMapBucket3 := map[string]interface{}{ + labelMapBucket3 := map[string]any{ "k0": "v0", "k1": "v1", "le": "4", } - labelMapBucket4 := map[string]interface{}{ + labelMapBucket4 := map[string]any{ "k0": "v0", "k1": "v1", "le": "+Inf", @@ -1136,7 +1136,7 @@ func sortDimensions(points []*sfxpb.DataPoint) { func doubleSFxDataPoint( metric string, metricType *sfxpb.MetricType, - dims map[string]interface{}, + dims map[string]any, ) *sfxpb.DataPoint { return &sfxpb.DataPoint{ Metric: metric, @@ -1150,7 +1150,7 @@ func doubleSFxDataPoint( func int64SFxDataPoint( metric string, metricType *sfxpb.MetricType, - dims map[string]interface{}, + dims map[string]any, ) *sfxpb.DataPoint { return &sfxpb.DataPoint{ Metric: metric, @@ -1166,7 +1166,7 @@ func histoValue(dps *sfxpb.DataPoint, val int64) *sfxpb.DataPoint { return dps } -func sfxDimensions(m map[string]interface{}) []*sfxpb.Dimension { +func sfxDimensions(m map[string]any) []*sfxpb.Dimension { sfxDims := make([]*sfxpb.Dimension, 0, len(m)) for k, v := range m { sfxDims = append(sfxDims, &sfxpb.Dimension{ diff --git a/exporter/signalfxexporter/internal/translation/dpfilters/filterset_test.go b/exporter/signalfxexporter/internal/translation/dpfilters/filterset_test.go index b95d308fd054..64293030ee2c 100644 --- a/exporter/signalfxexporter/internal/translation/dpfilters/filterset_test.go +++ b/exporter/signalfxexporter/internal/translation/dpfilters/filterset_test.go @@ -99,7 +99,7 @@ func TestFilterSet(t *testing.T) { { name: "Match based on dimension name as string", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ + Dimensions: map[string]any{ "container_name": "PO", }}}, expectedMatches: []*sfxpb.DataPoint{ @@ -118,8 +118,8 @@ func TestFilterSet(t *testing.T) { { name: "Match based on dimension name", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "container_name": []interface{}{"PO"}, + Dimensions: map[string]any{ + "container_name": []any{"PO"}, }}}, expectedMatches: []*sfxpb.DataPoint{ { @@ -137,8 +137,8 @@ func TestFilterSet(t *testing.T) { { name: "Match based on dimension name regex", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "container_name": []interface{}{`/^[A-Z][A-Z]$/`}, + Dimensions: map[string]any{ + "container_name": []any{`/^[A-Z][A-Z]$/`}, }}}, expectedMatches: []*sfxpb.DataPoint{ { @@ -156,8 +156,8 @@ func TestFilterSet(t *testing.T) { { name: "Match based on dimension presence", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "container_name": []interface{}{`/.+/`}, + Dimensions: map[string]any{ + "container_name": []any{`/.+/`}, }}}, expectedMatches: []*sfxpb.DataPoint{ { @@ -175,8 +175,8 @@ func TestFilterSet(t *testing.T) { { name: "Match based on dimension name glob", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "container_name": []interface{}{`*O*`}, + Dimensions: map[string]any{ + "container_name": []any{`*O*`}, }}}, expectedMatches: []*sfxpb.DataPoint{ { @@ -199,8 +199,8 @@ func TestFilterSet(t *testing.T) { name: "Match based on conjunction of both dimensions and metric name", excludes: []MetricFilter{{ MetricNames: []string{"*.utilization"}, - Dimensions: map[string]interface{}{ - "container_name": []interface{}{"test"}, + Dimensions: map[string]any{ + "container_name": []any{"test"}, }, }}, expectedMatches: []*sfxpb.DataPoint{ @@ -232,8 +232,8 @@ func TestFilterSet(t *testing.T) { { name: "Doesn't match if no metric name filter specified", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "container_name": []interface{}{"mycontainer"}, + Dimensions: map[string]any{ + "container_name": []any{"mycontainer"}, }}}, expectedNonMatches: []*sfxpb.DataPoint{ { @@ -244,9 +244,9 @@ func TestFilterSet(t *testing.T) { { name: "Doesn't match metric when no (matching) dimensions exist", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "host": []interface{}{"localhost"}, - "system": []interface{}{"r4"}, + Dimensions: map[string]any{ + "host": []any{"localhost"}, + "system": []any{"r4"}, }}}, expectedNonMatches: []*sfxpb.DataPoint{ { @@ -263,9 +263,9 @@ func TestFilterSet(t *testing.T) { { name: "Matches on at least one dimension", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "host": []interface{}{"localhost"}, - "system": []interface{}{"r4"}, + Dimensions: map[string]any{ + "host": []any{"localhost"}, + "system": []any{"r4"}, }}}, expectedMatches: []*sfxpb.DataPoint{ { @@ -279,9 +279,9 @@ func TestFilterSet(t *testing.T) { { name: "Matches against all dimension pairs", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "host": []interface{}{"localhost"}, - "system": []interface{}{"r4"}, + Dimensions: map[string]any{ + "host": []any{"localhost"}, + "system": []any{"r4"}, }}}, expectedMatches: []*sfxpb.DataPoint{ { @@ -305,8 +305,8 @@ func TestFilterSet(t *testing.T) { { name: "Negated dim values take precedent", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "container_name": []interface{}{"*", "!pause", "!/.*idle/"}, + Dimensions: map[string]any{ + "container_name": []any{"*", "!pause", "!/.*idle/"}, }}}, expectedMatches: []*sfxpb.DataPoint{ { @@ -343,8 +343,8 @@ func TestFilterSet(t *testing.T) { { name: "Error creating filter with empty dimension list", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "dim": []interface{}{}, + Dimensions: map[string]any{ + "dim": []any{}, }}}, wantErr: true, wantErrMsg: "string map value in filter cannot be empty", @@ -358,8 +358,8 @@ func TestFilterSet(t *testing.T) { { name: "Error creating filter with invalid glob in dimensions", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ - "container_name": []interface{}{"cpu.*["}, + Dimensions: map[string]any{ + "container_name": []any{"cpu.*["}, }}}, wantErr: true, wantErrMsg: "unexpected end of input", @@ -367,7 +367,7 @@ func TestFilterSet(t *testing.T) { { name: "Error on invalid dimensions input", excludes: []MetricFilter{{ - Dimensions: map[string]interface{}{ + Dimensions: map[string]any{ "host": 1, }}}, wantErr: true, diff --git a/exporter/signalfxexporter/internal/translation/dpfilters/metricfilter.go b/exporter/signalfxexporter/internal/translation/dpfilters/metricfilter.go index 34f50e156431..d1865c739cb7 100644 --- a/exporter/signalfxexporter/internal/translation/dpfilters/metricfilter.go +++ b/exporter/signalfxexporter/internal/translation/dpfilters/metricfilter.go @@ -13,7 +13,7 @@ type MetricFilter struct { // A map of dimension key/values to match against. All key/values must // match a datapoint for it to be matched. The map values can be either // a single string or a list of strings. - Dimensions map[string]interface{} `mapstructure:"dimensions"` + Dimensions map[string]any `mapstructure:"dimensions"` } func (mf *MetricFilter) normalize() (map[string][]string, error) { @@ -24,7 +24,7 @@ func (mf *MetricFilter) normalize() (map[string][]string, error) { dimSet := map[string][]string{} for k, v := range mf.Dimensions { switch s := v.(type) { - case []interface{}: + case []any: var newSet []string for _, iv := range s { newSet = append(newSet, fmt.Sprintf("%v", iv)) diff --git a/exporter/signalfxexporter/internal/translation/dpfilters/propertyfilter_test.go b/exporter/signalfxexporter/internal/translation/dpfilters/propertyfilter_test.go index acbc66a651f4..b66a687820d5 100644 --- a/exporter/signalfxexporter/internal/translation/dpfilters/propertyfilter_test.go +++ b/exporter/signalfxexporter/internal/translation/dpfilters/propertyfilter_test.go @@ -66,7 +66,7 @@ property_value: '!/property.value/'`, }, } { t.Run(test.name, func(t *testing.T) { - var conf map[string]interface{} + var conf map[string]any err := yaml.Unmarshal([]byte(test.yaml), &conf) require.NoError(t, err) diff --git a/exporter/signalfxexporter/internal/translation/logdata_to_signalfxv2_test.go b/exporter/signalfxexporter/internal/translation/logdata_to_signalfxv2_test.go index c78713bb9188..42daba690590 100644 --- a/exporter/signalfxexporter/internal/translation/logdata_to_signalfxv2_test.go +++ b/exporter/signalfxexporter/internal/translation/logdata_to_signalfxv2_test.go @@ -32,7 +32,7 @@ func TestLogDataToSignalFxEvents(t *testing.T) { Timestamp: msec, Category: &userDefinedCat, Dimensions: buildNDimensions(4), - Properties: mapToEventProps(map[string]interface{}{ + Properties: mapToEventProps(map[string]any{ "env": "prod", "isActive": true, "rack": 5, @@ -132,7 +132,7 @@ func TestLogDataToSignalFxEvents(t *testing.T) { } } -func mapToEventProps(m map[string]interface{}) []*sfxpb.Property { +func mapToEventProps(m map[string]any) []*sfxpb.Property { out := make([]*sfxpb.Property, 0, len(m)) for k, v := range m { var pval sfxpb.PropertyValue diff --git a/exporter/splunkhecexporter/buffer.go b/exporter/splunkhecexporter/buffer.go index cc9c4af65fa5..592e62b6ea6d 100644 --- a/exporter/splunkhecexporter/buffer.go +++ b/exporter/splunkhecexporter/buffer.go @@ -141,7 +141,7 @@ func (p bufferPool) put(bf buffer) { func newBufferPool(bufCap uint, compressionEnabled bool) bufferPool { return bufferPool{ &sync.Pool{ - New: func() interface{} { + New: func() any { innerBuffer := &bytes.Buffer{} if compressionEnabled { return &cancellableGzipWriter{ diff --git a/exporter/splunkhecexporter/client.go b/exporter/splunkhecexporter/client.go index 55271cfd57e9..074e6776642b 100644 --- a/exporter/splunkhecexporter/client.go +++ b/exporter/splunkhecexporter/client.go @@ -56,7 +56,7 @@ type client struct { } var jsonStreamPool = sync.Pool{ - New: func() interface{} { + New: func() any { return jsoniter.NewStream(jsoniter.ConfigDefault, nil, 512) }, } diff --git a/exporter/splunkhecexporter/integration_test.go b/exporter/splunkhecexporter/integration_test.go index 766ea5b7f645..88f315d4c2d6 100644 --- a/exporter/splunkhecexporter/integration_test.go +++ b/exporter/splunkhecexporter/integration_test.go @@ -255,7 +255,7 @@ func TestSplunkHecExporterEventsToSplunk(t *testing.T) { logger.Info("Splunk received %d events in the last minute", zap.Int("no. of events", len(events))) assert.True(t, len(events) == 1) // check events fields - data, ok := events[0].(map[string]interface{}) + data, ok := events[0].(map[string]any) if !ok { logger.Info("Invalid event format") } @@ -304,7 +304,7 @@ func TestSplunkHecExporterEventsToSplunkNonDefaultIndex(t *testing.T) { logger.Info("Splunk received %d events in the last minute", zap.Int("no. of events", len(events))) assert.True(t, len(events) == 1) // check events fields - data, ok := events[0].(map[string]interface{}) + data, ok := events[0].(map[string]any) if !ok { logger.Info("Invalid event format") } @@ -386,7 +386,7 @@ func TestSplunkHecExporterTracesToSplunk(t *testing.T) { logger.Info("Splunk received %d events in the last minute", zap.Int("no. of events", len(events))) assert.True(t, len(events) == 1) // check fields - data, ok := events[0].(map[string]interface{}) + data, ok := events[0].(map[string]any) if !ok { logger.Info("Invalid event format") } diff --git a/exporter/splunkhecexporter/internal/integrationtestutils/splunk.go b/exporter/splunkhecexporter/internal/integrationtestutils/splunk.go index 09a603db83c7..f89ea09b9be4 100644 --- a/exporter/splunkhecexporter/internal/integrationtestutils/splunk.go +++ b/exporter/splunkhecexporter/internal/integrationtestutils/splunk.go @@ -17,7 +17,7 @@ import ( "time" ) -func CheckEventsFromSplunk(searchQuery string, startTime string, endTimeOptional ...string) []interface{} { +func CheckEventsFromSplunk(searchQuery string, startTime string, endTimeOptional ...string) []any { logger := log.New(os.Stdout, "", log.LstdFlags) logger.Println("-->> Splunk Search: checking events in Splunk --") user := GetConfigVariable("USER") @@ -43,7 +43,7 @@ func CheckEventsFromSplunk(searchQuery string, startTime string, endTimeOptional return results } -func getSplunkSearchResults(user string, password string, baseURL string, jobID string) []interface{} { +func getSplunkSearchResults(user string, password string, baseURL string, jobID string) []any { logger := log.New(os.Stdout, "", log.LstdFlags) eventURL := fmt.Sprintf("%s/services/search/jobs/%s/events?output_mode=json", baseURL, jobID) logger.Println("URL: " + eventURL) @@ -68,7 +68,7 @@ func getSplunkSearchResults(user string, password string, baseURL string, jobID panic(err) } - var jsonResponseEvents map[string]interface{} + var jsonResponseEvents map[string]any err = json.Unmarshal(bodyEvents, &jsonResponseEvents) if err != nil { panic(err) @@ -76,12 +76,12 @@ func getSplunkSearchResults(user string, password string, baseURL string, jobID // logger.Println("json Response Events --->") # debug // logger.Println(jsonResponseEvents) # debug - results := jsonResponseEvents["results"].([]interface{}) + results := jsonResponseEvents["results"].([]any) // logger.Println(results) return results } -func checkSearchJobStatusCode(user string, password string, baseURL string, jobID string) interface{} { +func checkSearchJobStatusCode(user string, password string, baseURL string, jobID string) any { logger := log.New(os.Stdout, "", log.LstdFlags) checkEventURL := baseURL + "/services/search/jobs/" + jobID + "?output_mode=json" logger.Println("URL: " + checkEventURL) @@ -104,14 +104,14 @@ func checkSearchJobStatusCode(user string, password string, baseURL string, jobI if err != nil { panic(err) } - var checkJSONResponse map[string]interface{} + var checkJSONResponse map[string]any err = json.Unmarshal(checkBody, &checkJSONResponse) if err != nil { panic(err) } // logger.Println(checkJSONResponse) // debug // Print isDone field from response - isDone := checkJSONResponse["entry"].([]interface{})[0].(map[string]interface{})["content"].(map[string]interface{})["isDone"] + isDone := checkJSONResponse["entry"].([]any)[0].(map[string]any)["content"].(map[string]any)["isDone"] logger.Printf("Is Splunk Search compleated [isDone flag]: %v\n", isDone) return isDone } @@ -149,7 +149,7 @@ func postSearchRequest(user string, password string, baseURL string, searchQuery if err != nil { panic(err) } - var jsonResponse map[string]interface{} + var jsonResponse map[string]any err = json.Unmarshal(body, &jsonResponse) if err != nil { panic(err) @@ -158,7 +158,7 @@ func postSearchRequest(user string, password string, baseURL string, searchQuery return jsonResponse["sid"].(string) } -func CheckMetricsFromSplunk(index string, metricName string) []interface{} { +func CheckMetricsFromSplunk(index string, metricName string) []any { logger := log.New(os.Stdout, "", log.LstdFlags) logger.Println("-->> Splunk Search: checking metrics in Splunk --") baseURL := "https://" + GetConfigVariable("HOST") + ":" + GetConfigVariable("MANAGEMENT_PORT") @@ -184,12 +184,12 @@ func CheckMetricsFromSplunk(index string, metricName string) []interface{} { } defer resp.Body.Close() - var data map[string]interface{} + var data map[string]any if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { panic(err) } - events := data["entry"].([]interface{}) + events := data["entry"].([]any) // logger.Println(events) // debug return events diff --git a/exporter/splunkhecexporter/logdata_to_splunk.go b/exporter/splunkhecexporter/logdata_to_splunk.go index a668d42413bb..065b5e7c4b94 100644 --- a/exporter/splunkhecexporter/logdata_to_splunk.go +++ b/exporter/splunkhecexporter/logdata_to_splunk.go @@ -28,7 +28,7 @@ func mapLogRecordToSplunkEvent(res pcommon.Resource, lr plog.LogRecord, config * source := config.Source sourcetype := config.SourceType index := config.Index - fields := map[string]interface{}{} + fields := map[string]any{} sourceKey := config.HecToOtelAttrs.Source sourceTypeKey := config.HecToOtelAttrs.SourceType indexKey := config.HecToOtelAttrs.Index diff --git a/exporter/splunkhecexporter/logdata_to_splunk_test.go b/exporter/splunkhecexporter/logdata_to_splunk_test.go index 388e39b05b25..dc73249e2ec5 100644 --- a/exporter/splunkhecexporter/logdata_to_splunk_test.go +++ b/exporter/splunkhecexporter/logdata_to_splunk_test.go @@ -44,7 +44,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent("mylog", ts, map[string]interface{}{"custom": "custom"}, + commonLogSplunkEvent("mylog", ts, map[string]any{"custom": "custom"}, "myhost", "myapp", "myapp-type"), }, }, @@ -68,7 +68,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent("mylog", ts, map[string]interface{}{"custom": "custom"}, + commonLogSplunkEvent("mylog", ts, map[string]any{"custom": "custom"}, "myhost", "myapp", "myapp-type"), }, }, @@ -89,7 +89,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent("mylog", ts, map[string]interface{}{}, + commonLogSplunkEvent("mylog", ts, map[string]any{}, "unknown", "source", "sourcetype"), }, }, @@ -113,7 +113,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent("mylog", ts, map[string]interface{}{"foo": float64(123)}, "myhost", "myapp", "myapp-type"), + commonLogSplunkEvent("mylog", ts, map[string]any{"foo": float64(123)}, "myhost", "myapp", "myapp-type"), }, }, { @@ -133,7 +133,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent("mylog", ts, map[string]interface{}{"custom": "custom"}, "unknown", "source", "sourcetype"), + commonLogSplunkEvent("mylog", ts, map[string]any{"custom": "custom"}, "unknown", "source", "sourcetype"), }, }, { @@ -168,7 +168,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { }, wantSplunkEvents: []*splunk.Event{ func() *splunk.Event { - event := commonLogSplunkEvent("mylog", ts, map[string]interface{}{"custom": "custom", "myseverity": "DEBUG", "myseveritynum": plog.SeverityNumber(5)}, "myhost", "mysource", "mysourcetype") + event := commonLogSplunkEvent("mylog", ts, map[string]any{"custom": "custom", "myseverity": "DEBUG", "myseveritynum": plog.SeverityNumber(5)}, "myhost", "mysource", "mysourcetype") event.Index = "myindex" return event }(), @@ -188,7 +188,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent(nil, 0, map[string]interface{}{}, "unknown", "source", "sourcetype"), + commonLogSplunkEvent(nil, 0, map[string]any{}, "unknown", "source", "sourcetype"), }, }, { @@ -207,7 +207,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: func() []*splunk.Event { - event := commonLogSplunkEvent(nil, 0, map[string]interface{}{}, "unknown", "source", "sourcetype") + event := commonLogSplunkEvent(nil, 0, map[string]any{}, "unknown", "source", "sourcetype") event.Fields["span_id"] = "0000000000000032" event.Fields["trace_id"] = "00000000000000000000000000000064" return []*splunk.Event{event} @@ -233,7 +233,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent(float64(42), ts, map[string]interface{}{"custom": "custom"}, "myhost", "myapp", "myapp-type"), + commonLogSplunkEvent(float64(42), ts, map[string]any{"custom": "custom"}, "myhost", "myapp", "myapp-type"), }, }, { @@ -256,7 +256,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent(int64(42), ts, map[string]interface{}{"custom": "custom"}, "myhost", "myapp", "myapp-type"), + commonLogSplunkEvent(int64(42), ts, map[string]any{"custom": "custom"}, "myhost", "myapp", "myapp-type"), }, }, { @@ -279,7 +279,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent(true, ts, map[string]interface{}{"custom": "custom"}, "myhost", "myapp", "myapp-type"), + commonLogSplunkEvent(true, ts, map[string]any{"custom": "custom"}, "myhost", "myapp", "myapp-type"), }, }, { @@ -306,8 +306,8 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent(map[string]interface{}{"23": float64(45), "foo": "bar"}, ts, - map[string]interface{}{"custom": "custom"}, + commonLogSplunkEvent(map[string]any{"23": float64(45), "foo": "bar"}, ts, + map[string]any{"custom": "custom"}, "myhost", "myapp", "myapp-type"), }, }, @@ -330,7 +330,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent(nil, ts, map[string]interface{}{"custom": "custom"}, + commonLogSplunkEvent(nil, ts, map[string]any{"custom": "custom"}, "myhost", "myapp", "myapp-type"), }, }, @@ -357,7 +357,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent([]interface{}{"foo"}, ts, map[string]interface{}{"custom": "custom"}, + commonLogSplunkEvent([]any{"foo"}, ts, map[string]any{"custom": "custom"}, "myhost", "myapp", "myapp-type"), }, }, @@ -382,7 +382,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return createDefaultConfig().(*Config) }, wantSplunkEvents: func() []*splunk.Event { - event := commonLogSplunkEvent("mylog", ts, map[string]interface{}{ + event := commonLogSplunkEvent("mylog", ts, map[string]any{ "resourceAttr1": "some_string", }, "myhost-resource", "myapp-resource", "myapp-type-from-resource-attr") event.Index = "index-resource" @@ -413,7 +413,7 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { return config }, wantSplunkEvents: []*splunk.Event{ - commonLogSplunkEvent("mylog", ts, map[string]interface{}{"custom": "custom", "otel.log.severity.number": plog.SeverityNumberDebug, "otel.log.severity.text": "DEBUG"}, + commonLogSplunkEvent("mylog", ts, map[string]any{"custom": "custom", "otel.log.severity.number": plog.SeverityNumberDebug, "otel.log.severity.text": "DEBUG"}, "myhost", "myapp", "myapp-type"), }, }, @@ -430,9 +430,9 @@ func Test_mapLogRecordToSplunkEvent(t *testing.T) { } func commonLogSplunkEvent( - event interface{}, + event any, ts pcommon.Timestamp, - fields map[string]interface{}, + fields map[string]any, host string, source string, sourcetype string, diff --git a/exporter/splunkhecexporter/metricdata_to_splunk.go b/exporter/splunkhecexporter/metricdata_to_splunk.go index b0798078d017..d982c958896f 100644 --- a/exporter/splunkhecexporter/metricdata_to_splunk.go +++ b/exporter/splunkhecexporter/metricdata_to_splunk.go @@ -38,7 +38,7 @@ const ( minusInfValue = "-Inf" ) -func sanitizeFloat(value float64) interface{} { +func sanitizeFloat(value float64) any { if math.IsNaN(value) { return nanValue } @@ -60,7 +60,7 @@ func mapMetricToSplunkEvent(res pcommon.Resource, m pmetric.Metric, config *Conf source := config.Source sourceType := config.SourceType index := config.Index - commonFields := map[string]interface{}{} + commonFields := map[string]any{} res.Attributes().Range(func(k string, v pcommon.Value) bool { switch k { @@ -220,7 +220,7 @@ func mapMetricToSplunkEvent(res pcommon.Resource, m pmetric.Metric, config *Conf } } -func createEvent(timestamp pcommon.Timestamp, host string, source string, sourceType string, index string, fields map[string]interface{}) *splunk.Event { +func createEvent(timestamp pcommon.Timestamp, host string, source string, sourceType string, index string, fields map[string]any) *splunk.Event { return &splunk.Event{ Time: timestampToSecondsWithMillisecondPrecision(timestamp), Host: host, @@ -246,23 +246,23 @@ func copyEventWithoutValues(event *splunk.Event) *splunk.Event { } } -func populateAttributes(fields map[string]interface{}, attributeMap pcommon.Map) { +func populateAttributes(fields map[string]any, attributeMap pcommon.Map) { attributeMap.Range(func(k string, v pcommon.Value) bool { fields[k] = v.AsString() return true }) } -func cloneMap(fields map[string]interface{}) map[string]interface{} { - newFields := make(map[string]interface{}, len(fields)) +func cloneMap(fields map[string]any) map[string]any { + newFields := make(map[string]any, len(fields)) for k, v := range fields { newFields[k] = v } return newFields } -func cloneMapWithSelector(fields map[string]interface{}, selector func(string) bool) map[string]interface{} { - newFields := make(map[string]interface{}, len(fields)) +func cloneMapWithSelector(fields map[string]any, selector func(string) bool) map[string]any { + newFields := make(map[string]any, len(fields)) for k, v := range fields { if selector(k) { newFields[k] = v diff --git a/exporter/splunkhecexporter/metricdata_to_splunk_test.go b/exporter/splunkhecexporter/metricdata_to_splunk_test.go index 436c73377c0b..4146814ec6cc 100644 --- a/exporter/splunkhecexporter/metricdata_to_splunk_test.go +++ b/exporter/splunkhecexporter/metricdata_to_splunk_test.go @@ -66,7 +66,7 @@ func Test_metricDataToSplunk(t *testing.T) { return gauge }, wantSplunkMetrics: []*splunk.Event{ - commonSplunkMetric("gauge_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []interface{}{"v0", "v1", "Gauge"}, "NaN", "", "", "", "unknown"), + commonSplunkMetric("gauge_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []any{"v0", "v1", "Gauge"}, "NaN", "", "", "", "unknown"), }, configFn: func() *Config { return createDefaultConfig().(*Config) @@ -84,7 +84,7 @@ func Test_metricDataToSplunk(t *testing.T) { return gauge }, wantSplunkMetrics: []*splunk.Event{ - commonSplunkMetric("gauge_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []interface{}{"v0", "v1", "Gauge"}, "+Inf", "", "", "", "unknown"), + commonSplunkMetric("gauge_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []any{"v0", "v1", "Gauge"}, "+Inf", "", "", "", "unknown"), }, configFn: func() *Config { return createDefaultConfig().(*Config) @@ -102,7 +102,7 @@ func Test_metricDataToSplunk(t *testing.T) { return gauge }, wantSplunkMetrics: []*splunk.Event{ - commonSplunkMetric("gauge_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []interface{}{"v0", "v1", "Gauge"}, "-Inf", "", "", "", "unknown"), + commonSplunkMetric("gauge_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []any{"v0", "v1", "Gauge"}, "-Inf", "", "", "", "unknown"), }, configFn: func() *Config { return createDefaultConfig().(*Config) @@ -196,7 +196,7 @@ func Test_metricDataToSplunk(t *testing.T) { return intGauge }, wantSplunkMetrics: []*splunk.Event{ - commonSplunkMetric("gauge_int_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []interface{}{"v0", "v1", "Gauge"}, int64Val, "mysource", "mysourcetype", "myindex", "myhost"), + commonSplunkMetric("gauge_int_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []any{"v0", "v1", "Gauge"}, int64Val, "mysource", "mysourcetype", "myindex", "myhost"), }, configFn: func() *Config { return createDefaultConfig().(*Config) @@ -226,7 +226,7 @@ func Test_metricDataToSplunk(t *testing.T) { return doubleGauge }, wantSplunkMetrics: []*splunk.Event{ - commonSplunkMetric("gauge_double_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []interface{}{"v0", "v1", "Gauge"}, doubleVal, "mysource", "mysourcetype", "myindex", "myhost"), + commonSplunkMetric("gauge_double_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []any{"v0", "v1", "Gauge"}, doubleVal, "mysource", "mysourcetype", "myindex", "myhost"), }, configFn: func() *Config { return createDefaultConfig().(*Config) @@ -272,7 +272,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "metric_name:double_histogram_with_dims_sum": float64(23), @@ -285,7 +285,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "metric_name:double_histogram_with_dims_count": uint64(7), @@ -298,7 +298,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "le": "1", @@ -312,7 +312,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "le": "2", @@ -326,7 +326,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "le": "4", @@ -340,7 +340,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "le": "+Inf", @@ -372,7 +372,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "metric_name:int_sum_with_dims": int64(62), @@ -402,7 +402,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "metric_name:double_sum_with_dims": float64(62), @@ -440,7 +440,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "metric_name:summary_sum": float64(42), @@ -453,7 +453,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "metric_name:summary_count": uint64(2), @@ -466,7 +466,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "qt": "0.5", @@ -480,7 +480,7 @@ func Test_metricDataToSplunk(t *testing.T) { SourceType: "", Event: "metric", Time: tsMSecs, - Fields: map[string]interface{}{ + Fields: map[string]any{ "k0": "v0", "k1": "v1", "qt": "0.6", @@ -529,7 +529,7 @@ func Test_metricDataToSplunk(t *testing.T) { return doubleGauge }, wantSplunkMetrics: []*splunk.Event{ - commonSplunkMetric("gauge_double_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []interface{}{"v0", "v1", "Gauge"}, doubleVal, "mysource2", "mysourcetype2", "myindex2", "myhost2"), + commonSplunkMetric("gauge_double_with_dims", tsMSecs, []string{"k0", "k1", "metric_type"}, []any{"v0", "v1", "Gauge"}, doubleVal, "mysource2", "mysourcetype2", "myindex2", "myhost2"), }, configFn: func() *Config { cfg := createDefaultConfig().(*Config) @@ -575,17 +575,17 @@ func Test_mergeEventsToMultiMetricFormat(t *testing.T) { { name: "two events that can merge", events: []*splunk.Event{ - createEvent(ts, "host", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:mem": 123, }), - createEvent(ts, "host", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:othermem": 1233.4, }), }, merged: []*splunk.Event{ - createEvent(ts, "host", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:mem": 123, "metric_name:othermem": 1233.4, @@ -595,21 +595,21 @@ func Test_mergeEventsToMultiMetricFormat(t *testing.T) { { name: "two events that cannot merge", events: []*splunk.Event{ - createEvent(ts, "host", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:mem": 123, }), - createEvent(ts, "host2", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host2", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:othermem": 1233.4, }), }, merged: []*splunk.Event{ - createEvent(ts, "host2", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host2", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:othermem": 1233.4, }), - createEvent(ts, "host", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:mem": 123, }), @@ -618,17 +618,17 @@ func Test_mergeEventsToMultiMetricFormat(t *testing.T) { { name: "two events with the same fields, but different metric value, last value wins", events: []*splunk.Event{ - createEvent(ts, "host", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:mem": 123, }), - createEvent(ts, "host", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:mem": 1233.4, }), }, merged: []*splunk.Event{ - createEvent(ts, "host", "source", "sourcetype", "index", map[string]interface{}{ + createEvent(ts, "host", "source", "sourcetype", "index", map[string]any{ "foo": "bar", "metric_name:mem": 1233.4, }), @@ -658,14 +658,14 @@ func commonSplunkMetric( metricName string, ts float64, keys []string, - values []interface{}, - val interface{}, + values []any, + val any, source string, sourcetype string, index string, host string, ) *splunk.Event { - fields := map[string]interface{}{fmt.Sprintf("metric_name:%s", metricName): val} + fields := map[string]any{fmt.Sprintf("metric_name:%s", metricName): val} for i, k := range keys { fields[k] = values[i] diff --git a/exporter/splunkhecexporter/tracedata_to_splunk.go b/exporter/splunkhecexporter/tracedata_to_splunk.go index 3732959e3cf9..a00219b928e4 100644 --- a/exporter/splunkhecexporter/tracedata_to_splunk.go +++ b/exporter/splunkhecexporter/tracedata_to_splunk.go @@ -13,17 +13,17 @@ import ( // hecEvent is a data structure holding a span event to export explicitly to Splunk HEC. type hecEvent struct { - Attributes map[string]interface{} `json:"attributes,omitempty"` - Name string `json:"name"` - Timestamp pcommon.Timestamp `json:"timestamp"` + Attributes map[string]any `json:"attributes,omitempty"` + Name string `json:"name"` + Timestamp pcommon.Timestamp `json:"timestamp"` } // hecLink is a data structure holding a span link to export explicitly to Splunk HEC. type hecLink struct { - Attributes map[string]interface{} `json:"attributes,omitempty"` - TraceID string `json:"trace_id"` - SpanID string `json:"span_id"` - TraceState string `json:"trace_state"` + Attributes map[string]any `json:"attributes,omitempty"` + TraceID string `json:"trace_id"` + SpanID string `json:"span_id"` + TraceState string `json:"trace_state"` } // hecSpanStatus is a data structure holding the status of a span to export explicitly to Splunk HEC. @@ -34,17 +34,17 @@ type hecSpanStatus struct { // hecSpan is a data structure used to export explicitly a span to Splunk HEC. type hecSpan struct { - TraceID string `json:"trace_id"` - SpanID string `json:"span_id"` - ParentSpan string `json:"parent_span_id"` - Name string `json:"name"` - Attributes map[string]interface{} `json:"attributes,omitempty"` - EndTime pcommon.Timestamp `json:"end_time"` - Kind string `json:"kind"` - Status hecSpanStatus `json:"status,omitempty"` - StartTime pcommon.Timestamp `json:"start_time"` - Events []hecEvent `json:"events,omitempty"` - Links []hecLink `json:"links,omitempty"` + TraceID string `json:"trace_id"` + SpanID string `json:"span_id"` + ParentSpan string `json:"parent_span_id"` + Name string `json:"name"` + Attributes map[string]any `json:"attributes,omitempty"` + EndTime pcommon.Timestamp `json:"end_time"` + Kind string `json:"kind"` + Status hecSpanStatus `json:"status,omitempty"` + StartTime pcommon.Timestamp `json:"start_time"` + Events []hecEvent `json:"events,omitempty"` + Links []hecLink `json:"links,omitempty"` } func mapSpanToSplunkEvent(resource pcommon.Resource, span ptrace.Span, config *Config) *splunk.Event { @@ -57,7 +57,7 @@ func mapSpanToSplunkEvent(resource pcommon.Resource, span ptrace.Span, config *C source := config.Source sourceType := config.SourceType index := config.Index - commonFields := map[string]interface{}{} + commonFields := map[string]any{} resource.Attributes().Range(func(k string, v pcommon.Value) bool { switch k { case hostKey: diff --git a/exporter/splunkhecexporter/tracedata_to_splunk_test.go b/exporter/splunkhecexporter/tracedata_to_splunk_test.go index 008edff5b17f..377970076f19 100644 --- a/exporter/splunkhecexporter/tracedata_to_splunk_test.go +++ b/exporter/splunkhecexporter/tracedata_to_splunk_test.go @@ -126,7 +126,7 @@ func commonSplunkEvent( TraceID: "", SpanID: "", ParentSpan: "", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, EndTime: 0x0, @@ -134,20 +134,20 @@ func commonSplunkEvent( Status: hecSpanStatus{Message: "", Code: "STATUS_CODE_UNSET"}, Events: []hecEvent{ { - Attributes: map[string]interface{}{"foo": "bar"}, + Attributes: map[string]any{"foo": "bar"}, Name: "myEvent", Timestamp: ts + 3, }, }, Links: []hecLink{ { - Attributes: map[string]interface{}{"foo": int64(1), "bar": false, "foobar": []interface{}{"a", "b"}}, + Attributes: map[string]any{"foo": int64(1), "bar": false, "foobar": []any{"a", "b"}}, TraceID: "12345678000000000000000000000000", SpanID: "1234000000000000", TraceState: "OK", }, }, }, - Fields: map[string]interface{}{}, + Fields: map[string]any{}, } } diff --git a/exporter/sumologicexporter/graphite_formatter.go b/exporter/sumologicexporter/graphite_formatter.go index d68bf9acd834..3d3c605834ef 100644 --- a/exporter/sumologicexporter/graphite_formatter.go +++ b/exporter/sumologicexporter/graphite_formatter.go @@ -43,7 +43,7 @@ func (gf *graphiteFormatter) escapeGraphiteString(value string) string { // format returns metric name basing on template for given fields nas metric name func (gf *graphiteFormatter) format(f fields, metricName string) string { s := gf.template - labels := make([]interface{}, 0, len(s.matches)) + labels := make([]any, 0, len(s.matches)) for _, matchset := range s.matches { if matchset == graphiteMetricNamePlaceholder { diff --git a/exporter/sumologicexporter/source_format.go b/exporter/sumologicexporter/source_format.go index e46c76683da3..3591c3be319e 100644 --- a/exporter/sumologicexporter/source_format.go +++ b/exporter/sumologicexporter/source_format.go @@ -57,7 +57,7 @@ func newSourceFormats(cfg *Config) sourceFormats { // format converts sourceFormat to string. // Takes fields and put into template (%s placeholders) in order defined by matches func (s *sourceFormat) format(f fields) string { - labels := make([]interface{}, 0, len(s.matches)) + labels := make([]any, 0, len(s.matches)) for _, matchset := range s.matches { v, ok := f.orig.Get(matchset) diff --git a/exporter/syslogexporter/rfc5424_formatter.go b/exporter/syslogexporter/rfc5424_formatter.go index fa98da4f5d50..53e1bb872cc1 100644 --- a/exporter/syslogexporter/rfc5424_formatter.go +++ b/exporter/syslogexporter/rfc5424_formatter.go @@ -73,7 +73,7 @@ func (f *rfc5424Formatter) formatStructuredData(logRecord plog.LogRecord) string sdElements := []string{} for key, val := range structuredDataAttributeValue.Map().AsRaw() { sdElements = append(sdElements, key) - vval, ok := val.(map[string]interface{}) + vval, ok := val.(map[string]any) if !ok { continue } diff --git a/exporter/tanzuobservabilityexporter/metrics_exporter_test.go b/exporter/tanzuobservabilityexporter/metrics_exporter_test.go index 701ca9be4dcb..77eca0a5c020 100644 --- a/exporter/tanzuobservabilityexporter/metrics_exporter_test.go +++ b/exporter/tanzuobservabilityexporter/metrics_exporter_test.go @@ -32,7 +32,7 @@ func verifyPushMetricsData(t *testing.T, errorOnSend bool) error { addDataPoint( 7, 1631205001, - map[string]interface{}{ + map[string]any{ "env": "prod", "bucket": 73, }, diff --git a/exporter/tanzuobservabilityexporter/metrics_test.go b/exporter/tanzuobservabilityexporter/metrics_test.go index 2bd0396f5815..d37f85942894 100644 --- a/exporter/tanzuobservabilityexporter/metrics_test.go +++ b/exporter/tanzuobservabilityexporter/metrics_test.go @@ -30,7 +30,7 @@ func TestEndToEndGaugeConsumer(t *testing.T) { addDataPoint( 432.25, 1640123456, - map[string]interface{}{"source": "renamed", "host.name": "my_source", "env": "prod"}, + map[string]any{"source": "renamed", "host.name": "my_source", "env": "prod"}, dataPoints, ) // test if service.name gets converted to service @@ -83,7 +83,7 @@ func TestEndToEndGaugeConsumerWithResAttrsIncluded(t *testing.T) { addDataPoint( 432.25, 1640123456, - map[string]interface{}{"source": "renamed", "host.name": "my_source", "env": "prod"}, + map[string]any{"source": "renamed", "host.name": "my_source", "env": "prod"}, dataPoints, ) // test if service.name gets converted to service @@ -136,7 +136,7 @@ func TestEndToEndGaugeConsumerWithAppResAttrsExcluded(t *testing.T) { addDataPoint( 432.25, 1640123456, - map[string]interface{}{"source": "renamed", "host.name": "my_source", "env": "prod"}, + map[string]any{"source": "renamed", "host.name": "my_source", "env": "prod"}, dataPoints, ) // test if service.name gets converted to service @@ -436,7 +436,7 @@ func TestSumConsumerDelta(t *testing.T) { addDataPoint( 35, 1635205001, - map[string]interface{}{ + map[string]any{ "env": "dev", }, dataPoints, @@ -444,7 +444,7 @@ func TestSumConsumerDelta(t *testing.T) { addDataPoint( 52.375, 1635205002, - map[string]interface{}{ + map[string]any{ "env": "prod", }, dataPoints, @@ -488,7 +488,7 @@ func TestSumConsumerErrorOnSend(t *testing.T) { addDataPoint( 35, 1635205001, - map[string]interface{}{ + map[string]any{ "env": "dev", }, dataPoints, @@ -496,7 +496,7 @@ func TestSumConsumerErrorOnSend(t *testing.T) { addDataPoint( 52.375, 1635205002, - map[string]interface{}{ + map[string]any{ "env": "prod", }, dataPoints, @@ -524,7 +524,7 @@ func TestSumConsumerCumulative(t *testing.T) { addDataPoint( 62.25, 1634205001, - map[string]interface{}{ + map[string]any{ "env": "dev", }, dataPoints, @@ -562,7 +562,7 @@ func TestSumConsumerUnspecified(t *testing.T) { addDataPoint( 72.25, 1634206001, - map[string]interface{}{ + map[string]any{ "env": "qa", }, dataPoints, @@ -1343,13 +1343,13 @@ func verifyGaugeConsumer(t *testing.T, errorOnSend bool) { addDataPoint( 7, 1631205001, - map[string]interface{}{"env": "prod", "bucket": 73}, + map[string]any{"env": "prod", "bucket": 73}, dataPoints, ) addDataPoint( 7.5, 1631205002, - map[string]interface{}{"env": "prod", "bucket": 73}, + map[string]any{"env": "prod", "bucket": 73}, dataPoints, ) expected := []tobsMetric{ @@ -1430,9 +1430,9 @@ func newMetric(name string, typ pmetric.MetricType) pmetric.Metric { } func addDataPoint( - value interface{}, + value any, ts int64, - tags map[string]interface{}, + tags map[string]any, slice pmetric.NumberDataPointSlice, ) { dataPoint := slice.AppendEmpty() @@ -1453,7 +1453,7 @@ func setDataPointTimestamp(ts int64, dataPoint dataPointWithTimestamp) { pcommon.NewTimestampFromTime(time.Unix(ts, 0))) } -func setDataPointValue(value interface{}, dataPoint pmetric.NumberDataPoint) { +func setDataPointValue(value any, dataPoint pmetric.NumberDataPoint) { switch v := value.(type) { case int: dataPoint.SetIntValue(int64(v)) diff --git a/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice.go b/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice.go index 9b596515bbf9..766ed741486d 100644 --- a/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice.go +++ b/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice.go @@ -72,7 +72,7 @@ func resourceToLogContents(resource pcommon.Resource) []*cls.Log_Content { serviceName = service.AsString() } - fields := map[string]interface{}{} + fields := map[string]any{} attrs.Range(func(k string, v pcommon.Value) bool { if k == conventions.AttributeServiceName || k == conventions.AttributeHostName { return true @@ -126,7 +126,7 @@ func mapLogRecordToLogService(lr plog.LogRecord, preAllocCount := 16 clsLog.Contents = make([]*cls.Log_Content, 0, preAllocCount+len(resourceContents)+len(instrumentationLibraryContents)) - fields := map[string]interface{}{} + fields := map[string]any{} lr.Attributes().Range(func(k string, v pcommon.Value) bool { fields[k] = v.AsString() return true diff --git a/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice_test.go b/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice_test.go index cbbfe6d23e43..3c388dc9dbcc 100644 --- a/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice_test.go +++ b/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice_test.go @@ -115,7 +115,7 @@ func TestConvertLogs(t *testing.T) { } } -func loadFromJSON(file string, obj interface{}) error { +func loadFromJSON(file string, obj any) error { blob, err := os.ReadFile(file) if err == nil { err = json.Unmarshal(blob, obj) diff --git a/exporter/tencentcloudlogserviceexporter/proto/cls.pb.go b/exporter/tencentcloudlogserviceexporter/proto/cls.pb.go index 0aa7ea7b0b3b..74cc5275b25e 100644 --- a/exporter/tencentcloudlogserviceexporter/proto/cls.pb.go +++ b/exporter/tencentcloudlogserviceexporter/proto/cls.pb.go @@ -356,7 +356,7 @@ func file_cls_proto_rawDescGZIP() []byte { } var file_cls_proto_msgTypes = make([]protoimpl.MessageInfo, 5) -var file_cls_proto_goTypes = []interface{}{ +var file_cls_proto_goTypes = []any{ (*Log)(nil), // 0: Log (*LogTag)(nil), // 1: LogTag (*LogGroup)(nil), // 2: LogGroup @@ -381,7 +381,7 @@ func file_cls_proto_init() { return } if !protoimpl.UnsafeEnabled { - file_cls_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + file_cls_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*Log); i { case 0: return &v.state @@ -393,7 +393,7 @@ func file_cls_proto_init() { return nil } } - file_cls_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + file_cls_proto_msgTypes[1].Exporter = func(v any, i int) any { switch v := v.(*LogTag); i { case 0: return &v.state @@ -405,7 +405,7 @@ func file_cls_proto_init() { return nil } } - file_cls_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + file_cls_proto_msgTypes[2].Exporter = func(v any, i int) any { switch v := v.(*LogGroup); i { case 0: return &v.state @@ -417,7 +417,7 @@ func file_cls_proto_init() { return nil } } - file_cls_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + file_cls_proto_msgTypes[3].Exporter = func(v any, i int) any { switch v := v.(*LogGroupList); i { case 0: return &v.state @@ -429,7 +429,7 @@ func file_cls_proto_init() { return nil } } - file_cls_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + file_cls_proto_msgTypes[4].Exporter = func(v any, i int) any { switch v := v.(*Log_Content); i { case 0: return &v.state diff --git a/exporter/zipkinexporter/testutils_test.go b/exporter/zipkinexporter/testutils_test.go index 35f7c895d405..4a49155efce4 100644 --- a/exporter/zipkinexporter/testutils_test.go +++ b/exporter/zipkinexporter/testutils_test.go @@ -12,7 +12,7 @@ import ( ) func unmarshalZipkinSpanArrayToMap(t *testing.T, jsonStr string) map[zipkinmodel.ID]*zipkinmodel.SpanModel { - var i interface{} + var i any err := json.Unmarshal([]byte(jsonStr), &i) require.NoError(t, err) @@ -20,7 +20,7 @@ func unmarshalZipkinSpanArrayToMap(t *testing.T, jsonStr string) map[zipkinmodel results := make(map[zipkinmodel.ID]*zipkinmodel.SpanModel) switch x := i.(type) { - case []interface{}: + case []any: for _, j := range x { span := jsonToSpan(t, j) results[span.ID] = span @@ -32,7 +32,7 @@ func unmarshalZipkinSpanArrayToMap(t *testing.T, jsonStr string) map[zipkinmodel return results } -func jsonToSpan(t *testing.T, j interface{}) *zipkinmodel.SpanModel { +func jsonToSpan(t *testing.T, j any) *zipkinmodel.SpanModel { b, err := json.Marshal(j) require.NoError(t, err) span := &zipkinmodel.SpanModel{} diff --git a/extension/asapauthextension/extension.go b/extension/asapauthextension/extension.go index 9959f71efe58..19f8f764c694 100644 --- a/extension/asapauthextension/extension.go +++ b/extension/asapauthextension/extension.go @@ -37,7 +37,7 @@ func createASAPClientAuthenticator(cfg *Config) (auth.Client, error) { // perRPCAuth is a gRPC credentials.PerRPCCredentials implementation that returns an 'authorization' header. type perRPCAuth struct { provisioner asap.Provisioner - privateKey interface{} + privateKey any } // GetRequestMetadata returns the request metadata to be used with the RPC. diff --git a/extension/asapauthextension/extension_test.go b/extension/asapauthextension/extension_test.go index 05d44fb20701..ea136105f4e4 100644 --- a/extension/asapauthextension/extension_test.go +++ b/extension/asapauthextension/extension_test.go @@ -30,7 +30,7 @@ var _ http.RoundTripper = (*mockRoundTripper)(nil) // mockKeyFetcher implements asap.KeyFetcher, eliminating the need to contact a key server. type mockKeyFetcher struct{} -func (k *mockKeyFetcher) Fetch(_ string) (interface{}, error) { +func (k *mockKeyFetcher) Fetch(_ string) (any, error) { return asap.NewPublicKey([]byte(publicKey)) } diff --git a/extension/basicauthextension/extension.go b/extension/basicauthextension/extension.go index 28c69b9fcb1f..b7f49b018568 100644 --- a/extension/basicauthextension/extension.go +++ b/extension/basicauthextension/extension.go @@ -173,7 +173,7 @@ type authData struct { raw string } -func (a *authData) GetAttribute(name string) interface{} { +func (a *authData) GetAttribute(name string) any { switch name { case "username": return a.username diff --git a/extension/encoding/jsonlogencodingextension/extension.go b/extension/encoding/jsonlogencodingextension/extension.go index faac8f466f65..477a837e4b88 100644 --- a/extension/encoding/jsonlogencodingextension/extension.go +++ b/extension/encoding/jsonlogencodingextension/extension.go @@ -45,7 +45,7 @@ func (e *jsonLogExtension) UnmarshalLogs(buf []byte) (plog.Logs, error) { p := plog.NewLogs() // get json logs from the buffer - jsonVal := map[string]interface{}{} + jsonVal := map[string]any{} if err := jsoniter.Unmarshal(buf, &jsonVal); err != nil { return p, err } diff --git a/extension/observer/ecsobserver/exporter.go b/extension/observer/ecsobserver/exporter.go index cd8c2e013b83..4fff5f36536f 100644 --- a/extension/observer/ecsobserver/exporter.go +++ b/extension/observer/ecsobserver/exporter.go @@ -130,7 +130,7 @@ func (e *taskExporter) exportTask(task *taskAnnotated) ([]prometheusECSTarget, e target := containerTarget mappedPort, err := task.MappedPort(container, int64(matchedTarget.Port)) if err != nil { - err = errctx.WithValues(err, map[string]interface{}{ + err = errctx.WithValues(err, map[string]any{ errKeyTarget: matchedTarget, errKeyTask: task, }) diff --git a/extension/observer/ecsobserver/internal/ecsmock/service.go b/extension/observer/ecsobserver/internal/ecsmock/service.go index 6489102f3053..1d9dc1050d74 100644 --- a/extension/observer/ecsobserver/internal/ecsmock/service.go +++ b/extension/observer/ecsobserver/internal/ecsmock/service.go @@ -455,7 +455,7 @@ func getPage(p pageInput) (*pageOutput, error) { // 'generic' Start // getArns is used by both ListTasks and ListServices -func getArns(items interface{}, arnGetter func(i int) *string) []*string { +func getArns(items any, arnGetter func(i int) *string) []*string { rv := reflect.ValueOf(items) var arns []*string for i := 0; i < rv.Len(); i++ { diff --git a/extension/observer/ecsobserver/internal/errctx/value.go b/extension/observer/ecsobserver/internal/errctx/value.go index 7cdc4ac708f4..a1d85013ac96 100644 --- a/extension/observer/ecsobserver/internal/errctx/value.go +++ b/extension/observer/ecsobserver/internal/errctx/value.go @@ -21,7 +21,7 @@ type ErrorWithValue interface { // // It does NOT do recursive Value calls (like context.Context). // For getting value from entire error chain, use ValueFrom. - Value(key string) (v interface{}, ok bool) + Value(key string) (v any, ok bool) } // WithValue attaches a single key value pair to a non nil error. @@ -35,7 +35,7 @@ type ErrorWithValue interface { // const taskErrKey = "task" // return errctx.WithValue(taskErrKey, myTask) // task, ok := errctx.ValueFrom(err, taskErrKey) -func WithValue(err error, key string, val interface{}) error { +func WithValue(err error, key string, val any) error { if err == nil { return nil } @@ -57,12 +57,12 @@ func WithValue(err error, key string, val interface{}) error { } // WithValues attaches multiple key value pairs. The behavior is similar to WithValue. -func WithValues(err error, kvs map[string]interface{}) error { +func WithValues(err error, kvs map[string]any) error { if err == nil { return nil } // make a shallow copy, and hope the values in map are not map ... - m := make(map[string]interface{}) + m := make(map[string]any) for k, v := range kvs { if k == "" { panic("empty key in WithValues") @@ -79,7 +79,7 @@ func WithValues(err error, kvs map[string]interface{}) error { // from the first ErrorWithValue that contains the key. // e.g. for an error created using errctx.WithValue(errctx.WithValue(base, "k", "v1"), "k", "v2") // ValueFrom(err, "k") returns "v2". -func ValueFrom(err error, key string) (interface{}, bool) { +func ValueFrom(err error, key string) (any, bool) { if err == nil { return nil, false } @@ -99,7 +99,7 @@ func ValueFrom(err error, key string) (interface{}, bool) { // valueError only contains one pair, which is common type valueError struct { key string - val interface{} + val any inner error } @@ -107,7 +107,7 @@ func (e *valueError) Error() string { return fmt.Sprintf("%s %s=%v", e.inner.Error(), e.key, e.val) } -func (e *valueError) Value(key string) (interface{}, bool) { +func (e *valueError) Value(key string) (any, bool) { if key == e.key { return e.val, true } @@ -120,7 +120,7 @@ func (e *valueError) Unwrap() error { // valuesError contains multiple pairs type valuesError struct { - values map[string]interface{} + values map[string]any inner error } @@ -141,7 +141,7 @@ func (e *valuesError) Error() string { return sb.String() } -func (e *valuesError) Value(key string) (interface{}, bool) { +func (e *valuesError) Value(key string) (any, bool) { v, ok := e.values[key] return v, ok } diff --git a/extension/observer/ecsobserver/internal/errctx/value_test.go b/extension/observer/ecsobserver/internal/errctx/value_test.go index cad5ba947242..09b7bb8771eb 100644 --- a/extension/observer/ecsobserver/internal/errctx/value_test.go +++ b/extension/observer/ecsobserver/internal/errctx/value_test.go @@ -35,12 +35,12 @@ func TestWithValue(t *testing.T) { } func TestWithValues(t *testing.T) { - assert.Nil(t, WithValues(nil, map[string]interface{}{"a": "b"})) + assert.Nil(t, WithValues(nil, map[string]any{"a": "b"})) assert.Panics(t, func() { - _ = WithValues(fmt.Errorf("base"), map[string]interface{}{"": "123"}) + _ = WithValues(fmt.Errorf("base"), map[string]any{"": "123"}) }) - e1 := WithValues(fmt.Errorf("base"), map[string]interface{}{"a": "b", "c": 123}) + e1 := WithValues(fmt.Errorf("base"), map[string]any{"a": "b", "c": 123}) // NOTE: we sort the key in the impl so the test is not flaky assert.Equal(t, "base a=b c=123", e1.Error()) v1, ok := ValueFrom(e1, "a") diff --git a/extension/observer/endpoints.go b/extension/observer/endpoints.go index b8cc026f6d35..7754841bc758 100644 --- a/extension/observer/endpoints.go +++ b/extension/observer/endpoints.go @@ -13,7 +13,7 @@ type ( // EndpointID unique identifies an endpoint per-observer instance. EndpointID string // EndpointEnv is a map of endpoint attributes. - EndpointEnv map[string]interface{} + EndpointEnv map[string]any // EndpointType is a type of an endpoint like a port or pod. EndpointType string ) @@ -107,7 +107,7 @@ type Pod struct { } func (p *Pod) Env() EndpointEnv { - return map[string]interface{}{ + return map[string]any{ "uid": p.UID, "name": p.Name, "labels": p.Labels, @@ -133,7 +133,7 @@ type Port struct { } func (p *Port) Env() EndpointEnv { - return map[string]interface{}{ + return map[string]any{ "name": p.Name, "port": p.Port, "pod": p.Pod.Env(), @@ -162,7 +162,7 @@ type HostPort struct { } func (h *HostPort) Env() EndpointEnv { - return map[string]interface{}{ + return map[string]any{ "process_name": h.ProcessName, "command": h.Command, "is_ipv6": h.IsIPv6, @@ -201,7 +201,7 @@ type Container struct { } func (c *Container) Env() EndpointEnv { - return map[string]interface{}{ + return map[string]any{ "name": c.Name, "image": c.Image, "tag": c.Tag, @@ -245,7 +245,7 @@ type K8sNode struct { } func (n *K8sNode) Env() EndpointEnv { - return map[string]interface{}{ + return map[string]any{ "name": n.Name, "uid": n.UID, "annotations": n.Annotations, diff --git a/extension/observer/endpointswatcher.go b/extension/observer/endpointswatcher.go index 054d0caef412..237d602f647a 100644 --- a/extension/observer/endpointswatcher.go +++ b/extension/observer/endpointswatcher.go @@ -57,7 +57,7 @@ func (ew *EndpointsWatcher) ListAndWatch(notify Notify) { return case <-ticker.C: var toNotify []NotifyID - ew.toNotify.Range(func(notifyID, _ interface{}) bool { + ew.toNotify.Range(func(notifyID, _ any) bool { toNotify = append(toNotify, notifyID.(NotifyID)) return true }) diff --git a/extension/observer/hostobserver/extension_test.go b/extension/observer/hostobserver/extension_test.go index 0e7981c9b31d..5666735ff55c 100644 --- a/extension/observer/hostobserver/extension_test.go +++ b/extension/observer/hostobserver/extension_test.go @@ -123,7 +123,7 @@ type hostPort struct { err error } -func getHostAndPort(i interface{}) hostPort { +func getHostAndPort(i any) hostPort { var host, port string var err error switch conn := i.(type) { diff --git a/extension/observer/k8sobserver/handler.go b/extension/observer/k8sobserver/handler.go index d4918bd10aec..d39dabbafe26 100644 --- a/extension/observer/k8sobserver/handler.go +++ b/extension/observer/k8sobserver/handler.go @@ -29,7 +29,7 @@ type handler struct { func (h *handler) ListEndpoints() []observer.Endpoint { var endpoints []observer.Endpoint - h.endpoints.Range(func(endpointID, endpoint interface{}) bool { + h.endpoints.Range(func(endpointID, endpoint any) bool { if e, ok := endpoint.(observer.Endpoint); ok { endpoints = append(endpoints, e) } else { @@ -41,7 +41,7 @@ func (h *handler) ListEndpoints() []observer.Endpoint { } // OnAdd is called in response to a new pod or node being detected. -func (h *handler) OnAdd(objectInterface interface{}, _ bool) { +func (h *handler) OnAdd(objectInterface any, _ bool) { var endpoints []observer.Endpoint switch object := objectInterface.(type) { @@ -59,7 +59,7 @@ func (h *handler) OnAdd(objectInterface interface{}, _ bool) { } // OnUpdate is called in response to an existing pod or node changing. -func (h *handler) OnUpdate(oldObjectInterface, newObjectInterface interface{}) { +func (h *handler) OnUpdate(oldObjectInterface, newObjectInterface any) { oldEndpoints := map[observer.EndpointID]observer.Endpoint{} newEndpoints := map[observer.EndpointID]observer.Endpoint{} @@ -131,7 +131,7 @@ func (h *handler) OnUpdate(oldObjectInterface, newObjectInterface interface{}) { } // OnDelete is called in response to a pod or node being deleted. -func (h *handler) OnDelete(objectInterface interface{}) { +func (h *handler) OnDelete(objectInterface any) { var endpoints []observer.Endpoint switch object := objectInterface.(type) { diff --git a/extension/oidcauthextension/authdata.go b/extension/oidcauthextension/authdata.go index 51358bb63d4a..db1f99146dda 100644 --- a/extension/oidcauthextension/authdata.go +++ b/extension/oidcauthextension/authdata.go @@ -13,7 +13,7 @@ type authData struct { membership []string } -func (a *authData) GetAttribute(name string) interface{} { +func (a *authData) GetAttribute(name string) any { switch name { case "subject": return a.subject diff --git a/extension/oidcauthextension/extension.go b/extension/oidcauthextension/extension.go index 4c86b03e1f9d..49c7e1b1ecd8 100644 --- a/extension/oidcauthextension/extension.go +++ b/extension/oidcauthextension/extension.go @@ -97,7 +97,7 @@ func (e *oidcExtension) authenticate(ctx context.Context, headers map[string][]s return ctx, fmt.Errorf("failed to verify token: %w", err) } - claims := map[string]interface{}{} + claims := map[string]any{} if err = idToken.Claims(&claims); err != nil { // currently, this isn't a valid condition, the Verify call a few lines above // will already attempt to parse the payload as a json and set it as the claims @@ -126,7 +126,7 @@ func (e *oidcExtension) authenticate(ctx context.Context, headers map[string][]s return client.NewContext(ctx, cl), nil } -func getSubjectFromClaims(claims map[string]interface{}, usernameClaim string, fallback string) (string, error) { +func getSubjectFromClaims(claims map[string]any, usernameClaim string, fallback string) (string, error) { if len(usernameClaim) > 0 { username, found := claims[usernameClaim] if !found { @@ -144,7 +144,7 @@ func getSubjectFromClaims(claims map[string]interface{}, usernameClaim string, f return fallback, nil } -func getGroupsFromClaims(claims map[string]interface{}, groupsClaim string) ([]string, error) { +func getGroupsFromClaims(claims map[string]any, groupsClaim string) ([]string, error) { if len(groupsClaim) > 0 { var groups []string rawGroup, ok := claims[groupsClaim] @@ -156,7 +156,7 @@ func getGroupsFromClaims(claims map[string]interface{}, groupsClaim string) ([]s groups = append(groups, v) case []string: groups = v - case []interface{}: + case []any: groups = make([]string, 0, len(v)) for i := range v { groups = append(groups, fmt.Sprintf("%v", v[i])) diff --git a/extension/oidcauthextension/extension_test.go b/extension/oidcauthextension/extension_test.go index 0cf44c64af64..fff0f83e7370 100644 --- a/extension/oidcauthextension/extension_test.go +++ b/extension/oidcauthextension/extension_test.go @@ -42,7 +42,7 @@ func TestOIDCAuthenticationSucceeded(t *testing.T) { err = p.Start(context.Background(), componenttest.NewNopHost()) require.NoError(t, err) - payload, _ := json.Marshal(map[string]interface{}{ + payload, _ := json.Marshal(map[string]any{ "sub": "jdoe@example.com", "name": "jdoe", "iss": oidcServer.URL, @@ -311,7 +311,7 @@ func TestFailedToGetGroupsClaimFromToken(t *testing.T) { err = p.Start(context.Background(), componenttest.NewNopHost()) require.NoError(t, err) - payload, _ := json.Marshal(map[string]interface{}{ + payload, _ := json.Marshal(map[string]any{ "iss": oidcServer.URL, "some-non-string-field": 123, "aud": "unit-test", @@ -332,7 +332,7 @@ func TestFailedToGetGroupsClaimFromToken(t *testing.T) { func TestSubjectFromClaims(t *testing.T) { // prepare - claims := map[string]interface{}{ + claims := map[string]any{ "username": "jdoe", } @@ -346,7 +346,7 @@ func TestSubjectFromClaims(t *testing.T) { func TestSubjectFallback(t *testing.T) { // prepare - claims := map[string]interface{}{ + claims := map[string]any{ "sub": "jdoe", } @@ -362,7 +362,7 @@ func TestGroupsFromClaim(t *testing.T) { // prepare for _, tt := range []struct { casename string - input interface{} + input any expected []string }{ { @@ -377,12 +377,12 @@ func TestGroupsFromClaim(t *testing.T) { }, { "multiple-things", - []interface{}{"department-1", 123}, + []any{"department-1", 123}, []string{"department-1", "123"}, }, } { t.Run(tt.casename, func(t *testing.T) { - claims := map[string]interface{}{ + claims := map[string]any{ "sub": "jdoe", "memberships": tt.input, } @@ -397,7 +397,7 @@ func TestGroupsFromClaim(t *testing.T) { func TestEmptyGroupsClaim(t *testing.T) { // prepare - claims := map[string]interface{}{ + claims := map[string]any{ "sub": "jdoe", } diff --git a/extension/oidcauthextension/oidc_server_test.go b/extension/oidcauthextension/oidc_server_test.go index ba021d8ca27f..920205b6ad8a 100644 --- a/extension/oidcauthextension/oidc_server_test.go +++ b/extension/oidcauthextension/oidc_server_test.go @@ -31,14 +31,14 @@ type oidcServer struct { } func newOIDCServer() (*oidcServer, error) { - jwks := map[string]interface{}{} + jwks := map[string]any{} mux := http.NewServeMux() server := httptest.NewUnstartedServer(mux) mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") - err := json.NewEncoder(w).Encode(map[string]interface{}{ + err := json.NewEncoder(w).Encode(map[string]any{ "issuer": server.URL, "jwks_uri": fmt.Sprintf("%s/.well-known/jwks.json", server.URL), }) @@ -71,7 +71,7 @@ func newOIDCServer() (*oidcServer, error) { // #nosec sum := sha1.Sum(x509Cert) - jwks["keys"] = []map[string]interface{}{{ + jwks["keys"] = []map[string]any{{ "alg": "RS256", "kty": "RSA", "use": "sig", @@ -86,7 +86,7 @@ func newOIDCServer() (*oidcServer, error) { } func (s *oidcServer) token(jsonPayload []byte) (string, error) { - jsonHeader, err := json.Marshal(map[string]interface{}{ + jsonHeader, err := json.Marshal(map[string]any{ "alg": "RS256", "typ": "JWT", }) diff --git a/internal/aws/containerinsight/utils.go b/internal/aws/containerinsight/utils.go index 95b78da8eb00..4d735e53f81a 100644 --- a/internal/aws/containerinsight/utils.go +++ b/internal/aws/containerinsight/utils.go @@ -14,10 +14,10 @@ import ( "go.uber.org/zap" ) -// SumFields takes an array of type map[string]interface{} and do +// SumFields takes an array of type map[string]any and do // the summation on the values corresponding to the same keys. -// It is assumed that the underlying type of interface{} to be float64. -func SumFields(fields []map[string]interface{}) map[string]float64 { +// It is assumed that the underlying type of any to be float64. +func SumFields(fields []map[string]any) map[string]float64 { if len(fields) == 0 { return nil } @@ -155,7 +155,7 @@ func GetUnitForMetric(metric string) string { } // ConvertToOTLPMetrics converts a field containing metric values and a tag containing the relevant labels to OTLP metrics -func ConvertToOTLPMetrics(fields map[string]interface{}, tags map[string]string, logger *zap.Logger) pmetric.Metrics { +func ConvertToOTLPMetrics(fields map[string]any, tags map[string]string, logger *zap.Logger) pmetric.Metrics { md := pmetric.NewMetrics() rms := md.ResourceMetrics() rm := rms.AppendEmpty() diff --git a/internal/aws/containerinsight/utils_test.go b/internal/aws/containerinsight/utils_test.go index b6f49d66415a..457cb7350b5c 100644 --- a/internal/aws/containerinsight/utils_test.go +++ b/internal/aws/containerinsight/utils_test.go @@ -16,7 +16,7 @@ import ( ) func TestAggregateFields(t *testing.T) { - fields := []map[string]interface{}{ + fields := []map[string]any{ { "m1": float64(1), "m2": float64(2), @@ -41,10 +41,10 @@ func TestAggregateFields(t *testing.T) { assert.Equal(t, expected, SumFields(fields)) // test empty input - assert.Nil(t, SumFields([]map[string]interface{}{})) + assert.Nil(t, SumFields([]map[string]any{})) // test single input - fields = []map[string]interface{}{ + fields = []map[string]any{ { "m1": float64(2), "m2": float64(3), @@ -97,7 +97,7 @@ func TestIsPod(t *testing.T) { assert.Equal(t, false, IsPod(TypeInstance)) } -func convertToInt64(value interface{}) int64 { +func convertToInt64(value any) int64 { switch t := value.(type) { case int: return int64(t) @@ -118,7 +118,7 @@ func convertToInt64(value interface{}) int64 { return -1 } -func convertToFloat64(value interface{}) float64 { +func convertToFloat64(value any) float64 { switch t := value.(type) { case float32: return float64(t) @@ -131,7 +131,7 @@ func convertToFloat64(value interface{}) float64 { return -1.0 } -func checkMetricsAreExpected(t *testing.T, md pmetric.Metrics, fields map[string]interface{}, tags map[string]string, +func checkMetricsAreExpected(t *testing.T, md pmetric.Metrics, fields map[string]any, tags map[string]string, expectedUnits map[string]string) { rms := md.ResourceMetrics() @@ -181,14 +181,14 @@ func checkMetricsAreExpected(t *testing.T, md pmetric.Metrics, fields map[string } func TestConvertToOTLPMetricsForInvalidMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var tags map[string]string var md pmetric.Metrics now := time.Now() timestamp := strconv.FormatInt(now.UnixNano(), 10) // test container metrics - fields = map[string]interface{}{ + fields = map[string]any{ "node_cpu_limit": "an invalid value", } @@ -209,7 +209,7 @@ func TestConvertToOTLPMetricsForInvalidMetrics(t *testing.T) { } func TestConvertToOTLPMetricsForClusterMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var expectedUnits map[string]string var tags map[string]string var md pmetric.Metrics @@ -217,7 +217,7 @@ func TestConvertToOTLPMetricsForClusterMetrics(t *testing.T) { timestamp := strconv.FormatInt(now.UnixNano(), 10) // test cluster-level metrics - fields = map[string]interface{}{ + fields = map[string]any{ "cluster_failed_node_count": int64(1), "cluster_node_count": int64(3), } @@ -235,7 +235,7 @@ func TestConvertToOTLPMetricsForClusterMetrics(t *testing.T) { checkMetricsAreExpected(t, md, fields, tags, expectedUnits) // test cluster namespace metrics - fields = map[string]interface{}{ + fields = map[string]any{ "namespace_number_of_running_pods": int64(8), } expectedUnits = map[string]string{ @@ -251,7 +251,7 @@ func TestConvertToOTLPMetricsForClusterMetrics(t *testing.T) { checkMetricsAreExpected(t, md, fields, tags, expectedUnits) // test cluster service metrics - fields = map[string]interface{}{ + fields = map[string]any{ "service_number_of_running_pods": int64(8), } expectedUnits = map[string]string{ @@ -269,7 +269,7 @@ func TestConvertToOTLPMetricsForClusterMetrics(t *testing.T) { } func TestConvertToOTLPMetricsForContainerMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var expectedUnits map[string]string var tags map[string]string var md pmetric.Metrics @@ -277,7 +277,7 @@ func TestConvertToOTLPMetricsForContainerMetrics(t *testing.T) { timestamp := strconv.FormatInt(now.UnixNano(), 10) // test container metrics - fields = map[string]interface{}{ + fields = map[string]any{ "container_cpu_limit": int64(200), "container_cpu_request": int64(200), "container_cpu_usage_system": 2.7662289817161336, @@ -340,7 +340,7 @@ func TestConvertToOTLPMetricsForContainerMetrics(t *testing.T) { checkMetricsAreExpected(t, md, fields, tags, expectedUnits) // test container filesystem metrics - fields = map[string]interface{}{ + fields = map[string]any{ "container_filesystem_available": int64(0), "container_filesystem_capacity": int64(21462233088), "container_filesystem_usage": int64(36864), @@ -372,7 +372,7 @@ func TestConvertToOTLPMetricsForContainerMetrics(t *testing.T) { } func TestConvertToOTLPMetricsForNodeMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var expectedUnits map[string]string var tags map[string]string var md pmetric.Metrics @@ -380,7 +380,7 @@ func TestConvertToOTLPMetricsForNodeMetrics(t *testing.T) { timestamp := strconv.FormatInt(now.UnixNano(), 10) // test container metrics - fields = map[string]interface{}{ + fields = map[string]any{ "node_cpu_limit": int64(4000), "node_cpu_request": int64(610), "node_cpu_reserved_capacity": 15.25, @@ -467,7 +467,7 @@ func TestConvertToOTLPMetricsForNodeMetrics(t *testing.T) { } func TestConvertToOTLPMetricsForNodeDiskIOMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var expectedUnits map[string]string var tags map[string]string var md pmetric.Metrics @@ -475,7 +475,7 @@ func TestConvertToOTLPMetricsForNodeDiskIOMetrics(t *testing.T) { timestamp := strconv.FormatInt(now.UnixNano(), 10) // test container metrics - fields = map[string]interface{}{ + fields = map[string]any{ "node_diskio_io_service_bytes_async": 6704.018980016907, "node_diskio_io_service_bytes_read": float64(0), "node_diskio_io_service_bytes_sync": 284.2693560431197, @@ -516,7 +516,7 @@ func TestConvertToOTLPMetricsForNodeDiskIOMetrics(t *testing.T) { } func TestConvertToOTLPMetricsForNodeFSMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var expectedUnits map[string]string var tags map[string]string var md pmetric.Metrics @@ -524,7 +524,7 @@ func TestConvertToOTLPMetricsForNodeFSMetrics(t *testing.T) { timestamp := strconv.FormatInt(now.UnixNano(), 10) // test container metrics - fields = map[string]interface{}{ + fields = map[string]any{ "node_filesystem_available": int64(4271607808), "node_filesystem_capacity": int64(21462233088), "node_filesystem_inodes": int64(8450312), @@ -558,7 +558,7 @@ func TestConvertToOTLPMetricsForNodeFSMetrics(t *testing.T) { } func TestConvertToOTLPMetricsForNodeNetMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var expectedUnits map[string]string var tags map[string]string var md pmetric.Metrics @@ -566,7 +566,7 @@ func TestConvertToOTLPMetricsForNodeNetMetrics(t *testing.T) { timestamp := strconv.FormatInt(now.UnixNano(), 10) // test container metrics - fields = map[string]interface{}{ + fields = map[string]any{ "node_interface_network_rx_bytes": 294.8620421098953, "node_interface_network_rx_dropped": float64(0), "node_interface_network_rx_errors": float64(0), @@ -604,14 +604,14 @@ func TestConvertToOTLPMetricsForNodeNetMetrics(t *testing.T) { } func TestConvertToOTLPMetricsForPodMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var expectedUnits map[string]string var tags map[string]string var md pmetric.Metrics now := time.Now() timestamp := strconv.FormatInt(now.UnixNano(), 10) - fields = map[string]interface{}{ + fields = map[string]any{ "pod_cpu_limit": int64(200), "pod_cpu_request": int64(200), "pod_cpu_reserved_capacity": float64(5), @@ -705,7 +705,7 @@ func TestConvertToOTLPMetricsForPodMetrics(t *testing.T) { } func TestConvertToOTLPMetricsForPodNetMetrics(t *testing.T) { - var fields map[string]interface{} + var fields map[string]any var expectedUnits map[string]string var tags map[string]string var md pmetric.Metrics @@ -713,7 +713,7 @@ func TestConvertToOTLPMetricsForPodNetMetrics(t *testing.T) { timestamp := strconv.FormatInt(now.UnixNano(), 10) // test container metrics - fields = map[string]interface{}{ + fields = map[string]any{ "node_interface_network_rx_bytes": 294.8620421098953, "node_interface_network_rx_dropped": float64(0), "node_interface_network_rx_errors": float64(0), diff --git a/internal/aws/cwlogs/pusher.go b/internal/aws/cwlogs/pusher.go index 08ff8f549de2..cee16a6941bb 100644 --- a/internal/aws/cwlogs/pusher.go +++ b/internal/aws/cwlogs/pusher.go @@ -249,7 +249,7 @@ func (p *logPusher) ForceFlush() error { return nil } -func (p *logPusher) pushEventBatch(req interface{}) error { +func (p *logPusher) pushEventBatch(req any) error { // http://docs.aws.amazon.com/goto/SdkForGoV1/logs-2014-03-28/PutLogEvents // The log events in the batch must be in chronological ordered by their diff --git a/internal/aws/k8s/k8sclient/endpoint.go b/internal/aws/k8s/k8sclient/endpoint.go index da5ae371349f..9605774b2a5f 100644 --- a/internal/aws/k8s/k8sclient/endpoint.go +++ b/internal/aws/k8s/k8sclient/endpoint.go @@ -150,7 +150,7 @@ func (c *epClient) shutdown() { c.stopped = true } -func transformFuncEndpoint(obj interface{}) (interface{}, error) { +func transformFuncEndpoint(obj any) (any, error) { endpoint, ok := obj.(*v1.Endpoints) if !ok { return nil, fmt.Errorf("input obj %v is not Endpoint type", obj) diff --git a/internal/aws/k8s/k8sclient/endpoint_test.go b/internal/aws/k8s/k8sclient/endpoint_test.go index 7adb4e9ce9ee..abd7aea3a778 100644 --- a/internal/aws/k8s/k8sclient/endpoint_test.go +++ b/internal/aws/k8s/k8sclient/endpoint_test.go @@ -359,7 +359,7 @@ func setUpEndpointClient() (*epClient, chan struct{}) { func TestEpClient_PodKeyToServiceNames(t *testing.T) { client, stopChan := setUpEndpointClient() defer close(stopChan) - arrays := make([]interface{}, len(endpointsArray)) + arrays := make([]any, len(endpointsArray)) for i := range arrays { arrays[i] = endpointsArray[i] } diff --git a/internal/aws/k8s/k8sclient/helpers_test.go b/internal/aws/k8s/k8sclient/helpers_test.go index f0ade57b9a42..cce65edac1f5 100644 --- a/internal/aws/k8s/k8sclient/helpers_test.go +++ b/internal/aws/k8s/k8sclient/helpers_test.go @@ -67,8 +67,8 @@ func removeTempKubeConfig() { kubeConfigPath = "" } -func convertToInterfaceArray(objArray []runtime.Object) []interface{} { - array := make([]interface{}, len(objArray)) +func convertToInterfaceArray(objArray []runtime.Object) []any { + array := make([]any, len(objArray)) for i := range array { array[i] = objArray[i] } diff --git a/internal/aws/k8s/k8sclient/job.go b/internal/aws/k8s/k8sclient/job.go index 3f264616e8ec..3076e3546433 100644 --- a/internal/aws/k8s/k8sclient/job.go +++ b/internal/aws/k8s/k8sclient/job.go @@ -137,7 +137,7 @@ func (c *jobClient) shutdown() { c.stopped = true } -func transformFuncJob(obj interface{}) (interface{}, error) { +func transformFuncJob(obj any) (any, error) { job, ok := obj.(*batchv1.Job) if !ok { return nil, fmt.Errorf("input obj %v is not Job type", obj) diff --git a/internal/aws/k8s/k8sclient/job_test.go b/internal/aws/k8s/k8sclient/job_test.go index 38842d25eadc..44bd57e96127 100644 --- a/internal/aws/k8s/k8sclient/job_test.go +++ b/internal/aws/k8s/k8sclient/job_test.go @@ -44,7 +44,7 @@ func TestJobClient_JobToCronJob(t *testing.T) { fakeClientSet := fake.NewSimpleClientset(jobArray...) client, _ := newJobClient(fakeClientSet, zap.NewNop(), setOption) - jobs := make([]interface{}, len(jobArray)) + jobs := make([]any, len(jobArray)) for i := range jobArray { jobs[i] = jobArray[i] } diff --git a/internal/aws/k8s/k8sclient/node.go b/internal/aws/k8s/k8sclient/node.go index 37ebad0ab5d6..1f940beafdde 100644 --- a/internal/aws/k8s/k8sclient/node.go +++ b/internal/aws/k8s/k8sclient/node.go @@ -137,7 +137,7 @@ func (c *nodeClient) shutdown() { c.stopped = true } -func transformFuncNode(obj interface{}) (interface{}, error) { +func transformFuncNode(obj any) (any, error) { node, ok := obj.(*v1.Node) if !ok { return nil, fmt.Errorf("input obj %v is not Node type", obj) diff --git a/internal/aws/k8s/k8sclient/node_test.go b/internal/aws/k8s/k8sclient/node_test.go index bdc4b39aa7bf..c24106690f70 100644 --- a/internal/aws/k8s/k8sclient/node_test.go +++ b/internal/aws/k8s/k8sclient/node_test.go @@ -15,7 +15,7 @@ import ( "k8s.io/client-go/kubernetes/fake" ) -var nodeArray = []interface{}{ +var nodeArray = []any{ &v1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "ip-192-168-200-63.eu-west-1.compute.internal", diff --git a/internal/aws/k8s/k8sclient/obj_store.go b/internal/aws/k8s/k8sclient/obj_store.go index 90c9d35252ab..8f51bd5bf185 100644 --- a/internal/aws/k8s/k8sclient/obj_store.go +++ b/internal/aws/k8s/k8sclient/obj_store.go @@ -20,16 +20,16 @@ type ObjStore struct { mu sync.RWMutex refreshed bool - objs map[types.UID]interface{} + objs map[types.UID]any - transformFunc func(interface{}) (interface{}, error) + transformFunc func(any) (any, error) logger *zap.Logger } -func NewObjStore(transformFunc func(interface{}) (interface{}, error), logger *zap.Logger) *ObjStore { +func NewObjStore(transformFunc func(any) (any, error), logger *zap.Logger) *ObjStore { return &ObjStore{ transformFunc: transformFunc, - objs: map[types.UID]interface{}{}, + objs: map[types.UID]any{}, logger: logger, } } @@ -49,14 +49,14 @@ func (s *ObjStore) GetResetRefreshStatus() bool { // Add implements the Add method of the store interface. // Add adds an entry to the ObjStore. -func (s *ObjStore) Add(obj interface{}) error { +func (s *ObjStore) Add(obj any) error { o, err := meta.Accessor(obj) if err != nil { s.logger.Warn(fmt.Sprintf("Cannot find the metadata for %v.", obj)) return err } - var toCacheObj interface{} + var toCacheObj any if toCacheObj, err = s.transformFunc(obj); err != nil { s.logger.Warn(fmt.Sprintf("Failed to update obj %v in the cached store.", obj)) return err @@ -73,13 +73,13 @@ func (s *ObjStore) Add(obj interface{}) error { // Update implements the Update method of the store interface. // Update updates the existing entry in the ObjStore. -func (s *ObjStore) Update(obj interface{}) error { +func (s *ObjStore) Update(obj any) error { return s.Add(obj) } // Delete implements the Delete method of the store interface. // Delete deletes an existing entry in the ObjStore. -func (s *ObjStore) Delete(obj interface{}) error { +func (s *ObjStore) Delete(obj any) error { o, err := meta.Accessor(obj) if err != nil { @@ -98,11 +98,11 @@ func (s *ObjStore) Delete(obj interface{}) error { // List implements the List method of the store interface. // List lists all the objects in the ObjStore -func (s *ObjStore) List() []interface{} { +func (s *ObjStore) List() []any { s.mu.RLock() defer s.mu.RUnlock() - result := make([]interface{}, 0, len(s.objs)) + result := make([]any, 0, len(s.objs)) for _, v := range s.objs { result = append(result, v) } @@ -123,20 +123,20 @@ func (s *ObjStore) ListKeys() []string { } // Get implements the Get method of the store interface. -func (s *ObjStore) Get(_ interface{}) (item interface{}, exists bool, err error) { +func (s *ObjStore) Get(_ any) (item any, exists bool, err error) { return nil, false, nil } // GetByKey implements the GetByKey method of the store interface. -func (s *ObjStore) GetByKey(_ string) (item interface{}, exists bool, err error) { +func (s *ObjStore) GetByKey(_ string) (item any, exists bool, err error) { return nil, false, nil } // Replace implements the Replace method of the store interface. // Replace will delete the contents of the store, using instead the given list. -func (s *ObjStore) Replace(list []interface{}, _ string) error { +func (s *ObjStore) Replace(list []any, _ string) error { s.mu.Lock() - s.objs = map[types.UID]interface{}{} + s.objs = map[types.UID]any{} s.mu.Unlock() for _, o := range list { diff --git a/internal/aws/k8s/k8sclient/obj_store_test.go b/internal/aws/k8s/k8sclient/obj_store_test.go index bfdc1f6fb210..7f9f223a5732 100644 --- a/internal/aws/k8s/k8sclient/obj_store_test.go +++ b/internal/aws/k8s/k8sclient/obj_store_test.go @@ -15,11 +15,11 @@ import ( "k8s.io/apimachinery/pkg/types" ) -var transformFunc = func(v interface{}) (interface{}, error) { +var transformFunc = func(v any) (any, error) { return v, nil } -var transformFuncWithError = func(v interface{}) (interface{}, error) { +var transformFuncWithError = func(v any) (any, error) { return v, errors.New("an error") } @@ -46,7 +46,7 @@ func TestGetByKey(t *testing.T) { func TestGetListKeys(t *testing.T) { o := NewObjStore(transformFunc, zap.NewNop()) - o.objs = map[types.UID]interface{}{ + o.objs = map[types.UID]any{ "20036b33-cb03-489b-b778-e516b4dae519": "a", "7966452b-d896-4f5b-84a1-afbd4febc366": "b", "55f4f8dd-c4ae-4c18-947c-c0880bb0e05e": "c", @@ -64,7 +64,7 @@ func TestGetListKeys(t *testing.T) { func TestGetList(t *testing.T) { o := NewObjStore(transformFunc, zap.NewNop()) - o.objs = map[types.UID]interface{}{ + o.objs = map[types.UID]any{ "20036b33-cb03-489b-b778-e516b4dae519": "a", } val := o.List() @@ -78,7 +78,7 @@ func TestDelete(t *testing.T) { err := o.Delete(nil) assert.NotNil(t, err) - o.objs = map[types.UID]interface{}{ + o.objs = map[types.UID]any{ "bc5f5839-f62e-44b9-a79e-af250d92dcb1": &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "bc5f5839-f62e-44b9-a79e-af250d92dcb1", @@ -146,7 +146,7 @@ func TestAdd(t *testing.T) { func TestUpdate(t *testing.T) { o := NewObjStore(transformFunc, zap.NewNop()) - o.objs = map[types.UID]interface{}{ + o.objs = map[types.UID]any{ "bc5f5839-f62e-44b9-a79e-af250d92dcb1": &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "bc5f5839-f62e-44b9-a79e-af250d92dcb1", @@ -184,7 +184,7 @@ func TestUpdate(t *testing.T) { func TestReplace(t *testing.T) { o := NewObjStore(transformFuncWithError, zap.NewNop()) - objArray := []interface{}{ + objArray := []any{ &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "bc5f5839-f62e-44b9-a79e-af250d92dcb1", diff --git a/internal/aws/k8s/k8sclient/pod.go b/internal/aws/k8s/k8sclient/pod.go index 2414437ad863..48e0aaa06f2c 100644 --- a/internal/aws/k8s/k8sclient/pod.go +++ b/internal/aws/k8s/k8sclient/pod.go @@ -100,7 +100,7 @@ func (c *podClient) shutdown() { c.stopped = true } -func transformFuncPod(obj interface{}) (interface{}, error) { +func transformFuncPod(obj any) (any, error) { pod, ok := obj.(*v1.Pod) if !ok { return nil, fmt.Errorf("input obj %v is not Pod type", obj) diff --git a/internal/aws/k8s/k8sclient/pod_test.go b/internal/aws/k8s/k8sclient/pod_test.go index 899eff2776d6..1ddb57110595 100644 --- a/internal/aws/k8s/k8sclient/pod_test.go +++ b/internal/aws/k8s/k8sclient/pod_test.go @@ -15,7 +15,7 @@ import ( "k8s.io/client-go/kubernetes/fake" ) -var podArray = []interface{}{ +var podArray = []any{ &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "bc5f5839-f62e-44b9-a79e-af250d92dcb1", diff --git a/internal/aws/k8s/k8sclient/replicaset.go b/internal/aws/k8s/k8sclient/replicaset.go index 5d3639883edb..cfa73d773e67 100644 --- a/internal/aws/k8s/k8sclient/replicaset.go +++ b/internal/aws/k8s/k8sclient/replicaset.go @@ -139,7 +139,7 @@ func (c *replicaSetClient) shutdown() { c.stopped = true } -func transformFuncReplicaSet(obj interface{}) (interface{}, error) { +func transformFuncReplicaSet(obj any) (any, error) { replicaSet, ok := obj.(*appsv1.ReplicaSet) if !ok { return nil, fmt.Errorf("input obj %v is not ReplicaSet type", obj) diff --git a/internal/aws/k8s/k8sclient/replicaset_test.go b/internal/aws/k8s/k8sclient/replicaset_test.go index 3bc0bda3532c..cc4061f85431 100644 --- a/internal/aws/k8s/k8sclient/replicaset_test.go +++ b/internal/aws/k8s/k8sclient/replicaset_test.go @@ -51,7 +51,7 @@ func TestReplicaSetClient_ReplicaSetToDeployment(t *testing.T) { fakeClientSet := fake.NewSimpleClientset(replicaSetArray...) client, _ := newReplicaSetClient(fakeClientSet, zap.NewNop(), setOption) - replicaSets := make([]interface{}, len(replicaSetArray)) + replicaSets := make([]any, len(replicaSetArray)) for i := range replicaSetArray { replicaSets[i] = replicaSetArray[i] } diff --git a/internal/aws/metrics/metric_calculator.go b/internal/aws/metrics/metric_calculator.go index 80562799f287..2e1d1d722c07 100644 --- a/internal/aws/metrics/metric_calculator.go +++ b/internal/aws/metrics/metric_calculator.go @@ -18,13 +18,13 @@ const ( // CalculateFunc defines how to process metric values by the calculator. It // passes previously received MetricValue, and the current raw value and timestamp // as parameters. Returns true if the calculation is executed successfully. -type CalculateFunc func(prev *MetricValue, val interface{}, timestamp time.Time) (interface{}, bool) +type CalculateFunc func(prev *MetricValue, val any, timestamp time.Time) (any, bool) func NewFloat64DeltaCalculator() MetricCalculator { return NewMetricCalculator(calculateDelta) } -func calculateDelta(prev *MetricValue, val interface{}, _ time.Time) (interface{}, bool) { +func calculateDelta(prev *MetricValue, val any, _ time.Time) (any, bool) { var deltaValue float64 if prev != nil { deltaValue = val.(float64) - prev.RawValue.(float64) @@ -57,10 +57,10 @@ func NewMetricCalculator(calculateFunc CalculateFunc) MetricCalculator { // https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/eacfde3fcbd46ba60a6db0e9a41977390c4883bd/internal/aws/metrics/metric_calculator.go#L88-L91 // and delegates the calculation with value and timestamp back to CalculateFunc for the result. Returns // true if the calculation is executed successfully. -func (rm *MetricCalculator) Calculate(mKey Key, value interface{}, timestamp time.Time) (interface{}, bool) { +func (rm *MetricCalculator) Calculate(mKey Key, value any, timestamp time.Time) (any, bool) { cacheStore := rm.cache - var result interface{} + var result any var done bool rm.lock.Lock() @@ -87,11 +87,11 @@ func (rm *MetricCalculator) Shutdown() error { } type Key struct { - MetricMetadata interface{} + MetricMetadata any MetricLabels attribute.Distinct } -func NewKey(metricMetadata interface{}, labels map[string]string) Key { +func NewKey(metricMetadata any, labels map[string]string) Key { kvs := make([]attribute.KeyValue, 0, len(labels)) var sortable attribute.Sortable for k, v := range labels { @@ -107,7 +107,7 @@ func NewKey(metricMetadata interface{}, labels map[string]string) Key { } type MetricValue struct { - RawValue interface{} + RawValue any Timestamp time.Time } @@ -116,14 +116,14 @@ type MetricValue struct { type MapWithExpiry struct { lock *sync.Mutex ttl time.Duration - entries map[interface{}]*MetricValue + entries map[any]*MetricValue doneChan chan struct{} } // NewMapWithExpiry automatically starts a sweeper to enforce the maps TTL. ShutDown() must be called to ensure that these // go routines are properly cleaned up ShutDown() must be called. func NewMapWithExpiry(ttl time.Duration) *MapWithExpiry { - m := &MapWithExpiry{lock: &sync.Mutex{}, ttl: ttl, entries: make(map[interface{}]*MetricValue), doneChan: make(chan struct{})} + m := &MapWithExpiry{lock: &sync.Mutex{}, ttl: ttl, entries: make(map[any]*MetricValue), doneChan: make(chan struct{})} go m.sweep(m.CleanUp) return m } diff --git a/internal/aws/metrics/metric_calculator_test.go b/internal/aws/metrics/metric_calculator_test.go index 4a53ef16192f..27a32d0f62ae 100644 --- a/internal/aws/metrics/metric_calculator_test.go +++ b/internal/aws/metrics/metric_calculator_test.go @@ -53,7 +53,7 @@ func TestFloat64RateCalculatorWithTooFrequentUpdate(t *testing.T) { } func newFloat64RateCalculator() MetricCalculator { - return NewMetricCalculator(func(prev *MetricValue, val interface{}, timestampMs time.Time) (interface{}, bool) { + return NewMetricCalculator(func(prev *MetricValue, val any, timestampMs time.Time) (any, bool) { if prev != nil { deltaTimestampMs := timestampMs.Sub(prev.Timestamp).Milliseconds() deltaValue := val.(float64) - prev.RawValue.(float64) @@ -125,7 +125,7 @@ func TestMapWithExpiryCleanup(t *testing.T) { // the allotted sleep time. store := &MapWithExpiry{ ttl: time.Millisecond, - entries: make(map[interface{}]*MetricValue), + entries: make(map[any]*MetricValue), lock: &sync.Mutex{}, } value1 := rand.Float64() diff --git a/internal/aws/proxy/conn.go b/internal/aws/proxy/conn.go index 10b7bbee7f8e..24d48d65407e 100644 --- a/internal/aws/proxy/conn.go +++ b/internal/aws/proxy/conn.go @@ -158,7 +158,7 @@ func getRegionFromECSMetadata() (string, error) { return "", fmt.Errorf("unable to open ECS metadata file, path: %s, error: %w", metadataFilePath, err) } - var dat map[string]interface{} + var dat map[string]any err = json.Unmarshal(metadata, &dat) if err != nil { return "", fmt.Errorf("invalid json in read ECS metadata file content, path: %s, error: %w", diff --git a/internal/aws/xray/tracesegment.go b/internal/aws/xray/tracesegment.go index f33552ce7622..0fe82ce2d5b0 100644 --- a/internal/aws/xray/tracesegment.go +++ b/internal/aws/xray/tracesegment.go @@ -36,18 +36,18 @@ type Segment struct { Links []SpanLinkData `json:"links,omitempty"` // Optional fields for both Segment and subsegments - TraceID *string `json:"trace_id,omitempty"` - EndTime *float64 `json:"end_time,omitempty"` - InProgress *bool `json:"in_progress,omitempty"` - HTTP *HTTPData `json:"http,omitempty"` - Fault *bool `json:"fault,omitempty"` - Error *bool `json:"error,omitempty"` - Throttle *bool `json:"throttle,omitempty"` - Cause *CauseData `json:"cause,omitempty"` - AWS *AWSData `json:"aws,omitempty"` - Annotations map[string]interface{} `json:"annotations,omitempty"` - Metadata map[string]map[string]interface{} `json:"metadata,omitempty"` - Subsegments []Segment `json:"subsegments,omitempty"` + TraceID *string `json:"trace_id,omitempty"` + EndTime *float64 `json:"end_time,omitempty"` + InProgress *bool `json:"in_progress,omitempty"` + HTTP *HTTPData `json:"http,omitempty"` + Fault *bool `json:"fault,omitempty"` + Error *bool `json:"error,omitempty"` + Throttle *bool `json:"throttle,omitempty"` + Cause *CauseData `json:"cause,omitempty"` + AWS *AWSData `json:"aws,omitempty"` + Annotations map[string]any `json:"annotations,omitempty"` + Metadata map[string]map[string]any `json:"metadata,omitempty"` + Subsegments []Segment `json:"subsegments,omitempty"` // (for both embedded and independent) subsegment-only (optional) fields. // Please refer to https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-subsegments @@ -219,8 +219,8 @@ type RequestData struct { // ResponseData provides the shape for unmarshalling the response field. type ResponseData struct { - Status *int64 `json:"status,omitempty"` - ContentLength interface{} `json:"content_length,omitempty"` + Status *int64 `json:"status,omitempty"` + ContentLength any `json:"content_length,omitempty"` } // ECSData provides the shape for unmarshalling the ecs field. @@ -269,7 +269,7 @@ type ServiceData struct { // SpanLinkData provides the shape for unmarshalling the span links in the span link field. type SpanLinkData struct { - TraceID *string `json:"trace_id"` - SpanID *string `json:"id"` - Attributes map[string]interface{} `json:"attributes,omitempty"` + TraceID *string `json:"trace_id"` + SpanID *string `json:"id"` + Attributes map[string]any `json:"attributes,omitempty"` } diff --git a/internal/aws/xray/tracesegment_test.go b/internal/aws/xray/tracesegment_test.go index c39cadbaa364..6edffec73b2b 100644 --- a/internal/aws/xray/tracesegment_test.go +++ b/internal/aws/xray/tracesegment_test.go @@ -106,10 +106,10 @@ var rawExpectedSegmentForInstrumentedApp = Segment{ }, }, }, - Annotations: map[string]interface{}{ + Annotations: map[string]any{ "DDB.DescribeExistingTableAndPutToMissingTable.Annotation": "anno", }, - Metadata: map[string]map[string]interface{}{ + Metadata: map[string]map[string]any{ "default": { "DDB.DescribeExistingTableAndPutToMissingTable.AddMetadata": "meta", }, @@ -152,9 +152,9 @@ var rawExpectedSegmentForInstrumentedApp = Segment{ Name: String("connect"), StartTime: aws.Float64(1596566305.5357504), EndTime: aws.Float64(1596566305.575329), - Metadata: map[string]map[string]interface{}{ + Metadata: map[string]map[string]any{ "http": { - "connection": map[string]interface{}{ + "connection": map[string]any{ "reused": false, "was_idle": false, }, @@ -166,11 +166,11 @@ var rawExpectedSegmentForInstrumentedApp = Segment{ Name: String("dns"), StartTime: aws.Float64(1596566305.5357957), EndTime: aws.Float64(1596566305.5373216), - Metadata: map[string]map[string]interface{}{ + Metadata: map[string]map[string]any{ "http": { - "dns": map[string]interface{}{ - "addresses": []interface{}{ - map[string]interface{}{ + "dns": map[string]any{ + "addresses": []any{ + map[string]any{ "IP": "52.94.10.94", "Zone": "", }, @@ -185,9 +185,9 @@ var rawExpectedSegmentForInstrumentedApp = Segment{ Name: String("dial"), StartTime: aws.Float64(1596566305.5373297), EndTime: aws.Float64(1596566305.537964), - Metadata: map[string]map[string]interface{}{ + Metadata: map[string]map[string]any{ "http": { - "connect": map[string]interface{}{ + "connect": map[string]any{ "network": "tcp", }, }, @@ -198,9 +198,9 @@ var rawExpectedSegmentForInstrumentedApp = Segment{ Name: String("tls"), StartTime: aws.Float64(1596566305.5380135), EndTime: aws.Float64(1596566305.5753162), - Metadata: map[string]map[string]interface{}{ + Metadata: map[string]map[string]any{ "http": { - "tls": map[string]interface{}{ + "tls": map[string]any{ "cipher_suite": 49199.0, "did_resume": false, "negotiated_protocol": "http/1.1", diff --git a/internal/common/maps/maps.go b/internal/common/maps/maps.go index e3ff3658e490..8f8a3bc9e136 100644 --- a/internal/common/maps/maps.go +++ b/internal/common/maps/maps.go @@ -4,8 +4,8 @@ package maps // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/common/maps" // MergeRawMaps merges n maps with a later map's keys overriding earlier maps. -func MergeRawMaps(maps ...map[string]interface{}) map[string]interface{} { - ret := map[string]interface{}{} +func MergeRawMaps(maps ...map[string]any) map[string]any { + ret := map[string]any{} for _, m := range maps { for k, v := range m { diff --git a/internal/common/ttlmap/ttl_map.go b/internal/common/ttlmap/ttl_map.go index 154e9e3e2040..9485feb4e518 100644 --- a/internal/common/ttlmap/ttl_map.go +++ b/internal/common/ttlmap/ttl_map.go @@ -39,19 +39,19 @@ func (m *TTLMap) Start() { // Put adds the passed-in key and value to the underlying map. The current time // is attached to the entry for periodic expiration checking and eviction when // necessary. -func (m *TTLMap) Put(k string, v interface{}) { +func (m *TTLMap) Put(k string, v any) { m.md.put(k, v, time.Now().Unix()) } // Get returns the object in the underlying map at the given key. If there is no // value at that key, Get returns nil. -func (m *TTLMap) Get(k string) interface{} { +func (m *TTLMap) Get(k string) any { return m.md.get(k) } type entry struct { createTime int64 - v interface{} + v any } type ttlMapData struct { @@ -68,13 +68,13 @@ func newTTLMapData(maxAgeSeconds int64) *ttlMapData { } } -func (d *ttlMapData) put(k string, v interface{}, currTime int64) { +func (d *ttlMapData) put(k string, v any, currTime int64) { d.mux.Lock() d.m[k] = entry{v: v, createTime: currTime} d.mux.Unlock() } -func (d *ttlMapData) get(k string) interface{} { +func (d *ttlMapData) get(k string) any { d.mux.Lock() defer d.mux.Unlock() entry, ok := d.m[k] diff --git a/internal/coreinternal/attraction/attraction.go b/internal/coreinternal/attraction/attraction.go index 26689d9c4451..970bb91c2d4e 100644 --- a/internal/coreinternal/attraction/attraction.go +++ b/internal/coreinternal/attraction/attraction.go @@ -38,7 +38,7 @@ type ActionKeyValue struct { // Value specifies the value to populate for the key. // The type of the value is inferred from the configuration. - Value interface{} `mapstructure:"value"` + Value any `mapstructure:"value"` // A regex pattern must be specified for the action EXTRACT. // It uses the attribute specified by `key' to extract values from diff --git a/internal/coreinternal/attraction/attraction_test.go b/internal/coreinternal/attraction/attraction_test.go index 6873137b85bf..ac0f3ada90c3 100644 --- a/internal/coreinternal/attraction/attraction_test.go +++ b/internal/coreinternal/attraction/attraction_test.go @@ -23,8 +23,8 @@ import ( // Common structure for all the Tests type testCase struct { name string - inputAttributes map[string]interface{} - expectedAttributes map[string]interface{} + inputAttributes map[string]any + expectedAttributes map[string]any } // runIndividualTestCase is the common logic of passing trace data through a configured attributes processor. @@ -42,18 +42,18 @@ func TestAttributes_InsertValue(t *testing.T) { // Ensure `attribute1` is set for spans with no attributes. { name: "InsertEmptyAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": int64(123), }, }, // Ensure `attribute1` is set. { name: "InsertKeyNoExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "anotherkey": "bob", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "anotherkey": "bob", "attribute1": int64(123), }, @@ -61,10 +61,10 @@ func TestAttributes_InsertValue(t *testing.T) { // Ensures no insert is performed because the keys `attribute1` already exists. { name: "InsertKeyExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "attribute1": "bob", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": "bob", }, }, @@ -91,26 +91,26 @@ func TestAttributes_InsertFromAttribute(t *testing.T) { // Ensure no attribute is inserted because because attributes do not exist. { name: "InsertEmptyAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, // Ensure no attribute is inserted because because from_attribute `string_key` does not exist. { name: "InsertMissingFromAttribute", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "bob": int64(1), }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "bob": int64(1), }, }, // Ensure `string key` is set. { name: "InsertAttributeExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "anotherkey": int64(8892342), }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "anotherkey": int64(8892342), "string key": int64(8892342), }, @@ -118,11 +118,11 @@ func TestAttributes_InsertFromAttribute(t *testing.T) { // Ensures no insert is performed because the keys `string key` already exist. { name: "InsertKeysExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "anotherkey": int64(8892342), "string key": "here", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "anotherkey": int64(8892342), "string key": "here", }, @@ -149,26 +149,26 @@ func TestAttributes_UpdateValue(t *testing.T) { // Ensure no changes to the span as there is no attributes map. { name: "UpdateNoAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, // Ensure no changes to the span as the key does not exist. { name: "UpdateKeyNoExist", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "foo", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "foo", }, }, // Ensure the attribute `db.secret` is updated. { name: "UpdateAttributes", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "db.secret": "password1234", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "db.secret": "redacted", }, }, @@ -195,37 +195,37 @@ func TestAttributes_UpdateFromAttribute(t *testing.T) { // Ensure no changes to the span as there is no attributes map. { name: "UpdateNoAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, // Ensure the attribute `boo` isn't updated because attribute `foo` isn't present in the span. { name: "UpdateKeyNoExistFromAttribute", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "bob", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "bob", }, }, // Ensure no updates as the target key `boo` doesn't exists. { name: "UpdateKeyNoExistMainAttributed", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "foo": "over there", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "foo": "over there", }, }, // Ensure no updates as the target key `boo` doesn't exists. { name: "UpdateKeyFromExistingAttribute", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "foo": "there is a party over here", "boo": "not here", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "foo": "there is a party over here", "boo": "there is a party over here", }, @@ -252,18 +252,18 @@ func TestAttributes_UpsertValue(t *testing.T) { // Ensure `region` is set for spans with no attributes. { name: "UpsertNoAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "region": "planet-earth", }, }, // Ensure `region` is inserted for spans with some attributes(the key doesn't exist). { name: "UpsertAttributeNoExist", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "mission": "to mars", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "mission": "to mars", "region": "planet-earth", }, @@ -271,11 +271,11 @@ func TestAttributes_UpsertValue(t *testing.T) { // Ensure `region` is updated for spans with the attribute key `region`. { name: "UpsertAttributeExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "mission": "to mars", "region": "solar system", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "mission": "to mars", "region": "planet-earth", }, @@ -302,27 +302,27 @@ func TestAttributes_Extract(t *testing.T) { // Ensure `new_user_key` is not set for spans with no attributes. { name: "UpsertEmptyAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, // Ensure `new_user_key` is not inserted for spans with missing attribute `user_key`. { name: "No extract with no target key", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "ghosts are scary", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "ghosts are scary", }, }, // Ensure `new_user_key` is not inserted for spans with missing attribute `user_key`. { name: "No extract with non string target key", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "ghosts are scary", "user_key": int64(1234), }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "ghosts are scary", "user_key": int64(1234), }, @@ -331,11 +331,11 @@ func TestAttributes_Extract(t *testing.T) { // `user_key` because `user_key` does not match the regular expression. { name: "No extract with no pattern matching", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user_key": "does not match", "boo": "ghosts are scary", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user_key": "does not match", "boo": "ghosts are scary", }, @@ -345,11 +345,11 @@ func TestAttributes_Extract(t *testing.T) { // expression. { name: "No extract with no pattern matching", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user_key": "/api/v1/document/12345678/update", "boo": "ghosts are scary", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user_key": "/api/v1/document/12345678/update", "boo": "ghosts are scary", }, @@ -357,11 +357,11 @@ func TestAttributes_Extract(t *testing.T) { // Ensure `new_user_key` and `version` is inserted for spans with attribute `user_key`. { name: "Extract insert new values.", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user_key": "/api/v1/document/12345678/update/v1", "foo": "casper the friendly ghost", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user_key": "/api/v1/document/12345678/update/v1", "new_user_key": "12345678", "version": "v1", @@ -371,13 +371,13 @@ func TestAttributes_Extract(t *testing.T) { // Ensure `new_user_key` and `version` is updated for spans with attribute `user_key`. { name: "Extract updates existing values ", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user_key": "/api/v1/document/12345678/update/v1", "new_user_key": "2321", "version": "na", "foo": "casper the friendly ghost", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user_key": "/api/v1/document/12345678/update/v1", "new_user_key": "12345678", "version": "v1", @@ -387,12 +387,12 @@ func TestAttributes_Extract(t *testing.T) { // Ensure `new_user_key` is updated and `version` is inserted for spans with attribute `user_key`. { name: "Extract upserts values", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user_key": "/api/v1/document/12345678/update/v1", "new_user_key": "2321", "foo": "casper the friendly ghost", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user_key": "/api/v1/document/12345678/update/v1", "new_user_key": "12345678", "version": "v1", @@ -423,27 +423,27 @@ func TestAttributes_UpsertFromAttribute(t *testing.T) { // Ensure `new_user_key` is not set for spans with no attributes. { name: "UpsertEmptyAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, // Ensure `new_user_key` is not inserted for spans with missing attribute `user_key`. { name: "UpsertFromAttributeNoExist", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "ghosts are scary", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "ghosts are scary", }, }, // Ensure `new_user_key` is inserted for spans with attribute `user_key`. { name: "UpsertFromAttributeExistsInsert", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user_key": int64(2245), "foo": "casper the friendly ghost", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user_key": int64(2245), "new_user_key": int64(2245), "foo": "casper the friendly ghost", @@ -452,12 +452,12 @@ func TestAttributes_UpsertFromAttribute(t *testing.T) { // Ensure `new_user_key` is updated for spans with attribute `user_key`. { name: "UpsertFromAttributeExistsUpdate", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user_key": int64(2245), "new_user_key": int64(5422), "foo": "casper the friendly ghost", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user_key": int64(2245), "new_user_key": int64(2245), "foo": "casper the friendly ghost", @@ -485,41 +485,41 @@ func TestAttributes_Delete(t *testing.T) { // Ensure the span contains no changes. { name: "DeleteEmptyAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, // Ensure the span contains no changes because the key doesn't exist. { name: "DeleteAttributeNoExist", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "ghosts are scary", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "ghosts are scary", }, }, // Ensure `duplicate_key` is deleted for spans with the attribute set. { name: "DeleteAttributeExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "duplicate_key": 3245.6, "original_key": 3245.6, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "original_key": 3245.6, }, }, // Ensure `duplicate_key` is deleted by regexp for spans with the attribute set. { name: "DeleteAttributeExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "duplicate_key_a": 3245.6, "duplicate_key_b": 3245.6, "duplicate_key_c": 3245.6, "original_key": 3245.6, "not_duplicate_key": 3246.6, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "original_key": 3245.6, "not_duplicate_key": 3246.6, }, @@ -546,27 +546,27 @@ func TestAttributes_Delete_Regexp(t *testing.T) { // Ensure the span contains no changes. { name: "DeleteEmptyAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, // Ensure the span contains no changes because the key doesn't exist. { name: "DeleteAttributeNoExist", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "ghosts are scary", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "ghosts are scary", }, }, // Ensure `duplicate_key` is deleted for spans with the attribute set. { name: "DeleteAttributeExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "duplicate_key": 3245.6, "original_key": 3245.6, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "original_key": 3245.6, }, }, @@ -600,77 +600,77 @@ func TestAttributes_HashValue(t *testing.T) { // Ensure no changes to the span as there is no attributes map. { name: "HashNoAttributes", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, // Ensure no changes to the span as the key does not exist. { name: "HashKeyNoExist", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "foo", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "foo", }, }, // Ensure string data types are hashed correctly { name: "HashString", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "updateme": "foo", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "updateme": hash([]byte("foo")), }, }, // Ensure int data types are hashed correctly { name: "HashInt", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "updateme": intVal, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "updateme": hash(intBytes), }, }, // Ensure double data types are hashed correctly { name: "HashDouble", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "updateme": doubleVal, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "updateme": hash(doubleBytes), }, }, // Ensure bool data types are hashed correctly { name: "HashBoolTrue", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "updateme": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "updateme": hash([]byte{1}), }, }, // Ensure bool data types are hashed correctly { name: "HashBoolFalse", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "updateme": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "updateme": hash([]byte{0}), }, }, // Ensure regex pattern is being used { name: "HashRegex", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "updatemebyregexp": false, "donotupdatemebyregexp": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "updatemebyregexp": hash([]byte{0}), "donotupdatemebyregexp": false, }, @@ -695,10 +695,10 @@ func TestAttributes_HashValue(t *testing.T) { func TestAttributes_FromAttributeNoChange(t *testing.T) { tc := testCase{ name: "FromAttributeNoChange", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "boo": "ghosts are scary", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "boo": "ghosts are scary", }, } @@ -726,10 +726,10 @@ func TestAttributes_Ordering(t *testing.T) { // 3. delete `operation`. { name: "OrderingApplyAllSteps", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "foo": "casper the friendly ghost", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "foo": "casper the friendly ghost", "svc.operation": "default", }, @@ -740,11 +740,11 @@ func TestAttributes_Ordering(t *testing.T) { // 3. delete `operation`. { name: "OrderingOperationExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "foo": "casper the friendly ghost", "operation": "arithmetic", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "foo": "casper the friendly ghost", "svc.operation": "arithmetic", }, @@ -756,11 +756,11 @@ func TestAttributes_Ordering(t *testing.T) { // 3. delete `operation`. { name: "OrderingSvcOperationExists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "foo": "casper the friendly ghost", "svc.operation": "some value", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "foo": "casper the friendly ghost", "svc.operation": "default", }, @@ -772,12 +772,12 @@ func TestAttributes_Ordering(t *testing.T) { // 3. delete `operation`. { name: "OrderingBothAttributesExist", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "foo": "casper the friendly ghost", "operation": "arithmetic", "svc.operation": "add", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "foo": "casper the friendly ghost", "svc.operation": "arithmetic", }, @@ -949,9 +949,9 @@ func sha2Hash(b []byte) string { return fmt.Sprintf("%x", h.Sum(nil)) } -type mockInfoAuth map[string]interface{} +type mockInfoAuth map[string]any -func (a mockInfoAuth) GetAttribute(name string) interface{} { +func (a mockInfoAuth) GetAttribute(name string) any { return a[name] } @@ -978,49 +978,49 @@ func TestFromContext(t *testing.T) { testCases := []struct { name string ctx context.Context - expectedAttributes map[string]interface{} + expectedAttributes map[string]any action *ActionKeyValue }{ { name: "no_metadata", ctx: context.TODO(), - expectedAttributes: map[string]interface{}{}, + expectedAttributes: map[string]any{}, action: &ActionKeyValue{Key: "dest", FromContext: "source", Action: INSERT}, }, { name: "no_value", ctx: mdCtx, - expectedAttributes: map[string]interface{}{}, + expectedAttributes: map[string]any{}, action: &ActionKeyValue{Key: "dest", FromContext: "source", Action: INSERT}, }, { name: "single_value", ctx: mdCtx, - expectedAttributes: map[string]interface{}{"dest": "single_val"}, + expectedAttributes: map[string]any{"dest": "single_val"}, action: &ActionKeyValue{Key: "dest", FromContext: "source_single_val", Action: INSERT}, }, { name: "multiple_values", ctx: mdCtx, - expectedAttributes: map[string]interface{}{"dest": "first_val;second_val"}, + expectedAttributes: map[string]any{"dest": "first_val;second_val"}, action: &ActionKeyValue{Key: "dest", FromContext: "source_multiple_val", Action: INSERT}, }, { name: "with_metadata_prefix_single_value", ctx: mdCtx, - expectedAttributes: map[string]interface{}{"dest": "single_val"}, + expectedAttributes: map[string]any{"dest": "single_val"}, action: &ActionKeyValue{Key: "dest", FromContext: "metadata.source_single_val", Action: INSERT}, }, { name: "with_auth_prefix_single_value", ctx: mdCtx, - expectedAttributes: map[string]interface{}{"dest": "auth_val"}, + expectedAttributes: map[string]any{"dest": "auth_val"}, action: &ActionKeyValue{Key: "dest", FromContext: "auth.source_auth_val", Action: INSERT}, }, { name: "with_auth_prefix_no_value", ctx: mdCtx, - expectedAttributes: map[string]interface{}{}, + expectedAttributes: map[string]any{}, action: &ActionKeyValue{Key: "dest", FromContext: "auth.unknown_val", Action: INSERT}, }, } diff --git a/internal/coreinternal/metricstestutil/metric_diff.go b/internal/coreinternal/metricstestutil/metric_diff.go index 0f4b3400cc19..8fc5a20b9eac 100644 --- a/internal/coreinternal/metricstestutil/metric_diff.go +++ b/internal/coreinternal/metricstestutil/metric_diff.go @@ -15,8 +15,8 @@ import ( // testing. Two MetricDatas, when compared, could produce a list of MetricDiffs containing all of their // differences, which could be used to correct the differences between the expected and actual values. type MetricDiff struct { - ExpectedValue interface{} - ActualValue interface{} + ExpectedValue any + ActualValue any Msg string } @@ -308,15 +308,15 @@ func diffMetricAttrs(diffs []*MetricDiff, expected pcommon.Map, actual pcommon.M return diffs } -func diff(diffs []*MetricDiff, expected interface{}, actual interface{}, msg string) []*MetricDiff { +func diff(diffs []*MetricDiff, expected any, actual any, msg string) []*MetricDiff { out, _ := diffValues(diffs, expected, actual, msg) return out } func diffValues( diffs []*MetricDiff, - expected interface{}, - actual interface{}, + expected any, + actual any, msg string, ) ([]*MetricDiff, bool) { if !reflect.DeepEqual(expected, actual) { diff --git a/internal/coreinternal/timeutils/parser.go b/internal/coreinternal/timeutils/parser.go index b242b0ffd859..8af480096f2d 100644 --- a/internal/coreinternal/timeutils/parser.go +++ b/internal/coreinternal/timeutils/parser.go @@ -49,7 +49,7 @@ func ParseGotime(layout string, value any, location *time.Location) (time.Time, return SetTimestampYear(timeValue), nil } -func parseGotime(layout string, value interface{}, location *time.Location) (time.Time, error) { +func parseGotime(layout string, value any, location *time.Location) (time.Time, error) { var str string switch v := value.(type) { case string: diff --git a/internal/datadog/agent_test.go b/internal/datadog/agent_test.go index de754786417c..09133528eda6 100644 --- a/internal/datadog/agent_test.go +++ b/internal/datadog/agent_test.go @@ -41,7 +41,7 @@ func TestTraceAgent(t *testing.T) { { LibName: "libname", LibVersion: "1.2", - Attributes: map[string]interface{}{}, + Attributes: map[string]any{}, Spans: []*testutil.OTLPSpan{ {Name: "1"}, {Name: "2"}, @@ -51,7 +51,7 @@ func TestTraceAgent(t *testing.T) { { LibName: "other-libname", LibVersion: "2.1", - Attributes: map[string]interface{}{}, + Attributes: map[string]any{}, Spans: []*testutil.OTLPSpan{ {Name: "4", TraceID: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}, {Name: "5", TraceID: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}}, diff --git a/internal/filter/filterconfig/config.go b/internal/filter/filterconfig/config.go index 8859e001339e..4f77f99fe65f 100644 --- a/internal/filter/filterconfig/config.go +++ b/internal/filter/filterconfig/config.go @@ -198,7 +198,7 @@ type Attribute struct { // Values specifies the value to match against. // If it is not set, any value will match. - Value interface{} `mapstructure:"value"` + Value any `mapstructure:"value"` } // InstrumentationLibrary specifies the instrumentation library and optional version to match against. diff --git a/internal/filter/filterexpr/matcher.go b/internal/filter/filterexpr/matcher.go index f85f2c0dff68..f10603067ba6 100644 --- a/internal/filter/filterexpr/matcher.go +++ b/internal/filter/filterexpr/matcher.go @@ -14,7 +14,7 @@ import ( ) var vmPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &vm.VM{} }, } diff --git a/internal/filter/filterexpr/matcher_test.go b/internal/filter/filterexpr/matcher_test.go index 9610db0d580f..6e69c15e92a5 100644 --- a/internal/filter/filterexpr/matcher_test.go +++ b/internal/filter/filterexpr/matcher_test.go @@ -148,20 +148,20 @@ func TestNonMatchGaugeDataPointByMetricAndHasLabel(t *testing.T) { func TestMatchGaugeDataPointByMetricAndHasLabel(t *testing.T) { expression := `MetricName == 'my.metric' && HasLabel("foo")` - assert.True(t, testMatchGauge(t, "my.metric", expression, map[string]interface{}{"foo": ""})) + assert.True(t, testMatchGauge(t, "my.metric", expression, map[string]any{"foo": ""})) } func TestMatchGaugeDataPointByMetricAndLabelValue(t *testing.T) { expression := `MetricName == 'my.metric' && Label("foo") == "bar"` - assert.False(t, testMatchGauge(t, "my.metric", expression, map[string]interface{}{"foo": ""})) + assert.False(t, testMatchGauge(t, "my.metric", expression, map[string]any{"foo": ""})) } func TestNonMatchGaugeDataPointByMetricAndLabelValue(t *testing.T) { expression := `MetricName == 'my.metric' && Label("foo") == "bar"` - assert.False(t, testMatchGauge(t, "my.metric", expression, map[string]interface{}{"foo": ""})) + assert.False(t, testMatchGauge(t, "my.metric", expression, map[string]any{"foo": ""})) } -func testMatchGauge(t *testing.T, metricName, expression string, lbls map[string]interface{}) bool { +func testMatchGauge(t *testing.T, metricName, expression string, lbls map[string]any) bool { matcher, err := NewMatcher(expression) require.NoError(t, err) m := pmetric.NewMetric() diff --git a/internal/filter/filtermatcher/filtermatcher_test.go b/internal/filter/filtermatcher/filtermatcher_test.go index a7a3ca4bd508..4f755078bd90 100644 --- a/internal/filter/filtermatcher/filtermatcher_test.go +++ b/internal/filter/filtermatcher/filtermatcher_test.go @@ -194,9 +194,9 @@ func Test_Matching_False(t *testing.T) { } attrs := pcommon.NewMap() - assert.NoError(t, attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, attrs.FromRaw(map[string]any{ "keyInt": 123, - "keyMap": map[string]interface{}{}, + "keyMap": map[string]any{}, })) library := pcommon.NewInstrumentationScope() @@ -349,7 +349,7 @@ func Test_Matching_True(t *testing.T) { } attrs := pcommon.NewMap() - assert.NoError(t, attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, attrs.FromRaw(map[string]any{ "keyString": "arithmetic", "keyInt": 123, "keyDouble": 3245.6, diff --git a/internal/filter/filterottl/functions.go b/internal/filter/filterottl/functions.go index 1fd4eda51bd3..82c9c6b79997 100644 --- a/internal/filter/filterottl/functions.go +++ b/internal/filter/filterottl/functions.go @@ -64,7 +64,7 @@ func createMatchFunction[K any](_ ottl.FunctionContext, _ ottl.Arguments) (ottl. } func matchFn[K any]() (ottl.ExprFunc[K], error) { - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { return true, nil }, nil } @@ -89,7 +89,7 @@ func createHasAttributeOnDatapointFunction(_ ottl.FunctionContext, oArgs ottl.Ar } func hasAttributeOnDatapoint(key string, expectedVal string) (ottl.ExprFunc[ottlmetric.TransformContext], error) { - return func(ctx context.Context, tCtx ottlmetric.TransformContext) (interface{}, error) { + return func(ctx context.Context, tCtx ottlmetric.TransformContext) (any, error) { return checkDataPoints(tCtx, key, &expectedVal) }, nil } @@ -113,12 +113,12 @@ func createHasAttributeKeyOnDatapointFunction(_ ottl.FunctionContext, oArgs ottl } func hasAttributeKeyOnDatapoint(key string) (ottl.ExprFunc[ottlmetric.TransformContext], error) { - return func(ctx context.Context, tCtx ottlmetric.TransformContext) (interface{}, error) { + return func(ctx context.Context, tCtx ottlmetric.TransformContext) (any, error) { return checkDataPoints(tCtx, key, nil) }, nil } -func checkDataPoints(tCtx ottlmetric.TransformContext, key string, expectedVal *string) (interface{}, error) { +func checkDataPoints(tCtx ottlmetric.TransformContext, key string, expectedVal *string) (any, error) { metric := tCtx.GetMetric() //exhaustive:enforce switch metric.Type() { diff --git a/internal/k8sconfig/config.go b/internal/k8sconfig/config.go index b3ac3d13f334..b1ef343d97b2 100644 --- a/internal/k8sconfig/config.go +++ b/internal/k8sconfig/config.go @@ -19,7 +19,7 @@ import ( func init() { k8sruntime.ReallyCrash = false - k8sruntime.PanicHandlers = []func(interface{}){} + k8sruntime.PanicHandlers = []func(any){} } // AuthType describes the type of authentication to use for the K8s API diff --git a/internal/k8stest/k8s_collector.go b/internal/k8stest/k8s_collector.go index 6b259f7cb873..ebfe5035b28e 100644 --- a/internal/k8stest/k8s_collector.go +++ b/internal/k8stest/k8s_collector.go @@ -60,7 +60,7 @@ func WaitForCollectorToStart(t *testing.T, client *dynamic.DynamicClient, podNam if len(list.Items) == 0 { return false } - podPhase = list.Items[0].Object["status"].(map[string]interface{})["phase"].(string) + podPhase = list.Items[0].Object["status"].(map[string]any)["phase"].(string) return podPhase == "Running" }, time.Duration(podTimeoutMinutes)*time.Minute, 50*time.Millisecond, "collector pod haven't started within %d minutes, latest pod phase is %s", podTimeoutMinutes, podPhase) diff --git a/internal/k8stest/k8s_telemetrygen.go b/internal/k8stest/k8s_telemetrygen.go index 21cb5d6dfa04..e9aed1a856e0 100644 --- a/internal/k8stest/k8s_telemetrygen.go +++ b/internal/k8stest/k8s_telemetrygen.go @@ -67,7 +67,7 @@ func WaitForTelemetryGenToStart(t *testing.T, client *dynamic.DynamicClient, pod if len(list.Items) == 0 { return false } - podPhase = list.Items[0].Object["status"].(map[string]interface{})["phase"].(string) + podPhase = list.Items[0].Object["status"].(map[string]any)["phase"].(string) return podPhase == "Running" }, time.Duration(podTimeoutMinutes)*time.Minute, 50*time.Millisecond, "telemetrygen pod of Workload [%s] in datatype [%s] haven't started within %d minutes, latest pod phase is %s", workload, dataType, podTimeoutMinutes, podPhase) diff --git a/internal/metadataproviders/consul/metadata.go b/internal/metadataproviders/consul/metadata.go index e43ec968f047..5f393a1e3e39 100644 --- a/internal/metadataproviders/consul/metadata.go +++ b/internal/metadataproviders/consul/metadata.go @@ -16,7 +16,7 @@ type Provider interface { type consulMetadataImpl struct { consulClient *api.Client - allowedLabels map[string]interface{} + allowedLabels map[string]any } type Metadata struct { @@ -26,7 +26,7 @@ type Metadata struct { HostMetadata map[string]string } -func NewProvider(client *api.Client, allowedLabels map[string]interface{}) Provider { +func NewProvider(client *api.Client, allowedLabels map[string]any) Provider { return &consulMetadataImpl{consulClient: client, allowedLabels: allowedLabels} } diff --git a/internal/metadataproviders/consul/metadata_test.go b/internal/metadataproviders/consul/metadata_test.go index 189534e59fbf..16b2f8bac30e 100644 --- a/internal/metadataproviders/consul/metadata_test.go +++ b/internal/metadataproviders/consul/metadata_test.go @@ -36,7 +36,7 @@ func TestConsulHappyPath(t *testing.T) { config := api.DefaultConfig() config.Address = ts.URL - allowedLabels := map[string]interface{}{ + allowedLabels := map[string]any{ "test": nil, } client, err := api.NewClient(config) diff --git a/internal/sharedcomponent/sharedcomponent.go b/internal/sharedcomponent/sharedcomponent.go index cc4860f26cd3..d610fcab716f 100644 --- a/internal/sharedcomponent/sharedcomponent.go +++ b/internal/sharedcomponent/sharedcomponent.go @@ -15,19 +15,19 @@ import ( // SharedComponents a map that keeps reference of all created instances for a given configuration, // and ensures that the shared state is started and stopped only once. type SharedComponents struct { - comps map[interface{}]*SharedComponent + comps map[any]*SharedComponent } // NewSharedComponents returns a new empty SharedComponents. func NewSharedComponents() *SharedComponents { return &SharedComponents{ - comps: make(map[interface{}]*SharedComponent), + comps: make(map[any]*SharedComponent), } } // GetOrAdd returns the already created instance if exists, otherwise creates a new instance // and adds it to the map of references. -func (scs *SharedComponents) GetOrAdd(key interface{}, create func() component.Component) *SharedComponent { +func (scs *SharedComponents) GetOrAdd(key any, create func() component.Component) *SharedComponent { if c, ok := scs.comps[key]; ok { return c } diff --git a/internal/splunk/common.go b/internal/splunk/common.go index 49888c390540..7792b73381da 100644 --- a/internal/splunk/common.go +++ b/internal/splunk/common.go @@ -38,13 +38,13 @@ type AccessTokenPassthroughConfig struct { // Event represents a metric in Splunk HEC format type Event struct { - Time float64 `json:"time,omitempty"` // optional epoch time - set to zero if the event timestamp is missing or unknown (will be added at indexing time) - Host string `json:"host"` // hostname - Source string `json:"source,omitempty"` // optional description of the source of the event; typically the app's name - SourceType string `json:"sourcetype,omitempty"` // optional name of a Splunk parsing configuration; this is usually inferred by Splunk - Index string `json:"index,omitempty"` // optional name of the Splunk index to store the event in; not required if the token has a default index set in Splunk - Event interface{} `json:"event"` // type of event: set to "metric" or nil if the event represents a metric, or is the payload of the event. - Fields map[string]interface{} `json:"fields,omitempty"` // dimensions and metric data + Time float64 `json:"time,omitempty"` // optional epoch time - set to zero if the event timestamp is missing or unknown (will be added at indexing time) + Host string `json:"host"` // hostname + Source string `json:"source,omitempty"` // optional description of the source of the event; typically the app's name + SourceType string `json:"sourcetype,omitempty"` // optional name of a Splunk parsing configuration; this is usually inferred by Splunk + Index string `json:"index,omitempty"` // optional name of the Splunk index to store the event in; not required if the token has a default index set in Splunk + Event any `json:"event"` // type of event: set to "metric" or nil if the event represents a metric, or is the payload of the event. + Fields map[string]any `json:"fields,omitempty"` // dimensions and metric data } // IsMetric returns true if the Splunk event is a metric. @@ -53,8 +53,8 @@ func (e Event) IsMetric() bool { } // GetMetricValues extracts metric key value pairs from a Splunk HEC metric. -func (e Event) GetMetricValues() map[string]interface{} { - values := map[string]interface{}{} +func (e Event) GetMetricValues() map[string]any { + values := map[string]any{} for k, v := range e.Fields { if strings.HasPrefix(k, "metric_name:") { values[k[12:]] = v @@ -66,13 +66,13 @@ func (e Event) GetMetricValues() map[string]interface{} { // UnmarshalJSON unmarshals the JSON representation of an event func (e *Event) UnmarshalJSON(b []byte) error { rawEvent := struct { - Time interface{} `json:"time,omitempty"` - Host string `json:"host"` - Source string `json:"source,omitempty"` - SourceType string `json:"sourcetype,omitempty"` - Index string `json:"index,omitempty"` - Event interface{} `json:"event"` - Fields map[string]interface{} `json:"fields,omitempty"` + Time any `json:"time,omitempty"` + Host string `json:"host"` + Source string `json:"source,omitempty"` + SourceType string `json:"sourcetype,omitempty"` + Index string `json:"index,omitempty"` + Event any `json:"event"` + Fields map[string]any `json:"fields,omitempty"` }{} err := json.Unmarshal(b, &rawEvent) if err != nil { diff --git a/internal/splunk/common_test.go b/internal/splunk/common_test.go index 29208bbe6c35..621ae844a1f9 100644 --- a/internal/splunk/common_test.go +++ b/internal/splunk/common_test.go @@ -13,18 +13,18 @@ import ( func TestGetValues(t *testing.T) { metric := Event{ - Fields: map[string]interface{}{}, + Fields: map[string]any{}, } - assert.Equal(t, map[string]interface{}{}, metric.GetMetricValues()) + assert.Equal(t, map[string]any{}, metric.GetMetricValues()) metric.Fields["metric_name:foo"] = "bar" - assert.Equal(t, map[string]interface{}{"foo": "bar"}, metric.GetMetricValues()) + assert.Equal(t, map[string]any{"foo": "bar"}, metric.GetMetricValues()) metric.Fields["metric_name:foo2"] = "foobar" - assert.Equal(t, map[string]interface{}{"foo": "bar", "foo2": "foobar"}, metric.GetMetricValues()) + assert.Equal(t, map[string]any{"foo": "bar", "foo2": "foobar"}, metric.GetMetricValues()) } func TestIsMetric(t *testing.T) { ev := Event{ - Event: map[string]interface{}{}, + Event: map[string]any{}, } assert.False(t, ev.IsMetric()) metric := Event{ @@ -32,7 +32,7 @@ func TestIsMetric(t *testing.T) { } assert.True(t, metric.IsMetric()) arr := Event{ - Event: []interface{}{"foo", "bar"}, + Event: []any{"foo", "bar"}, } assert.False(t, arr.IsMetric()) yo := Event{ @@ -43,13 +43,13 @@ func TestIsMetric(t *testing.T) { func TestIsMetric_WithoutEventField(t *testing.T) { fieldsOnly := Event{ - Fields: map[string]interface{}{ + Fields: map[string]any{ "foo": "bar", }, } assert.False(t, fieldsOnly.IsMetric()) fieldsWithMetrics := Event{ - Fields: map[string]interface{}{ + Fields: map[string]any{ "foo": "bar", "metric_name:foo": 123, "foobar": "foobar", diff --git a/pkg/golden/golden.go b/pkg/golden/golden.go index 3233ef117e9c..2c7bc70c04ae 100644 --- a/pkg/golden/golden.go +++ b/pkg/golden/golden.go @@ -23,7 +23,7 @@ func ReadMetrics(filePath string) (pmetric.Metrics, error) { return pmetric.Metrics{}, err } if strings.HasSuffix(filePath, ".yaml") || strings.HasSuffix(filePath, ".yml") { - var m map[string]interface{} + var m map[string]any if err = yaml.Unmarshal(b, &m); err != nil { return pmetric.Metrics{}, err } @@ -54,7 +54,7 @@ func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) { if err != nil { return nil, err } - var jsonVal map[string]interface{} + var jsonVal map[string]any if err = json.Unmarshal(fileBytes, &jsonVal); err != nil { return nil, err } @@ -85,7 +85,7 @@ func ReadLogs(filePath string) (plog.Logs, error) { return plog.Logs{}, err } if strings.HasSuffix(filePath, ".yaml") || strings.HasSuffix(filePath, ".yml") { - var m map[string]interface{} + var m map[string]any if err = yaml.Unmarshal(b, &m); err != nil { return plog.Logs{}, err } @@ -116,7 +116,7 @@ func writeLogs(filePath string, logs plog.Logs) error { if err != nil { return err } - var jsonVal map[string]interface{} + var jsonVal map[string]any if err = json.Unmarshal(fileBytes, &jsonVal); err != nil { return err } @@ -136,7 +136,7 @@ func ReadTraces(filePath string) (ptrace.Traces, error) { return ptrace.Traces{}, err } if strings.HasSuffix(filePath, ".yaml") || strings.HasSuffix(filePath, ".yml") { - var m map[string]interface{} + var m map[string]any if err = yaml.Unmarshal(b, &m); err != nil { return ptrace.Traces{}, err } @@ -167,7 +167,7 @@ func writeTraces(filePath string, traces ptrace.Traces) error { if err != nil { return err } - var jsonVal map[string]interface{} + var jsonVal map[string]any if err = json.Unmarshal(fileBytes, &jsonVal); err != nil { return err } diff --git a/pkg/ottl/boolean_value_test.go b/pkg/ottl/boolean_value_test.go index c82e24272cef..a7843429406f 100644 --- a/pkg/ottl/boolean_value_test.go +++ b/pkg/ottl/boolean_value_test.go @@ -216,12 +216,12 @@ func Test_newConditionEvaluator_invalid(t *testing.T) { } func True() (ExprFunc[any], error) { - return func(ctx context.Context, tCtx any) (interface{}, error) { + return func(ctx context.Context, tCtx any) (any, error) { return true, nil }, nil } func False() (ExprFunc[any], error) { - return func(ctx context.Context, tCtx any) (interface{}, error) { + return func(ctx context.Context, tCtx any) (any, error) { return false, nil }, nil } diff --git a/pkg/ottl/compare_test.go b/pkg/ottl/compare_test.go index 257e05f7a5d7..b2dffba38a4f 100644 --- a/pkg/ottl/compare_test.go +++ b/pkg/ottl/compare_test.go @@ -105,7 +105,7 @@ func Test_compare(t *testing.T) { for _, tt := range tests { for _, op := range ops { t.Run(fmt.Sprintf("%s %v", tt.name, op), func(t *testing.T) { - p, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + p, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) if got := p.compare(tt.a, tt.b, op); got != tt.want[op] { t.Errorf("compare(%v, %v, %v) = %v, want %v", tt.a, tt.b, op, got, tt.want[op]) } @@ -119,7 +119,7 @@ func Test_compare(t *testing.T) { // The summary is that they're pretty fast; all the calls to compare are 12 ns/op or less on a 2019 intel // mac pro laptop, and none of them have any allocations. func BenchmarkCompareEQInt64(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -128,7 +128,7 @@ func BenchmarkCompareEQInt64(b *testing.B) { } func BenchmarkCompareEQFloat(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -137,7 +137,7 @@ func BenchmarkCompareEQFloat(b *testing.B) { } func BenchmarkCompareEQString(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -146,7 +146,7 @@ func BenchmarkCompareEQString(b *testing.B) { } func BenchmarkCompareEQPString(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -155,7 +155,7 @@ func BenchmarkCompareEQPString(b *testing.B) { } func BenchmarkCompareEQBytes(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -164,7 +164,7 @@ func BenchmarkCompareEQBytes(b *testing.B) { } func BenchmarkCompareEQNil(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -173,7 +173,7 @@ func BenchmarkCompareEQNil(b *testing.B) { } func BenchmarkCompareNEInt(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -182,7 +182,7 @@ func BenchmarkCompareNEInt(b *testing.B) { } func BenchmarkCompareNEFloat(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -191,7 +191,7 @@ func BenchmarkCompareNEFloat(b *testing.B) { } func BenchmarkCompareNEString(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -200,7 +200,7 @@ func BenchmarkCompareNEString(b *testing.B) { } func BenchmarkCompareLTFloat(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -209,7 +209,7 @@ func BenchmarkCompareLTFloat(b *testing.B) { } func BenchmarkCompareLTString(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -218,7 +218,7 @@ func BenchmarkCompareLTString(b *testing.B) { } func BenchmarkCompareLTNil(b *testing.B) { - testParser, _ := NewParser[interface{}](nil, nil, componenttest.NewNopTelemetrySettings()) + testParser, _ := NewParser[any](nil, nil, componenttest.NewNopTelemetrySettings()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { diff --git a/pkg/ottl/contexts/internal/map.go b/pkg/ottl/contexts/internal/map.go index 63be64719379..b45d61c177d6 100644 --- a/pkg/ottl/contexts/internal/map.go +++ b/pkg/ottl/contexts/internal/map.go @@ -11,7 +11,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" ) -func GetMapValue(m pcommon.Map, keys []ottl.Key) (interface{}, error) { +func GetMapValue(m pcommon.Map, keys []ottl.Key) (any, error) { if len(keys) == 0 { return nil, fmt.Errorf("cannot get map value without key") } @@ -26,7 +26,7 @@ func GetMapValue(m pcommon.Map, keys []ottl.Key) (interface{}, error) { return getIndexableValue(val, keys[1:]) } -func SetMapValue(m pcommon.Map, keys []ottl.Key, val interface{}) error { +func SetMapValue(m pcommon.Map, keys []ottl.Key, val any) error { if len(keys) == 0 { return fmt.Errorf("cannot set map value without key") } diff --git a/pkg/ottl/contexts/internal/metric.go b/pkg/ottl/contexts/internal/metric.go index 5dcdcdd690db..e34afd8854f6 100644 --- a/pkg/ottl/contexts/internal/metric.go +++ b/pkg/ottl/contexts/internal/metric.go @@ -54,10 +54,10 @@ func MetricPathGetSetter[K MetricContext](path []ottl.Field) (ottl.GetSetter[K], func accessMetric[K MetricContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetMetric(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newMetric, ok := val.(pmetric.Metric); ok { newMetric.CopyTo(tCtx.GetMetric()) } @@ -68,10 +68,10 @@ func accessMetric[K MetricContext]() ottl.StandardGetSetter[K] { func accessName[K MetricContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetMetric().Name(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { tCtx.GetMetric().SetName(str) } @@ -82,10 +82,10 @@ func accessName[K MetricContext]() ottl.StandardGetSetter[K] { func accessDescription[K MetricContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetMetric().Description(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { tCtx.GetMetric().SetDescription(str) } @@ -96,10 +96,10 @@ func accessDescription[K MetricContext]() ottl.StandardGetSetter[K] { func accessUnit[K MetricContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetMetric().Unit(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { tCtx.GetMetric().SetUnit(str) } @@ -110,10 +110,10 @@ func accessUnit[K MetricContext]() ottl.StandardGetSetter[K] { func accessType[K MetricContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return int64(tCtx.GetMetric().Type()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { // TODO Implement methods so correctly convert data types. // https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/10130 return nil @@ -123,7 +123,7 @@ func accessType[K MetricContext]() ottl.StandardGetSetter[K] { func accessAggTemporality[K MetricContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { metric := tCtx.GetMetric() switch metric.Type() { case pmetric.MetricTypeSum: @@ -135,7 +135,7 @@ func accessAggTemporality[K MetricContext]() ottl.StandardGetSetter[K] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newAggTemporality, ok := val.(int64); ok { metric := tCtx.GetMetric() switch metric.Type() { @@ -154,14 +154,14 @@ func accessAggTemporality[K MetricContext]() ottl.StandardGetSetter[K] { func accessIsMonotonic[K MetricContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { metric := tCtx.GetMetric() if metric.Type() == pmetric.MetricTypeSum { return metric.Sum().IsMonotonic(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newIsMonotonic, ok := val.(bool); ok { metric := tCtx.GetMetric() if metric.Type() == pmetric.MetricTypeSum { @@ -175,7 +175,7 @@ func accessIsMonotonic[K MetricContext]() ottl.StandardGetSetter[K] { func accessDataPoints[K MetricContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { metric := tCtx.GetMetric() //exhaustive:enforce switch metric.Type() { @@ -192,7 +192,7 @@ func accessDataPoints[K MetricContext]() ottl.StandardGetSetter[K] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { metric := tCtx.GetMetric() //exhaustive:enforce switch metric.Type() { diff --git a/pkg/ottl/contexts/internal/metric_test.go b/pkg/ottl/contexts/internal/metric_test.go index d4e079233825..8bbcb1d7d1df 100644 --- a/pkg/ottl/contexts/internal/metric_test.go +++ b/pkg/ottl/contexts/internal/metric_test.go @@ -27,8 +27,8 @@ func Test_MetricPathGetSetter(t *testing.T) { tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(metric pmetric.Metric) }{ { diff --git a/pkg/ottl/contexts/internal/resource.go b/pkg/ottl/contexts/internal/resource.go index 6a5b19415bbe..0303a4acd7b7 100644 --- a/pkg/ottl/contexts/internal/resource.go +++ b/pkg/ottl/contexts/internal/resource.go @@ -36,10 +36,10 @@ func ResourcePathGetSetter[K ResourceContext](path []ottl.Field) (ottl.GetSetter func accessResource[K ResourceContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetResource(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newRes, ok := val.(pcommon.Resource); ok { newRes.CopyTo(tCtx.GetResource()) } @@ -50,10 +50,10 @@ func accessResource[K ResourceContext]() ottl.StandardGetSetter[K] { func accessResourceAttributes[K ResourceContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetResource().Attributes(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if attrs, ok := val.(pcommon.Map); ok { attrs.CopyTo(tCtx.GetResource().Attributes()) } @@ -64,10 +64,10 @@ func accessResourceAttributes[K ResourceContext]() ottl.StandardGetSetter[K] { func accessResourceAttributesKey[K ResourceContext](keys []ottl.Key) ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return GetMapValue(tCtx.GetResource().Attributes(), keys) }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { return SetMapValue(tCtx.GetResource().Attributes(), keys, val) }, } @@ -75,10 +75,10 @@ func accessResourceAttributesKey[K ResourceContext](keys []ottl.Key) ottl.Standa func accessResourceDroppedAttributesCount[K ResourceContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return int64(tCtx.GetResource().DroppedAttributesCount()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetResource().SetDroppedAttributesCount(uint32(i)) } diff --git a/pkg/ottl/contexts/internal/resource_test.go b/pkg/ottl/contexts/internal/resource_test.go index fb569c50a333..97f93c044d46 100644 --- a/pkg/ottl/contexts/internal/resource_test.go +++ b/pkg/ottl/contexts/internal/resource_test.go @@ -23,8 +23,8 @@ func TestResourcePathGetSetter(t *testing.T) { tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(resource pcommon.Resource) }{ { @@ -311,7 +311,7 @@ func TestResourcePathGetSetter(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", diff --git a/pkg/ottl/contexts/internal/scope.go b/pkg/ottl/contexts/internal/scope.go index 796fec2df929..3ed068602f53 100644 --- a/pkg/ottl/contexts/internal/scope.go +++ b/pkg/ottl/contexts/internal/scope.go @@ -41,10 +41,10 @@ func ScopePathGetSetter[K InstrumentationScopeContext](path []ottl.Field) (ottl. func accessInstrumentationScope[K InstrumentationScopeContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetInstrumentationScope(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newIl, ok := val.(pcommon.InstrumentationScope); ok { newIl.CopyTo(tCtx.GetInstrumentationScope()) } @@ -55,10 +55,10 @@ func accessInstrumentationScope[K InstrumentationScopeContext]() ottl.StandardGe func accessInstrumentationScopeAttributes[K InstrumentationScopeContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetInstrumentationScope().Attributes(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if attrs, ok := val.(pcommon.Map); ok { attrs.CopyTo(tCtx.GetInstrumentationScope().Attributes()) } @@ -69,10 +69,10 @@ func accessInstrumentationScopeAttributes[K InstrumentationScopeContext]() ottl. func accessInstrumentationScopeAttributesKey[K InstrumentationScopeContext](keys []ottl.Key) ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return GetMapValue(tCtx.GetInstrumentationScope().Attributes(), keys) }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { return SetMapValue(tCtx.GetInstrumentationScope().Attributes(), keys, val) }, } @@ -80,10 +80,10 @@ func accessInstrumentationScopeAttributesKey[K InstrumentationScopeContext](keys func accessInstrumentationScopeName[K InstrumentationScopeContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetInstrumentationScope().Name(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { tCtx.GetInstrumentationScope().SetName(str) } @@ -94,10 +94,10 @@ func accessInstrumentationScopeName[K InstrumentationScopeContext]() ottl.Standa func accessInstrumentationScopeVersion[K InstrumentationScopeContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetInstrumentationScope().Version(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { tCtx.GetInstrumentationScope().SetVersion(str) } @@ -108,10 +108,10 @@ func accessInstrumentationScopeVersion[K InstrumentationScopeContext]() ottl.Sta func accessInstrumentationScopeDroppedAttributesCount[K InstrumentationScopeContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return int64(tCtx.GetInstrumentationScope().DroppedAttributesCount()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetInstrumentationScope().SetDroppedAttributesCount(uint32(i)) } diff --git a/pkg/ottl/contexts/internal/scope_test.go b/pkg/ottl/contexts/internal/scope_test.go index 066b1d67f706..1560ddb024ca 100644 --- a/pkg/ottl/contexts/internal/scope_test.go +++ b/pkg/ottl/contexts/internal/scope_test.go @@ -22,8 +22,8 @@ func TestScopePathGetSetter(t *testing.T) { tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(is pcommon.InstrumentationScope) }{ { @@ -354,7 +354,7 @@ func TestScopePathGetSetter(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", diff --git a/pkg/ottl/contexts/internal/slice.go b/pkg/ottl/contexts/internal/slice.go index 95bfc3767298..da846c61f05e 100644 --- a/pkg/ottl/contexts/internal/slice.go +++ b/pkg/ottl/contexts/internal/slice.go @@ -11,7 +11,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" ) -func GetSliceValue(s pcommon.Slice, keys []ottl.Key) (interface{}, error) { +func GetSliceValue(s pcommon.Slice, keys []ottl.Key) (any, error) { if len(keys) == 0 { return nil, fmt.Errorf("cannot get slice value without key") } @@ -27,7 +27,7 @@ func GetSliceValue(s pcommon.Slice, keys []ottl.Key) (interface{}, error) { return getIndexableValue(s.At(int(*keys[0].Int)), keys[1:]) } -func SetSliceValue(s pcommon.Slice, keys []ottl.Key, val interface{}) error { +func SetSliceValue(s pcommon.Slice, keys []ottl.Key, val any) error { if len(keys) == 0 { return fmt.Errorf("cannot set slice value without key") } diff --git a/pkg/ottl/contexts/internal/span.go b/pkg/ottl/contexts/internal/span.go index bc7b67f9e79d..0c6c48601f71 100644 --- a/pkg/ottl/contexts/internal/span.go +++ b/pkg/ottl/contexts/internal/span.go @@ -119,10 +119,10 @@ func SpanPathGetSetter[K SpanContext](path []ottl.Field) (ottl.GetSetter[K], err func accessSpan[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newSpan, ok := val.(ptrace.Span); ok { newSpan.CopyTo(tCtx.GetSpan()) } @@ -133,10 +133,10 @@ func accessSpan[K SpanContext]() ottl.StandardGetSetter[K] { func accessTraceID[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().TraceID(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newTraceID, ok := val.(pcommon.TraceID); ok { tCtx.GetSpan().SetTraceID(newTraceID) } @@ -147,11 +147,11 @@ func accessTraceID[K SpanContext]() ottl.StandardGetSetter[K] { func accessStringTraceID[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { id := tCtx.GetSpan().TraceID() return hex.EncodeToString(id[:]), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { id, err := ParseTraceID(str) if err != nil { @@ -166,10 +166,10 @@ func accessStringTraceID[K SpanContext]() ottl.StandardGetSetter[K] { func accessSpanID[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().SpanID(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newSpanID, ok := val.(pcommon.SpanID); ok { tCtx.GetSpan().SetSpanID(newSpanID) } @@ -180,11 +180,11 @@ func accessSpanID[K SpanContext]() ottl.StandardGetSetter[K] { func accessStringSpanID[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { id := tCtx.GetSpan().SpanID() return hex.EncodeToString(id[:]), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { id, err := ParseSpanID(str) if err != nil { @@ -199,10 +199,10 @@ func accessStringSpanID[K SpanContext]() ottl.StandardGetSetter[K] { func accessTraceState[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().TraceState().AsRaw(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { tCtx.GetSpan().TraceState().FromRaw(str) } @@ -219,7 +219,7 @@ func accessTraceStateKey[K SpanContext](keys []ottl.Key) (ottl.StandardGetSetter return ottl.StandardGetSetter[K]{}, fmt.Errorf("trace_state indexing type must be a string") } return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { if ts, err := trace.ParseTraceState(tCtx.GetSpan().TraceState().AsRaw()); err == nil { if keys[0].String == nil { return nil, err @@ -228,7 +228,7 @@ func accessTraceStateKey[K SpanContext](keys []ottl.Key) (ottl.StandardGetSetter } return nil, nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { if ts, err := trace.ParseTraceState(tCtx.GetSpan().TraceState().AsRaw()); err == nil { if updated, err := ts.Insert(*keys[0].String, str); err == nil { @@ -243,10 +243,10 @@ func accessTraceStateKey[K SpanContext](keys []ottl.Key) (ottl.StandardGetSetter func accessParentSpanID[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().ParentSpanID(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if newParentSpanID, ok := val.(pcommon.SpanID); ok { tCtx.GetSpan().SetParentSpanID(newParentSpanID) } @@ -257,11 +257,11 @@ func accessParentSpanID[K SpanContext]() ottl.StandardGetSetter[K] { func accessStringParentSpanID[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { id := tCtx.GetSpan().ParentSpanID() return hex.EncodeToString(id[:]), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { id, err := ParseSpanID(str) if err != nil { @@ -276,10 +276,10 @@ func accessStringParentSpanID[K SpanContext]() ottl.StandardGetSetter[K] { func accessSpanName[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().Name(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { tCtx.GetSpan().SetName(str) } @@ -290,10 +290,10 @@ func accessSpanName[K SpanContext]() ottl.StandardGetSetter[K] { func accessKind[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return int64(tCtx.GetSpan().Kind()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetSpan().SetKind(ptrace.SpanKind(i)) } @@ -304,10 +304,10 @@ func accessKind[K SpanContext]() ottl.StandardGetSetter[K] { func accessStringKind[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().Kind().String(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if s, ok := val.(string); ok { var kind ptrace.SpanKind switch s { @@ -335,10 +335,10 @@ func accessStringKind[K SpanContext]() ottl.StandardGetSetter[K] { func accessDeprecatedStringKind[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return traceutil.SpanKindStr(tCtx.GetSpan().Kind()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if s, ok := val.(string); ok { var kind ptrace.SpanKind switch s { @@ -366,10 +366,10 @@ func accessDeprecatedStringKind[K SpanContext]() ottl.StandardGetSetter[K] { func accessStartTimeUnixNano[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().StartTimestamp().AsTime().UnixNano(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetSpan().SetStartTimestamp(pcommon.NewTimestampFromTime(time.Unix(0, i))) } @@ -380,10 +380,10 @@ func accessStartTimeUnixNano[K SpanContext]() ottl.StandardGetSetter[K] { func accessEndTimeUnixNano[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().EndTimestamp().AsTime().UnixNano(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetSpan().SetEndTimestamp(pcommon.NewTimestampFromTime(time.Unix(0, i))) } @@ -394,10 +394,10 @@ func accessEndTimeUnixNano[K SpanContext]() ottl.StandardGetSetter[K] { func accessStartTime[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().StartTimestamp().AsTime(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(time.Time); ok { tCtx.GetSpan().SetStartTimestamp(pcommon.NewTimestampFromTime(i)) } @@ -408,10 +408,10 @@ func accessStartTime[K SpanContext]() ottl.StandardGetSetter[K] { func accessEndTime[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().EndTimestamp().AsTime(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(time.Time); ok { tCtx.GetSpan().SetEndTimestamp(pcommon.NewTimestampFromTime(i)) } @@ -422,10 +422,10 @@ func accessEndTime[K SpanContext]() ottl.StandardGetSetter[K] { func accessAttributes[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().Attributes(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if attrs, ok := val.(pcommon.Map); ok { attrs.CopyTo(tCtx.GetSpan().Attributes()) } @@ -436,10 +436,10 @@ func accessAttributes[K SpanContext]() ottl.StandardGetSetter[K] { func accessAttributesKey[K SpanContext](keys []ottl.Key) ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return GetMapValue(tCtx.GetSpan().Attributes(), keys) }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { return SetMapValue(tCtx.GetSpan().Attributes(), keys, val) }, } @@ -447,10 +447,10 @@ func accessAttributesKey[K SpanContext](keys []ottl.Key) ottl.StandardGetSetter[ func accessSpanDroppedAttributesCount[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return int64(tCtx.GetSpan().DroppedAttributesCount()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetSpan().SetDroppedAttributesCount(uint32(i)) } @@ -461,10 +461,10 @@ func accessSpanDroppedAttributesCount[K SpanContext]() ottl.StandardGetSetter[K] func accessEvents[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().Events(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if slc, ok := val.(ptrace.SpanEventSlice); ok { tCtx.GetSpan().Events().RemoveIf(func(event ptrace.SpanEvent) bool { return true @@ -478,10 +478,10 @@ func accessEvents[K SpanContext]() ottl.StandardGetSetter[K] { func accessDroppedEventsCount[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return int64(tCtx.GetSpan().DroppedEventsCount()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetSpan().SetDroppedEventsCount(uint32(i)) } @@ -492,10 +492,10 @@ func accessDroppedEventsCount[K SpanContext]() ottl.StandardGetSetter[K] { func accessLinks[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().Links(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if slc, ok := val.(ptrace.SpanLinkSlice); ok { tCtx.GetSpan().Links().RemoveIf(func(event ptrace.SpanLink) bool { return true @@ -509,10 +509,10 @@ func accessLinks[K SpanContext]() ottl.StandardGetSetter[K] { func accessDroppedLinksCount[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return int64(tCtx.GetSpan().DroppedLinksCount()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetSpan().SetDroppedLinksCount(uint32(i)) } @@ -523,10 +523,10 @@ func accessDroppedLinksCount[K SpanContext]() ottl.StandardGetSetter[K] { func accessStatus[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().Status(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if status, ok := val.(ptrace.Status); ok { status.CopyTo(tCtx.GetSpan().Status()) } @@ -537,10 +537,10 @@ func accessStatus[K SpanContext]() ottl.StandardGetSetter[K] { func accessStatusCode[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return int64(tCtx.GetSpan().Status().Code()), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if i, ok := val.(int64); ok { tCtx.GetSpan().Status().SetCode(ptrace.StatusCode(i)) } @@ -551,10 +551,10 @@ func accessStatusCode[K SpanContext]() ottl.StandardGetSetter[K] { func accessStatusMessage[K SpanContext]() ottl.StandardGetSetter[K] { return ottl.StandardGetSetter[K]{ - Getter: func(ctx context.Context, tCtx K) (interface{}, error) { + Getter: func(ctx context.Context, tCtx K) (any, error) { return tCtx.GetSpan().Status().Message(), nil }, - Setter: func(ctx context.Context, tCtx K, val interface{}) error { + Setter: func(ctx context.Context, tCtx K, val any) error { if str, ok := val.(string); ok { tCtx.GetSpan().Status().SetMessage(str) } diff --git a/pkg/ottl/contexts/internal/span_test.go b/pkg/ottl/contexts/internal/span_test.go index 8178f5b42ecd..6ccbf92e4a93 100644 --- a/pkg/ottl/contexts/internal/span_test.go +++ b/pkg/ottl/contexts/internal/span_test.go @@ -42,8 +42,8 @@ func TestSpanPathGetSetter(t *testing.T) { tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(span ptrace.Span) }{ { @@ -523,7 +523,7 @@ func TestSpanPathGetSetter(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", diff --git a/pkg/ottl/contexts/internal/value.go b/pkg/ottl/contexts/internal/value.go index 1ac4e322b98a..24df36d9783a 100644 --- a/pkg/ottl/contexts/internal/value.go +++ b/pkg/ottl/contexts/internal/value.go @@ -13,7 +13,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/internal/ottlcommon" ) -func SetValue(value pcommon.Value, val interface{}) error { +func SetValue(value pcommon.Value, val any) error { var err error switch v := val.(type) { case string: @@ -61,7 +61,7 @@ func SetValue(value pcommon.Value, val interface{}) error { v.CopyTo(value.SetEmptySlice()) case pcommon.Map: v.CopyTo(value.SetEmptyMap()) - case map[string]interface{}: + case map[string]any: value.SetEmptyMap() for mk, mv := range v { err = SetMapValue(value.Map(), []ottl.Key{{String: &mk}}, mv) diff --git a/pkg/ottl/contexts/ottldatapoint/datapoint.go b/pkg/ottl/contexts/ottldatapoint/datapoint.go index eaa51ff7f284..3d2ac0e22a2f 100644 --- a/pkg/ottl/contexts/ottldatapoint/datapoint.go +++ b/pkg/ottl/contexts/ottldatapoint/datapoint.go @@ -20,7 +20,7 @@ var _ internal.ResourceContext = TransformContext{} var _ internal.InstrumentationScopeContext = TransformContext{} type TransformContext struct { - dataPoint interface{} + dataPoint any metric pmetric.Metric metrics pmetric.MetricSlice instrumentationScope pcommon.InstrumentationScope @@ -30,7 +30,7 @@ type TransformContext struct { type Option func(*ottl.Parser[TransformContext]) -func NewTransformContext(dataPoint interface{}, metric pmetric.Metric, metrics pmetric.MetricSlice, instrumentationScope pcommon.InstrumentationScope, resource pcommon.Resource) TransformContext { +func NewTransformContext(dataPoint any, metric pmetric.Metric, metrics pmetric.MetricSlice, instrumentationScope pcommon.InstrumentationScope, resource pcommon.Resource) TransformContext { return TransformContext{ dataPoint: dataPoint, metric: metric, @@ -41,7 +41,7 @@ func NewTransformContext(dataPoint interface{}, metric pmetric.Metric, metrics p } } -func (tCtx TransformContext) GetDataPoint() interface{} { +func (tCtx TransformContext) GetDataPoint() any { return tCtx.dataPoint } @@ -206,10 +206,10 @@ func newPathGetSetter(path []ottl.Field) (ottl.GetSetter[TransformContext], erro func accessCache() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.getCache(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if m, ok := val.(pcommon.Map); ok { m.CopyTo(tCtx.getCache()) } @@ -220,10 +220,10 @@ func accessCache() ottl.StandardGetSetter[TransformContext] { func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.getCache(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.getCache(), keys, val) }, } @@ -231,7 +231,7 @@ func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { func accessAttributes() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return tCtx.GetDataPoint().(pmetric.NumberDataPoint).Attributes(), nil @@ -244,7 +244,7 @@ func accessAttributes() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: if attrs, ok := val.(pcommon.Map); ok { @@ -270,7 +270,7 @@ func accessAttributes() ottl.StandardGetSetter[TransformContext] { func accessAttributesKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return internal.GetMapValue(tCtx.GetDataPoint().(pmetric.NumberDataPoint).Attributes(), keys) @@ -283,7 +283,7 @@ func accessAttributesKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContex } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return internal.SetMapValue(tCtx.GetDataPoint().(pmetric.NumberDataPoint).Attributes(), keys, val) @@ -301,7 +301,7 @@ func accessAttributesKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContex func accessStartTimeUnixNano() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return tCtx.GetDataPoint().(pmetric.NumberDataPoint).StartTimestamp().AsTime().UnixNano(), nil @@ -314,7 +314,7 @@ func accessStartTimeUnixNano() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newTime, ok := val.(int64); ok { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: @@ -334,7 +334,7 @@ func accessStartTimeUnixNano() ottl.StandardGetSetter[TransformContext] { func accessStartTime() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return tCtx.GetDataPoint().(pmetric.NumberDataPoint).StartTimestamp().AsTime(), nil @@ -347,7 +347,7 @@ func accessStartTime() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newTime, ok := val.(time.Time); ok { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: @@ -367,7 +367,7 @@ func accessStartTime() ottl.StandardGetSetter[TransformContext] { func accessTimeUnixNano() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return tCtx.GetDataPoint().(pmetric.NumberDataPoint).Timestamp().AsTime().UnixNano(), nil @@ -380,7 +380,7 @@ func accessTimeUnixNano() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newTime, ok := val.(int64); ok { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: @@ -400,7 +400,7 @@ func accessTimeUnixNano() ottl.StandardGetSetter[TransformContext] { func accessTime() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return tCtx.GetDataPoint().(pmetric.NumberDataPoint).Timestamp().AsTime(), nil @@ -413,7 +413,7 @@ func accessTime() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newTime, ok := val.(time.Time); ok { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: @@ -433,13 +433,13 @@ func accessTime() ottl.StandardGetSetter[TransformContext] { func accessDoubleValue() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if numberDataPoint, ok := tCtx.GetDataPoint().(pmetric.NumberDataPoint); ok { return numberDataPoint.DoubleValue(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newDouble, ok := val.(float64); ok { if numberDataPoint, ok := tCtx.GetDataPoint().(pmetric.NumberDataPoint); ok { numberDataPoint.SetDoubleValue(newDouble) @@ -452,13 +452,13 @@ func accessDoubleValue() ottl.StandardGetSetter[TransformContext] { func accessIntValue() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if numberDataPoint, ok := tCtx.GetDataPoint().(pmetric.NumberDataPoint); ok { return numberDataPoint.IntValue(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newInt, ok := val.(int64); ok { if numberDataPoint, ok := tCtx.GetDataPoint().(pmetric.NumberDataPoint); ok { numberDataPoint.SetIntValue(newInt) @@ -471,7 +471,7 @@ func accessIntValue() ottl.StandardGetSetter[TransformContext] { func accessExemplars() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return tCtx.GetDataPoint().(pmetric.NumberDataPoint).Exemplars(), nil @@ -482,7 +482,7 @@ func accessExemplars() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newExemplars, ok := val.(pmetric.ExemplarSlice); ok { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: @@ -500,7 +500,7 @@ func accessExemplars() ottl.StandardGetSetter[TransformContext] { func accessFlags() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: return int64(tCtx.GetDataPoint().(pmetric.NumberDataPoint).Flags()), nil @@ -513,7 +513,7 @@ func accessFlags() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newFlags, ok := val.(int64); ok { switch tCtx.GetDataPoint().(type) { case pmetric.NumberDataPoint: @@ -533,7 +533,7 @@ func accessFlags() ottl.StandardGetSetter[TransformContext] { func accessCount() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.HistogramDataPoint: return int64(tCtx.GetDataPoint().(pmetric.HistogramDataPoint).Count()), nil @@ -544,7 +544,7 @@ func accessCount() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newCount, ok := val.(int64); ok { switch tCtx.GetDataPoint().(type) { case pmetric.HistogramDataPoint: @@ -562,7 +562,7 @@ func accessCount() ottl.StandardGetSetter[TransformContext] { func accessSum() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { switch tCtx.GetDataPoint().(type) { case pmetric.HistogramDataPoint: return tCtx.GetDataPoint().(pmetric.HistogramDataPoint).Sum(), nil @@ -573,7 +573,7 @@ func accessSum() ottl.StandardGetSetter[TransformContext] { } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newSum, ok := val.(float64); ok { switch tCtx.GetDataPoint().(type) { case pmetric.HistogramDataPoint: @@ -591,13 +591,13 @@ func accessSum() ottl.StandardGetSetter[TransformContext] { func accessExplicitBounds() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if histogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.HistogramDataPoint); ok { return histogramDataPoint.ExplicitBounds().AsRaw(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newExplicitBounds, ok := val.([]float64); ok { if histogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.HistogramDataPoint); ok { histogramDataPoint.ExplicitBounds().FromRaw(newExplicitBounds) @@ -610,13 +610,13 @@ func accessExplicitBounds() ottl.StandardGetSetter[TransformContext] { func accessBucketCounts() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if histogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.HistogramDataPoint); ok { return histogramDataPoint.BucketCounts().AsRaw(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newBucketCount, ok := val.([]uint64); ok { if histogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.HistogramDataPoint); ok { histogramDataPoint.BucketCounts().FromRaw(newBucketCount) @@ -629,13 +629,13 @@ func accessBucketCounts() ottl.StandardGetSetter[TransformContext] { func accessScale() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { return int64(expoHistogramDataPoint.Scale()), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newScale, ok := val.(int64); ok { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { expoHistogramDataPoint.SetScale(int32(newScale)) @@ -648,13 +648,13 @@ func accessScale() ottl.StandardGetSetter[TransformContext] { func accessZeroCount() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { return int64(expoHistogramDataPoint.ZeroCount()), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newZeroCount, ok := val.(int64); ok { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { expoHistogramDataPoint.SetZeroCount(uint64(newZeroCount)) @@ -667,13 +667,13 @@ func accessZeroCount() ottl.StandardGetSetter[TransformContext] { func accessPositive() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { return expoHistogramDataPoint.Positive(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newPositive, ok := val.(pmetric.ExponentialHistogramDataPointBuckets); ok { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { newPositive.CopyTo(expoHistogramDataPoint.Positive()) @@ -686,13 +686,13 @@ func accessPositive() ottl.StandardGetSetter[TransformContext] { func accessPositiveOffset() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { return int64(expoHistogramDataPoint.Positive().Offset()), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newPositiveOffset, ok := val.(int64); ok { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { expoHistogramDataPoint.Positive().SetOffset(int32(newPositiveOffset)) @@ -705,13 +705,13 @@ func accessPositiveOffset() ottl.StandardGetSetter[TransformContext] { func accessPositiveBucketCounts() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { return expoHistogramDataPoint.Positive().BucketCounts().AsRaw(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newPositiveBucketCounts, ok := val.([]uint64); ok { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { expoHistogramDataPoint.Positive().BucketCounts().FromRaw(newPositiveBucketCounts) @@ -724,13 +724,13 @@ func accessPositiveBucketCounts() ottl.StandardGetSetter[TransformContext] { func accessNegative() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { return expoHistogramDataPoint.Negative(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newNegative, ok := val.(pmetric.ExponentialHistogramDataPointBuckets); ok { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { newNegative.CopyTo(expoHistogramDataPoint.Negative()) @@ -743,13 +743,13 @@ func accessNegative() ottl.StandardGetSetter[TransformContext] { func accessNegativeOffset() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { return int64(expoHistogramDataPoint.Negative().Offset()), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newNegativeOffset, ok := val.(int64); ok { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { expoHistogramDataPoint.Negative().SetOffset(int32(newNegativeOffset)) @@ -762,13 +762,13 @@ func accessNegativeOffset() ottl.StandardGetSetter[TransformContext] { func accessNegativeBucketCounts() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { return expoHistogramDataPoint.Negative().BucketCounts().AsRaw(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newNegativeBucketCounts, ok := val.([]uint64); ok { if expoHistogramDataPoint, ok := tCtx.GetDataPoint().(pmetric.ExponentialHistogramDataPoint); ok { expoHistogramDataPoint.Negative().BucketCounts().FromRaw(newNegativeBucketCounts) @@ -781,13 +781,13 @@ func accessNegativeBucketCounts() ottl.StandardGetSetter[TransformContext] { func accessQuantileValues() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { if summaryDataPoint, ok := tCtx.GetDataPoint().(pmetric.SummaryDataPoint); ok { return summaryDataPoint.QuantileValues(), nil } return nil, nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newQuantileValues, ok := val.(pmetric.SummaryDataPointValueAtQuantileSlice); ok { if summaryDataPoint, ok := tCtx.GetDataPoint().(pmetric.SummaryDataPoint); ok { newQuantileValues.CopyTo(summaryDataPoint.QuantileValues()) diff --git a/pkg/ottl/contexts/ottldatapoint/datapoint_test.go b/pkg/ottl/contexts/ottldatapoint/datapoint_test.go index 8bc0b26b7202..bac2de90d839 100644 --- a/pkg/ottl/contexts/ottldatapoint/datapoint_test.go +++ b/pkg/ottl/contexts/ottldatapoint/datapoint_test.go @@ -23,8 +23,8 @@ func Test_newPathGetSetter_Cache(t *testing.T) { tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(cache pcommon.Map) valueType pmetric.NumberDataPointValueType }{ @@ -94,16 +94,16 @@ func Test_newPathGetSetter_NumberDataPoint(t *testing.T) { pMap2 := newPMap.PutEmptyMap("k2") pMap2.PutStr("k1", "string") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(pmetric.NumberDataPoint) valueType pmetric.NumberDataPointValueType }{ @@ -444,7 +444,7 @@ func Test_newPathGetSetter_NumberDataPoint(t *testing.T) { }, }, { - name: "attributes map[string]interface{}", + name: "attributes map[string]any", path: []ottl.Field{ { Name: "attributes", @@ -512,7 +512,7 @@ func Test_newPathGetSetter_NumberDataPoint(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", @@ -576,16 +576,16 @@ func Test_newPathGetSetter_HistogramDataPoint(t *testing.T) { pMap2 := newPMap.PutEmptyMap("k2") pMap2.PutStr("k1", "string") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(pmetric.HistogramDataPoint) }{ { @@ -924,7 +924,7 @@ func Test_newPathGetSetter_HistogramDataPoint(t *testing.T) { }, }, { - name: "attributes map[string]interface{}", + name: "attributes map[string]any", path: []ottl.Field{ { Name: "attributes", @@ -992,7 +992,7 @@ func Test_newPathGetSetter_HistogramDataPoint(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", @@ -1061,16 +1061,16 @@ func Test_newPathGetSetter_ExpoHistogramDataPoint(t *testing.T) { pMap2 := newPMap.PutEmptyMap("k2") pMap2.PutStr("k1", "string") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(pmetric.ExponentialHistogramDataPoint) }{ { @@ -1499,7 +1499,7 @@ func Test_newPathGetSetter_ExpoHistogramDataPoint(t *testing.T) { }, }, { - name: "attributes map[string]interface{}", + name: "attributes map[string]any", path: []ottl.Field{ { Name: "attributes", @@ -1567,7 +1567,7 @@ func Test_newPathGetSetter_ExpoHistogramDataPoint(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", @@ -1637,16 +1637,16 @@ func Test_newPathGetSetter_SummaryDataPoint(t *testing.T) { pMap2 := newPMap.PutEmptyMap("k2") pMap2.PutStr("k1", "string") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(pmetric.SummaryDataPoint) }{ { @@ -1959,7 +1959,7 @@ func Test_newPathGetSetter_SummaryDataPoint(t *testing.T) { }, }, { - name: "attributes map[string]interface{}", + name: "attributes map[string]any", path: []ottl.Field{ { Name: "attributes", @@ -2027,7 +2027,7 @@ func Test_newPathGetSetter_SummaryDataPoint(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", @@ -2123,8 +2123,8 @@ func Test_newPathGetSetter_Metric(t *testing.T) { tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(metric pmetric.Metric) }{ { diff --git a/pkg/ottl/contexts/ottllog/log.go b/pkg/ottl/contexts/ottllog/log.go index 3f592187f511..c9fe394bc4c5 100644 --- a/pkg/ottl/contexts/ottllog/log.go +++ b/pkg/ottl/contexts/ottllog/log.go @@ -203,10 +203,10 @@ func newPathGetSetter(path []ottl.Field) (ottl.GetSetter[TransformContext], erro func accessCache() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.getCache(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if m, ok := val.(pcommon.Map); ok { m.CopyTo(tCtx.getCache()) } @@ -217,10 +217,10 @@ func accessCache() ottl.StandardGetSetter[TransformContext] { func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.getCache(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.getCache(), keys, val) }, } @@ -228,10 +228,10 @@ func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { func accessTimeUnixNano() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().Timestamp().AsTime().UnixNano(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if i, ok := val.(int64); ok { tCtx.GetLogRecord().SetTimestamp(pcommon.NewTimestampFromTime(time.Unix(0, i))) } @@ -242,10 +242,10 @@ func accessTimeUnixNano() ottl.StandardGetSetter[TransformContext] { func accessObservedTimeUnixNano() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().ObservedTimestamp().AsTime().UnixNano(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if i, ok := val.(int64); ok { tCtx.GetLogRecord().SetObservedTimestamp(pcommon.NewTimestampFromTime(time.Unix(0, i))) } @@ -256,10 +256,10 @@ func accessObservedTimeUnixNano() ottl.StandardGetSetter[TransformContext] { func accessTime() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().Timestamp().AsTime(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if i, ok := val.(time.Time); ok { tCtx.GetLogRecord().SetTimestamp(pcommon.NewTimestampFromTime(i)) } @@ -270,10 +270,10 @@ func accessTime() ottl.StandardGetSetter[TransformContext] { func accessObservedTime() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().ObservedTimestamp().AsTime(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if i, ok := val.(time.Time); ok { tCtx.GetLogRecord().SetObservedTimestamp(pcommon.NewTimestampFromTime(i)) } @@ -284,10 +284,10 @@ func accessObservedTime() ottl.StandardGetSetter[TransformContext] { func accessSeverityNumber() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return int64(tCtx.GetLogRecord().SeverityNumber()), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if i, ok := val.(int64); ok { tCtx.GetLogRecord().SetSeverityNumber(plog.SeverityNumber(i)) } @@ -298,10 +298,10 @@ func accessSeverityNumber() ottl.StandardGetSetter[TransformContext] { func accessSeverityText() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().SeverityText(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if s, ok := val.(string); ok { tCtx.GetLogRecord().SetSeverityText(s) } @@ -312,10 +312,10 @@ func accessSeverityText() ottl.StandardGetSetter[TransformContext] { func accessBody() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return ottlcommon.GetValue(tCtx.GetLogRecord().Body()), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetValue(tCtx.GetLogRecord().Body(), val) }, } @@ -323,7 +323,7 @@ func accessBody() ottl.StandardGetSetter[TransformContext] { func accessBodyKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { body := tCtx.GetLogRecord().Body() switch body.Type() { case pcommon.ValueTypeMap: @@ -334,7 +334,7 @@ func accessBodyKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return nil, fmt.Errorf("log bodies of type %s cannot be indexed", body.Type().String()) } }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { body := tCtx.GetLogRecord().Body() switch body.Type() { case pcommon.ValueTypeMap: @@ -350,10 +350,10 @@ func accessBodyKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { func accessStringBody() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().Body().AsString(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if str, ok := val.(string); ok { tCtx.GetLogRecord().Body().SetStr(str) } @@ -364,10 +364,10 @@ func accessStringBody() ottl.StandardGetSetter[TransformContext] { func accessAttributes() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().Attributes(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if attrs, ok := val.(pcommon.Map); ok { attrs.CopyTo(tCtx.GetLogRecord().Attributes()) } @@ -378,10 +378,10 @@ func accessAttributes() ottl.StandardGetSetter[TransformContext] { func accessAttributesKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.GetLogRecord().Attributes(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.GetLogRecord().Attributes(), keys, val) }, } @@ -389,10 +389,10 @@ func accessAttributesKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContex func accessDroppedAttributesCount() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return int64(tCtx.GetLogRecord().DroppedAttributesCount()), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if i, ok := val.(int64); ok { tCtx.GetLogRecord().SetDroppedAttributesCount(uint32(i)) } @@ -403,10 +403,10 @@ func accessDroppedAttributesCount() ottl.StandardGetSetter[TransformContext] { func accessFlags() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return int64(tCtx.GetLogRecord().Flags()), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if i, ok := val.(int64); ok { tCtx.GetLogRecord().SetFlags(plog.LogRecordFlags(i)) } @@ -417,10 +417,10 @@ func accessFlags() ottl.StandardGetSetter[TransformContext] { func accessTraceID() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().TraceID(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newTraceID, ok := val.(pcommon.TraceID); ok { tCtx.GetLogRecord().SetTraceID(newTraceID) } @@ -431,11 +431,11 @@ func accessTraceID() ottl.StandardGetSetter[TransformContext] { func accessStringTraceID() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { id := tCtx.GetLogRecord().TraceID() return hex.EncodeToString(id[:]), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if str, ok := val.(string); ok { id, err := internal.ParseTraceID(str) if err != nil { @@ -450,10 +450,10 @@ func accessStringTraceID() ottl.StandardGetSetter[TransformContext] { func accessSpanID() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetLogRecord().SpanID(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newSpanID, ok := val.(pcommon.SpanID); ok { tCtx.GetLogRecord().SetSpanID(newSpanID) } @@ -464,11 +464,11 @@ func accessSpanID() ottl.StandardGetSetter[TransformContext] { func accessStringSpanID() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { id := tCtx.GetLogRecord().SpanID() return hex.EncodeToString(id[:]), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if str, ok := val.(string); ok { id, err := internal.ParseSpanID(str) if err != nil { diff --git a/pkg/ottl/contexts/ottllog/log_test.go b/pkg/ottl/contexts/ottllog/log_test.go index 555e10f3f28b..6a1b7fbbebc7 100644 --- a/pkg/ottl/contexts/ottllog/log_test.go +++ b/pkg/ottl/contexts/ottllog/log_test.go @@ -44,16 +44,16 @@ func Test_newPathGetSetter(t *testing.T) { newBodySlice := pcommon.NewSlice() newBodySlice.AppendEmpty().SetStr("data") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(log plog.LogRecord, il pcommon.InstrumentationScope, resource pcommon.Resource, cache pcommon.Map) bodyType string }{ @@ -574,7 +574,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, { - name: "attributes map[string]interface{}", + name: "attributes map[string]any", path: []ottl.Field{ { Name: "attributes", @@ -642,7 +642,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", diff --git a/pkg/ottl/contexts/ottlmetric/metrics.go b/pkg/ottl/contexts/ottlmetric/metrics.go index 4a4b81594541..92267ecadc7d 100644 --- a/pkg/ottl/contexts/ottlmetric/metrics.go +++ b/pkg/ottl/contexts/ottlmetric/metrics.go @@ -134,10 +134,10 @@ func newPathGetSetter(path []ottl.Field) (ottl.GetSetter[TransformContext], erro func accessCache() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.getCache(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if m, ok := val.(pcommon.Map); ok { m.CopyTo(tCtx.getCache()) } @@ -148,10 +148,10 @@ func accessCache() ottl.StandardGetSetter[TransformContext] { func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.getCache(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.getCache(), keys, val) }, } diff --git a/pkg/ottl/contexts/ottlmetric/metrics_test.go b/pkg/ottl/contexts/ottlmetric/metrics_test.go index e41e06f898db..f2480ac51ced 100644 --- a/pkg/ottl/contexts/ottlmetric/metrics_test.go +++ b/pkg/ottl/contexts/ottlmetric/metrics_test.go @@ -32,8 +32,8 @@ func Test_newPathGetSetter(t *testing.T) { tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(metric pmetric.Metric, cache pcommon.Map) }{ { diff --git a/pkg/ottl/contexts/ottlresource/resource.go b/pkg/ottl/contexts/ottlresource/resource.go index 1dc45dbdcedc..921d00311342 100644 --- a/pkg/ottl/contexts/ottlresource/resource.go +++ b/pkg/ottl/contexts/ottlresource/resource.go @@ -101,10 +101,10 @@ func newPathGetSetter(path []ottl.Field) (ottl.GetSetter[TransformContext], erro func accessCache() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.getCache(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if m, ok := val.(pcommon.Map); ok { m.CopyTo(tCtx.getCache()) } @@ -115,10 +115,10 @@ func accessCache() ottl.StandardGetSetter[TransformContext] { func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.getCache(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.getCache(), keys, val) }, } diff --git a/pkg/ottl/contexts/ottlresource/resource_test.go b/pkg/ottl/contexts/ottlresource/resource_test.go index 3950b02966fb..87d8cb397f2c 100644 --- a/pkg/ottl/contexts/ottlresource/resource_test.go +++ b/pkg/ottl/contexts/ottlresource/resource_test.go @@ -27,16 +27,16 @@ func Test_newPathGetSetter(t *testing.T) { pMap2 := newPMap.PutEmptyMap("k2") pMap2.PutStr("k1", "string") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(resource pcommon.Resource, cache pcommon.Map) }{ { @@ -370,7 +370,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", diff --git a/pkg/ottl/contexts/ottlscope/scope.go b/pkg/ottl/contexts/ottlscope/scope.go index b7df07b3d6a4..9c8ce9406c81 100644 --- a/pkg/ottl/contexts/ottlscope/scope.go +++ b/pkg/ottl/contexts/ottlscope/scope.go @@ -110,10 +110,10 @@ func newPathGetSetter(path []ottl.Field) (ottl.GetSetter[TransformContext], erro func accessCache() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.getCache(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if m, ok := val.(pcommon.Map); ok { m.CopyTo(tCtx.getCache()) } @@ -124,10 +124,10 @@ func accessCache() ottl.StandardGetSetter[TransformContext] { func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.getCache(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.getCache(), keys, val) }, } diff --git a/pkg/ottl/contexts/ottlscope/scope_test.go b/pkg/ottl/contexts/ottlscope/scope_test.go index f721aec67436..6c799558d1f2 100644 --- a/pkg/ottl/contexts/ottlscope/scope_test.go +++ b/pkg/ottl/contexts/ottlscope/scope_test.go @@ -27,16 +27,16 @@ func Test_newPathGetSetter(t *testing.T) { pMap2 := newPMap.PutEmptyMap("k2") pMap2.PutStr("k1", "string") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(is pcommon.InstrumentationScope, resource pcommon.Resource, cache pcommon.Map) }{ { @@ -302,7 +302,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, { - name: "attributes map[string]interface{}", + name: "attributes map[string]any", path: []ottl.Field{ { Name: "attributes", @@ -370,7 +370,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", diff --git a/pkg/ottl/contexts/ottlspan/span.go b/pkg/ottl/contexts/ottlspan/span.go index 05345a7fe4ac..34f3d2bcf599 100644 --- a/pkg/ottl/contexts/ottlspan/span.go +++ b/pkg/ottl/contexts/ottlspan/span.go @@ -125,10 +125,10 @@ func newPathGetSetter(path []ottl.Field) (ottl.GetSetter[TransformContext], erro func accessCache() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.getCache(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if m, ok := val.(pcommon.Map); ok { m.CopyTo(tCtx.getCache()) } @@ -139,10 +139,10 @@ func accessCache() ottl.StandardGetSetter[TransformContext] { func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.getCache(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.getCache(), keys, val) }, } diff --git a/pkg/ottl/contexts/ottlspan/span_test.go b/pkg/ottl/contexts/ottlspan/span_test.go index 884d49eecc76..0a195fff813d 100644 --- a/pkg/ottl/contexts/ottlspan/span_test.go +++ b/pkg/ottl/contexts/ottlspan/span_test.go @@ -46,16 +46,16 @@ func Test_newPathGetSetter(t *testing.T) { pMap2 := newPMap.PutEmptyMap("k2") pMap2.PutStr("k1", "string") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(span ptrace.Span, il pcommon.InstrumentationScope, resource pcommon.Resource, cache pcommon.Map) }{ { @@ -533,7 +533,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, { - name: "attributes map[string]interface{}", + name: "attributes map[string]any", path: []ottl.Field{ { Name: "attributes", @@ -601,7 +601,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", diff --git a/pkg/ottl/contexts/ottlspanevent/span_events.go b/pkg/ottl/contexts/ottlspanevent/span_events.go index 99f78d2a0c99..70014a486560 100644 --- a/pkg/ottl/contexts/ottlspanevent/span_events.go +++ b/pkg/ottl/contexts/ottlspanevent/span_events.go @@ -149,10 +149,10 @@ func newPathGetSetter(path []ottl.Field) (ottl.GetSetter[TransformContext], erro func accessCache() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.getCache(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if m, ok := val.(pcommon.Map); ok { m.CopyTo(tCtx.getCache()) } @@ -163,10 +163,10 @@ func accessCache() ottl.StandardGetSetter[TransformContext] { func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.getCache(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.getCache(), keys, val) }, } @@ -174,10 +174,10 @@ func accessCacheKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { func accessSpanEventTimeUnixNano() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetSpanEvent().Timestamp().AsTime().UnixNano(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newTimestamp, ok := val.(int64); ok { tCtx.GetSpanEvent().SetTimestamp(pcommon.NewTimestampFromTime(time.Unix(0, newTimestamp))) } @@ -188,10 +188,10 @@ func accessSpanEventTimeUnixNano() ottl.StandardGetSetter[TransformContext] { func accessSpanEventTime() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetSpanEvent().Timestamp().AsTime(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newTimestamp, ok := val.(time.Time); ok { tCtx.GetSpanEvent().SetTimestamp(pcommon.NewTimestampFromTime(newTimestamp)) } @@ -202,10 +202,10 @@ func accessSpanEventTime() ottl.StandardGetSetter[TransformContext] { func accessSpanEventName() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetSpanEvent().Name(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newName, ok := val.(string); ok { tCtx.GetSpanEvent().SetName(newName) } @@ -216,10 +216,10 @@ func accessSpanEventName() ottl.StandardGetSetter[TransformContext] { func accessSpanEventAttributes() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return tCtx.GetSpanEvent().Attributes(), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if attrs, ok := val.(pcommon.Map); ok { attrs.CopyTo(tCtx.GetSpanEvent().Attributes()) } @@ -230,10 +230,10 @@ func accessSpanEventAttributes() ottl.StandardGetSetter[TransformContext] { func accessSpanEventAttributesKey(keys []ottl.Key) ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return internal.GetMapValue(tCtx.GetSpanEvent().Attributes(), keys) }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { return internal.SetMapValue(tCtx.GetSpanEvent().Attributes(), keys, val) }, } @@ -241,10 +241,10 @@ func accessSpanEventAttributesKey(keys []ottl.Key) ottl.StandardGetSetter[Transf func accessSpanEventDroppedAttributeCount() ottl.StandardGetSetter[TransformContext] { return ottl.StandardGetSetter[TransformContext]{ - Getter: func(ctx context.Context, tCtx TransformContext) (interface{}, error) { + Getter: func(ctx context.Context, tCtx TransformContext) (any, error) { return int64(tCtx.GetSpanEvent().DroppedAttributesCount()), nil }, - Setter: func(ctx context.Context, tCtx TransformContext, val interface{}) error { + Setter: func(ctx context.Context, tCtx TransformContext, val any) error { if newCount, ok := val.(int64); ok { tCtx.GetSpanEvent().SetDroppedAttributesCount(uint32(newCount)) } diff --git a/pkg/ottl/contexts/ottlspanevent/span_events_test.go b/pkg/ottl/contexts/ottlspanevent/span_events_test.go index a96be125b274..1cb71ad73108 100644 --- a/pkg/ottl/contexts/ottlspanevent/span_events_test.go +++ b/pkg/ottl/contexts/ottlspanevent/span_events_test.go @@ -42,16 +42,16 @@ func Test_newPathGetSetter(t *testing.T) { pMap2 := newPMap.PutEmptyMap("k2") pMap2.PutStr("k1", "string") - newMap := make(map[string]interface{}) - newMap2 := make(map[string]interface{}) + newMap := make(map[string]any) + newMap2 := make(map[string]any) newMap2["k1"] = "string" newMap["k2"] = newMap2 tests := []struct { name string path []ottl.Field - orig interface{} - newVal interface{} + orig any + newVal any modified func(spanEvent ptrace.SpanEvent, span ptrace.Span, il pcommon.InstrumentationScope, resource pcommon.Resource, cache pcommon.Map) }{ { @@ -356,7 +356,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, { - name: "attributes map[string]interface{}", + name: "attributes map[string]any", path: []ottl.Field{ { Name: "attributes", @@ -424,7 +424,7 @@ func Test_newPathGetSetter(t *testing.T) { }, }, }, - orig: func() interface{} { + orig: func() any { return nil }(), newVal: "new", diff --git a/pkg/ottl/expression.go b/pkg/ottl/expression.go index e826d4324055..26da44c6c073 100644 --- a/pkg/ottl/expression.go +++ b/pkg/ottl/expression.go @@ -17,22 +17,22 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/internal/ottlcommon" ) -type ExprFunc[K any] func(ctx context.Context, tCtx K) (interface{}, error) +type ExprFunc[K any] func(ctx context.Context, tCtx K) (any, error) type Expr[K any] struct { exprFunc ExprFunc[K] } -func (e Expr[K]) Eval(ctx context.Context, tCtx K) (interface{}, error) { +func (e Expr[K]) Eval(ctx context.Context, tCtx K) (any, error) { return e.exprFunc(ctx, tCtx) } type Getter[K any] interface { - Get(ctx context.Context, tCtx K) (interface{}, error) + Get(ctx context.Context, tCtx K) (any, error) } type Setter[K any] interface { - Set(ctx context.Context, tCtx K, val interface{}) error + Set(ctx context.Context, tCtx K, val any) error } type GetSetter[K any] interface { @@ -41,23 +41,23 @@ type GetSetter[K any] interface { } type StandardGetSetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) - Setter func(ctx context.Context, tCtx K, val interface{}) error + Getter func(ctx context.Context, tCtx K) (any, error) + Setter func(ctx context.Context, tCtx K, val any) error } -func (path StandardGetSetter[K]) Get(ctx context.Context, tCtx K) (interface{}, error) { +func (path StandardGetSetter[K]) Get(ctx context.Context, tCtx K) (any, error) { return path.Getter(ctx, tCtx) } -func (path StandardGetSetter[K]) Set(ctx context.Context, tCtx K, val interface{}) error { +func (path StandardGetSetter[K]) Set(ctx context.Context, tCtx K, val any) error { return path.Setter(ctx, tCtx, val) } type literal[K any] struct { - value interface{} + value any } -func (l literal[K]) Get(context.Context, K) (interface{}, error) { +func (l literal[K]) Get(context.Context, K) (any, error) { return l.value, nil } @@ -66,7 +66,7 @@ type exprGetter[K any] struct { keys []Key } -func (g exprGetter[K]) Get(ctx context.Context, tCtx K) (interface{}, error) { +func (g exprGetter[K]) Get(ctx context.Context, tCtx K) (any, error) { result, err := g.expr.Eval(ctx, tCtx) if err != nil { return nil, err @@ -86,7 +86,7 @@ func (g exprGetter[K]) Get(ctx context.Context, tCtx K) (interface{}, error) { return nil, fmt.Errorf("key not found in map") } result = ottlcommon.GetValue(val) - case map[string]interface{}: + case map[string]any: val, ok := r[*k.String] if !ok { return nil, fmt.Errorf("key not found in map") @@ -102,7 +102,7 @@ func (g exprGetter[K]) Get(ctx context.Context, tCtx K) (interface{}, error) { return nil, fmt.Errorf("index %v out of bounds", *k.Int) } result = ottlcommon.GetValue(r.At(int(*k.Int))) - case []interface{}: + case []any: if int(*k.Int) >= len(r) || int(*k.Int) < 0 { return nil, fmt.Errorf("index %v out of bounds", *k.Int) } @@ -121,7 +121,7 @@ type listGetter[K any] struct { slice []Getter[K] } -func (l *listGetter[K]) Get(ctx context.Context, tCtx K) (interface{}, error) { +func (l *listGetter[K]) Get(ctx context.Context, tCtx K) (any, error) { evaluated := make([]any, len(l.slice)) for i, v := range l.slice { @@ -150,7 +150,7 @@ type StringGetter[K any] interface { // StandardStringGetter is a basic implementation of StringGetter type StandardStringGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } // Get retrieves a string value. @@ -185,7 +185,7 @@ type IntGetter[K any] interface { // StandardIntGetter is a basic implementation of IntGetter type StandardIntGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } // Get retrieves an int64 value. @@ -220,7 +220,7 @@ type FloatGetter[K any] interface { // StandardFloatGetter is a basic implementation of FloatGetter type StandardFloatGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } // Get retrieves a float64 value. @@ -297,7 +297,7 @@ type PMapGetter[K any] interface { // StandardPMapGetter is a basic implementation of PMapGetter type StandardPMapGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } // Get retrieves a pcommon.Map value. @@ -341,7 +341,7 @@ type StringLikeGetter[K any] interface { } type StandardStringLikeGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } func (g StandardStringLikeGetter[K]) Get(ctx context.Context, tCtx K) (*string, error) { @@ -389,7 +389,7 @@ type FloatLikeGetter[K any] interface { } type StandardFloatLikeGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } func (g StandardFloatLikeGetter[K]) Get(ctx context.Context, tCtx K) (*float64, error) { @@ -453,7 +453,7 @@ type IntLikeGetter[K any] interface { } type StandardIntLikeGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } func (g StandardIntLikeGetter[K]) Get(ctx context.Context, tCtx K) (*int64, error) { @@ -583,7 +583,7 @@ type TimeGetter[K any] interface { // StandardTimeGetter is a basic implementation of TimeGetter type StandardTimeGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } // Get retrieves a time.Time value. @@ -613,7 +613,7 @@ type DurationGetter[K any] interface { // StandardDurationGetter is a basic implementation of DurationGetter type StandardDurationGetter[K any] struct { - Getter func(ctx context.Context, tCtx K) (interface{}, error) + Getter func(ctx context.Context, tCtx K) (any, error) } // Get retrieves an time.Duration value. diff --git a/pkg/ottl/expression_test.go b/pkg/ottl/expression_test.go index 7b57713fb2c7..d99c44f92fb9 100644 --- a/pkg/ottl/expression_test.go +++ b/pkg/ottl/expression_test.go @@ -24,7 +24,7 @@ func hello() (ExprFunc[any], error) { } func pmap() (ExprFunc[any], error) { - return func(ctx context.Context, tCtx any) (interface{}, error) { + return func(ctx context.Context, tCtx any) (any, error) { m := pcommon.NewMap() m.PutEmptyMap("foo").PutStr("bar", "pass") return m, nil @@ -32,9 +32,9 @@ func pmap() (ExprFunc[any], error) { } func basicMap() (ExprFunc[any], error) { - return func(ctx context.Context, tCtx any) (interface{}, error) { - return map[string]interface{}{ - "foo": map[string]interface{}{ + return func(ctx context.Context, tCtx any) (any, error) { + return map[string]any{ + "foo": map[string]any{ "bar": "pass", }, }, nil @@ -42,7 +42,7 @@ func basicMap() (ExprFunc[any], error) { } func pslice() (ExprFunc[any], error) { - return func(ctx context.Context, tCtx any) (interface{}, error) { + return func(ctx context.Context, tCtx any) (any, error) { s := pcommon.NewSlice() s.AppendEmpty().SetEmptySlice().AppendEmpty().SetStr("pass") return s, nil @@ -50,9 +50,9 @@ func pslice() (ExprFunc[any], error) { } func basicSlice() (ExprFunc[any], error) { - return func(ctx context.Context, tCtx any) (interface{}, error) { - return []interface{}{ - []interface{}{ + return func(ctx context.Context, tCtx any) (any, error) { + return []any{ + []any{ "pass", }, }, nil @@ -63,8 +63,8 @@ func Test_newGetter(t *testing.T) { tests := []struct { name string val value - ctx interface{} - want interface{} + ctx any + want any }{ { name: "string literal", @@ -617,15 +617,15 @@ func Test_exprGetter_Get_Invalid(t *testing.T) { func Test_StandardStringGetter(t *testing.T) { tests := []struct { name string - getter StandardStringGetter[interface{}] - want interface{} + getter StandardStringGetter[any] + want any valid bool expectedErrorMsg string }{ { name: "string type", - getter: StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "str", nil }, }, @@ -634,8 +634,8 @@ func Test_StandardStringGetter(t *testing.T) { }, { name: "ValueTypeString type", - getter: StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return pcommon.NewValueStr("str"), nil }, }, @@ -644,8 +644,8 @@ func Test_StandardStringGetter(t *testing.T) { }, { name: "Incorrect type", - getter: StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -654,8 +654,8 @@ func Test_StandardStringGetter(t *testing.T) { }, { name: "nil", - getter: StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -709,14 +709,14 @@ func Test_FunctionGetter(t *testing.T) { name string getter StringGetter[any] function FunctionGetter[any] - want interface{} + want any valid bool expectedErrorMsg string }{ { name: "function getter", - getter: StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "str", nil }, }, @@ -726,8 +726,8 @@ func Test_FunctionGetter(t *testing.T) { }, { name: "function getter nil", - getter: StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -738,8 +738,8 @@ func Test_FunctionGetter(t *testing.T) { }, { name: "function arg mismatch", - getter: StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -750,8 +750,8 @@ func Test_FunctionGetter(t *testing.T) { }, { name: "Cannot create function", - getter: StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -770,7 +770,7 @@ func Test_FunctionGetter(t *testing.T) { } fn, err := editorArgs.Function.Get(&FuncArgs{Input: editorArgs.Replacement}) if tt.valid { - var result interface{} + var result any result, err = fn.Eval(context.Background(), nil) assert.NoError(t, err) assert.Equal(t, tt.want, result.(string)) @@ -783,8 +783,8 @@ func Test_FunctionGetter(t *testing.T) { // nolint:errorlint func Test_StandardStringGetter_WrappedError(t *testing.T) { - getter := StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } @@ -797,15 +797,15 @@ func Test_StandardStringGetter_WrappedError(t *testing.T) { func Test_StandardStringLikeGetter(t *testing.T) { tests := []struct { name string - getter StringLikeGetter[interface{}] - want interface{} + getter StringLikeGetter[any] + want any valid bool expectedErrorMsg string }{ { name: "string type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "str", nil }, }, @@ -814,8 +814,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "bool type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -824,8 +824,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "int64 type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return int64(1), nil }, }, @@ -834,8 +834,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "float64 type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1.1, nil }, }, @@ -844,8 +844,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "byte[] type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return []byte{0}, nil }, }, @@ -854,8 +854,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "pcommon.map type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { m := pcommon.NewMap() m.PutStr("test", "passed") return m, nil @@ -866,8 +866,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "pcommon.slice type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { s := pcommon.NewSlice() v := s.AppendEmpty() v.SetStr("test") @@ -879,8 +879,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "pcommon.value type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueInt(int64(100)) return v, nil }, @@ -890,8 +890,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "nil", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -900,8 +900,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { }, { name: "invalid type", - getter: StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return make(chan int), nil }, }, @@ -930,8 +930,8 @@ func Test_StandardStringLikeGetter(t *testing.T) { // nolint:errorlint func Test_StandardStringLikeGetter_WrappedError(t *testing.T) { - getter := StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } @@ -944,15 +944,15 @@ func Test_StandardStringLikeGetter_WrappedError(t *testing.T) { func Test_StandardFloatGetter(t *testing.T) { tests := []struct { name string - getter StandardFloatGetter[interface{}] - want interface{} + getter StandardFloatGetter[any] + want any valid bool expectedErrorMsg string }{ { name: "float64 type", - getter: StandardFloatGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1.1, nil }, }, @@ -961,8 +961,8 @@ func Test_StandardFloatGetter(t *testing.T) { }, { name: "ValueTypeFloat type", - getter: StandardFloatGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return pcommon.NewValueDouble(1.1), nil }, }, @@ -971,8 +971,8 @@ func Test_StandardFloatGetter(t *testing.T) { }, { name: "Incorrect type", - getter: StandardFloatGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -981,8 +981,8 @@ func Test_StandardFloatGetter(t *testing.T) { }, { name: "nil", - getter: StandardFloatGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -1007,8 +1007,8 @@ func Test_StandardFloatGetter(t *testing.T) { // nolint:errorlint func Test_StandardFloatGetter_WrappedError(t *testing.T) { - getter := StandardFloatGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardFloatGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } @@ -1021,15 +1021,15 @@ func Test_StandardFloatGetter_WrappedError(t *testing.T) { func Test_StandardFloatLikeGetter(t *testing.T) { tests := []struct { name string - getter FloatLikeGetter[interface{}] - want interface{} + getter FloatLikeGetter[any] + want any valid bool expectedErrorMsg string }{ { name: "string type", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "1.0", nil }, }, @@ -1038,8 +1038,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "int64 type", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return int64(1), nil }, }, @@ -1048,8 +1048,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "float64 type", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1.1, nil }, }, @@ -1058,8 +1058,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "float64 bool true", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -1068,8 +1068,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "float64 bool false", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return false, nil }, }, @@ -1078,8 +1078,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "pcommon.value type int", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueInt(int64(100)) return v, nil }, @@ -1089,8 +1089,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "pcommon.value type float", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueDouble(float64(1.1)) return v, nil }, @@ -1100,8 +1100,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "pcommon.value type string", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueStr("1.1") return v, nil }, @@ -1111,8 +1111,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "pcommon.value type bool true", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueBool(true) return v, nil }, @@ -1122,8 +1122,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "pcommon.value type bool false", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueBool(false) return v, nil }, @@ -1133,8 +1133,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "nil", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -1143,8 +1143,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "invalid type", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return []byte{}, nil }, }, @@ -1153,8 +1153,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { }, { name: "invalid pcommon.Value type", - getter: StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueMap() return v, nil }, @@ -1184,8 +1184,8 @@ func Test_StandardFloatLikeGetter(t *testing.T) { // nolint:errorlint func Test_StandardFloatLikeGetter_WrappedError(t *testing.T) { - getter := StandardFloatLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardFloatLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } @@ -1198,15 +1198,15 @@ func Test_StandardFloatLikeGetter_WrappedError(t *testing.T) { func Test_StandardIntGetter(t *testing.T) { tests := []struct { name string - getter StandardIntGetter[interface{}] - want interface{} + getter StandardIntGetter[any] + want any valid bool expectedErrorMsg string }{ { name: "int64 type", - getter: StandardIntGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return int64(1), nil }, }, @@ -1215,8 +1215,8 @@ func Test_StandardIntGetter(t *testing.T) { }, { name: "ValueTypeInt type", - getter: StandardIntGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return pcommon.NewValueInt(1), nil }, }, @@ -1225,8 +1225,8 @@ func Test_StandardIntGetter(t *testing.T) { }, { name: "Incorrect type", - getter: StandardIntGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -1235,8 +1235,8 @@ func Test_StandardIntGetter(t *testing.T) { }, { name: "nil", - getter: StandardIntGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -1261,8 +1261,8 @@ func Test_StandardIntGetter(t *testing.T) { // nolint:errorlint func Test_StandardIntGetter_WrappedError(t *testing.T) { - getter := StandardIntGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardIntGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } @@ -1275,15 +1275,15 @@ func Test_StandardIntGetter_WrappedError(t *testing.T) { func Test_StandardIntLikeGetter(t *testing.T) { tests := []struct { name string - getter IntLikeGetter[interface{}] - want interface{} + getter IntLikeGetter[any] + want any valid bool expectedErrorMsg string }{ { name: "string type", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "1", nil }, }, @@ -1292,8 +1292,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "int64 type", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return int64(1), nil }, }, @@ -1302,8 +1302,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "float64 type", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1.1, nil }, }, @@ -1312,8 +1312,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "primitive bool true", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -1322,8 +1322,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "primitive bool false", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return false, nil }, }, @@ -1332,8 +1332,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "pcommon.value type int", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueInt(int64(100)) return v, nil }, @@ -1343,8 +1343,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "pcommon.value type float", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueDouble(float64(1.9)) return v, nil }, @@ -1354,8 +1354,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "pcommon.value type string", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueStr("1") return v, nil }, @@ -1365,8 +1365,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "pcommon.value type bool true", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueBool(true) return v, nil }, @@ -1376,8 +1376,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "pcommon.value type bool false", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueBool(false) return v, nil }, @@ -1387,8 +1387,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "nil", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -1397,8 +1397,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "invalid type", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return []byte{}, nil }, }, @@ -1407,8 +1407,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { }, { name: "invalid pcommon.Value type", - getter: StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueMap() return v, nil }, @@ -1438,8 +1438,8 @@ func Test_StandardIntLikeGetter(t *testing.T) { // nolint:errorlint func Test_StandardIntLikeGetter_WrappedError(t *testing.T) { - getter := StandardIntLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardIntLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } @@ -1452,15 +1452,15 @@ func Test_StandardIntLikeGetter_WrappedError(t *testing.T) { func Test_StandardPMapGetter(t *testing.T) { tests := []struct { name string - getter StandardPMapGetter[interface{}] - want interface{} + getter StandardPMapGetter[any] + want any valid bool expectedErrorMsg string }{ { name: "pcommon.map type", - getter: StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return pcommon.NewMap(), nil }, }, @@ -1469,8 +1469,8 @@ func Test_StandardPMapGetter(t *testing.T) { }, { name: "map[string]any type", - getter: StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return make(map[string]any), nil }, }, @@ -1479,8 +1479,8 @@ func Test_StandardPMapGetter(t *testing.T) { }, { name: "ValueTypeMap type", - getter: StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return pcommon.NewValueMap(), nil }, }, @@ -1489,8 +1489,8 @@ func Test_StandardPMapGetter(t *testing.T) { }, { name: "Incorrect type", - getter: StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -1499,8 +1499,8 @@ func Test_StandardPMapGetter(t *testing.T) { }, { name: "nil", - getter: StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -1525,8 +1525,8 @@ func Test_StandardPMapGetter(t *testing.T) { // nolint:errorlint func Test_StandardPMapGetter_WrappedError(t *testing.T) { - getter := StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } @@ -1548,15 +1548,15 @@ func Test_StandardDurationGetter(t *testing.T) { tests := []struct { name string - getter StandardDurationGetter[interface{}] - want interface{} + getter StandardDurationGetter[any] + want any valid bool expectedErrorMsg string }{ { name: "complex duration", - getter: StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("1h1m1s") }, }, @@ -1565,8 +1565,8 @@ func Test_StandardDurationGetter(t *testing.T) { }, { name: "simple duration", - getter: StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100ns") }, }, @@ -1575,8 +1575,8 @@ func Test_StandardDurationGetter(t *testing.T) { }, { name: "complex duation values less than 1 seconc", - getter: StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("10ms66us7000ns") }, }, @@ -1585,8 +1585,8 @@ func Test_StandardDurationGetter(t *testing.T) { }, { name: "invalid duration units", - getter: StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("70ps") }, }, @@ -1595,8 +1595,8 @@ func Test_StandardDurationGetter(t *testing.T) { }, { name: "wrong type - int", - getter: StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, }, @@ -1605,8 +1605,8 @@ func Test_StandardDurationGetter(t *testing.T) { }, { name: "nil", - getter: StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -1630,8 +1630,8 @@ func Test_StandardDurationGetter(t *testing.T) { // nolint:errorlint func Test_StandardDurationGetter_WrappedError(t *testing.T) { - getter := StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } @@ -1644,15 +1644,15 @@ func Test_StandardDurationGetter_WrappedError(t *testing.T) { func Test_StandardTimeGetter(t *testing.T) { tests := []struct { name string - getter StandardTimeGetter[interface{}] + getter StandardTimeGetter[any] want string valid bool expectedErrorMsg string }{ { name: "2023 time", - getter: StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2023, 8, 17, 1, 1, 1, 1, time.UTC), nil }, }, @@ -1661,8 +1661,8 @@ func Test_StandardTimeGetter(t *testing.T) { }, { name: "before 2000 time", - getter: StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(1999, 12, 1, 10, 59, 58, 57, time.UTC), nil }, }, @@ -1671,8 +1671,8 @@ func Test_StandardTimeGetter(t *testing.T) { }, { name: "wrong type - duration", - getter: StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("70ns") }, }, @@ -1681,8 +1681,8 @@ func Test_StandardTimeGetter(t *testing.T) { }, { name: "wrong type - bool", - getter: StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -1691,8 +1691,8 @@ func Test_StandardTimeGetter(t *testing.T) { }, { name: "nil", - getter: StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter: StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -1719,8 +1719,8 @@ func Test_StandardTimeGetter(t *testing.T) { // nolint:errorlint func Test_StandardTimeGetter_WrappedError(t *testing.T) { - getter := StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, TypeError("") }, } diff --git a/pkg/ottl/factory.go b/pkg/ottl/factory.go index a5b805632d85..f4ff94f1872d 100644 --- a/pkg/ottl/factory.go +++ b/pkg/ottl/factory.go @@ -7,7 +7,7 @@ import "go.opentelemetry.io/collector/component" // Arguments holds the arguments for an OTTL function, with arguments // specified as fields on a struct. Argument ordering is defined -type Arguments interface{} +type Arguments any // FunctionContext contains data provided by the Collector // component to the OTTL for use in functions. diff --git a/pkg/ottl/functions_test.go b/pkg/ottl/functions_test.go index 07f18d545c5e..8e4d54e47aff 100644 --- a/pkg/ottl/functions_test.go +++ b/pkg/ottl/functions_test.go @@ -1519,8 +1519,8 @@ type floatSliceArguments struct { Floats []float64 } -func functionWithFloatSlice(floats []float64) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithFloatSlice(floats []float64) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(floats), nil }, nil } @@ -1529,8 +1529,8 @@ type intSliceArguments struct { Ints []int64 } -func functionWithIntSlice(ints []int64) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithIntSlice(ints []int64) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(ints), nil }, nil } @@ -1539,8 +1539,8 @@ type byteSliceArguments struct { Bytes []byte } -func functionWithByteSlice(bytes []byte) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithByteSlice(bytes []byte) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(bytes), nil }, nil } @@ -1549,8 +1549,8 @@ type getterSliceArguments struct { Getters []Getter[any] } -func functionWithGetterSlice(getters []Getter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithGetterSlice(getters []Getter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(getters), nil }, nil } @@ -1559,8 +1559,8 @@ type stringGetterSliceArguments struct { StringGetters []StringGetter[any] } -func functionWithStringGetterSlice(getters []StringGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithStringGetterSlice(getters []StringGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(getters), nil }, nil } @@ -1569,8 +1569,8 @@ type durationGetterSliceArguments struct { DurationGetters []DurationGetter[any] } -func functionWithDurationGetterSlice(_ []DurationGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithDurationGetterSlice(_ []DurationGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return nil, nil }, nil } @@ -1579,8 +1579,8 @@ type timeGetterSliceArguments struct { TimeGetters []TimeGetter[any] } -func functionWithTimeGetterSlice(_ []TimeGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithTimeGetterSlice(_ []TimeGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return nil, nil }, nil } @@ -1589,8 +1589,8 @@ type floatGetterSliceArguments struct { FloatGetters []FloatGetter[any] } -func functionWithFloatGetterSlice(getters []FloatGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithFloatGetterSlice(getters []FloatGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(getters), nil }, nil } @@ -1599,8 +1599,8 @@ type intGetterSliceArguments struct { IntGetters []IntGetter[any] } -func functionWithIntGetterSlice(getters []IntGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithIntGetterSlice(getters []IntGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(getters), nil }, nil } @@ -1609,8 +1609,8 @@ type pMapGetterSliceArguments struct { PMapGetters []PMapGetter[any] } -func functionWithPMapGetterSlice(getters []PMapGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithPMapGetterSlice(getters []PMapGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(getters), nil }, nil } @@ -1619,8 +1619,8 @@ type stringLikeGetterSliceArguments struct { StringLikeGetters []StringLikeGetter[any] } -func functionWithStringLikeGetterSlice(getters []StringLikeGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithStringLikeGetterSlice(getters []StringLikeGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(getters), nil }, nil } @@ -1629,8 +1629,8 @@ type floatLikeGetterSliceArguments struct { FloatLikeGetters []FloatLikeGetter[any] } -func functionWithFloatLikeGetterSlice(getters []FloatLikeGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithFloatLikeGetterSlice(getters []FloatLikeGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(getters), nil }, nil } @@ -1639,8 +1639,8 @@ type intLikeGetterSliceArguments struct { IntLikeGetters []IntLikeGetter[any] } -func functionWithIntLikeGetterSlice(getters []IntLikeGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithIntLikeGetterSlice(getters []IntLikeGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return len(getters), nil }, nil } @@ -1649,8 +1649,8 @@ type setterArguments struct { SetterArg Setter[any] } -func functionWithSetter(Setter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithSetter(Setter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1659,8 +1659,8 @@ type getSetterArguments struct { GetSetterArg GetSetter[any] } -func functionWithGetSetter(GetSetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithGetSetter(GetSetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1669,8 +1669,8 @@ type getterArguments struct { GetterArg Getter[any] } -func functionWithGetter(Getter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithGetter(Getter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1679,8 +1679,8 @@ type stringGetterArguments struct { StringGetterArg StringGetter[any] } -func functionWithStringGetter(StringGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithStringGetter(StringGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1689,8 +1689,8 @@ type durationGetterArguments struct { DurationGetterArg DurationGetter[any] } -func functionWithDurationGetter(DurationGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithDurationGetter(DurationGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1699,8 +1699,8 @@ type timeGetterArguments struct { TimeGetterArg TimeGetter[any] } -func functionWithTimeGetter(TimeGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithTimeGetter(TimeGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1709,8 +1709,8 @@ type functionGetterArguments struct { FunctionGetterArg FunctionGetter[any] } -func functionWithFunctionGetter(FunctionGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithFunctionGetter(FunctionGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "hashstring", nil }, nil } @@ -1719,8 +1719,8 @@ type stringLikeGetterArguments struct { StringLikeGetterArg StringLikeGetter[any] } -func functionWithStringLikeGetter(StringLikeGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithStringLikeGetter(StringLikeGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1729,8 +1729,8 @@ type floatGetterArguments struct { FloatGetterArg FloatGetter[any] } -func functionWithFloatGetter(FloatGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithFloatGetter(FloatGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1739,8 +1739,8 @@ type floatLikeGetterArguments struct { FloatLikeGetterArg FloatLikeGetter[any] } -func functionWithFloatLikeGetter(FloatLikeGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithFloatLikeGetter(FloatLikeGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1749,8 +1749,8 @@ type intGetterArguments struct { IntGetterArg IntGetter[any] } -func functionWithIntGetter(IntGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithIntGetter(IntGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1759,8 +1759,8 @@ type intLikeGetterArguments struct { IntLikeGetterArg IntLikeGetter[any] } -func functionWithIntLikeGetter(IntLikeGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithIntLikeGetter(IntLikeGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1769,8 +1769,8 @@ type pMapGetterArguments struct { PMapArg PMapGetter[any] } -func functionWithPMapGetter(PMapGetter[interface{}]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithPMapGetter(PMapGetter[any]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1779,8 +1779,8 @@ type stringArguments struct { StringArg string } -func functionWithString(string) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithString(string) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1789,8 +1789,8 @@ type floatArguments struct { FloatArg float64 } -func functionWithFloat(float64) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithFloat(float64) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1799,8 +1799,8 @@ type intArguments struct { IntArg int64 } -func functionWithInt(int64) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithInt(int64) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1809,8 +1809,8 @@ type boolArguments struct { BoolArg bool } -func functionWithBool(bool) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithBool(bool) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1822,8 +1822,8 @@ type multipleArgsArguments struct { IntArg int64 } -func functionWithMultipleArgs(GetSetter[interface{}], string, float64, int64) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithMultipleArgs(GetSetter[any], string, float64, int64) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } @@ -1835,8 +1835,8 @@ type optionalArgsArguments struct { OptionalFloatArg Optional[float64] `ottlarg:"3"` } -func functionWithOptionalArgs(_ GetSetter[interface{}], _ string, stringOpt Optional[StringGetter[any]], floatOpt Optional[float64]) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithOptionalArgs(_ GetSetter[any], _ string, stringOpt Optional[StringGetter[any]], floatOpt Optional[float64]) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { argCount := 2 if !stringOpt.IsEmpty() { @@ -1852,9 +1852,9 @@ func functionWithOptionalArgs(_ GetSetter[interface{}], _ string, stringOpt Opti type errorFunctionArguments struct{} -func functionThatHasAnError() (ExprFunc[interface{}], error) { +func functionThatHasAnError() (ExprFunc[any], error) { err := errors.New("testing") - return func(context.Context, interface{}) (interface{}, error) { + return func(context.Context, any) (any, error) { return "anything", nil }, err } @@ -1863,8 +1863,8 @@ type enumArguments struct { EnumArg Enum } -func functionWithEnum(Enum) (ExprFunc[interface{}], error) { - return func(context.Context, interface{}) (interface{}, error) { +func functionWithEnum(Enum) (ExprFunc[any], error) { + return func(context.Context, any) (any, error) { return "anything", nil }, nil } diff --git a/pkg/ottl/internal/ottlcommon/value.go b/pkg/ottl/internal/ottlcommon/value.go index 1af1caf7bb92..75ea60fbfa87 100644 --- a/pkg/ottl/internal/ottlcommon/value.go +++ b/pkg/ottl/internal/ottlcommon/value.go @@ -7,7 +7,7 @@ import ( "go.opentelemetry.io/collector/pdata/pcommon" ) -func GetValue(val pcommon.Value) interface{} { +func GetValue(val pcommon.Value) any { switch val.Type() { case pcommon.ValueTypeStr: return val.Str() diff --git a/pkg/ottl/math.go b/pkg/ottl/math.go index 897ed22c3ade..eae661e639ef 100644 --- a/pkg/ottl/math.go +++ b/pkg/ottl/math.go @@ -55,7 +55,7 @@ func (p *Parser[K]) evaluateMathValue(val *mathValue) (Getter[K], error) { func attemptMathOperation[K any](lhs Getter[K], op mathOp, rhs Getter[K]) Getter[K] { return exprGetter[K]{ expr: Expr[K]{ - exprFunc: func(ctx context.Context, tCtx K) (interface{}, error) { + exprFunc: func(ctx context.Context, tCtx K) (any, error) { x, err := lhs.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/math_test.go b/pkg/ottl/math_test.go index 183a62a8141f..e993b3dd8d53 100644 --- a/pkg/ottl/math_test.go +++ b/pkg/ottl/math_test.go @@ -18,24 +18,24 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottltest" ) -func mathParsePath(val *Path) (GetSetter[interface{}], error) { +func mathParsePath(val *Path) (GetSetter[any], error) { if val != nil && len(val.Fields) > 0 && val.Fields[0].Name == "one" { - return &StandardGetSetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + return &StandardGetSetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(1), nil }, }, nil } if val != nil && len(val.Fields) > 0 && val.Fields[0].Name == "two" { - return &StandardGetSetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + return &StandardGetSetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(2), nil }, }, nil } if val != nil && len(val.Fields) > 0 && val.Fields[0].Name == "three" && val.Fields[1].Name == "one" { - return &StandardGetSetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + return &StandardGetSetter[any]{ + Getter: func(context.Context, any) (any, error) { return 3.1, nil }, }, nil @@ -44,19 +44,19 @@ func mathParsePath(val *Path) (GetSetter[interface{}], error) { } func one[K any]() (ExprFunc[K], error) { - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { return int64(1), nil }, nil } func two[K any]() (ExprFunc[K], error) { - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { return int64(2), nil }, nil } func threePointOne[K any]() (ExprFunc[K], error) { - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { return 3.1, nil }, nil } @@ -66,7 +66,7 @@ func testTime[K any](time string, format string) (ExprFunc[K], error) { if err != nil { return nil, err } - return func(_ context.Context, tCtx K) (interface{}, error) { + return func(_ context.Context, tCtx K) (any, error) { timestamp, err := timeutils.ParseStrptime(format, time, loc) return timestamp, err }, nil @@ -74,7 +74,7 @@ func testTime[K any](time string, format string) (ExprFunc[K], error) { func testDuration[K any](duration string) (ExprFunc[K], error) { if duration != "" { - return func(_ context.Context, tCtx K) (interface{}, error) { + return func(_ context.Context, tCtx K) (any, error) { dur, err := time.ParseDuration(duration) return dur, err }, nil @@ -88,7 +88,7 @@ type sumArguments struct { //nolint:unparam func sum[K any](ints []int64) (ExprFunc[K], error) { - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { result := int64(0) for _, x := range ints { result += x @@ -101,7 +101,7 @@ func Test_evaluateMathExpression(t *testing.T) { tests := []struct { name string input string - expected interface{} + expected any }{ { name: "simple subtraction", diff --git a/pkg/ottl/ottlfuncs/func_concat.go b/pkg/ottl/ottlfuncs/func_concat.go index 08a0db0d863c..ec40780371df 100644 --- a/pkg/ottl/ottlfuncs/func_concat.go +++ b/pkg/ottl/ottlfuncs/func_concat.go @@ -31,7 +31,7 @@ func createConcatFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) ( } func concat[K any](vals []ottl.StringLikeGetter[K], delimiter string) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { builder := strings.Builder{} for i, rv := range vals { val, err := rv.Get(ctx, tCtx) diff --git a/pkg/ottl/ottlfuncs/func_concat_test.go b/pkg/ottl/ottlfuncs/func_concat_test.go index b1f66ca01cd3..6bb9db510882 100644 --- a/pkg/ottl/ottlfuncs/func_concat_test.go +++ b/pkg/ottl/ottlfuncs/func_concat_test.go @@ -16,20 +16,20 @@ import ( func Test_concat(t *testing.T) { tests := []struct { name string - vals []ottl.StandardStringLikeGetter[interface{}] + vals []ottl.StandardStringLikeGetter[any] delimiter string expected string }{ { name: "concat strings", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "hello", nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "world", nil }, }, @@ -39,19 +39,19 @@ func Test_concat(t *testing.T) { }, { name: "nil", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "hello", nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "world", nil }, }, @@ -61,14 +61,14 @@ func Test_concat(t *testing.T) { }, { name: "integers", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "hello", nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return int64(1), nil }, }, @@ -78,14 +78,14 @@ func Test_concat(t *testing.T) { }, { name: "floats", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "hello", nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return 3.14159, nil }, }, @@ -95,14 +95,14 @@ func Test_concat(t *testing.T) { }, { name: "booleans", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "hello", nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -112,9 +112,9 @@ func Test_concat(t *testing.T) { }, { name: "byte slices", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0xd2, 0xe6, 0x3c, 0xbe, 0x71, 0xf5, 0xa8}, nil }, }, @@ -124,16 +124,16 @@ func Test_concat(t *testing.T) { }, { name: "pcommon.Slice", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { s := pcommon.NewSlice() _ = s.FromRaw([]any{1, 2}) return s, nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { s := pcommon.NewSlice() _ = s.FromRaw([]any{3, 4}) return s, nil @@ -145,16 +145,16 @@ func Test_concat(t *testing.T) { }, { name: "maps", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { m := pcommon.NewMap() m.PutStr("a", "b") return m, nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { m := pcommon.NewMap() m.PutStr("c", "d") return m, nil @@ -166,19 +166,19 @@ func Test_concat(t *testing.T) { }, { name: "empty string values", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -188,9 +188,9 @@ func Test_concat(t *testing.T) { }, { name: "single argument", - vals: []ottl.StandardStringLikeGetter[interface{}]{ + vals: []ottl.StandardStringLikeGetter[any]{ { - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "hello", nil }, }, @@ -200,20 +200,20 @@ func Test_concat(t *testing.T) { }, { name: "no arguments", - vals: []ottl.StandardStringLikeGetter[interface{}]{}, + vals: []ottl.StandardStringLikeGetter[any]{}, delimiter: "-", expected: "", }, { name: "no arguments with an empty delimiter", - vals: []ottl.StandardStringLikeGetter[interface{}]{}, + vals: []ottl.StandardStringLikeGetter[any]{}, delimiter: "", expected: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - getters := make([]ottl.StringLikeGetter[interface{}], len(tt.vals)) + getters := make([]ottl.StringLikeGetter[any], len(tt.vals)) for i, val := range tt.vals { getters[i] = val @@ -228,12 +228,12 @@ func Test_concat(t *testing.T) { } func Test_concat_error(t *testing.T) { - target := &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return make(chan int), nil }, } - exprFunc := concat[interface{}]([]ottl.StringLikeGetter[interface{}]{target}, "test") + exprFunc := concat[any]([]ottl.StringLikeGetter[any]{target}, "test") _, err := exprFunc(context.Background(), nil) assert.Error(t, err) } diff --git a/pkg/ottl/ottlfuncs/func_convert_case.go b/pkg/ottl/ottlfuncs/func_convert_case.go index 79970fd3322f..95a9bd848fa0 100644 --- a/pkg/ottl/ottlfuncs/func_convert_case.go +++ b/pkg/ottl/ottlfuncs/func_convert_case.go @@ -37,7 +37,7 @@ func convertCase[K any](target ottl.StringGetter[K], toCase string) (ottl.ExprFu return nil, fmt.Errorf("invalid case: %s, allowed cases are: lower, upper, snake, camel", toCase) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_convert_case_test.go b/pkg/ottl/ottlfuncs/func_convert_case_test.go index 2fa59d9dd717..1e7134f49940 100644 --- a/pkg/ottl/ottlfuncs/func_convert_case_test.go +++ b/pkg/ottl/ottlfuncs/func_convert_case_test.go @@ -16,15 +16,15 @@ import ( func Test_convertCase(t *testing.T) { tests := []struct { name string - target ottl.StringGetter[interface{}] + target ottl.StringGetter[any] toCase string - expected interface{} + expected any }{ // snake case { name: "snake simple convert", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "simpleString", nil }, }, @@ -33,8 +33,8 @@ func Test_convertCase(t *testing.T) { }, { name: "snake noop already snake case", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "simple_string", nil }, }, @@ -43,8 +43,8 @@ func Test_convertCase(t *testing.T) { }, { name: "snake multiple uppercase", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "CPUUtilizationMetric", nil }, }, @@ -53,8 +53,8 @@ func Test_convertCase(t *testing.T) { }, { name: "snake hyphens", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "simple-string", nil }, }, @@ -63,8 +63,8 @@ func Test_convertCase(t *testing.T) { }, { name: "snake empty string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -74,8 +74,8 @@ func Test_convertCase(t *testing.T) { // camel case { name: "camel simple convert", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "simple_string", nil }, }, @@ -84,8 +84,8 @@ func Test_convertCase(t *testing.T) { }, { name: "snake noop already snake case", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "SimpleString", nil }, }, @@ -94,8 +94,8 @@ func Test_convertCase(t *testing.T) { }, { name: "snake hyphens", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "simple-string", nil }, }, @@ -104,8 +104,8 @@ func Test_convertCase(t *testing.T) { }, { name: "snake empty string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -115,8 +115,8 @@ func Test_convertCase(t *testing.T) { // upper case { name: "upper simple", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "simple", nil }, }, @@ -125,8 +125,8 @@ func Test_convertCase(t *testing.T) { }, { name: "upper complex", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "complex_SET-of.WORDS1234", nil }, }, @@ -135,8 +135,8 @@ func Test_convertCase(t *testing.T) { }, { name: "upper empty string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -146,8 +146,8 @@ func Test_convertCase(t *testing.T) { // lower case { name: "lower simple", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "SIMPLE", nil }, }, @@ -156,8 +156,8 @@ func Test_convertCase(t *testing.T) { }, { name: "lower complex", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "complex_SET-of.WORDS1234", nil }, }, @@ -166,8 +166,8 @@ func Test_convertCase(t *testing.T) { }, { name: "lower empty string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -189,13 +189,13 @@ func Test_convertCase(t *testing.T) { func Test_convertCaseError(t *testing.T) { tests := []struct { name string - target ottl.StringGetter[interface{}] + target ottl.StringGetter[any] toCase string }{ { name: "error bad case", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "simpleString", nil }, }, @@ -214,14 +214,14 @@ func Test_convertCaseError(t *testing.T) { func Test_convertCaseRuntimeError(t *testing.T) { tests := []struct { name string - target ottl.StringGetter[interface{}] + target ottl.StringGetter[any] toCase string expectedError string }{ { name: "non-string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 10, nil }, }, @@ -230,8 +230,8 @@ func Test_convertCaseRuntimeError(t *testing.T) { }, { name: "nil", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_delete_key.go b/pkg/ottl/ottlfuncs/func_delete_key.go index 443f3d8df5b1..4dae69be0c5e 100644 --- a/pkg/ottl/ottlfuncs/func_delete_key.go +++ b/pkg/ottl/ottlfuncs/func_delete_key.go @@ -30,7 +30,7 @@ func createDeleteKeyFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments } func deleteKey[K any](target ottl.PMapGetter[K], key string) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_delete_key_test.go b/pkg/ottl/ottlfuncs/func_delete_key_test.go index a7eee3b1fc48..c08fbfce644e 100644 --- a/pkg/ottl/ottlfuncs/func_delete_key_test.go +++ b/pkg/ottl/ottlfuncs/func_delete_key_test.go @@ -20,7 +20,7 @@ func Test_deleteKey(t *testing.T) { input.PutBool("test3", true) target := &ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Map) (any, error) { return tCtx, nil }, } @@ -80,29 +80,29 @@ func Test_deleteKey(t *testing.T) { func Test_deleteKey_bad_input(t *testing.T) { input := pcommon.NewValueStr("not a map") - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } key := "anything" - exprFunc := deleteKey[interface{}](target, key) + exprFunc := deleteKey[any](target, key) _, err := exprFunc(nil, input) assert.Error(t, err) } func Test_deleteKey_get_nil(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } key := "anything" - exprFunc := deleteKey[interface{}](target, key) + exprFunc := deleteKey[any](target, key) _, err := exprFunc(nil, nil) assert.Error(t, err) } diff --git a/pkg/ottl/ottlfuncs/func_delete_matching_keys.go b/pkg/ottl/ottlfuncs/func_delete_matching_keys.go index 18144d046889..1fb45df1e38b 100644 --- a/pkg/ottl/ottlfuncs/func_delete_matching_keys.go +++ b/pkg/ottl/ottlfuncs/func_delete_matching_keys.go @@ -37,7 +37,7 @@ func deleteMatchingKeys[K any](target ottl.PMapGetter[K], pattern string) (ottl. if err != nil { return nil, fmt.Errorf("the regex pattern supplied to delete_matching_keys is not a valid pattern: %w", err) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_delete_matching_keys_test.go b/pkg/ottl/ottlfuncs/func_delete_matching_keys_test.go index 63fe52721045..fae9cbfcf525 100644 --- a/pkg/ottl/ottlfuncs/func_delete_matching_keys_test.go +++ b/pkg/ottl/ottlfuncs/func_delete_matching_keys_test.go @@ -21,7 +21,7 @@ func Test_deleteMatchingKeys(t *testing.T) { input.PutBool("test3", true) target := &ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Map) (any, error) { return tCtx, nil }, } @@ -80,13 +80,13 @@ func Test_deleteMatchingKeys(t *testing.T) { func Test_deleteMatchingKeys_bad_input(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - exprFunc, err := deleteMatchingKeys[interface{}](target, "anything") + exprFunc, err := deleteMatchingKeys[any](target, "anything") assert.NoError(t, err) _, err = exprFunc(nil, input) @@ -94,28 +94,28 @@ func Test_deleteMatchingKeys_bad_input(t *testing.T) { } func Test_deleteMatchingKeys_get_nil(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - exprFunc, err := deleteMatchingKeys[interface{}](target, "anything") + exprFunc, err := deleteMatchingKeys[any](target, "anything") assert.NoError(t, err) _, err = exprFunc(nil, nil) assert.Error(t, err) } func Test_deleteMatchingKeys_invalid_pattern(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { t.Errorf("nothing should be received in this scenario") return nil, nil }, } invalidRegexPattern := "*" - _, err := deleteMatchingKeys[interface{}](target, invalidRegexPattern) + _, err := deleteMatchingKeys[any](target, invalidRegexPattern) require.Error(t, err) assert.ErrorContains(t, err, "error parsing regexp:") } diff --git a/pkg/ottl/ottlfuncs/func_double.go b/pkg/ottl/ottlfuncs/func_double.go index c454a6363e5d..9453d2b52b24 100644 --- a/pkg/ottl/ottlfuncs/func_double.go +++ b/pkg/ottl/ottlfuncs/func_double.go @@ -29,7 +29,7 @@ func createDoubleFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) ( } func doubleFunc[K any](target ottl.FloatLikeGetter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { value, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_double_test.go b/pkg/ottl/ottlfuncs/func_double_test.go index 0e81df0e6681..6a9ebda2894a 100644 --- a/pkg/ottl/ottlfuncs/func_double_test.go +++ b/pkg/ottl/ottlfuncs/func_double_test.go @@ -15,8 +15,8 @@ import ( func Test_Double(t *testing.T) { tests := []struct { name string - value interface{} - expected interface{} + value any + expected any err bool }{ { @@ -75,9 +75,9 @@ func Test_Double(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - exprFunc := doubleFunc[interface{}](&ottl.StandardFloatLikeGetter[interface{}]{ + exprFunc := doubleFunc[any](&ottl.StandardFloatLikeGetter[any]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + Getter: func(context.Context, any) (any, error) { return test.value, nil }, }) diff --git a/pkg/ottl/ottlfuncs/func_duration.go b/pkg/ottl/ottlfuncs/func_duration.go index 395d1fed05be..e125ff2b90d3 100644 --- a/pkg/ottl/ottlfuncs/func_duration.go +++ b/pkg/ottl/ottlfuncs/func_duration.go @@ -29,7 +29,7 @@ func createDurationFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) } func Duration[K any](duration ottl.StringGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { d, err := duration.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_duration_test.go b/pkg/ottl/ottlfuncs/func_duration_test.go index 878e289080fe..fecb19c1e9d6 100644 --- a/pkg/ottl/ottlfuncs/func_duration_test.go +++ b/pkg/ottl/ottlfuncs/func_duration_test.go @@ -17,29 +17,29 @@ import ( func Test_Duration(t *testing.T) { tests := []struct { name string - duration ottl.StringGetter[interface{}] + duration ottl.StringGetter[any] expected time.Duration }{ { name: "100 milliseconds", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "100ms", nil }, }, expected: time.Duration(100000000), }, { name: "234 microseconds", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "234us", nil }, }, expected: time.Duration(234000), }, { name: "777 nanoseconds", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "777ns", nil }, }, @@ -47,8 +47,8 @@ func Test_Duration(t *testing.T) { }, { name: "one second", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "1s", nil }, }, @@ -56,8 +56,8 @@ func Test_Duration(t *testing.T) { }, { name: "two hundred second", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "200s", nil }, }, @@ -65,8 +65,8 @@ func Test_Duration(t *testing.T) { }, { name: "three minutes", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "3m", nil }, }, @@ -74,8 +74,8 @@ func Test_Duration(t *testing.T) { }, { name: "45 minutes", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "45m", nil }, }, @@ -83,8 +83,8 @@ func Test_Duration(t *testing.T) { }, { name: "7 mins, 12 secs", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "7m12s", nil }, }, @@ -92,8 +92,8 @@ func Test_Duration(t *testing.T) { }, { name: "4 hours", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "4h", nil }, }, @@ -101,8 +101,8 @@ func Test_Duration(t *testing.T) { }, { name: "5 hours, 23 mins, 59 secs", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "5h23m59s", nil }, }, @@ -110,8 +110,8 @@ func Test_Duration(t *testing.T) { }, { name: "5 hours, 59 secs", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "5h59s", nil }, }, @@ -119,8 +119,8 @@ func Test_Duration(t *testing.T) { }, { name: "5 hours, 23 mins", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "5h23m", nil }, }, @@ -128,8 +128,8 @@ func Test_Duration(t *testing.T) { }, { name: "2 mins, 1 sec, 64 microsecs", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "2m1s64us", nil }, }, @@ -137,8 +137,8 @@ func Test_Duration(t *testing.T) { }, { name: "59 hours, 1 min, 78 millisecs", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "59h1m78ms", nil }, }, @@ -159,13 +159,13 @@ func Test_Duration(t *testing.T) { func Test_DurationError(t *testing.T) { tests := []struct { name string - duration ottl.StringGetter[interface{}] + duration ottl.StringGetter[any] expectedError string }{ { name: "empty duration", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -173,8 +173,8 @@ func Test_DurationError(t *testing.T) { }, { name: "empty duration", - duration: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "one second", nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_extract_patterns.go b/pkg/ottl/ottlfuncs/func_extract_patterns.go index 8eef411ebdfb..d03411c527a8 100644 --- a/pkg/ottl/ottlfuncs/func_extract_patterns.go +++ b/pkg/ottl/ottlfuncs/func_extract_patterns.go @@ -49,7 +49,7 @@ func extractPatterns[K any](target ottl.StringGetter[K], pattern string) (ottl.E return nil, fmt.Errorf("at least 1 named capture group must be supplied in the given regex") } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_extract_patterns_test.go b/pkg/ottl/ottlfuncs/func_extract_patterns_test.go index d051eb1a8476..ac2b5280e1ee 100644 --- a/pkg/ottl/ottlfuncs/func_extract_patterns_test.go +++ b/pkg/ottl/ottlfuncs/func_extract_patterns_test.go @@ -16,7 +16,7 @@ import ( func Test_extractPatterns(t *testing.T) { target := &ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `a=b c=d`, nil }, } @@ -76,7 +76,7 @@ func Test_extractPatterns_validation(t *testing.T) { { name: "bad regex", target: &ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "foobar", nil }, }, @@ -85,7 +85,7 @@ func Test_extractPatterns_validation(t *testing.T) { { name: "no named capture group", target: &ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return "foobar", nil }, }, @@ -110,7 +110,7 @@ func Test_extractPatterns_bad_input(t *testing.T) { { name: "target is non-string", target: &ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return 123, nil }, }, @@ -119,7 +119,7 @@ func Test_extractPatterns_bad_input(t *testing.T) { { name: "target is nil", target: &ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_fnv.go b/pkg/ottl/ottlfuncs/func_fnv.go index 8da56e599748..5df53a4737e1 100644 --- a/pkg/ottl/ottlfuncs/func_fnv.go +++ b/pkg/ottl/ottlfuncs/func_fnv.go @@ -31,7 +31,7 @@ func createFnvFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ott func FNVHashString[K any](target ottl.StringGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_fnv_test.go b/pkg/ottl/ottlfuncs/func_fnv_test.go index 3a0e4f6f83c5..277699475a16 100644 --- a/pkg/ottl/ottlfuncs/func_fnv_test.go +++ b/pkg/ottl/ottlfuncs/func_fnv_test.go @@ -15,8 +15,8 @@ import ( func Test_FNV(t *testing.T) { tests := []struct { name string - value interface{} - expected interface{} + value any + expected any err bool }{ { @@ -32,8 +32,8 @@ func Test_FNV(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc, err := FNVHashString[interface{}](&ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc, err := FNVHashString[any](&ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) @@ -52,7 +52,7 @@ func Test_FNV(t *testing.T) { func Test_FNVError(t *testing.T) { tests := []struct { name string - value interface{} + value any err bool expectedError string }{ @@ -69,8 +69,8 @@ func Test_FNVError(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc, err := FNVHashString[interface{}](&ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc, err := FNVHashString[any](&ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) diff --git a/pkg/ottl/ottlfuncs/func_hours.go b/pkg/ottl/ottlfuncs/func_hours.go index c4b465503996..66ab2dbcad1a 100644 --- a/pkg/ottl/ottlfuncs/func_hours.go +++ b/pkg/ottl/ottlfuncs/func_hours.go @@ -28,7 +28,7 @@ func createHoursFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (o } func Hours[K any](duration ottl.DurationGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { d, err := duration.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_hours_test.go b/pkg/ottl/ottlfuncs/func_hours_test.go index e8fe9af871ac..dd899fbe0084 100644 --- a/pkg/ottl/ottlfuncs/func_hours_test.go +++ b/pkg/ottl/ottlfuncs/func_hours_test.go @@ -16,13 +16,13 @@ import ( func Test_Hours(t *testing.T) { tests := []struct { name string - duration ottl.DurationGetter[interface{}] + duration ottl.DurationGetter[any] expected float64 }{ { name: "100 hours", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100h") }, }, @@ -30,8 +30,8 @@ func Test_Hours(t *testing.T) { }, { name: "1 min", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100m") }, }, @@ -39,8 +39,8 @@ func Test_Hours(t *testing.T) { }, { name: "234 milliseconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("234ms") }, }, @@ -48,8 +48,8 @@ func Test_Hours(t *testing.T) { }, { name: "1 hour 40 mins 3 seconds 30 milliseconds 100 microseconds 1 nanosecond", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("1h40m3s30ms100us1ns") }, }, diff --git a/pkg/ottl/ottlfuncs/func_int.go b/pkg/ottl/ottlfuncs/func_int.go index 94c7c1356394..db021fb82fab 100644 --- a/pkg/ottl/ottlfuncs/func_int.go +++ b/pkg/ottl/ottlfuncs/func_int.go @@ -29,7 +29,7 @@ func createIntFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ott } func intFunc[K any](target ottl.IntLikeGetter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { value, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_int_test.go b/pkg/ottl/ottlfuncs/func_int_test.go index 163f57bd2fb1..fbb18405c16c 100644 --- a/pkg/ottl/ottlfuncs/func_int_test.go +++ b/pkg/ottl/ottlfuncs/func_int_test.go @@ -15,8 +15,8 @@ import ( func Test_Int(t *testing.T) { tests := []struct { name string - value interface{} - expected interface{} + value any + expected any err bool }{ { @@ -73,8 +73,8 @@ func Test_Int(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc := intFunc[interface{}](&ottl.StandardIntLikeGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc := intFunc[any](&ottl.StandardIntLikeGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) diff --git a/pkg/ottl/ottlfuncs/func_is_map.go b/pkg/ottl/ottlfuncs/func_is_map.go index 25dfb8383994..3e36056b748e 100644 --- a/pkg/ottl/ottlfuncs/func_is_map.go +++ b/pkg/ottl/ottlfuncs/func_is_map.go @@ -30,7 +30,7 @@ func createIsMapFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (o // nolint:errorlint func isMap[K any](target ottl.PMapGetter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { _, err := target.Get(ctx, tCtx) // Use type assertion because we don't want to check wrapped errors switch err.(type) { diff --git a/pkg/ottl/ottlfuncs/func_is_map_test.go b/pkg/ottl/ottlfuncs/func_is_map_test.go index 7c2deb61bed6..65936196504e 100644 --- a/pkg/ottl/ottlfuncs/func_is_map_test.go +++ b/pkg/ottl/ottlfuncs/func_is_map_test.go @@ -16,7 +16,7 @@ import ( func Test_IsMap(t *testing.T) { tests := []struct { name string - value interface{} + value any expected bool }{ { @@ -48,7 +48,7 @@ func Test_IsMap(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exprFunc := isMap[any](&ottl.StandardPMapGetter[any]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) @@ -62,7 +62,7 @@ func Test_IsMap(t *testing.T) { // nolint:errorlint func Test_IsMap_Error(t *testing.T) { exprFunc := isMap[any](&ottl.StandardPMapGetter[any]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + Getter: func(context.Context, any) (any, error) { return nil, ottl.TypeError("") }, }) diff --git a/pkg/ottl/ottlfuncs/func_is_match.go b/pkg/ottl/ottlfuncs/func_is_match.go index b9f09c11cf20..4b7d1b1c771b 100644 --- a/pkg/ottl/ottlfuncs/func_is_match.go +++ b/pkg/ottl/ottlfuncs/func_is_match.go @@ -35,7 +35,7 @@ func isMatch[K any](target ottl.StringLikeGetter[K], pattern string) (ottl.ExprF if err != nil { return nil, fmt.Errorf("the pattern supplied to IsMatch is not a valid regexp pattern: %w", err) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_is_match_test.go b/pkg/ottl/ottlfuncs/func_is_match_test.go index 07e8f4013628..9ad128bc8d04 100644 --- a/pkg/ottl/ottlfuncs/func_is_match_test.go +++ b/pkg/ottl/ottlfuncs/func_is_match_test.go @@ -17,14 +17,14 @@ import ( func Test_isMatch(t *testing.T) { tests := []struct { name string - target ottl.StringLikeGetter[interface{}] + target ottl.StringLikeGetter[any] pattern string expected bool }{ { name: "replace match true", - target: &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "hello world", nil }, }, @@ -33,8 +33,8 @@ func Test_isMatch(t *testing.T) { }, { name: "replace match false", - target: &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "goodbye world", nil }, }, @@ -43,8 +43,8 @@ func Test_isMatch(t *testing.T) { }, { name: "replace match complex", - target: &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "-12.001", nil }, }, @@ -53,8 +53,8 @@ func Test_isMatch(t *testing.T) { }, { name: "target bool", - target: &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return true, nil }, }, @@ -63,8 +63,8 @@ func Test_isMatch(t *testing.T) { }, { name: "target int", - target: &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return int64(1), nil }, }, @@ -73,8 +73,8 @@ func Test_isMatch(t *testing.T) { }, { name: "target float", - target: &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1.1, nil }, }, @@ -83,8 +83,8 @@ func Test_isMatch(t *testing.T) { }, { name: "target pcommon.Value", - target: &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { v := pcommon.NewValueEmpty() v.SetStr("test") return v, nil @@ -95,8 +95,8 @@ func Test_isMatch(t *testing.T) { }, { name: "nil target", - target: &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, @@ -116,22 +116,22 @@ func Test_isMatch(t *testing.T) { } func Test_isMatch_validation(t *testing.T) { - target := &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "anything", nil }, } - _, err := isMatch[interface{}](target, "\\K") + _, err := isMatch[any](target, "\\K") require.Error(t, err) } func Test_isMatch_error(t *testing.T) { - target := &ottl.StandardStringLikeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardStringLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return make(chan int), nil }, } - exprFunc, err := isMatch[interface{}](target, "test") + exprFunc, err := isMatch[any](target, "test") assert.NoError(t, err) _, err = exprFunc(context.Background(), nil) require.Error(t, err) diff --git a/pkg/ottl/ottlfuncs/func_is_string.go b/pkg/ottl/ottlfuncs/func_is_string.go index 29d2a1843c93..d2e5c00650cf 100644 --- a/pkg/ottl/ottlfuncs/func_is_string.go +++ b/pkg/ottl/ottlfuncs/func_is_string.go @@ -30,7 +30,7 @@ func createIsStringFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) // nolint:errorlint func isString[K any](target ottl.StringGetter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { _, err := target.Get(ctx, tCtx) // Use type assertion because we don't want to check wrapped errors switch err.(type) { diff --git a/pkg/ottl/ottlfuncs/func_is_string_test.go b/pkg/ottl/ottlfuncs/func_is_string_test.go index 912837e355b7..5f91b7475ed4 100644 --- a/pkg/ottl/ottlfuncs/func_is_string_test.go +++ b/pkg/ottl/ottlfuncs/func_is_string_test.go @@ -16,7 +16,7 @@ import ( func Test_IsString(t *testing.T) { tests := []struct { name string - value interface{} + value any expected bool }{ { @@ -48,7 +48,7 @@ func Test_IsString(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exprFunc := isString[any](&ottl.StandardStringGetter[any]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) @@ -62,7 +62,7 @@ func Test_IsString(t *testing.T) { // nolint:errorlint func Test_IsString_Error(t *testing.T) { exprFunc := isString[any](&ottl.StandardStringGetter[any]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + Getter: func(context.Context, any) (any, error) { return nil, ottl.TypeError("") }, }) diff --git a/pkg/ottl/ottlfuncs/func_keep_keys.go b/pkg/ottl/ottlfuncs/func_keep_keys.go index 59b58ead88ea..6cae0c4c3795 100644 --- a/pkg/ottl/ottlfuncs/func_keep_keys.go +++ b/pkg/ottl/ottlfuncs/func_keep_keys.go @@ -37,7 +37,7 @@ func keepKeys[K any](target ottl.PMapGetter[K], keys []string) ottl.ExprFunc[K] keySet[key] = struct{}{} } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_keep_keys_test.go b/pkg/ottl/ottlfuncs/func_keep_keys_test.go index 4cae89fa4871..49b4648219c6 100644 --- a/pkg/ottl/ottlfuncs/func_keep_keys_test.go +++ b/pkg/ottl/ottlfuncs/func_keep_keys_test.go @@ -20,7 +20,7 @@ func Test_keepKeys(t *testing.T) { input.PutBool("test3", true) target := &ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Map) (any, error) { return tCtx, nil }, } @@ -81,30 +81,30 @@ func Test_keepKeys(t *testing.T) { func Test_keepKeys_bad_input(t *testing.T) { input := pcommon.NewValueStr("not a map") - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } keys := []string{"anything"} - exprFunc := keepKeys[interface{}](target, keys) + exprFunc := keepKeys[any](target, keys) _, err := exprFunc(nil, input) assert.Error(t, err) } func Test_keepKeys_get_nil(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } keys := []string{"anything"} - exprFunc := keepKeys[interface{}](target, keys) + exprFunc := keepKeys[any](target, keys) _, err := exprFunc(nil, nil) assert.Error(t, err) } diff --git a/pkg/ottl/ottlfuncs/func_len.go b/pkg/ottl/ottlfuncs/func_len.go index 9a566b05562c..35a8aaf2214d 100644 --- a/pkg/ottl/ottlfuncs/func_len.go +++ b/pkg/ottl/ottlfuncs/func_len.go @@ -40,7 +40,7 @@ func createLenFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ott // nolint:exhaustive func computeLen[K any](target ottl.Getter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_len_test.go b/pkg/ottl/ottlfuncs/func_len_test.go index 7595c12a9ff1..c72243648c7b 100644 --- a/pkg/ottl/ottlfuncs/func_len_test.go +++ b/pkg/ottl/ottlfuncs/func_len_test.go @@ -146,7 +146,7 @@ func Test_Len(t *testing.T) { tests := []struct { name string - value interface{} + value any expected int64 }{ { @@ -284,7 +284,7 @@ func Test_Len(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exprFunc := computeLen[any](&ottl.StandardGetSetter[any]{ - Getter: func(context context.Context, tCtx any) (interface{}, error) { + Getter: func(context context.Context, tCtx any) (any, error) { return tt.value, nil }, }) @@ -306,7 +306,7 @@ func dummyMap(size int) map[string]any { // nolint:errorlint func Test_Len_Error(t *testing.T) { exprFunc := computeLen[any](&ottl.StandardGetSetter[any]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + Getter: func(context.Context, any) (any, error) { return 24, nil }, }) diff --git a/pkg/ottl/ottlfuncs/func_limit.go b/pkg/ottl/ottlfuncs/func_limit.go index 1fec372fa174..81c3a4a7f4bf 100644 --- a/pkg/ottl/ottlfuncs/func_limit.go +++ b/pkg/ottl/ottlfuncs/func_limit.go @@ -47,7 +47,7 @@ func limit[K any](target ottl.PMapGetter[K], limit int64, priorityKeys []string) keep[key] = struct{}{} } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_limit_test.go b/pkg/ottl/ottlfuncs/func_limit_test.go index 885a894f7632..c2818c5ff219 100644 --- a/pkg/ottl/ottlfuncs/func_limit_test.go +++ b/pkg/ottl/ottlfuncs/func_limit_test.go @@ -20,7 +20,7 @@ func Test_limit(t *testing.T) { input.PutBool("test3", true) target := &ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Map) (any, error) { return tCtx, nil }, } @@ -131,18 +131,18 @@ func Test_limit(t *testing.T) { func Test_limit_validation(t *testing.T) { tests := []struct { name string - target ottl.PMapGetter[interface{}] + target ottl.PMapGetter[any] keep []string limit int64 }{ { name: "limit less than zero", - target: &ottl.StandardPMapGetter[interface{}]{}, + target: &ottl.StandardPMapGetter[any]{}, limit: int64(-1), }, { name: "limit less than # of keep attrs", - target: &ottl.StandardPMapGetter[interface{}]{}, + target: &ottl.StandardPMapGetter[any]{}, keep: []string{"test", "test"}, limit: int64(1), }, @@ -157,26 +157,26 @@ func Test_limit_validation(t *testing.T) { func Test_limit_bad_input(t *testing.T) { input := pcommon.NewValueStr("not a map") - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - exprFunc, err := limit[interface{}](target, 1, []string{}) + exprFunc, err := limit[any](target, 1, []string{}) assert.NoError(t, err) _, err = exprFunc(nil, input) assert.Error(t, err) } func Test_limit_get_nil(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - exprFunc, err := limit[interface{}](target, 1, []string{}) + exprFunc, err := limit[any](target, 1, []string{}) assert.NoError(t, err) _, err = exprFunc(nil, nil) assert.Error(t, err) diff --git a/pkg/ottl/ottlfuncs/func_log.go b/pkg/ottl/ottlfuncs/func_log.go index 8e6111ad8fb8..2c6547c670b9 100644 --- a/pkg/ottl/ottlfuncs/func_log.go +++ b/pkg/ottl/ottlfuncs/func_log.go @@ -30,7 +30,7 @@ func createLogFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ott } func logFunc[K any](target ottl.FloatLikeGetter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { value, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_log_test.go b/pkg/ottl/ottlfuncs/func_log_test.go index 5701084ce82d..1a7442ca08fa 100644 --- a/pkg/ottl/ottlfuncs/func_log_test.go +++ b/pkg/ottl/ottlfuncs/func_log_test.go @@ -16,8 +16,8 @@ import ( func Test_Log(t *testing.T) { noErrorTests := []struct { name string - value interface{} - expected interface{} + value any + expected any }{ { name: "string", @@ -47,8 +47,8 @@ func Test_Log(t *testing.T) { } for _, tt := range noErrorTests { t.Run(tt.name, func(t *testing.T) { - exprFunc := logFunc[interface{}](&ottl.StandardFloatLikeGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc := logFunc[any](&ottl.StandardFloatLikeGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) @@ -59,7 +59,7 @@ func Test_Log(t *testing.T) { } errorTests := []struct { name string - value interface{} + value any errorStr string }{ { @@ -95,8 +95,8 @@ func Test_Log(t *testing.T) { } for _, tt := range errorTests { t.Run(tt.name, func(t *testing.T) { - exprFunc := logFunc[interface{}](&ottl.StandardFloatLikeGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc := logFunc[any](&ottl.StandardFloatLikeGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) diff --git a/pkg/ottl/ottlfuncs/func_merge_maps.go b/pkg/ottl/ottlfuncs/func_merge_maps.go index 5560def71010..ed74e7ee9ef7 100644 --- a/pkg/ottl/ottlfuncs/func_merge_maps.go +++ b/pkg/ottl/ottlfuncs/func_merge_maps.go @@ -49,7 +49,7 @@ func mergeMaps[K any](target ottl.PMapGetter[K], source ottl.PMapGetter[K], stra return nil, fmt.Errorf("invalid value for strategy, %v, must be 'insert', 'update' or 'upsert'", strategy) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { targetMap, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_merge_maps_test.go b/pkg/ottl/ottlfuncs/func_merge_maps_test.go index 8c071bb2c723..fdcd8475a76c 100644 --- a/pkg/ottl/ottlfuncs/func_merge_maps_test.go +++ b/pkg/ottl/ottlfuncs/func_merge_maps_test.go @@ -19,7 +19,7 @@ func Test_MergeMaps(t *testing.T) { input.PutStr("attr1", "value1") targetGetter := &ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Map) (any, error) { return tCtx, nil }, } @@ -33,7 +33,7 @@ func Test_MergeMaps(t *testing.T) { { name: "Upsert no conflicting keys", source: ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, _ pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, _ pcommon.Map) (any, error) { m := pcommon.NewMap() m.PutStr("attr2", "value2") return m, nil @@ -48,7 +48,7 @@ func Test_MergeMaps(t *testing.T) { { name: "Upsert conflicting key", source: ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, _ pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, _ pcommon.Map) (any, error) { m := pcommon.NewMap() m.PutStr("attr1", "value3") m.PutStr("attr2", "value2") @@ -64,7 +64,7 @@ func Test_MergeMaps(t *testing.T) { { name: "Insert no conflicting keys", source: ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, _ pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, _ pcommon.Map) (any, error) { m := pcommon.NewMap() m.PutStr("attr2", "value2") return m, nil @@ -79,7 +79,7 @@ func Test_MergeMaps(t *testing.T) { { name: "Insert conflicting key", source: ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, _ pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, _ pcommon.Map) (any, error) { m := pcommon.NewMap() m.PutStr("attr1", "value3") m.PutStr("attr2", "value2") @@ -95,7 +95,7 @@ func Test_MergeMaps(t *testing.T) { { name: "Update no conflicting keys", source: ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, _ pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, _ pcommon.Map) (any, error) { m := pcommon.NewMap() m.PutStr("attr2", "value2") return m, nil @@ -109,7 +109,7 @@ func Test_MergeMaps(t *testing.T) { { name: "Update conflicting key", source: ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, _ pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, _ pcommon.Map) (any, error) { m := pcommon.NewMap() m.PutStr("attr1", "value3") return m, nil @@ -142,36 +142,36 @@ func Test_MergeMaps(t *testing.T) { } func Test_MergeMaps_bad_target(t *testing.T) { - input := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + input := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, } - exprFunc, err := mergeMaps[interface{}](target, input, "insert") + exprFunc, err := mergeMaps[any](target, input, "insert") assert.NoError(t, err) _, err = exprFunc(nil, input) assert.Error(t, err) } func Test_MergeMaps_bad_input(t *testing.T) { - input := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + input := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, } - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - exprFunc, err := mergeMaps[interface{}](target, input, "insert") + exprFunc, err := mergeMaps[any](target, input, "insert") assert.NoError(t, err) _, err = exprFunc(nil, input) assert.Error(t, err) diff --git a/pkg/ottl/ottlfuncs/func_microseconds.go b/pkg/ottl/ottlfuncs/func_microseconds.go index 9c0bdc94c096..0855efaca055 100644 --- a/pkg/ottl/ottlfuncs/func_microseconds.go +++ b/pkg/ottl/ottlfuncs/func_microseconds.go @@ -28,7 +28,7 @@ func createMicrosecondsFunction[K any](_ ottl.FunctionContext, oArgs ottl.Argume } func Microseconds[K any](duration ottl.DurationGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { d, err := duration.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_microseconds_test.go b/pkg/ottl/ottlfuncs/func_microseconds_test.go index 7e3c9b8c66be..d3e4faf99899 100644 --- a/pkg/ottl/ottlfuncs/func_microseconds_test.go +++ b/pkg/ottl/ottlfuncs/func_microseconds_test.go @@ -16,13 +16,13 @@ import ( func Test_Microseconds(t *testing.T) { tests := []struct { name string - duration ottl.DurationGetter[interface{}] + duration ottl.DurationGetter[any] expected int64 }{ { name: "100 microseconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100us") }, }, @@ -30,8 +30,8 @@ func Test_Microseconds(t *testing.T) { }, { name: "1000 hour", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100h") }, }, @@ -39,8 +39,8 @@ func Test_Microseconds(t *testing.T) { }, { name: "50 mins", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("50m") }, }, @@ -48,8 +48,8 @@ func Test_Microseconds(t *testing.T) { }, { name: "1 hour 40 mins 3 seconds 30 milliseconds 100 microseconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("1h40m3s30ms100us") }, }, diff --git a/pkg/ottl/ottlfuncs/func_milliseconds.go b/pkg/ottl/ottlfuncs/func_milliseconds.go index cd59ffb54c7b..da787e0e157e 100644 --- a/pkg/ottl/ottlfuncs/func_milliseconds.go +++ b/pkg/ottl/ottlfuncs/func_milliseconds.go @@ -28,7 +28,7 @@ func createMillisecondsFunction[K any](_ ottl.FunctionContext, oArgs ottl.Argume } func Milliseconds[K any](duration ottl.DurationGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { d, err := duration.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_milliseconds_test.go b/pkg/ottl/ottlfuncs/func_milliseconds_test.go index 4f8f95e57cc0..bdbb9ad1ccab 100644 --- a/pkg/ottl/ottlfuncs/func_milliseconds_test.go +++ b/pkg/ottl/ottlfuncs/func_milliseconds_test.go @@ -16,13 +16,13 @@ import ( func Test_Milliseconds(t *testing.T) { tests := []struct { name string - duration ottl.DurationGetter[interface{}] + duration ottl.DurationGetter[any] expected int64 }{ { name: "100 Milliseconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100ms") }, }, @@ -30,8 +30,8 @@ func Test_Milliseconds(t *testing.T) { }, { name: "1000 hour", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100h") }, }, @@ -39,8 +39,8 @@ func Test_Milliseconds(t *testing.T) { }, { name: "47 mins", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("47m") }, }, @@ -48,8 +48,8 @@ func Test_Milliseconds(t *testing.T) { }, { name: "1 hour 40 mins 3 seconds 30 milliseconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("1h40m3s30ms") }, }, diff --git a/pkg/ottl/ottlfuncs/func_minutes.go b/pkg/ottl/ottlfuncs/func_minutes.go index 366922d4b722..5048befc5725 100644 --- a/pkg/ottl/ottlfuncs/func_minutes.go +++ b/pkg/ottl/ottlfuncs/func_minutes.go @@ -28,7 +28,7 @@ func createMinutesFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) } func Minutes[K any](duration ottl.DurationGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { d, err := duration.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_minutes_test.go b/pkg/ottl/ottlfuncs/func_minutes_test.go index 687078007335..a4367c0179e7 100644 --- a/pkg/ottl/ottlfuncs/func_minutes_test.go +++ b/pkg/ottl/ottlfuncs/func_minutes_test.go @@ -16,13 +16,13 @@ import ( func Test_Minutes(t *testing.T) { tests := []struct { name string - duration ottl.DurationGetter[interface{}] + duration ottl.DurationGetter[any] expected float64 }{ { name: "100 minutes", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100m") }, }, @@ -30,8 +30,8 @@ func Test_Minutes(t *testing.T) { }, { name: "1 hour", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("1h") }, }, @@ -39,8 +39,8 @@ func Test_Minutes(t *testing.T) { }, { name: "234 milliseconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("234ms") }, }, @@ -48,8 +48,8 @@ func Test_Minutes(t *testing.T) { }, { name: "1 hour 40 mins 3 seconds 30 milliseconds 100 microseconds 1 nanosecond", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("1h40m3s30ms100us1ns") }, }, diff --git a/pkg/ottl/ottlfuncs/func_nanoseconds.go b/pkg/ottl/ottlfuncs/func_nanoseconds.go index 95700900501c..2bb2cd7d1dd4 100644 --- a/pkg/ottl/ottlfuncs/func_nanoseconds.go +++ b/pkg/ottl/ottlfuncs/func_nanoseconds.go @@ -28,7 +28,7 @@ func createNanosecondsFunction[K any](_ ottl.FunctionContext, oArgs ottl.Argumen } func Nanoseconds[K any](duration ottl.DurationGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { d, err := duration.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_nanoseconds_test.go b/pkg/ottl/ottlfuncs/func_nanoseconds_test.go index 395743c84b10..67e297488455 100644 --- a/pkg/ottl/ottlfuncs/func_nanoseconds_test.go +++ b/pkg/ottl/ottlfuncs/func_nanoseconds_test.go @@ -16,13 +16,13 @@ import ( func Test_Nanoseconds(t *testing.T) { tests := []struct { name string - duration ottl.DurationGetter[interface{}] + duration ottl.DurationGetter[any] expected int64 }{ { name: "100 nanoseconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100ns") }, }, @@ -30,8 +30,8 @@ func Test_Nanoseconds(t *testing.T) { }, { name: "1 hour", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100h") }, }, @@ -39,8 +39,8 @@ func Test_Nanoseconds(t *testing.T) { }, { name: "23 mins", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("23m") }, }, @@ -48,8 +48,8 @@ func Test_Nanoseconds(t *testing.T) { }, { name: "1 hour 40 mins 3 seconds 30 milliseconds 100 microseconds 1 nanosecond", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("1h40m3s30ms100us1ns") }, }, diff --git a/pkg/ottl/ottlfuncs/func_now.go b/pkg/ottl/ottlfuncs/func_now.go index 4829d57f767a..51815d3f6864 100644 --- a/pkg/ottl/ottlfuncs/func_now.go +++ b/pkg/ottl/ottlfuncs/func_now.go @@ -11,7 +11,7 @@ import ( ) func now[K any]() (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { return time.Now(), nil }, nil } diff --git a/pkg/ottl/ottlfuncs/func_now_test.go b/pkg/ottl/ottlfuncs/func_now_test.go index a96751201654..fc742ab72018 100644 --- a/pkg/ottl/ottlfuncs/func_now_test.go +++ b/pkg/ottl/ottlfuncs/func_now_test.go @@ -11,7 +11,7 @@ import ( ) func Test_Now(t *testing.T) { - exprFunc, err := now[interface{}]() + exprFunc, err := now[any]() assert.NoError(t, err) value, err := exprFunc(nil, nil) diff --git a/pkg/ottl/ottlfuncs/func_parse_json.go b/pkg/ottl/ottlfuncs/func_parse_json.go index 7ca06f83034b..8cca75f71601 100644 --- a/pkg/ottl/ottlfuncs/func_parse_json.go +++ b/pkg/ottl/ottlfuncs/func_parse_json.go @@ -41,12 +41,12 @@ func createParseJSONFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments // JSON arrays -> pdata.SliceValue // JSON objects -> map[string]any func parseJSON[K any](target ottl.StringGetter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { targetVal, err := target.Get(ctx, tCtx) if err != nil { return nil, err } - var parsedValue map[string]interface{} + var parsedValue map[string]any err = jsoniter.UnmarshalFromString(targetVal, &parsedValue) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_parse_json_test.go b/pkg/ottl/ottlfuncs/func_parse_json_test.go index 8feade85ef8f..d8421901bd5e 100644 --- a/pkg/ottl/ottlfuncs/func_parse_json_test.go +++ b/pkg/ottl/ottlfuncs/func_parse_json_test.go @@ -23,7 +23,7 @@ func Test_ParseJSON(t *testing.T) { { name: "handle string", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"test":"string value"}`, nil }, }, @@ -34,7 +34,7 @@ func Test_ParseJSON(t *testing.T) { { name: "handle bool", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"test":true}`, nil }, }, @@ -45,7 +45,7 @@ func Test_ParseJSON(t *testing.T) { { name: "handle int", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"test":1}`, nil }, }, @@ -56,7 +56,7 @@ func Test_ParseJSON(t *testing.T) { { name: "handle float", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"test":1.1}`, nil }, }, @@ -67,7 +67,7 @@ func Test_ParseJSON(t *testing.T) { { name: "handle nil", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"test":null}`, nil }, }, @@ -78,7 +78,7 @@ func Test_ParseJSON(t *testing.T) { { name: "handle array", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"test":["string","value"]}`, nil }, }, @@ -91,7 +91,7 @@ func Test_ParseJSON(t *testing.T) { { name: "handle nested object", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"test":{"nested":"true"}}`, nil }, }, @@ -103,7 +103,7 @@ func Test_ParseJSON(t *testing.T) { { name: "updates existing", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"existing":"pass"}`, nil }, }, @@ -114,7 +114,7 @@ func Test_ParseJSON(t *testing.T) { { name: "complex", target: ottl.StandardStringGetter[any]{ - Getter: func(ctx context.Context, tCtx any) (interface{}, error) { + Getter: func(ctx context.Context, tCtx any) (any, error) { return `{"test1":{"nested":"true"},"test2":"string","test3":1,"test4":1.1,"test5":[[1], [2, 3],[]],"test6":null}`, nil }, }, @@ -159,12 +159,12 @@ func Test_ParseJSON(t *testing.T) { } func Test_ParseJSON_Error(t *testing.T) { - target := &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, } - exprFunc := parseJSON[interface{}](target) + exprFunc := parseJSON[any](target) _, err := exprFunc(context.Background(), nil) assert.Error(t, err) } diff --git a/pkg/ottl/ottlfuncs/func_replace_all_matches.go b/pkg/ottl/ottlfuncs/func_replace_all_matches.go index 8ea90b32fe0f..597cf878a12c 100644 --- a/pkg/ottl/ottlfuncs/func_replace_all_matches.go +++ b/pkg/ottl/ottlfuncs/func_replace_all_matches.go @@ -43,7 +43,7 @@ func replaceAllMatches[K any](target ottl.PMapGetter[K], pattern string, replace if err != nil { return nil, fmt.Errorf("the pattern supplied to replace_match is not a valid pattern: %w", err) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) var replacementVal string if err != nil { diff --git a/pkg/ottl/ottlfuncs/func_replace_all_matches_test.go b/pkg/ottl/ottlfuncs/func_replace_all_matches_test.go index 4529f701ebc3..88d1d7fe019e 100644 --- a/pkg/ottl/ottlfuncs/func_replace_all_matches_test.go +++ b/pkg/ottl/ottlfuncs/func_replace_all_matches_test.go @@ -30,7 +30,7 @@ func Test_replaceAllMatches(t *testing.T) { optionalArg := ottl.NewTestingOptional[ottl.FunctionGetter[pcommon.Map]](ottlValue) target := &ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Map) (any, error) { return tCtx, nil }, } @@ -48,7 +48,7 @@ func Test_replaceAllMatches(t *testing.T) { target: target, pattern: "hello*", replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "hello {universe}", nil }, }, @@ -64,7 +64,7 @@ func Test_replaceAllMatches(t *testing.T) { target: target, pattern: "hello*", replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "hello {universe}", nil }, }, @@ -80,7 +80,7 @@ func Test_replaceAllMatches(t *testing.T) { target: target, pattern: "nothing*", replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "nothing {matches}", nil }, }, @@ -114,19 +114,19 @@ func Test_replaceAllMatches(t *testing.T) { func Test_replaceAllMatches_bad_input(t *testing.T) { input := pcommon.NewValueStr("not a map") - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{replacement}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceAllMatches[interface{}](target, "*", replacement, function) + exprFunc, err := replaceAllMatches[any](target, "*", replacement, function) assert.NoError(t, err) _, err = exprFunc(nil, input) assert.Error(t, err) @@ -134,19 +134,19 @@ func Test_replaceAllMatches_bad_input(t *testing.T) { func Test_replaceAllMatches_bad_function_input(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return nil, nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceAllMatches[interface{}](target, "regexp", replacement, function) + exprFunc, err := replaceAllMatches[any](target, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -157,25 +157,25 @@ func Test_replaceAllMatches_bad_function_input(t *testing.T) { func Test_replaceAllMatches_bad_function_result(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{replacement}", nil }, } - ottlValue := ottl.StandardFunctionGetter[interface{}]{ + ottlValue := ottl.StandardFunctionGetter[any]{ FCtx: ottl.FunctionContext{ Set: componenttest.NewNopTelemetrySettings(), }, - Fact: StandardConverters[interface{}]()["IsString"], + Fact: StandardConverters[any]()["IsString"], } - function := ottl.NewTestingOptional[ottl.FunctionGetter[interface{}]](ottlValue) + function := ottl.NewTestingOptional[ottl.FunctionGetter[any]](ottlValue) - exprFunc, err := replaceAllMatches[interface{}](target, "regexp", replacement, function) + exprFunc, err := replaceAllMatches[any](target, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -184,19 +184,19 @@ func Test_replaceAllMatches_bad_function_result(t *testing.T) { } func Test_replaceAllMatches_get_nil(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{anything}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceAllMatches[interface{}](target, "*", replacement, function) + exprFunc, err := replaceAllMatches[any](target, "*", replacement, function) assert.NoError(t, err) _, err = exprFunc(nil, nil) assert.Error(t, err) diff --git a/pkg/ottl/ottlfuncs/func_replace_all_patterns.go b/pkg/ottl/ottlfuncs/func_replace_all_patterns.go index 47021b6bff01..2c7ee3ef3386 100644 --- a/pkg/ottl/ottlfuncs/func_replace_all_patterns.go +++ b/pkg/ottl/ottlfuncs/func_replace_all_patterns.go @@ -53,7 +53,7 @@ func replaceAllPatterns[K any](target ottl.PMapGetter[K], mode string, regexPatt return nil, fmt.Errorf("invalid mode %v, must be either 'key' or 'value'", mode) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) var replacementVal string if err != nil { diff --git a/pkg/ottl/ottlfuncs/func_replace_all_patterns_test.go b/pkg/ottl/ottlfuncs/func_replace_all_patterns_test.go index 29bb2b2669f0..c171b40e9cea 100644 --- a/pkg/ottl/ottlfuncs/func_replace_all_patterns_test.go +++ b/pkg/ottl/ottlfuncs/func_replace_all_patterns_test.go @@ -33,7 +33,7 @@ func Test_replaceAllPatterns(t *testing.T) { optionalArg := ottl.NewTestingOptional[ottl.FunctionGetter[pcommon.Map]](ottlValue) target := &ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Map) (any, error) { return tCtx, nil }, } @@ -53,7 +53,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeValue, pattern: "hello", replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "hello {universe}", nil }, }, @@ -73,7 +73,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeValue, pattern: "hello", replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "hello {universe}", nil }, }, @@ -93,7 +93,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeValue, pattern: "nothing", replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "nothing {matches}", nil }, }, @@ -113,7 +113,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeValue, pattern: `world[^\s]*(\s?)`, replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "**** ", nil }, }, @@ -133,7 +133,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeKey, pattern: "test2", replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "foo", nil }, }, @@ -154,7 +154,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeKey, pattern: "nothing", replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "nothing {matches}", nil }, }, @@ -175,7 +175,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeKey, pattern: `test`, replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "test.", nil }, }, @@ -196,7 +196,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeValue, pattern: `world(\d)`, replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "world-$1", nil }, }, @@ -217,7 +217,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeKey, pattern: `test(\d)`, replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "test-$1", nil }, }, @@ -237,7 +237,7 @@ func Test_replaceAllPatterns(t *testing.T) { mode: modeValue, pattern: `world(\d)`, replacement: ottl.StandardStringGetter[pcommon.Map]{ - Getter: func(context.Context, pcommon.Map) (interface{}, error) { + Getter: func(context.Context, pcommon.Map) (any, error) { return "$$world-$1", nil }, }, @@ -274,19 +274,19 @@ func Test_replaceAllPatterns(t *testing.T) { func Test_replaceAllPatterns_bad_input(t *testing.T) { input := pcommon.NewValueStr("not a map") - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{replacement}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceAllPatterns[interface{}](target, modeValue, "regexpattern", replacement, function) + exprFunc, err := replaceAllPatterns[any](target, modeValue, "regexpattern", replacement, function) assert.Nil(t, err) _, err = exprFunc(nil, input) @@ -295,19 +295,19 @@ func Test_replaceAllPatterns_bad_input(t *testing.T) { func Test_replaceAllPatterns_bad_function_input(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return nil, nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceAllPatterns[interface{}](target, modeValue, "regexp", replacement, function) + exprFunc, err := replaceAllPatterns[any](target, modeValue, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -318,25 +318,25 @@ func Test_replaceAllPatterns_bad_function_input(t *testing.T) { func Test_replaceAllPatterns_bad_function_result(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{anything}", nil }, } - ottlValue := ottl.StandardFunctionGetter[interface{}]{ + ottlValue := ottl.StandardFunctionGetter[any]{ FCtx: ottl.FunctionContext{ Set: componenttest.NewNopTelemetrySettings(), }, - Fact: StandardConverters[interface{}]()["IsString"], + Fact: StandardConverters[any]()["IsString"], } - function := ottl.NewTestingOptional[ottl.FunctionGetter[interface{}]](ottlValue) + function := ottl.NewTestingOptional[ottl.FunctionGetter[any]](ottlValue) - exprFunc, err := replaceAllPatterns[interface{}](target, modeValue, "regexp", replacement, function) + exprFunc, err := replaceAllPatterns[any](target, modeValue, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -345,19 +345,19 @@ func Test_replaceAllPatterns_bad_function_result(t *testing.T) { } func Test_replaceAllPatterns_get_nil(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{anything}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceAllPatterns[interface{}](target, modeValue, "regexp", replacement, function) + exprFunc, err := replaceAllPatterns[any](target, modeValue, "regexp", replacement, function) assert.NoError(t, err) _, err = exprFunc(nil, nil) @@ -365,42 +365,42 @@ func Test_replaceAllPatterns_get_nil(t *testing.T) { } func Test_replaceAllPatterns_invalid_pattern(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { t.Errorf("nothing should be received in this scenario") return nil, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{anything}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} invalidRegexPattern := "*" - exprFunc, err := replaceAllPatterns[interface{}](target, modeValue, invalidRegexPattern, replacement, function) + exprFunc, err := replaceAllPatterns[any](target, modeValue, invalidRegexPattern, replacement, function) require.Error(t, err) assert.ErrorContains(t, err, "error parsing regexp:") assert.Nil(t, exprFunc) } func Test_replaceAllPatterns_invalid_model(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { t.Errorf("nothing should be received in this scenario") return nil, nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{anything}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} invalidMode := "invalid" - exprFunc, err := replaceAllPatterns[interface{}](target, invalidMode, "regex", replacement, function) + exprFunc, err := replaceAllPatterns[any](target, invalidMode, "regex", replacement, function) assert.Nil(t, exprFunc) assert.Contains(t, err.Error(), "invalid mode") } diff --git a/pkg/ottl/ottlfuncs/func_replace_match.go b/pkg/ottl/ottlfuncs/func_replace_match.go index d56ef4b75edd..123320caa421 100644 --- a/pkg/ottl/ottlfuncs/func_replace_match.go +++ b/pkg/ottl/ottlfuncs/func_replace_match.go @@ -42,7 +42,7 @@ func replaceMatch[K any](target ottl.GetSetter[K], pattern string, replacement o if err != nil { return nil, fmt.Errorf("the pattern supplied to replace_match is not a valid pattern: %w", err) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) var replacementVal string if err != nil { diff --git a/pkg/ottl/ottlfuncs/func_replace_match_test.go b/pkg/ottl/ottlfuncs/func_replace_match_test.go index e3fe48cca750..5de8512f1c1e 100644 --- a/pkg/ottl/ottlfuncs/func_replace_match_test.go +++ b/pkg/ottl/ottlfuncs/func_replace_match_test.go @@ -25,10 +25,10 @@ func Test_replaceMatch(t *testing.T) { } optionalArg := ottl.NewTestingOptional[ottl.FunctionGetter[pcommon.Value]](ottlValue) target := &ottl.StandardGetSetter[pcommon.Value]{ - Getter: func(ctx context.Context, tCtx pcommon.Value) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Value) (any, error) { return tCtx.Str(), nil }, - Setter: func(ctx context.Context, tCtx pcommon.Value, val interface{}) error { + Setter: func(ctx context.Context, tCtx pcommon.Value, val any) error { tCtx.SetStr(val.(string)) return nil }, @@ -47,7 +47,7 @@ func Test_replaceMatch(t *testing.T) { target: target, pattern: "hello*", replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "hello {universe}", nil }, }, @@ -61,7 +61,7 @@ func Test_replaceMatch(t *testing.T) { target: target, pattern: "hello*", replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "hello {universe}", nil }, }, @@ -75,7 +75,7 @@ func Test_replaceMatch(t *testing.T) { target: target, pattern: "goodbye*", replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "goodbye {universe}", nil }, }, @@ -105,23 +105,23 @@ func Test_replaceMatch(t *testing.T) { func Test_replaceMatch_bad_input(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{replacement}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceMatch[interface{}](target, "*", replacement, function) + exprFunc, err := replaceMatch[any](target, "*", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -133,23 +133,23 @@ func Test_replaceMatch_bad_input(t *testing.T) { func Test_replaceMatch_bad_function_input(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return nil, nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceMatch[interface{}](target, "regexp", replacement, function) + exprFunc, err := replaceMatch[any](target, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -160,29 +160,29 @@ func Test_replaceMatch_bad_function_input(t *testing.T) { func Test_replaceMatch_bad_function_result(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return nil, nil }, } - ottlValue := ottl.StandardFunctionGetter[interface{}]{ + ottlValue := ottl.StandardFunctionGetter[any]{ FCtx: ottl.FunctionContext{ Set: componenttest.NewNopTelemetrySettings(), }, - Fact: StandardConverters[interface{}]()["IsString"], + Fact: StandardConverters[any]()["IsString"], } - function := ottl.NewTestingOptional[ottl.FunctionGetter[interface{}]](ottlValue) + function := ottl.NewTestingOptional[ottl.FunctionGetter[any]](ottlValue) - exprFunc, err := replaceMatch[interface{}](target, "regexp", replacement, function) + exprFunc, err := replaceMatch[any](target, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -192,23 +192,23 @@ func Test_replaceMatch_bad_function_result(t *testing.T) { } func Test_replaceMatch_get_nil(t *testing.T) { - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{anything}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replaceMatch[interface{}](target, "*", replacement, function) + exprFunc, err := replaceMatch[any](target, "*", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, nil) diff --git a/pkg/ottl/ottlfuncs/func_replace_pattern.go b/pkg/ottl/ottlfuncs/func_replace_pattern.go index b69ea098e2fa..aed32367ddc6 100644 --- a/pkg/ottl/ottlfuncs/func_replace_pattern.go +++ b/pkg/ottl/ottlfuncs/func_replace_pattern.go @@ -41,7 +41,7 @@ func replacePattern[K any](target ottl.GetSetter[K], regexPattern string, replac if err != nil { return nil, fmt.Errorf("the regex pattern supplied to replace_pattern is not a valid pattern: %w", err) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { originalVal, err := target.Get(ctx, tCtx) var replacementVal string if err != nil { diff --git a/pkg/ottl/ottlfuncs/func_replace_pattern_test.go b/pkg/ottl/ottlfuncs/func_replace_pattern_test.go index 87812b2684ac..66edf7d25177 100644 --- a/pkg/ottl/ottlfuncs/func_replace_pattern_test.go +++ b/pkg/ottl/ottlfuncs/func_replace_pattern_test.go @@ -25,10 +25,10 @@ func Test_replacePattern(t *testing.T) { } optionalArg := ottl.NewTestingOptional[ottl.FunctionGetter[pcommon.Value]](ottlValue) target := &ottl.StandardGetSetter[pcommon.Value]{ - Getter: func(ctx context.Context, tCtx pcommon.Value) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Value) (any, error) { return tCtx.Str(), nil }, - Setter: func(ctx context.Context, tCtx pcommon.Value, val interface{}) error { + Setter: func(ctx context.Context, tCtx pcommon.Value, val any) error { tCtx.SetStr(val.(string)) return nil }, @@ -47,7 +47,7 @@ func Test_replacePattern(t *testing.T) { target: target, pattern: `passwd\=[^\s]*(\s?)`, replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "passwd=*** ", nil }, }, @@ -61,7 +61,7 @@ func Test_replacePattern(t *testing.T) { target: target, pattern: `passwd\=[^\s]*(\s?)`, replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "passwd=*** ", nil }, }, @@ -75,7 +75,7 @@ func Test_replacePattern(t *testing.T) { target: target, pattern: `nomatch\=[^\s]*(\s?)`, replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "shouldnotbeinoutput", nil }, }, @@ -89,7 +89,7 @@ func Test_replacePattern(t *testing.T) { target: target, pattern: `key[^\s]*(\s?)`, replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "**** ", nil }, }, @@ -103,7 +103,7 @@ func Test_replacePattern(t *testing.T) { target: target, pattern: `(\w+)=(\w+)`, replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "$1:$2", nil }, }, @@ -117,7 +117,7 @@ func Test_replacePattern(t *testing.T) { target: target, pattern: `passwd\=[^\s]*(\s?)`, replacement: ottl.StandardStringGetter[pcommon.Value]{ - Getter: func(context.Context, pcommon.Value) (interface{}, error) { + Getter: func(context.Context, pcommon.Value) (any, error) { return "passwd=$$$$$$ ", nil }, }, @@ -147,23 +147,23 @@ func Test_replacePattern(t *testing.T) { func Test_replacePattern_bad_input(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{replacement}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replacePattern[interface{}](target, "regexp", replacement, function) + exprFunc, err := replacePattern[any](target, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -174,23 +174,23 @@ func Test_replacePattern_bad_input(t *testing.T) { func Test_replacePattern_bad_function_input(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return nil, nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replacePattern[interface{}](target, "regexp", replacement, function) + exprFunc, err := replacePattern[any](target, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -201,29 +201,29 @@ func Test_replacePattern_bad_function_input(t *testing.T) { func Test_replacePattern_bad_function_result(t *testing.T) { input := pcommon.NewValueInt(1) - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return nil, nil }, } - ottlValue := ottl.StandardFunctionGetter[interface{}]{ + ottlValue := ottl.StandardFunctionGetter[any]{ FCtx: ottl.FunctionContext{ Set: componenttest.NewNopTelemetrySettings(), }, - Fact: StandardConverters[interface{}]()["IsString"], + Fact: StandardConverters[any]()["IsString"], } - function := ottl.NewTestingOptional[ottl.FunctionGetter[interface{}]](ottlValue) + function := ottl.NewTestingOptional[ottl.FunctionGetter[any]](ottlValue) - exprFunc, err := replacePattern[interface{}](target, "regexp", replacement, function) + exprFunc, err := replacePattern[any](target, "regexp", replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, input) @@ -233,23 +233,23 @@ func Test_replacePattern_bad_function_result(t *testing.T) { } func Test_replacePattern_get_nil(t *testing.T) { - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{anything}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} - exprFunc, err := replacePattern[interface{}](target, `nomatch\=[^\s]*(\s?)`, replacement, function) + exprFunc, err := replacePattern[any](target, `nomatch\=[^\s]*(\s?)`, replacement, function) assert.NoError(t, err) result, err := exprFunc(nil, nil) @@ -258,25 +258,25 @@ func Test_replacePattern_get_nil(t *testing.T) { } func Test_replacePatterns_invalid_pattern(t *testing.T) { - target := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { t.Errorf("nothing should be received in this scenario") return nil, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - replacement := &ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + replacement := &ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return "{anything}", nil }, } - function := ottl.Optional[ottl.FunctionGetter[interface{}]]{} + function := ottl.Optional[ottl.FunctionGetter[any]]{} invalidRegexPattern := "*" - _, err := replacePattern[interface{}](target, invalidRegexPattern, replacement, function) + _, err := replacePattern[any](target, invalidRegexPattern, replacement, function) require.Error(t, err) assert.ErrorContains(t, err, "error parsing regexp:") } diff --git a/pkg/ottl/ottlfuncs/func_seconds.go b/pkg/ottl/ottlfuncs/func_seconds.go index da570ce1d5fe..7c7e57d62902 100644 --- a/pkg/ottl/ottlfuncs/func_seconds.go +++ b/pkg/ottl/ottlfuncs/func_seconds.go @@ -28,7 +28,7 @@ func createSecondsFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) } func Seconds[K any](duration ottl.DurationGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { d, err := duration.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_seconds_test.go b/pkg/ottl/ottlfuncs/func_seconds_test.go index c8d7f72ca1b4..5b218b8eb1a4 100644 --- a/pkg/ottl/ottlfuncs/func_seconds_test.go +++ b/pkg/ottl/ottlfuncs/func_seconds_test.go @@ -16,13 +16,13 @@ import ( func Test_Seconds(t *testing.T) { tests := []struct { name string - duration ottl.DurationGetter[interface{}] + duration ottl.DurationGetter[any] expected float64 }{ { name: "100 seconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100s") }, }, @@ -30,8 +30,8 @@ func Test_Seconds(t *testing.T) { }, { name: "1 hour", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("100h") }, }, @@ -39,8 +39,8 @@ func Test_Seconds(t *testing.T) { }, { name: "11 mins", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("11m") }, }, @@ -48,8 +48,8 @@ func Test_Seconds(t *testing.T) { }, { name: "50 microseconds", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("11us") }, }, @@ -57,8 +57,8 @@ func Test_Seconds(t *testing.T) { }, { name: "1 hour 40 mins 3 seconds 30 milliseconds 100 microseconds 1 nanosecond", - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.ParseDuration("1h40m3s30ms100us1ns") }, }, diff --git a/pkg/ottl/ottlfuncs/func_set.go b/pkg/ottl/ottlfuncs/func_set.go index 6a8f0da3f0fb..a0ce390a4788 100644 --- a/pkg/ottl/ottlfuncs/func_set.go +++ b/pkg/ottl/ottlfuncs/func_set.go @@ -30,7 +30,7 @@ func createSetFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ott } func set[K any](target ottl.Setter[K], value ottl.Getter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := value.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_set_test.go b/pkg/ottl/ottlfuncs/func_set_test.go index b0f2859b13be..90666002153f 100644 --- a/pkg/ottl/ottlfuncs/func_set_test.go +++ b/pkg/ottl/ottlfuncs/func_set_test.go @@ -17,7 +17,7 @@ func Test_set(t *testing.T) { input := pcommon.NewValueStr("original name") target := &ottl.StandardGetSetter[pcommon.Value]{ - Setter: func(ctx context.Context, tCtx pcommon.Value, val interface{}) error { + Setter: func(ctx context.Context, tCtx pcommon.Value, val any) error { tCtx.SetStr(val.(string)) return nil }, @@ -33,7 +33,7 @@ func Test_set(t *testing.T) { name: "set name", setter: target, getter: ottl.StandardGetSetter[pcommon.Value]{ - Getter: func(ctx context.Context, tCtx pcommon.Value) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Value) (any, error) { return "new name", nil }, }, @@ -45,7 +45,7 @@ func Test_set(t *testing.T) { name: "set nil value", setter: target, getter: ottl.StandardGetSetter[pcommon.Value]{ - Getter: func(ctx context.Context, tCtx pcommon.Value) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Value) (any, error) { return nil, nil }, }, @@ -73,20 +73,20 @@ func Test_set(t *testing.T) { } func Test_set_get_nil(t *testing.T) { - setter := &ottl.StandardGetSetter[interface{}]{ - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + setter := &ottl.StandardGetSetter[any]{ + Setter: func(ctx context.Context, tCtx any, val any) error { t.Errorf("nothing should be set in this scenario") return nil }, } - getter := &ottl.StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + getter := &ottl.StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - exprFunc := set[interface{}](setter, getter) + exprFunc := set[any](setter, getter) result, err := exprFunc(nil, nil) assert.NoError(t, err) diff --git a/pkg/ottl/ottlfuncs/func_sha1.go b/pkg/ottl/ottlfuncs/func_sha1.go index e091d2110fb6..1e4c22a50e41 100644 --- a/pkg/ottl/ottlfuncs/func_sha1.go +++ b/pkg/ottl/ottlfuncs/func_sha1.go @@ -32,7 +32,7 @@ func createSHA1Function[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ot func SHA1HashString[K any](target ottl.StringGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_sha1_test.go b/pkg/ottl/ottlfuncs/func_sha1_test.go index 9b2d384ed095..6518c093da90 100644 --- a/pkg/ottl/ottlfuncs/func_sha1_test.go +++ b/pkg/ottl/ottlfuncs/func_sha1_test.go @@ -15,8 +15,8 @@ import ( func Test_SHA1(t *testing.T) { tests := []struct { name string - value interface{} - expected interface{} + value any + expected any err bool }{ { @@ -32,8 +32,8 @@ func Test_SHA1(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc, err := SHA1HashString[interface{}](&ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc, err := SHA1HashString[any](&ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) @@ -52,7 +52,7 @@ func Test_SHA1(t *testing.T) { func Test_SHA1Error(t *testing.T) { tests := []struct { name string - value interface{} + value any err bool expectedError string }{ @@ -69,8 +69,8 @@ func Test_SHA1Error(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc, err := SHA1HashString[interface{}](&ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc, err := SHA1HashString[any](&ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) diff --git a/pkg/ottl/ottlfuncs/func_sha256.go b/pkg/ottl/ottlfuncs/func_sha256.go index 179d8bbe7b2f..b2201c71b901 100644 --- a/pkg/ottl/ottlfuncs/func_sha256.go +++ b/pkg/ottl/ottlfuncs/func_sha256.go @@ -32,7 +32,7 @@ func createSHA256Function[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) ( func SHA256HashString[K any](target ottl.StringGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_sha256_test.go b/pkg/ottl/ottlfuncs/func_sha256_test.go index 5d308f2faed5..0a73e581650c 100644 --- a/pkg/ottl/ottlfuncs/func_sha256_test.go +++ b/pkg/ottl/ottlfuncs/func_sha256_test.go @@ -15,8 +15,8 @@ import ( func Test_SHA256(t *testing.T) { tests := []struct { name string - value interface{} - expected interface{} + value any + expected any err bool }{ { @@ -32,8 +32,8 @@ func Test_SHA256(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc, err := SHA256HashString[interface{}](&ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc, err := SHA256HashString[any](&ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) @@ -52,7 +52,7 @@ func Test_SHA256(t *testing.T) { func Test_SHA256Error(t *testing.T) { tests := []struct { name string - value interface{} + value any err bool expectedError string }{ @@ -69,8 +69,8 @@ func Test_SHA256Error(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc, err := SHA256HashString[interface{}](&ottl.StandardStringGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + exprFunc, err := SHA256HashString[any](&ottl.StandardStringGetter[any]{ + Getter: func(context.Context, any) (any, error) { return tt.value, nil }, }) diff --git a/pkg/ottl/ottlfuncs/func_span_id.go b/pkg/ottl/ottlfuncs/func_span_id.go index 74f9ee910ad5..79359fbf663e 100644 --- a/pkg/ottl/ottlfuncs/func_span_id.go +++ b/pkg/ottl/ottlfuncs/func_span_id.go @@ -38,7 +38,7 @@ func spanID[K any](bytes []byte) (ottl.ExprFunc[K], error) { var idArr [8]byte copy(idArr[:8], bytes) id := pcommon.SpanID(idArr) - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { return id, nil }, nil } diff --git a/pkg/ottl/ottlfuncs/func_span_id_test.go b/pkg/ottl/ottlfuncs/func_span_id_test.go index 532813eeef5b..700b30972e3f 100644 --- a/pkg/ottl/ottlfuncs/func_span_id_test.go +++ b/pkg/ottl/ottlfuncs/func_span_id_test.go @@ -25,7 +25,7 @@ func Test_spanID(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc, err := spanID[interface{}](tt.bytes) + exprFunc, err := spanID[any](tt.bytes) assert.NoError(t, err) result, err := exprFunc(nil, nil) assert.NoError(t, err) @@ -50,7 +50,7 @@ func Test_spanID_validation(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, err := spanID[interface{}](tt.bytes) + _, err := spanID[any](tt.bytes) require.Error(t, err) assert.ErrorContains(t, err, "span ids must be 8 bytes") }) diff --git a/pkg/ottl/ottlfuncs/func_split.go b/pkg/ottl/ottlfuncs/func_split.go index 24e45fcb5c09..904be7ad64a6 100644 --- a/pkg/ottl/ottlfuncs/func_split.go +++ b/pkg/ottl/ottlfuncs/func_split.go @@ -31,7 +31,7 @@ func createSplitFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (o } func split[K any](target ottl.StringGetter[K], delimiter string) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { val, err := target.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_split_test.go b/pkg/ottl/ottlfuncs/func_split_test.go index 06ab92308f9d..9d12d0044d92 100644 --- a/pkg/ottl/ottlfuncs/func_split_test.go +++ b/pkg/ottl/ottlfuncs/func_split_test.go @@ -15,14 +15,14 @@ import ( func Test_split(t *testing.T) { tests := []struct { name string - target ottl.StringGetter[interface{}] + target ottl.StringGetter[any] delimiter string - expected interface{} + expected any }{ { name: "split string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "A|B|C", nil }, }, @@ -31,8 +31,8 @@ func Test_split(t *testing.T) { }, { name: "split empty string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -41,8 +41,8 @@ func Test_split(t *testing.T) { }, { name: "split empty delimiter", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "A|B|C", nil }, }, @@ -51,8 +51,8 @@ func Test_split(t *testing.T) { }, { name: "split empty string and empty delimiter", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -71,12 +71,12 @@ func Test_split(t *testing.T) { } func Test_Split_Error(t *testing.T) { - target := &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, } - exprFunc := split[interface{}](target, ",") + exprFunc := split[any](target, ",") _, err := exprFunc(context.Background(), nil) assert.Error(t, err) } diff --git a/pkg/ottl/ottlfuncs/func_substring.go b/pkg/ottl/ottlfuncs/func_substring.go index 974a110b8716..817d23d78e68 100644 --- a/pkg/ottl/ottlfuncs/func_substring.go +++ b/pkg/ottl/ottlfuncs/func_substring.go @@ -31,7 +31,7 @@ func createSubstringFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments } func substring[K any](target ottl.StringGetter[K], startGetter ottl.IntGetter[K], lengthGetter ottl.IntGetter[K]) ottl.ExprFunc[K] { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { start, err := startGetter.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_substring_test.go b/pkg/ottl/ottlfuncs/func_substring_test.go index 1b659e9b6d76..5a65afff4bfb 100644 --- a/pkg/ottl/ottlfuncs/func_substring_test.go +++ b/pkg/ottl/ottlfuncs/func_substring_test.go @@ -15,25 +15,25 @@ import ( func Test_substring(t *testing.T) { tests := []struct { name string - target ottl.StringGetter[interface{}] - start ottl.IntGetter[interface{}] - length ottl.IntGetter[interface{}] - expected interface{} + target ottl.StringGetter[any] + start ottl.IntGetter[any] + length ottl.IntGetter[any] + expected any }{ { name: "substring", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "123456789", nil }, }, - start: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + start: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(3), nil }, }, - length: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + length: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(3), nil }, }, @@ -41,18 +41,18 @@ func Test_substring(t *testing.T) { }, { name: "substring with result of total string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "123456789", nil }, }, - start: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + start: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(0), nil }, }, - length: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + length: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(9), nil }, }, @@ -72,42 +72,42 @@ func Test_substring(t *testing.T) { func Test_substring_validation(t *testing.T) { tests := []struct { name string - target ottl.StringGetter[interface{}] - start ottl.IntGetter[interface{}] - length ottl.IntGetter[interface{}] + target ottl.StringGetter[any] + start ottl.IntGetter[any] + length ottl.IntGetter[any] }{ { name: "substring with result of empty string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "123456789", nil }, }, - start: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + start: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(0), nil }, }, - length: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + length: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(0), nil }, }, }, { name: "substring with invalid start index", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "123456789", nil }, }, - start: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + start: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(-1), nil }, }, - length: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + length: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(6), nil }, }, @@ -126,78 +126,78 @@ func Test_substring_validation(t *testing.T) { func Test_substring_error(t *testing.T) { tests := []struct { name string - target ottl.StringGetter[interface{}] - start ottl.IntGetter[interface{}] - length ottl.IntGetter[interface{}] + target ottl.StringGetter[any] + start ottl.IntGetter[any] + length ottl.IntGetter[any] }{ { name: "substring empty string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, - start: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + start: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(3), nil }, }, - length: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + length: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(6), nil }, }, }, { name: "substring with invalid length index", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "123456789", nil }, }, - start: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + start: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(3), nil }, }, - length: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + length: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(20), nil }, }, }, { name: "substring non-string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return 123456789, nil }, }, - start: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + start: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(3), nil }, }, - length: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + length: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(6), nil }, }, }, { name: "substring nil string", - target: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, }, - start: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + start: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(3), nil }, }, - length: &ottl.StandardIntGetter[interface{}]{ - Getter: func(context.Context, interface{}) (interface{}, error) { + length: &ottl.StandardIntGetter[any]{ + Getter: func(context.Context, any) (any, error) { return int64(6), nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_time.go b/pkg/ottl/ottlfuncs/func_time.go index 427069eb2cdb..a6ef708b0921 100644 --- a/pkg/ottl/ottlfuncs/func_time.go +++ b/pkg/ottl/ottlfuncs/func_time.go @@ -38,7 +38,7 @@ func Time[K any](inputTime ottl.StringGetter[K], format string) (ottl.ExprFunc[K return nil, err } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { t, err := inputTime.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_time_test.go b/pkg/ottl/ottlfuncs/func_time_test.go index fb54ac8b1729..eae82bf3bf33 100644 --- a/pkg/ottl/ottlfuncs/func_time_test.go +++ b/pkg/ottl/ottlfuncs/func_time_test.go @@ -17,14 +17,14 @@ import ( func Test_Time(t *testing.T) { tests := []struct { name string - time ottl.StringGetter[interface{}] + time ottl.StringGetter[any] format string expected time.Time }{ { name: "simple short form", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "2023-04-12", nil }, }, @@ -33,8 +33,8 @@ func Test_Time(t *testing.T) { }, { name: "simple short form with short year and slashes", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "11/11/11", nil }, }, @@ -43,8 +43,8 @@ func Test_Time(t *testing.T) { }, { name: "month day year", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "02/04/2023", nil }, }, @@ -53,8 +53,8 @@ func Test_Time(t *testing.T) { }, { name: "simple long form", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "July 31, 1993", nil }, }, @@ -63,8 +63,8 @@ func Test_Time(t *testing.T) { }, { name: "date with timestamp", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "Mar 14 2023 17:02:59", nil }, }, @@ -73,8 +73,8 @@ func Test_Time(t *testing.T) { }, { name: "day of the week long form", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "Monday, May 01, 2023", nil }, }, @@ -83,8 +83,8 @@ func Test_Time(t *testing.T) { }, { name: "short weekday, short month, long format", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "Sat, May 20, 2023", nil }, }, @@ -93,8 +93,8 @@ func Test_Time(t *testing.T) { }, { name: "short months", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "Feb 15, 2023", nil }, }, @@ -103,8 +103,8 @@ func Test_Time(t *testing.T) { }, { name: "timestamp with time zone offset", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "2023-05-26 12:34:56 HST", nil }, }, @@ -113,8 +113,8 @@ func Test_Time(t *testing.T) { }, { name: "short date with timestamp without time zone offset", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "2023-05-26T12:34:56 GMT", nil }, }, @@ -123,8 +123,8 @@ func Test_Time(t *testing.T) { }, { name: "RFC 3339 in custom format", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "2012-11-01T22:08:41+0000 EST", nil }, }, @@ -133,8 +133,8 @@ func Test_Time(t *testing.T) { }, { name: "RFC 3339 in custom format before 2000", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "1986-10-01T00:17:33 MST", nil }, }, @@ -143,8 +143,8 @@ func Test_Time(t *testing.T) { }, { name: "no location", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "2022/01/01", nil }, }, @@ -166,14 +166,14 @@ func Test_Time(t *testing.T) { func Test_TimeError(t *testing.T) { tests := []struct { name string - time ottl.StringGetter[interface{}] + time ottl.StringGetter[any] format string expectedError string }{ { name: "invalid short format", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "11/11/11", nil }, }, @@ -182,8 +182,8 @@ func Test_TimeError(t *testing.T) { }, { name: "invalid RFC3339 with no time", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "", nil }, }, @@ -204,14 +204,14 @@ func Test_TimeError(t *testing.T) { func Test_TimeFormatError(t *testing.T) { tests := []struct { name string - time ottl.StringGetter[interface{}] + time ottl.StringGetter[any] format string expectedError string }{ { name: "invalid short with no format", - time: &ottl.StandardStringGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardStringGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "11/11/11", nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_trace_id.go b/pkg/ottl/ottlfuncs/func_trace_id.go index c28013b75ab2..a8717209ff0c 100644 --- a/pkg/ottl/ottlfuncs/func_trace_id.go +++ b/pkg/ottl/ottlfuncs/func_trace_id.go @@ -38,7 +38,7 @@ func traceID[K any](bytes []byte) (ottl.ExprFunc[K], error) { var idArr [16]byte copy(idArr[:16], bytes) id := pcommon.TraceID(idArr) - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { return id, nil }, nil } diff --git a/pkg/ottl/ottlfuncs/func_trace_id_test.go b/pkg/ottl/ottlfuncs/func_trace_id_test.go index 2885e8b9b75f..4df12bdf6bdf 100644 --- a/pkg/ottl/ottlfuncs/func_trace_id_test.go +++ b/pkg/ottl/ottlfuncs/func_trace_id_test.go @@ -25,7 +25,7 @@ func Test_traceID(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - exprFunc, err := traceID[interface{}](tt.bytes) + exprFunc, err := traceID[any](tt.bytes) assert.NoError(t, err) result, err := exprFunc(nil, nil) assert.NoError(t, err) @@ -50,7 +50,7 @@ func Test_traceID_validation(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, err := traceID[interface{}](tt.bytes) + _, err := traceID[any](tt.bytes) require.Error(t, err) assert.ErrorContains(t, err, "traces ids must be 16 bytes") }) diff --git a/pkg/ottl/ottlfuncs/func_truncate_all.go b/pkg/ottl/ottlfuncs/func_truncate_all.go index 5d1a7fc08365..dd47e7e96d87 100644 --- a/pkg/ottl/ottlfuncs/func_truncate_all.go +++ b/pkg/ottl/ottlfuncs/func_truncate_all.go @@ -35,7 +35,7 @@ func TruncateAll[K any](target ottl.PMapGetter[K], limit int64) (ottl.ExprFunc[K if limit < 0 { return nil, fmt.Errorf("invalid limit for truncate_all function, %d cannot be negative", limit) } - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { if limit < 0 { return nil, nil } diff --git a/pkg/ottl/ottlfuncs/func_truncate_all_test.go b/pkg/ottl/ottlfuncs/func_truncate_all_test.go index ff980a48d956..a04ecac3089f 100644 --- a/pkg/ottl/ottlfuncs/func_truncate_all_test.go +++ b/pkg/ottl/ottlfuncs/func_truncate_all_test.go @@ -21,7 +21,7 @@ func Test_truncateAll(t *testing.T) { input.PutBool("test3", true) target := &ottl.StandardPMapGetter[pcommon.Map]{ - Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { + Getter: func(ctx context.Context, tCtx pcommon.Map) (any, error) { return tCtx, nil }, } @@ -94,20 +94,20 @@ func Test_truncateAll(t *testing.T) { } func Test_truncateAll_validation(t *testing.T) { - _, err := TruncateAll[interface{}](&ottl.StandardPMapGetter[interface{}]{}, -1) + _, err := TruncateAll[any](&ottl.StandardPMapGetter[any]{}, -1) require.Error(t, err) assert.ErrorContains(t, err, "invalid limit for truncate_all function, -1 cannot be negative") } func Test_truncateAll_bad_input(t *testing.T) { input := pcommon.NewValueStr("not a map") - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - exprFunc, err := TruncateAll[interface{}](target, 1) + exprFunc, err := TruncateAll[any](target, 1) assert.NoError(t, err) _, err = exprFunc(nil, input) @@ -115,13 +115,13 @@ func Test_truncateAll_bad_input(t *testing.T) { } func Test_truncateAll_get_nil(t *testing.T) { - target := &ottl.StandardPMapGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + target := &ottl.StandardPMapGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, } - exprFunc, err := TruncateAll[interface{}](target, 1) + exprFunc, err := TruncateAll[any](target, 1) assert.NoError(t, err) _, err = exprFunc(nil, nil) diff --git a/pkg/ottl/ottlfuncs/func_truncate_time.go b/pkg/ottl/ottlfuncs/func_truncate_time.go index 434b765ae4ae..3d122dfb8740 100644 --- a/pkg/ottl/ottlfuncs/func_truncate_time.go +++ b/pkg/ottl/ottlfuncs/func_truncate_time.go @@ -29,7 +29,7 @@ func createTruncateTimeFunction[K any](_ ottl.FunctionContext, oArgs ottl.Argume } func TruncateTime[K any](inputTime ottl.TimeGetter[K], inputDuration ottl.DurationGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { t, err := inputTime.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_truncate_time_test.go b/pkg/ottl/ottlfuncs/func_truncate_time_test.go index 925b5f58b70a..33781d3b478e 100644 --- a/pkg/ottl/ottlfuncs/func_truncate_time_test.go +++ b/pkg/ottl/ottlfuncs/func_truncate_time_test.go @@ -17,19 +17,19 @@ import ( func Test_TruncateTime(t *testing.T) { tests := []struct { name string - time ottl.TimeGetter[interface{}] - duration ottl.DurationGetter[interface{}] + time ottl.TimeGetter[any] + duration ottl.DurationGetter[any] expected time.Time }{ { name: "truncate to 1s", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2022, 1, 1, 1, 1, 1, 999999999, time.Local), nil }, }, - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { d, _ := time.ParseDuration("1s") return d, nil }, @@ -38,13 +38,13 @@ func Test_TruncateTime(t *testing.T) { }, { name: "truncate to 1ms", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2022, 1, 1, 1, 1, 1, 999999999, time.Local), nil }, }, - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { d, _ := time.ParseDuration("1ms") return d, nil }, @@ -53,13 +53,13 @@ func Test_TruncateTime(t *testing.T) { }, { name: "truncate old time", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(1980, 9, 9, 9, 59, 59, 999999999, time.Local), nil }, }, - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { d, _ := time.ParseDuration("1h") return d, nil }, @@ -81,19 +81,19 @@ func Test_TruncateTime(t *testing.T) { func Test_TruncateTimeError(t *testing.T) { tests := []struct { name string - time ottl.TimeGetter[interface{}] - duration ottl.DurationGetter[interface{}] + time ottl.TimeGetter[any] + duration ottl.DurationGetter[any] expectedError string }{ { name: "not a time", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "11/11/11", nil }, }, - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { d, _ := time.ParseDuration("1ms") return d, nil }, @@ -102,13 +102,13 @@ func Test_TruncateTimeError(t *testing.T) { }, { name: "not a duration", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Now(), nil }, }, - duration: &ottl.StandardDurationGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + duration: &ottl.StandardDurationGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return "string", nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_unix_micro.go b/pkg/ottl/ottlfuncs/func_unix_micro.go index 94a5e010dd4f..d55f717c7509 100644 --- a/pkg/ottl/ottlfuncs/func_unix_micro.go +++ b/pkg/ottl/ottlfuncs/func_unix_micro.go @@ -28,7 +28,7 @@ func createUnixMicroFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments } func UnixMicro[K any](inputTime ottl.TimeGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { t, err := inputTime.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_unix_micro_test.go b/pkg/ottl/ottlfuncs/func_unix_micro_test.go index bc4a3e5435bd..86759fa202f1 100644 --- a/pkg/ottl/ottlfuncs/func_unix_micro_test.go +++ b/pkg/ottl/ottlfuncs/func_unix_micro_test.go @@ -16,13 +16,13 @@ import ( func Test_TimeUnixMicro(t *testing.T) { tests := []struct { name string - time ottl.TimeGetter[interface{}] + time ottl.TimeGetter[any] expected time.Time }{ { name: "January 1, 2023", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2023, 1, 1, 0, 0, 0, 0, time.Local), nil }, }, @@ -30,8 +30,8 @@ func Test_TimeUnixMicro(t *testing.T) { }, { name: "April 30, 2001, 3pm", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2001, 4, 30, 15, 0, 0, 0, time.Local), nil }, }, @@ -39,8 +39,8 @@ func Test_TimeUnixMicro(t *testing.T) { }, { name: "November 12, 1980, 4:35:01am", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(1980, 11, 12, 4, 35, 1, 0, time.Local), nil }, }, @@ -48,8 +48,8 @@ func Test_TimeUnixMicro(t *testing.T) { }, { name: "October 4, 2020, 5:05 5 microseconds 5 nanosecs", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2020, 10, 4, 5, 5, 5, 5, time.Local), nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_unix_milli.go b/pkg/ottl/ottlfuncs/func_unix_milli.go index dac3f7d65237..8f5e587c73b6 100644 --- a/pkg/ottl/ottlfuncs/func_unix_milli.go +++ b/pkg/ottl/ottlfuncs/func_unix_milli.go @@ -28,7 +28,7 @@ func createUnixMilliFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments } func UnixMilli[K any](inputTime ottl.TimeGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { t, err := inputTime.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_unix_milli_test.go b/pkg/ottl/ottlfuncs/func_unix_milli_test.go index d77cca91f928..798b755f69aa 100644 --- a/pkg/ottl/ottlfuncs/func_unix_milli_test.go +++ b/pkg/ottl/ottlfuncs/func_unix_milli_test.go @@ -16,13 +16,13 @@ import ( func Test_TimeUnixMilli(t *testing.T) { tests := []struct { name string - time ottl.TimeGetter[interface{}] + time ottl.TimeGetter[any] expected time.Time }{ { name: "January 1, 2022", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2022, 1, 1, 0, 0, 0, 0, time.Local), nil }, }, @@ -30,8 +30,8 @@ func Test_TimeUnixMilli(t *testing.T) { }, { name: "May 30, 2002, 3pm", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2002, 5, 30, 15, 0, 0, 0, time.Local), nil }, }, @@ -39,8 +39,8 @@ func Test_TimeUnixMilli(t *testing.T) { }, { name: "September 12, 1980, 4:35:01am", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(1980, 9, 12, 4, 35, 1, 0, time.Local), nil }, }, @@ -48,8 +48,8 @@ func Test_TimeUnixMilli(t *testing.T) { }, { name: "October 4, 2020, 5:05 5 microseconds 5 nanosecs", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2020, 10, 4, 5, 5, 5, 5, time.Local), nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_unix_nano.go b/pkg/ottl/ottlfuncs/func_unix_nano.go index 8935aea5325e..4c027d855fcb 100644 --- a/pkg/ottl/ottlfuncs/func_unix_nano.go +++ b/pkg/ottl/ottlfuncs/func_unix_nano.go @@ -28,7 +28,7 @@ func createUnixNanoFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) } func UnixNano[K any](inputTime ottl.TimeGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { t, err := inputTime.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_unix_nano_test.go b/pkg/ottl/ottlfuncs/func_unix_nano_test.go index 6e65a1b89746..25d40c532f0d 100644 --- a/pkg/ottl/ottlfuncs/func_unix_nano_test.go +++ b/pkg/ottl/ottlfuncs/func_unix_nano_test.go @@ -16,13 +16,13 @@ import ( func Test_TimeUnixNano(t *testing.T) { tests := []struct { name string - time ottl.TimeGetter[interface{}] + time ottl.TimeGetter[any] expected time.Time }{ { name: "January 1, 2023", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2023, 1, 1, 0, 0, 0, 0, time.Local), nil }, }, @@ -30,8 +30,8 @@ func Test_TimeUnixNano(t *testing.T) { }, { name: "April 30, 2000, 1pm", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2000, 4, 30, 13, 0, 0, 0, time.Local), nil }, }, @@ -39,8 +39,8 @@ func Test_TimeUnixNano(t *testing.T) { }, { name: "December 12, 1980, 4:35:01am", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(1980, 12, 12, 4, 35, 1, 0, time.Local), nil }, }, @@ -48,8 +48,8 @@ func Test_TimeUnixNano(t *testing.T) { }, { name: "October 4, 2020, 5:05 5 microseconds 5 nanosecs", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2020, 10, 4, 5, 5, 5, 5, time.Local), nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_unix_seconds.go b/pkg/ottl/ottlfuncs/func_unix_seconds.go index c79c6b9f7bcc..612a87f8c50c 100644 --- a/pkg/ottl/ottlfuncs/func_unix_seconds.go +++ b/pkg/ottl/ottlfuncs/func_unix_seconds.go @@ -28,7 +28,7 @@ func createUnixSecondsFunction[K any](_ ottl.FunctionContext, oArgs ottl.Argumen } func UnixSeconds[K any](inputTime ottl.TimeGetter[K]) (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { t, err := inputTime.Get(ctx, tCtx) if err != nil { return nil, err diff --git a/pkg/ottl/ottlfuncs/func_unix_seconds_test.go b/pkg/ottl/ottlfuncs/func_unix_seconds_test.go index 22fe577c48ee..c0eabdaef415 100644 --- a/pkg/ottl/ottlfuncs/func_unix_seconds_test.go +++ b/pkg/ottl/ottlfuncs/func_unix_seconds_test.go @@ -16,13 +16,13 @@ import ( func Test_TimeUnixSeconds(t *testing.T) { tests := []struct { name string - time ottl.TimeGetter[interface{}] + time ottl.TimeGetter[any] expected time.Time }{ { name: "January 1, 2023", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2023, 1, 1, 0, 0, 0, 0, time.Local), nil }, }, @@ -30,8 +30,8 @@ func Test_TimeUnixSeconds(t *testing.T) { }, { name: "March 31, 2000, 4pm", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2000, 3, 31, 16, 0, 0, 0, time.Local), nil }, }, @@ -39,8 +39,8 @@ func Test_TimeUnixSeconds(t *testing.T) { }, { name: "December 12, 1980, 4:35:01am", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(1980, 12, 12, 4, 35, 1, 0, time.Local), nil }, }, @@ -48,8 +48,8 @@ func Test_TimeUnixSeconds(t *testing.T) { }, { name: "October 4, 2020, 5:05 5 microseconds 5 nanosecs", - time: &ottl.StandardTimeGetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + time: &ottl.StandardTimeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return time.Date(2020, 10, 4, 5, 5, 5, 5, time.Local), nil }, }, diff --git a/pkg/ottl/ottlfuncs/func_uuid.go b/pkg/ottl/ottlfuncs/func_uuid.go index 2bee69bcf430..9c03835f5037 100644 --- a/pkg/ottl/ottlfuncs/func_uuid.go +++ b/pkg/ottl/ottlfuncs/func_uuid.go @@ -12,7 +12,7 @@ import ( ) func uuid[K any]() (ottl.ExprFunc[K], error) { - return func(ctx context.Context, tCtx K) (interface{}, error) { + return func(ctx context.Context, tCtx K) (any, error) { u := guuid.New() return u.String(), nil }, nil diff --git a/pkg/ottl/ottlfuncs/func_uuid_test.go b/pkg/ottl/ottlfuncs/func_uuid_test.go index c923ac3ae2f4..2c27b5bca517 100644 --- a/pkg/ottl/ottlfuncs/func_uuid_test.go +++ b/pkg/ottl/ottlfuncs/func_uuid_test.go @@ -10,7 +10,7 @@ import ( ) func Test_UUID(t *testing.T) { - exprFunc, err := uuid[interface{}]() + exprFunc, err := uuid[any]() assert.NoError(t, err) value, err := exprFunc(nil, nil) diff --git a/pkg/ottl/parser_test.go b/pkg/ottl/parser_test.go index 470957cb2c74..df63d9384076 100644 --- a/pkg/ottl/parser_test.go +++ b/pkg/ottl/parser_test.go @@ -1088,43 +1088,43 @@ func Test_parse(t *testing.T) { } } -func testParsePath(val *Path) (GetSetter[interface{}], error) { +func testParsePath(val *Path) (GetSetter[any], error) { if val != nil && len(val.Fields) > 0 && (val.Fields[0].Name == "name" || val.Fields[0].Name == "attributes") { - return &StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + return &StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { return tCtx, nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { reflect.DeepEqual(tCtx, val) return nil }, }, nil } if val.Fields[0].Name == "dur1" || val.Fields[0].Name == "dur2" { - return &StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + return &StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { m, ok := tCtx.(map[string]time.Duration) if !ok { return nil, fmt.Errorf("unable to convert transform context to map of strings to times") } return m[val.Fields[0].Name], nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { reflect.DeepEqual(tCtx, val) return nil }, }, nil } if val.Fields[0].Name == "time1" || val.Fields[0].Name == "time2" { - return &StandardGetSetter[interface{}]{ - Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + return &StandardGetSetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { m, ok := tCtx.(map[string]time.Time) if !ok { return nil, fmt.Errorf("unable to convert transform context to map of strings to times") } return m[val.Fields[0].Name], nil }, - Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error { + Setter: func(ctx context.Context, tCtx any, val any) error { reflect.DeepEqual(tCtx, val) return nil }, @@ -1727,15 +1727,15 @@ func Test_parseStatement(t *testing.T) { func Test_Execute(t *testing.T) { tests := []struct { name string - condition boolExpressionEvaluator[interface{}] - function ExprFunc[interface{}] + condition boolExpressionEvaluator[any] + function ExprFunc[any] expectedCondition bool - expectedResult interface{} + expectedResult any }{ { name: "Condition matched", - condition: alwaysTrue[interface{}], - function: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + condition: alwaysTrue[any], + function: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, expectedCondition: true, @@ -1743,8 +1743,8 @@ func Test_Execute(t *testing.T) { }, { name: "Condition not matched", - condition: alwaysFalse[interface{}], - function: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + condition: alwaysFalse[any], + function: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, expectedCondition: false, @@ -1752,8 +1752,8 @@ func Test_Execute(t *testing.T) { }, { name: "No result", - condition: alwaysTrue[interface{}], - function: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + condition: alwaysTrue[any], + function: func(ctx context.Context, tCtx any) (any, error) { return nil, nil }, expectedCondition: true, @@ -1762,7 +1762,7 @@ func Test_Execute(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - statement := Statement[interface{}]{ + statement := Statement[any]{ condition: BoolExpr[any]{tt.condition}, function: Expr[any]{exprFunc: tt.function}, } @@ -1778,46 +1778,46 @@ func Test_Execute(t *testing.T) { func Test_Statements_Execute_Error(t *testing.T) { tests := []struct { name string - condition boolExpressionEvaluator[interface{}] - function ExprFunc[interface{}] + condition boolExpressionEvaluator[any] + function ExprFunc[any] errorMode ErrorMode }{ { name: "IgnoreError error from condition", - condition: func(context.Context, interface{}) (bool, error) { + condition: func(context.Context, any) (bool, error) { return true, fmt.Errorf("test") }, - function: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + function: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, errorMode: IgnoreError, }, { name: "PropagateError error from condition", - condition: func(context.Context, interface{}) (bool, error) { + condition: func(context.Context, any) (bool, error) { return true, fmt.Errorf("test") }, - function: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + function: func(ctx context.Context, tCtx any) (any, error) { return 1, nil }, errorMode: PropagateError, }, { name: "IgnoreError error from function", - condition: func(context.Context, interface{}) (bool, error) { + condition: func(context.Context, any) (bool, error) { return true, nil }, - function: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + function: func(ctx context.Context, tCtx any) (any, error) { return 1, fmt.Errorf("test") }, errorMode: IgnoreError, }, { name: "PropagateError error from function", - condition: func(context.Context, interface{}) (bool, error) { + condition: func(context.Context, any) (bool, error) { return true, nil }, - function: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + function: func(ctx context.Context, tCtx any) (any, error) { return 1, fmt.Errorf("test") }, errorMode: PropagateError, @@ -1825,8 +1825,8 @@ func Test_Statements_Execute_Error(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - statements := Statements[interface{}]{ - statements: []*Statement[interface{}]{ + statements := Statements[any]{ + statements: []*Statement[any]{ { condition: BoolExpr[any]{tt.condition}, function: Expr[any]{exprFunc: tt.function}, @@ -1849,46 +1849,46 @@ func Test_Statements_Execute_Error(t *testing.T) { func Test_Statements_Eval(t *testing.T) { tests := []struct { name string - conditions []boolExpressionEvaluator[interface{}] - function ExprFunc[interface{}] + conditions []boolExpressionEvaluator[any] + function ExprFunc[any] errorMode ErrorMode expectedResult bool }{ { name: "True", - conditions: []boolExpressionEvaluator[interface{}]{ - alwaysTrue[interface{}], + conditions: []boolExpressionEvaluator[any]{ + alwaysTrue[any], }, errorMode: IgnoreError, expectedResult: true, }, { name: "At least one True", - conditions: []boolExpressionEvaluator[interface{}]{ - alwaysFalse[interface{}], - alwaysFalse[interface{}], - alwaysTrue[interface{}], + conditions: []boolExpressionEvaluator[any]{ + alwaysFalse[any], + alwaysFalse[any], + alwaysTrue[any], }, errorMode: IgnoreError, expectedResult: true, }, { name: "False", - conditions: []boolExpressionEvaluator[interface{}]{ - alwaysFalse[interface{}], - alwaysFalse[interface{}], + conditions: []boolExpressionEvaluator[any]{ + alwaysFalse[any], + alwaysFalse[any], }, errorMode: IgnoreError, expectedResult: false, }, { name: "Error is false when using Ignore", - conditions: []boolExpressionEvaluator[interface{}]{ - alwaysFalse[interface{}], - func(context.Context, interface{}) (bool, error) { + conditions: []boolExpressionEvaluator[any]{ + alwaysFalse[any], + func(context.Context, any) (bool, error) { return true, fmt.Errorf("test") }, - alwaysTrue[interface{}], + alwaysTrue[any], }, errorMode: IgnoreError, expectedResult: true, @@ -1896,19 +1896,19 @@ func Test_Statements_Eval(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - var rawStatements []*Statement[interface{}] + var rawStatements []*Statement[any] for _, condition := range tt.conditions { - rawStatements = append(rawStatements, &Statement[interface{}]{ + rawStatements = append(rawStatements, &Statement[any]{ condition: BoolExpr[any]{condition}, function: Expr[any]{ - exprFunc: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + exprFunc: func(ctx context.Context, tCtx any) (any, error) { return nil, fmt.Errorf("function should not be called") }, }, }) } - statements := Statements[interface{}]{ + statements := Statements[any]{ statements: rawStatements, telemetrySettings: componenttest.NewNopTelemetrySettings(), errorMode: tt.errorMode, @@ -1924,14 +1924,14 @@ func Test_Statements_Eval(t *testing.T) { func Test_Statements_Eval_Error(t *testing.T) { tests := []struct { name string - conditions []boolExpressionEvaluator[interface{}] - function ExprFunc[interface{}] + conditions []boolExpressionEvaluator[any] + function ExprFunc[any] errorMode ErrorMode }{ { name: "Propagate Error from function", - conditions: []boolExpressionEvaluator[interface{}]{ - func(context.Context, interface{}) (bool, error) { + conditions: []boolExpressionEvaluator[any]{ + func(context.Context, any) (bool, error) { return true, fmt.Errorf("test") }, }, @@ -1940,19 +1940,19 @@ func Test_Statements_Eval_Error(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - var rawStatements []*Statement[interface{}] + var rawStatements []*Statement[any] for _, condition := range tt.conditions { - rawStatements = append(rawStatements, &Statement[interface{}]{ + rawStatements = append(rawStatements, &Statement[any]{ condition: BoolExpr[any]{condition}, function: Expr[any]{ - exprFunc: func(ctx context.Context, tCtx interface{}) (interface{}, error) { + exprFunc: func(ctx context.Context, tCtx any) (any, error) { return nil, fmt.Errorf("function should not be called") }, }, }) } - statements := Statements[interface{}]{ + statements := Statements[any]{ statements: rawStatements, telemetrySettings: componenttest.NewNopTelemetrySettings(), errorMode: tt.errorMode, diff --git a/pkg/pdatautil/hash.go b/pkg/pdatautil/hash.go index 7900120cd6c3..650258445b4c 100644 --- a/pkg/pdatautil/hash.go +++ b/pkg/pdatautil/hash.go @@ -44,7 +44,7 @@ func newHashWriter() *hashWriter { } var hashWriterPool = &sync.Pool{ - New: func() interface{} { return newHashWriter() }, + New: func() any { return newHashWriter() }, } // MapHash return a hash for the provided map. diff --git a/pkg/stanza/adapter/converter.go b/pkg/stanza/adapter/converter.go index 52709c6c41fd..ada2d75823b1 100644 --- a/pkg/stanza/adapter/converter.go +++ b/pkg/stanza/adapter/converter.go @@ -266,7 +266,7 @@ func convertInto(ent *entry.Entry, dest plog.LogRecord) { } } -func upsertToAttributeVal(value interface{}, dest pcommon.Value) { +func upsertToAttributeVal(value any, dest pcommon.Value) { switch t := value.(type) { case bool: dest.SetBool(t) @@ -300,23 +300,23 @@ func upsertToAttributeVal(value interface{}, dest pcommon.Value) { dest.SetDouble(t) case float32: dest.SetDouble(float64(t)) - case map[string]interface{}: + case map[string]any: upsertToMap(t, dest.SetEmptyMap()) - case []interface{}: + case []any: upsertToSlice(t, dest.SetEmptySlice()) default: dest.SetStr(fmt.Sprintf("%v", t)) } } -func upsertToMap(obsMap map[string]interface{}, dest pcommon.Map) { +func upsertToMap(obsMap map[string]any, dest pcommon.Map) { dest.EnsureCapacity(len(obsMap)) for k, v := range obsMap { upsertToAttributeVal(v, dest.PutEmpty(k)) } } -func upsertToSlice(obsArr []interface{}, dest pcommon.Slice) { +func upsertToSlice(obsArr []any, dest pcommon.Slice) { dest.EnsureCapacity(len(obsArr)) for _, v := range obsArr { upsertToAttributeVal(v, dest.AppendEmpty()) @@ -407,11 +407,11 @@ func newHashWriter() *hashWriter { } var hashWriterPool = &sync.Pool{ - New: func() interface{} { return newHashWriter() }, + New: func() any { return newHashWriter() }, } // HashResource will hash an entry.Entry.Resource -func HashResource(resource map[string]interface{}) uint64 { +func HashResource(resource map[string]any) uint64 { if len(resource) == 0 { return emptyResourceID } diff --git a/pkg/stanza/adapter/converter_test.go b/pkg/stanza/adapter/converter_test.go index 2105976bd4cf..baf775fe39ab 100644 --- a/pkg/stanza/adapter/converter_test.go +++ b/pkg/stanza/adapter/converter_test.go @@ -50,32 +50,32 @@ func complexEntriesForNDifferentHosts(count int, n int) []*entry.Entry { for i := 0; i < count; i++ { e := entry.New() e.Severity = entry.Error - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "host": fmt.Sprintf("host-%d", i%n), "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", }, } - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", "bytes": []byte("asdf"), - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", "bytes": []byte("asdf"), - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, @@ -92,43 +92,43 @@ func complexEntriesForNDifferentHosts(count int, n int) []*entry.Entry { func complexEntry() *entry.Entry { e := entry.New() e.Severity = entry.Error - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", }, } - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", }, } - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", // "bytes": []byte("asdf"), - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", // "bytes": []byte("asdf"), - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, // "double": 12.34, @@ -143,17 +143,17 @@ func complexEntry() *entry.Entry { func TestHashResource(t *testing.T) { testcases := []struct { name string - baseline map[string]interface{} - same []map[string]interface{} - diff []map[string]interface{} + baseline map[string]any + same []map[string]any + diff []map[string]any }{ { name: "empty", - baseline: map[string]interface{}{}, - same: []map[string]interface{}{ + baseline: map[string]any{}, + same: []map[string]any{ {}, }, - diff: []map[string]interface{}{ + diff: []map[string]any{ { "a": "b", }, @@ -164,15 +164,15 @@ func TestHashResource(t *testing.T) { }, { name: "single_string", - baseline: map[string]interface{}{ + baseline: map[string]any{ "one": "two", }, - same: []map[string]interface{}{ + same: []map[string]any{ { "one": "two", }, }, - diff: []map[string]interface{}{ + diff: []map[string]any{ { "a": "b", }, @@ -187,11 +187,11 @@ func TestHashResource(t *testing.T) { }, { name: "multi_string", - baseline: map[string]interface{}{ + baseline: map[string]any{ "one": "two", "a": "b", }, - same: []map[string]interface{}{ + same: []map[string]any{ { "one": "two", "a": "b", @@ -201,7 +201,7 @@ func TestHashResource(t *testing.T) { "one": "two", }, }, - diff: []map[string]interface{}{ + diff: []map[string]any{ { "a": "b", }, @@ -212,36 +212,36 @@ func TestHashResource(t *testing.T) { }, { name: "multi_type", - baseline: map[string]interface{}{ + baseline: map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{}, + "object": map[string]any{}, }, - same: []map[string]interface{}{ + same: []map[string]any{ { "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{}, + "object": map[string]any{}, }, { - "object": map[string]interface{}{}, + "object": map[string]any{}, "double": 12.34, "int": 123, "bool": true, "string": "hello", }, }, - diff: []map[string]interface{}{ + diff: []map[string]any{ { "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "string": "hello", }, }, @@ -249,58 +249,58 @@ func TestHashResource(t *testing.T) { }, { name: "nested", - baseline: map[string]interface{}{ + baseline: map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{}, + "object": map[string]any{}, }, }, }, - same: []map[string]interface{}{ + same: []map[string]any{ { "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{}, + "object": map[string]any{}, }, }, }, }, - diff: []map[string]interface{}{ + diff: []map[string]any{ { "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{}, + "object": map[string]any{}, }, }, }, @@ -438,12 +438,12 @@ func TestConvertMetadata(t *testing.T) { e.Timestamp = now e.Severity = entry.Error e.AddResourceKey("type", "global") - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "bool": true, "int": 123, "double": 12.34, "string": "hello", - "object": map[string]interface{}{ + "object": map[string]any{ "bool": true, "int": 123, "double": 12.34, @@ -524,7 +524,7 @@ func TestConvertSimpleBody(t *testing.T) { } func TestConvertMapBody(t *testing.T) { - structuredBody := map[string]interface{}{ + structuredBody := map[string]any{ "true": true, "false": false, "string": "string", @@ -569,7 +569,7 @@ func TestConvertMapBody(t *testing.T) { } func TestConvertArrayBody(t *testing.T) { - structuredBody := []interface{}{ + structuredBody := []any{ true, false, "string", @@ -586,8 +586,8 @@ func TestConvertArrayBody(t *testing.T) { uint64(1), float32(1), float64(1), - []interface{}{"string", 1}, - map[string]interface{}{"one": 1, "yes": true}, + []any{"string", 1}, + map[string]any{"one": 1, "yes": true}, } result := anyToBody(structuredBody).Slice() @@ -634,9 +634,9 @@ func TestConvertUnknownBody(t *testing.T) { func TestConvertNestedMapBody(t *testing.T) { unknownType := map[string]int{"0": 0, "1": 1} - structuredBody := map[string]interface{}{ - "array": []interface{}{0, 1}, - "map": map[string]interface{}{"0": 0, "1": "one"}, + structuredBody := map[string]any{ + "array": []any{0, 1}, + "map": map[string]any{"0": 0, "1": "one"}, "unknown": unknownType, } @@ -658,7 +658,7 @@ func TestConvertNestedMapBody(t *testing.T) { require.Equal(t, fmt.Sprintf("%v", unknownType), unknownAttVal.Str()) } -func anyToBody(body interface{}) pcommon.Value { +func anyToBody(body any) pcommon.Value { entry := entry.New() entry.Body = body return convert(entry).Body() @@ -885,7 +885,7 @@ func BenchmarkGetResourceID(b *testing.B) { } func BenchmarkGetResourceIDEmptyResource(b *testing.B) { - res := map[string]interface{}{} + res := map[string]any{} b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -894,7 +894,7 @@ func BenchmarkGetResourceIDEmptyResource(b *testing.B) { } func BenchmarkGetResourceIDSingleResource(b *testing.B) { - res := map[string]interface{}{ + res := map[string]any{ "resource": "value", } b.ReportAllocs() @@ -905,9 +905,9 @@ func BenchmarkGetResourceIDSingleResource(b *testing.B) { } func BenchmarkGetResourceIDComplexResource(b *testing.B) { - res := map[string]interface{}{ + res := map[string]any{ "resource": "value", - "object": map[string]interface{}{ + "object": map[string]any{ "one": "two", "three": 4, }, @@ -919,8 +919,8 @@ func BenchmarkGetResourceIDComplexResource(b *testing.B) { } } -func getResource() map[string]interface{} { - return map[string]interface{}{ +func getResource() map[string]any { + return map[string]any{ "file.name": "filename.log", "file.directory": "/some_directory", "host.name": "localhost", @@ -954,7 +954,7 @@ func (r resourceIDOutputSlice) Swap(i, j int) { func TestGetResourceID(t *testing.T) { testCases := []struct { name string - input map[string]interface{} + input map[string]any }{ { name: "Typical Resource", @@ -962,28 +962,28 @@ func TestGetResourceID(t *testing.T) { }, { name: "Empty value/key", - input: map[string]interface{}{ + input: map[string]any{ "SomeKey": "", "": "Ooops", }, }, { name: "Empty value/key (reversed)", - input: map[string]interface{}{ + input: map[string]any{ "": "SomeKey", "Ooops": "", }, }, { name: "Ambiguous map 1", - input: map[string]interface{}{ + input: map[string]any{ "AB": "CD", "EF": "G", }, }, { name: "Ambiguous map 2", - input: map[string]interface{}{ + input: map[string]any{ "ABC": "DE", "F": "G", }, @@ -994,7 +994,7 @@ func TestGetResourceID(t *testing.T) { }, { name: "Long resource value", - input: map[string]interface{}{ + input: map[string]any{ "key": "This is a really long resource value; It's so long that the internal pre-allocated buffer doesn't hold it.", }, }, @@ -1019,6 +1019,6 @@ func TestGetResourceID(t *testing.T) { func TestGetResourceIDEmptyAndNilAreEqual(t *testing.T) { nilID := HashResource(nil) - emptyID := HashResource(map[string]interface{}{}) + emptyID := HashResource(map[string]any{}) require.Equal(t, nilID, emptyID) } diff --git a/pkg/stanza/entry/attribute_field.go b/pkg/stanza/entry/attribute_field.go index f177bfe6ae12..aa1be059e45a 100644 --- a/pkg/stanza/entry/attribute_field.go +++ b/pkg/stanza/entry/attribute_field.go @@ -53,7 +53,7 @@ func (f AttributeField) String() string { } // Get will return the attribute value and a boolean indicating if it exists -func (f AttributeField) Get(entry *Entry) (interface{}, bool) { +func (f AttributeField) Get(entry *Entry) (any, bool) { if entry.Attributes == nil { return "", false } @@ -68,7 +68,7 @@ func (f AttributeField) Get(entry *Entry) (interface{}, bool) { } for _, key := range f.Keys[1:] { - currentMap, ok := currentValue.(map[string]interface{}) + currentMap, ok := currentValue.(map[string]any) if !ok { return nil, false } @@ -84,12 +84,12 @@ func (f AttributeField) Get(entry *Entry) (interface{}, bool) { // Set will set a value on an entry's attributes using the field. // If a key already exists, it will be overwritten. -func (f AttributeField) Set(entry *Entry, value interface{}) error { +func (f AttributeField) Set(entry *Entry, value any) error { if entry.Attributes == nil { - entry.Attributes = map[string]interface{}{} + entry.Attributes = map[string]any{} } - mapValue, isMapValue := value.(map[string]interface{}) + mapValue, isMapValue := value.(map[string]any) if isMapValue { f.Merge(entry, mapValue) return nil @@ -112,7 +112,7 @@ func (f AttributeField) Set(entry *Entry, value interface{}) error { // Merge will attempt to merge the contents of a map into an entry's attributes. // It will overwrite any intermediate values as necessary. -func (f AttributeField) Merge(entry *Entry, mapValues map[string]interface{}) { +func (f AttributeField) Merge(entry *Entry, mapValues map[string]any) { currentMap := entry.Attributes for _, key := range f.Keys { @@ -126,7 +126,7 @@ func (f AttributeField) Merge(entry *Entry, mapValues map[string]interface{}) { // Delete removes a value from an entry's attributes using the field. // It will return the deleted value and whether the field existed. -func (f AttributeField) Delete(entry *Entry) (interface{}, bool) { +func (f AttributeField) Delete(entry *Entry) (any, bool) { if entry.Attributes == nil { return "", false } @@ -149,7 +149,7 @@ func (f AttributeField) Delete(entry *Entry) (interface{}, bool) { return currentValue, true } - currentMap, ok = currentValue.(map[string]interface{}) + currentMap, ok = currentValue.(map[string]any) if !ok { break } @@ -183,7 +183,7 @@ func (f *AttributeField) UnmarshalJSON(raw []byte) error { } // UnmarshalYAML will attempt to unmarshal a field from YAML. -func (f *AttributeField) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (f *AttributeField) UnmarshalYAML(unmarshal func(any) error) error { var value string if err := unmarshal(&value); err != nil { return fmt.Errorf("the field is not a string: %w", err) diff --git a/pkg/stanza/entry/attribute_field_test.go b/pkg/stanza/entry/attribute_field_test.go index cbb8c24ddf0a..ade5c61bd999 100644 --- a/pkg/stanza/entry/attribute_field_test.go +++ b/pkg/stanza/entry/attribute_field_test.go @@ -17,8 +17,8 @@ func TestAttributeFieldGet(t *testing.T) { cases := []struct { name string field Field - attributes map[string]interface{} - expected interface{} + attributes map[string]any + expected any expectedOK bool }{ { @@ -38,7 +38,7 @@ func TestAttributeFieldGet(t *testing.T) { { "Simple", NewAttributeField("test"), - map[string]interface{}{ + map[string]any{ "test": "val", }, "val", @@ -47,7 +47,7 @@ func TestAttributeFieldGet(t *testing.T) { { "NonexistentKey", NewAttributeField("nonexistent"), - map[string]interface{}{ + map[string]any{ "test": "val", }, nil, @@ -98,9 +98,9 @@ func TestAttributeFieldDelete(t *testing.T) { cases := []struct { name string field Field - attributes map[string]interface{} - expectedAttributes map[string]interface{} - expectedReturned interface{} + attributes map[string]any + expectedAttributes map[string]any + expectedReturned any expectedOK bool }{ { @@ -115,7 +115,7 @@ func TestAttributeFieldDelete(t *testing.T) { "SimpleKey", NewAttributeField("simple_key"), testMap(), - map[string]interface{}{ + map[string]any{ "map_key": nestedMap(), }, "simple_value", @@ -124,9 +124,9 @@ func TestAttributeFieldDelete(t *testing.T) { { "EmptyAttributesAndField", NewAttributeField(), - map[string]interface{}{}, + map[string]any{}, nil, - map[string]interface{}{}, + map[string]any{}, true, }, { @@ -149,9 +149,9 @@ func TestAttributeFieldDelete(t *testing.T) { "NestedKey", NewAttributeField("map_key", "nested_key"), testMap(), - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", - "map_key": map[string]interface{}{}, + "map_key": map[string]any{}, }, "nested_value", true, @@ -160,7 +160,7 @@ func TestAttributeFieldDelete(t *testing.T) { "MapKey", NewAttributeField("map_key"), testMap(), - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", }, nestedMap(), @@ -192,9 +192,9 @@ func TestAttributeFieldSet(t *testing.T) { cases := []struct { name string field Field - attributes map[string]interface{} - val interface{} - expected map[string]interface{} + attributes map[string]any + val any + expected map[string]any expectedErr bool }{ { @@ -202,7 +202,7 @@ func TestAttributeFieldSet(t *testing.T) { NewAttributeField("test"), nil, "val", - map[string]interface{}{ + map[string]any{ "test": "val", }, false, @@ -218,7 +218,7 @@ func TestAttributeFieldSet(t *testing.T) { { "OverwriteRootWithMap", NewAttributeField(), - map[string]interface{}{}, + map[string]any{}, testMap(), testMap(), false, @@ -226,12 +226,12 @@ func TestAttributeFieldSet(t *testing.T) { { "MergeOverRoot", NewAttributeField(), - map[string]interface{}{ + map[string]any{ "simple_key": "clobbered", "hello": "world", }, testMap(), - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", "map_key": nestedMap(), "hello": "world", @@ -241,9 +241,9 @@ func TestAttributeFieldSet(t *testing.T) { { "Simple", NewAttributeField("test"), - map[string]interface{}{}, + map[string]any{}, "val", - map[string]interface{}{ + map[string]any{ "test": "val", }, false, @@ -251,11 +251,11 @@ func TestAttributeFieldSet(t *testing.T) { { "OverwriteString", NewAttributeField("test"), - map[string]interface{}{ + map[string]any{ "test": "original", }, "val", - map[string]interface{}{ + map[string]any{ "test": "val", }, false, @@ -263,9 +263,9 @@ func TestAttributeFieldSet(t *testing.T) { { "NonString", NewAttributeField("test"), - map[string]interface{}{}, + map[string]any{}, 123, - map[string]interface{}{ + map[string]any{ "test": 123, }, false, @@ -273,12 +273,12 @@ func TestAttributeFieldSet(t *testing.T) { { "Map", NewAttributeField("test"), - map[string]interface{}{}, - map[string]interface{}{ + map[string]any{}, + map[string]any{ "test": 123, }, - map[string]interface{}{ - "test": map[string]interface{}{ + map[string]any{ + "test": map[string]any{ "test": 123, }, }, @@ -287,7 +287,7 @@ func TestAttributeFieldSet(t *testing.T) { { "NewMapValue", NewAttributeField(), - map[string]interface{}{}, + map[string]any{}, testMap(), testMap(), false, @@ -295,9 +295,9 @@ func TestAttributeFieldSet(t *testing.T) { { "NewRootField", NewAttributeField("new_key"), - map[string]interface{}{}, + map[string]any{}, "new_value", - map[string]interface{}{ + map[string]any{ "new_key": "new_value", }, false, @@ -305,10 +305,10 @@ func TestAttributeFieldSet(t *testing.T) { { "NewNestedField", NewAttributeField("new_key", "nested_key"), - map[string]interface{}{}, + map[string]any{}, "nested_value", - map[string]interface{}{ - "new_key": map[string]interface{}{ + map[string]any{ + "new_key": map[string]any{ "nested_key": "nested_value", }, }, @@ -319,7 +319,7 @@ func TestAttributeFieldSet(t *testing.T) { NewAttributeField("map_key"), testMap(), "new_value", - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", "map_key": "new_value", }, @@ -329,12 +329,12 @@ func TestAttributeFieldSet(t *testing.T) { "MergedNestedValue", NewAttributeField("map_key"), testMap(), - map[string]interface{}{ + map[string]any{ "merged_key": "merged_value", }, - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", - "map_key": map[string]interface{}{ + "map_key": map[string]any{ "nested_key": "nested_value", "merged_key": "merged_value", }, @@ -377,11 +377,11 @@ func TestAttributeFieldChild(t *testing.T) { func TestAttributeFieldMerge(t *testing.T) { entry := &Entry{} - entry.Attributes = map[string]interface{}{"old": "values"} + entry.Attributes = map[string]any{"old": "values"} field := AttributeField{[]string{"embedded"}} - values := map[string]interface{}{"new": "values"} + values := map[string]any{"new": "values"} field.Merge(entry, values) - expected := map[string]interface{}{"embedded": values, "old": "values"} + expected := map[string]any{"embedded": values, "old": "values"} require.Equal(t, expected, entry.Attributes) } diff --git a/pkg/stanza/entry/body_field.go b/pkg/stanza/entry/body_field.go index 7913c7b01b14..4db2363b4980 100644 --- a/pkg/stanza/entry/body_field.go +++ b/pkg/stanza/entry/body_field.go @@ -54,11 +54,11 @@ func (f BodyField) String() string { // Get will retrieve a value from an entry's body using the field. // It will return the value and whether the field existed. -func (f BodyField) Get(entry *Entry) (interface{}, bool) { - var currentValue interface{} = entry.Body +func (f BodyField) Get(entry *Entry) (any, bool) { + var currentValue = entry.Body for _, key := range f.Keys { - currentMap, ok := currentValue.(map[string]interface{}) + currentMap, ok := currentValue.(map[string]any) if !ok { return nil, false } @@ -74,8 +74,8 @@ func (f BodyField) Get(entry *Entry) (interface{}, bool) { // Set will set a value on an entry's body using the field. // If a key already exists, it will be overwritten. -func (f BodyField) Set(entry *Entry, value interface{}) error { - mapValue, isMapValue := value.(map[string]interface{}) +func (f BodyField) Set(entry *Entry, value any) error { + mapValue, isMapValue := value.(map[string]any) if isMapValue { f.Merge(entry, mapValue) return nil @@ -86,9 +86,9 @@ func (f BodyField) Set(entry *Entry, value interface{}) error { return nil } - currentMap, ok := entry.Body.(map[string]interface{}) + currentMap, ok := entry.Body.(map[string]any) if !ok { - currentMap = map[string]interface{}{} + currentMap = map[string]any{} entry.Body = currentMap } @@ -104,10 +104,10 @@ func (f BodyField) Set(entry *Entry, value interface{}) error { // Merge will attempt to merge the contents of a map into an entry's body. // It will overwrite any intermediate values as necessary. -func (f BodyField) Merge(entry *Entry, mapValues map[string]interface{}) { - currentMap, ok := entry.Body.(map[string]interface{}) +func (f BodyField) Merge(entry *Entry, mapValues map[string]any) { + currentMap, ok := entry.Body.(map[string]any) if !ok { - currentMap = map[string]interface{}{} + currentMap = map[string]any{} entry.Body = currentMap } @@ -122,7 +122,7 @@ func (f BodyField) Merge(entry *Entry, mapValues map[string]interface{}) { // Delete removes a value from an entry's body using the field. // It will return the deleted value and whether the field existed. -func (f BodyField) Delete(entry *Entry) (interface{}, bool) { +func (f BodyField) Delete(entry *Entry) (any, bool) { if f.isRoot() { oldBody := entry.Body entry.Body = nil @@ -131,7 +131,7 @@ func (f BodyField) Delete(entry *Entry) (interface{}, bool) { currentValue := entry.Body for i, key := range f.Keys { - currentMap, ok := currentValue.(map[string]interface{}) + currentMap, ok := currentValue.(map[string]any) if !ok { break } @@ -175,7 +175,7 @@ func (f *BodyField) UnmarshalJSON(raw []byte) error { } // UnmarshalYAML will attempt to unmarshal a field from YAML. -func (f *BodyField) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (f *BodyField) UnmarshalYAML(unmarshal func(any) error) error { var value string if err := unmarshal(&value); err != nil { return fmt.Errorf("the field is not a string: %w", err) diff --git a/pkg/stanza/entry/body_field_test.go b/pkg/stanza/entry/body_field_test.go index 80c56912c1ef..66100bb33adf 100644 --- a/pkg/stanza/entry/body_field_test.go +++ b/pkg/stanza/entry/body_field_test.go @@ -13,15 +13,15 @@ import ( yaml "gopkg.in/yaml.v2" ) -func testMap() map[string]interface{} { - return map[string]interface{}{ +func testMap() map[string]any { + return map[string]any{ "simple_key": "simple_value", "map_key": nestedMap(), } } -func nestedMap() map[string]interface{} { - return map[string]interface{}{ +func nestedMap() map[string]any { + return map[string]any{ "nested_key": "nested_value", } } @@ -30,8 +30,8 @@ func TestNewBodyFieldGet(t *testing.T) { cases := []struct { name string field Field - body interface{} - expectedVal interface{} + body any + expectedVal any expectedOk bool }{ { @@ -105,16 +105,16 @@ func TestBodyFieldDelete(t *testing.T) { cases := []struct { name string field Field - body interface{} - expectedBody interface{} - expectedReturned interface{} + body any + expectedBody any + expectedReturned any expectedOk bool }{ { "SimpleKey", NewBodyField("simple_key"), testMap(), - map[string]interface{}{ + map[string]any{ "map_key": nestedMap(), }, "simple_value", @@ -123,9 +123,9 @@ func TestBodyFieldDelete(t *testing.T) { { "EmptyBodyAndField", NewBodyField(), - map[string]interface{}{}, + map[string]any{}, nil, - map[string]interface{}{}, + map[string]any{}, true, }, { @@ -148,9 +148,9 @@ func TestBodyFieldDelete(t *testing.T) { "NestedKey", NewBodyField("map_key", "nested_key"), testMap(), - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", - "map_key": map[string]interface{}{}, + "map_key": map[string]any{}, }, "nested_value", true, @@ -159,7 +159,7 @@ func TestBodyFieldDelete(t *testing.T) { "MapKey", NewBodyField("map_key"), testMap(), - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", }, nestedMap(), @@ -191,9 +191,9 @@ func TestBodyFieldSet(t *testing.T) { cases := []struct { name string field Field - body interface{} - setTo interface{} - expectedVal interface{} + body any + setTo any + expectedVal any }{ { "OverwriteMap", @@ -214,8 +214,8 @@ func TestBodyFieldSet(t *testing.T) { NewBodyField("embedded", "field"), "raw_value", "new_value", - map[string]interface{}{ - "embedded": map[string]interface{}{ + map[string]any{ + "embedded": map[string]any{ "field": "new_value", }, }, @@ -223,26 +223,26 @@ func TestBodyFieldSet(t *testing.T) { { "NewMapValue", NewBodyField(), - map[string]interface{}{}, + map[string]any{}, testMap(), testMap(), }, { "NewRootField", NewBodyField("new_key"), - map[string]interface{}{}, + map[string]any{}, "new_value", - map[string]interface{}{ + map[string]any{ "new_key": "new_value", }, }, { "NewNestedField", NewBodyField("new_key", "nested_key"), - map[string]interface{}{}, + map[string]any{}, "nested_value", - map[string]interface{}{ - "new_key": map[string]interface{}{ + map[string]any{ + "new_key": map[string]any{ "nested_key": "nested_value", }, }, @@ -252,7 +252,7 @@ func TestBodyFieldSet(t *testing.T) { NewBodyField("map_key"), testMap(), "new_value", - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", "map_key": "new_value", }, @@ -261,12 +261,12 @@ func TestBodyFieldSet(t *testing.T) { "MergedNestedValue", NewBodyField("map_key"), testMap(), - map[string]interface{}{ + map[string]any{ "merged_key": "merged_value", }, - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", - "map_key": map[string]interface{}{ + "map_key": map[string]any{ "nested_key": "nested_value", "merged_key": "merged_value", }, @@ -305,9 +305,9 @@ func TestBodyFieldMerge(t *testing.T) { entry := &Entry{} entry.Body = "raw_value" field := BodyField{[]string{"embedded"}} - values := map[string]interface{}{"new": "values"} + values := map[string]any{"new": "values"} field.Merge(entry, values) - expected := map[string]interface{}{"embedded": values} + expected := map[string]any{"embedded": values} require.Equal(t, expected, entry.Body) } diff --git a/pkg/stanza/entry/copy.go b/pkg/stanza/entry/copy.go index 07e5862b9639..5b7b610c3f1d 100644 --- a/pkg/stanza/entry/copy.go +++ b/pkg/stanza/entry/copy.go @@ -6,13 +6,13 @@ package entry // import "github.com/open-telemetry/opentelemetry-collector-contr import "encoding/json" // copyValue will deep copy a value based on its type. -func copyValue(v interface{}) interface{} { +func copyValue(v any) any { switch value := v.(type) { case string, int, bool, byte, nil: return value case map[string]string: return copyStringMap(value) - case map[string]interface{}: + case map[string]any: return copyInterfaceMap(value) case []string: return copyStringArray(value) @@ -20,7 +20,7 @@ func copyValue(v interface{}) interface{} { return copyByteArray(value) case []int: return copyIntArray(value) - case []interface{}: + case []any: return copyInterfaceArray(value) default: return copyUnknown(value) @@ -37,8 +37,8 @@ func copyStringMap(m map[string]string) map[string]string { } // copyInterfaceMap will deep copy a map of interfaces. -func copyInterfaceMap(m map[string]interface{}) map[string]interface{} { - mapCopy := make(map[string]interface{}) +func copyInterfaceMap(m map[string]any) map[string]any { + mapCopy := make(map[string]any) for k, v := range m { mapCopy[k] = copyValue(v) } @@ -67,8 +67,8 @@ func copyIntArray(a []int) []int { } // copyInterfaceArray will deep copy an array of interfaces. -func copyInterfaceArray(a []interface{}) []interface{} { - arrayCopy := make([]interface{}, 0, len(a)) +func copyInterfaceArray(a []any) []any { + arrayCopy := make([]any, 0, len(a)) for _, v := range a { arrayCopy = append(arrayCopy, copyValue(v)) } @@ -77,8 +77,8 @@ func copyInterfaceArray(a []interface{}) []interface{} { // copyUnknown will copy an unknown value using json encoding. // If this process fails, the result will be an empty interface. -func copyUnknown(value interface{}) interface{} { - var result interface{} +func copyUnknown(value any) any { + var result any b, _ := json.Marshal(value) _ = json.Unmarshal(b, &result) return result diff --git a/pkg/stanza/entry/copy_test.go b/pkg/stanza/entry/copy_test.go index 65bb903f2ba4..27cec125551f 100644 --- a/pkg/stanza/entry/copy_test.go +++ b/pkg/stanza/entry/copy_test.go @@ -30,7 +30,7 @@ func TestCopyValueByte(t *testing.T) { } func TestCopyValueNil(t *testing.T) { - var value interface{} + var value any require.Equal(t, nil, copyValue(value)) } @@ -50,7 +50,7 @@ func TestCopyValueByteArray(t *testing.T) { } func TestCopyValueInterfaceArray(t *testing.T) { - value := []interface{}{"test", true, 5} + value := []any{"test", true, 5} require.Equal(t, value, copyValue(value)) } @@ -60,7 +60,7 @@ func TestCopyValueStringMap(t *testing.T) { } func TestCopyValueInterfaceMap(t *testing.T) { - value := map[string]interface{}{"test": 5} + value := map[string]any{"test": 5} require.Equal(t, value, copyValue(value)) } @@ -72,7 +72,7 @@ func TestCopyValueUnknown(t *testing.T) { Test: "value", } copiedValue := copyValue(unknownValue) - expectedValue := map[string]interface{}{ + expectedValue := map[string]any{ "Test": "value", } require.Equal(t, expectedValue, copiedValue) @@ -88,7 +88,7 @@ func TestCopyStringMap(t *testing.T) { } func TestCopyInterfaceMap(t *testing.T) { - stringMap := map[string]interface{}{ + stringMap := map[string]any{ "message": "test", } copiedMap := copyInterfaceMap(stringMap) @@ -118,10 +118,10 @@ func TestCopyIntArray(t *testing.T) { } func TestCopyInterfaceArray(t *testing.T) { - interfaceArray := []interface{}{"test", 0, true} + interfaceArray := []any{"test", 0, true} copiedArray := copyInterfaceArray(interfaceArray) interfaceArray[0] = "new" - require.Equal(t, []interface{}{"test", 0, true}, copiedArray) + require.Equal(t, []any{"test", 0, true}, copiedArray) } func TestCopyUnknownValueValid(t *testing.T) { @@ -132,17 +132,17 @@ func TestCopyUnknownValueValid(t *testing.T) { Test: "value", } copiedValue := copyUnknown(unknownValue) - expectedValue := map[string]interface{}{ + expectedValue := map[string]any{ "Test": "value", } require.Equal(t, expectedValue, copiedValue) } func TestCopyUnknownValueInalid(t *testing.T) { - unknownValue := map[string]interface{}{ + unknownValue := map[string]any{ "foo": make(chan int), } copiedValue := copyUnknown(unknownValue) - var expectedValue interface{} + var expectedValue any require.Equal(t, expectedValue, copiedValue) } diff --git a/pkg/stanza/entry/entry.go b/pkg/stanza/entry/entry.go index 98c1611151f5..882f22695f41 100644 --- a/pkg/stanza/entry/entry.go +++ b/pkg/stanza/entry/entry.go @@ -12,17 +12,17 @@ var timeNow = time.Now // Entry is a flexible representation of log data associated with a timestamp. type Entry struct { - ObservedTimestamp time.Time `json:"observed_timestamp" yaml:"observed_timestamp"` - Timestamp time.Time `json:"timestamp" yaml:"timestamp"` - Body interface{} `json:"body" yaml:"body"` - Attributes map[string]interface{} `json:"attributes,omitempty" yaml:"attributes,omitempty"` - Resource map[string]interface{} `json:"resource,omitempty" yaml:"resource,omitempty"` - SeverityText string `json:"severity_text,omitempty" yaml:"severity_text,omitempty"` - SpanID []byte `json:"span_id,omitempty" yaml:"span_id,omitempty"` - TraceID []byte `json:"trace_id,omitempty" yaml:"trace_id,omitempty"` - TraceFlags []byte `json:"trace_flags,omitempty" yaml:"trace_flags,omitempty"` - Severity Severity `json:"severity" yaml:"severity"` - ScopeName string `json:"scope_name" yaml:"scope_name"` + ObservedTimestamp time.Time `json:"observed_timestamp" yaml:"observed_timestamp"` + Timestamp time.Time `json:"timestamp" yaml:"timestamp"` + Body any `json:"body" yaml:"body"` + Attributes map[string]any `json:"attributes,omitempty" yaml:"attributes,omitempty"` + Resource map[string]any `json:"resource,omitempty" yaml:"resource,omitempty"` + SeverityText string `json:"severity_text,omitempty" yaml:"severity_text,omitempty"` + SpanID []byte `json:"span_id,omitempty" yaml:"span_id,omitempty"` + TraceID []byte `json:"trace_id,omitempty" yaml:"trace_id,omitempty"` + TraceFlags []byte `json:"trace_flags,omitempty" yaml:"trace_flags,omitempty"` + Severity Severity `json:"severity" yaml:"severity"` + ScopeName string `json:"scope_name" yaml:"scope_name"` } // New will create a new log entry with current timestamp and an empty body. @@ -35,7 +35,7 @@ func New() *Entry { // AddAttribute will add a key/value pair to the entry's attributes. func (entry *Entry) AddAttribute(key, value string) { if entry.Attributes == nil { - entry.Attributes = make(map[string]interface{}) + entry.Attributes = make(map[string]any) } entry.Attributes[key] = value } @@ -43,36 +43,36 @@ func (entry *Entry) AddAttribute(key, value string) { // AddResourceKey wil add a key/value pair to the entry's resource. func (entry *Entry) AddResourceKey(key, value string) { if entry.Resource == nil { - entry.Resource = make(map[string]interface{}) + entry.Resource = make(map[string]any) } entry.Resource[key] = value } // Get will return the value of a field on the entry, including a boolean indicating if the field exists. -func (entry *Entry) Get(field FieldInterface) (interface{}, bool) { +func (entry *Entry) Get(field FieldInterface) (any, bool) { return field.Get(entry) } // Set will set the value of a field on the entry. -func (entry *Entry) Set(field FieldInterface, val interface{}) error { +func (entry *Entry) Set(field FieldInterface, val any) error { return field.Set(entry, val) } // Delete will delete a field from the entry. -func (entry *Entry) Delete(field FieldInterface) (interface{}, bool) { +func (entry *Entry) Delete(field FieldInterface) (any, bool) { return field.Delete(entry) } // Read will read the value of a field into a designated interface. -func (entry *Entry) Read(field FieldInterface, dest interface{}) error { +func (entry *Entry) Read(field FieldInterface, dest any) error { switch dest := dest.(type) { case *string: return entry.readToString(field, dest) - case *map[string]interface{}: + case *map[string]any: return entry.readToInterfaceMap(field, dest) case *map[string]string: return entry.readToStringMap(field, dest) - case *interface{}: + case *any: return entry.readToInterface(field, dest) default: return fmt.Errorf("can not read to unsupported type '%T'", dest) @@ -80,10 +80,10 @@ func (entry *Entry) Read(field FieldInterface, dest interface{}) error { } // readToInterface reads a field to a designated interface pointer. -func (entry *Entry) readToInterface(field FieldInterface, dest *interface{}) error { +func (entry *Entry) readToInterface(field FieldInterface, dest *any) error { val, ok := entry.Get(field) if !ok { - return fmt.Errorf("field '%s' is missing and can not be read as a interface{}", field) + return fmt.Errorf("field '%s' is missing and can not be read as a any", field) } *dest = val @@ -110,16 +110,16 @@ func (entry *Entry) readToString(field FieldInterface, dest *string) error { } // readToInterfaceMap reads a field to a designated map interface pointer. -func (entry *Entry) readToInterfaceMap(field FieldInterface, dest *map[string]interface{}) error { +func (entry *Entry) readToInterfaceMap(field FieldInterface, dest *map[string]any) error { val, ok := entry.Get(field) if !ok { - return fmt.Errorf("field '%s' is missing and can not be read as a map[string]interface{}", field) + return fmt.Errorf("field '%s' is missing and can not be read as a map[string]any", field) } - if m, ok := val.(map[string]interface{}); ok { + if m, ok := val.(map[string]any); ok { *dest = m } else { - return fmt.Errorf("field '%s' of type '%T' can not be cast to a map[string]interface{}", field, val) + return fmt.Errorf("field '%s' of type '%T' can not be cast to a map[string]any", field, val) } return nil @@ -133,7 +133,7 @@ func (entry *Entry) readToStringMap(field FieldInterface, dest *map[string]strin } switch m := val.(type) { - case map[string]interface{}: + case map[string]any: newDest := make(map[string]string) for k, v := range m { if vStr, ok := v.(string); ok { @@ -143,7 +143,7 @@ func (entry *Entry) readToStringMap(field FieldInterface, dest *map[string]strin } } *dest = newDest - case map[interface{}]interface{}: + case map[any]any: newDest := make(map[string]string) for k, v := range m { keyStr, ok := k.(string) diff --git a/pkg/stanza/entry/entry_test.go b/pkg/stanza/entry/entry_test.go index 07f852a029ec..702b0b2e8bba 100644 --- a/pkg/stanza/entry/entry_test.go +++ b/pkg/stanza/entry/entry_test.go @@ -12,25 +12,25 @@ import ( func TestRead(t *testing.T) { testEntry := &Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "string_field": "string_val", "byte_field": []byte(`test`), - "map_string_interface_field": map[string]interface{}{ + "map_string_interface_field": map[string]any{ "nested": "interface_val", }, - "map_string_interface_nonstring_field": map[string]interface{}{ + "map_string_interface_nonstring_field": map[string]any{ "nested": 111, }, "map_string_string_field": map[string]string{ "nested": "string_val", }, - "map_interface_interface_field": map[interface{}]interface{}{ + "map_interface_interface_field": map[any]any{ "nested": "interface_val", }, - "map_interface_interface_nonstring_key_field": map[interface{}]interface{}{ + "map_interface_interface_nonstring_key_field": map[any]any{ 100: "interface_val", }, - "map_interface_interface_nonstring_value_field": map[interface{}]interface{}{ + "map_interface_interface_nonstring_value_field": map[any]any{ "nested": 100, }, }, @@ -61,56 +61,56 @@ func TestRead(t *testing.T) { require.Error(t, err) }) - t.Run("map[string]interface{}", func(t *testing.T) { - var m map[string]interface{} + t.Run("map[string]any", func(t *testing.T) { + var m map[string]any err := testEntry.Read(NewBodyField("map_string_interface_field"), &m) require.NoError(t, err) - require.Equal(t, map[string]interface{}{"nested": "interface_val"}, m) + require.Equal(t, map[string]any{"nested": "interface_val"}, m) }) - t.Run("map[string]interface{} error", func(t *testing.T) { - var m map[string]interface{} + t.Run("map[string]any error", func(t *testing.T) { + var m map[string]any err := testEntry.Read(NewBodyField("string_field"), &m) require.Error(t, err) }) - t.Run("map[string]string from map[string]interface{}", func(t *testing.T) { + t.Run("map[string]string from map[string]any", func(t *testing.T) { var m map[string]string err := testEntry.Read(NewBodyField("map_string_interface_field"), &m) require.NoError(t, err) require.Equal(t, map[string]string{"nested": "interface_val"}, m) }) - t.Run("map[string]string from map[string]interface{} err", func(t *testing.T) { + t.Run("map[string]string from map[string]any err", func(t *testing.T) { var m map[string]string err := testEntry.Read(NewBodyField("map_string_interface_nonstring_field"), &m) require.Error(t, err) }) - t.Run("map[string]string from map[interface{}]interface{}", func(t *testing.T) { + t.Run("map[string]string from map[any]any", func(t *testing.T) { var m map[string]string err := testEntry.Read(NewBodyField("map_interface_interface_field"), &m) require.NoError(t, err) require.Equal(t, map[string]string{"nested": "interface_val"}, m) }) - t.Run("map[string]string from map[interface{}]interface{} nonstring key error", func(t *testing.T) { + t.Run("map[string]string from map[any]any nonstring key error", func(t *testing.T) { var m map[string]string err := testEntry.Read(NewBodyField("map_interface_interface_nonstring_key_field"), &m) require.Error(t, err) }) - t.Run("map[string]string from map[interface{}]interface{} nonstring value error", func(t *testing.T) { + t.Run("map[string]string from map[any]any nonstring value error", func(t *testing.T) { var m map[string]string err := testEntry.Read(NewBodyField("map_interface_interface_nonstring_value_field"), &m) require.Error(t, err) }) - t.Run("interface{} from any", func(t *testing.T) { - var i interface{} + t.Run("any from any", func(t *testing.T) { + var i any err := testEntry.Read(NewBodyField("map_interface_interface_field"), &i) require.NoError(t, err) - require.Equal(t, map[interface{}]interface{}{"nested": "interface_val"}, i) + require.Equal(t, map[any]any{"nested": "interface_val"}, i) }) t.Run("string from []byte", func(t *testing.T) { @@ -130,8 +130,8 @@ func TestCopy(t *testing.T) { entry.ObservedTimestamp = now entry.Timestamp = time.Time{} entry.Body = "test" - entry.Attributes = map[string]interface{}{"label": "value"} - entry.Resource = map[string]interface{}{"resource": "value"} + entry.Attributes = map[string]any{"label": "value"} + entry.Resource = map[string]any{"resource": "value"} entry.TraceID = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f} entry.SpanID = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08} entry.TraceFlags = []byte{0x01} @@ -142,8 +142,8 @@ func TestCopy(t *testing.T) { entry.SeverityText = "1" entry.Timestamp = time.Now() entry.Body = "new" - entry.Attributes = map[string]interface{}{"label": "new value"} - entry.Resource = map[string]interface{}{"resource": "new value"} + entry.Attributes = map[string]any{"label": "new value"} + entry.Resource = map[string]any{"resource": "new value"} entry.TraceID[0] = 0xff entry.SpanID[0] = 0xff entry.TraceFlags[0] = 0xff @@ -153,8 +153,8 @@ func TestCopy(t *testing.T) { require.Equal(t, time.Time{}, cp.Timestamp) require.Equal(t, Severity(0), cp.Severity) require.Equal(t, "ok", cp.SeverityText) - require.Equal(t, map[string]interface{}{"label": "value"}, cp.Attributes) - require.Equal(t, map[string]interface{}{"resource": "value"}, cp.Resource) + require.Equal(t, map[string]any{"label": "value"}, cp.Attributes) + require.Equal(t, map[string]any{"resource": "value"}, cp.Resource) require.Equal(t, "test", cp.Body) require.Equal(t, []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, cp.TraceID) require.Equal(t, []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, cp.SpanID) @@ -172,8 +172,8 @@ func TestCopyNil(t *testing.T) { entry.SeverityText = "1" entry.Timestamp = time.Now() entry.Body = "new" - entry.Attributes = map[string]interface{}{"label": "new value"} - entry.Resource = map[string]interface{}{"resource": "new value"} + entry.Attributes = map[string]any{"label": "new value"} + entry.Resource = map[string]any{"resource": "new value"} entry.TraceID = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f} entry.SpanID = []byte{0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x01, 0x02, 0x03} entry.TraceFlags = []byte{0x01} @@ -183,8 +183,8 @@ func TestCopyNil(t *testing.T) { require.Equal(t, time.Time{}, cp.Timestamp) require.Equal(t, Severity(0), cp.Severity) require.Equal(t, "", cp.SeverityText) - require.Equal(t, map[string]interface{}{}, cp.Attributes) - require.Equal(t, map[string]interface{}{}, cp.Resource) + require.Equal(t, map[string]any{}, cp.Attributes) + require.Equal(t, map[string]any{}, cp.Resource) require.Equal(t, nil, cp.Body) require.Equal(t, []byte{}, cp.TraceID) require.Equal(t, []byte{}, cp.SpanID) @@ -259,24 +259,24 @@ func TestFieldFromString(t *testing.T) { func TestAddAttribute(t *testing.T) { entry := Entry{} entry.AddAttribute("label", "value") - expected := map[string]interface{}{"label": "value"} + expected := map[string]any{"label": "value"} require.Equal(t, expected, entry.Attributes) } func TestAddResourceKey(t *testing.T) { entry := Entry{} entry.AddResourceKey("key", "value") - expected := map[string]interface{}{"key": "value"} + expected := map[string]any{"key": "value"} require.Equal(t, expected, entry.Resource) } func TestReadToInterfaceMapWithMissingField(t *testing.T) { entry := Entry{} field := NewAttributeField("label") - dest := map[string]interface{}{} + dest := map[string]any{} err := entry.readToInterfaceMap(field, &dest) require.Error(t, err) - require.Contains(t, err.Error(), "can not be read as a map[string]interface{}") + require.Contains(t, err.Error(), "can not be read as a map[string]any") } func TestReadToStringMapWithMissingField(t *testing.T) { @@ -291,10 +291,10 @@ func TestReadToStringMapWithMissingField(t *testing.T) { func TestReadToInterfaceMissingField(t *testing.T) { entry := Entry{} field := NewAttributeField("label") - var dest interface{} + var dest any err := entry.readToInterface(field, &dest) require.Error(t, err) - require.Contains(t, err.Error(), "can not be read as a interface{}") + require.Contains(t, err.Error(), "can not be read as a any") } func TestDefaultTimestamps(t *testing.T) { diff --git a/pkg/stanza/entry/field.go b/pkg/stanza/entry/field.go index 170aea25ba9e..c2007c2646a2 100644 --- a/pkg/stanza/entry/field.go +++ b/pkg/stanza/entry/field.go @@ -29,9 +29,9 @@ type RootableField struct { // FieldInterface is a field on an entry. type FieldInterface interface { - Get(*Entry) (interface{}, bool) - Set(entry *Entry, value interface{}) error - Delete(entry *Entry) (interface{}, bool) + Get(*Entry) (any, bool) + Set(entry *Entry, value any) error + Delete(entry *Entry) (any, bool) String() string } @@ -59,7 +59,7 @@ func (r *RootableField) UnmarshalJSON(raw []byte) error { } // UnmarshalYAML will unmarshal a field from YAML -func (f *Field) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (f *Field) UnmarshalYAML(unmarshal func(any) error) error { var s string err := unmarshal(&s) if err != nil { @@ -70,7 +70,7 @@ func (f *Field) UnmarshalYAML(unmarshal func(interface{}) error) error { } // UnmarshalYAML will unmarshal a field from YAML -func (r *RootableField) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (r *RootableField) UnmarshalYAML(unmarshal func(any) error) error { var s string err := unmarshal(&s) if err != nil { @@ -251,15 +251,15 @@ func toJSONDot(prefix string, keys []string) string { // getNestedMap will get a nested map assigned to a key. // If the map does not exist, it will create and return it. -func getNestedMap(currentMap map[string]interface{}, key string) map[string]interface{} { +func getNestedMap(currentMap map[string]any, key string) map[string]any { currentValue, ok := currentMap[key] if !ok { - currentMap[key] = map[string]interface{}{} + currentMap[key] = map[string]any{} } - nextMap, ok := currentValue.(map[string]interface{}) + nextMap, ok := currentValue.(map[string]any) if !ok { - nextMap = map[string]interface{}{} + nextMap = map[string]any{} currentMap[key] = nextMap } diff --git a/pkg/stanza/entry/nil_field.go b/pkg/stanza/entry/nil_field.go index 85fa0da3990f..5439c0012b48 100644 --- a/pkg/stanza/entry/nil_field.go +++ b/pkg/stanza/entry/nil_field.go @@ -9,17 +9,17 @@ package entry // import "github.com/open-telemetry/opentelemetry-collector-contr type NilField struct{} // Get will return always return nil -func (l NilField) Get(_ *Entry) (interface{}, bool) { +func (l NilField) Get(_ *Entry) (any, bool) { return nil, true } // Set will do nothing and return no error -func (l NilField) Set(_ *Entry, _ interface{}) error { +func (l NilField) Set(_ *Entry, _ any) error { return nil } // Delete will do nothing and return no error -func (l NilField) Delete(_ *Entry) (interface{}, bool) { +func (l NilField) Delete(_ *Entry) (any, bool) { return nil, true } diff --git a/pkg/stanza/entry/resource_field.go b/pkg/stanza/entry/resource_field.go index 11c16dfeedbe..5e9ebc6d528c 100644 --- a/pkg/stanza/entry/resource_field.go +++ b/pkg/stanza/entry/resource_field.go @@ -53,7 +53,7 @@ func (f ResourceField) String() string { } // Get will return the resource value and a boolean indicating if it exists -func (f ResourceField) Get(entry *Entry) (interface{}, bool) { +func (f ResourceField) Get(entry *Entry) (any, bool) { if entry.Resource == nil { return "", false } @@ -68,7 +68,7 @@ func (f ResourceField) Get(entry *Entry) (interface{}, bool) { } for _, key := range f.Keys[1:] { - currentMap, ok := currentValue.(map[string]interface{}) + currentMap, ok := currentValue.(map[string]any) if !ok { return nil, false } @@ -84,12 +84,12 @@ func (f ResourceField) Get(entry *Entry) (interface{}, bool) { // Set will set a value on an entry's resource using the field. // If a key already exists, it will be overwritten. -func (f ResourceField) Set(entry *Entry, value interface{}) error { +func (f ResourceField) Set(entry *Entry, value any) error { if entry.Resource == nil { - entry.Resource = map[string]interface{}{} + entry.Resource = map[string]any{} } - mapValue, isMapValue := value.(map[string]interface{}) + mapValue, isMapValue := value.(map[string]any) if isMapValue { f.Merge(entry, mapValue) return nil @@ -112,7 +112,7 @@ func (f ResourceField) Set(entry *Entry, value interface{}) error { // Merge will attempt to merge the contents of a map into an entry's resource. // It will overwrite any intermediate values as necessary. -func (f ResourceField) Merge(entry *Entry, mapValues map[string]interface{}) { +func (f ResourceField) Merge(entry *Entry, mapValues map[string]any) { currentMap := entry.Resource for _, key := range f.Keys { @@ -126,7 +126,7 @@ func (f ResourceField) Merge(entry *Entry, mapValues map[string]interface{}) { // Delete removes a value from an entry's resource using the field. // It will return the deleted value and whether the field existed. -func (f ResourceField) Delete(entry *Entry) (interface{}, bool) { +func (f ResourceField) Delete(entry *Entry) (any, bool) { if entry.Resource == nil { return "", false } @@ -149,7 +149,7 @@ func (f ResourceField) Delete(entry *Entry) (interface{}, bool) { return currentValue, true } - currentMap, ok = currentValue.(map[string]interface{}) + currentMap, ok = currentValue.(map[string]any) if !ok { break } @@ -183,7 +183,7 @@ func (f *ResourceField) UnmarshalJSON(raw []byte) error { } // UnmarshalYAML will attempt to unmarshal a field from YAML. -func (f *ResourceField) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (f *ResourceField) UnmarshalYAML(unmarshal func(any) error) error { var value string if err := unmarshal(&value); err != nil { return fmt.Errorf("the field is not a string: %w", err) diff --git a/pkg/stanza/entry/resource_field_test.go b/pkg/stanza/entry/resource_field_test.go index b0411b7cb210..6dbe6c499699 100644 --- a/pkg/stanza/entry/resource_field_test.go +++ b/pkg/stanza/entry/resource_field_test.go @@ -17,8 +17,8 @@ func TestResourceFieldGet(t *testing.T) { cases := []struct { name string field Field - resource map[string]interface{} - expected interface{} + resource map[string]any + expected any expectedOK bool }{ { @@ -38,7 +38,7 @@ func TestResourceFieldGet(t *testing.T) { { "Simple", NewResourceField("test"), - map[string]interface{}{ + map[string]any{ "test": "val", }, "val", @@ -47,7 +47,7 @@ func TestResourceFieldGet(t *testing.T) { { "NonexistentKey", NewResourceField("nonexistent"), - map[string]interface{}{ + map[string]any{ "test": "val", }, nil, @@ -98,9 +98,9 @@ func TestResourceFieldDelete(t *testing.T) { cases := []struct { name string field Field - resource map[string]interface{} - expectedResource map[string]interface{} - expectedReturned interface{} + resource map[string]any + expectedResource map[string]any + expectedReturned any expectedOK bool }{ { @@ -115,7 +115,7 @@ func TestResourceFieldDelete(t *testing.T) { "SimpleKey", NewResourceField("simple_key"), testMap(), - map[string]interface{}{ + map[string]any{ "map_key": nestedMap(), }, "simple_value", @@ -124,9 +124,9 @@ func TestResourceFieldDelete(t *testing.T) { { "EmptyResourceAndField", NewResourceField(), - map[string]interface{}{}, + map[string]any{}, nil, - map[string]interface{}{}, + map[string]any{}, true, }, { @@ -149,9 +149,9 @@ func TestResourceFieldDelete(t *testing.T) { "NestedKey", NewResourceField("map_key", "nested_key"), testMap(), - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", - "map_key": map[string]interface{}{}, + "map_key": map[string]any{}, }, "nested_value", true, @@ -160,7 +160,7 @@ func TestResourceFieldDelete(t *testing.T) { "MapKey", NewResourceField("map_key"), testMap(), - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", }, nestedMap(), @@ -192,9 +192,9 @@ func TestResourceFieldSet(t *testing.T) { cases := []struct { name string field Field - resource map[string]interface{} - val interface{} - expected map[string]interface{} + resource map[string]any + val any + expected map[string]any expectedErr bool }{ { @@ -202,7 +202,7 @@ func TestResourceFieldSet(t *testing.T) { NewResourceField("test"), nil, "val", - map[string]interface{}{ + map[string]any{ "test": "val", }, false, @@ -218,7 +218,7 @@ func TestResourceFieldSet(t *testing.T) { { "OverwriteRootWithMap", NewResourceField(), - map[string]interface{}{}, + map[string]any{}, testMap(), testMap(), false, @@ -226,12 +226,12 @@ func TestResourceFieldSet(t *testing.T) { { "MergeOverRoot", NewResourceField(), - map[string]interface{}{ + map[string]any{ "simple_key": "clobbered", "hello": "world", }, testMap(), - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", "map_key": nestedMap(), "hello": "world", @@ -241,9 +241,9 @@ func TestResourceFieldSet(t *testing.T) { { "Simple", NewResourceField("test"), - map[string]interface{}{}, + map[string]any{}, "val", - map[string]interface{}{ + map[string]any{ "test": "val", }, false, @@ -251,11 +251,11 @@ func TestResourceFieldSet(t *testing.T) { { "OverwriteString", NewResourceField("test"), - map[string]interface{}{ + map[string]any{ "test": "original", }, "val", - map[string]interface{}{ + map[string]any{ "test": "val", }, false, @@ -263,9 +263,9 @@ func TestResourceFieldSet(t *testing.T) { { "NonString", NewResourceField("test"), - map[string]interface{}{}, + map[string]any{}, 123, - map[string]interface{}{ + map[string]any{ "test": 123, }, false, @@ -273,12 +273,12 @@ func TestResourceFieldSet(t *testing.T) { { "Map", NewResourceField("test"), - map[string]interface{}{}, - map[string]interface{}{ + map[string]any{}, + map[string]any{ "test": 123, }, - map[string]interface{}{ - "test": map[string]interface{}{ + map[string]any{ + "test": map[string]any{ "test": 123, }, }, @@ -287,7 +287,7 @@ func TestResourceFieldSet(t *testing.T) { { "NewMapValue", NewResourceField(), - map[string]interface{}{}, + map[string]any{}, testMap(), testMap(), false, @@ -295,9 +295,9 @@ func TestResourceFieldSet(t *testing.T) { { "NewRootField", NewResourceField("new_key"), - map[string]interface{}{}, + map[string]any{}, "new_value", - map[string]interface{}{ + map[string]any{ "new_key": "new_value", }, false, @@ -305,10 +305,10 @@ func TestResourceFieldSet(t *testing.T) { { "NewNestedField", NewResourceField("new_key", "nested_key"), - map[string]interface{}{}, + map[string]any{}, "nested_value", - map[string]interface{}{ - "new_key": map[string]interface{}{ + map[string]any{ + "new_key": map[string]any{ "nested_key": "nested_value", }, }, @@ -319,7 +319,7 @@ func TestResourceFieldSet(t *testing.T) { NewResourceField("map_key"), testMap(), "new_value", - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", "map_key": "new_value", }, @@ -329,12 +329,12 @@ func TestResourceFieldSet(t *testing.T) { "MergedNestedValue", NewResourceField("map_key"), testMap(), - map[string]interface{}{ + map[string]any{ "merged_key": "merged_value", }, - map[string]interface{}{ + map[string]any{ "simple_key": "simple_value", - "map_key": map[string]interface{}{ + "map_key": map[string]any{ "nested_key": "nested_value", "merged_key": "merged_value", }, @@ -377,11 +377,11 @@ func TestResourceFieldChild(t *testing.T) { func TestResourceFieldMerge(t *testing.T) { entry := &Entry{} - entry.Resource = map[string]interface{}{"old": "values"} + entry.Resource = map[string]any{"old": "values"} field := ResourceField{[]string{"embedded"}} - values := map[string]interface{}{"new": "values"} + values := map[string]any{"new": "values"} field.Merge(entry, values) - expected := map[string]interface{}{"embedded": values, "old": "values"} + expected := map[string]any{"embedded": values, "old": "values"} require.Equal(t, expected, entry.Resource) } diff --git a/pkg/stanza/fileconsumer/internal/checkpoint/checkpoint_test.go b/pkg/stanza/fileconsumer/internal/checkpoint/checkpoint_test.go index 406a8b262bd2..fd239efdb755 100644 --- a/pkg/stanza/fileconsumer/internal/checkpoint/checkpoint_test.go +++ b/pkg/stanza/fileconsumer/internal/checkpoint/checkpoint_test.go @@ -76,7 +76,7 @@ func TestNopEncodingDifferentLogSizes(t *testing.T) { { Fingerprint: &fingerprint.Fingerprint{FirstBytes: []byte("foo")}, Offset: 3, - FileAttributes: map[string]interface{}{ + FileAttributes: map[string]any{ "hello": "world", }, }, @@ -88,7 +88,7 @@ func TestNopEncodingDifferentLogSizes(t *testing.T) { { Fingerprint: &fingerprint.Fingerprint{FirstBytes: []byte("ab")}, Offset: 2, - FileAttributes: map[string]interface{}{ + FileAttributes: map[string]any{ "hello2": "world2", }, HeaderFinalized: true, @@ -132,7 +132,7 @@ func TestMigrateHeaderAttributes(t *testing.T) { { Fingerprint: &fingerprint.Fingerprint{FirstBytes: []byte("foo")}, Offset: 3, - FileAttributes: map[string]interface{}{ + FileAttributes: map[string]any{ "hello": "world", }, }, diff --git a/pkg/stanza/operator/config.go b/pkg/stanza/operator/config.go index 553588ec8439..99256be30518 100644 --- a/pkg/stanza/operator/config.go +++ b/pkg/stanza/operator/config.go @@ -58,8 +58,8 @@ func (c *Config) UnmarshalJSON(bytes []byte) error { } // UnmarshalYAML will unmarshal a config from YAML. -func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { - rawConfig := map[string]interface{}{} +func (c *Config) UnmarshalYAML(unmarshal func(any) error) error { + rawConfig := map[string]any{} err := unmarshal(&rawConfig) if err != nil { return fmt.Errorf("failed to unmarshal yaml to base config: %w", err) diff --git a/pkg/stanza/operator/helper/attributer_test.go b/pkg/stanza/operator/helper/attributer_test.go index d21af81da4b1..61203d87b2b6 100644 --- a/pkg/stanza/operator/helper/attributer_test.go +++ b/pkg/stanza/operator/helper/attributer_test.go @@ -32,7 +32,7 @@ func TestAttributer(t *testing.T) { entry.New(), func() *entry.Entry { e := entry.New() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "label1": "value1", } return e @@ -50,7 +50,7 @@ func TestAttributer(t *testing.T) { entry.New(), func() *entry.Entry { e := entry.New() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "label1": "startend", } return e @@ -68,7 +68,7 @@ func TestAttributer(t *testing.T) { entry.New(), func() *entry.Entry { e := entry.New() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "label1": "foo", } return e diff --git a/pkg/stanza/operator/helper/bytesize.go b/pkg/stanza/operator/helper/bytesize.go index 288e5e977529..f4ed7110bbb1 100644 --- a/pkg/stanza/operator/helper/bytesize.go +++ b/pkg/stanza/operator/helper/bytesize.go @@ -20,7 +20,7 @@ func (h *ByteSize) UnmarshalText(text []byte) (err error) { slice[0] = byte('"') slice = append(slice, text...) slice = append(slice, byte('"')) - unmarshal := func(i interface{}) error { + unmarshal := func(i any) error { return json.Unmarshal(slice, &i) } diff --git a/pkg/stanza/operator/helper/expr_string.go b/pkg/stanza/operator/helper/expr_string.go index 3a8abadb49c3..571751e01698 100644 --- a/pkg/stanza/operator/helper/expr_string.go +++ b/pkg/stanza/operator/helper/expr_string.go @@ -107,7 +107,7 @@ type ExprString struct { } // Render will render an ExprString as a string -func (e *ExprString) Render(env map[string]interface{}) (string, error) { +func (e *ExprString) Render(env map[string]any) (string, error) { var b strings.Builder for i := 0; i < len(e.SubExprs); i++ { b.WriteString(e.SubStrings[i]) @@ -142,16 +142,16 @@ func (p *patcher) Visit(node *ast.Node) { } var envPool = sync.Pool{ - New: func() interface{} { - return map[string]interface{}{ + New: func() any { + return map[string]any{ "os_env_func": os.Getenv, } }, } // GetExprEnv returns a map of key/value pairs that can be be used to evaluate an expression -func GetExprEnv(e *entry.Entry) map[string]interface{} { - env := envPool.Get().(map[string]interface{}) +func GetExprEnv(e *entry.Entry) map[string]any { + env := envPool.Get().(map[string]any) env["$"] = e.Body env["body"] = e.Body env["attributes"] = e.Attributes @@ -162,6 +162,6 @@ func GetExprEnv(e *entry.Entry) map[string]interface{} { } // PutExprEnv adds a key/value pair that will can be used to evaluate an expression -func PutExprEnv(e map[string]interface{}) { +func PutExprEnv(e map[string]any) { envPool.Put(e) } diff --git a/pkg/stanza/operator/helper/expr_string_test.go b/pkg/stanza/operator/helper/expr_string_test.go index f8fe3e0b8754..235a26969373 100644 --- a/pkg/stanza/operator/helper/expr_string_test.go +++ b/pkg/stanza/operator/helper/expr_string_test.go @@ -18,10 +18,10 @@ func TestExprString(t *testing.T) { exampleEntry := func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "test": "value", } - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "id": "value", } return e diff --git a/pkg/stanza/operator/helper/identifier_test.go b/pkg/stanza/operator/helper/identifier_test.go index efb2ecc938c7..bba0bfcd0741 100644 --- a/pkg/stanza/operator/helper/identifier_test.go +++ b/pkg/stanza/operator/helper/identifier_test.go @@ -32,7 +32,7 @@ func TestIdentifier(t *testing.T) { entry.New(), func() *entry.Entry { e := entry.New() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key1": "value1", } return e @@ -50,7 +50,7 @@ func TestIdentifier(t *testing.T) { entry.New(), func() *entry.Entry { e := entry.New() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key1": "startend", } return e @@ -68,7 +68,7 @@ func TestIdentifier(t *testing.T) { entry.New(), func() *entry.Entry { e := entry.New() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key1": "foo", } return e diff --git a/pkg/stanza/operator/helper/input.go b/pkg/stanza/operator/helper/input.go index b8cc6951a144..9b6fa5e44c6e 100644 --- a/pkg/stanza/operator/helper/input.go +++ b/pkg/stanza/operator/helper/input.go @@ -62,7 +62,7 @@ type InputOperator struct { } // NewEntry will create a new entry using the `attributes`, and `resource` configuration. -func (i *InputOperator) NewEntry(value interface{}) (*entry.Entry, error) { +func (i *InputOperator) NewEntry(value any) (*entry.Entry, error) { entry := entry.New() entry.Body = value diff --git a/pkg/stanza/operator/helper/parser.go b/pkg/stanza/operator/helper/parser.go index 57c230f39201..56a188086611 100644 --- a/pkg/stanza/operator/helper/parser.go +++ b/pkg/stanza/operator/helper/parser.go @@ -187,4 +187,4 @@ func (p *ParserOperator) ParseWith(ctx context.Context, entry *entry.Entry, pars } // ParseFunction is function that parses a raw value. -type ParseFunction = func(interface{}) (interface{}, error) +type ParseFunction = func(any) (any, error) diff --git a/pkg/stanza/operator/helper/parser_test.go b/pkg/stanza/operator/helper/parser_test.go index 31b948dfdaab..38cf33dadada 100644 --- a/pkg/stanza/operator/helper/parser_test.go +++ b/pkg/stanza/operator/helper/parser_test.go @@ -110,7 +110,7 @@ func TestParserMissingField(t *testing.T) { }, ParseFrom: entry.NewBodyField("test"), } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, nil } ctx := context.Background() @@ -129,7 +129,7 @@ func TestParserInvalidParseDrop(t *testing.T) { }, ParseFrom: entry.NewBodyField(), } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, fmt.Errorf("parse failure") } ctx := context.Background() @@ -149,7 +149,7 @@ func TestParserInvalidParseSend(t *testing.T) { }, ParseFrom: entry.NewBodyField(), } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, fmt.Errorf("parse failure") } ctx := context.Background() @@ -177,7 +177,7 @@ func TestParserInvalidTimeParseDrop(t *testing.T) { }(), }, } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, nil } ctx := context.Background() @@ -204,7 +204,7 @@ func TestParserInvalidTimeParseSend(t *testing.T) { }(), }, } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, nil } ctx := context.Background() @@ -228,7 +228,7 @@ func TestParserInvalidSeverityParseDrop(t *testing.T) { ParseFrom: entry.NewBodyField(), ParseTo: entry.NewBodyField(), } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, nil } ctx := context.Background() @@ -266,7 +266,7 @@ func TestParserInvalidTimeValidSeverityParse(t *testing.T) { ParseFrom: entry.NewBodyField(), ParseTo: entry.NewBodyField(), } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, nil } ctx := context.Background() @@ -318,7 +318,7 @@ func TestParserValidTimeInvalidSeverityParse(t *testing.T) { ParseFrom: entry.NewBodyField(), ParseTo: entry.NewBodyField(), } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, nil } ctx := context.Background() @@ -353,7 +353,7 @@ func TestParserOutput(t *testing.T) { ParseFrom: entry.NewBodyField(), ParseTo: entry.NewBodyField(), } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { return i, nil } ctx := context.Background() @@ -386,7 +386,7 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "value", } return e @@ -407,7 +407,7 @@ func TestParserFields(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Body = keyValue - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "value", } return e @@ -428,7 +428,7 @@ func TestParserFields(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Body = keyValue - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "value", } return e @@ -448,9 +448,9 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Body = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Body = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "key": "value", }, }, @@ -473,9 +473,9 @@ func TestParserFields(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Body = keyValue - e.Attributes = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Attributes = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "key": "value", }, }, @@ -498,9 +498,9 @@ func TestParserFields(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Body = keyValue - e.Resource = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Resource = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "key": "value", }, }, @@ -523,7 +523,7 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "value", } e.Body = "value" @@ -538,8 +538,8 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Body = map[string]interface{}{ - "one": map[string]interface{}{ + e.Body = map[string]any{ + "one": map[string]any{ "two": keyValue, }, } @@ -548,12 +548,12 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Body = map[string]interface{}{ - "one": map[string]interface{}{ + e.Body = map[string]any{ + "one": map[string]any{ "two": keyValue, }, } - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "value", } return e @@ -567,8 +567,8 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Attributes = map[string]interface{}{ - "one": map[string]interface{}{ + e.Attributes = map[string]any{ + "one": map[string]any{ "two": keyValue, }, } @@ -577,9 +577,9 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "value", - "one": map[string]interface{}{ + "one": map[string]any{ "two": keyValue, }, } @@ -594,8 +594,8 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Resource = map[string]interface{}{ - "one": map[string]interface{}{ + e.Resource = map[string]any{ + "one": map[string]any{ "two": keyValue, }, } @@ -604,11 +604,11 @@ func TestParserFields(t *testing.T) { func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "value", } - e.Resource = map[string]interface{}{ - "one": map[string]interface{}{ + e.Resource = map[string]any{ + "one": map[string]any{ "two": keyValue, }, } @@ -617,9 +617,9 @@ func TestParserFields(t *testing.T) { }, } - parse := func(i interface{}) (interface{}, error) { + parse := func(i any) (any, error) { split := strings.Split(i.(string), ":") - return map[string]interface{}{split[0]: split[1]}, nil + return map[string]any{split[0]: split[1]}, nil } for _, tc := range cases { @@ -647,7 +647,7 @@ func NewTestParserConfig() ParserConfig { expect.TimeParser = &tp sp := NewSeverityConfig() - sp.Mapping = map[string]interface{}{ + sp.Mapping = map[string]any{ "info": "3xx", "warn": "4xx", } diff --git a/pkg/stanza/operator/helper/scope_name_test.go b/pkg/stanza/operator/helper/scope_name_test.go index 1f0084f9c66b..e91c5baf34fb 100644 --- a/pkg/stanza/operator/helper/scope_name_test.go +++ b/pkg/stanza/operator/helper/scope_name_test.go @@ -51,14 +51,14 @@ func TestScopeNameParser(t *testing.T) { }, input: func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{"logger": testScopeName} + e.Body = map[string]any{"logger": testScopeName} e.ObservedTimestamp = now return e }(), expectErr: true, expected: func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{"logger": testScopeName} + e.Body = map[string]any{"logger": testScopeName} e.ObservedTimestamp = now return e }(), @@ -70,13 +70,13 @@ func TestScopeNameParser(t *testing.T) { }, input: func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{"logger": testScopeName} + e.Body = map[string]any{"logger": testScopeName} e.ObservedTimestamp = now return e }(), expected: func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{"logger": testScopeName} + e.Body = map[string]any{"logger": testScopeName} e.ScopeName = testScopeName e.ObservedTimestamp = now return e diff --git a/pkg/stanza/operator/helper/severity.go b/pkg/stanza/operator/helper/severity.go index 3194e3622db1..3164de4db67a 100644 --- a/pkg/stanza/operator/helper/severity.go +++ b/pkg/stanza/operator/helper/severity.go @@ -49,7 +49,7 @@ type severityMap map[string]entry.Severity // 1. severity level if found, or default level // 2. string version of input value // 3. error if invalid input type -func (m severityMap) find(value interface{}) (entry.Severity, string, error) { +func (m severityMap) find(value any) (entry.Severity, string, error) { switch v := value.(type) { case int: strV := strconv.Itoa(v) diff --git a/pkg/stanza/operator/helper/severity_builder.go b/pkg/stanza/operator/helper/severity_builder.go index 2f11e0d4db60..f2d5cd1b6726 100644 --- a/pkg/stanza/operator/helper/severity_builder.go +++ b/pkg/stanza/operator/helper/severity_builder.go @@ -111,10 +111,10 @@ func NewSeverityConfig() SeverityConfig { // SeverityConfig allows users to specify how to parse a severity from a field. type SeverityConfig struct { - ParseFrom *entry.Field `mapstructure:"parse_from,omitempty"` - Preset string `mapstructure:"preset,omitempty"` - Mapping map[string]interface{} `mapstructure:"mapping,omitempty"` - OverwriteText bool `mapstructure:"overwrite_text,omitempty"` + ParseFrom *entry.Field `mapstructure:"parse_from,omitempty"` + Preset string `mapstructure:"preset,omitempty"` + Mapping map[string]any `mapstructure:"mapping,omitempty"` + OverwriteText bool `mapstructure:"overwrite_text,omitempty"` } // Build builds a SeverityParser from a SeverityConfig @@ -128,7 +128,7 @@ func (c *SeverityConfig) Build(_ *zap.SugaredLogger) (SeverityParser, error) { } switch u := unknown.(type) { - case []interface{}: // check before interface{} + case []any: // check before any for _, value := range u { v, err := parseableValues(value) if err != nil { @@ -136,7 +136,7 @@ func (c *SeverityConfig) Build(_ *zap.SugaredLogger) (SeverityParser, error) { } operatorMapping.add(sev, v...) } - case interface{}: + case any: v, err := parseableValues(u) if err != nil { return SeverityParser{}, err @@ -158,13 +158,13 @@ func (c *SeverityConfig) Build(_ *zap.SugaredLogger) (SeverityParser, error) { return p, nil } -func validateSeverity(severity interface{}) (entry.Severity, error) { +func validateSeverity(severity any) (entry.Severity, error) { sev, _, err := getBuiltinMapping("aliases").find(severity) return sev, err } -func isRange(value interface{}) (int, int, bool) { - rawMap, ok := value.(map[string]interface{}) +func isRange(value any) (int, int, bool) { + rawMap, ok := value.(map[string]any) if !ok { return 0, 0, false } @@ -196,7 +196,7 @@ func expandRange(min, max int) []string { return rangeOfStrings } -func parseableValues(value interface{}) ([]string, error) { +func parseableValues(value any) ([]string, error) { switch v := value.(type) { case int: return []string{strconv.Itoa(v)}, nil // store as string because we will compare as string diff --git a/pkg/stanza/operator/helper/severity_test.go b/pkg/stanza/operator/helper/severity_test.go index 67cd0fdcf579..c82d88afcee5 100644 --- a/pkg/stanza/operator/helper/severity_test.go +++ b/pkg/stanza/operator/helper/severity_test.go @@ -18,9 +18,9 @@ import ( type severityTestCase struct { name string - sample interface{} + sample any mappingSet string - mapping map[string]interface{} + mapping map[string]any buildErr bool parseErr bool expected entry.Severity @@ -68,7 +68,7 @@ func validMappingKeyCases() []severityTestCase { severityTestCase{ name: k, sample: "my_custom_value", - mapping: map[string]interface{}{k: "my_custom_value"}, + mapping: map[string]any{k: "my_custom_value"}, expected: v, }) } @@ -133,13 +133,13 @@ func otlpSevCases() []severityTestCase { return cases } -var allTheThingsMap = map[string]interface{}{ +var allTheThingsMap = map[string]any{ "info": "3xx", "error3": "4xx", "debug4": "5xx", - "trace2": []interface{}{ + "trace2": []any{ "ttttttracer", - map[string]interface{}{"min": 1111, "max": 1234}, + map[string]any{"min": 1111, "max": 1234}, }, "12": "infooo", "fatal2": "", @@ -210,13 +210,13 @@ func TestSeverityParser(t *testing.T) { { name: "custom-string", sample: "NOOOOOOO", - mapping: map[string]interface{}{"error": "NOOOOOOO"}, + mapping: map[string]any{"error": "NOOOOOOO"}, expected: entry.Error, }, { name: "custom-string-overwrite-text", sample: "NOOOOOOO", - mapping: map[string]interface{}{"error": "NOOOOOOO"}, + mapping: map[string]any{"error": "NOOOOOOO"}, expected: entry.Error, expectedText: "ERROR", overwriteText: true, @@ -224,19 +224,19 @@ func TestSeverityParser(t *testing.T) { { name: "custom-string-caps-key", sample: "NOOOOOOO", - mapping: map[string]interface{}{"ErRoR": "NOOOOOOO"}, + mapping: map[string]any{"ErRoR": "NOOOOOOO"}, expected: entry.Error, }, { name: "custom-int", sample: 1234, - mapping: map[string]interface{}{"error": 1234}, + mapping: map[string]any{"error": 1234}, expected: entry.Error, }, { name: "custom-int-overwrite-text", sample: 1234, - mapping: map[string]interface{}{"error": 1234}, + mapping: map[string]any{"error": 1234}, expected: entry.Error, expectedText: "ERROR", overwriteText: true, @@ -244,31 +244,31 @@ func TestSeverityParser(t *testing.T) { { name: "mixed-list-string", sample: "ThiS Is BaD", - mapping: map[string]interface{}{"error": []interface{}{"NOOOOOOO", "this is bad", 1234}}, + mapping: map[string]any{"error": []any{"NOOOOOOO", "this is bad", 1234}}, expected: entry.Error, }, { name: "custom-float64", sample: float64(6), - mapping: map[string]interface{}{"error": 6}, + mapping: map[string]any{"error": 6}, expected: entry.Error, }, { name: "mixed-list-int", sample: 1234, - mapping: map[string]interface{}{"error": []interface{}{"NOOOOOOO", "this is bad", 1234}}, + mapping: map[string]any{"error": []any{"NOOOOOOO", "this is bad", 1234}}, expected: entry.Error, }, { name: "numbered-level", sample: "critical", - mapping: map[string]interface{}{"error2": "critical"}, + mapping: map[string]any{"error2": "critical"}, expected: entry.Error2, }, { name: "numbered-level-overwrite-text", sample: "critical", - mapping: map[string]interface{}{"error2": "critical"}, + mapping: map[string]any{"error2": "critical"}, expected: entry.Error2, expectedText: "ERROR2", overwriteText: true, @@ -276,25 +276,25 @@ func TestSeverityParser(t *testing.T) { { name: "override-standard", sample: "error", - mapping: map[string]interface{}{"error3": []interface{}{"error"}}, + mapping: map[string]any{"error3": []any{"error"}}, expected: entry.Error3, }, { name: "level-unfound", sample: "not-in-the-list-but-thats-ok", - mapping: map[string]interface{}{"error4": []interface{}{"hey!", 1234}}, + mapping: map[string]any{"error4": []any{"hey!", 1234}}, expected: entry.Default, }, { name: "in-range", sample: 123, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Error, }, { name: "in-range-overwrite-text", sample: 123, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Error, expectedText: "ERROR", overwriteText: true, @@ -302,73 +302,73 @@ func TestSeverityParser(t *testing.T) { { name: "in-range-min", sample: 120, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Error, }, { name: "in-range-max", sample: 125, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Error, }, { name: "out-of-range-min-minus", sample: 119, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Default, }, { name: "out-of-range-max-plus", sample: 126, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Default, }, { name: "range-out-of-order", sample: 123, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 125, "max": 120}}, + mapping: map[string]any{"error": map[string]any{"min": 125, "max": 120}}, expected: entry.Error, }, { name: "Http2xx-hit", sample: 201, - mapping: map[string]interface{}{"error": "2xx"}, + mapping: map[string]any{"error": "2xx"}, expected: entry.Error, }, { name: "Http2xx-miss", sample: 301, - mapping: map[string]interface{}{"error": "2xx"}, + mapping: map[string]any{"error": "2xx"}, expected: entry.Default, }, { name: "Http3xx-hit", sample: 301, - mapping: map[string]interface{}{"error": "3xx"}, + mapping: map[string]any{"error": "3xx"}, expected: entry.Error, }, { name: "Http4xx-hit", sample: "404", - mapping: map[string]interface{}{"error": "4xx"}, + mapping: map[string]any{"error": "4xx"}, expected: entry.Error, }, { name: "Http5xx-hit", sample: 555, - mapping: map[string]interface{}{"error": "5xx"}, + mapping: map[string]any{"error": "5xx"}, expected: entry.Error, }, { name: "Http-All", sample: "301", - mapping: map[string]interface{}{"debug": "2xx", "info": "3xx", "error": "4xx", "warn": "5xx"}, + mapping: map[string]any{"debug": "2xx", "info": "3xx", "error": "4xx", "warn": "5xx"}, expected: entry.Info, }, { name: "Http-All-Overwrite-Text", sample: "301", - mapping: map[string]interface{}{"debug": "2xx", "info": "3xx", "error": "4xx", "warn": "5xx"}, + mapping: map[string]any{"debug": "2xx", "info": "3xx", "error": "4xx", "warn": "5xx"}, expected: entry.Info, expectedText: "INFO", overwriteText: true, diff --git a/pkg/stanza/operator/helper/time.go b/pkg/stanza/operator/helper/time.go index 12a74ee45b9c..411012f5897d 100644 --- a/pkg/stanza/operator/helper/time.go +++ b/pkg/stanza/operator/helper/time.go @@ -168,7 +168,7 @@ func (t *TimeParser) Parse(entry *entry.Entry) error { return nil } -func (t *TimeParser) parseEpochTime(value interface{}) (time.Time, error) { +func (t *TimeParser) parseEpochTime(value any) (time.Time, error) { stamp, err := getEpochStamp(t.Layout, value) if err != nil { return time.Time{}, err @@ -197,7 +197,7 @@ func (t *TimeParser) parseEpochTime(value interface{}) (time.Time, error) { } } -func getEpochStamp(layout string, value interface{}) (string, error) { +func getEpochStamp(layout string, value any) (string, error) { switch v := value.(type) { case string: return v, nil diff --git a/pkg/stanza/operator/helper/time_test.go b/pkg/stanza/operator/helper/time_test.go index 447a08786ed8..3911df78ab05 100644 --- a/pkg/stanza/operator/helper/time_test.go +++ b/pkg/stanza/operator/helper/time_test.go @@ -35,7 +35,7 @@ func TestTimeParser(t *testing.T) { testCases := []struct { name string - sample interface{} + sample any expected time.Time gotimeLayout string strptimeLayout string @@ -288,7 +288,7 @@ func TestTimeParser(t *testing.T) { func TestTimeEpochs(t *testing.T) { testCases := []struct { name string - sample interface{} + sample any layout string expected time.Time maxLoss time.Duration @@ -449,7 +449,7 @@ func TestTimeEpochs(t *testing.T) { func TestTimeErrors(t *testing.T) { testCases := []struct { name string - sample interface{} + sample any layoutType string layout string location string @@ -559,7 +559,7 @@ func parseTimeTestConfig(layoutType, layout, location string, parseFrom entry.Fi } } -func makeTestEntry(field entry.Field, value interface{}) *entry.Entry { +func makeTestEntry(field entry.Field, value any) *entry.Entry { e := entry.New() _ = e.Set(field, value) return e diff --git a/pkg/stanza/operator/input/file/config.go b/pkg/stanza/operator/input/file/config.go index e912fe984f8f..0e5a24e7096f 100644 --- a/pkg/stanza/operator/input/file/config.go +++ b/pkg/stanza/operator/input/file/config.go @@ -44,11 +44,11 @@ func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) { return nil, err } - var toBody toBodyFunc = func(token []byte) interface{} { + var toBody toBodyFunc = func(token []byte) any { return string(token) } if decode.IsNop(c.Config.Encoding) { - toBody = func(token []byte) interface{} { + toBody = func(token []byte) any { copied := make([]byte, len(token)) copy(copied, token) return copied diff --git a/pkg/stanza/operator/input/file/file.go b/pkg/stanza/operator/input/file/file.go index db07503868ca..4e42725dce4d 100644 --- a/pkg/stanza/operator/input/file/file.go +++ b/pkg/stanza/operator/input/file/file.go @@ -13,7 +13,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/helper" ) -type toBodyFunc func([]byte) interface{} +type toBodyFunc func([]byte) any // Input is an operator that monitors files for entries type Input struct { diff --git a/pkg/stanza/operator/input/generate/generate.go b/pkg/stanza/operator/input/generate/generate.go index 314e2487920c..d62e21a965bd 100644 --- a/pkg/stanza/operator/input/generate/generate.go +++ b/pkg/stanza/operator/input/generate/generate.go @@ -101,16 +101,16 @@ func (g *Input) Stop() error { return nil } -func recursiveMapInterfaceToMapString(m interface{}) interface{} { +func recursiveMapInterfaceToMapString(m any) any { switch m := m.(type) { - case map[string]interface{}: - newMap := make(map[string]interface{}) + case map[string]any: + newMap := make(map[string]any) for k, v := range m { newMap[k] = recursiveMapInterfaceToMapString(v) } return newMap - case map[interface{}]interface{}: - newMap := make(map[string]interface{}) + case map[any]any: + newMap := make(map[string]any) for k, v := range m { str, ok := k.(string) if !ok { diff --git a/pkg/stanza/operator/input/journald/journald.go b/pkg/stanza/operator/input/journald/journald.go index 66ee3be7ccfb..1a2315af9dc4 100644 --- a/pkg/stanza/operator/input/journald/journald.go +++ b/pkg/stanza/operator/input/journald/journald.go @@ -333,7 +333,7 @@ func (operator *Input) Start(persister operator.Persister) error { } func (operator *Input) parseJournalEntry(line []byte) (*entry.Entry, string, error) { - var body map[string]interface{} + var body map[string]any err := operator.json.Unmarshal(line, &body) if err != nil { return nil, "", err diff --git a/pkg/stanza/operator/input/journald/journald_test.go b/pkg/stanza/operator/input/journald/journald_test.go index 1382fb87da28..fdd9641b5032 100644 --- a/pkg/stanza/operator/input/journald/journald_test.go +++ b/pkg/stanza/operator/input/journald/journald_test.go @@ -78,7 +78,7 @@ func TestInputJournald(t *testing.T) { require.NoError(t, op.Stop()) }() - expected := map[string]interface{}{ + expected := map[string]any{ "_BOOT_ID": "c4fa36de06824d21835c05ff80c54468", "_CAP_EFFECTIVE": "0", "_TRANSPORT": "journal", diff --git a/pkg/stanza/operator/input/syslog/syslog_test.go b/pkg/stanza/operator/input/syslog/syslog_test.go index f080cd6f4da4..961612b9aea6 100644 --- a/pkg/stanza/operator/input/syslog/syslog_test.go +++ b/pkg/stanza/operator/input/syslog/syslog_test.go @@ -41,7 +41,7 @@ var ( Timestamp: time.Date(2015, 8, 5, 21, 58, 59, 693000000, time.UTC), Severity: entry.Info, SeverityText: "info", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "appname": "SecureAuth0", "facility": 10, "hostname": "192.168.2.132", @@ -49,8 +49,8 @@ var ( "msg_id": "ID52020", "priority": 86, "proc_id": "23108", - "structured_data": map[string]interface{}{ - "SecureAuth@27389": map[string]interface{}{ + "structured_data": map[string]any{ + "SecureAuth@27389": map[string]any{ "PEN": "27389", "Realm": "SecureAuth0", "UserHostAddress": "192.168.2.132", diff --git a/pkg/stanza/operator/input/tcp/tcp_test.go b/pkg/stanza/operator/input/tcp/tcp_test.go index dbfdc97e4d27..3bb3c0cbe4be 100644 --- a/pkg/stanza/operator/input/tcp/tcp_test.go +++ b/pkg/stanza/operator/input/tcp/tcp_test.go @@ -155,7 +155,7 @@ func tcpInputAttributesTest(input []byte, expected []string) func(t *testing.T) for _, expectedMessage := range expected { select { case entry := <-entryChan: - expectedAttributes := map[string]interface{}{ + expectedAttributes := map[string]any{ "net.transport": "IP.TCP", } if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok { diff --git a/pkg/stanza/operator/input/udp/udp_test.go b/pkg/stanza/operator/input/udp/udp_test.go index 7695b734af90..276dd6cdf2b2 100644 --- a/pkg/stanza/operator/input/udp/udp_test.go +++ b/pkg/stanza/operator/input/udp/udp_test.go @@ -101,7 +101,7 @@ func udpInputAttributesTest(input []byte, expected []string) func(t *testing.T) for _, expectedBody := range expected { select { case entry := <-entryChan: - expectedAttributes := map[string]interface{}{ + expectedAttributes := map[string]any{ "net.transport": "IP.UDP", } // LocalAddr for udpInput.connection is a server address diff --git a/pkg/stanza/operator/input/windows/security.go b/pkg/stanza/operator/input/windows/security.go index 5a5bc8a98719..55ff4b4477e4 100644 --- a/pkg/stanza/operator/input/windows/security.go +++ b/pkg/stanza/operator/input/windows/security.go @@ -7,9 +7,9 @@ import ( "strings" ) -func parseSecurity(message string) (string, map[string]interface{}) { +func parseSecurity(message string) (string, map[string]any) { var subject string - details := map[string]interface{}{} + details := map[string]any{} mp := newMessageProcessor(message) @@ -58,8 +58,8 @@ func parseSecurity(message string) (string, map[string]interface{}) { return subject, details } -func (mp *messageProcessor) consumeSubsection(depth int) map[string]interface{} { - sub := map[string]interface{}{} +func (mp *messageProcessor) consumeSubsection(depth int) map[string]any { + sub := map[string]any{} for mp.hasNext() { l := mp.next() switch l.t { diff --git a/pkg/stanza/operator/input/windows/security_test.go b/pkg/stanza/operator/input/windows/security_test.go index eb8db267fe67..ab7a891d7b79 100644 --- a/pkg/stanza/operator/input/windows/security_test.go +++ b/pkg/stanza/operator/input/windows/security_test.go @@ -55,7 +55,7 @@ func TestParseSecurity(t *testing.T) { require.NoError(t, err, "problem reading expected details") // This is a little silly, but if we rely on unmarshaling - // then []string gets converted to []interface{} and the comparison fails + // then []string gets converted to []any and the comparison fails detailBytes, err := json.Marshal(details) require.NoError(t, err, "problem processing details result") diff --git a/pkg/stanza/operator/input/windows/xml.go b/pkg/stanza/operator/input/windows/xml.go index 76e37c4db8c3..859d72a0b527 100644 --- a/pkg/stanza/operator/input/windows/xml.go +++ b/pkg/stanza/operator/input/windows/xml.go @@ -76,7 +76,7 @@ func (e *EventXML) parseSeverity() entry.Severity { } // parseBody will parse a body from the event. -func (e *EventXML) parseBody() map[string]interface{} { +func (e *EventXML) parseBody() map[string]any { message, details := e.parseMessage() level := e.RenderedLevel @@ -99,12 +99,12 @@ func (e *EventXML) parseBody() map[string]interface{} { keywords = e.Keywords } - body := map[string]interface{}{ - "event_id": map[string]interface{}{ + body := map[string]any{ + "event_id": map[string]any{ "qualifiers": e.EventID.Qualifiers, "id": e.EventID.ID, }, - "provider": map[string]interface{}{ + "provider": map[string]any{ "name": e.Provider.Name, "guid": e.Provider.GUID, "event_source": e.Provider.EventSourceName, @@ -139,7 +139,7 @@ func (e *EventXML) parseBody() map[string]interface{} { } // parseMessage will attempt to parse a message into a message and details -func (e *EventXML) parseMessage() (string, map[string]interface{}) { +func (e *EventXML) parseMessage() (string, map[string]any) { switch e.Channel { case "Security": return parseSecurity(e.Message) @@ -150,8 +150,8 @@ func (e *EventXML) parseMessage() (string, map[string]interface{}) { // parse event data into a map[string]interface // see: https://learn.microsoft.com/en-us/windows/win32/wes/eventschema-datafieldtype-complextype -func parseEventData(eventData EventData) map[string]interface{} { - outputMap := make(map[string]interface{}, 3) +func parseEventData(eventData EventData) map[string]any { + outputMap := make(map[string]any, 3) if eventData.Name != "" { outputMap["name"] = eventData.Name } @@ -163,9 +163,9 @@ func parseEventData(eventData EventData) map[string]interface{} { return outputMap } - dataMaps := make([]interface{}, len(eventData.Data)) + dataMaps := make([]any, len(eventData.Data)) for i, data := range eventData.Data { - dataMaps[i] = map[string]interface{}{ + dataMaps[i] = map[string]any{ data.Name: data.Value, } } diff --git a/pkg/stanza/operator/input/windows/xml_test.go b/pkg/stanza/operator/input/windows/xml_test.go index 98a2b7235791..734ccc881b69 100644 --- a/pkg/stanza/operator/input/windows/xml_test.go +++ b/pkg/stanza/operator/input/windows/xml_test.go @@ -91,12 +91,12 @@ func TestParseBody(t *testing.T) { RenderedKeywords: []string{"RenderedKeywords"}, } - expected := map[string]interface{}{ - "event_id": map[string]interface{}{ + expected := map[string]any{ + "event_id": map[string]any{ "id": uint32(1), "qualifiers": uint16(2), }, - "provider": map[string]interface{}{ + "provider": map[string]any{ "name": "provider", "guid": "guid", "event_source": "event source", @@ -110,10 +110,10 @@ func TestParseBody(t *testing.T) { "task": "rendered_task", "opcode": "rendered_opcode", "keywords": []string{"RenderedKeywords"}, - "event_data": map[string]interface{}{ - "data": []interface{}{ - map[string]interface{}{"1st_name": "value"}, - map[string]interface{}{"2nd_name": "another_value"}, + "event_data": map[string]any{ + "data": []any{ + map[string]any{"1st_name": "value"}, + map[string]any{"2nd_name": "another_value"}, }, }, } @@ -159,12 +159,12 @@ func TestParseBodySecurityExecution(t *testing.T) { RenderedKeywords: []string{"RenderedKeywords"}, } - expected := map[string]interface{}{ - "event_id": map[string]interface{}{ + expected := map[string]any{ + "event_id": map[string]any{ "id": uint32(1), "qualifiers": uint16(2), }, - "provider": map[string]interface{}{ + "provider": map[string]any{ "name": "provider", "guid": "guid", "event_source": "event source", @@ -185,10 +185,10 @@ func TestParseBodySecurityExecution(t *testing.T) { "security": map[string]any{ "user_id": "my-user-id", }, - "event_data": map[string]interface{}{ - "data": []interface{}{ - map[string]interface{}{"name": "value"}, - map[string]interface{}{"another_name": "another_value"}, + "event_data": map[string]any{ + "data": []any{ + map[string]any{"name": "value"}, + map[string]any{"another_name": "another_value"}, }, }, } @@ -245,12 +245,12 @@ func TestParseBodyFullExecution(t *testing.T) { RenderedKeywords: []string{"RenderedKeywords"}, } - expected := map[string]interface{}{ - "event_id": map[string]interface{}{ + expected := map[string]any{ + "event_id": map[string]any{ "id": uint32(1), "qualifiers": uint16(2), }, - "provider": map[string]interface{}{ + "provider": map[string]any{ "name": "provider", "guid": "guid", "event_source": "event source", @@ -276,10 +276,10 @@ func TestParseBodyFullExecution(t *testing.T) { "security": map[string]any{ "user_id": "my-user-id", }, - "event_data": map[string]interface{}{ - "data": []interface{}{ - map[string]interface{}{"name": "value"}, - map[string]interface{}{"another_name": "another_value"}, + "event_data": map[string]any{ + "data": []any{ + map[string]any{"name": "value"}, + map[string]any{"another_name": "another_value"}, }, }, } @@ -314,12 +314,12 @@ func TestParseNoRendered(t *testing.T) { }, } - expected := map[string]interface{}{ - "event_id": map[string]interface{}{ + expected := map[string]any{ + "event_id": map[string]any{ "id": uint32(1), "qualifiers": uint16(2), }, - "provider": map[string]interface{}{ + "provider": map[string]any{ "name": "provider", "guid": "guid", "event_source": "event source", @@ -333,10 +333,10 @@ func TestParseNoRendered(t *testing.T) { "task": "task", "opcode": "opcode", "keywords": []string{"keyword"}, - "event_data": map[string]interface{}{ - "data": []interface{}{ - map[string]interface{}{"name": "value"}, - map[string]interface{}{"another_name": "another_value"}, + "event_data": map[string]any{ + "data": []any{ + map[string]any{"name": "value"}, + map[string]any{"another_name": "another_value"}, }, }, } @@ -375,12 +375,12 @@ func TestParseBodySecurity(t *testing.T) { RenderedKeywords: []string{"RenderedKeywords"}, } - expected := map[string]interface{}{ - "event_id": map[string]interface{}{ + expected := map[string]any{ + "event_id": map[string]any{ "id": uint32(1), "qualifiers": uint16(2), }, - "provider": map[string]interface{}{ + "provider": map[string]any{ "name": "provider", "guid": "guid", "event_source": "event source", @@ -394,10 +394,10 @@ func TestParseBodySecurity(t *testing.T) { "task": "rendered_task", "opcode": "rendered_opcode", "keywords": []string{"RenderedKeywords"}, - "event_data": map[string]interface{}{ - "data": []interface{}{ - map[string]interface{}{"name": "value"}, - map[string]interface{}{"another_name": "another_value"}, + "event_data": map[string]any{ + "data": []any{ + map[string]any{"name": "value"}, + map[string]any{"another_name": "another_value"}, }, }, } @@ -415,10 +415,10 @@ func TestParseEventData(t *testing.T) { } parsed := xmlMap.parseBody() - expectedMap := map[string]interface{}{ + expectedMap := map[string]any{ "name": "EVENT_DATA", - "data": []interface{}{ - map[string]interface{}{"name": "value"}, + "data": []any{ + map[string]any{"name": "value"}, }, "binary": "2D20", } @@ -431,10 +431,10 @@ func TestParseEventData(t *testing.T) { } parsed = xmlMixed.parseBody() - expectedSlice := map[string]interface{}{ - "data": []interface{}{ - map[string]interface{}{"name": "value"}, - map[string]interface{}{"": "no_name"}}, + expectedSlice := map[string]any{ + "data": []any{ + map[string]any{"name": "value"}, + map[string]any{"": "no_name"}}, } require.Equal(t, expectedSlice, parsed["event_data"]) } diff --git a/pkg/stanza/operator/operatortest/confmap.go b/pkg/stanza/operator/operatortest/confmap.go index fae58a405f02..f5ce8b4c9f31 100644 --- a/pkg/stanza/operator/operatortest/confmap.go +++ b/pkg/stanza/operator/operatortest/confmap.go @@ -25,7 +25,7 @@ type ConfigUnmarshalTests struct { // ConfigUnmarshalTest is used for testing golden configs type ConfigUnmarshalTest struct { Name string - Expect interface{} + Expect any ExpectErr bool } diff --git a/pkg/stanza/operator/parser/csv/csv.go b/pkg/stanza/operator/parser/csv/csv.go index fc0241793fbe..7829f8e8c592 100644 --- a/pkg/stanza/operator/parser/csv/csv.go +++ b/pkg/stanza/operator/parser/csv/csv.go @@ -113,7 +113,7 @@ type Parser struct { parse parseFunc } -type parseFunc func(interface{}) (interface{}, error) +type parseFunc func(any) (any, error) // Process will parse an entry for csv. func (r *Parser) Process(ctx context.Context, e *entry.Entry) error { @@ -152,7 +152,7 @@ func generateParseFunc(headers []string, fieldDelimiter rune, lazyQuotes bool, i // generateCSVParseFunc returns a parse function for a given header and field delimiter, which parses a line of CSV text. func generateCSVParseFunc(headers []string, fieldDelimiter rune, lazyQuotes bool) parseFunc { - return func(value interface{}) (interface{}, error) { + return func(value any) (any, error) { csvLine, err := valueAsString(value) if err != nil { return nil, err @@ -209,7 +209,7 @@ func generateCSVParseFunc(headers []string, fieldDelimiter rune, lazyQuotes bool // generateSplitParseFunc returns a parse function (which ignores quotes) for a given header and field delimiter. func generateSplitParseFunc(headers []string, fieldDelimiter rune) parseFunc { - return func(value interface{}) (interface{}, error) { + return func(value any) (any, error) { csvLine, err := valueAsString(value) if err != nil { return nil, err @@ -222,7 +222,7 @@ func generateSplitParseFunc(headers []string, fieldDelimiter rune) parseFunc { } // valueAsString interprets the given value as a string. -func valueAsString(value interface{}) (string, error) { +func valueAsString(value any) (string, error) { var s string switch t := value.(type) { case string: @@ -237,8 +237,8 @@ func valueAsString(value interface{}) (string, error) { } // headersMap creates a map of headers[i] -> fields[i]. -func headersMap(headers []string, fields []string) (map[string]interface{}, error) { - parsedValues := make(map[string]interface{}) +func headersMap(headers []string, fields []string) (map[string]any, error) { + parsedValues := make(map[string]any) if len(fields) != len(headers) { return nil, fmt.Errorf("wrong number of fields: expected %d, found %d", len(headers), len(fields)) diff --git a/pkg/stanza/operator/parser/csv/csv_test.go b/pkg/stanza/operator/parser/csv/csv_test.go index 2c8dde2b619b..9bc66207f915 100644 --- a/pkg/stanza/operator/parser/csv/csv_test.go +++ b/pkg/stanza/operator/parser/csv/csv_test.go @@ -119,7 +119,7 @@ func TestParserCSV(t *testing.T) { []entry.Entry{ { Body: "stanza,INFO,started agent", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "sev": "INFO", "msg": "started agent", @@ -144,7 +144,7 @@ func TestParserCSV(t *testing.T) { []entry.Entry{ { Body: "stanza|INFO|started agent", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "sev": "INFO", "msg": "started agent", @@ -173,7 +173,7 @@ func TestParserCSV(t *testing.T) { []entry.Entry{ { Body: "stanza,INFO,started agent", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "sev": "INFO", "msg": "started agent", @@ -181,7 +181,7 @@ func TestParserCSV(t *testing.T) { }, { Body: "stanza,ERROR,agent killed", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "sev": "ERROR", "msg": "agent killed", @@ -189,7 +189,7 @@ func TestParserCSV(t *testing.T) { }, { Body: "kernel,TRACE,oom", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "kernel", "sev": "TRACE", "msg": "oom", @@ -213,7 +213,7 @@ func TestParserCSV(t *testing.T) { []entry.Entry{ { Body: "stanza;Evergreen;1;555-5555;agent", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "address": "Evergreen", "age": "1", @@ -233,7 +233,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "name,age,height,number", }, Body: "stanza dev,1,400,555-555-5555", @@ -241,7 +241,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "name,age,height,number", "name": "stanza dev", "age": "1", @@ -263,7 +263,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "name|age|height|number", }, Body: "stanza dev,1,400,555-555-5555", @@ -271,7 +271,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "name|age|height|number", "name": "stanza dev", "age": "1", @@ -292,19 +292,19 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "name,age,height,number", }, Body: "stanza dev,1,400,555-555-5555", }, { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "x,y", }, Body: "000100,2", }, { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "a,b,c,d,e,f", }, Body: "1,2,3,4,5,6", @@ -312,7 +312,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "name,age,height,number", "name": "stanza dev", "age": "1", @@ -322,7 +322,7 @@ func TestParserCSV(t *testing.T) { Body: "stanza dev,1,400,555-555-5555", }, { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "x,y", "x": "000100", "y": "2", @@ -330,7 +330,7 @@ func TestParserCSV(t *testing.T) { Body: "000100,2", }, { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Fields": "a,b,c,d,e,f", "a": "1", "b": "2", @@ -353,7 +353,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "columns": "name age height number", }, Body: "stanza dev 1 400 555-555-5555", @@ -361,8 +361,8 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: func() map[string]interface{} { - m := map[string]interface{}{ + Attributes: func() map[string]any { + m := map[string]any{ "name": "stanza dev", "age": "1", "height": "400", @@ -390,7 +390,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Body: map[string]interface{}{ + Body: map[string]any{ "name": "stanza dev", "age": "1", "height": "400", @@ -413,7 +413,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Body: map[string]interface{}{ + Body: map[string]any{ "name": "stanza", "age": "1", "height": "400", @@ -436,7 +436,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "timestamp": "20210316 17:08:01", "serverhost": "oiq-int-mysql", "username": "load", @@ -466,7 +466,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "address": "Evergreen", "age": "", @@ -492,7 +492,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "address": "Evergreen", "age": "1", @@ -517,7 +517,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "address": "Evergreen,49508", "age": "1", @@ -542,7 +542,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "bob \"the man\"", "address": "Evergreen", "age": "1", @@ -568,7 +568,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "1", "height": "400", @@ -594,7 +594,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "1", "height": "400", @@ -620,7 +620,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "1", "height": "400", @@ -645,7 +645,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "1", "height": "400", @@ -670,7 +670,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "1", "height": "400", @@ -695,7 +695,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza \"log parser\"", "age": "1", "height": "6ft", @@ -721,7 +721,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza log parser", "age": "1", "height": "6ft", @@ -747,7 +747,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza log parser", "age": "1", "height": "6ft", @@ -773,7 +773,7 @@ func TestParserCSV(t *testing.T) { }, []entry.Entry{ { - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza log parser", "age": "\"1", "height": "\"6ft", @@ -826,12 +826,12 @@ func TestParserCSVMultiline(t *testing.T) { cases := []struct { name string input string - expected map[string]interface{} + expected map[string]any }{ { "no_newlines", "aaaa,bbbb,cccc,dddd,eeee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb", "C": "cccc", @@ -842,7 +842,7 @@ func TestParserCSVMultiline(t *testing.T) { { "first_field", "aa\naa,bbbb,cccc,dddd,eeee", - map[string]interface{}{ + map[string]any{ "A": "aa\naa", "B": "bbbb", "C": "cccc", @@ -853,7 +853,7 @@ func TestParserCSVMultiline(t *testing.T) { { "middle_field", "aaaa,bbbb,cc\ncc,dddd,eeee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb", "C": "cc\ncc", @@ -864,7 +864,7 @@ func TestParserCSVMultiline(t *testing.T) { { "last_field", "aaaa,bbbb,cccc,dddd,e\neee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb", "C": "cccc", @@ -875,7 +875,7 @@ func TestParserCSVMultiline(t *testing.T) { { "multiple_fields", "aaaa,bb\nbb,ccc\nc,dddd,e\neee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bb\nbb", "C": "ccc\nc", @@ -886,7 +886,7 @@ func TestParserCSVMultiline(t *testing.T) { { "multiple_first_field", "a\na\na\na,bbbb,cccc,dddd,eeee", - map[string]interface{}{ + map[string]any{ "A": "a\na\na\na", "B": "bbbb", "C": "cccc", @@ -897,7 +897,7 @@ func TestParserCSVMultiline(t *testing.T) { { "multiple_middle_field", "aaaa,bbbb,c\nc\nc\nc,dddd,eeee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb", "C": "c\nc\nc\nc", @@ -908,7 +908,7 @@ func TestParserCSVMultiline(t *testing.T) { { "multiple_last_field", "aaaa,bbbb,cccc,dddd,e\ne\ne\ne", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb", "C": "cccc", @@ -919,7 +919,7 @@ func TestParserCSVMultiline(t *testing.T) { { "leading_newline", "\naaaa,bbbb,cccc,dddd,eeee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb", "C": "cccc", @@ -930,7 +930,7 @@ func TestParserCSVMultiline(t *testing.T) { { "trailing_newline", "aaaa,bbbb,cccc,dddd,eeee\n", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb", "C": "cccc", @@ -941,7 +941,7 @@ func TestParserCSVMultiline(t *testing.T) { { "leading_newline_field", "aaaa,\nbbbb,\ncccc,\ndddd,eeee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "\nbbbb", "C": "\ncccc", @@ -952,7 +952,7 @@ func TestParserCSVMultiline(t *testing.T) { { "trailing_newline_field", "aaaa,bbbb\n,cccc\n,dddd\n,eeee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb\n", "C": "cccc\n", @@ -963,7 +963,7 @@ func TestParserCSVMultiline(t *testing.T) { { "empty_lines_unquoted", "aa\n\naa,bbbb,c\n\nccc,dddd,eee\n\ne", - map[string]interface{}{ + map[string]any{ "A": "aa\naa", "B": "bbbb", "C": "c\nccc", @@ -974,7 +974,7 @@ func TestParserCSVMultiline(t *testing.T) { { "empty_lines_quoted", "\"aa\n\naa\",bbbb,\"c\n\nccc\",dddd,\"eee\n\ne\"", - map[string]interface{}{ + map[string]any{ "A": "aa\n\naa", "B": "bbbb", "C": "c\n\nccc", @@ -985,7 +985,7 @@ func TestParserCSVMultiline(t *testing.T) { { "everything", "\n\na\na\n\naa,\n\nbb\nbb\n\n,\"cc\ncc\n\n\",\ndddd\n,eeee\n\n", - map[string]interface{}{ + map[string]any{ "A": "a\na\naa", "B": "\nbb\nbb\n", "C": "cc\ncc\n\n", @@ -998,7 +998,7 @@ func TestParserCSVMultiline(t *testing.T) { `aaaa,bb bb,cccc,dd dd,eeee`, - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bb\nbb", "C": "cccc", @@ -1009,7 +1009,7 @@ dd,eeee`, { "return_in_quotes", "aaaa,\"bbbb\",\"cc\ncc\",dddd,eeee", - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "bbbb", "C": "cc\ncc", @@ -1021,7 +1021,7 @@ dd,eeee`, "return_in_double_quotes", `aaaa,"""bbbb""","""cc cc""",dddd,eeee`, - map[string]interface{}{ + map[string]any{ "A": "aaaa", "B": "\"bbbb\"", "C": "\"cc\ncc\"", diff --git a/pkg/stanza/operator/parser/json/config_test.go b/pkg/stanza/operator/parser/json/config_test.go index 22675a015418..1add671e730a 100644 --- a/pkg/stanza/operator/parser/json/config_test.go +++ b/pkg/stanza/operator/parser/json/config_test.go @@ -65,7 +65,7 @@ func TestConfig(t *testing.T) { parseField := entry.NewBodyField("severity_field") severityParser := helper.NewSeverityConfig() severityParser.ParseFrom = &parseField - mapping := map[string]interface{}{ + mapping := map[string]any{ "critical": "5xx", "error": "4xx", "info": "3xx", diff --git a/pkg/stanza/operator/parser/json/json.go b/pkg/stanza/operator/parser/json/json.go index 8b88aa8903bf..b5e278f551d9 100644 --- a/pkg/stanza/operator/parser/json/json.go +++ b/pkg/stanza/operator/parser/json/json.go @@ -63,8 +63,8 @@ func (j *Parser) Process(ctx context.Context, entry *entry.Entry) error { } // parse will parse a value as JSON. -func (j *Parser) parse(value interface{}) (interface{}, error) { - var parsedValue map[string]interface{} +func (j *Parser) parse(value any) (any, error) { + var parsedValue map[string]any switch m := value.(type) { case string: err := j.json.UnmarshalFromString(m, &parsedValue) diff --git a/pkg/stanza/operator/parser/json/json_test.go b/pkg/stanza/operator/parser/json/json_test.go index cd8d8a08db4d..ec353b0f7850 100644 --- a/pkg/stanza/operator/parser/json/json_test.go +++ b/pkg/stanza/operator/parser/json/json_test.go @@ -77,7 +77,7 @@ func TestParser(t *testing.T) { Body: `{}`, }, &entry.Entry{ - Attributes: map[string]interface{}{}, + Attributes: map[string]any{}, Body: `{}`, }, }, @@ -88,7 +88,7 @@ func TestParser(t *testing.T) { Body: `{"superkey":"superval"}`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "superkey": "superval", }, Body: `{"superkey":"superval"}`, @@ -108,7 +108,7 @@ func TestParser(t *testing.T) { Body: `{"superkey":"superval","timestamp":1136214245}`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "superkey": "superval", "timestamp": float64(1136214245), }, @@ -127,7 +127,7 @@ func TestParser(t *testing.T) { Body: `{"superkey":"superval","logger_name":"logger"}`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "superkey": "superval", "logger_name": "logger", }, diff --git a/pkg/stanza/operator/parser/keyvalue/config_test.go b/pkg/stanza/operator/parser/keyvalue/config_test.go index 51de89da1306..899c263bbdef 100644 --- a/pkg/stanza/operator/parser/keyvalue/config_test.go +++ b/pkg/stanza/operator/parser/keyvalue/config_test.go @@ -65,7 +65,7 @@ func TestConfig(t *testing.T) { parseField := entry.NewBodyField("severity_field") severityField := helper.NewSeverityConfig() severityField.ParseFrom = &parseField - mapping := map[string]interface{}{ + mapping := map[string]any{ "critical": "5xx", "error": "4xx", "info": "3xx", diff --git a/pkg/stanza/operator/parser/keyvalue/keyvalue.go b/pkg/stanza/operator/parser/keyvalue/keyvalue.go index f34c03082ea2..64608131e56c 100644 --- a/pkg/stanza/operator/parser/keyvalue/keyvalue.go +++ b/pkg/stanza/operator/parser/keyvalue/keyvalue.go @@ -88,7 +88,7 @@ func (kv *Parser) Process(ctx context.Context, entry *entry.Entry) error { } // parse will parse a value as key values. -func (kv *Parser) parse(value interface{}) (interface{}, error) { +func (kv *Parser) parse(value any) (any, error) { switch m := value.(type) { case string: return kv.parser(m, kv.delimiter) @@ -97,12 +97,12 @@ func (kv *Parser) parse(value interface{}) (interface{}, error) { } } -func (kv *Parser) parser(input string, delimiter string) (map[string]interface{}, error) { +func (kv *Parser) parser(input string, delimiter string) (map[string]any, error) { if input == "" { return nil, fmt.Errorf("parse from field %s is empty", kv.ParseFrom.String()) } - parsed := make(map[string]interface{}) + parsed := make(map[string]any) var err error for _, raw := range kv.pairSplitFunc(input) { diff --git a/pkg/stanza/operator/parser/keyvalue/keyvalue_test.go b/pkg/stanza/operator/parser/keyvalue/keyvalue_test.go index 9978558e88c8..8cfccd8ea363 100644 --- a/pkg/stanza/operator/parser/keyvalue/keyvalue_test.go +++ b/pkg/stanza/operator/parser/keyvalue/keyvalue_test.go @@ -168,7 +168,7 @@ func TestParser(t *testing.T) { Body: "name=stanza age=2", }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "2", }, @@ -183,16 +183,16 @@ func TestParser(t *testing.T) { kv.ParseFrom = entry.NewBodyField("test") }, &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "test": "name=otel age=2", }, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "otel", "age": "2", }, - Body: map[string]interface{}{ + Body: map[string]any{ "test": "name=otel age=2", }, }, @@ -208,8 +208,8 @@ func TestParser(t *testing.T) { Body: "name=stanza age=10", }, &entry.Entry{ - Body: map[string]interface{}{ - "test": map[string]interface{}{ + Body: map[string]any{ + "test": map[string]any{ "name": "stanza", "age": "10", }, @@ -225,16 +225,16 @@ func TestParser(t *testing.T) { kv.ParseTo = entry.RootableField{Field: entry.NewBodyField("to")} }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "from": "name=stanza age=10", }, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "from": "name=stanza age=10", }, - Body: map[string]interface{}{ - "to": map[string]interface{}{ + Body: map[string]any{ + "to": map[string]any{ "name": "stanza", "age": "10", }, @@ -250,7 +250,7 @@ func TestParser(t *testing.T) { Body: `requestClientApplication="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "requestClientApplication": `Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0`, }, Body: `requestClientApplication="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"`, @@ -265,7 +265,7 @@ func TestParser(t *testing.T) { Body: "name=\"stanza\" age=2", }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "2", }, @@ -281,7 +281,7 @@ func TestParser(t *testing.T) { Body: "description='stanza deployment number 5' x=y", }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "description": "stanza deployment number 5", "x": "y", }, @@ -297,7 +297,7 @@ func TestParser(t *testing.T) { Body: `name=" stanza " age=2`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "2", }, @@ -313,7 +313,7 @@ func TestParser(t *testing.T) { Body: `" name "=" stanza " age=2`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "2", }, @@ -330,14 +330,14 @@ func TestParser(t *testing.T) { kv.ParseTo = entry.RootableField{Field: entry.NewBodyField("testparsed")} }, &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "testfield": `name|" stanza " age|2 key|value`, }, }, &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "testfield": `name|" stanza " age|2 key|value`, - "testparsed": map[string]interface{}{ + "testparsed": map[string]any{ "name": "stanza", "age": "2", "key": "value", @@ -356,7 +356,7 @@ func TestParser(t *testing.T) { Body: `name==" stanza " age==2 key==value`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "2", "key": "value", @@ -375,7 +375,7 @@ func TestParser(t *testing.T) { Body: `name=stanza|age=2 | key=value`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "2", "key": "value", @@ -396,7 +396,7 @@ age=2^ key=value`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "name": "stanza", "age": "2", "key": "value", @@ -415,7 +415,7 @@ key=value`, Body: "name=stanza age=1 job=\"software engineering\" location=\"grand rapids michigan\" src=\"10.3.3.76\" dst=172.217.0.10 protocol=udp sport=57112 dport=443 translated_src_ip=96.63.176.3 translated_port=57112", }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "age": "1", "dport": "443", "dst": "172.217.0.10", @@ -440,7 +440,7 @@ key=value`, Body: `id=LVM_Sonicwall sn=22255555 time="2021-09-22 16:30:31" fw=14.165.177.10 pri=6 c=1024 gcat=2 m=97 msg="Web site hit" srcMac=6c:0b:84:3f:fa:63 src=192.168.50.2:52006:X0 srcZone=LAN natSrc=14.165.177.10:58457 dstMac=08:b2:58:46:30:54 dst=15.159.150.83:443:X1 dstZone=WAN natDst=15.159.150.83:443 proto=tcp/https sent=1422 rcvd=5993 rule="6 (LAN->WAN)" app=48 dstname=example.space.dev.com arg=/ code=27 Category="Information Technology/Computers" note="Policy: a0, Info: 888 " n=3412158`, }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "id": "LVM_Sonicwall", "sn": "22255555", "time": "2021-09-22 16:30:31", diff --git a/pkg/stanza/operator/parser/regex/cache.go b/pkg/stanza/operator/parser/regex/cache.go index 3f69cb8cd69c..735831119427 100644 --- a/pkg/stanza/operator/parser/regex/cache.go +++ b/pkg/stanza/operator/parser/regex/cache.go @@ -12,9 +12,9 @@ import ( // cache allows operators to cache a value and look it up later type cache interface { - get(key string) interface{} - add(key string, data interface{}) bool - copy() map[string]interface{} + get(key string) any + add(key string, data any) bool + copy() map[string]any maxSize() uint16 } @@ -25,7 +25,7 @@ func newMemoryCache(maxSize uint16, interval uint64) *memoryCache { limit := uint64(maxSize) + 1 return &memoryCache{ - cache: make(map[string]interface{}), + cache: make(map[string]any), keys: make(chan string, maxSize), limiter: newStartedAtomicLimiter(limit, interval), } @@ -39,7 +39,7 @@ func newMemoryCache(maxSize uint16, interval uint64) *memoryCache { // item using a FIFO style queue. type memoryCache struct { // Key / Value pairs of cached items - cache map[string]interface{} + cache map[string]any // When the cache is full, the oldest entry's key is // read from the channel and used to index into the @@ -57,7 +57,7 @@ type memoryCache struct { var _ cache = (&memoryCache{}) // get returns a cached entry, nil if it does not exist -func (m *memoryCache) get(key string) interface{} { +func (m *memoryCache) get(key string) any { // Read and unlock as fast as possible m.mutex.RLock() data := m.cache[key] @@ -68,7 +68,7 @@ func (m *memoryCache) get(key string) interface{} { // add inserts an item into the cache, if the cache is full, the // oldest item is removed -func (m *memoryCache) add(key string, data interface{}) bool { +func (m *memoryCache) add(key string, data any) bool { if m.limiter.throttled() { return false } @@ -94,8 +94,8 @@ func (m *memoryCache) add(key string, data interface{}) bool { } // copy returns a deep copy of the cache -func (m *memoryCache) copy() map[string]interface{} { - cp := make(map[string]interface{}, cap(m.keys)) +func (m *memoryCache) copy() map[string]any { + cp := make(map[string]any, cap(m.keys)) m.mutex.Lock() defer m.mutex.Unlock() diff --git a/pkg/stanza/operator/parser/regex/cache_test.go b/pkg/stanza/operator/parser/regex/cache_test.go index ed2d834f8cd6..0403593c31f8 100644 --- a/pkg/stanza/operator/parser/regex/cache_test.go +++ b/pkg/stanza/operator/parser/regex/cache_test.go @@ -23,7 +23,7 @@ func TestNewMemoryCache(t *testing.T) { "size-50", 50, &memoryCache{ - cache: make(map[string]interface{}), + cache: make(map[string]any), keys: make(chan string, 50), }, 50, @@ -43,7 +43,7 @@ func TestMemory(t *testing.T) { cases := []struct { name string cache *memoryCache - input map[string]interface{} + input map[string]any expect *memoryCache }{ { @@ -51,7 +51,7 @@ func TestMemory(t *testing.T) { func() *memoryCache { return newMemoryCache(3, 0) }(), - map[string]interface{}{ + map[string]any{ "key": "value", "map-value": map[string]string{ "x": "y", @@ -59,7 +59,7 @@ func TestMemory(t *testing.T) { }, }, &memoryCache{ - cache: map[string]interface{}{ + cache: map[string]any{ "key": "value", "map-value": map[string]string{ "x": "y", @@ -103,7 +103,7 @@ func TestCleanupLast(t *testing.T) { } // make sure the cache looks the way we expect - expectCache := map[string]interface{}{ + expectCache := map[string]any{ "1": 1, // oldest key, will be removed when 11 is added "2": 2, "3": 3, @@ -132,7 +132,7 @@ func TestCleanupLast(t *testing.T) { } // All entries should have been replaced by now - expectCache = map[string]interface{}{ + expectCache = map[string]any{ "11": 11, "12": 12, "13": 13, diff --git a/pkg/stanza/operator/parser/regex/config_test.go b/pkg/stanza/operator/parser/regex/config_test.go index 956fe0fc49da..eb075914ede5 100644 --- a/pkg/stanza/operator/parser/regex/config_test.go +++ b/pkg/stanza/operator/parser/regex/config_test.go @@ -73,7 +73,7 @@ func TestParserGoldenConfig(t *testing.T) { parseField := entry.NewBodyField("severity_field") severityParser := helper.NewSeverityConfig() severityParser.ParseFrom = &parseField - mapping := map[string]interface{}{ + mapping := map[string]any{ "critical": "5xx", "error": "4xx", "info": "3xx", diff --git a/pkg/stanza/operator/parser/regex/regex.go b/pkg/stanza/operator/parser/regex/regex.go index eb2dfba3347a..67df235db838 100644 --- a/pkg/stanza/operator/parser/regex/regex.go +++ b/pkg/stanza/operator/parser/regex/regex.go @@ -100,7 +100,7 @@ func (r *Parser) Process(ctx context.Context, entry *entry.Entry) error { } // parse will parse a value using the supplied regex. -func (r *Parser) parse(value interface{}) (interface{}, error) { +func (r *Parser) parse(value any) (any, error) { var raw string switch m := value.(type) { case string: @@ -111,7 +111,7 @@ func (r *Parser) parse(value interface{}) (interface{}, error) { return r.match(raw) } -func (r *Parser) match(value string) (interface{}, error) { +func (r *Parser) match(value string) (any, error) { if r.cache != nil { if x := r.cache.get(value); x != nil { return x, nil @@ -123,7 +123,7 @@ func (r *Parser) match(value string) (interface{}, error) { return nil, fmt.Errorf("regex pattern does not match") } - parsedValues := map[string]interface{}{} + parsedValues := map[string]any{} for i, subexp := range r.regexp.SubexpNames() { if i == 0 { // Skip whole match diff --git a/pkg/stanza/operator/parser/regex/regex_test.go b/pkg/stanza/operator/parser/regex/regex_test.go index e19d95b84d36..20831497f1fa 100644 --- a/pkg/stanza/operator/parser/regex/regex_test.go +++ b/pkg/stanza/operator/parser/regex/regex_test.go @@ -84,7 +84,7 @@ func TestParserRegex(t *testing.T) { }, &entry.Entry{ Body: "a=b", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "a": "b", }, }, @@ -100,7 +100,7 @@ func TestParserRegex(t *testing.T) { }, &entry.Entry{ Body: "a=b", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "a": "b", }, }, @@ -116,7 +116,7 @@ func TestParserRegex(t *testing.T) { }, &entry.Entry{ Body: "coredns-5644d7b6d9-mzngq_kube-system_coredns-901f7510281180a402936c92f5bc0f3557f5a21ccb5a4591c5bf98f3ddbffdd6.log", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "container_id": "901f7510281180a402936c92f5bc0f3557f5a21ccb5a4591c5bf98f3ddbffdd6", "container_name": "coredns", "namespace": "kube-system", diff --git a/pkg/stanza/operator/parser/scope/scope_name_test.go b/pkg/stanza/operator/parser/scope/scope_name_test.go index 83dfa39220af..f99b62e8c7c4 100644 --- a/pkg/stanza/operator/parser/scope/scope_name_test.go +++ b/pkg/stanza/operator/parser/scope/scope_name_test.go @@ -55,14 +55,14 @@ func TestScopeNameParser(t *testing.T) { }(), input: func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{"logger": testScopeName} + e.Body = map[string]any{"logger": testScopeName} e.ObservedTimestamp = now return e }(), expectErr: true, expected: func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{"logger": testScopeName} + e.Body = map[string]any{"logger": testScopeName} e.ObservedTimestamp = now return e }(), @@ -76,13 +76,13 @@ func TestScopeNameParser(t *testing.T) { }(), input: func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{"logger": testScopeName} + e.Body = map[string]any{"logger": testScopeName} e.ObservedTimestamp = now return e }(), expected: func() *entry.Entry { e := entry.New() - e.Body = map[string]interface{}{"logger": testScopeName} + e.Body = map[string]any{"logger": testScopeName} e.ScopeName = testScopeName e.ObservedTimestamp = now return e diff --git a/pkg/stanza/operator/parser/severity/severity_test.go b/pkg/stanza/operator/parser/severity/severity_test.go index d9d612b9a782..f381d0e8a477 100644 --- a/pkg/stanza/operator/parser/severity/severity_test.go +++ b/pkg/stanza/operator/parser/severity/severity_test.go @@ -17,23 +17,23 @@ import ( type severityTestCase struct { name string - sample interface{} + sample any mappingSet string - mapping map[string]interface{} + mapping map[string]any buildErr bool parseErr bool expected entry.Severity } func TestSeverityParser(t *testing.T) { - allTheThingsMap := map[string]interface{}{ + allTheThingsMap := map[string]any{ "info": "3xx", "error3": "4xx", "debug4": "5xx", - "trace2": []interface{}{ + "trace2": []any{ "ttttttracer", []byte{100, 100, 100}, - map[string]interface{}{"min": 1111, "max": 1234}, + map[string]any{"min": 1111, "max": 1234}, }, "fatal2": "", } @@ -66,103 +66,103 @@ func TestSeverityParser(t *testing.T) { { name: "custom-string", sample: "NOOOOOOO", - mapping: map[string]interface{}{"error": "NOOOOOOO"}, + mapping: map[string]any{"error": "NOOOOOOO"}, expected: entry.Error, }, { name: "custom-string-caps-key", sample: "NOOOOOOO", - mapping: map[string]interface{}{"ErRoR": "NOOOOOOO"}, + mapping: map[string]any{"ErRoR": "NOOOOOOO"}, expected: entry.Error, }, { name: "custom-int", sample: 1234, - mapping: map[string]interface{}{"error": 1234}, + mapping: map[string]any{"error": 1234}, expected: entry.Error, }, { name: "mixed-list-string", sample: "ThiS Is BaD", - mapping: map[string]interface{}{"error": []interface{}{"NOOOOOOO", "this is bad", 1234}}, + mapping: map[string]any{"error": []any{"NOOOOOOO", "this is bad", 1234}}, expected: entry.Error, }, { name: "mixed-list-int", sample: 1234, - mapping: map[string]interface{}{"error": []interface{}{"NOOOOOOO", "this is bad", 1234}}, + mapping: map[string]any{"error": []any{"NOOOOOOO", "this is bad", 1234}}, expected: entry.Error, }, { name: "in-range", sample: 123, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Error, }, { name: "in-range-min", sample: 120, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Error, }, { name: "in-range-max", sample: 125, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Error, }, { name: "out-of-range-min-minus", sample: 119, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Default, }, { name: "out-of-range-max-plus", sample: 126, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 120, "max": 125}}, + mapping: map[string]any{"error": map[string]any{"min": 120, "max": 125}}, expected: entry.Default, }, { name: "range-out-of-order", sample: 123, - mapping: map[string]interface{}{"error": map[string]interface{}{"min": 125, "max": 120}}, + mapping: map[string]any{"error": map[string]any{"min": 125, "max": 120}}, expected: entry.Error, }, { name: "Http2xx-hit", sample: 201, - mapping: map[string]interface{}{"error": "2xx"}, + mapping: map[string]any{"error": "2xx"}, expected: entry.Error, }, { name: "Http2xx-miss", sample: 301, - mapping: map[string]interface{}{"error": "2xx"}, + mapping: map[string]any{"error": "2xx"}, expected: entry.Default, }, { name: "Http3xx-hit", sample: 301, - mapping: map[string]interface{}{"error": "3xx"}, + mapping: map[string]any{"error": "3xx"}, expected: entry.Error, }, { name: "Http4xx-hit", sample: "404", - mapping: map[string]interface{}{"error": "4xx"}, + mapping: map[string]any{"error": "4xx"}, expected: entry.Error, }, { name: "Http5xx-hit", sample: 555, - mapping: map[string]interface{}{"error": "5xx"}, + mapping: map[string]any{"error": "5xx"}, expected: entry.Error, }, { name: "Http-All", sample: "301", - mapping: map[string]interface{}{"debug": "2xx", "info": "3xx", "error": "4xx", "warn": "5xx"}, + mapping: map[string]any{"debug": "2xx", "info": "3xx", "error": "4xx", "warn": "5xx"}, expected: entry.Info, }, { @@ -249,7 +249,7 @@ func runSeverityParseTest(cfg *Config, ent *entry.Entry, buildErr bool, parseErr } } -func parseSeverityTestConfig(parseFrom entry.Field, preset string, mapping map[string]interface{}) *Config { +func parseSeverityTestConfig(parseFrom entry.Field, preset string, mapping map[string]any) *Config { cfg := NewConfigWithID("test_operator_id") cfg.OutputIDs = []string{"output1"} cfg.SeverityConfig = helper.SeverityConfig{ @@ -260,7 +260,7 @@ func parseSeverityTestConfig(parseFrom entry.Field, preset string, mapping map[s return cfg } -func makeTestEntry(t *testing.T, field entry.Field, value interface{}) *entry.Entry { +func makeTestEntry(t *testing.T, field entry.Field, value any) *entry.Entry { e := entry.New() require.NoError(t, e.Set(field, value)) return e diff --git a/pkg/stanza/operator/parser/syslog/config_test.go b/pkg/stanza/operator/parser/syslog/config_test.go index 0cdc3c5b389f..d86a76b1824b 100644 --- a/pkg/stanza/operator/parser/syslog/config_test.go +++ b/pkg/stanza/operator/parser/syslog/config_test.go @@ -99,7 +99,7 @@ func TestUnmarshal(t *testing.T) { parseField := entry.NewBodyField("severity_field") severityParser := helper.NewSeverityConfig() severityParser.ParseFrom = &parseField - mapping := map[string]interface{}{ + mapping := map[string]any{ "critical": "5xx", "error": "4xx", "info": "3xx", diff --git a/pkg/stanza/operator/parser/syslog/data.go b/pkg/stanza/operator/parser/syslog/data.go index 378aa69d0b42..5c6b0f0009b5 100644 --- a/pkg/stanza/operator/parser/syslog/data.go +++ b/pkg/stanza/operator/parser/syslog/data.go @@ -71,7 +71,7 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { Timestamp: time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), ts.Minute(), ts.Second(), 0, location["utc"]), Severity: entry.Error2, SeverityText: "crit", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "appname": "apache_server", "facility": 4, "hostname": "1.2.3.4", @@ -98,7 +98,7 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { Timestamp: time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), ts.Minute(), ts.Second(), 0, location["detroit"]), Severity: entry.Error2, SeverityText: "crit", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "appname": "apache_server", "facility": 4, "hostname": "1.2.3.4", @@ -125,7 +125,7 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { Timestamp: time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), ts.Minute(), ts.Second(), 0, location["athens"]), Severity: entry.Error2, SeverityText: "crit", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "appname": "apache_server", "facility": 4, "hostname": "1.2.3.4", @@ -151,7 +151,7 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { Timestamp: time.Date(2015, 8, 5, 21, 58, 59, 693000000, time.UTC), Severity: entry.Info, SeverityText: "info", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "appname": "SecureAuth0", "facility": 10, "hostname": "192.168.2.132", @@ -159,8 +159,8 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { "msg_id": "ID52020", "priority": 86, "proc_id": "23108", - "structured_data": map[string]interface{}{ - "SecureAuth@27389": map[string]interface{}{ + "structured_data": map[string]any{ + "SecureAuth@27389": map[string]any{ "PEN": "27389", "Realm": "SecureAuth0", "UserHostAddress": "192.168.2.132", @@ -189,7 +189,7 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { Timestamp: time.Date(2015, 8, 5, 21, 58, 59, 693000000, time.UTC), Severity: entry.Info, SeverityText: "info", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "appname": "SecureAuth0", "facility": 10, "hostname": "192.168.2.132", @@ -197,8 +197,8 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { "msg_id": "ID52020", "priority": 86, "proc_id": "23108", - "structured_data": map[string]interface{}{ - "SecureAuth@27389": map[string]interface{}{ + "structured_data": map[string]any{ + "SecureAuth@27389": map[string]any{ "PEN": "27389", "Realm": "SecureAuth0", "UserHostAddress": "192.168.2.132", @@ -227,7 +227,7 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { Timestamp: time.Date(2015, 8, 5, 21, 58, 59, 693000000, time.UTC), Severity: entry.Info, SeverityText: "info", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "appname": "SecureAuth0", "facility": 10, "hostname": "192.168.2.132", @@ -235,8 +235,8 @@ func CreateCases(basicConfig func() *Config) ([]Case, error) { "msg_id": "ID52020", "priority": 86, "proc_id": "23108", - "structured_data": map[string]interface{}{ - "SecureAuth@27389": map[string]interface{}{ + "structured_data": map[string]any{ + "SecureAuth@27389": map[string]any{ "PEN": "27389", "Realm": "SecureAuth0", "UserHostAddress": "192.168.2.132", diff --git a/pkg/stanza/operator/parser/syslog/syslog.go b/pkg/stanza/operator/parser/syslog/syslog.go index f8e9b3efe3c1..376ed1baca4a 100644 --- a/pkg/stanza/operator/parser/syslog/syslog.go +++ b/pkg/stanza/operator/parser/syslog/syslog.go @@ -159,7 +159,7 @@ func (s *Parser) Process(ctx context.Context, entry *entry.Entry) error { } // parse will parse a value as syslog. -func (s *Parser) parse(value interface{}) (interface{}, error) { +func (s *Parser) parse(value any) (any, error) { bytes, err := toBytes(value) if err != nil { return nil, err @@ -186,8 +186,8 @@ func (s *Parser) parse(value interface{}) (interface{}, error) { } // parseRFC3164 will parse an RFC3164 syslog message. -func (s *Parser) parseRFC3164(syslogMessage *rfc3164.SyslogMessage) (map[string]interface{}, error) { - value := map[string]interface{}{ +func (s *Parser) parseRFC3164(syslogMessage *rfc3164.SyslogMessage) (map[string]any, error) { + value := map[string]any{ "timestamp": syslogMessage.Timestamp, "priority": syslogMessage.Priority, "facility": syslogMessage.Facility, @@ -202,8 +202,8 @@ func (s *Parser) parseRFC3164(syslogMessage *rfc3164.SyslogMessage) (map[string] } // parseRFC5424 will parse an RFC5424 syslog message. -func (s *Parser) parseRFC5424(syslogMessage *rfc5424.SyslogMessage) (map[string]interface{}, error) { - value := map[string]interface{}{ +func (s *Parser) parseRFC5424(syslogMessage *rfc5424.SyslogMessage) (map[string]any, error) { + value := map[string]any{ "timestamp": syslogMessage.Timestamp, "priority": syslogMessage.Priority, "facility": syslogMessage.Facility, @@ -220,7 +220,7 @@ func (s *Parser) parseRFC5424(syslogMessage *rfc5424.SyslogMessage) (map[string] } // toSafeMap will dereference any pointers on the supplied map. -func (s *Parser) toSafeMap(message map[string]interface{}) (map[string]interface{}, error) { +func (s *Parser) toSafeMap(message map[string]any) (map[string]any, error) { for key, val := range message { switch v := val.(type) { case *string: @@ -257,13 +257,13 @@ func (s *Parser) toSafeMap(message map[string]interface{}) (map[string]interface return message, nil } -// convertMap converts map[string]map[string]string to map[string]interface{} +// convertMap converts map[string]map[string]string to map[string]any // which is expected by stanza converter -func convertMap(data map[string]map[string]string) map[string]interface{} { - ret := map[string]interface{}{} +func convertMap(data map[string]map[string]string) map[string]any { + ret := map[string]any{} for key, value := range data { - ret[key] = map[string]interface{}{} - r := ret[key].(map[string]interface{}) + ret[key] = map[string]any{} + r := ret[key].(map[string]any) for k, v := range value { r[k] = v @@ -273,7 +273,7 @@ func convertMap(data map[string]map[string]string) map[string]interface{} { return ret } -func toBytes(value interface{}) ([]byte, error) { +func toBytes(value any) ([]byte, error) { switch v := value.(type) { case string: return []byte(v), nil diff --git a/pkg/stanza/operator/parser/time/time_test.go b/pkg/stanza/operator/parser/time/time_test.go index 1785c8db405b..f88bb17a0ed4 100644 --- a/pkg/stanza/operator/parser/time/time_test.go +++ b/pkg/stanza/operator/parser/time/time_test.go @@ -99,7 +99,7 @@ func TestProcess(t *testing.T) { input: func() *entry.Entry { e := entry.New() e.ObservedTimestamp = now - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "app_time": "Mon Jan 2 15:04:05 UTC 2006", } return e @@ -107,7 +107,7 @@ func TestProcess(t *testing.T) { expect: &entry.Entry{ ObservedTimestamp: now, Timestamp: time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC), - Body: map[string]interface{}{ + Body: map[string]any{ "app_time": "Mon Jan 2 15:04:05 UTC 2006", }, }, @@ -147,7 +147,7 @@ func TestTimeParser(t *testing.T) { testCases := []struct { name string - sample interface{} + sample any expected time.Time gotimeLayout string strptimeLayout string @@ -269,7 +269,7 @@ func TestTimeParser(t *testing.T) { func TestTimeEpochs(t *testing.T) { testCases := []struct { name string - sample interface{} + sample any layout string expected time.Time maxLoss time.Duration @@ -430,7 +430,7 @@ func TestTimeEpochs(t *testing.T) { func TestTimeErrors(t *testing.T) { testCases := []struct { name string - sample interface{} + sample any layoutType string layout string buildErr bool @@ -489,7 +489,7 @@ func TestTimeErrors(t *testing.T) { } } -func makeTestEntry(t *testing.T, field entry.Field, value interface{}) *entry.Entry { +func makeTestEntry(t *testing.T, field entry.Field, value any) *entry.Entry { e := entry.New() require.NoError(t, e.Set(field, value)) return e diff --git a/pkg/stanza/operator/parser/trace/trace_test.go b/pkg/stanza/operator/parser/trace/trace_test.go index a3226628b832..d14a40b86eef 100644 --- a/pkg/stanza/operator/parser/trace/trace_test.go +++ b/pkg/stanza/operator/parser/trace/trace_test.go @@ -131,7 +131,7 @@ func TestProcess(t *testing.T) { return cfg.Build(testutil.Logger(t)) }, &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "app_span_id": "480140f3d770a5ae32f0a22b6a812cff", "app_trace_id": "92c3792d54ba94f3", "trace_flags_field": "01", @@ -141,7 +141,7 @@ func TestProcess(t *testing.T) { SpanID: testSpanIDBytes, TraceID: testTraceIDBytes, TraceFlags: testTraceFlagsBytes, - Body: map[string]interface{}{ + Body: map[string]any{ "app_span_id": "480140f3d770a5ae32f0a22b6a812cff", "app_trace_id": "92c3792d54ba94f3", "trace_flags_field": "01", @@ -165,8 +165,8 @@ func TestProcess(t *testing.T) { func TestTraceParserParse(t *testing.T) { cases := []struct { name string - inputRecord map[string]interface{} - expectedRecord map[string]interface{} + inputRecord map[string]any + expectedRecord map[string]any expectErr bool traceID string spanID string @@ -174,12 +174,12 @@ func TestTraceParserParse(t *testing.T) { }{ { "AllFields", - map[string]interface{}{ + map[string]any{ "trace_id": "480140f3d770a5ae32f0a22b6a812cff", "span_id": "92c3792d54ba94f3", "trace_flags": "01", }, - map[string]interface{}{ + map[string]any{ "trace_id": "480140f3d770a5ae32f0a22b6a812cff", "span_id": "92c3792d54ba94f3", "trace_flags": "01", @@ -191,12 +191,12 @@ func TestTraceParserParse(t *testing.T) { }, { "WrongFields", - map[string]interface{}{ + map[string]any{ "traceId": "480140f3d770a5ae32f0a22b6a812cff", "traceFlags": "01", "spanId": "92c3792d54ba94f3", }, - map[string]interface{}{ + map[string]any{ "traceId": "480140f3d770a5ae32f0a22b6a812cff", "spanId": "92c3792d54ba94f3", "traceFlags": "01", @@ -208,10 +208,10 @@ func TestTraceParserParse(t *testing.T) { }, { "OnlyTraceId", - map[string]interface{}{ + map[string]any{ "trace_id": "480140f3d770a5ae32f0a22b6a812cff", }, - map[string]interface{}{ + map[string]any{ "trace_id": "480140f3d770a5ae32f0a22b6a812cff", }, false, @@ -221,12 +221,12 @@ func TestTraceParserParse(t *testing.T) { }, { "WrongTraceIdFormat", - map[string]interface{}{ + map[string]any{ "trace_id": "foo_bar", "span_id": "92c3792d54ba94f3", "trace_flags": "01", }, - map[string]interface{}{ + map[string]any{ "trace_id": "foo_bar", "span_id": "92c3792d54ba94f3", "trace_flags": "01", @@ -238,12 +238,12 @@ func TestTraceParserParse(t *testing.T) { }, { "WrongTraceFlagFormat", - map[string]interface{}{ + map[string]any{ "trace_id": "480140f3d770a5ae32f0a22b6a812cff", "span_id": "92c3792d54ba94f3", "trace_flags": "foo_bar", }, - map[string]interface{}{ + map[string]any{ "trace_id": "480140f3d770a5ae32f0a22b6a812cff", "span_id": "92c3792d54ba94f3", "trace_flags": "foo_bar", diff --git a/pkg/stanza/operator/parser/uri/config_test.go b/pkg/stanza/operator/parser/uri/config_test.go index 71582458fa54..325a136a3040 100644 --- a/pkg/stanza/operator/parser/uri/config_test.go +++ b/pkg/stanza/operator/parser/uri/config_test.go @@ -65,7 +65,7 @@ func TestParserGoldenConfig(t *testing.T) { parseField := entry.NewBodyField("severity_field") severityField := helper.NewSeverityConfig() severityField.ParseFrom = &parseField - mapping := map[string]interface{}{ + mapping := map[string]any{ "critical": "5xx", "error": "4xx", "info": "3xx", diff --git a/pkg/stanza/operator/parser/uri/uri.go b/pkg/stanza/operator/parser/uri/uri.go index 8199fcc0d67a..621709c8364b 100644 --- a/pkg/stanza/operator/parser/uri/uri.go +++ b/pkg/stanza/operator/parser/uri/uri.go @@ -62,7 +62,7 @@ func (u *Parser) Process(ctx context.Context, entry *entry.Entry) error { } // parse will parse a uri from a field and attach it to an entry. -func (u *Parser) parse(value interface{}) (interface{}, error) { +func (u *Parser) parse(value any) (any, error) { switch m := value.(type) { case string: return parseURI(m) @@ -72,8 +72,8 @@ func (u *Parser) parse(value interface{}) (interface{}, error) { } // parseURI takes an absolute or relative uri and returns the parsed values. -func parseURI(value string) (map[string]interface{}, error) { - m := make(map[string]interface{}) +func parseURI(value string) (map[string]any, error) { + m := make(map[string]any) if strings.HasPrefix(value, "?") { // remove the query string '?' prefix before parsing @@ -92,7 +92,7 @@ func parseURI(value string) (map[string]interface{}, error) { } // urlToMap converts a url.URL to a map, excludes any values that are not set. -func urlToMap(p *url.URL, m map[string]interface{}) map[string]interface{} { +func urlToMap(p *url.URL, m map[string]any) map[string]any { scheme := p.Scheme if scheme != "" { m["scheme"] = scheme @@ -122,25 +122,25 @@ func urlToMap(p *url.URL, m map[string]interface{}) map[string]interface{} { } // queryToMap converts a query string url.Values to a map. -func queryToMap(query url.Values, m map[string]interface{}) map[string]interface{} { +func queryToMap(query url.Values, m map[string]any) map[string]any { // no-op if query is empty, do not create the key m["query"] if len(query) == 0 { return m } /* 'parameter' will represent url.Values - map[string]interface{}{ - "parameter-a": []interface{}{ + map[string]any{ + "parameter-a": []any{ "a", "b", }, - "parameter-b": []interface{}{ + "parameter-b": []any{ "x", "y", }, } */ - parameters := map[string]interface{}{} + parameters := map[string]any{} for param, values := range query { parameters[param] = queryParamValuesToMap(values) } @@ -150,8 +150,8 @@ func queryToMap(query url.Values, m map[string]interface{}) map[string]interface // queryParamValuesToMap takes query string parameter values and // returns an []interface populated with the values -func queryParamValuesToMap(values []string) []interface{} { - v := make([]interface{}, len(values)) +func queryParamValuesToMap(values []string) []any { + v := make([]any, len(values)) for i, value := range values { v[i] = value } diff --git a/pkg/stanza/operator/parser/uri/uri_test.go b/pkg/stanza/operator/parser/uri/uri_test.go index 011546a919b5..a1160c8d4c8c 100644 --- a/pkg/stanza/operator/parser/uri/uri_test.go +++ b/pkg/stanza/operator/parser/uri/uri_test.go @@ -74,12 +74,12 @@ func TestProcess(t *testing.T) { Body: "https://google.com:443/path?user=dev", }, &entry.Entry{ - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "host": "google.com", "port": "443", "path": "/path", - "query": map[string]interface{}{ - "user": []interface{}{ + "query": map[string]any{ + "user": []any{ "dev", }, }, @@ -97,19 +97,19 @@ func TestProcess(t *testing.T) { return cfg.Build(testutil.Logger(t)) }, &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "url": "https://google.com:443/path?user=dev", }, }, &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "url": "https://google.com:443/path?user=dev", - "url2": map[string]interface{}{ + "url2": map[string]any{ "host": "google.com", "port": "443", "path": "/path", - "query": map[string]interface{}{ - "user": []interface{}{ + "query": map[string]any{ + "user": []any{ "dev", }, }, @@ -126,20 +126,20 @@ func TestProcess(t *testing.T) { return cfg.Build(testutil.Logger(t)) }, &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "url": "https://google.com:443/path?user=dev", }, }, &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "url": "https://google.com:443/path?user=dev", }, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "host": "google.com", "port": "443", "path": "/path", - "query": map[string]interface{}{ - "user": []interface{}{ + "query": map[string]any{ + "user": []any{ "dev", }, }, @@ -164,19 +164,19 @@ func TestProcess(t *testing.T) { func TestParserParse(t *testing.T) { cases := []struct { name string - inputBody interface{} - outputBody map[string]interface{} + inputBody any + outputBody map[string]any expectErr bool }{ { "string", "http://www.google.com/app?env=prod", - map[string]interface{}{ + map[string]any{ "scheme": "http", "host": "www.google.com", "path": "/app", - "query": map[string]interface{}{ - "env": []interface{}{ + "query": map[string]any{ + "env": []any{ "prod", }, }, @@ -204,13 +204,13 @@ func TestParseURI(t *testing.T) { cases := []struct { name string inputBody string - outputBody map[string]interface{} + outputBody map[string]any expectErr bool }{ { "scheme-http", "http://", - map[string]interface{}{ + map[string]any{ "scheme": "http", }, false, @@ -218,7 +218,7 @@ func TestParseURI(t *testing.T) { { "scheme-user", "http://myuser:mypass@", - map[string]interface{}{ + map[string]any{ "scheme": "http", "user": "myuser", }, @@ -227,7 +227,7 @@ func TestParseURI(t *testing.T) { { "scheme-host", "http://golang.com", - map[string]interface{}{ + map[string]any{ "scheme": "http", "host": "golang.com", }, @@ -236,7 +236,7 @@ func TestParseURI(t *testing.T) { { "scheme-host-root", "http://golang.com/", - map[string]interface{}{ + map[string]any{ "scheme": "http", "host": "golang.com", "path": "/", @@ -246,7 +246,7 @@ func TestParseURI(t *testing.T) { { "scheme-host-minimal", "http://golang", - map[string]interface{}{ + map[string]any{ "scheme": "http", "host": "golang", }, @@ -255,13 +255,13 @@ func TestParseURI(t *testing.T) { { "host-missing-scheme", "golang.org", - map[string]interface{}{}, + map[string]any{}, true, }, { "sheme-port", "http://:8080", - map[string]interface{}{ + map[string]any{ "scheme": "http", "port": "8080", }, @@ -270,13 +270,13 @@ func TestParseURI(t *testing.T) { { "port-missing-scheme", ":8080", - map[string]interface{}{}, + map[string]any{}, true, }, { "path", "/docs", - map[string]interface{}{ + map[string]any{ "path": "/docs", }, false, @@ -284,7 +284,7 @@ func TestParseURI(t *testing.T) { { "path-advanced", `/x/y%2Fz`, - map[string]interface{}{ + map[string]any{ "path": `/x/y%2Fz`, }, false, @@ -292,7 +292,7 @@ func TestParseURI(t *testing.T) { { "path-root", "/", - map[string]interface{}{ + map[string]any{ "path": "/", }, false, @@ -300,10 +300,10 @@ func TestParseURI(t *testing.T) { { "path-query", "/v1/app?user=golang", - map[string]interface{}{ + map[string]any{ "path": "/v1/app", - "query": map[string]interface{}{ - "user": []interface{}{ + "query": map[string]any{ + "user": []any{ "golang", }, }, @@ -313,13 +313,13 @@ func TestParseURI(t *testing.T) { { "invalid-query", "?q;go", - map[string]interface{}{}, + map[string]any{}, true, }, { "scheme-path", "http:///v1/app", - map[string]interface{}{ + map[string]any{ "scheme": "http", "path": "/v1/app", }, @@ -328,14 +328,14 @@ func TestParseURI(t *testing.T) { { "scheme-host-query", "https://app.com?token=0000&env=prod&env=stage", - map[string]interface{}{ + map[string]any{ "scheme": "https", "host": "app.com", - "query": map[string]interface{}{ - "token": []interface{}{ + "query": map[string]any{ + "token": []any{ "0000", }, - "env": []interface{}{ + "env": []any{ "prod", "stage", }, @@ -346,7 +346,7 @@ func TestParseURI(t *testing.T) { { "minimal", "http://golang.org", - map[string]interface{}{ + map[string]any{ "scheme": "http", "host": "golang.org", }, @@ -355,20 +355,20 @@ func TestParseURI(t *testing.T) { { "advanced", "https://go:password@golang.org:8443/v2/app?env=stage&token=456&index=105838&env=prod", - map[string]interface{}{ + map[string]any{ "scheme": "https", "user": "go", "host": "golang.org", "port": "8443", "path": "/v2/app", - "query": map[string]interface{}{ - "token": []interface{}{ + "query": map[string]any{ + "token": []any{ "456", }, - "index": []interface{}{ + "index": []any{ "105838", }, - "env": []interface{}{ + "env": []any{ "stage", "prod", }, @@ -379,10 +379,10 @@ func TestParseURI(t *testing.T) { { "magnet", "magnet:?xt=urn:sha1:HNCKHTQCWBTRNJIV4WNAE52SJUQCZO6C", - map[string]interface{}{ + map[string]any{ "scheme": "magnet", - "query": map[string]interface{}{ - "xt": []interface{}{ + "query": map[string]any{ + "xt": []any{ "urn:sha1:HNCKHTQCWBTRNJIV4WNAE52SJUQCZO6C", }, }, @@ -392,7 +392,7 @@ func TestParseURI(t *testing.T) { { "sftp", "sftp://ftp.com//home/name/employee.csv", - map[string]interface{}{ + map[string]any{ "scheme": "sftp", "host": "ftp.com", "path": "//home/name/employee.csv", @@ -402,26 +402,26 @@ func TestParseURI(t *testing.T) { { "missing-schema", "golang.org/app", - map[string]interface{}{}, + map[string]any{}, true, }, { "query-advanced", "?token=0000&env=prod&env=stage&task=update&task=new&action=update", - map[string]interface{}{ - "query": map[string]interface{}{ - "token": []interface{}{ + map[string]any{ + "query": map[string]any{ + "token": []any{ "0000", }, - "env": []interface{}{ + "env": []any{ "prod", "stage", }, - "task": []interface{}{ + "task": []any{ "update", "new", }, - "action": []interface{}{ + "action": []any{ "update", }, }, @@ -431,9 +431,9 @@ func TestParseURI(t *testing.T) { { "query", "?token=0000", - map[string]interface{}{ - "query": map[string]interface{}{ - "token": []interface{}{ + map[string]any{ + "query": map[string]any{ + "token": []any{ "0000", }, }, @@ -443,15 +443,15 @@ func TestParseURI(t *testing.T) { { "query-empty", "?", - map[string]interface{}{}, + map[string]any{}, false, }, { "query-empty-key", "?user=", - map[string]interface{}{ - "query": map[string]interface{}{ - "user": []interface{}{ + map[string]any{ + "query": map[string]any{ + "user": []any{ "", // no value }, }, @@ -463,7 +463,7 @@ func TestParseURI(t *testing.T) { { "query-no-?-prefix", "user=dev", - map[string]interface{}{}, + map[string]any{}, true, }, } @@ -499,7 +499,7 @@ func TestURLToMap(t *testing.T) { cases := []struct { name string inputBody *url.URL - outputBody map[string]interface{} + outputBody map[string]any }{ { "absolute-uri", @@ -509,13 +509,13 @@ func TestURLToMap(t *testing.T) { Path: "/app", RawQuery: "stage=prod&stage=dev", }, - map[string]interface{}{ + map[string]any{ "scheme": "https", "host": "google.com", "port": "8443", "path": "/app", - "query": map[string]interface{}{ - "stage": []interface{}{ + "query": map[string]any{ + "stage": []any{ "prod", "dev", }, @@ -528,7 +528,7 @@ func TestURLToMap(t *testing.T) { Scheme: "http", Host: "google.com", }, - map[string]interface{}{ + map[string]any{ "scheme": "http", "host": "google.com", }, @@ -539,10 +539,10 @@ func TestURLToMap(t *testing.T) { Path: "/app", RawQuery: "stage=prod&stage=dev", }, - map[string]interface{}{ + map[string]any{ "path": "/app", - "query": map[string]interface{}{ - "stage": []interface{}{ + "query": map[string]any{ + "stage": []any{ "prod", "dev", }, @@ -554,7 +554,7 @@ func TestURLToMap(t *testing.T) { &url.URL{ Path: "/app", }, - map[string]interface{}{ + map[string]any{ "path": "/app", }, }, @@ -563,9 +563,9 @@ func TestURLToMap(t *testing.T) { &url.URL{ RawQuery: "stage=prod&stage=dev", }, - map[string]interface{}{ - "query": map[string]interface{}{ - "stage": []interface{}{ + map[string]any{ + "query": map[string]any{ + "stage": []any{ "prod", "dev", }, @@ -576,7 +576,7 @@ func TestURLToMap(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - m := make(map[string]interface{}) + m := make(map[string]any) require.Equal(t, tc.outputBody, urlToMap(tc.inputBody, m)) }) } @@ -586,7 +586,7 @@ func TestQueryToMap(t *testing.T) { cases := []struct { name string inputBody url.Values - outputBody map[string]interface{} + outputBody map[string]any }{ { "query", @@ -596,9 +596,9 @@ func TestQueryToMap(t *testing.T) { "dev", }, }, - map[string]interface{}{ - "query": map[string]interface{}{ - "stage": []interface{}{ + map[string]any{ + "query": map[string]any{ + "stage": []any{ "prod", "dev", }, @@ -608,13 +608,13 @@ func TestQueryToMap(t *testing.T) { { "empty", url.Values{}, - map[string]interface{}{}, + map[string]any{}, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - m := make(map[string]interface{}) + m := make(map[string]any) require.Equal(t, tc.outputBody, queryToMap(tc.inputBody, m)) }) } @@ -624,7 +624,7 @@ func TestQueryParamValuesToMap(t *testing.T) { cases := []struct { name string inputBody []string - outputBody []interface{} + outputBody []any }{ { "simple", @@ -632,7 +632,7 @@ func TestQueryParamValuesToMap(t *testing.T) { "prod", "dev", }, - []interface{}{ + []any{ "prod", "dev", }, @@ -640,7 +640,7 @@ func TestQueryParamValuesToMap(t *testing.T) { { "empty", []string{}, - []interface{}{}, + []any{}, }, } @@ -662,7 +662,7 @@ func BenchmarkParserParse(b *testing.B) { } func BenchmarkURLToMap(b *testing.B) { - m := make(map[string]interface{}) + m := make(map[string]any) v := "https://dev:password@www.golang.org:8443/v1/app/stage?token=d9e28b1d-2c7b-4853-be6a-d94f34a5d4ab&env=prod&env=stage&token=c6fa29f9-a31b-4584-b98d-aa8473b0e18d®ion=us-east1b&mode=fast" u, err := url.ParseRequestURI(v) if err != nil { @@ -674,7 +674,7 @@ func BenchmarkURLToMap(b *testing.B) { } func BenchmarkQueryToMap(b *testing.B) { - m := make(map[string]interface{}) + m := make(map[string]any) v := "?token=d9e28b1d-2c7b-4853-be6a-d94f34a5d4ab&env=prod&env=stage&token=c6fa29f9-a31b-4584-b98d-aa8473b0e18d®ion=us-east1b&mode=fast" u, err := url.ParseQuery(v) if err != nil { diff --git a/pkg/stanza/operator/transformer/add/add.go b/pkg/stanza/operator/transformer/add/add.go index ab6bba81873a..428024385c54 100644 --- a/pkg/stanza/operator/transformer/add/add.go +++ b/pkg/stanza/operator/transformer/add/add.go @@ -38,7 +38,7 @@ func NewConfigWithID(operatorID string) *Config { type Config struct { helper.TransformerConfig `mapstructure:",squash"` Field entry.Field `mapstructure:"field"` - Value interface{} `mapstructure:"value,omitempty"` + Value any `mapstructure:"value,omitempty"` } // Build will build an add operator from the supplied configuration @@ -74,7 +74,7 @@ type Transformer struct { helper.TransformerOperator Field entry.Field - Value interface{} + Value any program *vm.Program } diff --git a/pkg/stanza/operator/transformer/add/add_test.go b/pkg/stanza/operator/transformer/add/add_test.go index c30ec16ed698..1d491b41ae9c 100644 --- a/pkg/stanza/operator/transformer/add/add_test.go +++ b/pkg/stanza/operator/transformer/add/add_test.go @@ -29,9 +29,9 @@ func TestProcessAndBuild(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Timestamp = time.Unix(1586632809, 0) - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -50,7 +50,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body.(map[string]interface{})["new"] = "randomMessage" + e.Body.(map[string]any)["new"] = "randomMessage" return e }, false, @@ -66,7 +66,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body.(map[string]interface{})["new"] = "val_suffix" + e.Body.(map[string]any)["new"] = "val_suffix" return e }, false, @@ -76,8 +76,8 @@ func TestProcessAndBuild(t *testing.T) { func() *Config { cfg := NewConfig() cfg.Field = entry.NewBodyField("new") - cfg.Value = map[interface{}]interface{}{ - "nest": map[interface{}]interface{}{ + cfg.Value = map[any]any{ + "nest": map[any]any{ "key": "val", }, } @@ -86,13 +86,13 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, - "new": map[interface{}]interface{}{ - "nest": map[interface{}]interface{}{ + "new": map[any]any{ + "nest": map[any]any{ "key": "val", }, }, @@ -112,7 +112,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"new": "some.attribute"} + e.Attributes = map[string]any{"new": "some.attribute"} return e }, false, @@ -128,7 +128,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{"new": "some.resource"} + e.Resource = map[string]any{"new": "some.resource"} return e }, false, @@ -144,7 +144,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{"new": "val_suffix"} + e.Resource = map[string]any{"new": "val_suffix"} return e }, false, @@ -160,9 +160,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, "new": 1, @@ -182,9 +182,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, "new": []int{1, 2, 3, 4}, @@ -204,9 +204,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": []int{1, 2, 3, 4}, - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -225,7 +225,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "new": 1, } return e @@ -243,7 +243,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "new": 1, } return e @@ -255,7 +255,7 @@ func TestProcessAndBuild(t *testing.T) { func() *Config { cfg := NewConfig() cfg.Field = entry.NewAttributeField("one", "two") - cfg.Value = map[string]interface{}{ + cfg.Value = map[string]any{ "new": 1, } return cfg @@ -263,9 +263,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Attributes = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "new": 1, }, }, @@ -279,7 +279,7 @@ func TestProcessAndBuild(t *testing.T) { func() *Config { cfg := NewConfig() cfg.Field = entry.NewResourceField("one", "two") - cfg.Value = map[string]interface{}{ + cfg.Value = map[string]any{ "new": 1, } return cfg @@ -287,9 +287,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Resource = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "new": 1, }, }, @@ -309,7 +309,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "fookey": "foo_val", } return e @@ -327,7 +327,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "fookey": "foo_val", } return e diff --git a/pkg/stanza/operator/transformer/add/config_test.go b/pkg/stanza/operator/transformer/add/config_test.go index 6abd54a26e1f..90b84b6848e6 100644 --- a/pkg/stanza/operator/transformer/add/config_test.go +++ b/pkg/stanza/operator/transformer/add/config_test.go @@ -39,8 +39,8 @@ func TestUnmarshal(t *testing.T) { Expect: func() *Config { cfg := NewConfig() cfg.Field = entry.NewBodyField("new") - cfg.Value = map[string]interface{}{ - "nest": map[string]interface{}{"key": "val"}, + cfg.Value = map[string]any{ + "nest": map[string]any{"key": "val"}, } return cfg }(), @@ -68,8 +68,8 @@ func TestUnmarshal(t *testing.T) { Expect: func() *Config { cfg := NewConfig() cfg.Field = entry.NewAttributeField("one", "two") - cfg.Value = map[string]interface{}{ - "nest": map[string]interface{}{"key": "val"}, + cfg.Value = map[string]any{ + "nest": map[string]any{"key": "val"}, } return cfg }(), @@ -97,8 +97,8 @@ func TestUnmarshal(t *testing.T) { Expect: func() *Config { cfg := NewConfig() cfg.Field = entry.NewResourceField("one", "two") - cfg.Value = map[string]interface{}{ - "nest": map[string]interface{}{"key": "val"}, + cfg.Value = map[string]any{ + "nest": map[string]any{"key": "val"}, } return cfg }(), @@ -117,7 +117,7 @@ func TestUnmarshal(t *testing.T) { Expect: func() *Config { cfg := NewConfig() cfg.Field = entry.NewBodyField("new") - cfg.Value = []interface{}{1, 2, 3, 4} + cfg.Value = []any{1, 2, 3, 4} return cfg }(), }, @@ -126,7 +126,7 @@ func TestUnmarshal(t *testing.T) { Expect: func() *Config { cfg := NewConfig() cfg.Field = entry.NewAttributeField("new") - cfg.Value = []interface{}{1, 2, 3, 4} + cfg.Value = []any{1, 2, 3, 4} return cfg }(), }, @@ -136,7 +136,7 @@ func TestUnmarshal(t *testing.T) { Expect: func() *Config { cfg := NewConfig() cfg.Field = entry.NewResourceField("new") - cfg.Value = []interface{}{1, 2, 3, 4} + cfg.Value = []any{1, 2, 3, 4} return cfg }(), }, diff --git a/pkg/stanza/operator/transformer/copy/copy_test.go b/pkg/stanza/operator/transformer/copy/copy_test.go index f408a7c63022..fd695171be81 100644 --- a/pkg/stanza/operator/transformer/copy/copy_test.go +++ b/pkg/stanza/operator/transformer/copy/copy_test.go @@ -29,9 +29,9 @@ func TestBuildAndProcess(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Timestamp = time.Unix(1586632809, 0) - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -51,9 +51,9 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, "key2": "val", @@ -73,9 +73,9 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, "key2": "nestedval", @@ -95,9 +95,9 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", "key2": "val", }, @@ -117,13 +117,13 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } - e.Attributes = map[string]interface{}{"key2": "val"} + e.Attributes = map[string]any{"key2": "val"} return e }, }, @@ -139,11 +139,11 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Attributes = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, }, @@ -164,11 +164,11 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Resource = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, }, @@ -188,19 +188,19 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"key": "val"} + e.Attributes = map[string]any{"key": "val"} return e }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, "key2": "val", } - e.Attributes = map[string]interface{}{"key": "val"} + e.Attributes = map[string]any{"key": "val"} return e }, }, @@ -215,13 +215,13 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"key": "val"} + e.Attributes = map[string]any{"key": "val"} return e }, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"key": "val"} - e.Resource = map[string]interface{}{"key2": "val"} + e.Attributes = map[string]any{"key": "val"} + e.Resource = map[string]any{"key2": "val"} return e }, }, @@ -237,7 +237,7 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", "nested": "val", } diff --git a/pkg/stanza/operator/transformer/filter/filter_test.go b/pkg/stanza/operator/transformer/filter/filter_test.go index c286852badee..ea44bb0c5d7d 100644 --- a/pkg/stanza/operator/transformer/filter/filter_test.go +++ b/pkg/stanza/operator/transformer/filter/filter_test.go @@ -29,7 +29,7 @@ func TestTransformer(t *testing.T) { { "BodyMatch", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -39,7 +39,7 @@ func TestTransformer(t *testing.T) { { "NoMatchBody", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "invalid", }, }, @@ -49,10 +49,10 @@ func TestTransformer(t *testing.T) { { "MatchAttribute", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "key": "value", }, }, @@ -62,9 +62,9 @@ func TestTransformer(t *testing.T) { { "MatchBodyNested", &entry.Entry{ - Body: map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + Body: map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "key": "value", }, }, @@ -76,12 +76,12 @@ func TestTransformer(t *testing.T) { { "MatchAttributeNested", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, - Attributes: map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + Attributes: map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "key": "value", }, }, @@ -93,12 +93,12 @@ func TestTransformer(t *testing.T) { { "MatchResourceNested", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, - Resource: map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + Resource: map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "key": "value", }, }, @@ -110,11 +110,11 @@ func TestTransformer(t *testing.T) { { "MatchResourceBracketed", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, - Resource: map[string]interface{}{ - "one": map[string]interface{}{ + Resource: map[string]any{ + "one": map[string]any{ "two.stilltwo": "value", }, }, @@ -125,7 +125,7 @@ func TestTransformer(t *testing.T) { { "NoMatchAttribute", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -135,7 +135,7 @@ func TestTransformer(t *testing.T) { { "MatchEnv", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -145,7 +145,7 @@ func TestTransformer(t *testing.T) { { "NoMatchEnv", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -198,7 +198,7 @@ func TestFilterDropRatio(t *testing.T) { require.True(t, ok) testEntry := &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, } diff --git a/pkg/stanza/operator/transformer/flatten/flatten.go b/pkg/stanza/operator/transformer/flatten/flatten.go index 25a07d9641b8..f40eef2564a6 100644 --- a/pkg/stanza/operator/transformer/flatten/flatten.go +++ b/pkg/stanza/operator/transformer/flatten/flatten.go @@ -95,7 +95,7 @@ func (p *Transformer[T]) Transform(entry *entry.Entry) error { return fmt.Errorf("apply flatten: field %s does not exist on entry", p.Field) } - valMap, ok := val.(map[string]interface{}) + valMap, ok := val.(map[string]any) if !ok { // The field we were asked to flatten was not a map, so put it back err := entry.Set(p.Field, val) diff --git a/pkg/stanza/operator/transformer/flatten/flatten_test.go b/pkg/stanza/operator/transformer/flatten/flatten_test.go index 4ce1fabafff6..491a58d2fc3d 100644 --- a/pkg/stanza/operator/transformer/flatten/flatten_test.go +++ b/pkg/stanza/operator/transformer/flatten/flatten_test.go @@ -29,21 +29,21 @@ func TestBuildAndProcess(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Timestamp = time.Unix(1586632809, 0) - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -61,7 +61,7 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", "nestedkey": "nestedval", } @@ -78,9 +78,9 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey1": "nestedval", "nestedkey2": "nestedval", "nestedkey3": "nestedval", @@ -91,7 +91,7 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", "nestedkey1": "nestedval", "nestedkey2": "nestedval", @@ -111,10 +111,10 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ - "secondlevel": map[string]interface{}{ + "nested": map[string]any{ + "secondlevel": map[string]any{ "nestedkey": "nestedval", }, }, @@ -123,9 +123,9 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -142,10 +142,10 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ - "secondlevel": map[string]interface{}{ + "nested": map[string]any{ + "secondlevel": map[string]any{ "nestedkey1": "nestedval", "nestedkey2": "nestedval", "nestedkey3": "nestedval", @@ -157,9 +157,9 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey1": "nestedval", "nestedkey2": "nestedval", "nestedkey3": "nestedval", @@ -179,10 +179,10 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ - "secondlevel": map[string]interface{}{ + "nested": map[string]any{ + "secondlevel": map[string]any{ "nestedkey": "nestedval", }, }, @@ -191,9 +191,9 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "secondlevel": map[string]interface{}{ + "secondlevel": map[string]any{ "nestedkey": "nestedval", }, } @@ -210,9 +210,9 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "key": "nestedval", }, } @@ -220,7 +220,7 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "nestedval", } return e @@ -247,10 +247,10 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", - "nested": map[string]interface{}{ - "secondlevel": map[string]interface{}{ + "nested": map[string]any{ + "secondlevel": map[string]any{ "nestedkey1": "nestedval", "nestedkey2": "nestedval", "nestedkey3": "nestedval", @@ -262,9 +262,9 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey1": "nestedval", "nestedkey2": "nestedval", "nestedkey3": "nestedval", @@ -284,10 +284,10 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", - "nested": map[string]interface{}{ - "secondlevel": map[string]interface{}{ + "nested": map[string]any{ + "secondlevel": map[string]any{ "nestedkey1": "nestedval", "nestedkey2": "nestedval", "nestedkey3": "nestedval", @@ -299,9 +299,9 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey1": "nestedval", "nestedkey2": "nestedval", "nestedkey3": "nestedval", diff --git a/pkg/stanza/operator/transformer/move/move_test.go b/pkg/stanza/operator/transformer/move/move_test.go index 81bdc1c6fc35..b991292321b4 100644 --- a/pkg/stanza/operator/transformer/move/move_test.go +++ b/pkg/stanza/operator/transformer/move/move_test.go @@ -29,9 +29,9 @@ func TestProcessAndBuild(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Timestamp = time.Unix(1586632809, 0) - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -51,9 +51,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "new": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -72,12 +72,12 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ - "nested": map[string]interface{}{ + e.Body = map[string]any{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } - e.Attributes = map[string]interface{}{"new": "val"} + e.Attributes = map[string]any{"new": "val"} return e }, }, @@ -92,19 +92,19 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"new": "val"} + e.Attributes = map[string]any{"new": "val"} return e }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", "new": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } - e.Attributes = map[string]interface{}{} + e.Attributes = map[string]any{} return e }, }, @@ -119,13 +119,13 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"new": "val"} + e.Attributes = map[string]any{"new": "val"} return e }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{"new": "val"} - e.Attributes = map[string]interface{}{} + e.Resource = map[string]any{"new": "val"} + e.Attributes = map[string]any{} return e }, }, @@ -140,13 +140,13 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"dotted.field.name": "val"} + e.Attributes = map[string]any{"dotted.field.name": "val"} return e }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{"new": "val"} - e.Attributes = map[string]interface{}{} + e.Resource = map[string]any{"new": "val"} + e.Attributes = map[string]any{} return e }, }, @@ -161,13 +161,13 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"dotted.field.name": "val"} + e.Attributes = map[string]any{"dotted.field.name": "val"} return e }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{"dotted.field.name": "val"} - e.Attributes = map[string]interface{}{} + e.Resource = map[string]any{"dotted.field.name": "val"} + e.Attributes = map[string]any{} return e }, }, @@ -182,13 +182,13 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{"new": "val"} + e.Attributes = map[string]any{"new": "val"} return e }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{"dotted.field.name": "val"} - e.Attributes = map[string]interface{}{} + e.Resource = map[string]any{"dotted.field.name": "val"} + e.Attributes = map[string]any{} return e }, }, @@ -203,13 +203,13 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{"new": "val"} + e.Resource = map[string]any{"new": "val"} return e }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{} - e.Attributes = map[string]interface{}{"new": "val"} + e.Resource = map[string]any{} + e.Attributes = map[string]any{"new": "val"} return e }, }, @@ -225,9 +225,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "NewNested": map[string]interface{}{ + "NewNested": map[string]any{ "nestedkey": "nestedval", }, } @@ -246,9 +246,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{}, + "nested": map[string]any{}, "unnestedkey": "nestedval", } return e @@ -266,9 +266,9 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, "newnestedkey": "nestedval", @@ -277,9 +277,9 @@ func TestProcessAndBuild(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", "newnestedkey": "nestedval", }, @@ -298,11 +298,11 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", - "nested2": map[string]interface{}{ + "nested2": map[string]any{ "nestedkey": "nestedval", }, }, @@ -311,12 +311,12 @@ func TestProcessAndBuild(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, - "nested2": map[string]interface{}{ + "nested2": map[string]any{ "nestedkey": "nestedval", }, } @@ -335,11 +335,11 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", } - e.Resource = map[string]interface{}{ - "NewNested": map[string]interface{}{ + e.Resource = map[string]any{ + "NewNested": map[string]any{ "nestedkey": "nestedval", }, } @@ -359,11 +359,11 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", } - e.Attributes = map[string]interface{}{ - "NewNested": map[string]interface{}{ + e.Attributes = map[string]any{ + "NewNested": map[string]any{ "nestedkey": "nestedval", }, } @@ -383,13 +383,13 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{}, + "nested": map[string]any{}, } - e.Attributes = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Attributes = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "three": "nestedval", }, }, @@ -409,9 +409,9 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{ + e.Attributes = map[string]any{ + "one": map[string]any{ + "two": map[string]any{ "three": "nestedval", }, }, @@ -421,9 +421,9 @@ func TestProcessAndBuild(t *testing.T) { func() *entry.Entry { e := newTestEntry() e.Body = "nestedval" - e.Attributes = map[string]interface{}{ - "one": map[string]interface{}{ - "two": map[string]interface{}{}, + e.Attributes = map[string]any{ + "one": map[string]any{ + "two": map[string]any{}, }, } return e @@ -440,10 +440,10 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ - "wrapper": map[string]interface{}{ + e.Body = map[string]any{ + "wrapper": map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, }, @@ -452,9 +452,9 @@ func TestProcessAndBuild(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -489,7 +489,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", "nestedkey": "nestedval", } diff --git a/pkg/stanza/operator/transformer/recombine/recombine.go b/pkg/stanza/operator/transformer/recombine/recombine.go index 44b48be8fd6d..8a204e50aa1d 100644 --- a/pkg/stanza/operator/transformer/recombine/recombine.go +++ b/pkg/stanza/operator/transformer/recombine/recombine.go @@ -115,7 +115,7 @@ func (c *Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) { overwriteWithOldest: overwriteWithOldest, batchMap: make(map[string]*sourceBatch), batchPool: sync.Pool{ - New: func() interface{} { + New: func() any { return &sourceBatch{ entries: []*entry.Entry{}, recombined: &bytes.Buffer{}, diff --git a/pkg/stanza/operator/transformer/recombine/recombine_test.go b/pkg/stanza/operator/transformer/recombine/recombine_test.go index 3bb5fff876aa..9887d28cc537 100644 --- a/pkg/stanza/operator/transformer/recombine/recombine_test.go +++ b/pkg/stanza/operator/transformer/recombine/recombine_test.go @@ -27,7 +27,7 @@ func TestTransformer(t *testing.T) { t1 := time.Date(2020, time.April, 11, 21, 34, 01, 0, time.UTC) t2 := time.Date(2020, time.April, 11, 21, 34, 02, 0, time.UTC) - entryWithBody := func(ts time.Time, body interface{}) *entry.Entry { + entryWithBody := func(ts time.Time, body any) *entry.Entry { e := entry.New() e.ObservedTimestamp = now e.Timestamp = ts @@ -35,7 +35,7 @@ func TestTransformer(t *testing.T) { return e } - entryWithBodyAttr := func(ts time.Time, body interface{}, Attr map[string]string) *entry.Entry { + entryWithBodyAttr := func(ts time.Time, body any, Attr map[string]string) *entry.Entry { e := entryWithBody(ts, body) for k, v := range Attr { e.AddAttribute(k, v) diff --git a/pkg/stanza/operator/transformer/remove/remove_test.go b/pkg/stanza/operator/transformer/remove/remove_test.go index 58a53d52429e..e22b64f5da06 100644 --- a/pkg/stanza/operator/transformer/remove/remove_test.go +++ b/pkg/stanza/operator/transformer/remove/remove_test.go @@ -29,9 +29,9 @@ func TestProcessAndBuild(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Timestamp = time.Unix(1586632809, 0) - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -49,8 +49,8 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ - "nested": map[string]interface{}{ + e.Body = map[string]any{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -68,9 +68,9 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{}, + "nested": map[string]any{}, } return e }, @@ -85,9 +85,9 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -95,9 +95,9 @@ func TestProcessAndBuild(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", - "nested": map[string]interface{}{}, + "nested": map[string]any{}, } return e }, @@ -112,9 +112,9 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -122,9 +122,9 @@ func TestProcessAndBuild(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", - "nested": map[string]interface{}{}, + "nested": map[string]any{}, } return e }, @@ -140,7 +140,7 @@ func TestProcessAndBuild(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", } return e @@ -156,14 +156,14 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", } return e }, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{} + e.Attributes = map[string]any{} return e }, false, @@ -177,14 +177,14 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", } return e }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{} + e.Resource = map[string]any{} return e }, false, @@ -213,7 +213,7 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", } return e @@ -234,7 +234,7 @@ func TestProcessAndBuild(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", } return e diff --git a/pkg/stanza/operator/transformer/remove/rootable_field.go b/pkg/stanza/operator/transformer/remove/rootable_field.go index a3eea497ea1d..3272fe6900d2 100644 --- a/pkg/stanza/operator/transformer/remove/rootable_field.go +++ b/pkg/stanza/operator/transformer/remove/rootable_field.go @@ -32,7 +32,7 @@ func (f *rootableField) UnmarshalJSON(raw []byte) error { } // UnmarshalYAML will unmarshal a field from YAML -func (f *rootableField) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (f *rootableField) UnmarshalYAML(unmarshal func(any) error) error { var s string err := unmarshal(&s) if err != nil { @@ -66,7 +66,7 @@ func (f *rootableField) unmarshalCheckString(s string) error { } // Get gets the value of the field if the flags for 'allAttributes' or 'allResource' isn't set -func (f *rootableField) Get(entry *entry.Entry) (interface{}, bool) { +func (f *rootableField) Get(entry *entry.Entry) (any, bool) { if f.allAttributes || f.allResource { return nil, false } diff --git a/pkg/stanza/operator/transformer/retain/retain_test.go b/pkg/stanza/operator/transformer/retain/retain_test.go index 3a216e9bf136..66998d35b9bd 100644 --- a/pkg/stanza/operator/transformer/retain/retain_test.go +++ b/pkg/stanza/operator/transformer/retain/retain_test.go @@ -29,9 +29,9 @@ func TestBuildAndProcess(t *testing.T) { e := entry.New() e.ObservedTimestamp = now e.Timestamp = time.Unix(1586632809, 0) - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, } @@ -50,7 +50,7 @@ func TestBuildAndProcess(t *testing.T) { newTestEntry, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", } return e @@ -67,12 +67,12 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, - "nested2": map[string]interface{}{ + "nested2": map[string]any{ "nestedkey": "nestedval", }, } @@ -80,9 +80,9 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested2": map[string]interface{}{ + "nested2": map[string]any{ "nestedkey": "nestedval", }, } @@ -104,30 +104,30 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "foo": "bar", - "one": map[string]interface{}{ - "two": map[string]interface{}{ + "one": map[string]any{ + "two": map[string]any{ "keepme": 1, }, "deleteme": "yes", }, "hello": "world", } - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "foo": "bar", - "one": map[string]interface{}{ - "two": map[string]interface{}{ + "one": map[string]any{ + "two": map[string]any{ "keepme": 1, }, "deleteme": "yes", }, "hello": "world", } - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "foo": "bar", - "one": map[string]interface{}{ - "two": map[string]interface{}{ + "one": map[string]any{ + "two": map[string]any{ "keepme": 1, }, "deleteme": "yes", @@ -138,26 +138,26 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "foo": "bar", - "one": map[string]interface{}{ - "two": map[string]interface{}{ + "one": map[string]any{ + "two": map[string]any{ "keepme": 1, }, }, } - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "foo": "bar", - "one": map[string]interface{}{ - "two": map[string]interface{}{ + "one": map[string]any{ + "two": map[string]any{ "keepme": 1, }, }, } - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "foo": "bar", - "one": map[string]interface{}{ - "two": map[string]interface{}{ + "one": map[string]any{ + "two": map[string]any{ "keepme": 1, }, }, @@ -175,12 +175,12 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, - "nested2": map[string]interface{}{ + "nested2": map[string]any{ "nestedkey": "nestedval", }, } @@ -188,8 +188,8 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ - "nested2": map[string]interface{}{ + e.Body = map[string]any{ + "nested2": map[string]any{ "nestedkey": "nestedval", }, } @@ -206,12 +206,12 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", - "nested": map[string]interface{}{ + "nested": map[string]any{ "nestedkey": "nestedval", }, - "nested2": map[string]interface{}{ + "nested2": map[string]any{ "nestedkey2": "nestedval", }, } @@ -219,8 +219,8 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Body = map[string]interface{}{ - "nested2": map[string]interface{}{ + e.Body = map[string]any{ + "nested2": map[string]any{ "nestedkey2": "nestedval", }, } @@ -237,14 +237,14 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", } return e }, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key": "val", } return e @@ -261,7 +261,7 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key1": "val", "key2": "val", "key3": "val", @@ -270,7 +270,7 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key1": "val", "key2": "val", } @@ -287,14 +287,14 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", } return e }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key": "val", } return e @@ -311,7 +311,7 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key1": "val", "key2": "val", "key3": "val", @@ -320,7 +320,7 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key1": "val", "key2": "val", } @@ -339,11 +339,11 @@ func TestBuildAndProcess(t *testing.T) { }(), func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key1": "val", "key2": "val", } - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key3": "val", "key4": "val", } @@ -351,13 +351,13 @@ func TestBuildAndProcess(t *testing.T) { }, func() *entry.Entry { e := newTestEntry() - e.Resource = map[string]interface{}{ + e.Resource = map[string]any{ "key1": "val", } - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "key3": "val", } - e.Body = map[string]interface{}{ + e.Body = map[string]any{ "key": "val", } return e diff --git a/pkg/stanza/operator/transformer/router/router_test.go b/pkg/stanza/operator/transformer/router/router_test.go index b9c6f6240072..8c023eabe7d8 100644 --- a/pkg/stanza/operator/transformer/router/router_test.go +++ b/pkg/stanza/operator/transformer/router/router_test.go @@ -34,7 +34,7 @@ func TestTransformer(t *testing.T) { routes []*RouteConfig defaultOutput []string expectedCounts map[string]int - expectedAttributes map[string]interface{} + expectedAttributes map[string]any }{ { "DefaultRoute", @@ -67,7 +67,7 @@ func TestTransformer(t *testing.T) { { "SimpleMatch", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -90,7 +90,7 @@ func TestTransformer(t *testing.T) { { "MatchWithAttribute", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -112,14 +112,14 @@ func TestTransformer(t *testing.T) { }, nil, map[string]int{"output2": 1}, - map[string]interface{}{ + map[string]any{ "label-key": "label-value", }, }, { "MatchEnv", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -142,7 +142,7 @@ func TestTransformer(t *testing.T) { { "UseDefault", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -160,7 +160,7 @@ func TestTransformer(t *testing.T) { { "MatchBeforeDefault", &entry.Entry{ - Body: map[string]interface{}{ + Body: map[string]any{ "message": "test_message", }, }, @@ -187,7 +187,7 @@ func TestTransformer(t *testing.T) { require.NoError(t, err) results := map[string]int{} - var attributes map[string]interface{} + var attributes map[string]any mock1 := testutil.NewMockOperator("output1") mock1.On("Process", mock.Anything, mock.Anything).Return(nil).Run(func(args mock.Arguments) { diff --git a/pkg/stanza/operator/transformer/unquote/unquote_test.go b/pkg/stanza/operator/transformer/unquote/unquote_test.go index dcdc6239ea17..620338bbaef1 100644 --- a/pkg/stanza/operator/transformer/unquote/unquote_test.go +++ b/pkg/stanza/operator/transformer/unquote/unquote_test.go @@ -153,14 +153,14 @@ func TestBuildAndProcess(t *testing.T) { }(), input: func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "foo": "\"val\"", } return e }, output: func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "foo": "val", } return e @@ -175,14 +175,14 @@ func TestBuildAndProcess(t *testing.T) { }(), input: func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "foo": "\"val\"", } return e }, output: func() *entry.Entry { e := newTestEntry() - e.Attributes = map[string]interface{}{ + e.Attributes = map[string]any{ "foo": "\"val\"", } return e diff --git a/pkg/stanza/testutil/mocks.go b/pkg/stanza/testutil/mocks.go index 029f0f8e4e99..6d727f03b809 100644 --- a/pkg/stanza/testutil/mocks.go +++ b/pkg/stanza/testutil/mocks.go @@ -80,7 +80,7 @@ func (f *FakeOutput) Process(_ context.Context, entry *entry.Entry) error { // ExpectBody expects that a body will be received by the fake operator within a second // and that it is equal to the given body -func (f *FakeOutput) ExpectBody(t testing.TB, body interface{}) { +func (f *FakeOutput) ExpectBody(t testing.TB, body any) { select { case e := <-f.Received: require.Equal(t, body, e.Body) diff --git a/pkg/translator/azure/resourcelogs_to_logs.go b/pkg/translator/azure/resourcelogs_to_logs.go index 0c8cfd97d3da..0b243d812a64 100644 --- a/pkg/translator/azure/resourcelogs_to_logs.go +++ b/pkg/translator/azure/resourcelogs_to_logs.go @@ -58,10 +58,10 @@ type azureLogRecord struct { DurationMs *json.Number `json:"durationMs"` CallerIPAddress *string `json:"callerIpAddress"` CorrelationID *string `json:"correlationId"` - Identity *interface{} `json:"identity"` + Identity *any `json:"identity"` Level *json.Number `json:"Level"` Location *string `json:"location"` - Properties *interface{} `json:"properties"` + Properties *any `json:"properties"` } var _ plog.Unmarshaler = (*ResourceLogsUnmarshaler)(nil) @@ -159,8 +159,8 @@ func asSeverity(number json.Number) plog.SeverityNumber { } } -func extractRawAttributes(log azureLogRecord) map[string]interface{} { - var attrs = map[string]interface{}{} +func extractRawAttributes(log azureLogRecord) map[string]any { + var attrs = map[string]any{} attrs[azureCategory] = log.Category setIf(attrs, azureCorrelationID, log.CorrelationID) @@ -190,7 +190,7 @@ func extractRawAttributes(log azureLogRecord) map[string]interface{} { return attrs } -func setIf(attrs map[string]interface{}, key string, value *string) { +func setIf(attrs map[string]any, key string, value *string) { if value != nil && *value != "" { attrs[key] = *value } diff --git a/pkg/translator/azure/resourcelogs_to_logs_test.go b/pkg/translator/azure/resourcelogs_to_logs_test.go index 93312c6e2a52..34535766b5a5 100644 --- a/pkg/translator/azure/resourcelogs_to_logs_test.go +++ b/pkg/translator/azure/resourcelogs_to_logs_test.go @@ -196,7 +196,7 @@ func TestAsSeverity(t *testing.T) { } func TestSetIf(t *testing.T) { - m := map[string]interface{}{} + m := map[string]any{} setIf(m, "key", nil) actual, found := m["key"] @@ -230,9 +230,9 @@ func TestExtractRawAttributes(t *testing.T) { level := json.Number("Informational") location := "location" - identity := interface{}("someone") + identity := any("someone") - properties := interface{}(map[string]interface{}{ + properties := any(map[string]any{ "a": uint64(1), "b": true, "c": 1.23, @@ -242,7 +242,7 @@ func TestExtractRawAttributes(t *testing.T) { tests := []struct { name string log azureLogRecord - expected map[string]interface{} + expected map[string]any }{ { name: "minimal", @@ -253,7 +253,7 @@ func TestExtractRawAttributes(t *testing.T) { Category: "category", DurationMs: &badDuration, }, - expected: map[string]interface{}{ + expected: map[string]any{ azureOperationName: "operation.name", azureCategory: "category", conventions.AttributeCloudProvider: conventions.AttributeCloudProviderAzure, @@ -268,7 +268,7 @@ func TestExtractRawAttributes(t *testing.T) { Category: "category", DurationMs: &badDuration, }, - expected: map[string]interface{}{ + expected: map[string]any{ azureOperationName: "operation.name", azureCategory: "category", conventions.AttributeCloudProvider: conventions.AttributeCloudProviderAzure, @@ -294,7 +294,7 @@ func TestExtractRawAttributes(t *testing.T) { Location: &location, Properties: &properties, }, - expected: map[string]interface{}{ + expected: map[string]any{ azureTenantID: "tenant.id", azureOperationName: "operation.name", azureOperationVersion: "operation.version", diff --git a/pkg/translator/jaeger/jaegerproto_to_traces_test.go b/pkg/translator/jaeger/jaegerproto_to_traces_test.go index 1252b2c8af31..3ea43570d863 100644 --- a/pkg/translator/jaeger/jaegerproto_to_traces_test.go +++ b/pkg/translator/jaeger/jaegerproto_to_traces_test.go @@ -397,7 +397,7 @@ func TestSetInternalSpanStatus(t *testing.T) { tests := []struct { name string - attrs map[string]interface{} + attrs map[string]any status ptrace.Status kind ptrace.SpanKind attrsModifiedLen int // Length of attributes map after dropping converted fields @@ -409,7 +409,7 @@ func TestSetInternalSpanStatus(t *testing.T) { }, { name: "error tag set -> Error status", - attrs: map[string]interface{}{ + attrs: map[string]any{ tracetranslator.TagError: true, }, status: errorStatus, @@ -417,7 +417,7 @@ func TestSetInternalSpanStatus(t *testing.T) { }, { name: "status.code is set as string", - attrs: map[string]interface{}{ + attrs: map[string]any{ conventions.OtelStatusCode: statusOk, }, status: okStatus, @@ -425,7 +425,7 @@ func TestSetInternalSpanStatus(t *testing.T) { }, { name: "status.code, status.message and error tags are set", - attrs: map[string]interface{}{ + attrs: map[string]any{ tracetranslator.TagError: true, conventions.OtelStatusCode: statusError, conventions.OtelStatusDescription: "Error: Invalid argument", @@ -435,7 +435,7 @@ func TestSetInternalSpanStatus(t *testing.T) { }, { name: "http.status_code tag is set as string", - attrs: map[string]interface{}{ + attrs: map[string]any{ conventions.AttributeHTTPStatusCode: "404", }, status: errorStatus, @@ -443,7 +443,7 @@ func TestSetInternalSpanStatus(t *testing.T) { }, { name: "http.status_code, http.status_message and error tags are set", - attrs: map[string]interface{}{ + attrs: map[string]any{ tracetranslator.TagError: true, conventions.AttributeHTTPStatusCode: 404, tracetranslator.TagHTTPStatusMsg: "HTTP 404: Not Found", @@ -453,7 +453,7 @@ func TestSetInternalSpanStatus(t *testing.T) { }, { name: "status.code has precedence over http.status_code.", - attrs: map[string]interface{}{ + attrs: map[string]any{ conventions.OtelStatusCode: statusOk, conventions.AttributeHTTPStatusCode: 500, tracetranslator.TagHTTPStatusMsg: "Server Error", @@ -463,7 +463,7 @@ func TestSetInternalSpanStatus(t *testing.T) { }, { name: "Ignore http.status_code == 200 if error set to true.", - attrs: map[string]interface{}{ + attrs: map[string]any{ tracetranslator.TagError: true, conventions.AttributeHTTPStatusCode: 200, }, @@ -473,7 +473,7 @@ func TestSetInternalSpanStatus(t *testing.T) { { name: "the 4xx range span status MUST be left unset in case of SpanKind.SERVER", kind: ptrace.SpanKindServer, - attrs: map[string]interface{}{ + attrs: map[string]any{ tracetranslator.TagError: false, conventions.AttributeHTTPStatusCode: 404, }, diff --git a/pkg/translator/loki/convert_test.go b/pkg/translator/loki/convert_test.go index b5e603848f18..9961998f596a 100644 --- a/pkg/translator/loki/convert_test.go +++ b/pkg/translator/loki/convert_test.go @@ -16,8 +16,8 @@ import ( func TestConvertAttributesAndMerge(t *testing.T) { testCases := []struct { desc string - logAttrs map[string]interface{} - resAttrs map[string]interface{} + logAttrs map[string]any + resAttrs map[string]any expected model.LabelSet defaultLabelsEnabled map[string]bool }{ @@ -27,7 +27,7 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "selected log attribute should be included", - logAttrs: map[string]interface{}{ + logAttrs: map[string]any{ "host.name": "guarana", "pod.name": "should-be-ignored", hintAttributes: "host.name", @@ -39,10 +39,10 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "selected resource attribute should be included", - logAttrs: map[string]interface{}{ + logAttrs: map[string]any{ hintResources: "host.name", }, - resAttrs: map[string]interface{}{ + resAttrs: map[string]any{ "host.name": "guarana", "pod.name": "should-be-ignored", }, @@ -53,8 +53,8 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "selected attributes from resource attributes should be included", - logAttrs: map[string]interface{}{}, - resAttrs: map[string]interface{}{ + logAttrs: map[string]any{}, + resAttrs: map[string]any{ hintResources: "host.name", "host.name": "hostname-from-resources", "pod.name": "should-be-ignored", @@ -66,12 +66,12 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "selected attributes from both sources should have most specific win", - logAttrs: map[string]interface{}{ + logAttrs: map[string]any{ "host.name": "hostname-from-attributes", hintAttributes: "host.name", hintResources: "host.name", }, - resAttrs: map[string]interface{}{ + resAttrs: map[string]any{ "host.name": "hostname-from-resources", "pod.name": "should-be-ignored", }, @@ -82,7 +82,7 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "it should be possible to override the exporter label", - logAttrs: map[string]interface{}{ + logAttrs: map[string]any{ hintAttributes: "exporter", "exporter": "overridden", }, @@ -92,7 +92,7 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "it should add service.namespace/service.name as job label if both of them are present", - resAttrs: map[string]interface{}{ + resAttrs: map[string]any{ "service.namespace": "my-service-namespace", "service.name": "my-service-name", }, @@ -103,7 +103,7 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "it should add service.name as job label if service.namespace is missing", - resAttrs: map[string]interface{}{ + resAttrs: map[string]any{ "service.name": "my-service-name", }, expected: model.LabelSet{ @@ -113,7 +113,7 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "it shouldn't add service.namespace as job label if service.name is missing", - resAttrs: map[string]interface{}{ + resAttrs: map[string]any{ "service.namespace": "my-service-namespace", }, expected: model.LabelSet{ @@ -122,7 +122,7 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "it should add service.instance.id as instance label if service.instance.id is present", - resAttrs: map[string]interface{}{ + resAttrs: map[string]any{ "service.instance.id": "my-service-instance-id", }, expected: model.LabelSet{ @@ -132,7 +132,7 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "it shouldn't add job, instance, exporter labels if they disabled in config", - resAttrs: map[string]interface{}{ + resAttrs: map[string]any{ "service.instance.id": "my-service-instance-id", "service.namespace": "my-service-namespace", "service.name": "my-service-name", @@ -146,7 +146,7 @@ func TestConvertAttributesAndMerge(t *testing.T) { }, { desc: "it should add job label because it is enabled in config, and exporter label because it is not mentioned in config and that's why enabled by default", - resAttrs: map[string]interface{}{ + resAttrs: map[string]any{ "service.instance.id": "my-service-instance-id", "service.namespace": "my-service-namespace", "service.name": "my-service-name", @@ -182,13 +182,13 @@ func TestConvertAttributesToLabels(t *testing.T) { testCases := []struct { desc string - attrsAvailable map[string]interface{} + attrsAvailable map[string]any attrsToSelect pcommon.Value expected model.LabelSet }{ { desc: "string value", - attrsAvailable: map[string]interface{}{ + attrsAvailable: map[string]any{ "host.name": "guarana", }, attrsToSelect: pcommon.NewValueStr("host.name"), @@ -198,7 +198,7 @@ func TestConvertAttributesToLabels(t *testing.T) { }, { desc: "list of values as string", - attrsAvailable: map[string]interface{}{ + attrsAvailable: map[string]any{ "host.name": "guarana", "pod.name": "pod-123", }, @@ -210,7 +210,7 @@ func TestConvertAttributesToLabels(t *testing.T) { }, { desc: "list of values as slice", - attrsAvailable: map[string]interface{}{ + attrsAvailable: map[string]any{ "host.name": "guarana", "pod.name": "pod-123", }, @@ -222,8 +222,8 @@ func TestConvertAttributesToLabels(t *testing.T) { }, { desc: "nested attributes", - attrsAvailable: map[string]interface{}{ - "host": map[string]interface{}{ + attrsAvailable: map[string]any{ + "host": map[string]any{ "name": "guarana", }, "pod.name": "pod-123", @@ -248,13 +248,13 @@ func TestConvertAttributesToLabels(t *testing.T) { func TestRemoveAttributes(t *testing.T) { testCases := []struct { desc string - attrs map[string]interface{} + attrs map[string]any labels model.LabelSet - expected map[string]interface{} + expected map[string]any }{ { desc: "remove hints", - attrs: map[string]interface{}{ + attrs: map[string]any{ hintAttributes: "some.field", hintResources: "some.other.field", hintFormat: "logfmt", @@ -262,20 +262,20 @@ func TestRemoveAttributes(t *testing.T) { "host.name": "guarana", }, labels: model.LabelSet{}, - expected: map[string]interface{}{ + expected: map[string]any{ "host.name": "guarana", }, }, { desc: "remove attributes promoted to labels", - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", "pod.name": "guarana-123", }, labels: model.LabelSet{ "host.name": "guarana", }, - expected: map[string]interface{}{ + expected: map[string]any{ "pod.name": "guarana-123", }, }, @@ -294,15 +294,15 @@ func TestGetAttribute(t *testing.T) { testCases := []struct { desc string attr string - attrs map[string]interface{} + attrs map[string]any expected pcommon.Value ok bool }{ { desc: "attributes don't contain dotted names", attr: "host.name", - attrs: map[string]interface{}{ - "host": map[string]interface{}{ + attrs: map[string]any{ + "host": map[string]any{ "name": "guarana", }, }, @@ -312,8 +312,8 @@ func TestGetAttribute(t *testing.T) { { desc: "attributes contain dotted name on the nested level", attr: "log.file.name", - attrs: map[string]interface{}{ - "log": map[string]interface{}{ + attrs: map[string]any{ + "log": map[string]any{ "file.name": "foo", }, }, @@ -323,8 +323,8 @@ func TestGetAttribute(t *testing.T) { { desc: "attributes contain dotted name on the upper level", attr: "log.file.name", - attrs: map[string]interface{}{ - "log.file": map[string]interface{}{ + attrs: map[string]any{ + "log.file": map[string]any{ "name": "foo", }, }, @@ -334,7 +334,7 @@ func TestGetAttribute(t *testing.T) { { desc: "attributes contain dotted attribute", attr: "log.file.name", - attrs: map[string]interface{}{ + attrs: map[string]any{ "log.file.name": "foo", }, expected: pcommon.NewValueStr("foo"), @@ -343,7 +343,7 @@ func TestGetAttribute(t *testing.T) { { desc: "dotted name that doesn't match attr", attr: "log.file.name", - attrs: map[string]interface{}{ + attrs: map[string]any{ "log.file": "foo", }, expected: pcommon.Value{}, @@ -352,14 +352,14 @@ func TestGetAttribute(t *testing.T) { { desc: "should get the longest match", attr: "log.file.name", - attrs: map[string]interface{}{ + attrs: map[string]any{ "log.file.name": "foo", - "log": map[string]interface{}{ - "file": map[string]interface{}{ + "log": map[string]any{ + "file": map[string]any{ "name": "bar", }, }, - "log.file": map[string]interface{}{ + "log.file": map[string]any{ "name": "baz", }, }, diff --git a/pkg/translator/loki/encode.go b/pkg/translator/loki/encode.go index 591c78ed4a0e..2174b71f6fce 100644 --- a/pkg/translator/loki/encode.go +++ b/pkg/translator/loki/encode.go @@ -18,21 +18,21 @@ import ( // JSON representation of the LogRecord as described by https://developers.google.com/protocol-buffers/docs/proto3#json type lokiEntry struct { - Name string `json:"name,omitempty"` - Body json.RawMessage `json:"body,omitempty"` - TraceID string `json:"traceid,omitempty"` - SpanID string `json:"spanid,omitempty"` - Severity string `json:"severity,omitempty"` - Flags uint32 `json:"flags,omitempty"` - Attributes map[string]interface{} `json:"attributes,omitempty"` - Resources map[string]interface{} `json:"resources,omitempty"` - InstrumentationScope *instrumentationScope `json:"instrumentation_scope,omitempty"` + Name string `json:"name,omitempty"` + Body json.RawMessage `json:"body,omitempty"` + TraceID string `json:"traceid,omitempty"` + SpanID string `json:"spanid,omitempty"` + Severity string `json:"severity,omitempty"` + Flags uint32 `json:"flags,omitempty"` + Attributes map[string]any `json:"attributes,omitempty"` + Resources map[string]any `json:"resources,omitempty"` + InstrumentationScope *instrumentationScope `json:"instrumentation_scope,omitempty"` } type instrumentationScope struct { - Name string `json:"name,omitempty"` - Version string `json:"version,omitempty"` - Attributes map[string]interface{} `json:"attributes,omitempty"` + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + Attributes map[string]any `json:"attributes,omitempty"` } // Encode converts an OTLP log record and its resource attributes into a JSON @@ -139,7 +139,7 @@ func serializeBodyJSON(body pcommon.Value) ([]byte, error) { return json.Marshal(body.AsRaw()) } -func bodyToKeyvals(body pcommon.Value) []interface{} { +func bodyToKeyvals(body pcommon.Value) []any { switch body.Type() { case pcommon.ValueTypeEmpty: return nil @@ -148,7 +148,7 @@ func bodyToKeyvals(body pcommon.Value) []interface{} { value := body.Str() keyvals, err := parseLogfmtLine(value) if err != nil { - return []interface{}{"msg", body.Str()} + return []any{"msg", body.Str()} } return *keyvals case pcommon.ValueTypeMap: @@ -156,24 +156,24 @@ func bodyToKeyvals(body pcommon.Value) []interface{} { case pcommon.ValueTypeSlice: return valueToKeyvals("body", body) default: - return []interface{}{"msg", body.AsRaw()} + return []any{"msg", body.AsRaw()} } } -func valueToKeyvals(key string, value pcommon.Value) []interface{} { +func valueToKeyvals(key string, value pcommon.Value) []any { switch value.Type() { case pcommon.ValueTypeEmpty: return nil case pcommon.ValueTypeStr: - return []interface{}{key, value.Str()} + return []any{key, value.Str()} case pcommon.ValueTypeBool: - return []interface{}{key, value.Bool()} + return []any{key, value.Bool()} case pcommon.ValueTypeInt: - return []interface{}{key, value.Int()} + return []any{key, value.Int()} case pcommon.ValueTypeDouble: - return []interface{}{key, value.Double()} + return []any{key, value.Double()} case pcommon.ValueTypeMap: - var keyvals []interface{} + var keyvals []any prefix := "" if key != "" { prefix = key + "_" @@ -189,19 +189,19 @@ func valueToKeyvals(key string, value pcommon.Value) []interface{} { if key != "" { prefix = key + "_" } - var keyvals []interface{} + var keyvals []any for i := 0; i < value.Slice().Len(); i++ { v := value.Slice().At(i) keyvals = append(keyvals, valueToKeyvals(fmt.Sprintf("%s%d", prefix, i), v)...) } return keyvals default: - return []interface{}{key, value.AsRaw()} + return []any{key, value.AsRaw()} } } // if given key:value pair already exists in keyvals, replace value. Otherwise append -func keyvalsReplaceOrAppend(keyvals []interface{}, key string, value interface{}) []interface{} { +func keyvalsReplaceOrAppend(keyvals []any, key string, value any) []any { for i := 0; i < len(keyvals); i += 2 { if keyvals[i] == key { keyvals[i+1] = value @@ -211,8 +211,8 @@ func keyvalsReplaceOrAppend(keyvals []interface{}, key string, value interface{} return append(keyvals, key, value) } -func parseLogfmtLine(line string) (*[]interface{}, error) { - var keyvals []interface{} +func parseLogfmtLine(line string) (*[]any, error) { + var keyvals []any decoder := logfmt.NewDecoder(strings.NewReader(line)) decoder.ScanRecord() for decoder.ScanKeyval() { diff --git a/pkg/translator/loki/logs_to_loki_test.go b/pkg/translator/loki/logs_to_loki_test.go index 517f878f5c28..af5c09ff9f4e 100644 --- a/pkg/translator/loki/logs_to_loki_test.go +++ b/pkg/translator/loki/logs_to_loki_test.go @@ -238,9 +238,9 @@ func TestLogsToLokiRequestWithGroupingByTenant(t *testing.T) { func TestLogsToLokiRequestWithoutTenant(t *testing.T) { testCases := []struct { desc string - hints map[string]interface{} - attrs map[string]interface{} - res map[string]interface{} + hints map[string]any + attrs map[string]any + res map[string]any severity plog.SeverityNumber levelAttribute string expectedLabel string @@ -249,11 +249,11 @@ func TestLogsToLokiRequestWithoutTenant(t *testing.T) { }{ { desc: "with attribute to label and regular attribute", - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", "http.status": 200, }, - hints: map[string]interface{}{ + hints: map[string]any{ hintAttributes: "host.name", }, expectedLabel: `{exporter="OTLP", host_name="guarana"}`, @@ -265,11 +265,11 @@ func TestLogsToLokiRequestWithoutTenant(t *testing.T) { }, { desc: "with resource to label and regular resource", - res: map[string]interface{}{ + res: map[string]any{ "host.name": "guarana", "region.az": "eu-west-1a", }, - hints: map[string]interface{}{ + hints: map[string]any{ hintResources: "host.name", }, expectedLabel: `{exporter="OTLP", host_name="guarana"}`, @@ -281,11 +281,11 @@ func TestLogsToLokiRequestWithoutTenant(t *testing.T) { }, { desc: "with logfmt format", - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", "http.status": 200, }, - hints: map[string]interface{}{ + hints: map[string]any{ hintAttributes: "host.name", hintFormat: formatLogfmt, }, @@ -346,10 +346,10 @@ func TestLogsToLokiRequestWithoutTenant(t *testing.T) { }, { desc: "with severity, already existing level and hint attribute", - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", }, - hints: map[string]interface{}{ + hints: map[string]any{ hintAttributes: "host.name", }, severity: plog.SeverityNumberDebug4, @@ -363,10 +363,10 @@ func TestLogsToLokiRequestWithoutTenant(t *testing.T) { }, { desc: "with existing level and hint attributes contain level", - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", }, - hints: map[string]interface{}{ + hints: map[string]any{ hintAttributes: "level, host.name", }, levelAttribute: "dummy", @@ -379,15 +379,15 @@ func TestLogsToLokiRequestWithoutTenant(t *testing.T) { }, { desc: "with hint attributes and resource attributes as string", - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", "host.ip": "127.0.0.1", }, - res: map[string]interface{}{ + res: map[string]any{ "service.name": "my-service", "service.namespace": "my-namespace", }, - hints: map[string]interface{}{ + hints: map[string]any{ hintAttributes: "host.name, host.ip", hintResources: "service.name, service.namespace", }, @@ -401,15 +401,15 @@ func TestLogsToLokiRequestWithoutTenant(t *testing.T) { }, { desc: "with hint attributes as slice", - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", "host.ip": "127.0.0.1", }, - res: map[string]interface{}{ + res: map[string]any{ "service.name": "my-service", "service.namespace": "my-namespace", }, - hints: map[string]interface{}{ + hints: map[string]any{ hintAttributes: []any{"host.name", "host.ip"}, hintResources: []any{"service.name", "service.namespace"}, }, @@ -449,7 +449,7 @@ func TestLogsToLokiRequestWithoutTenant(t *testing.T) { logs := slogs.At(j).LogRecords() for k := 0; k < logs.Len(); k++ { log := logs.At(k) - attrs := map[string]interface{}{} + attrs := map[string]any{} if len(tt.attrs) > 0 { attrs = tt.attrs } @@ -496,9 +496,9 @@ func TestLogToLokiEntry(t *testing.T) { timestamp time.Time severity plog.SeverityNumber levelAttribute string - res map[string]interface{} - attrs map[string]interface{} - hints map[string]interface{} + res map[string]any + attrs map[string]any + hints map[string]any instrumentationScope *instrumentationScope expected *PushEntry err error @@ -507,11 +507,11 @@ func TestLogToLokiEntry(t *testing.T) { { name: "with attribute to label and regular attribute", timestamp: time.Unix(0, 1677592916000000000), - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", "http.status": 200, }, - hints: map[string]interface{}{ + hints: map[string]any{ hintAttributes: "host.name", }, expected: &PushEntry{ @@ -529,11 +529,11 @@ func TestLogToLokiEntry(t *testing.T) { { name: "with resource to label and regular resource", timestamp: time.Unix(0, 1677592916000000000), - res: map[string]interface{}{ + res: map[string]any{ "host.name": "guarana", "region.az": "eu-west-1a", }, - hints: map[string]interface{}{ + hints: map[string]any{ hintResources: "host.name", }, expected: &PushEntry{ @@ -550,11 +550,11 @@ func TestLogToLokiEntry(t *testing.T) { { name: "with logfmt format", timestamp: time.Unix(0, 1677592916000000000), - attrs: map[string]interface{}{ + attrs: map[string]any{ "host.name": "guarana", "http.status": 200, }, - hints: map[string]interface{}{ + hints: map[string]any{ hintAttributes: "host.name", hintFormat: formatLogfmt, }, @@ -623,7 +623,7 @@ func TestLogToLokiEntry(t *testing.T) { instrumentationScope: &instrumentationScope{ Name: "otlp", Version: "v1", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, }, @@ -640,7 +640,7 @@ func TestLogToLokiEntry(t *testing.T) { { name: "with unknown format hint", timestamp: time.Unix(0, 1677592916000000000), - hints: map[string]interface{}{ + hints: map[string]any{ hintFormat: "my-format", }, expected: nil, @@ -695,13 +695,13 @@ func TestLogToLokiEntry(t *testing.T) { func TestGetTenantFromTenantHint(t *testing.T) { testCases := []struct { name string - attrs map[string]interface{} - res map[string]interface{} + attrs map[string]any + res map[string]any expected string }{ { name: "tenant in attributes", - attrs: map[string]interface{}{ + attrs: map[string]any{ hintTenant: "tenant.id", "tenant.id": "1", }, @@ -709,7 +709,7 @@ func TestGetTenantFromTenantHint(t *testing.T) { }, { name: "tenant in resources", - res: map[string]interface{}{ + res: map[string]any{ hintTenant: "tenant.id", "tenant.id": "1", }, @@ -717,11 +717,11 @@ func TestGetTenantFromTenantHint(t *testing.T) { }, { name: "if tenant set in resources and attributes, the one in resource should win", - res: map[string]interface{}{ + res: map[string]any{ hintTenant: "tenant.id", "tenant.id": "1", }, - attrs: map[string]interface{}{ + attrs: map[string]any{ hintTenant: "tenant.id", "tenant.id": "2", }, diff --git a/pkg/translator/loki/loki_to_otlp_test.go b/pkg/translator/loki/loki_to_otlp_test.go index 67ac6bf3a4f1..0581310bd462 100644 --- a/pkg/translator/loki/loki_to_otlp_test.go +++ b/pkg/translator/loki/loki_to_otlp_test.go @@ -47,7 +47,7 @@ func TestPushRequestToLogs(t *testing.T) { { Timestamp: 1676888496000000000, Body: pcommon.NewValueStr("logline 1"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", "label1": "value1", }, @@ -71,7 +71,7 @@ func TestPushRequestToLogs(t *testing.T) { { Timestamp: 1676888496000000000, Body: pcommon.NewValueStr("logline 1"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "label1": "value1", }, }, @@ -92,7 +92,7 @@ func TestPushRequestToLogs(t *testing.T) { type Log struct { Timestamp int64 Body pcommon.Value - Attributes map[string]interface{} + Attributes map[string]any } func generateLogs(logs []Log) plog.Logs { diff --git a/pkg/translator/opencensus/oc_to_traces_test.go b/pkg/translator/opencensus/oc_to_traces_test.go index 4e86cb31e9db..53273767e9f8 100644 --- a/pkg/translator/opencensus/oc_to_traces_test.go +++ b/pkg/translator/opencensus/oc_to_traces_test.go @@ -81,7 +81,7 @@ func TestInitAttributeMapFromOC(t *testing.T) { } attrs = pcommon.NewMap() initAttributeMapFromOC(ocAttrs, attrs) - assert.Equal(t, map[string]interface{}{"abc": "def"}, attrs.AsRaw()) + assert.Equal(t, map[string]any{"abc": "def"}, attrs.AsRaw()) assert.EqualValues(t, 234, ocAttrsToDroppedAttributes(ocAttrs)) ocAttrs.AttributeMap["intval"] = &octrace.AttributeValue{ @@ -96,7 +96,7 @@ func TestInitAttributeMapFromOC(t *testing.T) { attrs = pcommon.NewMap() initAttributeMapFromOC(ocAttrs, attrs) - assert.EqualValues(t, map[string]interface{}{ + assert.EqualValues(t, map[string]any{ "abc": "def", "intval": int64(345), "boolval": true, diff --git a/pkg/translator/opencensus/traces_to_oc_test.go b/pkg/translator/opencensus/traces_to_oc_test.go index abfbebc594c1..8d0293441937 100644 --- a/pkg/translator/opencensus/traces_to_oc_test.go +++ b/pkg/translator/opencensus/traces_to_oc_test.go @@ -72,7 +72,7 @@ func TestAttributesMapToOC(t *testing.T) { ocAttrs.AttributeMap["doubleval"] = &octrace.AttributeValue{ Value: &octrace.AttributeValue_DoubleValue{DoubleValue: 4.5}, } - assert.NoError(t, attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, attrs.FromRaw(map[string]any{ "abc": "def", "intval": 345, "boolval": true, diff --git a/pkg/translator/prometheusremotewrite/helper_test.go b/pkg/translator/prometheusremotewrite/helper_test.go index 237179798f72..d7203f4508b1 100644 --- a/pkg/translator/prometheusremotewrite/helper_test.go +++ b/pkg/translator/prometheusremotewrite/helper_test.go @@ -505,7 +505,7 @@ func Test_getPromExemplars(t *testing.T) { } func TestAddResourceTargetInfo(t *testing.T) { - resourceAttrMap := map[string]interface{}{ + resourceAttrMap := map[string]any{ conventions.AttributeServiceName: "service-name", conventions.AttributeServiceNamespace: "service-namespace", conventions.AttributeServiceInstanceID: "service-instance-id", diff --git a/pkg/translator/signalfx/to_metrics_test.go b/pkg/translator/signalfx/to_metrics_test.go index 10e68200a926..9b2e95676346 100644 --- a/pkg/translator/signalfx/to_metrics_test.go +++ b/pkg/translator/signalfx/to_metrics_test.go @@ -277,7 +277,7 @@ func TestToMetrics(t *testing.T) { } } -func buildDefaultMetrics(t *testing.T, typ pmetric.MetricType, value interface{}, now time.Time) pmetric.Metrics { +func buildDefaultMetrics(t *testing.T, typ pmetric.MetricType, value any, now time.Time) pmetric.Metrics { out := pmetric.NewMetrics() rm := out.ResourceMetrics().AppendEmpty() ilm := rm.ScopeMetrics().AppendEmpty() diff --git a/pkg/translator/zipkin/zipkinv1/json_test.go b/pkg/translator/zipkin/zipkinv1/json_test.go index 507229545ae0..2c11a5fcff63 100644 --- a/pkg/translator/zipkin/zipkinv1/json_test.go +++ b/pkg/translator/zipkin/zipkinv1/json_test.go @@ -158,7 +158,7 @@ func TestMultipleJSONV1BatchesToTraces(t *testing.T) { blob, err := os.ReadFile("./testdata/zipkin_v1_multiple_batches.json") require.NoError(t, err, "Failed to load test data") - var batches []interface{} + var batches []any err = json.Unmarshal(blob, &batches) require.NoError(t, err, "Failed to load the batches") @@ -576,7 +576,7 @@ var tracesFromZipkinV1 = func() ptrace.Traces { span.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Unix(1544805927, 454487000))) span.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Unix(1544805927, 457320000))) //nolint:errcheck - span.Attributes().FromRaw(map[string]interface{}{ + span.Attributes().FromRaw(map[string]any{ "http.status_code": 200, "http.url": "http://localhost:9000/trace/2", "success": true, diff --git a/pkg/translator/zipkin/zipkinv2/to_translator.go b/pkg/translator/zipkin/zipkinv2/to_translator.go index ed11b1297b10..8bff5a6731bc 100644 --- a/pkg/translator/zipkin/zipkinv2/to_translator.go +++ b/pkg/translator/zipkin/zipkinv2/to_translator.go @@ -224,7 +224,7 @@ func zTagsToSpanLinks(tags map[string]string, dest ptrace.SpanLinkSlice) error { jsonParts := parts[3 : partCnt-1] jsonStr = strings.Join(jsonParts, "|") } - var attrs map[string]interface{} + var attrs map[string]any if err := json.Unmarshal([]byte(jsonStr), &attrs); err != nil { return err } @@ -261,7 +261,7 @@ func populateSpanEvents(zspan *zipkinmodel.SpanModel, events ptrace.SpanEventSli jsonParts := parts[1 : partCnt-1] jsonStr = strings.Join(jsonParts, "|") } - var attrs map[string]interface{} + var attrs map[string]any if err := json.Unmarshal([]byte(jsonStr), &attrs); err != nil { return err } @@ -278,7 +278,7 @@ func populateSpanEvents(zspan *zipkinmodel.SpanModel, events ptrace.SpanEventSli return nil } -func jsonMapToAttributeMap(attrs map[string]interface{}, dest pcommon.Map) error { +func jsonMapToAttributeMap(attrs map[string]any, dest pcommon.Map) error { for key, val := range attrs { if s, ok := val.(string); ok { dest.PutStr(key, s) diff --git a/processor/attributesprocessor/attributes_log_test.go b/processor/attributesprocessor/attributes_log_test.go index 5eadd37e7c7f..db6e0d705347 100644 --- a/processor/attributesprocessor/attributes_log_test.go +++ b/processor/attributesprocessor/attributes_log_test.go @@ -24,8 +24,8 @@ import ( // Common structure for all the Tests type logTestCase struct { name string - inputAttributes map[string]interface{} - expectedAttributes map[string]interface{} + inputAttributes map[string]any + expectedAttributes map[string]any } // runIndividualLogTestCase is the common logic of passing trace data through a configured attributes processor. @@ -37,7 +37,7 @@ func runIndividualLogTestCase(t *testing.T, tt logTestCase, tp processor.Logs) { }) } -func generateLogData(resourceName string, attrs map[string]interface{}) plog.Logs { +func generateLogData(resourceName string, attrs map[string]any) plog.Logs { td := plog.NewLogs() res := td.ResourceLogs().AppendEmpty() res.Resource().Attributes().PutStr("name", resourceName) @@ -97,32 +97,32 @@ func TestAttributes_FilterLogs(t *testing.T) { testCases := []logTestCase{ { name: "apply processor", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply processor with different value for exclude property", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "incorrect name for include property", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "attribute match for exclude property", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -158,37 +158,37 @@ func TestAttributes_FilterLogsByNameStrict(t *testing.T) { testCases := []logTestCase{ { name: "apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "incorrect_log_name", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "dont_apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "incorrect_log_name_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -221,37 +221,37 @@ func TestAttributes_FilterLogsByNameRegexp(t *testing.T) { testCases := []logTestCase{ { name: "apply_to_log_with_no_attrs", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply_to_log_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "incorrect_log_name", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "apply_dont_apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "incorrect_log_name_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -284,37 +284,37 @@ func TestLogAttributes_Hash(t *testing.T) { testCases := []logTestCase{ { name: "String", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.email": "john.doe@example.com", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.email": "836f82db99121b3481011f16b49dfa5fbc714a0d1b1b9f784a1ebbbf5b39577f", }, }, { name: "Int", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.id": 10, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.id": "a111f275cc2e7588000001d300a31e76336d15b9d314cd1a1d8f3d3556975eed", }, }, { name: "Double", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.balance": 99.1, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.balance": "05fabd78b01be9692863cb0985f600c99da82979af18db5c55173c2a30adb924", }, }, { name: "Bool", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.authenticated": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.authenticated": "4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a", }, }, @@ -343,55 +343,55 @@ func TestLogAttributes_Convert(t *testing.T) { testCases := []logTestCase{ { name: "int to int", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": 1, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": 1, }, }, { name: "false to int", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": 0, }, }, { name: "String to int (good)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": "123", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": 123, }, }, { name: "String to int (bad)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": "int-10", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": "int-10", }, }, { name: "String to double", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.double": "123.6", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.double": 123.6, }, }, { name: "Double to string", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.string": 99.1, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.string": "99.1", }, }, @@ -419,25 +419,25 @@ func BenchmarkAttributes_FilterLogsByName(b *testing.B) { testCases := []logTestCase{ { name: "apply_to_log_with_no_attrs", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply_to_log_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "dont_apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, } diff --git a/processor/attributesprocessor/attributes_metric_test.go b/processor/attributesprocessor/attributes_metric_test.go index f91b388c63ad..6c9f4b1171b2 100644 --- a/processor/attributesprocessor/attributes_metric_test.go +++ b/processor/attributesprocessor/attributes_metric_test.go @@ -24,8 +24,8 @@ import ( // Common structure for all the Tests type metricTestCase struct { name string - inputAttributes map[string]interface{} - expectedAttributes map[string]interface{} + inputAttributes map[string]any + expectedAttributes map[string]any } // runIndividualMetricTestCase is the common logic of passing metric data through a configured attributes processor. @@ -37,7 +37,7 @@ func runIndividualMetricTestCase(t *testing.T, mt metricTestCase, mp processor.M }) } -func generateMetricData(resourceName string, attrs map[string]interface{}) pmetric.Metrics { +func generateMetricData(resourceName string, attrs map[string]any) pmetric.Metrics { md := pmetric.NewMetrics() res := md.ResourceMetrics().AppendEmpty() res.Resource().Attributes().PutStr("name", resourceName) @@ -105,32 +105,32 @@ func TestAttributes_FilterMetrics(t *testing.T) { testCases := []metricTestCase{ { name: "apply processor", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply processor with different value for exclude property", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "incorrect name for include property", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "attribute match for exclude property", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -166,37 +166,37 @@ func TestAttributes_FilterMetricsByNameStrict(t *testing.T) { testCases := []metricTestCase{ { name: "apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "incorrect_metric_name", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "dont_apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "incorrect_metric_name_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -230,37 +230,37 @@ func TestAttributes_FilterMetricsByNameRegexp(t *testing.T) { testCases := []metricTestCase{ { name: "apply_to_metric_with_no_attrs", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply_to_metric_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "incorrect_metric_name", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "apply_dont_apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "incorrect_metric_name_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -293,37 +293,37 @@ func TestMetricAttributes_Hash(t *testing.T) { testCases := []metricTestCase{ { name: "String", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.email": "john.doe@example.com", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.email": "836f82db99121b3481011f16b49dfa5fbc714a0d1b1b9f784a1ebbbf5b39577f", }, }, { name: "Int", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.id": 10, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.id": "a111f275cc2e7588000001d300a31e76336d15b9d314cd1a1d8f3d3556975eed", }, }, { name: "Double", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.balance": 99.1, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.balance": "05fabd78b01be9692863cb0985f600c99da82979af18db5c55173c2a30adb924", }, }, { name: "Bool", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.authenticated": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.authenticated": "4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a", }, }, @@ -351,37 +351,37 @@ func TestMetricAttributes_Convert(t *testing.T) { testCases := []metricTestCase{ { name: "String to int (good)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": "123", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": 123, }, }, { name: "String to int (bad)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": "int-10", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": "int-10", }, }, { name: "String to double", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.double": "3.141e2", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.double": 314.1, }, }, { name: "Double to string", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.string": 99.1, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.string": "99.1", }, }, @@ -409,25 +409,25 @@ func BenchmarkAttributes_FilterMetricsByName(b *testing.B) { testCases := []metricTestCase{ { name: "apply_to_metric_with_no_attrs", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply_to_metric_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "dont_apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, } diff --git a/processor/attributesprocessor/attributes_trace_test.go b/processor/attributesprocessor/attributes_trace_test.go index 956335977b0b..7f92ff497c32 100644 --- a/processor/attributesprocessor/attributes_trace_test.go +++ b/processor/attributesprocessor/attributes_trace_test.go @@ -26,8 +26,8 @@ import ( type testCase struct { name string serviceName string - inputAttributes map[string]interface{} - expectedAttributes map[string]interface{} + inputAttributes map[string]any + expectedAttributes map[string]any } // runIndividualTestCase is the common logic of passing trace data through a configured attributes processor. @@ -39,7 +39,7 @@ func runIndividualTestCase(t *testing.T, tt testCase, tp processor.Traces) { }) } -func generateTraceData(serviceName, spanName string, attrs map[string]interface{}) ptrace.Traces { +func generateTraceData(serviceName, spanName string, attrs map[string]any) ptrace.Traces { td := ptrace.NewTraces() rs := td.ResourceSpans().AppendEmpty() if serviceName != "" { @@ -107,18 +107,18 @@ func TestAttributes_FilterSpans(t *testing.T) { { name: "apply processor", serviceName: "svcB", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply processor with different value for exclude property", serviceName: "svcB", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, @@ -126,16 +126,16 @@ func TestAttributes_FilterSpans(t *testing.T) { { name: "incorrect name for include property", serviceName: "noname", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "attribute match for exclude property", serviceName: "svcB", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -171,18 +171,18 @@ func TestAttributes_FilterSpansByNameStrict(t *testing.T) { { name: "apply", serviceName: "svcB", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply", serviceName: "svcB", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, @@ -190,22 +190,22 @@ func TestAttributes_FilterSpansByNameStrict(t *testing.T) { { name: "incorrect_span_name", serviceName: "svcB", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "dont_apply", serviceName: "svcB", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "incorrect_span_name_with_attr", serviceName: "svcB", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -239,18 +239,18 @@ func TestAttributes_FilterSpansByNameRegexp(t *testing.T) { { name: "apply_to_span_with_no_attrs", serviceName: "svcB", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply_to_span_with_attr", serviceName: "svcB", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, @@ -258,22 +258,22 @@ func TestAttributes_FilterSpansByNameRegexp(t *testing.T) { { name: "incorrect_span_name", serviceName: "svcB", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "apply_dont_apply", serviceName: "svcB", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, { name: "incorrect_span_name_with_attr", serviceName: "svcB", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "NoModification": true, }, }, @@ -306,37 +306,37 @@ func TestAttributes_Hash(t *testing.T) { testCases := []testCase{ { name: "String", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.email": "john.doe@example.com", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.email": "836f82db99121b3481011f16b49dfa5fbc714a0d1b1b9f784a1ebbbf5b39577f", }, }, { name: "Int", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.id": 10, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.id": "a111f275cc2e7588000001d300a31e76336d15b9d314cd1a1d8f3d3556975eed", }, }, { name: "Double", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.balance": 99.1, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.balance": "05fabd78b01be9692863cb0985f600c99da82979af18db5c55173c2a30adb924", }, }, { name: "Bool", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "user.authenticated": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "user.authenticated": "4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a", }, }, @@ -365,82 +365,82 @@ func TestAttributes_Convert(t *testing.T) { testCases := []testCase{ { name: "int to int", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": 1, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": 1, }, }, { name: "true to int", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": true, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": 1, }, }, { name: "false to int", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": 0, }, }, { name: "String to int (good)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": "123", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": 123, }, }, { name: "String to int (bad)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.int": "int-10", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.int": "int-10", }, }, { name: "String to double (int-ish)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.double": "123", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.double": 123.0, }, }, { name: "String to double (double-ish)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.double": "123.6", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.double": 123.6, }, }, { name: "String to double (bad)", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.double": "int-10", }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.double": "int-10", }, }, { name: "Double to string", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "to.string": 99.1, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "to.string": "99.1", }, }, @@ -468,25 +468,25 @@ func BenchmarkAttributes_FilterSpansByName(b *testing.B) { testCases := []testCase{ { name: "apply_to_span_with_no_attrs", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{ + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{ "attribute1": 123, }, }, { name: "apply_to_span_with_attr", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "NoModification": false, }, - expectedAttributes: map[string]interface{}{ + expectedAttributes: map[string]any{ "attribute1": 123, "NoModification": false, }, }, { name: "dont_apply", - inputAttributes: map[string]interface{}{}, - expectedAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, + expectedAttributes: map[string]any{}, }, } diff --git a/processor/cumulativetodeltaprocessor/internal/tracking/tracker.go b/processor/cumulativetodeltaprocessor/internal/tracking/tracker.go index 5844325a7043..21435a14b35c 100644 --- a/processor/cumulativetodeltaprocessor/internal/tracking/tracker.go +++ b/processor/cumulativetodeltaprocessor/internal/tracking/tracker.go @@ -54,7 +54,7 @@ func (i *InitialValue) UnmarshalText(text []byte) error { } var identityBufferPool = sync.Pool{ - New: func() interface{} { + New: func() any { return bytes.NewBuffer(make([]byte, initialBytes)) }, } @@ -203,7 +203,7 @@ func (t *MetricTracker) Convert(in MetricPoint) (out DeltaValue, valid bool) { } func (t *MetricTracker) removeStale(staleBefore pcommon.Timestamp) { - t.states.Range(func(key, value interface{}) bool { + t.states.Range(func(key, value any) bool { s := value.(*State) // There is a known race condition here. diff --git a/processor/cumulativetodeltaprocessor/internal/tracking/tracker_test.go b/processor/cumulativetodeltaprocessor/internal/tracking/tracker_test.go index 1f9d79743bda..8312532b7e4c 100644 --- a/processor/cumulativetodeltaprocessor/internal/tracking/tracker_test.go +++ b/processor/cumulativetodeltaprocessor/internal/tracking/tracker_test.go @@ -298,7 +298,7 @@ func Test_metricTracker_removeStale(t *testing.T) { tr.removeStale(currentTime) gotOut := make(map[string]*State) - tr.states.Range(func(key, value interface{}) bool { + tr.states.Range(func(key, value any) bool { gotOut[key.(string)] = value.(*State) return true }) diff --git a/processor/cumulativetodeltaprocessor/processor.go b/processor/cumulativetodeltaprocessor/processor.go index 6ebaf40c7fb3..83130ea97ee4 100644 --- a/processor/cumulativetodeltaprocessor/processor.go +++ b/processor/cumulativetodeltaprocessor/processor.go @@ -116,7 +116,7 @@ func (ctdp *cumulativeToDeltaProcessor) shouldConvertMetric(metricName string) b (ctdp.excludeFS == nil || !ctdp.excludeFS.Matches(metricName)) } -func (ctdp *cumulativeToDeltaProcessor) convertDataPoints(in interface{}, baseIdentity tracking.MetricIdentity) { +func (ctdp *cumulativeToDeltaProcessor) convertDataPoints(in any, baseIdentity tracking.MetricIdentity) { if dps, ok := in.(pmetric.NumberDataPointSlice); ok { dps.RemoveIf(func(dp pmetric.NumberDataPoint) bool { id := baseIdentity @@ -159,7 +159,7 @@ func (ctdp *cumulativeToDeltaProcessor) convertDataPoints(in interface{}, baseId } } -func (ctdp *cumulativeToDeltaProcessor) convertHistogramDataPoints(in interface{}, baseIdentity tracking.MetricIdentity) { +func (ctdp *cumulativeToDeltaProcessor) convertHistogramDataPoints(in any, baseIdentity tracking.MetricIdentity) { if dps, ok := in.(pmetric.HistogramDataPointSlice); ok { dps.RemoveIf(func(dp pmetric.HistogramDataPoint) bool { id := baseIdentity diff --git a/processor/filterprocessor/logs_test.go b/processor/filterprocessor/logs_test.go index 29fadfcdb57c..d53e2077058a 100644 --- a/processor/filterprocessor/logs_test.go +++ b/processor/filterprocessor/logs_test.go @@ -31,8 +31,8 @@ type logNameTest struct { type logWithResource struct { logNames []string - resourceAttributes map[string]interface{} - recordAttributes map[string]interface{} + resourceAttributes map[string]any + recordAttributes map[string]any severityText string body string severityNumber plog.SeverityNumber @@ -47,7 +47,7 @@ var ( inLogForResourceTest = []logWithResource{ { logNames: []string{"log1", "log2"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val1", "attr2": "attr2/val2", "attr3": "attr3/val3", @@ -58,13 +58,13 @@ var ( inLogForTwoResource = []logWithResource{ { logNames: []string{"log1", "log2"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val1", }, }, { logNames: []string{"log3", "log4"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val2", }, }, @@ -73,19 +73,19 @@ var ( inLogForTwoResourceWithRecordAttributes = []logWithResource{ { logNames: []string{"log1", "log2"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val1", }, - recordAttributes: map[string]interface{}{ + recordAttributes: map[string]any{ "rec": "rec/val1", }, }, { logNames: []string{"log3", "log4"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val2", }, - recordAttributes: map[string]interface{}{ + recordAttributes: map[string]any{ "rec": "rec/val2", }, }, @@ -93,28 +93,28 @@ var ( inLogForThreeResourceWithRecordAttributes = []logWithResource{ { logNames: []string{"log1", "log2"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val1", }, - recordAttributes: map[string]interface{}{ + recordAttributes: map[string]any{ "rec": "rec/val1", }, }, { logNames: []string{"log3", "log4"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val2", }, - recordAttributes: map[string]interface{}{ + recordAttributes: map[string]any{ "rec": "rec/val2", }, }, { logNames: []string{"log5"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val5", }, - recordAttributes: map[string]interface{}{ + recordAttributes: map[string]any{ "rec": "rec/val5", }, }, @@ -123,25 +123,25 @@ var ( inLogForFourResource = []logWithResource{ { logNames: []string{"log1"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr": "attr/val1", }, }, { logNames: []string{"log2"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr": "attr/val2", }, }, { logNames: []string{"log3"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr": "attr/val3", }, }, { logNames: []string{"log4"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr": "attr/val4", }, }, diff --git a/processor/filterprocessor/metrics_test.go b/processor/filterprocessor/metrics_test.go index b3d5ceecc906..76708634d268 100644 --- a/processor/filterprocessor/metrics_test.go +++ b/processor/filterprocessor/metrics_test.go @@ -36,7 +36,7 @@ type metricNameTest struct { type metricWithResource struct { metricNames []string - resourceAttributes map[string]interface{} + resourceAttributes map[string]any } var ( @@ -71,7 +71,7 @@ var ( inMetricForResourceTest = []metricWithResource{ { metricNames: []string{"metric1", "metric2"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val1", "attr2": "attr2/val2", "attr3": "attr3/val3", @@ -82,13 +82,13 @@ var ( inMetricForTwoResource = []metricWithResource{ { metricNames: []string{"metric1", "metric2"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val1", }, }, { metricNames: []string{"metric3", "metric4"}, - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "attr1": "attr1/val2", }, }, diff --git a/processor/filterprocessor/traces_test.go b/processor/filterprocessor/traces_test.go index f102cc959bce..0f68747d1ee8 100644 --- a/processor/filterprocessor/traces_test.go +++ b/processor/filterprocessor/traces_test.go @@ -27,8 +27,8 @@ type testTrace struct { spanName string libraryName string libraryVersion string - resourceAttributes map[string]interface{} - tags map[string]interface{} + resourceAttributes map[string]any + tags map[string]any } // All the data we need to define a test @@ -47,10 +47,10 @@ var ( spanName: "test!", libraryName: "otel", libraryVersion: "11", - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "service.name": "test_service", }, - tags: map[string]interface{}{ + tags: map[string]any{ "db.type": "redis", }, }, @@ -61,7 +61,7 @@ var ( spanName: "test!", libraryName: "otel", libraryVersion: "11", - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "service.name": "keep", }, }, @@ -69,7 +69,7 @@ var ( spanName: "test!", libraryName: "otel", libraryVersion: "11", - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "service.name": "dont_keep", }, }, @@ -77,7 +77,7 @@ var ( spanName: "test!", libraryName: "otel", libraryVersion: "11", - resourceAttributes: map[string]interface{}{ + resourceAttributes: map[string]any{ "service.name": "keep", }, }, diff --git a/processor/groupbytraceprocessor/event.go b/processor/groupbytraceprocessor/event.go index d5069f03a907..d7c26ca1b449 100644 --- a/processor/groupbytraceprocessor/event.go +++ b/processor/groupbytraceprocessor/event.go @@ -38,7 +38,7 @@ var ( seed = maphash.MakeSeed() hashPool = sync.Pool{ - New: func() interface{} { + New: func() any { var hash maphash.Hash hash.SetSeed(seed) return &hash @@ -51,7 +51,7 @@ var ( type eventType int type event struct { typ eventType - payload interface{} + payload any } type tracesWithID struct { diff --git a/processor/groupbytraceprocessor/event_test.go b/processor/groupbytraceprocessor/event_test.go index bc6635d4d4e0..d96605109118 100644 --- a/processor/groupbytraceprocessor/event_test.go +++ b/processor/groupbytraceprocessor/event_test.go @@ -24,7 +24,7 @@ func TestEventCallback(t *testing.T) { for _, tt := range []struct { casename string typ eventType - payload interface{} + payload any registerCallback func(em *eventMachine, wg *sync.WaitGroup) }{ { diff --git a/processor/k8sattributesprocessor/internal/kube/client.go b/processor/k8sattributesprocessor/internal/kube/client.go index 1a995fb9649c..805820d3ad4a 100644 --- a/processor/k8sattributesprocessor/internal/kube/client.go +++ b/processor/k8sattributesprocessor/internal/kube/client.go @@ -133,7 +133,7 @@ func New(logger *zap.Logger, apiCfg k8sconfig.APIConfig, rules ExtractionRules, c.informer = newInformer(c.kc, c.Filters.Namespace, labelSelector, fieldSelector) err = c.informer.SetTransform( - func(object interface{}) (interface{}, error) { + func(object any) (any, error) { originalPod, success := object.(*api_v1.Pod) if !success { // means this is a cache.DeletedFinalStateUnknown, in which case we do nothing return object, nil @@ -154,7 +154,7 @@ func New(logger *zap.Logger, apiCfg k8sconfig.APIConfig, rules ExtractionRules, } c.replicasetInformer = newReplicaSetInformer(c.kc, c.Filters.Namespace) err = c.replicasetInformer.SetTransform( - func(object interface{}) (interface{}, error) { + func(object any) (any, error) { originalReplicaset, success := object.(*apps_v1.ReplicaSet) if !success { // means this is a cache.DeletedFinalStateUnknown, in which case we do nothing return object, nil @@ -227,7 +227,7 @@ func (c *WatchClient) Stop() { close(c.stopCh) } -func (c *WatchClient) handlePodAdd(obj interface{}) { +func (c *WatchClient) handlePodAdd(obj any) { observability.RecordPodAdded() if pod, ok := obj.(*api_v1.Pod); ok { c.addOrUpdatePod(pod) @@ -238,7 +238,7 @@ func (c *WatchClient) handlePodAdd(obj interface{}) { observability.RecordPodTableSize(int64(podTableSize)) } -func (c *WatchClient) handlePodUpdate(_, newPod interface{}) { +func (c *WatchClient) handlePodUpdate(_, newPod any) { observability.RecordPodUpdated() if pod, ok := newPod.(*api_v1.Pod); ok { // TODO: update or remove based on whether container is ready/unready?. @@ -250,7 +250,7 @@ func (c *WatchClient) handlePodUpdate(_, newPod interface{}) { observability.RecordPodTableSize(int64(podTableSize)) } -func (c *WatchClient) handlePodDelete(obj interface{}) { +func (c *WatchClient) handlePodDelete(obj any) { observability.RecordPodDeleted() if pod, ok := ignoreDeletedFinalStateUnknown(obj).(*api_v1.Pod); ok { c.forgetPod(pod) @@ -261,7 +261,7 @@ func (c *WatchClient) handlePodDelete(obj interface{}) { observability.RecordPodTableSize(int64(podTableSize)) } -func (c *WatchClient) handleNamespaceAdd(obj interface{}) { +func (c *WatchClient) handleNamespaceAdd(obj any) { observability.RecordNamespaceAdded() if namespace, ok := obj.(*api_v1.Namespace); ok { c.addOrUpdateNamespace(namespace) @@ -270,7 +270,7 @@ func (c *WatchClient) handleNamespaceAdd(obj interface{}) { } } -func (c *WatchClient) handleNamespaceUpdate(_, newNamespace interface{}) { +func (c *WatchClient) handleNamespaceUpdate(_, newNamespace any) { observability.RecordNamespaceUpdated() if namespace, ok := newNamespace.(*api_v1.Namespace); ok { c.addOrUpdateNamespace(namespace) @@ -279,7 +279,7 @@ func (c *WatchClient) handleNamespaceUpdate(_, newNamespace interface{}) { } } -func (c *WatchClient) handleNamespaceDelete(obj interface{}) { +func (c *WatchClient) handleNamespaceDelete(obj any) { observability.RecordNamespaceDeleted() if namespace, ok := ignoreDeletedFinalStateUnknown(obj).(*api_v1.Namespace); ok { c.m.Lock() @@ -295,7 +295,7 @@ func (c *WatchClient) handleNamespaceDelete(obj interface{}) { } } -func (c *WatchClient) handleNodeAdd(obj interface{}) { +func (c *WatchClient) handleNodeAdd(obj any) { observability.RecordNodeAdded() if node, ok := obj.(*api_v1.Node); ok { c.addOrUpdateNode(node) @@ -304,7 +304,7 @@ func (c *WatchClient) handleNodeAdd(obj interface{}) { } } -func (c *WatchClient) handleNodeUpdate(_, newNode interface{}) { +func (c *WatchClient) handleNodeUpdate(_, newNode any) { observability.RecordNodeUpdated() if node, ok := newNode.(*api_v1.Node); ok { c.addOrUpdateNode(node) @@ -313,7 +313,7 @@ func (c *WatchClient) handleNodeUpdate(_, newNode interface{}) { } } -func (c *WatchClient) handleNodeDelete(obj interface{}) { +func (c *WatchClient) handleNodeDelete(obj any) { observability.RecordNodeDeleted() if node, ok := ignoreDeletedFinalStateUnknown(obj).(*api_v1.Node); ok { c.m.Lock() @@ -948,7 +948,7 @@ func needContainerAttributes(rules ExtractionRules) bool { rules.ContainerID } -func (c *WatchClient) handleReplicaSetAdd(obj interface{}) { +func (c *WatchClient) handleReplicaSetAdd(obj any) { observability.RecordReplicaSetAdded() if replicaset, ok := obj.(*apps_v1.ReplicaSet); ok { c.addOrUpdateReplicaSet(replicaset) @@ -957,7 +957,7 @@ func (c *WatchClient) handleReplicaSetAdd(obj interface{}) { } } -func (c *WatchClient) handleReplicaSetUpdate(_, newRS interface{}) { +func (c *WatchClient) handleReplicaSetUpdate(_, newRS any) { observability.RecordReplicaSetUpdated() if replicaset, ok := newRS.(*apps_v1.ReplicaSet); ok { c.addOrUpdateReplicaSet(replicaset) @@ -966,7 +966,7 @@ func (c *WatchClient) handleReplicaSetUpdate(_, newRS interface{}) { } } -func (c *WatchClient) handleReplicaSetDelete(obj interface{}) { +func (c *WatchClient) handleReplicaSetDelete(obj any) { observability.RecordReplicaSetDeleted() if replicaset, ok := ignoreDeletedFinalStateUnknown(obj).(*apps_v1.ReplicaSet); ok { c.m.Lock() @@ -1028,7 +1028,7 @@ func (c *WatchClient) getReplicaSet(uid string) (*ReplicaSet, bool) { // ignoreDeletedFinalStateUnknown returns the object wrapped in // DeletedFinalStateUnknown. Useful in OnDelete resource event handlers that do // not need the additional context. -func ignoreDeletedFinalStateUnknown(obj interface{}) interface{} { +func ignoreDeletedFinalStateUnknown(obj any) any { if obj, ok := obj.(cache.DeletedFinalStateUnknown); ok { return obj.Obj } diff --git a/processor/k8sattributesprocessor/internal/kube/client_test.go b/processor/k8sattributesprocessor/internal/kube/client_test.go index 38feedde29e4..4640dbbd8273 100644 --- a/processor/k8sattributesprocessor/internal/kube/client_test.go +++ b/processor/k8sattributesprocessor/internal/kube/client_test.go @@ -46,7 +46,7 @@ func newPodIdentifier(from string, name string, value string) PodIdentifier { } } -func podAddAndUpdateTest(t *testing.T, c *WatchClient, handler func(obj interface{})) { +func podAddAndUpdateTest(t *testing.T, c *WatchClient, handler func(obj any)) { assert.Equal(t, 0, len(c.Pods)) // pod without IP @@ -91,7 +91,7 @@ func podAddAndUpdateTest(t *testing.T, c *WatchClient, handler func(obj interfac } -func namespaceAddAndUpdateTest(t *testing.T, c *WatchClient, handler func(obj interface{})) { +func namespaceAddAndUpdateTest(t *testing.T, c *WatchClient, handler func(obj any)) { assert.Equal(t, 0, len(c.Namespaces)) namespace := &api_v1.Namespace{} @@ -116,7 +116,7 @@ func namespaceAddAndUpdateTest(t *testing.T, c *WatchClient, handler func(obj in assert.Equal(t, "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", got.NamespaceUID) } -func nodeAddAndUpdateTest(t *testing.T, c *WatchClient, handler func(obj interface{})) { +func nodeAddAndUpdateTest(t *testing.T, c *WatchClient, handler func(obj any)) { assert.Equal(t, 0, len(c.Nodes)) node := &api_v1.Node{} @@ -410,7 +410,7 @@ func TestPodAddOutOfSync(t *testing.T) { func TestPodUpdate(t *testing.T) { c, _ := newTestClient(t) - podAddAndUpdateTest(t, c, func(obj interface{}) { + podAddAndUpdateTest(t, c, func(obj any) { // first argument (old pod) is not used right now c.handlePodUpdate(&api_v1.Pod{}, obj) }) @@ -418,7 +418,7 @@ func TestPodUpdate(t *testing.T) { func TestNamespaceUpdate(t *testing.T) { c, _ := newTestClient(t) - namespaceAddAndUpdateTest(t, c, func(obj interface{}) { + namespaceAddAndUpdateTest(t, c, func(obj any) { // first argument (old namespace) is not used right now c.handleNamespaceUpdate(&api_v1.Namespace{}, obj) }) @@ -426,7 +426,7 @@ func TestNamespaceUpdate(t *testing.T) { func TestNodeUpdate(t *testing.T) { c, _ := newTestClient(t) - nodeAddAndUpdateTest(t, c, func(obj interface{}) { + nodeAddAndUpdateTest(t, c, func(obj any) { // first argument (old node) is not used right now c.handleNodeUpdate(&api_v1.Node{}, obj) }) diff --git a/processor/k8sattributesprocessor/internal/kube/fake_informer.go b/processor/k8sattributesprocessor/internal/kube/fake_informer.go index 04494161c5f0..058cd2eddf73 100644 --- a/processor/k8sattributesprocessor/internal/kube/fake_informer.go +++ b/processor/k8sattributesprocessor/internal/kube/fake_informer.go @@ -56,7 +56,7 @@ func (f *FakeInformer) SetTransform(_ cache.TransformFunc) error { } func (f *FakeInformer) GetStore() cache.Store { - return cache.NewStore(func(obj interface{}) (string, error) { return "", nil }) + return cache.NewStore(func(obj any) (string, error) { return "", nil }) } func (f *FakeInformer) GetController() cache.Controller { @@ -81,7 +81,7 @@ func (f *FakeNamespaceInformer) AddEventHandlerWithResyncPeriod(_ cache.Resource } func (f *FakeNamespaceInformer) GetStore() cache.Store { - return cache.NewStore(func(obj interface{}) (string, error) { return "", nil }) + return cache.NewStore(func(obj any) (string, error) { return "", nil }) } func (f *FakeNamespaceInformer) GetController() cache.Controller { @@ -111,7 +111,7 @@ func (f *FakeReplicaSetInformer) SetTransform(_ cache.TransformFunc) error { } func (f *FakeReplicaSetInformer) GetStore() cache.Store { - return cache.NewStore(func(obj interface{}) (string, error) { return "", nil }) + return cache.NewStore(func(obj any) (string, error) { return "", nil }) } func (f *FakeReplicaSetInformer) GetController() cache.Controller { @@ -176,7 +176,7 @@ func (f *NoOpInformer) SetTransform(_ cache.TransformFunc) error { } func (f *NoOpInformer) GetStore() cache.Store { - return cache.NewStore(func(obj interface{}) (string, error) { return "", nil }) + return cache.NewStore(func(obj any) (string, error) { return "", nil }) } func (f *NoOpInformer) GetController() cache.Controller { diff --git a/processor/metricstransformprocessor/operation_aggregate_labels.go b/processor/metricstransformprocessor/operation_aggregate_labels.go index dccc9ec869f3..6beabc6b7fc8 100644 --- a/processor/metricstransformprocessor/operation_aggregate_labels.go +++ b/processor/metricstransformprocessor/operation_aggregate_labels.go @@ -83,10 +83,10 @@ func mergeDataPoints(to pmetric.Metric, aggType aggregationType, ag aggGroups) { func groupNumberDataPoints(dps pmetric.NumberDataPointSlice, useStartTime bool, dpsByAttrsAndTs map[string]pmetric.NumberDataPointSlice) { - var keyHashParts []interface{} + var keyHashParts []any for i := 0; i < dps.Len(); i++ { if useStartTime { - keyHashParts = []interface{}{dps.At(i).StartTimestamp().String()} + keyHashParts = []any{dps.At(i).StartTimestamp().String()} } key := dataPointHashKey(dps.At(i).Attributes(), dps.At(i).Timestamp(), keyHashParts...) if _, ok := dpsByAttrsAndTs[key]; !ok { @@ -100,7 +100,7 @@ func groupHistogramDataPoints(dps pmetric.HistogramDataPointSlice, useStartTime dpsByAttrsAndTs map[string]pmetric.HistogramDataPointSlice) { for i := 0; i < dps.Len(); i++ { dp := dps.At(i) - keyHashParts := make([]interface{}, 0, dp.ExplicitBounds().Len()+4) + keyHashParts := make([]any, 0, dp.ExplicitBounds().Len()+4) for b := 0; b < dp.ExplicitBounds().Len(); b++ { keyHashParts = append(keyHashParts, dp.ExplicitBounds().At(b)) } @@ -121,7 +121,7 @@ func groupExponentialHistogramDataPoints(dps pmetric.ExponentialHistogramDataPoi dpsByAttrsAndTs map[string]pmetric.ExponentialHistogramDataPointSlice) { for i := 0; i < dps.Len(); i++ { dp := dps.At(i) - keyHashParts := make([]interface{}, 0, 5) + keyHashParts := make([]any, 0, 5) keyHashParts = append(keyHashParts, dp.Scale(), dp.HasMin(), dp.HasMax(), uint32(dp.Flags()), dp.Negative().Offset(), dp.Positive().Offset()) if useStartTime { @@ -147,8 +147,8 @@ func filterAttrs(metric pmetric.Metric, filterAttrKeys map[string]bool) { }) } -func dataPointHashKey(atts pcommon.Map, ts pcommon.Timestamp, other ...interface{}) string { - hashParts := []interface{}{atts.AsRaw(), ts.String()} +func dataPointHashKey(atts pcommon.Map, ts pcommon.Timestamp, other ...any) string { + hashParts := []any{atts.AsRaw(), ts.String()} jsonStr, _ := json.Marshal(append(hashParts, other...)) return string(jsonStr) } diff --git a/processor/redactionprocessor/processor_test.go b/processor/redactionprocessor/processor_test.go index 15b2b1632b70..b44ab20c950e 100644 --- a/processor/redactionprocessor/processor_test.go +++ b/processor/redactionprocessor/processor_test.go @@ -340,7 +340,7 @@ func TestProcessAttrsAppliedTwice(t *testing.T) { require.NoError(t, err) attrs := pcommon.NewMap() - assert.NoError(t, attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, attrs.FromRaw(map[string]any{ "id": 5, "redundant": 1.2, "mystery": "mystery ****", diff --git a/processor/resourcedetectionprocessor/internal/aws/eks/detector_test.go b/processor/resourcedetectionprocessor/internal/aws/eks/detector_test.go index 4d4b5b111970..daf8a9bedbda 100644 --- a/processor/resourcedetectionprocessor/internal/aws/eks/detector_test.go +++ b/processor/resourcedetectionprocessor/internal/aws/eks/detector_test.go @@ -44,7 +44,7 @@ func TestEKS(t *testing.T) { res, _, err := eksResourceDetector.Detect(ctx) require.NoError(t, err) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "cloud.provider": "aws", "cloud.platform": "aws_eks", }, res.Attributes().AsRaw(), "Resource object returned is incorrect") diff --git a/processor/resourcedetectionprocessor/internal/aws/lambda/lambda_test.go b/processor/resourcedetectionprocessor/internal/aws/lambda/lambda_test.go index babc11eb9229..46dcd2a7c82b 100644 --- a/processor/resourcedetectionprocessor/internal/aws/lambda/lambda_test.go +++ b/processor/resourcedetectionprocessor/internal/aws/lambda/lambda_test.go @@ -27,7 +27,7 @@ func TestLambda(t *testing.T) { require.NoError(t, err) require.NotNil(t, res) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ conventions.AttributeCloudProvider: conventions.AttributeCloudProviderAWS, conventions.AttributeCloudPlatform: conventions.AttributeCloudPlatformAWSLambda, conventions.AttributeFaaSName: functionName, diff --git a/processor/resourcedetectionprocessor/internal/azure/aks/aks_test.go b/processor/resourcedetectionprocessor/internal/azure/aks/aks_test.go index aa8da732bcfc..4ce567164f9b 100644 --- a/processor/resourcedetectionprocessor/internal/azure/aks/aks_test.go +++ b/processor/resourcedetectionprocessor/internal/azure/aks/aks_test.go @@ -31,7 +31,7 @@ func TestDetector_Detect_K8s_Azure(t *testing.T) { res, schemaURL, err := detector.Detect(context.Background()) require.NoError(t, err) assert.Equal(t, conventions.SchemaURL, schemaURL) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "cloud.provider": "azure", "cloud.platform": "azure_aks", }, res.Attributes().AsRaw(), "Resource attrs returned are incorrect") diff --git a/processor/resourcedetectionprocessor/internal/consul/config.go b/processor/resourcedetectionprocessor/internal/consul/config.go index b47f84fce29f..a994ac4fbc91 100644 --- a/processor/resourcedetectionprocessor/internal/consul/config.go +++ b/processor/resourcedetectionprocessor/internal/consul/config.go @@ -39,7 +39,7 @@ type Config struct { // Allowlist of [Consul // Metadata](https://www.consul.io/docs/agent/options#node_meta) keys to use as // resource attributes. - MetaLabels map[string]interface{} `mapstructure:"meta"` + MetaLabels map[string]any `mapstructure:"meta"` // ResourceAttributes configuration for Consul detector ResourceAttributes metadata.ResourceAttributesConfig `mapstructure:"resource_attributes"` diff --git a/processor/resourcedetectionprocessor/internal/resourcedetection.go b/processor/resourcedetectionprocessor/internal/resourcedetection.go index 449d41f820bd..95dd29243b7a 100644 --- a/processor/resourcedetectionprocessor/internal/resourcedetection.go +++ b/processor/resourcedetectionprocessor/internal/resourcedetection.go @@ -23,7 +23,7 @@ type Detector interface { Detect(ctx context.Context) (resource pcommon.Resource, schemaURL string, err error) } -type DetectorConfig interface{} +type DetectorConfig any type ResourceDetectorConfig interface { GetConfigFromType(DetectorType) DetectorConfig diff --git a/processor/resourcedetectionprocessor/internal/resourcedetection_test.go b/processor/resourcedetectionprocessor/internal/resourcedetection_test.go index d629ac957052..bd5dbb6d8261 100644 --- a/processor/resourcedetectionprocessor/internal/resourcedetection_test.go +++ b/processor/resourcedetectionprocessor/internal/resourcedetection_test.go @@ -210,7 +210,7 @@ func TestDetectResource_Parallel(t *testing.T) { md3 := NewMockParallelDetector() md3.On("Detect").Return(pcommon.NewResource(), errors.New("an error")) - expectedResourceAttrs := map[string]interface{}{"a": "1", "b": "2", "c": "3"} + expectedResourceAttrs := map[string]any{"a": "1", "b": "2", "c": "3"} p := NewResourceProvider(zap.NewNop(), time.Second, nil, md1, md2, md3) diff --git a/processor/routingprocessor/factory.go b/processor/routingprocessor/factory.go index e146d0892db9..8523a4c5433d 100644 --- a/processor/routingprocessor/factory.go +++ b/processor/routingprocessor/factory.go @@ -61,7 +61,7 @@ func createLogsProcessor(_ context.Context, params processor.CreateSettings, cfg return newLogProcessor(params.TelemetrySettings, cfg) } -func warnIfNotLastInPipeline(nextConsumer interface{}, logger *zap.Logger) { +func warnIfNotLastInPipeline(nextConsumer any, logger *zap.Logger) { _, ok := nextConsumer.(component.Component) if ok { logger.Warn("another processor has been defined after the routing processor: it will NOT receive any data!") diff --git a/processor/routingprocessor/internal/common/functions.go b/processor/routingprocessor/internal/common/functions.go index c4556f67390d..489dd39285bb 100644 --- a/processor/routingprocessor/internal/common/functions.go +++ b/processor/routingprocessor/internal/common/functions.go @@ -11,7 +11,7 @@ import ( ) func createRouteFunction[K any](_ ottl.FunctionContext, _ ottl.Arguments) (ottl.ExprFunc[K], error) { - return func(context.Context, K) (interface{}, error) { + return func(context.Context, K) (any, error) { return true, nil }, nil } diff --git a/processor/servicegraphprocessor/processor.go b/processor/servicegraphprocessor/processor.go index 28fb5ca8893a..866b49009647 100644 --- a/processor/servicegraphprocessor/processor.go +++ b/processor/servicegraphprocessor/processor.go @@ -76,7 +76,7 @@ type serviceGraphProcessor struct { metricMutex sync.RWMutex keyToMetric map[string]metricSeries - shutdownCh chan interface{} + shutdownCh chan any } func newProcessor(logger *zap.Logger, config component.Config) *serviceGraphProcessor { @@ -116,7 +116,7 @@ func newProcessor(logger *zap.Logger, config component.Config) *serviceGraphProc reqServerDurationSecondsBucketCounts: make(map[string][]uint64), reqDurationBounds: bounds, keyToMetric: make(map[string]metricSeries), - shutdownCh: make(chan interface{}), + shutdownCh: make(chan any), } } diff --git a/processor/spanmetricsprocessor/processor_test.go b/processor/spanmetricsprocessor/processor_test.go index 52c25e7ca39f..1955dd41ce43 100644 --- a/processor/spanmetricsprocessor/processor_test.go +++ b/processor/spanmetricsprocessor/processor_test.go @@ -756,8 +756,8 @@ func TestBuildKeyWithDimensions(t *testing.T) { for _, tc := range []struct { name string optionalDims []dimension - resourceAttrMap map[string]interface{} - spanAttrMap map[string]interface{} + resourceAttrMap map[string]any + spanAttrMap map[string]any wantKey string }{ { @@ -783,7 +783,7 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - spanAttrMap: map[string]interface{}{ + spanAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u000099", @@ -793,7 +793,7 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - resourceAttrMap: map[string]interface{}{ + resourceAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u000099", @@ -803,10 +803,10 @@ func TestBuildKeyWithDimensions(t *testing.T) { optionalDims: []dimension{ {name: "foo"}, }, - spanAttrMap: map[string]interface{}{ + spanAttrMap: map[string]any{ "foo": 100, }, - resourceAttrMap: map[string]interface{}{ + resourceAttrMap: map[string]any{ "foo": 99, }, wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u0000100", diff --git a/processor/spanprocessor/span_test.go b/processor/spanprocessor/span_test.go index a9125d0aee8e..93252b7a4dc3 100644 --- a/processor/spanprocessor/span_test.go +++ b/processor/spanprocessor/span_test.go @@ -40,9 +40,9 @@ func TestNewTracesProcessor(t *testing.T) { type testCase struct { serviceName string inputName string - inputAttributes map[string]interface{} + inputAttributes map[string]any outputName string - outputAttributes map[string]interface{} + outputAttributes map[string]any } // runIndividualTestCase is the common logic of passing trace data through a configured attributes processor. @@ -55,7 +55,7 @@ func runIndividualTestCase(t *testing.T, tt testCase, tp processor.Traces) { }) } -func generateTraceData(serviceName, inputName string, attrs map[string]interface{}) ptrace.Traces { +func generateTraceData(serviceName, inputName string, attrs map[string]any) ptrace.Traces { td := ptrace.NewTraces() rs := td.ResourceSpans().AppendEmpty() if serviceName != "" { @@ -137,47 +137,47 @@ func TestSpanProcessor_Values(t *testing.T) { }, { inputName: "empty-attributes", - inputAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, outputName: "empty-attributes", - outputAttributes: map[string]interface{}{}, + outputAttributes: map[string]any{}, }, { inputName: "string-type", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "key1": "bob", }, outputName: "bob", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "key1": "bob", }, }, { inputName: "int-type", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "key1": 123, }, outputName: "123", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "key1": 123, }, }, { inputName: "double-type", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "key1": 234.129312, }, outputName: "234.129312", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "key1": 234.129312, }, }, { inputName: "bool-type", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "key1": true, }, outputName: "true", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "key1": true, }, }, @@ -224,13 +224,13 @@ func TestSpanProcessor_MissingKeys(t *testing.T) { testCases := []testCase{ { inputName: "first-keys-missing", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "key2": 123, "key3": 234.129312, "key4": true, }, outputName: "first-keys-missing", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "key2": 123, "key3": 234.129312, "key4": true, @@ -238,13 +238,13 @@ func TestSpanProcessor_MissingKeys(t *testing.T) { }, { inputName: "middle-key-missing", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "key1": "bob", "key2": 123, "key4": true, }, outputName: "middle-key-missing", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "key1": "bob", "key2": 123, "key4": true, @@ -252,13 +252,13 @@ func TestSpanProcessor_MissingKeys(t *testing.T) { }, { inputName: "last-key-missing", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "key1": "bob", "key2": 123, "key3": 234.129312, }, outputName: "last-key-missing", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "key1": "bob", "key2": 123, "key3": 234.129312, @@ -266,14 +266,14 @@ func TestSpanProcessor_MissingKeys(t *testing.T) { }, { inputName: "all-keys-exists", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "key1": "bob", "key2": 123, "key3": 234.129312, "key4": true, }, outputName: "bob::123::234.129312::true", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "key1": "bob", "key2": 123, "key3": 234.129312, @@ -312,7 +312,7 @@ func TestSpanProcessor_Separator(t *testing.T) { traceData := generateTraceData( "", "ensure no separator in the rename with one key", - map[string]interface{}{ + map[string]any{ "key1": "bob", }) assert.NoError(t, tp.ConsumeTraces(context.Background(), traceData)) @@ -320,7 +320,7 @@ func TestSpanProcessor_Separator(t *testing.T) { assert.NoError(t, ptracetest.CompareTraces(generateTraceData( "", "bob", - map[string]interface{}{ + map[string]any{ "key1": "bob", }), traceData)) } @@ -340,7 +340,7 @@ func TestSpanProcessor_NoSeparatorMultipleKeys(t *testing.T) { traceData := generateTraceData( "", - "ensure no separator in the rename with two keys", map[string]interface{}{ + "ensure no separator in the rename with two keys", map[string]any{ "key1": "bob", "key2": 123, }) @@ -349,7 +349,7 @@ func TestSpanProcessor_NoSeparatorMultipleKeys(t *testing.T) { assert.NoError(t, ptracetest.CompareTraces(generateTraceData( "", "bob123", - map[string]interface{}{ + map[string]any{ "key1": "bob", "key2": 123, }), traceData)) @@ -371,7 +371,7 @@ func TestSpanProcessor_SeparatorMultipleKeys(t *testing.T) { traceData := generateTraceData( "", "rename with separators and multiple keys", - map[string]interface{}{ + map[string]any{ "key1": "bob", "key2": 123, "key3": 234.129312, @@ -382,7 +382,7 @@ func TestSpanProcessor_SeparatorMultipleKeys(t *testing.T) { assert.NoError(t, ptracetest.CompareTraces(generateTraceData( "", "bob::123::234.129312::true", - map[string]interface{}{ + map[string]any{ "key1": "bob", "key2": 123, "key3": 234.129312, @@ -406,7 +406,7 @@ func TestSpanProcessor_NilName(t *testing.T) { traceData := generateTraceData( "", "", - map[string]interface{}{ + map[string]any{ "key1": "bob", }) assert.NoError(t, tp.ConsumeTraces(context.Background(), traceData)) @@ -414,7 +414,7 @@ func TestSpanProcessor_NilName(t *testing.T) { assert.NoError(t, ptracetest.CompareTraces(generateTraceData( "", "bob", - map[string]interface{}{ + map[string]any{ "key1": "bob", }), traceData)) } @@ -431,9 +431,9 @@ func TestSpanProcessor_ToAttributes(t *testing.T) { rules: []string{`^\/api\/v1\/document\/(?P.*)\/update\/1$`}, testCase: testCase{ inputName: "/api/v1/document/321083210/update/1", - inputAttributes: map[string]interface{}{}, + inputAttributes: map[string]any{}, outputName: "/api/v1/document/{documentId}/update/1", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "documentId": "321083210", }, }, @@ -444,7 +444,7 @@ func TestSpanProcessor_ToAttributes(t *testing.T) { testCase: testCase{ inputName: "/api/v1/document/321083210/update/2", outputName: "/api/{version}/document/{documentId}/update/2", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "documentId": "321083210", "version": "v1", }, @@ -457,7 +457,7 @@ func TestSpanProcessor_ToAttributes(t *testing.T) { testCase: testCase{ inputName: "/api/v1/document/321083210/update/3", outputName: "/api/{version}/document/{documentId}/update/3", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "documentId": "321083210", "version": "v1", }, @@ -471,7 +471,7 @@ func TestSpanProcessor_ToAttributes(t *testing.T) { testCase: testCase{ inputName: "/api/v1/document/321083210/update/4", outputName: "/api/v1/document/{documentId}/update/4", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "documentId": "321083210", }, }, @@ -520,29 +520,29 @@ func TestSpanProcessor_skipSpan(t *testing.T) { serviceName: "banks", inputName: "www.test.com/code", outputName: "{operation_website}", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "operation_website": "www.test.com/code", }, }, { serviceName: "banks", inputName: "donot/", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "operation_website": "www.test.com/code", }, outputName: "{operation_website}", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "operation_website": "donot/", }, }, { serviceName: "banks", inputName: "donot/change", - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "operation_website": "www.test.com/code", }, outputName: "donot/change", - outputAttributes: map[string]interface{}{ + outputAttributes: map[string]any{ "operation_website": "www.test.com/code", }, }, @@ -572,7 +572,7 @@ func TestSpanProcessor_skipSpan(t *testing.T) { } } -func generateTraceDataSetStatus(code ptrace.StatusCode, description string, attrs map[string]interface{}) ptrace.Traces { +func generateTraceDataSetStatus(code ptrace.StatusCode, description string, attrs map[string]any) ptrace.Traces { td := ptrace.NewTraces() rs := td.ResourceSpans().AppendEmpty() span := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty() @@ -624,7 +624,7 @@ func TestSpanProcessor_setStatusCodeConditionally(t *testing.T) { require.NotNil(t, tp) testCases := []struct { - inputAttributes map[string]interface{} + inputAttributes map[string]any inputStatusCode ptrace.StatusCode outputStatusCode ptrace.StatusCode outputStatusDescription string @@ -635,7 +635,7 @@ func TestSpanProcessor_setStatusCodeConditionally(t *testing.T) { outputStatusCode: ptrace.StatusCodeOk, }, { - inputAttributes: map[string]interface{}{ + inputAttributes: map[string]any{ "http.status_code": 400, }, inputStatusCode: ptrace.StatusCodeOk, diff --git a/processor/sumologicprocessor/processor_test.go b/processor/sumologicprocessor/processor_test.go index 93aa412a7699..35ff285c8e4d 100644 --- a/processor/sumologicprocessor/processor_test.go +++ b/processor/sumologicprocessor/processor_test.go @@ -653,7 +653,7 @@ func TestTranslateDockerMetrics(t *testing.T) { originalNames []string translatedNames []string originalResourceAttributes map[string]string - translatedResourceAttributes map[string]interface{} + translatedResourceAttributes map[string]any shouldTranslate bool }{ { @@ -665,7 +665,7 @@ func TestTranslateDockerMetrics(t *testing.T) { "container.image.name": "a", "container.name": "a", }, - translatedResourceAttributes: map[string]interface{}{ + translatedResourceAttributes: map[string]any{ "container.FullID": "a", "container.ImageName": "a", "container.Name": "a", @@ -681,7 +681,7 @@ func TestTranslateDockerMetrics(t *testing.T) { "container.image.name": "a", "container.name": "a", }, - translatedResourceAttributes: map[string]interface{}{ + translatedResourceAttributes: map[string]any{ "container.id": "a", "container.image.name": "a", "container.name": "a", diff --git a/processor/sumologicprocessor/translate_attributes_processor_test.go b/processor/sumologicprocessor/translate_attributes_processor_test.go index 7ea13b9614a7..c9dd1443e2cc 100644 --- a/processor/sumologicprocessor/translate_attributes_processor_test.go +++ b/processor/sumologicprocessor/translate_attributes_processor_test.go @@ -115,7 +115,7 @@ func assertAttribute(t *testing.T, metadata pcommon.Map, attributeName string, e } var ( - benchPdataAttributes = map[string]interface{}{ + benchPdataAttributes = map[string]any{ "host.name": pcommon.NewValueStr("testing-host"), "host.id": pcommon.NewValueStr("my-host-id"), "host.type": pcommon.NewValueStr("my-host-type"), diff --git a/processor/tailsamplingprocessor/internal/sampling/boolean_tag_filter_test.go b/processor/tailsamplingprocessor/internal/sampling/boolean_tag_filter_test.go index bb43e17b4775..71bdf180849f 100644 --- a/processor/tailsamplingprocessor/internal/sampling/boolean_tag_filter_test.go +++ b/processor/tailsamplingprocessor/internal/sampling/boolean_tag_filter_test.go @@ -16,10 +16,10 @@ import ( func TestBooleanTagFilter(t *testing.T) { - var empty = map[string]interface{}{} + var empty = map[string]any{} filter := NewBooleanAttributeFilter(componenttest.NewNopTelemetrySettings(), "example", true) - resAttr := map[string]interface{}{} + resAttr := map[string]any{} resAttr["example"] = 8 cases := []struct { @@ -54,7 +54,7 @@ func TestBooleanTagFilter(t *testing.T) { } } -func newTraceBoolAttrs(nodeAttrs map[string]interface{}, spanAttrKey string, spanAttrValue bool) *TraceData { +func newTraceBoolAttrs(nodeAttrs map[string]any, spanAttrKey string, spanAttrValue bool) *TraceData { traces := ptrace.NewTraces() rs := traces.ResourceSpans().AppendEmpty() //nolint:errcheck diff --git a/processor/tailsamplingprocessor/internal/sampling/numeric_tag_filter_test.go b/processor/tailsamplingprocessor/internal/sampling/numeric_tag_filter_test.go index 29871debfcff..7c5a6bc70726 100644 --- a/processor/tailsamplingprocessor/internal/sampling/numeric_tag_filter_test.go +++ b/processor/tailsamplingprocessor/internal/sampling/numeric_tag_filter_test.go @@ -17,10 +17,10 @@ import ( func TestNumericTagFilter(t *testing.T) { - var empty = map[string]interface{}{} + var empty = map[string]any{} filter := NewNumericAttributeFilter(componenttest.NewNopTelemetrySettings(), "example", math.MinInt32, math.MaxInt32, false) - resAttr := map[string]interface{}{} + resAttr := map[string]any{} resAttr["example"] = 8 cases := []struct { @@ -67,10 +67,10 @@ func TestNumericTagFilter(t *testing.T) { func TestNumericTagFilterInverted(t *testing.T) { - var empty = map[string]interface{}{} + var empty = map[string]any{} filter := NewNumericAttributeFilter(componenttest.NewNopTelemetrySettings(), "example", math.MinInt32, math.MaxInt32, true) - resAttr := map[string]interface{}{} + resAttr := map[string]any{} resAttr["example"] = 8 cases := []struct { @@ -115,7 +115,7 @@ func TestNumericTagFilterInverted(t *testing.T) { } } -func newTraceIntAttrs(nodeAttrs map[string]interface{}, spanAttrKey string, spanAttrValue int64) *TraceData { +func newTraceIntAttrs(nodeAttrs map[string]any, spanAttrKey string, spanAttrValue int64) *TraceData { traces := ptrace.NewTraces() rs := traces.ResourceSpans().AppendEmpty() //nolint:errcheck diff --git a/processor/tailsamplingprocessor/internal/sampling/string_tag_filter_test.go b/processor/tailsamplingprocessor/internal/sampling/string_tag_filter_test.go index 8bd2ffcf5358..65bed0193a09 100644 --- a/processor/tailsamplingprocessor/internal/sampling/string_tag_filter_test.go +++ b/processor/tailsamplingprocessor/internal/sampling/string_tag_filter_test.go @@ -32,19 +32,19 @@ func TestStringTagFilter(t *testing.T) { }{ { Desc: "nonmatching node attribute key", - Trace: newTraceStringAttrs(map[string]interface{}{"non_matching": "value"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"non_matching": "value"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"value"}, EnabledRegexMatching: false, CacheMaxSize: defaultCacheSize}, Decision: NotSampled, }, { Desc: "nonmatching node attribute value", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "non_matching"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "non_matching"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"value"}, EnabledRegexMatching: false, CacheMaxSize: defaultCacheSize}, Decision: NotSampled, }, { Desc: "matching node attribute", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "value"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "value"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"value"}, EnabledRegexMatching: false, CacheMaxSize: defaultCacheSize}, Decision: Sampled, }, @@ -86,7 +86,7 @@ func TestStringTagFilter(t *testing.T) { }, { Desc: "matching plain text node attribute in regex", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "value"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "value"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"value"}, EnabledRegexMatching: true, CacheMaxSize: defaultCacheSize}, Decision: Sampled, }, @@ -98,31 +98,31 @@ func TestStringTagFilter(t *testing.T) { }, { Desc: "invert nonmatching node attribute key", - Trace: newTraceStringAttrs(map[string]interface{}{"non_matching": "value"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"non_matching": "value"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"value"}, EnabledRegexMatching: false, CacheMaxSize: defaultCacheSize, InvertMatch: true}, Decision: InvertSampled, }, { Desc: "invert nonmatching node attribute value", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "non_matching"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "non_matching"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"value"}, EnabledRegexMatching: false, CacheMaxSize: defaultCacheSize, InvertMatch: true}, Decision: InvertSampled, }, { Desc: "invert nonmatching node attribute list", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "non_matching"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "non_matching"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"first_value", "value", "last_value"}, EnabledRegexMatching: false, CacheMaxSize: defaultCacheSize, InvertMatch: true}, Decision: InvertSampled, }, { Desc: "invert matching node attribute", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "value"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "value"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"value"}, EnabledRegexMatching: false, CacheMaxSize: defaultCacheSize, InvertMatch: true}, Decision: InvertNotSampled, }, { Desc: "invert matching node attribute list", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "value"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "value"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"first_value", "value", "last_value"}, EnabledRegexMatching: false, CacheMaxSize: defaultCacheSize, InvertMatch: true}, Decision: InvertNotSampled, }, @@ -182,13 +182,13 @@ func TestStringTagFilter(t *testing.T) { }, { Desc: "invert matching plain text node attribute in regex", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "value"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "value"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"value"}, EnabledRegexMatching: true, CacheMaxSize: defaultCacheSize, InvertMatch: true}, Decision: InvertNotSampled, }, { Desc: "invert matching plain text node attribute in regex list", - Trace: newTraceStringAttrs(map[string]interface{}{"example": "value"}, "", ""), + Trace: newTraceStringAttrs(map[string]any{"example": "value"}, "", ""), filterCfg: &TestStringAttributeCfg{Key: "example", Values: []string{"first_value", "value", "last_value"}, EnabledRegexMatching: true, CacheMaxSize: defaultCacheSize, InvertMatch: true}, Decision: InvertNotSampled, }, @@ -211,7 +211,7 @@ func TestStringTagFilter(t *testing.T) { } func BenchmarkStringTagFilterEvaluatePlainText(b *testing.B) { - trace := newTraceStringAttrs(map[string]interface{}{"example": "value"}, "", "") + trace := newTraceStringAttrs(map[string]any{"example": "value"}, "", "") filter := NewStringAttributeFilter(componenttest.NewNopTelemetrySettings(), "example", []string{"value"}, false, 0, false) b.ResetTimer() for i := 0; i < b.N; i++ { @@ -221,7 +221,7 @@ func BenchmarkStringTagFilterEvaluatePlainText(b *testing.B) { } func BenchmarkStringTagFilterEvaluateRegex(b *testing.B) { - trace := newTraceStringAttrs(map[string]interface{}{"example": "grpc.health.v1.HealthCheck"}, "", "") + trace := newTraceStringAttrs(map[string]any{"example": "grpc.health.v1.HealthCheck"}, "", "") filter := NewStringAttributeFilter(componenttest.NewNopTelemetrySettings(), "example", []string{"v[0-9]+.HealthCheck$"}, true, 0, false) b.ResetTimer() for i := 0; i < b.N; i++ { @@ -230,7 +230,7 @@ func BenchmarkStringTagFilterEvaluateRegex(b *testing.B) { } } -func newTraceStringAttrs(nodeAttrs map[string]interface{}, spanAttrKey string, spanAttrValue string) *TraceData { +func newTraceStringAttrs(nodeAttrs map[string]any, spanAttrKey string, spanAttrValue string) *TraceData { traces := ptrace.NewTraces() rs := traces.ResourceSpans().AppendEmpty() //nolint:errcheck diff --git a/processor/tailsamplingprocessor/processor_test.go b/processor/tailsamplingprocessor/processor_test.go index 94d574c90009..c0a70d659f80 100644 --- a/processor/tailsamplingprocessor/processor_test.go +++ b/processor/tailsamplingprocessor/processor_test.go @@ -344,7 +344,7 @@ func TestConcurrentTraceMapSize(t *testing.T) { // Since we can't guarantee the order of insertion the only thing that can be checked is // if the number of traces on the map matches the expected value. cnt := 0 - tsp.idToTrace.Range(func(_ interface{}, _ interface{}) bool { + tsp.idToTrace.Range(func(_ any, _ any) bool { cnt++ return true }) diff --git a/processor/transformprocessor/internal/metrics/func_convert_gauge_to_sum.go b/processor/transformprocessor/internal/metrics/func_convert_gauge_to_sum.go index 6eea0a12012d..640d26d2f063 100644 --- a/processor/transformprocessor/internal/metrics/func_convert_gauge_to_sum.go +++ b/processor/transformprocessor/internal/metrics/func_convert_gauge_to_sum.go @@ -43,7 +43,7 @@ func convertGaugeToSum(stringAggTemp string, monotonic bool) (ottl.ExprFunc[ottl return nil, fmt.Errorf("unknown aggregation temporality: %s", stringAggTemp) } - return func(_ context.Context, tCtx ottldatapoint.TransformContext) (interface{}, error) { + return func(_ context.Context, tCtx ottldatapoint.TransformContext) (any, error) { metric := tCtx.GetMetric() if metric.Type() != pmetric.MetricTypeGauge { return nil, nil diff --git a/processor/transformprocessor/internal/metrics/func_convert_sum_to_gauge.go b/processor/transformprocessor/internal/metrics/func_convert_sum_to_gauge.go index 22a57425e244..5166795b8730 100644 --- a/processor/transformprocessor/internal/metrics/func_convert_sum_to_gauge.go +++ b/processor/transformprocessor/internal/metrics/func_convert_sum_to_gauge.go @@ -21,7 +21,7 @@ func createConvertSumToGaugeFunction(_ ottl.FunctionContext, _ ottl.Arguments) ( } func convertSumToGauge() (ottl.ExprFunc[ottldatapoint.TransformContext], error) { - return func(_ context.Context, tCtx ottldatapoint.TransformContext) (interface{}, error) { + return func(_ context.Context, tCtx ottldatapoint.TransformContext) (any, error) { metric := tCtx.GetMetric() if metric.Type() != pmetric.MetricTypeSum { return nil, nil diff --git a/processor/transformprocessor/internal/metrics/func_convert_summary_count_val_to_sum.go b/processor/transformprocessor/internal/metrics/func_convert_summary_count_val_to_sum.go index dfd5bc550bd1..c329ba34fd0d 100644 --- a/processor/transformprocessor/internal/metrics/func_convert_summary_count_val_to_sum.go +++ b/processor/transformprocessor/internal/metrics/func_convert_summary_count_val_to_sum.go @@ -42,7 +42,7 @@ func convertSummaryCountValToSum(stringAggTemp string, monotonic bool) (ottl.Exp default: return nil, fmt.Errorf("unknown aggregation temporality: %s", stringAggTemp) } - return func(_ context.Context, tCtx ottldatapoint.TransformContext) (interface{}, error) { + return func(_ context.Context, tCtx ottldatapoint.TransformContext) (any, error) { metric := tCtx.GetMetric() if metric.Type() != pmetric.MetricTypeSummary { return nil, nil diff --git a/processor/transformprocessor/internal/metrics/func_convert_summary_sum_val_to_sum.go b/processor/transformprocessor/internal/metrics/func_convert_summary_sum_val_to_sum.go index d5557a87b415..1deb6bdb2710 100644 --- a/processor/transformprocessor/internal/metrics/func_convert_summary_sum_val_to_sum.go +++ b/processor/transformprocessor/internal/metrics/func_convert_summary_sum_val_to_sum.go @@ -42,7 +42,7 @@ func convertSummarySumValToSum(stringAggTemp string, monotonic bool) (ottl.ExprF default: return nil, fmt.Errorf("unknown aggregation temporality: %s", stringAggTemp) } - return func(_ context.Context, tCtx ottldatapoint.TransformContext) (interface{}, error) { + return func(_ context.Context, tCtx ottldatapoint.TransformContext) (any, error) { metric := tCtx.GetMetric() if metric.Type() != pmetric.MetricTypeSummary { return nil, nil diff --git a/processor/transformprocessor/internal/metrics/func_extract_count_metric.go b/processor/transformprocessor/internal/metrics/func_extract_count_metric.go index b10dfc4ff873..789a6226beba 100644 --- a/processor/transformprocessor/internal/metrics/func_extract_count_metric.go +++ b/processor/transformprocessor/internal/metrics/func_extract_count_metric.go @@ -32,7 +32,7 @@ func createExtractCountMetricFunction(_ ottl.FunctionContext, oArgs ottl.Argumen } func extractCountMetric(monotonic bool) (ottl.ExprFunc[ottlmetric.TransformContext], error) { - return func(_ context.Context, tCtx ottlmetric.TransformContext) (interface{}, error) { + return func(_ context.Context, tCtx ottlmetric.TransformContext) (any, error) { metric := tCtx.GetMetric() invalidMetricTypeError := fmt.Errorf("extract_count_metric requires an input metric of type Histogram, ExponentialHistogram or Summary, got %s", metric.Type()) diff --git a/processor/transformprocessor/internal/metrics/func_extract_sum_metric.go b/processor/transformprocessor/internal/metrics/func_extract_sum_metric.go index 63cd74d067ee..78b47623cdf3 100644 --- a/processor/transformprocessor/internal/metrics/func_extract_sum_metric.go +++ b/processor/transformprocessor/internal/metrics/func_extract_sum_metric.go @@ -43,7 +43,7 @@ type SumCountDataPoint interface { } func extractSumMetric(monotonic bool) (ottl.ExprFunc[ottlmetric.TransformContext], error) { - return func(_ context.Context, tCtx ottlmetric.TransformContext) (interface{}, error) { + return func(_ context.Context, tCtx ottlmetric.TransformContext) (any, error) { metric := tCtx.GetMetric() invalidMetricTypeError := fmt.Errorf("extract_sum_metric requires an input metric of type Histogram, ExponentialHistogram or Summary, got %s", metric.Type()) diff --git a/receiver/aerospikereceiver/cluster/mocks/Node.go b/receiver/aerospikereceiver/cluster/mocks/Node.go index dacb253beddb..07f96a41aaac 100644 --- a/receiver/aerospikereceiver/cluster/mocks/Node.go +++ b/receiver/aerospikereceiver/cluster/mocks/Node.go @@ -33,11 +33,11 @@ func (_m *Node) GetName() string { // RequestInfo provides a mock function with given fields: _a0, _a1 func (_m *Node) RequestInfo(_a0 *aerospike.InfoPolicy, _a1 ...string) (map[string]string, aerospike.Error) { - _va := make([]interface{}, len(_a1)) + _va := make([]any, len(_a1)) for _i := range _a1 { _va[_i] = _a1[_i] } - var _ca []interface{} + var _ca []any _ca = append(_ca, _a0) _ca = append(_ca, _va...) ret := _m.Called(_ca...) diff --git a/receiver/aerospikereceiver/cluster/mocks/asconn.go b/receiver/aerospikereceiver/cluster/mocks/asconn.go index b5ad7c05e48f..e57b1c287b10 100644 --- a/receiver/aerospikereceiver/cluster/mocks/asconn.go +++ b/receiver/aerospikereceiver/cluster/mocks/asconn.go @@ -37,11 +37,11 @@ func (_m *Asconn) Login(_a0 *aerospike.ClientPolicy) aerospike.Error { // RequestInfo provides a mock function with given fields: _a0 func (_m *Asconn) RequestInfo(_a0 ...string) (map[string]string, aerospike.Error) { - _va := make([]interface{}, len(_a0)) + _va := make([]any, len(_a0)) for _i := range _a0 { _va[_i] = _a0[_i] } - var _ca []interface{} + var _ca []any _ca = append(_ca, _va...) ret := _m.Called(_ca...) diff --git a/receiver/aerospikereceiver/cluster/node_test.go b/receiver/aerospikereceiver/cluster/node_test.go index d24a7d1a41b0..a09b53c989c7 100644 --- a/receiver/aerospikereceiver/cluster/node_test.go +++ b/receiver/aerospikereceiver/cluster/node_test.go @@ -76,7 +76,7 @@ func TestNode_NewConnNode(t *testing.T) { func TestNode_RequestInfo(t *testing.T) { conn := mocks.NewAsconn(t) nodeName := "BB990C28F270008" - commands := []interface{}{"node", "statistics"} + commands := []any{"node", "statistics"} cPolicy := as.NewClientPolicy() diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_nolinux.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_nolinux.go index 4e7871dbb9f4..19999a2f3b95 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_nolinux.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_nolinux.go @@ -34,13 +34,13 @@ type Decorator interface { type Option func(*Cadvisor) // WithDecorator constructs an option for configuring the metric decorator -func WithDecorator(_ interface{}) Option { +func WithDecorator(_ any) Option { return func(c *Cadvisor) { // do nothing } } -func WithECSInfoCreator(_ interface{}) Option { +func WithECSInfoCreator(_ any) Option { return func(c *Cadvisor) { // do nothing } diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/diskio_extractor_test.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/diskio_extractor_test.go index 517d63fd1b42..f8492d8d0c85 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/diskio_extractor_test.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/diskio_extractor_test.go @@ -30,14 +30,14 @@ func TestDiskIOStats(t *testing.T) { cMetrics = extractor.GetValue(result2[0], nil, containerType) } - expectedFieldsService := map[string]interface{}{ + expectedFieldsService := map[string]any{ "node_diskio_io_service_bytes_write": float64(10000), "node_diskio_io_service_bytes_total": float64(10010), "node_diskio_io_service_bytes_async": float64(10000), "node_diskio_io_service_bytes_sync": float64(10000), "node_diskio_io_service_bytes_read": float64(10), } - expectedFieldsServiced := map[string]interface{}{ + expectedFieldsServiced := map[string]any{ "node_diskio_io_serviced_async": float64(10), "node_diskio_io_serviced_sync": float64(10), "node_diskio_io_serviced_read": float64(10), @@ -64,14 +64,14 @@ func TestDiskIOStats(t *testing.T) { cMetrics = extractor.GetValue(result2[0], nil, containerType) } - expectedFieldsService = map[string]interface{}{ + expectedFieldsService = map[string]any{ "instance_diskio_io_service_bytes_write": float64(10000), "instance_diskio_io_service_bytes_total": float64(10010), "instance_diskio_io_service_bytes_async": float64(10000), "instance_diskio_io_service_bytes_sync": float64(10000), "instance_diskio_io_service_bytes_read": float64(10), } - expectedFieldsServiced = map[string]interface{}{ + expectedFieldsServiced = map[string]any{ "instance_diskio_io_serviced_async": float64(10), "instance_diskio_io_serviced_sync": float64(10), "instance_diskio_io_serviced_read": float64(10), diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go index 559ee5481f81..398ad4805a59 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go @@ -37,7 +37,7 @@ type CAdvisorMetric struct { // source of the metric for debugging merge conflict cgroupPath string // key/value pairs that are typed and contain the metric (numerical) data - fields map[string]interface{} + fields map[string]any // key/value string pairs that are used to identify the metrics tags map[string]string @@ -46,7 +46,7 @@ type CAdvisorMetric struct { func newCadvisorMetric(mType string, logger *zap.Logger) *CAdvisorMetric { metric := &CAdvisorMetric{ - fields: make(map[string]interface{}), + fields: make(map[string]any), tags: make(map[string]string), logger: logger, } @@ -58,7 +58,7 @@ func (c *CAdvisorMetric) GetTags() map[string]string { return c.tags } -func (c *CAdvisorMetric) GetFields() map[string]interface{} { +func (c *CAdvisorMetric) GetFields() map[string]any { return c.fields } @@ -76,11 +76,11 @@ func (c *CAdvisorMetric) HasField(key string) bool { return c.fields[key] != nil } -func (c *CAdvisorMetric) AddField(key string, val interface{}) { +func (c *CAdvisorMetric) AddField(key string, val any) { c.fields[key] = val } -func (c *CAdvisorMetric) GetField(key string) interface{} { +func (c *CAdvisorMetric) GetField(key string) any { return c.fields[key] } @@ -115,7 +115,7 @@ func (c *CAdvisorMetric) Merge(src *CAdvisorMetric) { } func newFloat64RateCalculator() awsmetrics.MetricCalculator { - return awsmetrics.NewMetricCalculator(func(prev *awsmetrics.MetricValue, val interface{}, timestamp time.Time) (interface{}, bool) { + return awsmetrics.NewMetricCalculator(func(prev *awsmetrics.MetricValue, val any, timestamp time.Time) (any, bool) { if prev != nil { deltaNs := timestamp.Sub(prev.Timestamp) deltaValue := val.(float64) - prev.RawValue.(float64) @@ -127,8 +127,8 @@ func newFloat64RateCalculator() awsmetrics.MetricCalculator { }) } -func assignRateValueToField(rateCalculator *awsmetrics.MetricCalculator, fields map[string]interface{}, metricName string, - cinfoName string, curVal interface{}, curTime time.Time, multiplier float64) { +func assignRateValueToField(rateCalculator *awsmetrics.MetricCalculator, fields map[string]any, metricName string, + cinfoName string, curVal any, curTime time.Time, multiplier float64) { mKey := awsmetrics.NewKey(cinfoName+metricName, nil) if val, ok := rateCalculator.Calculate(mKey, curVal, curTime); ok { fields[metricName] = val.(float64) * multiplier diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor_helpers_test.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor_helpers_test.go index cdca51543209..b0f6985d102b 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor_helpers_test.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor_helpers_test.go @@ -80,7 +80,7 @@ func AssertContainsTaggedUint( func AssertContainsTaggedField( t *testing.T, cadvisorMetric *CAdvisorMetric, - expectedFields map[string]interface{}, + expectedFields map[string]any, expectedTags map[string]string, ) { diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor_test.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor_test.go index 8aaed84d16ea..79e1ce986820 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor_test.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor_test.go @@ -15,12 +15,12 @@ import ( func TestCAdvisorMetric_Merge(t *testing.T) { src := &CAdvisorMetric{ - fields: map[string]interface{}{"value1": 1, "value2": 2}, + fields: map[string]any{"value1": 1, "value2": 2}, tags: map[string]string{ci.Timestamp: "1586331559882"}, logger: zap.NewNop(), } dest := &CAdvisorMetric{ - fields: map[string]interface{}{"value1": 3, "value3": 3}, + fields: map[string]any{"value1": 3, "value3": 3}, tags: map[string]string{ci.Timestamp: "1586331559973"}, logger: zap.NewNop(), } @@ -83,7 +83,7 @@ func TestGetMetricKey(t *testing.T) { func TestMergeMetrics(t *testing.T) { cpuMetrics := &CAdvisorMetric{ - fields: map[string]interface{}{ + fields: map[string]any{ "node_cpu_usage_total": float64(10), "node_cpu_usage_user": float64(10), }, @@ -93,7 +93,7 @@ func TestMergeMetrics(t *testing.T) { } memMetrics := &CAdvisorMetric{ - fields: map[string]interface{}{ + fields: map[string]any{ "node_memory_cache": uint(25645056), }, tags: map[string]string{ @@ -107,7 +107,7 @@ func TestMergeMetrics(t *testing.T) { } expected := &CAdvisorMetric{ - fields: map[string]interface{}{ + fields: map[string]any{ "node_cpu_usage_total": float64(10), "node_cpu_usage_user": float64(10), "node_memory_cache": uint(25645056), diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/fs_extractor_test.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/fs_extractor_test.go index 91affcc7a9ac..41dd6a57ef62 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/fs_extractor_test.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/fs_extractor_test.go @@ -26,7 +26,7 @@ func TestFSStats(t *testing.T) { cMetrics = extractor.GetValue(result[0], nil, containerType) } - expectedFields := map[string]interface{}{ + expectedFields := map[string]any{ "container_filesystem_usage": uint64(25661440), "container_filesystem_capacity": uint64(21462233088), "container_filesystem_available": uint64(0), @@ -59,7 +59,7 @@ func TestFSStats(t *testing.T) { cMetrics = extractor.GetValue(result2[0], nil, containerType) } - expectedFields = map[string]interface{}{ + expectedFields = map[string]any{ "node_filesystem_available": uint64(67108864), "node_filesystem_capacity": uint64(67108864), "node_filesystem_inodes": uint64(2052980), @@ -74,7 +74,7 @@ func TestFSStats(t *testing.T) { } AssertContainsTaggedField(t, cMetrics[0], expectedFields, expectedTags) - expectedFields = map[string]interface{}{ + expectedFields = map[string]any{ "node_filesystem_available": uint64(6925574144), "node_filesystem_capacity": uint64(21462233088), "node_filesystem_inodes": uint64(10484672), @@ -89,7 +89,7 @@ func TestFSStats(t *testing.T) { } AssertContainsTaggedField(t, cMetrics[1], expectedFields, expectedTags) - expectedFields = map[string]interface{}{ + expectedFields = map[string]any{ "node_filesystem_available": uint64(10682417152), "node_filesystem_capacity": uint64(10726932480), "node_filesystem_inodes": uint64(5242880), diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/net_extractor.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/net_extractor.go index 35df5aea6b4c..3affa24971fd 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/net_extractor.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/net_extractor.go @@ -46,12 +46,12 @@ func (n *NetMetricExtractor) GetValue(info *cinfo.ContainerInfo, _ CPUMemInfoPro curIfceStats := getInterfacesStats(curStats) // used for aggregation - netIfceMetrics := make([]map[string]interface{}, len(curIfceStats)) + netIfceMetrics := make([]map[string]any, len(curIfceStats)) metrics := make([]*CAdvisorMetric, len(curIfceStats)) for i, cur := range curIfceStats { mType := getNetMetricType(containerType, n.logger) - netIfceMetric := make(map[string]interface{}) + netIfceMetric := make(map[string]any) infoName := info.Name + containerType + cur.Name // used to identify the network interface multiplier := float64(time.Second) diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/net_extractor_test.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/net_extractor_test.go index 6cf6ff341bc7..c5c067286690 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/net_extractor_test.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/net_extractor_test.go @@ -27,7 +27,7 @@ func TestNetStats(t *testing.T) { cMetrics = extractor.GetValue(result2[0], nil, containerType) } - expectedFields := []map[string]interface{}{ + expectedFields := []map[string]any{ { "node_interface_network_rx_bytes": float64(382.28706877648807), "node_interface_network_rx_dropped": float64(0), diff --git a/receiver/awscontainerinsightreceiver/internal/host/ebsvolume_test.go b/receiver/awscontainerinsightreceiver/internal/host/ebsvolume_test.go index 0500b9300d3f..a2495704f6d4 100644 --- a/receiver/awscontainerinsightreceiver/internal/host/ebsvolume_test.go +++ b/receiver/awscontainerinsightreceiver/internal/host/ebsvolume_test.go @@ -122,7 +122,7 @@ func (m *mockFileInfo) IsDir() bool { return false } -func (m *mockFileInfo) Sys() interface{} { +func (m *mockFileInfo) Sys() any { return nil } diff --git a/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver.go b/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver.go index cc7b2b309a20..48063a9931cf 100644 --- a/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver.go +++ b/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver.go @@ -41,7 +41,7 @@ type eventBroadcaster interface { StartRecordingToSink(sink record.EventSink) watch.Interface // StartLogging starts sending events received from this EventBroadcaster to the given logging // function. The return value can be ignored or used to stop recording, if desired. - StartLogging(logf func(format string, args ...interface{})) watch.Interface + StartLogging(logf func(format string, args ...any)) watch.Interface // NewRecorder returns an EventRecorder that can be used to send events to this EventBroadcaster // with the event source set to the given event source. NewRecorder(scheme *runtime.Scheme, source v1.EventSource) record.EventRecorder @@ -128,7 +128,7 @@ func (k *K8sAPIServer) GetMetrics() []pmetric.Metrics { k.logger.Info("collect data from K8s API Server...") timestampNs := strconv.FormatInt(time.Now().UnixNano(), 10) - fields := map[string]interface{}{ + fields := map[string]any{ "cluster_failed_node_count": k.nodeClient.ClusterFailedNodeCount(), "cluster_node_count": k.nodeClient.ClusterNodeCount(), } @@ -146,7 +146,7 @@ func (k *K8sAPIServer) GetMetrics() []pmetric.Metrics { result = append(result, md) for service, podNum := range k.epClient.ServiceToPodNum() { - fields := map[string]interface{}{ + fields := map[string]any{ "service_number_of_running_pods": podNum, } attributes := map[string]string{ @@ -168,7 +168,7 @@ func (k *K8sAPIServer) GetMetrics() []pmetric.Metrics { } for namespace, podNum := range k.podClient.NamespaceToRunningPodNum() { - fields := map[string]interface{}{ + fields := map[string]any{ "namespace_number_of_running_pods": podNum, } attributes := map[string]string{ diff --git a/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver_test.go b/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver_test.go index f5d36c93ddd8..01346de29937 100644 --- a/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver_test.go +++ b/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver_test.go @@ -96,7 +96,7 @@ func (m *mockEventBroadcaster) StartRecordingToSink(_ record.EventSink) watch.In return watch.NewFake() } -func (m *mockEventBroadcaster) StartLogging(_ func(format string, args ...interface{})) watch.Interface { +func (m *mockEventBroadcaster) StartLogging(_ func(format string, args ...any)) watch.Interface { return watch.NewFake() } diff --git a/receiver/awscontainerinsightreceiver/internal/stores/nodeinfo.go b/receiver/awscontainerinsightreceiver/internal/stores/nodeinfo.go index 5304ba33c232..71ed28e9240e 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/nodeinfo.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/nodeinfo.go @@ -37,13 +37,13 @@ func newNodeInfo(logger *zap.Logger) *nodeInfo { return nc } -func (n *nodeInfo) setCPUCapacity(cpuCapacity interface{}) { +func (n *nodeInfo) setCPUCapacity(cpuCapacity any) { n.cpuLock.Lock() defer n.cpuLock.Unlock() n.CPUCapacity = forceConvertToInt64(cpuCapacity, n.logger) } -func (n *nodeInfo) setMemCapacity(memCapacity interface{}) { +func (n *nodeInfo) setMemCapacity(memCapacity any) { n.memLock.Lock() defer n.memLock.Unlock() n.MemCapacity = forceConvertToInt64(memCapacity, n.logger) @@ -73,7 +73,7 @@ func (n *nodeInfo) getNodeStats() nodeStats { return n.nodeStats } -func forceConvertToInt64(v interface{}, logger *zap.Logger) uint64 { +func forceConvertToInt64(v any, logger *zap.Logger) uint64 { var value uint64 switch t := v.(type) { diff --git a/receiver/awscontainerinsightreceiver/internal/stores/podstore.go b/receiver/awscontainerinsightreceiver/internal/stores/podstore.go index 9c587f9564f1..3edd62433d5a 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/podstore.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/podstore.go @@ -58,7 +58,7 @@ type mapWithExpiry struct { *awsmetrics.MapWithExpiry } -func (m *mapWithExpiry) Get(key string) (interface{}, bool) { +func (m *mapWithExpiry) Get(key string) (any, bool) { m.MapWithExpiry.Lock() defer m.MapWithExpiry.Unlock() if val, ok := m.MapWithExpiry.Get(awsmetrics.NewKey(key, nil)); ok { @@ -68,7 +68,7 @@ func (m *mapWithExpiry) Get(key string) (interface{}, bool) { return nil, false } -func (m *mapWithExpiry) Set(key string, content interface{}) { +func (m *mapWithExpiry) Set(key string, content any) { m.MapWithExpiry.Lock() defer m.MapWithExpiry.Unlock() val := awsmetrics.MetricValue{ @@ -146,7 +146,7 @@ func (p *PodStore) Shutdown() error { return errs } -func (p *PodStore) getPrevMeasurement(metricType, metricKey string) (interface{}, bool) { +func (p *PodStore) getPrevMeasurement(metricType, metricKey string) (any, bool) { prevMeasurement, ok := p.prevMeasurements[metricType] if !ok { return nil, false @@ -161,7 +161,7 @@ func (p *PodStore) getPrevMeasurement(metricType, metricKey string) (interface{} return content, true } -func (p *PodStore) setPrevMeasurement(metricType, metricKey string, content interface{}) { +func (p *PodStore) setPrevMeasurement(metricType, metricKey string, content any) { prevMeasurement, ok := p.prevMeasurements[metricType] if !ok { prevMeasurement = newMapWithExpiry(measurementsExpiry) @@ -183,7 +183,7 @@ func (p *PodStore) RefreshTick(ctx context.Context) { } } -func (p *PodStore) Decorate(ctx context.Context, metric CIMetric, kubernetesBlob map[string]interface{}) bool { +func (p *PodStore) Decorate(ctx context.Context, metric CIMetric, kubernetesBlob map[string]any) bool { if metric.GetTag(ci.MetricType) == ci.TypeNode { p.decorateNode(metric) } else if metric.GetTag(ci.K8sPodNameKey) != "" { @@ -519,7 +519,7 @@ func getRequestForContainer(resource corev1.ResourceName, spec corev1.Container) return 0, false } -func addContainerID(pod *corev1.Pod, metric CIMetric, kubernetesBlob map[string]interface{}, logger *zap.Logger) { +func addContainerID(pod *corev1.Pod, metric CIMetric, kubernetesBlob map[string]any, logger *zap.Logger) { if containerName := metric.GetTag(ci.ContainerNamekey); containerName != "" { rawID := "" for _, container := range pod.Status.ContainerStatuses { @@ -544,7 +544,7 @@ func addContainerID(pod *corev1.Pod, metric CIMetric, kubernetesBlob map[string] } } -func addLabels(pod *corev1.Pod, kubernetesBlob map[string]interface{}) { +func addLabels(pod *corev1.Pod, kubernetesBlob map[string]any) { labels := make(map[string]string) for k, v := range pod.Labels { labels[k] = v @@ -558,8 +558,8 @@ func getJobNamePrefix(podName string) string { return re.Split(podName, 2)[0] } -func (p *PodStore) addPodOwnersAndPodName(metric CIMetric, pod *corev1.Pod, kubernetesBlob map[string]interface{}) { - var owners []interface{} +func (p *PodStore) addPodOwnersAndPodName(metric CIMetric, pod *corev1.Pod, kubernetesBlob map[string]any) { + var owners []any podName := "" for _, owner := range pod.OwnerReferences { if owner.Kind != "" && owner.Name != "" { diff --git a/receiver/awscontainerinsightreceiver/internal/stores/podstore_test.go b/receiver/awscontainerinsightreceiver/internal/stores/podstore_test.go index 447ceb91f12a..89c91bdcb3d9 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/podstore_test.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/podstore_test.go @@ -198,7 +198,7 @@ func getPodStore() *PodStore { } } -func generateMetric(fields map[string]interface{}, tags map[string]string) CIMetric { +func generateMetric(fields map[string]any, tags map[string]string) CIMetric { return &mockCIMetric{ tags: tags, fields: fields, @@ -213,7 +213,7 @@ func TestPodStore_decorateCpu(t *testing.T) { // test pod metrics tags := map[string]string{ci.MetricType: ci.TypePod} - fields := map[string]interface{}{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} + fields := map[string]any{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} metric := generateMetric(fields, tags) podStore.decorateCPU(metric, pod) @@ -226,7 +226,7 @@ func TestPodStore_decorateCpu(t *testing.T) { // test container metrics tags = map[string]string{ci.MetricType: ci.TypeContainer, ci.ContainerNamekey: "ubuntu"} - fields = map[string]interface{}{ci.MetricName(ci.TypeContainer, ci.CPUTotal): float64(1)} + fields = map[string]any{ci.MetricName(ci.TypeContainer, ci.CPUTotal): float64(1)} metric = generateMetric(fields, tags) podStore.decorateCPU(metric, pod) @@ -241,7 +241,7 @@ func TestPodStore_decorateMem(t *testing.T) { pod := getBaseTestPodInfo() tags := map[string]string{ci.MetricType: ci.TypePod} - fields := map[string]interface{}{ci.MetricName(ci.TypePod, ci.MemWorkingset): uint64(10 * 1024 * 1024)} + fields := map[string]any{ci.MetricName(ci.TypePod, ci.MemWorkingset): uint64(10 * 1024 * 1024)} metric := generateMetric(fields, tags) podStore.decorateMem(metric, pod) @@ -253,7 +253,7 @@ func TestPodStore_decorateMem(t *testing.T) { assert.Equal(t, uint64(10*1024*1024), metric.GetField("pod_memory_working_set").(uint64)) tags = map[string]string{ci.MetricType: ci.TypeContainer, ci.ContainerNamekey: "ubuntu"} - fields = map[string]interface{}{ci.MetricName(ci.TypeContainer, ci.MemWorkingset): float64(10 * 1024 * 1024)} + fields = map[string]any{ci.MetricName(ci.TypeContainer, ci.MemWorkingset): float64(10 * 1024 * 1024)} metric = generateMetric(fields, tags) podStore.decorateMem(metric, pod) @@ -267,7 +267,7 @@ func TestPodStore_addContainerCount(t *testing.T) { pod := getBaseTestPodInfo() tags := map[string]string{ci.MetricType: ci.TypePod} - fields := map[string]interface{}{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} + fields := map[string]any{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} metric := generateMetric(fields, tags) @@ -286,7 +286,7 @@ func TestPodStore_addContainerCount(t *testing.T) { func TestPodStore_addStatus(t *testing.T) { pod := getBaseTestPodInfo() tags := map[string]string{ci.MetricType: ci.TypePod, ci.K8sNamespace: "default", ci.K8sPodNameKey: "cpu-limit"} - fields := map[string]interface{}{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} + fields := map[string]any{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} podStore := getPodStore() defer require.NoError(t, podStore.Shutdown()) metric := generateMetric(fields, tags) @@ -343,22 +343,22 @@ func TestPodStore_addStatus(t *testing.T) { func TestPodStore_addContainerID(t *testing.T) { pod := getBaseTestPodInfo() tags := map[string]string{ci.ContainerNamekey: "ubuntu", ci.ContainerIDkey: "123"} - fields := map[string]interface{}{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} - kubernetesBlob := map[string]interface{}{} + fields := map[string]any{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} + kubernetesBlob := map[string]any{} metric := generateMetric(fields, tags) addContainerID(pod, metric, kubernetesBlob, zap.NewNop()) - expected := map[string]interface{}{} + expected := map[string]any{} expected["docker"] = map[string]string{"container_id": "637631e2634ea92c0c1aa5d24734cfe794f09c57933026592c12acafbaf6972c"} assert.Equal(t, expected, kubernetesBlob) assert.Equal(t, metric.GetTag(ci.ContainerNamekey), "ubuntu") tags = map[string]string{ci.ContainerNamekey: "notUbuntu", ci.ContainerIDkey: "123"} - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} metric = generateMetric(fields, tags) addContainerID(pod, metric, kubernetesBlob, zap.NewNop()) - expected = map[string]interface{}{} + expected = map[string]any{} expected["container_id"] = "123" assert.Equal(t, expected, kubernetesBlob) assert.Equal(t, metric.GetTag(ci.ContainerNamekey), "notUbuntu") @@ -366,9 +366,9 @@ func TestPodStore_addContainerID(t *testing.T) { func TestPodStore_addLabel(t *testing.T) { pod := getBaseTestPodInfo() - kubernetesBlob := map[string]interface{}{} + kubernetesBlob := map[string]any{} addLabels(pod, kubernetesBlob) - expected := map[string]interface{}{} + expected := map[string]any{} expected["labels"] = map[string]string{"app": "hello_test"} assert.Equal(t, expected, kubernetesBlob) } @@ -414,7 +414,7 @@ func TestPodStore_addPodOwnersAndPodNameFallback(t *testing.T) { podStore := &PodStore{k8sClient: &mockK8sClient1{}} pod := getBaseTestPodInfo() tags := map[string]string{ci.MetricType: ci.TypePod, ci.ContainerNamekey: "ubuntu"} - fields := map[string]interface{}{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} + fields := map[string]any{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} metric := generateMetric(fields, tags) // Test ReplicaSet @@ -422,10 +422,10 @@ func TestPodStore_addPodOwnersAndPodNameFallback(t *testing.T) { suffix := "-42kcz" pod.OwnerReferences[0].Kind = ci.ReplicaSet pod.OwnerReferences[0].Name = rsName + suffix - kubernetesBlob := map[string]interface{}{} + kubernetesBlob := map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner := map[string]interface{}{} - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.Deployment, "owner_name": rsName}} + expectedOwner := map[string]any{} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.Deployment, "owner_name": rsName}} expectedOwnerName := rsName assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) @@ -436,9 +436,9 @@ func TestPodStore_addPodOwnersAndPodNameFallback(t *testing.T) { suffix = "-0123456789" pod.OwnerReferences[0].Kind = ci.Job pod.OwnerReferences[0].Name = jobName + suffix - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.CronJob, "owner_name": jobName}} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.CronJob, "owner_name": jobName}} expectedOwnerName = jobName assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) @@ -449,15 +449,15 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { pod := getBaseTestPodInfo() tags := map[string]string{ci.MetricType: ci.TypePod, ci.ContainerNamekey: "ubuntu"} - fields := map[string]interface{}{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} + fields := map[string]any{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} // Test DaemonSet metric := generateMetric(fields, tags) - kubernetesBlob := map[string]interface{}{} + kubernetesBlob := map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner := map[string]interface{}{} - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.DaemonSet, "owner_name": "DaemonSetTest"}} + expectedOwner := map[string]any{} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.DaemonSet, "owner_name": "DaemonSetTest"}} expectedOwnerName := "DaemonSetTest" assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) @@ -467,9 +467,9 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { rsName := "ReplicaSetTest" pod.OwnerReferences[0].Kind = ci.ReplicaSet pod.OwnerReferences[0].Name = rsName - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.ReplicaSet, "owner_name": rsName}} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.ReplicaSet, "owner_name": rsName}} expectedOwnerName = rsName assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) @@ -479,9 +479,9 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { ssName := "StatefulSetTest" pod.OwnerReferences[0].Kind = ci.StatefulSet pod.OwnerReferences[0].Name = ssName - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.StatefulSet, "owner_name": ssName}} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.StatefulSet, "owner_name": ssName}} expectedOwnerName = "cpu-limit" assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) @@ -491,9 +491,9 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { rcName := "ReplicationControllerTest" pod.OwnerReferences[0].Kind = ci.ReplicationController pod.OwnerReferences[0].Name = rcName - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.ReplicationController, "owner_name": rcName}} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.ReplicationController, "owner_name": rcName}} expectedOwnerName = rcName assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, "", metric.GetTag(ci.FullPodNameKey)) @@ -508,18 +508,18 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { surfixHash := ".088123x12" pod.Name = jobName + surfixHash pod.OwnerReferences[0].Name = jobName + surfixHash - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.Job, "owner_name": jobName + surfixHash}} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.Job, "owner_name": jobName + surfixHash}} expectedOwnerName = jobName + surfixHash assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, pod.Name, metric.GetTag(ci.FullPodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) podStore.prefFullPodName = false - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.Job, "owner_name": jobName}} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.Job, "owner_name": jobName}} expectedOwnerName = jobName assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) @@ -529,9 +529,9 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { dpName := "DeploymentTest" pod.OwnerReferences[0].Kind = ci.ReplicaSet pod.OwnerReferences[0].Name = dpName + "-sftrz2785" - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.Deployment, "owner_name": dpName}} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.Deployment, "owner_name": dpName}} expectedOwnerName = dpName assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) @@ -541,9 +541,9 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { cjName := "CronJobTest" pod.OwnerReferences[0].Kind = ci.Job pod.OwnerReferences[0].Name = cjName + "-1556582405" - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) - expectedOwner["pod_owners"] = []interface{}{map[string]string{"owner_kind": ci.CronJob, "owner_name": cjName}} + expectedOwner["pod_owners"] = []any{map[string]string{"owner_kind": ci.CronJob, "owner_name": cjName}} expectedOwnerName = cjName assert.Equal(t, expectedOwnerName, metric.GetTag(ci.PodNameKey)) assert.Equal(t, expectedOwner, kubernetesBlob) @@ -554,7 +554,7 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { kpName := kubeProxy + "-xyz1" pod.OwnerReferences = nil pod.Name = kpName - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) assert.Equal(t, kpName, metric.GetTag(ci.PodNameKey)) assert.True(t, len(kubernetesBlob) == 0) @@ -563,7 +563,7 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { metric = generateMetric(fields, tags) pod.OwnerReferences = nil pod.Name = kpName - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} podStore.addPodOwnersAndPodName(metric, pod, kubernetesBlob) assert.Equal(t, kubeProxy, metric.GetTag(ci.PodNameKey)) assert.True(t, len(kubernetesBlob) == 0) @@ -600,7 +600,7 @@ func TestPodStore_decorateNode(t *testing.T) { podStore.refreshInternal(time.Now(), podList) tags := map[string]string{ci.MetricType: ci.TypeNode} - fields := map[string]interface{}{ + fields := map[string]any{ ci.MetricName(ci.TypeNode, ci.CPUTotal): float64(100), ci.MetricName(ci.TypeNode, ci.CPULimit): uint64(4000), ci.MetricName(ci.TypeNode, ci.MemWorkingset): float64(100 * 1024 * 1024), @@ -635,7 +635,7 @@ func TestPodStore_Decorate(t *testing.T) { podStore := getPodStore() defer require.NoError(t, podStore.Shutdown()) podStore.podClient = &mockPodClient{} - kubernetesBlob := map[string]interface{}{} + kubernetesBlob := map[string]any{} ok := podStore.Decorate(ctx, metric, kubernetesBlob) assert.True(t, ok) diff --git a/receiver/awscontainerinsightreceiver/internal/stores/servicestore.go b/receiver/awscontainerinsightreceiver/internal/stores/servicestore.go index 827dc73526d2..cd1d6e69617c 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/servicestore.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/servicestore.go @@ -52,7 +52,7 @@ func (s *ServiceStore) RefreshTick(ctx context.Context) { // Decorate decorates metrics and update kubernetesBlob // service info is not mandatory -func (s *ServiceStore) Decorate(_ context.Context, metric CIMetric, _ map[string]interface{}) bool { +func (s *ServiceStore) Decorate(_ context.Context, metric CIMetric, _ map[string]any) bool { if metric.HasTag(ci.K8sPodNameKey) { podKey := createPodKeyFromMetric(metric) if podKey == "" { diff --git a/receiver/awscontainerinsightreceiver/internal/stores/servicestore_test.go b/receiver/awscontainerinsightreceiver/internal/stores/servicestore_test.go index 9cb295f61cf0..a7e1604fe496 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/servicestore_test.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/servicestore_test.go @@ -41,7 +41,7 @@ func TestServiceStore(t *testing.T) { ci.K8sNamespace: "default", }, } - kubernetesBlob := map[string]interface{}{} + kubernetesBlob := map[string]any{} ok := s.Decorate(ctx, metric, kubernetesBlob) assert.True(t, ok) assert.Equal(t, "test-service", metric.GetTag(ci.TypeService)) @@ -52,7 +52,7 @@ func TestServiceStore(t *testing.T) { ci.K8sPodNameKey: "test-pod", }, } - kubernetesBlob = map[string]interface{}{} + kubernetesBlob = map[string]any{} ok = s.Decorate(ctx, metric, kubernetesBlob) assert.False(t, ok) assert.Equal(t, "", metric.GetTag(ci.TypeService)) diff --git a/receiver/awscontainerinsightreceiver/internal/stores/store.go b/receiver/awscontainerinsightreceiver/internal/stores/store.go index 2e4754660665..da9be89624ae 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/store.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/store.go @@ -20,8 +20,8 @@ var _ cadvisor.Decorator = &K8sDecorator{} // CIMetric represents the raw metric interface for container insights type CIMetric interface { HasField(key string) bool - AddField(key string, val interface{}) - GetField(key string) interface{} + AddField(key string, val any) + GetField(key string) any HasTag(key string) bool AddTag(key, val string) GetTag(key string) string @@ -29,7 +29,7 @@ type CIMetric interface { } type K8sStore interface { - Decorate(ctx context.Context, metric CIMetric, kubernetesBlob map[string]interface{}) bool + Decorate(ctx context.Context, metric CIMetric, kubernetesBlob map[string]any) bool RefreshTick(ctx context.Context) } @@ -89,7 +89,7 @@ func NewK8sDecorator(ctx context.Context, tagService bool, prefFullPodName bool, } func (k *K8sDecorator) Decorate(metric *extractors.CAdvisorMetric) *extractors.CAdvisorMetric { - kubernetesBlob := map[string]interface{}{} + kubernetesBlob := map[string]any{} for _, store := range k.stores { ok := store.Decorate(k.ctx, metric, kubernetesBlob) if !ok { diff --git a/receiver/awscontainerinsightreceiver/internal/stores/utils.go b/receiver/awscontainerinsightreceiver/internal/stores/utils.go index 0092686f2a3b..a0f187a388df 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/utils.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/utils.go @@ -132,7 +132,7 @@ func TagMetricSource(metric CIMetric) { } } -func AddKubernetesInfo(metric CIMetric, kubernetesBlob map[string]interface{}) { +func AddKubernetesInfo(metric CIMetric, kubernetesBlob map[string]any) { needMoveToKubernetes := map[string]string{ci.ContainerNamekey: "container_name", ci.K8sPodNameKey: "pod_name", ci.PodIDKey: "pod_id"} diff --git a/receiver/awscontainerinsightreceiver/internal/stores/utils_test.go b/receiver/awscontainerinsightreceiver/internal/stores/utils_test.go index d5b808165ef5..903c59fba462 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/utils_test.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/utils_test.go @@ -15,18 +15,18 @@ import ( type mockCIMetric struct { tags map[string]string - fields map[string]interface{} + fields map[string]any } func (m *mockCIMetric) HasField(key string) bool { return m.fields[key] != nil } -func (m *mockCIMetric) AddField(key string, val interface{}) { +func (m *mockCIMetric) AddField(key string, val any) { m.fields[key] = val } -func (m *mockCIMetric) GetField(key string) interface{} { +func (m *mockCIMetric) GetField(key string) any { return m.fields[key] } @@ -58,7 +58,7 @@ func TestUtils_parseCronJobFromJob(t *testing.T) { } func TestUtils_addKubernetesInfo(t *testing.T) { - fields := map[string]interface{}{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} + fields := map[string]any{ci.MetricName(ci.TypePod, ci.CPUTotal): float64(1)} tags := map[string]string{ ci.ContainerNamekey: "testContainer", ci.K8sPodNameKey: "testPod", @@ -74,7 +74,7 @@ func TestUtils_addKubernetesInfo(t *testing.T) { fields: fields, } - kubernetesBlob := map[string]interface{}{} + kubernetesBlob := map[string]any{} AddKubernetesInfo(metric, kubernetesBlob) assert.Equal(t, "", metric.GetTag(ci.ContainerNamekey)) assert.Equal(t, "", metric.GetTag(ci.K8sPodNameKey)) @@ -83,7 +83,7 @@ func TestUtils_addKubernetesInfo(t *testing.T) { assert.Equal(t, "testService", metric.GetTag(ci.TypeService)) assert.Equal(t, "testNode", metric.GetTag(ci.NodeNameKey)) - expectedKubeBlob := map[string]interface{}{"container_name": "testContainer", "host": "testNode", "namespace_name": "testNamespace", "pod_id": "123", "pod_name": "testPod", "service_name": "testService"} + expectedKubeBlob := map[string]any{"container_name": "testContainer", "host": "testNode", "namespace_name": "testNamespace", "pod_id": "123", "pod_name": "testPod", "service_name": "testService"} assert.Equal(t, expectedKubeBlob, kubernetesBlob) } diff --git a/receiver/awsfirehosereceiver/receiver_test.go b/receiver/awsfirehosereceiver/receiver_test.go index 397af7609708..2174938bcfac 100644 --- a/receiver/awsfirehosereceiver/receiver_test.go +++ b/receiver/awsfirehosereceiver/receiver_test.go @@ -102,7 +102,7 @@ func TestFirehoseRequest(t *testing.T) { testCases := map[string]struct { headers map[string]string commonAttributes map[string]string - body interface{} + body any consumer firehoseConsumer wantStatusCode int wantErr error diff --git a/receiver/awsxrayreceiver/internal/translator/annotations.go b/receiver/awsxrayreceiver/internal/translator/annotations.go index 9949ccc69921..95ef2f29d442 100644 --- a/receiver/awsxrayreceiver/internal/translator/annotations.go +++ b/receiver/awsxrayreceiver/internal/translator/annotations.go @@ -9,7 +9,7 @@ import ( awsxray "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/xray" ) -func addAnnotations(annos map[string]interface{}, attrs pcommon.Map) { +func addAnnotations(annos map[string]any, attrs pcommon.Map) { if len(annos) > 0 { keys := attrs.PutEmptySlice(awsxray.AWSXraySegmentAnnotationsAttribute) keys.EnsureCapacity(len(annos)) diff --git a/receiver/awsxrayreceiver/internal/translator/annotations_test.go b/receiver/awsxrayreceiver/internal/translator/annotations_test.go index c2c5de6f21e9..5e29f7c312d7 100644 --- a/receiver/awsxrayreceiver/internal/translator/annotations_test.go +++ b/receiver/awsxrayreceiver/internal/translator/annotations_test.go @@ -15,7 +15,7 @@ import ( ) func TestAddAnnotations(t *testing.T) { - input := make(map[string]interface{}) + input := make(map[string]any) input["int"] = 0 input["int32"] = int32(1) input["int64"] = int64(2) @@ -42,7 +42,7 @@ func TestAddAnnotations(t *testing.T) { expectedKeys.AppendEmpty().SetStr("float32") expectedKeys.AppendEmpty().SetStr("float64") - assert.True(t, cmp.Equal(expectedAttrMap.AsRaw(), attrMap.AsRaw(), cmpopts.SortSlices(func(x, y interface{}) bool { + assert.True(t, cmp.Equal(expectedAttrMap.AsRaw(), attrMap.AsRaw(), cmpopts.SortSlices(func(x, y any) bool { return x.(string) < y.(string) })), "attribute maps differ") } diff --git a/receiver/awsxrayreceiver/internal/translator/metadata.go b/receiver/awsxrayreceiver/internal/translator/metadata.go index 50933f69e9d3..7136fc67b225 100644 --- a/receiver/awsxrayreceiver/internal/translator/metadata.go +++ b/receiver/awsxrayreceiver/internal/translator/metadata.go @@ -11,7 +11,7 @@ import ( awsxray "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/xray" ) -func addMetadata(meta map[string]map[string]interface{}, attrs pcommon.Map) error { +func addMetadata(meta map[string]map[string]any, attrs pcommon.Map) error { for k, v := range meta { val, err := json.Marshal(v) if err != nil { diff --git a/receiver/awsxrayreceiver/internal/translator/translator_test.go b/receiver/awsxrayreceiver/internal/translator/translator_test.go index deef223a9ed8..748084cc0f0b 100644 --- a/receiver/awsxrayreceiver/internal/translator/translator_test.go +++ b/receiver/awsxrayreceiver/internal/translator/translator_test.go @@ -49,7 +49,7 @@ type eventProps struct { func TestTranslation(t *testing.T) { var defaultServerSpanAttrs = func(seg *awsxray.Segment) pcommon.Map { m := pcommon.NewMap() - assert.NoError(t, m.FromRaw(map[string]interface{}{ + assert.NoError(t, m.FromRaw(map[string]any{ conventions.AttributeHTTPMethod: *seg.HTTP.Request.Method, conventions.AttributeHTTPClientIP: *seg.HTTP.Request.ClientIP, conventions.AttributeHTTPUserAgent: *seg.HTTP.Request.UserAgent, @@ -64,7 +64,7 @@ func TestTranslation(t *testing.T) { testCase string expectedUnmarshallFailure bool samplePath string - expectedResourceAttrs func(seg *awsxray.Segment) map[string]interface{} + expectedResourceAttrs func(seg *awsxray.Segment) map[string]any expectedRecord xray.TelemetryRecord propsPerSpan func(testCase string, t *testing.T, seg *awsxray.Segment) []perSpanProperties verification func(testCase string, @@ -76,8 +76,8 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateInstrumentedServerSegment", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "serverSample.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { - return map[string]interface{}{ + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { + return map[string]any{ conventions.AttributeServiceName: *seg.Name, conventions.AttributeCloudProvider: conventions.AttributeCloudProviderAWS, conventions.AttributeTelemetrySDKVersion: *seg.AWS.XRay.SDKVersion, @@ -122,8 +122,8 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateInstrumentedClientSegment", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "ddbSample.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { - return map[string]interface{}{ + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { + return map[string]any{ conventions.AttributeServiceName: *seg.Name, conventions.AttributeCloudProvider: conventions.AttributeCloudProviderAWS, conventions.AttributeTelemetrySDKVersion: *seg.AWS.XRay.SDKVersion, @@ -187,7 +187,7 @@ func TestTranslation(t *testing.T) { subseg7318 := seg.Subsegments[0].Subsegments[0] childSpan7318Attrs := pcommon.NewMap() - assert.NoError(t, childSpan7318Attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, childSpan7318Attrs.FromRaw(map[string]any{ awsxray.AWSServiceAttribute: *subseg7318.Name, conventions.AttributeHTTPResponseContentLength: int64(subseg7318.HTTP.Response.ContentLength.(float64)), conventions.AttributeHTTPStatusCode: *subseg7318.HTTP.Response.Status, @@ -383,7 +383,7 @@ func TestTranslation(t *testing.T) { subseg7163 := seg.Subsegments[0].Subsegments[1] childSpan7163Attrs := pcommon.NewMap() - assert.NoError(t, childSpan7163Attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, childSpan7163Attrs.FromRaw(map[string]any{ awsxray.AWSServiceAttribute: *subseg7163.Name, conventions.AttributeHTTPStatusCode: *subseg7163.HTTP.Response.Status, conventions.AttributeHTTPResponseContentLength: int64(subseg7163.HTTP.Response.ContentLength.(float64)), @@ -529,8 +529,8 @@ func TestTranslation(t *testing.T) { { testCase: "[aws] TranslateMissingAWSFieldSegment", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "awsMissingAwsField.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { - return map[string]interface{}{ + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { + return map[string]any{ conventions.AttributeServiceName: *seg.Name, conventions.AttributeCloudProvider: "unknown", } @@ -569,8 +569,8 @@ func TestTranslation(t *testing.T) { { testCase: "[aws] TranslateEC2AWSFieldsSegment", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "awsValidAwsFields.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { - return map[string]interface{}{ + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { + return map[string]any{ conventions.AttributeServiceName: *seg.Name, conventions.AttributeCloudProvider: conventions.AttributeCloudProviderAWS, conventions.AttributeCloudAccountID: *seg.AWS.AccountID, @@ -623,8 +623,8 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateCauseIsExceptionId", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "minCauseIsExceptionId.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { - return map[string]interface{}{ + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { + return map[string]any{ conventions.AttributeServiceName: *seg.Name, conventions.AttributeCloudProvider: "unknown", } @@ -663,7 +663,7 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateInvalidNamespace", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "invalidNamespace.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { return nil }, expectedRecord: xray.TelemetryRecord{ @@ -685,8 +685,8 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateIndepSubsegment", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "indepSubsegment.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { - return map[string]interface{}{ + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { + return map[string]any{ conventions.AttributeServiceName: *seg.Name, conventions.AttributeCloudProvider: "unknown", } @@ -697,7 +697,7 @@ func TestTranslation(t *testing.T) { }, propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { attrs := pcommon.NewMap() - assert.NoError(t, attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, attrs.FromRaw(map[string]any{ conventions.AttributeHTTPMethod: *seg.HTTP.Request.Method, conventions.AttributeHTTPStatusCode: *seg.HTTP.Response.Status, conventions.AttributeHTTPURL: *seg.HTTP.Request.URL, @@ -733,8 +733,8 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateIndepSubsegmentForContentLengthString", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "indepSubsegmentWithContentLengthString.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { - return map[string]interface{}{ + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { + return map[string]any{ conventions.AttributeServiceName: *seg.Name, conventions.AttributeCloudProvider: "unknown", } @@ -745,7 +745,7 @@ func TestTranslation(t *testing.T) { }, propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { attrs := pcommon.NewMap() - assert.NoError(t, attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, attrs.FromRaw(map[string]any{ conventions.AttributeHTTPMethod: *seg.HTTP.Request.Method, conventions.AttributeHTTPStatusCode: *seg.HTTP.Response.Status, conventions.AttributeHTTPURL: *seg.HTTP.Request.URL, @@ -782,8 +782,8 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateSql", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "indepSubsegmentWithSql.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { - return map[string]interface{}{ + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { + return map[string]any{ conventions.AttributeServiceName: *seg.Name, conventions.AttributeCloudProvider: "unknown", } @@ -794,7 +794,7 @@ func TestTranslation(t *testing.T) { }, propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { attrs := pcommon.NewMap() - assert.NoError(t, attrs.FromRaw(map[string]interface{}{ + assert.NoError(t, attrs.FromRaw(map[string]any{ conventions.AttributeDBConnectionString: "jdbc:postgresql://aawijb5u25wdoy.cpamxznpdoq8.us-west-2." + "rds.amazonaws.com:5432", conventions.AttributeDBName: "ebdb", @@ -831,7 +831,7 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateInvalidSqlUrl", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "indepSubsegmentWithInvalidSqlUrl.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { return nil }, expectedRecord: xray.TelemetryRecord{ @@ -856,7 +856,7 @@ func TestTranslation(t *testing.T) { testCase: "TranslateJsonUnmarshallFailed", expectedUnmarshallFailure: true, samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "minCauseIsInvalid.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { return nil }, expectedRecord: xray.TelemetryRecord{ @@ -880,7 +880,7 @@ func TestTranslation(t *testing.T) { { testCase: "TranslateRootSegValidationFailed", samplePath: filepath.Join("../../../../internal/aws/xray", "testdata", "segmentValidationFailed.txt"), - expectedResourceAttrs: func(seg *awsxray.Segment) map[string]interface{} { + expectedResourceAttrs: func(seg *awsxray.Segment) map[string]any { return nil }, expectedRecord: xray.TelemetryRecord{ @@ -978,7 +978,7 @@ func initExceptionEvents(expectedSeg *awsxray.Segment) []eventProps { } func initResourceSpans(t *testing.T, expectedSeg *awsxray.Segment, - resourceAttrs map[string]interface{}, + resourceAttrs map[string]any, propsPerSpan []perSpanProperties, ) ptrace.ResourceSpans { if expectedSeg == nil { diff --git a/receiver/azureblobreceiver/blobeventhandler.go b/receiver/azureblobreceiver/blobeventhandler.go index b5543435fd92..44fa7c44080b 100644 --- a/receiver/azureblobreceiver/blobeventhandler.go +++ b/receiver/azureblobreceiver/blobeventhandler.go @@ -71,7 +71,7 @@ func (p *azureBlobEventHandler) newMessageHandler(ctx context.Context, event *ev Subject string EventType string ID string - Data map[string]interface{} + Data map[string]any DataVersion string MetadataVersion string EsventTime string diff --git a/receiver/azureeventhubreceiver/eventhubhandler_test.go b/receiver/azureeventhubreceiver/eventhubhandler_test.go index 79af423d0ae1..8fdb6778f9c6 100644 --- a/receiver/azureeventhubreceiver/eventhubhandler_test.go +++ b/receiver/azureeventhubreceiver/eventhubhandler_test.go @@ -134,7 +134,7 @@ func TestEventhubHandler_newMessageHandler(t *testing.T) { err = ehHandler.newMessageHandler(context.Background(), &eventhub.Event{ Data: []byte("hello"), PartitionKey: nil, - Properties: map[string]interface{}{"foo": "bar"}, + Properties: map[string]any{"foo": "bar"}, ID: "11234", SystemProperties: &eventhub.SystemProperties{ SequenceNumber: nil, diff --git a/receiver/bigipreceiver/client.go b/receiver/bigipreceiver/client.go index eb43f99e553d..6e54d8102b81 100644 --- a/receiver/bigipreceiver/client.go +++ b/receiver/bigipreceiver/client.go @@ -188,7 +188,7 @@ func (c *bigipClient) GetNodes(ctx context.Context) (nodes *models.Nodes, err er } // post makes a POST request for the passed in path and stores result in the respObj -func (c *bigipClient) post(ctx context.Context, path string, respObj interface{}) error { +func (c *bigipClient) post(ctx context.Context, path string, respObj any) error { // Construct endpoint and create request url := c.hostEndpoint + path postBody, _ := json.Marshal(map[string]string{ @@ -206,7 +206,7 @@ func (c *bigipClient) post(ctx context.Context, path string, respObj interface{} } // get makes a GET request (with token in header) for the passed in path and stores result in the respObj -func (c *bigipClient) get(ctx context.Context, path string, respObj interface{}) error { +func (c *bigipClient) get(ctx context.Context, path string, respObj any) error { // Construct endpoint and create request url := c.hostEndpoint + path req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) @@ -219,7 +219,7 @@ func (c *bigipClient) get(ctx context.Context, path string, respObj interface{}) } // makeHTTPRequest makes the request and decodes the body into the respObj on a 200 Status -func (c *bigipClient) makeHTTPRequest(req *http.Request, respObj interface{}) (err error) { +func (c *bigipClient) makeHTTPRequest(req *http.Request, respObj any) (err error) { // Make request resp, err := c.client.Do(req) if err != nil { diff --git a/receiver/carbonreceiver/protocol/config_test.go b/receiver/carbonreceiver/protocol/config_test.go index 3340721a79e1..9cc9e12f3913 100644 --- a/receiver/carbonreceiver/protocol/config_test.go +++ b/receiver/carbonreceiver/protocol/config_test.go @@ -13,14 +13,14 @@ import ( func TestLoadParserConfig(t *testing.T) { tests := []struct { name string - cfgMap map[string]interface{} + cfgMap map[string]any cfg Config want Config wantErr bool }{ { name: "unknow_type", - cfgMap: map[string]interface{}{"type": "unknow"}, + cfgMap: map[string]any{"type": "unknow"}, cfg: Config{Type: "unknown"}, want: Config{Type: "unknown"}, wantErr: true, @@ -29,10 +29,10 @@ func TestLoadParserConfig(t *testing.T) { // Keep this test before the default_regex to ensure that the // default configuration is not being corrupted. name: "custom_delimiter", - cfgMap: map[string]interface{}{ + cfgMap: map[string]any{ "type": "regex", - "config": map[string]interface{}{ - "rules": []interface{}{map[string]interface{}{"regexp": "(?.*test)"}}, + "config": map[string]any{ + "rules": []any{map[string]any{"regexp": "(?.*test)"}}, }, }, cfg: Config{Type: "regex"}, @@ -46,7 +46,7 @@ func TestLoadParserConfig(t *testing.T) { }, { name: "default_regex", - cfgMap: map[string]interface{}{"type": "regex"}, + cfgMap: map[string]any{"type": "regex"}, cfg: Config{Type: "regex"}, want: Config{ Type: "regex", diff --git a/receiver/carbonreceiver/reporter.go b/receiver/carbonreceiver/reporter.go index 475bb30001fd..2f61e2ab64c3 100644 --- a/receiver/carbonreceiver/reporter.go +++ b/receiver/carbonreceiver/reporter.go @@ -93,7 +93,7 @@ func (r *reporter) OnMetricsProcessed( r.obsrecv.EndMetricsOp(ctx, "carbon", numReceivedMetricPoints, err) } -func (r *reporter) OnDebugf(template string, args ...interface{}) { +func (r *reporter) OnDebugf(template string, args ...any) { if r.logger.Check(zap.DebugLevel, "debug") != nil { r.sugaredLogger.Debugf(template, args...) } diff --git a/receiver/carbonreceiver/transport/mock_reporter.go b/receiver/carbonreceiver/transport/mock_reporter.go index d9369f11fe83..4c59251e87fd 100644 --- a/receiver/carbonreceiver/transport/mock_reporter.go +++ b/receiver/carbonreceiver/transport/mock_reporter.go @@ -34,7 +34,7 @@ func (m *MockReporter) OnMetricsProcessed(_ context.Context, _ int, _ error) { m.wgMetricsProcessed.Done() } -func (m *MockReporter) OnDebugf(_ string, _ ...interface{}) { +func (m *MockReporter) OnDebugf(_ string, _ ...any) { } // WaitAllOnMetricsProcessedCalls blocks until the number of expected calls diff --git a/receiver/carbonreceiver/transport/server.go b/receiver/carbonreceiver/transport/server.go index 91c888fad1cf..126834967793 100644 --- a/receiver/carbonreceiver/transport/server.go +++ b/receiver/carbonreceiver/transport/server.go @@ -60,5 +60,5 @@ type Reporter interface { // OnDebugf allows less structured reporting for debugging scenarios. OnDebugf( template string, - args ...interface{}) + args ...any) } diff --git a/receiver/cloudflarereceiver/logs.go b/receiver/cloudflarereceiver/logs.go index 9b58e69cc3e5..ad4256f57b9e 100644 --- a/receiver/cloudflarereceiver/logs.go +++ b/receiver/cloudflarereceiver/logs.go @@ -190,14 +190,14 @@ func (l *logsReceiver) handleRequest(rw http.ResponseWriter, req *http.Request) rw.WriteHeader(http.StatusOK) } -func parsePayload(payload []byte) ([]map[string]interface{}, error) { +func parsePayload(payload []byte) ([]map[string]any, error) { lines := bytes.Split(payload, []byte("\n")) - logs := make([]map[string]interface{}, 0, len(lines)) + logs := make([]map[string]any, 0, len(lines)) for _, line := range lines { if len(line) == 0 { continue } - var log map[string]interface{} + var log map[string]any err := json.Unmarshal(line, &log) if err != nil { return logs, err @@ -207,11 +207,11 @@ func parsePayload(payload []byte) ([]map[string]interface{}, error) { return logs, nil } -func (l *logsReceiver) processLogs(now pcommon.Timestamp, logs []map[string]interface{}) plog.Logs { +func (l *logsReceiver) processLogs(now pcommon.Timestamp, logs []map[string]any) plog.Logs { pLogs := plog.NewLogs() // Group logs by ZoneName field if it was configured so it can be used as a resource attribute - groupedLogs := make(map[string][]map[string]interface{}) + groupedLogs := make(map[string][]map[string]any) for _, log := range logs { zone := "" if v, ok := log["ZoneName"]; ok { diff --git a/receiver/cloudflarereceiver/logs_test.go b/receiver/cloudflarereceiver/logs_test.go index 8a26b5f92195..6a0ac738da63 100644 --- a/receiver/cloudflarereceiver/logs_test.go +++ b/receiver/cloudflarereceiver/logs_test.go @@ -53,7 +53,7 @@ func TestPayloadToLogRecord(t *testing.T) { for idx, line := range strings.Split(payload, "\n") { lr := sl.LogRecords().AppendEmpty() - require.NoError(t, lr.Attributes().FromRaw(map[string]interface{}{ + require.NoError(t, lr.Attributes().FromRaw(map[string]any{ "http_request.client_ip": fmt.Sprintf("89.163.253.%d", 200+idx), })) @@ -63,7 +63,7 @@ func TestPayloadToLogRecord(t *testing.T) { lr.SetSeverityNumber(plog.SeverityNumberInfo) lr.SetSeverityText(plog.SeverityNumberInfo.String()) - var log map[string]interface{} + var log map[string]any err := json.Unmarshal([]byte(line), &log) require.NoError(t, err) @@ -81,7 +81,7 @@ func TestPayloadToLogRecord(t *testing.T) { logs := plog.NewLogs() rl := logs.ResourceLogs().AppendEmpty() - require.NoError(t, rl.Resource().Attributes().FromRaw(map[string]interface{}{ + require.NoError(t, rl.Resource().Attributes().FromRaw(map[string]any{ "cloudflare.zone": "otlpdev.net", })) @@ -89,7 +89,7 @@ func TestPayloadToLogRecord(t *testing.T) { sl.Scope().SetName(receiverScopeName) lr := sl.LogRecords().AppendEmpty() - require.NoError(t, lr.Attributes().FromRaw(map[string]interface{}{ + require.NoError(t, lr.Attributes().FromRaw(map[string]any{ "http_request.client_ip": "47.35.104.49", })) @@ -99,7 +99,7 @@ func TestPayloadToLogRecord(t *testing.T) { lr.SetSeverityNumber(plog.SeverityNumberWarn) lr.SetSeverityText(plog.SeverityNumberWarn.String()) - var log map[string]interface{} + var log map[string]any err := json.Unmarshal([]byte(payload), &log) require.NoError(t, err) @@ -143,7 +143,7 @@ func TestPayloadToLogRecord(t *testing.T) { } func payloadToExpectedBody(t *testing.T, payload string, lr plog.LogRecord) { - var body map[string]interface{} + var body map[string]any err := json.Unmarshal([]byte(payload), &body) require.NoError(t, err) require.NoError(t, lr.Body().SetEmptyMap().FromRaw(body)) diff --git a/receiver/collectdreceiver/collectd.go b/receiver/collectdreceiver/collectd.go index a57220bd333f..5b733a0e0fb9 100644 --- a/receiver/collectdreceiver/collectd.go +++ b/receiver/collectdreceiver/collectd.go @@ -17,19 +17,19 @@ import ( ) type collectDRecord struct { - Dsnames []*string `json:"dsnames"` - Dstypes []*string `json:"dstypes"` - Host *string `json:"host"` - Interval *float64 `json:"interval"` - Plugin *string `json:"plugin"` - PluginInstance *string `json:"plugin_instance"` - Time *float64 `json:"time"` - TypeS *string `json:"type"` - TypeInstance *string `json:"type_instance"` - Values []*json.Number `json:"values"` - Message *string `json:"message"` - Meta map[string]interface{} `json:"meta"` - Severity *string `json:"severity"` + Dsnames []*string `json:"dsnames"` + Dstypes []*string `json:"dstypes"` + Host *string `json:"host"` + Interval *float64 `json:"interval"` + Plugin *string `json:"plugin"` + PluginInstance *string `json:"plugin_instance"` + Time *float64 `json:"time"` + TypeS *string `json:"type"` + TypeInstance *string `json:"type_instance"` + Values []*json.Number `json:"values"` + Message *string `json:"message"` + Meta map[string]any `json:"meta"` + Severity *string `json:"severity"` } type createMetricInfo struct { diff --git a/receiver/couchdbreceiver/client.go b/receiver/couchdbreceiver/client.go index 1523e3a22721..a23a5d967a71 100644 --- a/receiver/couchdbreceiver/client.go +++ b/receiver/couchdbreceiver/client.go @@ -17,7 +17,7 @@ import ( // client defines the basic HTTP client interface. type client interface { Get(path string) ([]byte, error) - GetStats(nodeName string) (map[string]interface{}, error) + GetStats(nodeName string) (map[string]any, error) } var _ client = (*couchDBClient)(nil) @@ -76,14 +76,14 @@ func (c *couchDBClient) Get(path string) ([]byte, error) { } // GetStats gets couchdb stats at a specific node name endpoint. -func (c *couchDBClient) GetStats(nodeName string) (map[string]interface{}, error) { +func (c *couchDBClient) GetStats(nodeName string) (map[string]any, error) { path := fmt.Sprintf("/_node/%s/_stats/couchdb", nodeName) body, err := c.Get(path) if err != nil { return nil, err } - var stats map[string]interface{} + var stats map[string]any err = json.Unmarshal(body, &stats) if err != nil { return nil, err diff --git a/receiver/couchdbreceiver/client_test.go b/receiver/couchdbreceiver/client_test.go index 54ec0ddb9195..136db521dd8c 100644 --- a/receiver/couchdbreceiver/client_test.go +++ b/receiver/couchdbreceiver/client_test.go @@ -169,7 +169,7 @@ func TestGetNodeStats(t *testing.T) { require.Nil(t, actualStats) }) t.Run("no error", func(t *testing.T) { - expectedStats := map[string]interface{}{"key": []interface{}{"value"}} + expectedStats := map[string]any{"key": []any{"value"}} couchdbClient := defaultClient(t, ts.URL) actualStats, err := couchdbClient.GetStats("_local") diff --git a/receiver/couchdbreceiver/metrics.go b/receiver/couchdbreceiver/metrics.go index b837d4c6103a..ff759f542e28 100644 --- a/receiver/couchdbreceiver/metrics.go +++ b/receiver/couchdbreceiver/metrics.go @@ -12,7 +12,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/couchdbreceiver/internal/metadata" ) -func (c *couchdbScraper) recordCouchdbAverageRequestTimeDataPoint(now pcommon.Timestamp, stats map[string]interface{}, errs *scrapererror.ScrapeErrors) { +func (c *couchdbScraper) recordCouchdbAverageRequestTimeDataPoint(now pcommon.Timestamp, stats map[string]any, errs *scrapererror.ScrapeErrors) { averageRequestTimeMetricKey := []string{"request_time", "value", "arithmetic_mean"} averageRequestTimeValue, err := getValueFromBody(averageRequestTimeMetricKey, stats) if err != nil { @@ -28,7 +28,7 @@ func (c *couchdbScraper) recordCouchdbAverageRequestTimeDataPoint(now pcommon.Ti c.mb.RecordCouchdbAverageRequestTimeDataPoint(now, parsedValue) } -func (c *couchdbScraper) recordCouchdbHttpdBulkRequestsDataPoint(now pcommon.Timestamp, stats map[string]interface{}, errs *scrapererror.ScrapeErrors) { +func (c *couchdbScraper) recordCouchdbHttpdBulkRequestsDataPoint(now pcommon.Timestamp, stats map[string]any, errs *scrapererror.ScrapeErrors) { httpdBulkRequestsMetricKey := []string{"httpd", "bulk_requests", "value"} httpdBulkRequestsMetricValue, err := getValueFromBody(httpdBulkRequestsMetricKey, stats) if err != nil { @@ -44,7 +44,7 @@ func (c *couchdbScraper) recordCouchdbHttpdBulkRequestsDataPoint(now pcommon.Tim c.mb.RecordCouchdbHttpdBulkRequestsDataPoint(now, parsedValue) } -func (c *couchdbScraper) recordCouchdbHttpdRequestsDataPoint(now pcommon.Timestamp, stats map[string]interface{}, errs *scrapererror.ScrapeErrors) { +func (c *couchdbScraper) recordCouchdbHttpdRequestsDataPoint(now pcommon.Timestamp, stats map[string]any, errs *scrapererror.ScrapeErrors) { for methodVal, method := range metadata.MapAttributeHTTPMethod { httpdRequestMethodKey := []string{"httpd_request_methods", methodVal, "value"} httpdRequestMethodValue, err := getValueFromBody(httpdRequestMethodKey, stats) @@ -62,7 +62,7 @@ func (c *couchdbScraper) recordCouchdbHttpdRequestsDataPoint(now pcommon.Timesta } } -func (c *couchdbScraper) recordCouchdbHttpdResponsesDataPoint(now pcommon.Timestamp, stats map[string]interface{}, errs *scrapererror.ScrapeErrors) { +func (c *couchdbScraper) recordCouchdbHttpdResponsesDataPoint(now pcommon.Timestamp, stats map[string]any, errs *scrapererror.ScrapeErrors) { codes := []string{"200", "201", "202", "204", "206", "301", "302", "304", "400", "401", "403", "404", "405", "406", "409", "412", "413", "414", "415", "416", "417", "500", "501", "503"} for _, code := range codes { httpdResponsetCodeKey := []string{"httpd_status_codes", code, "value"} @@ -81,7 +81,7 @@ func (c *couchdbScraper) recordCouchdbHttpdResponsesDataPoint(now pcommon.Timest } } -func (c *couchdbScraper) recordCouchdbHttpdViewsDataPoint(now pcommon.Timestamp, stats map[string]interface{}, errs *scrapererror.ScrapeErrors) { +func (c *couchdbScraper) recordCouchdbHttpdViewsDataPoint(now pcommon.Timestamp, stats map[string]any, errs *scrapererror.ScrapeErrors) { for viewVal, view := range metadata.MapAttributeView { viewKey := []string{"httpd", viewVal, "value"} viewValue, err := getValueFromBody(viewKey, stats) @@ -99,7 +99,7 @@ func (c *couchdbScraper) recordCouchdbHttpdViewsDataPoint(now pcommon.Timestamp, } } -func (c *couchdbScraper) recordCouchdbDatabaseOpenDataPoint(now pcommon.Timestamp, stats map[string]interface{}, errs *scrapererror.ScrapeErrors) { +func (c *couchdbScraper) recordCouchdbDatabaseOpenDataPoint(now pcommon.Timestamp, stats map[string]any, errs *scrapererror.ScrapeErrors) { openDatabaseKey := []string{"open_databases", "value"} openDatabaseMetricValue, err := getValueFromBody(openDatabaseKey, stats) if err != nil { @@ -115,7 +115,7 @@ func (c *couchdbScraper) recordCouchdbDatabaseOpenDataPoint(now pcommon.Timestam c.mb.RecordCouchdbDatabaseOpenDataPoint(now, parsedValue) } -func (c *couchdbScraper) recordCouchdbFileDescriptorOpenDataPoint(now pcommon.Timestamp, stats map[string]interface{}, errs *scrapererror.ScrapeErrors) { +func (c *couchdbScraper) recordCouchdbFileDescriptorOpenDataPoint(now pcommon.Timestamp, stats map[string]any, errs *scrapererror.ScrapeErrors) { fileDescriptorKey := []string{"open_os_files", "value"} fileDescriptorMetricValue, err := getValueFromBody(fileDescriptorKey, stats) if err != nil { @@ -131,7 +131,7 @@ func (c *couchdbScraper) recordCouchdbFileDescriptorOpenDataPoint(now pcommon.Ti c.mb.RecordCouchdbFileDescriptorOpenDataPoint(now, parsedValue) } -func (c *couchdbScraper) recordCouchdbDatabaseOperationsDataPoint(now pcommon.Timestamp, stats map[string]interface{}, errs *scrapererror.ScrapeErrors) { +func (c *couchdbScraper) recordCouchdbDatabaseOperationsDataPoint(now pcommon.Timestamp, stats map[string]any, errs *scrapererror.ScrapeErrors) { operations := []metadata.AttributeOperation{metadata.AttributeOperationReads, metadata.AttributeOperationWrites} keyPaths := [][]string{{"database_reads", "value"}, {"database_writes", "value"}} for i := 0; i < len(operations); i++ { @@ -151,10 +151,10 @@ func (c *couchdbScraper) recordCouchdbDatabaseOperationsDataPoint(now pcommon.Ti } } -func getValueFromBody(keys []string, body map[string]interface{}) (interface{}, error) { - var currentValue interface{} = body +func getValueFromBody(keys []string, body map[string]any) (any, error) { + var currentValue any = body for _, key := range keys { - currentBody, ok := currentValue.(map[string]interface{}) + currentBody, ok := currentValue.(map[string]any) if !ok { return nil, fmt.Errorf("could not find key in body") } @@ -167,7 +167,7 @@ func getValueFromBody(keys []string, body map[string]interface{}) (interface{}, return currentValue, nil } -func (c *couchdbScraper) parseInt(value interface{}) (int64, error) { +func (c *couchdbScraper) parseInt(value any) (int64, error) { switch i := value.(type) { case int64: return i, nil @@ -177,7 +177,7 @@ func (c *couchdbScraper) parseInt(value interface{}) (int64, error) { return 0, fmt.Errorf("could not parse value as int") } -func (c *couchdbScraper) parseFloat(value interface{}) (float64, error) { +func (c *couchdbScraper) parseFloat(value any) (float64, error) { if f, ok := value.(float64); ok { return f, nil } diff --git a/receiver/couchdbreceiver/scraper_test.go b/receiver/couchdbreceiver/scraper_test.go index fed821b21a77..398c06e2f6c2 100644 --- a/receiver/couchdbreceiver/scraper_test.go +++ b/receiver/couchdbreceiver/scraper_test.go @@ -72,7 +72,7 @@ func TestScrape(t *testing.T) { t.Run("scrape returns nothing", func(t *testing.T) { mockClient := new(mockClient) - mockClient.On("GetStats", "_local").Return(map[string]interface{}{}, nil) + mockClient.On("GetStats", "_local").Return(map[string]any{}, nil) scraper := newCouchdbScraper(receivertest.NewNopCreateSettings(), cfg) scraper.client = mockClient @@ -175,8 +175,8 @@ func TestMetricSettings(t *testing.T) { require.Equal(t, metrics.MetricCount(), 1) } -func getStats(filename string) (map[string]interface{}, error) { - var stats map[string]interface{} +func getStats(filename string) (map[string]any, error) { + var stats map[string]any if filename == "" { return nil, errors.New("bad response") @@ -226,14 +226,14 @@ func (_m *mockClient) Get(path string) ([]byte, error) { } // GetStats provides a mock function with given fields: nodeName -func (_m *mockClient) GetStats(nodeName string) (map[string]interface{}, error) { +func (_m *mockClient) GetStats(nodeName string) (map[string]any, error) { ret := _m.Called(nodeName) - var r0 map[string]interface{} - if rf, ok := ret.Get(0).(func(string) map[string]interface{}); ok { + var r0 map[string]any + if rf, ok := ret.Get(0).(func(string) map[string]any); ok { r0 = rf(nodeName) } else if ret.Get(0) != nil { - r0 = ret.Get(0).(map[string]interface{}) + r0 = ret.Get(0).(map[string]any) } var r1 error diff --git a/receiver/datadogreceiver/translator.go b/receiver/datadogreceiver/translator.go index 8112c7aef007..cd9bc38c2bba 100644 --- a/receiver/datadogreceiver/translator.go +++ b/receiver/datadogreceiver/translator.go @@ -177,7 +177,7 @@ func translateDataDogKeyToOtel(k string) string { } var bufferPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(bytes.Buffer) }, } diff --git a/receiver/datadogreceiver/translator_test.go b/receiver/datadogreceiver/translator_test.go index 9f550f483015..472e05fc07ad 100644 --- a/receiver/datadogreceiver/translator_test.go +++ b/receiver/datadogreceiver/translator_test.go @@ -15,7 +15,7 @@ import ( vmsgp "github.com/vmihailenco/msgpack/v4" ) -var data = [2]interface{}{ +var data = [2]any{ 0: []string{ 0: "baggage", 1: "item", @@ -30,7 +30,7 @@ var data = [2]interface{}{ 10: "sql", 11: "service.name", }, - 1: [][][12]interface{}{ + 1: [][][12]any{ { { 6, @@ -42,13 +42,13 @@ var data = [2]interface{}{ int64(123), int64(456), 1, - map[interface{}]interface{}{ + map[any]any{ 8: 9, 0: 1, 2: 3, 11: 6, }, - map[interface{}]float64{ + map[any]float64{ 5: 1.2, }, 10, diff --git a/receiver/fluentforwardreceiver/conversion.go b/receiver/fluentforwardreceiver/conversion.go index 5bf55dcaaf7c..7ede36943b49 100644 --- a/receiver/fluentforwardreceiver/conversion.go +++ b/receiver/fluentforwardreceiver/conversion.go @@ -29,7 +29,7 @@ type Event interface { Compressed() string } -type OptionsMap map[string]interface{} +type OptionsMap map[string]any // Chunk returns the `chunk` option or blank string if it was not set. func (om OptionsMap) Chunk() string { @@ -73,7 +73,7 @@ func (em EventMode) String() string { // parseInterfaceToMap takes map of interface objects and returns // AttributeValueMap -func parseInterfaceToMap(msi map[string]interface{}, dest pcommon.Value) { +func parseInterfaceToMap(msi map[string]any, dest pcommon.Value) { am := dest.SetEmptyMap() am.EnsureCapacity(len(msi)) for k, value := range msi { @@ -83,7 +83,7 @@ func parseInterfaceToMap(msi map[string]interface{}, dest pcommon.Value) { // parseInterfaceToArray takes array of interface objects and returns // AttributeValueArray -func parseInterfaceToArray(ai []interface{}, dest pcommon.Value) { +func parseInterfaceToArray(ai []any, dest pcommon.Value) { av := dest.SetEmptySlice() av.EnsureCapacity(len(ai)) for _, value := range ai { @@ -92,7 +92,7 @@ func parseInterfaceToArray(ai []interface{}, dest pcommon.Value) { } // parseToAttributeValue converts interface object to AttributeValue -func parseToAttributeValue(val interface{}, dest pcommon.Value) { +func parseToAttributeValue(val any, dest pcommon.Value) { // See https://github.com/tinylib/msgp/wiki/Type-Mapping-Rules switch r := val.(type) { case bool: @@ -106,9 +106,9 @@ func parseToAttributeValue(val interface{}, dest pcommon.Value) { // Sometimes strings come in as bytes array case []byte: dest.SetStr(string(r)) - case map[string]interface{}: + case map[string]any: parseInterfaceToMap(r, dest) - case []interface{}: + case []any: parseInterfaceToArray(r, dest) case float32: dest.SetDouble(float64(r)) @@ -120,7 +120,7 @@ func parseToAttributeValue(val interface{}, dest pcommon.Value) { } } -func timeFromTimestamp(ts interface{}) (time.Time, error) { +func timeFromTimestamp(ts any) (time.Time, error) { switch v := ts.(type) { case uint64: return time.Unix(int64(v), 0), nil diff --git a/receiver/fluentforwardreceiver/conversion_test.go b/receiver/fluentforwardreceiver/conversion_test.go index 78783b269cea..220de31de6b0 100644 --- a/receiver/fluentforwardreceiver/conversion_test.go +++ b/receiver/fluentforwardreceiver/conversion_test.go @@ -27,7 +27,7 @@ func TestMessageEventConversion(t *testing.T) { Log{ Timestamp: 1593031012000000000, Body: pcommon.NewValueStr("..."), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "container_id": "b00a67eb645849d6ab38ff8beb4aad035cc7e917bf123c3e9057c7e89fc73d2d", "container_name": "/unruffled_cannon", "fluent.tag": "b00a67eb6458", @@ -94,7 +94,7 @@ func TestAttributeTypeConversion(t *testing.T) { Log{ Timestamp: 5000000000000, Body: pcommon.NewValueEmpty(), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "a": 5.0, "b": 6.0, "c": true, @@ -109,7 +109,7 @@ func TestAttributeTypeConversion(t *testing.T) { "k": -1, "l": "(0+0i)", "m": "\001e\002", - "n": []interface{}{"first", "second"}, + "n": []any{"first", "second"}, "o": "cde", "p": nil, }, @@ -240,7 +240,7 @@ func TestBodyConversion(t *testing.T) { Log{ Timestamp: 5000000000000, Body: body, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "my-tag", }, }, diff --git a/receiver/fluentforwardreceiver/receiver_test.go b/receiver/fluentforwardreceiver/receiver_test.go index 29a12b9b1f77..269e5a13ca74 100644 --- a/receiver/fluentforwardreceiver/receiver_test.go +++ b/receiver/fluentforwardreceiver/receiver_test.go @@ -111,7 +111,7 @@ func TestMessageEvent(t *testing.T) { require.NoError(t, plogtest.CompareLogs(logConstructor(Log{ Timestamp: 1593031012000000000, Body: pcommon.NewValueStr("..."), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "container_id": "b00a67eb645849d6ab38ff8beb4aad035cc7e917bf123c3e9057c7e89fc73d2d", "container_name": "/unruffled_cannon", "fluent.tag": "b00a67eb6458", @@ -142,7 +142,7 @@ func TestForwardEvent(t *testing.T) { Log{ Timestamp: 1593032377776693638, Body: pcommon.NewValueEmpty(), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Mem.free": 848908, "Mem.total": 7155496, "Mem.used": 6306588, @@ -155,7 +155,7 @@ func TestForwardEvent(t *testing.T) { Log{ Timestamp: 1593032378756829346, Body: pcommon.NewValueEmpty(), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "Mem.free": 848908, "Mem.total": 7155496, "Mem.used": 6306588, @@ -192,7 +192,7 @@ func TestEventAcknowledgment(t *testing.T) { require.Equal(t, len(b), n) require.NoError(t, conn.SetReadDeadline(time.Now().Add(5*time.Second))) - resp := map[string]interface{}{} + resp := map[string]any{} err = msgp.NewReader(conn).ReadMapStrIntf(resp) require.NoError(t, err) @@ -221,7 +221,7 @@ func TestForwardPackedEvent(t *testing.T) { Log{ Timestamp: 1593032517024597622, Body: pcommon.NewValueStr("starting fluentd worker pid=17 ppid=7 worker=0"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", "pid": 17, "ppid": 7, @@ -231,21 +231,21 @@ func TestForwardPackedEvent(t *testing.T) { Log{ Timestamp: 1593032517028573686, Body: pcommon.NewValueStr("delayed_commit_timeout is overwritten by ack_response_timeout"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", }, }, Log{ Timestamp: 1593032517028815948, Body: pcommon.NewValueStr("following tail of /var/log/kern.log"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", }, }, Log{ Timestamp: 1593032517031174229, Body: pcommon.NewValueStr("fluentd worker is now running worker=0"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", "worker": 0, }, @@ -253,7 +253,7 @@ func TestForwardPackedEvent(t *testing.T) { Log{ Timestamp: 1593032522187382822, Body: pcommon.NewValueStr("fluentd worker is now stopping worker=0"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", "worker": 0, }, @@ -283,7 +283,7 @@ func TestForwardPackedCompressedEvent(t *testing.T) { Log{ Timestamp: 1593032426012197420, Body: pcommon.NewValueStr("starting fluentd worker pid=17 ppid=7 worker=0"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", "pid": 17, "ppid": 7, @@ -293,21 +293,21 @@ func TestForwardPackedCompressedEvent(t *testing.T) { Log{ Timestamp: 1593032426013724933, Body: pcommon.NewValueStr("delayed_commit_timeout is overwritten by ack_response_timeout"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", }, }, Log{ Timestamp: 1593032426020510455, Body: pcommon.NewValueStr("following tail of /var/log/kern.log"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", }, }, Log{ Timestamp: 1593032426024346580, Body: pcommon.NewValueStr("fluentd worker is now running worker=0"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", "worker": 0, }, @@ -315,7 +315,7 @@ func TestForwardPackedCompressedEvent(t *testing.T) { Log{ Timestamp: 1593032434346935532, Body: pcommon.NewValueStr("fluentd worker is now stopping worker=0"), - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "fluent.tag": "fluent.info", "worker": 0, }, diff --git a/receiver/fluentforwardreceiver/util_test.go b/receiver/fluentforwardreceiver/util_test.go index 663fb3af109b..745365bd07d3 100644 --- a/receiver/fluentforwardreceiver/util_test.go +++ b/receiver/fluentforwardreceiver/util_test.go @@ -13,7 +13,7 @@ import ( type Log struct { Timestamp int64 Body pcommon.Value - Attributes map[string]interface{} + Attributes map[string]any } // logConstructor is a convenience function for constructing logs for tests in a way that is diff --git a/receiver/gitproviderreceiver/internal/scraper.go b/receiver/gitproviderreceiver/internal/scraper.go index ab1d4fead9ab..4ae3a471a0ed 100644 --- a/receiver/gitproviderreceiver/internal/scraper.go +++ b/receiver/gitproviderreceiver/internal/scraper.go @@ -17,8 +17,7 @@ type ScraperFactory interface { CreateMetricsScraper(ctx context.Context, params receiver.CreateSettings, cfg Config) (scraperhelper.Scraper, error) } -type Config interface { -} +type Config any type ScraperConfig struct { } diff --git a/receiver/googlecloudspannerreceiver/internal/filter/itemcardinality_test.go b/receiver/googlecloudspannerreceiver/internal/filter/itemcardinality_test.go index 98c8b8023716..cc6dd3f5246f 100644 --- a/receiver/googlecloudspannerreceiver/internal/filter/itemcardinality_test.go +++ b/receiver/googlecloudspannerreceiver/internal/filter/itemcardinality_test.go @@ -145,7 +145,7 @@ func TestItemCardinalityFilter_Filter(t *testing.T) { // Doing this to avoid of relying on timeouts and sleeps(avoid potential flaky tests) syncChannel := make(chan bool) - filterCasted.cache.SetExpirationCallback(func(key string, value interface{}) { + filterCasted.cache.SetExpirationCallback(func(key string, value any) { if filterCasted.cache.Count() > 0 { // Waiting until cache is really empty - all items are expired return @@ -203,7 +203,7 @@ func TestItemCardinalityFilter_FilterItems(t *testing.T) { // Doing this to avoid of relying on timeouts and sleeps(avoid potential flaky tests) syncChannel := make(chan bool) - filterCasted.cache.SetExpirationCallback(func(key string, value interface{}) { + filterCasted.cache.SetExpirationCallback(func(key string, value any) { if filterCasted.cache.Count() > 0 { // Waiting until cache is really empty - all items are expired return diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/labelvalue.go b/receiver/googlecloudspannerreceiver/internal/metadata/labelvalue.go index 224945191985..b293ee766dc8 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/labelvalue.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/labelvalue.go @@ -11,17 +11,17 @@ import ( "go.opentelemetry.io/collector/pdata/pcommon" ) -type newLabelValueFunction func(m LabelValueMetadata, value interface{}) LabelValue +type newLabelValueFunction func(m LabelValueMetadata, value any) LabelValue type LabelValueMetadata interface { ValueMetadata ValueType() ValueType - NewLabelValue(value interface{}) LabelValue + NewLabelValue(value any) LabelValue } type LabelValue interface { Metadata() LabelValueMetadata - Value() interface{} + Value() any SetValueTo(attributes pcommon.Map) } @@ -33,11 +33,11 @@ type queryLabelValueMetadata struct { valueHolderFunc valueHolderFunction } -func (m queryLabelValueMetadata) ValueHolder() interface{} { +func (m queryLabelValueMetadata) ValueHolder() any { return m.valueHolderFunc() } -func (m queryLabelValueMetadata) NewLabelValue(value interface{}) LabelValue { +func (m queryLabelValueMetadata) NewLabelValue(value any) LabelValue { return m.newLabelValueFunc(m, value) } @@ -87,7 +87,7 @@ func (v stringLabelValue) Metadata() LabelValueMetadata { return v.metadata } -func (v stringLabelValue) Value() interface{} { +func (v stringLabelValue) Value() any { return v.value } @@ -95,7 +95,7 @@ func (v stringLabelValue) SetValueTo(attributes pcommon.Map) { attributes.PutStr(v.metadata.Name(), v.value) } -func newStringLabelValue(metadata LabelValueMetadata, valueHolder interface{}) LabelValue { +func newStringLabelValue(metadata LabelValueMetadata, valueHolder any) LabelValue { return stringLabelValue{ metadata: metadata, value: *valueHolder.(*string), @@ -106,7 +106,7 @@ func (v int64LabelValue) Metadata() LabelValueMetadata { return v.metadata } -func (v int64LabelValue) Value() interface{} { +func (v int64LabelValue) Value() any { return v.value } @@ -114,7 +114,7 @@ func (v int64LabelValue) SetValueTo(attributes pcommon.Map) { attributes.PutInt(v.metadata.Name(), v.value) } -func newInt64LabelValue(metadata LabelValueMetadata, valueHolder interface{}) LabelValue { +func newInt64LabelValue(metadata LabelValueMetadata, valueHolder any) LabelValue { return int64LabelValue{ metadata: metadata, value: *valueHolder.(*int64), @@ -125,7 +125,7 @@ func (v boolLabelValue) Metadata() LabelValueMetadata { return v.metadata } -func (v boolLabelValue) Value() interface{} { +func (v boolLabelValue) Value() any { return v.value } @@ -133,7 +133,7 @@ func (v boolLabelValue) SetValueTo(attributes pcommon.Map) { attributes.PutBool(v.metadata.Name(), v.value) } -func newBoolLabelValue(metadata LabelValueMetadata, valueHolder interface{}) LabelValue { +func newBoolLabelValue(metadata LabelValueMetadata, valueHolder any) LabelValue { return boolLabelValue{ metadata: metadata, value: *valueHolder.(*bool), @@ -144,7 +144,7 @@ func (v stringSliceLabelValue) Metadata() LabelValueMetadata { return v.metadata } -func (v stringSliceLabelValue) Value() interface{} { +func (v stringSliceLabelValue) Value() any { return v.value } @@ -152,7 +152,7 @@ func (v stringSliceLabelValue) SetValueTo(attributes pcommon.Map) { attributes.PutStr(v.metadata.Name(), v.value) } -func newStringSliceLabelValue(metadata LabelValueMetadata, valueHolder interface{}) LabelValue { +func newStringSliceLabelValue(metadata LabelValueMetadata, valueHolder any) LabelValue { value := *valueHolder.(*[]string) sort.Strings(value) @@ -169,7 +169,7 @@ func (v byteSliceLabelValue) Metadata() LabelValueMetadata { return v.metadata } -func (v byteSliceLabelValue) Value() interface{} { +func (v byteSliceLabelValue) Value() any { return v.value } @@ -189,7 +189,7 @@ func (v *stringLabelValue) ModifyValue(s string) { v.value = s } -func newByteSliceLabelValue(metadata LabelValueMetadata, valueHolder interface{}) LabelValue { +func newByteSliceLabelValue(metadata LabelValueMetadata, valueHolder any) LabelValue { return byteSliceLabelValue{ metadata: metadata, value: string(*valueHolder.(*[]byte)), @@ -200,7 +200,7 @@ func (v lockRequestSliceLabelValue) Metadata() LabelValueMetadata { return v.metadata } -func (v lockRequestSliceLabelValue) Value() interface{} { +func (v lockRequestSliceLabelValue) Value() any { return v.value } @@ -214,7 +214,7 @@ type lockRequest struct { TransactionTag string `spanner:"transaction_tag"` } -func newLockRequestSliceLabelValue(metadata LabelValueMetadata, valueHolder interface{}) LabelValue { +func newLockRequestSliceLabelValue(metadata LabelValueMetadata, valueHolder any) LabelValue { value := *valueHolder.(*[]*lockRequest) // During the specifics of this label we need to take into account only distinct values uniqueValueItems := make(map[string]struct{}) @@ -251,37 +251,37 @@ func NewLabelValueMetadata(name string, columnName string, valueType ValueType) switch valueType { case StringValueType: newLabelValueFunc = newStringLabelValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder string return &valueHolder } case IntValueType: newLabelValueFunc = newInt64LabelValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder int64 return &valueHolder } case BoolValueType: newLabelValueFunc = newBoolLabelValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder bool return &valueHolder } case StringSliceValueType: newLabelValueFunc = newStringSliceLabelValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder []string return &valueHolder } case ByteSliceValueType: newLabelValueFunc = newByteSliceLabelValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder []byte return &valueHolder } case LockRequestSliceValueType: newLabelValueFunc = newLockRequestSliceLabelValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder []*lockRequest return &valueHolder } diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint.go index acd6d8072b88..26f76aec92df 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint.go @@ -47,7 +47,7 @@ type dataForHashing struct { // Fields must be exported for hashing purposes type label struct { Name string - Value interface{} + Value any } func (mdp *MetricsDataPoint) CopyTo(dataPoint pmetric.NumberDataPoint) { diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint_test.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint_test.go index 11baf37ebb14..e8cc49cd09c6 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint_test.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint_test.go @@ -260,7 +260,7 @@ func assertLabelValue(t *testing.T, attributesMap pcommon.Map, labelValue LabelV } } -func assertStringLabelValue(t *testing.T, attributesMap pcommon.Map, labelName string, expectedValue interface{}) { +func assertStringLabelValue(t *testing.T, attributesMap pcommon.Map, labelName string, expectedValue any) { value, exists := attributesMap.Get(labelName) assert.True(t, exists) @@ -276,7 +276,7 @@ func assertMetricValue(t *testing.T, metricValue MetricValue, dataPoint pmetric. } } -func assertLabel(t *testing.T, lbl label, expectedName string, expectedValue interface{}) { +func assertLabel(t *testing.T, lbl label, expectedName string, expectedValue any) { assert.Equal(t, expectedName, lbl.Name) assert.Equal(t, expectedValue, lbl.Value) } diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricsmetadata_test.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricsmetadata_test.go index 9b9b18b4866e..7f9d4a22caa2 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricsmetadata_test.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricsmetadata_test.go @@ -28,12 +28,12 @@ func TestMetricsMetadata_Timestamp(t *testing.T) { testCases := map[string]struct { metadata *MetricsMetadata rowColumnNames []string - rowColumnValues []interface{} + rowColumnValues []any errorRequired bool }{ - "Happy path": {&MetricsMetadata{TimestampColumnName: timestampColumnName}, []string{timestampColumnName}, []interface{}{time.Now().UTC()}, false}, - "No timestamp column name": {&MetricsMetadata{}, []string{}, []interface{}{}, false}, - "With error": {&MetricsMetadata{TimestampColumnName: "nonExistingColumn"}, []string{timestampColumnName}, []interface{}{time.Now().UTC()}, true}, + "Happy path": {&MetricsMetadata{TimestampColumnName: timestampColumnName}, []string{timestampColumnName}, []any{time.Now().UTC()}, false}, + "No timestamp column name": {&MetricsMetadata{}, []string{}, []any{}, false}, + "With error": {&MetricsMetadata{TimestampColumnName: "nonExistingColumn"}, []string{timestampColumnName}, []any{time.Now().UTC()}, true}, } for name, testCase := range testCases { @@ -62,8 +62,8 @@ func TestToLabelValue(t *testing.T) { testCases := map[string]struct { valueType ValueType expectedType LabelValue - expectedValue interface{} - expectedTransformedValue interface{} + expectedValue any + expectedTransformedValue any }{ "String label value metadata": {StringValueType, stringLabelValue{}, stringValue, nil}, "Int64 label value metadata": {IntValueType, int64LabelValue{}, int64Value, nil}, @@ -75,7 +75,7 @@ func TestToLabelValue(t *testing.T) { for name, testCase := range testCases { t.Run(name, func(t *testing.T) { - row, _ := spanner.NewRow(rowColumnNames, []interface{}{testCase.expectedValue}) + row, _ := spanner.NewRow(rowColumnNames, []any{testCase.expectedValue}) metadata, _ := NewLabelValueMetadata(labelName, labelColumnName, testCase.valueType) labelValue, _ := toLabelValue(metadata, row) @@ -117,7 +117,7 @@ func TestMetricsMetadata_ToLabelValues_AllPossibleMetadata(t *testing.T) { byteSliceLabelValueMetadata.ColumnName(), lockRequestSliceLabelValueMetadata.ColumnName(), }, - []interface{}{ + []any{ stringValue, boolValue, int64Value, @@ -148,7 +148,7 @@ func TestMetricsMetadata_ToLabelValues_Error(t *testing.T) { stringLabelValueMetadata, _ := NewLabelValueMetadata("nonExisting", "nonExistingColumn", StringValueType) queryLabelValuesMetadata := []LabelValueMetadata{stringLabelValueMetadata} metadata := MetricsMetadata{QueryLabelValuesMetadata: queryLabelValuesMetadata} - row, _ := spanner.NewRow([]string{}, []interface{}{}) + row, _ := spanner.NewRow([]string{}, []any{}) labelValues, err := metadata.toLabelValues(row) @@ -162,7 +162,7 @@ func TestToMetricValue(t *testing.T) { testCases := map[string]struct { valueType ValueType expectedType MetricValue - expectedValue interface{} + expectedValue any }{ "Int64 metric value metadata": {IntValueType, int64MetricValue{}, int64Value}, "Float64 metric value metadata": {FloatValueType, float64MetricValue{}, float64Value}, @@ -170,7 +170,7 @@ func TestToMetricValue(t *testing.T) { for name, testCase := range testCases { t.Run(name, func(t *testing.T) { - row, _ := spanner.NewRow(rowColumnNames, []interface{}{testCase.expectedValue}) + row, _ := spanner.NewRow(rowColumnNames, []any{testCase.expectedValue}) metadata, _ := NewMetricValueMetadata(metricName, metricColumnName, metricDataType, metricUnit, testCase.valueType) metricValue, _ := toMetricValue(metadata, row) @@ -198,7 +198,7 @@ func TestMetricsMetadata_ToMetricValues_AllPossibleMetadata(t *testing.T) { metadata := MetricsMetadata{QueryMetricValuesMetadata: queryMetricValuesMetadata} row, _ := spanner.NewRow( []string{int64MetricValueMetadata.ColumnName(), float64MetricValueMetadata.ColumnName()}, - []interface{}{int64Value, float64Value}) + []any{int64Value, float64Value}) metricValues, _ := metadata.toMetricValues(row) @@ -217,7 +217,7 @@ func TestMetricsMetadata_ToMetricValues_Error(t *testing.T) { "nonExistingMetricColumnName", metricDataType, metricUnit, IntValueType) queryMetricValuesMetadata := []MetricValueMetadata{int64MetricValueMetadata} metadata := MetricsMetadata{QueryMetricValuesMetadata: queryMetricValuesMetadata} - row, _ := spanner.NewRow([]string{}, []interface{}{}) + row, _ := spanner.NewRow([]string{}, []any{}) metricValues, err := metadata.toMetricValues(row) @@ -241,13 +241,13 @@ func TestMetricsMetadata_RowToMetricsDataPoints(t *testing.T) { } testCases := map[string]struct { rowColumnNames []string - rowColumnValues []interface{} + rowColumnValues []any expectError bool }{ - "Happy path": {[]string{labelColumnName, metricColumnName, timestampColumnName}, []interface{}{stringValue, int64Value, timestamp}, false}, - "Error on timestamp": {[]string{labelColumnName, metricColumnName}, []interface{}{stringValue, int64Value}, true}, - "Error on label value": {[]string{metricColumnName, timestampColumnName}, []interface{}{int64Value, timestamp}, true}, - "Error on metric value": {[]string{labelColumnName, timestampColumnName}, []interface{}{stringValue, timestamp}, true}, + "Happy path": {[]string{labelColumnName, metricColumnName, timestampColumnName}, []any{stringValue, int64Value, timestamp}, false}, + "Error on timestamp": {[]string{labelColumnName, metricColumnName}, []any{stringValue, int64Value}, true}, + "Error on label value": {[]string{metricColumnName, timestampColumnName}, []any{int64Value, timestamp}, true}, + "Error on metric value": {[]string{labelColumnName, timestampColumnName}, []any{stringValue, timestamp}, true}, } for name, testCase := range testCases { diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricvalue.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricvalue.go index 34f24948b5d1..d5f78b5c1710 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricvalue.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricvalue.go @@ -10,19 +10,19 @@ import ( "go.opentelemetry.io/collector/pdata/pmetric" ) -type newMetricValueFunction func(m MetricValueMetadata, value interface{}) MetricValue +type newMetricValueFunction func(m MetricValueMetadata, value any) MetricValue type MetricValueMetadata interface { ValueMetadata ValueType() ValueType DataType() MetricType Unit() string - NewMetricValue(value interface{}) MetricValue + NewMetricValue(value any) MetricValue } type MetricValue interface { Metadata() MetricValueMetadata - Value() interface{} + Value() any SetValueTo(ndp pmetric.NumberDataPoint) } @@ -51,11 +51,11 @@ type nullFloat64MetricValue struct { value spanner.NullFloat64 } -func (m queryMetricValueMetadata) ValueHolder() interface{} { +func (m queryMetricValueMetadata) ValueHolder() any { return m.valueHolderFunc() } -func (m queryMetricValueMetadata) NewMetricValue(value interface{}) MetricValue { +func (m queryMetricValueMetadata) NewMetricValue(value any) MetricValue { return m.newMetricValueFunc(m, value) } @@ -91,15 +91,15 @@ func (v nullFloat64MetricValue) Metadata() MetricValueMetadata { return v.metadata } -func (v int64MetricValue) Value() interface{} { +func (v int64MetricValue) Value() any { return v.value } -func (v float64MetricValue) Value() interface{} { +func (v float64MetricValue) Value() any { return v.value } -func (v nullFloat64MetricValue) Value() interface{} { +func (v nullFloat64MetricValue) Value() any { return v.value } @@ -119,21 +119,21 @@ func (v nullFloat64MetricValue) SetValueTo(point pmetric.NumberDataPoint) { } } -func newInt64MetricValue(metadata MetricValueMetadata, valueHolder interface{}) MetricValue { +func newInt64MetricValue(metadata MetricValueMetadata, valueHolder any) MetricValue { return int64MetricValue{ metadata: metadata, value: *valueHolder.(*int64), } } -func newFloat64MetricValue(metadata MetricValueMetadata, valueHolder interface{}) MetricValue { +func newFloat64MetricValue(metadata MetricValueMetadata, valueHolder any) MetricValue { return float64MetricValue{ metadata: metadata, value: *valueHolder.(*float64), } } -func newNullFloat64MetricValue(metadata MetricValueMetadata, valueHolder interface{}) MetricValue { +func newNullFloat64MetricValue(metadata MetricValueMetadata, valueHolder any) MetricValue { return nullFloat64MetricValue{ metadata: metadata, value: *valueHolder.(*spanner.NullFloat64), @@ -149,19 +149,19 @@ func NewMetricValueMetadata(name string, columnName string, dataType MetricType, switch valueType { case IntValueType: newMetricValueFunc = newInt64MetricValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder int64 return &valueHolder } case FloatValueType: newMetricValueFunc = newFloat64MetricValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder float64 return &valueHolder } case NullFloatValueType: newMetricValueFunc = newNullFloat64MetricValue - valueHolderFunc = func() interface{} { + valueHolderFunc = func() any { var valueHolder spanner.NullFloat64 return &valueHolder } diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/valuemetadata.go b/receiver/googlecloudspannerreceiver/internal/metadata/valuemetadata.go index d3cc37ec4395..c6b2f174ca52 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/valuemetadata.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/valuemetadata.go @@ -20,7 +20,7 @@ const ( type ValueMetadata interface { Name() string ColumnName() string - ValueHolder() interface{} + ValueHolder() any } -type valueHolderFunction func() interface{} +type valueHolderFunction func() any diff --git a/receiver/googlecloudspannerreceiver/internal/statsreader/statements.go b/receiver/googlecloudspannerreceiver/internal/statsreader/statements.go index 00edbf892f53..651b775f94ff 100644 --- a/receiver/googlecloudspannerreceiver/internal/statsreader/statements.go +++ b/receiver/googlecloudspannerreceiver/internal/statsreader/statements.go @@ -29,12 +29,12 @@ type statsStatement struct { } func currentStatsStatement(args statementArgs) statsStatement { - stmt := spanner.Statement{SQL: args.query, Params: map[string]interface{}{}} + stmt := spanner.Statement{SQL: args.query, Params: map[string]any{}} if args.topMetricsQueryMaxRows > 0 { stmt = spanner.Statement{ SQL: args.query + topMetricsQueryLimitCondition, - Params: map[string]interface{}{ + Params: map[string]any{ topMetricsQueryLimitParameterName: args.topMetricsQueryMaxRows, }, } @@ -50,7 +50,7 @@ func intervalStatsStatement(args statementArgs) statsStatement { stmt := currentStatsStatement(args) if len(stmt.statement.Params) == 0 { - stmt.statement.Params = map[string]interface{}{} + stmt.statement.Params = map[string]any{} } stmt.statement.Params[pullTimestampParameterName] = args.pullTimestamp diff --git a/receiver/googlecloudspannerreceiver/internal/statsreader/statements_test.go b/receiver/googlecloudspannerreceiver/internal/statsreader/statements_test.go index fbd3debb948c..8ba1d982048b 100644 --- a/receiver/googlecloudspannerreceiver/internal/statsreader/statements_test.go +++ b/receiver/googlecloudspannerreceiver/internal/statsreader/statements_test.go @@ -20,10 +20,10 @@ func TestCurrentStatsStatement(t *testing.T) { testCases := map[string]struct { topMetricsQueryMaxRows int expectedSQL string - expectedParams map[string]interface{} + expectedParams map[string]any }{ - "Statement with top metrics query max rows": {topMetricsQueryMaxRows, query + topMetricsQueryLimitCondition, map[string]interface{}{topMetricsQueryLimitParameterName: topMetricsQueryMaxRows}}, - "Statement without top metrics query max rows": {0, query, map[string]interface{}{}}, + "Statement with top metrics query max rows": {topMetricsQueryMaxRows, query + topMetricsQueryLimitCondition, map[string]any{topMetricsQueryLimitParameterName: topMetricsQueryMaxRows}}, + "Statement without top metrics query max rows": {0, query, map[string]any{}}, } for name, testCase := range testCases { @@ -49,13 +49,13 @@ func TestIntervalStatsStatement(t *testing.T) { testCases := map[string]struct { topMetricsQueryMaxRows int expectedSQL string - expectedParams map[string]interface{} + expectedParams map[string]any }{ - "Statement with top metrics query max rows": {topMetricsQueryMaxRows, query + topMetricsQueryLimitCondition, map[string]interface{}{ + "Statement with top metrics query max rows": {topMetricsQueryMaxRows, query + topMetricsQueryLimitCondition, map[string]any{ topMetricsQueryLimitParameterName: topMetricsQueryMaxRows, pullTimestampParameterName: pullTimestamp, }}, - "Statement without top metrics query max rows": {0, query, map[string]interface{}{pullTimestampParameterName: pullTimestamp}}, + "Statement without top metrics query max rows": {0, query, map[string]any{pullTimestampParameterName: pullTimestamp}}, } for name, testCase := range testCases { diff --git a/receiver/googlecloudspannerreceiver/internal/statsreader/statsreaders_mockedspanner_test.go b/receiver/googlecloudspannerreceiver/internal/statsreader/statsreaders_mockedspanner_test.go index a95cbcc55dca..60e44be45502 100644 --- a/receiver/googlecloudspannerreceiver/internal/statsreader/statsreaders_mockedspanner_test.go +++ b/receiver/googlecloudspannerreceiver/internal/statsreader/statsreaders_mockedspanner_test.go @@ -157,13 +157,13 @@ func TestStatsReaders_Read(t *testing.T) { _, err = databaseClient.Apply(ctx, []*spanner.Mutation{ spanner.Insert("STATS", []string{"INTERVAL_END", "METRIC_LABEL", "METRIC_VALUE"}, - []interface{}{timestamp, "Qwerty", 10}), + []any{timestamp, "Qwerty", 10}), spanner.Insert("STATS", []string{"INTERVAL_END", "METRIC_LABEL", "METRIC_VALUE"}, - []interface{}{timestamp.Add(-1 * time.Minute), "Test", 20}), + []any{timestamp.Add(-1 * time.Minute), "Test", 20}), spanner.Insert("STATS", []string{"INTERVAL_END", "METRIC_LABEL", "METRIC_VALUE"}, - []interface{}{timestamp.Add(-1 * time.Minute), "Spanner", 30}), + []any{timestamp.Add(-1 * time.Minute), "Spanner", 30}), }) require.NoError(t, err) diff --git a/receiver/influxdbreceiver/logger.go b/receiver/influxdbreceiver/logger.go index dc9a48ad9197..07d6e2ba9ed7 100644 --- a/receiver/influxdbreceiver/logger.go +++ b/receiver/influxdbreceiver/logger.go @@ -18,6 +18,6 @@ func newZapInfluxLogger(logger *zap.Logger) common.Logger { } } -func (l zapInfluxLogger) Debug(msg string, kv ...interface{}) { +func (l zapInfluxLogger) Debug(msg string, kv ...any) { l.SugaredLogger.Debugw(msg, kv...) } diff --git a/receiver/influxdbreceiver/receiver.go b/receiver/influxdbreceiver/receiver.go index 98d957a68863..a09baf0ffe2a 100644 --- a/receiver/influxdbreceiver/receiver.go +++ b/receiver/influxdbreceiver/receiver.go @@ -156,7 +156,7 @@ func (r *metricsReceiver) handleWrite(w http.ResponseWriter, req *http.Request) return } - fields := make(map[string]interface{}) + fields := make(map[string]any) for k, vField, err = lpDecoder.NextField(); k != nil && err == nil; k, vField, err = lpDecoder.NextField() { fields[string(k)] = vField.Interface() } diff --git a/receiver/influxdbreceiver/receiver_test.go b/receiver/influxdbreceiver/receiver_test.go index c2c16668df88..84444f0de285 100644 --- a/receiver/influxdbreceiver/receiver_test.go +++ b/receiver/influxdbreceiver/receiver_test.go @@ -48,7 +48,7 @@ func TestWriteLineProtocol_v2API(t *testing.T) { batchPoints, err := influxdb1.NewBatchPoints(influxdb1.BatchPointsConfig{Precision: "µs"}) require.NoError(t, err) - point, err := influxdb1.NewPoint("cpu_temp", map[string]string{"foo": "bar"}, map[string]interface{}{"gauge": 87.332}) + point, err := influxdb1.NewPoint("cpu_temp", map[string]string{"foo": "bar"}, map[string]any{"gauge": 87.332}) require.NoError(t, err) batchPoints.AddPoint(point) err = client.Write(batchPoints) diff --git a/receiver/k8sclusterreceiver/informer_transform.go b/receiver/k8sclusterreceiver/informer_transform.go index 4790c6a43370..17486d4d8204 100644 --- a/receiver/k8sclusterreceiver/informer_transform.go +++ b/receiver/k8sclusterreceiver/informer_transform.go @@ -20,7 +20,7 @@ import ( // transformObject transforms the k8s object by removing the data that is not utilized by the receiver. // Only highly utilized objects are transformed here while others are kept as is. -func transformObject(object interface{}) (interface{}, error) { +func transformObject(object any) (any, error) { switch o := object.(type) { case *corev1.Pod: return pod.Transform(o), nil diff --git a/receiver/k8sclusterreceiver/informer_transform_test.go b/receiver/k8sclusterreceiver/informer_transform_test.go index 6dc9f3218f2a..0151b8215ba4 100644 --- a/receiver/k8sclusterreceiver/informer_transform_test.go +++ b/receiver/k8sclusterreceiver/informer_transform_test.go @@ -19,8 +19,8 @@ func TestTransformObject(t *testing.T) { intPtr := &i tests := []struct { name string - object interface{} - want interface{} + object any + want any same bool }{ { diff --git a/receiver/k8sclusterreceiver/internal/collection/collector_test.go b/receiver/k8sclusterreceiver/internal/collection/collector_test.go index 1cdd6e4a89e3..1c519efdc8ee 100644 --- a/receiver/k8sclusterreceiver/internal/collection/collector_test.go +++ b/receiver/k8sclusterreceiver/internal/collection/collector_test.go @@ -21,7 +21,7 @@ func TestCollectMetricData(t *testing.T) { var expectedRMs int ms.Setup(gvk.Pod, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "pod1-uid": testutils.NewPodWithContainer( "1", testutils.NewPodSpecWithContainer("container-name"), @@ -32,7 +32,7 @@ func TestCollectMetricData(t *testing.T) { expectedRMs += 2 // 1 for pod, 1 for container ms.Setup(gvk.Node, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "node1-uid": testutils.NewNode("1"), "node2-uid": testutils.NewNode("2"), }, @@ -40,70 +40,70 @@ func TestCollectMetricData(t *testing.T) { expectedRMs += 2 ms.Setup(gvk.Namespace, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "namespace1-uid": testutils.NewNamespace("1"), }, }) expectedRMs++ ms.Setup(gvk.ReplicationController, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "replicationcontroller1-uid": testutils.NewReplicationController("1"), }, }) expectedRMs++ ms.Setup(gvk.ResourceQuota, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "resourcequota1-uid": testutils.NewResourceQuota("1"), }, }) expectedRMs++ ms.Setup(gvk.Deployment, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "deployment1-uid": testutils.NewDeployment("1"), }, }) expectedRMs++ ms.Setup(gvk.ReplicaSet, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "replicaset1-uid": testutils.NewReplicaSet("1"), }, }) expectedRMs++ ms.Setup(gvk.DaemonSet, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "daemonset1-uid": testutils.NewDaemonset("1"), }, }) expectedRMs++ ms.Setup(gvk.StatefulSet, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "statefulset1-uid": testutils.NewStatefulset("1"), }, }) expectedRMs++ ms.Setup(gvk.Job, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "job1-uid": testutils.NewJob("1"), }, }) expectedRMs++ ms.Setup(gvk.CronJob, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "cronjob1-uid": testutils.NewCronJob("1"), }, }) expectedRMs++ ms.Setup(gvk.HorizontalPodAutoscaler, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "horizontalpodautoscaler1-uid": testutils.NewHPA("1"), }, }) diff --git a/receiver/k8sclusterreceiver/internal/deployment/deployments_test.go b/receiver/k8sclusterreceiver/internal/deployment/deployments_test.go index b5d6de49a449..14abd33b4cc7 100644 --- a/receiver/k8sclusterreceiver/internal/deployment/deployments_test.go +++ b/receiver/k8sclusterreceiver/internal/deployment/deployments_test.go @@ -36,7 +36,7 @@ func TestDeploymentMetrics(t *testing.T) { rm := m.ResourceMetrics().At(0) assert.Equal(t, - map[string]interface{}{ + map[string]any{ "k8s.deployment.uid": "test-deployment-1-uid", "k8s.deployment.name": "test-deployment-1", "k8s.namespace.name": "test-namespace", diff --git a/receiver/k8sclusterreceiver/internal/pod/pods_test.go b/receiver/k8sclusterreceiver/internal/pod/pods_test.go index a1e722bd98e4..e9ec03ab0ef1 100644 --- a/receiver/k8sclusterreceiver/internal/pod/pods_test.go +++ b/receiver/k8sclusterreceiver/internal/pod/pods_test.go @@ -287,7 +287,7 @@ func mockMetadataStore(to testCaseOptions) *metadata.Store { } store := &testutils.MockStore{ - Cache: map[string]interface{}{}, + Cache: map[string]any{}, WantErr: to.wantErrFromCache, } diff --git a/receiver/k8sclusterreceiver/internal/statefulset/statefulsets_test.go b/receiver/k8sclusterreceiver/internal/statefulset/statefulsets_test.go index 22fe9097a973..f94c82537390 100644 --- a/receiver/k8sclusterreceiver/internal/statefulset/statefulsets_test.go +++ b/receiver/k8sclusterreceiver/internal/statefulset/statefulsets_test.go @@ -32,7 +32,7 @@ func TestStatefulsetMetrics(t *testing.T) { rm := m.ResourceMetrics().At(0) assert.Equal(t, - map[string]interface{}{ + map[string]any{ "k8s.statefulset.uid": "test-statefulset-1-uid", "k8s.statefulset.name": "test-statefulset-1", "k8s.namespace.name": "test-namespace", diff --git a/receiver/k8sclusterreceiver/internal/testutils/mock_cache_store.go b/receiver/k8sclusterreceiver/internal/testutils/mock_cache_store.go index a0223c3b5d32..e8ff138bd532 100644 --- a/receiver/k8sclusterreceiver/internal/testutils/mock_cache_store.go +++ b/receiver/k8sclusterreceiver/internal/testutils/mock_cache_store.go @@ -12,10 +12,10 @@ import ( type MockStore struct { cache.Store WantErr bool - Cache map[string]interface{} + Cache map[string]any } -func (ms *MockStore) GetByKey(id string) (interface{}, bool, error) { +func (ms *MockStore) GetByKey(id string) (any, bool, error) { if ms.WantErr { return nil, false, errors.New("") } @@ -23,8 +23,8 @@ func (ms *MockStore) GetByKey(id string) (interface{}, bool, error) { return item, exits, nil } -func (ms *MockStore) List() []interface{} { - out := make([]interface{}, len(ms.Cache)) +func (ms *MockStore) List() []any { + out := make([]any, len(ms.Cache)) i := 0 for _, item := range ms.Cache { out[i] = item diff --git a/receiver/k8sclusterreceiver/internal/testutils/objects.go b/receiver/k8sclusterreceiver/internal/testutils/objects.go index e331fda815dc..f94b2a90bfbf 100644 --- a/receiver/k8sclusterreceiver/internal/testutils/objects.go +++ b/receiver/k8sclusterreceiver/internal/testutils/objects.go @@ -281,7 +281,7 @@ func NewEvictedTerminatedPodStatusWithContainer(containerName, containerID strin }, } } -func WithOwnerReferences(or []v1.OwnerReference, obj interface{}) interface{} { +func WithOwnerReferences(or []v1.OwnerReference, obj any) any { switch o := obj.(type) { case *corev1.Pod: o.OwnerReferences = or diff --git a/receiver/k8sclusterreceiver/receiver_test.go b/receiver/k8sclusterreceiver/receiver_test.go index c6b18cbdd315..f7d1713a373c 100644 --- a/receiver/k8sclusterreceiver/receiver_test.go +++ b/receiver/k8sclusterreceiver/receiver_test.go @@ -192,7 +192,7 @@ func TestReceiverWithMetadata(t *testing.T) { require.NoError(t, r.Shutdown(ctx)) } -func getUpdatedPod(pod *corev1.Pod) interface{} { +func getUpdatedPod(pod *corev1.Pod) any { return &corev1.Pod{ ObjectMeta: v1.ObjectMeta{ Name: pod.Name, diff --git a/receiver/k8sclusterreceiver/watcher.go b/receiver/k8sclusterreceiver/watcher.go index fa9d923a2158..5ac39e548281 100644 --- a/receiver/k8sclusterreceiver/watcher.go +++ b/receiver/k8sclusterreceiver/watcher.go @@ -243,7 +243,7 @@ func (rw *resourceWatcher) setupInformer(gvk schema.GroupVersionKind, informer c rw.metadataStore.Setup(gvk, informer.GetStore()) } -func (rw *resourceWatcher) onAdd(obj interface{}) { +func (rw *resourceWatcher) onAdd(obj any) { rw.waitForInitialInformerSync() // Sync metadata only if there's at least one destination for it to sent. @@ -258,7 +258,7 @@ func (rw *resourceWatcher) hasDestination() bool { return len(rw.metadataConsumers) != 0 || rw.entityLogConsumer != nil } -func (rw *resourceWatcher) onUpdate(oldObj, newObj interface{}) { +func (rw *resourceWatcher) onUpdate(oldObj, newObj any) { rw.waitForInitialInformerSync() // Sync metadata only if there's at least one destination for it to sent. @@ -270,7 +270,7 @@ func (rw *resourceWatcher) onUpdate(oldObj, newObj interface{}) { } // objMetadata returns the metadata for the given object. -func (rw *resourceWatcher) objMetadata(obj interface{}) map[experimentalmetricmetadata.ResourceID]*metadata.KubernetesMetadata { +func (rw *resourceWatcher) objMetadata(obj any) map[experimentalmetricmetadata.ResourceID]*metadata.KubernetesMetadata { switch o := obj.(type) { case *corev1.Pod: return pod.GetMetadata(o, rw.metadataStore, rw.logger) diff --git a/receiver/k8sclusterreceiver/watcher_test.go b/receiver/k8sclusterreceiver/watcher_test.go index c6c7ee62988a..e3e63f56b43e 100644 --- a/receiver/k8sclusterreceiver/watcher_test.go +++ b/receiver/k8sclusterreceiver/watcher_test.go @@ -306,7 +306,7 @@ func TestObjMetadata(t *testing.T) { tests := []struct { name string metadataStore *metadata.Store - resource interface{} + resource any want map[experimentalmetricmetadata.ResourceID]*metadata.KubernetesMetadata }{ { @@ -363,7 +363,7 @@ func TestObjMetadata(t *testing.T) { metadataStore: func() *metadata.Store { ms := metadata.NewStore() ms.Setup(gvk.Service, &testutils.MockStore{ - Cache: map[string]interface{}{ + Cache: map[string]any{ "test-namespace/test-service": &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "test-service", @@ -553,7 +553,7 @@ var allPodMetadata = func(metadata map[string]string) map[string]string { return out } -func podWithAdditionalLabels(labels map[string]string, pod *corev1.Pod) interface{} { +func podWithAdditionalLabels(labels map[string]string, pod *corev1.Pod) any { if pod.Labels == nil { pod.Labels = make(map[string]string, len(labels)) } diff --git a/receiver/k8seventsreceiver/receiver.go b/receiver/k8seventsreceiver/receiver.go index 1395c733af72..acaf7d461c2b 100644 --- a/receiver/k8seventsreceiver/receiver.go +++ b/receiver/k8seventsreceiver/receiver.go @@ -90,11 +90,11 @@ func (kr *k8seventsReceiver) startWatch(ns string) { stopperChan := make(chan struct{}) kr.stopperChanList = append(kr.stopperChanList, stopperChan) kr.startWatchingNamespace(kr.client, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { ev := obj.(*corev1.Event) kr.handleEvent(ev) }, - UpdateFunc: func(_, obj interface{}) { + UpdateFunc: func(_, obj any) { ev := obj.(*corev1.Event) kr.handleEvent(ev) }, diff --git a/receiver/k8sobjectsreceiver/mock_dynamic_client_test.go b/receiver/k8sobjectsreceiver/mock_dynamic_client_test.go index 9280bb503710..267559d0aedc 100644 --- a/receiver/k8sobjectsreceiver/mock_dynamic_client_test.go +++ b/receiver/k8sobjectsreceiver/mock_dynamic_client_test.go @@ -57,12 +57,12 @@ func (c mockDynamicClient) deletePods(objects ...*unstructured.Unstructured) { } } -func generatePod(name, namespace string, labels map[string]interface{}, resourceVersion string) *unstructured.Unstructured { +func generatePod(name, namespace string, labels map[string]any, resourceVersion string) *unstructured.Unstructured { pod := unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "Pods", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": namespace, "name": name, "labels": labels, diff --git a/receiver/k8sobjectsreceiver/receiver_test.go b/receiver/k8sobjectsreceiver/receiver_test.go index 6047f6321428..d24b19752ee7 100644 --- a/receiver/k8sobjectsreceiver/receiver_test.go +++ b/receiver/k8sobjectsreceiver/receiver_test.go @@ -38,13 +38,13 @@ func TestPullObject(t *testing.T) { mockClient := newMockDynamicClient() mockClient.createPods( - generatePod("pod1", "default", map[string]interface{}{ + generatePod("pod1", "default", map[string]any{ "environment": "production", }, "1"), - generatePod("pod2", "default", map[string]interface{}{ + generatePod("pod2", "default", map[string]any{ "environment": "test", }, "2"), - generatePod("pod3", "default_ignore", map[string]interface{}{ + generatePod("pod3", "default_ignore", map[string]any{ "environment": "production", }, "3"), ) @@ -86,7 +86,7 @@ func TestWatchObject(t *testing.T) { mockClient := newMockDynamicClient() mockClient.createPods( - generatePod("pod1", "default", map[string]interface{}{ + generatePod("pod1", "default", map[string]any{ "environment": "production", }, "1"), ) @@ -123,13 +123,13 @@ func TestWatchObject(t *testing.T) { assert.Equal(t, 0, consumer.Count()) mockClient.createPods( - generatePod("pod2", "default", map[string]interface{}{ + generatePod("pod2", "default", map[string]any{ "environment": "test", }, "2"), - generatePod("pod3", "default_ignore", map[string]interface{}{ + generatePod("pod3", "default_ignore", map[string]any{ "environment": "production", }, "3"), - generatePod("pod4", "default", map[string]interface{}{ + generatePod("pod4", "default", map[string]any{ "environment": "production", }, "4"), ) @@ -138,7 +138,7 @@ func TestWatchObject(t *testing.T) { assert.Equal(t, 2, consumer.Count()) mockClient.deletePods( - generatePod("pod2", "default", map[string]interface{}{ + generatePod("pod2", "default", map[string]any{ "environment": "test", }, "2"), ) @@ -155,7 +155,7 @@ func TestExludeDeletedTrue(t *testing.T) { mockClient := newMockDynamicClient() mockClient.createPods( - generatePod("pod1", "default", map[string]interface{}{ + generatePod("pod1", "default", map[string]any{ "environment": "production", }, "1"), ) @@ -195,7 +195,7 @@ func TestExludeDeletedTrue(t *testing.T) { assert.Equal(t, 0, consumer.Count()) mockClient.deletePods( - generatePod("pod1", "default", map[string]interface{}{ + generatePod("pod1", "default", map[string]any{ "environment": "test", }, "1"), ) diff --git a/receiver/k8sobjectsreceiver/unstructured_to_logdata.go b/receiver/k8sobjectsreceiver/unstructured_to_logdata.go index 589b0547b369..fbb415155dc4 100644 --- a/receiver/k8sobjectsreceiver/unstructured_to_logdata.go +++ b/receiver/k8sobjectsreceiver/unstructured_to_logdata.go @@ -24,7 +24,7 @@ func watchObjectsToLogData(event *watch.Event, observedAt time.Time, config *K8s ul := unstructured.UnstructuredList{ Items: []unstructured.Unstructured{{ - Object: map[string]interface{}{ + Object: map[string]any{ "type": string(event.Type), "object": udata.Object, }, @@ -32,7 +32,7 @@ func watchObjectsToLogData(event *watch.Event, observedAt time.Time, config *K8s } return unstructuredListToLogData(&ul, observedAt, config, func(attrs pcommon.Map) { - objectMeta := udata.Object["metadata"].(map[string]interface{}) + objectMeta := udata.Object["metadata"].(map[string]any) name := objectMeta["name"].(string) if name != "" { attrs.PutStr("event.domain", "k8s") diff --git a/receiver/k8sobjectsreceiver/unstructured_to_logdata_test.go b/receiver/k8sobjectsreceiver/unstructured_to_logdata_test.go index d25c8116bcd8..5735e6d084cb 100644 --- a/receiver/k8sobjectsreceiver/unstructured_to_logdata_test.go +++ b/receiver/k8sobjectsreceiver/unstructured_to_logdata_test.go @@ -103,10 +103,10 @@ func TestUnstructuredListToLogData(t *testing.T) { event := &watch.Event{ Type: watch.Added, Object: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Event", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "generic-name", }, }, @@ -143,10 +143,10 @@ func TestUnstructuredListToLogData(t *testing.T) { event := &watch.Event{ Type: watch.Added, Object: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Event", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "generic-name", }, }, diff --git a/receiver/kafkareceiver/json_unmarshaler.go b/receiver/kafkareceiver/json_unmarshaler.go index a91360c24457..9ff02d03a6ea 100644 --- a/receiver/kafkareceiver/json_unmarshaler.go +++ b/receiver/kafkareceiver/json_unmarshaler.go @@ -22,7 +22,7 @@ func (r *jsonLogsUnmarshaler) Unmarshal(buf []byte) (plog.Logs, error) { p := plog.NewLogs() // get json logs from the buffer - jsonVal := map[string]interface{}{} + jsonVal := map[string]any{} if err := jsoniter.Unmarshal(buf, &jsonVal); err != nil { return p, err } diff --git a/receiver/kubeletstatsreceiver/factory_test.go b/receiver/kubeletstatsreceiver/factory_test.go index d7223bcc0e03..d65225d39575 100644 --- a/receiver/kubeletstatsreceiver/factory_test.go +++ b/receiver/kubeletstatsreceiver/factory_test.go @@ -140,7 +140,7 @@ func TestCustomUnmarshaller(t *testing.T) { args args result *Config mockUnmarshallFailure bool - configOverride map[string]interface{} + configOverride map[string]any wantErr bool }{ { @@ -184,7 +184,7 @@ func TestCustomUnmarshaller(t *testing.T) { }, }, }, - configOverride: map[string]interface{}{ + configOverride: map[string]any{ "metric_groups": []string{string(kubelet.ContainerMetricGroup)}, "collection_interval": 20 * time.Second, }, @@ -201,7 +201,7 @@ func TestCustomUnmarshaller(t *testing.T) { t.Run(tt.name, func(t *testing.T) { if tt.mockUnmarshallFailure { // some arbitrary failure. - err := tt.args.componentParser.Merge(confmap.NewFromStringMap(map[string]interface{}{metricGroupsConfig: map[string]string{"foo": "bar"}})) + err := tt.args.componentParser.Merge(confmap.NewFromStringMap(map[string]any{metricGroupsConfig: map[string]string{"foo": "bar"}})) require.NoError(t, err) } diff --git a/receiver/kubeletstatsreceiver/internal/kubelet/metadata_test.go b/receiver/kubeletstatsreceiver/internal/kubelet/metadata_test.go index ae9309a375c0..dfb666c1e703 100644 --- a/receiver/kubeletstatsreceiver/internal/kubelet/metadata_test.go +++ b/receiver/kubeletstatsreceiver/internal/kubelet/metadata_test.go @@ -66,13 +66,13 @@ func TestSetExtraLabels(t *testing.T) { metadata Metadata args []string wantError string - want map[string]interface{} + want map[string]any }{ { name: "no_labels", metadata: NewMetadata([]MetadataLabel{}, nil, nil), args: []string{"uid", "container.id", "container"}, - want: map[string]interface{}{}, + want: map[string]any{}, }, { name: "set_container_id_valid", @@ -100,7 +100,7 @@ func TestSetExtraLabels(t *testing.T) { }, }, nil), args: []string{"uid-1234", "container.id", "container1"}, - want: map[string]interface{}{ + want: map[string]any{ string(MetadataLabelContainerID): "test-container", }, }, @@ -130,7 +130,7 @@ func TestSetExtraLabels(t *testing.T) { }, }, nil), args: []string{"uid-1234", "container.id", "init-container1"}, - want: map[string]interface{}{ + want: map[string]any{ string(MetadataLabelContainerID): "test-init-container", }, }, @@ -236,7 +236,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { name string vs v1.VolumeSource args []string - want map[string]interface{} + want map[string]any }{ { name: "hostPath", @@ -244,7 +244,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { HostPath: &v1.HostPathVolumeSource{}, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "hostPath", }, }, @@ -254,7 +254,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { ConfigMap: &v1.ConfigMapVolumeSource{}, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "configMap", }, }, @@ -264,7 +264,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { EmptyDir: &v1.EmptyDirVolumeSource{}, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "emptyDir", }, }, @@ -274,7 +274,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { Secret: &v1.SecretVolumeSource{}, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "secret", }, }, @@ -284,7 +284,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { DownwardAPI: &v1.DownwardAPIVolumeSource{}, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "downwardAPI", }, }, @@ -296,7 +296,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { }, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "persistentVolumeClaim", "k8s.persistentvolumeclaim.name": "claim-name", }, @@ -311,7 +311,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { }, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "awsElasticBlockStore", "aws.volume.id": "volume_id", "fs.type": "fs_type", @@ -328,7 +328,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { }, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "gcePersistentDisk", "gce.pd.name": "pd_name", "fs.type": "fs_type", @@ -344,7 +344,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { }, }, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.type": "glusterfs", "glusterfs.endpoints.name": "endspoints_name", "glusterfs.path": "path", @@ -354,7 +354,7 @@ func TestSetExtraLabelsForVolumeTypes(t *testing.T) { name: "unsupported type", vs: v1.VolumeSource{}, args: []string{"uid-1234", "k8s.volume.type"}, - want: map[string]interface{}{}, + want: map[string]any{}, }, } for _, tt := range tests { diff --git a/receiver/kubeletstatsreceiver/internal/kubelet/volume_test.go b/receiver/kubeletstatsreceiver/internal/kubelet/volume_test.go index bc0ef5dfc300..55feefa5c238 100644 --- a/receiver/kubeletstatsreceiver/internal/kubelet/volume_test.go +++ b/receiver/kubeletstatsreceiver/internal/kubelet/volume_test.go @@ -29,7 +29,7 @@ func TestDetailedPVCLabels(t *testing.T) { volumeSource v1.VolumeSource pod pod detailedPVCLabelsSetterOverride func(rb *metadata.ResourceBuilder, volCacheID, volumeClaim, namespace string) error - want map[string]interface{} + want map[string]any }{ { name: "persistentVolumeClaim - with detailed PVC labels (AWS)", @@ -50,7 +50,7 @@ func TestDetailedPVCLabels(t *testing.T) { }) return nil }, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.name": "volume0", "k8s.volume.type": "awsElasticBlockStore", "aws.volume.id": "volume_id", @@ -81,7 +81,7 @@ func TestDetailedPVCLabels(t *testing.T) { }) return nil }, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.name": "volume0", "k8s.volume.type": "gcePersistentDisk", "gce.pd.name": "pd_name", @@ -111,7 +111,7 @@ func TestDetailedPVCLabels(t *testing.T) { }) return nil }, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.name": "volume0", "k8s.volume.type": "glusterfs", "glusterfs.endpoints.name": "endpoints_name", @@ -139,7 +139,7 @@ func TestDetailedPVCLabels(t *testing.T) { }) return nil }, - want: map[string]interface{}{ + want: map[string]any{ "k8s.volume.name": "volume0", "k8s.volume.type": "local", "k8s.persistentvolumeclaim.name": "claim-name", diff --git a/receiver/lokireceiver/loki_test.go b/receiver/lokireceiver/loki_test.go index 6b09db511f93..8e5b2614b7db 100644 --- a/receiver/lokireceiver/loki_test.go +++ b/receiver/lokireceiver/loki_test.go @@ -162,7 +162,7 @@ func TestSendingProtobufPushRequestToHTTPEndpoint(t *testing.T) { expected: generateLogs([]Log{ { Timestamp: 1676888496000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 1"), @@ -208,14 +208,14 @@ func TestSendingPushRequestToHTTPEndpoint(t *testing.T) { expected: generateLogs([]Log{ { Timestamp: 1676888496000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 1"), }, { Timestamp: 1676888497000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 2"), @@ -231,14 +231,14 @@ func TestSendingPushRequestToHTTPEndpoint(t *testing.T) { expected: generateLogs([]Log{ { Timestamp: 1676888496000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 1"), }, { Timestamp: 1676888497000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 2"), @@ -254,14 +254,14 @@ func TestSendingPushRequestToHTTPEndpoint(t *testing.T) { expected: generateLogs([]Log{ { Timestamp: 1676888496000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 1"), }, { Timestamp: 1676888497000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 2"), @@ -277,14 +277,14 @@ func TestSendingPushRequestToHTTPEndpoint(t *testing.T) { expected: generateLogs([]Log{ { Timestamp: 1676888496000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 1"), }, { Timestamp: 1676888497000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 2"), @@ -341,7 +341,7 @@ func TestSendingPushRequestToGRPCEndpoint(t *testing.T) { expected: generateLogs([]Log{ { Timestamp: 1676888496000000000, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "foo": "bar", }, Body: pcommon.NewValueStr("logline 1"), @@ -365,7 +365,7 @@ func TestSendingPushRequestToGRPCEndpoint(t *testing.T) { type Log struct { Timestamp int64 Body pcommon.Value - Attributes map[string]interface{} + Attributes map[string]any } func generateLogs(logs []Log) plog.Logs { diff --git a/receiver/mongodbatlasreceiver/access_logs.go b/receiver/mongodbatlasreceiver/access_logs.go index c18a0254d3c8..8d258c0b29be 100644 --- a/receiver/mongodbatlasreceiver/access_logs.go +++ b/receiver/mongodbatlasreceiver/access_logs.go @@ -259,15 +259,15 @@ func getTimestamp(log *mongodbatlas.AccessLogs) (time.Time, error) { body, err := parseLogMessage(log) if err != nil { // If body couldn't be parsed, we'll still use the outer Timestamp field to determine the new max date. - body = map[string]interface{}{} + body = map[string]any{} } return getTimestampPreparsedBody(log, body) } -func getTimestampPreparsedBody(log *mongodbatlas.AccessLogs, body map[string]interface{}) (time.Time, error) { +func getTimestampPreparsedBody(log *mongodbatlas.AccessLogs, body map[string]any) (time.Time, error) { // If the log message has a timestamp, use that. When present, it has more precision than the timestamp from the access log entry. if tMap, ok := body["t"]; ok { - if dateMap, ok := tMap.(map[string]interface{}); ok { + if dateMap, ok := tMap.(map[string]any); ok { if v, ok := dateMap["$date"]; ok { if dateStr, ok := v.(string); ok { return time.Parse(time.RFC3339, dateStr) @@ -291,8 +291,8 @@ func getTimestampPreparsedBody(log *mongodbatlas.AccessLogs, body map[string]int return t, nil } -func parseLogMessage(log *mongodbatlas.AccessLogs) (map[string]interface{}, error) { - var body map[string]interface{} +func parseLogMessage(log *mongodbatlas.AccessLogs) (map[string]any, error) { + var body map[string]any if err := json.Unmarshal([]byte(log.LogLine), &body); err != nil { return nil, err } diff --git a/receiver/mongodbatlasreceiver/access_logs_test.go b/receiver/mongodbatlasreceiver/access_logs_test.go index e08f54bba83e..08e1669c16be 100644 --- a/receiver/mongodbatlasreceiver/access_logs_test.go +++ b/receiver/mongodbatlasreceiver/access_logs_test.go @@ -78,7 +78,7 @@ func TestAccessLogToLogRecord(t *testing.T) { expectedLogs := plog.NewLogs() rl := expectedLogs.ResourceLogs().AppendEmpty() - assert.NoError(t, rl.Resource().Attributes().FromRaw(map[string]interface{}{ + assert.NoError(t, rl.Resource().Attributes().FromRaw(map[string]any{ "mongodbatlas.project.name": testProjectName, "mongodbatlas.project.id": testProjectID, "mongodbatlas.org.id": testOrgID, @@ -88,7 +88,7 @@ func TestAccessLogToLogRecord(t *testing.T) { records := rl.ScopeLogs().AppendEmpty().LogRecords() // First log is an example of a success, and tests that the timestamp works parsed from the log line lr := records.AppendEmpty() - assert.NoError(t, lr.Attributes().FromRaw(map[string]interface{}{ + assert.NoError(t, lr.Attributes().FromRaw(map[string]any{ "event.domain": "mongodbatlas", "auth.result": "success", "auth.source": "admin", @@ -102,13 +102,13 @@ func TestAccessLogToLogRecord(t *testing.T) { lr.SetSeverityNumber(plog.SeverityNumberInfo) lr.SetSeverityText(plog.SeverityNumberInfo.String()) - var logBody map[string]interface{} + var logBody map[string]any assert.NoError(t, json.Unmarshal([]byte(inputLogs[0].LogLine), &logBody)) assert.NoError(t, lr.Body().SetEmptyMap().FromRaw(logBody)) // Second log is an example of a failure, and tests that the timestamp is missing from the log line lr = records.AppendEmpty() - assert.NoError(t, lr.Attributes().FromRaw(map[string]interface{}{ + assert.NoError(t, lr.Attributes().FromRaw(map[string]any{ "event.domain": "mongodbatlas", "auth.result": "failure", "auth.failure_reason": "User not found", @@ -124,7 +124,7 @@ func TestAccessLogToLogRecord(t *testing.T) { lr.SetSeverityNumber(plog.SeverityNumberWarn) lr.SetSeverityText(plog.SeverityNumberWarn.String()) - logBody = map[string]interface{}{} + logBody = map[string]any{} assert.NoError(t, json.Unmarshal([]byte(inputLogs[1].LogLine), &logBody)) assert.NoError(t, lr.Body().SetEmptyMap().FromRaw(logBody)) diff --git a/receiver/mongodbatlasreceiver/alerts_test.go b/receiver/mongodbatlasreceiver/alerts_test.go index c3601b34ff84..6f141b574167 100644 --- a/receiver/mongodbatlasreceiver/alerts_test.go +++ b/receiver/mongodbatlasreceiver/alerts_test.go @@ -63,12 +63,12 @@ func TestPayloadToLogRecord(t *testing.T) { rl := logs.ResourceLogs().AppendEmpty() lr := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty() - assert.NoError(t, rl.Resource().Attributes().FromRaw(map[string]interface{}{ + assert.NoError(t, rl.Resource().Attributes().FromRaw(map[string]any{ "mongodbatlas.group.id": "some-group-id", "mongodbatlas.alert.config.id": "123", })) - assert.NoError(t, lr.Attributes().FromRaw(map[string]interface{}{ + assert.NoError(t, lr.Attributes().FromRaw(map[string]any{ "created": "2022-06-03T22:30:31Z", "message": "Some event happened", "event.domain": "mongodbatlas", @@ -120,14 +120,14 @@ func TestPayloadToLogRecord(t *testing.T) { rl := logs.ResourceLogs().AppendEmpty() lr := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty() - assert.NoError(t, rl.Resource().Attributes().FromRaw(map[string]interface{}{ + assert.NoError(t, rl.Resource().Attributes().FromRaw(map[string]any{ "mongodbatlas.group.id": "some-group-id", "mongodbatlas.alert.config.id": "123", "mongodbatlas.cluster.name": "cluster-name", "mongodbatlas.replica_set.name": "replica-set", })) - assert.NoError(t, lr.Attributes().FromRaw(map[string]interface{}{ + assert.NoError(t, lr.Attributes().FromRaw(map[string]any{ "acknowledgement.comment": "Scheduled maintenance", "acknowledgement.until": "2022-06-03T22:32:34Z", "acknowledgement.username": "devops", diff --git a/receiver/mongodbatlasreceiver/internal/model/logs.go b/receiver/mongodbatlasreceiver/internal/model/logs.go index bdb17d3d49c6..297681587848 100644 --- a/receiver/mongodbatlasreceiver/internal/model/logs.go +++ b/receiver/mongodbatlasreceiver/internal/model/logs.go @@ -9,13 +9,13 @@ import ( // LogEntry represents a MongoDB Atlas JSON log entry type LogEntry struct { - Timestamp LogTimestamp `json:"t"` - Severity string `json:"s"` - Component string `json:"c"` - ID int64 `json:"id"` - Context string `json:"ctx"` - Message string `json:"msg"` - Attributes map[string]interface{} `json:"attr"` + Timestamp LogTimestamp `json:"t"` + Severity string `json:"s"` + Component string `json:"c"` + ID int64 `json:"id"` + Context string `json:"ctx"` + Message string `json:"msg"` + Attributes map[string]any `json:"attr"` // Raw is the original log line. It is not a part of the payload, but transient data added during decoding. Raw string `json:"-"` } diff --git a/receiver/mongodbatlasreceiver/mongodb_event_to_logdata_test.go b/receiver/mongodbatlasreceiver/mongodb_event_to_logdata_test.go index a9a01d5c706d..267b652558fe 100644 --- a/receiver/mongodbatlasreceiver/mongodb_event_to_logdata_test.go +++ b/receiver/mongodbatlasreceiver/mongodb_event_to_logdata_test.go @@ -228,7 +228,7 @@ func getTestEvent4_4() model.LogEntry { ID: 12312, Context: "context", Message: "Connection ended", - Attributes: map[string]interface{}{"connectionCount": 47, "connectionId": 9052, "remote": "192.168.253.105:59742", "id": "93a8f190-afd0-422d-9de6-f6c5e833e35f"}, + Attributes: map[string]any{"connectionCount": 47, "connectionId": 9052, "remote": "192.168.253.105:59742", "id": "93a8f190-afd0-422d-9de6-f6c5e833e35f"}, Raw: "RAW MESSAGE", } } diff --git a/receiver/mongodbreceiver/client.go b/receiver/mongodbreceiver/client.go index c9da17fb49d0..1cf92a5a2c79 100644 --- a/receiver/mongodbreceiver/client.go +++ b/receiver/mongodbreceiver/client.go @@ -18,7 +18,7 @@ import ( // client is an interface that exposes functionality towards a mongo environment type client interface { - ListDatabaseNames(ctx context.Context, filters interface{}, opts ...*options.ListDatabasesOptions) ([]string, error) + ListDatabaseNames(ctx context.Context, filters any, opts ...*options.ListDatabasesOptions) ([]string, error) ListCollectionNames(ctx context.Context, DBName string) ([]string, error) Disconnect(context.Context) error GetVersion(context.Context) (*version.Version, error) diff --git a/receiver/mongodbreceiver/client_test.go b/receiver/mongodbreceiver/client_test.go index ec60c379a3fe..1f67c2a2e57c 100644 --- a/receiver/mongodbreceiver/client_test.go +++ b/receiver/mongodbreceiver/client_test.go @@ -24,7 +24,7 @@ import ( // while also testing with exclusively mtest. type fakeClient struct{ mock.Mock } -func (fc *fakeClient) ListDatabaseNames(ctx context.Context, filters interface{}, opts ...*options.ListDatabasesOptions) ([]string, error) { +func (fc *fakeClient) ListDatabaseNames(ctx context.Context, filters any, opts ...*options.ListDatabasesOptions) ([]string, error) { args := fc.Called(ctx, filters, opts) return args.Get(0).([]string), args.Error(1) } diff --git a/receiver/mongodbreceiver/metrics.go b/receiver/mongodbreceiver/metrics.go index acae06d91914..9d0b36578537 100644 --- a/receiver/mongodbreceiver/metrics.go +++ b/receiver/mongodbreceiver/metrics.go @@ -562,7 +562,7 @@ func collectMetric(document bson.M, path []string) (int64, error) { return parseInt(metric) } -func dig(document bson.M, path []string) (interface{}, error) { +func dig(document bson.M, path []string) (any, error) { curItem, remainingPath := path[0], path[1:] value := document[curItem] if value == nil { @@ -574,7 +574,7 @@ func dig(document bson.M, path []string) (interface{}, error) { return dig(value.(bson.M), remainingPath) } -func parseInt(val interface{}) (int64, error) { +func parseInt(val any) (int64, error) { switch v := val.(type) { case int: return int64(v), nil diff --git a/receiver/mysqlreceiver/client.go b/receiver/mysqlreceiver/client.go index 4acd14bfa8d6..165a8e9f257d 100644 --- a/receiver/mysqlreceiver/client.go +++ b/receiver/mysqlreceiver/client.go @@ -367,7 +367,7 @@ func (c *mySQLClient) getReplicaStatusStats() ([]ReplicaStatusStats, error) { var stats []ReplicaStatusStats for rows.Next() { var s ReplicaStatusStats - dest := []interface{}{} + dest := []any{} for _, col := range cols { switch strings.ToLower(col) { case "replica_io_state": diff --git a/receiver/oracledbreceiver/db_client.go b/receiver/oracledbreceiver/db_client.go index 3f8fa60d83ab..cb3c171a8600 100644 --- a/receiver/oracledbreceiver/db_client.go +++ b/receiver/oracledbreceiver/db_client.go @@ -50,7 +50,7 @@ func (cl dbSQLClient) metricRows(ctx context.Context) ([]metricRow, error) { } for _, sqlType := range types { colName := sqlType.Name() - var v interface{} + var v any row.attrs[colName] = func() string { format := "%v" if v == nil { @@ -78,7 +78,7 @@ func (cl dbSQLClient) metricRows(ctx context.Context) ([]metricRow, error) { type reusableRow struct { attrs map[string]func() string - scanDest []interface{} + scanDest []any } func (row reusableRow) toMetricRow() metricRow { diff --git a/receiver/podmanreceiver/libpod_data.go b/receiver/podmanreceiver/libpod_data.go index 128388af9da4..d68e72648e61 100644 --- a/receiver/podmanreceiver/libpod_data.go +++ b/receiver/podmanreceiver/libpod_data.go @@ -28,7 +28,7 @@ type container struct { Pid int Pod string PodName string - Ports []map[string]interface{} + Ports []map[string]any Size map[string]string StartedAt int State string diff --git a/receiver/podmanreceiver/receiver_windows.go b/receiver/podmanreceiver/receiver_windows.go index 35edce335f77..15a741ed82e3 100644 --- a/receiver/podmanreceiver/receiver_windows.go +++ b/receiver/podmanreceiver/receiver_windows.go @@ -16,7 +16,7 @@ func newMetricsReceiver( settings receiver.CreateSettings, config *Config, nextConsumer consumer.Metrics, - clientFactory interface{}, + clientFactory any, ) (receiver.Metrics, error) { return nil, fmt.Errorf("podman receiver is not supported on windows") } diff --git a/receiver/prometheusreceiver/config.go b/receiver/prometheusreceiver/config.go index 2a76e3c22d14..edcd0d2e5861 100644 --- a/receiver/prometheusreceiver/config.go +++ b/receiver/prometheusreceiver/config.go @@ -52,7 +52,7 @@ type Config struct { // ConfigPlaceholder is just an entry to make the configuration pass a check // that requires that all keys present in the config actually exist on the // structure, ie.: it will error if an unknown key is present. - ConfigPlaceholder interface{} `mapstructure:"config"` + ConfigPlaceholder any `mapstructure:"config"` // EnableProtobufNegotiation allows the collector to set the scraper option for // protobuf negotiation when conferring with a prometheus client. @@ -66,7 +66,7 @@ type targetAllocator struct { // ConfigPlaceholder is just an entry to make the configuration pass a check // that requires that all keys present in the config actually exist on the // structure, ie.: it will error if an unknown key is present. - ConfigPlaceholder interface{} `mapstructure:"http_sd_config"` + ConfigPlaceholder any `mapstructure:"http_sd_config"` HTTPSDConfig *promHTTP.SDConfig `mapstructure:"-"` } diff --git a/receiver/prometheusreceiver/internal/logger.go b/receiver/prometheusreceiver/internal/logger.go index 726d236574df..cd9ac7f20a99 100644 --- a/receiver/prometheusreceiver/internal/logger.go +++ b/receiver/prometheusreceiver/internal/logger.go @@ -30,10 +30,10 @@ type zapToGokitLogAdapter struct { type logData struct { level level.Value msg string - otherFields []interface{} + otherFields []any } -func (w *zapToGokitLogAdapter) Log(keyvals ...interface{}) error { +func (w *zapToGokitLogAdapter) Log(keyvals ...any) error { // expecting key value pairs, the number of items need to be even if len(keyvals)%2 == 0 { // Extract log level and message and log them using corresponding zap function @@ -47,7 +47,7 @@ func (w *zapToGokitLogAdapter) Log(keyvals ...interface{}) error { return nil } -func extractLogData(keyvals []interface{}) logData { +func extractLogData(keyvals []any) logData { ld := logData{ level: level.InfoValue(), // default } @@ -78,7 +78,7 @@ func extractLogData(keyvals []interface{}) logData { } // check if a given key-value pair represents go-kit log message and return it -func matchLogMessage(key interface{}, val interface{}) (string, bool) { +func matchLogMessage(key any, val any) (string, bool) { if strKey, ok := key.(string); !ok || strKey != msgKey { return "", false } @@ -91,7 +91,7 @@ func matchLogMessage(key interface{}, val interface{}) (string, bool) { } // check if a given key-value pair represents go-kit log level and return it -func matchLogLevel(key interface{}, val interface{}) (level.Value, bool) { +func matchLogLevel(key any, val any) (level.Value, bool) { strKey, ok := key.(string) if !ok || strKey != levelKey { return nil, false @@ -107,7 +107,7 @@ func matchLogLevel(key interface{}, val interface{}) (level.Value, bool) { //revive:disable:error-return // check if a given key-value pair represents an error and return it -func matchError(key interface{}, val interface{}) (error, bool) { +func matchError(key any, val any) (error, bool) { strKey, ok := key.(string) if !ok || strKey != errKey { return nil, false @@ -123,7 +123,7 @@ func matchError(key interface{}, val interface{}) (error, bool) { //revive:enable:error-return // find a matching zap logging function to be used for a given level -func levelToFunc(logger *zap.SugaredLogger, lvl level.Value) func(string, ...interface{}) { +func levelToFunc(logger *zap.SugaredLogger, lvl level.Value) func(string, ...any) { switch lvl { case level.DebugValue(): return logger.Debugw diff --git a/receiver/prometheusreceiver/internal/logger_test.go b/receiver/prometheusreceiver/internal/logger_test.go index 5a17fd051a27..037e23d94894 100644 --- a/receiver/prometheusreceiver/internal/logger_test.go +++ b/receiver/prometheusreceiver/internal/logger_test.go @@ -20,13 +20,13 @@ import ( func TestLog(t *testing.T) { tcs := []struct { name string - input []interface{} + input []any wantLevel zapcore.Level wantMessage string }{ { name: "Starting provider", - input: []interface{}{ + input: []any{ "level", level.DebugValue(), "msg", @@ -41,7 +41,7 @@ func TestLog(t *testing.T) { }, { name: "Scrape failed", - input: []interface{}{ + input: []any{ "level", level.ErrorValue(), "scrape_pool", @@ -84,10 +84,10 @@ func TestLog(t *testing.T) { func TestExtractLogData(t *testing.T) { tcs := []struct { name string - input []interface{} + input []any wantLevel level.Value wantMessage string - wantOutput []interface{} + wantOutput []any }{ { name: "nil fields", @@ -98,14 +98,14 @@ func TestExtractLogData(t *testing.T) { }, { name: "empty fields", - input: []interface{}{}, + input: []any{}, wantLevel: level.InfoValue(), // Default wantMessage: "", wantOutput: nil, }, { name: "info level", - input: []interface{}{ + input: []any{ "level", level.InfoValue(), }, @@ -115,7 +115,7 @@ func TestExtractLogData(t *testing.T) { }, { name: "warn level", - input: []interface{}{ + input: []any{ "level", level.WarnValue(), }, @@ -125,7 +125,7 @@ func TestExtractLogData(t *testing.T) { }, { name: "error level", - input: []interface{}{ + input: []any{ "level", level.ErrorValue(), }, @@ -135,7 +135,7 @@ func TestExtractLogData(t *testing.T) { }, { name: "debug level + extra fields", - input: []interface{}{ + input: []any{ "timestamp", 1596604719, "level", @@ -145,13 +145,13 @@ func TestExtractLogData(t *testing.T) { }, wantLevel: level.DebugValue(), wantMessage: "http client error", - wantOutput: []interface{}{ + wantOutput: []any{ "timestamp", 1596604719, }, }, { name: "missing level field", - input: []interface{}{ + input: []any{ "timestamp", 1596604719, "msg", @@ -159,18 +159,18 @@ func TestExtractLogData(t *testing.T) { }, wantLevel: level.InfoValue(), // Default wantMessage: "http client error", - wantOutput: []interface{}{ + wantOutput: []any{ "timestamp", 1596604719, }, }, { name: "invalid level type", - input: []interface{}{ + input: []any{ "level", "warn", // String is not recognized }, wantLevel: level.InfoValue(), // Default - wantOutput: []interface{}{ + wantOutput: []any{ "level", "warn", // Field is preserved }, }, diff --git a/receiver/prometheusreceiver/metrics_receiver_helper_test.go b/receiver/prometheusreceiver/metrics_receiver_helper_test.go index 30646cedd4ac..248c7ff380c3 100644 --- a/receiver/prometheusreceiver/metrics_receiver_helper_test.go +++ b/receiver/prometheusreceiver/metrics_receiver_helper_test.go @@ -115,7 +115,7 @@ type testData struct { // setupMockPrometheus to create a mocked prometheus based on targets, returning the server and a prometheus exporting // config func setupMockPrometheus(tds ...*testData) (*mockPrometheus, *promcfg.Config, error) { - jobs := make([]map[string]interface{}, 0, len(tds)) + jobs := make([]map[string]any, 0, len(tds)) endpoints := make(map[string][]mockPrometheusResponse) metricPaths := make([]string, len(tds)) for i, t := range tds { @@ -126,18 +126,18 @@ func setupMockPrometheus(tds ...*testData) (*mockPrometheus, *promcfg.Config, er mp := newMockPrometheus(endpoints) u, _ := url.Parse(mp.srv.URL) for i := 0; i < len(tds); i++ { - job := make(map[string]interface{}) + job := make(map[string]any) job["job_name"] = tds[i].name job["metrics_path"] = metricPaths[i] job["scrape_interval"] = "1s" job["scrape_timeout"] = "500ms" - job["static_configs"] = []map[string]interface{}{{"targets": []string{u.Host}}} + job["static_configs"] = []map[string]any{{"targets": []string{u.Host}}} jobs = append(jobs, job) } if len(jobs) != len(tds) { log.Fatal("len(jobs) != len(targets), make sure job names are unique") } - configP := make(map[string]interface{}) + configP := make(map[string]any) configP["scrape_configs"] = jobs cfg, err := yaml.Marshal(&configP) if err != nil { diff --git a/receiver/prometheusreceiver/metrics_receiver_target_allocator_test.go b/receiver/prometheusreceiver/metrics_receiver_target_allocator_test.go index 2ad8d462388c..5feed213d1d4 100644 --- a/receiver/prometheusreceiver/metrics_receiver_target_allocator_test.go +++ b/receiver/prometheusreceiver/metrics_receiver_target_allocator_test.go @@ -42,7 +42,7 @@ type mockTargetAllocatorResponse struct { type mockTargetAllocatorResponseRaw struct { code int - data interface{} + data any } type hTTPSDResponse struct { @@ -162,7 +162,7 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { responses: Responses{ responses: map[string][]mockTargetAllocatorResponseRaw{ "/scrape_configs": { - mockTargetAllocatorResponseRaw{code: 200, data: map[string]map[string]interface{}{ + mockTargetAllocatorResponseRaw{code: 200, data: map[string]map[string]any{ "job1": { "job_name": "job1", "scrape_interval": "30s", @@ -256,7 +256,7 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { responses: Responses{ responses: map[string][]mockTargetAllocatorResponseRaw{ "/scrape_configs": { - mockTargetAllocatorResponseRaw{code: 200, data: map[string]map[string]interface{}{ + mockTargetAllocatorResponseRaw{code: 200, data: map[string]map[string]any{ "job1": { "job_name": "job1", "scrape_interval": "30s", @@ -348,7 +348,7 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { }, responses: map[string][]mockTargetAllocatorResponseRaw{ "/scrape_configs": { - mockTargetAllocatorResponseRaw{code: 200, data: map[string]map[string]interface{}{ + mockTargetAllocatorResponseRaw{code: 200, data: map[string]map[string]any{ "job1": { "job_name": "job1", "scrape_interval": "30s", @@ -368,7 +368,7 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { "metric_relabel_configs": nil, }, }}, - mockTargetAllocatorResponseRaw{code: 200, data: map[string]map[string]interface{}{ + mockTargetAllocatorResponseRaw{code: 200, data: map[string]map[string]any{ "job1": { "job_name": "job1", "scrape_interval": "30s", @@ -460,8 +460,8 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { }, responses: map[string][]mockTargetAllocatorResponseRaw{ "/scrape_configs": { - mockTargetAllocatorResponseRaw{code: 404, data: map[string]map[string]interface{}{}}, - mockTargetAllocatorResponseRaw{code: 404, data: map[string]map[string]interface{}{}}, + mockTargetAllocatorResponseRaw{code: 404, data: map[string]map[string]any{}}, + mockTargetAllocatorResponseRaw{code: 404, data: map[string]map[string]any{}}, }, }, }, diff --git a/receiver/rabbitmqreceiver/client.go b/receiver/rabbitmqreceiver/client.go index f0888e0f9ae7..f1ed478d8ecf 100644 --- a/receiver/rabbitmqreceiver/client.go +++ b/receiver/rabbitmqreceiver/client.go @@ -66,7 +66,7 @@ func (c *rabbitmqClient) GetQueues(ctx context.Context) ([]*models.Queue, error) return queues, nil } -func (c *rabbitmqClient) get(ctx context.Context, path string, respObj interface{}) error { +func (c *rabbitmqClient) get(ctx context.Context, path string, respObj any) error { // Construct endpoint and create request url := c.hostEndpoint + path req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) diff --git a/receiver/rabbitmqreceiver/internal/models/models.go b/receiver/rabbitmqreceiver/internal/models/models.go index d015548343fd..0d97f616f320 100644 --- a/receiver/rabbitmqreceiver/internal/models/models.go +++ b/receiver/rabbitmqreceiver/internal/models/models.go @@ -16,5 +16,5 @@ type Queue struct { ReadyMessages int64 `json:"messages_ready"` // Embedded Metrics - MessageStats map[string]interface{} `json:"message_stats"` + MessageStats map[string]any `json:"message_stats"` } diff --git a/receiver/rabbitmqreceiver/scraper.go b/receiver/rabbitmqreceiver/scraper.go index 06bb76d6c34d..68a0f8649d7a 100644 --- a/receiver/rabbitmqreceiver/scraper.go +++ b/receiver/rabbitmqreceiver/scraper.go @@ -129,7 +129,7 @@ func (r *rabbitmqScraper) collectQueue(queue *models.Queue, now pcommon.Timestam // convertValToInt64 values from message state unmarshal as float64s but should be int64. // Need to do a double cast to get an int64. // This should never fail but worth checking just in case. -func convertValToInt64(val interface{}) (int64, bool) { +func convertValToInt64(val any) (int64, bool) { f64Val, ok := val.(float64) if !ok { return 0, ok diff --git a/receiver/receivercreator/config.go b/receiver/receivercreator/config.go index 4b5ea1483bcf..68deedf82abe 100644 --- a/receiver/receivercreator/config.go +++ b/receiver/receivercreator/config.go @@ -33,7 +33,7 @@ type receiverConfig struct { } // userConfigMap is an arbitrary map of string keys to arbitrary values as specified by the user -type userConfigMap map[string]interface{} +type userConfigMap map[string]any // receiverTemplate is the configuration of a single subreceiver. type receiverTemplate struct { @@ -44,7 +44,7 @@ type receiverTemplate struct { Rule string `mapstructure:"rule"` // ResourceAttributes is a map of resource attributes to add to just this receiver's resource metrics. // It can contain expr expressions for endpoint env value expansion - ResourceAttributes map[string]interface{} `mapstructure:"resource_attributes"` + ResourceAttributes map[string]any `mapstructure:"resource_attributes"` rule rule } diff --git a/receiver/receivercreator/config_expansion.go b/receiver/receivercreator/config_expansion.go index 48c93614bb54..ea4223a9fd44 100644 --- a/receiver/receivercreator/config_expansion.go +++ b/receiver/receivercreator/config_expansion.go @@ -25,14 +25,14 @@ import ( // of the expression. For instance: // // `"secure" in pod.labels` -> true (boolean) -func evalBackticksInConfigValue(configValue string, env observer.EndpointEnv) (interface{}, error) { +func evalBackticksInConfigValue(configValue string, env observer.EndpointEnv) (any, error) { // Tracks index into configValue where an expression (backtick) begins. -1 is unset. exprStartIndex := -1 // Accumulate expanded string. output := &strings.Builder{} // Accumulate results of calls to eval for use at the end to return well-typed // results if possible. - var expansions []interface{} + var expansions []any // Loop through configValue one rune at a time using exprStartIndex to keep track of // inside or outside of expressions. @@ -91,16 +91,16 @@ func evalBackticksInConfigValue(configValue string, env observer.EndpointEnv) (i // expandConfig will walk the provided user config and expand any `backticked` content // with associated observer.EndpointEnv values. func expandConfig(cfg userConfigMap, env observer.EndpointEnv) (userConfigMap, error) { - expanded, err := expandAny(map[string]interface{}(cfg), env) + expanded, err := expandAny(map[string]any(cfg), env) if err != nil { return nil, err } - return expanded.(map[string]interface{}), nil + return expanded.(map[string]any), nil } // expandAny recursively expands any expressions in backticks inside values of input using // env as variables available within the expression, returning a copy of input -func expandAny(input interface{}, env observer.EndpointEnv) (interface{}, error) { +func expandAny(input any, env observer.EndpointEnv) (any, error) { switch v := input.(type) { case string: res, err := evalBackticksInConfigValue(v, env) @@ -108,18 +108,18 @@ func expandAny(input interface{}, env observer.EndpointEnv) (interface{}, error) return nil, fmt.Errorf("failed evaluating config expression for %v: %w", v, err) } return res, nil - case []string, []interface{}: - var vSlice []interface{} + case []string, []any: + var vSlice []any if vss, ok := v.([]string); ok { // expanded strings aren't guaranteed to remain them, so we - // coerce to interface{} for shared []interface{} expansion path + // coerce to any for shared []any expansion path for _, vs := range vss { vSlice = append(vSlice, vs) } } else { - vSlice = v.([]interface{}) + vSlice = v.([]any) } - expandedSlice := make([]interface{}, 0, len(vSlice)) + expandedSlice := make([]any, 0, len(vSlice)) for _, val := range vSlice { expanded, err := expandAny(val, env) if err != nil { @@ -128,8 +128,8 @@ func expandAny(input interface{}, env observer.EndpointEnv) (interface{}, error) expandedSlice = append(expandedSlice, expanded) } return expandedSlice, nil - case map[string]interface{}: - expandedMap := map[string]interface{}{} + case map[string]any: + expandedMap := map[string]any{} for key, val := range v { expandedVal, err := expandAny(val, env) if err != nil { diff --git a/receiver/receivercreator/config_expansion_test.go b/receiver/receivercreator/config_expansion_test.go index 1ac7bbf37abb..cedbaef9fe1e 100644 --- a/receiver/receivercreator/config_expansion_test.go +++ b/receiver/receivercreator/config_expansion_test.go @@ -13,14 +13,14 @@ import ( func Test_expandConfigValue(t *testing.T) { type args struct { - env map[string]interface{} + env map[string]any configValue string } - localhostEnv := map[string]interface{}{ + localhostEnv := map[string]any{ "endpoint": "localhost", - "nested": map[string]interface{}{ - "outer": map[string]interface{}{ - "inner": map[string]interface{}{ + "nested": map[string]any{ + "outer": map[string]any{ + "inner": map[string]any{ "value": 123, }, }, @@ -29,19 +29,19 @@ func Test_expandConfigValue(t *testing.T) { tests := []struct { name string args args - want interface{} + want any wantErr bool }{ // Non-error cases. {"normal string", args{nil, "str"}, "str", false}, {"expanded string", args{localhostEnv, "`endpoint + ':1234'`"}, "localhost:1234", false}, - {"expanded boolean", args{map[string]interface{}{ + {"expanded boolean", args{map[string]any{ "secure": "true", }, "`secure == 'true'`"}, true, false}, - {"expanded number", args{map[string]interface{}{ + {"expanded number", args{map[string]any{ "secure": "true", }, "`secure == 'true' ? 443 : 80`"}, 443, false}, - {"multiple expressions", args{map[string]interface{}{ + {"multiple expressions", args{map[string]any{ "endpoint": "localhost", "port": 1234, }, "`endpoint`:`port`"}, "localhost:1234", false}, @@ -86,11 +86,11 @@ func Test_userConfigMap_resolve(t *testing.T) { }{ // Note: {"multi-level maps", userConfigMap{ - "one": map[string]interface{}{ + "one": map[string]any{ "two": "`endpoint`", }, }, args{observer.EndpointEnv{"endpoint": "localhost"}}, userConfigMap{ - "one": map[string]interface{}{ + "one": map[string]any{ "two": "localhost", }, }, false}, @@ -103,17 +103,17 @@ func Test_userConfigMap_resolve(t *testing.T) { }, { "nested slices and maps", userConfigMap{ - "one": []interface{}{ + "one": []any{ "`one`:6379", - map[string]interface{}{ - "two": []interface{}{ + map[string]any{ + "two": []any{ "`two`:6379", }, - "three": []interface{}{ - map[string]interface{}{ + "three": []any{ + map[string]any{ "three": "abc`three`xyz", }, - map[string]interface{}{ + map[string]any{ "four": []string{ "`first`", "second", @@ -130,18 +130,18 @@ func Test_userConfigMap_resolve(t *testing.T) { "first": "first.value", "third": "third.value", }}, userConfigMap{ - "one": []interface{}{ + "one": []any{ "one.value:6379", - map[string]interface{}{ - "two": []interface{}{ + map[string]any{ + "two": []any{ "two.value:6379", }, - "three": []interface{}{ - map[string]interface{}{ + "three": []any{ + map[string]any{ "three": "abcthree.valuexyz", }, - map[string]interface{}{ - "four": []interface{}{ + map[string]any{ + "four": []any{ "first.value", "second", "abc third.value xyz", diff --git a/receiver/receivercreator/config_test.go b/receiver/receivercreator/config_test.go index 666a691e4dfa..2062a93c8c6f 100644 --- a/receiver/receivercreator/config_test.go +++ b/receiver/receivercreator/config_test.go @@ -88,7 +88,7 @@ func TestLoadConfig(t *testing.T) { endpointID: "endpoint.id", }, Rule: `type == "port"`, - ResourceAttributes: map[string]interface{}{"one": "two"}, + ResourceAttributes: map[string]any{"one": "two"}, rule: portRule, }, "nop/1": { @@ -100,7 +100,7 @@ func TestLoadConfig(t *testing.T) { endpointID: "endpoint.id", }, Rule: `type == "port"`, - ResourceAttributes: map[string]interface{}{"two": "three"}, + ResourceAttributes: map[string]any{"two": "three"}, rule: portRule, }, }, diff --git a/receiver/receivercreator/observerhandler_test.go b/receiver/receivercreator/observerhandler_test.go index 5e1039534d1c..49237519eea2 100644 --- a/receiver/receivercreator/observerhandler_test.go +++ b/receiver/receivercreator/observerhandler_test.go @@ -76,7 +76,7 @@ func TestOnAddForMetrics(t *testing.T) { receiverConfig: rcvrCfg, rule: portRule, Rule: `type == "port"`, - ResourceAttributes: map[string]interface{}{}, + ResourceAttributes: map[string]any{}, }, } @@ -178,7 +178,7 @@ func TestOnAddForLogs(t *testing.T) { receiverConfig: rcvrCfg, rule: portRule, Rule: `type == "port"`, - ResourceAttributes: map[string]interface{}{}, + ResourceAttributes: map[string]any{}, }, } @@ -280,7 +280,7 @@ func TestOnAddForTraces(t *testing.T) { receiverConfig: rcvrCfg, rule: portRule, Rule: `type == "port"`, - ResourceAttributes: map[string]interface{}{}, + ResourceAttributes: map[string]any{}, }, } @@ -337,7 +337,7 @@ func TestOnRemoveForMetrics(t *testing.T) { receiverConfig: rcvrCfg, rule: portRule, Rule: `type == "port"`, - ResourceAttributes: map[string]interface{}{}, + ResourceAttributes: map[string]any{}, }, } handler, r := newObserverHandler(t, cfg, nil, consumertest.NewNop(), nil) @@ -366,7 +366,7 @@ func TestOnRemoveForLogs(t *testing.T) { receiverConfig: rcvrCfg, rule: portRule, Rule: `type == "port"`, - ResourceAttributes: map[string]interface{}{}, + ResourceAttributes: map[string]any{}, }, } handler, r := newObserverHandler(t, cfg, consumertest.NewNop(), nil, nil) @@ -395,7 +395,7 @@ func TestOnChange(t *testing.T) { receiverConfig: rcvrCfg, rule: portRule, Rule: `type == "port"`, - ResourceAttributes: map[string]interface{}{}, + ResourceAttributes: map[string]any{}, }, } handler, r := newObserverHandler(t, cfg, nil, consumertest.NewNop(), nil) diff --git a/receiver/receivercreator/rules.go b/receiver/receivercreator/rules.go index 6e9221c22193..1ff394a4e6bf 100644 --- a/receiver/receivercreator/rules.go +++ b/receiver/receivercreator/rules.go @@ -42,9 +42,9 @@ func newRule(ruleStr string) (rule, error) { // expr v1.14.1 introduced a `type` builtin whose implementation we relocate to `typeOf` // to avoid collision expr.DisableBuiltin("type"), - expr.Function("typeOf", func(params ...interface{}) (interface{}, error) { + expr.Function("typeOf", func(params ...any) (any, error) { return builtin.Type(params[0]), nil - }, new(func(interface{}) string)), + }, new(func(any) string)), ) if err != nil { return rule{}, err diff --git a/receiver/receivercreator/runner_test.go b/receiver/receivercreator/runner_test.go index a48b46e2eb5b..c6aeff382a6a 100644 --- a/receiver/receivercreator/runner_test.go +++ b/receiver/receivercreator/runner_test.go @@ -93,7 +93,7 @@ func TestValidateSetEndpointFromConfig(t *testing.T) { inheritedEndpointConfMap, inheritedEndpoint, inheritedErr := mergeTemplatedAndDiscoveredConfigs( receiverWithEndpoint, map[string]any{ endpointConfigKey: "an.endpoint", - }, map[string]interface{}{}, + }, map[string]any{}, ) require.Equal(t, map[string]any{endpointConfigKey: "an.endpoint"}, inheritedEndpointConfMap.ToStringMap()) require.Equal(t, "an.endpoint", inheritedEndpoint) @@ -112,7 +112,7 @@ func TestValidateSetEndpointFromConfig(t *testing.T) { inheritedEndpointConfMap, inheritedEndpoint, inheritedErr = mergeTemplatedAndDiscoveredConfigs( receiverWithoutEndpoint, map[string]any{ endpointConfigKey: "an.endpoint", - }, map[string]interface{}{}, + }, map[string]any{}, ) require.Equal(t, map[string]any{endpointConfigKey: "an.endpoint"}, inheritedEndpointConfMap.ToStringMap()) require.Equal(t, "an.endpoint", inheritedEndpoint) diff --git a/receiver/redisreceiver/metric_functions.go b/receiver/redisreceiver/metric_functions.go index 78088dc0017b..ab93867ddee0 100644 --- a/receiver/redisreceiver/metric_functions.go +++ b/receiver/redisreceiver/metric_functions.go @@ -11,8 +11,8 @@ import ( // dataPointRecorders is called once at startup. Returns recorders for all metrics (except keyspace) // we want to extract from Redis INFO. -func (rs *redisScraper) dataPointRecorders() map[string]interface{} { - return map[string]interface{}{ +func (rs *redisScraper) dataPointRecorders() map[string]any { + return map[string]any{ "blocked_clients": rs.mb.RecordRedisClientsBlockedDataPoint, "client_recent_max_input_buffer": rs.mb.RecordRedisClientsMaxInputBufferDataPoint, "client_recent_max_output_buffer": rs.mb.RecordRedisClientsMaxOutputBufferDataPoint, diff --git a/receiver/riakreceiver/client.go b/receiver/riakreceiver/client.go index 34374e26de86..0fc53f158e65 100644 --- a/receiver/riakreceiver/client.go +++ b/receiver/riakreceiver/client.go @@ -66,7 +66,7 @@ func (c *riakClient) GetStats(ctx context.Context) (*model.Stats, error) { return stats, nil } -func (c *riakClient) get(ctx context.Context, path string, respObj interface{}) error { +func (c *riakClient) get(ctx context.Context, path string, respObj any) error { // Construct endpoint and create request url := c.hostEndpoint + path req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) diff --git a/receiver/saphanareceiver/client.go b/receiver/saphanareceiver/client.go index 20e17640e7f5..da0a45f84a71 100644 --- a/receiver/saphanareceiver/client.go +++ b/receiver/saphanareceiver/client.go @@ -23,7 +23,7 @@ type client interface { // Wraps the result of a query so that it can be mocked in tests type resultWrapper interface { - Scan(dest ...interface{}) error + Scan(dest ...any) error Close() error Next() bool } @@ -43,7 +43,7 @@ func (w *standardResultWrapper) Next() bool { return w.rows.Next() } -func (w *standardResultWrapper) Scan(dest ...interface{}) error { +func (w *standardResultWrapper) Scan(dest ...any) error { return w.rows.Scan(dest...) } @@ -148,7 +148,7 @@ func (c *sapHanaClient) collectDataFromQuery(ctx context.Context, query *monitor ROW_ITERATOR: for rows.Next() { expectedFields := len(query.orderedMetricLabels) + len(query.orderedResourceLabels) + len(query.orderedStats) - rowFields := make([]interface{}, expectedFields) + rowFields := make([]any, expectedFields) // Build a list of addresses that rows.Scan will load column data into for i := range rowFields { @@ -206,7 +206,7 @@ ROW_ITERATOR: return data, errors.Combine() } -func convertInterfaceToString(input interface{}) (sql.NullString, error) { +func convertInterfaceToString(input any) (sql.NullString, error) { if val, ok := input.(*sql.NullString); ok { return *val, nil } diff --git a/receiver/saphanareceiver/client_test.go b/receiver/saphanareceiver/client_test.go index a6c21683e710..da5a6e3c4bad 100644 --- a/receiver/saphanareceiver/client_test.go +++ b/receiver/saphanareceiver/client_test.go @@ -26,7 +26,7 @@ func (m *testResultWrapper) Next() bool { return m.current < len(m.contents) } -func (m *testResultWrapper) Scan(dest ...interface{}) error { +func (m *testResultWrapper) Scan(dest ...any) error { for i, output := range dest { d, _ := output.(*sql.NullString) *d = m.contents[m.current][i] diff --git a/receiver/sapmreceiver/trace_receiver.go b/receiver/sapmreceiver/trace_receiver.go index ac1dc968d817..7a7ce06bdd20 100644 --- a/receiver/sapmreceiver/trace_receiver.go +++ b/receiver/sapmreceiver/trace_receiver.go @@ -26,7 +26,7 @@ import ( ) var gzipWriterPool = &sync.Pool{ - New: func() interface{} { + New: func() any { return gzip.NewWriter(io.Discard) }, } diff --git a/receiver/signalfxreceiver/signalfxv2_event_to_logdata_test.go b/receiver/signalfxreceiver/signalfxv2_event_to_logdata_test.go index 2ca976a5abab..3a0aff8bff18 100644 --- a/receiver/signalfxreceiver/signalfxv2_event_to_logdata_test.go +++ b/receiver/signalfxreceiver/signalfxv2_event_to_logdata_test.go @@ -30,7 +30,7 @@ func TestSignalFxV2EventsToLogData(t *testing.T) { Timestamp: msec, Category: &userDefinedCat, Dimensions: buildNDimensions(3), - Properties: mapToEventProps(map[string]interface{}{ + Properties: mapToEventProps(map[string]any{ "env": "prod", "isActive": true, "rack": 5, @@ -95,7 +95,7 @@ func TestSignalFxV2EventsToLogData(t *testing.T) { } } -func mapToEventProps(m map[string]interface{}) []*sfxpb.Property { +func mapToEventProps(m map[string]any) []*sfxpb.Property { out := make([]*sfxpb.Property, 0, len(m)) for k, v := range m { var pval sfxpb.PropertyValue diff --git a/receiver/snmpreceiver/client.go b/receiver/snmpreceiver/client.go index 33ab9f60b041..dd4b30a49265 100644 --- a/receiver/snmpreceiver/client.go +++ b/receiver/snmpreceiver/client.go @@ -29,7 +29,7 @@ const ( type SNMPData struct { columnOID string // optional oid string - value interface{} + value any valueType oidDataType } @@ -372,7 +372,7 @@ func (c *snmpClient) convertSnmpPDUToSnmpData(pdu gosnmp.SnmpPDU) SNMPData { // This is a convenience function to make working with SnmpPDU's easier - it // reduces the need for type assertions. A int64 is convenient, as SNMP can // return int32, uint32, and int64. -func (c snmpClient) toInt64(name string, value interface{}) (int64, error) { +func (c snmpClient) toInt64(name string, value any) (int64, error) { switch value := value.(type) { // shadow case uint: return int64(value), nil @@ -405,7 +405,7 @@ func (c snmpClient) toInt64(name string, value interface{}) (int64, error) { // This is a convenience function to make working with SnmpPDU's easier - it // reduces the need for type assertions. A float64 is convenient, as SNMP can // return float32 and float64. -func (c snmpClient) toFloat64(name string, value interface{}) (float64, error) { +func (c snmpClient) toFloat64(name string, value any) (float64, error) { switch value := value.(type) { // shadow case float32: return float64(value), nil @@ -428,7 +428,7 @@ func (c snmpClient) toFloat64(name string, value interface{}) (float64, error) { // // This is a convenience function to make working with SnmpPDU's easier - it // reduces the need for type assertions. -func toString(value interface{}) string { +func toString(value any) string { switch value := value.(type) { // shadow case []byte: return string(value) diff --git a/receiver/snowflakereceiver/client_test.go b/receiver/snowflakereceiver/client_test.go index 656e22426192..1fd59b5e8638 100644 --- a/receiver/snowflakereceiver/client_test.go +++ b/receiver/snowflakereceiver/client_test.go @@ -65,7 +65,7 @@ func TestMetricQueries(t *testing.T) { query string columns []string params []driver.Value - expect interface{} + expect any }{ { desc: "FetchBillingMetrics", diff --git a/receiver/solacereceiver/internal/model/egress/v1/egress_v1.pb.go b/receiver/solacereceiver/internal/model/egress/v1/egress_v1.pb.go index eff5062d3022..32ebaa51a1e6 100644 --- a/receiver/solacereceiver/internal/model/egress/v1/egress_v1.pb.go +++ b/receiver/solacereceiver/internal/model/egress/v1/egress_v1.pb.go @@ -989,7 +989,7 @@ func file_egress_v1_proto_rawDescGZIP() []byte { var file_egress_v1_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_egress_v1_proto_msgTypes = make([]protoimpl.MessageInfo, 6) -var file_egress_v1_proto_goTypes = []interface{}{ +var file_egress_v1_proto_goTypes = []any{ (SpanData_SendSpan_Outcome)(0), // 0: solace.messaging.proto.broker.trace.egress.v1.SpanData.SendSpan.Outcome (SpanData_TransactionEvent_Type)(0), // 1: solace.messaging.proto.broker.trace.egress.v1.SpanData.TransactionEvent.Type (SpanData_TransactionEvent_Initiator)(0), // 2: solace.messaging.proto.broker.trace.egress.v1.SpanData.TransactionEvent.Initiator @@ -1022,7 +1022,7 @@ func file_egress_v1_proto_init() { return } if !protoimpl.UnsafeEnabled { - file_egress_v1_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + file_egress_v1_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*SpanData); i { case 0: return &v.state @@ -1034,7 +1034,7 @@ func file_egress_v1_proto_init() { return nil } } - file_egress_v1_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + file_egress_v1_proto_msgTypes[1].Exporter = func(v any, i int) any { switch v := v.(*SpanData_EgressSpan); i { case 0: return &v.state @@ -1046,7 +1046,7 @@ func file_egress_v1_proto_init() { return nil } } - file_egress_v1_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + file_egress_v1_proto_msgTypes[2].Exporter = func(v any, i int) any { switch v := v.(*SpanData_SendSpan); i { case 0: return &v.state @@ -1058,7 +1058,7 @@ func file_egress_v1_proto_init() { return nil } } - file_egress_v1_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + file_egress_v1_proto_msgTypes[3].Exporter = func(v any, i int) any { switch v := v.(*SpanData_TransactionEvent); i { case 0: return &v.state @@ -1070,7 +1070,7 @@ func file_egress_v1_proto_init() { return nil } } - file_egress_v1_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + file_egress_v1_proto_msgTypes[4].Exporter = func(v any, i int) any { switch v := v.(*SpanData_TransactionEvent_Xid); i { case 0: return &v.state @@ -1082,7 +1082,7 @@ func file_egress_v1_proto_init() { return nil } } - file_egress_v1_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + file_egress_v1_proto_msgTypes[5].Exporter = func(v any, i int) any { switch v := v.(*SpanData_TransactionEvent_LocalTransactionId); i { case 0: return &v.state @@ -1095,15 +1095,15 @@ func file_egress_v1_proto_init() { } } } - file_egress_v1_proto_msgTypes[0].OneofWrappers = []interface{}{} - file_egress_v1_proto_msgTypes[1].OneofWrappers = []interface{}{ + file_egress_v1_proto_msgTypes[0].OneofWrappers = []any{} + file_egress_v1_proto_msgTypes[1].OneofWrappers = []any{ (*SpanData_EgressSpan_SendSpan)(nil), } - file_egress_v1_proto_msgTypes[2].OneofWrappers = []interface{}{ + file_egress_v1_proto_msgTypes[2].OneofWrappers = []any{ (*SpanData_SendSpan_QueueName)(nil), (*SpanData_SendSpan_TopicEndpointName)(nil), } - file_egress_v1_proto_msgTypes[3].OneofWrappers = []interface{}{ + file_egress_v1_proto_msgTypes[3].OneofWrappers = []any{ (*SpanData_TransactionEvent_Xid_)(nil), (*SpanData_TransactionEvent_LocalId)(nil), } diff --git a/receiver/solacereceiver/internal/model/receive/v1/receive_v1.pb.go b/receiver/solacereceiver/internal/model/receive/v1/receive_v1.pb.go index 0036839e2c5b..1304a7041ca4 100644 --- a/receiver/solacereceiver/internal/model/receive/v1/receive_v1.pb.go +++ b/receiver/solacereceiver/internal/model/receive/v1/receive_v1.pb.go @@ -1647,7 +1647,7 @@ func file_receive_v1_proto_rawDescGZIP() []byte { var file_receive_v1_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_receive_v1_proto_msgTypes = make([]protoimpl.MessageInfo, 7) -var file_receive_v1_proto_goTypes = []interface{}{ +var file_receive_v1_proto_goTypes = []any{ (SpanData_DeliveryMode)(0), // 0: solace.messaging.proto.broker.trace.receive.v1.SpanData.DeliveryMode (SpanData_TransactionEvent_Type)(0), // 1: solace.messaging.proto.broker.trace.receive.v1.SpanData.TransactionEvent.Type (SpanData_TransactionEvent_Initiator)(0), // 2: solace.messaging.proto.broker.trace.receive.v1.SpanData.TransactionEvent.Initiator @@ -1682,7 +1682,7 @@ func file_receive_v1_proto_init() { return } if !protoimpl.UnsafeEnabled { - file_receive_v1_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + file_receive_v1_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*SpanData); i { case 0: return &v.state @@ -1694,7 +1694,7 @@ func file_receive_v1_proto_init() { return nil } } - file_receive_v1_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + file_receive_v1_proto_msgTypes[2].Exporter = func(v any, i int) any { switch v := v.(*SpanData_UserPropertyValue); i { case 0: return &v.state @@ -1706,7 +1706,7 @@ func file_receive_v1_proto_init() { return nil } } - file_receive_v1_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + file_receive_v1_proto_msgTypes[3].Exporter = func(v any, i int) any { switch v := v.(*SpanData_TransactionEvent); i { case 0: return &v.state @@ -1718,7 +1718,7 @@ func file_receive_v1_proto_init() { return nil } } - file_receive_v1_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + file_receive_v1_proto_msgTypes[4].Exporter = func(v any, i int) any { switch v := v.(*SpanData_EnqueueEvent); i { case 0: return &v.state @@ -1730,7 +1730,7 @@ func file_receive_v1_proto_init() { return nil } } - file_receive_v1_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + file_receive_v1_proto_msgTypes[5].Exporter = func(v any, i int) any { switch v := v.(*SpanData_TransactionEvent_Xid); i { case 0: return &v.state @@ -1742,7 +1742,7 @@ func file_receive_v1_proto_init() { return nil } } - file_receive_v1_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + file_receive_v1_proto_msgTypes[6].Exporter = func(v any, i int) any { switch v := v.(*SpanData_TransactionEvent_LocalTransactionId); i { case 0: return &v.state @@ -1755,8 +1755,8 @@ func file_receive_v1_proto_init() { } } } - file_receive_v1_proto_msgTypes[0].OneofWrappers = []interface{}{} - file_receive_v1_proto_msgTypes[2].OneofWrappers = []interface{}{ + file_receive_v1_proto_msgTypes[0].OneofWrappers = []any{} + file_receive_v1_proto_msgTypes[2].OneofWrappers = []any{ (*SpanData_UserPropertyValue_NullValue)(nil), (*SpanData_UserPropertyValue_BoolValue)(nil), (*SpanData_UserPropertyValue_Uint8Value)(nil), @@ -1774,11 +1774,11 @@ func file_receive_v1_proto_init() { (*SpanData_UserPropertyValue_DoubleValue)(nil), (*SpanData_UserPropertyValue_DestinationValue)(nil), } - file_receive_v1_proto_msgTypes[3].OneofWrappers = []interface{}{ + file_receive_v1_proto_msgTypes[3].OneofWrappers = []any{ (*SpanData_TransactionEvent_Xid_)(nil), (*SpanData_TransactionEvent_LocalId)(nil), } - file_receive_v1_proto_msgTypes[4].OneofWrappers = []interface{}{ + file_receive_v1_proto_msgTypes[4].OneofWrappers = []any{ (*SpanData_EnqueueEvent_QueueName)(nil), (*SpanData_EnqueueEvent_TopicEndpointName)(nil), } diff --git a/receiver/solacereceiver/messaging_service_test.go b/receiver/solacereceiver/messaging_service_test.go index 2d93b556e7e6..be6d5b575d45 100644 --- a/receiver/solacereceiver/messaging_service_test.go +++ b/receiver/solacereceiver/messaging_service_test.go @@ -505,7 +505,7 @@ func TestAMQPSubstituteVariables(t *testing.T) { // testFunctionEquality will check that the pointer names are the same for the two functions. // It is not a perfect comparison but will perform well differentiating between anonymous // functions and the amqp named functinos -func testFunctionEquality(t *testing.T, f1, f2 interface{}) { +func testFunctionEquality(t *testing.T, f1, f2 any) { assert.True(t, (f1 == nil) == (f2 == nil)) if f1 == nil { return diff --git a/receiver/solacereceiver/observability_test.go b/receiver/solacereceiver/observability_test.go index c0a54d33dd87..95de0c6e3720 100644 --- a/receiver/solacereceiver/observability_test.go +++ b/receiver/solacereceiver/observability_test.go @@ -56,7 +56,7 @@ func TestRecordMetrics(t *testing.T) { } } -func validateMetric(t *testing.T, v *view.View, expected interface{}) { +func validateMetric(t *testing.T, v *view.View, expected any) { // hack to reset stats to 0 defer func() { view.Unregister(v) diff --git a/receiver/solacereceiver/receiver_test.go b/receiver/solacereceiver/receiver_test.go index 0e639ab6c61f..2dfd97be13bd 100644 --- a/receiver/solacereceiver/receiver_test.go +++ b/receiver/solacereceiver/receiver_test.go @@ -29,7 +29,7 @@ import ( func TestReceiveMessage(t *testing.T) { someError := errors.New("some error") - validateMetrics := func(receivedMsgVal, droppedMsgVal, fatalUnmarshalling, reportedSpan interface{}) func(t *testing.T, receiver *solaceTracesReceiver) { + validateMetrics := func(receivedMsgVal, droppedMsgVal, fatalUnmarshalling, reportedSpan any) func(t *testing.T, receiver *solaceTracesReceiver) { return func(t *testing.T, receiver *solaceTracesReceiver) { validateReceiverMetrics(t, receiver, receivedMsgVal, droppedMsgVal, fatalUnmarshalling, reportedSpan) } @@ -549,7 +549,7 @@ func newReceiver(t *testing.T) (*solaceTracesReceiver, *mockMessagingService, *m return receiver, service, unmarshaller } -func validateReceiverMetrics(t *testing.T, receiver *solaceTracesReceiver, receivedMsgVal, droppedMsgVal, fatalUnmarshalling, reportedSpan interface{}) { +func validateReceiverMetrics(t *testing.T, receiver *solaceTracesReceiver, receivedMsgVal, droppedMsgVal, fatalUnmarshalling, reportedSpan any) { validateMetric(t, receiver.metrics.views.receivedSpanMessages, receivedMsgVal) validateMetric(t, receiver.metrics.views.droppedSpanMessages, droppedMsgVal) validateMetric(t, receiver.metrics.views.fatalUnmarshallingErrors, fatalUnmarshalling) diff --git a/receiver/solacereceiver/unmarshaller_egress_test.go b/receiver/solacereceiver/unmarshaller_egress_test.go index 6376706d3e7b..40de4ada6c39 100644 --- a/receiver/solacereceiver/unmarshaller_egress_test.go +++ b/receiver/solacereceiver/unmarshaller_egress_test.go @@ -38,8 +38,8 @@ func TestEgressUnmarshallerMapResourceSpan(t *testing.T) { tests := []struct { name string spanData *egress_v1.SpanData - want map[string]interface{} - expectedUnmarshallingErrors interface{} + want map[string]any + expectedUnmarshallingErrors any }{ { name: "Maps All Fields When Present", @@ -48,7 +48,7 @@ func TestEgressUnmarshallerMapResourceSpan(t *testing.T) { MessageVpnName: &vpnName, SolosVersion: version, }, - want: map[string]interface{}{ + want: map[string]any{ "service.name": routerName, "service.instance.id": vpnName, "service.version": version, @@ -57,7 +57,7 @@ func TestEgressUnmarshallerMapResourceSpan(t *testing.T) { { name: "Does Not Map Fields When Not Present", spanData: &egress_v1.SpanData{}, - want: map[string]interface{}{ + want: map[string]any{ "service.version": "", "service.name": "", }, @@ -264,7 +264,7 @@ func TestEgressUnmarshallerEgressSpan(t *testing.T) { name string spanData *egress_v1.SpanData_EgressSpan want *ptrace.Span - expectedUnmarshallingErrors interface{} + expectedUnmarshallingErrors any } tests := []testCase{ { @@ -311,8 +311,8 @@ func TestEgressUnmarshallerEgressSpan(t *testing.T) { func TestEgressUnmarshallerSendSpanAttributes(t *testing.T) { // creates a base attribute map that additional data can be added to // does not include outcome or source. Attributes will override all fields in base - getSpan := func(attributes map[string]interface{}, name string) ptrace.Span { - base := map[string]interface{}{ + getSpan := func(attributes map[string]any, name string) ptrace.Span { + base := map[string]any{ "messaging.system": "SolacePubSub+", "messaging.operation": "send", "messaging.protocol": "MQTT", @@ -345,7 +345,7 @@ func TestEgressUnmarshallerSendSpanAttributes(t *testing.T) { name string spanData *egress_v1.SpanData_SendSpan want ptrace.Span - expectedUnmarshallingErrors interface{} + expectedUnmarshallingErrors any }{ { name: "With Queue source", @@ -354,7 +354,7 @@ func TestEgressUnmarshallerSendSpanAttributes(t *testing.T) { QueueName: "someQueue", }, }), - want: getSpan(map[string]interface{}{ + want: getSpan(map[string]any{ "messaging.source.name": "someQueue", "messaging.source.kind": "queue", }, "someQueue send"), @@ -366,7 +366,7 @@ func TestEgressUnmarshallerSendSpanAttributes(t *testing.T) { TopicEndpointName: "0123456789abcdef0123456789abcdeg", }, }), - want: getSpan(map[string]interface{}{ + want: getSpan(map[string]any{ "messaging.source.name": "0123456789abcdef0123456789abcdeg", "messaging.source.kind": "topic-endpoint", }, "0123456789abcdef0123456789abcdeg send"), @@ -378,7 +378,7 @@ func TestEgressUnmarshallerSendSpanAttributes(t *testing.T) { QueueName: "#P2P/QTMP/myQueue", }, }), - want: getSpan(map[string]interface{}{ + want: getSpan(map[string]any{ "messaging.source.name": "#P2P/QTMP/myQueue", "messaging.source.kind": "queue", }, "(anonymous) send"), @@ -390,7 +390,7 @@ func TestEgressUnmarshallerSendSpanAttributes(t *testing.T) { TopicEndpointName: "0123456789abcdef0123456789abcdef", }, }), - want: getSpan(map[string]interface{}{ + want: getSpan(map[string]any{ "messaging.source.name": "0123456789abcdef0123456789abcdef", "messaging.source.kind": "topic-endpoint", }, "(anonymous) send"), @@ -398,7 +398,7 @@ func TestEgressUnmarshallerSendSpanAttributes(t *testing.T) { { name: "With Unknown Endpoint source", spanData: getSendSpan(&egress_v1.SpanData_SendSpan{}), - want: getSpan(map[string]interface{}{}, "(unknown) send"), + want: getSpan(map[string]any{}, "(unknown) send"), expectedUnmarshallingErrors: 1, }, } @@ -425,7 +425,7 @@ func TestEgressUnmarshallerSendSpanAttributes(t *testing.T) { for outcomeKey, outcomeName := range outcomes { t.Run("With outcome "+outcomeName, func(t *testing.T) { u := newTestEgressV1Unmarshaller(t) - expected := getSpan(map[string]interface{}{ + expected := getSpan(map[string]any{ "messaging.source.name": "someQueue", "messaging.source.kind": "queue", "messaging.solace.send.outcome": outcomeName, @@ -449,7 +449,7 @@ func TestEgressUnmarshallerTransactionEvent(t *testing.T) { name string spanData *egress_v1.SpanData_TransactionEvent populateExpectedSpan func(span ptrace.Span) - unmarshallingErrors interface{} + unmarshallingErrors any }{ { // Local Transaction name: "Local Transaction Event", @@ -466,7 +466,7 @@ func TestEgressUnmarshallerTransactionEvent(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "commit", 123456789, map[string]interface{}{ + populateEvent(t, span, "commit", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "client", "messaging.solace.transaction_id": 12345, "messaging.solace.transacted_session_name": "my-session-name", @@ -489,7 +489,7 @@ func TestEgressUnmarshallerTransactionEvent(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "session_timeout", 123456789, map[string]interface{}{ + populateEvent(t, span, "session_timeout", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "client", "messaging.solace.transaction_id": 12345, "messaging.solace.transacted_session_name": "my-session-name", @@ -512,7 +512,7 @@ func TestEgressUnmarshallerTransactionEvent(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "rollback_only", 123456789, map[string]interface{}{ + populateEvent(t, span, "rollback_only", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "client", "messaging.solace.transaction_id": 12345, "messaging.solace.transacted_session_name": "my-session-name", @@ -535,7 +535,7 @@ func TestEgressUnmarshallerTransactionEvent(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "end", 123456789, map[string]interface{}{ + populateEvent(t, span, "end", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "administrator", "messaging.solace.transaction_xid": "0000007b-000814fe-804020100804020100", }) @@ -557,7 +557,7 @@ func TestEgressUnmarshallerTransactionEvent(t *testing.T) { ErrorDescription: &someErrorString, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "prepare", 123456789, map[string]interface{}{ + populateEvent(t, span, "prepare", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "broker", "messaging.solace.transaction_xid": "0000007b--", "messaging.solace.transaction_error_message": someErrorString, @@ -571,7 +571,7 @@ func TestEgressUnmarshallerTransactionEvent(t *testing.T) { Type: egress_v1.SpanData_TransactionEvent_Type(12345), }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "Unknown Transaction Event (12345)", 123456789, map[string]interface{}{ + populateEvent(t, span, "Unknown Transaction Event (12345)", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "client", }) }, @@ -586,7 +586,7 @@ func TestEgressUnmarshallerTransactionEvent(t *testing.T) { TransactionId: nil, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "rollback", 123456789, map[string]interface{}{ + populateEvent(t, span, "rollback", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "Unknown Transaction Initiator (12345)", }) }, diff --git a/receiver/solacereceiver/unmarshaller_receive.go b/receiver/solacereceiver/unmarshaller_receive.go index 1ad06ebe3b38..92484cd33314 100644 --- a/receiver/solacereceiver/unmarshaller_receive.go +++ b/receiver/solacereceiver/unmarshaller_receive.go @@ -358,7 +358,7 @@ func (u *brokerTraceReceiveUnmarshallerV1) unmarshalBaggage(toMap pcommon.Map, b // insertUserProperty will instert a user property value with the given key to an attribute if possible. // Since AttributeMap only supports int64 integer types, uint64 data may be misrepresented. -func (u *brokerTraceReceiveUnmarshallerV1) insertUserProperty(toMap pcommon.Map, key string, value interface{}) { +func (u *brokerTraceReceiveUnmarshallerV1) insertUserProperty(toMap pcommon.Map, key string, value any) { const ( // userPropertiesPrefixAttrKey is the key used to prefix all user properties userPropertiesAttrKeyPrefix = "messaging.solace.user_properties." diff --git a/receiver/solacereceiver/unmarshaller_receive_test.go b/receiver/solacereceiver/unmarshaller_receive_test.go index f0c02bc54648..2b09392594cc 100644 --- a/receiver/solacereceiver/unmarshaller_receive_test.go +++ b/receiver/solacereceiver/unmarshaller_receive_test.go @@ -25,8 +25,8 @@ func TestReceiveUnmarshallerMapResourceSpan(t *testing.T) { tests := []struct { name string spanData *receive_v1.SpanData - want map[string]interface{} - expectedUnmarshallingErrors interface{} + want map[string]any + expectedUnmarshallingErrors any }{ { name: "Maps All Fields When Present", @@ -35,7 +35,7 @@ func TestReceiveUnmarshallerMapResourceSpan(t *testing.T) { MessageVpnName: &vpnName, SolosVersion: version, }, - want: map[string]interface{}{ + want: map[string]any{ "service.name": routerName, "service.instance.id": vpnName, "service.version": version, @@ -44,7 +44,7 @@ func TestReceiveUnmarshallerMapResourceSpan(t *testing.T) { { name: "Does Not Map Fields When Not Present", spanData: &receive_v1.SpanData{}, - want: map[string]interface{}{ + want: map[string]any{ "service.version": "", "service.name": "", }, @@ -144,8 +144,8 @@ func TestReceiveUnmarshallerMapClientSpanAttributes(t *testing.T) { tests := []struct { name string spanData *receive_v1.SpanData - want map[string]interface{} - expectedUnmarshallingErrors interface{} + want map[string]any + expectedUnmarshallingErrors any }{ { name: "With All Valid Attributes", @@ -183,7 +183,7 @@ func TestReceiveUnmarshallerMapClientSpanAttributes(t *testing.T) { }, }, }, - want: map[string]interface{}{ + want: map[string]any{ "messaging.system": "SolacePubSub+", "messaging.operation": "receive", "messaging.protocol": "MQTT", @@ -239,7 +239,7 @@ func TestReceiveUnmarshallerMapClientSpanAttributes(t *testing.T) { "special_key": nil, }, }, - want: map[string]interface{}{ + want: map[string]any{ "messaging.system": "SolacePubSub+", "messaging.operation": "receive", "messaging.protocol": "MQTT", @@ -283,7 +283,7 @@ func TestReceiveUnmarshallerMapClientSpanAttributes(t *testing.T) { }, }, // we no longer expect the port when the IP is not present - want: map[string]interface{}{ + want: map[string]any{ "messaging.system": "SolacePubSub+", "messaging.operation": "receive", "messaging.protocol": "MQTT", @@ -321,7 +321,7 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { name string spanData *receive_v1.SpanData populateExpectedSpan func(span ptrace.Span) - unmarshallingErrors interface{} + unmarshallingErrors any }{ { // don't expect any events when none are present in the span data name: "No Events", @@ -340,7 +340,7 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "somequeue enqueue", 123456789, map[string]interface{}{ + populateEvent(t, span, "somequeue enqueue", 123456789, map[string]any{ "messaging.solace.destination_type": "queue", "messaging.solace.rejects_all_enqueues": false, "messaging.solace.partition_number": 345, @@ -360,7 +360,7 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "sometopic enqueue", 123456789, map[string]interface{}{ + populateEvent(t, span, "sometopic enqueue", 123456789, map[string]any{ "messaging.solace.destination_type": "topic-endpoint", "messaging.solace.enqueue_error_message": someErrorString, "messaging.solace.rejects_all_enqueues": true, @@ -382,11 +382,11 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "somequeue enqueue", 123456789, map[string]interface{}{ + populateEvent(t, span, "somequeue enqueue", 123456789, map[string]any{ "messaging.solace.destination_type": "queue", "messaging.solace.rejects_all_enqueues": false, }) - populateEvent(t, span, "sometopic enqueue", 2345678, map[string]interface{}{ + populateEvent(t, span, "sometopic enqueue", 2345678, map[string]any{ "messaging.solace.destination_type": "topic-endpoint", "messaging.solace.rejects_all_enqueues": false, }) @@ -422,7 +422,7 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "commit", 123456789, map[string]interface{}{ + populateEvent(t, span, "commit", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "client", "messaging.solace.transaction_id": 12345, "messaging.solace.transacted_session_name": "my-session-name", @@ -447,7 +447,7 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "end", 123456789, map[string]interface{}{ + populateEvent(t, span, "end", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "administrator", "messaging.solace.transaction_xid": "0000007b-000814fe-804020100804020100", }) @@ -471,7 +471,7 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "prepare", 123456789, map[string]interface{}{ + populateEvent(t, span, "prepare", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "broker", "messaging.solace.transaction_xid": "0000007b--", "messaging.solace.transaction_error_message": someErrorString, @@ -487,7 +487,7 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "Unknown Transaction Event (12345)", 123456789, map[string]interface{}{ + populateEvent(t, span, "Unknown Transaction Event (12345)", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "client", }) }, @@ -504,7 +504,7 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "rollback", 123456789, map[string]interface{}{ + populateEvent(t, span, "rollback", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "Unknown Transaction Initiator (12345)", }) }, @@ -538,15 +538,15 @@ func TestReceiveUnmarshallerEvents(t *testing.T) { }, }, populateExpectedSpan: func(span ptrace.Span) { - populateEvent(t, span, "somequeue enqueue", 123456789, map[string]interface{}{ + populateEvent(t, span, "somequeue enqueue", 123456789, map[string]any{ "messaging.solace.destination_type": "queue", "messaging.solace.rejects_all_enqueues": false, }) - populateEvent(t, span, "sometopic enqueue", 2345678, map[string]interface{}{ + populateEvent(t, span, "sometopic enqueue", 2345678, map[string]any{ "messaging.solace.destination_type": "topic-endpoint", "messaging.solace.rejects_all_enqueues": true, }) - populateEvent(t, span, "rollback_only", 123456789, map[string]interface{}{ + populateEvent(t, span, "rollback_only", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "client", "messaging.solace.transaction_id": 12345, "messaging.solace.transacted_session_name": "my-session-name", @@ -574,7 +574,7 @@ func TestReceiveUnmarshallerRGMID(t *testing.T) { name string in []byte expected string - numErr interface{} + numErr any }{ { name: "Valid RGMID", @@ -620,7 +620,7 @@ func TestReceiveUnmarshallerReceiveBaggageString(t *testing.T) { name: "Valid baggage", baggage: `someKey=someVal`, expected: func(m pcommon.Map) { - assert.NoError(t, m.FromRaw(map[string]interface{}{ + assert.NoError(t, m.FromRaw(map[string]any{ "messaging.solace.message.baggage.someKey": "someVal", })) }, @@ -629,7 +629,7 @@ func TestReceiveUnmarshallerReceiveBaggageString(t *testing.T) { name: "Valid baggage with properties", baggage: `someKey=someVal;someProp=someOtherThing,someOtherKey=someOtherVal;someProp=NewProp123;someOtherProp=AnotherProp192`, expected: func(m pcommon.Map) { - assert.NoError(t, m.FromRaw(map[string]interface{}{ + assert.NoError(t, m.FromRaw(map[string]any{ "messaging.solace.message.baggage.someKey": "someVal", "messaging.solace.message.baggage_metadata.someKey": "someProp=someOtherThing", "messaging.solace.message.baggage.someOtherKey": `someOtherVal`, @@ -668,7 +668,7 @@ func TestReceiveUnmarshallerReceiveBaggageString(t *testing.T) { func TestReceiveUnmarshallerInsertUserProperty(t *testing.T) { emojiVal := 0xf09f92a9 testCases := []struct { - data interface{} + data any expectedType pcommon.ValueType validate func(val pcommon.Value) }{ diff --git a/receiver/solacereceiver/unmarshaller_test.go b/receiver/solacereceiver/unmarshaller_test.go index 187194456c0e..d9dc765af76f 100644 --- a/receiver/solacereceiver/unmarshaller_test.go +++ b/receiver/solacereceiver/unmarshaller_test.go @@ -204,7 +204,7 @@ func TestSolaceMessageUnmarshallerUnmarshal(t *testing.T) { want: func() *ptrace.Traces { traces := ptrace.NewTraces() resource := traces.ResourceSpans().AppendEmpty() - populateAttributes(t, resource.Resource().Attributes(), map[string]interface{}{ + populateAttributes(t, resource.Resource().Attributes(), map[string]any{ "service.name": "someRouterName", "service.instance.id": "someVpnName", "service.version": "10.0.0", @@ -220,7 +220,7 @@ func TestSolaceMessageUnmarshallerUnmarshal(t *testing.T) { span.SetName("(topic) receive") span.Status().SetCode(ptrace.StatusCodeUnset) spanAttrs := span.Attributes() - populateAttributes(t, spanAttrs, map[string]interface{}{ + populateAttributes(t, spanAttrs, map[string]any{ "messaging.system": "SolacePubSub+", "messaging.operation": "receive", "messaging.protocol": "MQTT", @@ -247,15 +247,15 @@ func TestSolaceMessageUnmarshallerUnmarshal(t *testing.T) { "net.peer.port": int64(12345), "messaging.solace.user_properties.special_key": true, }) - populateEvent(t, span, "somequeue enqueue", 123456789, map[string]interface{}{ + populateEvent(t, span, "somequeue enqueue", 123456789, map[string]any{ "messaging.solace.destination_type": "queue", "messaging.solace.rejects_all_enqueues": false, }) - populateEvent(t, span, "sometopic enqueue", 2345678, map[string]interface{}{ + populateEvent(t, span, "sometopic enqueue", 2345678, map[string]any{ "messaging.solace.destination_type": "topic-endpoint", "messaging.solace.rejects_all_enqueues": false, }) - populateEvent(t, span, "session_timeout", 123456789, map[string]interface{}{ + populateEvent(t, span, "session_timeout", 123456789, map[string]any{ "messaging.solace.transaction_initiator": "client", "messaging.solace.transaction_id": 12345, "messaging.solace.transacted_session_name": "my-session-name", @@ -298,7 +298,7 @@ func TestSolaceMessageUnmarshallerUnmarshal(t *testing.T) { want: func() *ptrace.Traces { traces := ptrace.NewTraces() resource := traces.ResourceSpans().AppendEmpty() - populateAttributes(t, resource.Resource().Attributes(), map[string]interface{}{ + populateAttributes(t, resource.Resource().Attributes(), map[string]any{ "service.name": "someRouterName", "service.instance.id": "someVpnName", "service.version": "10.0.0", @@ -376,14 +376,14 @@ func compareSpans(t *testing.T, expected, actual ptrace.Span) { } } -func populateEvent(t *testing.T, span ptrace.Span, name string, timestamp uint64, attributes map[string]interface{}) { +func populateEvent(t *testing.T, span ptrace.Span, name string, timestamp uint64, attributes map[string]any) { spanEvent := span.Events().AppendEmpty() spanEvent.SetName(name) spanEvent.SetTimestamp(pcommon.Timestamp(timestamp)) populateAttributes(t, spanEvent.Attributes(), attributes) } -func populateAttributes(t *testing.T, attrMap pcommon.Map, attributes map[string]interface{}) { +func populateAttributes(t *testing.T, attrMap pcommon.Map, attributes map[string]any) { for key, val := range attributes { switch casted := val.(type) { case string: diff --git a/receiver/splunkhecreceiver/receiver.go b/receiver/splunkhecreceiver/receiver.go index 4e7ce883a91d..6f62bc6dcd8e 100644 --- a/receiver/splunkhecreceiver/receiver.go +++ b/receiver/splunkhecreceiver/receiver.go @@ -125,7 +125,7 @@ func newMetricsReceiver( WriteTimeout: defaultServerTimeout, }, obsrecv: obsrecv, - gzipReaderPool: &sync.Pool{New: func() interface{} { return new(gzip.Reader) }}, + gzipReaderPool: &sync.Pool{New: func() any { return new(gzip.Reader) }}, } return r, nil @@ -169,7 +169,7 @@ func newLogsReceiver( ReadHeaderTimeout: defaultServerTimeout, WriteTimeout: defaultServerTimeout, }, - gzipReaderPool: &sync.Pool{New: func() interface{} { return new(gzip.Reader) }}, + gzipReaderPool: &sync.Pool{New: func() any { return new(gzip.Reader) }}, obsrecv: obsrecv, } @@ -464,14 +464,14 @@ func (r *splunkReceiver) handleHealthReq(writer http.ResponseWriter, _ *http.Req _, _ = writer.Write([]byte(responseHecHealthy)) } -func isFlatJSONField(field interface{}) bool { +func isFlatJSONField(field any) bool { switch value := field.(type) { - case map[string]interface{}: + case map[string]any: return false - case []interface{}: + case []any: for _, v := range value { switch v.(type) { - case map[string]interface{}, []interface{}: + case map[string]any, []any: return false } } diff --git a/receiver/splunkhecreceiver/receiver_test.go b/receiver/splunkhecreceiver/receiver_test.go index 271427d7e6cc..408c732afcf5 100644 --- a/receiver/splunkhecreceiver/receiver_test.go +++ b/receiver/splunkhecreceiver/receiver_test.go @@ -190,7 +190,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusOK, status) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "text": "Success", "code": float64(0), }, body) @@ -216,7 +216,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusBadRequest, status) - assert.Equal(t, map[string]interface{}{"code": float64(6), "text": "Invalid data format"}, body) + assert.Equal(t, map[string]any{"code": float64(6), "text": "Invalid data format"}, body) }, }, { @@ -227,7 +227,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusBadRequest, status) - assert.Equal(t, map[string]interface{}{"code": float64(5), "text": "No data"}, body) + assert.Equal(t, map[string]any{"code": float64(5), "text": "No data"}, body) }, }, { @@ -240,7 +240,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusBadRequest, status) - assert.Equal(t, map[string]interface{}{"code": float64(6), "text": "Invalid data format"}, body) + assert.Equal(t, map[string]any{"code": float64(6), "text": "Invalid data format"}, body) }, }, { @@ -255,7 +255,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusBadRequest, status) - assert.Equal(t, map[string]interface{}{"code": float64(12), "text": "Event field is required"}, body) + assert.Equal(t, map[string]any{"code": float64(12), "text": "Event field is required"}, body) }, }, { @@ -270,7 +270,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusBadRequest, status) - assert.Equal(t, map[string]interface{}{"code": float64(13), "text": "Event field cannot be blank"}, body) + assert.Equal(t, map[string]any{"code": float64(13), "text": "Event field cannot be blank"}, body) }, }, { @@ -283,7 +283,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusOK, status) - assert.Equal(t, map[string]interface{}{"code": float64(0), "text": "Success"}, body) + assert.Equal(t, map[string]any{"code": float64(0), "text": "Success"}, body) }, assertSink: func(t *testing.T, sink *consumertest.LogsSink) { assert.Equal(t, 1, len(sink.AllLogs())) @@ -302,7 +302,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusOK, status) - assert.Equal(t, map[string]interface{}{"code": float64(0), "text": "Success"}, body) + assert.Equal(t, map[string]any{"code": float64(0), "text": "Success"}, body) }, assertSink: func(t *testing.T, sink *consumertest.LogsSink) { assert.Equal(t, 0, len(sink.AllLogs())) @@ -329,7 +329,7 @@ func Test_splunkhecReceiver_handleReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusOK, status) - assert.Equal(t, map[string]interface{}{"code": float64(0), "text": "Success"}, body) + assert.Equal(t, map[string]any{"code": float64(0), "text": "Success"}, body) }, }, { @@ -744,7 +744,7 @@ func Test_Logs_splunkhecReceiver_IndexSourceTypePassthrough(t *testing.T) { var body any assert.NoError(t, json.Unmarshal(respBytes, &body)) assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "text": "Success", "code": float64(0), }, body) @@ -842,7 +842,7 @@ func Test_Metrics_splunkhecReceiver_IndexSourceTypePassthrough(t *testing.T) { var body any assert.NoError(t, json.Unmarshal(respBytes, &body)) assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "text": "Success", "code": float64(0), }, body) @@ -860,7 +860,7 @@ func buildSplunkHecMetricsMsg(time float64, value int64, dimensions uint) *splun ev := &splunk.Event{ Time: time, Event: "metric", - Fields: map[string]interface{}{ + Fields: map[string]any{ "metric_name:foo": value, }, } @@ -875,7 +875,7 @@ func buildSplunkHecMsg(time float64, dimensions uint) *splunk.Event { ev := &splunk.Event{ Time: time, Event: "foo", - Fields: map[string]interface{}{}, + Fields: map[string]any{}, Index: "myindex", SourceType: "custom:sourcetype", } @@ -969,7 +969,7 @@ func Test_splunkhecReceiver_handleRawReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusBadRequest, status) - assert.Equal(t, map[string]interface{}{"code": float64(5), "text": "No data"}, body) + assert.Equal(t, map[string]any{"code": float64(5), "text": "No data"}, body) }, }, @@ -1046,7 +1046,7 @@ func Test_splunkhecReceiver_handleRawReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusBadRequest, status) - assert.Equal(t, map[string]interface{}{"code": float64(6), "text": "Invalid data format"}, body) + assert.Equal(t, map[string]any{"code": float64(6), "text": "Invalid data format"}, body) }, }, { @@ -1065,7 +1065,7 @@ func Test_splunkhecReceiver_handleRawReq(t *testing.T) { }(), assertResponse: func(t *testing.T, status int, body any) { assert.Equal(t, http.StatusBadRequest, status) - assert.Equal(t, map[string]interface{}{"code": float64(6), "text": "Invalid data format"}, body) + assert.Equal(t, map[string]any{"code": float64(6), "text": "Invalid data format"}, body) }, }, } @@ -1125,28 +1125,28 @@ func Test_splunkhecreceiver_handle_nested_fields(t *testing.T) { t.Parallel() tests := []struct { name string - field interface{} + field any success bool }{ { name: "map", - field: map[string]interface{}{}, + field: map[string]any{}, success: false, }, { name: "flat_array", - field: []interface{}{1, 2, 3}, + field: []any{1, 2, 3}, success: true, }, { name: "nested_array", - field: []interface{}{1, []interface{}{1, 2}}, + field: []any{1, []any{1, 2}}, success: false, }, { name: "array_of_map", - field: []interface{}{ - map[string]interface{}{ + field: []any{ + map[string]any{ "key": "value", }, }, diff --git a/receiver/splunkhecreceiver/splunk_to_logdata.go b/receiver/splunkhecreceiver/splunk_to_logdata.go index 1ebeef6652a8..bb5b07b897f7 100644 --- a/receiver/splunkhecreceiver/splunk_to_logdata.go +++ b/receiver/splunkhecreceiver/splunk_to_logdata.go @@ -122,7 +122,7 @@ func appendSplunkMetadata(rl plog.ResourceLogs, attrs splunk.HecToOtelAttrs, hos } } -func convertToValue(logger *zap.Logger, src interface{}, dest pcommon.Value) error { +func convertToValue(logger *zap.Logger, src any, dest pcommon.Value) error { switch value := src.(type) { case nil: case string: @@ -133,9 +133,9 @@ func convertToValue(logger *zap.Logger, src interface{}, dest pcommon.Value) err dest.SetDouble(value) case bool: dest.SetBool(value) - case map[string]interface{}: + case map[string]any: return convertToAttributeMap(logger, value, dest) - case []interface{}: + case []any: return convertToSliceVal(logger, value, dest) default: logger.Debug("Unsupported value conversion", zap.Any("value", src)) @@ -145,7 +145,7 @@ func convertToValue(logger *zap.Logger, src interface{}, dest pcommon.Value) err return nil } -func convertToSliceVal(logger *zap.Logger, value []interface{}, dest pcommon.Value) error { +func convertToSliceVal(logger *zap.Logger, value []any, dest pcommon.Value) error { arr := dest.SetEmptySlice() for _, elt := range value { err := convertToValue(logger, elt, arr.AppendEmpty()) @@ -156,7 +156,7 @@ func convertToSliceVal(logger *zap.Logger, value []interface{}, dest pcommon.Val return nil } -func convertToAttributeMap(logger *zap.Logger, value map[string]interface{}, dest pcommon.Value) error { +func convertToAttributeMap(logger *zap.Logger, value map[string]any, dest pcommon.Value) error { attrMap := dest.SetEmptyMap() keys := make([]string, 0, len(value)) for k := range value { diff --git a/receiver/splunkhecreceiver/splunk_to_logdata_test.go b/receiver/splunkhecreceiver/splunk_to_logdata_test.go index 836963e37178..a207cea45683 100644 --- a/receiver/splunkhecreceiver/splunk_to_logdata_test.go +++ b/receiver/splunkhecreceiver/splunk_to_logdata_test.go @@ -50,7 +50,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "mysourcetype", Index: "myindex", Event: "value", - Fields: map[string]interface{}{ + Fields: map[string]any{ "foo": "bar", }, }, @@ -71,7 +71,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "mysourcetype", Index: "myindex", Event: 12.3, - Fields: map[string]interface{}{ + Fields: map[string]any{ "foo": "bar", }, }, @@ -93,8 +93,8 @@ func Test_SplunkHecToLogData(t *testing.T) { Source: "mysource", SourceType: "mysourcetype", Index: "myindex", - Event: []interface{}{"foo", "bar"}, - Fields: map[string]interface{}{ + Event: []any{"foo", "bar"}, + Fields: map[string]any{ "foo": "bar", }, }, @@ -120,8 +120,8 @@ func Test_SplunkHecToLogData(t *testing.T) { Source: "mysource", SourceType: "mysourcetype", Index: "myindex", - Event: map[string]interface{}{"foos": []interface{}{"foo", "bar", "foobar"}, "bool": false, "someInt": int64(12)}, - Fields: map[string]interface{}{ + Event: map[string]any{"foos": []any{"foo", "bar", "foobar"}, "bool": false, "someInt": int64(12)}, + Fields: map[string]any{ "foo": "bar", }, }, @@ -152,7 +152,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "mysourcetype", Index: "myindex", Event: "value", - Fields: map[string]interface{}{ + Fields: map[string]any{ "foo": "bar", }, }, @@ -172,7 +172,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "mysourcetype", Index: "myindex", Event: "value", - Fields: map[string]interface{}{ + Fields: map[string]any{ "foo": "bar", }, }, @@ -213,7 +213,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "1", Index: "1", Event: "Event-1", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value1", }, }, @@ -224,7 +224,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "2", Index: "2", Event: "Event-2", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value2", }, }, @@ -235,7 +235,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "1", Index: "1", Event: "Event-3", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value1", }, }, @@ -246,7 +246,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "2", Index: "2", Event: "Event-4", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value2", }, }, @@ -257,7 +257,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "1", Index: "2", Event: "Event-5", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value1-2", }, }, @@ -268,7 +268,7 @@ func Test_SplunkHecToLogData(t *testing.T) { SourceType: "2", Index: "1", Event: "Event-6", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value2-1", }, }, @@ -530,7 +530,7 @@ func TestConvertToValueFloat(t *testing.T) { func TestConvertToValueMap(t *testing.T) { value := pcommon.NewValueEmpty() - assert.NoError(t, convertToValue(zap.NewNop(), map[string]interface{}{"foo": "bar"}, value)) + assert.NoError(t, convertToValue(zap.NewNop(), map[string]any{"foo": "bar"}, value)) atts := pcommon.NewValueMap() attMap := atts.Map() attMap.PutStr("foo", "bar") @@ -539,7 +539,7 @@ func TestConvertToValueMap(t *testing.T) { func TestConvertToValueArray(t *testing.T) { value := pcommon.NewValueEmpty() - assert.NoError(t, convertToValue(zap.NewNop(), []interface{}{"foo"}, value)) + assert.NoError(t, convertToValue(zap.NewNop(), []any{"foo"}, value)) arrValue := pcommon.NewValueSlice() arr := arrValue.Slice() arr.AppendEmpty().SetStr("foo") @@ -551,9 +551,9 @@ func TestConvertToValueInvalid(t *testing.T) { } func TestConvertToValueInvalidInMap(t *testing.T) { - assert.Error(t, convertToValue(zap.NewNop(), map[string]interface{}{"foo": splunk.Event{}}, pcommon.NewValueEmpty())) + assert.Error(t, convertToValue(zap.NewNop(), map[string]any{"foo": splunk.Event{}}, pcommon.NewValueEmpty())) } func TestConvertToValueInvalidInArray(t *testing.T) { - assert.Error(t, convertToValue(zap.NewNop(), []interface{}{splunk.Event{}}, pcommon.NewValueEmpty())) + assert.Error(t, convertToValue(zap.NewNop(), []any{splunk.Event{}}, pcommon.NewValueEmpty())) } diff --git a/receiver/splunkhecreceiver/splunkhec_to_metricdata.go b/receiver/splunkhecreceiver/splunkhec_to_metricdata.go index b61d0fb0c727..e8586d088d6e 100644 --- a/receiver/splunkhecreceiver/splunkhec_to_metricdata.go +++ b/receiver/splunkhecreceiver/splunkhec_to_metricdata.go @@ -123,7 +123,7 @@ func convertTimestamp(sec float64) pcommon.Timestamp { } // Extract dimensions from the Splunk event fields to populate metric data point attributes. -func buildAttributes(dimensions map[string]interface{}) pcommon.Map { +func buildAttributes(dimensions map[string]any) pcommon.Map { attributes := pcommon.NewMap() attributes.EnsureCapacity(len(dimensions)) for key, val := range dimensions { diff --git a/receiver/splunkhecreceiver/splunkhec_to_metricdata_test.go b/receiver/splunkhecreceiver/splunkhec_to_metricdata_test.go index 6f0f820b6bb4..81e12717bbaa 100644 --- a/receiver/splunkhecreceiver/splunkhec_to_metricdata_test.go +++ b/receiver/splunkhecreceiver/splunkhec_to_metricdata_test.go @@ -32,7 +32,7 @@ func Test_splunkV2ToMetricsData(t *testing.T) { SourceType: "sourcetype", Index: "index", Event: "metrics", - Fields: map[string]interface{}{ + Fields: map[string]any{ "metric_name:single": int64Ptr(13), "k0": "v0", "k1": "v1", @@ -315,7 +315,7 @@ func TestGroupMetricsByResource(t *testing.T) { Source: "1", SourceType: "1", Index: "1", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value1", "metric_name:m1": int64(1), }, @@ -326,7 +326,7 @@ func TestGroupMetricsByResource(t *testing.T) { Source: "2", SourceType: "2", Index: "2", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value2", "metric_name:m2": int64(2), }, @@ -337,7 +337,7 @@ func TestGroupMetricsByResource(t *testing.T) { Source: "1", SourceType: "1", Index: "1", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value1", "metric_name:m1": int64(3), }, @@ -349,7 +349,7 @@ func TestGroupMetricsByResource(t *testing.T) { SourceType: "2", Index: "2", Event: "Event-4", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value2", "metric_name:m2": int64(4), }, @@ -360,7 +360,7 @@ func TestGroupMetricsByResource(t *testing.T) { Source: "2", SourceType: "1", Index: "2", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value1-2", "metric_name:m12": int64(5), }, @@ -372,7 +372,7 @@ func TestGroupMetricsByResource(t *testing.T) { SourceType: "2", Index: "1", Event: "Event-6", - Fields: map[string]interface{}{ + Fields: map[string]any{ "field": "value2-1", "metric_name:m21": int64(6), }, diff --git a/receiver/statsdreceiver/internal/transport/mock_reporter.go b/receiver/statsdreceiver/internal/transport/mock_reporter.go index 33d8ac8ce535..6e8b25818bed 100644 --- a/receiver/statsdreceiver/internal/transport/mock_reporter.go +++ b/receiver/statsdreceiver/internal/transport/mock_reporter.go @@ -33,7 +33,7 @@ func (m *MockReporter) OnMetricsProcessed(_ context.Context, _ int, _ error) { m.wgMetricsProcessed.Done() } -func (m *MockReporter) OnDebugf(_ string, _ ...interface{}) { +func (m *MockReporter) OnDebugf(_ string, _ ...any) { } // WaitAllOnMetricsProcessedCalls blocks until the number of expected calls diff --git a/receiver/statsdreceiver/internal/transport/server.go b/receiver/statsdreceiver/internal/transport/server.go index 7b3cdab6006f..5cc0474bf9de 100644 --- a/receiver/statsdreceiver/internal/transport/server.go +++ b/receiver/statsdreceiver/internal/transport/server.go @@ -61,5 +61,5 @@ type Reporter interface { // OnDebugf allows less structured reporting for debugging scenarios. OnDebugf( template string, - args ...interface{}) + args ...any) } diff --git a/receiver/statsdreceiver/reporter.go b/receiver/statsdreceiver/reporter.go index 7f02d8bc6d0e..3baa8a8975da 100644 --- a/receiver/statsdreceiver/reporter.go +++ b/receiver/statsdreceiver/reporter.go @@ -92,7 +92,7 @@ func (r *reporter) OnMetricsProcessed( r.obsrecv.EndMetricsOp(ctx, "statsd", numReceivedMessages, err) } -func (r *reporter) OnDebugf(template string, args ...interface{}) { +func (r *reporter) OnDebugf(template string, args ...any) { if r.logger.Check(zap.DebugLevel, "debug") != nil { r.sugaredLogger.Debugf(template, args...) } diff --git a/receiver/vcenterreceiver/internal/mockserver/client_mock.go b/receiver/vcenterreceiver/internal/mockserver/client_mock.go index 8a5a63347475..492e7b8642a4 100644 --- a/receiver/vcenterreceiver/internal/mockserver/client_mock.go +++ b/receiver/vcenterreceiver/internal/mockserver/client_mock.go @@ -30,7 +30,7 @@ type soapRequest struct { } type soapEnvelope struct { - Body map[string]interface{} `json:"Body"` + Body map[string]any `json:"Body"` } // MockServer has access to recorded SOAP responses and will serve them over http based off the scraper's API calls @@ -67,7 +67,7 @@ func MockServer(t *testing.T, useTLS bool) *httptest.Server { return httptest.NewServer(handlerFunc) } -func routeBody(t *testing.T, requestType string, body map[string]interface{}) ([]byte, error) { +func routeBody(t *testing.T, requestType string, body map[string]any) ([]byte, error) { switch requestType { case "RetrieveServiceContent": return loadResponse("service-content.xml") @@ -84,28 +84,28 @@ func routeBody(t *testing.T, requestType string, body map[string]interface{}) ([ return []byte{}, errNotFound } -func routeRetreiveProperties(t *testing.T, body map[string]interface{}) ([]byte, error) { - rp, ok := body["RetrieveProperties"].(map[string]interface{}) +func routeRetreiveProperties(t *testing.T, body map[string]any) ([]byte, error) { + rp, ok := body["RetrieveProperties"].(map[string]any) require.True(t, ok) - specSet := rp["specSet"].(map[string]interface{}) + specSet := rp["specSet"].(map[string]any) var objectSetArray = false - objectSet, ok := specSet["objectSet"].(map[string]interface{}) + objectSet, ok := specSet["objectSet"].(map[string]any) if !ok { objectSetArray = true } var propSetArray = false - propSet, ok := specSet["propSet"].(map[string]interface{}) + propSet, ok := specSet["propSet"].(map[string]any) if !ok { propSetArray = true } - var obj map[string]interface{} + var obj map[string]any var content string var contentType string if !objectSetArray { - obj = objectSet["obj"].(map[string]interface{}) + obj = objectSet["obj"].(map[string]any) content = obj["#content"].(string) contentType = obj["-type"].(string) } @@ -119,9 +119,9 @@ func routeRetreiveProperties(t *testing.T, body map[string]interface{}) ([]byte, case content == "domain-c8" && contentType == "ClusterComputeResource": if propSetArray { - pSet := specSet["propSet"].([]interface{}) + pSet := specSet["propSet"].([]any) for _, prop := range pSet { - spec := prop.(map[string]interface{}) + spec := prop.(map[string]any) specType := spec["type"].(string) if specType == "ResourcePool" { return loadResponse("resource-pool.xml") @@ -143,9 +143,9 @@ func routeRetreiveProperties(t *testing.T, body map[string]interface{}) ([]byte, case content == "group-h5" && contentType == "Folder": if propSetArray { - arr := specSet["propSet"].([]interface{}) + arr := specSet["propSet"].([]any) for _, i := range arr { - m, ok := i.(map[string]interface{}) + m, ok := i.(map[string]any) require.True(t, ok) if m["type"] == "ClusterComputeResource" { return loadResponse("host-cluster.xml") @@ -161,7 +161,7 @@ func routeRetreiveProperties(t *testing.T, body map[string]interface{}) ([]byte, return loadResponse("datastore-summary.xml") case contentType == "HostSystem": - if ps, ok := propSet["pathSet"].([]interface{}); ok { + if ps, ok := propSet["pathSet"].([]any); ok { for _, v := range ps { if v == "summary.hardware" { return loadResponse("host-properties.xml") @@ -198,7 +198,7 @@ func routeRetreiveProperties(t *testing.T, body map[string]interface{}) ([]byte, return loadResponse("vm-empty-folder.xml") case contentType == "ResourcePool": - if ps, ok := propSet["pathSet"].([]interface{}); ok { + if ps, ok := propSet["pathSet"].([]any); ok { for _, prop := range ps { if prop == "summary" { return loadResponse("resource-pool-summary.xml") @@ -206,16 +206,16 @@ func routeRetreiveProperties(t *testing.T, body map[string]interface{}) ([]byte, } } - if ss, ok := objectSet["selectSet"].(map[string]interface{}); ok && ss["path"] == "resourcePool" { + if ss, ok := objectSet["selectSet"].(map[string]any); ok && ss["path"] == "resourcePool" { return loadResponse("resource-pool-group.xml") } case objectSetArray: - objectArray := specSet["objectSet"].([]interface{}) + objectArray := specSet["objectSet"].([]any) for _, i := range objectArray { - m, ok := i.(map[string]interface{}) + m, ok := i.(map[string]any) require.True(t, ok) - mObj := m["obj"].(map[string](interface{})) + mObj := m["obj"].(map[string](any)) typeString := mObj["-type"] if typeString == "HostSystem" { return loadResponse("host-names.xml") @@ -226,11 +226,11 @@ func routeRetreiveProperties(t *testing.T, body map[string]interface{}) ([]byte, return []byte{}, errNotFound } -func routePerformanceQuery(t *testing.T, body map[string]interface{}) ([]byte, error) { - queryPerf := body["QueryPerf"].(map[string]interface{}) +func routePerformanceQuery(t *testing.T, body map[string]any) ([]byte, error) { + queryPerf := body["QueryPerf"].(map[string]any) require.NotNil(t, queryPerf) - querySpec := queryPerf["querySpec"].(map[string]interface{}) - entity := querySpec["entity"].(map[string]interface{}) + querySpec := queryPerf["querySpec"].(map[string]any) + entity := querySpec["entity"].(map[string]any) switch entity["-type"] { case "HostSystem": return loadResponse("host-performance-counters.xml") diff --git a/receiver/webhookeventreceiver/receiver.go b/receiver/webhookeventreceiver/receiver.go index 4c553d973c1f..f8720a10879c 100644 --- a/receiver/webhookeventreceiver/receiver.go +++ b/receiver/webhookeventreceiver/receiver.go @@ -75,7 +75,7 @@ func newLogsReceiver(params receiver.CreateSettings, cfg Config, consumer consum cfg: &cfg, logConsumer: consumer, obsrecv: obsrecv, - gzipPool: &sync.Pool{New: func() interface{} { return new(gzip.Reader) }}, + gzipPool: &sync.Pool{New: func() any { return new(gzip.Reader) }}, } return er, nil diff --git a/receiver/windowseventlogreceiver/receiver_windows_test.go b/receiver/windowseventlogreceiver/receiver_windows_test.go index 03adbcd47137..176954cd8091 100644 --- a/receiver/windowseventlogreceiver/receiver_windows_test.go +++ b/receiver/windowseventlogreceiver/receiver_windows_test.go @@ -115,16 +115,16 @@ func TestReadWindowsEventLogger(t *testing.T) { require.Equal(t, logMessage, body["message"]) eventData := body["event_data"] - eventDataMap, ok := eventData.(map[string]interface{}) + eventDataMap, ok := eventData.(map[string]any) require.True(t, ok) - require.Equal(t, map[string]interface{}{ - "data": []interface{}{map[string]interface{}{"": "Test log"}}, + require.Equal(t, map[string]any{ + "data": []any{map[string]any{"": "Test log"}}, }, eventDataMap) eventID := body["event_id"] require.NotNil(t, eventID) - eventIDMap, ok := eventID.(map[string]interface{}) + eventIDMap, ok := eventID.(map[string]any) require.True(t, ok) require.Equal(t, int64(10), eventIDMap["id"]) } diff --git a/receiver/zipkinreceiver/trace_receiver_test.go b/receiver/zipkinreceiver/trace_receiver_test.go index 8a4d4737f710..901cde948738 100644 --- a/receiver/zipkinreceiver/trace_receiver_test.go +++ b/receiver/zipkinreceiver/trace_receiver_test.go @@ -443,7 +443,7 @@ func TestReceiverConvertsStringsToTypes(t *testing.T) { td := next.AllTraces()[0] span := td.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0) - expected := map[string]interface{}{ + expected := map[string]any{ "cache_hit": true, "ping_count": int64(25), "timeout": 12.3, diff --git a/testbed/correctnesstests/metrics/results.go b/testbed/correctnesstests/metrics/results.go index da862246839d..c39fe1adb94b 100644 --- a/testbed/correctnesstests/metrics/results.go +++ b/testbed/correctnesstests/metrics/results.go @@ -39,7 +39,7 @@ func (r *results) Init(resultsDir string) { ) } -func (r *results) Add(_ string, rslt interface{}) { +func (r *results) Add(_ string, rslt any) { tr := rslt.(result) line := fmt.Sprintf( "%-40s|%-6s|%9d|\n", diff --git a/testbed/mockdatareceivers/mockawsxrayreceiver/trace_receiver.go b/testbed/mockdatareceivers/mockawsxrayreceiver/trace_receiver.go index f13507b4fed0..7fb89bb3d4ab 100644 --- a/testbed/mockdatareceivers/mockawsxrayreceiver/trace_receiver.go +++ b/testbed/mockdatareceivers/mockawsxrayreceiver/trace_receiver.go @@ -108,7 +108,7 @@ func (ar *MockAwsXrayReceiver) handleRequest(req *http.Request) error { log.Fatalln(err) } - var result map[string]interface{} + var result map[string]any if err = json.Unmarshal(body, &result); err != nil { log.Fatalln(err) @@ -140,13 +140,13 @@ func (ar *MockAwsXrayReceiver) Shutdown(context.Context) error { } func ToTraces(rawSeg []byte) (ptrace.Traces, error) { - var result map[string]interface{} + var result map[string]any err := json.Unmarshal(rawSeg, &result) if err != nil { return ptrace.Traces{}, err } - records, ok := result["TraceSegmentDocuments"].([]interface{}) + records, ok := result["TraceSegmentDocuments"].([]any) if !ok { panic("Not a slice") } diff --git a/testbed/testbed/mock_backend_test.go b/testbed/testbed/mock_backend_test.go index d5493cbafb00..f8614d01aea4 100644 --- a/testbed/testbed/mock_backend_test.go +++ b/testbed/testbed/mock_backend_test.go @@ -63,7 +63,7 @@ func TestGeneratorAndBackend(t *testing.T) { // WaitFor the specific condition for up to 10 seconds. Records a test error // if condition does not become true. -func WaitFor(t *testing.T, cond func() bool, errMsg ...interface{}) bool { +func WaitFor(t *testing.T, cond func() bool, errMsg ...any) bool { startTime := time.Now() // Start with 5 ms waiting interval between condition re-evaluation. diff --git a/testbed/testbed/results.go b/testbed/testbed/results.go index 505df5ec3e14..0e7b03599a50 100644 --- a/testbed/testbed/results.go +++ b/testbed/testbed/results.go @@ -18,7 +18,7 @@ type TestResultsSummary interface { // Init creates and open the file and write headers. Init(resultsDir string) // Add results for one test. - Add(testName string, result interface{}) + Add(testName string, result any) // Save the total results and close the file. Save() } @@ -90,7 +90,7 @@ func (r *PerformanceResults) Save() { } // Add results for one test. -func (r *PerformanceResults) Add(_ string, result interface{}) { +func (r *PerformanceResults) Add(_ string, result any) { testResult, ok := result.(*PerformanceTestResult) if !ok { return @@ -182,8 +182,8 @@ type TraceAssertionFailure struct { typeName string dataComboName string fieldPath string - expectedValue interface{} - actualValue interface{} + expectedValue any + actualValue any sumCount int } @@ -213,7 +213,7 @@ func (r *CorrectnessResults) Init(resultsDir string) { "----------------------------------------|------|-------:|---------:|-------------:|------------:|--------\n") } -func (r *CorrectnessResults) Add(_ string, result interface{}) { +func (r *CorrectnessResults) Add(_ string, result any) { testResult, ok := result.(*CorrectnessTestResult) if !ok { return diff --git a/testbed/testbed/test_case.go b/testbed/testbed/test_case.go index c765f334ed9e..24801797bca2 100644 --- a/testbed/testbed/test_case.go +++ b/testbed/testbed/test_case.go @@ -254,7 +254,7 @@ func (tc *TestCase) Sleep(d time.Duration) { // if time is out and condition does not become true. If error is signaled // while waiting the function will return false, but will not record additional // test error (we assume that signaled error is already recorded in indicateError()). -func (tc *TestCase) WaitForN(cond func() bool, duration time.Duration, errMsg interface{}) bool { +func (tc *TestCase) WaitForN(cond func() bool, duration time.Duration, errMsg any) bool { startTime := time.Now() // Start with 5 ms waiting interval between condition re-evaluation. @@ -285,7 +285,7 @@ func (tc *TestCase) WaitForN(cond func() bool, duration time.Duration, errMsg in } // WaitFor is like WaitForN but with a fixed duration of 10 seconds -func (tc *TestCase) WaitFor(cond func() bool, errMsg interface{}) bool { +func (tc *TestCase) WaitFor(cond func() bool, errMsg any) bool { return tc.WaitForN(cond, time.Second*10, errMsg) } diff --git a/testbed/tests/syslog_integration_test.go b/testbed/tests/syslog_integration_test.go index 512fb115f631..04195a0105c3 100644 --- a/testbed/tests/syslog_integration_test.go +++ b/testbed/tests/syslog_integration_test.go @@ -24,7 +24,7 @@ type expectedDataType struct { severityNumber plog.SeverityNumber severityText string timestamp pcommon.Timestamp - attributes map[string]interface{} + attributes map[string]any } func TestSyslogComplementaryRFC5424(t *testing.T) { @@ -34,11 +34,11 @@ func TestSyslogComplementaryRFC5424(t *testing.T) { severityNumber: 10, severityText: "notice", timestamp: 1065910455003000000, - attributes: map[string]interface{}{ + attributes: map[string]any{ "message": "Some message", "msg_id": "ID47", - "structured_data": map[string]interface{}{ - "exampleSDID@32473": map[string]interface{}{ + "structured_data": map[string]any{ + "exampleSDID@32473": map[string]any{ "iut": "3", }, }, @@ -54,7 +54,7 @@ func TestSyslogComplementaryRFC5424(t *testing.T) { severityNumber: 19, severityText: "alert", timestamp: 1065910455008000000, - attributes: map[string]interface{}{ + attributes: map[string]any{ "priority": int64(17), "version": int64(3), "facility": int64(2), @@ -72,7 +72,7 @@ func TestSyslogComplementaryRFC3164(t *testing.T) { timestamp: 1697062455000000000, severityNumber: 18, severityText: "crit", - attributes: map[string]interface{}{ + attributes: map[string]any{ "message": "'su root' failed for lonvick on /dev/pts/8", "hostname": "mymachine", "appname": "su", @@ -85,7 +85,7 @@ func TestSyslogComplementaryRFC3164(t *testing.T) { timestamp: 1697062455000000000, severityNumber: 17, severityText: "err", - attributes: map[string]interface{}{ + attributes: map[string]any{ "message": "-", "priority": int64(19), "facility": int64(2), @@ -148,7 +148,7 @@ service: // prepare data message := "" - expectedAttributes := []map[string]interface{}{} + expectedAttributes := []map[string]any{} expectedLogs := plog.NewLogs() rl := expectedLogs.ResourceLogs().AppendEmpty() lrs := rl.ScopeLogs().AppendEmpty().LogRecords() @@ -181,7 +181,7 @@ service: require.Equal(t, backend.ReceivedLogs[0].ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().Len(), len(expectedData)) // Clean received logs - attributes := []map[string]interface{}{} + attributes := []map[string]any{} lrs = backend.ReceivedLogs[0].ResourceLogs().At(0).ScopeLogs().At(0).LogRecords() for i := 0; i < lrs.Len(); i++ {