-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathregistry.go
343 lines (310 loc) · 7.59 KB
/
registry.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package herd
import (
"bufio"
"context"
"fmt"
"net"
"os"
"os/exec"
"os/signal"
"reflect"
"sort"
"strings"
"syscall"
"github.com/hashicorp/go-plugin"
"github.com/seveas/scattergather"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"golang.org/x/crypto/ssh"
)
var availableProviders = make(map[string]func(string) HostProvider)
var magicProviders = make(map[string]func() HostProvider)
func Providers() []string {
ret := []string{}
for k := range availableProviders {
ret = append(ret, k)
}
sort.Strings(ret)
return ret
}
func RegisterProvider(name string, constructor func(string) HostProvider, magic func() HostProvider) {
availableProviders[name] = constructor
if magic != nil {
magicProviders[name] = magic
}
}
type Registry struct {
providers []HostProvider
hosts *HostSet
globPrefixes map[string]func(string, *HostSet) (*HostSet, error)
dataDir string
cacheDir string
magicLoaded bool
}
type HostProvider interface {
Name() string
Prefix() string
ParseViper(v *viper.Viper) error
Load(ctx context.Context, l LoadingMessage) (*HostSet, error)
Equivalent(p HostProvider) bool
}
type HostKeyProvider interface {
LoadHostKeys(ctx context.Context, l LoadingMessage) (map[string][]ssh.PublicKey, error)
}
type DataLoader interface {
SetDataDir(string) error
}
type Cache interface {
Source() HostProvider
Invalidate()
Keep()
SetCacheDir(string)
}
func NewRegistry(dataDir, cacheDir string) *Registry {
return &Registry{
providers: []HostProvider{},
dataDir: dataDir,
cacheDir: cacheDir,
globPrefixes: map[string]func(string, *HostSet) (*HostSet, error){
"file:": fileFilter,
},
}
}
func NewProvider(pname, name string) (HostProvider, error) {
if pname == "" {
return nil, fmt.Errorf("No provider specified")
}
c, ok := availableProviders[pname]
if !ok {
// Try finding a plugin by this name, if we have the provider plugin loaded
if c, ok := availableProviders["plugin"]; ok {
if _, err := exec.LookPath(fmt.Sprintf("herd-provider-%s", name)); err == nil {
return c(name), nil
}
}
return nil, fmt.Errorf("No such provider: %s", pname)
}
return c(name), nil
}
func (r *Registry) LoadMagicProviders() {
for _, fnc := range magicProviders {
if p := fnc(); p != nil {
r.AddMagicProvider(p)
}
}
r.magicLoaded = true
}
func (r *Registry) LoadHostKeys(ctx context.Context, lm LoadingMessage) error {
if r.magicLoaded {
return nil
}
sg := scattergather.New[map[string][]ssh.PublicKey](int64(len(r.providers)))
for _, fnc := range magicProviders {
p := fnc()
if hp, ok := p.(HostKeyProvider); ok {
hp := hp
sg.Run(context.Background(), func() (map[string][]ssh.PublicKey, error) {
return hp.LoadHostKeys(ctx, lm)
})
}
}
allKeys, err := sg.Wait()
if err != nil {
return err
}
r.hosts.addHostKeys(allKeys)
return nil
}
func (r *Registry) LoadProviders(c *viper.Viper) error {
rerr := &MultiError{Subject: "Errors loading providers"}
// And now all the explicitly configured ones
for key := range c.AllSettings() {
ps := c.Sub(key)
pname := ps.GetString("Provider")
if ps.IsSet("Enabled") && !ps.GetBool("Enabled") {
logrus.Debugf("Skipping disabled provider %s", key)
continue
}
p, err := NewProvider(pname, key)
if err != nil {
rerr.Add(fmt.Errorf("Error parsing config for %s: %s", key, err))
} else {
err = p.ParseViper(ps)
if err != nil {
rerr.Add(fmt.Errorf("Error parsing config for %s: %s", key, err))
} else {
r.AddProvider(p)
}
}
}
if rerr.HasErrors() {
return rerr
}
return nil
}
func (r *Registry) AddProvider(p HostProvider) {
logrus.Debugf("Adding provider %s", p.Name())
if c, ok := p.(Cache); ok {
c.SetCacheDir(r.cacheDir)
}
if c, ok := stripCache(p).(DataLoader); ok {
_ = c.SetDataDir(r.dataDir)
}
r.providers = append(r.providers, p)
}
func (r *Registry) AddMagicProvider(p HostProvider) {
sp := stripCache(p)
if c, ok := sp.(DataLoader); ok {
if err := c.SetDataDir(r.dataDir); err != nil {
return
}
}
for _, pr := range r.providers {
pr := stripCache(pr)
if reflect.TypeOf(sp) != reflect.TypeOf(pr) {
continue
}
if sp.Equivalent(pr) {
return
}
}
r.AddProvider(p)
}
func stripCache(p HostProvider) HostProvider {
if c, ok := p.(Cache); ok {
return c.Source()
}
return p
}
func (r *Registry) InvalidateCache() {
for _, p := range r.providers {
if c, ok := p.(Cache); ok {
c.Invalidate()
}
}
}
func (r *Registry) KeepCaches() {
for _, p := range r.providers {
if c, ok := p.(Cache); ok {
c.Keep()
}
}
}
func (r *Registry) LoadHosts(ctx context.Context, lm LoadingMessage) error {
if r.hosts != nil {
return fmt.Errorf("Hosts have already been loaded")
}
ch := make(chan os.Signal, 2)
signal.Notify(ch, os.Interrupt)
go func() {
for sig := range ch {
plugin.CleanupClients()
if sn, ok := sig.(syscall.Signal); ok {
os.Exit(128 + int(sn))
} else {
os.Exit(1)
}
}
}()
defer func() {
plugin.CleanupClients()
signal.Stop(ch)
close(ch)
signal.Reset()
}()
sg := scattergather.New[*HostSet](int64(len(r.providers)))
sg.KeepAllResults(true)
for _, p := range r.providers {
sg.Run(ctx, func() (*HostSet, error) {
hosts, err := p.Load(ctx, lm)
lm(p.Name(), true, err)
if err != nil && hosts == nil {
return hosts, err
}
logrus.Debugf("%d hosts returned from %s", len(hosts.hosts), p.Name())
for _, host := range hosts.hosts {
if p.Prefix() != "" {
host.Attributes = host.Attributes.prefix(p.Prefix())
}
host.Attributes["herd_provider"] = []string{p.Name()}
}
return hosts, err
})
}
hostSets, err := sg.Wait()
r.hosts = MergeHostSets(hostSets)
lm("", true, err)
return err
}
func (r *Registry) Search(hostnameGlob string, attributes MatchAttributes, sampled []string, count int) *HostSet {
ret := r.hosts
for glob, fnc := range r.globPrefixes {
if strings.HasPrefix(hostnameGlob, glob) {
var err error
ret, err = fnc(hostnameGlob[len(glob):], ret)
if err != nil {
logrus.Errorf("Error applying filter %s: %s", glob, err)
ret = &HostSet{}
}
hostnameGlob = "*"
break
}
}
ret = ret.Search(hostnameGlob, attributes)
if len(ret.hosts) == 0 && attributes != nil && len(attributes) == 0 {
if _, err := net.LookupHost(hostnameGlob); err == nil {
ret = &HostSet{hosts: []*Host{NewHost(hostnameGlob, "", HostAttributes{})}}
}
}
if len(sampled) != 0 {
ret.Sort()
ret.Sample(sampled, count)
}
return ret
}
func (r *Registry) AddGlobPrefix(prefix string, fnc func(string, *HostSet) (*HostSet, error)) {
if _, ok := r.globPrefixes[prefix]; ok {
logrus.Warnf("Overwriting glob prefix `%s`", prefix)
}
r.globPrefixes[prefix] = fnc
}
func (r *Registry) GlobPrefixes() []string {
ret := make([]string, 0, len(r.globPrefixes))
for k := range r.globPrefixes {
ret = append(ret, k)
}
return ret
}
func fileFilter(fn string, hs *HostSet) (*HostSet, error) {
seen := make(map[string]bool)
file, err := os.Open(fn)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
seen[strings.TrimSpace(scanner.Text())] = true
}
hs = hs.Filter(func(h *Host) bool {
if _, ok := seen[h.Name]; !ok {
return false
}
delete(seen, h.Name)
return true
})
// We synthesize hosts that were not yet seen in the inventory
for h := range seen {
hs.hosts = append(hs.hosts, NewHost(h, "", HostAttributes{}))
}
return hs, nil
}
func (r *Registry) Settings() (string, map[string]interface{}) {
providers := make([]string, len(r.providers))
for i, p := range r.providers {
providers[i] = p.Name()
}
return "Registry", map[string]interface{}{
"Providers": providers,
}
}