plugins: cleanup sockets when done

Since 509123f935, we've been leaking sockets
in the filesystem on platforms where abstract sockets aren't supported.

That change relied on Go to cleanup our sockets for us, which Go will happily
do as long as we make sure to close the listener, which we weren't previously
doing unless to signal the plugin to terminate.

This change adds a deferred call to `PluginServer.Close()`, which makes sure we
close the plugin server at the end of the plugin execution, so that we never exit
without cleaning up.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
This commit is contained in:
Laura Brehm 2024-06-11 18:01:56 +01:00
parent 591bd17424
commit 3dcc653533
No known key found for this signature in database
GPG Key ID: CFBF847B4A313468
2 changed files with 13 additions and 0 deletions

View File

@ -9,6 +9,8 @@ import (
"os"
"runtime"
"sync"
"github.com/sirupsen/logrus"
)
// EnvKey represents the well-known environment variable used to pass the
@ -30,6 +32,7 @@ func NewPluginServer(h func(net.Conn)) (*PluginServer, error) {
if err != nil {
return nil, err
}
logrus.Trace("Plugin server listening on ", l.Addr())
if h == nil {
h = func(net.Conn) {}
@ -92,6 +95,7 @@ func (pl *PluginServer) Addr() net.Addr {
//
// The error value is that of the underlying [net.Listner.Close] call.
func (pl *PluginServer) Close() error {
logrus.Trace("Closing plugin server")
// Close connections first to ensure the connections get io.EOF instead
// of a connection reset.
pl.closeAllConns()
@ -107,6 +111,10 @@ func (pl *PluginServer) closeAllConns() {
pl.mu.Lock()
defer pl.mu.Unlock()
if pl.closed {
return
}
// Prevent new connections from being accepted.
pl.closed = true

View File

@ -245,6 +245,11 @@ func tryPluginRun(ctx context.Context, dockerCli command.Cli, cmd *cobra.Command
if err == nil {
plugincmd.Env = append(plugincmd.Env, socket.EnvKey+"="+srv.Addr().String())
}
defer func() {
// Close the server when plugin execution is over, so that in case
// it's still open, any sockets on the filesystem are cleaned up.
_ = srv.Close()
}()
// Set additional environment variables specified by the caller.
plugincmd.Env = append(plugincmd.Env, envs...)