Debian Codegraph @

filter/config.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package filter // import "go.opentelemetry.io/collector/filter"
5
6 import (
7 "errors"
8 "regexp"
9 )
10
11 // Config configures the matching behavior of a Filter.
12 type Config struct {
13 Strict string `mapstructure:"strict"`
14 Regex string `mapstructure:"regexp"`
15 // prevent unkeyed literal initialization
16 _ struct{}
17 }
18
19 func (c Config) Validate() error {
20 if c.Strict == "" && c.Regex == "" {
21 return errors.New("must specify either strict or regex")
22 }
23 if c.Strict != "" && c.Regex != "" {
24 return errors.New("strict and regex cannot be used together")
25 }
26
27 if c.Regex != "" {
28 _, err := regexp.Compile(c.Regex)
29 if err != nil {
30 return err
31 }
32 }
33
34 return nil
35 }
36
37 type combinedFilter struct {
38 stricts map[any]struct{}
39 regexes []*regexp.Regexp
40 }
41
42 // CreateFilter creates a Filter out of a set of Config configuration objects.
43 func CreateFilter(configs []Config) Filter {
44 cf := &combinedFilter{
45 stricts: make(map[any]struct{}),
46 }
47 for _, config := range configs {
48 if config.Strict != "" {
49 cf.stricts[config.Strict] = struct{}{}
50 }
51
52 if config.Regex != "" {
53 // Validate() call above ensures that the regex is valid.
54 re := regexp.MustCompile(config.Regex)
55 cf.regexes = append(cf.regexes, re)
56 }
57 }
58 return cf
59 }
60
61 func (cf *combinedFilter) Matches(toMatch any) bool {
62 _, ok := cf.stricts[toMatch]
63 if ok {
64 return ok
65 }
66 if str, ok := toMatch.(string); ok {
67 for _, re := range cf.regexes {
68 if re.MatchString(str) {
69 return true
70 }
71 }
72 }
73 return false
74 }