-
Notifications
You must be signed in to change notification settings - Fork 200
/
loader.go
253 lines (213 loc) · 6.57 KB
/
loader.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
package pluggable
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"time"
"get.porter.sh/porter/pkg/config"
"get.porter.sh/porter/pkg/plugins"
hclog "github.com/hashicorp/go-hclog"
plugin "github.com/hashicorp/go-plugin"
"github.com/pkg/errors"
)
// PluginLoader handles finding, configuring and loading porter plugins.
type PluginLoader struct {
*config.Config
SelectedPluginKey *plugins.PluginKey
SelectedPluginConfig interface{}
}
func NewPluginLoader(c *config.Config) *PluginLoader {
return &PluginLoader{
Config: c,
}
}
// Load a plugin, returning the plugin's interface which the caller must then cast to
// the typed interface, a cleanup function to stop the plugin when finished communicating with it,
// and an error if the plugin could not be loaded.
func (l *PluginLoader) Load(pluginType PluginTypeConfig) (interface{}, func(), error) {
err := l.selectPlugin(pluginType)
if err != nil {
return nil, nil, err
}
l.SelectedPluginKey.Interface = pluginType.Interface
var pluginCommand *exec.Cmd
if l.SelectedPluginKey.IsInternal {
porterPath, err := l.GetPorterPath()
if err != nil {
return nil, nil, errors.Wrap(err, "could not determine the path to the porter client")
}
pluginCommand = l.NewCommand(porterPath, "plugin", "run", l.SelectedPluginKey.String())
} else {
pluginPath, err := l.GetPluginPath(l.SelectedPluginKey.Binary)
if err != nil {
return nil, nil, err
}
pluginCommand = l.NewCommand(pluginPath, "run", l.SelectedPluginKey.String())
}
configReader, err := l.readPluginConfig()
if err != nil {
return nil, nil, err
}
pluginCommand.Stdin = configReader
// Explicitly set PORTER_HOME for the plugin
pluginCommand.Env = l.Environ()
if l.DebugPlugins {
fmt.Fprintf(l.Err, "Resolved %s plugin to %s\n", pluginType.Interface, l.SelectedPluginKey)
if l.SelectedPluginConfig != nil {
fmt.Fprintf(l.Err, "Resolved plugin config: \n %#v\n", l.SelectedPluginConfig)
}
fmt.Fprintln(l.Err, strings.Join(pluginCommand.Args, " "))
}
pluginOutput := bytes.NewBufferString("")
logger := hclog.New(&hclog.LoggerOptions{
Name: "porter",
Output: pluginOutput,
Level: hclog.Debug,
JSONFormat: true,
})
if l.DebugPlugins {
logger.SetLevel(hclog.Info)
go l.logPluginMessages(pluginOutput)
}
pluginTypes := map[string]plugin.Plugin{
pluginType.Interface: pluginType.Plugin,
}
var errbuf bytes.Buffer
client := plugin.NewClient(&plugin.ClientConfig{
HandshakeConfig: plugins.HandshakeConfig,
Plugins: pluginTypes,
Cmd: pluginCommand,
Logger: logger,
Stderr: &errbuf,
})
cleanup := func() {
client.Kill()
}
// Connect via RPC
rpcClient, err := client.Client()
if err != nil {
cleanup()
if stderr := errbuf.String(); stderr != "" {
err = errors.Wrap(errors.New(stderr), err.Error())
}
return nil, nil, errors.Wrapf(err, "could not connect to the %s plugin", l.SelectedPluginKey)
}
cleanup, err = l.setUpDebugger(client, cleanup)
if err != nil {
return nil, nil, errors.Wrap(err, "could not set up debugger for plugin")
}
// Request the plugin
raw, err := rpcClient.Dispense(pluginType.Interface)
if err != nil {
cleanup()
return nil, nil, errors.Wrapf(err, "could not connect to the %s plugin", l.SelectedPluginKey)
}
return raw, cleanup, nil
}
func (l *PluginLoader) setUpDebugger(client *plugin.Client, cleanup func()) (func(), error) {
debugContext := l.Context.PlugInDebugContext
if len(debugContext.RunPlugInInDebugger) > 0 && strings.ToLower(l.SelectedPluginKey.String()) == strings.TrimSpace(strings.ToLower(debugContext.RunPlugInInDebugger)) {
if !isDelveInstalled() {
return cleanup, errors.New("Delve needs to be installed to debug plugins")
}
listen := fmt.Sprintf("--listen=127.0.0.1:%s", debugContext.DebuggerPort)
if len(debugContext.PlugInWorkingDirectory) == 0 {
return cleanup, errors.New("Plugin Working Directory is required for debugging")
}
wd := fmt.Sprintf("--wd=%s", debugContext.PlugInWorkingDirectory)
pid := client.ReattachConfig().Pid
dlvCmd := exec.Command("dlv", "attach", strconv.Itoa(pid), "--headless=true", "--api-version=2", "--log", listen, "--accept-multiclient", wd)
dlvCmd.Stderr = os.Stderr
dlvCmd.Stdout = os.Stdout
err := dlvCmd.Start()
if err != nil {
return cleanup, errors.Wrap(err, "Error starting dlv")
}
dlvCmdTerminated := make(chan error)
go func() {
dlvCmdTerminated <- dlvCmd.Wait()
}()
// dlv attach does not fail immediately but is common (e.g. if plugin is compiled with ldflags that prevent debugging)
// so pause here to make sure that it has attached correctly and not failed
time.Sleep(2 * time.Second)
select {
case err = <-dlvCmdTerminated:
return cleanup, errors.Wrap(err, "dlv exited unexpectedly")
default:
}
newcleanup := func() {
if dlvCmd.Process != nil {
select {
case err = <-dlvCmdTerminated:
default:
_ = dlvCmd.Process.Kill()
}
}
cleanup()
}
return newcleanup, nil
}
return cleanup, nil
}
func (l *PluginLoader) logPluginMessages(pluginOutput io.Reader) {
r := bufio.NewReader(pluginOutput)
for {
line, err := r.ReadString('\n')
if err != nil {
continue
}
if line == "" {
return
}
var pluginLog map[string]interface{}
err = json.Unmarshal([]byte(line), &pluginLog)
if err != nil {
// plaintext log
fmt.Fprintln(l.Err, line)
} else {
// print just the message from the json log
fmt.Fprintln(l.Err, pluginLog["@message"])
}
}
}
// selectPlugin picks the plugin to use and loads its configuration.
func (l *PluginLoader) selectPlugin(cfg PluginTypeConfig) error {
l.SelectedPluginKey = nil
l.SelectedPluginConfig = nil
var pluginKey string
defaultStore := cfg.GetDefaultPluggable(l.Config.Data)
if defaultStore != "" {
is, err := cfg.GetPluggable(l.Config.Data, defaultStore)
if err != nil {
return err
}
pluginKey = is.GetPluginSubKey()
l.SelectedPluginConfig = is.GetConfig()
}
// If there isn't a specific plugin configured for this plugin type, fall back to the default plugin for this type
if pluginKey == "" {
pluginKey = cfg.GetDefaultPlugin(l.Config.Data)
}
key, err := plugins.ParsePluginKey(pluginKey)
if err != nil {
return err
}
l.SelectedPluginKey = &key
return nil
}
func (l *PluginLoader) readPluginConfig() (io.Reader, error) {
if l.SelectedPluginConfig == nil {
return &bytes.Buffer{}, nil
}
b, err := json.Marshal(l.SelectedPluginConfig)
if err != nil {
return nil, errors.Wrapf(err, "could not marshal plugin config %#v", l.SelectedPluginConfig)
}
return bytes.NewBuffer(b), nil
}