Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[chore][fileconsumer] Move file finding and filtering into subpackage #24853

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .chloggen/pkg-stanza-fileconsumer-sort.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: deprecation

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: pkg/stanza

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Deprecate fileconsumer MatchingCriteria in favor of new matcher package

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [24853]

# (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:

# 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: [api]
41 changes: 10 additions & 31 deletions pkg/stanza/fileconsumer/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import (
"fmt"
"time"

"github.com/bmatcuk/doublestar/v4"
"go.opentelemetry.io/collector/featuregate"
"go.uber.org/zap"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/fileconsumer/emit"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/fileconsumer/internal/fingerprint"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/fileconsumer/internal/header"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/fileconsumer/matcher"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/helper"
)
Expand Down Expand Up @@ -58,7 +58,7 @@ func NewConfig() *Config {

// Config is the configuration of a file input operator
type Config struct {
MatchingCriteria `mapstructure:",squash"`
matcher.Criteria `mapstructure:",squash"`
IncludeFileName bool `mapstructure:"include_file_name,omitempty"`
IncludeFilePath bool `mapstructure:"include_file_path,omitempty"`
IncludeFileNameResolved bool `mapstructure:"include_file_name_resolved,omitempty"`
Expand Down Expand Up @@ -140,6 +140,11 @@ func (c Config) buildManager(logger *zap.SugaredLogger, emit emit.Callback, fact
}
}

fileMatcher, err := matcher.New(c.Criteria)
if err != nil {
return nil, err
}

return &Manager{
SugaredLogger: logger.With("component", "fileconsumer"),
cancel: func() {},
Expand All @@ -159,7 +164,7 @@ func (c Config) buildManager(logger *zap.SugaredLogger, emit emit.Callback, fact
encodingConfig: c.Splitter.EncodingConfig,
headerConfig: hCfg,
},
finder: c.MatchingCriteria,
fileMatcher: fileMatcher,
roller: newRoller(),
pollInterval: c.PollInterval,
maxBatchFiles: c.MaxConcurrentFiles / 2,
Expand All @@ -179,34 +184,8 @@ func (c Config) validate() error {
return fmt.Errorf("`header` requires feature gate `%s`", AllowHeaderMetadataParsing.ID())
}

if len(c.Include) == 0 {
return fmt.Errorf("required argument `include` is empty")
}

// Ensure includes can be parsed as globs
for _, include := range c.Include {
_, err := doublestar.PathMatch(include, "matchstring")
if err != nil {
return fmt.Errorf("parse include glob: %w", err)
}
}

// Ensure excludes can be parsed as globs
for _, exclude := range c.Exclude {
_, err := doublestar.PathMatch(exclude, "matchstring")
if err != nil {
return fmt.Errorf("parse exclude glob: %w", err)
}
}

if len(c.OrderingCriteria.SortBy) != 0 && c.OrderingCriteria.Regex == "" {
return fmt.Errorf("`regex` must be specified when `sort_by` is specified")
}

for _, sr := range c.OrderingCriteria.SortBy {
if err := sr.validate(); err != nil {
return err
}
if _, err := matcher.New(c.Criteria); err != nil {
return err
}

if c.MaxLogSize <= 0 {
Expand Down
81 changes: 35 additions & 46 deletions pkg/stanza/fileconsumer/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/featuregate"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/fileconsumer/matcher"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/helper"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/operatortest"
Expand Down Expand Up @@ -163,17 +164,15 @@ func TestUnmarshal(t *testing.T) {
Name: "sort_by_timestamp",
Expect: func() *mockOperatorConfig {
cfg := NewConfig()
cfg.OrderingCriteria.Regex = `err\.[a-zA-Z]\.\d+\.(?P<rotation_time>\d{10})\.log`
cfg.OrderingCriteria.SortBy = []sortRuleImpl{
{
&TimestampSortRule{
baseSortRule: baseSortRule{
SortType: sortTypeTimestamp,
RegexKey: "rotation_time",
Ascending: true,
},
Location: "utc",
Layout: `%Y%m%d%H`,
cfg.OrderingCriteria = matcher.OrderingCriteria{
Regex: `err\.[a-zA-Z]\.\d+\.(?P<rotation_time>\d{10})\.log`,
SortBy: []matcher.Sort{
{
SortType: "timestamp",
RegexKey: "rotation_time",
Ascending: true,
Location: "utc",
Layout: `%Y%m%d%H`,
},
},
}
Expand All @@ -184,14 +183,12 @@ func TestUnmarshal(t *testing.T) {
Name: "sort_by_numeric",
Expect: func() *mockOperatorConfig {
cfg := NewConfig()
cfg.OrderingCriteria.Regex = `err\.(?P<file_num>[a-zA-Z])\.\d+\.\d{10}\.log`
cfg.OrderingCriteria.SortBy = []sortRuleImpl{
{
&NumericSortRule{
baseSortRule: baseSortRule{
SortType: sortTypeNumeric,
RegexKey: "file_num",
},
cfg.OrderingCriteria = matcher.OrderingCriteria{
Regex: `err\.(?P<file_num>[a-zA-Z])\.\d+\.\d{10}\.log`,
SortBy: []matcher.Sort{
{
SortType: "numeric",
RegexKey: "file_num",
},
},
}
Expand Down Expand Up @@ -432,7 +429,6 @@ func TestBuild(t *testing.T) {
func(f *Config) {},
require.NoError,
func(t *testing.T, f *Manager) {
require.Equal(t, f.finder.Include, []string{"/var/log/testpath.*"})
require.Equal(t, f.pollInterval, 10*time.Millisecond)
},
},
Expand Down Expand Up @@ -575,13 +571,11 @@ func TestBuild(t *testing.T) {
{
"BadOrderingCriteriaRegex",
func(f *Config) {
f.OrderingCriteria.SortBy = []sortRuleImpl{
{
&NumericSortRule{
baseSortRule: baseSortRule{
RegexKey: "value",
SortType: sortTypeNumeric,
},
f.OrderingCriteria = matcher.OrderingCriteria{
SortBy: []matcher.Sort{
{
SortType: "numeric",
RegexKey: "value",
},
},
}
Expand All @@ -590,16 +584,14 @@ func TestBuild(t *testing.T) {
nil,
},
{
"BasicOrderingCriteriaTimetsamp",
"OrderingCriteriaTimestampMissingLayout",
func(f *Config) {
f.OrderingCriteria.Regex = ".*"
f.OrderingCriteria.SortBy = []sortRuleImpl{
{
&TimestampSortRule{
baseSortRule: baseSortRule{
RegexKey: "value",
SortType: sortTypeTimestamp,
},
f.OrderingCriteria = matcher.OrderingCriteria{
Regex: ".*",
SortBy: []matcher.Sort{
{
SortType: "timestamp",
RegexKey: "value",
},
},
}
Expand All @@ -610,15 +602,13 @@ func TestBuild(t *testing.T) {
{
"GoodOrderingCriteriaTimestamp",
func(f *Config) {
f.OrderingCriteria.Regex = ".*"
f.OrderingCriteria.SortBy = []sortRuleImpl{
{
&TimestampSortRule{
baseSortRule: baseSortRule{
RegexKey: "value",
SortType: sortTypeTimestamp,
},
Layout: "%Y%m%d%H",
f.OrderingCriteria = matcher.OrderingCriteria{
Regex: ".*",
SortBy: []matcher.Sort{
{
SortType: "timestamp",
RegexKey: "value",
Layout: "%Y%m%d%H",
},
},
}
Expand Down Expand Up @@ -668,7 +658,6 @@ func TestBuildWithSplitFunc(t *testing.T) {
func(f *Config) {},
require.NoError,
func(t *testing.T, f *Manager) {
require.Equal(t, f.finder.Include, []string{"/var/log/testpath.*"})
require.Equal(t, f.pollInterval, 10*time.Millisecond)
},
},
Expand Down
13 changes: 5 additions & 8 deletions pkg/stanza/fileconsumer/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"go.uber.org/zap"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/fileconsumer/internal/fingerprint"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/fileconsumer/matcher"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator"
)

Expand All @@ -31,7 +32,7 @@ type Manager struct {
cancel context.CancelFunc

readerFactory readerFactory
finder MatchingCriteria
fileMatcher *matcher.Matcher
roller roller
persister operator.Persister

Expand All @@ -56,12 +57,8 @@ func (m *Manager) Start(persister operator.Persister) error {
return fmt.Errorf("read known files from database: %w", err)
}

if files, err := m.finder.findFiles(); err != nil {
m.Warnw("error occurred while finding files", "error", err.Error())
} else if len(files) == 0 {
m.Warnw("no files match the configured include patterns",
"include", m.finder.Include,
"exclude", m.finder.Exclude)
if _, err := m.fileMatcher.MatchFiles(); err != nil {
m.Warnw("finding files", "error", err.Error())
}

// Start polling goroutine
Expand Down Expand Up @@ -116,7 +113,7 @@ func (m *Manager) poll(ctx context.Context) {
batchesProcessed := 0

// Get the list of paths on disk
matches, err := m.finder.findFiles()
matches, err := m.fileMatcher.MatchFiles()
if err != nil {
m.Errorf("error finding files: %s", err)
}
Expand Down
Loading