[component] Add MustNewType constructor for component.Type (#9414)

**Description:** 

- Adds `component.MustNewType` to create a type. This function panics if
the type has invalid characters. Add similar functions
`component.MustNewID` and `component.MustNewIDWithName`.
- Adds `component.Type.String` to recover the string
- Use `component.MustNewType`, `component.MustNewID`,
`component.MustNewIDWithName` and `component.Type.String` everywhere in
this codebase. To do this I changed `component.Type` into an opaque
struct and checked for compile-time errors.

Some notes:

1. All components currently on core and contrib follow this rule. This
is still breaking for other components.
2. A future PR will change this into a struct, to actually validate this
(right now you can just do `component.Type("anything")` to bypass
validation). I want to do this in two steps to avoid breaking contrib
tests: we first introduce this function, and after that we change into a
struct.

**Link to tracking Issue:** Updates #9208
This commit is contained in:
Pablo Baeyens 2024-02-02 16:33:03 +00:00 committed by GitHub
parent 366573219e
commit 26c157e3bf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
96 changed files with 1602 additions and 1201 deletions

View File

@ -0,0 +1,26 @@
# Use this changelog template to create an entry for release notes.
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: breaking
# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
component: component
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Validate component.Type at creation and unmarshaling time.
# One or more tracking issues or pull requests related to the change
issues: [9208]
# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext: |
- A component.Type must start with an ASCII alphabetic character and can only contain ASCII alphanumeric characters and '_'.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [api]

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("file")
)
const (
Type = "file"
TracesStability = component.StabilityLevelBeta
LogsStability = component.StabilityLevelDevelopment
MetricsStability = component.StabilityLevelStable

View File

@ -365,8 +365,11 @@ import (
"go.opentelemetry.io/otel/trace"
)
var (
Type = component.MustNewType("foo")
)
const (
Type = "foo"
MetricsStability = component.StabilityLevelBeta
)
@ -399,8 +402,11 @@ import (
"go.opentelemetry.io/otel/trace"
)
var (
Type = component.MustNewType("foo")
)
const (
Type = "foo"
MetricsStability = component.StabilityLevelAlpha
)

View File

@ -8,8 +8,11 @@ import (
"go.opentelemetry.io/otel/trace"
)
var (
Type = component.MustNewType("{{ .Type }}")
)
const (
Type = "{{ .Type }}"
{{- range $stability, $signals := .Status.Stability }}
{{- range $signal := $signals }}
{{ toCamelCase $signal }}Stability = component.StabilityLevel{{ casesTitle $stability }}
@ -23,4 +26,4 @@ func Meter(settings component.TelemetrySettings) metric.Meter {
func Tracer(settings component.TelemetrySettings) trace.Tracer {
return settings.TracerProvider.Tracer("{{ .ScopeName }}")
}
}

View File

@ -6,6 +6,7 @@ package main
import (
"errors"
"fmt"
"regexp"
"go.uber.org/multierr"
@ -29,10 +30,20 @@ func (md *metadata) Validate() error {
return errs
}
// typeRegexp is used to validate the type of a component.
// A type must start with an ASCII alphabetic character and
// can only contain ASCII alphanumeric characters and '_'.
// This must be kept in sync with the regex in component/config.go.
var typeRegexp = regexp.MustCompile(`^[a-zA-Z][0-9a-zA-Z_]*$`)
func (md *metadata) validateType() error {
if md.Type == "" {
return errors.New("missing type")
}
if !typeRegexp.MatchString(md.Type) {
return fmt.Errorf("invalid character(s) in type %q", md.Type)
}
return nil
}

View File

@ -21,5 +21,5 @@ func TestNewNopHost(t *testing.T) {
nh.ReportFatalError(errors.New("TestError"))
assert.Nil(t, nh.GetExporters()) // nolint: staticcheck
assert.Nil(t, nh.GetExtensions())
assert.Nil(t, nh.GetFactory(component.KindReceiver, "test"))
assert.Nil(t, nh.GetFactory(component.KindReceiver, component.MustNewType("test")))
}

View File

@ -36,10 +36,10 @@ func TestPromChecker(t *testing.T) {
pc, err := newStubPromChecker()
require.NoError(t, err)
scraper := component.NewID("fakeScraper")
receiver := component.NewID("fakeReceiver")
processor := component.NewID("fakeProcessor")
exporter := component.NewID("fakeExporter")
scraper := component.MustNewID("fakeScraper")
receiver := component.MustNewID("fakeReceiver")
processor := component.MustNewID("fakeProcessor")
exporter := component.MustNewID("fakeExporter")
transport := "fakeTransport"
assert.NoError(t,

View File

@ -4,7 +4,9 @@
package component // import "go.opentelemetry.io/collector/component"
import (
"fmt"
"reflect"
"regexp"
"go.uber.org/multierr"
@ -110,6 +112,45 @@ func callValidateIfPossible(v reflect.Value) error {
// Type is the component type as it is used in the config.
type Type string
// String returns the string representation of the type.
func (t Type) String() string {
return string(t)
}
// typeRegexp is used to validate the type of a component.
// A type must start with an ASCII alphabetic character and
// can only contain ASCII alphanumeric characters and '_'.
// This must be kept in sync with the regex in cmd/mdatagen/validate.go.
var typeRegexp = regexp.MustCompile(`^[a-zA-Z][0-9a-zA-Z_]*$`)
// NewType creates a type. It returns an error if the type is invalid.
// A type must
// - have at least one character,
// - start with an ASCII alphabetic character and
// - can only contain ASCII alphanumeric characters and '_'.
func NewType(ty string) (Type, error) {
if len(ty) == 0 {
return Type(""), fmt.Errorf("id must not be empty")
}
if !typeRegexp.MatchString(ty) {
return Type(""), fmt.Errorf("invalid character(s) in type %q", ty)
}
return Type(ty), nil
}
// MustNewType creates a type. It panics if the type is invalid.
// A type must
// - have at least one character,
// - start with an ASCII alphabetic character and
// - can only contain ASCII alphanumeric characters and '_'.
func MustNewType(strType string) Type {
ty, err := NewType(strType)
if err != nil {
panic(err)
}
return ty
}
// DataType is a special Type that represents the data types supported by the collector. We currently support
// collecting metrics, traces and logs, this can expand in the future.
type DataType = Type

View File

@ -5,12 +5,16 @@ package component
import (
"errors"
"fmt"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var _ fmt.Stringer = (Type)("")
type configChildStruct struct {
Child errConfig
ChildPtr *errConfig
@ -194,3 +198,222 @@ func TestValidateConfig(t *testing.T) {
})
}
}
func TestNewType(t *testing.T) {
tests := []struct {
name string
shouldErr bool
}{
{name: "active_directory_ds"},
{name: "aerospike"},
{name: "alertmanager"},
{name: "alibabacloud_logservice"},
{name: "apache"},
{name: "apachespark"},
{name: "asapclient"},
{name: "attributes"},
{name: "awscloudwatch"},
{name: "awscloudwatchlogs"},
{name: "awscloudwatchmetrics"},
{name: "awscontainerinsightreceiver"},
{name: "awsecscontainermetrics"},
{name: "awsemf"},
{name: "awsfirehose"},
{name: "awskinesis"},
{name: "awsproxy"},
{name: "awss3"},
{name: "awsxray"},
{name: "azureblob"},
{name: "azuredataexplorer"},
{name: "azureeventhub"},
{name: "azuremonitor"},
{name: "basicauth"},
{name: "batch"},
{name: "bearertokenauth"},
{name: "bigip"},
{name: "carbon"},
{name: "cassandra"},
{name: "chrony"},
{name: "clickhouse"},
{name: "cloudflare"},
{name: "cloudfoundry"},
{name: "collectd"},
{name: "configschema"},
{name: "coralogix"},
{name: "couchdb"},
{name: "count"},
{name: "cumulativetodelta"},
{name: "datadog"},
{name: "dataset"},
{name: "db_storage"},
{name: "debug"},
{name: "deltatorate"},
{name: "demo"},
{name: "docker_observer"},
{name: "docker_stats"},
{name: "dynatrace"},
{name: "ecs_observer"},
{name: "ecs_task_observer"},
{name: "elasticsearch"},
{name: "exceptions"},
{name: "experimental_metricsgeneration"},
{name: "expvar"},
{name: "f5cloud"},
{name: "failover"},
{name: "file"},
{name: "filelog"},
{name: "filestats"},
{name: "file_storage"},
{name: "filter"},
{name: "flinkmetrics"},
{name: "fluentforward"},
{name: "forward"},
{name: "githubgen"},
{name: "gitprovider"},
{name: "golden"},
{name: "googlecloud"},
{name: "googlecloudpubsub"},
{name: "googlecloudspanner"},
{name: "googlemanagedprometheus"},
{name: "groupbyattrs"},
{name: "groupbytrace"},
{name: "haproxy"},
{name: "headers_setter"},
{name: "health_check"},
{name: "honeycombmarker"},
{name: "hostmetrics"},
{name: "host_observer"},
{name: "httpcheck"},
{name: "http_forwarder"},
{name: "iis"},
{name: "influxdb"},
{name: "instana"},
{name: "interval"},
{name: "jaeger"},
{name: "jaeger_encoding"},
{name: "jaegerremotesampling"},
{name: "jmx"},
{name: "journald"},
{name: "json_log_encoding"},
{name: "k8sattributes"},
{name: "k8s_cluster"},
{name: "k8s_events"},
{name: "k8sobjects"},
{name: "k8s_observer"},
{name: "kafka"},
{name: "kafkametrics"},
{name: "kinetica"},
{name: "kubeletstats"},
{name: "loadbalancing"},
{name: "logging"},
{name: "logicmonitor"},
{name: "logstransform"},
{name: "logzio"},
{name: "loki"},
{name: "mdatagen"},
{name: "memcached"},
{name: "memory_ballast"},
{name: "memory_limiter"},
{name: "metricstransform"},
{name: "mezmo"},
{name: "mongodb"},
{name: "mongodbatlas"},
{name: "mysql"},
{name: "namedpipe"},
{name: "nginx"},
{name: "nsxt"},
{name: "oauth2client"},
{name: "oidc"},
{name: "opamp"},
{name: "opampsupervisor"},
{name: "opencensus"},
{name: "opensearch"},
{name: "oracledb"},
{name: "osquery"},
{name: "otelarrow"},
{name: "otelcontribcol"},
{name: "oteltestbedcol"},
{name: "otlp"},
{name: "otlp_encoding"},
{name: "otlphttp"},
{name: "otlpjsonfile"},
{name: "ottl"},
{name: "podman_stats"},
{name: "postgresql"},
{name: "pprof"},
{name: "probabilistic_sampler"},
{name: "prometheus"},
{name: "prometheusremotewrite"},
{name: "prometheus_simple"},
{name: "pulsar"},
{name: "purefa"},
{name: "purefb"},
{name: "rabbitmq"},
{name: "receiver_creator"},
{name: "redaction"},
{name: "redis"},
{name: "remotetap"},
{name: "resource"},
{name: "resourcedetection"},
{name: "riak"},
{name: "routing"},
{name: "saphana"},
{name: "sapm"},
{name: "schema"},
{name: "sentry"},
{name: "servicegraph"},
{name: "signalfx"},
{name: "sigv4auth"},
{name: "skywalking"},
{name: "snmp"},
{name: "snowflake"},
{name: "solace"},
{name: "solarwindsapmsettings"},
{name: "span"},
{name: "spanmetrics"},
{name: "splunkenterprise"},
{name: "splunk_hec"},
{name: "sqlquery"},
{name: "sqlserver"},
{name: "sshcheck"},
{name: "statsd"},
{name: "sumologic"},
{name: "syslog"},
{name: "tail_sampling"},
{name: "tcplog"},
{name: "telemetrygen"},
{name: "tencentcloud_logservice"},
{name: "text_encoding"},
{name: "transform"},
{name: "udplog"},
{name: "vcenter"},
{name: "wavefront"},
{name: "webhookevent"},
{name: "windowseventlog"},
{name: "windowsperfcounters"},
{name: "zipkin"},
{name: "zipkin_encoding"},
{name: "zookeeper"},
{name: "zpages"},
{name: "", shouldErr: true},
{name: "contains spaces", shouldErr: true},
{name: "contains-dashes", shouldErr: true},
{name: "0startswithnumber", shouldErr: true},
{name: "contains/slash", shouldErr: true},
{name: "contains:colon", shouldErr: true},
{name: "contains#hash", shouldErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ty, err := NewType(tt.name)
if tt.shouldErr {
assert.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, tt.name, ty.String())
}
})
}
}

View File

@ -26,11 +26,23 @@ func NewID(typeVal Type) ID {
return ID{typeVal: typeVal}
}
// MustNewID builds a Type and returns a new ID with the given Type and empty name.
// See MustNewType to check the valid values of typeVal.
func MustNewID(typeVal string) ID {
return ID{typeVal: MustNewType(typeVal)}
}
// NewIDWithName returns a new ID with the given Type and name.
func NewIDWithName(typeVal Type, nameVal string) ID {
return ID{typeVal: typeVal, nameVal: nameVal}
}
// MustNewIDWithName builds a Type and returns a new ID with the given Type and name.
// See MustNewType to check the valid values of typeVal.
func MustNewIDWithName(typeVal string, nameVal string) ID {
return ID{typeVal: MustNewType(typeVal), nameVal: nameVal}
}
// Type returns the type of the component.
func (id ID) Type() Type {
return id.typeVal
@ -51,34 +63,41 @@ func (id ID) MarshalText() (text []byte, err error) {
func (id *ID) UnmarshalText(text []byte) error {
idStr := string(text)
items := strings.SplitN(idStr, typeAndNameSeparator, 2)
var typeStr, nameStr string
if len(items) >= 1 {
id.typeVal = Type(strings.TrimSpace(items[0]))
typeStr = strings.TrimSpace(items[0])
}
if len(items) == 1 && id.typeVal == "" {
if len(items) == 1 && typeStr == "" {
return errors.New("id must not be empty")
}
if id.typeVal == "" {
if typeStr == "" {
return fmt.Errorf("in %q id: the part before %s should not be empty", idStr, typeAndNameSeparator)
}
if len(items) > 1 {
// "name" part is present.
id.nameVal = strings.TrimSpace(items[1])
if id.nameVal == "" {
nameStr = strings.TrimSpace(items[1])
if nameStr == "" {
return fmt.Errorf("in %q id: the part after %s should not be empty", idStr, typeAndNameSeparator)
}
}
var err error
if id.typeVal, err = NewType(typeStr); err != nil {
return fmt.Errorf("in %q id: %w", idStr, err)
}
id.nameVal = nameStr
return nil
}
// String returns the ID string representation as "type[/name]" format.
func (id ID) String() string {
if id.nameVal == "" {
return string(id.typeVal)
return id.typeVal.String()
}
return string(id.typeVal) + typeAndNameSeparator + id.nameVal
return id.typeVal.String() + typeAndNameSeparator + id.nameVal
}

View File

@ -10,13 +10,14 @@ import (
)
func TestMarshalText(t *testing.T) {
id := NewIDWithName("test", "name")
id := NewIDWithName(MustNewType("test"), "name")
got, err := id.MarshalText()
assert.NoError(t, err)
assert.Equal(t, id.String(), string(got))
}
func TestUnmarshalText(t *testing.T) {
validType := MustNewType("valid_type")
var testCases = []struct {
idStr string
expectedErr bool
@ -24,15 +25,15 @@ func TestUnmarshalText(t *testing.T) {
}{
{
idStr: "valid_type",
expectedID: ID{typeVal: "valid_type", nameVal: ""},
expectedID: ID{typeVal: validType, nameVal: ""},
},
{
idStr: "valid_type/valid_name",
expectedID: ID{typeVal: "valid_type", nameVal: "valid_name"},
expectedID: ID{typeVal: validType, nameVal: "valid_name"},
},
{
idStr: " valid_type / valid_name ",
expectedID: ID{typeVal: "valid_type", nameVal: "valid_name"},
expectedID: ID{typeVal: validType, nameVal: "valid_name"},
},
{
idStr: "/valid_name",

View File

@ -13,6 +13,8 @@ import (
"go.opentelemetry.io/collector/extension/auth"
)
var mockID = component.MustNewID("mock")
func TestGetServer(t *testing.T) {
testCases := []struct {
desc string
@ -34,10 +36,10 @@ func TestGetServer(t *testing.T) {
t.Run(tC.desc, func(t *testing.T) {
// prepare
cfg := &Authentication{
AuthenticatorID: component.NewID("mock"),
AuthenticatorID: mockID,
}
ext := map[component.ID]component.Component{
component.NewID("mock"): tC.authenticator,
mockID: tC.authenticator,
}
authenticator, err := cfg.GetServerAuthenticator(ext)
@ -56,7 +58,7 @@ func TestGetServer(t *testing.T) {
func TestGetServerFails(t *testing.T) {
cfg := &Authentication{
AuthenticatorID: component.NewID("does-not-exist"),
AuthenticatorID: component.MustNewID("does_not_exist"),
}
authenticator, err := cfg.GetServerAuthenticator(map[component.ID]component.Component{})
@ -85,10 +87,10 @@ func TestGetClient(t *testing.T) {
t.Run(tC.desc, func(t *testing.T) {
// prepare
cfg := &Authentication{
AuthenticatorID: component.NewID("mock"),
AuthenticatorID: mockID,
}
ext := map[component.ID]component.Component{
component.NewID("mock"): tC.authenticator,
mockID: tC.authenticator,
}
authenticator, err := cfg.GetClientAuthenticator(ext)
@ -107,7 +109,7 @@ func TestGetClient(t *testing.T) {
func TestGetClientFails(t *testing.T) {
cfg := &Authentication{
AuthenticatorID: component.NewID("does-not-exist"),
AuthenticatorID: component.MustNewID("does_not_exist"),
}
authenticator, err := cfg.GetClientAuthenticator(map[component.ID]component.Component{})
assert.ErrorIs(t, err, errAuthenticatorNotFound)

View File

@ -50,8 +50,15 @@ func init() {
balancer.Register(testBalancerBuilder{})
}
var (
componentID = component.MustNewID("component")
testAuthID = component.MustNewID("testauth")
mockID = component.MustNewID("mock")
doesntExistID = component.MustNewID("doesntexist")
)
func TestDefaultGrpcClientSettings(t *testing.T) {
tt, err := componenttest.SetupTelemetry(component.NewID("component"))
tt, err := componenttest.SetupTelemetry(componentID)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
@ -66,7 +73,7 @@ func TestDefaultGrpcClientSettings(t *testing.T) {
}
func TestAllGrpcClientSettings(t *testing.T) {
tt, err := componenttest.SetupTelemetry(component.NewID("component"))
tt, err := componenttest.SetupTelemetry(componentID)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
@ -96,11 +103,11 @@ func TestAllGrpcClientSettings(t *testing.T) {
WaitForReady: true,
BalancerName: "round_robin",
Authority: "pseudo-authority",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("testauth")},
Auth: &configauth.Authentication{AuthenticatorID: testAuthID},
},
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("testauth"): &authtest.MockClient{},
testAuthID: &authtest.MockClient{},
},
},
},
@ -125,11 +132,11 @@ func TestAllGrpcClientSettings(t *testing.T) {
WaitForReady: true,
BalancerName: "round_robin",
Authority: "pseudo-authority",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("testauth")},
Auth: &configauth.Authentication{AuthenticatorID: testAuthID},
},
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("testauth"): &authtest.MockClient{},
testAuthID: &authtest.MockClient{},
},
},
},
@ -154,11 +161,11 @@ func TestAllGrpcClientSettings(t *testing.T) {
WaitForReady: true,
BalancerName: "configgrpc_balancer_test",
Authority: "pseudo-authority",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("testauth")},
Auth: &configauth.Authentication{AuthenticatorID: testAuthID},
},
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("testauth"): &authtest.MockClient{},
testAuthID: &authtest.MockClient{},
},
},
},
@ -223,11 +230,11 @@ func TestGrpcServerAuthSettings(t *testing.T) {
},
}
gss.Auth = &configauth.Authentication{
AuthenticatorID: component.NewID("mock"),
AuthenticatorID: mockID,
}
host := &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): auth.NewServer(),
mockID: auth.NewServer(),
},
}
srv, err := gss.ToServer(host, componenttest.NewNopTelemetrySettings())
@ -236,7 +243,7 @@ func TestGrpcServerAuthSettings(t *testing.T) {
}
func TestGRPCClientSettingsError(t *testing.T) {
tt, err := componenttest.SetupTelemetry(component.NewID("component"))
tt, err := componenttest.SetupTelemetry(componentID)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
@ -303,7 +310,7 @@ func TestGRPCClientSettingsError(t *testing.T) {
err: "failed to resolve authenticator \"doesntexist\": authenticator not found",
settings: ClientConfig{
Endpoint: "localhost:1234",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("doesntexist")},
Auth: &configauth.Authentication{AuthenticatorID: doesntExistID},
},
host: &mockHost{ext: map[component.ID]component.Component{}},
},
@ -311,7 +318,7 @@ func TestGRPCClientSettingsError(t *testing.T) {
err: "no extensions configuration available",
settings: ClientConfig{
Endpoint: "localhost:1234",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("doesntexist")},
Auth: &configauth.Authentication{AuthenticatorID: doesntExistID},
},
host: &mockHost{},
},
@ -359,7 +366,7 @@ func TestGRPCClientSettingsError(t *testing.T) {
}
func TestUseSecure(t *testing.T) {
tt, err := componenttest.SetupTelemetry(component.NewID("component"))
tt, err := componenttest.SetupTelemetry(componentID)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
@ -498,7 +505,7 @@ func TestGRPCServerSettings_ToListener_Error(t *testing.T) {
}
func TestHttpReception(t *testing.T) {
tt, err := componenttest.SetupTelemetry(component.NewID("component"))
tt, err := componenttest.SetupTelemetry(componentID)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
@ -650,7 +657,7 @@ func TestReceiveOnUnixDomainSocket(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping test on windows")
}
tt, err := componenttest.SetupTelemetry(component.NewID("component"))
tt, err := componenttest.SetupTelemetry(componentID)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
@ -879,7 +886,7 @@ func TestClientInfoInterceptors(t *testing.T) {
},
}
tt, err := componenttest.SetupTelemetry(component.NewID("component"))
tt, err := componenttest.SetupTelemetry(componentID)
require.NoError(t, err)
defer func() {
require.NoError(t, tt.Shutdown(context.Background()))

View File

@ -42,10 +42,17 @@ func (c *customRoundTripper) RoundTrip(_ *http.Request) (*http.Response, error)
return nil, nil
}
var (
testAuthID = component.MustNewID("testauth")
mockID = component.MustNewID("mock")
dummyID = component.MustNewID("dummy")
nonExistingID = component.MustNewID("nonexisting")
)
func TestAllHTTPClientSettings(t *testing.T) {
host := &mockHost{
ext: map[component.ID]component.Component{
component.NewID("testauth"): &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
testAuthID: &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
},
}
@ -187,7 +194,7 @@ func TestAllHTTPClientSettings(t *testing.T) {
func TestPartialHTTPClientSettings(t *testing.T) {
host := &mockHost{
ext: map[component.ID]component.Component{
component.NewID("testauth"): &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
testAuthID: &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
},
}
@ -329,7 +336,7 @@ func TestHTTPClientSettingsError(t *testing.T) {
err: "failed to resolve authenticator \"dummy\": authenticator not found",
settings: HTTPClientConfig{
Endpoint: "https://localhost:1234/v1/traces",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("dummy")},
Auth: &configauth.Authentication{AuthenticatorID: dummyID},
},
},
}
@ -357,7 +364,7 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
shouldErr: false,
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): &authtest.MockClient{
mockID: &authtest.MockClient{
ResultRoundTripper: &customRoundTripper{},
},
},
@ -367,12 +374,12 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
name: "with_auth_configuration_and_no_extension",
settings: HTTPClientConfig{
Endpoint: "localhost:1234",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("dummy")},
Auth: &configauth.Authentication{AuthenticatorID: dummyID},
},
shouldErr: true,
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
mockID: &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
},
},
},
@ -380,7 +387,7 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
name: "with_auth_configuration_and_no_extension_map",
settings: HTTPClientConfig{
Endpoint: "localhost:1234",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("dummy")},
Auth: &configauth.Authentication{AuthenticatorID: dummyID},
},
shouldErr: true,
host: componenttest.NewNopHost(),
@ -389,12 +396,12 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
name: "with_auth_configuration_has_extension",
settings: HTTPClientConfig{
Endpoint: "localhost:1234",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("mock")},
Auth: &configauth.Authentication{AuthenticatorID: mockID},
},
shouldErr: false,
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
mockID: &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
},
},
},
@ -402,13 +409,13 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
name: "with_auth_configuration_has_extension_and_headers",
settings: HTTPClientConfig{
Endpoint: "localhost:1234",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("mock")},
Auth: &configauth.Authentication{AuthenticatorID: mockID},
Headers: map[string]configopaque.String{"foo": "bar"},
},
shouldErr: false,
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
mockID: &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
},
},
},
@ -416,13 +423,13 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
name: "with_auth_configuration_has_extension_and_compression",
settings: HTTPClientConfig{
Endpoint: "localhost:1234",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("mock")},
Auth: &configauth.Authentication{AuthenticatorID: mockID},
Compression: configcompression.Gzip,
},
shouldErr: false,
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
mockID: &authtest.MockClient{ResultRoundTripper: &customRoundTripper{}},
},
},
},
@ -430,12 +437,12 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
name: "with_auth_configuration_has_err_extension",
settings: HTTPClientConfig{
Endpoint: "localhost:1234",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("mock")},
Auth: &configauth.Authentication{AuthenticatorID: mockID},
},
shouldErr: true,
host: &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): &authtest.MockClient{
mockID: &authtest.MockClient{
ResultRoundTripper: &customRoundTripper{}, MustError: true},
},
},
@ -862,13 +869,13 @@ func TestHttpCorsWithSettings(t *testing.T) {
AllowedOrigins: []string{"*"},
},
Auth: &configauth.Authentication{
AuthenticatorID: component.NewID("mock"),
AuthenticatorID: mockID,
},
}
host := &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): auth.NewServer(
mockID: auth.NewServer(
auth.WithServerAuthenticate(func(ctx context.Context, headers map[string][]string) (context.Context, error) {
return ctx, errors.New("Settings failed")
}),
@ -1128,13 +1135,13 @@ func TestServerAuth(t *testing.T) {
hss := HTTPServerConfig{
Endpoint: "localhost:0",
Auth: &configauth.Authentication{
AuthenticatorID: component.NewID("mock"),
AuthenticatorID: mockID,
},
}
host := &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): auth.NewServer(
mockID: auth.NewServer(
auth.WithServerAuthenticate(func(ctx context.Context, headers map[string][]string) (context.Context, error) {
authCalled = true
return ctx, nil
@ -1162,7 +1169,7 @@ func TestServerAuth(t *testing.T) {
func TestInvalidServerAuth(t *testing.T) {
hss := HTTPServerConfig{
Auth: &configauth.Authentication{
AuthenticatorID: component.NewID("non-existing"),
AuthenticatorID: nonExistingID,
},
}
@ -1176,12 +1183,12 @@ func TestFailedServerAuth(t *testing.T) {
hss := HTTPServerConfig{
Endpoint: "localhost:0",
Auth: &configauth.Authentication{
AuthenticatorID: component.NewID("mock"),
AuthenticatorID: mockID,
},
}
host := &mockHost{
ext: map[component.ID]component.Component{
component.NewID("mock"): auth.NewServer(
mockID: auth.NewServer(
auth.WithServerAuthenticate(func(ctx context.Context, headers map[string][]string) (context.Context, error) {
return ctx, errors.New("Settings failed")
}),

View File

@ -17,14 +17,16 @@ import (
"go.opentelemetry.io/collector/consumer/consumertest"
)
func TestNewFactoryNoOptions(t *testing.T) {
const typeStr = "test"
defaultCfg := struct{}{}
factory := NewFactory(typeStr, func() component.Config { return &defaultCfg })
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
var (
testType = component.MustNewType("test")
testID = component.MustNewIDWithName("type", "name")
)
testID := component.NewIDWithName("type", "name")
func TestNewFactoryNoOptions(t *testing.T) {
defaultCfg := struct{}{}
factory := NewFactory(testType, func() component.Config { return &defaultCfg })
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
_, err := factory.CreateTracesToTraces(context.Background(), CreateSettings{ID: testID}, &defaultCfg, nil)
assert.Equal(t, err, errDataTypes(testID, component.DataTypeTraces, component.DataTypeTraces))
@ -49,17 +51,14 @@ func TestNewFactoryNoOptions(t *testing.T) {
}
func TestNewFactoryWithSameTypes(t *testing.T) {
const typeStr = "test"
defaultCfg := struct{}{}
factory := NewFactory(typeStr, func() component.Config { return &defaultCfg },
factory := NewFactory(testType, func() component.Config { return &defaultCfg },
WithTracesToTraces(createTracesToTraces, component.StabilityLevelAlpha),
WithMetricsToMetrics(createMetricsToMetrics, component.StabilityLevelBeta),
WithLogsToLogs(createLogsToLogs, component.StabilityLevelUnmaintained))
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
testID := component.NewIDWithName("type", "name")
assert.Equal(t, component.StabilityLevelAlpha, factory.TracesToTracesStability())
_, err := factory.CreateTracesToTraces(context.Background(), CreateSettings{ID: testID}, &defaultCfg, nil)
assert.NoError(t, err)
@ -89,20 +88,17 @@ func TestNewFactoryWithSameTypes(t *testing.T) {
}
func TestNewFactoryWithTranslateTypes(t *testing.T) {
const typeStr = "test"
defaultCfg := struct{}{}
factory := NewFactory(typeStr, func() component.Config { return &defaultCfg },
factory := NewFactory(testType, func() component.Config { return &defaultCfg },
WithTracesToMetrics(createTracesToMetrics, component.StabilityLevelDevelopment),
WithTracesToLogs(createTracesToLogs, component.StabilityLevelAlpha),
WithMetricsToTraces(createMetricsToTraces, component.StabilityLevelBeta),
WithMetricsToLogs(createMetricsToLogs, component.StabilityLevelStable),
WithLogsToTraces(createLogsToTraces, component.StabilityLevelDeprecated),
WithLogsToMetrics(createLogsToMetrics, component.StabilityLevelUnmaintained))
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
testID := component.NewIDWithName("type", "name")
_, err := factory.CreateTracesToTraces(context.Background(), CreateSettings{ID: testID}, &defaultCfg, nil)
assert.Equal(t, err, errDataTypes(testID, component.DataTypeTraces, component.DataTypeTraces))
_, err = factory.CreateMetricsToMetrics(context.Background(), CreateSettings{ID: testID}, &defaultCfg, nil)
@ -136,9 +132,8 @@ func TestNewFactoryWithTranslateTypes(t *testing.T) {
}
func TestNewFactoryWithAllTypes(t *testing.T) {
const typeStr = "test"
defaultCfg := struct{}{}
factory := NewFactory(typeStr, func() component.Config { return &defaultCfg },
factory := NewFactory(testType, func() component.Config { return &defaultCfg },
WithTracesToTraces(createTracesToTraces, component.StabilityLevelAlpha),
WithTracesToMetrics(createTracesToMetrics, component.StabilityLevelDevelopment),
WithTracesToLogs(createTracesToLogs, component.StabilityLevelAlpha),
@ -148,7 +143,7 @@ func TestNewFactoryWithAllTypes(t *testing.T) {
WithLogsToTraces(createLogsToTraces, component.StabilityLevelDeprecated),
WithLogsToMetrics(createLogsToMetrics, component.StabilityLevelUnmaintained),
WithLogsToLogs(createLogsToLogs, component.StabilityLevelUnmaintained))
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
assert.Equal(t, component.StabilityLevelAlpha, factory.TracesToTracesStability())
@ -189,8 +184,8 @@ func TestMakeFactoryMap(t *testing.T) {
out map[component.Type]Factory
}
p1 := NewFactory("p1", nil)
p2 := NewFactory("p2", nil)
p1 := NewFactory(component.MustNewType("p1"), nil)
p2 := NewFactory(component.MustNewType("p2"), nil)
testCases := []testCase{
{
name: "different names",
@ -202,7 +197,7 @@ func TestMakeFactoryMap(t *testing.T) {
},
{
name: "same name",
in: []Factory{p1, p2, NewFactory("p1", nil)},
in: []Factory{p1, p2, NewFactory(component.MustNewType("p1"), nil)},
},
}
@ -223,9 +218,9 @@ func TestMakeFactoryMap(t *testing.T) {
func TestBuilder(t *testing.T) {
defaultCfg := struct{}{}
factories, err := MakeFactoryMap([]Factory{
NewFactory("err", nil),
NewFactory(component.MustNewType("err"), nil),
NewFactory(
"all",
component.MustNewType("all"),
func() component.Config { return &defaultCfg },
WithTracesToTraces(createTracesToTraces, component.StabilityLevelDevelopment),
WithTracesToMetrics(createTracesToMetrics, component.StabilityLevelDevelopment),
@ -247,28 +242,28 @@ func TestBuilder(t *testing.T) {
}{
{
name: "unknown",
id: component.NewID("unknown"),
id: component.MustNewID("unknown"),
err: func(_, _ component.DataType) string {
return "connector factory not available for: \"unknown\""
},
},
{
name: "err",
id: component.NewID("err"),
id: component.MustNewID("err"),
err: func(expType, rcvType component.DataType) string {
return fmt.Sprintf("connector \"err\" cannot connect from %s to %s: telemetry type is not supported", expType, rcvType)
},
},
{
name: "all",
id: component.NewID("all"),
id: component.MustNewID("all"),
err: func(_, _ component.DataType) string {
return ""
},
},
{
name: "all/named",
id: component.NewIDWithName("all", "named"),
id: component.MustNewIDWithName("all", "named"),
err: func(_, _ component.DataType) string {
return ""
},
@ -366,7 +361,7 @@ func TestBuilderMissingConfig(t *testing.T) {
defaultCfg := struct{}{}
factories, err := MakeFactoryMap([]Factory{
NewFactory(
"all",
component.MustNewType("all"),
func() component.Config { return &defaultCfg },
WithTracesToTraces(createTracesToTraces, component.StabilityLevelDevelopment),
WithTracesToMetrics(createTracesToMetrics, component.StabilityLevelDevelopment),
@ -383,7 +378,7 @@ func TestBuilderMissingConfig(t *testing.T) {
require.NoError(t, err)
bErr := NewBuilder(map[component.ID]component.Config{}, factories)
missingID := component.NewIDWithName("all", "missing")
missingID := component.MustNewIDWithName("all", "missing")
t2t, err := bErr.CreateTracesToTraces(context.Background(), createSettings(missingID), nil)
assert.EqualError(t, err, "connector \"all/missing\" is not configured")
@ -423,17 +418,17 @@ func TestBuilderMissingConfig(t *testing.T) {
}
func TestBuilderGetters(t *testing.T) {
factories, err := MakeFactoryMap([]Factory{NewFactory("foo", nil)}...)
factories, err := MakeFactoryMap([]Factory{NewFactory(component.MustNewType("foo"), nil)}...)
require.NoError(t, err)
cfgs := map[component.ID]component.Config{component.NewID("foo"): struct{}{}}
cfgs := map[component.ID]component.Config{component.MustNewID("foo"): struct{}{}}
b := NewBuilder(cfgs, factories)
assert.True(t, b.IsConfigured(component.NewID("foo")))
assert.False(t, b.IsConfigured(component.NewID("bar")))
assert.True(t, b.IsConfigured(component.MustNewID("foo")))
assert.False(t, b.IsConfigured(component.MustNewID("bar")))
assert.NotNil(t, b.Factory(component.NewID("foo").Type()))
assert.Nil(t, b.Factory(component.NewID("bar").Type()))
assert.NotNil(t, b.Factory(component.MustNewID("foo").Type()))
assert.Nil(t, b.Factory(component.MustNewID("bar").Type()))
}
var nopInstance = &nopConnector{

View File

@ -13,11 +13,12 @@ import (
"go.opentelemetry.io/collector/consumer/consumertest"
)
const typeStr = "nop"
var nopType = component.MustNewType("nop")
// NewNopCreateSettings returns a new nop settings for Create* functions.
func NewNopCreateSettings() connector.CreateSettings {
return connector.CreateSettings{
ID: component.NewID(nopType),
TelemetrySettings: componenttest.NewNopTelemetrySettings(),
BuildInfo: component.NewDefaultBuildInfo(),
}
@ -28,7 +29,7 @@ type nopConfig struct{}
// NewNopFactory returns a connector.Factory that constructs nop processors.
func NewNopFactory() connector.Factory {
return connector.NewFactory(
"nop",
nopType,
func() component.Config {
return &nopConfig{}
},
@ -93,8 +94,8 @@ func NewNopBuilder() *connector.Builder {
// Use a different ID than receivertest and exportertest to avoid ambiguous
// configuration scenarios. Ambiguous IDs are detected in the 'otelcol' package,
// but lower level packages such as 'service' assume that IDs are disambiguated.
connID := component.NewIDWithName(typeStr, "conn")
connID := component.NewIDWithName(nopType, "conn")
return connector.NewBuilder(
map[component.ID]component.Config{connID: nopFactory.CreateDefaultConfig()},
map[component.Type]connector.Factory{typeStr: nopFactory})
map[component.Type]connector.Factory{nopType: nopFactory})
}

View File

@ -21,7 +21,7 @@ import (
func TestNewNopConnectorFactory(t *testing.T) {
factory := NewNopFactory()
require.NotNil(t, factory)
assert.Equal(t, component.Type("nop"), factory.Type())
assert.Equal(t, component.MustNewType("nop"), factory.Type())
cfg := factory.CreateDefaultConfig()
assert.Equal(t, &nopConfig{}, cfg)
@ -87,7 +87,7 @@ func TestNewNopBuilder(t *testing.T) {
factory := NewNopFactory()
cfg := factory.CreateDefaultConfig()
set := NewNopCreateSettings()
set.ID = component.NewIDWithName(typeStr, "conn")
set.ID = component.NewIDWithName(nopType, "conn")
tracesToTraces, err := factory.CreateTracesToTraces(context.Background(), set, cfg, consumertest.NewNop())
require.NoError(t, err)

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("forward")
)
const (
Type = "forward"
TracesToTracesStability = component.StabilityLevelBeta
MetricsToMetricsStability = component.StabilityLevelBeta
LogsToLogsStability = component.StabilityLevelBeta

View File

@ -48,7 +48,7 @@ func fuzzLogs(numIDs, numCons, numLogs int) func(*testing.T) {
// If any consumer is mutating, the router must report mutating
for i := 0; i < numCons; i++ {
allIDs = append(allIDs, component.NewIDWithName("sink", strconv.Itoa(numCons)))
allIDs = append(allIDs, component.MustNewIDWithName("sink", strconv.Itoa(numCons)))
// Random chance for each consumer to be mutating
if (numCons+numLogs+i)%4 == 0 {
allCons = append(allCons, &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)})
@ -108,8 +108,8 @@ func TestLogsRouterConsumers(t *testing.T) {
ctx := context.Background()
ld := testdata.GenerateLogs(1)
fooID := component.NewID("foo")
barID := component.NewID("bar")
fooID := component.MustNewID("foo")
barID := component.MustNewID("bar")
foo := new(consumertest.LogsSink)
bar := new(consumertest.LogsSink)
@ -150,7 +150,7 @@ func TestLogsRouterConsumers(t *testing.T) {
assert.Nil(t, none)
assert.Error(t, err)
fake, err := r.Consumer(component.NewID("fake"))
fake, err := r.Consumer(component.MustNewID("fake"))
assert.Nil(t, fake)
assert.Error(t, err)
}

View File

@ -48,7 +48,7 @@ func fuzzMetrics(numIDs, numCons, numMetrics int) func(*testing.T) {
// If any consumer is mutating, the router must report mutating
for i := 0; i < numCons; i++ {
allIDs = append(allIDs, component.NewIDWithName("sink", strconv.Itoa(numCons)))
allIDs = append(allIDs, component.MustNewIDWithName("sink", strconv.Itoa(numCons)))
// Random chance for each consumer to be mutating
if (numCons+numMetrics+i)%4 == 0 {
allCons = append(allCons, &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)})
@ -108,8 +108,8 @@ func TestMetricsRouterConsumers(t *testing.T) {
ctx := context.Background()
md := testdata.GenerateMetrics(1)
fooID := component.NewID("foo")
barID := component.NewID("bar")
fooID := component.MustNewID("foo")
barID := component.MustNewID("bar")
foo := new(consumertest.MetricsSink)
bar := new(consumertest.MetricsSink)
@ -150,7 +150,7 @@ func TestMetricsRouterConsumers(t *testing.T) {
assert.Nil(t, none)
assert.Error(t, err)
fake, err := r.Consumer(component.NewID("fake"))
fake, err := r.Consumer(component.MustNewID("fake"))
assert.Nil(t, fake)
assert.Error(t, err)
}

View File

@ -48,7 +48,7 @@ func fuzzTraces(numIDs, numCons, numTraces int) func(*testing.T) {
// If any consumer is mutating, the router must report mutating
for i := 0; i < numCons; i++ {
allIDs = append(allIDs, component.NewIDWithName("sink", strconv.Itoa(numCons)))
allIDs = append(allIDs, component.MustNewIDWithName("sink", strconv.Itoa(numCons)))
// Random chance for each consumer to be mutating
if (numCons+numTraces+i)%4 == 0 {
allCons = append(allCons, &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)})
@ -108,8 +108,8 @@ func TestTracesRouterConsumer(t *testing.T) {
ctx := context.Background()
td := testdata.GenerateTraces(1)
fooID := component.NewID("foo")
barID := component.NewID("bar")
fooID := component.MustNewID("foo")
barID := component.MustNewID("bar")
foo := new(consumertest.TracesSink)
bar := new(consumertest.TracesSink)
@ -150,7 +150,7 @@ func TestTracesRouterConsumer(t *testing.T) {
assert.Nil(t, none)
assert.Error(t, err)
fake, err := r.Consumer(component.NewID("fake"))
fake, err := r.Consumer(component.MustNewID("fake"))
assert.Nil(t, fake)
assert.Error(t, err)
}

View File

@ -13,9 +13,10 @@ import (
"go.opentelemetry.io/collector/exporter/internal/common"
)
// The value of "type" key in configuration.
var componentType = component.MustNewType("debug")
const (
// The value of "type" key in configuration.
typeStr = "debug"
defaultSamplingInitial = 2
defaultSamplingThereafter = 500
)
@ -23,7 +24,7 @@ const (
// NewFactory creates a factory for Debug exporter
func NewFactory() exporter.Factory {
return exporter.NewFactory(
typeStr,
componentType,
createDefaultConfig,
exporter.WithTraces(createTracesExporter, metadata.TracesStability),
exporter.WithMetrics(createMetricsExporter, metadata.MetricsStability),

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("debug")
)
const (
Type = "debug"
TracesStability = component.StabilityLevelDevelopment
MetricsStability = component.StabilityLevelDevelopment
LogsStability = component.StabilityLevelDevelopment

View File

@ -16,12 +16,12 @@ import (
)
func TestNewFactory(t *testing.T) {
const typeStr = "test"
var testType = component.MustNewType("test")
defaultCfg := struct{}{}
factory := NewFactory(
typeStr,
testType,
func() component.Config { return &defaultCfg })
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
_, err := factory.CreateTracesExporter(context.Background(), CreateSettings{}, &defaultCfg)
assert.Error(t, err)
@ -32,15 +32,15 @@ func TestNewFactory(t *testing.T) {
}
func TestNewFactoryWithOptions(t *testing.T) {
const typeStr = "test"
var testType = component.MustNewType("test")
defaultCfg := struct{}{}
factory := NewFactory(
typeStr,
testType,
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelDevelopment),
WithMetrics(createMetrics, component.StabilityLevelAlpha),
WithLogs(createLogs, component.StabilityLevelDeprecated))
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
assert.Equal(t, component.StabilityLevelDevelopment, factory.TracesExporterStability())
@ -63,8 +63,8 @@ func TestMakeFactoryMap(t *testing.T) {
out map[component.Type]Factory
}
p1 := NewFactory("p1", nil)
p2 := NewFactory("p2", nil)
p1 := NewFactory(component.MustNewType("p1"), nil)
p2 := NewFactory(component.MustNewType("p2"), nil)
testCases := []testCase{
{
name: "different names",
@ -76,7 +76,7 @@ func TestMakeFactoryMap(t *testing.T) {
},
{
name: "same name",
in: []Factory{p1, p2, NewFactory("p1", nil)},
in: []Factory{p1, p2, NewFactory(component.MustNewType("p1"), nil)},
},
}
@ -97,9 +97,9 @@ func TestMakeFactoryMap(t *testing.T) {
func TestBuilder(t *testing.T) {
defaultCfg := struct{}{}
factories, err := MakeFactoryMap([]Factory{
NewFactory("err", nil),
NewFactory(component.MustNewType("err"), nil),
NewFactory(
"all",
component.MustNewType("all"),
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelDevelopment),
WithMetrics(createMetrics, component.StabilityLevelAlpha),
@ -115,21 +115,21 @@ func TestBuilder(t *testing.T) {
}{
{
name: "unknown",
id: component.NewID("unknown"),
id: component.MustNewID("unknown"),
err: "exporter factory not available for: \"unknown\"",
},
{
name: "err",
id: component.NewID("err"),
id: component.MustNewID("err"),
err: "telemetry type is not supported",
},
{
name: "all",
id: component.NewID("all"),
id: component.MustNewID("all"),
},
{
name: "all/named",
id: component.NewIDWithName("all", "named"),
id: component.MustNewIDWithName("all", "named"),
},
}
@ -172,7 +172,7 @@ func TestBuilderMissingConfig(t *testing.T) {
defaultCfg := struct{}{}
factories, err := MakeFactoryMap([]Factory{
NewFactory(
"all",
component.MustNewType("all"),
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelDevelopment),
WithMetrics(createMetrics, component.StabilityLevelAlpha),
@ -183,7 +183,7 @@ func TestBuilderMissingConfig(t *testing.T) {
require.NoError(t, err)
bErr := NewBuilder(map[component.ID]component.Config{}, factories)
missingID := component.NewIDWithName("all", "missing")
missingID := component.MustNewIDWithName("all", "missing")
te, err := bErr.CreateTraces(context.Background(), createSettings(missingID))
assert.EqualError(t, err, "exporter \"all/missing\" is not configured")
@ -199,14 +199,14 @@ func TestBuilderMissingConfig(t *testing.T) {
}
func TestBuilderFactory(t *testing.T) {
factories, err := MakeFactoryMap([]Factory{NewFactory("foo", nil)}...)
factories, err := MakeFactoryMap([]Factory{NewFactory(component.MustNewType("foo"), nil)}...)
require.NoError(t, err)
cfgs := map[component.ID]component.Config{component.NewID("foo"): struct{}{}}
cfgs := map[component.ID]component.Config{component.MustNewID("foo"): struct{}{}}
b := NewBuilder(cfgs, factories)
assert.NotNil(t, b.Factory(component.NewID("foo").Type()))
assert.Nil(t, b.Factory(component.NewID("bar").Type()))
assert.NotNil(t, b.Factory(component.MustNewID("foo").Type()))
assert.Nil(t, b.Factory(component.MustNewID("bar").Type()))
}
var nopInstance = &nopExporter{

View File

@ -22,7 +22,8 @@ import (
)
var (
defaultID = component.NewID("test")
defaultType = component.MustNewType("test")
defaultID = component.NewID(defaultType)
defaultSettings = func() exporter.CreateSettings {
set := exportertest.NewNopCreateSettings()
set.ID = defaultID
@ -35,11 +36,11 @@ func newNoopObsrepSender(_ *ObsReport) requestSender {
}
func TestBaseExporter(t *testing.T) {
be, err := newBaseExporter(defaultSettings, "", false, nil, nil, newNoopObsrepSender)
be, err := newBaseExporter(defaultSettings, defaultType, false, nil, nil, newNoopObsrepSender)
require.NoError(t, err)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
require.NoError(t, be.Shutdown(context.Background()))
be, err = newBaseExporter(defaultSettings, "", true, nil, nil, newNoopObsrepSender)
be, err = newBaseExporter(defaultSettings, defaultType, true, nil, nil, newNoopObsrepSender)
require.NoError(t, err)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
require.NoError(t, be.Shutdown(context.Background()))
@ -48,7 +49,7 @@ func TestBaseExporter(t *testing.T) {
func TestBaseExporterWithOptions(t *testing.T) {
want := errors.New("my error")
be, err := newBaseExporter(
defaultSettings, "", false, nil, nil, newNoopObsrepSender,
defaultSettings, defaultType, false, nil, nil, newNoopObsrepSender,
WithStart(func(ctx context.Context, host component.Host) error { return want }),
WithShutdown(func(ctx context.Context) error { return want }),
WithTimeout(NewDefaultTimeoutSettings()),
@ -68,12 +69,12 @@ func checkStatus(t *testing.T, sd sdktrace.ReadOnlySpan, err error) {
}
func TestQueueRetryOptionsWithRequestExporter(t *testing.T) {
bs, err := newBaseExporter(exportertest.NewNopCreateSettings(), "", true, nil, nil, newNoopObsrepSender,
bs, err := newBaseExporter(exportertest.NewNopCreateSettings(), defaultType, true, nil, nil, newNoopObsrepSender,
WithRetry(configretry.NewDefaultBackOffConfig()))
require.Nil(t, err)
require.True(t, bs.requestExporter)
require.Panics(t, func() {
_, _ = newBaseExporter(exportertest.NewNopCreateSettings(), "", true, nil, nil, newNoopObsrepSender,
_, _ = newBaseExporter(exportertest.NewNopCreateSettings(), defaultType, true, nil, nil, newNoopObsrepSender,
WithRetry(configretry.NewDefaultBackOffConfig()), WithQueue(NewDefaultQueueSettings()))
})
}
@ -84,7 +85,7 @@ func TestBaseExporterLogging(t *testing.T) {
set.Logger = zap.New(logger)
rCfg := configretry.NewDefaultBackOffConfig()
rCfg.Enabled = false
bs, err := newBaseExporter(set, "", true, nil, nil, newNoopObsrepSender, WithRetry(rCfg))
bs, err := newBaseExporter(set, defaultType, true, nil, nil, newNoopObsrepSender, WithRetry(rCfg))
require.Nil(t, err)
require.True(t, bs.requestExporter)
sendErr := bs.send(context.Background(), newErrorRequest())

View File

@ -511,7 +511,7 @@ func toStorageClient(ctx context.Context, storageID component.ID, host component
return nil, errWrongExtensionType
}
return storageExt.GetClient(ctx, component.KindExporter, ownerID, string(signal))
return storageExt.GetClient(ctx, component.KindExporter, ownerID, signal.String())
}
func getItemKey(index uint64) string {

View File

@ -293,14 +293,14 @@ func TestToStorageClient(t *testing.T) {
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
storageID := component.NewIDWithName("file_storage", strconv.Itoa(tC.storageIndex))
storageID := component.MustNewIDWithName("file_storage", strconv.Itoa(tC.storageIndex))
var extensions = map[component.ID]component.Component{}
for i := 0; i < tC.numStorages; i++ {
extensions[component.NewIDWithName("file_storage", strconv.Itoa(i))] = NewMockStorageExtension(tC.getClientError)
extensions[component.MustNewIDWithName("file_storage", strconv.Itoa(i))] = NewMockStorageExtension(tC.getClientError)
}
host := &mockHost{ext: extensions}
ownerID := component.NewID("foo_exporter")
ownerID := component.MustNewID("foo_exporter")
// execute
client, err := toStorageClient(context.Background(), storageID, host, ownerID, component.DataTypeTraces)
@ -318,7 +318,7 @@ func TestToStorageClient(t *testing.T) {
}
func TestInvalidStorageExtensionType(t *testing.T) {
storageID := component.NewIDWithName("extension", "extension")
storageID := component.MustNewIDWithName("extension", "extension")
// make a test extension
factory := extensiontest.NewNopFactory()
@ -330,7 +330,7 @@ func TestInvalidStorageExtensionType(t *testing.T) {
storageID: extension,
}
host := &mockHost{ext: extensions}
ownerID := component.NewID("foo_exporter")
ownerID := component.MustNewID("foo_exporter")
// execute
client, err := toStorageClient(context.Background(), storageID, host, ownerID, component.DataTypeTraces)

View File

@ -37,7 +37,7 @@ const (
)
var (
fakeLogsExporterName = component.NewIDWithName("fake_logs_exporter", "with_name")
fakeLogsExporterName = component.MustNewIDWithName("fake_logs_exporter", "with_name")
fakeLogsExporterConfig = struct{}{}
)
@ -157,12 +157,12 @@ func TestLogsRequestExporter_Default_ExportError(t *testing.T) {
func TestLogsExporter_WithPersistentQueue(t *testing.T) {
qCfg := NewDefaultQueueSettings()
storageID := component.NewIDWithName("file_storage", "storage")
storageID := component.MustNewIDWithName("file_storage", "storage")
qCfg.StorageID = &storageID
rCfg := configretry.NewDefaultBackOffConfig()
ts := consumertest.LogsSink{}
set := exportertest.NewNopCreateSettings()
set.ID = component.NewIDWithName("test_logs", "with_persistent_queue")
set.ID = component.MustNewIDWithName("test_logs", "with_persistent_queue")
te, err := NewLogsExporter(context.Background(), set, &fakeLogsExporterConfig, ts.ConsumeLogs, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)

View File

@ -37,7 +37,7 @@ const (
)
var (
fakeMetricsExporterName = component.NewIDWithName("fake_metrics_exporter", "with_name")
fakeMetricsExporterName = component.MustNewIDWithName("fake_metrics_exporter", "with_name")
fakeMetricsExporterConfig = struct{}{}
)
@ -158,12 +158,12 @@ func TestMetricsRequestExporter_Default_ExportError(t *testing.T) {
func TestMetricsExporter_WithPersistentQueue(t *testing.T) {
qCfg := NewDefaultQueueSettings()
storageID := component.NewIDWithName("file_storage", "storage")
storageID := component.MustNewIDWithName("file_storage", "storage")
qCfg.StorageID = &storageID
rCfg := configretry.NewDefaultBackOffConfig()
ms := consumertest.MetricsSink{}
set := exportertest.NewNopCreateSettings()
set.ID = component.NewIDWithName("test_metrics", "with_persistent_queue")
set.ID = component.MustNewIDWithName("test_metrics", "with_persistent_queue")
te, err := NewMetricsExporter(context.Background(), set, &fakeTracesExporterConfig, ms.ConsumeMetrics, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)

View File

@ -20,7 +20,7 @@ import (
)
var (
exporterID = component.NewID("fakeExporter")
exporterID = component.MustNewID("fakeExporter")
errFake = errors.New("errFake")
)

View File

@ -15,7 +15,7 @@ import (
)
func TestExportEnqueueFailure(t *testing.T) {
exporterID := component.NewID("fakeExporter")
exporterID := component.MustNewID("fakeExporter")
tt, err := componenttest.SetupTelemetry(exporterID)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })

View File

@ -26,7 +26,7 @@ func TestQueuedRetry_StopWhileWaiting(t *testing.T) {
qCfg := NewDefaultQueueSettings()
qCfg.NumConsumers = 1
rCfg := configretry.NewDefaultBackOffConfig()
be, err := newBaseExporter(defaultSettings, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(defaultSettings, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
ocs := be.obsrepSender.(*observabilityConsumerSender)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
@ -58,7 +58,7 @@ func TestQueuedRetry_DoNotPreserveCancellation(t *testing.T) {
qCfg := NewDefaultQueueSettings()
qCfg.NumConsumers = 1
rCfg := configretry.NewDefaultBackOffConfig()
be, err := newBaseExporter(defaultSettings, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(defaultSettings, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
ocs := be.obsrepSender.(*observabilityConsumerSender)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
@ -88,7 +88,7 @@ func TestQueuedRetry_RejectOnFull(t *testing.T) {
set := exportertest.NewNopCreateSettings()
logger, observed := observer.New(zap.ErrorLevel)
set.Logger = zap.New(logger)
be, err := newBaseExporter(set, "", false, nil, nil, newNoopObsrepSender, WithQueue(qCfg))
be, err := newBaseExporter(set, defaultType, false, nil, nil, newNoopObsrepSender, WithQueue(qCfg))
require.NoError(t, err)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
t.Cleanup(func() {
@ -108,7 +108,7 @@ func TestQueuedRetryHappyPath(t *testing.T) {
qCfg := NewDefaultQueueSettings()
rCfg := configretry.NewDefaultBackOffConfig()
set := exporter.CreateSettings{ID: defaultID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}
be, err := newBaseExporter(set, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(set, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
ocs := be.obsrepSender.(*observabilityConsumerSender)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
@ -145,7 +145,7 @@ func TestQueuedRetry_QueueMetricsReported(t *testing.T) {
qCfg.NumConsumers = 0 // to make every request go straight to the queue
rCfg := configretry.NewDefaultBackOffConfig()
set := exporter.CreateSettings{ID: defaultID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}
be, err := newBaseExporter(set, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(set, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
@ -237,11 +237,11 @@ func TestQueuedRetryPersistenceEnabled(t *testing.T) {
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
qCfg := NewDefaultQueueSettings()
storageID := component.NewIDWithName("file_storage", "storage")
storageID := component.MustNewIDWithName("file_storage", "storage")
qCfg.StorageID = &storageID // enable persistence
rCfg := configretry.NewDefaultBackOffConfig()
set := exporter.CreateSettings{ID: defaultID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}
be, err := newBaseExporter(set, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(set, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
var extensions = map[component.ID]component.Component{
@ -261,11 +261,11 @@ func TestQueuedRetryPersistenceEnabledStorageError(t *testing.T) {
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
qCfg := NewDefaultQueueSettings()
storageID := component.NewIDWithName("file_storage", "storage")
storageID := component.MustNewIDWithName("file_storage", "storage")
qCfg.StorageID = &storageID // enable persistence
rCfg := configretry.NewDefaultBackOffConfig()
set := exporter.CreateSettings{ID: defaultID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}
be, err := newBaseExporter(set, "", false, mockRequestMarshaler, mockRequestUnmarshaler(&mockRequest{}), newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(set, defaultType, false, mockRequestMarshaler, mockRequestUnmarshaler(&mockRequest{}), newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
var extensions = map[component.ID]component.Component{
@ -280,7 +280,7 @@ func TestQueuedRetryPersistenceEnabledStorageError(t *testing.T) {
func TestQueuedRetryPersistentEnabled_NoDataLossOnShutdown(t *testing.T) {
qCfg := NewDefaultQueueSettings()
qCfg.NumConsumers = 1
storageID := component.NewIDWithName("file_storage", "storage")
storageID := component.MustNewIDWithName("file_storage", "storage")
qCfg.StorageID = &storageID // enable persistence to ensure data is re-queued on shutdown
rCfg := configretry.NewDefaultBackOffConfig()
@ -288,7 +288,7 @@ func TestQueuedRetryPersistentEnabled_NoDataLossOnShutdown(t *testing.T) {
rCfg.MaxElapsedTime = 0 // retry infinitely so shutdown can be triggered
mockReq := newErrorRequest()
be, err := newBaseExporter(defaultSettings, "", false, mockRequestMarshaler, mockRequestUnmarshaler(mockReq),
be, err := newBaseExporter(defaultSettings, defaultType, false, mockRequestMarshaler, mockRequestUnmarshaler(mockReq),
newNoopObsrepSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
@ -312,7 +312,7 @@ func TestQueuedRetryPersistentEnabled_NoDataLossOnShutdown(t *testing.T) {
// start the exporter again replacing the preserved mockRequest in the unmarshaler with a new one that doesn't fail.
replacedReq := newMockRequest(1, nil)
be, err = newBaseExporter(defaultSettings, "", false, mockRequestMarshaler, mockRequestUnmarshaler(replacedReq),
be, err = newBaseExporter(defaultSettings, defaultType, false, mockRequestMarshaler, mockRequestUnmarshaler(replacedReq),
newNoopObsrepSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
require.NoError(t, be.Start(context.Background(), host))
@ -323,7 +323,7 @@ func TestQueuedRetryPersistentEnabled_NoDataLossOnShutdown(t *testing.T) {
}
func TestQueueSenderNoStartShutdown(t *testing.T) {
qs := newQueueSender(NewDefaultQueueSettings(), exportertest.NewNopCreateSettings(), "", nil, nil, nil)
qs := newQueueSender(NewDefaultQueueSettings(), exportertest.NewNopCreateSettings(), defaultType, nil, nil, nil)
assert.NoError(t, qs.Shutdown(context.Background()))
}

View File

@ -38,7 +38,7 @@ func TestQueuedRetry_DropOnPermanentError(t *testing.T) {
qCfg := NewDefaultQueueSettings()
rCfg := configretry.NewDefaultBackOffConfig()
mockR := newMockRequest(2, consumererror.NewPermanent(errors.New("bad data")))
be, err := newBaseExporter(defaultSettings, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(defaultSettings, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
ocs := be.obsrepSender.(*observabilityConsumerSender)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
@ -61,7 +61,7 @@ func TestQueuedRetry_DropOnNoRetry(t *testing.T) {
qCfg := NewDefaultQueueSettings()
rCfg := configretry.NewDefaultBackOffConfig()
rCfg.Enabled = false
be, err := newBaseExporter(defaultSettings, "", false, mockRequestMarshaler,
be, err := newBaseExporter(defaultSettings, defaultType, false, mockRequestMarshaler,
mockRequestUnmarshaler(newMockRequest(2, errors.New("transient error"))),
newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
@ -88,7 +88,7 @@ func TestQueuedRetry_OnError(t *testing.T) {
qCfg.NumConsumers = 1
rCfg := configretry.NewDefaultBackOffConfig()
rCfg.InitialInterval = 0
be, err := newBaseExporter(defaultSettings, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(defaultSettings, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
t.Cleanup(func() {
@ -116,7 +116,7 @@ func TestQueuedRetry_MaxElapsedTime(t *testing.T) {
rCfg := configretry.NewDefaultBackOffConfig()
rCfg.InitialInterval = time.Millisecond
rCfg.MaxElapsedTime = 100 * time.Millisecond
be, err := newBaseExporter(defaultSettings, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(defaultSettings, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
ocs := be.obsrepSender.(*observabilityConsumerSender)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
@ -162,7 +162,7 @@ func TestQueuedRetry_ThrottleError(t *testing.T) {
qCfg.NumConsumers = 1
rCfg := configretry.NewDefaultBackOffConfig()
rCfg.InitialInterval = 10 * time.Millisecond
be, err := newBaseExporter(defaultSettings, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(defaultSettings, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
ocs := be.obsrepSender.(*observabilityConsumerSender)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))
@ -194,7 +194,7 @@ func TestQueuedRetry_RetryOnError(t *testing.T) {
qCfg.QueueSize = 1
rCfg := configretry.NewDefaultBackOffConfig()
rCfg.InitialInterval = 0
be, err := newBaseExporter(defaultSettings, "", false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
be, err := newBaseExporter(defaultSettings, defaultType, false, nil, nil, newObservabilityConsumerSender, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)
ocs := be.obsrepSender.(*observabilityConsumerSender)
require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))

View File

@ -37,7 +37,7 @@ const (
)
var (
fakeTracesExporterName = component.NewIDWithName("fake_traces_exporter", "with_name")
fakeTracesExporterName = component.MustNewIDWithName("fake_traces_exporter", "with_name")
fakeTracesExporterConfig = struct{}{}
)
@ -155,12 +155,12 @@ func TestTracesRequestExporter_Default_ExportError(t *testing.T) {
func TestTracesExporter_WithPersistentQueue(t *testing.T) {
qCfg := NewDefaultQueueSettings()
storageID := component.NewIDWithName("file_storage", "storage")
storageID := component.MustNewIDWithName("file_storage", "storage")
qCfg.StorageID = &storageID
rCfg := configretry.NewDefaultBackOffConfig()
ts := consumertest.TracesSink{}
set := exportertest.NewNopCreateSettings()
set.ID = component.NewIDWithName("test_traces", "with_persistent_queue")
set.ID = component.MustNewIDWithName("test_traces", "with_persistent_queue")
te, err := NewTracesExporter(context.Background(), set, &fakeTracesExporterConfig, ts.ConsumeTraces, WithRetry(rCfg), WithQueue(qCfg))
require.NoError(t, err)

View File

@ -78,7 +78,7 @@ func (mef *mockExporterFactory) createMockLogsExporter(
func newMockExporterFactory(mr *mockReceiver) exporter.Factory {
mef := &mockExporterFactory{mr: mr}
return exporter.NewFactory(
"pass_through_exporter",
component.MustNewType("pass_through_exporter"),
func() component.Config { return &nopConfig{} },
exporter.WithTraces(mef.createMockTracesExporter, component.StabilityLevelBeta),
exporter.WithMetrics(mef.createMockMetricsExporter, component.StabilityLevelBeta),
@ -87,7 +87,7 @@ func newMockExporterFactory(mr *mockReceiver) exporter.Factory {
}
func newMockReceiverFactory(mr *mockReceiver) receiver.Factory {
return receiver.NewFactory("pass_through_receiver",
return receiver.NewFactory(component.MustNewType("pass_through_receiver"),
func() component.Config { return &nopConfig{} },
receiver.WithTraces(func(_ context.Context, _ receiver.CreateSettings, _ component.Config, c consumer.Traces) (receiver.Traces, error) {
mr.Traces = c

View File

@ -12,11 +12,12 @@ import (
"go.opentelemetry.io/collector/exporter"
)
const typeStr = "nop"
var nopType = component.MustNewType("nop")
// NewNopCreateSettings returns a new nop settings for Create*Exporter functions.
func NewNopCreateSettings() exporter.CreateSettings {
return exporter.CreateSettings{
ID: component.NewID(nopType),
TelemetrySettings: componenttest.NewNopTelemetrySettings(),
BuildInfo: component.NewDefaultBuildInfo(),
}
@ -25,7 +26,7 @@ func NewNopCreateSettings() exporter.CreateSettings {
// NewNopFactory returns an exporter.Factory that constructs nop exporters.
func NewNopFactory() exporter.Factory {
return exporter.NewFactory(
"nop",
nopType,
func() component.Config { return &nopConfig{} },
exporter.WithTraces(createTracesExporter, component.StabilityLevelStable),
exporter.WithMetrics(createMetricsExporter, component.StabilityLevelStable),
@ -62,6 +63,6 @@ type nopExporter struct {
func NewNopBuilder() *exporter.Builder {
nopFactory := NewNopFactory()
return exporter.NewBuilder(
map[component.ID]component.Config{component.NewID(typeStr): nopFactory.CreateDefaultConfig()},
map[component.Type]exporter.Factory{typeStr: nopFactory})
map[component.ID]component.Config{component.NewID(nopType): nopFactory.CreateDefaultConfig()},
map[component.Type]exporter.Factory{nopType: nopFactory})
}

View File

@ -20,7 +20,7 @@ import (
func TestNewNopFactory(t *testing.T) {
factory := NewNopFactory()
require.NotNil(t, factory)
assert.Equal(t, component.Type("nop"), factory.Type())
assert.Equal(t, component.MustNewType("nop"), factory.Type())
cfg := factory.CreateDefaultConfig()
assert.Equal(t, &nopConfig{}, cfg)
@ -50,7 +50,7 @@ func TestNewNopBuilder(t *testing.T) {
factory := NewNopFactory()
cfg := factory.CreateDefaultConfig()
set := NewNopCreateSettings()
set.ID = component.NewID(typeStr)
set.ID = component.NewID(nopType)
traces, err := factory.CreateTracesExporter(context.Background(), set, cfg)
require.NoError(t, err)

View File

@ -15,9 +15,10 @@ import (
"go.opentelemetry.io/collector/exporter/loggingexporter/internal/metadata"
)
// The value of "type" key in configuration.
var componentType = component.MustNewType("logging")
const (
// The value of "type" key in configuration.
typeStr = "logging"
defaultSamplingInitial = 2
defaultSamplingThereafter = 500
)
@ -25,7 +26,7 @@ const (
// NewFactory creates a factory for Logging exporter
func NewFactory() exporter.Factory {
return exporter.NewFactory(
typeStr,
componentType,
createDefaultConfig,
exporter.WithTraces(createTracesExporter, metadata.TracesStability),
exporter.WithMetrics(createMetricsExporter, metadata.MetricsStability),

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("logging")
)
const (
Type = "logging"
TracesStability = component.StabilityLevelDeprecated
MetricsStability = component.StabilityLevelDeprecated
LogsStability = component.StabilityLevelDeprecated

View File

@ -74,7 +74,7 @@ func TestUnmarshalConfig(t *testing.T) {
},
WriteBufferSize: 512 * 1024,
BalancerName: "round_robin",
Auth: &configauth.Authentication{AuthenticatorID: component.NewID("nop")},
Auth: &configauth.Authentication{AuthenticatorID: component.MustNewID("nop")},
},
}, cfg)
}

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("otlp")
)
const (
Type = "otlp"
LogsStability = component.StabilityLevelBeta
TracesStability = component.StabilityLevelStable
MetricsStability = component.StabilityLevelStable

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("otlphttp")
)
const (
Type = "otlphttp"
LogsStability = component.StabilityLevelBeta
TracesStability = component.StabilityLevelStable
MetricsStability = component.StabilityLevelStable

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("memory_ballast")
)
const (
Type = "memory_ballast"
ExtensionStability = component.StabilityLevelDeprecated
)

View File

@ -21,18 +21,18 @@ type nopExtension struct {
}
func TestNewFactory(t *testing.T) {
const typeStr = "test"
var testType = component.MustNewType("test")
defaultCfg := struct{}{}
nopExtensionInstance := new(nopExtension)
factory := NewFactory(
typeStr,
testType,
func() component.Config { return &defaultCfg },
func(ctx context.Context, settings CreateSettings, extension component.Config) (Extension, error) {
return nopExtensionInstance, nil
},
component.StabilityLevelDevelopment)
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
assert.Equal(t, component.StabilityLevelDevelopment, factory.ExtensionStability())
@ -48,8 +48,8 @@ func TestMakeFactoryMap(t *testing.T) {
out map[component.Type]Factory
}
p1 := NewFactory("p1", nil, nil, component.StabilityLevelAlpha)
p2 := NewFactory("p2", nil, nil, component.StabilityLevelAlpha)
p1 := NewFactory(component.MustNewType("p1"), nil, nil, component.StabilityLevelAlpha)
p2 := NewFactory(component.MustNewType("p2"), nil, nil, component.StabilityLevelAlpha)
testCases := []testCase{
{
name: "different names",
@ -61,7 +61,7 @@ func TestMakeFactoryMap(t *testing.T) {
},
{
name: "same name",
in: []Factory{p1, p2, NewFactory("p1", nil, nil, component.StabilityLevelAlpha)},
in: []Factory{p1, p2, NewFactory(component.MustNewType("p1"), nil, nil, component.StabilityLevelAlpha)},
},
}
for i := range testCases {
@ -79,14 +79,14 @@ func TestMakeFactoryMap(t *testing.T) {
}
func TestBuilder(t *testing.T) {
const typeStr = "test"
var testType = component.MustNewType("test")
defaultCfg := struct{}{}
testID := component.NewID(typeStr)
unknownID := component.NewID("unknown")
testID := component.NewID(testType)
unknownID := component.MustNewID("unknown")
factories, err := MakeFactoryMap([]Factory{
NewFactory(
typeStr,
testType,
func() component.Config { return &defaultCfg },
func(ctx context.Context, settings CreateSettings, extension component.Config) (Extension, error) {
return nopExtension{CreateSettings: settings}, nil
@ -111,20 +111,20 @@ func TestBuilder(t *testing.T) {
assert.EqualError(t, err, "extension factory not available for: \"unknown\"")
assert.Nil(t, missingType)
missingCfg, err := b.Create(context.Background(), createSettings(component.NewIDWithName(typeStr, "foo")))
missingCfg, err := b.Create(context.Background(), createSettings(component.NewIDWithName(testType, "foo")))
assert.EqualError(t, err, "extension \"test/foo\" is not configured")
assert.Nil(t, missingCfg)
}
func TestBuilderFactory(t *testing.T) {
factories, err := MakeFactoryMap([]Factory{NewFactory("foo", nil, nil, component.StabilityLevelDevelopment)}...)
factories, err := MakeFactoryMap([]Factory{NewFactory(component.MustNewType("foo"), nil, nil, component.StabilityLevelDevelopment)}...)
require.NoError(t, err)
cfgs := map[component.ID]component.Config{component.NewID("foo"): struct{}{}}
cfgs := map[component.ID]component.Config{component.MustNewID("foo"): struct{}{}}
b := NewBuilder(cfgs, factories)
assert.NotNil(t, b.Factory(component.NewID("foo").Type()))
assert.Nil(t, b.Factory(component.NewID("bar").Type()))
assert.NotNil(t, b.Factory(component.MustNewID("foo").Type()))
assert.Nil(t, b.Factory(component.MustNewID("bar").Type()))
}
func createSettings(id component.ID) CreateSettings {

View File

@ -11,11 +11,12 @@ import (
"go.opentelemetry.io/collector/extension"
)
const typeStr = "nop"
var nopType = component.MustNewType("nop")
// NewNopCreateSettings returns a new nop settings for extension.Factory Create* functions.
func NewNopCreateSettings() extension.CreateSettings {
return extension.CreateSettings{
ID: component.NewID(nopType),
TelemetrySettings: componenttest.NewNopTelemetrySettings(),
BuildInfo: component.NewDefaultBuildInfo(),
}
@ -24,7 +25,7 @@ func NewNopCreateSettings() extension.CreateSettings {
// NewNopFactory returns an extension.Factory that constructs nop extensions.
func NewNopFactory() extension.Factory {
return extension.NewFactory(
"nop",
nopType,
func() component.Config {
return &nopConfig{}
},
@ -48,6 +49,6 @@ type nopExtension struct {
func NewNopBuilder() *extension.Builder {
nopFactory := NewNopFactory()
return extension.NewBuilder(
map[component.ID]component.Config{component.NewID(typeStr): nopFactory.CreateDefaultConfig()},
map[component.Type]extension.Factory{typeStr: nopFactory})
map[component.ID]component.Config{component.NewID(nopType): nopFactory.CreateDefaultConfig()},
map[component.Type]extension.Factory{nopType: nopFactory})
}

View File

@ -17,7 +17,7 @@ import (
func TestNewNopFactory(t *testing.T) {
factory := NewNopFactory()
require.NotNil(t, factory)
assert.Equal(t, component.Type("nop"), factory.Type())
assert.Equal(t, component.MustNewType("nop"), factory.Type())
cfg := factory.CreateDefaultConfig()
assert.Equal(t, &nopConfig{}, cfg)
@ -34,7 +34,7 @@ func TestNewNopBuilder(t *testing.T) {
factory := NewNopFactory()
cfg := factory.CreateDefaultConfig()
set := NewNopCreateSettings()
set.ID = component.NewID(typeStr)
set.ID = component.NewID(nopType)
ext, err := factory.CreateExtension(context.Background(), set, cfg)
require.NoError(t, err)

View File

@ -24,7 +24,7 @@ func NewStatusWatcherExtensionFactory(
onStatusChanged func(source *component.InstanceID, event *component.StatusEvent),
) extension.Factory {
return extension.NewFactory(
"statuswatcher",
component.MustNewType("statuswatcher"),
func() component.Config {
return &struct{}{}
},

View File

@ -23,7 +23,7 @@ func TestStatusWatcherExtension(t *testing.T) {
},
)
require.NotNil(t, factory)
assert.Equal(t, component.Type("statuswatcher"), factory.Type())
assert.Equal(t, component.MustNewType("statuswatcher"), factory.Type())
cfg := factory.CreateDefaultConfig()
assert.Equal(t, &struct{}{}, cfg)

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("memory_limiter")
)
const (
Type = "memory_limiter"
ExtensionStability = component.StabilityLevelDevelopment
)

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("zpages")
)
const (
Type = "zpages"
ExtensionStability = component.StabilityLevelBeta
)

View File

@ -173,7 +173,7 @@ type host struct {
func (h *host) GetExtensions() map[component.ID]component.Component {
ret := make(map[component.ID]component.Component)
ret[component.NewID("ballast")] = &ballastExtension{ballastSize: h.ballastSize}
ret[component.MustNewID("ballast")] = &ballastExtension{ballastSize: h.ballastSize}
return ret
}

View File

@ -15,7 +15,7 @@ import (
"go.opentelemetry.io/collector/component/componenttest"
)
var id = component.NewID("test")
var id = component.MustNewID("test")
type baseComponent struct {
component.StartFunc

View File

@ -16,6 +16,8 @@ import (
"go.opentelemetry.io/collector/component"
)
var nopType = component.MustNewType("nop")
func TestNewBuildSubCommand(t *testing.T) {
cfgProvider, err := NewConfigProvider(newDefaultConfigProviderSettings([]string{filepath.Join("testdata", "otelcol-nop.yaml")}))
require.NoError(t, err)
@ -31,7 +33,7 @@ func TestNewBuildSubCommand(t *testing.T) {
ExpectedYamlStruct := componentsOutput{
BuildInfo: component.NewDefaultBuildInfo(),
Receivers: []componentWithStability{{
Name: component.Type("nop"),
Name: nopType,
Stability: map[string]string{
"logs": "Stable",
"metrics": "Stable",
@ -39,7 +41,7 @@ func TestNewBuildSubCommand(t *testing.T) {
},
}},
Processors: []componentWithStability{{
Name: component.Type("nop"),
Name: nopType,
Stability: map[string]string{
"logs": "Stable",
"metrics": "Stable",
@ -47,7 +49,7 @@ func TestNewBuildSubCommand(t *testing.T) {
},
}},
Exporters: []componentWithStability{{
Name: component.Type("nop"),
Name: nopType,
Stability: map[string]string{
"logs": "Stable",
"metrics": "Stable",
@ -55,7 +57,7 @@ func TestNewBuildSubCommand(t *testing.T) {
},
}},
Connectors: []componentWithStability{{
Name: component.Type("nop"),
Name: nopType,
Stability: map[string]string{
"logs-to-logs": "Development",
"logs-to-metrics": "Development",
@ -71,7 +73,7 @@ func TestNewBuildSubCommand(t *testing.T) {
},
}},
Extensions: []componentWithStability{{
Name: component.Type("nop"),
Name: nopType,
Stability: map[string]string{
"extension": "Stable",
},

View File

@ -76,7 +76,7 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-extension-reference",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Service.Extensions = append(cfg.Service.Extensions, component.NewIDWithName("nop", "2"))
cfg.Service.Extensions = append(cfg.Service.Extensions, component.MustNewIDWithName("nop", "2"))
return cfg
},
expected: errors.New(`service::extensions: references extension "nop/2" which is not configured`),
@ -85,8 +85,8 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-receiver-reference",
cfgFn: func() *Config {
cfg := generateConfig()
pipe := cfg.Service.Pipelines[component.NewID("traces")]
pipe.Receivers = append(pipe.Receivers, component.NewIDWithName("nop", "2"))
pipe := cfg.Service.Pipelines[component.MustNewID("traces")]
pipe.Receivers = append(pipe.Receivers, component.MustNewIDWithName("nop", "2"))
return cfg
},
expected: errors.New(`service::pipelines::traces: references receiver "nop/2" which is not configured`),
@ -95,8 +95,8 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-processor-reference",
cfgFn: func() *Config {
cfg := generateConfig()
pipe := cfg.Service.Pipelines[component.NewID("traces")]
pipe.Processors = append(pipe.Processors, component.NewIDWithName("nop", "2"))
pipe := cfg.Service.Pipelines[component.MustNewID("traces")]
pipe.Processors = append(pipe.Processors, component.MustNewIDWithName("nop", "2"))
return cfg
},
expected: errors.New(`service::pipelines::traces: references processor "nop/2" which is not configured`),
@ -105,8 +105,8 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-exporter-reference",
cfgFn: func() *Config {
cfg := generateConfig()
pipe := cfg.Service.Pipelines[component.NewID("traces")]
pipe.Exporters = append(pipe.Exporters, component.NewIDWithName("nop", "2"))
pipe := cfg.Service.Pipelines[component.MustNewID("traces")]
pipe.Exporters = append(pipe.Exporters, component.MustNewIDWithName("nop", "2"))
return cfg
},
expected: errors.New(`service::pipelines::traces: references exporter "nop/2" which is not configured`),
@ -115,7 +115,7 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-receiver-config",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Receivers[component.NewID("nop")] = &errConfig{
cfg.Receivers[component.MustNewID("nop")] = &errConfig{
validateErr: errInvalidRecvConfig,
}
return cfg
@ -126,7 +126,7 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-exporter-config",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Exporters[component.NewID("nop")] = &errConfig{
cfg.Exporters[component.MustNewID("nop")] = &errConfig{
validateErr: errInvalidExpConfig,
}
return cfg
@ -137,7 +137,7 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-processor-config",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Processors[component.NewID("nop")] = &errConfig{
cfg.Processors[component.MustNewID("nop")] = &errConfig{
validateErr: errInvalidProcConfig,
}
return cfg
@ -148,7 +148,7 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-extension-config",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Extensions[component.NewID("nop")] = &errConfig{
cfg.Extensions[component.MustNewID("nop")] = &errConfig{
validateErr: errInvalidExtConfig,
}
return cfg
@ -159,7 +159,7 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-connector-config",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Connectors[component.NewIDWithName("nop", "conn")] = &errConfig{
cfg.Connectors[component.MustNewIDWithName("nop", "conn")] = &errConfig{
validateErr: errInvalidConnConfig,
}
return cfg
@ -170,34 +170,34 @@ func TestConfigValidate(t *testing.T) {
name: "ambiguous-connector-name-as-receiver",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Receivers[component.NewID("nop/2")] = &errConfig{}
cfg.Connectors[component.NewID("nop/2")] = &errConfig{}
pipe := cfg.Service.Pipelines[component.NewID("traces")]
pipe.Receivers = append(pipe.Receivers, component.NewIDWithName("nop", "2"))
pipe.Exporters = append(pipe.Exporters, component.NewIDWithName("nop", "2"))
cfg.Receivers[component.MustNewID("nop2")] = &errConfig{}
cfg.Connectors[component.MustNewID("nop2")] = &errConfig{}
pipe := cfg.Service.Pipelines[component.MustNewID("traces")]
pipe.Receivers = append(pipe.Receivers, component.MustNewIDWithName("nop", "2"))
pipe.Exporters = append(pipe.Exporters, component.MustNewIDWithName("nop", "2"))
return cfg
},
expected: errors.New(`connectors::nop/2: ambiguous ID: Found both "nop/2" receiver and "nop/2" connector. Change one of the components' IDs to eliminate ambiguity (e.g. rename "nop/2" connector to "nop/2/connector")`),
expected: errors.New(`connectors::nop2: ambiguous ID: Found both "nop2" receiver and "nop2" connector. Change one of the components' IDs to eliminate ambiguity (e.g. rename "nop2" connector to "nop2/connector")`),
},
{
name: "ambiguous-connector-name-as-exporter",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Exporters[component.NewID("nop/2")] = &errConfig{}
cfg.Connectors[component.NewID("nop/2")] = &errConfig{}
pipe := cfg.Service.Pipelines[component.NewID("traces")]
pipe.Receivers = append(pipe.Receivers, component.NewIDWithName("nop", "2"))
pipe.Exporters = append(pipe.Exporters, component.NewIDWithName("nop", "2"))
cfg.Exporters[component.MustNewID("nop2")] = &errConfig{}
cfg.Connectors[component.MustNewID("nop2")] = &errConfig{}
pipe := cfg.Service.Pipelines[component.MustNewID("traces")]
pipe.Receivers = append(pipe.Receivers, component.MustNewIDWithName("nop", "2"))
pipe.Exporters = append(pipe.Exporters, component.MustNewIDWithName("nop", "2"))
return cfg
},
expected: errors.New(`connectors::nop/2: ambiguous ID: Found both "nop/2" exporter and "nop/2" connector. Change one of the components' IDs to eliminate ambiguity (e.g. rename "nop/2" connector to "nop/2/connector")`),
expected: errors.New(`connectors::nop2: ambiguous ID: Found both "nop2" exporter and "nop2" connector. Change one of the components' IDs to eliminate ambiguity (e.g. rename "nop2" connector to "nop2/connector")`),
},
{
name: "invalid-connector-reference-as-receiver",
cfgFn: func() *Config {
cfg := generateConfig()
pipe := cfg.Service.Pipelines[component.NewID("traces")]
pipe.Receivers = append(pipe.Receivers, component.NewIDWithName("nop", "conn2"))
pipe := cfg.Service.Pipelines[component.MustNewID("traces")]
pipe.Receivers = append(pipe.Receivers, component.MustNewIDWithName("nop", "conn2"))
return cfg
},
expected: errors.New(`service::pipelines::traces: references receiver "nop/conn2" which is not configured`),
@ -206,8 +206,8 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-connector-reference-as-receiver",
cfgFn: func() *Config {
cfg := generateConfig()
pipe := cfg.Service.Pipelines[component.NewID("traces")]
pipe.Exporters = append(pipe.Exporters, component.NewIDWithName("nop", "conn2"))
pipe := cfg.Service.Pipelines[component.MustNewID("traces")]
pipe.Exporters = append(pipe.Exporters, component.MustNewIDWithName("nop", "conn2"))
return cfg
},
expected: errors.New(`service::pipelines::traces: references exporter "nop/conn2" which is not configured`),
@ -234,19 +234,19 @@ func TestConfigValidate(t *testing.T) {
func generateConfig() *Config {
return &Config{
Receivers: map[component.ID]component.Config{
component.NewID("nop"): &errConfig{},
component.MustNewID("nop"): &errConfig{},
},
Exporters: map[component.ID]component.Config{
component.NewID("nop"): &errConfig{},
component.MustNewID("nop"): &errConfig{},
},
Processors: map[component.ID]component.Config{
component.NewID("nop"): &errConfig{},
component.MustNewID("nop"): &errConfig{},
},
Connectors: map[component.ID]component.Config{
component.NewIDWithName("nop", "conn"): &errConfig{},
component.MustNewIDWithName("nop", "conn"): &errConfig{},
},
Extensions: map[component.ID]component.Config{
component.NewID("nop"): &errConfig{},
component.MustNewID("nop"): &errConfig{},
},
Service: service.Config{
Telemetry: telemetry.Config{
@ -265,12 +265,12 @@ func generateConfig() *Config {
Address: ":8080",
},
},
Extensions: []component.ID{component.NewID("nop")},
Extensions: []component.ID{component.MustNewID("nop")},
Pipelines: pipelines.Config{
component.NewID("traces"): {
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
component.MustNewID("traces"): {
Receivers: []component.ID{component.MustNewID("nop")},
Processors: []component.ID{component.MustNewID("nop")},
Exporters: []component.ID{component.MustNewID("nop")},
},
},
},

View File

@ -18,6 +18,8 @@ import (
"go.opentelemetry.io/collector/receiver/receivertest"
)
var nopType = component.MustNewType("nop")
var testKinds = []struct {
kind string
factories map[component.Type]component.Factory
@ -25,31 +27,31 @@ var testKinds = []struct {
{
kind: "receiver",
factories: map[component.Type]component.Factory{
"nop": receivertest.NewNopFactory(),
nopType: receivertest.NewNopFactory(),
},
},
{
kind: "processor",
factories: map[component.Type]component.Factory{
"nop": processortest.NewNopFactory(),
nopType: processortest.NewNopFactory(),
},
},
{
kind: "exporter",
factories: map[component.Type]component.Factory{
"nop": exportertest.NewNopFactory(),
nopType: exportertest.NewNopFactory(),
},
},
{
kind: "connector",
factories: map[component.Type]component.Factory{
"nop": connectortest.NewNopFactory(),
nopType: connectortest.NewNopFactory(),
},
},
{
kind: "extension",
factories: map[component.Type]component.Factory{
"nop": extensiontest.NewNopFactory(),
nopType: extensiontest.NewNopFactory(),
},
},
}
@ -65,8 +67,8 @@ func TestUnmarshal(t *testing.T) {
require.NoError(t, cfgs.Unmarshal(conf))
assert.Equal(t, map[component.ID]component.Config{
component.NewID("nop"): tk.factories["nop"].CreateDefaultConfig(),
component.NewIDWithName("nop", "my"+tk.kind): tk.factories["nop"].CreateDefaultConfig(),
component.NewID(nopType): tk.factories[nopType].CreateDefaultConfig(),
component.NewIDWithName(nopType, "my"+tk.kind): tk.factories[nopType].CreateDefaultConfig(),
}, cfgs.Configs())
})
}

View File

@ -23,39 +23,39 @@ func TestLoadConfig(t *testing.T) {
// Verify extensions.
require.Len(t, cfg.Extensions, 2)
assert.Contains(t, cfg.Extensions, component.NewID("nop"))
assert.Contains(t, cfg.Extensions, component.NewIDWithName("nop", "myextension"))
assert.Contains(t, cfg.Extensions, component.MustNewID("nop"))
assert.Contains(t, cfg.Extensions, component.MustNewIDWithName("nop", "myextension"))
// Verify receivers
require.Len(t, cfg.Receivers, 2)
assert.Contains(t, cfg.Receivers, component.NewID("nop"))
assert.Contains(t, cfg.Receivers, component.NewIDWithName("nop", "myreceiver"))
assert.Contains(t, cfg.Receivers, component.MustNewID("nop"))
assert.Contains(t, cfg.Receivers, component.MustNewIDWithName("nop", "myreceiver"))
// Verify exporters
assert.Len(t, cfg.Exporters, 2)
assert.Contains(t, cfg.Exporters, component.NewID("nop"))
assert.Contains(t, cfg.Exporters, component.NewIDWithName("nop", "myexporter"))
assert.Contains(t, cfg.Exporters, component.MustNewID("nop"))
assert.Contains(t, cfg.Exporters, component.MustNewIDWithName("nop", "myexporter"))
// Verify procs
assert.Len(t, cfg.Processors, 2)
assert.Contains(t, cfg.Processors, component.NewID("nop"))
assert.Contains(t, cfg.Processors, component.NewIDWithName("nop", "myprocessor"))
assert.Contains(t, cfg.Processors, component.MustNewID("nop"))
assert.Contains(t, cfg.Processors, component.MustNewIDWithName("nop", "myprocessor"))
// Verify connectors
assert.Len(t, cfg.Connectors, 1)
assert.Contains(t, cfg.Connectors, component.NewIDWithName("nop", "myconnector"))
assert.Contains(t, cfg.Connectors, component.MustNewIDWithName("nop", "myconnector"))
// Verify service.
require.Len(t, cfg.Service.Extensions, 1)
assert.Contains(t, cfg.Service.Extensions, component.NewID("nop"))
assert.Contains(t, cfg.Service.Extensions, component.MustNewID("nop"))
require.Len(t, cfg.Service.Pipelines, 1)
assert.Equal(t,
&pipelines.PipelineConfig{
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
Receivers: []component.ID{component.MustNewID("nop")},
Processors: []component.ID{component.MustNewID("nop")},
Exporters: []component.ID{component.MustNewID("nop")},
},
cfg.Service.Pipelines[component.NewID("traces")],
cfg.Service.Pipelines[component.MustNewID("traces")],
"Did not load pipeline config correctly")
}

View File

@ -11,32 +11,34 @@ import (
"go.opentelemetry.io/collector/component"
)
var nopType = component.MustNewType("nop")
func TestNopFactories(t *testing.T) {
nopFactories, err := NopFactories()
require.NoError(t, err)
require.Equal(t, 1, len(nopFactories.Receivers))
nopReceiverFactory, ok := nopFactories.Receivers["nop"]
nopReceiverFactory, ok := nopFactories.Receivers[nopType]
require.True(t, ok)
require.Equal(t, component.Type("nop"), nopReceiverFactory.Type())
require.Equal(t, nopType, nopReceiverFactory.Type())
require.Equal(t, 1, len(nopFactories.Processors))
nopProcessorFactory, ok := nopFactories.Processors["nop"]
nopProcessorFactory, ok := nopFactories.Processors[nopType]
require.True(t, ok)
require.Equal(t, component.Type("nop"), nopProcessorFactory.Type())
require.Equal(t, nopType, nopProcessorFactory.Type())
require.Equal(t, 1, len(nopFactories.Exporters))
nopExporterFactory, ok := nopFactories.Exporters["nop"]
nopExporterFactory, ok := nopFactories.Exporters[nopType]
require.True(t, ok)
require.Equal(t, component.Type("nop"), nopExporterFactory.Type())
require.Equal(t, nopType, nopExporterFactory.Type())
require.Equal(t, 1, len(nopFactories.Extensions))
nopExtensionFactory, ok := nopFactories.Extensions["nop"]
nopExtensionFactory, ok := nopFactories.Extensions[nopType]
require.True(t, ok)
require.Equal(t, component.Type("nop"), nopExtensionFactory.Type())
require.Equal(t, nopType, nopExtensionFactory.Type())
require.Equal(t, 1, len(nopFactories.Connectors))
nopConnectorFactory, ok := nopFactories.Connectors["nop"]
nopConnectorFactory, ok := nopFactories.Connectors[nopType]
require.True(t, ok)
require.Equal(t, component.Type("nop"), nopConnectorFactory.Type())
require.Equal(t, nopType, nopConnectorFactory.Type())
}

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("batch")
)
const (
Type = "batch"
TracesStability = component.StabilityLevelBeta
MetricsStability = component.StabilityLevelBeta
LogsStability = component.StabilityLevelBeta

View File

@ -75,7 +75,7 @@ func setupTelemetry(t *testing.T) testTelemetry {
func (tt *testTelemetry) NewProcessorCreateSettings() processor.CreateSettings {
settings := processortest.NewNopCreateSettings()
settings.MeterProvider = tt.meterProvider
settings.ID = component.NewID(typeStr)
settings.ID = component.MustNewID("batch")
return settings
}

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("memory_limiter")
)
const (
Type = "memory_limiter"
TracesStability = component.StabilityLevelBeta
MetricsStability = component.StabilityLevelBeta
LogsStability = component.StabilityLevelBeta

View File

@ -467,7 +467,7 @@ type host struct {
func (h *host) GetExtensions() map[component.ID]component.Component {
ret := make(map[component.ID]component.Component)
ret[component.NewID("ballast")] = &ballastExtension{ballastSize: h.ballastSize}
ret[component.MustNewID("ballast")] = &ballastExtension{ballastSize: h.ballastSize}
return ret
}

View File

@ -17,12 +17,12 @@ import (
)
func TestNewFactory(t *testing.T) {
const typeStr = "test"
var testType = component.MustNewType("test")
defaultCfg := struct{}{}
factory := NewFactory(
typeStr,
testType,
func() component.Config { return &defaultCfg })
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
_, err := factory.CreateTracesProcessor(context.Background(), CreateSettings{}, &defaultCfg, nil)
assert.Error(t, err)
@ -33,15 +33,15 @@ func TestNewFactory(t *testing.T) {
}
func TestNewFactoryWithOptions(t *testing.T) {
const typeStr = "test"
var testType = component.MustNewType("test")
defaultCfg := struct{}{}
factory := NewFactory(
typeStr,
testType,
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelAlpha),
WithMetrics(createMetrics, component.StabilityLevelBeta),
WithLogs(createLogs, component.StabilityLevelUnmaintained))
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
assert.Equal(t, component.StabilityLevelAlpha, factory.TracesProcessorStability())
@ -64,8 +64,8 @@ func TestMakeFactoryMap(t *testing.T) {
out map[component.Type]Factory
}
p1 := NewFactory("p1", nil)
p2 := NewFactory("p2", nil)
p1 := NewFactory(component.MustNewType("p1"), nil)
p2 := NewFactory(component.MustNewType("p2"), nil)
testCases := []testCase{
{
name: "different names",
@ -77,7 +77,7 @@ func TestMakeFactoryMap(t *testing.T) {
},
{
name: "same name",
in: []Factory{p1, p2, NewFactory("p1", nil)},
in: []Factory{p1, p2, NewFactory(component.MustNewType("p1"), nil)},
},
}
@ -98,9 +98,9 @@ func TestMakeFactoryMap(t *testing.T) {
func TestBuilder(t *testing.T) {
defaultCfg := struct{}{}
factories, err := MakeFactoryMap([]Factory{
NewFactory("err", nil),
NewFactory(component.MustNewType("err"), nil),
NewFactory(
"all",
component.MustNewType("all"),
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelDevelopment),
WithMetrics(createMetrics, component.StabilityLevelAlpha),
@ -116,21 +116,21 @@ func TestBuilder(t *testing.T) {
}{
{
name: "unknown",
id: component.NewID("unknown"),
id: component.MustNewID("unknown"),
err: "processor factory not available for: \"unknown\"",
},
{
name: "err",
id: component.NewID("err"),
id: component.MustNewID("err"),
err: "telemetry type is not supported",
},
{
name: "all",
id: component.NewID("all"),
id: component.MustNewID("all"),
},
{
name: "all/named",
id: component.NewIDWithName("all", "named"),
id: component.MustNewIDWithName("all", "named"),
},
}
@ -173,7 +173,7 @@ func TestBuilderMissingConfig(t *testing.T) {
defaultCfg := struct{}{}
factories, err := MakeFactoryMap([]Factory{
NewFactory(
"all",
component.MustNewType("all"),
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelDevelopment),
WithMetrics(createMetrics, component.StabilityLevelAlpha),
@ -184,7 +184,7 @@ func TestBuilderMissingConfig(t *testing.T) {
require.NoError(t, err)
bErr := NewBuilder(map[component.ID]component.Config{}, factories)
missingID := component.NewIDWithName("all", "missing")
missingID := component.MustNewIDWithName("all", "missing")
te, err := bErr.CreateTraces(context.Background(), createSettings(missingID), nil)
assert.EqualError(t, err, "processor \"all/missing\" is not configured")
@ -200,14 +200,14 @@ func TestBuilderMissingConfig(t *testing.T) {
}
func TestBuilderFactory(t *testing.T) {
factories, err := MakeFactoryMap([]Factory{NewFactory("foo", nil)}...)
factories, err := MakeFactoryMap([]Factory{NewFactory(component.MustNewType("foo"), nil)}...)
require.NoError(t, err)
cfgs := map[component.ID]component.Config{component.NewID("foo"): struct{}{}}
cfgs := map[component.ID]component.Config{component.MustNewID("foo"): struct{}{}}
b := NewBuilder(cfgs, factories)
assert.NotNil(t, b.Factory(component.NewID("foo").Type()))
assert.Nil(t, b.Factory(component.NewID("bar").Type()))
assert.NotNil(t, b.Factory(component.MustNewID("foo").Type()))
assert.Nil(t, b.Factory(component.MustNewID("bar").Type()))
}
var nopInstance = &nopProcessor{

View File

@ -16,7 +16,7 @@ import (
)
var (
processorID = component.NewID("fakeProcessor")
processorID = component.MustNewID("fakeProcessor")
)
func TestProcessorTraceData(t *testing.T) {

View File

@ -13,11 +13,12 @@ import (
"go.opentelemetry.io/collector/processor"
)
const typeStr = "nop"
var nopType = component.MustNewType("nop")
// NewNopCreateSettings returns a new nop settings for Create* functions.
func NewNopCreateSettings() processor.CreateSettings {
return processor.CreateSettings{
ID: component.NewID(nopType),
TelemetrySettings: componenttest.NewNopTelemetrySettings(),
BuildInfo: component.NewDefaultBuildInfo(),
}
@ -26,7 +27,7 @@ func NewNopCreateSettings() processor.CreateSettings {
// NewNopFactory returns a component.ProcessorFactory that constructs nop processors.
func NewNopFactory() processor.Factory {
return processor.NewFactory(
"nop",
nopType,
func() component.Config { return &nopConfig{} },
processor.WithTraces(createTracesProcessor, component.StabilityLevelStable),
processor.WithMetrics(createMetricsProcessor, component.StabilityLevelStable),
@ -63,6 +64,6 @@ type nopProcessor struct {
func NewNopBuilder() *processor.Builder {
nopFactory := NewNopFactory()
return processor.NewBuilder(
map[component.ID]component.Config{component.NewID(typeStr): nopFactory.CreateDefaultConfig()},
map[component.Type]processor.Factory{typeStr: nopFactory})
map[component.ID]component.Config{component.NewID(nopType): nopFactory.CreateDefaultConfig()},
map[component.Type]processor.Factory{nopType: nopFactory})
}

View File

@ -22,7 +22,7 @@ import (
func TestNewNopFactory(t *testing.T) {
factory := NewNopFactory()
require.NotNil(t, factory)
assert.Equal(t, component.Type("nop"), factory.Type())
assert.Equal(t, component.MustNewType("nop"), factory.Type())
cfg := factory.CreateDefaultConfig()
assert.Equal(t, &nopConfig{}, cfg)
@ -55,7 +55,7 @@ func TestNewNopBuilder(t *testing.T) {
factory := NewNopFactory()
cfg := factory.CreateDefaultConfig()
set := NewNopCreateSettings()
set.ID = component.NewID(typeStr)
set.ID = component.NewID(nopType)
traces, err := factory.CreateTracesProcessor(context.Background(), set, cfg, consumertest.NewNop())
require.NoError(t, err)

View File

@ -24,7 +24,7 @@ func NewUnhealthyProcessorCreateSettings() processor.CreateSettings {
// NewUnhealthyProcessorFactory returns a component.ProcessorFactory that constructs nop processors.
func NewUnhealthyProcessorFactory() processor.Factory {
return processor.NewFactory(
"unhealthy",
component.MustNewType("unhealthy"),
func() component.Config {
return &struct{}{}
},

View File

@ -22,7 +22,7 @@ import (
func TestNewUnhealthyProcessorFactory(t *testing.T) {
factory := NewUnhealthyProcessorFactory()
require.NotNil(t, factory)
assert.Equal(t, component.Type("unhealthy"), factory.Type())
assert.Equal(t, component.MustNewType("unhealthy"), factory.Type())
cfg := factory.CreateDefaultConfig()
assert.Equal(t, &struct{}{}, cfg)

View File

@ -92,7 +92,7 @@ func otlpReceiverOnGRPCServer(t *testing.T, lc consumer.Logs) net.Addr {
})
set := receivertest.NewNopCreateSettings()
set.ID = component.NewIDWithName("otlp", "log")
set.ID = component.MustNewIDWithName("otlp", "log")
obsreport, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: set.ID,
Transport: "grpc",

View File

@ -9,8 +9,11 @@ import (
"go.opentelemetry.io/collector/component"
)
var (
Type = component.MustNewType("otlp")
)
const (
Type = "otlp"
LogsStability = component.StabilityLevelBeta
TracesStability = component.StabilityLevelStable
MetricsStability = component.StabilityLevelStable

View File

@ -93,7 +93,7 @@ func otlpReceiverOnGRPCServer(t *testing.T, mc consumer.Metrics) net.Addr {
})
set := receivertest.NewNopCreateSettings()
set.ID = component.NewIDWithName("otlp", "metrics")
set.ID = component.MustNewIDWithName("otlp", "metrics")
obsreport, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: set.ID,
Transport: "grpc",

View File

@ -89,7 +89,7 @@ func otlpReceiverOnGRPCServer(t *testing.T, tc consumer.Traces) net.Addr {
})
set := receivertest.NewNopCreateSettings()
set.ID = component.NewIDWithName("otlp", "trace")
set.ID = component.MustNewIDWithName("otlp", "trace")
obsreport, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: set.ID,
Transport: "grpc",

View File

@ -48,7 +48,7 @@ import (
const otlpReceiverName = "receiver_test"
var otlpReceiverID = component.NewIDWithName("otlp", otlpReceiverName)
var otlpReceiverID = component.MustNewIDWithName("otlp", otlpReceiverName)
func TestJsonHttp(t *testing.T) {
tests := []struct {

View File

@ -17,12 +17,12 @@ import (
)
func TestNewFactory(t *testing.T) {
const typeStr = "test"
var testType = component.MustNewType("test")
defaultCfg := struct{}{}
factory := NewFactory(
typeStr,
testType,
func() component.Config { return &defaultCfg })
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
_, err := factory.CreateTracesReceiver(context.Background(), CreateSettings{}, &defaultCfg, nil)
assert.Error(t, err)
@ -33,15 +33,15 @@ func TestNewFactory(t *testing.T) {
}
func TestNewFactoryWithOptions(t *testing.T) {
const typeStr = "test"
var testType = component.MustNewType("test")
defaultCfg := struct{}{}
factory := NewFactory(
typeStr,
testType,
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelDeprecated),
WithMetrics(createMetrics, component.StabilityLevelAlpha),
WithLogs(createLogs, component.StabilityLevelStable))
assert.EqualValues(t, typeStr, factory.Type())
assert.EqualValues(t, testType, factory.Type())
assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())
assert.Equal(t, component.StabilityLevelDeprecated, factory.TracesReceiverStability())
@ -64,8 +64,8 @@ func TestMakeFactoryMap(t *testing.T) {
out map[component.Type]Factory
}
p1 := NewFactory("p1", nil)
p2 := NewFactory("p2", nil)
p1 := NewFactory(component.MustNewType("p1"), nil)
p2 := NewFactory(component.MustNewType("p2"), nil)
testCases := []testCase{
{
name: "different names",
@ -77,7 +77,7 @@ func TestMakeFactoryMap(t *testing.T) {
},
{
name: "same name",
in: []Factory{p1, p2, NewFactory("p1", nil)},
in: []Factory{p1, p2, NewFactory(component.MustNewType("p1"), nil)},
},
}
@ -98,9 +98,9 @@ func TestMakeFactoryMap(t *testing.T) {
func TestBuilder(t *testing.T) {
defaultCfg := struct{}{}
factories, err := MakeFactoryMap([]Factory{
NewFactory("err", nil),
NewFactory(component.MustNewType("err"), nil),
NewFactory(
"all",
component.MustNewType("all"),
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelDevelopment),
WithMetrics(createMetrics, component.StabilityLevelAlpha),
@ -116,21 +116,21 @@ func TestBuilder(t *testing.T) {
}{
{
name: "unknown",
id: component.NewID("unknown"),
id: component.MustNewID("unknown"),
err: "receiver factory not available for: \"unknown\"",
},
{
name: "err",
id: component.NewID("err"),
id: component.MustNewID("err"),
err: "telemetry type is not supported",
},
{
name: "all",
id: component.NewID("all"),
id: component.MustNewID("all"),
},
{
name: "all/named",
id: component.NewIDWithName("all", "named"),
id: component.MustNewIDWithName("all", "named"),
},
}
@ -173,7 +173,7 @@ func TestBuilderMissingConfig(t *testing.T) {
defaultCfg := struct{}{}
factories, err := MakeFactoryMap([]Factory{
NewFactory(
"all",
component.MustNewType("all"),
func() component.Config { return &defaultCfg },
WithTraces(createTraces, component.StabilityLevelDevelopment),
WithMetrics(createMetrics, component.StabilityLevelAlpha),
@ -184,7 +184,7 @@ func TestBuilderMissingConfig(t *testing.T) {
require.NoError(t, err)
bErr := NewBuilder(map[component.ID]component.Config{}, factories)
missingID := component.NewIDWithName("all", "missing")
missingID := component.MustNewIDWithName("all", "missing")
te, err := bErr.CreateTraces(context.Background(), createSettings(missingID), nil)
assert.EqualError(t, err, "receiver \"all/missing\" is not configured")
@ -200,14 +200,14 @@ func TestBuilderMissingConfig(t *testing.T) {
}
func TestBuilderFactory(t *testing.T) {
factories, err := MakeFactoryMap([]Factory{NewFactory("foo", nil)}...)
factories, err := MakeFactoryMap([]Factory{NewFactory(component.MustNewType("foo"), nil)}...)
require.NoError(t, err)
cfgs := map[component.ID]component.Config{component.NewID("foo"): struct{}{}}
cfgs := map[component.ID]component.Config{component.MustNewID("foo"): struct{}{}}
b := NewBuilder(cfgs, factories)
assert.NotNil(t, b.Factory(component.NewID("foo").Type()))
assert.Nil(t, b.Factory(component.NewID("bar").Type()))
assert.NotNil(t, b.Factory(component.MustNewID("foo").Type()))
assert.Nil(t, b.Factory(component.MustNewID("bar").Type()))
}
var nopInstance = &nopReceiver{

View File

@ -25,7 +25,7 @@ const (
)
var (
receiverID = component.NewID("fakeReceiver")
receiverID = component.MustNewID("fakeReceiver")
errFake = errors.New("errFake")
)

View File

@ -83,7 +83,7 @@ func (g *exampleGenerator) Generate() []UniqueIDAttrVal {
func newExampleFactory() receiver.Factory {
return receiver.NewFactory(
"example_receiver",
component.MustNewType("example_receiver"),
func() component.Config {
return &exampleReceiverConfig{}
},

View File

@ -12,11 +12,12 @@ import (
"go.opentelemetry.io/collector/receiver"
)
const typeStr = "nop"
var componentType = component.MustNewType("nop")
// NewNopCreateSettings returns a new nop settings for Create* functions.
func NewNopCreateSettings() receiver.CreateSettings {
return receiver.CreateSettings{
ID: component.NewID(componentType),
TelemetrySettings: componenttest.NewNopTelemetrySettings(),
BuildInfo: component.NewDefaultBuildInfo(),
}
@ -25,7 +26,7 @@ func NewNopCreateSettings() receiver.CreateSettings {
// NewNopFactory returns a receiver.Factory that constructs nop receivers.
func NewNopFactory() receiver.Factory {
return receiver.NewFactory(
"nop",
componentType,
func() component.Config { return &nopConfig{} },
receiver.WithTraces(createTraces, component.StabilityLevelStable),
receiver.WithMetrics(createMetrics, component.StabilityLevelStable),
@ -58,6 +59,6 @@ type nopReceiver struct {
func NewNopBuilder() *receiver.Builder {
nopFactory := NewNopFactory()
return receiver.NewBuilder(
map[component.ID]component.Config{component.NewID(typeStr): nopFactory.CreateDefaultConfig()},
map[component.Type]receiver.Factory{typeStr: nopFactory})
map[component.ID]component.Config{component.NewID(componentType): nopFactory.CreateDefaultConfig()},
map[component.Type]receiver.Factory{componentType: nopFactory})
}

View File

@ -15,10 +15,12 @@ import (
"go.opentelemetry.io/collector/consumer/consumertest"
)
var nopType = component.MustNewType("nop")
func TestNewNopFactory(t *testing.T) {
factory := NewNopFactory()
require.NotNil(t, factory)
assert.Equal(t, component.Type("nop"), factory.Type())
assert.Equal(t, nopType, factory.Type())
cfg := factory.CreateDefaultConfig()
assert.Equal(t, &nopConfig{}, cfg)
@ -45,7 +47,7 @@ func TestNewNopBuilder(t *testing.T) {
factory := NewNopFactory()
cfg := factory.CreateDefaultConfig()
set := NewNopCreateSettings()
set.ID = component.NewID(typeStr)
set.ID = component.NewID(nopType)
traces, err := factory.CreateTracesReceiver(context.Background(), set, cfg, consumertest.NewNop())
require.NoError(t, err)

View File

@ -130,7 +130,7 @@ func (s *ObsReport) EndMetricsOp(
// end span according to errors
if span.IsRecording() {
span.SetAttributes(
attribute.String(obsmetrics.FormatKey, string(component.DataTypeMetrics)),
attribute.String(obsmetrics.FormatKey, component.DataTypeMetrics.String()),
attribute.Int64(obsmetrics.ScrapedMetricPointsKey, int64(numScrapedMetrics)),
attribute.Int64(obsmetrics.ErroredMetricPointsKey, int64(numErroredMetrics)),
)

View File

@ -21,8 +21,8 @@ import (
)
var (
receiverID = component.NewID("fakeReceiver")
scraperID = component.NewID("fakeScraper")
receiverID = component.MustNewID("fakeReceiver")
scraperID = component.MustNewID("fakeScraper")
errFake = errors.New("errFake")
partialErrFake = scrapererror.NewPartialScrapeError(errFake, 1)

View File

@ -67,7 +67,7 @@ func NewScraper(name string, scrape ScrapeFunc, options ...ScraperOption) (Scrap
}
bs := &baseScraper{
ScrapeFunc: scrape,
id: component.NewID(component.Type(name)),
id: component.NewID(component.MustNewType(name)),
}
for _, op := range options {
op(bs)

View File

@ -134,7 +134,7 @@ func TestScrapeController(t *testing.T) {
for _, test := range testCases {
test := test
t.Run(test.name, func(t *testing.T) {
receiverID := component.NewID("receiver")
receiverID := component.MustNewID("receiver")
tt, err := componenttest.SetupTelemetry(receiverID)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
@ -326,7 +326,7 @@ func assertScraperViews(t *testing.T, tt componenttest.TestTelemetry, expectedEr
}
}
require.NoError(t, tt.CheckScraperMetrics(component.NewID("receiver"), component.NewID("scraper"), expectedScraped, expectedErrored))
require.NoError(t, tt.CheckScraperMetrics(component.MustNewID("receiver"), component.MustNewID("scraper"), expectedScraped, expectedErrored))
}
func TestSingleScrapePerInterval(t *testing.T) {
@ -337,7 +337,7 @@ func TestSingleScrapePerInterval(t *testing.T) {
tickerCh := make(chan time.Time)
scp, err := NewScraper("", tsm.scrape)
scp, err := NewScraper("scaper", tsm.scrape)
assert.NoError(t, err)
receiver, err := NewScraperControllerReceiver(
@ -379,7 +379,7 @@ func TestScrapeControllerStartsOnInit(t *testing.T) {
ch: make(chan int, 1),
}
scp, err := NewScraper("", tsm.scrape)
scp, err := NewScraper("scraper", tsm.scrape)
require.NoError(t, err, "Must not error when creating scraper")
r, err := NewScraperControllerReceiver(

View File

@ -8,6 +8,8 @@ import (
"time"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/collector/component"
)
func TestScrapeControllerSettings(t *testing.T) {
@ -20,7 +22,7 @@ func TestScrapeControllerSettings(t *testing.T) {
}{
{
name: "default configuration",
set: NewDefaultScraperControllerSettings(""),
set: NewDefaultScraperControllerSettings(component.MustNewType("test")),
errVal: "",
},
{

View File

@ -42,7 +42,7 @@ func TestConfigValidate(t *testing.T) {
name: "duplicate-processor-reference",
cfgFn: func() *Config {
cfg := generateConfig()
pipe := cfg.Pipelines[component.NewID("traces")]
pipe := cfg.Pipelines[component.MustNewID("traces")]
pipe.Processors = append(pipe.Processors, pipe.Processors...)
return cfg
},
@ -52,10 +52,10 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-service-pipeline-type",
cfgFn: func() *Config {
cfg := generateConfig()
cfg.Pipelines[component.NewID("wrongtype")] = &pipelines.PipelineConfig{
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
cfg.Pipelines[component.MustNewID("wrongtype")] = &pipelines.PipelineConfig{
Receivers: []component.ID{component.MustNewID("nop")},
Processors: []component.ID{component.MustNewID("nop")},
Exporters: []component.ID{component.MustNewID("nop")},
}
return cfg
},
@ -99,12 +99,12 @@ func generateConfig() *Config {
Address: ":8080",
},
},
Extensions: extensions.Config{component.NewID("nop")},
Extensions: extensions.Config{component.MustNewID("nop")},
Pipelines: pipelines.Config{
component.NewID("traces"): {
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
component.MustNewID("traces"): {
Receivers: []component.ID{component.MustNewID("nop")},
Processors: []component.ID{component.MustNewID("nop")},
Exporters: []component.ID{component.MustNewID("nop")},
},
},
}

View File

@ -38,17 +38,17 @@ func TestBuildExtensions(t *testing.T) {
{
name: "extension_not_configured",
config: Config{
component.NewID("myextension"),
component.MustNewID("myextension"),
},
wantErrMsg: "failed to create extension \"myextension\": extension \"myextension\" is not configured",
},
{
name: "missing_extension_factory",
extensionsConfigs: map[component.ID]component.Config{
component.NewID("unknown"): nopExtensionConfig,
component.MustNewID("unknown"): nopExtensionConfig,
},
config: Config{
component.NewID("unknown"),
component.MustNewID("unknown"),
},
wantErrMsg: "failed to create extension \"unknown\": extension factory not available for: \"unknown\"",
},
@ -212,11 +212,11 @@ func TestNotifyConfig(t *testing.T) {
notificationError := errors.New("Error processing config")
nopExtensionFactory := extensiontest.NewNopFactory()
nopExtensionConfig := nopExtensionFactory.CreateDefaultConfig()
n1ExtensionFactory := newConfigWatcherExtensionFactory("notifiable1", func() error { return nil })
n1ExtensionFactory := newConfigWatcherExtensionFactory(component.MustNewType("notifiable1"), func() error { return nil })
n1ExtensionConfig := n1ExtensionFactory.CreateDefaultConfig()
n2ExtensionFactory := newConfigWatcherExtensionFactory("notifiable2", func() error { return nil })
n2ExtensionFactory := newConfigWatcherExtensionFactory(component.MustNewType("notifiable2"), func() error { return nil })
n2ExtensionConfig := n1ExtensionFactory.CreateDefaultConfig()
nErrExtensionFactory := newConfigWatcherExtensionFactory("notifiableErr", func() error { return notificationError })
nErrExtensionFactory := newConfigWatcherExtensionFactory(component.MustNewType("notifiableErr"), func() error { return notificationError })
nErrExtensionConfig := nErrExtensionFactory.CreateDefaultConfig()
tests := []struct {
@ -230,52 +230,52 @@ func TestNotifyConfig(t *testing.T) {
{
name: "No notifiable extensions",
factories: map[component.Type]extension.Factory{
"nop": nopExtensionFactory,
component.MustNewType("nop"): nopExtensionFactory,
},
extensionsConfigs: map[component.ID]component.Config{
component.NewID("nop"): nopExtensionConfig,
component.MustNewID("nop"): nopExtensionConfig,
},
serviceExtensions: []component.ID{
component.NewID("nop"),
component.MustNewID("nop"),
},
},
{
name: "One notifiable extension",
factories: map[component.Type]extension.Factory{
"notifiable1": n1ExtensionFactory,
component.MustNewType("notifiable1"): n1ExtensionFactory,
},
extensionsConfigs: map[component.ID]component.Config{
component.NewID("notifiable1"): n1ExtensionConfig,
component.MustNewID("notifiable1"): n1ExtensionConfig,
},
serviceExtensions: []component.ID{
component.NewID("notifiable1"),
component.MustNewID("notifiable1"),
},
},
{
name: "Multiple notifiable extensions",
factories: map[component.Type]extension.Factory{
"notifiable1": n1ExtensionFactory,
"notifiable2": n2ExtensionFactory,
component.MustNewType("notifiable1"): n1ExtensionFactory,
component.MustNewType("notifiable2"): n2ExtensionFactory,
},
extensionsConfigs: map[component.ID]component.Config{
component.NewID("notifiable1"): n1ExtensionConfig,
component.NewID("notifiable2"): n2ExtensionConfig,
component.MustNewID("notifiable1"): n1ExtensionConfig,
component.MustNewID("notifiable2"): n2ExtensionConfig,
},
serviceExtensions: []component.ID{
component.NewID("notifiable1"),
component.NewID("notifiable2"),
component.MustNewID("notifiable1"),
component.MustNewID("notifiable2"),
},
},
{
name: "Errors in extension notification",
factories: map[component.Type]extension.Factory{
"notifiableErr": nErrExtensionFactory,
component.MustNewType("notifiableErr"): nErrExtensionFactory,
},
extensionsConfigs: map[component.ID]component.Config{
component.NewID("notifiableErr"): nErrExtensionConfig,
component.MustNewID("notifiableErr"): nErrExtensionConfig,
},
serviceExtensions: []component.ID{
component.NewID("notifiableErr"),
component.MustNewID("notifiableErr"),
},
want: notificationError,
},
@ -335,7 +335,7 @@ func newConfigWatcherExtensionFactory(name component.Type, fn func() error) exte
func newBadExtensionFactory() extension.Factory {
return extension.NewFactory(
"bf",
component.MustNewType("bf"),
func() component.Config {
return &struct{}{}
},
@ -348,7 +348,7 @@ func newBadExtensionFactory() extension.Factory {
func newCreateErrorExtensionFactory() extension.Factory {
return extension.NewFactory(
"err",
component.MustNewType("err"),
func() component.Config {
return &struct{}{}
},
@ -410,14 +410,15 @@ func TestStatusReportedOnStartupShutdown(t *testing.T) {
},
} {
t.Run(tc.name, func(t *testing.T) {
compID := component.NewID("statustest")
factory := newStatusTestExtensionFactory("statustest", tc.startErr, tc.shutdownErr)
statusType := component.MustNewType("statustest")
compID := component.NewID(statusType)
factory := newStatusTestExtensionFactory(statusType, tc.startErr, tc.shutdownErr)
config := factory.CreateDefaultConfig()
extensionsConfigs := map[component.ID]component.Config{
compID: config,
}
factories := map[component.Type]extension.Factory{
"statustest": factory,
statusType: factory,
}
extensions, err := New(
context.Background(),
@ -484,7 +485,7 @@ func newStatusTestExtensionFactory(name component.Type, startErr, shutdownErr er
func newRecordingExtensionFactory(startCallback func(set extension.CreateSettings, host component.Host) error, shutdownCallback func(set extension.CreateSettings) error) extension.Factory {
return extension.NewFactory(
"recording",
component.MustNewType("recording"),
func() component.Config {
return &recordingExtensionConfig{}
},
@ -519,7 +520,7 @@ func (ext *recordingExtension) Dependencies() []component.ID {
}
deps := make([]component.ID, len(ext.config.dependencies))
for i, dep := range ext.config.dependencies {
deps[i] = component.NewIDWithName("recording", dep)
deps[i] = component.MustNewIDWithName("recording", dep)
}
return deps
}

View File

@ -25,7 +25,7 @@ func ReceiverLogger(logger *zap.Logger, id component.ID, dt component.DataType)
return logger.With(
zap.String(zapKindKey, strings.ToLower(component.KindReceiver.String())),
zap.String(zapNameKey, id.String()),
zap.String(zapDataTypeKey, string(dt)))
zap.String(zapDataTypeKey, dt.String()))
}
func ProcessorLogger(logger *zap.Logger, id component.ID, pipelineID component.ID) *zap.Logger {
@ -38,7 +38,7 @@ func ProcessorLogger(logger *zap.Logger, id component.ID, pipelineID component.I
func ExporterLogger(logger *zap.Logger, id component.ID, dt component.DataType) *zap.Logger {
return logger.With(
zap.String(zapKindKey, strings.ToLower(component.KindExporter.String())),
zap.String(zapDataTypeKey, string(dt)),
zap.String(zapDataTypeKey, dt.String()),
zap.String(zapNameKey, id.String()))
}
@ -52,6 +52,6 @@ func ConnectorLogger(logger *zap.Logger, id component.ID, expDT, rcvDT component
return logger.With(
zap.String(zapKindKey, strings.ToLower(component.KindConnector.String())),
zap.String(zapNameKey, id.String()),
zap.String(zapExporterInPipeline, string(expDT)),
zap.String(zapReceiverInPipeline, string(rcvDT)))
zap.String(zapExporterInPipeline, expDT.String()),
zap.String(zapReceiverInPipeline, rcvDT.String()))
}

File diff suppressed because it is too large Load Diff

View File

@ -61,7 +61,7 @@ type receiverNode struct {
func newReceiverNode(pipelineType component.DataType, recvID component.ID) *receiverNode {
return &receiverNode{
nodeID: newNodeID(receiverSeed, string(pipelineType), recvID.String()),
nodeID: newNodeID(receiverSeed, pipelineType.String(), recvID.String()),
componentID: recvID,
pipelineType: pipelineType,
}
@ -165,7 +165,7 @@ type exporterNode struct {
func newExporterNode(pipelineType component.DataType, exprID component.ID) *exporterNode {
return &exporterNode{
nodeID: newNodeID(exporterSeed, string(pipelineType), exprID.String()),
nodeID: newNodeID(exporterSeed, pipelineType.String(), exprID.String()),
componentID: exprID,
pipelineType: pipelineType,
}
@ -215,7 +215,7 @@ type connectorNode struct {
func newConnectorNode(exprPipelineType, rcvrPipelineType component.DataType, connID component.ID) *connectorNode {
return &connectorNode{
nodeID: newNodeID(connectorSeed, connID.String(), string(exprPipelineType), string(rcvrPipelineType)),
nodeID: newNodeID(connectorSeed, connID.String(), exprPipelineType.String(), rcvrPipelineType.String()),
componentID: connID,
exprPipelineType: exprPipelineType,
rcvrPipelineType: rcvrPipelineType,

View File

@ -55,7 +55,7 @@ func (g *Graph) HandleZPages(w http.ResponseWriter, r *http.Request) {
sumData.Rows = append(sumData.Rows, zpages.SummaryPipelinesTableRowData{
FullName: c.String(),
InputType: string(c.Type()),
InputType: c.Type().String(),
MutatesData: p.capabilitiesNode.getConsumer().Capabilities().MutatesData,
Receivers: recvIDs,
Processors: procIDs,

View File

@ -15,7 +15,7 @@ import (
"go.opentelemetry.io/collector/pdata/ptrace"
)
const connType = "exampleconnector"
var connType = component.MustNewType("exampleconnector")
// ExampleConnectorFactory is factory for ExampleConnector.
var ExampleConnectorFactory = connector.NewFactory(
@ -36,7 +36,7 @@ var ExampleConnectorFactory = connector.NewFactory(
)
var MockForwardConnectorFactory = connector.NewFactory(
"mockforward",
component.MustNewType("mockforward"),
createExampleConnectorDefaultConfig,
connector.WithTracesToTraces(createExampleTracesToTraces, component.StabilityLevelDevelopment),
connector.WithMetricsToMetrics(createExampleMetricsToMetrics, component.StabilityLevelDevelopment),

View File

@ -14,14 +14,13 @@ import (
"go.opentelemetry.io/collector/pdata/ptrace"
)
const (
typeStr = "exampleexporter"
stability = component.StabilityLevelDevelopment
)
var testType = component.MustNewType("exampleexporter")
const stability = component.StabilityLevelDevelopment
// ExampleExporterFactory is factory for ExampleExporter.
var ExampleExporterFactory = exporter.NewFactory(
typeStr,
testType,
createExporterDefaultConfig,
exporter.WithTraces(createTracesExporter, stability),
exporter.WithMetrics(createMetricsExporter, stability),

View File

@ -11,7 +11,7 @@ import (
"go.opentelemetry.io/collector/processor"
)
const procType = "exampleprocessor"
var procType = component.MustNewType("exampleprocessor")
// ExampleProcessorFactory is factory for ExampleProcessor.
var ExampleProcessorFactory = processor.NewFactory(

View File

@ -11,7 +11,7 @@ import (
"go.opentelemetry.io/collector/receiver"
)
const receiverType = component.Type("examplereceiver")
var receiverType = component.MustNewType("examplereceiver")
// ExampleReceiverFactory is factory for ExampleReceiver.
var ExampleReceiverFactory = receiver.NewFactory(

View File

@ -14,7 +14,7 @@ import (
"go.opentelemetry.io/collector/pdata/ptrace"
)
const routerType = "examplerouter"
var routerType = component.MustNewType("examplerouter")
// ExampleRouterFactory is factory for ExampleRouter.
var ExampleRouterFactory = connector.NewFactory(

View File

@ -31,8 +31,8 @@ func TestExampleRouter(t *testing.T) {
}
func TestTracesRouter(t *testing.T) {
leftID := component.NewIDWithName("sink", "left")
rightID := component.NewIDWithName("sink", "right")
leftID := component.MustNewIDWithName("sink", "left")
rightID := component.MustNewIDWithName("sink", "right")
sinkLeft := new(consumertest.TracesSink)
sinkRight := new(consumertest.TracesSink)
@ -70,8 +70,8 @@ func TestTracesRouter(t *testing.T) {
}
func TestMetricsRouter(t *testing.T) {
leftID := component.NewIDWithName("sink", "left")
rightID := component.NewIDWithName("sink", "right")
leftID := component.MustNewIDWithName("sink", "left")
rightID := component.MustNewIDWithName("sink", "right")
sinkLeft := new(consumertest.MetricsSink)
sinkRight := new(consumertest.MetricsSink)
@ -109,8 +109,8 @@ func TestMetricsRouter(t *testing.T) {
}
func TestLogsRouter(t *testing.T) {
leftID := component.NewIDWithName("sink", "left")
rightID := component.NewIDWithName("sink", "right")
leftID := component.MustNewIDWithName("sink", "left")
rightID := component.MustNewIDWithName("sink", "right")
sinkLeft := new(consumertest.LogsSink)
sinkRight := new(consumertest.LogsSink)

View File

@ -28,7 +28,7 @@ func TestConfigValidate(t *testing.T) {
name: "duplicate-processor-reference",
cfgFn: func() Config {
cfg := generateConfig()
pipe := cfg[component.NewID("traces")]
pipe := cfg[component.MustNewID("traces")]
pipe.Processors = append(pipe.Processors, pipe.Processors...)
return cfg
},
@ -38,7 +38,7 @@ func TestConfigValidate(t *testing.T) {
name: "missing-pipeline-receivers",
cfgFn: func() Config {
cfg := generateConfig()
cfg[component.NewID("traces")].Receivers = nil
cfg[component.MustNewID("traces")].Receivers = nil
return cfg
},
expected: fmt.Errorf(`pipeline "traces": %w`, errMissingServicePipelineReceivers),
@ -47,7 +47,7 @@ func TestConfigValidate(t *testing.T) {
name: "missing-pipeline-exporters",
cfgFn: func() Config {
cfg := generateConfig()
cfg[component.NewID("traces")].Exporters = nil
cfg[component.MustNewID("traces")].Exporters = nil
return cfg
},
expected: fmt.Errorf(`pipeline "traces": %w`, errMissingServicePipelineExporters),
@ -63,10 +63,10 @@ func TestConfigValidate(t *testing.T) {
name: "invalid-service-pipeline-type",
cfgFn: func() Config {
cfg := generateConfig()
cfg[component.NewID("wrongtype")] = &PipelineConfig{
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
cfg[component.MustNewID("wrongtype")] = &PipelineConfig{
Receivers: []component.ID{component.MustNewID("nop")},
Processors: []component.ID{component.MustNewID("nop")},
Exporters: []component.ID{component.MustNewID("nop")},
}
return cfg
},
@ -84,10 +84,10 @@ func TestConfigValidate(t *testing.T) {
func generateConfig() Config {
return map[component.ID]*PipelineConfig{
component.NewID("traces"): {
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
component.MustNewID("traces"): {
Receivers: []component.ID{component.MustNewID("nop")},
Processors: []component.ID{component.MustNewID("nop")},
Exporters: []component.ID{component.MustNewID("nop")},
},
}
}

View File

@ -168,6 +168,11 @@ func ownMetricsTestCases() []ownMetricsTestCase {
}}
}
var (
nopType = component.MustNewType("nop")
wrongType = component.MustNewType("wrong")
)
func TestServiceGetFactory(t *testing.T) {
set := newNopSettings()
srv, err := New(context.Background(), set, newNopConfig())
@ -178,23 +183,23 @@ func TestServiceGetFactory(t *testing.T) {
assert.NoError(t, srv.Shutdown(context.Background()))
})
assert.Nil(t, srv.host.GetFactory(component.KindReceiver, "wrongtype"))
assert.Equal(t, set.Receivers.Factory("nop"), srv.host.GetFactory(component.KindReceiver, "nop"))
assert.Nil(t, srv.host.GetFactory(component.KindReceiver, wrongType))
assert.Equal(t, set.Receivers.Factory(nopType), srv.host.GetFactory(component.KindReceiver, nopType))
assert.Nil(t, srv.host.GetFactory(component.KindProcessor, "wrongtype"))
assert.Equal(t, set.Processors.Factory("nop"), srv.host.GetFactory(component.KindProcessor, "nop"))
assert.Nil(t, srv.host.GetFactory(component.KindProcessor, wrongType))
assert.Equal(t, set.Processors.Factory(nopType), srv.host.GetFactory(component.KindProcessor, nopType))
assert.Nil(t, srv.host.GetFactory(component.KindExporter, "wrongtype"))
assert.Equal(t, set.Exporters.Factory("nop"), srv.host.GetFactory(component.KindExporter, "nop"))
assert.Nil(t, srv.host.GetFactory(component.KindExporter, wrongType))
assert.Equal(t, set.Exporters.Factory(nopType), srv.host.GetFactory(component.KindExporter, nopType))
assert.Nil(t, srv.host.GetFactory(component.KindConnector, "wrongtype"))
assert.Equal(t, set.Connectors.Factory("nop"), srv.host.GetFactory(component.KindConnector, "nop"))
assert.Nil(t, srv.host.GetFactory(component.KindConnector, wrongType))
assert.Equal(t, set.Connectors.Factory(nopType), srv.host.GetFactory(component.KindConnector, nopType))
assert.Nil(t, srv.host.GetFactory(component.KindExtension, "wrongtype"))
assert.Equal(t, set.Extensions.Factory("nop"), srv.host.GetFactory(component.KindExtension, "nop"))
assert.Nil(t, srv.host.GetFactory(component.KindExtension, wrongType))
assert.Equal(t, set.Extensions.Factory(nopType), srv.host.GetFactory(component.KindExtension, nopType))
// Try retrieve non existing component.Kind.
assert.Nil(t, srv.host.GetFactory(42, "nop"))
assert.Nil(t, srv.host.GetFactory(42, nopType))
}
func TestServiceGetExtensions(t *testing.T) {
@ -209,7 +214,7 @@ func TestServiceGetExtensions(t *testing.T) {
extMap := srv.host.GetExtensions()
assert.Len(t, extMap, 1)
assert.Contains(t, extMap, component.NewID("nop"))
assert.Contains(t, extMap, component.NewID(nopType))
}
func TestServiceGetExporters(t *testing.T) {
@ -224,18 +229,18 @@ func TestServiceGetExporters(t *testing.T) {
expMap := srv.host.GetExporters()
assert.Len(t, expMap, 3)
assert.Len(t, expMap[component.DataTypeTraces], 1)
assert.Contains(t, expMap[component.DataTypeTraces], component.NewID("nop"))
assert.Contains(t, expMap[component.DataTypeTraces], component.NewID(nopType))
assert.Len(t, expMap[component.DataTypeMetrics], 1)
assert.Contains(t, expMap[component.DataTypeMetrics], component.NewID("nop"))
assert.Contains(t, expMap[component.DataTypeMetrics], component.NewID(nopType))
assert.Len(t, expMap[component.DataTypeLogs], 1)
assert.Contains(t, expMap[component.DataTypeLogs], component.NewID("nop"))
assert.Contains(t, expMap[component.DataTypeLogs], component.NewID(nopType))
}
// TestServiceTelemetryCleanupOnError tests that if newService errors due to an invalid config telemetry is cleaned up
// and another service with a valid config can be started right after.
func TestServiceTelemetryCleanupOnError(t *testing.T) {
invalidCfg := newNopConfig()
invalidCfg.Pipelines[component.NewID("traces")].Processors[0] = component.NewID("invalid")
invalidCfg.Pipelines[component.MustNewID("traces")].Processors[0] = component.MustNewID("invalid")
// Create a service with an invalid config and expect an error
_, err := New(context.Background(), newNopSettings(), invalidCfg)
require.Error(t, err)
@ -270,12 +275,12 @@ func testCollectorStartHelper(t *testing.T, tc ownMetricsTestCase) {
set := newNopSettings()
set.BuildInfo = component.BuildInfo{Version: "test version", Command: otelCommand}
set.Extensions = extension.NewBuilder(
map[component.ID]component.Config{component.NewID("zpages"): &zpagesextension.Config{TCPAddr: confignet.TCPAddr{Endpoint: zpagesAddr}}},
map[component.Type]extension.Factory{"zpages": zpagesextension.NewFactory()})
map[component.ID]component.Config{component.MustNewID("zpages"): &zpagesextension.Config{TCPAddr: confignet.TCPAddr{Endpoint: zpagesAddr}}},
map[component.Type]extension.Factory{component.MustNewType("zpages"): zpagesextension.NewFactory()})
set.LoggingOptions = []zap.Option{zap.Hooks(hook)}
cfg := newNopConfig()
cfg.Extensions = []component.ID{component.NewID("zpages")}
cfg.Extensions = []component.ID{component.MustNewID("zpages")}
cfg.Telemetry.Metrics.Address = metricsAddr
cfg.Telemetry.Resource = make(map[string]*string)
// Include resource attributes under the service::telemetry::resource key.
@ -351,7 +356,7 @@ func TestExtensionNotificationFailure(t *testing.T) {
set := newNopSettings()
cfg := newNopConfig()
var extName component.Type = "configWatcher"
var extName = component.MustNewType("configWatcher")
configWatcherExtensionFactory := newConfigWatcherExtensionFactory(extName)
set.Extensions = extension.NewBuilder(
map[component.ID]component.Config{component.NewID(extName): configWatcherExtensionFactory.CreateDefaultConfig()},
@ -374,7 +379,7 @@ func TestNilCollectorEffectiveConfig(t *testing.T) {
set.CollectorConf = nil
cfg := newNopConfig()
var extName component.Type = "configWatcher"
var extName = component.MustNewType("configWatcher")
configWatcherExtensionFactory := newConfigWatcherExtensionFactory(extName)
set.Extensions = extension.NewBuilder(
map[component.ID]component.Config{component.NewID(extName): configWatcherExtensionFactory.CreateDefaultConfig()},
@ -527,27 +532,27 @@ func newNopSettings() Settings {
func newNopConfig() Config {
return newNopConfigPipelineConfigs(pipelines.Config{
component.NewID("traces"): {
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
component.MustNewID("traces"): {
Receivers: []component.ID{component.NewID(nopType)},
Processors: []component.ID{component.NewID(nopType)},
Exporters: []component.ID{component.NewID(nopType)},
},
component.NewID("metrics"): {
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
component.MustNewID("metrics"): {
Receivers: []component.ID{component.NewID(nopType)},
Processors: []component.ID{component.NewID(nopType)},
Exporters: []component.ID{component.NewID(nopType)},
},
component.NewID("logs"): {
Receivers: []component.ID{component.NewID("nop")},
Processors: []component.ID{component.NewID("nop")},
Exporters: []component.ID{component.NewID("nop")},
component.MustNewID("logs"): {
Receivers: []component.ID{component.NewID(nopType)},
Processors: []component.ID{component.NewID(nopType)},
Exporters: []component.ID{component.NewID(nopType)},
},
})
}
func newNopConfigPipelineConfigs(pipelineCfgs pipelines.Config) Config {
return Config{
Extensions: extensions.Config{component.NewID("nop")},
Extensions: extensions.Config{component.NewID(nopType)},
Pipelines: pipelineCfgs,
Telemetry: telemetry.Config{
Logs: telemetry.LogsConfig{