-
Notifications
You must be signed in to change notification settings - Fork 53
/
discovery.go
96 lines (90 loc) · 2.12 KB
/
discovery.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
package plugins
import (
"path/filepath"
"github.com/rancher/opni/pkg/plugins/meta"
"github.com/spf13/afero"
"go.uber.org/zap"
)
type Filter = func(meta.PluginMeta) bool
type DiscoveryConfig struct {
// Directory to search for plugins
Dir string
// Optional filesystem (defaults to os filesystem)
Fs afero.Fs
// Optional filters to allow excluding plugins from discovery
Filters []Filter
// If true, query the plugin for its supported modes. The available modes
// will be stored in the plugin's ExtendedMetadata and can be used in filters.
QueryModes bool
// Optional logger, defaults to no logging
Logger *zap.SugaredLogger
}
func (dc DiscoveryConfig) Discover() []meta.PluginMeta {
if dc.Fs == nil {
dc.Fs = afero.NewOsFs()
}
paths, err := afero.Glob(dc.Fs, filepath.Join(dc.Dir, DefaultPluginGlob))
if err != nil {
panic(err)
}
var result []meta.PluginMeta
PLUGINS:
for _, path := range paths {
f, err := dc.Fs.Open(path)
if err != nil {
if dc.Logger != nil {
dc.Logger.With(
zap.Error(err),
"plugin", path,
).Error("failed to open plugin for reading")
}
continue
}
md, err := meta.ReadFile(f)
if err != nil {
if dc.Logger != nil {
dc.Logger.With(
zap.Error(err),
"plugin", path,
).Error("failed to read plugin metadata")
}
f.Close()
continue
}
f.Close()
if dc.QueryModes {
if dc.Fs != nil {
if _, ok := dc.Fs.(*afero.OsFs); !ok {
panic("cannot query plugin modes with custom filesystem")
}
}
modes, err := meta.QueryPluginModes(md.BinaryPath)
if err != nil {
if dc.Logger != nil {
dc.Logger.With(
zap.Error(err),
"plugin", path,
).Error("failed to query plugin modes")
}
continue
}
if md.ExtendedMetadata == nil {
md.ExtendedMetadata = &meta.ExtendedPluginMeta{}
}
md.ExtendedMetadata.ModeList = modes
}
for i, filter := range dc.Filters {
if !filter(md) {
if dc.Logger != nil {
dc.Logger.With(
"plugin", path,
"filter", i,
).Debug("plugin ignored due to filter")
}
continue PLUGINS
}
}
result = append(result, md)
}
return result
}