-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.go
More file actions
222 lines (189 loc) · 4.68 KB
/
Copy pathplugin.go
File metadata and controls
222 lines (189 loc) · 4.68 KB
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
package simplestdioplugin
import (
"context"
"errors"
"fmt"
"os"
"path"
"strings"
"sync"
"time"
)
type execPluginInput struct {
location string
logger func(string)
router map[string]func(data []byte) ([]byte, error)
args []string
}
type StartPluginConfig struct {
// BaseDir is base location to look for plugin
BaseDir string
// Extension is plugin file extension
Extension string
// LogFunc is function that is used to log plugin debug message, keep nil to disable
LogFunc func(string)
// Router is functions that can be called from plugin side
Router map[string]func(data []byte) ([]byte, error)
}
type PluginMap struct {
Map *sync.Map
}
// GetPluginNames list available plugins name
func (mapped *PluginMap) GetPluginNames() []string {
result := []string{}
mapped.Map.Range(func(key, value any) bool {
data, ok := value.(*PluginRunning)
if ok {
result = append(result, data.Name)
}
return true
})
return result
}
// GetPluginByName returns plugin instance by name
func (mapped *PluginMap) GetPluginByName(plugin_name string) (*PluginRunning, error) {
val, ok := mapped.Map.Load(plugin_name)
if !ok {
return nil, errors.New("plugin not found")
}
result, ok := val.(*PluginRunning)
if !ok {
return nil, errors.New("plugin not found")
}
return result, nil
}
func findPluginPath(base_location string, extension string) ([]string, error) {
dirs, err := os.ReadDir(base_location)
if err != nil {
return nil, err
}
result := []string{}
for _, val := range dirs {
if !val.IsDir() && strings.Contains(val.Name(), "."+extension) {
result = append(result, path.Join(base_location, val.Name()))
}
}
return result, nil
}
func pluginRoutine(ctx context.Context, config StartPluginConfig, plugin_map *PluginMap, args ...string) error {
if config.LogFunc == nil {
config.LogFunc = func(message string) {}
}
locations, err := findPluginPath(config.BaseDir, config.Extension)
if err != nil {
return err
}
go func() {
for {
select {
case <-ctx.Done():
return
default:
plugin_map.Map.Range(func(key, value any) bool {
p, ok := value.(*PluginRunning)
if ok {
if p.cmd.ProcessState != nil {
_ = execPlugin(ctx, plugin_map.Map, execPluginInput{
location: p.Path,
logger: p.log_func,
router: p.router,
args: p.cmd.Args,
})
} else {
p.heartbeat_c <- struct{}{}
}
}
return true
})
time.Sleep(3 * time.Second)
}
}
}()
for _, val := range locations {
if err := execPlugin(ctx, plugin_map.Map, execPluginInput{
location: val,
logger: config.LogFunc,
router: config.Router,
args: args,
}); err != nil {
return err
}
}
return nil
}
func execPlugin(ctx context.Context, syncMap *sync.Map, input execPluginInput) error {
name := path.Base(input.location)
cmd := commandContext(ctx, input.location, input.args...)
pr1, pw1, err := os.Pipe()
if err != nil {
return err
}
pr2, pw2, err := os.Pipe()
if err != nil {
return err
}
pr3, pw3, err := os.Pipe()
if err != nil {
return err
}
cmd.Stdin = pr1
cmd.Stdout = pw2
cmd.Stderr = pw3
if err := cmd.Start(); err != nil {
return err
}
plugin_running := &PluginRunning{
Name: name,
Path: input.location,
log_func: input.logger,
router: input.router,
resp_mutex: sync.RWMutex{},
resp_map: make(map[string]chan ReadResult),
req_c: make(chan ReadResult),
heartbeat_c: make(chan struct{}),
cmd: cmd,
pipe_in: pw1,
pipe_out: pr2,
pipe_err: pr3,
}
input.logger(fmt.Sprintf("started plugin %s (%s) pid: %d", name, input.location, cmd.Process.Pid))
go func() {
if err := plugin_running.runner(ctx); err != nil {
input.logger(fmt.Sprintf("plugin runner %s exited: %s", name, err.Error()))
}
}()
go func() {
if err := plugin_running.reader(ctx); err != nil {
input.logger(fmt.Sprintf("plugin reader %s exited: %s", name, err.Error()))
}
}()
go func() {
if err := plugin_running.stderr(ctx); err != nil {
input.logger(err.Error())
}
}()
go func() {
if err := cmd.Wait(); err != nil {
input.logger(fmt.Sprintf("plugin %s exited: %s", name, err.Error()))
}
// cleanup
pr1.Close()
pw1.Close()
pr2.Close()
pw2.Close()
pr3.Close()
pw3.Close()
close(plugin_running.req_c)
close(plugin_running.heartbeat_c)
}()
syncMap.Store(name, plugin_running)
return nil
}
// StartPlugin search for available plugins and runs it
func StartPlugin(ctx context.Context, config StartPluginConfig, args ...string) (*PluginMap, error) {
plugin_map := &PluginMap{Map: &sync.Map{}}
if err := pluginRoutine(ctx, config, plugin_map, args...); err != nil {
return nil, err
}
return plugin_map, nil
}