github.com/influxdata/telegraf@v1.30.3/internal/templating/matcher.go (about) 1 package templating 2 3 import ( 4 "strings" 5 ) 6 7 // matcher determines which template should be applied to a given metric 8 // based on a filter tree. 9 type matcher struct { 10 root *node 11 defaultTemplate *Template 12 } 13 14 // newMatcher creates a new matcher. 15 func newMatcher(defaultTemplate *Template) *matcher { 16 return &matcher{ 17 root: &node{}, 18 defaultTemplate: defaultTemplate, 19 } 20 } 21 22 func (m *matcher) addSpec(tmplt templateSpec) error { 23 // Parse out the default tags specific to this template 24 tags := map[string]string{} 25 if tmplt.tagstring != "" { 26 for _, kv := range strings.Split(tmplt.tagstring, ",") { 27 parts := strings.Split(kv, "=") 28 tags[parts[0]] = parts[1] 29 } 30 } 31 32 tmpl, err := NewTemplate(tmplt.separator, tmplt.template, tags) 33 if err != nil { 34 return err 35 } 36 m.add(tmplt.filter, tmpl) 37 return nil 38 } 39 40 // add inserts the template in the filter tree based the given filter 41 func (m *matcher) add(filter string, template *Template) { 42 if filter == "" { 43 m.defaultTemplate = template 44 m.root.separator = template.separator 45 return 46 } 47 m.root.insert(filter, template) 48 } 49 50 // match returns the template that matches the given measurement line. 51 // If no template matches, the default template is returned. 52 func (m *matcher) match(line string) *Template { 53 tmpl := m.root.search(line) 54 if tmpl != nil { 55 return tmpl 56 } 57 return m.defaultTemplate 58 }