forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
namespace.go
106 lines (86 loc) · 2.04 KB
/
namespace.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package processors
import (
"errors"
"fmt"
"strings"
"github.com/elastic/beats/libbeat/common"
)
type Namespace struct {
reg map[string]pluginer
}
type plugin struct {
c Constructor
}
type pluginer interface {
Plugin() Constructor
}
func NewNamespace() *Namespace {
return &Namespace{
reg: map[string]pluginer{},
}
}
func (ns *Namespace) Register(name string, factory Constructor) error {
p := plugin{NewConditional(factory)}
names := strings.Split(name, ".")
if err := ns.add(names, p); err != nil {
return fmt.Errorf("plugin %s registration fail %v", name, err)
}
return nil
}
func (ns *Namespace) add(names []string, p pluginer) error {
name := names[0]
// register plugin if intermediate node in path being processed
if len(names) == 1 {
if _, found := ns.reg[name]; found {
return errors.New("exists already")
}
ns.reg[name] = p
return nil
}
// check if namespace path already exists
tmp, found := ns.reg[name]
if found {
ns, ok := tmp.(*Namespace)
if !ok {
return errors.New("non-namespace plugin already registered")
}
return ns.add(names[1:], p)
}
// register new namespace
sub := NewNamespace()
err := sub.add(names[1:], p)
if err != nil {
return err
}
ns.reg[name] = sub
return nil
}
func (ns *Namespace) Plugin() Constructor {
return NewConditional(func(cfg common.Config) (Processor, error) {
var section string
for _, name := range cfg.GetFields() {
if name == "when" { // TODO: remove check for "when" once fields are filtered
continue
}
if section != "" {
return nil, fmt.Errorf("Too many lookup modules configured (%v, %v)",
section, name)
}
section = name
}
if section == "" {
return nil, errors.New("No lookup module configured")
}
backend, found := ns.reg[section]
if !found {
return nil, fmt.Errorf("Unknown lookup module: %v", section)
}
config, err := cfg.Child(section, -1)
if err != nil {
return nil, err
}
constructor := backend.Plugin()
return constructor(*config)
})
}
func (p plugin) Plugin() Constructor { return p.c }