diff --git a/.chloggen/codeboten_rm-deprecatedjaegermods.yaml b/.chloggen/codeboten_rm-deprecatedjaegermods.yaml new file mode 100755 index 000000000000..38faf41c8c98 --- /dev/null +++ b/.chloggen/codeboten_rm-deprecatedjaegermods.yaml @@ -0,0 +1,31 @@ +# Use this changelog template to create an entry for release notes. + +# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix' +change_type: enhancement + +# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver) +component: jaegerreceiver,jaegerremotesamplingextension + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: mark featuregates to replace Thrift-gen with Proto-gen types for sampling strategies as stable + +# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. +issues: [27636] + +# (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: | + The following featuregates are stable: + - extension.jaegerremotesampling.replaceThriftWithProto + - receiver.jaegerreceiver.replaceThriftWithProto + +# If your change doesn't affect end users or the exported elements of any package, +# you should instead start your pull request title with [chore] or use the "Skip Changelog" label. +# 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: [] + \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 557e83ab53d2..9db096f041aa 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -103,7 +103,6 @@ extension/headerssetterextension/ @open-te extension/healthcheckextension/ @open-telemetry/collector-contrib-approvers @jpkrohling extension/httpforwarder/ @open-telemetry/collector-contrib-approvers @atoulme @rmfitzpatrick extension/jaegerremotesampling/ @open-telemetry/collector-contrib-approvers @jpkrohling @frzifus -extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/ @open-telemetry/collector-contrib-approvers @jpkrohling @frzifus extension/oauth2clientauthextension/ @open-telemetry/collector-contrib-approvers @pavankrish123 @jpkrohling extension/observer/ @open-telemetry/collector-contrib-approvers @dmitryax @rmfitzpatrick extension/observer/dockerobserver/ @open-telemetry/collector-contrib-approvers @MovieStoreGuy @@ -221,7 +220,6 @@ receiver/httpcheckreceiver/ @open-te receiver/iisreceiver/ @open-telemetry/collector-contrib-approvers @Mrod1598 @djaglowski receiver/influxdbreceiver/ @open-telemetry/collector-contrib-approvers @jacobmarble receiver/jaegerreceiver/ @open-telemetry/collector-contrib-approvers @jpkrohling -receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/ @open-telemetry/collector-contrib-approvers @jpkrohling receiver/jmxreceiver/ @open-telemetry/collector-contrib-approvers @rmfitzpatrick receiver/journaldreceiver/ @open-telemetry/collector-contrib-approvers @sumo-drosiek @djaglowski receiver/k8sclusterreceiver/ @open-telemetry/collector-contrib-approvers @dmitryax @TylerHelmuth @povilasv diff --git a/.github/ISSUE_TEMPLATE/bug_report.yaml b/.github/ISSUE_TEMPLATE/bug_report.yaml index 9e0d570e2b2f..050e78eeb78c 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yaml +++ b/.github/ISSUE_TEMPLATE/bug_report.yaml @@ -95,7 +95,6 @@ body: - extension/healthcheck - extension/httpforwarder - extension/jaegerremotesampling - - extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated - extension/oauth2clientauth - extension/observer - extension/observer/dockerobserver @@ -209,7 +208,6 @@ body: - receiver/iis - receiver/influxdb - receiver/jaeger - - receiver/jaeger/internal/jaegerreceiverdeprecated - receiver/jmx - receiver/journald - receiver/k8scluster diff --git a/.github/ISSUE_TEMPLATE/feature_request.yaml b/.github/ISSUE_TEMPLATE/feature_request.yaml index 0208530d2a80..b6d99c298db3 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yaml +++ b/.github/ISSUE_TEMPLATE/feature_request.yaml @@ -89,7 +89,6 @@ body: - extension/healthcheck - extension/httpforwarder - extension/jaegerremotesampling - - extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated - extension/oauth2clientauth - extension/observer - extension/observer/dockerobserver @@ -203,7 +202,6 @@ body: - receiver/iis - receiver/influxdb - receiver/jaeger - - receiver/jaeger/internal/jaegerreceiverdeprecated - receiver/jmx - receiver/journald - receiver/k8scluster diff --git a/.github/ISSUE_TEMPLATE/other.yaml b/.github/ISSUE_TEMPLATE/other.yaml index 5cfc9c3838e5..6c95e4dec60d 100644 --- a/.github/ISSUE_TEMPLATE/other.yaml +++ b/.github/ISSUE_TEMPLATE/other.yaml @@ -89,7 +89,6 @@ body: - extension/healthcheck - extension/httpforwarder - extension/jaegerremotesampling - - extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated - extension/oauth2clientauth - extension/observer - extension/observer/dockerobserver @@ -203,7 +202,6 @@ body: - receiver/iis - receiver/influxdb - receiver/jaeger - - receiver/jaeger/internal/jaegerreceiverdeprecated - receiver/jmx - receiver/journald - receiver/k8scluster diff --git a/exporter/logzioexporter/go.mod b/exporter/logzioexporter/go.mod index fbca2dffef46..2e927450596b 100644 --- a/exporter/logzioexporter/go.mod +++ b/exporter/logzioexporter/go.mod @@ -66,7 +66,7 @@ require ( go.opentelemetry.io/otel v1.21.0 // indirect go.opentelemetry.io/otel/metric v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect - go.uber.org/atomic v1.10.0 // indirect + go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/net v0.19.0 // indirect golang.org/x/sys v0.15.0 // indirect diff --git a/exporter/logzioexporter/go.sum b/exporter/logzioexporter/go.sum index ccbfdaa2b8fc..e7e7b43eee92 100644 --- a/exporter/logzioexporter/go.sum +++ b/exporter/logzioexporter/go.sum @@ -180,8 +180,8 @@ go.opentelemetry.io/otel/sdk v1.21.0 h1:FTt8qirL1EysG6sTQRZ5TokkU8d0ugCj8htOgThZ go.opentelemetry.io/otel/sdk/metric v1.21.0 h1:smhI5oD714d6jHE6Tie36fPx4WDFIg+Y6RfAY4ICcR0= go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc= go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= diff --git a/exporter/pulsarexporter/go.mod b/exporter/pulsarexporter/go.mod index 14f011dc5ebb..2d118d7acafc 100644 --- a/exporter/pulsarexporter/go.mod +++ b/exporter/pulsarexporter/go.mod @@ -77,7 +77,7 @@ require ( go.opentelemetry.io/otel v1.21.0 // indirect go.opentelemetry.io/otel/metric v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect - go.uber.org/atomic v1.10.0 // indirect + go.uber.org/atomic v1.11.0 // indirect golang.org/x/crypto v0.15.0 // indirect golang.org/x/net v0.18.0 // indirect golang.org/x/oauth2 v0.14.0 // indirect diff --git a/exporter/pulsarexporter/go.sum b/exporter/pulsarexporter/go.sum index a86e886bc80b..fc76c911a889 100644 --- a/exporter/pulsarexporter/go.sum +++ b/exporter/pulsarexporter/go.sum @@ -461,8 +461,8 @@ go.opentelemetry.io/otel/sdk/metric v1.21.0 h1:smhI5oD714d6jHE6Tie36fPx4WDFIg+Y6 go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc= go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= diff --git a/exporter/sapmexporter/go.mod b/exporter/sapmexporter/go.mod index bf0304f6ae60..3e999fbff22a 100644 --- a/exporter/sapmexporter/go.mod +++ b/exporter/sapmexporter/go.mod @@ -54,7 +54,7 @@ require ( go.opentelemetry.io/otel v1.21.0 // indirect go.opentelemetry.io/otel/metric v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect - go.uber.org/atomic v1.10.0 // indirect + go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/net v0.18.0 // indirect golang.org/x/sys v0.15.0 // indirect diff --git a/exporter/sapmexporter/go.sum b/exporter/sapmexporter/go.sum index 8f1966d32b67..31081cfb579c 100644 --- a/exporter/sapmexporter/go.sum +++ b/exporter/sapmexporter/go.sum @@ -153,8 +153,8 @@ go.opentelemetry.io/otel/sdk v1.21.0 h1:FTt8qirL1EysG6sTQRZ5TokkU8d0ugCj8htOgThZ go.opentelemetry.io/otel/sdk/metric v1.21.0 h1:smhI5oD714d6jHE6Tie36fPx4WDFIg+Y6RfAY4ICcR0= go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc= go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= diff --git a/extension/jaegerremotesampling/factory.go b/extension/jaegerremotesampling/factory.go index 5e58da518306..78a128f9134d 100644 --- a/extension/jaegerremotesampling/factory.go +++ b/extension/jaegerremotesampling/factory.go @@ -15,16 +15,11 @@ import ( "go.opentelemetry.io/collector/featuregate" "go.uber.org/zap" - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated" "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/metadata" ) // NewFactory creates a factory for the jaeger remote sampling extension. func NewFactory() extension.Factory { - if !protoGate.IsEnabled() { - return jaegerremotesamplingdeprecated.NewFactory() - } - return extension.NewFactory( metadata.Type, createDefaultConfig, @@ -56,14 +51,14 @@ func logDeprecation(logger *zap.Logger) { }) } -const protoInsteadOfThrift = "extension.jaegerremotesampling.replaceThriftWithProto" - +// nolint var protoGate = featuregate.GlobalRegistry().MustRegister( - protoInsteadOfThrift, - featuregate.StageBeta, + "extension.jaegerremotesampling.replaceThriftWithProto", + featuregate.StageStable, featuregate.WithRegisterDescription( "When enabled, the jaegerremotesampling will use Proto-gen over Thrift-gen.", ), + featuregate.WithRegisterToVersion("0.92.0"), ) func createExtension(_ context.Context, set extension.CreateSettings, cfg component.Config) (extension.Extension, error) { diff --git a/extension/jaegerremotesampling/go.mod b/extension/jaegerremotesampling/go.mod index fbb77e79d812..85137dc47776 100644 --- a/extension/jaegerremotesampling/go.mod +++ b/extension/jaegerremotesampling/go.mod @@ -5,7 +5,6 @@ go 1.20 require ( github.com/fortytw2/leaktest v1.3.0 github.com/jaegertracing/jaeger v1.48.0 - github.com/spf13/viper v1.17.0 github.com/stretchr/testify v1.8.4 github.com/tilinna/clock v1.1.0 go.opentelemetry.io/collector/component v0.90.2-0.20231201205146-6e2fdc755b34 @@ -53,6 +52,7 @@ require ( github.com/spf13/afero v1.10.0 // indirect github.com/spf13/cast v1.5.1 // indirect github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/viper v1.17.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect github.com/uber/jaeger-lib v2.4.1+incompatible // indirect diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/README.md b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/README.md deleted file mode 100644 index 7dae0b40c1b9..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# DO NOT USE THIS PACKAGE - -This package is a workaround to bump the jaeger dependency and will be removed soon. - -For more details see: https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/18485 diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/config.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/config.go deleted file mode 100644 index e7730c9791c5..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/config.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerremotesamplingdeprecated // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated" - -import ( - "errors" - "time" - - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" -) - -var ( - errTooManySources = errors.New("too many sources specified, has to be either 'file' or 'remote'") - errNoSources = errors.New("no sources specified, has to be either 'file' or 'remote'") - errAtLeastOneProtocol = errors.New("no protocols selected to serve the strategies, use 'grpc', 'http', or both") -) - -// Config has the configuration for the extension enabling the health check -// extension, used to report the health status of the service. -type Config struct { - *confighttp.HTTPServerSettings `mapstructure:"http"` - *configgrpc.GRPCServerSettings `mapstructure:"grpc"` - - // Source configures the source for the strategies file. One of `remote` or `file` has to be specified. - Source Source `mapstructure:"source"` -} - -type Source struct { - // Remote defines the remote location for the file - Remote *configgrpc.GRPCClientSettings `mapstructure:"remote"` - - // File specifies a local file as the strategies source - File string `mapstructure:"file"` - - // ReloadInterval determines the periodicity to refresh the strategies - ReloadInterval time.Duration `mapstructure:"reload_interval"` -} - -var _ component.Config = (*Config)(nil) - -// Validate checks if the extension configuration is valid -func (cfg *Config) Validate() error { - if cfg.HTTPServerSettings == nil && cfg.GRPCServerSettings == nil { - return errAtLeastOneProtocol - } - - if cfg.Source.File != "" && cfg.Source.Remote != nil { - return errTooManySources - } - - if cfg.Source.File == "" && cfg.Source.Remote == nil { - return errNoSources - } - - return nil -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/config_test.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/config_test.go deleted file mode 100644 index ec1081657ba8..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/config_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerremotesamplingdeprecated - -import ( - "path/filepath" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/config/confignet" - "go.opentelemetry.io/collector/confmap/confmaptest" - - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/metadata" -) - -func TestLoadConfig(t *testing.T) { - t.Parallel() - - tests := []struct { - id component.ID - expected component.Config - }{ - { - id: component.NewID(metadata.Type), - expected: &Config{ - HTTPServerSettings: &confighttp.HTTPServerSettings{Endpoint: ":5778"}, - GRPCServerSettings: &configgrpc.GRPCServerSettings{NetAddr: confignet.NetAddr{ - Endpoint: ":14250", - Transport: "tcp", - }}, - Source: Source{ - Remote: &configgrpc.GRPCClientSettings{ - Endpoint: "jaeger-collector:14250", - }, - }, - }, - }, - { - id: component.NewIDWithName(metadata.Type, "1"), - expected: &Config{ - HTTPServerSettings: &confighttp.HTTPServerSettings{Endpoint: ":5778"}, - GRPCServerSettings: &configgrpc.GRPCServerSettings{NetAddr: confignet.NetAddr{ - Endpoint: ":14250", - Transport: "tcp", - }}, - Source: Source{ - ReloadInterval: time.Second, - File: "/etc/otelcol/sampling_strategies.json", - }, - }, - }, - } - for _, tt := range tests { - t.Run(tt.id.String(), func(t *testing.T) { - cm, err := confmaptest.LoadConf(filepath.Join("testdata", "config.yaml")) - require.NoError(t, err) - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - sub, err := cm.Sub(tt.id.String()) - require.NoError(t, err) - require.NoError(t, component.UnmarshalConfig(sub, cfg)) - assert.NoError(t, component.ValidateConfig(cfg)) - assert.Equal(t, tt.expected, cfg) - }) - } -} - -func TestValidate(t *testing.T) { - - testCases := []struct { - desc string - cfg Config - expected error - }{ - { - desc: "no receiving protocols", - cfg: Config{}, - expected: errAtLeastOneProtocol, - }, - { - desc: "no sources", - cfg: Config{ - GRPCServerSettings: &configgrpc.GRPCServerSettings{}, - }, - expected: errNoSources, - }, - { - desc: "too many sources", - cfg: Config{ - GRPCServerSettings: &configgrpc.GRPCServerSettings{}, - Source: Source{ - Remote: &configgrpc.GRPCClientSettings{}, - File: "/tmp/some-file", - }, - }, - expected: errTooManySources, - }, - } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - res := tC.cfg.Validate() - assert.Equal(t, tC.expected, res) - }) - } -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/extension.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/extension.go deleted file mode 100644 index b1ab4ef9ae50..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/extension.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerremotesamplingdeprecated // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated" - -import ( - "context" - "fmt" - - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/extension" - "go.uber.org/zap" - - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal" - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static" -) - -var _ extension.Extension = (*jrsExtension)(nil) - -type jrsExtension struct { - cfg *Config - telemetry component.TelemetrySettings - - httpServer component.Component - grpcServer component.Component - samplingStore strategystore.StrategyStore - - closers []func() error -} - -func newExtension(cfg *Config, telemetry component.TelemetrySettings) *jrsExtension { - jrse := &jrsExtension{ - cfg: cfg, - telemetry: telemetry, - } - return jrse -} - -func (jrse *jrsExtension) Start(ctx context.Context, host component.Host) error { - // the config validation will take care of ensuring we have one and only one of the following about the - // source of the sampling config: - // - remote (gRPC) - // - local file - // we can then use a simplified logic here to assign the appropriate store - if jrse.cfg.Source.File != "" { - opts := static.Options{ - StrategiesFile: jrse.cfg.Source.File, - ReloadInterval: jrse.cfg.Source.ReloadInterval, - } - ss, err := static.NewStrategyStore(opts, jrse.telemetry.Logger) - if err != nil { - return fmt.Errorf("failed to create the local file strategy store: %w", err) - } - - // there's a Close function on the concrete type, which is not visible to us... - // how can we close it then? - jrse.samplingStore = ss - } - - if jrse.cfg.Source.Remote != nil { - conn, err := jrse.cfg.Source.Remote.ToClientConn(ctx, host, jrse.telemetry) - if err != nil { - return fmt.Errorf("failed to create the remote strategy store: %w", err) - } - jrse.closers = append(jrse.closers, conn.Close) - remoteStore, closer := internal.NewRemoteStrategyStore( - conn, - jrse.cfg.Source.Remote, - jrse.cfg.Source.ReloadInterval, - ) - jrse.closers = append(jrse.closers, closer.Close) - jrse.samplingStore = remoteStore - } - - if jrse.cfg.HTTPServerSettings != nil { - httpServer, err := internal.NewHTTP(jrse.telemetry, *jrse.cfg.HTTPServerSettings, jrse.samplingStore) - if err != nil { - return fmt.Errorf("error while creating the HTTP server: %w", err) - } - jrse.httpServer = httpServer - // then we start our own server interfaces, starting with the HTTP one - if err := jrse.httpServer.Start(ctx, host); err != nil { - return fmt.Errorf("error while starting the HTTP server: %w", err) - } - } - - if jrse.cfg.GRPCServerSettings != nil { - grpcServer, err := internal.NewGRPC(jrse.telemetry, *jrse.cfg.GRPCServerSettings, jrse.samplingStore) - if err != nil { - return fmt.Errorf("error while creating the gRPC server: %w", err) - } - jrse.grpcServer = grpcServer - // start our gRPC server interface - if err := jrse.grpcServer.Start(ctx, host); err != nil { - return fmt.Errorf("error while starting the gRPC server: %w", err) - } - } - - return nil -} - -func (jrse *jrsExtension) Shutdown(ctx context.Context) error { - // we probably don't want to break whenever an error occurs, we want to continue and close the other resources - if jrse.httpServer != nil { - if err := jrse.httpServer.Shutdown(ctx); err != nil { - jrse.telemetry.Logger.Error("error while shutting down the HTTP server", zap.Error(err)) - } - } - - if jrse.grpcServer != nil { - if err := jrse.grpcServer.Shutdown(ctx); err != nil { - jrse.telemetry.Logger.Error("error while shutting down the gRPC server", zap.Error(err)) - } - } - - for _, closer := range jrse.closers { - if err := closer(); err != nil { - jrse.telemetry.Logger.Error("error while shutting down the sampling store", zap.Error(err)) - } - } - - return nil -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/extension_test.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/extension_test.go deleted file mode 100644 index 7497ce089457..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/extension_test.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerremotesamplingdeprecated - -import ( - "context" - "fmt" - "net" - "net/http" - "path/filepath" - "testing" - "time" - - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component/componenttest" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/configopaque" - "go.opentelemetry.io/collector/config/configtls" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" -) - -func TestNewExtension(t *testing.T) { - // test - cfg := testConfig() - cfg.Source.File = filepath.Join("testdata", "strategy.json") - e := newExtension(cfg, componenttest.NewNopTelemetrySettings()) - - // verify - assert.NotNil(t, e) -} - -func TestStartAndShutdownLocalFile(t *testing.T) { - // prepare - cfg := testConfig() - cfg.Source.File = filepath.Join("testdata", "strategy.json") - - e := newExtension(cfg, componenttest.NewNopTelemetrySettings()) - require.NotNil(t, e) - require.NoError(t, e.Start(context.Background(), componenttest.NewNopHost())) - - // test and verify - assert.NoError(t, e.Shutdown(context.Background())) -} - -func TestRemote(t *testing.T) { - for _, tc := range []struct { - name string - remoteClientHeaderConfig map[string]configopaque.String - performedClientCallCount int - expectedOutboundGrpcCallCount int - reloadInterval time.Duration - }{ - { - name: "no configured header additions and no configured reload_interval", - performedClientCallCount: 3, - expectedOutboundGrpcCallCount: 3, - }, - { - name: "configured header additions", - performedClientCallCount: 3, - expectedOutboundGrpcCallCount: 3, - remoteClientHeaderConfig: map[string]configopaque.String{ - "testheadername": "testheadervalue", - "anotherheadername": "anotherheadervalue", - }, - }, - { - name: "reload_interval set to nonzero value caching outbound same-service gRPC calls", - reloadInterval: time.Minute * 5, - performedClientCallCount: 3, - expectedOutboundGrpcCallCount: 1, - remoteClientHeaderConfig: map[string]configopaque.String{ - "somecoolheader": "some-more-coverage-whynot", - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - // prepare the socket the mock server will listen at - lis, err := net.Listen("tcp", "127.0.0.1:0") - require.NoError(t, err) - - // create the mock server - server := grpc.NewServer() - - // register the service - mockServer := &samplingServer{} - api_v2.RegisterSamplingManagerServer(server, mockServer) - - go func() { - err = server.Serve(lis) - require.NoError(t, err) - }() - - // create the config, pointing to the mock server - cfg := testConfig() - cfg.GRPCServerSettings.NetAddr.Endpoint = "127.0.0.1:0" - cfg.Source.ReloadInterval = tc.reloadInterval - cfg.Source.Remote = &configgrpc.GRPCClientSettings{ - Endpoint: fmt.Sprintf("127.0.0.1:%d", lis.Addr().(*net.TCPAddr).Port), - TLSSetting: configtls.TLSClientSetting{ - Insecure: true, // test only - }, - WaitForReady: true, - Headers: tc.remoteClientHeaderConfig, - } - - // create the extension - e := newExtension(cfg, componenttest.NewNopTelemetrySettings()) - require.NotNil(t, e) - - // start the server - assert.NoError(t, e.Start(context.Background(), componenttest.NewNopHost())) - - // make test case defined number of calls - for i := 0; i < tc.performedClientCallCount; i++ { - resp, err := http.Get("http://127.0.0.1:5779/sampling?service=foo") - assert.NoError(t, err) - assert.Equal(t, 200, resp.StatusCode) - } - - // shut down the server - assert.NoError(t, e.Shutdown(context.Background())) - - // verify observed calls - assert.Len(t, mockServer.observedCalls, tc.expectedOutboundGrpcCallCount) - for _, singleCall := range mockServer.observedCalls { - assert.Equal(t, &api_v2.SamplingStrategyParameters{ - ServiceName: "foo", - }, singleCall.params) - md, ok := metadata.FromIncomingContext(singleCall.ctx) - assert.True(t, ok) - for expectedHeaderName, expectedHeaderValue := range tc.remoteClientHeaderConfig { - assert.Equal(t, []string{string(expectedHeaderValue)}, md.Get(expectedHeaderName)) - } - } - }) - } -} - -type samplingServer struct { - api_v2.UnimplementedSamplingManagerServer - observedCalls []observedCall -} - -type observedCall struct { - ctx context.Context - params *api_v2.SamplingStrategyParameters -} - -func (s *samplingServer) GetSamplingStrategy(ctx context.Context, params *api_v2.SamplingStrategyParameters) (*api_v2.SamplingStrategyResponse, error) { - s.observedCalls = append(s.observedCalls, observedCall{ - ctx: ctx, - params: params, - }) - return &api_v2.SamplingStrategyResponse{ - StrategyType: api_v2.SamplingStrategyType_PROBABILISTIC, - }, nil -} - -func testConfig() *Config { - cfg := createDefaultConfig().(*Config) - cfg.HTTPServerSettings.Endpoint = "127.0.0.1:5779" - cfg.GRPCServerSettings.NetAddr.Endpoint = "127.0.0.1:14251" - return cfg -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/factory.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/factory.go deleted file mode 100644 index 0d0d2269cd0c..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/factory.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerremotesamplingdeprecated // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated" - -import ( - "context" - - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/config/confignet" - "go.opentelemetry.io/collector/extension" - - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/metadata" -) - -// NewFactory creates a factory for the OIDC Authenticator extension. -func NewFactory() extension.Factory { - return extension.NewFactory( - metadata.Type, - createDefaultConfig, - createExtension, - metadata.ExtensionStability, - ) -} - -func createDefaultConfig() component.Config { - return &Config{ - HTTPServerSettings: &confighttp.HTTPServerSettings{ - Endpoint: ":5778", - }, - GRPCServerSettings: &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: ":14250", - Transport: "tcp", - }, - }, - Source: Source{}, - } -} - -func createExtension(_ context.Context, set extension.CreateSettings, cfg component.Config) (extension.Extension, error) { - return newExtension(cfg.(*Config), set.TelemetrySettings), nil -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/factory_test.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/factory_test.go deleted file mode 100644 index 826378250c60..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/factory_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerremotesamplingdeprecated - -import ( - "context" - "testing" - - "github.com/stretchr/testify/assert" - "go.opentelemetry.io/collector/component/componenttest" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/config/confignet" - "go.opentelemetry.io/collector/extension/extensiontest" -) - -func TestCreateDefaultConfig(t *testing.T) { - // prepare and test - expected := &Config{ - HTTPServerSettings: &confighttp.HTTPServerSettings{Endpoint: ":5778"}, - GRPCServerSettings: &configgrpc.GRPCServerSettings{NetAddr: confignet.NetAddr{ - Endpoint: ":14250", - Transport: "tcp", - }}, - } - - // test - cfg := createDefaultConfig() - - // verify - assert.Equal(t, expected, cfg) - assert.NoError(t, componenttest.CheckConfigStruct(cfg)) -} - -func TestCreateExtension(t *testing.T) { - cfg := createDefaultConfig().(*Config) - - ext, err := createExtension(context.Background(), extensiontest.NewNopCreateSettings(), cfg) - assert.NoError(t, err) - assert.NotNil(t, ext) -} - -func TestNewFactory(t *testing.T) { - f := NewFactory() - assert.NotNil(t, f) -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc.go deleted file mode 100644 index 3b4546f3f3da..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package internal // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal" - -import ( - "context" - "errors" - "fmt" - "net" - - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configgrpc" - "go.uber.org/zap" - "google.golang.org/grpc/health" - "google.golang.org/grpc/health/grpc_health_v1" - "google.golang.org/grpc/reflection" - - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling" - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" -) - -var _ component.Component = (*SamplingGRPCServer)(nil) - -var errGRPCServerNotRunning = errors.New("gRPC server is not running") - -type grpcServer interface { - Serve(lis net.Listener) error - GracefulStop() - Stop() -} - -// NewGRPC returns a new sampling gRPC Server. -func NewGRPC( - telemetry component.TelemetrySettings, - settings configgrpc.GRPCServerSettings, - strategyStore strategystore.StrategyStore, -) (*SamplingGRPCServer, error) { - if strategyStore == nil { - return nil, errMissingStrategyStore - } - - return &SamplingGRPCServer{ - telemetry: telemetry, - settings: settings, - strategyStore: strategyStore, - }, nil -} - -// SamplingGRPCServer implements component.Component to make the life cycle easy to manage. -type SamplingGRPCServer struct { - telemetry component.TelemetrySettings - settings configgrpc.GRPCServerSettings - strategyStore strategystore.StrategyStore - - grpcServer grpcServer -} - -func (s *SamplingGRPCServer) Start(_ context.Context, host component.Host) error { - server, err := s.settings.ToServer(host, s.telemetry) - if err != nil { - return err - } - reflection.Register(server) - s.grpcServer = server - - api_v2.RegisterSamplingManagerServer(server, sampling.NewGRPCHandler(s.strategyStore)) - - healthServer := health.NewServer() - healthServer.SetServingStatus("jaeger.api_v2.SamplingManager", grpc_health_v1.HealthCheckResponse_SERVING) - grpc_health_v1.RegisterHealthServer(server, healthServer) - - listener, err := s.settings.ToListener() - if err != nil { - return fmt.Errorf("failed to listen on gRPC port: %w", err) - } - - go func() { - if err := s.grpcServer.Serve(listener); err != nil { - s.telemetry.Logger.Error("could not launch gRPC service", zap.Error(err)) - } - }() - - return nil -} - -// Shutdown tries to terminate connections gracefully as long as the passed context is valid. -func (s *SamplingGRPCServer) Shutdown(ctx context.Context) error { - if s.grpcServer == nil { - return errGRPCServerNotRunning - } - - ch := make(chan struct{}) - go func() { - s.grpcServer.GracefulStop() - ch <- struct{}{} - }() - - select { - case <-ctx.Done(): - s.grpcServer.Stop() - case <-ch: - } - - return nil -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc/manager.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc/manager.go deleted file mode 100644 index 9468968dd07c..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc/manager.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package grpc // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc" - -import ( - "context" - "errors" - - "github.com/jaegertracing/jaeger/model/converter/thrift/jaeger" - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - "github.com/jaegertracing/jaeger/thrift-gen/baggage" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "google.golang.org/grpc" -) - -// SamplingManager returns sampling decisions from collector over gRPC. -type SamplingManager struct { - client api_v2.SamplingManagerClient -} - -// NewConfigManager creates gRPC sampling manager. -func NewConfigManager(conn *grpc.ClientConn) *SamplingManager { - return &SamplingManager{ - client: api_v2.NewSamplingManagerClient(conn), - } -} - -// GetSamplingStrategy returns sampling strategies from collector. -func (s *SamplingManager) GetSamplingStrategy(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) { - r, err := s.client.GetSamplingStrategy(ctx, &api_v2.SamplingStrategyParameters{ServiceName: serviceName}) - if err != nil { - return nil, err - } - return jaeger.ConvertSamplingResponseFromDomain(r) -} - -// GetBaggageRestrictions returns baggage restrictions from collector. -func (s *SamplingManager) GetBaggageRestrictions(_ context.Context, _ string) ([]*baggage.BaggageRestriction, error) { - return nil, errors.New("baggage not implemented") -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc_test.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc_test.go deleted file mode 100644 index 9d93aff32fd8..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package internal - -import ( - "context" - "net" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component/componenttest" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confignet" -) - -func TestMissingClientConfigManagerGRPC(t *testing.T) { - s, err := NewGRPC(componenttest.NewNopTelemetrySettings(), configgrpc.GRPCServerSettings{}, nil) - assert.Equal(t, errMissingStrategyStore, err) - assert.Nil(t, s) -} - -func TestStartAndStopGRPC(t *testing.T) { - // prepare - srvSettings := configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: "127.0.0.1:0", - Transport: "tcp", - }, - } - s, err := NewGRPC(componenttest.NewNopTelemetrySettings(), srvSettings, &mockCfgMgr{}) - require.NoError(t, err) - require.NotNil(t, s) - - // test - assert.NoError(t, s.Start(context.Background(), componenttest.NewNopHost())) - assert.NoError(t, s.Shutdown(context.Background())) -} - -func TestSamplingGRPCServer_Shutdown(t *testing.T) { - tt := []struct { - name string - grpcServer grpcServer - timeout time.Duration - expect error - }{ - { - name: "graceful stop is successful without delay", - grpcServer: &grpcServerMock{}, - timeout: time.Minute, - }, - { - name: "graceful stop is successful with delay", - grpcServer: &grpcServerMock{ - timeToGracefulStop: 5 * time.Second, - }, - timeout: time.Minute, - }, - { - name: "context timed out", - grpcServer: &grpcServerMock{ - timeToGracefulStop: time.Minute, - }, - timeout: 5 * time.Second, - }, - { - name: "grpc server not started", - timeout: time.Minute, - expect: errGRPCServerNotRunning, - }, - } - - for _, tc := range tt { - t.Run(tc.name, func(t *testing.T) { - srv := &SamplingGRPCServer{grpcServer: tc.grpcServer} - ctx, cancel := context.WithTimeout(context.Background(), tc.timeout) - defer cancel() - assert.Equal(t, tc.expect, srv.Shutdown(ctx)) - }) - } -} - -type grpcServerMock struct { - timeToGracefulStop time.Duration -} - -func (g *grpcServerMock) Serve(_ net.Listener) error { return nil } -func (g *grpcServerMock) Stop() {} -func (g *grpcServerMock) GracefulStop() { time.Sleep(g.timeToGracefulStop) } diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/http.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/http.go deleted file mode 100644 index 569c5cf71f3c..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/http.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package internal // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal" - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "sync" - - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/confighttp" - - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" -) - -var ( - errMissingStrategyStore = errors.New("the strategy store has not been provided") -) - -var _ component.Component = (*SamplingHTTPServer)(nil) - -type SamplingHTTPServer struct { - telemetry component.TelemetrySettings - settings confighttp.HTTPServerSettings - strategyStore strategystore.StrategyStore - - mux *http.ServeMux - srv *http.Server - shutdownWG *sync.WaitGroup -} - -func NewHTTP(telemetry component.TelemetrySettings, settings confighttp.HTTPServerSettings, strategyStore strategystore.StrategyStore) (*SamplingHTTPServer, error) { - if strategyStore == nil { - return nil, errMissingStrategyStore - } - - srv := &SamplingHTTPServer{ - telemetry: telemetry, - settings: settings, - strategyStore: strategyStore, - - shutdownWG: &sync.WaitGroup{}, - } - - srv.mux = http.NewServeMux() - - // SEE: https://www.jaegertracing.io/docs/1.41/apis/#remote-sampling-configuration-stable - srv.mux.Handle("/sampling", http.HandlerFunc(srv.samplingStrategyHandler)) - - return srv, nil -} - -func (h *SamplingHTTPServer) Start(_ context.Context, host component.Host) error { - var err error - h.srv, err = h.settings.ToServer(host, h.telemetry, h.mux) - if err != nil { - return err - } - - var hln net.Listener - hln, err = h.settings.ToListener() - if err != nil { - return err - } - - h.shutdownWG.Add(1) - go func() { - defer h.shutdownWG.Done() - - if err := h.srv.Serve(hln); err != nil && !errors.Is(err, http.ErrServerClosed) { - host.ReportFatalError(err) - } - }() - - return nil -} - -func (h *SamplingHTTPServer) Shutdown(ctx context.Context) error { - err := h.srv.Shutdown(ctx) - h.shutdownWG.Wait() - return err -} - -func (h *SamplingHTTPServer) samplingStrategyHandler(rw http.ResponseWriter, r *http.Request) { - svc := r.URL.Query().Get("service") - if len(svc) == 0 { - err := errors.New("'service' parameter must be provided") - http.Error(rw, err.Error(), http.StatusBadRequest) - return - } - - resp, err := h.strategyStore.GetSamplingStrategy(r.Context(), svc) - if err != nil { - err = fmt.Errorf("failed to get sampling strategy for service %q: %w", svc, err) - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - - jsonBytes, err := json.Marshal(resp) - if err != nil { - err = fmt.Errorf("cannot convert sampling strategy to JSON: %w", err) - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - - rw.Header().Add("Content-Type", "application/json") - if _, err := rw.Write(jsonBytes); err != nil { - err = fmt.Errorf("cannot write response to client: %w", err) - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/http_test.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/http_test.go deleted file mode 100644 index 1ba09da63752..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/http_test.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package internal - -import ( - "context" - "errors" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component/componenttest" - "go.opentelemetry.io/collector/config/confighttp" -) - -func TestMissingClientConfigManagerHTTP(t *testing.T) { - s, err := NewHTTP(componenttest.NewNopTelemetrySettings(), confighttp.HTTPServerSettings{}, nil) - assert.Equal(t, errMissingStrategyStore, err) - assert.Nil(t, s) -} - -func TestStartAndStopHTTP(t *testing.T) { - // prepare - srvSettings := confighttp.HTTPServerSettings{ - Endpoint: "127.0.0.1:0", - } - s, err := NewHTTP(componenttest.NewNopTelemetrySettings(), srvSettings, &mockCfgMgr{}) - require.NoError(t, err) - require.NotNil(t, s) - - // test - assert.NoError(t, s.Start(context.Background(), componenttest.NewNopHost())) - assert.NoError(t, s.Shutdown(context.Background())) -} - -func TestEndpointsAreWired(t *testing.T) { - testCases := []struct { - desc string - endpoint string - }{ - { - desc: "new", - endpoint: "/sampling", - }, - } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - // prepare - s, err := NewHTTP(componenttest.NewNopTelemetrySettings(), confighttp.HTTPServerSettings{}, &mockCfgMgr{}) - require.NoError(t, err) - require.NotNil(t, s) - - srv := httptest.NewServer(s.mux) - defer func() { - srv.Close() - }() - - // test - resp, err := srv.Client().Get(fmt.Sprintf("%s%s?service=foo", srv.URL, tC.endpoint)) - require.NoError(t, err) - - // verify - samplingStrategiesBytes, err := io.ReadAll(resp.Body) - require.NoError(t, err) - resp.Body.Close() - - body := string(samplingStrategiesBytes) - assert.Equal(t, `{"strategyType":"PROBABILISTIC"}`, body) - }) - } -} - -func TestServiceNameIsRequired(t *testing.T) { - // prepare - s, err := NewHTTP(componenttest.NewNopTelemetrySettings(), confighttp.HTTPServerSettings{}, &mockCfgMgr{}) - require.NoError(t, err) - require.NotNil(t, s) - - rw := httptest.NewRecorder() - req := &http.Request{ - URL: &url.URL{}, - } - - // test - s.samplingStrategyHandler(rw, req) - - // verify - body, _ := io.ReadAll(rw.Body) - assert.Contains(t, string(body), "'service' parameter must be provided") -} - -func TestErrorFromClientConfigManager(t *testing.T) { - s, err := NewHTTP(componenttest.NewNopTelemetrySettings(), confighttp.HTTPServerSettings{}, &mockCfgMgr{}) - require.NoError(t, err) - require.NotNil(t, s) - - s.strategyStore = &mockCfgMgr{ - getSamplingStrategyFunc: func(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) { - return nil, errors.New("some error") - }, - } - - rw := httptest.NewRecorder() - req := &http.Request{ - URL: &url.URL{ - RawQuery: "service=foo", - }, - } - - // test - s.samplingStrategyHandler(rw, req) - - // verify - body, _ := io.ReadAll(rw.Body) - assert.Contains(t, string(body), "failed to get sampling strategy for service") -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/internal_test.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/internal_test.go deleted file mode 100644 index bc93e72db672..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/internal_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package internal - -import ( - "context" - - "github.com/jaegertracing/jaeger/thrift-gen/sampling" -) - -type mockCfgMgr struct { - getSamplingStrategyFunc func(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) -} - -func (m *mockCfgMgr) GetSamplingStrategy(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) { - if m.getSamplingStrategyFunc != nil { - return m.getSamplingStrategyFunc(ctx, serviceName) - } - return sampling.NewSamplingStrategyResponse(), nil -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/metadata/generated_status.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/metadata/generated_status.go deleted file mode 100644 index 7a0b3224ccbc..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/metadata/generated_status.go +++ /dev/null @@ -1,12 +0,0 @@ -// Code generated by mdatagen. DO NOT EDIT. - -package metadata - -import ( - "go.opentelemetry.io/collector/component" -) - -const ( - Type = "jaegerremotesampling" - ExtensionStability = component.StabilityLevelAlpha -) diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_cache.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_cache.go deleted file mode 100644 index 6c723d1601ac..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_cache.go +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package internal // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal" - -import ( - "context" - "sync" - "time" - - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "github.com/tilinna/clock" -) - -type serviceStrategyCache interface { - get(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, bool) - put(ctx context.Context, serviceName string, response *sampling.SamplingStrategyResponse) - Close() error -} - -// serviceStrategyCacheEntry is a timestamped sampling strategy response -type serviceStrategyCacheEntry struct { - retrievedAt time.Time - strategyResponse *sampling.SamplingStrategyResponse -} - -// serviceStrategyTTLCache is a naive in-memory TTL serviceStrategyTTLCache of service-specific sampling strategies -// returned from the remote source. Each cached item has its own TTL used to determine whether it is valid for read -// usage (based on the time of write). -type serviceStrategyTTLCache struct { - itemTTL time.Duration - - stopCh chan struct{} - rw sync.RWMutex - items map[string]serviceStrategyCacheEntry -} - -// Initial size of cache's underlying map -const initialRemoteResponseCacheSize = 32 - -func newServiceStrategyCache(itemTTL time.Duration) serviceStrategyCache { - result := &serviceStrategyTTLCache{ - itemTTL: itemTTL, - items: make(map[string]serviceStrategyCacheEntry, initialRemoteResponseCacheSize), - stopCh: make(chan struct{}), - } - - // Launches a "cleaner" goroutine that naively blows away stale items with a frequency equal to the item TTL. - // Note that this is for memory usage and not for correctness (the get() function checks item validity). - go result.periodicallyClearCache(context.Background(), itemTTL) - return result -} - -// get returns a cached sampling strategy if one is present and is no older than the serviceStrategyTTLCache's per-item TTL. -func (c *serviceStrategyTTLCache) get( - ctx context.Context, - serviceName string, -) (*sampling.SamplingStrategyResponse, bool) { - c.rw.RLock() - defer c.rw.RUnlock() - found, ok := c.items[serviceName] - if !ok { - return nil, false - } - if c.staleItem(ctx, found) { - return nil, false - } - return found.strategyResponse, true -} - -// put unconditionally overwrites the given service's serviceStrategyTTLCache item entry and resets its timestamp used for TTL checks. -func (c *serviceStrategyTTLCache) put( - ctx context.Context, - serviceName string, - response *sampling.SamplingStrategyResponse, -) { - c.rw.Lock() - defer c.rw.Unlock() - c.items[serviceName] = serviceStrategyCacheEntry{ - strategyResponse: response, - retrievedAt: clock.Now(ctx), - } -} - -// periodicallyClearCache periodically clears expired items from the cache and replaces the backing map with only -// valid (fresh) items. Note that this is not necessary for correctness, just preferred for memory usage hygiene. -// Client request activity drives the replacement of stale items with fresh items upon cache misses for any service. -func (c *serviceStrategyTTLCache) periodicallyClearCache( - ctx context.Context, - schedulingPeriod time.Duration, -) { - ticker := clock.NewTicker(ctx, schedulingPeriod) - for { - select { - case <-ticker.C: - c.rw.Lock() - newItems := make(map[string]serviceStrategyCacheEntry, initialRemoteResponseCacheSize) - for serviceName, item := range c.items { - if !c.staleItem(ctx, item) { - newItems[serviceName] = item - } - } - // Notice that we swap the map rather than using map's delete (which doesn't reduce its allocated size). - c.items = newItems - c.rw.Unlock() - case <-c.stopCh: - return - } - } -} - -func (c *serviceStrategyTTLCache) Close() error { - close(c.stopCh) - return nil -} - -func (c *serviceStrategyTTLCache) staleItem(ctx context.Context, item serviceStrategyCacheEntry) bool { - return clock.Now(ctx).After(item.retrievedAt.Add(c.itemTTL)) -} - -type noopStrategyCache struct{} - -func (n *noopStrategyCache) get(_ context.Context, _ string) (*sampling.SamplingStrategyResponse, bool) { - return nil, false -} - -func (n *noopStrategyCache) put(_ context.Context, _ string, _ *sampling.SamplingStrategyResponse) { -} - -func (n *noopStrategyCache) Close() error { - return nil -} - -func newNoopStrategyCache() serviceStrategyCache { - return &noopStrategyCache{} -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_cache_test.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_cache_test.go deleted file mode 100644 index b1d037aba01e..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_cache_test.go +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package internal - -import ( - "context" - "fmt" - "sync" - "testing" - "time" - - "github.com/fortytw2/leaktest" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "github.com/stretchr/testify/assert" - "github.com/tilinna/clock" -) - -const cacheTestItemTTL = 50 * time.Millisecond - -var testStrategyResponseA = &sampling.SamplingStrategyResponse{ - ProbabilisticSampling: &sampling.ProbabilisticSamplingStrategy{ - SamplingRate: 0.1337, - }, -} - -var testStrategyResponseB = &sampling.SamplingStrategyResponse{ - OperationSampling: &sampling.PerOperationSamplingStrategies{ - DefaultSamplingProbability: 0.001, - PerOperationStrategies: []*sampling.OperationSamplingStrategy{ - { - Operation: "always-sampled-op", - ProbabilisticSampling: &sampling.ProbabilisticSamplingStrategy{ - SamplingRate: 1.0, - }, - }, - { - Operation: "never-sampled-op", - ProbabilisticSampling: &sampling.ProbabilisticSamplingStrategy{ - SamplingRate: 0, - }, - }, - }, - }, -} - -func Test_serviceStrategyCache_ReadWriteSequence(t *testing.T) { - testTime := time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC) - mock := clock.NewMock(testTime) - ctx, cfn := mock.DeadlineContext(context.Background(), testTime.Add(3*time.Minute)) - defer cfn() - - cache := newServiceStrategyCache(cacheTestItemTTL).(*serviceStrategyTTLCache) - defer func() { - assert.NoError(t, cache.Close()) - }() - - // initial read returns nothing - result, ok := cache.get(ctx, "fooSvc") - assert.False(t, ok) - assert.Nil(t, result) - result, ok = cache.get(ctx, "barSvc") - assert.False(t, ok) - assert.Nil(t, result) - - // perform a write for fooSvc at testTime - firstWriteTime := mock.Now() - cache.put(ctx, "fooSvc", testStrategyResponseA) - - // whitebox assert for internal timestamp tracking (we don't want a caching bug manifesting as stale data serving) - // (post-write) - assert.Equal(t, serviceStrategyCacheEntry{ - retrievedAt: firstWriteTime, - strategyResponse: testStrategyResponseA, - }, cache.items["fooSvc"]) - - // read without time advancing - result, ok = cache.get(ctx, "fooSvc") - assert.True(t, ok) - assert.Equal(t, testStrategyResponseA, result) - result, ok = cache.get(ctx, "barSvc") - assert.False(t, ok) - assert.Nil(t, result) - - // reading does not mutate internal cache state - assert.Equal(t, serviceStrategyCacheEntry{ - retrievedAt: firstWriteTime, - strategyResponse: testStrategyResponseA, - }, cache.items["fooSvc"]) - - // advance time (still within TTL time range) - mock.Add(20 * time.Millisecond) - - // the written item is still available - result, ok = cache.get(ctx, "fooSvc") - assert.True(t, ok) - assert.Equal(t, testStrategyResponseA, result) - result, ok = cache.get(ctx, "barSvc") - assert.False(t, ok) - assert.Nil(t, result) - - // advance time (just before end of TTL time range) - mock.Add(30 * time.Millisecond) - - // the written item is still available - result, ok = cache.get(ctx, "fooSvc") - assert.True(t, ok) - assert.Equal(t, testStrategyResponseA, result) - result, ok = cache.get(ctx, "barSvc") - assert.False(t, ok) - assert.Nil(t, result) - - // advance time (across TTL range) - mock.Add(1 * time.Millisecond) - - // the (now stale) cached item is no longer available - result, ok = cache.get(ctx, "fooSvc") - assert.False(t, ok) - assert.Nil(t, result) - result, ok = cache.get(ctx, "barSvc") - assert.False(t, ok) - assert.Nil(t, result) - - assert.Equal(t, serviceStrategyCacheEntry{ - retrievedAt: firstWriteTime, - strategyResponse: testStrategyResponseA, - }, cache.items["fooSvc"]) -} - -func Test_serviceStrategyCache_WritesUpdateTimestamp(t *testing.T) { - startTime := time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC) - mock := clock.NewMock(startTime) - ctx, cfn := mock.DeadlineContext(context.Background(), startTime.Add(3*time.Minute)) - defer cfn() - - cache := newServiceStrategyCache(cacheTestItemTTL).(*serviceStrategyTTLCache) - defer func() { - assert.NoError(t, cache.Close()) - }() - - // initial read returns nothing - result, ok := cache.get(ctx, "fooSvc") - assert.False(t, ok) - assert.Nil(t, result) - result, ok = cache.get(ctx, "barSvc") - assert.False(t, ok) - assert.Nil(t, result) - - // perform a write for barSvc at startTime + 10ms - firstWriteTime := mock.Add(10 * time.Millisecond) - cache.put(ctx, "barSvc", testStrategyResponseA) - - // whitebox assert for internal timestamp tracking - assert.Equal(t, serviceStrategyCacheEntry{ - retrievedAt: firstWriteTime, - strategyResponse: testStrategyResponseA, - }, cache.items["barSvc"]) - - // read without time advancing - result, ok = cache.get(ctx, "fooSvc") - assert.False(t, ok) - assert.Nil(t, result) - result, ok = cache.get(ctx, "barSvc") - assert.True(t, ok) - assert.Equal(t, testStrategyResponseA, result) - - // advance time (still within TTL time range) - mock.Add(10 * time.Millisecond) - - // the written item is still available - result, ok = cache.get(ctx, "fooSvc") - assert.False(t, ok) - assert.Nil(t, result) - result, ok = cache.get(ctx, "barSvc") - assert.True(t, ok) - assert.Equal(t, testStrategyResponseA, result) - - // perform a write for barSvc at startTime + 30ms (still within TTL, but we retain this more recent data) - secondWriteTime := mock.Add(10 * time.Millisecond) - cache.put(ctx, "barSvc", testStrategyResponseB) - - // whitebox assert for internal timestamp tracking (post-write, still-fresh cache entry replaced with newer data) - assert.Equal(t, serviceStrategyCacheEntry{ - retrievedAt: secondWriteTime, - strategyResponse: testStrategyResponseB, - }, cache.items["barSvc"]) - - // the written item is still available - result, ok = cache.get(ctx, "fooSvc") - assert.False(t, ok) - assert.Nil(t, result) - result, ok = cache.get(ctx, "barSvc") - assert.True(t, ok) - assert.Equal(t, testStrategyResponseB, result) - - // advance time (to end of what is now a new/full TTL for the new fresh item) - mock.Add(cacheTestItemTTL) - - result, ok = cache.get(ctx, "fooSvc") - assert.False(t, ok) - assert.Nil(t, result) - result, ok = cache.get(ctx, "barSvc") - assert.True(t, ok) - assert.Equal(t, testStrategyResponseB, result) - - // advance time beyond the newer item's TTL - mock.Add(1) - - // the (now stale) cached item is no longer available - result, ok = cache.get(ctx, "fooSvc") - assert.False(t, ok) - assert.Nil(t, result) - result, ok = cache.get(ctx, "barSvc") - assert.False(t, ok) - assert.Nil(t, result) - - // internal state for now-stale second written item is still maintained - assert.Equal(t, serviceStrategyCacheEntry{ - retrievedAt: secondWriteTime, - strategyResponse: testStrategyResponseB, - }, cache.items["barSvc"]) -} - -func Test_serviceStrategyCache_Concurrency(t *testing.T) { - defer leaktest.CheckTimeout(t, time.Minute*3) - - cache := newServiceStrategyCache(cacheTestItemTTL).(*serviceStrategyTTLCache) - defer func() { - assert.NoError(t, cache.Close()) - }() - - // newServiceStrategyCache invokes this as well but with a practically-motivated period that is too long for tests. - // We should at least exercise it for consideration by the race detector. - // NB: We don't use a mock clock in this concurrency test case. - go cache.periodicallyClearCache(context.Background(), time.Millisecond*1) - - numThreads := 4 - numIterationsPerThread := 32 - - wg := sync.WaitGroup{} - wg.Add(numThreads) - for i := 0; i < numThreads; i++ { - ii := i - go func() { - for j := 0; j < numIterationsPerThread; j++ { - for _, svcName := range []string{ - fmt.Sprintf("thread-specific-service-%d", ii), - "contended-for-service", - } { - if _, ok := cache.get(context.Background(), svcName); !ok { - cache.put(context.Background(), svcName, &sampling.SamplingStrategyResponse{}) - } - } - } - wg.Done() - }() - } - wg.Wait() -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_store.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_store.go deleted file mode 100644 index ed8caa73c440..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/remote_strategy_store.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package internal // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal" - -import ( - "context" - "fmt" - "io" - "time" - - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/configopaque" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" - - grpcstore "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/grpc" - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" -) - -type grpcRemoteStrategyStore struct { - headerAdditions map[string]configopaque.String - delegate *grpcstore.SamplingManager - cache serviceStrategyCache -} - -// NewRemoteStrategyStore returns a StrategyStore that delegates to the configured Jaeger gRPC endpoint, making -// extension-configured enhancements (header additions only for now) to the gRPC context of every outbound gRPC call. -// Note: it would be nice to expand the configuration surface to include an optional TTL-based caching behavior -// for service-specific outbound GetSamplingStrategy calls. -func NewRemoteStrategyStore( - conn *grpc.ClientConn, - grpcClientSettings *configgrpc.GRPCClientSettings, - reloadInterval time.Duration, -) (strategystore.StrategyStore, io.Closer) { - cache := newNoopStrategyCache() - if reloadInterval > 0 { - cache = newServiceStrategyCache(reloadInterval) - } - - return &grpcRemoteStrategyStore{ - headerAdditions: grpcClientSettings.Headers, - delegate: grpcstore.NewConfigManager(conn), - cache: cache, - }, cache -} - -func (g *grpcRemoteStrategyStore) GetSamplingStrategy( - ctx context.Context, - serviceName string, -) (*sampling.SamplingStrategyResponse, error) { - if cachedResponse, ok := g.cache.get(ctx, serviceName); ok { - return cachedResponse, nil - } - freshResult, err := g.delegate.GetSamplingStrategy(g.enhanceContext(ctx), serviceName) - if err != nil { - return nil, fmt.Errorf("remote call failed: %w", err) - } - g.cache.put(ctx, serviceName, freshResult) - return freshResult, nil -} - -// This function is used to add the extension configuration defined HTTP headers to a given outbound gRPC call's context. -func (g *grpcRemoteStrategyStore) enhanceContext(ctx context.Context) context.Context { - md := metadata.New(nil) - for k, v := range g.headerAdditions { - md.Set(k, string(v)) - } - return metadata.NewOutgoingContext(ctx, md) -} - -func (g *grpcRemoteStrategyStore) Close() error { - return g.cache.Close() -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/grpc_handler.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/grpc_handler.go deleted file mode 100644 index f2e7fd094034..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/grpc_handler.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sampling // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling" - -import ( - "context" - - "github.com/jaegertracing/jaeger/model/converter/thrift/jaeger" - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" -) - -// GRPCHandler is sampling strategy handler for gRPC. -type GRPCHandler struct { - store strategystore.StrategyStore -} - -// NewGRPCHandler creates a handler that controls sampling strategies for services. -func NewGRPCHandler(store strategystore.StrategyStore) GRPCHandler { - return GRPCHandler{ - store: store, - } -} - -// GetSamplingStrategy returns sampling decision from store. -func (s GRPCHandler) GetSamplingStrategy(ctx context.Context, param *api_v2.SamplingStrategyParameters) (*api_v2.SamplingStrategyResponse, error) { - r, err := s.store.GetSamplingStrategy(ctx, param.GetServiceName()) - if err != nil { - return nil, err - } - return jaeger.ConvertSamplingResponseToDomain(r) -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/model/sampling.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/model/sampling.go deleted file mode 100644 index 264c4f68c53a..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/model/sampling.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/model" - -// Throughput keeps track of the queries an operation received. -type Throughput struct { - Service string - Operation string - Count int64 - Probabilities map[string]struct{} -} - -// ServiceOperationProbabilities contains the sampling probabilities for all operations in a service. -// ie [service][operation] = probability -type ServiceOperationProbabilities map[string]map[string]float64 - -// ServiceOperationQPS contains the qps for all operations in a service. -// ie [service][operation] = qps -type ServiceOperationQPS map[string]map[string]float64 - -// ProbabilityAndQPS contains the sampling probability and measured qps for an operation. -type ProbabilityAndQPS struct { - Probability float64 - QPS float64 -} - -// ServiceOperationData contains the sampling probabilities and measured qps for all operations in a service. -// ie [service][operation] = ProbabilityAndQPS -type ServiceOperationData map[string]map[string]*ProbabilityAndQPS diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore/factory.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore/factory.go deleted file mode 100644 index fcc04bff2c7e..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore/factory.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strategystore // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" - -import ( - "github.com/jaegertracing/jaeger/pkg/metrics" - "github.com/jaegertracing/jaeger/storage" - "go.uber.org/zap" -) - -// Factory defines an interface for a factory that can create implementations of different strategy storage components. -// Implementations are also encouraged to implement plugin.Configurable interface. -// -// # See also -// -// plugin.Configurable -type Factory interface { //nolint:gci - // Initialize performs internal initialization of the factory. - Initialize(metricsFactory metrics.Factory, ssFactory storage.SamplingStoreFactory, logger *zap.Logger) error - - // CreateStrategyStore initializes the StrategyStore and returns it. - CreateStrategyStore() (StrategyStore, Aggregator, error) -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore/interface.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore/interface.go deleted file mode 100644 index ca0b38ec8ca2..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore/interface.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strategystore // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" - -import ( - "context" - "io" - - "github.com/jaegertracing/jaeger/thrift-gen/sampling" -) - -// StrategyStore keeps track of service specific sampling strategies. -type StrategyStore interface { - // GetSamplingStrategy retrieves the sampling strategy for the specified service. - GetSamplingStrategy(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) -} - -// Aggregator defines an interface used to aggregate operation throughput. -type Aggregator interface { - // Close() from io.Closer stops the aggregator from aggregating throughput. - io.Closer - - // RecordThroughput records throughput for an operation for aggregation. - RecordThroughput(service, operation, samplerType string, probability float64) - - // Start starts aggregating operation throughput. - Start() -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/constants.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/constants.go deleted file mode 100644 index c5d4b299ed25..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/constants.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package static // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static" - -import ( - "github.com/jaegertracing/jaeger/thrift-gen/sampling" -) - -const ( - // samplerTypeProbabilistic is the type of sampler that samples traces - // with a certain fixed probability. - samplerTypeProbabilistic = "probabilistic" - - // samplerTypeRateLimiting is the type of sampler that samples - // only up to a fixed number of traces per second. - samplerTypeRateLimiting = "ratelimiting" - - // defaultSamplingProbability is the default sampling probability the - // Strategy Store will use if none is provided. - defaultSamplingProbability = 0.001 -) - -// defaultStrategy is the default sampling strategy the Strategy Store will return -// if none is provided. -func defaultStrategyResponse() *sampling.SamplingStrategyResponse { - return &sampling.SamplingStrategyResponse{ - StrategyType: sampling.SamplingStrategyType_PROBABILISTIC, - ProbabilisticSampling: &sampling.ProbabilisticSamplingStrategy{ - SamplingRate: defaultSamplingProbability, - }, - } -} - -func defaultStrategies() *storedStrategies { - s := &storedStrategies{ - serviceStrategies: make(map[string]*sampling.SamplingStrategyResponse), - } - s.defaultStrategy = defaultStrategyResponse() - return s -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/factory.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/factory.go deleted file mode 100644 index 81f55ea8feb7..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/factory.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package static // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static" - -import ( - "flag" - - "github.com/jaegertracing/jaeger/pkg/metrics" - "github.com/jaegertracing/jaeger/plugin" - "github.com/jaegertracing/jaeger/storage" - "github.com/spf13/viper" - "go.uber.org/zap" - - "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" -) - -var _ plugin.Configurable = (*Factory)(nil) - -// Factory implements strategystore.Factory for a static strategy store. -type Factory struct { - options *Options - logger *zap.Logger -} - -// NewFactory creates a new Factory. -func NewFactory() *Factory { - return &Factory{ - options: &Options{}, - logger: zap.NewNop(), - } -} - -// AddFlags implements plugin.Configurable -func (f *Factory) AddFlags(flagSet *flag.FlagSet) { - AddFlags(flagSet) -} - -// InitFromViper implements plugin.Configurable -func (f *Factory) InitFromViper(v *viper.Viper, _ *zap.Logger) { - f.options.InitFromViper(v) -} - -// Initialize implements strategystore.Factory -func (f *Factory) Initialize(_ metrics.Factory, _ storage.SamplingStoreFactory, logger *zap.Logger) error { - f.logger = logger - return nil -} - -// CreateStrategyStore implements strategystore.Factory -func (f *Factory) CreateStrategyStore() (strategystore.StrategyStore, strategystore.Aggregator, error) { - s, err := NewStrategyStore(*f.options, f.logger) - if err != nil { - return nil, nil, err - } - - return s, nil, nil -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/options.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/options.go deleted file mode 100644 index 32d3312ec463..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/options.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package static // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static" - -import ( - "flag" - "time" - - "github.com/spf13/viper" -) - -const ( - // samplingStrategiesFile contains the name of CLI option for config file. - samplingStrategiesFile = "sampling.strategies-file" - samplingStrategiesReloadInterval = "sampling.strategies-reload-interval" -) - -// Options holds configuration for the static sampling strategy store. -type Options struct { - // StrategiesFile is the path for the sampling strategies file in JSON format - StrategiesFile string - // ReloadInterval is the time interval to check and reload sampling strategies file - ReloadInterval time.Duration -} - -// AddFlags adds flags for Options -func AddFlags(flagSet *flag.FlagSet) { - flagSet.Duration(samplingStrategiesReloadInterval, 0, "Reload interval to check and reload sampling strategies file. Zero value means no reloading") - flagSet.String(samplingStrategiesFile, "", "The path for the sampling strategies file in JSON format. See sampling documentation to see format of the file") -} - -// InitFromViper initializes Options with properties from viper -func (opts *Options) InitFromViper(v *viper.Viper) *Options { - opts.StrategiesFile = v.GetString(samplingStrategiesFile) - opts.ReloadInterval = v.GetDuration(samplingStrategiesReloadInterval) - return opts -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/strategy.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/strategy.go deleted file mode 100644 index 8dddbebb2846..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/strategy.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package static // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static" - -// strategy defines a sampling strategy. Type can be "probabilistic" or "ratelimiting" -// and Param will represent "sampling probability" and "max traces per second" respectively. -type strategy struct { - Type string `json:"type"` - Param float64 `json:"param"` -} - -// operationStrategy defines an operation specific sampling strategy. -type operationStrategy struct { - Operation string `json:"operation"` - strategy -} - -// serviceStrategy defines a service specific sampling strategy. -type serviceStrategy struct { - Service string `json:"service"` - OperationStrategies []*operationStrategy `json:"operation_strategies"` - strategy -} - -// strategies holds a default sampling strategy and service specific sampling strategies. -type strategies struct { - DefaultStrategy *serviceStrategy `json:"default_strategy"` - ServiceStrategies []*serviceStrategy `json:"service_strategies"` -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/strategy_store.go b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/strategy_store.go deleted file mode 100644 index 5b64519a3d16..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static/strategy_store.go +++ /dev/null @@ -1,339 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package static // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/static" - -import ( - "bytes" - "context" - "encoding/gob" - "encoding/json" - "fmt" - "net/http" - "net/url" - "os" - "path/filepath" - "sync/atomic" - "time" - - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "go.uber.org/zap" - - ss "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/internal/sampling/strategystore" -) - -// null represents "null" JSON value and -// it un-marshals to nil pointer. -var nullJSON = []byte("null") - -type strategyStore struct { - logger *zap.Logger - - storedStrategies atomic.Value // holds *storedStrategies - - cancelFunc context.CancelFunc -} - -type storedStrategies struct { - defaultStrategy *sampling.SamplingStrategyResponse - serviceStrategies map[string]*sampling.SamplingStrategyResponse -} - -type strategyLoader func() ([]byte, error) - -// NewStrategyStore creates a strategy store that holds static sampling strategies. -func NewStrategyStore(options Options, logger *zap.Logger) (ss.StrategyStore, error) { - ctx, cancelFunc := context.WithCancel(context.Background()) - h := &strategyStore{ - logger: logger, - cancelFunc: cancelFunc, - } - h.storedStrategies.Store(defaultStrategies()) - - if options.StrategiesFile == "" { - h.parseStrategies(nil) - return h, nil - } - - loadFn := h.samplingStrategyLoader(options.StrategiesFile) - strategies, err := loadStrategies(loadFn) - if err != nil { - return nil, err - } - h.parseStrategies(strategies) - - if options.ReloadInterval > 0 { - go h.autoUpdateStrategies(ctx, options.ReloadInterval, loadFn) - } - return h, nil -} - -// GetSamplingStrategy implements StrategyStore#GetSamplingStrategy. -func (h *strategyStore) GetSamplingStrategy(_ context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) { - ss := h.storedStrategies.Load().(*storedStrategies) - serviceStrategies := ss.serviceStrategies - if strategy, ok := serviceStrategies[serviceName]; ok { - return strategy, nil - } - h.logger.Debug("sampling strategy not found, using default", zap.String("service", serviceName)) - return ss.defaultStrategy, nil -} - -// Close stops updating the strategies -func (h *strategyStore) Close() { - h.cancelFunc() -} - -func (h *strategyStore) downloadSamplingStrategies(url string) ([]byte, error) { - h.logger.Info("Downloading sampling strategies", zap.String("url", url)) - resp, err := http.Get(url) //nolint:gosec - if err != nil { - return nil, fmt.Errorf("failed to download sampling strategies: %w", err) - } - - defer resp.Body.Close() - buf := new(bytes.Buffer) - if _, err = buf.ReadFrom(resp.Body); err != nil { - return nil, fmt.Errorf("failed to read sampling strategies HTTP response body: %w", err) - } - - if resp.StatusCode == http.StatusServiceUnavailable { - return nullJSON, nil - } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf( - "receiving %s while downloading strategies file: %s", - resp.Status, - buf.String(), - ) - } - - return buf.Bytes(), nil -} - -func isURL(str string) bool { - u, err := url.Parse(str) - return err == nil && u.Scheme != "" && u.Host != "" -} - -func (h *strategyStore) samplingStrategyLoader(strategiesFile string) strategyLoader { - if isURL(strategiesFile) { - return func() ([]byte, error) { - return h.downloadSamplingStrategies(strategiesFile) - } - } - - return func() ([]byte, error) { - h.logger.Info("Loading sampling strategies", zap.String("filename", strategiesFile)) - currBytes, err := os.ReadFile(filepath.Clean(strategiesFile)) - if err != nil { - return nil, fmt.Errorf("failed to read strategies file %s: %w", strategiesFile, err) - } - return currBytes, nil - } -} - -func (h *strategyStore) autoUpdateStrategies(ctx context.Context, interval time.Duration, loader strategyLoader) { - lastValue := string(nullJSON) - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - lastValue = h.reloadSamplingStrategy(loader, lastValue) - case <-ctx.Done(): - return - } - } -} - -func (h *strategyStore) reloadSamplingStrategy(loadFn strategyLoader, lastValue string) string { - newValue, err := loadFn() - if err != nil { - h.logger.Error("failed to re-load sampling strategies", zap.Error(err)) - return lastValue - } - if lastValue == string(newValue) { - return lastValue - } - if err := h.updateSamplingStrategy(newValue); err != nil { - h.logger.Error("failed to update sampling strategies", zap.Error(err)) - return lastValue - } - return string(newValue) -} - -func (h *strategyStore) updateSamplingStrategy(bytes []byte) error { - var strategies strategies //nolint:govet - if err := json.Unmarshal(bytes, &strategies); err != nil { - return fmt.Errorf("failed to unmarshal sampling strategies: %w", err) - } - h.parseStrategies(&strategies) - h.logger.Info("Updated sampling strategies:" + string(bytes)) - return nil -} - -// TODO good candidate for a global util function -func loadStrategies(loadFn strategyLoader) (*strategies, error) { - strategyBytes, err := loadFn() - if err != nil { - return nil, err - } - - var strategies *strategies - if err := json.Unmarshal(strategyBytes, &strategies); err != nil { - return nil, fmt.Errorf("failed to unmarshal strategies: %w", err) - } - return strategies, nil -} - -func (h *strategyStore) parseStrategies(strategies *strategies) { - if strategies == nil { - h.logger.Info("No sampling strategies provided or URL is unavailable, using defaults") - return - } - newStore := defaultStrategies() - if strategies.DefaultStrategy != nil { - newStore.defaultStrategy = h.parseServiceStrategies(strategies.DefaultStrategy) - } - - merge := true - if newStore.defaultStrategy.OperationSampling == nil || - newStore.defaultStrategy.OperationSampling.PerOperationStrategies == nil { - merge = false - } - - for _, s := range strategies.ServiceStrategies { - newStore.serviceStrategies[s.Service] = h.parseServiceStrategies(s) - - // Merge with the default operation strategies, because only merging with - // the default strategy has no effect on service strategies (the default strategy - // is not merged with and only used as a fallback). - opS := newStore.serviceStrategies[s.Service].OperationSampling - if opS == nil { - if newStore.defaultStrategy.OperationSampling == nil || - newStore.serviceStrategies[s.Service].ProbabilisticSampling == nil { - continue - } - // Service has no per-operation strategies, so just reference the default settings and change default samplingRate. - newOpS := *newStore.defaultStrategy.OperationSampling - newOpS.DefaultSamplingProbability = newStore.serviceStrategies[s.Service].ProbabilisticSampling.SamplingRate - newStore.serviceStrategies[s.Service].OperationSampling = &newOpS - continue - } - if merge { - opS.PerOperationStrategies = mergePerOperationSamplingStrategies( - opS.PerOperationStrategies, - newStore.defaultStrategy.OperationSampling.PerOperationStrategies) - } - } - h.storedStrategies.Store(newStore) -} - -// mergePerOperationStrategies merges two operation strategies a and b, where a takes precedence over b. -func mergePerOperationSamplingStrategies( - a, b []*sampling.OperationSamplingStrategy, -) []*sampling.OperationSamplingStrategy { - m := make(map[string]bool) - for _, aOp := range a { - m[aOp.Operation] = true - } - for _, bOp := range b { - if m[bOp.Operation] { - continue - } - a = append(a, bOp) - } - return a -} - -func (h *strategyStore) parseServiceStrategies(strategy *serviceStrategy) *sampling.SamplingStrategyResponse { - resp := h.parseStrategy(&strategy.strategy) - if len(strategy.OperationStrategies) == 0 { - return resp - } - opS := &sampling.PerOperationSamplingStrategies{ - DefaultSamplingProbability: defaultSamplingProbability, - } - if resp.StrategyType == sampling.SamplingStrategyType_PROBABILISTIC { - opS.DefaultSamplingProbability = resp.ProbabilisticSampling.SamplingRate - } - for _, operationStrategy := range strategy.OperationStrategies { - s, ok := h.parseOperationStrategy(operationStrategy, opS) - if !ok { - continue - } - - opS.PerOperationStrategies = append(opS.PerOperationStrategies, - &sampling.OperationSamplingStrategy{ - Operation: operationStrategy.Operation, - ProbabilisticSampling: s.ProbabilisticSampling, - }) - } - resp.OperationSampling = opS - return resp -} - -func (h *strategyStore) parseOperationStrategy( - strategy *operationStrategy, - parent *sampling.PerOperationSamplingStrategies, -) (s *sampling.SamplingStrategyResponse, ok bool) { - s = h.parseStrategy(&strategy.strategy) - if s.StrategyType == sampling.SamplingStrategyType_RATE_LIMITING { - // TODO OperationSamplingStrategy only supports probabilistic sampling - h.logger.Warn( - fmt.Sprintf( - "Operation strategies only supports probabilistic sampling at the moment,"+ - "'%s' defaulting to probabilistic sampling with probability %f", - strategy.Operation, parent.DefaultSamplingProbability), - zap.Any("strategy", strategy)) - return nil, false - } - return s, true -} - -func (h *strategyStore) parseStrategy(strategy *strategy) *sampling.SamplingStrategyResponse { - switch strategy.Type { - case samplerTypeProbabilistic: - return &sampling.SamplingStrategyResponse{ - StrategyType: sampling.SamplingStrategyType_PROBABILISTIC, - ProbabilisticSampling: &sampling.ProbabilisticSamplingStrategy{ - SamplingRate: strategy.Param, - }, - } - case samplerTypeRateLimiting: - return &sampling.SamplingStrategyResponse{ - StrategyType: sampling.SamplingStrategyType_RATE_LIMITING, - RateLimitingSampling: &sampling.RateLimitingSamplingStrategy{ - MaxTracesPerSecond: int16(strategy.Param), - }, - } - default: - h.logger.Warn("Failed to parse sampling strategy", zap.Any("strategy", strategy)) - return defaultStrategyResponse() - } -} - -func deepCopy(s *sampling.SamplingStrategyResponse) *sampling.SamplingStrategyResponse { //nolint:unused - var buf bytes.Buffer - enc := gob.NewEncoder(&buf) - dec := gob.NewDecoder(&buf) - _ = enc.Encode(*s) - var result sampling.SamplingStrategyResponse //nolint:revive - _ = dec.Decode(&result) - return &result -} diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/metadata.yaml b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/metadata.yaml deleted file mode 100644 index 73a23a66c216..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/metadata.yaml +++ /dev/null @@ -1,13 +0,0 @@ -type: jaegerremotesampling - -status: - class: extension - stability: - alpha: [extension] - distributions: - - contrib - - grafana - - redhat - - sumo - codeowners: - active: [jpkrohling, frzifus] diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/testdata/config.yaml b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/testdata/config.yaml deleted file mode 100644 index ec8bd9d9814a..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/testdata/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -jaegerremotesampling: - source: - remote: - endpoint: jaeger-collector:14250 -jaegerremotesampling/1: - source: - reload_interval: 1s - file: /etc/otelcol/sampling_strategies.json diff --git a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/testdata/strategy.json b/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/testdata/strategy.json deleted file mode 100644 index d086c64042db..000000000000 --- a/extension/jaegerremotesampling/internal/jaegerremotesamplingdeprecated/testdata/strategy.json +++ /dev/null @@ -1 +0,0 @@ -{"strategyType":"PROBABILISTIC"} \ No newline at end of file diff --git a/pkg/translator/jaeger/go.mod b/pkg/translator/jaeger/go.mod index 112a9cae4e70..6d0ba70d48c3 100644 --- a/pkg/translator/jaeger/go.mod +++ b/pkg/translator/jaeger/go.mod @@ -15,6 +15,7 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.3 // indirect + github.com/google/go-cmp v0.6.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -22,7 +23,7 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect github.com/uber/jaeger-lib v2.4.1+incompatible // indirect - go.uber.org/atomic v1.10.0 // indirect + go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.26.0 // indirect golang.org/x/net v0.18.0 // indirect diff --git a/pkg/translator/jaeger/go.sum b/pkg/translator/jaeger/go.sum index cb769c49232f..b02be35b2711 100644 --- a/pkg/translator/jaeger/go.sum +++ b/pkg/translator/jaeger/go.sum @@ -10,7 +10,8 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaS github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/jaegertracing/jaeger v1.41.0 h1:vVNky8dP46M2RjGaZ7qRENqylW+tBFay3h57N16Ip7M= github.com/jaegertracing/jaeger v1.41.0/go.mod h1:SIkAT75iVmA9U+mESGYuMH6UQv6V9Qy4qxo0lwfCQAc= @@ -45,8 +46,8 @@ go.opentelemetry.io/collector/pdata v1.0.1-0.20231201205146-6e2fdc755b34 h1:dVqK go.opentelemetry.io/collector/pdata v1.0.1-0.20231201205146-6e2fdc755b34/go.mod h1:TsDFgs4JLNG7t6x9D8kGswXUz4mme+MyNChHx8zSF6k= go.opentelemetry.io/collector/semconv v0.90.2-0.20231201205146-6e2fdc755b34 h1:kv7QJcgWCg+gvEtcAeFsmRD3DePlNlTWFOCNyuJ4sEY= go.opentelemetry.io/collector/semconv v0.90.2-0.20231201205146-6e2fdc755b34/go.mod h1:j/8THcqVxFna1FpvA2zYIsUperEtOaRaqoLYIN4doWw= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= diff --git a/receiver/jaegerreceiver/factory.go b/receiver/jaegerreceiver/factory.go index 960d1773f6c9..daf3ccbd5347 100644 --- a/receiver/jaegerreceiver/factory.go +++ b/receiver/jaegerreceiver/factory.go @@ -18,7 +18,6 @@ import ( "go.opentelemetry.io/collector/receiver" "go.uber.org/zap" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/metadata" ) @@ -51,21 +50,18 @@ func logDeprecation(logger *zap.Logger) { }) } -const protoInsteadOfThrift = "receiver.jaegerreceiver.replaceThriftWithProto" - +// nolint var protoGate = featuregate.GlobalRegistry().MustRegister( - protoInsteadOfThrift, - featuregate.StageBeta, + "receiver.jaegerreceiver.replaceThriftWithProto", + featuregate.StageStable, featuregate.WithRegisterDescription( "When enabled, the jaegerreceiver will use Proto-gen over Thrift-gen.", ), + featuregate.WithRegisterToVersion("0.92.0"), ) // NewFactory creates a new Jaeger receiver factory. func NewFactory() receiver.Factory { - if !protoGate.IsEnabled() { - return jaegerreceiverdeprecated.NewFactory() - } return receiver.NewFactory( metadata.Type, createDefaultConfig, diff --git a/receiver/jaegerreceiver/go.mod b/receiver/jaegerreceiver/go.mod index 66f900887ed8..22c8294ff5f6 100644 --- a/receiver/jaegerreceiver/go.mod +++ b/receiver/jaegerreceiver/go.mod @@ -22,7 +22,6 @@ require ( go.opentelemetry.io/collector/semconv v0.90.2-0.20231201205146-6e2fdc755b34 go.uber.org/multierr v1.11.0 go.uber.org/zap v1.26.0 - golang.org/x/net v0.19.0 google.golang.org/grpc v1.59.0 ) @@ -70,6 +69,7 @@ require ( go.opentelemetry.io/otel/metric v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect go.uber.org/atomic v1.11.0 // indirect + golang.org/x/net v0.19.0 // indirect golang.org/x/oauth2 v0.14.0 // indirect golang.org/x/sys v0.15.0 // indirect golang.org/x/text v0.14.0 // indirect diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/README.md b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/README.md deleted file mode 100644 index 7dae0b40c1b9..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# DO NOT USE THIS PACKAGE - -This package is a workaround to bump the jaeger dependency and will be removed soon. - -For more details see: https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/18485 diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/config.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/config.go deleted file mode 100644 index d4f812507080..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/config.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerreceiverdeprecated // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated" - -import ( - "fmt" - "net" - "strconv" - "time" - - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/confmap" -) - -const ( - // The config field id to load the protocol map from - protocolsFieldName = "protocols" - - // Default UDP server options - defaultQueueSize = 1_000 - defaultMaxPacketSize = 65_000 - defaultServerWorkers = 10 - defaultSocketBufferSize = 0 -) - -// RemoteSamplingConfig defines config key for remote sampling fetch endpoint -type RemoteSamplingConfig struct { - HostEndpoint string `mapstructure:"host_endpoint"` - StrategyFile string `mapstructure:"strategy_file"` - StrategyFileReloadInterval time.Duration `mapstructure:"strategy_file_reload_interval"` - configgrpc.GRPCClientSettings `mapstructure:",squash"` -} - -// Protocols is the configuration for the supported protocols. -type Protocols struct { - GRPC *configgrpc.GRPCServerSettings `mapstructure:"grpc"` - ThriftHTTP *confighttp.HTTPServerSettings `mapstructure:"thrift_http"` - ThriftBinary *ProtocolUDP `mapstructure:"thrift_binary"` - ThriftCompact *ProtocolUDP `mapstructure:"thrift_compact"` -} - -// ProtocolUDP is the configuration for a UDP protocol. -type ProtocolUDP struct { - Endpoint string `mapstructure:"endpoint"` - ServerConfigUDP `mapstructure:",squash"` -} - -// ServerConfigUDP is the server configuration for a UDP protocol. -type ServerConfigUDP struct { - QueueSize int `mapstructure:"queue_size"` - MaxPacketSize int `mapstructure:"max_packet_size"` - Workers int `mapstructure:"workers"` - SocketBufferSize int `mapstructure:"socket_buffer_size"` -} - -// defaultServerConfigUDP creates the default ServerConfigUDP. -func defaultServerConfigUDP() ServerConfigUDP { - return ServerConfigUDP{ - QueueSize: defaultQueueSize, - MaxPacketSize: defaultMaxPacketSize, - Workers: defaultServerWorkers, - SocketBufferSize: defaultSocketBufferSize, - } -} - -// Config defines configuration for Jaeger receiver. -type Config struct { - Protocols `mapstructure:"protocols"` - RemoteSampling *RemoteSamplingConfig `mapstructure:"remote_sampling"` -} - -var _ component.Config = (*Config)(nil) -var _ confmap.Unmarshaler = (*Config)(nil) - -// Validate checks the receiver configuration is valid -func (cfg *Config) Validate() error { - if cfg.GRPC == nil && - cfg.ThriftHTTP == nil && - cfg.ThriftBinary == nil && - cfg.ThriftCompact == nil { - return fmt.Errorf("must specify at least one protocol when using the Jaeger receiver") - } - - if cfg.GRPC != nil { - if err := checkPortFromEndpoint(cfg.GRPC.NetAddr.Endpoint); err != nil { - return fmt.Errorf("invalid port number for the gRPC endpoint: %w", err) - } - } - - if cfg.ThriftHTTP != nil { - if err := checkPortFromEndpoint(cfg.ThriftHTTP.Endpoint); err != nil { - return fmt.Errorf("invalid port number for the Thrift HTTP endpoint: %w", err) - } - } - - if cfg.ThriftBinary != nil { - if err := checkPortFromEndpoint(cfg.ThriftBinary.Endpoint); err != nil { - return fmt.Errorf("invalid port number for the Thrift UDP Binary endpoint: %w", err) - } - } - - if cfg.ThriftCompact != nil { - if err := checkPortFromEndpoint(cfg.ThriftCompact.Endpoint); err != nil { - return fmt.Errorf("invalid port number for the Thrift UDP Compact endpoint: %w", err) - } - } - - if cfg.RemoteSampling != nil { - if err := checkPortFromEndpoint(cfg.RemoteSampling.HostEndpoint); err != nil { - return fmt.Errorf("invalid port number for the Remote Sampling endpoint: %w", err) - } - - if len(cfg.RemoteSampling.StrategyFile) != 0 && cfg.GRPC == nil { - return fmt.Errorf("strategy file requires the gRPC protocol to be enabled") - } - - if cfg.RemoteSampling.StrategyFileReloadInterval < 0 { - return fmt.Errorf("strategy file reload interval should be great or equal zero") - } - } - - return nil -} - -// Unmarshal a config.Parser into the config struct. -func (cfg *Config) Unmarshal(componentParser *confmap.Conf) error { - if componentParser == nil || len(componentParser.AllKeys()) == 0 { - return fmt.Errorf("empty config for Jaeger receiver") - } - - // UnmarshalExact will not set struct properties to nil even if no key is provided, - // so set the protocol structs to nil where the keys were omitted. - err := componentParser.Unmarshal(cfg, confmap.WithErrorUnused()) - if err != nil { - return err - } - - protocols, err := componentParser.Sub(protocolsFieldName) - if err != nil { - return err - } - - if !protocols.IsSet(protoGRPC) { - cfg.GRPC = nil - } - if !protocols.IsSet(protoThriftHTTP) { - cfg.ThriftHTTP = nil - } - if !protocols.IsSet(protoThriftBinary) { - cfg.ThriftBinary = nil - } - if !protocols.IsSet(protoThriftCompact) { - cfg.ThriftCompact = nil - } - - return nil -} - -// checkPortFromEndpoint checks that the endpoint string contains a port in the format "address:port". If the -// port number cannot be parsed, returns an error. -func checkPortFromEndpoint(endpoint string) error { - _, portStr, err := net.SplitHostPort(endpoint) - if err != nil { - return fmt.Errorf("endpoint is not formatted correctly: %w", err) - } - port, err := strconv.ParseInt(portStr, 10, 0) - if err != nil { - return fmt.Errorf("endpoint port is not a number: %w", err) - } - if port < 1 || port > 65535 { - return fmt.Errorf("port number must be between 1 and 65535") - } - return nil -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/config_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/config_test.go deleted file mode 100644 index 14b13bbcee3e..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/config_test.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerreceiverdeprecated - -import ( - "path/filepath" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/config/confignet" - "go.opentelemetry.io/collector/config/configtls" - "go.opentelemetry.io/collector/confmap/confmaptest" - - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/metadata" -) - -func TestLoadConfig(t *testing.T) { - t.Parallel() - - cm, err := confmaptest.LoadConf(filepath.Join("testdata", "config.yaml")) - require.NoError(t, err) - - tests := []struct { - id component.ID - expected component.Config - }{ - { - id: component.NewIDWithName(metadata.Type, "customname"), - expected: &Config{ - Protocols: Protocols{ - GRPC: &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: "localhost:9876", - Transport: "tcp", - }, - }, - ThriftHTTP: &confighttp.HTTPServerSettings{ - Endpoint: ":3456", - }, - ThriftCompact: &ProtocolUDP{ - Endpoint: "0.0.0.0:456", - ServerConfigUDP: ServerConfigUDP{ - QueueSize: 100_000, - MaxPacketSize: 131_072, - Workers: 100, - SocketBufferSize: 65_536, - }, - }, - ThriftBinary: &ProtocolUDP{ - Endpoint: "0.0.0.0:789", - ServerConfigUDP: ServerConfigUDP{ - QueueSize: 1_000, - MaxPacketSize: 65_536, - Workers: 5, - SocketBufferSize: 0, - }, - }, - }, - RemoteSampling: &RemoteSamplingConfig{ - HostEndpoint: "0.0.0.0:5778", - GRPCClientSettings: configgrpc.GRPCClientSettings{ - Endpoint: "jaeger-collector:1234", - }, - StrategyFile: "/etc/strategies.json", - StrategyFileReloadInterval: time.Second * 10, - }, - }, - }, - { - id: component.NewIDWithName(metadata.Type, "defaults"), - expected: &Config{ - Protocols: Protocols{ - GRPC: &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: defaultGRPCBindEndpoint, - Transport: "tcp", - }, - }, - ThriftHTTP: &confighttp.HTTPServerSettings{ - Endpoint: defaultHTTPBindEndpoint, - }, - ThriftCompact: &ProtocolUDP{ - Endpoint: defaultThriftCompactBindEndpoint, - ServerConfigUDP: defaultServerConfigUDP(), - }, - ThriftBinary: &ProtocolUDP{ - Endpoint: defaultThriftBinaryBindEndpoint, - ServerConfigUDP: defaultServerConfigUDP(), - }, - }, - }, - }, - { - id: component.NewIDWithName(metadata.Type, "mixed"), - expected: &Config{ - Protocols: Protocols{ - GRPC: &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: "localhost:9876", - Transport: "tcp", - }, - }, - ThriftCompact: &ProtocolUDP{ - Endpoint: defaultThriftCompactBindEndpoint, - ServerConfigUDP: defaultServerConfigUDP(), - }, - }, - }, - }, - { - id: component.NewIDWithName(metadata.Type, "tls"), - expected: &Config{ - Protocols: Protocols{ - GRPC: &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: "localhost:9876", - Transport: "tcp", - }, - TLSSetting: &configtls.TLSServerSetting{ - TLSSetting: configtls.TLSSetting{ - CertFile: "/test.crt", - KeyFile: "/test.key", - }, - }, - }, - ThriftHTTP: &confighttp.HTTPServerSettings{ - Endpoint: ":3456", - }, - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.id.String(), func(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - sub, err := cm.Sub(tt.id.String()) - require.NoError(t, err) - require.NoError(t, component.UnmarshalConfig(sub, cfg)) - - assert.NoError(t, component.ValidateConfig(cfg)) - assert.Equal(t, tt.expected, cfg) - }) - } -} - -func TestFailedLoadConfig(t *testing.T) { - cm, err := confmaptest.LoadConf(filepath.Join("testdata", "config.yaml")) - require.NoError(t, err) - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - sub, err := cm.Sub(component.NewIDWithName(metadata.Type, "typo_default_proto_config").String()) - require.NoError(t, err) - err = component.UnmarshalConfig(sub, cfg) - assert.EqualError(t, err, "1 error(s) decoding:\n\n* 'protocols' has invalid keys: thrift_htttp") - - sub, err = cm.Sub(component.NewIDWithName(metadata.Type, "bad_proto_config").String()) - require.NoError(t, err) - err = component.UnmarshalConfig(sub, cfg) - assert.EqualError(t, err, "1 error(s) decoding:\n\n* 'protocols' has invalid keys: thrift_htttp") - - sub, err = cm.Sub(component.NewIDWithName(metadata.Type, "empty").String()) - require.NoError(t, err) - err = component.UnmarshalConfig(sub, cfg) - assert.EqualError(t, err, "empty config for Jaeger receiver") -} - -func TestInvalidConfig(t *testing.T) { - testCases := []struct { - desc string - apply func(*Config) - err string - }{ - { - desc: "thrift-http-no-port", - apply: func(cfg *Config) { - cfg.ThriftHTTP = &confighttp.HTTPServerSettings{ - Endpoint: "localhost:", - } - }, - err: "receiver creation with no port number for Thrift HTTP must fail", - }, - { - desc: "thrift-udp-compact-no-port", - apply: func(cfg *Config) { - cfg.ThriftCompact = &ProtocolUDP{ - Endpoint: "localhost:", - } - }, - err: "receiver creation with no port number for Thrift UDP - Compact must fail", - }, - { - desc: "thrift-udp-binary-no-port", - apply: func(cfg *Config) { - cfg.ThriftBinary = &ProtocolUDP{ - Endpoint: "localhost:", - } - }, - err: "receiver creation with no port number for Thrift UDP - Binary must fail", - }, - { - desc: "remote-sampling-http-no-port", - apply: func(cfg *Config) { - cfg.RemoteSampling = &RemoteSamplingConfig{ - HostEndpoint: "localhost:", - } - }, - err: "receiver creation with no port number for the remote sampling HTTP endpoint must fail", - }, - { - desc: "grpc-invalid-host", - apply: func(cfg *Config) { - cfg.GRPC = &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: "1234", - Transport: "tcp", - }, - } - }, - err: "receiver creation with bad hostname must fail", - }, - { - desc: "no-protocols", - apply: func(cfg *Config) { - cfg.Protocols = Protocols{} - }, - err: "receiver creation with no protocols must fail", - }, - { - desc: "port-outside-of-range", - apply: func(cfg *Config) { - cfg.ThriftBinary = &ProtocolUDP{ - Endpoint: "localhost:65536", - } - }, - err: "receiver creation with too large port number must fail", - }, - { - desc: "port-outside-of-range", - apply: func(cfg *Config) { - cfg.Protocols = Protocols{} - cfg.ThriftCompact = &ProtocolUDP{ - Endpoint: defaultThriftCompactBindEndpoint, - } - cfg.RemoteSampling = &RemoteSamplingConfig{ - HostEndpoint: "localhost:5778", - StrategyFile: "strategies.json", - } - }, - err: "receiver creation without gRPC and with remote sampling config", - }, - { - desc: "reload-interval-outside-of-range", - apply: func(cfg *Config) { - cfg.Protocols.GRPC = &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: "1234", - Transport: "tcp", - }, - } - cfg.RemoteSampling = &RemoteSamplingConfig{ - HostEndpoint: "localhost:5778", - StrategyFile: "strategies.json", - StrategyFileReloadInterval: -time.Second, - } - }, - err: "strategy file reload interval should be great zero", - }, - } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig().(*Config) - - tC.apply(cfg) - - err := component.ValidateConfig(cfg) - assert.Error(t, err, tC.err) - - }) - } -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/doc.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/doc.go deleted file mode 100644 index 3b7bdb3c2c1e..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -//go:generate mdatagen metadata.yaml - -// Package jaegerreceiver receives Jaeger traces. -package jaegerreceiverdeprecated // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated" diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/errors.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/errors.go deleted file mode 100644 index b1312c9621f6..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/errors.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerreceiverdeprecated // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated" - -type httpError struct { - msg string - statusCode int -} - -func (h httpError) Error() string { - return h.msg -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/factory.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/factory.go deleted file mode 100644 index b40c19f1bd7f..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/factory.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerreceiverdeprecated // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated" - -// This file implements factory for Jaeger receiver. - -import ( - "context" - - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/config/confignet" - "go.opentelemetry.io/collector/consumer" - "go.opentelemetry.io/collector/receiver" - - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/metadata" -) - -const ( - // Protocol values. - protoGRPC = "grpc" - protoThriftHTTP = "thrift_http" - protoThriftBinary = "thrift_binary" - protoThriftCompact = "thrift_compact" - - // Default endpoints to bind to. - defaultGRPCBindEndpoint = "0.0.0.0:14250" - defaultHTTPBindEndpoint = "0.0.0.0:14268" - defaultThriftCompactBindEndpoint = "0.0.0.0:6831" - defaultThriftBinaryBindEndpoint = "0.0.0.0:6832" -) - -// NewFactory creates a new Jaeger receiver factory. -func NewFactory() receiver.Factory { - return receiver.NewFactory( - metadata.Type, - createDefaultConfig, - receiver.WithTraces(createTracesReceiver, metadata.TracesStability)) -} - -// CreateDefaultConfig creates the default configuration for Jaeger receiver. -func createDefaultConfig() component.Config { - return &Config{ - Protocols: Protocols{ - GRPC: &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: defaultGRPCBindEndpoint, - Transport: "tcp", - }, - }, - ThriftHTTP: &confighttp.HTTPServerSettings{ - Endpoint: defaultHTTPBindEndpoint, - }, - ThriftBinary: &ProtocolUDP{ - Endpoint: defaultThriftBinaryBindEndpoint, - ServerConfigUDP: defaultServerConfigUDP(), - }, - ThriftCompact: &ProtocolUDP{ - Endpoint: defaultThriftCompactBindEndpoint, - ServerConfigUDP: defaultServerConfigUDP(), - }, - }, - } -} - -// createTracesReceiver creates a trace receiver based on provided config. -func createTracesReceiver( - _ context.Context, - set receiver.CreateSettings, - cfg component.Config, - nextConsumer consumer.Traces, -) (receiver.Traces, error) { - - // Convert settings in the source config to configuration struct - // that Jaeger receiver understands. - // Error handling for the conversion is done in the Validate function from the Config object itself. - - rCfg := cfg.(*Config) - - var config configuration - // Set ports - if rCfg.Protocols.GRPC != nil { - config.CollectorGRPCServerSettings = *rCfg.Protocols.GRPC - } - - if rCfg.Protocols.ThriftHTTP != nil { - config.CollectorHTTPSettings = *rCfg.ThriftHTTP - } - - if rCfg.Protocols.ThriftBinary != nil { - config.AgentBinaryThrift = *rCfg.ThriftBinary - } - - if rCfg.Protocols.ThriftCompact != nil { - config.AgentCompactThrift = *rCfg.ThriftCompact - } - - // Create the receiver. - return newJaegerReceiver(set.ID, &config, nextConsumer, set) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/factory_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/factory_test.go deleted file mode 100644 index 87b99596571a..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/factory_test.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerreceiverdeprecated - -import ( - "context" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/component/componenttest" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/config/confignet" - "go.opentelemetry.io/collector/config/configtls" - "go.opentelemetry.io/collector/confmap/confmaptest" - "go.opentelemetry.io/collector/receiver/receivertest" - - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/metadata" -) - -func TestTypeStr(t *testing.T) { - factory := NewFactory() - - assert.Equal(t, "jaeger", string(factory.Type())) -} - -func TestCreateDefaultConfig(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - assert.NotNil(t, cfg, "failed to create default config") - assert.NoError(t, componenttest.CheckConfigStruct(cfg)) -} - -func TestCreateReceiver(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - // have to enable at least one protocol for the jaeger receiver to be created - cfg.(*Config).Protocols.GRPC = &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: defaultGRPCBindEndpoint, - Transport: "tcp", - }, - } - set := receivertest.NewNopCreateSettings() - tReceiver, err := factory.CreateTracesReceiver(context.Background(), set, cfg, nil) - assert.NoError(t, err, "receiver creation failed") - assert.NotNil(t, tReceiver, "receiver creation failed") - - mReceiver, err := factory.CreateMetricsReceiver(context.Background(), set, cfg, nil) - assert.Equal(t, err, component.ErrDataTypeIsNotSupported) - assert.Nil(t, mReceiver) -} - -func TestCreateReceiverGeneralConfig(t *testing.T) { - cm, err := confmaptest.LoadConf(filepath.Join("testdata", "config.yaml")) - require.NoError(t, err) - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - sub, err := cm.Sub(component.NewIDWithName(metadata.Type, "customname").String()) - require.NoError(t, err) - require.NoError(t, component.UnmarshalConfig(sub, cfg)) - - set := receivertest.NewNopCreateSettings() - tReceiver, err := factory.CreateTracesReceiver(context.Background(), set, cfg, nil) - assert.NoError(t, err, "receiver creation failed") - assert.NotNil(t, tReceiver, "receiver creation failed") - - mReceiver, err := factory.CreateMetricsReceiver(context.Background(), set, cfg, nil) - assert.Equal(t, err, component.ErrDataTypeIsNotSupported) - assert.Nil(t, mReceiver) -} - -// default ports retrieved from https://www.jaegertracing.io/docs/1.16/deployment/ -func TestCreateDefaultGRPCEndpoint(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - cfg.(*Config).Protocols.GRPC = &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: defaultGRPCBindEndpoint, - Transport: "tcp", - }, - } - set := receivertest.NewNopCreateSettings() - r, err := factory.CreateTracesReceiver(context.Background(), set, cfg, nil) - - assert.NoError(t, err, "unexpected error creating receiver") - assert.Equal(t, defaultGRPCBindEndpoint, r.(*jReceiver).config.CollectorGRPCServerSettings.NetAddr.Endpoint, "grpc port should be default") -} - -func TestCreateTLSGPRCEndpoint(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - cfg.(*Config).Protocols.GRPC = &configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: defaultGRPCBindEndpoint, - Transport: "tcp", - }, - TLSSetting: &configtls.TLSServerSetting{ - TLSSetting: configtls.TLSSetting{ - CertFile: "./testdata/server.crt", - KeyFile: "./testdata/server.key", - }, - }, - } - set := receivertest.NewNopCreateSettings() - - _, err := factory.CreateTracesReceiver(context.Background(), set, cfg, nil) - assert.NoError(t, err, "tls-enabled receiver creation failed") -} - -func TestCreateTLSThriftHTTPEndpoint(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - cfg.(*Config).Protocols.ThriftHTTP = &confighttp.HTTPServerSettings{ - Endpoint: defaultHTTPBindEndpoint, - TLSSetting: &configtls.TLSServerSetting{ - TLSSetting: configtls.TLSSetting{ - CertFile: "./testdata/server.crt", - KeyFile: "./testdata/server.key", - }, - }, - } - - set := receivertest.NewNopCreateSettings() - - _, err := factory.CreateTracesReceiver(context.Background(), set, cfg, nil) - assert.NoError(t, err, "tls-enabled receiver creation failed") -} - -func TestCreateInvalidHTTPEndpoint(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - set := receivertest.NewNopCreateSettings() - r, err := factory.CreateTracesReceiver(context.Background(), set, cfg, nil) - - assert.NoError(t, err, "unexpected error creating receiver") - assert.Equal(t, defaultHTTPBindEndpoint, r.(*jReceiver).config.CollectorHTTPSettings.Endpoint, "http port should be default") -} - -func TestCreateInvalidThriftBinaryEndpoint(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - cfg.(*Config).Protocols.ThriftBinary = &ProtocolUDP{ - Endpoint: defaultThriftBinaryBindEndpoint, - } - set := receivertest.NewNopCreateSettings() - r, err := factory.CreateTracesReceiver(context.Background(), set, cfg, nil) - - assert.NoError(t, err, "unexpected error creating receiver") - assert.Equal(t, defaultThriftBinaryBindEndpoint, r.(*jReceiver).config.AgentBinaryThrift.Endpoint, "thrift port should be default") -} - -func TestCreateInvalidThriftCompactEndpoint(t *testing.T) { - factory := NewFactory() - cfg := factory.CreateDefaultConfig() - - cfg.(*Config).Protocols.ThriftCompact = &ProtocolUDP{ - Endpoint: defaultThriftCompactBindEndpoint, - } - set := receivertest.NewNopCreateSettings() - r, err := factory.CreateTracesReceiver(context.Background(), set, cfg, nil) - - assert.NoError(t, err, "unexpected error creating receiver") - assert.Equal(t, defaultThriftCompactBindEndpoint, r.(*jReceiver).config.AgentCompactThrift.Endpoint, "thrift port should be default") -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/cfgmgr.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/cfgmgr.go deleted file mode 100644 index c4132a8126ad..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/cfgmgr.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2020 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clientcfghttp // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp" - -import ( - "context" - "errors" - - "github.com/jaegertracing/jaeger/thrift-gen/baggage" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore" -) - -// ConfigManager implements ClientConfigManager. -type ConfigManager struct { - SamplingStrategyStore strategystore.StrategyStore - BaggageManager baggage.BaggageRestrictionManager -} - -// GetSamplingStrategy implements ClientConfigManager.GetSamplingStrategy. -func (c *ConfigManager) GetSamplingStrategy(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) { - return c.SamplingStrategyStore.GetSamplingStrategy(ctx, serviceName) -} - -// GetBaggageRestrictions implements ClientConfigManager.GetBaggageRestrictions. -func (c *ConfigManager) GetBaggageRestrictions(ctx context.Context, serviceName string) ([]*baggage.BaggageRestriction, error) { - if c.BaggageManager == nil { - return nil, errors.New("baggage restrictions not implemented") - } - return c.BaggageManager.GetBaggageRestrictions(ctx, serviceName) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/cfgmgr_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/cfgmgr_test.go deleted file mode 100644 index e510385c5527..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/cfgmgr_test.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2020 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clientcfghttp - -import ( - "context" - "errors" - "testing" - - "github.com/jaegertracing/jaeger/thrift-gen/baggage" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type mockSamplingStore struct { - samplingResponse *sampling.SamplingStrategyResponse -} - -func (m *mockSamplingStore) GetSamplingStrategy(_ context.Context, _ string) (*sampling.SamplingStrategyResponse, error) { - if m.samplingResponse == nil { - return nil, errors.New("no mock response provided") - } - return m.samplingResponse, nil -} - -type mockBaggageMgr struct { - baggageResponse []*baggage.BaggageRestriction -} - -func (m *mockBaggageMgr) GetBaggageRestrictions(_ context.Context, _ string) ([]*baggage.BaggageRestriction, error) { - if m.baggageResponse == nil { - return nil, errors.New("no mock response provided") - } - return m.baggageResponse, nil -} - -func TestConfigManager(t *testing.T) { - bgm := &mockBaggageMgr{} - mgr := &ConfigManager{ - SamplingStrategyStore: &mockSamplingStore{ - samplingResponse: &sampling.SamplingStrategyResponse{}, - }, - BaggageManager: bgm, - } - t.Run("GetSamplingStrategy", func(t *testing.T) { - r, err := mgr.GetSamplingStrategy(context.Background(), "foo") - require.NoError(t, err) - assert.Equal(t, sampling.SamplingStrategyResponse{}, *r) - }) - t.Run("GetBaggageRestrictions", func(t *testing.T) { - expResp := []*baggage.BaggageRestriction{} - bgm.baggageResponse = expResp - r, err := mgr.GetBaggageRestrictions(context.Background(), "foo") - require.NoError(t, err) - assert.Equal(t, expResp, r) - }) - t.Run("GetBaggageRestrictionsError", func(t *testing.T) { - mgr.BaggageManager = nil - _, err := mgr.GetBaggageRestrictions(context.Background(), "foo") - assert.EqualError(t, err, "baggage restrictions not implemented") - }) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/handler.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/handler.go deleted file mode 100644 index 828481b385ae..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/handler.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clientcfghttp // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp" - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "strings" - - "github.com/gorilla/mux" - "github.com/jaegertracing/jaeger/pkg/metrics" - tSampling "github.com/jaegertracing/jaeger/thrift-gen/sampling" - - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager" -) - -const mimeTypeApplicationJSON = "application/json" - -var errBadRequest = errors.New("bad request") - -// HTTPHandlerParams contains parameters that must be passed to NewHTTPHandler. -type HTTPHandlerParams struct { - ConfigManager configmanager.ClientConfigManager // required - MetricsFactory metrics.Factory // required - - // BasePath will be used as a prefix for the endpoints, e.g. "/api" - BasePath string - - // LegacySamplingEndpoint enables returning sampling strategy from "/" endpoint - // using Thrift 0.9.2 enum codes. - LegacySamplingEndpoint bool -} - -// HTTPHandler implements endpoints for used by Jaeger clients to retrieve client configuration, -// such as sampling and baggage restrictions. -type HTTPHandler struct { - params HTTPHandlerParams - metrics struct { - // Number of good sampling requests - SamplingRequestSuccess metrics.Counter `metric:"http-server.requests" tags:"type=sampling"` - - // Number of good sampling requests against the old endpoint / using Thrift 0.9.2 enum codes - LegacySamplingRequestSuccess metrics.Counter `metric:"http-server.requests" tags:"type=sampling-legacy"` - - // Number of good baggage requests - BaggageRequestSuccess metrics.Counter `metric:"http-server.requests" tags:"type=baggage"` - - // Number of bad requests (400s) - BadRequest metrics.Counter `metric:"http-server.errors" tags:"status=4xx,source=all"` - - // Number of collector proxy failures - CollectorProxyFailures metrics.Counter `metric:"http-server.errors" tags:"status=5xx,source=collector-proxy"` - - // Number of bad responses due to malformed thrift - BadThriftFailures metrics.Counter `metric:"http-server.errors" tags:"status=5xx,source=thrift"` - - // Number of failed response writes from http server - WriteFailures metrics.Counter `metric:"http-server.errors" tags:"status=5xx,source=write"` - } -} - -// NewHTTPHandler creates new HTTPHandler. -func NewHTTPHandler(params HTTPHandlerParams) *HTTPHandler { - handler := &HTTPHandler{params: params} - metrics.MustInit(&handler.metrics, params.MetricsFactory, nil) - return handler -} - -// RegisterRoutes registers configuration handlers with Gorilla Router. -func (h *HTTPHandler) RegisterRoutes(router *mux.Router) { - prefix := h.params.BasePath - if h.params.LegacySamplingEndpoint { - router.HandleFunc(prefix+"/", func(w http.ResponseWriter, r *http.Request) { - h.serveSamplingHTTP(w, r, true /* thriftEnums092 */) - }).Methods(http.MethodGet) - } - - router.HandleFunc(prefix+"/sampling", func(w http.ResponseWriter, r *http.Request) { - h.serveSamplingHTTP(w, r, false /* thriftEnums092 */) - }).Methods(http.MethodGet) - - router.HandleFunc(prefix+"/baggageRestrictions", func(w http.ResponseWriter, r *http.Request) { - h.serveBaggageHTTP(w, r) - }).Methods(http.MethodGet) -} - -func (h *HTTPHandler) serviceFromRequest(w http.ResponseWriter, r *http.Request) (string, error) { - services := r.URL.Query()["service"] - if len(services) != 1 { - h.metrics.BadRequest.Inc(1) - http.Error(w, "'service' parameter must be provided once", http.StatusBadRequest) - return "", errBadRequest - } - return services[0], nil -} - -func (h *HTTPHandler) writeJSON(w http.ResponseWriter, json []byte) error { - w.Header().Add("Content-Type", mimeTypeApplicationJSON) - if _, err := w.Write(json); err != nil { - h.metrics.WriteFailures.Inc(1) - return err - } - return nil -} - -func (h *HTTPHandler) serveSamplingHTTP(w http.ResponseWriter, r *http.Request, thriftEnums092 bool) { - service, err := h.serviceFromRequest(w, r) - if err != nil { - return - } - resp, err := h.params.ConfigManager.GetSamplingStrategy(r.Context(), service) - if err != nil { - h.metrics.CollectorProxyFailures.Inc(1) - http.Error(w, fmt.Sprintf("collector error: %+v", err), http.StatusInternalServerError) - return - } - jsonBytes, err := json.Marshal(resp) - if err != nil { - h.metrics.BadThriftFailures.Inc(1) - http.Error(w, "cannot marshall Thrift to JSON", http.StatusInternalServerError) - return - } - if thriftEnums092 { - jsonBytes = h.encodeThriftEnums092(jsonBytes) - } - if err = h.writeJSON(w, jsonBytes); err != nil { - return - } - if thriftEnums092 { - h.metrics.LegacySamplingRequestSuccess.Inc(1) - } else { - h.metrics.SamplingRequestSuccess.Inc(1) - } -} - -func (h *HTTPHandler) serveBaggageHTTP(w http.ResponseWriter, r *http.Request) { - service, err := h.serviceFromRequest(w, r) - if err != nil { - return - } - resp, err := h.params.ConfigManager.GetBaggageRestrictions(r.Context(), service) - if err != nil { - h.metrics.CollectorProxyFailures.Inc(1) - http.Error(w, fmt.Sprintf("collector error: %+v", err), http.StatusInternalServerError) - return - } - // NB. it's literally impossible for this Marshal to fail - jsonBytes, _ := json.Marshal(resp) - if err = h.writeJSON(w, jsonBytes); err != nil { - return - } - h.metrics.BaggageRequestSuccess.Inc(1) -} - -var samplingStrategyTypes = []tSampling.SamplingStrategyType{ - tSampling.SamplingStrategyType_PROBABILISTIC, - tSampling.SamplingStrategyType_RATE_LIMITING, -} - -// Replace string enum values produced from Thrift 0.9.3 generated classes -// with integer codes produced from Thrift 0.9.2 generated classes. -// -// For example: -// -// Thrift 0.9.2 classes generate this JSON: -// {"strategyType":0,"probabilisticSampling":{"samplingRate":0.5},"rateLimitingSampling":null,"operationSampling":null} -// -// Thrift 0.9.3 classes generate this JSON: -// {"strategyType":"PROBABILISTIC","probabilisticSampling":{"samplingRate":0.5}} -func (h *HTTPHandler) encodeThriftEnums092(json []byte) []byte { - str := string(json) - for _, strategyType := range samplingStrategyTypes { - str = strings.Replace( - str, - fmt.Sprintf(`"strategyType":"%s"`, strategyType.String()), - fmt.Sprintf(`"strategyType":%d`, strategyType), - 1, - ) - } - return []byte(str) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/.nocover b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/.nocover deleted file mode 100644 index 152f4437a158..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/.nocover +++ /dev/null @@ -1 +0,0 @@ -Thrift-generated files diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/constants.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/constants.go deleted file mode 100644 index 4486e3c2db91..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/constants.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Autogenerated by Thrift Compiler (0.9.2) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package sampling - -import ( - "bytes" - "fmt" - - "github.com/apache/thrift/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = bytes.Equal - -func init() { -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/ttypes.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/ttypes.go deleted file mode 100644 index 1a2724652a03..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2/ttypes.go +++ /dev/null @@ -1,790 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Autogenerated by Thrift Compiler (0.9.2) but manually adapted to 0.14.x - -// nolint -package sampling // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp/thrift-0.9.2" - -import ( - "bytes" - "context" - "fmt" - - "github.com/apache/thrift/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = bytes.Equal - -var GoUnusedProtection__ int - -type SamplingStrategyType int64 - -const ( - SamplingStrategyType_PROBABILISTIC SamplingStrategyType = 0 - SamplingStrategyType_RATE_LIMITING SamplingStrategyType = 1 -) - -func (p SamplingStrategyType) String() string { - switch p { - case SamplingStrategyType_PROBABILISTIC: - return "SamplingStrategyType_PROBABILISTIC" - case SamplingStrategyType_RATE_LIMITING: - return "SamplingStrategyType_RATE_LIMITING" - } - return "" -} - -func SamplingStrategyTypeFromString(s string) (SamplingStrategyType, error) { - switch s { - case "SamplingStrategyType_PROBABILISTIC": - return SamplingStrategyType_PROBABILISTIC, nil - case "SamplingStrategyType_RATE_LIMITING": - return SamplingStrategyType_RATE_LIMITING, nil - } - return SamplingStrategyType(0), fmt.Errorf("not a valid SamplingStrategyType string") -} - -func SamplingStrategyTypePtr(v SamplingStrategyType) *SamplingStrategyType { return &v } - -type ProbabilisticSamplingStrategy struct { - SamplingRate float64 `thrift:"samplingRate,1,required" json:"samplingRate"` -} - -func NewProbabilisticSamplingStrategy() *ProbabilisticSamplingStrategy { - return &ProbabilisticSamplingStrategy{} -} - -func (p *ProbabilisticSamplingStrategy) GetSamplingRate() float64 { - return p.SamplingRate -} -func (p *ProbabilisticSamplingStrategy) Read(iprot thrift.TProtocol) error { - ctx := context.Background() - if _, err := iprot.ReadStructBegin(ctx); err != nil { - return fmt.Errorf("%T read error: %s", p, err) - } - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin(ctx) - if err != nil { - return fmt.Errorf("%T field %d read error: %s", p, fieldId, err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.ReadField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(ctx, fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(ctx); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(ctx); err != nil { - return fmt.Errorf("%T read struct end error: %s", p, err) - } - return nil -} - -func (p *ProbabilisticSamplingStrategy) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadDouble(context.Background()); err != nil { - return fmt.Errorf("error reading field 1: %s", err) - } else { - p.SamplingRate = v - } - return nil -} - -func (p *ProbabilisticSamplingStrategy) Write(oprot thrift.TProtocol) error { - ctx := context.Background() - if err := oprot.WriteStructBegin(ctx, "ProbabilisticSamplingStrategy"); err != nil { - return fmt.Errorf("%T write struct begin error: %s", p, err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(ctx); err != nil { - return fmt.Errorf("write field stop error: %s", err) - } - if err := oprot.WriteStructEnd(ctx); err != nil { - return fmt.Errorf("write struct stop error: %s", err) - } - return nil -} - -func (p *ProbabilisticSamplingStrategy) writeField1(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if err := oprot.WriteFieldBegin(ctx, "samplingRate", thrift.DOUBLE, 1); err != nil { - return fmt.Errorf("%T write field begin error 1:samplingRate: %s", p, err) - } - if err := oprot.WriteDouble(ctx, float64(p.SamplingRate)); err != nil { - return fmt.Errorf("%T.samplingRate (1) field write error: %s", p, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 1:samplingRate: %s", p, err) - } - return err -} - -func (p *ProbabilisticSamplingStrategy) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ProbabilisticSamplingStrategy(%+v)", *p) -} - -type RateLimitingSamplingStrategy struct { - MaxTracesPerSecond int16 `thrift:"maxTracesPerSecond,1,required" json:"maxTracesPerSecond"` -} - -func NewRateLimitingSamplingStrategy() *RateLimitingSamplingStrategy { - return &RateLimitingSamplingStrategy{} -} - -func (p *RateLimitingSamplingStrategy) GetMaxTracesPerSecond() int16 { - return p.MaxTracesPerSecond -} -func (p *RateLimitingSamplingStrategy) Read(iprot thrift.TProtocol) error { - ctx := context.Background() - if _, err := iprot.ReadStructBegin(ctx); err != nil { - return fmt.Errorf("%T read error: %s", p, err) - } - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin(ctx) - if err != nil { - return fmt.Errorf("%T field %d read error: %s", p, fieldId, err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.ReadField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(ctx, fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(ctx); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(ctx); err != nil { - return fmt.Errorf("%T read struct end error: %s", p, err) - } - return nil -} - -func (p *RateLimitingSamplingStrategy) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI16(context.Background()); err != nil { - return fmt.Errorf("error reading field 1: %s", err) - } else { - p.MaxTracesPerSecond = v - } - return nil -} - -func (p *RateLimitingSamplingStrategy) Write(oprot thrift.TProtocol) error { - ctx := context.Background() - if err := oprot.WriteStructBegin(ctx, "RateLimitingSamplingStrategy"); err != nil { - return fmt.Errorf("%T write struct begin error: %s", p, err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(ctx); err != nil { - return fmt.Errorf("write field stop error: %s", err) - } - if err := oprot.WriteStructEnd(ctx); err != nil { - return fmt.Errorf("write struct stop error: %s", err) - } - return nil -} - -func (p *RateLimitingSamplingStrategy) writeField1(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if err := oprot.WriteFieldBegin(ctx, "maxTracesPerSecond", thrift.I16, 1); err != nil { - return fmt.Errorf("%T write field begin error 1:maxTracesPerSecond: %s", p, err) - } - if err := oprot.WriteI16(ctx, int16(p.MaxTracesPerSecond)); err != nil { - return fmt.Errorf("%T.maxTracesPerSecond (1) field write error: %s", p, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 1:maxTracesPerSecond: %s", p, err) - } - return err -} - -func (p *RateLimitingSamplingStrategy) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("RateLimitingSamplingStrategy(%+v)", *p) -} - -type OperationSamplingStrategy struct { - Operation string `thrift:"operation,1,required" json:"operation"` - ProbabilisticSampling *ProbabilisticSamplingStrategy `thrift:"probabilisticSampling,2,required" json:"probabilisticSampling"` -} - -func NewOperationSamplingStrategy() *OperationSamplingStrategy { - return &OperationSamplingStrategy{} -} - -func (p *OperationSamplingStrategy) GetOperation() string { - return p.Operation -} - -var OperationSamplingStrategy_ProbabilisticSampling_DEFAULT *ProbabilisticSamplingStrategy - -func (p *OperationSamplingStrategy) GetProbabilisticSampling() *ProbabilisticSamplingStrategy { - if !p.IsSetProbabilisticSampling() { - return OperationSamplingStrategy_ProbabilisticSampling_DEFAULT - } - return p.ProbabilisticSampling -} -func (p *OperationSamplingStrategy) IsSetProbabilisticSampling() bool { - return p.ProbabilisticSampling != nil -} - -func (p *OperationSamplingStrategy) Read(iprot thrift.TProtocol) error { - ctx := context.Background() - if _, err := iprot.ReadStructBegin(ctx); err != nil { - return fmt.Errorf("%T read error: %s", p, err) - } - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin(ctx) - if err != nil { - return fmt.Errorf("%T field %d read error: %s", p, fieldId, err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.ReadField1(iprot); err != nil { - return err - } - case 2: - if err := p.ReadField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(ctx, fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(ctx); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(ctx); err != nil { - return fmt.Errorf("%T read struct end error: %s", p, err) - } - return nil -} - -func (p *OperationSamplingStrategy) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(context.Background()); err != nil { - return fmt.Errorf("error reading field 1: %s", err) - } else { - p.Operation = v - } - return nil -} - -func (p *OperationSamplingStrategy) ReadField2(iprot thrift.TProtocol) error { - p.ProbabilisticSampling = &ProbabilisticSamplingStrategy{} - if err := p.ProbabilisticSampling.Read(iprot); err != nil { - return fmt.Errorf("%T error reading struct: %s", p.ProbabilisticSampling, err) - } - return nil -} - -func (p *OperationSamplingStrategy) Write(oprot thrift.TProtocol) error { - ctx := context.Background() - if err := oprot.WriteStructBegin(ctx, "OperationSamplingStrategy"); err != nil { - return fmt.Errorf("%T write struct begin error: %s", p, err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(ctx); err != nil { - return fmt.Errorf("write field stop error: %s", err) - } - if err := oprot.WriteStructEnd(ctx); err != nil { - return fmt.Errorf("write struct stop error: %s", err) - } - return nil -} - -func (p *OperationSamplingStrategy) writeField1(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if err := oprot.WriteFieldBegin(ctx, "operation", thrift.STRING, 1); err != nil { - return fmt.Errorf("%T write field begin error 1:operation: %s", p, err) - } - if err := oprot.WriteString(ctx, string(p.Operation)); err != nil { - return fmt.Errorf("%T.operation (1) field write error: %s", p, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 1:operation: %s", p, err) - } - return err -} - -func (p *OperationSamplingStrategy) writeField2(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if err := oprot.WriteFieldBegin(ctx, "probabilisticSampling", thrift.STRUCT, 2); err != nil { - return fmt.Errorf("%T write field begin error 2:probabilisticSampling: %s", p, err) - } - if err := p.ProbabilisticSampling.Write(oprot); err != nil { - return fmt.Errorf("%T error writing struct: %s", p.ProbabilisticSampling, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 2:probabilisticSampling: %s", p, err) - } - return err -} - -func (p *OperationSamplingStrategy) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("OperationSamplingStrategy(%+v)", *p) -} - -type PerOperationSamplingStrategies struct { - DefaultSamplingProbability float64 `thrift:"defaultSamplingProbability,1,required" json:"defaultSamplingProbability"` - DefaultLowerBoundTracesPerSecond float64 `thrift:"defaultLowerBoundTracesPerSecond,2,required" json:"defaultLowerBoundTracesPerSecond"` - PerOperationStrategies []*OperationSamplingStrategy `thrift:"perOperationStrategies,3,required" json:"perOperationStrategies"` -} - -func NewPerOperationSamplingStrategies() *PerOperationSamplingStrategies { - return &PerOperationSamplingStrategies{} -} - -func (p *PerOperationSamplingStrategies) GetDefaultSamplingProbability() float64 { - return p.DefaultSamplingProbability -} - -func (p *PerOperationSamplingStrategies) GetDefaultLowerBoundTracesPerSecond() float64 { - return p.DefaultLowerBoundTracesPerSecond -} - -func (p *PerOperationSamplingStrategies) GetPerOperationStrategies() []*OperationSamplingStrategy { - return p.PerOperationStrategies -} -func (p *PerOperationSamplingStrategies) Read(iprot thrift.TProtocol) error { - ctx := context.Background() - if _, err := iprot.ReadStructBegin(ctx); err != nil { - return fmt.Errorf("%T read error: %s", p, err) - } - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin(ctx) - if err != nil { - return fmt.Errorf("%T field %d read error: %s", p, fieldId, err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.ReadField1(iprot); err != nil { - return err - } - case 2: - if err := p.ReadField2(iprot); err != nil { - return err - } - case 3: - if err := p.ReadField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(ctx, fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(ctx); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(ctx); err != nil { - return fmt.Errorf("%T read struct end error: %s", p, err) - } - return nil -} - -func (p *PerOperationSamplingStrategies) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadDouble(context.Background()); err != nil { - return fmt.Errorf("error reading field 1: %s", err) - } else { - p.DefaultSamplingProbability = v - } - return nil -} - -func (p *PerOperationSamplingStrategies) ReadField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadDouble(context.Background()); err != nil { - return fmt.Errorf("error reading field 2: %s", err) - } else { - p.DefaultLowerBoundTracesPerSecond = v - } - return nil -} - -func (p *PerOperationSamplingStrategies) ReadField3(iprot thrift.TProtocol) error { - ctx := context.Background() - _, size, err := iprot.ReadListBegin(ctx) - if err != nil { - return fmt.Errorf("error reading list begin: %s", err) - } - tSlice := make([]*OperationSamplingStrategy, 0, size) - p.PerOperationStrategies = tSlice - for i := 0; i < size; i++ { - _elem0 := &OperationSamplingStrategy{} - if err := _elem0.Read(iprot); err != nil { - return fmt.Errorf("%T error reading struct: %s", _elem0, err) - } - p.PerOperationStrategies = append(p.PerOperationStrategies, _elem0) - } - if err := iprot.ReadListEnd(ctx); err != nil { - return fmt.Errorf("error reading list end: %s", err) - } - return nil -} - -func (p *PerOperationSamplingStrategies) Write(oprot thrift.TProtocol) error { - ctx := context.Background() - if err := oprot.WriteStructBegin(ctx, "PerOperationSamplingStrategies"); err != nil { - return fmt.Errorf("%T write struct begin error: %s", p, err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(ctx); err != nil { - return fmt.Errorf("write field stop error: %s", err) - } - if err := oprot.WriteStructEnd(ctx); err != nil { - return fmt.Errorf("write struct stop error: %s", err) - } - return nil -} - -func (p *PerOperationSamplingStrategies) writeField1(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if err := oprot.WriteFieldBegin(ctx, "defaultSamplingProbability", thrift.DOUBLE, 1); err != nil { - return fmt.Errorf("%T write field begin error 1:defaultSamplingProbability: %s", p, err) - } - if err := oprot.WriteDouble(ctx, float64(p.DefaultSamplingProbability)); err != nil { - return fmt.Errorf("%T.defaultSamplingProbability (1) field write error: %s", p, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 1:defaultSamplingProbability: %s", p, err) - } - return err -} - -func (p *PerOperationSamplingStrategies) writeField2(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if err := oprot.WriteFieldBegin(ctx, "defaultLowerBoundTracesPerSecond", thrift.DOUBLE, 2); err != nil { - return fmt.Errorf("%T write field begin error 2:defaultLowerBoundTracesPerSecond: %s", p, err) - } - if err := oprot.WriteDouble(ctx, float64(p.DefaultLowerBoundTracesPerSecond)); err != nil { - return fmt.Errorf("%T.defaultLowerBoundTracesPerSecond (2) field write error: %s", p, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 2:defaultLowerBoundTracesPerSecond: %s", p, err) - } - return err -} - -func (p *PerOperationSamplingStrategies) writeField3(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if err := oprot.WriteFieldBegin(ctx, "perOperationStrategies", thrift.LIST, 3); err != nil { - return fmt.Errorf("%T write field begin error 3:perOperationStrategies: %s", p, err) - } - if err := oprot.WriteListBegin(ctx, thrift.STRUCT, len(p.PerOperationStrategies)); err != nil { - return fmt.Errorf("error writing list begin: %s", err) - } - for _, v := range p.PerOperationStrategies { - if err := v.Write(oprot); err != nil { - return fmt.Errorf("%T error writing struct: %s", v, err) - } - } - if err := oprot.WriteListEnd(ctx); err != nil { - return fmt.Errorf("error writing list end: %s", err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 3:perOperationStrategies: %s", p, err) - } - return err -} - -func (p *PerOperationSamplingStrategies) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("PerOperationSamplingStrategies(%+v)", *p) -} - -type SamplingStrategyResponse struct { - StrategyType SamplingStrategyType `thrift:"strategyType,1,required" json:"strategyType"` - ProbabilisticSampling *ProbabilisticSamplingStrategy `thrift:"probabilisticSampling,2" json:"probabilisticSampling"` - RateLimitingSampling *RateLimitingSamplingStrategy `thrift:"rateLimitingSampling,3" json:"rateLimitingSampling"` - OperationSampling *PerOperationSamplingStrategies `thrift:"operationSampling,4" json:"operationSampling"` -} - -func NewSamplingStrategyResponse() *SamplingStrategyResponse { - return &SamplingStrategyResponse{} -} - -func (p *SamplingStrategyResponse) GetStrategyType() SamplingStrategyType { - return p.StrategyType -} - -var SamplingStrategyResponse_ProbabilisticSampling_DEFAULT *ProbabilisticSamplingStrategy - -func (p *SamplingStrategyResponse) GetProbabilisticSampling() *ProbabilisticSamplingStrategy { - if !p.IsSetProbabilisticSampling() { - return SamplingStrategyResponse_ProbabilisticSampling_DEFAULT - } - return p.ProbabilisticSampling -} - -var SamplingStrategyResponse_RateLimitingSampling_DEFAULT *RateLimitingSamplingStrategy - -func (p *SamplingStrategyResponse) GetRateLimitingSampling() *RateLimitingSamplingStrategy { - if !p.IsSetRateLimitingSampling() { - return SamplingStrategyResponse_RateLimitingSampling_DEFAULT - } - return p.RateLimitingSampling -} - -var SamplingStrategyResponse_OperationSampling_DEFAULT *PerOperationSamplingStrategies - -func (p *SamplingStrategyResponse) GetOperationSampling() *PerOperationSamplingStrategies { - if !p.IsSetOperationSampling() { - return SamplingStrategyResponse_OperationSampling_DEFAULT - } - return p.OperationSampling -} -func (p *SamplingStrategyResponse) IsSetProbabilisticSampling() bool { - return p.ProbabilisticSampling != nil -} - -func (p *SamplingStrategyResponse) IsSetRateLimitingSampling() bool { - return p.RateLimitingSampling != nil -} - -func (p *SamplingStrategyResponse) IsSetOperationSampling() bool { - return p.OperationSampling != nil -} - -func (p *SamplingStrategyResponse) Read(iprot thrift.TProtocol) error { - ctx := context.Background() - if _, err := iprot.ReadStructBegin(ctx); err != nil { - return fmt.Errorf("%T read error: %s", p, err) - } - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin(ctx) - if err != nil { - return fmt.Errorf("%T field %d read error: %s", p, fieldId, err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.ReadField1(iprot); err != nil { - return err - } - case 2: - if err := p.ReadField2(iprot); err != nil { - return err - } - case 3: - if err := p.ReadField3(iprot); err != nil { - return err - } - case 4: - if err := p.ReadField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(ctx, fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(ctx); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(ctx); err != nil { - return fmt.Errorf("%T read struct end error: %s", p, err) - } - return nil -} - -func (p *SamplingStrategyResponse) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(context.Background()); err != nil { - return fmt.Errorf("error reading field 1: %s", err) - } else { - temp := SamplingStrategyType(v) - p.StrategyType = temp - } - return nil -} - -func (p *SamplingStrategyResponse) ReadField2(iprot thrift.TProtocol) error { - p.ProbabilisticSampling = &ProbabilisticSamplingStrategy{} - if err := p.ProbabilisticSampling.Read(iprot); err != nil { - return fmt.Errorf("%T error reading struct: %s", p.ProbabilisticSampling, err) - } - return nil -} - -func (p *SamplingStrategyResponse) ReadField3(iprot thrift.TProtocol) error { - p.RateLimitingSampling = &RateLimitingSamplingStrategy{} - if err := p.RateLimitingSampling.Read(iprot); err != nil { - return fmt.Errorf("%T error reading struct: %s", p.RateLimitingSampling, err) - } - return nil -} - -func (p *SamplingStrategyResponse) ReadField4(iprot thrift.TProtocol) error { - p.OperationSampling = &PerOperationSamplingStrategies{} - if err := p.OperationSampling.Read(iprot); err != nil { - return fmt.Errorf("%T error reading struct: %s", p.OperationSampling, err) - } - return nil -} - -func (p *SamplingStrategyResponse) Write(oprot thrift.TProtocol) error { - ctx := context.Background() - if err := oprot.WriteStructBegin(ctx, "SamplingStrategyResponse"); err != nil { - return fmt.Errorf("%T write struct begin error: %s", p, err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(ctx); err != nil { - return fmt.Errorf("write field stop error: %s", err) - } - if err := oprot.WriteStructEnd(ctx); err != nil { - return fmt.Errorf("write struct stop error: %s", err) - } - return nil -} - -func (p *SamplingStrategyResponse) writeField1(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if err := oprot.WriteFieldBegin(ctx, "strategyType", thrift.I32, 1); err != nil { - return fmt.Errorf("%T write field begin error 1:strategyType: %s", p, err) - } - if err := oprot.WriteI32(ctx, int32(p.StrategyType)); err != nil { - return fmt.Errorf("%T.strategyType (1) field write error: %s", p, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 1:strategyType: %s", p, err) - } - return err -} - -func (p *SamplingStrategyResponse) writeField2(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if p.IsSetProbabilisticSampling() { - if err := oprot.WriteFieldBegin(ctx, "probabilisticSampling", thrift.STRUCT, 2); err != nil { - return fmt.Errorf("%T write field begin error 2:probabilisticSampling: %s", p, err) - } - if err := p.ProbabilisticSampling.Write(oprot); err != nil { - return fmt.Errorf("%T error writing struct: %s", p.ProbabilisticSampling, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 2:probabilisticSampling: %s", p, err) - } - } - return err -} - -func (p *SamplingStrategyResponse) writeField3(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if p.IsSetRateLimitingSampling() { - if err := oprot.WriteFieldBegin(ctx, "rateLimitingSampling", thrift.STRUCT, 3); err != nil { - return fmt.Errorf("%T write field begin error 3:rateLimitingSampling: %s", p, err) - } - if err := p.RateLimitingSampling.Write(oprot); err != nil { - return fmt.Errorf("%T error writing struct: %s", p.RateLimitingSampling, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 3:rateLimitingSampling: %s", p, err) - } - } - return err -} - -func (p *SamplingStrategyResponse) writeField4(oprot thrift.TProtocol) (err error) { - ctx := context.Background() - if p.IsSetOperationSampling() { - if err := oprot.WriteFieldBegin(ctx, "operationSampling", thrift.STRUCT, 4); err != nil { - return fmt.Errorf("%T write field begin error 4:operationSampling: %s", p, err) - } - if err := p.OperationSampling.Write(oprot); err != nil { - return fmt.Errorf("%T error writing struct: %s", p.OperationSampling, err) - } - if err := oprot.WriteFieldEnd(ctx); err != nil { - return fmt.Errorf("%T write field end error 4:operationSampling: %s", p, err) - } - } - return err -} - -func (p *SamplingStrategyResponse) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("SamplingStrategyResponse(%+v)", *p) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/grpc/manager.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/grpc/manager.go deleted file mode 100644 index 2cb700f76d82..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/grpc/manager.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package grpc // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/grpc" - -import ( - "context" - "errors" - - "github.com/jaegertracing/jaeger/model/converter/thrift/jaeger" - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - "github.com/jaegertracing/jaeger/thrift-gen/baggage" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "google.golang.org/grpc" -) - -// SamplingManager returns sampling decisions from collector over gRPC. -type SamplingManager struct { - client api_v2.SamplingManagerClient -} - -// NewConfigManager creates gRPC sampling manager. -func NewConfigManager(conn *grpc.ClientConn) *SamplingManager { - return &SamplingManager{ - client: api_v2.NewSamplingManagerClient(conn), - } -} - -// GetSamplingStrategy returns sampling strategies from collector. -func (s *SamplingManager) GetSamplingStrategy(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) { - r, err := s.client.GetSamplingStrategy(ctx, &api_v2.SamplingStrategyParameters{ServiceName: serviceName}) - if err != nil { - return nil, err - } - return jaeger.ConvertSamplingResponseFromDomain(r) -} - -// GetBaggageRestrictions returns baggage restrictions from collector. -func (s *SamplingManager) GetBaggageRestrictions(_ context.Context, _ string) ([]*baggage.BaggageRestriction, error) { - return nil, errors.New("baggage not implemented") -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/manager.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/manager.go deleted file mode 100644 index 5ff87d249ab5..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/manager.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package configmanager // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager" - -import ( - "context" - - "github.com/jaegertracing/jaeger/thrift-gen/baggage" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" -) - -// ClientConfigManager decides: -// 1) which sampling strategy a given service should be using -// 2) which baggage restrictions a given service should be using. -type ClientConfigManager interface { - GetSamplingStrategy(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) - GetBaggageRestrictions(ctx context.Context, serviceName string) ([]*baggage.BaggageRestriction, error) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/metrics.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/metrics.go deleted file mode 100644 index 33a37d12a450..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager/metrics.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package configmanager // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager" - -import ( - "context" - - "github.com/jaegertracing/jaeger/pkg/metrics" - "github.com/jaegertracing/jaeger/thrift-gen/baggage" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" -) - -// configManagerMetrics holds metrics related to ClientConfigManager -type configManagerMetrics struct { - // Number of successful sampling rate responses from collector - SamplingSuccess metrics.Counter `metric:"collector-proxy" tags:"result=ok,endpoint=sampling"` - - // Number of failed sampling rate responses from collector - SamplingFailures metrics.Counter `metric:"collector-proxy" tags:"result=err,endpoint=sampling"` - - // Number of successful baggage restriction responses from collector - BaggageSuccess metrics.Counter `metric:"collector-proxy" tags:"result=ok,endpoint=baggage"` - - // Number of failed baggage restriction responses from collector - BaggageFailures metrics.Counter `metric:"collector-proxy" tags:"result=err,endpoint=baggage"` -} - -// ManagerWithMetrics is manager with metrics integration. -type ManagerWithMetrics struct { - wrapped ClientConfigManager - metrics configManagerMetrics -} - -// WrapWithMetrics wraps ClientConfigManager and creates metrics for its invocations. -func WrapWithMetrics(manager ClientConfigManager, mFactory metrics.Factory) *ManagerWithMetrics { - m := configManagerMetrics{} - _ = metrics.Init(&m, mFactory, nil) - return &ManagerWithMetrics{wrapped: manager, metrics: m} -} - -// GetSamplingStrategy returns sampling strategy from server. -func (m *ManagerWithMetrics) GetSamplingStrategy(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) { - r, err := m.wrapped.GetSamplingStrategy(ctx, serviceName) - if err != nil { - m.metrics.SamplingFailures.Inc(1) - } else { - m.metrics.SamplingSuccess.Inc(1) - } - return r, err -} - -// GetBaggageRestrictions returns baggage restrictions from server. -func (m *ManagerWithMetrics) GetBaggageRestrictions(ctx context.Context, serviceName string) ([]*baggage.BaggageRestriction, error) { - r, err := m.wrapped.GetBaggageRestrictions(ctx, serviceName) - if err != nil { - m.metrics.BaggageFailures.Inc(1) - } else { - m.metrics.BaggageSuccess.Inc(1) - } - return r, err -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/httpserver/srv.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/httpserver/srv.go deleted file mode 100644 index f988c8579c60..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/httpserver/srv.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package httpserver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/httpserver" - -import ( - "net/http" - "time" - - "github.com/gorilla/mux" - "github.com/jaegertracing/jaeger/pkg/metrics" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" - - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/clientcfghttp" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager" -) - -// NewHTTPServer creates a new server that hosts an HTTP/JSON endpoint for clients -// to query for sampling strategies and baggage restrictions. -func NewHTTPServer(hostPort string, manager configmanager.ClientConfigManager, mFactory metrics.Factory, logger *zap.Logger) *http.Server { - handler := clientcfghttp.NewHTTPHandler(clientcfghttp.HTTPHandlerParams{ - ConfigManager: manager, - MetricsFactory: mFactory, - LegacySamplingEndpoint: true, - }) - r := mux.NewRouter() - handler.RegisterRoutes(r) - errorLog, _ := zap.NewStdLogAt(logger, zapcore.ErrorLevel) - return &http.Server{ - Addr: hostPort, - Handler: r, - ErrorLog: errorLog, - ReadHeaderTimeout: 2 * time.Second, - } -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/httpserver/srv_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/httpserver/srv_test.go deleted file mode 100644 index 272bb9b579a9..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/httpserver/srv_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package httpserver - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "go.uber.org/zap" -) - -func TestHTTPServer(t *testing.T) { - s := NewHTTPServer(":1", nil, nil, zap.NewNop()) - assert.NotNil(t, s) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/metadata/generated_status.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/metadata/generated_status.go deleted file mode 100644 index efc542c560a6..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/metadata/generated_status.go +++ /dev/null @@ -1,12 +0,0 @@ -// Code generated by mdatagen. DO NOT EDIT. - -package metadata - -import ( - "go.opentelemetry.io/collector/component" -) - -const ( - Type = "jaeger" - TracesStability = component.StabilityLevelBeta -) diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/grpc_handler.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/grpc_handler.go deleted file mode 100644 index 468f3202acdb..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/grpc_handler.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sampling // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling" - -import ( - "context" - - "github.com/jaegertracing/jaeger/model/converter/thrift/jaeger" - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore" -) - -// GRPCHandler is sampling strategy handler for gRPC. -type GRPCHandler struct { - store strategystore.StrategyStore -} - -// NewGRPCHandler creates a handler that controls sampling strategies for services. -func NewGRPCHandler(store strategystore.StrategyStore) GRPCHandler { - return GRPCHandler{ - store: store, - } -} - -// GetSamplingStrategy returns sampling decision from store. -func (s GRPCHandler) GetSamplingStrategy(ctx context.Context, param *api_v2.SamplingStrategyParameters) (*api_v2.SamplingStrategyResponse, error) { - r, err := s.store.GetSamplingStrategy(ctx, param.GetServiceName()) - if err != nil { - return nil, err - } - return jaeger.ConvertSamplingResponseToDomain(r) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/grpc_handler_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/grpc_handler_test.go deleted file mode 100644 index 350670c5f098..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/grpc_handler_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sampling - -import ( - "errors" - "testing" - - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "golang.org/x/net/context" -) - -type mockSamplingStore struct{} - -func (s mockSamplingStore) GetSamplingStrategy(_ context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) { - if serviceName == "error" { - return nil, errors.New("some error") - } else if serviceName == "nil" { - return nil, nil - } - return &sampling.SamplingStrategyResponse{StrategyType: sampling.SamplingStrategyType_PROBABILISTIC}, nil -} - -func TestNewGRPCHandler(t *testing.T) { - tests := []struct { - req *api_v2.SamplingStrategyParameters - resp *api_v2.SamplingStrategyResponse - err string - }{ - {req: &api_v2.SamplingStrategyParameters{ServiceName: "error"}, err: "some error"}, - {req: &api_v2.SamplingStrategyParameters{ServiceName: "nil"}, resp: nil}, - {req: &api_v2.SamplingStrategyParameters{ServiceName: "foo"}, resp: &api_v2.SamplingStrategyResponse{StrategyType: api_v2.SamplingStrategyType_PROBABILISTIC}}, - } - h := NewGRPCHandler(mockSamplingStore{}) - for _, test := range tests { - resp, err := h.GetSamplingStrategy(context.Background(), test.req) - if test.err != "" { - assert.EqualError(t, err, test.err) - require.Nil(t, resp) - } else { - require.NoError(t, err) - assert.Equal(t, test.resp, resp) - } - } -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/model/empty_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/model/empty_test.go deleted file mode 100644 index 7a825c8ad6d4..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/model/empty_test.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -// import "testing" - -// func TestNothing(t *testing.T) { -// // just get the code coverage -// } diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/model/sampling.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/model/sampling.go deleted file mode 100644 index dac7fdef1ee1..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/model/sampling.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/model" - -// Throughput keeps track of the queries an operation received. -type Throughput struct { - Service string - Operation string - Count int64 - Probabilities map[string]struct{} -} - -// ServiceOperationProbabilities contains the sampling probabilities for all operations in a service. -// ie [service][operation] = probability -type ServiceOperationProbabilities map[string]map[string]float64 - -// ServiceOperationQPS contains the qps for all operations in a service. -// ie [service][operation] = qps -type ServiceOperationQPS map[string]map[string]float64 - -// ProbabilityAndQPS contains the sampling probability and measured qps for an operation. -type ProbabilityAndQPS struct { - Probability float64 - QPS float64 -} - -// ServiceOperationData contains the sampling probabilities and measured qps for all operations in a service. -// ie [service][operation] = ProbabilityAndQPS -type ServiceOperationData map[string]map[string]*ProbabilityAndQPS diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/empty_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/empty_test.go deleted file mode 100644 index 67dcb38f4611..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/empty_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2019 The Jaeger Authors. -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Copyright (c) 2019 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strategystore diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/factory.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/factory.go deleted file mode 100644 index bf8db2d1efc6..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/factory.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strategystore // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore" - -import ( - "github.com/jaegertracing/jaeger/pkg/metrics" - "github.com/jaegertracing/jaeger/storage" - "go.uber.org/zap" -) - -// Factory defines an interface for a factory that can create implementations of different strategy storage components. -// Implementations are also encouraged to implement plugin.Configurable interface. -// -// # See also -// -// plugin.Configurable -type Factory interface { - // Initialize performs internal initialization of the factory. - Initialize(metricsFactory metrics.Factory, ssFactory storage.SamplingStoreFactory, logger *zap.Logger) error - - // CreateStrategyStore initializes the StrategyStore and returns it. - CreateStrategyStore() (StrategyStore, Aggregator, error) -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/interface.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/interface.go deleted file mode 100644 index dc0404c7c69d..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore/interface.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Copyright (c) 2018 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strategystore // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/sampling/strategystore" - -import ( - "context" - "io" - - "github.com/jaegertracing/jaeger/thrift-gen/sampling" -) - -// StrategyStore keeps track of service specific sampling strategies. -type StrategyStore interface { - // GetSamplingStrategy retrieves the sampling strategy for the specified service. - GetSamplingStrategy(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) -} - -// Aggregator defines an interface used to aggregate operation throughput. -type Aggregator interface { - // Close() from io.Closer stops the aggregator from aggregating throughput. - io.Closer - - // RecordThroughput records throughput for an operation for aggregation. - RecordThroughput(service, operation, samplerType string, probability float64) - - // Start starts aggregating operation throughput. - Start() -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/jaeger_agent_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/jaeger_agent_test.go deleted file mode 100644 index ac99069be3b4..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/jaeger_agent_test.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerreceiverdeprecated - -import ( - "context" - "fmt" - "net" - "net/http" - "testing" - "time" - - "github.com/apache/thrift/lib/go/thrift" - "github.com/jaegertracing/jaeger/cmd/agent/app/servers/thriftudp" - "github.com/jaegertracing/jaeger/model" - jaegerconvert "github.com/jaegertracing/jaeger/model/converter/thrift/jaeger" - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - "github.com/jaegertracing/jaeger/thrift-gen/agent" - jaegerthrift "github.com/jaegertracing/jaeger/thrift-gen/jaeger" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/component/componenttest" - "go.opentelemetry.io/collector/consumer/consumertest" - "go.opentelemetry.io/collector/pdata/ptrace" - "go.opentelemetry.io/collector/receiver/receivertest" - conventions "go.opentelemetry.io/collector/semconv/v1.6.1" - "google.golang.org/grpc" - - "github.com/open-telemetry/opentelemetry-collector-contrib/internal/common/testutil" - "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/translator/jaeger" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/metadata" -) - -var jaegerAgent = component.NewIDWithName(metadata.Type, "agent_test") - -func TestJaegerAgentUDP_ThriftCompact(t *testing.T) { - addr := testutil.GetAvailableLocalAddress(t) - testJaegerAgent(t, addr, &configuration{ - AgentCompactThrift: ProtocolUDP{ - Endpoint: addr, - ServerConfigUDP: defaultServerConfigUDP(), - }, - }) -} - -func TestJaegerAgentUDP_ThriftCompact_InvalidPort(t *testing.T) { - config := &configuration{ - AgentCompactThrift: ProtocolUDP{ - Endpoint: "0.0.0.0:999999", - ServerConfigUDP: defaultServerConfigUDP(), - }, - } - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerAgent, config, nil, set) - require.NoError(t, err) - - assert.Error(t, jr.Start(context.Background(), componenttest.NewNopHost()), "should not have been able to startTraceReception") - - require.NoError(t, jr.Shutdown(context.Background())) -} - -func TestJaegerAgentUDP_ThriftBinary(t *testing.T) { - addr := testutil.GetAvailableLocalAddress(t) - testJaegerAgent(t, addr, &configuration{ - AgentBinaryThrift: ProtocolUDP{ - Endpoint: addr, - ServerConfigUDP: defaultServerConfigUDP(), - }, - }) -} - -func TestJaegerAgentUDP_ThriftBinary_PortInUse(t *testing.T) { - // This test confirms that the thrift binary port is opened correctly. This is all we can test at the moment. See above. - addr := testutil.GetAvailableLocalAddress(t) - - config := &configuration{ - AgentBinaryThrift: ProtocolUDP{ - Endpoint: addr, - ServerConfigUDP: defaultServerConfigUDP(), - }, - } - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerAgent, config, nil, set) - require.NoError(t, err) - - assert.NoError(t, jr.startAgent(componenttest.NewNopHost()), "Start failed") - t.Cleanup(func() { require.NoError(t, jr.Shutdown(context.Background())) }) - - l, err := net.Listen("udp", addr) - assert.Error(t, err, "should not have been able to listen to the port") - - if l != nil { - l.Close() - } -} - -func TestJaegerAgentUDP_ThriftBinary_InvalidPort(t *testing.T) { - config := &configuration{ - AgentBinaryThrift: ProtocolUDP{ - Endpoint: "0.0.0.0:999999", - ServerConfigUDP: defaultServerConfigUDP(), - }, - } - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerAgent, config, nil, set) - require.NoError(t, err) - - assert.Error(t, jr.Start(context.Background(), componenttest.NewNopHost()), "should not have been able to startTraceReception") - - require.NoError(t, jr.Shutdown(context.Background())) -} - -func initializeGRPCTestServer(t *testing.T, beforeServe func(server *grpc.Server), opts ...grpc.ServerOption) (*grpc.Server, net.Addr) { - server := grpc.NewServer(opts...) - lis, err := net.Listen("tcp", "localhost:0") - require.NoError(t, err) - beforeServe(server) - go func() { - err := server.Serve(lis) - require.NoError(t, err) - }() - return server, lis.Addr() -} - -type mockSamplingHandler struct { -} - -func (*mockSamplingHandler) GetSamplingStrategy(context.Context, *api_v2.SamplingStrategyParameters) (*api_v2.SamplingStrategyResponse, error) { - return &api_v2.SamplingStrategyResponse{StrategyType: api_v2.SamplingStrategyType_PROBABILISTIC}, nil -} - -func TestJaegerHTTP(t *testing.T) { - s, _ := initializeGRPCTestServer(t, func(s *grpc.Server) { - api_v2.RegisterSamplingManagerServer(s, &mockSamplingHandler{}) - }) - defer s.GracefulStop() - - endpoint := testutil.GetAvailableLocalAddress(t) - config := &configuration{ - AgentHTTPEndpoint: endpoint, - } - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerAgent, config, nil, set) - require.NoError(t, err) - t.Cleanup(func() { require.NoError(t, jr.Shutdown(context.Background())) }) - - assert.NoError(t, jr.Start(context.Background(), componenttest.NewNopHost()), "Start failed") - - // allow http server to start - assert.Eventually(t, func() bool { - var conn net.Conn - conn, err = net.Dial("tcp", endpoint) - if err == nil && conn != nil { - conn.Close() - return true - } - return false - }, 10*time.Second, 5*time.Millisecond, "failed to wait for the port to be open") - - resp, err := http.Get(fmt.Sprintf("http://%s/sampling?service=test", endpoint)) - assert.NoError(t, err, "should not have failed to make request") - if resp != nil { - assert.Equal(t, 500, resp.StatusCode, "should have returned 200") - return - } - t.Fail() -} - -func testJaegerAgent(t *testing.T, agentEndpoint string, receiverConfig *configuration) { - // 1. Create the Jaeger receiver aka "server" - sink := new(consumertest.TracesSink) - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerAgent, receiverConfig, sink, set) - require.NoError(t, err) - t.Cleanup(func() { require.NoError(t, jr.Shutdown(context.Background())) }) - - for i := 0; i < 3; i++ { - err = jr.Start(context.Background(), componenttest.NewNopHost()) - if err == nil { - break - } - - time.Sleep(50 * time.Millisecond) - } - require.NoError(t, err, "Start failed") - - // 2. Then send spans to the Jaeger receiver. - jexp, err := newClientUDP(agentEndpoint, jr.config.AgentBinaryThrift.Endpoint != "") - require.NoError(t, err, "Failed to create the Jaeger OpenTelemetry exporter for the live application") - - // 3. Now finally send some spans - td := generateTraceData() - batches, err := jaeger.ProtoFromTraces(td) - require.NoError(t, err) - for _, batch := range batches { - require.NoError(t, jexp.EmitBatch(context.Background(), modelToThrift(batch))) - } - - require.Eventually(t, func() bool { - return sink.SpanCount() > 0 - }, 10*time.Second, 5*time.Millisecond) - - gotTraces := sink.AllTraces() - require.Equal(t, 1, len(gotTraces)) - assert.EqualValues(t, td, gotTraces[0]) -} - -func newClientUDP(hostPort string, binary bool) (*agent.AgentClient, error) { - clientTransport, err := thriftudp.NewTUDPClientTransport(hostPort, "") - if err != nil { - return nil, err - } - var protocolFactory thrift.TProtocolFactory - if binary { - protocolFactory = thrift.NewTBinaryProtocolFactoryConf(nil) - } else { - protocolFactory = thrift.NewTCompactProtocolFactoryConf(nil) - } - return agent.NewAgentClientFactory(clientTransport, protocolFactory), nil -} - -// Cannot use the testdata because timestamps are nanoseconds. -func generateTraceData() ptrace.Traces { - td := ptrace.NewTraces() - rs := td.ResourceSpans().AppendEmpty() - rs.Resource().Attributes().PutStr(conventions.AttributeServiceName, "test") - span := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty() - span.SetSpanID([8]byte{0, 1, 2, 3, 4, 5, 6, 7}) - span.SetTraceID([16]byte{0, 1, 2, 3, 4, 5, 6, 7, 7, 6, 5, 4, 3, 2, 1, 0}) - span.SetStartTimestamp(1581452772000000000) - span.SetEndTimestamp(1581452773000000000) - return td -} - -func modelToThrift(batch *model.Batch) *jaegerthrift.Batch { - return &jaegerthrift.Batch{ - Process: processModelToThrift(batch.Process), - Spans: jaegerconvert.FromDomain(batch.Spans), - } -} - -func processModelToThrift(process *model.Process) *jaegerthrift.Process { - if process == nil { - return nil - } - return &jaegerthrift.Process{ - ServiceName: process.ServiceName, - } -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/metadata.yaml b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/metadata.yaml deleted file mode 100644 index 7b9b51627872..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/metadata.yaml +++ /dev/null @@ -1,17 +0,0 @@ -type: jaeger - -status: - class: receiver - stability: - beta: [traces] - distributions: - - core - - contrib - - aws - - grafana - - observiq - - redhat - - splunk - - sumo - codeowners: - active: [jpkrohling] diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/ca.crt b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/ca.crt deleted file mode 100644 index 5b3ac9ca4d1f..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/ca.crt +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDNjCCAh4CCQDm8/gmxPra7zANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJB -VTESMBAGA1UECAwJQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoM -CU15T3JnTmFtZTEVMBMGA1UEAwwMTXlDb21tb25OYW1lMB4XDTIyMDgwMzA0NDQ0 -OFoXDTMyMDczMTA0NDQ0OFowXTELMAkGA1UEBhMCQVUxEjAQBgNVBAgMCUF1c3Ry -YWxpYTEPMA0GA1UEBwwGU3lkbmV5MRIwEAYDVQQKDAlNeU9yZ05hbWUxFTATBgNV -BAMMDE15Q29tbW9uTmFtZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AKDQxV8fMvsl4YhMiY3EiT0ylKQ0VkUwvWE4yfem6LFYaZa0fOe1zc3V9DXmcH9A -PXXa+XwlK7xfXSddGoD7XfxLKdU8FiU+bXs/pEeRPQ+5oraInTcAQ265HXkPmiiQ -XN6qRlwAoC2NgV9OKvUHEqpw/Z/edCLfbBipT+PfBeAtK9Dv0v3hXAqDQlotERxM -uRa9VYETbw/hjj+DIVGZWCnpiQXlepxoZJJiGw1p2Ca0aN5mWDNvMz9bFWo+Szz6 -FqR1S6Tqw5M3jS0NMkI1e0mZSxGBqYXy/x7ep9j5UjmAtHl8oKpDS23HXqnxnjLi -mnM/dipizaJKwidw9SA/fRMCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAZsJE1yx/ -m9zy29eB6l2278bWvRP/2zbpBVziOmwLq5vYdtTn9S1o8TJ8MFAa3B9D0oLSb+n5 -biJqK4rwKRWezoalHo6/vVxQDY1FgVT0RmYKdL9xdc4YBPdBfHnvlEqcXPYBpvoH -0w0ZIu1UxkDij8RNxc5aePflAyVZxg3RNh0jN0qiwB2d4VqOzr9XAh4b1DFRaI9r -X0MG+4ptxdNM7StKJGsJvnZ686Ep/6/2Z4B2guBGkcoSuSRUwr1ft8DuJBM5QLwa -wUPFTcCoyfHzNpYaIp2pTSScFEXmLlV/E7TiST0EEiqNsZAaDPttuAdDRSUe/1CX -hxDsgqzefB2kWQ== ------END CERTIFICATE----- diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/client.crt b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/client.crt deleted file mode 100644 index af6038866c2e..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/client.crt +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDVTCCAj2gAwIBAgIJAOPSCYfRo9dVMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV -BAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG -A1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz -MDQ0NDQ4WhcNMzIwNzMxMDQ0NDQ4WjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ -QXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV -MBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB -CgKCAQEAzEzroaSqc9ytdbHvtDtLlLL7DFflK8Xuya1DZRXaqWEZN7wluCCnKWbO -qqSKSDsDgiIj3in5yhQfw+ekQ9+WQmJJVbxclBy8RPFZABHuYkP8JwhqezW0ozK8 -soUOxTjj5khuznUyqihx3fBVOS3eyRW89M7k8RRj7IWctlFzPHhFCdCWMzM9rkBU -lI+a2igqkGMA/1w5/Q9+d0FvPOlvi47JSzZx47TU3TI7vppr+UQmA6L+IZvdA04A -KjBYH1YNo2Ek5z1j+B9dnXlhYhe+OeB18dUAVwPqh9MGOn5wDYYdKMC78v0OWnC3 -EHTAbixEB8Mwgh74xYpQPnMB09csKwIDAQABoxgwFjAUBgNVHREEDTALgglsb2Nh -bGhvc3QwDQYJKoZIhvcNAQELBQADggEBACvgrBWXuUKB9EUOHdJcIvaGlalZXgbA -qX62ipSx9L791NSwpf9S9iZjDmzNpxizOzSSznHoxObsgCa5R1yMiqvcjmVBUJbw -JfYH6Gt4glk2alNL8PjY/6SnG08t+xkvXHtdKO6asC0L1GmM9BPnd+djFyMqsPXx -CaHLERK2HgbDXvumlPWmR9j8zm/jen3Pw/w3KKc+5XLrc5V5zcG0+WqV307MaIOS -vIm4BhUABC4co01vwWvA+OrSy+sAyfMPeuPHe2kVUPwKMIciVGyl58BrVtvqcHZW -sHGa/cOSp4B/6DXjbcvO8G4CA0VGKl0X7QENSi4x09HsgnQ75DMWvk8= ------END CERTIFICATE----- diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/client.key b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/client.key deleted file mode 100644 index 68761c8f7309..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/client.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAzEzroaSqc9ytdbHvtDtLlLL7DFflK8Xuya1DZRXaqWEZN7wl -uCCnKWbOqqSKSDsDgiIj3in5yhQfw+ekQ9+WQmJJVbxclBy8RPFZABHuYkP8Jwhq -ezW0ozK8soUOxTjj5khuznUyqihx3fBVOS3eyRW89M7k8RRj7IWctlFzPHhFCdCW -MzM9rkBUlI+a2igqkGMA/1w5/Q9+d0FvPOlvi47JSzZx47TU3TI7vppr+UQmA6L+ -IZvdA04AKjBYH1YNo2Ek5z1j+B9dnXlhYhe+OeB18dUAVwPqh9MGOn5wDYYdKMC7 -8v0OWnC3EHTAbixEB8Mwgh74xYpQPnMB09csKwIDAQABAoIBAC8KXw7/DUhUPZRl -/h1vsb1xYKC89EWZ85t4S5ZQ6+IoO1g7+CtnSVYdF+TusfBjtjEWj0+uNpey/oVr -JsWCC+UJIH2fO2nXG/p739RGTK9PnBWYuHvaJ9eT7SLlxDrhGIiDkQ/0qE/JtD44 -AkeCKlP+r11m7gwcd82UDjtkkbYQSZkEh4m4AAF3TNxan2B+9KrgAX9KT1fNrs8B -XPzo/y3YXHEhIpvFyxm96+R/gaVTvfk2CQD/rnfoB5y3W3zfvFwWvnSQRoZqamQQ -Zza8b7HQ0P0mLJxlt0ui1jkEe3ljqKA3CgHhWh0NYPtgfKA5+61xo4XA83k7UvR+ -Ku5My7ECgYEA+E5fkfX8cr0BqIAMNuGuagTelADfAPWlATtzcJqOXZMFLkWJ9NxI -IioQ3I88YjBmGqP/+ktGsIz7N+GB0liXU2iU3c1vOnXuoQJNsXhcRTb5YjTk3e3L -qGPj+fS3ZlgjnO3IBLubjH47klJr2oGw1x4MfB6zWN9p1OwJHcQQPJ8CgYEA0qF7 -qTw8558/lS70CrdkhrtHaeseWCyv94nodcHGY3SxvVVzJsxP6So02ovnatfxS2IC -/6V2VQPnXnHBFCREw1NpiG1lVaxiDpKBTd7hd3rv/KqYojb22NVZqFoW5nUrot/x -li/krgelc0+RiIDHXKLp9MNu/yurWmEWD2p52PUCgYBTH1Fo+FLZSiJq+Oqd2LDd -duHX4+7DUHg7UF6VvHeaJaRfWBIVsURIg5J/c0fAivkzQ+FmNZrlcVyL2WbvNo75 -8hGbqrDofiAzMCU4GtWwqfWUBab0EC3UIhRoUZ6vmSPa3dLOmss4ne1tT0Ahtrav -XLTLPC/HuYqhJ57pov/YewKBgFI6ap1x/9Do0Zi7ANjiKaOTn1iRSoJfx76anx7B -rGKNXwosPs0pvBSpvoKHVavXa8LjG4qUHPMpl/y96gOj+RhMCwoQsxvUNV+9AC/X -UCwl2WTJcNb7IDkcaWkY6pHDsmpehOD+B4eNQqEWshkZNTtL+ovsc/u4H6gj+MnB -5pm1AoGBALUwryV4ue/e1KU73Q852yfiH6RkPfO33IiBsLzUT5XJ+y7SKUP2BwGB -vnkB2wf/X7JlGxGrGMJLpgNQTFAkJ4DFsObE9nNh4bSfmQOz3+1OtCLUPn1/+Yjh -Z9GL7LODsu+UDKnDvxc6e91fGQz9nSxGhSgWntC/e2sGxU4T5H+5 ------END RSA PRIVATE KEY----- diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/config.yaml b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/config.yaml deleted file mode 100644 index e380fcdd7a99..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/config.yaml +++ /dev/null @@ -1,67 +0,0 @@ -# The following demonstrates specifying different endpoints. -# The Jaeger receiver connects to ports on all available network interfaces. -# Ex: `endpoint: "9876"` is incorrect. -# Ex: `endpoint: "1.2.3.4:9876"` and ":9876" is correct. -jaeger/customname: - protocols: - grpc: - endpoint: "localhost:9876" - thrift_http: - endpoint: ":3456" - thrift_compact: - endpoint: "0.0.0.0:456" - queue_size: 100_000 - max_packet_size: 131_072 - workers: 100 - socket_buffer_size: 65_536 - thrift_binary: - endpoint: "0.0.0.0:789" - queue_size: 1_000 - max_packet_size: 65_536 - workers: 5 - socket_buffer_size: 0 - remote_sampling: - host_endpoint: "0.0.0.0:5778" - endpoint: "jaeger-collector:1234" - strategy_file: "/etc/strategies.json" - strategy_file_reload_interval: 10s -# The following demonstrates how to enable protocols with defaults. -jaeger/defaults: - protocols: - grpc: - thrift_http: - thrift_compact: - thrift_binary: -# The following demonstrates only enabling certain protocols with defaults/overrides. -jaeger/mixed: - protocols: - grpc: - endpoint: "localhost:9876" - thrift_compact: -# The following demonstrates specifying different endpoints. -# The Jaeger receiver connects to ports on all available network interfaces. -# Ex: `endpoint: "9876"` is incorrect. -# Ex: `endpoint: "1.2.3.4:9876"` and ":9876" is correct. -jaeger/tls: - protocols: - grpc: - tls: - cert_file: /test.crt - key_file: /test.key - endpoint: "localhost:9876" - thrift_http: - endpoint: ":3456" -jaeger/empty: -# The following demonstrates how to enable protocols with defaults -jaeger/typo_default_proto_config: - protocols: - grpc: - endpoint: "127.0.0.1:123" - thrift_htttp: -jaeger/no_proto_config: - protocols: -# The following demonstrates how to enable protocols with defaults -jaeger/bad_proto_config: - protocols: - thrift_htttp: - endpoint: "127.0.0.1:123" diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/server.crt b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/server.crt deleted file mode 100644 index f92d2acb9105..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/server.crt +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDVTCCAj2gAwIBAgIJAOPSCYfRo9dUMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV -BAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG -A1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz -MDQ0NDQ4WhcNMzIwNzMxMDQ0NDQ4WjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ -QXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV -MBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB -CgKCAQEAyEPiDsD4JXTB7AeyVsFkhKLq1jQCgtWTEQoFYW6lSnbD+yGhUcN1ntpU -R4QSFm+NmIPHzoD3wgwZ5Fcp1Tir3HgnvKJeUhVNnPE1EZcuiO69n0W8SGqLExVK -noEH3gI9Zygen0aHhN6b1za+m67j9FYIhbxN6jZJ83XP7t5N56trWGQ3sZA8Tsqs -oFHTrNVjE1IugPaQs4qst/qFIRbC6z47LarUmXG2jrTAMJQBqBeaxaEWy5Ty9gNy -nz4fqli9/faUJkyocyhOn971EDK3PSR5BV/MGWHfvcgKrsNyJh6/njQjQIGHZAZo -ooIKEzPvoCGHfJrhYd8UKw+RkHgtWwIDAQABoxgwFjAUBgNVHREEDTALgglsb2Nh -bGhvc3QwDQYJKoZIhvcNAQELBQADggEBAGKl+WK1Mf6g5D+bKvb5fq1GCJyLLL2I -Skmr+HRfnCzFrrdB6uL5IHiZ5xHJ1xZkoymGF0WabcsmYDe0J19nFWUH6Jv8CeFC -2Qz/iy+XZxWQxD17yRTpek48HxGVio4bwzGGsQN13+RVPbocqpiu3oKeO1NAei8J -intveT0LiwsKQ6VhJ39lu0ayAWUc+5FaDwtCMjU+1uSVRivMWkAXFTol6eKG8iAJ -kqtMaeagEkWWLb+UMV22XpaYNiTfQ2OKqUTcZUPzokNn/Mr45nRsc1ZFNie8UuiK -6HXiFa7p6QFY74Tqot9fS1tpp63S/k70KM5/wZs7E452Bj67+TRTcOY= ------END CERTIFICATE----- diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/server.key b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/server.key deleted file mode 100644 index 3090f4e00bb6..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/server.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEogIBAAKCAQEAyEPiDsD4JXTB7AeyVsFkhKLq1jQCgtWTEQoFYW6lSnbD+yGh -UcN1ntpUR4QSFm+NmIPHzoD3wgwZ5Fcp1Tir3HgnvKJeUhVNnPE1EZcuiO69n0W8 -SGqLExVKnoEH3gI9Zygen0aHhN6b1za+m67j9FYIhbxN6jZJ83XP7t5N56trWGQ3 -sZA8TsqsoFHTrNVjE1IugPaQs4qst/qFIRbC6z47LarUmXG2jrTAMJQBqBeaxaEW -y5Ty9gNynz4fqli9/faUJkyocyhOn971EDK3PSR5BV/MGWHfvcgKrsNyJh6/njQj -QIGHZAZoooIKEzPvoCGHfJrhYd8UKw+RkHgtWwIDAQABAoIBAGjbumK1QXkDQIKg -qQ1p54LXdxS/WM0+nOmgEJ8qexuZQhadTkVsjYqmkNh9W6cps782yQjkWFXfVjNM -PFgrezlOJKhNcAuUofXaCkpymWgTcXAS6HoWZ0mPrWl+8Cqbi6EWzaniGRVGJd0z -CeykTzFhVscHiNhooqH6fux4s9vn5FDgflVpka0XuOuurF6+9inCAVJHN1C3BNLD -tyZEFW31nR7ImOp37pEI6nE/Q2ecBT97j4kFN+hzYsH4qUYq2iAA/bR4ZLwZ17xc -FbFeGEmVhePVpNPAQ82v36AlWQsK30y7DwPsWlYRkcpsG3QP6+TGnaBM0AFCypY4 -w12DzaECgYEA+pLx3KmVH0zaPiTXFI/RRedipYkmIlyMI+/GfuSInXSWlCSvdOV/ -PTrQoVNvsmObz73kAh2I+KGS9+7arX4O4Qm74Sb3SbCHUGa/wNyv8Nqvo9LraRR0 -RY2fgAS3UL2ZHESJX5aVXa5S3it1tu10K8c9ofpekq/uJ5IaJ81FvbECgYEAzJoN -NRTUCR721wFo4t4OYUdbxLU8CKvj0osouQAQwYhT+EKCp1I9pqvvE4Amxi2Xmysv -Eu4JGy4Ti3jWAwu1XwhkwzSGTuN2/ECJ7EunaFXGeYef9RqR2+JCqGadLfnZZGsN -5/NlbZZ8+Em//9wGDmZz9ZJFnZZPSHxgKmKdYssCgYAqPatYL55b8HC6GSvI45W7 -2w3eKgirsj5NsJYdvhjpskXQI38Qjb+tasTQ7WffAru5gaF2WdRFVbeY5EMpDB8m -AKYThqYZXhDxlOCueoWObM8/JsdYp4ISV5WT1zev/MZa5ZLi8leruz9tBJaLh+wV -lTjmnXZj9BSJxy9xlkEzgQKBgFU8ICBq6uJZ2e88ERvh8g+okJxj+/yIz0IY4wAe -/NwDFSgpXRCjfDeBDPoMuxp4R95GoTe7nmOKUG4cCtv99rL+ZivEJ+eZbyorIMol -wjn+8c4TKBoN1ZHKsoZBKV3L5jqlNofYp/p9ZNZyst++I2/AUrKNGx9JTQIfflhp -+LL9AoGAKyMMGec4MyP3KA4AEEOTShgJ0P6zSj3i/rsC8jiH6yIxSO+Ii+9BdzlF -WblemYFFa5AwWeogycdeWwAX4YVrYAsZmmVb/zt/KvJIi9OwwtmAwGaLLl1Zqtca -uGOifl+ukutwvmL5pzKyCP3SxwkG0F9mVWQVhg13L+/YDZ8v0tg= ------END RSA PRIVATE KEY----- diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/strategies.json b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/strategies.json deleted file mode 100644 index 4e8eff73f3f1..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/testdata/strategies.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "service_strategies": [ - { - "service": "foo", - "type": "probabilistic", - "param": 0.8, - "operation_strategies": [ - { - "operation": "op1", - "type": "probabilistic", - "param": 0.2 - }, - { - "operation": "op2", - "type": "probabilistic", - "param": 0.4 - } - ] - }, - { - "service": "bar", - "type": "ratelimiting", - "param": 5 - } - ], - "default_strategy": { - "type": "probabilistic", - "param": 0.5 - } - } \ No newline at end of file diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/trace_receiver.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/trace_receiver.go deleted file mode 100644 index 7679e2e054db..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/trace_receiver.go +++ /dev/null @@ -1,424 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerreceiverdeprecated // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated" - -import ( - "context" - "errors" - "fmt" - "html" - "io" - "mime" - "net/http" - "sync" - - apacheThrift "github.com/apache/thrift/lib/go/thrift" - "github.com/gorilla/mux" - "github.com/jaegertracing/jaeger/cmd/agent/app/processors" - "github.com/jaegertracing/jaeger/cmd/agent/app/servers" - "github.com/jaegertracing/jaeger/cmd/agent/app/servers/thriftudp" - "github.com/jaegertracing/jaeger/model" - "github.com/jaegertracing/jaeger/pkg/metrics" - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - "github.com/jaegertracing/jaeger/thrift-gen/agent" - "github.com/jaegertracing/jaeger/thrift-gen/baggage" - "github.com/jaegertracing/jaeger/thrift-gen/jaeger" - "github.com/jaegertracing/jaeger/thrift-gen/sampling" - "github.com/jaegertracing/jaeger/thrift-gen/zipkincore" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/consumer" - "go.opentelemetry.io/collector/receiver" - "go.opentelemetry.io/collector/receiver/receiverhelper" - "go.uber.org/multierr" - "google.golang.org/grpc" - - jaegertranslator "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/translator/jaeger" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/configmanager" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/internal/httpserver" -) - -// configuration defines the behavior and the ports that -// the Jaeger receiver will use. -type configuration struct { - CollectorHTTPSettings confighttp.HTTPServerSettings - CollectorGRPCServerSettings configgrpc.GRPCServerSettings - - AgentCompactThrift ProtocolUDP - AgentBinaryThrift ProtocolUDP - AgentHTTPEndpoint string -} - -// Receiver type is used to receive spans that were originally intended to be sent to Jaeger. -// This receiver is basically a Jaeger collector. -type jReceiver struct { - nextConsumer consumer.Traces - id component.ID - - config *configuration - - grpc *grpc.Server - collectorServer *http.Server - - agentProcessors []processors.Processor - agentServer *http.Server - - goroutines sync.WaitGroup - - settings receiver.CreateSettings - - grpcObsrecv *receiverhelper.ObsReport - httpObsrecv *receiverhelper.ObsReport -} - -const ( - agentTransportBinary = "udp_thrift_binary" - agentTransportCompact = "udp_thrift_compact" - collectorHTTPTransport = "collector_http" - grpcTransport = "grpc" - - thriftFormat = "thrift" - protobufFormat = "protobuf" -) - -var ( - acceptedThriftFormats = map[string]struct{}{ - "application/x-thrift": {}, - "application/vnd.apache.thrift.binary": {}, - } -) - -// newJaegerReceiver creates a TracesReceiver that receives traffic as a Jaeger collector, and -// also as a Jaeger agent. -func newJaegerReceiver( - id component.ID, - config *configuration, - nextConsumer consumer.Traces, - set receiver.CreateSettings, -) (*jReceiver, error) { - grpcObsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{ - ReceiverID: id, - Transport: grpcTransport, - ReceiverCreateSettings: set, - }) - if err != nil { - return nil, err - } - httpObsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{ - ReceiverID: id, - Transport: collectorHTTPTransport, - ReceiverCreateSettings: set, - }) - if err != nil { - return nil, err - } - - return &jReceiver{ - config: config, - nextConsumer: nextConsumer, - id: id, - settings: set, - grpcObsrecv: grpcObsrecv, - httpObsrecv: httpObsrecv, - }, nil -} - -func (jr *jReceiver) Start(_ context.Context, host component.Host) error { - if err := jr.startAgent(host); err != nil { - return err - } - - return jr.startCollector(host) -} - -func (jr *jReceiver) Shutdown(ctx context.Context) error { - var errs error - - if jr.agentServer != nil { - if aerr := jr.agentServer.Shutdown(ctx); aerr != nil { - errs = multierr.Append(errs, aerr) - } - } - for _, processor := range jr.agentProcessors { - processor.Stop() - } - - if jr.collectorServer != nil { - if cerr := jr.collectorServer.Shutdown(ctx); cerr != nil { - errs = multierr.Append(errs, cerr) - } - } - if jr.grpc != nil { - jr.grpc.GracefulStop() - } - - jr.goroutines.Wait() - return errs -} - -func consumeTraces(ctx context.Context, batch *jaeger.Batch, consumer consumer.Traces) (int, error) { - if batch == nil { - return 0, nil - } - td, err := jaegertranslator.ThriftToTraces(batch) - if err != nil { - return 0, err - } - return len(batch.Spans), consumer.ConsumeTraces(ctx, td) -} - -var _ agent.Agent = (*agentHandler)(nil) -var _ api_v2.CollectorServiceServer = (*jReceiver)(nil) -var _ configmanager.ClientConfigManager = (*notImplementedConfigManager)(nil) - -var errNotImplemented = fmt.Errorf("not implemented") - -type notImplementedConfigManager struct{} - -func (notImplementedConfigManager) GetSamplingStrategy(_ context.Context, _ string) (*sampling.SamplingStrategyResponse, error) { - return nil, errNotImplemented -} - -func (notImplementedConfigManager) GetBaggageRestrictions(_ context.Context, _ string) ([]*baggage.BaggageRestriction, error) { - return nil, errNotImplemented -} - -type agentHandler struct { - nextConsumer consumer.Traces - obsrecv *receiverhelper.ObsReport -} - -// EmitZipkinBatch is unsupported agent's -func (h *agentHandler) EmitZipkinBatch(context.Context, []*zipkincore.Span) (err error) { - panic("unsupported receiver") -} - -// EmitBatch implements thrift-gen/agent/Agent and it forwards -// Jaeger spans received by the Jaeger agent processor. -func (h *agentHandler) EmitBatch(ctx context.Context, batch *jaeger.Batch) error { - ctx = h.obsrecv.StartTracesOp(ctx) - numSpans, err := consumeTraces(ctx, batch, h.nextConsumer) - h.obsrecv.EndTracesOp(ctx, thriftFormat, numSpans, err) - return err -} - -func (jr *jReceiver) PostSpans(ctx context.Context, r *api_v2.PostSpansRequest) (*api_v2.PostSpansResponse, error) { - ctx = jr.grpcObsrecv.StartTracesOp(ctx) - - batch := r.GetBatch() - td, err := jaegertranslator.ProtoToTraces([]*model.Batch{&batch}) - if err != nil { - jr.grpcObsrecv.EndTracesOp(ctx, protobufFormat, len(batch.Spans), err) - return nil, err - } - - err = jr.nextConsumer.ConsumeTraces(ctx, td) - jr.grpcObsrecv.EndTracesOp(ctx, protobufFormat, len(batch.Spans), err) - if err != nil { - return nil, err - } - - return &api_v2.PostSpansResponse{}, nil -} - -func (jr *jReceiver) startAgent(host component.Host) error { - if jr.config == nil { - return nil - } - - if jr.config.AgentBinaryThrift.Endpoint != "" { - obsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{ - ReceiverID: jr.id, - Transport: agentTransportBinary, - ReceiverCreateSettings: jr.settings, - }) - if err != nil { - return err - } - - h := &agentHandler{ - nextConsumer: jr.nextConsumer, - obsrecv: obsrecv, - } - processor, err := jr.buildProcessor(jr.config.AgentBinaryThrift.Endpoint, jr.config.AgentBinaryThrift.ServerConfigUDP, apacheThrift.NewTBinaryProtocolFactoryConf(nil), h) - if err != nil { - return err - } - jr.agentProcessors = append(jr.agentProcessors, processor) - } - - if jr.config.AgentCompactThrift.Endpoint != "" { - obsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{ - ReceiverID: jr.id, - Transport: agentTransportCompact, - ReceiverCreateSettings: jr.settings, - }) - if err != nil { - return err - } - h := &agentHandler{ - nextConsumer: jr.nextConsumer, - obsrecv: obsrecv, - } - processor, err := jr.buildProcessor(jr.config.AgentCompactThrift.Endpoint, jr.config.AgentCompactThrift.ServerConfigUDP, apacheThrift.NewTCompactProtocolFactoryConf(nil), h) - if err != nil { - return err - } - jr.agentProcessors = append(jr.agentProcessors, processor) - } - - jr.goroutines.Add(len(jr.agentProcessors)) - for _, processor := range jr.agentProcessors { - go func(p processors.Processor) { - defer jr.goroutines.Done() - p.Serve() - }(processor) - } - - if jr.config.AgentHTTPEndpoint != "" { - jr.agentServer = httpserver.NewHTTPServer(jr.config.AgentHTTPEndpoint, ¬ImplementedConfigManager{}, metrics.NullFactory, jr.settings.Logger) - - jr.goroutines.Add(1) - go func() { - defer jr.goroutines.Done() - if err := jr.agentServer.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) && err != nil { - host.ReportFatalError(fmt.Errorf("jaeger agent server error: %w", err)) - } - }() - } - - return nil -} - -func (jr *jReceiver) buildProcessor(address string, cfg ServerConfigUDP, factory apacheThrift.TProtocolFactory, a agent.Agent) (processors.Processor, error) { - handler := agent.NewAgentProcessor(a) - transport, err := thriftudp.NewTUDPServerTransport(address) - if err != nil { - return nil, err - } - if cfg.SocketBufferSize > 0 { - if err = transport.SetSocketBufferSize(cfg.SocketBufferSize); err != nil { - return nil, err - } - } - server, err := servers.NewTBufferedServer(transport, cfg.QueueSize, cfg.MaxPacketSize, metrics.NullFactory) - if err != nil { - return nil, err - } - processor, err := processors.NewThriftProcessor(server, cfg.Workers, metrics.NullFactory, factory, handler, jr.settings.Logger) - if err != nil { - return nil, err - } - return processor, nil -} - -func (jr *jReceiver) decodeThriftHTTPBody(r *http.Request) (*jaeger.Batch, *httpError) { - bodyBytes, err := io.ReadAll(r.Body) - r.Body.Close() - if err != nil { - return nil, &httpError{ - fmt.Sprintf("Unable to process request body: %v", err), - http.StatusInternalServerError, - } - } - - contentType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) - if err != nil { - return nil, &httpError{ - fmt.Sprintf("Cannot parse content type: %v", err), - http.StatusBadRequest, - } - } - if _, ok := acceptedThriftFormats[contentType]; !ok { - return nil, &httpError{ - fmt.Sprintf("Unsupported content type: %v", contentType), - http.StatusBadRequest, - } - } - - tdes := apacheThrift.NewTDeserializer() - batch := &jaeger.Batch{} - if err = tdes.Read(r.Context(), batch, bodyBytes); err != nil { - return nil, &httpError{ - fmt.Sprintf("Unable to process request body: %v", err), - http.StatusBadRequest, - } - } - return batch, nil -} - -// HandleThriftHTTPBatch implements Jaeger HTTP Thrift handler. -func (jr *jReceiver) HandleThriftHTTPBatch(w http.ResponseWriter, r *http.Request) { - ctx := jr.httpObsrecv.StartTracesOp(r.Context()) - - batch, hErr := jr.decodeThriftHTTPBody(r) - if hErr != nil { - http.Error(w, html.EscapeString(hErr.msg), hErr.statusCode) - jr.httpObsrecv.EndTracesOp(ctx, thriftFormat, 0, hErr) - return - } - - numSpans, err := consumeTraces(ctx, batch, jr.nextConsumer) - if err != nil { - http.Error(w, fmt.Sprintf("Cannot submit Jaeger batch: %v", err), http.StatusInternalServerError) - } else { - w.WriteHeader(http.StatusAccepted) - } - jr.httpObsrecv.EndTracesOp(ctx, thriftFormat, numSpans, err) -} - -func (jr *jReceiver) startCollector(host component.Host) error { - if jr.config == nil { - return nil - } - - if jr.config.CollectorHTTPSettings.Endpoint != "" { - cln, err := jr.config.CollectorHTTPSettings.ToListener() - if err != nil { - return fmt.Errorf("failed to bind to Collector address %q: %w", - jr.config.CollectorHTTPSettings.Endpoint, err) - } - - nr := mux.NewRouter() - nr.HandleFunc("/api/traces", jr.HandleThriftHTTPBatch).Methods(http.MethodPost) - jr.collectorServer, err = jr.config.CollectorHTTPSettings.ToServer(host, jr.settings.TelemetrySettings, nr) - if err != nil { - return err - } - - jr.goroutines.Add(1) - go func() { - defer jr.goroutines.Done() - if errHTTP := jr.collectorServer.Serve(cln); !errors.Is(errHTTP, http.ErrServerClosed) && errHTTP != nil { - host.ReportFatalError(errHTTP) - } - }() - } - - if jr.config.CollectorGRPCServerSettings.NetAddr.Endpoint != "" { - var err error - jr.grpc, err = jr.config.CollectorGRPCServerSettings.ToServer(host, jr.settings.TelemetrySettings) - if err != nil { - return fmt.Errorf("failed to build the options for the Jaeger gRPC Collector: %w", err) - } - - ln, err := jr.config.CollectorGRPCServerSettings.ToListener() - if err != nil { - return fmt.Errorf("failed to bind to gRPC address %q: %w", jr.config.CollectorGRPCServerSettings.NetAddr, err) - } - - api_v2.RegisterCollectorServiceServer(jr.grpc, jr) - - jr.goroutines.Add(1) - go func() { - defer jr.goroutines.Done() - if errGrpc := jr.grpc.Serve(ln); !errors.Is(errGrpc, grpc.ErrServerStopped) && errGrpc != nil { - host.ReportFatalError(errGrpc) - } - }() - } - - return nil -} diff --git a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/trace_receiver_test.go b/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/trace_receiver_test.go deleted file mode 100644 index f82b540edc67..000000000000 --- a/receiver/jaegerreceiver/internal/jaegerreceiverdeprecated/trace_receiver_test.go +++ /dev/null @@ -1,413 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package jaegerreceiverdeprecated - -import ( - "bytes" - "context" - "encoding/binary" - "fmt" - "io" - "net" - "net/http" - "net/http/httptest" - "path/filepath" - "testing" - "time" - - "github.com/apache/thrift/lib/go/thrift" - "github.com/jaegertracing/jaeger/model" - "github.com/jaegertracing/jaeger/proto-gen/api_v2" - jaegerthrift "github.com/jaegertracing/jaeger/thrift-gen/jaeger" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/component/componenttest" - "go.opentelemetry.io/collector/config/configgrpc" - "go.opentelemetry.io/collector/config/confighttp" - "go.opentelemetry.io/collector/config/confignet" - "go.opentelemetry.io/collector/config/configtls" - "go.opentelemetry.io/collector/consumer/consumertest" - "go.opentelemetry.io/collector/pdata/pcommon" - "go.opentelemetry.io/collector/pdata/ptrace" - "go.opentelemetry.io/collector/receiver/receivertest" - conventions "go.opentelemetry.io/collector/semconv/v1.6.1" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/insecure" - - "github.com/open-telemetry/opentelemetry-collector-contrib/internal/common/testutil" - "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/translator/jaeger" -) - -var jaegerReceiver = component.NewIDWithName("jaeger", "receiver_test") - -func TestTraceSource(t *testing.T) { - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerReceiver, &configuration{}, nil, set) - require.NoError(t, err) - require.NotNil(t, jr) -} - -func jaegerBatchToHTTPBody(b *jaegerthrift.Batch) (*http.Request, error) { - body, err := thrift.NewTSerializer().Write(context.Background(), b) - if err != nil { - return nil, err - } - r := httptest.NewRequest("POST", "/api/traces", bytes.NewReader(body)) - r.Header.Add("content-type", "application/x-thrift") - return r, nil -} - -func TestThriftHTTPBodyDecode(t *testing.T) { - jr := jReceiver{} - batch := &jaegerthrift.Batch{ - Process: jaegerthrift.NewProcess(), - Spans: []*jaegerthrift.Span{jaegerthrift.NewSpan()}, - } - r, err := jaegerBatchToHTTPBody(batch) - require.NoError(t, err, "failed to prepare http body") - - gotBatch, hErr := jr.decodeThriftHTTPBody(r) - require.Nil(t, hErr, "failed to decode http body") - assert.Equal(t, batch, gotBatch) -} - -func TestReception(t *testing.T) { - addr := testutil.GetAvailableLocalAddress(t) - // 1. Create the Jaeger receiver aka "server" - config := &configuration{ - CollectorHTTPSettings: confighttp.HTTPServerSettings{ - Endpoint: addr, - }, - } - sink := new(consumertest.TracesSink) - - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerReceiver, config, sink, set) - require.NoError(t, err) - - require.NoError(t, jr.Start(context.Background(), componenttest.NewNopHost())) - t.Cleanup(func() { require.NoError(t, jr.Shutdown(context.Background())) }) - - // 2. Then send spans to the Jaeger receiver. - _, port, _ := net.SplitHostPort(addr) - collectorAddr := fmt.Sprintf("http://localhost:%s/api/traces", port) - td := generateTraceData() - batches, err := jaeger.ProtoFromTraces(td) - require.NoError(t, err) - for _, batch := range batches { - require.NoError(t, sendToCollector(collectorAddr, modelToThrift(batch))) - } - - assert.NoError(t, err, "should not have failed to create the Jaeger OpenCensus exporter") - - gotTraces := sink.AllTraces() - assert.Equal(t, 1, len(gotTraces)) - - assert.EqualValues(t, td, gotTraces[0]) -} - -func TestPortsNotOpen(t *testing.T) { - // an empty config should result in no open ports - config := &configuration{} - - sink := new(consumertest.TracesSink) - - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerReceiver, config, sink, set) - require.NoError(t, err) - - require.NoError(t, jr.Start(context.Background(), componenttest.NewNopHost())) - t.Cleanup(func() { require.NoError(t, jr.Shutdown(context.Background())) }) - - // there is a race condition here that we're ignoring. - // this test may occasionally pass incorrectly, but it will not fail incorrectly - // TODO: consider adding a way for a receiver to asynchronously signal that is ready to receive spans to eliminate races/arbitrary waits - l, err := net.Listen("tcp", "localhost:14250") - assert.NoError(t, err, "should have been able to listen on 14250. jaeger receiver incorrectly started grpc") - if l != nil { - l.Close() - } - - l, err = net.Listen("tcp", "localhost:14268") - assert.NoError(t, err, "should have been able to listen on 14268. jaeger receiver incorrectly started thrift_http") - if l != nil { - l.Close() - } -} - -func TestGRPCReception(t *testing.T) { - // prepare - config := &configuration{ - CollectorGRPCServerSettings: configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: testutil.GetAvailableLocalAddress(t), - Transport: "tcp", - }, - }, - } - sink := new(consumertest.TracesSink) - - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerReceiver, config, sink, set) - require.NoError(t, err) - - require.NoError(t, jr.Start(context.Background(), componenttest.NewNopHost())) - t.Cleanup(func() { require.NoError(t, jr.Shutdown(context.Background())) }) - - conn, err := grpc.Dial(config.CollectorGRPCServerSettings.NetAddr.Endpoint, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) - require.NoError(t, err) - defer conn.Close() - - cl := api_v2.NewCollectorServiceClient(conn) - - now := time.Unix(1542158650, 536343000).UTC() - d10min := 10 * time.Minute - d2sec := 2 * time.Second - nowPlus10min := now.Add(d10min) - nowPlus10min2sec := now.Add(d10min).Add(d2sec) - - // test - req := grpcFixture(t, now, d10min, d2sec) - resp, err := cl.PostSpans(context.Background(), req, grpc.WaitForReady(true)) - - // verify - assert.NoError(t, err, "should not have failed to post spans") - assert.NotNil(t, resp, "response should not have been nil") - - gotTraces := sink.AllTraces() - assert.Equal(t, 1, len(gotTraces)) - want := expectedTraceData(now, nowPlus10min, nowPlus10min2sec) - - assert.Len(t, req.Batch.Spans, want.SpanCount(), "got a conflicting amount of spans") - - assert.EqualValues(t, want, gotTraces[0]) -} - -func TestGRPCReceptionWithTLS(t *testing.T) { - // prepare - tlsCreds := &configtls.TLSServerSetting{ - TLSSetting: configtls.TLSSetting{ - CertFile: filepath.Join("testdata", "server.crt"), - KeyFile: filepath.Join("testdata", "server.key"), - }, - } - - grpcServerSettings := configgrpc.GRPCServerSettings{ - NetAddr: confignet.NetAddr{ - Endpoint: testutil.GetAvailableLocalAddress(t), - Transport: "tcp", - }, - TLSSetting: tlsCreds, - } - - config := &configuration{ - CollectorGRPCServerSettings: grpcServerSettings, - } - sink := new(consumertest.TracesSink) - - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerReceiver, config, sink, set) - require.NoError(t, err) - - require.NoError(t, jr.Start(context.Background(), componenttest.NewNopHost())) - t.Cleanup(func() { require.NoError(t, jr.Shutdown(context.Background())) }) - - creds, err := credentials.NewClientTLSFromFile(filepath.Join("testdata", "server.crt"), "localhost") - require.NoError(t, err) - conn, err := grpc.Dial(grpcServerSettings.NetAddr.Endpoint, grpc.WithTransportCredentials(creds), grpc.WithBlock()) - require.NoError(t, err) - defer conn.Close() - - cl := api_v2.NewCollectorServiceClient(conn) - - now := time.Now() - d10min := 10 * time.Minute - d2sec := 2 * time.Second - nowPlus10min := now.Add(d10min) - nowPlus10min2sec := now.Add(d10min).Add(d2sec) - - // test - req := grpcFixture(t, now, d10min, d2sec) - resp, err := cl.PostSpans(context.Background(), req, grpc.WaitForReady(true)) - - // verify - assert.NoError(t, err, "should not have failed to post spans") - assert.NotNil(t, resp, "response should not have been nil") - - gotTraces := sink.AllTraces() - assert.Equal(t, 1, len(gotTraces)) - want := expectedTraceData(now, nowPlus10min, nowPlus10min2sec) - - assert.Len(t, req.Batch.Spans, want.SpanCount(), "got a conflicting amount of spans") - assert.EqualValues(t, want, gotTraces[0]) -} - -func expectedTraceData(t1, t2, t3 time.Time) ptrace.Traces { - traceID := pcommon.TraceID( - [16]byte{0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, 0x80}) - parentSpanID := pcommon.SpanID([8]byte{0x1F, 0x1E, 0x1D, 0x1C, 0x1B, 0x1A, 0x19, 0x18}) - childSpanID := pcommon.SpanID([8]byte{0xAF, 0xAE, 0xAD, 0xAC, 0xAB, 0xAA, 0xA9, 0xA8}) - - traces := ptrace.NewTraces() - rs := traces.ResourceSpans().AppendEmpty() - rs.Resource().Attributes().PutStr(conventions.AttributeServiceName, "issaTest") - rs.Resource().Attributes().PutBool("bool", true) - rs.Resource().Attributes().PutStr("string", "yes") - rs.Resource().Attributes().PutInt("int64", 10000000) - spans := rs.ScopeSpans().AppendEmpty().Spans() - - span0 := spans.AppendEmpty() - span0.SetSpanID(childSpanID) - span0.SetParentSpanID(parentSpanID) - span0.SetTraceID(traceID) - span0.SetName("DBSearch") - span0.SetStartTimestamp(pcommon.NewTimestampFromTime(t1)) - span0.SetEndTimestamp(pcommon.NewTimestampFromTime(t2)) - span0.Status().SetCode(ptrace.StatusCodeError) - span0.Status().SetMessage("Stale indices") - - span1 := spans.AppendEmpty() - span1.SetSpanID(parentSpanID) - span1.SetTraceID(traceID) - span1.SetName("ProxyFetch") - span1.SetStartTimestamp(pcommon.NewTimestampFromTime(t2)) - span1.SetEndTimestamp(pcommon.NewTimestampFromTime(t3)) - span1.Status().SetCode(ptrace.StatusCodeError) - span1.Status().SetMessage("Frontend crash") - - return traces -} - -func grpcFixture(t *testing.T, t1 time.Time, d1, d2 time.Duration) *api_v2.PostSpansRequest { - traceID := model.TraceID{} - require.NoError(t, traceID.Unmarshal([]byte{0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, 0x80})) - - parentSpanID := model.NewSpanID(binary.BigEndian.Uint64([]byte{0x1F, 0x1E, 0x1D, 0x1C, 0x1B, 0x1A, 0x19, 0x18})) - childSpanID := model.NewSpanID(binary.BigEndian.Uint64([]byte{0xAF, 0xAE, 0xAD, 0xAC, 0xAB, 0xAA, 0xA9, 0xA8})) - - return &api_v2.PostSpansRequest{ - Batch: model.Batch{ - Process: &model.Process{ - ServiceName: "issaTest", - Tags: []model.KeyValue{ - model.Bool("bool", true), - model.String("string", "yes"), - model.Int64("int64", 1e7), - }, - }, - Spans: []*model.Span{ - { - TraceID: traceID, - SpanID: childSpanID, - OperationName: "DBSearch", - StartTime: t1, - Duration: d1, - Tags: []model.KeyValue{ - model.String(conventions.OtelStatusDescription, "Stale indices"), - model.Int64(conventions.OtelStatusCode, int64(ptrace.StatusCodeError)), - model.Bool("error", true), - }, - References: []model.SpanRef{ - { - TraceID: traceID, - SpanID: parentSpanID, - RefType: model.SpanRefType_CHILD_OF, - }, - }, - }, - { - TraceID: traceID, - SpanID: parentSpanID, - OperationName: "ProxyFetch", - StartTime: t1.Add(d1), - Duration: d2, - Tags: []model.KeyValue{ - model.String(conventions.OtelStatusDescription, "Frontend crash"), - model.Int64(conventions.OtelStatusCode, int64(ptrace.StatusCodeError)), - model.Bool("error", true), - }, - }, - }, - }, - } -} - -func TestSampling(t *testing.T) { - config := &configuration{ - CollectorGRPCServerSettings: configgrpc.GRPCServerSettings{NetAddr: confignet.NetAddr{ - Endpoint: testutil.GetAvailableLocalAddress(t), - Transport: "tcp", - }}, - } - sink := new(consumertest.TracesSink) - - set := receivertest.NewNopCreateSettings() - jr, err := newJaegerReceiver(jaegerReceiver, config, sink, set) - require.NoError(t, err) - - require.NoError(t, jr.Start(context.Background(), componenttest.NewNopHost())) - t.Cleanup(func() { require.NoError(t, jr.Shutdown(context.Background())) }) - - conn, err := grpc.Dial(config.CollectorGRPCServerSettings.NetAddr.Endpoint, grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) - defer conn.Close() - - cl := api_v2.NewSamplingManagerClient(conn) - - resp, err := cl.GetSamplingStrategy(context.Background(), &api_v2.SamplingStrategyParameters{ - ServiceName: "foo", - }) - assert.Error(t, err, "expect: unknown service jaeger.api_v2.SamplingManager") - assert.Nil(t, resp) -} - -func TestConsumeThriftTrace(t *testing.T) { - tests := []struct { - batch *jaegerthrift.Batch - numSpans int - }{ - { - batch: nil, - }, - { - batch: &jaegerthrift.Batch{Spans: []*jaegerthrift.Span{{}}}, - numSpans: 1, - }, - } - for _, test := range tests { - numSpans, err := consumeTraces(context.Background(), test.batch, consumertest.NewNop()) - require.NoError(t, err) - assert.Equal(t, test.numSpans, numSpans) - } -} - -func sendToCollector(endpoint string, batch *jaegerthrift.Batch) error { - buf, err := thrift.NewTSerializer().Write(context.Background(), batch) - if err != nil { - return err - } - req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(buf)) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/x-thrift") - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return err - } - - _, err = io.Copy(io.Discard, resp.Body) - if err != nil { - return err - } - resp.Body.Close() - - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return fmt.Errorf("failed to upload traces; HTTP status code: %d", resp.StatusCode) - } - return nil -} diff --git a/receiver/sapmreceiver/go.mod b/receiver/sapmreceiver/go.mod index 4025ab314923..9cdb53178dde 100644 --- a/receiver/sapmreceiver/go.mod +++ b/receiver/sapmreceiver/go.mod @@ -4,7 +4,7 @@ go 1.20 require ( github.com/gorilla/mux v1.8.1 - github.com/jaegertracing/jaeger v1.41.0 + github.com/jaegertracing/jaeger v1.48.0 github.com/klauspost/compress v1.17.4 github.com/open-telemetry/opentelemetry-collector-contrib/internal/common v0.90.1 github.com/open-telemetry/opentelemetry-collector-contrib/internal/splunk v0.90.1 @@ -63,7 +63,7 @@ require ( go.opentelemetry.io/otel v1.21.0 // indirect go.opentelemetry.io/otel/metric v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect - go.uber.org/atomic v1.10.0 // indirect + go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.26.0 // indirect golang.org/x/net v0.19.0 // indirect diff --git a/receiver/sapmreceiver/go.sum b/receiver/sapmreceiver/go.sum index 52fb3afcdc1a..170068141ddf 100644 --- a/receiver/sapmreceiver/go.sum +++ b/receiver/sapmreceiver/go.sum @@ -64,8 +64,8 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/jaegertracing/jaeger v1.41.0 h1:vVNky8dP46M2RjGaZ7qRENqylW+tBFay3h57N16Ip7M= -github.com/jaegertracing/jaeger v1.41.0/go.mod h1:SIkAT75iVmA9U+mESGYuMH6UQv6V9Qy4qxo0lwfCQAc= +github.com/jaegertracing/jaeger v1.48.0 h1:YuKooQ7qJsjgxws9xuf8C/BLNTPx8qTAJz4wv7IHhSc= +github.com/jaegertracing/jaeger v1.48.0/go.mod h1:BoAPkdCAIEuLsVz/EDhjXd+GSVpHtJhiGqWoFEvBCKg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= @@ -173,8 +173,8 @@ go.opentelemetry.io/otel/sdk v1.21.0 h1:FTt8qirL1EysG6sTQRZ5TokkU8d0ugCj8htOgThZ go.opentelemetry.io/otel/sdk/metric v1.21.0 h1:smhI5oD714d6jHE6Tie36fPx4WDFIg+Y6RfAY4ICcR0= go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc= go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=