2023-04-10 15:36:59 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2019-09-03 15:43:38 +00:00
|
|
|
package allocrunner
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-04-02 00:24:02 +00:00
|
|
|
"errors"
|
2019-09-03 15:43:38 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2022-04-02 00:24:02 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
2019-09-03 15:43:38 +00:00
|
|
|
"github.com/hashicorp/nomad/client/allocdir"
|
|
|
|
"github.com/hashicorp/nomad/client/allocrunner/interfaces"
|
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
|
|
|
"github.com/hashicorp/nomad/nomad/structs/config"
|
|
|
|
)
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
const (
|
|
|
|
consulGRPCSockHookName = "consul_grpc_socket"
|
2020-07-29 14:25:29 +00:00
|
|
|
|
|
|
|
// socketProxyStopWaitTime is the amount of time to wait for a socket proxy
|
|
|
|
// to stop before assuming something went awry and return a timeout error.
|
|
|
|
socketProxyStopWaitTime = 3 * time.Second
|
2022-11-21 15:19:09 +00:00
|
|
|
|
|
|
|
// consulGRPCFallbackPort is the last resort fallback port to use in
|
|
|
|
// combination with the Consul HTTP config address when creating the
|
|
|
|
// socket.
|
|
|
|
consulGRPCFallbackPort = "8502"
|
2020-07-13 21:53:10 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
errSocketProxyTimeout = errors.New("timed out waiting for socket proxy to exit")
|
|
|
|
)
|
2019-09-03 15:43:38 +00:00
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
// consulGRPCSocketHook creates Unix sockets to allow communication from inside a
|
|
|
|
// netns to Consul gRPC endpoint.
|
|
|
|
//
|
2023-01-30 14:48:43 +00:00
|
|
|
// Noop for allocations without a group Connect block using bridge networking.
|
2020-07-13 21:53:10 +00:00
|
|
|
type consulGRPCSocketHook struct {
|
|
|
|
logger hclog.Logger
|
2019-09-03 15:43:38 +00:00
|
|
|
|
2020-07-29 14:14:24 +00:00
|
|
|
// mu synchronizes proxy and alloc which may be mutated and read concurrently
|
|
|
|
// via Prerun, Update, Postrun.
|
|
|
|
mu sync.Mutex
|
|
|
|
alloc *structs.Allocation
|
|
|
|
proxy *grpcSocketProxy
|
2019-09-03 15:43:38 +00:00
|
|
|
}
|
|
|
|
|
2022-11-21 15:19:09 +00:00
|
|
|
func newConsulGRPCSocketHook(
|
|
|
|
logger hclog.Logger, alloc *structs.Allocation, allocDir *allocdir.AllocDir,
|
|
|
|
config *config.ConsulConfig, nodeAttrs map[string]string) *consulGRPCSocketHook {
|
|
|
|
|
|
|
|
// Attempt to find the gRPC port via the node attributes, otherwise use the
|
|
|
|
// default fallback.
|
|
|
|
consulGRPCPort, ok := nodeAttrs["consul.grpc"]
|
|
|
|
if !ok {
|
|
|
|
consulGRPCPort = consulGRPCFallbackPort
|
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
return &consulGRPCSocketHook{
|
|
|
|
alloc: alloc,
|
2022-11-21 15:19:09 +00:00
|
|
|
proxy: newGRPCSocketProxy(logger, allocDir, config, consulGRPCPort),
|
2020-07-13 21:53:10 +00:00
|
|
|
logger: logger.Named(consulGRPCSockHookName),
|
2019-09-03 15:43:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
func (*consulGRPCSocketHook) Name() string {
|
|
|
|
return consulGRPCSockHookName
|
2019-09-03 15:43:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// shouldRun returns true if the Unix socket should be created and proxied.
|
|
|
|
// Requires the mutex to be held.
|
2020-07-13 21:53:10 +00:00
|
|
|
func (h *consulGRPCSocketHook) shouldRun() bool {
|
2019-09-03 15:43:38 +00:00
|
|
|
tg := h.alloc.Job.LookupTaskGroup(h.alloc.TaskGroup)
|
2020-07-29 14:11:42 +00:00
|
|
|
|
|
|
|
// we must be in bridge networking and at least one connect sidecar task
|
|
|
|
if !tgFirstNetworkIsBridge(tg) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-09-03 15:43:38 +00:00
|
|
|
for _, s := range tg.Services {
|
2020-07-28 20:12:08 +00:00
|
|
|
if s.Connect.HasSidecar() || s.Connect.IsGateway() {
|
2019-09-03 15:43:38 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
func (h *consulGRPCSocketHook) Prerun() error {
|
2019-09-03 15:43:38 +00:00
|
|
|
h.mu.Lock()
|
|
|
|
defer h.mu.Unlock()
|
|
|
|
|
|
|
|
if !h.shouldRun() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return h.proxy.run(h.alloc)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update creates a gRPC socket file and proxy if there are any Connect
|
|
|
|
// services.
|
2020-07-13 21:53:10 +00:00
|
|
|
func (h *consulGRPCSocketHook) Update(req *interfaces.RunnerUpdateRequest) error {
|
2019-09-03 15:43:38 +00:00
|
|
|
h.mu.Lock()
|
|
|
|
defer h.mu.Unlock()
|
|
|
|
|
|
|
|
h.alloc = req.Alloc
|
|
|
|
|
|
|
|
if !h.shouldRun() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return h.proxy.run(h.alloc)
|
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
func (h *consulGRPCSocketHook) Postrun() error {
|
2019-09-03 15:43:38 +00:00
|
|
|
h.mu.Lock()
|
|
|
|
defer h.mu.Unlock()
|
|
|
|
|
|
|
|
if err := h.proxy.stop(); err != nil {
|
|
|
|
// Only log failures to stop proxies. Worst case scenario is a
|
|
|
|
// small goroutine leak.
|
|
|
|
h.logger.Debug("error stopping Consul proxy", "error", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
type grpcSocketProxy struct {
|
|
|
|
logger hclog.Logger
|
2019-09-03 15:43:38 +00:00
|
|
|
allocDir *allocdir.AllocDir
|
|
|
|
config *config.ConsulConfig
|
|
|
|
|
2022-11-21 15:19:09 +00:00
|
|
|
// consulGRPCFallbackPort is the port to use if the operator did not
|
|
|
|
// specify a gRPC config address.
|
|
|
|
consulGRPCFallbackPort string
|
|
|
|
|
2019-09-03 15:43:38 +00:00
|
|
|
ctx context.Context
|
|
|
|
cancel func()
|
|
|
|
doneCh chan struct{}
|
|
|
|
runOnce bool
|
|
|
|
}
|
|
|
|
|
2022-11-21 15:19:09 +00:00
|
|
|
func newGRPCSocketProxy(
|
|
|
|
logger hclog.Logger, allocDir *allocdir.AllocDir, config *config.ConsulConfig,
|
|
|
|
consulGRPCFallbackPort string) *grpcSocketProxy {
|
|
|
|
|
2019-09-03 15:43:38 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
2020-07-13 21:53:10 +00:00
|
|
|
return &grpcSocketProxy{
|
2022-11-21 15:19:09 +00:00
|
|
|
allocDir: allocDir,
|
|
|
|
config: config,
|
|
|
|
consulGRPCFallbackPort: consulGRPCFallbackPort,
|
|
|
|
ctx: ctx,
|
|
|
|
cancel: cancel,
|
|
|
|
doneCh: make(chan struct{}),
|
|
|
|
logger: logger,
|
2019-09-03 15:43:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// run socket proxy if allocation requires it, it isn't already running, and it
|
|
|
|
// hasn't been told to stop.
|
|
|
|
//
|
|
|
|
// NOT safe for concurrent use.
|
2020-07-13 21:53:10 +00:00
|
|
|
func (p *grpcSocketProxy) run(alloc *structs.Allocation) error {
|
2019-09-03 15:43:38 +00:00
|
|
|
// Only run once.
|
2020-07-13 21:53:10 +00:00
|
|
|
if p.runOnce {
|
2019-09-03 15:43:38 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Only run once. Never restart.
|
|
|
|
select {
|
2020-07-13 21:53:10 +00:00
|
|
|
case <-p.doneCh:
|
|
|
|
p.logger.Trace("socket proxy already shutdown; exiting")
|
2019-09-03 15:43:38 +00:00
|
|
|
return nil
|
2020-07-13 21:53:10 +00:00
|
|
|
case <-p.ctx.Done():
|
|
|
|
p.logger.Trace("socket proxy already done; exiting")
|
2019-09-03 15:43:38 +00:00
|
|
|
return nil
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
// make sure either grpc or http consul address has been configured
|
|
|
|
if p.config.GRPCAddr == "" && p.config.Addr == "" {
|
|
|
|
return errors.New("consul address must be set on nomad client")
|
|
|
|
}
|
|
|
|
|
|
|
|
destAddr := p.config.GRPCAddr
|
2019-09-03 15:43:38 +00:00
|
|
|
if destAddr == "" {
|
|
|
|
// No GRPCAddr defined. Use Addr but replace port with the gRPC
|
|
|
|
// default of 8502.
|
2020-07-13 21:53:10 +00:00
|
|
|
host, _, err := net.SplitHostPort(p.config.Addr)
|
2019-09-03 15:43:38 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error parsing Consul address %q: %v",
|
2020-07-13 21:53:10 +00:00
|
|
|
p.config.Addr, err)
|
2019-09-03 15:43:38 +00:00
|
|
|
}
|
2022-11-21 15:19:09 +00:00
|
|
|
destAddr = net.JoinHostPort(host, p.consulGRPCFallbackPort)
|
2019-09-03 15:43:38 +00:00
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
hostGRPCSocketPath := filepath.Join(p.allocDir.AllocDir, allocdir.AllocGRPCSocket)
|
2019-09-19 18:37:20 +00:00
|
|
|
|
|
|
|
// if the socket already exists we'll try to remove it, but if not then any
|
|
|
|
// other errors will bubble up to the caller here or when we try to listen
|
2020-07-13 21:53:10 +00:00
|
|
|
_, err := os.Stat(hostGRPCSocketPath)
|
2019-09-19 18:37:20 +00:00
|
|
|
if err == nil {
|
2020-07-13 21:53:10 +00:00
|
|
|
err := os.Remove(hostGRPCSocketPath)
|
2019-09-19 18:37:20 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"unable to remove existing unix socket for Consul gRPC endpoint: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
listener, err := net.Listen("unix", hostGRPCSocketPath)
|
2019-09-03 15:43:38 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to create unix socket for Consul gRPC endpoint: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// The gRPC socket should be usable by all users in case a task is
|
|
|
|
// running as an unprivileged user. Unix does not allow setting domain
|
|
|
|
// socket permissions when creating the file, so we must manually call
|
|
|
|
// chmod afterwards.
|
|
|
|
// https://github.com/golang/go/issues/11822
|
2020-07-13 21:53:10 +00:00
|
|
|
if err := os.Chmod(hostGRPCSocketPath, os.ModePerm); err != nil {
|
2019-09-03 15:43:38 +00:00
|
|
|
return fmt.Errorf("unable to set permissions on unix socket for Consul gRPC endpoint: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
2020-07-13 21:53:10 +00:00
|
|
|
proxy(p.ctx, p.logger, destAddr, listener)
|
|
|
|
p.cancel()
|
|
|
|
close(p.doneCh)
|
2019-09-03 15:43:38 +00:00
|
|
|
}()
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
p.runOnce = true
|
2019-09-03 15:43:38 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// stop the proxy and blocks until the proxy has stopped. Returns an error if
|
|
|
|
// the proxy does not exit in a timely fashion.
|
2020-07-13 21:53:10 +00:00
|
|
|
func (p *grpcSocketProxy) stop() error {
|
|
|
|
p.cancel()
|
2019-09-03 15:43:38 +00:00
|
|
|
|
|
|
|
// If proxy was never run, don't wait for anything to shutdown.
|
2020-07-13 21:53:10 +00:00
|
|
|
if !p.runOnce {
|
2019-09-03 15:43:38 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
select {
|
2020-07-13 21:53:10 +00:00
|
|
|
case <-p.doneCh:
|
2019-09-03 15:43:38 +00:00
|
|
|
return nil
|
2020-07-29 14:25:29 +00:00
|
|
|
case <-time.After(socketProxyStopWaitTime):
|
2020-07-13 21:53:10 +00:00
|
|
|
return errSocketProxyTimeout
|
2019-09-03 15:43:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
// Proxy between a listener and destination.
|
|
|
|
func proxy(ctx context.Context, logger hclog.Logger, destAddr string, l net.Listener) {
|
2019-09-03 15:43:38 +00:00
|
|
|
// Wait for all connections to be done before exiting to prevent
|
|
|
|
// goroutine leaks.
|
|
|
|
wg := sync.WaitGroup{}
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
defer func() {
|
|
|
|
// Must cancel context and close listener before waiting
|
|
|
|
cancel()
|
2020-07-13 21:53:10 +00:00
|
|
|
_ = l.Close()
|
2019-09-03 15:43:38 +00:00
|
|
|
wg.Wait()
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Close Accept() when context is cancelled
|
|
|
|
go func() {
|
|
|
|
<-ctx.Done()
|
2020-07-13 21:53:10 +00:00
|
|
|
_ = l.Close()
|
2019-09-03 15:43:38 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
for ctx.Err() == nil {
|
|
|
|
conn, err := l.Accept()
|
|
|
|
if err != nil {
|
|
|
|
if ctx.Err() != nil {
|
|
|
|
// Accept errors during shutdown are to be expected
|
|
|
|
return
|
|
|
|
}
|
2020-07-13 21:53:10 +00:00
|
|
|
logger.Error("error in socket proxy; shutting down proxy", "error", err, "dest", destAddr)
|
2019-09-03 15:43:38 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
2020-07-13 21:53:10 +00:00
|
|
|
proxyConn(ctx, logger, destAddr, conn)
|
2019-09-03 15:43:38 +00:00
|
|
|
}()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// proxyConn proxies between an existing net.Conn and a destination address. If
|
|
|
|
// the destAddr starts with "unix://" it is treated as a path to a unix socket.
|
|
|
|
// Otherwise it is treated as a host for a TCP connection.
|
|
|
|
//
|
|
|
|
// When the context is cancelled proxyConn blocks until all goroutines shutdown
|
|
|
|
// to prevent leaks.
|
|
|
|
func proxyConn(ctx context.Context, logger hclog.Logger, destAddr string, conn net.Conn) {
|
|
|
|
// Close the connection when we're done with it.
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
// Detect unix sockets
|
|
|
|
network := "tcp"
|
|
|
|
const unixPrefix = "unix://"
|
|
|
|
if strings.HasPrefix(destAddr, unixPrefix) {
|
|
|
|
network = "unix"
|
|
|
|
destAddr = destAddr[len(unixPrefix):]
|
|
|
|
}
|
|
|
|
|
|
|
|
dialer := &net.Dialer{}
|
|
|
|
dest, err := dialer.DialContext(ctx, network, destAddr)
|
|
|
|
if err == context.Canceled || err == context.DeadlineExceeded {
|
|
|
|
logger.Trace("proxy exiting gracefully", "error", err, "dest", destAddr,
|
|
|
|
"src_local", conn.LocalAddr(), "src_remote", conn.RemoteAddr())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("error connecting to grpc", "error", err, "dest", destAddr)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for goroutines to exit before exiting to prevent leaking.
|
|
|
|
wg := sync.WaitGroup{}
|
|
|
|
defer wg.Wait()
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
// socket -> consul
|
2019-09-03 15:43:38 +00:00
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
|
|
|
defer cancel()
|
|
|
|
n, err := io.Copy(dest, conn)
|
|
|
|
if ctx.Err() == nil && err != nil {
|
2021-08-05 09:27:35 +00:00
|
|
|
// expect disconnects when proxying http
|
|
|
|
logger.Trace("error message received proxying to Consul",
|
|
|
|
"msg", err, "dest", destAddr, "src_local", conn.LocalAddr(),
|
|
|
|
"src_remote", conn.RemoteAddr(), "bytes", n)
|
2019-09-03 15:43:38 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
logger.Trace("proxy to Consul complete",
|
|
|
|
"src_local", conn.LocalAddr(), "src_remote", conn.RemoteAddr(),
|
|
|
|
"bytes", n,
|
|
|
|
)
|
|
|
|
}()
|
|
|
|
|
2020-07-13 21:53:10 +00:00
|
|
|
// consul -> socket
|
2019-09-03 15:43:38 +00:00
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
|
|
|
defer cancel()
|
|
|
|
n, err := io.Copy(conn, dest)
|
|
|
|
if ctx.Err() == nil && err != nil {
|
2021-08-05 09:27:35 +00:00
|
|
|
logger.Trace("error message received proxying from Consul",
|
|
|
|
"msg", err, "dest", destAddr, "src_local", conn.LocalAddr(),
|
|
|
|
"src_remote", conn.RemoteAddr(), "bytes", n)
|
2019-09-03 15:43:38 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
logger.Trace("proxy from Consul complete",
|
|
|
|
"src_local", conn.LocalAddr(), "src_remote", conn.RemoteAddr(),
|
|
|
|
"bytes", n,
|
|
|
|
)
|
|
|
|
}()
|
|
|
|
|
|
|
|
// When cancelled close connections to break out of copies goroutines.
|
|
|
|
<-ctx.Done()
|
2020-07-13 21:53:10 +00:00
|
|
|
_ = conn.Close()
|
|
|
|
_ = dest.Close()
|
2019-09-03 15:43:38 +00:00
|
|
|
}
|