-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugins.go
100 lines (86 loc) · 1.74 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
package plugins
import (
"errors"
"sync"
"github.com/Sirupsen/logrus"
)
var (
ErrNotImplements = errors.New("Plugin does not implement the requested driver")
)
type plugins struct {
sync.Mutex
plugins map[string]*Plugin
}
var (
storage = plugins{plugins: make(map[string]*Plugin)}
extpointHandlers = make(map[string]func(string, *Client))
)
type Manifest struct {
Implements []string
}
type Plugin struct {
Name string
Addr string
Client *Client
Manifest *Manifest
}
func (p *Plugin) activate() error {
m := new(Manifest)
p.Client = NewClient(p.Addr)
err := p.Client.Call("Plugin.Activate", nil, m)
if err != nil {
return err
}
logrus.Debugf("%s's manifest: %v", p.Name, m)
p.Manifest = m
for _, iface := range m.Implements {
handler, handled := extpointHandlers[iface]
if !handled {
continue
}
handler(p.Name, p.Client)
}
return nil
}
func load(name string) (*Plugin, error) {
registry := newLocalRegistry("")
pl, err := registry.Plugin(name)
if err != nil {
return nil, err
}
if err := pl.activate(); err != nil {
return nil, err
}
return pl, nil
}
func get(name string) (*Plugin, error) {
storage.Lock()
defer storage.Unlock()
pl, ok := storage.plugins[name]
if ok {
return pl, nil
}
pl, err := load(name)
if err != nil {
return nil, err
}
logrus.Debugf("Plugin: %v", pl)
storage.plugins[name] = pl
return pl, nil
}
func Get(name, imp string) (*Plugin, error) {
pl, err := get(name)
if err != nil {
return nil, err
}
for _, driver := range pl.Manifest.Implements {
logrus.Debugf("%s implements: %s", name, driver)
if driver == imp {
return pl, nil
}
}
return nil, ErrNotImplements
}
func Handle(iface string, fn func(string, *Client)) {
extpointHandlers[iface] = fn
}