forked from trustmaster/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugins.go
103 lines (91 loc) · 2.27 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
package goflow
import (
"fmt"
"io/ioutil"
"path"
"plugin"
"strings"
)
const plugInSuffix = `_goplug.so`
//PlugIn something
type PlugIn interface {
Component
SetParams(params map[string]interface{}) error
GetParams() map[string]interface{}
GetParam(param string) interface{}
}
//PlugInS something
type PlugInS struct {
params map[string]interface{}
persist bool
}
func processForever(c Component) {
for {
c.Process()
}
}
func process(c Component) {
c.Process()
}
func (s *PlugInS) Process() {
if s.persist {
processForever(s)
} else {
process(s)
}
}
func (s *PlugInS) SetParams(params map[string]interface{}) error {
s.params = params
value, ok := params["persist"].(bool)
if ok {
s.persist = value
} else {
s.persist = false
}
return nil
}
func (s *PlugInS) GetParams() map[string]interface{} {
return s.params
}
func (s *PlugInS) GetParam(param string) interface{} {
return s.params[param]
}
// LoadComponents goes through all paths, opens all plugins in those paths
// and loads them into factory
// Plugins are denoted by *_goplug.so, The filename must begin with a capitolized letter
func LoadComponents(paths []string, factory *Factory) ([]string, error) {
var loaded []string
for _, apath := range paths {
//fmt.Println("Loading plugins at", apath)
files, err := ioutil.ReadDir(apath)
if err != nil {
fmt.Printf("Path %s not found, error=%s.", apath, err.Error())
continue
}
for _, file := range files {
if strings.HasSuffix(file.Name(), plugInSuffix) {
plugpath := path.Join(apath, file.Name())
plug, err := plugin.Open(plugpath)
if err != nil {
fmt.Printf("Can't open plugin %s, error=%s.", plugpath, err.Error())
continue
}
//get name from name - _goplug.so and register with contructor
name := strings.TrimSuffix(file.Name(), plugInSuffix)
symbol, err := plug.Lookup(name)
if err != nil {
fmt.Printf("Can't find symbol %s in plugin %s, error=%s.", name, plugpath, err.Error())
continue
}
constructor := symbol.(func() (interface{}, error))
anerr := factory.Register(name, constructor)
if anerr != nil {
fmt.Printf("Failed to register plugin %s, error=%s.", plugpath, err.Error())
continue
}
loaded = append(loaded, name)
}
}
}
return loaded, nil
}