-
Notifications
You must be signed in to change notification settings - Fork 927
/
plugins.go
75 lines (61 loc) · 1.57 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
package common
import (
"github.com/sirupsen/logrus"
"sync"
)
var (
Plugins []Plugin
)
// Plugin represents a plugin, all plugins needs to implement this at a bare minimum
type Plugin interface {
Name() string
}
type PluginWithLogging interface {
Logger() *logrus.Entry
SetLogger(entry *logrus.Entry)
}
// RegisterPlugin registers a plugin, should be called when the bot is starting up
func RegisterPlugin(plugin Plugin) {
Plugins = append(Plugins, plugin)
if cast, ok := plugin.(PluginWithLogging); ok {
cast.SetLogger(logrus.WithField("P", plugin.Name()))
}
}
// RegisterPluginL registers a plugin, should be called when the bot is starting up
func RegisterPluginL(pl Plugin) {
if _, ok := pl.(PluginWithLogging); !ok {
logrus.Fatal("Not a PluginWithLogging: ", pl.Name())
}
RegisterPlugin(pl)
}
type BasePlugin struct {
Entry *logrus.Entry
}
var _ PluginWithLogging = (*BasePlugin)(nil)
func (p *BasePlugin) Logger() *logrus.Entry {
return p.Entry
}
func (p *BasePlugin) SetLogger(entry *logrus.Entry) {
p.Entry = entry
}
type BackgroundWorkerPlugin interface {
RunBackgroundWorker()
StopBackgroundWorker(wg *sync.WaitGroup)
}
func RunBackgroundWorkers() {
for _, p := range Plugins {
if bwc, ok := p.(BackgroundWorkerPlugin); ok {
logrus.Info("Running background worker: ", p.Name())
go bwc.RunBackgroundWorker()
}
}
}
func StopBackgroundWorkers(wg *sync.WaitGroup) {
for _, p := range Plugins {
if bwc, ok := p.(BackgroundWorkerPlugin); ok {
logrus.Info("Stopping background worker: ", p.Name())
wg.Add(1)
go bwc.StopBackgroundWorker(wg)
}
}
}