Debian Codegraph @

testscript/plugin/plugin.go

raw symbols SCIP
1 package plugin
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "os"
8 "os/exec"
9 "sync"
10 "time"
11
12 "github.com/rogpeppe/go-internal/testscript"
13 )
14
15 // Setup registers the "plugin" command into p so that test scripts can use
16 // plugins. Plugins are discovered, started and queried lazily the first time
17 // a script runs "plugin <name>".
18 //
19 // The returned cleanup function must be called when the whole test run has
20 // finished; it shuts down any plugin processes that were started. Because
21 // [testscript.Run] runs scripts as parallel subtests that execute after the
22 // calling test function returns, the cleanup function must be registered with
23 // t.Cleanup rather than deferred: a deferred call would run before the scripts
24 // (and the plugin processes they start) had finished, leaving processes alive.
25 func Setup(p *testscript.Params) (cleanup func(), err error) {
26 ps := &plugins{
27 started: make(map[string]*startedPlugin),
28 }
29 if p.Cmds == nil {
30 p.Cmds = make(map[string]func(ts *testscript.TestScript, neg bool, args []string))
31 }
32 p.Cmds["plugin"] = ps.cmdPlugin
33 return ps.close, nil
34 }
35
36 type plugins struct {
37 // mu guards the fields below it.
38 mu sync.Mutex
39 started map[string]*startedPlugin
40 }
41
42 type startedPlugin struct {
43 client Interface
44 info PluginInfo
45 proc *procConn
46 }
47
48 func (ps *plugins) close() {
49 ps.mu.Lock()
50 defer ps.mu.Unlock()
51 for _, sp := range ps.started {
52 sp.client.Close()
53 }
54 ps.started = make(map[string]*startedPlugin)
55 }
56
57 // get returns the started plugin with the given name, starting it on first
58 // use.
59 func (ps *plugins) get(name string) (*startedPlugin, error) {
60 ps.mu.Lock()
61 defer ps.mu.Unlock()
62 if sp := ps.started[name]; sp != nil {
63 return sp, nil
64 }
65 exe := "testscript-plugin-" + name
66 path, err := exec.LookPath(exe)
67 if err != nil {
68 return nil, fmt.Errorf("cannot find plugin executable %q: %v", exe, err)
69 }
70 conn, err := startProcess(path)
71 if err != nil {
72 return nil, fmt.Errorf("cannot start plugin %q: %v", name, err)
73 }
74 client, err := NewClient(conn)
75 if err != nil {
76 return nil, fmt.Errorf("cannot start plugin %q: %v", name, err)
77 }
78 sp := &startedPlugin{
79 client: client,
80 info: client.Info(),
81 proc: conn,
82 }
83 ps.started[name] = sp
84 return sp, nil
85 }
86
87 // startProcess starts the plugin executable at path and returns a connection
88 // to it: data written to the connection goes to the process's standard input,
89 // data read comes from its standard output, and its standard error is captured
90 // so it can be reported through the log of whichever test is interacting with
91 // the plugin. Closing the connection shuts the process down.
92 func startProcess(path string) (*procConn, error) {
93 cmd := exec.Command(path)
94 w, err := cmd.StdinPipe()
95 if err != nil {
96 return nil, err
97 }
98 r, err := cmd.StdoutPipe()
99 if err != nil {
100 return nil, err
101 }
102 stderr := new(lockedBuffer)
103 cmd.Stderr = stderr
104 if err := cmd.Start(); err != nil {
105 return nil, err
106 }
107 return &procConn{cmd: cmd, r: r, w: w, stderr: stderr}, nil
108 }
109
110 // procConn is the connection to a plugin subprocess, presenting its
111 // stdin/stdout as an [io.ReadWriteCloser].
112 type procConn struct {
113 cmd *exec.Cmd
114 r io.ReadCloser
115 w io.WriteCloser
116 stderr *lockedBuffer
117 }
118
119 func (p *procConn) Read(b []byte) (int, error) { return p.r.Read(b) }
120 func (p *procConn) Write(b []byte) (int, error) { return p.w.Write(b) }
121
122 // Close shuts the process down: closing its standard input signals the plugin
123 // server loop to exit; if it does not exit promptly it is killed.
124 func (p *procConn) Close() error {
125 p.w.Close()
126 done := make(chan struct{})
127 go func() {
128 p.cmd.Wait()
129 close(done)
130 }()
131 select {
132 case <-done:
133 case <-time.After(5 * time.Second):
134 p.cmd.Process.Kill()
135 <-done
136 }
137 p.r.Close()
138 // The process has exited, so its standard error is fully captured. Any
139 // output not already reported through a test's log (for example a crash
140 // during shutdown, which belongs to no test) is written to the host's
141 // standard error as a last resort so it is not lost.
142 if out := p.stderr.drain(); out != "" {
143 fmt.Fprintf(os.Stderr, "plugin stderr: %s", out)
144 }
145 return nil
146 }
147
148 // cmdPlugin implements the "plugin <name> [<dir>]" command. It creates a
149 // per-test instance of the named plugin, applies the environment variables it
150 // provides, and registers the commands it provides for the current test.
151 func (ps *plugins) cmdPlugin(ts *testscript.TestScript, neg bool, args []string) {
152 if neg {
153 ts.Fatalf("plugin command does not support negation")
154 }
155 if len(args) < 1 || len(args) > 2 {
156 ts.Fatalf("usage: plugin <name> [<dir>]")
157 }
158 name := args[0]
159 sp, err := ps.get(name)
160 if err != nil {
161 ts.Fatalf("%v", err)
162 }
163
164 env := resolveEnv(ts, sp.info.RequiredEnv)
165 dir := ""
166 if len(args) > 1 {
167 dir = ts.MkAbs(args[1])
168 }
169 inst, err := sp.client.NewTestInstance(TestParams{
170 TestName: ts.Name(),
171 PluginParamsDir: dir,
172 Env: env,
173 })
174 logPluginStderr(ts, name, sp)
175 if err != nil {
176 ts.Fatalf("cannot create instance of plugin %q: %v", name, err)
177 }
178 ts.Defer(inst.Close)
179
180 ps.applyEnv(ts, name, sp.info, inst.Env())
181 for cmdName := range sp.info.Cmds {
182 ts.SetCmd(cmdName, ps.makeCmd(name, sp, cmdName, inst))
183 }
184 }
185
186 // makeCmd returns the testscript command implementation for a command
187 // provided by a plugin.
188 func (ps *plugins) makeCmd(name string, sp *startedPlugin, cmdName string, inst TestInstance) func(*testscript.TestScript, bool, []string) {
189 cmdInfo := sp.info.Cmds[cmdName]
190 return func(ts *testscript.TestScript, neg bool, args []string) {
191 env := resolveEnv(ts, cmdInfo.RequiredEnv)
192 res, err := inst.RunCmd(CmdParams{
193 Name: cmdName,
194 Args: args,
195 Dir: ts.MkAbs("."),
196 Env: env,
197 })
198 logPluginStderr(ts, name, sp)
199 if err != nil {
200 // A plugin/transport failure is fatal regardless of negation.
201 ts.Fatalf("plugin %q failed to run command %q: %v", name, cmdName, err)
202 }
203 if cmdInfo.WritesOutput {
204 ts.Stdout().Write(res.Stdout)
205 ts.Stderr().Write(res.Stderr)
206 }
207 ps.applyEnv(ts, name, sp.info, res.Env)
208
209 if res.Err != "" {
210 ts.Logf("[%v]\n", res.Err)
211 if !neg {
212 ts.Fatalf("unexpected command failure")
213 }
214 } else if neg {
215 ts.Fatalf("unexpected command success")
216 }
217 }
218 }
219
220 // applyEnv sets the environment variables provided by a plugin, rejecting any
221 // that the plugin did not declare in its ResultEnv.
222 func (ps *plugins) applyEnv(ts *testscript.TestScript, name string, info PluginInfo, env map[string]string) {
223 for k, v := range env {
224 if !info.ResultEnv[k] {
225 ts.Fatalf("plugin %q tried to set undeclared environment variable %q", name, k)
226 }
227 ts.Setenv(k, v)
228 }
229 }
230
231 // resolveEnv returns the values of the requested environment variables in the
232 // test environment.
233 func resolveEnv(ts *testscript.TestScript, required map[string]bool) map[string]string {
234 env := make(map[string]string)
235 for varName := range required {
236 env[varName] = ts.Getenv(varName)
237 }
238 return env
239 }
240
241 // logPluginStderr reports any output the plugin process has written to its
242 // standard error since the last call, attributing it to the given test's log.
243 // Because a single plugin process is shared by all tests using it, this is
244 // best-effort: output is surfaced through whichever test next interacts with
245 // the plugin, but it keeps the output within the test framework rather than
246 // letting it interleave on the host's standard error.
247 func logPluginStderr(ts *testscript.TestScript, name string, sp *startedPlugin) {
248 if out := sp.proc.stderr.drain(); out != "" {
249 ts.Logf("plugin %q stderr: %s", name, out)
250 }
251 }
252
253 // lockedBuffer is an [io.Writer], safe for concurrent use, that accumulates
254 // writes until drained. It captures a plugin process's standard error so it
255 // can be reported through a test's log.
256 //
257 // mu guards the fields below it.
258 type lockedBuffer struct {
259 mu sync.Mutex
260 buf bytes.Buffer
261 }
262
263 func (b *lockedBuffer) Write(p []byte) (int, error) {
264 b.mu.Lock()
265 defer b.mu.Unlock()
266 return b.buf.Write(p)
267 }
268
269 // drain returns any data accumulated since the last call and resets the buffer.
270 func (b *lockedBuffer) drain() string {
271 b.mu.Lock()
272 defer b.mu.Unlock()
273 s := b.buf.String()
274 b.buf.Reset()
275 return s
276 }