From 3f6e6e9bce8be0a823ed69cc92de2465af4a6977 Mon Sep 17 00:00:00 2001 From: Antoine Toulme Date: Wed, 5 Oct 2022 11:43:19 -0700 Subject: [PATCH] remove some exports from the smartagent receiver (#2077) * remove some exports from the smartagent receiver * rename go receiver output -> out --- .../receiver/smartagentreceiver/config.go | 4 +- .../smartagentreceiver/converter/event.go | 20 +-- .../receiver/smartagentreceiver/factory.go | 6 +- .../smartagentreceiver/factory_test.go | 12 +- .../receiver/smartagentreceiver/output.go | 140 +++++++++--------- .../smartagentreceiver/output_test.go | 40 ++--- .../smartagentreceiver/output_traces_test.go | 38 ++--- .../receiver/smartagentreceiver/receiver.go | 28 ++-- .../smartagentreceiver/receiver_test.go | 26 ++-- .../receiver/smartagentreceiver/reflect.go | 16 +- .../smartagentreceiver/reflect_test.go | 16 +- 11 files changed, 173 insertions(+), 173 deletions(-) diff --git a/internal/receiver/smartagentreceiver/config.go b/internal/receiver/smartagentreceiver/config.go index 98148e32bbd..a91886bc190 100644 --- a/internal/receiver/smartagentreceiver/config.go +++ b/internal/receiver/smartagentreceiver/config.go @@ -187,14 +187,14 @@ func setHostAndPortViaEndpoint(endpoint string, monitorConfig any) error { } if host != "" { - _, err := SetStructFieldIfZeroValue(monitorConfig, "Host", host) + _, err := setStructFieldIfZeroValue(monitorConfig, "Host", host) if err != nil { return fmt.Errorf("unable to set monitor Host field using Endpoint-derived value of %s: %w", host, err) } } if port != 0 { - _, err := SetStructFieldIfZeroValue(monitorConfig, "Port", port) + _, err := setStructFieldIfZeroValue(monitorConfig, "Port", port) if err != nil { return fmt.Errorf("unable to set monitor Port field using Endpoint-derived value of %d: %w", port, err) } diff --git a/internal/receiver/smartagentreceiver/converter/event.go b/internal/receiver/smartagentreceiver/converter/event.go index b2e2e037465..d0cb9a4a7c2 100644 --- a/internal/receiver/smartagentreceiver/converter/event.go +++ b/internal/receiver/smartagentreceiver/converter/event.go @@ -24,12 +24,12 @@ import ( ) const ( - // SFxEventCategoryKey key for splunk event category, - SFxEventCategoryKey = "com.splunk.signalfx.event_category" - // SFxEventPropertiesKey key for splunk event properties. - SFxEventPropertiesKey = "com.splunk.signalfx.event_properties" - // SFxEventType key for splunk event type - SFxEventType = "com.splunk.signalfx.event_type" + // sfxEventCategoryKey key for splunk event category, + sfxEventCategoryKey = "com.splunk.signalfx.event_category" + // sfxEventPropertiesKey key for splunk event properties. + sfxEventPropertiesKey = "com.splunk.signalfx.event_properties" + // sfxEventType key for splunk event type + sfxEventType = "com.splunk.signalfx.event_type" ) // eventToLog converts a SFx event to a plog.Logs entry suitable for consumption by LogConsumer. @@ -58,17 +58,17 @@ func sfxEventToPDataLogs(event *event.Event, logger *zap.Logger) plog.Logs { if event.Category == 0 { // This attribute must be present or SFx exporter will not know it's an event - attrs.PutEmpty(SFxEventCategoryKey) + attrs.PutEmpty(sfxEventCategoryKey) } else { - attrs.PutInt(SFxEventCategoryKey, int64(event.Category)) + attrs.PutInt(sfxEventCategoryKey, int64(event.Category)) } if event.EventType != "" { - attrs.PutString(SFxEventType, event.EventType) + attrs.PutString(sfxEventType, event.EventType) } if len(event.Properties) > 0 { - propMap := attrs.PutEmptyMap(SFxEventPropertiesKey) + propMap := attrs.PutEmptyMap(sfxEventPropertiesKey) propMap.EnsureCapacity(len(event.Properties)) for property, value := range event.Properties { diff --git a/internal/receiver/smartagentreceiver/factory.go b/internal/receiver/smartagentreceiver/factory.go index 32bd96bb728..517b5bc578d 100644 --- a/internal/receiver/smartagentreceiver/factory.go +++ b/internal/receiver/smartagentreceiver/factory.go @@ -31,10 +31,10 @@ var ( // Smart Agent receivers can be for metrics or logs (events). // We keep store of them to ensure the same instance is used for a given config. receiverStoreLock = sync.Mutex{} - receiverStore = map[*Config]*Receiver{} + receiverStore = map[*Config]*receiver{} ) -func getOrCreateReceiver(cfg config.Receiver, params component.ReceiverCreateSettings) (*Receiver, error) { +func getOrCreateReceiver(cfg config.Receiver, params component.ReceiverCreateSettings) (*receiver, error) { receiverStoreLock.Lock() defer receiverStoreLock.Unlock() receiverConfig := cfg.(*Config) @@ -46,7 +46,7 @@ func getOrCreateReceiver(cfg config.Receiver, params component.ReceiverCreateSet receiver, ok := receiverStore[receiverConfig] if !ok { - receiver = NewReceiver(params, *receiverConfig) + receiver = newReceiver(params, *receiverConfig) receiverStore[receiverConfig] = receiver } diff --git a/internal/receiver/smartagentreceiver/factory_test.go b/internal/receiver/smartagentreceiver/factory_test.go index 1fbc3b90c01..57d36131d09 100644 --- a/internal/receiver/smartagentreceiver/factory_test.go +++ b/internal/receiver/smartagentreceiver/factory_test.go @@ -139,9 +139,9 @@ func TestCreateMetricsThenLogsAndThenTracesReceiver(t *testing.T) { assert.Same(t, logsReceiver, tracesReceiver) assert.Same(t, metricsReceiver, receiverStore[cfg.(*Config)]) - assert.Same(t, nextMetricsConsumer, metricsReceiver.(*Receiver).nextMetricsConsumer) - assert.Same(t, nextLogsConsumer, metricsReceiver.(*Receiver).nextLogsConsumer) - assert.Same(t, nextTracesConsumer, metricsReceiver.(*Receiver).nextTracesConsumer) + assert.Same(t, nextMetricsConsumer, metricsReceiver.(*receiver).nextMetricsConsumer) + assert.Same(t, nextLogsConsumer, metricsReceiver.(*receiver).nextLogsConsumer) + assert.Same(t, nextTracesConsumer, metricsReceiver.(*receiver).nextTracesConsumer) } func TestCreateTracesThenLogsAndThenMetricsReceiver(t *testing.T) { @@ -169,7 +169,7 @@ func TestCreateTracesThenLogsAndThenMetricsReceiver(t *testing.T) { assert.Same(t, logsReceiver, tracesReceiver) assert.Same(t, metricsReceiver, receiverStore[cfg.(*Config)]) - assert.Same(t, nextMetricsConsumer, metricsReceiver.(*Receiver).nextMetricsConsumer) - assert.Same(t, nextLogsConsumer, metricsReceiver.(*Receiver).nextLogsConsumer) - assert.Same(t, nextTracesConsumer, metricsReceiver.(*Receiver).nextTracesConsumer) + assert.Same(t, nextMetricsConsumer, metricsReceiver.(*receiver).nextMetricsConsumer) + assert.Same(t, nextLogsConsumer, metricsReceiver.(*receiver).nextLogsConsumer) + assert.Same(t, nextTracesConsumer, metricsReceiver.(*receiver).nextTracesConsumer) } diff --git a/internal/receiver/smartagentreceiver/output.go b/internal/receiver/smartagentreceiver/output.go index 5322ab019da..5bf6e42e68f 100644 --- a/internal/receiver/smartagentreceiver/output.go +++ b/internal/receiver/smartagentreceiver/output.go @@ -35,11 +35,11 @@ import ( const internalTransport = "internal" -// Output is an implementation of a Smart Agent FilteringOutput that receives datapoints, events, and dimension updates +// output is an implementation of a Smart Agent FilteringOutput that receives datapoints, events, and dimension updates // from a configured monitor. It will forward all datapoints to the nextMetricsConsumer, all dimension updates to the // nextDimensionClients as determined by the associated items in Config.MetadataClients, and all events to the // nextLogsConsumer. -type Output struct { +type output struct { nextMetricsConsumer consumer.Metrics nextLogsConsumer consumer.Logs nextTracesConsumer consumer.Traces @@ -54,15 +54,15 @@ type Output struct { nextDimensionClients []metadata.MetadataExporter } -var _ types.Output = (*Output)(nil) -var _ types.FilteringOutput = (*Output)(nil) +var _ types.Output = (*output)(nil) +var _ types.FilteringOutput = (*output)(nil) -func NewOutput( +func newOutput( config Config, filtering *monitorFiltering, nextMetricsConsumer consumer.Metrics, nextLogsConsumer consumer.Logs, nextTracesConsumer consumer.Traces, host component.Host, params component.ReceiverCreateSettings, -) *Output { - return &Output{ +) *output { + return &output{ receiverID: config.ID(), nextMetricsConsumer: nextMetricsConsumer, nextLogsConsumer: nextLogsConsumer, @@ -162,77 +162,77 @@ func getLoneSFxExporter(host component.Host, exporterType collectorConfig.DataTy } -func (output *Output) AddDatapointExclusionFilter(filter dpfilters.DatapointFilter) { - output.logger.Debug("AddDatapointExclusionFilter has been called", zap.Any("filter", filter)) - output.monitorFiltering.AddDatapointExclusionFilter(filter) +func (out *output) AddDatapointExclusionFilter(filter dpfilters.DatapointFilter) { + out.logger.Debug("AddDatapointExclusionFilter has been called", zap.Any("filter", filter)) + out.monitorFiltering.AddDatapointExclusionFilter(filter) } -func (output *Output) EnabledMetrics() []string { - output.logger.Debug("EnabledMetrics has been called.") - return output.monitorFiltering.EnabledMetrics() +func (out *output) EnabledMetrics() []string { + out.logger.Debug("EnabledMetrics has been called.") + return out.monitorFiltering.EnabledMetrics() } -func (output *Output) HasEnabledMetricInGroup(group string) bool { - output.logger.Debug("HasEnabledMetricInGroup has been called", zap.String("group", group)) - return output.monitorFiltering.HasEnabledMetricInGroup(group) +func (out *output) HasEnabledMetricInGroup(group string) bool { + out.logger.Debug("HasEnabledMetricInGroup has been called", zap.String("group", group)) + return out.monitorFiltering.HasEnabledMetricInGroup(group) } -func (output *Output) HasAnyExtraMetrics() bool { - output.logger.Debug("HasAnyExtraMetrics has been called.") - return output.monitorFiltering.HasAnyExtraMetrics() +func (out *output) HasAnyExtraMetrics() bool { + out.logger.Debug("HasAnyExtraMetrics has been called.") + return out.monitorFiltering.HasAnyExtraMetrics() } -// Copy clones the Output to provide to child monitors with their own extraDimensions. -func (output *Output) Copy() types.Output { - output.logger.Debug("Copying Output", zap.Any("output", output)) - cp := *output - cp.extraDimensions = utils.CloneStringMap(output.extraDimensions) - cp.extraSpanTags = utils.CloneStringMap(output.extraSpanTags) - cp.defaultSpanTags = utils.CloneStringMap(output.defaultSpanTags) +// Copy clones the output to provide to child monitors with their own extraDimensions. +func (out *output) Copy() types.Output { + out.logger.Debug("Copying out", zap.Any("out", out)) + cp := *out + cp.extraDimensions = utils.CloneStringMap(out.extraDimensions) + cp.extraSpanTags = utils.CloneStringMap(out.extraSpanTags) + cp.defaultSpanTags = utils.CloneStringMap(out.defaultSpanTags) return &cp } -func (output *Output) SendDatapoints(datapoints ...*datapoint.Datapoint) { - if output.nextMetricsConsumer == nil { +func (out *output) SendDatapoints(datapoints ...*datapoint.Datapoint) { + if out.nextMetricsConsumer == nil { return } - ctx := output.reporter.StartMetricsOp(context.Background()) + ctx := out.reporter.StartMetricsOp(context.Background()) - datapoints = output.filterDatapoints(datapoints) + datapoints = out.filterDatapoints(datapoints) for _, dp := range datapoints { - // Output's extraDimensions take priority over datapoint's - dp.Dimensions = utils.MergeStringMaps(dp.Dimensions, output.extraDimensions) + // out's extraDimensions take priority over datapoint's + dp.Dimensions = utils.MergeStringMaps(dp.Dimensions, out.extraDimensions) } - metrics, err := output.translator.ToMetrics(datapoints) + metrics, err := out.translator.ToMetrics(datapoints) if err != nil { - output.logger.Error("error converting SFx datapoints to ptrace.Traces", zap.Error(err)) + out.logger.Error("error converting SFx datapoints to ptrace.Traces", zap.Error(err)) } numPoints := metrics.DataPointCount() - err = output.nextMetricsConsumer.ConsumeMetrics(context.Background(), metrics) - output.reporter.EndMetricsOp(ctx, typeStr, numPoints, err) + err = out.nextMetricsConsumer.ConsumeMetrics(context.Background(), metrics) + out.reporter.EndMetricsOp(ctx, typeStr, numPoints, err) } -func (output *Output) SendEvent(event *event.Event) { - if output.nextLogsConsumer == nil { +func (out *output) SendEvent(event *event.Event) { + if out.nextLogsConsumer == nil { return } - logs, err := output.translator.ToLogs(event) + logs, err := out.translator.ToLogs(event) if err != nil { - output.logger.Error("error converting SFx events to ptrace.Traces", zap.Error(err)) + out.logger.Error("error converting SFx events to ptrace.Traces", zap.Error(err)) } - err = output.nextLogsConsumer.ConsumeLogs(context.Background(), logs) + err = out.nextLogsConsumer.ConsumeLogs(context.Background(), logs) if err != nil { - output.logger.Debug("SendEvent has failed", zap.Error(err)) + out.logger.Debug("SendEvent has failed", zap.Error(err)) } } -func (output *Output) SendSpans(spans ...*trace.Span) { - if output.nextTracesConsumer == nil { +func (out *output) SendSpans(spans ...*trace.Span) { + if out.nextTracesConsumer == nil { return } @@ -241,71 +241,71 @@ func (output *Output) SendSpans(spans ...*trace.Span) { span.Tags = map[string]string{} } - for name, value := range output.defaultSpanTags { + for name, value := range out.defaultSpanTags { // If the tags are already set, don't override if _, ok := span.Tags[name]; !ok { span.Tags[name] = value } } - span.Tags = utils.MergeStringMaps(span.Tags, output.extraSpanTags) + span.Tags = utils.MergeStringMaps(span.Tags, out.extraSpanTags) } - traces, err := output.translator.ToTraces(spans) + traces, err := out.translator.ToTraces(spans) if err != nil { - output.logger.Error("error converting SFx spans to ptrace.Traces", zap.Error(err)) + out.logger.Error("error converting SFx spans to ptrace.Traces", zap.Error(err)) } - err = output.nextTracesConsumer.ConsumeTraces(context.Background(), traces) + err = out.nextTracesConsumer.ConsumeTraces(context.Background(), traces) if err != nil { - output.logger.Debug("SendSpans has failed", zap.Error(err)) + out.logger.Debug("SendSpans has failed", zap.Error(err)) } } -func (output *Output) SendDimensionUpdate(dimension *types.Dimension) { - if len(output.nextDimensionClients) == 0 { +func (out *output) SendDimensionUpdate(dimension *types.Dimension) { + if len(out.nextDimensionClients) == 0 { return } metadataUpdate := dimensionToMetadataUpdate(*dimension) - for _, consumer := range output.nextDimensionClients { + for _, consumer := range out.nextDimensionClients { err := consumer.ConsumeMetadata([]*metadata.MetadataUpdate{&metadataUpdate}) if err != nil { - output.logger.Debug("SendDimensionUpdate has failed", zap.Error(err)) + out.logger.Debug("SendDimensionUpdate has failed", zap.Error(err)) } } } -func (output *Output) AddExtraDimension(key, value string) { - output.logger.Debug("Adding extra dimension", zap.String("key", key), zap.String("value", value)) - output.extraDimensions[key] = value +func (out *output) AddExtraDimension(key, value string) { + out.logger.Debug("Adding extra dimension", zap.String("key", key), zap.String("value", value)) + out.extraDimensions[key] = value } -func (output *Output) RemoveExtraDimension(key string) { - output.logger.Debug("Removing extra dimension", zap.String("key", key)) - delete(output.extraDimensions, key) +func (out *output) RemoveExtraDimension(key string) { + out.logger.Debug("Removing extra dimension", zap.String("key", key)) + delete(out.extraDimensions, key) } -func (output *Output) AddExtraSpanTag(key, value string) { - output.extraSpanTags[key] = value +func (out *output) AddExtraSpanTag(key, value string) { + out.extraSpanTags[key] = value } -func (output *Output) RemoveExtraSpanTag(key string) { - delete(output.extraSpanTags, key) +func (out *output) RemoveExtraSpanTag(key string) { + delete(out.extraSpanTags, key) } -func (output *Output) AddDefaultSpanTag(key, value string) { - output.defaultSpanTags[key] = value +func (out *output) AddDefaultSpanTag(key, value string) { + out.defaultSpanTags[key] = value } -func (output *Output) RemoveDefaultSpanTag(key string) { - delete(output.defaultSpanTags, key) +func (out *output) RemoveDefaultSpanTag(key string) { + delete(out.defaultSpanTags, key) } -func (output *Output) filterDatapoints(datapoints []*datapoint.Datapoint) []*datapoint.Datapoint { +func (out *output) filterDatapoints(datapoints []*datapoint.Datapoint) []*datapoint.Datapoint { filteredDatapoints := make([]*datapoint.Datapoint, 0, len(datapoints)) for _, dp := range datapoints { - if output.monitorFiltering.filterSet == nil || !output.monitorFiltering.filterSet.Matches(dp) { + if out.monitorFiltering.filterSet == nil || !out.monitorFiltering.filterSet.Matches(dp) { filteredDatapoints = append(filteredDatapoints, dp) } } diff --git a/internal/receiver/smartagentreceiver/output_test.go b/internal/receiver/smartagentreceiver/output_test.go index cf3dbb4fc01..759c2bc6fa6 100644 --- a/internal/receiver/smartagentreceiver/output_test.go +++ b/internal/receiver/smartagentreceiver/output_test.go @@ -42,7 +42,7 @@ import ( func TestOutput(t *testing.T) { rcs := component.ReceiverCreateSettings{} rcs.Logger = zap.NewNop() - output := NewOutput( + output := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), @@ -72,7 +72,7 @@ func TestHasEnabledMetric(t *testing.T) { Groups: utils.StringSet("mem"), }, zap.NewNop()) require.NoError(t, err) - output := NewOutput( + output := newOutput( Config{}, monitorFiltering, consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -81,7 +81,7 @@ func TestHasEnabledMetric(t *testing.T) { // Empty metadata monitorFiltering, err = newMonitorFiltering(&saconfig.MonitorConfig{}, nil, zap.NewNop()) require.NoError(t, err) - output = NewOutput( + output = newOutput( Config{}, monitorFiltering, consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -104,7 +104,7 @@ func TestHasEnabledMetricInGroup(t *testing.T) { }, }, zap.NewNop()) require.NoError(t, err) - output := NewOutput( + output := newOutput( Config{}, monitorFiltering, consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -114,7 +114,7 @@ func TestHasEnabledMetricInGroup(t *testing.T) { // Empty metadata monitorFiltering, err = newMonitorFiltering(&saconfig.MonitorConfig{}, nil, zap.NewNop()) require.NoError(t, err) - output = NewOutput( + output = newOutput( Config{}, monitorFiltering, consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -122,33 +122,33 @@ func TestHasEnabledMetricInGroup(t *testing.T) { } func TestExtraDimensions(t *testing.T) { - output := NewOutput( + o := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) - assert.Empty(t, output.extraDimensions) + assert.Empty(t, o.extraDimensions) - output.RemoveExtraDimension("not_a_known_dimension_name") + o.RemoveExtraDimension("not_a_known_dimension_name") - output.AddExtraDimension("a_dimension_name", "a_value") - assert.Equal(t, "a_value", output.extraDimensions["a_dimension_name"]) + o.AddExtraDimension("a_dimension_name", "a_value") + assert.Equal(t, "a_value", o.extraDimensions["a_dimension_name"]) - cp, ok := output.Copy().(*Output) + cp, ok := o.Copy().(*output) require.True(t, ok) assert.Equal(t, "a_value", cp.extraDimensions["a_dimension_name"]) cp.RemoveExtraDimension("a_dimension_name") assert.Empty(t, cp.extraDimensions["a_dimension_name"]) - assert.Equal(t, "a_value", output.extraDimensions["a_dimension_name"]) + assert.Equal(t, "a_value", o.extraDimensions["a_dimension_name"]) cp.AddExtraDimension("another_dimension_name", "another_dimension_value") assert.Equal(t, "another_dimension_value", cp.extraDimensions["another_dimension_name"]) - assert.Empty(t, output.extraDimensions["another_dimension_name"]) + assert.Empty(t, o.extraDimensions["another_dimension_name"]) } func TestSendDimensionUpdate(t *testing.T) { mmc := mockMetadataClient{id: config.NewComponentID("signalfx")} - output := NewOutput( + output := newOutput( Config{}, fakeMonitorFiltering(), &mmc, consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -170,7 +170,7 @@ func TestSendDimensionUpdate(t *testing.T) { } func TestSendDimensionUpdateWithInvalidExporter(t *testing.T) { - output := NewOutput( + output := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -182,7 +182,7 @@ func TestSendDimensionUpdateWithInvalidExporter(t *testing.T) { func TestSendDimensionUpdateFromConfigMetadataExporters(t *testing.T) { mmc := mockMetadataClient{id: config.NewComponentID("mockmetadataexporter")} - output := NewOutput( + output := newOutput( Config{ DimensionClients: []string{"mockmetadataexporter", "exampleexporter", "metricsreceiver", "notareceiver", "notreal"}, }, @@ -206,7 +206,7 @@ func TestSendDimensionUpdateFromConfigMetadataExporters(t *testing.T) { func TestSendDimensionUpdateFromNextConsumerMetadataExporters(t *testing.T) { mmc := mockMetadataClient{id: config.NewComponentID("signalfx")} - output := NewOutput( + output := newOutput( Config{}, fakeMonitorFiltering(), &mmc, consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -223,7 +223,7 @@ func TestSendDimensionUpdateFromNextConsumerMetadataExporters(t *testing.T) { func TestSendEvent(t *testing.T) { mmc := mockMetadataClient{id: config.NewComponentID("signalfx")} - output := NewOutput( + output := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), &mmc, consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -252,7 +252,7 @@ func TestSendEvent(t *testing.T) { func TestDimensionClientDefaultsToSFxExporter(t *testing.T) { mmc := mockMetadataClient{id: config.NewComponentID("signalfx")} - output := NewOutput( + output := newOutput( Config{DimensionClients: nil}, fakeMonitorFiltering(), consumertest.NewNop(), @@ -274,7 +274,7 @@ func TestDimensionClientDefaultsToSFxExporter(t *testing.T) { func TestDimensionClientDefaultsRequiresLoneSFxExporter(t *testing.T) { mmc := mockMetadataClient{id: config.NewComponentID("signalfx")} - output := NewOutput( + output := newOutput( Config{DimensionClients: nil}, fakeMonitorFiltering(), consumertest.NewNop(), diff --git a/internal/receiver/smartagentreceiver/output_traces_test.go b/internal/receiver/smartagentreceiver/output_traces_test.go index 888573ce832..2d8dc9e3e55 100644 --- a/internal/receiver/smartagentreceiver/output_traces_test.go +++ b/internal/receiver/smartagentreceiver/output_traces_test.go @@ -28,7 +28,7 @@ import ( ) func TestSendSpansWithoutNextTracesConsumer(t *testing.T) { - output := NewOutput( + output := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), consumertest.NewNop(), nil, componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -37,58 +37,58 @@ func TestSendSpansWithoutNextTracesConsumer(t *testing.T) { } func TestExtraSpanTags(t *testing.T) { - output := NewOutput( + o := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) - assert.Empty(t, output.extraSpanTags) + assert.Empty(t, o.extraSpanTags) - output.RemoveExtraSpanTag("not_a_known_tag") + o.RemoveExtraSpanTag("not_a_known_tag") - output.AddExtraSpanTag("a_tag", "a_value") - assert.Equal(t, "a_value", output.extraSpanTags["a_tag"]) + o.AddExtraSpanTag("a_tag", "a_value") + assert.Equal(t, "a_value", o.extraSpanTags["a_tag"]) - cp, ok := output.Copy().(*Output) + cp, ok := o.Copy().(*output) require.True(t, ok) assert.Equal(t, "a_value", cp.extraSpanTags["a_tag"]) cp.RemoveExtraSpanTag("a_tag") assert.Empty(t, cp.extraSpanTags["a_tag"]) - assert.Equal(t, "a_value", output.extraSpanTags["a_tag"]) + assert.Equal(t, "a_value", o.extraSpanTags["a_tag"]) cp.AddExtraSpanTag("another_tag", "another_tag_value") assert.Equal(t, "another_tag_value", cp.extraSpanTags["another_tag"]) - assert.Empty(t, output.extraSpanTags["another_tag"]) + assert.Empty(t, o.extraSpanTags["another_tag"]) } func TestDefaultSpanTags(t *testing.T) { - output := NewOutput( + o := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), consumertest.NewNop(), consumertest.NewNop(), componenttest.NewNopHost(), newReceiverCreateSettings(), ) - assert.Empty(t, output.defaultSpanTags) + assert.Empty(t, o.defaultSpanTags) - output.RemoveDefaultSpanTag("not_a_known_tag") + o.RemoveDefaultSpanTag("not_a_known_tag") - output.AddDefaultSpanTag("a_tag", "a_value") - assert.Equal(t, "a_value", output.defaultSpanTags["a_tag"]) + o.AddDefaultSpanTag("a_tag", "a_value") + assert.Equal(t, "a_value", o.defaultSpanTags["a_tag"]) - cp, ok := output.Copy().(*Output) + cp, ok := o.Copy().(*output) require.True(t, ok) assert.Equal(t, "a_value", cp.defaultSpanTags["a_tag"]) cp.RemoveDefaultSpanTag("a_tag") assert.Empty(t, cp.defaultSpanTags["a_tag"]) - assert.Equal(t, "a_value", output.defaultSpanTags["a_tag"]) + assert.Equal(t, "a_value", o.defaultSpanTags["a_tag"]) cp.AddDefaultSpanTag("another_tag", "another_tag_value") assert.Equal(t, "another_tag_value", cp.defaultSpanTags["another_tag"]) - assert.Empty(t, output.defaultSpanTags["another_tag"]) + assert.Empty(t, o.defaultSpanTags["another_tag"]) } func TestSendSpansWithDefaultAndExtraSpanTags(t *testing.T) { tracesSink := consumertest.TracesSink{} - output := NewOutput( + output := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), consumertest.NewNop(), &tracesSink, componenttest.NewNopHost(), newReceiverCreateSettings(), ) @@ -181,7 +181,7 @@ func TestSendSpansWithConsumerError(t *testing.T) { err := fmt.Errorf("desired error") tracesConsumer := consumertest.NewErr(err) - output := NewOutput( + output := newOutput( Config{}, fakeMonitorFiltering(), consumertest.NewNop(), consumertest.NewNop(), tracesConsumer, componenttest.NewNopHost(), rcs, ) diff --git a/internal/receiver/smartagentreceiver/receiver.go b/internal/receiver/smartagentreceiver/receiver.go index 52e784ad10d..b6e9514eeb9 100644 --- a/internal/receiver/smartagentreceiver/receiver.go +++ b/internal/receiver/smartagentreceiver/receiver.go @@ -40,10 +40,10 @@ import ( "github.com/signalfx/splunk-otel-collector/internal/extension/smartagentextension" ) -const setOutputErrMsg = "unable to set Output field of monitor" +const setOutputErrMsg = "unable to set output field of monitor" const systemTypeKey = "system.type" -type Receiver struct { +type receiver struct { monitor any nextMetricsConsumer consumer.Metrics nextLogsConsumer consumer.Logs @@ -54,7 +54,7 @@ type Receiver struct { sync.Mutex } -var _ component.MetricsReceiver = (*Receiver)(nil) +var _ component.MetricsReceiver = (*receiver)(nil) var ( saConfig *saconfig.Config @@ -65,33 +65,33 @@ var ( configureLogrusOnce sync.Once ) -func NewReceiver(params component.ReceiverCreateSettings, config Config) *Receiver { - return &Receiver{ +func newReceiver(params component.ReceiverCreateSettings, config Config) *receiver { + return &receiver{ logger: params.Logger, params: params, config: &config, } } -func (r *Receiver) registerMetricsConsumer(metricsConsumer consumer.Metrics) { +func (r *receiver) registerMetricsConsumer(metricsConsumer consumer.Metrics) { r.Lock() defer r.Unlock() r.nextMetricsConsumer = metricsConsumer } -func (r *Receiver) registerLogsConsumer(logsConsumer consumer.Logs) { +func (r *receiver) registerLogsConsumer(logsConsumer consumer.Logs) { r.Lock() defer r.Unlock() r.nextLogsConsumer = logsConsumer } -func (r *Receiver) registerTracesConsumer(tracesConsumer consumer.Traces) { +func (r *receiver) registerTracesConsumer(tracesConsumer consumer.Traces) { r.Lock() defer r.Unlock() r.nextTracesConsumer = tracesConsumer } -func (r *Receiver) Start(_ context.Context, host component.Host) error { +func (r *receiver) Start(_ context.Context, host component.Host) error { // subsequent Start() invocations should noop if r.monitor != nil { return nil @@ -133,7 +133,7 @@ func (r *Receiver) Start(_ context.Context, host component.Host) error { return saconfig.CallConfigure(r.monitor, r.config.monitorConfig) } -func (r *Receiver) Shutdown(context.Context) error { +func (r *receiver) Shutdown(context.Context) error { if r.monitor == nil { return fmt.Errorf("smartagentreceiver's Shutdown() called before Start() or with invalid monitor state") } else if shutdownable, ok := (r.monitor).(monitors.Shutdownable); !ok { @@ -144,7 +144,7 @@ func (r *Receiver) Shutdown(context.Context) error { return nil } -func (r *Receiver) createMonitor(monitorType string, host component.Host) (monitor any, err error) { +func (r *receiver) createMonitor(monitorType string, host component.Host) (monitor any, err error) { // retrieve registered MonitorFactory from agent's registration store monitorFactory, ok := monitors.MonitorFactories[monitorType] if !ok { @@ -166,10 +166,10 @@ func (r *Receiver) createMonitor(monitorType string, host component.Host) (monit return nil, err } - output := NewOutput( + output := newOutput( *r.config, monitorFiltering, r.nextMetricsConsumer, r.nextLogsConsumer, r.nextTracesConsumer, host, r.params, ) - set, err := SetStructFieldWithExplicitType( + set, err := setStructFieldWithExplicitType( monitor, "Output", output, reflect.TypeOf((*types.Output)(nil)).Elem(), reflect.TypeOf((*types.FilteringOutput)(nil)).Elem(), @@ -212,7 +212,7 @@ func stripMonitorTypePrefix(s string) string { return s[idx+1:] } -func (r *Receiver) setUpSmartAgentConfigProvider(extensions map[config.ComponentID]component.Extension) { +func (r *receiver) setUpSmartAgentConfigProvider(extensions map[config.ComponentID]component.Extension) { // If smartagent extension is not configured, use the default config. f := smartagentextension.NewFactory() saConfig = &f.CreateDefaultConfig().(*smartagentextension.Config).Config diff --git a/internal/receiver/smartagentreceiver/receiver_test.go b/internal/receiver/smartagentreceiver/receiver_test.go index 84140742922..fe3c9eac661 100644 --- a/internal/receiver/smartagentreceiver/receiver_test.go +++ b/internal/receiver/smartagentreceiver/receiver_test.go @@ -94,7 +94,7 @@ func TestSmartAgentReceiver(t *testing.T) { t.Cleanup(cleanUp) cfg := newConfig("valid", "cpu", 10) consumer := new(consumertest.MetricsSink) - receiver := NewReceiver(newReceiverCreateSettings(), cfg) + receiver := newReceiver(newReceiverCreateSettings(), cfg) receiver.registerMetricsConsumer(consumer) require.NoError(t, receiver.Start(context.Background(), componenttest.NewNopHost())) @@ -105,7 +105,7 @@ func TestSmartAgentReceiver(t *testing.T) { require.True(t, isMonitor) monitorOutput := monitor.Output - _, isOutput := monitorOutput.(*Output) + _, isOutput := monitorOutput.(*output) assert.True(t, isOutput) assert.Eventuallyf(t, func() bool { @@ -184,7 +184,7 @@ func TestStripMonitorTypePrefix(t *testing.T) { func TestStartReceiverWithInvalidMonitorConfig(t *testing.T) { t.Cleanup(cleanUp) cfg := newConfig("invalid", "cpu", -123) - receiver := NewReceiver(newReceiverCreateSettings(), cfg) + receiver := newReceiver(newReceiverCreateSettings(), cfg) err := receiver.Start(context.Background(), componenttest.NewNopHost()) assert.EqualError(t, err, "config validation failed for \"smartagent/invalid\": intervalSeconds must be greater than 0s (-123 provided)", @@ -194,7 +194,7 @@ func TestStartReceiverWithInvalidMonitorConfig(t *testing.T) { func TestStartReceiverWithUnknownMonitorType(t *testing.T) { t.Cleanup(cleanUp) cfg := newConfig("invalid", "notamonitortype", 1) - receiver := NewReceiver(newReceiverCreateSettings(), cfg) + receiver := newReceiver(newReceiverCreateSettings(), cfg) err := receiver.Start(context.Background(), componenttest.NewNopHost()) assert.EqualError(t, err, "failed creating monitor \"notamonitortype\": unable to find MonitorFactory for \"notamonitortype\"", @@ -204,7 +204,7 @@ func TestStartReceiverWithUnknownMonitorType(t *testing.T) { func TestStartAndShutdown(t *testing.T) { t.Cleanup(cleanUp) cfg := newConfig("valid", "cpu", 1) - receiver := NewReceiver(newReceiverCreateSettings(), cfg) + receiver := newReceiver(newReceiverCreateSettings(), cfg) err := receiver.Start(context.Background(), componenttest.NewNopHost()) require.NoError(t, err) @@ -215,7 +215,7 @@ func TestStartAndShutdown(t *testing.T) { func TestOutOfOrderShutdownInvocations(t *testing.T) { t.Cleanup(cleanUp) cfg := newConfig("valid", "cpu", 1) - receiver := NewReceiver(newReceiverCreateSettings(), cfg) + receiver := newReceiver(newReceiverCreateSettings(), cfg) err := receiver.Shutdown(context.Background()) require.Error(t, err) @@ -227,14 +227,14 @@ func TestOutOfOrderShutdownInvocations(t *testing.T) { func TestMultipleInstacesOfSameMonitorType(t *testing.T) { t.Cleanup(cleanUp) cfg := newConfig("valid", "cpu", 1) - fstRcvr := NewReceiver(newReceiverCreateSettings(), cfg) + fstRcvr := newReceiver(newReceiverCreateSettings(), cfg) ctx := context.Background() mh := internaltest.NewAssertNoErrorHost(t) require.NoError(t, fstRcvr.Start(ctx, mh)) require.NoError(t, fstRcvr.Shutdown(ctx)) - sndRcvr := NewReceiver(newReceiverCreateSettings(), cfg) + sndRcvr := newReceiver(newReceiverCreateSettings(), cfg) assert.NoError(t, sndRcvr.Start(ctx, mh)) assert.NoError(t, sndRcvr.Shutdown(ctx)) } @@ -242,7 +242,7 @@ func TestMultipleInstacesOfSameMonitorType(t *testing.T) { func TestInvalidMonitorStateAtShutdown(t *testing.T) { t.Cleanup(cleanUp) cfg := newConfig("valid", "cpu", 1) - receiver := NewReceiver(newReceiverCreateSettings(), cfg) + receiver := newReceiver(newReceiverCreateSettings(), cfg) receiver.monitor = new(any) err := receiver.Shutdown(context.Background()) @@ -270,11 +270,11 @@ func TestConfirmStartingReceiverWithInvalidMonitorInstancesDoesntPanic(t *testin monitors.MonitorMetadatas["notarealmonitor"] = &monitors.Metadata{MonitorType: "notarealmonitor"} cfg := newConfig("invalid", "notarealmonitor", 123) - receiver := NewReceiver(newReceiverCreateSettings(), cfg) + receiver := newReceiver(newReceiverCreateSettings(), cfg) err := receiver.Start(context.Background(), componenttest.NewNopHost()) require.Error(tt, err) assert.Contains(tt, err.Error(), - fmt.Sprintf("failed creating monitor \"notarealmonitor\": unable to set Output field of monitor%s", test.expectedError), + fmt.Sprintf("failed creating monitor \"notarealmonitor\": unable to set output field of monitor%s", test.expectedError), ) }) } @@ -284,7 +284,7 @@ func TestFilteringNoMetadata(t *testing.T) { t.Cleanup(cleanUp) monitors.MonitorFactories["fakemonitor"] = func() any { return struct{}{} } cfg := newConfig("valid", "fakemonitor", 1) - receiver := NewReceiver(newReceiverCreateSettings(), cfg) + receiver := newReceiver(newReceiverCreateSettings(), cfg) err := receiver.Start(context.Background(), componenttest.NewNopHost()) require.EqualError(t, err, "failed creating monitor \"fakemonitor\": could not find monitor metadata of type fakemonitor") } @@ -296,7 +296,7 @@ func TestSmartAgentConfigProviderOverrides(t *testing.T) { logger := zap.New(observedLogger) rcs := newReceiverCreateSettings() rcs.Logger = logger - r := NewReceiver(rcs, cfg) + r := newReceiver(rcs, cfg) configs := getSmartAgentExtensionConfig(t) host := &mockHost{ diff --git a/internal/receiver/smartagentreceiver/reflect.go b/internal/receiver/smartagentreceiver/reflect.go index c63b42911fe..27a5bed706c 100644 --- a/internal/receiver/smartagentreceiver/reflect.go +++ b/internal/receiver/smartagentreceiver/reflect.go @@ -19,10 +19,10 @@ import ( "reflect" ) -// SetStructFieldWithExplicitType sets the first occurrence of a (potentially embedded) struct field w/ name fieldName and first occurring fieldType +// setStructFieldWithExplicitType sets the first occurrence of a (potentially embedded) struct field w/ name fieldName and first occurring fieldType // to desired value, if available. Returns true if successfully set, false otherwise. // Error contains if field undetected or if issues occur with reflect usage. -func SetStructFieldWithExplicitType(strukt any, fieldName string, value any, fieldTypes ...reflect.Type) (bool, error) { +func setStructFieldWithExplicitType(strukt any, fieldName string, value any, fieldTypes ...reflect.Type) (bool, error) { var err error for _, fieldType := range fieldTypes { var set bool @@ -34,16 +34,16 @@ func SetStructFieldWithExplicitType(strukt any, fieldName string, value any, fie return false, err } -// SetStructFieldIfZeroValue same as SetStructField() but only if first occurrence of the field is of zero value. -func SetStructFieldIfZeroValue(strukt any, fieldName string, value any) (bool, error) { +// setStructFieldIfZeroValue same as SetStructField() but only if first occurrence of the field is of zero value. +func setStructFieldIfZeroValue(strukt any, fieldName string, value any) (bool, error) { fieldType := reflect.TypeOf(value) return setStructField(strukt, fieldName, value, fieldType, true) } -// GetSettableStructFieldValue finds the first occurrence of a valid, settable field value from a potentially embedded struct +// getSettableStructFieldValue finds the first occurrence of a valid, settable field value from a potentially embedded struct // with a fieldName of desired type. // Based on https://github.com/signalfx/signalfx-agent/blob/731c2a0b5ff5ac324130453b02dd9cb7c912c0d5/pkg/utils/reflection.go#L36 -func GetSettableStructFieldValue(strukt any, fieldName string, fieldType reflect.Type) (*reflect.Value, error) { +func getSettableStructFieldValue(strukt any, fieldName string, fieldType reflect.Type) (*reflect.Value, error) { reflectedStruct := reflect.Indirect(reflect.ValueOf(strukt)) if reflectedStruct.IsValid() && reflectedStruct.Type().Kind() == reflect.Struct { fieldValue := reflectedStruct.FieldByName(fieldName) @@ -52,7 +52,7 @@ func GetSettableStructFieldValue(strukt any, fieldName string, fieldType reflect for i := 0; i < reflectedStruct.Type().NumField(); i++ { field := reflectedStruct.Type().Field(i) if field.Type.Kind() == reflect.Struct && field.Anonymous && reflectedStruct.Field(i).CanSet() { - candidate, _ := GetSettableStructFieldValue(reflectedStruct.Field(i).Interface(), fieldName, fieldType) + candidate, _ := getSettableStructFieldValue(reflectedStruct.Field(i).Interface(), fieldName, fieldType) if candidate != nil { valueCandidates = append(valueCandidates, *candidate) } @@ -71,7 +71,7 @@ func GetSettableStructFieldValue(strukt any, fieldName string, fieldType reflect } func setStructField(strukt any, fieldName string, value any, fieldType reflect.Type, onlyIfZero bool) (bool, error) { - valuePtr, err := GetSettableStructFieldValue(strukt, fieldName, fieldType) + valuePtr, err := getSettableStructFieldValue(strukt, fieldName, fieldType) if err != nil { return false, err } diff --git a/internal/receiver/smartagentreceiver/reflect_test.go b/internal/receiver/smartagentreceiver/reflect_test.go index a951b472e55..72a51ba787f 100644 --- a/internal/receiver/smartagentreceiver/reflect_test.go +++ b/internal/receiver/smartagentreceiver/reflect_test.go @@ -47,14 +47,14 @@ func TestGetSettableStructFieldValue(t *testing.T) { }, YetAnotherThing: "yet another thing", } - fieldValue, err := GetSettableStructFieldValue(envelope, "Thing", stringType) + fieldValue, err := getSettableStructFieldValue(envelope, "Thing", stringType) require.NoError(t, err) require.NotNil(t, fieldValue) require.Equal(t, "thing", fieldValue.String()) fieldValue.Set(reflect.ValueOf("something else")) require.Equal(t, "something else", envelope.Thing) - fieldValue, err = GetSettableStructFieldValue(envelope, "AnotherThing", stringType) + fieldValue, err = getSettableStructFieldValue(envelope, "AnotherThing", stringType) require.NoError(t, err) require.NotNil(t, fieldValue) require.Equal(t, "another thing", fieldValue.String()) @@ -62,11 +62,11 @@ func TestGetSettableStructFieldValue(t *testing.T) { require.Equal(t, "used to be 'another thing'", envelope.AnotherThing) // Envelope isn't addressable so its exported fields cannot be set - fieldValue, err = GetSettableStructFieldValue(*envelope, "YetAnotherThing", stringType) + fieldValue, err = getSettableStructFieldValue(*envelope, "YetAnotherThing", stringType) require.NoError(t, err) require.Nil(t, fieldValue) - fieldValue, err = GetSettableStructFieldValue(envelope, "YetAnotherThing", stringType) + fieldValue, err = getSettableStructFieldValue(envelope, "YetAnotherThing", stringType) require.NoError(t, err) require.NotNil(t, fieldValue) require.Equal(t, "yet another thing", fieldValue.String()) @@ -76,7 +76,7 @@ func TestGetSettableStructFieldValue(t *testing.T) { func TestSetStructFieldWithExplicitType(t *testing.T) { envelope := &Envelope{YetAnotherThing: "not zero value"} - set, err := SetStructFieldWithExplicitType( + set, err := setStructFieldWithExplicitType( envelope, "YetAnotherThing", "desired value", reflect.TypeOf(nil), reflect.TypeOf(1), stringType, reflect.TypeOf(struct{}{}), ) @@ -84,7 +84,7 @@ func TestSetStructFieldWithExplicitType(t *testing.T) { require.True(t, set) require.Equal(t, "desired value", envelope.YetAnotherThing) - set, err = SetStructFieldWithExplicitType( + set, err = setStructFieldWithExplicitType( envelope, "Thing", "another desired value", reflect.TypeOf(nil), reflect.TypeOf(1), stringType, reflect.TypeOf(struct{}{}), ) @@ -95,12 +95,12 @@ func TestSetStructFieldWithExplicitType(t *testing.T) { func TestSetStructFieldWithZeroValue(t *testing.T) { envelope := &Envelope{YetAnotherThing: "not zero value"} - set, err := SetStructFieldIfZeroValue(envelope, "Thing", "desired value") + set, err := setStructFieldIfZeroValue(envelope, "Thing", "desired value") require.NoError(t, err) require.True(t, set) require.Equal(t, "desired value", envelope.Thing) - set, err = SetStructFieldIfZeroValue(envelope, "YetAnotherThing", "should not take") + set, err = setStructFieldIfZeroValue(envelope, "YetAnotherThing", "should not take") require.NoError(t, err) require.False(t, set) require.Equal(t, "not zero value", envelope.YetAnotherThing)