-
Notifications
You must be signed in to change notification settings - Fork 8
/
plugins.go
107 lines (83 loc) · 2.53 KB
/
plugins.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
107
package main
import (
"github.com/myzhan/goreplay-udp/input"
"github.com/myzhan/goreplay-udp/output"
"io"
"reflect"
"strings"
"sync"
)
// InOutPlugins struct for holding references to plugins
type InOutPlugins struct {
Inputs []io.Reader
Outputs []io.Writer
All []interface{}
}
var pluginMu sync.Mutex
// Plugins holds all the plugin objects
var Plugins = new(InOutPlugins)
// extractLimitOptions detects if plugin get called with limiter support
// Returns address and limit
func extractLimitOptions(options string) (string, string) {
split := strings.Split(options, "|")
if len(split) > 1 {
return split[0], split[1]
}
return split[0], ""
}
// Automatically detects type of plugin and initialize it
//
// See this article if curious about reflect stuff below: http://blog.burntsushi.net/type-parametric-functions-golang
func registerPlugin(constructor interface{}, options ...interface{}) {
var path, limit string
vc := reflect.ValueOf(constructor)
// Pre-processing options to make it work with reflect
vo := []reflect.Value{}
for _, oi := range options {
vo = append(vo, reflect.ValueOf(oi))
}
if len(vo) > 0 {
// Removing limit options from path
path, limit = extractLimitOptions(vo[0].String())
// Writing value back without limiter "|" options
vo[0] = reflect.ValueOf(path)
}
// Calling our constructor with list of given options
plugin := vc.Call(vo)[0].Interface()
if limit != "" {
plugin = NewLimiter(plugin, limit)
}
_, isR := plugin.(io.Reader)
_, isW := plugin.(io.Writer)
// Some of the output can be Readers as well because return responses
if isR && !isW {
Plugins.Inputs = append(Plugins.Inputs, plugin.(io.Reader))
}
if isW {
Plugins.Outputs = append(Plugins.Outputs, plugin.(io.Writer))
}
Plugins.All = append(Plugins.All, plugin)
}
// InitPlugins specify and initialize all available plugins
func InitPlugins() {
pluginMu.Lock()
defer pluginMu.Unlock()
if Settings.outputStdout {
registerPlugin(output.NewStdOutput)
}
if Settings.outputNull {
registerPlugin(output.NewNullOutput)
}
for _, options := range Settings.inputUDP {
registerPlugin(input.NewUDPInput, options, Settings.inputUDPTrackResponse)
}
for _, options := range Settings.inputFile {
registerPlugin(input.NewFileInput, options, Settings.inputFileLoop)
}
for _, options := range Settings.outputFile {
registerPlugin(output.NewFileOutput, options, &Settings.outputFileConfig)
}
for _, options := range Settings.outputUDP {
registerPlugin(output.NewUDPOutput, options, &Settings.outputUDPConfig)
}
}