From 8724cca45d3a16072e97d35c0c641eac5ad09a70 Mon Sep 17 00:00:00 2001 From: Raj Nishtala Date: Wed, 27 Nov 2024 18:57:26 -0500 Subject: [PATCH] Remove the deprecated syslog exporter after upstream API breaking changes --- pkg/exporter/syslogexporter/Makefile | 1 - pkg/exporter/syslogexporter/README.md | 157 -------------- pkg/exporter/syslogexporter/config.go | 92 -------- pkg/exporter/syslogexporter/config_test.go | 84 -------- .../syslogexporter/examples/config.yaml | 68 ------ .../examples/config_with_token.yaml | 75 ------- pkg/exporter/syslogexporter/exporter.go | 154 -------------- pkg/exporter/syslogexporter/exporter_test.go | 196 ----------------- pkg/exporter/syslogexporter/factory.go | 69 ------ pkg/exporter/syslogexporter/factory_test.go | 57 ----- pkg/exporter/syslogexporter/go.mod | 54 ----- pkg/exporter/syslogexporter/go.sum | 150 ------------- pkg/exporter/syslogexporter/syslog.go | 197 ------------------ pkg/exporter/syslogexporter/syslog_test.go | 72 ------- pkg/exporter/syslogexporter/utils.go | 66 ------ pkg/exporter/syslogexporter/utils_test.go | 94 --------- 16 files changed, 1586 deletions(-) delete mode 100644 pkg/exporter/syslogexporter/Makefile delete mode 100644 pkg/exporter/syslogexporter/README.md delete mode 100644 pkg/exporter/syslogexporter/config.go delete mode 100644 pkg/exporter/syslogexporter/config_test.go delete mode 100644 pkg/exporter/syslogexporter/examples/config.yaml delete mode 100644 pkg/exporter/syslogexporter/examples/config_with_token.yaml delete mode 100644 pkg/exporter/syslogexporter/exporter.go delete mode 100644 pkg/exporter/syslogexporter/exporter_test.go delete mode 100644 pkg/exporter/syslogexporter/factory.go delete mode 100644 pkg/exporter/syslogexporter/factory_test.go delete mode 100644 pkg/exporter/syslogexporter/go.mod delete mode 100644 pkg/exporter/syslogexporter/go.sum delete mode 100644 pkg/exporter/syslogexporter/syslog.go delete mode 100644 pkg/exporter/syslogexporter/syslog_test.go delete mode 100644 pkg/exporter/syslogexporter/utils.go delete mode 100644 pkg/exporter/syslogexporter/utils_test.go diff --git a/pkg/exporter/syslogexporter/Makefile b/pkg/exporter/syslogexporter/Makefile deleted file mode 100644 index ded7a36092..0000000000 --- a/pkg/exporter/syslogexporter/Makefile +++ /dev/null @@ -1 +0,0 @@ -include ../../Makefile.Common diff --git a/pkg/exporter/syslogexporter/README.md b/pkg/exporter/syslogexporter/README.md deleted file mode 100644 index b2649b75be..0000000000 --- a/pkg/exporter/syslogexporter/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# Syslog Exporter - -**Stability level**: Deprecated - -This exporter is deprecated in favor of the [syslog exporter][syslog_exporter_contrib] that lives in the [OpenTelemetry Collector Contrib][contrib_repo] repository. -The functionality is the same but the configuration is slightly different. - -To migrate, rename the following keys in configuration for `syslogexporter`: - -- rename `protocol` property to `network` -- rename `format` property to `protocol` - -For example, given the following configuration: - -```yaml - syslog: - protocol: tcp - port: 514 - endpoint: 127.0.0.1 - format: rfc5424 - tls: - ca_file: ca.pem - cert_file: cert.pem - key_file: key.pem -``` - -change it to: - -```yaml - syslog: - network: tcp - port: 514 - endpoint: 127.0.0.1 - protocol: rfc5424 - tls: - ca_file: ca.pem - cert_file: cert.pem - key_file: key.pem -``` - -[syslog_exporter_contrib]: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/exporter/syslogexporter/README.md -[contrib_repo]: https://github.com/open-telemetry/opentelemetry-collector-contrib/ - -## About The Exporter - -The syslog exporter supports sending messages to a remote syslog server. - -- This exporter can forward syslog messages to a third party [syslog server][rsyslog] using [RFC5424][RFC5424] and [RFC3164][RFC3164]. -- It also supports sending syslog messages to the [Cloud Syslog Source][CloudSyslogSource] configured on a Sumo Logic hosted collector - using the [RFC5424][RFC5424] format, token required by [Cloud Syslog Source][CloudSyslogSource] can be added using [Logs Transform Processor][logstransform], - please see [example configuration][configWithToken]. -- It is recommended that this syslog exporter be used with the [syslog_parser][syslog_parser] configured in the receiver. - This ensures that all the syslog message headers are populated with the expected values. -- Not using the `syslog_parser` will result in the syslog message being populated with default header values. - -## Configuration - -**The following are a few configuration options available to forward syslog messages**: - -- `endpoint` - (default = `host.domain.com`) syslog endpoint (FQDN or IP address) -- `protocol` - (default = `tcp`) tcp/udp -- `port` - (default = `514`) A syslog port -- `format` - (default = `rfc5424`) rfc5424/rfc3164 - - `rfc5424` - Expects the syslog messages to be rfc5424 compliant - - `rfc3164` - Expects the syslog messages to be rfc3164 compliant -- `tls` - configuration for TLS/mTLS - - `insecure` (default = `false`) whether to enable client transport security, by default, TLS is enabled. - - `cert_file` - Path to the TLS cert to use for TLS required connections. Should only be used if `insecure` is set to `false`. - - `key_file` - Path to the TLS key to use for TLS required connections. Should only be used if `insecure` is set to `false`. - - `ca_file` - Path to the CA cert. For a client this verifies the server certificate. For a server this verifies client certificates. If empty uses system root CA. Should only be used if `insecure` is set to `false`. - - `insecure_skip_verify` - (default = `false`) whether to skip verifying the certificate or not. - - `min_version` (default = `1.2`) Minimum acceptable TLS version - - `max_version` (default = `""` handled by [crypto/tls][cryptoTLS] - currently TLS 1.3) Maximum acceptable TLS version. - - `reload_interval` - Specifies the duration after which the certificate will be reloaded. If not set, it will never be reloaded. - -Please refer to the yaml below to configure the syslog exporter: - -```yaml -extensions: - file_storage/syslog: - directory: . - timeout: 10s - -exporters: - syslog: - protocol: tcp - port: 6514 # 514 (UDP) - endpoint: 127.0.0.1 # FQDN or IP address - tls: - ca_file: certs/servercert.pem - cert_file: certs/cert.pem - key_file: certs/key.pem - format: rfc5424 # rfc5424 or rfc3164 - - - # for below described queueing and retry related configuration please refer to: - # https://github.com/open-telemetry/opentelemetry-collector/blob/main/exporter/exporterhelper/README.md#configuration - retry_on_failure: - # default = true - enabled: true - # time to wait after the first failure before retrying; - # ignored if enabled is false, default = 5s - initial_interval: 10s - # is the upper bound on backoff; ignored if enabled is false, default = 30s - max_interval: 40s - # is the maximum amount of time spent trying to send a batch; - # ignored if enabled is false, default = 120s - max_elapsed_time: 150s - - sending_queue: - # default = false - enabled: true - # number of consumers that dequeue batches; ignored if enabled is false, - # default = 10 - num_consumers: 20 - # when set, enables persistence and uses the component specified as a storage extension for the persistent queue - # make sure to configure and add a `file_storage` extension in `service.extensions`. - # default = None - storage: file_storage/syslog - # maximum number of batches kept in memory before data; - # ignored if enabled is false, default = 5000 - # - # user should calculate this as num_seconds * requests_per_second where: - # num_seconds is the number of seconds to buffer in case of a backend outage, - # requests_per_second is the average number of requests per seconds. - queue_size: 10000 -receivers: - filelog: - start_at: beginning - include: - - /other/path/**/*.txt - operators: - - type: syslog_parser - protocol: rfc5424 # the format used here must match the syslog exporter - -service: - telemetry: - logs: - level: "info" - extensions: - - file_storage/syslog - pipelines: - logs: - receivers: - - filelog - exporters: - - syslog -``` - -[rsyslog]: https://www.rsyslog.com/ -[RFC5424]: https://www.rfc-editor.org/rfc/rfc5424 -[RFC3164]: https://www.rfc-editor.org/rfc/rfc3164 -[CloudSyslogSource]: https://help.sumologic.com/docs/send-data/hosted-collectors/cloud-syslog-source/ -[logstransform]: https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/logstransformprocessor -[configWithToken]: ./examples/config_with_token.yaml -[syslog_parser]: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/pkg/stanza/docs/operators/syslog_parser.md -[cryptoTLS]: https://github.com/golang/go/blob/518889b35cb07f3e71963f2ccfc0f96ee26a51ce/src/crypto/tls/common.go#L706-L709 diff --git a/pkg/exporter/syslogexporter/config.go b/pkg/exporter/syslogexporter/config.go deleted file mode 100644 index 88b20fac48..0000000000 --- a/pkg/exporter/syslogexporter/config.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "errors" - "strings" - - "github.com/THREATINT/go-net" - "go.opentelemetry.io/collector/config/configretry" - "go.opentelemetry.io/collector/config/configtls" - "go.opentelemetry.io/collector/exporter/exporterhelper" - "go.uber.org/multierr" -) - -var ( - errUnsupportedPort = errors.New("unsupported port: port is required, must be in the range 1-65535") - errInvalidEndpoint = errors.New("invalid endpoint: endpoint is required, must be a valid FQDN or IP address") - errUnsupportedProtocol = errors.New("unsupported protocol: protocol is required, only tcp/udp supported") - errUnsupportedFormat = errors.New("unsupported format: Only rfc5424 and rfc3164 supported") -) - -// Config defines configuration for Syslog exporter. -type Config struct { - // Syslog server address - Endpoint string `mapstructure:"endpoint"` - // Syslog server port - Port int `mapstructure:"port"` - // Protocol for syslog communication - // options: tcp, udp - Protocol string `mapstructure:"protocol"` - // Format of syslog messages - Format string `mapstructure:"format"` - - // TLSSetting struct exposes TLS client configuration. - TLSSetting configtls.ClientConfig `mapstructure:"tls"` - - exporterhelper.QueueSettings `mapstructure:"sending_queue"` - configretry.BackOffConfig `mapstructure:"retry_on_failure"` -} - -// Validate the configuration for errors. This is required by component.Config. -func (cfg *Config) Validate() error { - invalidFields := []error{} - if cfg.Port < 1 || cfg.Port > 65525 { - invalidFields = append(invalidFields, errUnsupportedPort) - } - - if !net.IsFQDN(cfg.Endpoint) && !net.IsIPAddr(cfg.Endpoint) && cfg.Endpoint != "localhost" { - invalidFields = append(invalidFields, errInvalidEndpoint) - } - - if strings.ToLower(cfg.Protocol) != "tcp" && strings.ToLower(cfg.Protocol) != "udp" { - invalidFields = append(invalidFields, errUnsupportedProtocol) - } - - switch cfg.Format { - case formatRFC3164Str: - case formatRFC5424Str: - default: - invalidFields = append(invalidFields, errUnsupportedFormat) - } - - if len(invalidFields) > 0 { - return multierr.Combine(invalidFields...) - } - - return nil -} - -const ( - // Syslog Protocol - DefaultProtocol = "tcp" - // Syslog Port - DefaultPort = 514 - // Syslog Endpoint - DefaultEndpoint = "host.domain.com" - // Syslog format - DefaultFormat = "rfc5424" -) diff --git a/pkg/exporter/syslogexporter/config_test.go b/pkg/exporter/syslogexporter/config_test.go deleted file mode 100644 index 3c80390778..0000000000 --- a/pkg/exporter/syslogexporter/config_test.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestValidate(t *testing.T) { - - tests := []struct { - name string - cfg *Config - err string - }{ - { - name: "invalid Port", - cfg: &Config{ - Port: 515444, - Endpoint: "host.domain.com", - Format: "rfc542", - Protocol: "udp", - }, - err: "unsupported port: port is required, must be in the range 1-65535; " + - "unsupported format: Only rfc5424 and rfc3164 supported", - }, - - { - name: "invalid Endpoint", - cfg: &Config{ - Port: 514, - Endpoint: "", - Format: "rfc5424", - Protocol: "udp", - }, - err: "invalid endpoint: endpoint is required, must be a valid FQDN or IP address", - }, - - { - name: "unsupported Protocol", - cfg: &Config{ - Port: 514, - Endpoint: "host.domain.com", - Format: "rfc5424", - Protocol: "ftp", - }, - err: "unsupported protocol: protocol is required, only tcp/udp supported", - }, - { - name: "Unsupported Format", - cfg: &Config{ - Port: 514, - Endpoint: "host.domain.com", - Protocol: "udp", - Format: "rfc", - }, - err: "unsupported format: Only rfc5424 and rfc3164 supported", - }, - } - for _, testInstance := range tests { - t.Run(testInstance.name, func(t *testing.T) { - err := testInstance.cfg.Validate() - if testInstance.err != "" { - assert.EqualError(t, err, testInstance.err) - } else { - assert.NoError(t, err) - } - }) - } -} diff --git a/pkg/exporter/syslogexporter/examples/config.yaml b/pkg/exporter/syslogexporter/examples/config.yaml deleted file mode 100644 index a4ff1fefb4..0000000000 --- a/pkg/exporter/syslogexporter/examples/config.yaml +++ /dev/null @@ -1,68 +0,0 @@ -extensions: - file_storage/syslog: - directory: /tmp/otc - timeout: 10s - -exporters: - syslog: - protocol: tcp - port: 514 - endpoint: 127.0.0.1 - tls: - ca_file: certs/servercert.pem - cert_file: certs/cert.pem - key_file: certs/key.pem - format: rfc5424 - - # for below described queueing and retry related configuration please refer to: - # https://github.com/open-telemetry/opentelemetry-collector/blob/main/exporter/exporterhelper/README.md#configuration - retry_on_failure: - # default = true - enabled: true - # time to wait after the first failure before retrying; - # ignored if enabled is false, default = 5s - initial_interval: 10s - # is the upper bound on backoff; ignored if enabled is false, default = 30s - max_interval: 40s - # is the maximum amount of time spent trying to send a batch; - # ignored if enabled is false, default = 120s - max_elapsed_time: 150s - - sending_queue: - # default = false - enabled: true - # number of consumers that dequeue batches; ignored if enabled is false, - # default = 10 - num_consumers: 20 - # when set, enables persistence and uses the component specified as a storage extension for the persistent queue - # make sure to configure and add a `file_storage` extension in `service.extensions`. - # default = None - storage: file_storage/syslog - # maximum number of batches kept in memory before data; - # ignored if enabled is false, default = 5000 - # - # user should calculate this as num_seconds * requests_per_second where: - # num_seconds is the number of seconds to buffer in case of a backend outage, - # requests_per_second is the average number of requests per seconds. - queue_size: 10000 -receivers: - filelog: - start_at: beginning - include: - - /other/path/**/*.txt - operators: - - type: syslog_parser - protocol: rfc5424 - -service: - telemetry: - logs: - level: "debug" - extensions: - - file_storage/syslog - pipelines: - logs: - receivers: - - filelog - exporters: - - syslog diff --git a/pkg/exporter/syslogexporter/examples/config_with_token.yaml b/pkg/exporter/syslogexporter/examples/config_with_token.yaml deleted file mode 100644 index 0c124968fd..0000000000 --- a/pkg/exporter/syslogexporter/examples/config_with_token.yaml +++ /dev/null @@ -1,75 +0,0 @@ -extensions: - file_storage/syslog: - directory: /tmp/otc - timeout: 10s - -exporters: - syslog: - protocol: tcp - port: 514 - endpoint: 127.0.0.1 - tls: - ca_file: certs/servercert.pem - cert_file: certs/cert.pem - key_file: certs/key.pem - format: rfc5424 - - # for below described queueing and retry related configuration please refer to: - # https://github.com/open-telemetry/opentelemetry-collector/blob/main/exporter/exporterhelper/README.md#configuration - retry_on_failure: - # default = true - enabled: true - # time to wait after the first failure before retrying; - # ignored if enabled is false, default = 5s - initial_interval: 10s - # is the upper bound on backoff; ignored if enabled is false, default = 30s - max_interval: 40s - # is the maximum amount of time spent trying to send a batch; - # ignored if enabled is false, default = 120s - max_elapsed_time: 150s - - sending_queue: - # default = false - enabled: true - # number of consumers that dequeue batches; ignored if enabled is false, - # default = 10 - num_consumers: 20 - # when set, enables persistence and uses the component specified as a storage extension for the persistent queue - # make sure to configure and add a `file_storage` extension in `service.extensions`. - # default = None - storage: file_storage/syslog - # maximum number of batches kept in memory before data; - # ignored if enabled is false, default = 5000 - # - # user should calculate this as num_seconds * requests_per_second where: - # num_seconds is the number of seconds to buffer in case of a backend outage, - # requests_per_second is the average number of requests per seconds. - queue_size: 10000 -receivers: - filelog: - start_at: beginning - include: - - /other/path/**/*.txt - operators: - - type: syslog_parser - protocol: rfc5424 -processors: - logstransform: - operators: - - type: add - field: attributes.message - value: EXPR("YOUR_TOKEN " + attributes.message) -service: - telemetry: - logs: - level: "debug" - extensions: - - file_storage/syslog - pipelines: - logs: - receivers: - - filelog - processors: - - logstransform - exporters: - - syslog diff --git a/pkg/exporter/syslogexporter/exporter.go b/pkg/exporter/syslogexporter/exporter.go deleted file mode 100644 index fcc8b8c793..0000000000 --- a/pkg/exporter/syslogexporter/exporter.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "context" - "crypto/tls" - "fmt" - "time" - - "go.opentelemetry.io/collector/consumer/consumererror" - "go.opentelemetry.io/collector/exporter" - "go.opentelemetry.io/collector/exporter/exporterhelper" - "go.opentelemetry.io/collector/pdata/pcommon" - "go.opentelemetry.io/collector/pdata/plog" - "go.uber.org/multierr" - "go.uber.org/zap" -) - -type syslogexporter struct { - config *Config - logger *zap.Logger - tlsConfig *tls.Config -} - -func initExporter(cfg *Config, createSettings exporter.Settings) (*syslogexporter, error) { - tlsConfig, err := cfg.TLSSetting.LoadTLSConfig(context.Background()) - if err != nil { - return nil, err - } - - s := &syslogexporter{ - config: cfg, - logger: createSettings.Logger, - tlsConfig: tlsConfig, - } - - s.logger.Info("Syslog Exporter configured", - zap.String("endpoint", cfg.Endpoint), - zap.String("protocol", cfg.Protocol), - zap.Int("port", cfg.Port), - ) - - return s, nil -} - -func newLogsExporter( - ctx context.Context, - params exporter.Settings, - cfg *Config, -) (exporter.Logs, error) { - s, err := initExporter(cfg, params) - if err != nil { - return nil, fmt.Errorf("failed to initialize the logs exporter: %w", err) - } - - return exporterhelper.NewLogsExporter( - ctx, - params, - cfg, - s.pushLogsData, - exporterhelper.WithTimeout(exporterhelper.TimeoutSettings{Timeout: 0}), - exporterhelper.WithRetry(cfg.BackOffConfig), - exporterhelper.WithQueue(cfg.QueueSettings), - ) -} - -func (se *syslogexporter) logsToMap(record plog.LogRecord) map[string]any { - attributes := record.Attributes().AsRaw() - return attributes -} - -func (se *syslogexporter) getTimestamp(record plog.LogRecord) time.Time { - timestamp := record.Timestamp().AsTime() - return timestamp -} - -func (se *syslogexporter) pushLogsData(ctx context.Context, ld plog.Logs) error { - type droppedResourceRecords struct { - resource pcommon.Resource - records []plog.LogRecord - } - var ( - errs []error - dropped []droppedResourceRecords - ) - rls := ld.ResourceLogs() - for i := 0; i < rls.Len(); i++ { - rl := rls.At(i) - if droppedRecords, err := se.sendSyslogs(rl); err != nil { - dropped = append(dropped, droppedResourceRecords{ - resource: rl.Resource(), - records: droppedRecords, - }) - errs = append(errs, err) - } - } - if len(dropped) > 0 { - ld = plog.NewLogs() - for i := range dropped { - rls := ld.ResourceLogs().AppendEmpty() - logRecords := rls.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty() - dropped[i].resource.CopyTo(rls.Resource()) - for j := 0; j < len(dropped[i].records); j++ { - dropped[i].records[j].CopyTo(logRecords) - } - } - errs = deduplicateErrors(errs) - return consumererror.NewLogs(multierr.Combine(errs...), ld) - } - se.logger.Info("Connected successfully, exporting logs....") - return nil -} - -func (se *syslogexporter) sendSyslogs(rl plog.ResourceLogs) ([]plog.LogRecord, error) { - var ( - errs []error - droppedRecords []plog.LogRecord - ) - slgs := rl.ScopeLogs() - for i := 0; i < slgs.Len(); i++ { - slg := slgs.At(i) - for j := 0; j < slg.LogRecords().Len(); j++ { - lr := slg.LogRecords().At(j) - formattedLine := se.logsToMap(lr) - timestamp := se.getTimestamp(lr) - s, errConn := Connect(se.logger, se.config, se.tlsConfig) - if errConn != nil { - droppedRecords = append(droppedRecords, lr) - errs = append(errs, errConn) - continue - } - defer s.Close() - err := s.Write(formattedLine, timestamp) - if err != nil { - droppedRecords = append(droppedRecords, lr) - errs = append(errs, err) - } - } - } - return droppedRecords, multierr.Combine(errs...) -} diff --git a/pkg/exporter/syslogexporter/exporter_test.go b/pkg/exporter/syslogexporter/exporter_test.go deleted file mode 100644 index 52641a82ee..0000000000 --- a/pkg/exporter/syslogexporter/exporter_test.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "context" - "errors" - "io" - "net" - "strconv" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/consumer/consumererror" - "go.opentelemetry.io/collector/exporter" - "go.opentelemetry.io/collector/pdata/pcommon" - "go.opentelemetry.io/collector/pdata/plog" - "go.uber.org/zap" -) - -var expectedForm = "<165>1 2003-08-24T12:14:15Z 192.0.2.1 myproc 8710 - - It's time to make the do-nuts.\n" -var originalForm = "<165>1 2003-08-24T05:14:15-07:00 192.0.2.1 myproc 8710 - - It's time to make the do-nuts." - -type exporterTest struct { - srv net.TCPListener - exp *syslogexporter -} - -func exampleLog(t *testing.T) plog.LogRecord { - buffer := plog.NewLogRecord() - buffer.Body().SetStr(originalForm) - timestamp := "2003-08-24T05:14:15-07:00" - timeStr, err := time.Parse(time.RFC3339, timestamp) - require.NoError(t, err, "failed to start test syslog server") - ts := pcommon.NewTimestampFromTime(timeStr) - buffer.SetTimestamp(ts) - attrMap := map[string]any{"proc_id": "8710", "message": "It's time to make the do-nuts.", - "appname": "myproc", "hostname": "192.0.2.1", "priority": int64(165), - "version": int64(1)} - for k, v := range attrMap { - if _, ok := v.(string); ok { - buffer.Attributes().PutStr(k, v.(string)) - } else { - buffer.Attributes().PutInt(k, v.(int64)) - } - } - return buffer -} - -func LogRecordsToLogs(record plog.LogRecord) plog.Logs { - logs := plog.NewLogs() - logsSlice := logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords() - ls := logsSlice.AppendEmpty() - record.CopyTo(ls) - return logs -} - -func createExporterCreateSettings() exporter.Settings { - return exporter.Settings{ - TelemetrySettings: component.TelemetrySettings{ - Logger: zap.NewNop(), - }, - } -} - -func TestInitExporter(t *testing.T) { - _, err := initExporter(&Config{Endpoint: "test.com", - Protocol: "tcp", - Port: 514, - Format: "rfc5424"}, createExporterCreateSettings()) - assert.NoError(t, err) -} - -func buildValidExporter(t *testing.T, server net.TCPListener, cfg *Config) (*syslogexporter, error) { - var port string - var err error - hostPort := server.Addr().String() - cfg.Endpoint, port, err = net.SplitHostPort(hostPort) - require.NoError(t, err, "could not parse port") - cfg.Port, err = strconv.Atoi(port) - require.NoError(t, err, "type error") - exp, err := initExporter(cfg, createExporterCreateSettings()) - require.NoError(t, err) - return exp, err -} - -func buildInvalidExporter(t *testing.T, server net.TCPListener, cfg *Config) (*syslogexporter, error) { - var port string - var err error - hostPort := server.Addr().String() - cfg.Endpoint, port, err = net.SplitHostPort(hostPort) - require.NoError(t, err, "could not parse endpoint") - require.NotNil(t, port) - invalidPort := "112" // Assign invalid port - cfg.Port, err = strconv.Atoi(invalidPort) - require.NoError(t, err, "type error") - exp, err := initExporter(cfg, createExporterCreateSettings()) - require.NoError(t, err) - return exp, err -} - -func createServer() (net.TCPListener, error) { - var addr net.TCPAddr - addr.IP = net.IP{127, 0, 0, 1} - addr.Port = 0 - testServer, err := net.ListenTCP("tcp", &addr) - return *testServer, err -} - -func prepareExporterTest(t *testing.T, cfg *Config, invalidExporter bool) *exporterTest { - // Start a test syslog server - var err error - testServer, err := createServer() - require.NoError(t, err, "failed to start test syslog server") - var exp *syslogexporter - if invalidExporter { - exp, err = buildInvalidExporter(t, testServer, cfg) - } else { - exp, err = buildValidExporter(t, testServer, cfg) - } - require.NoError(t, err, "Error building exporter") - require.NotNil(t, exp) - return &exporterTest{ - srv: testServer, - exp: exp, - } - -} - -func createTestConfig() *Config { - config := createDefaultConfig().(*Config) - config.Protocol = "tcp" - config.TLSSetting.Insecure = true - return config -} - -func TestSyslogExportSuccess(t *testing.T) { - test := prepareExporterTest(t, createTestConfig(), false) - require.NotNil(t, test.exp) - defer test.srv.Close() - go func() { - buffer := exampleLog(t) - logs := LogRecordsToLogs(buffer) - err := test.exp.pushLogsData(context.Background(), logs) - require.NoError(t, err, "could not send message") - }() - err := test.srv.SetDeadline(time.Now().Add(time.Second * 1)) - require.NoError(t, err, "cannot set deadline") - conn, err := test.srv.AcceptTCP() - require.NoError(t, err, "could not accept connection") - defer conn.Close() - b, err := io.ReadAll(conn) - require.NoError(t, err, "could not read all") - assert.Equal(t, string(b), expectedForm) -} - -func TestSyslogExportFail(t *testing.T) { - test := prepareExporterTest(t, createTestConfig(), true) - defer test.srv.Close() - buffer := exampleLog(t) - logs := LogRecordsToLogs(buffer) - consumerErr := test.exp.pushLogsData(context.Background(), logs) - var consumerErrorLogs consumererror.Logs - ok := errors.As(consumerErr, &consumerErrorLogs) - assert.Equal(t, ok, true) - consumerLogs := consumererror.Logs.Data(consumerErrorLogs) - rls := consumerLogs.ResourceLogs() - require.Equal(t, 1, rls.Len()) - scl := rls.At(0).ScopeLogs() - require.Equal(t, 1, scl.Len()) - lrs := scl.At(0).LogRecords() - require.Equal(t, 1, lrs.Len()) - droppedLog := lrs.At(0).Body().AsString() - err := test.srv.SetDeadline(time.Now().Add(time.Second * 1)) - require.NoError(t, err, "cannot set deadline") - conn, err := test.srv.AcceptTCP() - require.ErrorContains(t, err, "i/o timeout") - require.Nil(t, conn) - assert.ErrorContains(t, consumerErr, "dial tcp 127.0.0.1:112: connect") - assert.Equal(t, droppedLog, originalForm) -} diff --git a/pkg/exporter/syslogexporter/factory.go b/pkg/exporter/syslogexporter/factory.go deleted file mode 100644 index 294dde5862..0000000000 --- a/pkg/exporter/syslogexporter/factory.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "context" - "fmt" - - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configretry" - "go.opentelemetry.io/collector/exporter" - "go.opentelemetry.io/collector/exporter/exporterhelper" -) - -const ( - // The value of "type" key in configuration. - typeStr = "syslog" - stabilityLevel = component.StabilityLevelDeprecated -) - -var Type = component.MustNewType(typeStr) - -// NewFactory returns a new factory for the syslog exporter. -func NewFactory() exporter.Factory { - return exporter.NewFactory( - Type, - createDefaultConfig, - exporter.WithLogs(createLogsExporter, stabilityLevel), - ) -} - -func createDefaultConfig() component.Config { - qs := exporterhelper.NewDefaultQueueSettings() - qs.Enabled = false - - return &Config{ - Endpoint: DefaultEndpoint, - Port: DefaultPort, - Format: DefaultFormat, - Protocol: DefaultProtocol, - BackOffConfig: configretry.NewDefaultBackOffConfig(), - QueueSettings: qs, - } -} - -func createLogsExporter( - ctx context.Context, - params exporter.Settings, - cfg component.Config, -) (exporter.Logs, error) { - exp, err := newLogsExporter(ctx, params, cfg.(*Config)) - if err != nil { - return nil, fmt.Errorf("failed to create the logs exporter: %w", err) - } - - return exp, nil -} diff --git a/pkg/exporter/syslogexporter/factory_test.go b/pkg/exporter/syslogexporter/factory_test.go deleted file mode 100644 index 6fb145b2f7..0000000000 --- a/pkg/exporter/syslogexporter/factory_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "testing" - "time" - - "github.com/cenkalti/backoff/v4" - "github.com/stretchr/testify/assert" - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/config/configretry" - "go.opentelemetry.io/collector/exporter/exporterhelper" -) - -func TestType(t *testing.T) { - factory := NewFactory() - pType := factory.Type() - assert.Equal(t, pType, Type) -} - -func TestCreateDefaultConfig(t *testing.T) { - cfg := createDefaultConfig() - - assert.Equal(t, cfg, &Config{ - Endpoint: "host.domain.com", - Port: 514, - Protocol: "tcp", - Format: "rfc5424", - QueueSettings: exporterhelper.QueueSettings{ - Enabled: false, - NumConsumers: 10, - QueueSize: 1000, - }, - BackOffConfig: configretry.BackOffConfig{ - Enabled: true, - InitialInterval: 5 * time.Second, - RandomizationFactor: backoff.DefaultRandomizationFactor, - Multiplier: backoff.DefaultMultiplier, - MaxInterval: 30 * time.Second, - MaxElapsedTime: 5 * time.Minute, - }, - }) - assert.NoError(t, component.ValidateConfig(cfg)) -} diff --git a/pkg/exporter/syslogexporter/go.mod b/pkg/exporter/syslogexporter/go.mod deleted file mode 100644 index e684e40c4c..0000000000 --- a/pkg/exporter/syslogexporter/go.mod +++ /dev/null @@ -1,54 +0,0 @@ -module github.com/SumoLogic/sumologic-otel-collector/pkg/exporter/syslogexporter - -go 1.22.0 - -toolchain go1.22.8 - -require ( - github.com/stretchr/testify v1.9.0 - go.opentelemetry.io/collector/component v0.114.0 - go.opentelemetry.io/collector/config/configretry v1.20.0 - go.opentelemetry.io/collector/config/configtls v1.12.0 - go.opentelemetry.io/collector/consumer/consumererror v0.114.0 - go.opentelemetry.io/collector/exporter v0.114.0 - go.opentelemetry.io/collector/pdata v1.20.0 - go.uber.org/zap v1.27.0 -) - -require ( - github.com/PuerkitoBio/purell v1.2.0 // indirect - github.com/fsnotify/fsnotify v1.7.0 // indirect - github.com/go-logr/logr v1.4.2 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/google/uuid v1.6.0 // indirect - go.opentelemetry.io/collector/config/configopaque v1.12.0 // indirect - go.opentelemetry.io/collector/config/configtelemetry v0.114.0 // indirect - go.opentelemetry.io/collector/extension v0.114.0 // indirect - go.opentelemetry.io/collector/extension/experimental/storage v0.114.0 // indirect - go.opentelemetry.io/collector/pdata/pprofile v0.114.0 // indirect - go.opentelemetry.io/collector/pipeline v0.114.0 // indirect - go.opentelemetry.io/otel/sdk v1.32.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240822170219-fc7c04adadcd // indirect -) - -require ( - github.com/THREATINT/go-net v1.2.23 - github.com/cenkalti/backoff/v4 v4.3.0 - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/gogo/protobuf v1.3.2 // 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 - github.com/pmezard/go-difflib v1.0.0 // indirect - go.opentelemetry.io/collector/consumer v0.114.0 // indirect - go.opentelemetry.io/otel v1.32.0 // indirect - go.opentelemetry.io/otel/metric v1.32.0 // indirect - go.opentelemetry.io/otel/trace v1.32.0 // indirect - go.uber.org/multierr v1.11.0 - golang.org/x/net v0.28.0 // indirect - golang.org/x/sys v0.27.0 // indirect - golang.org/x/text v0.17.0 // indirect - google.golang.org/grpc v1.67.1 // indirect - google.golang.org/protobuf v1.35.1 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect -) diff --git a/pkg/exporter/syslogexporter/go.sum b/pkg/exporter/syslogexporter/go.sum deleted file mode 100644 index 7972b4d389..0000000000 --- a/pkg/exporter/syslogexporter/go.sum +++ /dev/null @@ -1,150 +0,0 @@ -github.com/PuerkitoBio/purell v1.2.0 h1:/Jdm5QfyM8zdlqT6WVZU4cfP23sot6CEHA4CS49Ezig= -github.com/PuerkitoBio/purell v1.2.0/go.mod h1:OhLRTaaIzhvIyofkJfB24gokC7tM42Px5UhoT32THBk= -github.com/THREATINT/go-net v1.2.23 h1:mAyZiHhzugEXXQUCcX6CxUz1z/GvR3OFZhTnDa+UPzk= -github.com/THREATINT/go-net v1.2.23/go.mod h1:q63ju+fM11y3JwlQkRRpyrZhv3DoXQw2djKjt7Iy2/c= -github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= -github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= -github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -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/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -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= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= -github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -go.opentelemetry.io/collector/component v0.114.0 h1:SVGbm5LvHGSTEDv7p92oPuBgK5tuiWR82I9+LL4TtBE= -go.opentelemetry.io/collector/component v0.114.0/go.mod h1:MLxtjZ6UVHjDxSdhGLuJfHBHvfl1iT/Y7IaQPD24Eww= -go.opentelemetry.io/collector/component/componenttest v0.114.0 h1:GM4FTTlfeXoVm6sZYBHImwlRN8ayh2oAfUhvaFj7Zo8= -go.opentelemetry.io/collector/component/componenttest v0.114.0/go.mod h1:ZZEJMtbJtoVC/3/9R1HzERq+cYQRxuMFQrPCpfZ4Xos= -go.opentelemetry.io/collector/config/configopaque v1.12.0 h1:aIsp9NdcLZSiG4YDoFPGXhmma03Tk+6e89+n8GtU/Mc= -go.opentelemetry.io/collector/config/configopaque v1.12.0/go.mod h1:0xURn2sOy5j4fbaocpEYfM97HPGsiffkkVudSPyTJlM= -go.opentelemetry.io/collector/config/configretry v1.20.0 h1:z679mrMlW2a6tOOYPGdrS/QfALxdzWLQUOpH8Uu+D5Y= -go.opentelemetry.io/collector/config/configretry v1.20.0/go.mod h1:KvQF5cfphq1rQm1dKR4eLDNQYw6iI2fY72NMZVa+0N0= -go.opentelemetry.io/collector/config/configtelemetry v0.114.0 h1:kjLeyrumge6wsX6ZIkicdNOlBXaEyW2PI2ZdVXz/rzY= -go.opentelemetry.io/collector/config/configtelemetry v0.114.0/go.mod h1:R0MBUxjSMVMIhljuDHWIygzzJWQyZHXXWIgQNxcFwhc= -go.opentelemetry.io/collector/config/configtls v1.12.0 h1:Px0+GE4LE/9sXMgkwBb5g8QHWvnrnuRg9BLSa+QtxgM= -go.opentelemetry.io/collector/config/configtls v1.12.0/go.mod h1:aeCGPlvrWhc+EySpIKdelPAj4l9wXKzZPouQO3NIoTs= -go.opentelemetry.io/collector/consumer v0.114.0 h1:1zVaHvfIZowGwZRitRBRo3i+RP2StlU+GClYiofSw0Q= -go.opentelemetry.io/collector/consumer v0.114.0/go.mod h1:d+Mrzt9hsH1ub3zmwSlnQVPLeTYir4Mgo7CrWfnncN4= -go.opentelemetry.io/collector/consumer/consumererror v0.114.0 h1:r2YiELfWerb40FHD23V04gNjIkLUcjEKGxI4Vtm2iO4= -go.opentelemetry.io/collector/consumer/consumererror v0.114.0/go.mod h1:MzIrLQ5jptO2egypolhlAbZsWZr29WC4FhSxQjnxcvg= -go.opentelemetry.io/collector/consumer/consumerprofiles v0.114.0 h1:5pXYy3E6UK5Huu3aQbsYL8B6E6MyWx4fvXXDn+oXZaA= -go.opentelemetry.io/collector/consumer/consumerprofiles v0.114.0/go.mod h1:PMq3f54KcJQO4v1tue0QxQScu7REFVADlXxXSAYMiN0= -go.opentelemetry.io/collector/consumer/consumertest v0.114.0 h1:isaTwJK5DOy8Bs7GuLq23ejfgj8gLIo5dOUvkRnLF4g= -go.opentelemetry.io/collector/consumer/consumertest v0.114.0/go.mod h1:GNeLPkfRPdh06n/Rv1UKa/cAtCKjN0a7ADyHjIj4HFE= -go.opentelemetry.io/collector/exporter v0.114.0 h1:5/0BBpXuCJQSQ5SQf31g7j6T4XEKkyx9mZMcA2rS5e8= -go.opentelemetry.io/collector/exporter v0.114.0/go.mod h1:atpd0wWXgh5LAZ0REU/d/Ti/q50HDfnlBIjMjJQlKFg= -go.opentelemetry.io/collector/exporter/exporterprofiles v0.114.0 h1:/wmWOSBHcvtz3Pbv7+rWCqPPQuNvYaoidKKaOqZsLKs= -go.opentelemetry.io/collector/exporter/exporterprofiles v0.114.0/go.mod h1:epRYTkyJZTSQZBJflMGHUyUo2EdLPhsaZEyo5Qm848A= -go.opentelemetry.io/collector/exporter/exportertest v0.114.0 h1:vo0idBJT+QACSM1KpjVLm9VeiXVwO7y4UnMpGxN6EyM= -go.opentelemetry.io/collector/exporter/exportertest v0.114.0/go.mod h1:420ssFrhaphneybstbMeSIiqSRoaBARPgO71O17foaM= -go.opentelemetry.io/collector/extension v0.114.0 h1:9Qb92y8hD2WDC5aMDoj4JNQN+/5BQYJWPUPzLXX+iGw= -go.opentelemetry.io/collector/extension v0.114.0/go.mod h1:Yk2/1ptVgfTr12t+22v93nYJpioP14pURv2YercSzU0= -go.opentelemetry.io/collector/extension/experimental/storage v0.114.0 h1:hLyX9UvmY0t6iBnk3CqvyNck2U0QjPACekj7pDRx2hA= -go.opentelemetry.io/collector/extension/experimental/storage v0.114.0/go.mod h1:WqYRQVJjJLE1rm+y/ks1wPdPRGWePEvE1VO07xm2J2k= -go.opentelemetry.io/collector/extension/extensiontest v0.114.0 h1:ibXDms1qrswlvlR6b3d2BeyI8sXUXoFV11yOi9Sop8o= -go.opentelemetry.io/collector/extension/extensiontest v0.114.0/go.mod h1:/bOYmqu5yTDfI1bJZUxFqm8ZtmcodpquebiSxiQxtDY= -go.opentelemetry.io/collector/pdata v1.20.0 h1:ePcwt4bdtISP0loHaE+C9xYoU2ZkIvWv89Fob16o9SM= -go.opentelemetry.io/collector/pdata v1.20.0/go.mod h1:Ox1YVLe87cZDB/TL30i4SUz1cA5s6AM6SpFMfY61ICs= -go.opentelemetry.io/collector/pdata/pprofile v0.114.0 h1:pUNfTzsI/JUTiE+DScDM4lsrPoxnVNLI2fbTxR/oapo= -go.opentelemetry.io/collector/pdata/pprofile v0.114.0/go.mod h1:4aNcj6WM1n1uXyFSXlhVs4ibrERgNYsTbzcYI2zGhxA= -go.opentelemetry.io/collector/pdata/testdata v0.114.0 h1:+AzszWSL1i4K6meQ8rU0JDDW55SYCXa6FVqfDixhhTo= -go.opentelemetry.io/collector/pdata/testdata v0.114.0/go.mod h1:bv8XFdCTZxG2MQB5l9dKxSxf5zBrcodwO6JOy1+AxXM= -go.opentelemetry.io/collector/pipeline v0.114.0 h1:v3YOhc5z0tD6QbO5n/pnftpIeroihM2ks9Z2yKPCcwY= -go.opentelemetry.io/collector/pipeline v0.114.0/go.mod h1:4vOvjVsoYTHVGTbfFwqfnQOSV2K3RKUHofh3jNRc2Mg= -go.opentelemetry.io/collector/receiver v0.114.0 h1:90SAnXAjNq7/k52/pFmmb06Cf1YauoPYtbio4aOXafY= -go.opentelemetry.io/collector/receiver v0.114.0/go.mod h1:KUGT0/D953LXbGH/D3lLPU8yrU3HfWnUqpt4W4hSOnE= -go.opentelemetry.io/collector/receiver/receiverprofiles v0.114.0 h1:ibhEfGpvNB3yrtpl2jYFabrunMk1hurxvMYpM0b1Ck4= -go.opentelemetry.io/collector/receiver/receiverprofiles v0.114.0/go.mod h1:UZyRfaasw+NLvN10AN8IQnmj5tQ3BOUH1uP2ctpO9f0= -go.opentelemetry.io/collector/receiver/receivertest v0.114.0 h1:D+Kh9t2n4asTnM+TiSxbrKlUemLZandWntj17BJWWb0= -go.opentelemetry.io/collector/receiver/receivertest v0.114.0/go.mod h1:mNSHQ13vFmqD+VAcRzLjStFBejbcWUn2Mp0pAd7Op+U= -go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= -go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= -go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= -go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= -go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4= -go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU= -go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU= -go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ= -go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= -go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= -go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= -go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= -go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= -go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= -golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= -golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= -golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240822170219-fc7c04adadcd h1:6TEm2ZxXoQmFWFlt1vNxvVOa1Q0dXFQD1m/rYjXmS0E= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240822170219-fc7c04adadcd/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU= -google.golang.org/grpc v1.67.1 h1:zWnc1Vrcno+lHZCOofnIMvycFcc0QRGIzm9dhnDX68E= -google.golang.org/grpc v1.67.1/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA= -google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= -google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/pkg/exporter/syslogexporter/syslog.go b/pkg/exporter/syslogexporter/syslog.go deleted file mode 100644 index 0dd0ddeb0a..0000000000 --- a/pkg/exporter/syslogexporter/syslog.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "crypto/tls" - "fmt" - "net" - "strings" - "sync" - "time" - - "go.uber.org/zap" -) - -const defaultPriority = 165 -const defaultFacility = 1 -const versionRFC5424 = 1 - -const formatRFC5424Str = "rfc5424" -const formatRFC3164Str = "rfc3164" - -const priority = "priority" -const facility = "facility" -const version = "version" -const hostname = "hostname" -const app = "appname" -const pid = "proc_id" -const msgID = "msg_id" -const structuredData = "structured_data" -const message = "message" - -const emptyValue = "-" - -type Syslog struct { - network string - addr string - format string - tlsConfig *tls.Config - logger *zap.Logger - mu sync.Mutex - conn net.Conn -} - -func Connect(logger *zap.Logger, cfg *Config, tlsConfig *tls.Config) (*Syslog, error) { - s := &Syslog{ - logger: logger, - network: cfg.Protocol, - addr: fmt.Sprintf("%s:%d", cfg.Endpoint, cfg.Port), - format: cfg.Format, - tlsConfig: tlsConfig, - } - - s.mu.Lock() - defer s.mu.Unlock() - - err := s.connect() - if err != nil { - return nil, err - } - return s, err -} - -func (s *Syslog) Close() error { - s.mu.Lock() - defer s.mu.Unlock() - - if s.conn != nil { - err := s.conn.Close() - s.conn = nil - return err - } - return nil -} - -func (s *Syslog) connect() error { - if s.conn != nil { - s.conn.Close() - s.conn = nil - } - var err error - if s.tlsConfig != nil { - s.conn, err = tls.Dial("tcp", s.addr, s.tlsConfig) - } else { - s.conn, err = net.Dial(s.network, s.addr) - } - return err -} - -func (s *Syslog) Write(msg map[string]any, timestamp time.Time) error { - s.mu.Lock() - defer s.mu.Unlock() - - msgStr := s.formatMsg(msg, timestamp) - - if s.conn != nil { - if err := s.write(msgStr); err == nil { - return nil - } - } - if err := s.connect(); err != nil { - return err - } - - return s.write(msgStr) -} - -func (s *Syslog) write(msg string) error { - // check if logs contains new line character at the end, if not add it - if !strings.HasSuffix(msg, "\n") { - msg = fmt.Sprintf("%s%s", msg, "\n") - } - _, err := fmt.Fprint(s.conn, msg) - return err -} - -func (s *Syslog) formatMsg(msg map[string]any, timestamp time.Time) string { - switch s.format { - case formatRFC3164Str: - return s.formatRFC3164(msg, timestamp) - case formatRFC5424Str: - return s.formatRFC5424(msg, timestamp) - default: - panic(fmt.Sprintf("unsupported syslog format, format: %s", s.format)) - } -} - -func (s *Syslog) addStructuredData(msg map[string]any) { - if s.format != formatRFC5424Str { - return - } - - sd, ok := msg[structuredData].(map[string]map[string]string) - if !ok { - msg[structuredData] = emptyValue - } else { - sdElements := []string{} - for key, val := range sd { - sdElements = append(sdElements, key) - for k, v := range val { - sdElements = append(sdElements, fmt.Sprintf("%s=\"%s\"", k, v)) - } - } - msg[structuredData] = sdElements - } -} - -func populateDefaults(msg map[string]any, msgProperties []string) { - - for _, msgProperty := range msgProperties { - msgValue, ok := msg[msgProperty] - if !ok && msgProperty == priority { - msg[msgProperty] = defaultPriority - return - } - if !ok && msgProperty == version { - msg[msgProperty] = versionRFC5424 - return - } - if !ok && msgProperty == facility { - msg[msgProperty] = defaultFacility - return - } - if !ok { - msg[msgProperty] = emptyValue - return - } - msg[msgProperty] = msgValue - } -} - -func (s *Syslog) formatRFC3164(msg map[string]any, timestamp time.Time) string { - msgProperties := []string{priority, hostname, message} - populateDefaults(msg, msgProperties) - timestampString := timestamp.Format("2006-01-02T15:04:05.000-03:00") - return fmt.Sprintf("<%d>%s %s %s", msg[priority], timestampString, msg[hostname], msg[message]) -} - -func (s *Syslog) formatRFC5424(msg map[string]any, timestamp time.Time) string { - msgProperties := []string{priority, version, hostname, app, pid, msgID, message, structuredData} - populateDefaults(msg, msgProperties) - s.addStructuredData(msg) - timestampString := timestamp.Format(time.RFC3339) - return fmt.Sprintf("<%d>%d %s %s %s %s %s %s %s", msg[priority], msg[version], timestampString, msg[hostname], msg[app], msg[pid], msg[msgID], msg[structuredData], msg[message]) -} diff --git a/pkg/exporter/syslogexporter/syslog_test.go b/pkg/exporter/syslogexporter/syslog_test.go deleted file mode 100644 index 528ac6d2b1..0000000000 --- a/pkg/exporter/syslogexporter/syslog_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "fmt" - "regexp" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestFormatRFC5424(t *testing.T) { - - s := Syslog{format: formatRFC5424Str} - - msg := map[string]any{"timestamp": "2003-08-24T05:14:15.000003-07:00", "appname": "myproc", "facility": 20, - "hostname": "192.0.2.1", "log.file.name": "syslog", "message": "It's time to make the do-nuts.", "priority": 165, - "proc_id": "8710", "version": 1} - expected := "<165>1 2003-08-24T05:14:15-07:00 192.0.2.1 myproc 8710 - - It's time to make the do-nuts." - timeObj1, err := time.Parse(time.RFC3339, "2003-08-24T05:14:15.000003-07:00") - assert.Equal(t, expected, s.formatRFC5424(msg, timeObj1)) - assert.Nil(t, err) - - msg2 := map[string]any{"timestamp": "2003-10-11T22:14:15.003Z", "appname": "evntslog", "facility": 20, - "hostname": "mymachine.example.com", "log.file.name": "syslog", "message": "BOMAn application event log entry...", - "msg_id": "ID47", "priority": 165, "proc_id": "111", "version": 1} - - expected2 := "<165>1 2003-10-11T22:14:15Z mymachine.example.com evntslog 111 ID47 - BOMAn application event log entry..." - timeObj2, err := time.Parse(time.RFC3339, "2003-10-11T22:14:15.003Z") - assert.Nil(t, err) - assert.Equal(t, expected2, s.formatRFC5424(msg2, timeObj2)) - - msg3 := map[string]any{"timestamp": "2003-08-24T05:14:15.000003-07:00", "appname": "myproc", "facility": 20, - "hostname": "192.0.2.1", "log.file.name": "syslog", "message": "It's time to make the do-nuts.", - "priority": 165, "proc_id": "8710", "version": 1, - "structured_data": map[string]map[string]string{"SecureAuth@27389": { - "PEN": "27389", - "Realm": "SecureAuth0", - "UserHostAddress": "192.168.2.132", - "UserID": "Tester2", - }, - }, - } - - expectedForm := "\\<165\\>1 2003-08-24T05:14:15-07:00 192\\.0\\.2\\.1 myproc 8710 - " + - "\\[\\S+ \\S+ \\S+ \\S+ \\S+\\] It's time to make the do-nuts\\." - timeObj3, err := time.Parse(time.RFC3339, "2003-08-24T05:14:15.000003-07:00") - assert.Nil(t, err) - formattedMsg := s.formatRFC5424(msg3, timeObj3) - matched, err := regexp.MatchString(expectedForm, formattedMsg) - assert.Nil(t, err) - assert.Equal(t, true, matched, fmt.Sprintf("unexpected form of formatted message, formatted message: %s, regexp: %s", formattedMsg, expectedForm)) - assert.Equal(t, true, strings.Contains(formattedMsg, "Realm=\"SecureAuth0\"")) - assert.Equal(t, true, strings.Contains(formattedMsg, "UserHostAddress=\"192.168.2.132\"")) - assert.Equal(t, true, strings.Contains(formattedMsg, "UserID=\"Tester2\"")) - assert.Equal(t, true, strings.Contains(formattedMsg, "PEN=\"27389\"")) -} diff --git a/pkg/exporter/syslogexporter/utils.go b/pkg/exporter/syslogexporter/utils.go deleted file mode 100644 index c2fa675db8..0000000000 --- a/pkg/exporter/syslogexporter/utils.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import "fmt" - -type errorWithCount struct { - err error - count int -} - -// deduplicateErrors replaces duplicate instances of the same error in a slice -// with a single error containing the number of times it occurred added as a suffix. -// For example, three occurrences of "error: 502 Bad Gateway" -// are replaced with a single instance of "error: 502 Bad Gateway (x3)". -func deduplicateErrors(errs []error) []error { - if len(errs) < 2 { - return errs - } - errorsWithCounts := []errorWithCount{} - for _, err := range errs { - found := false - for i := range errorsWithCounts { - if errorsWithCounts[i].err.Error() == err.Error() { - found = true - errorsWithCounts[i].count++ - break - } - } - if !found { - errorsWithCounts = append(errorsWithCounts, errorWithCount{ - err: err, - count: 1, - }) - } - } - var uniqueErrors []error - for _, errorWithCount := range errorsWithCounts { - if errorWithCount.count == 1 { - uniqueErrors = append(uniqueErrors, errorWithCount.err) - } else { - uniqueErrors = append(uniqueErrors, fmt.Errorf("%w (x%d)", errorWithCount.err, errorWithCount.count)) - } - } - return uniqueErrors -} - -func errorListToStringSlice(errList []error) []string { - errStrList := make([]string, len(errList)) - for i, err := range errList { - errStrList[i] = err.Error() - } - return errStrList -} diff --git a/pkg/exporter/syslogexporter/utils_test.go b/pkg/exporter/syslogexporter/utils_test.go deleted file mode 100644 index 85ecee3781..0000000000 --- a/pkg/exporter/syslogexporter/utils_test.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2023, OpenTelemetry 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 syslogexporter - -import ( - "errors" - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestDeduplicateErrors(t *testing.T) { - testCases := []struct { - name string - errs []error - expected []error - }{ - { - name: "nil is returned as nil", - errs: nil, - expected: nil, - }, - { - name: "single error is returned as-is", - errs: []error{ - errors.New("Single error"), - }, - expected: []error{ - errors.New("Single error"), - }, - }, - { - name: "duplicates are removed", - errs: []error{ - errors.New("failed sending data: 502 Bad Gateway"), - errors.New("dial tcp 127.0.0.1:514: connect: connection refused"), - errors.New("failed sending data: 502 Bad Gateway"), - errors.New("dial tcp 127.0.0.1:514: connect: connection refused"), - errors.New("dial tcp 127.0.0.1:514: connect: connection refused"), - errors.New("dial tcp 127.0.0.1:514: connect: connection refused"), - errors.New("failed sending data: 504 Gateway Timeout"), - errors.New("failed sending data: 502 Bad Gateway"), - }, - expected: []error{ - fmt.Errorf("%w (x3)", errors.New("failed sending data: 502 Bad Gateway")), - fmt.Errorf("%w (x4)", errors.New("dial tcp 127.0.0.1:514: connect: connection refused")), - errors.New("failed sending data: 504 Gateway Timeout"), - }, - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - assert.Equal(t, testCase.expected, deduplicateErrors(testCase.errs)) - }) - } -} - -func TestErrorString(t *testing.T) { - testCases := []struct { - name string - errs []error - expected []string - }{ - { - name: "duplicates are removed", - errs: []error{ - errors.New("failed sending data: 502 Bad Gateway"), - errors.New("dial tcp 127.0.0.1:514: connect: connection refused"), - }, - expected: []string{"failed sending data: 502 Bad Gateway", - "dial tcp 127.0.0.1:514: connect: connection refused"}, - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - assert.Equal(t, testCase.expected, errorListToStringSlice(testCase.errs)) - }) - } -}