2019-08-12 22:41:39 +00:00
|
|
|
package taskrunner
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2019-12-18 16:23:16 +00:00
|
|
|
"io/ioutil"
|
2019-08-12 22:41:39 +00:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"path/filepath"
|
|
|
|
"time"
|
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
2019-08-12 22:41:39 +00:00
|
|
|
"github.com/hashicorp/nomad/client/allocdir"
|
|
|
|
"github.com/hashicorp/nomad/client/allocrunner/interfaces"
|
|
|
|
agentconsul "github.com/hashicorp/nomad/command/agent/consul"
|
2020-01-07 02:53:45 +00:00
|
|
|
"github.com/hashicorp/nomad/helper"
|
2019-08-12 22:41:39 +00:00
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
2019-12-18 16:23:16 +00:00
|
|
|
"github.com/pkg/errors"
|
2019-08-12 22:41:39 +00:00
|
|
|
)
|
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
const envoyBootstrapHookName = "envoy_bootstrap"
|
|
|
|
|
|
|
|
type envoyBootstrapHookConfig struct {
|
|
|
|
alloc *structs.Allocation
|
|
|
|
consulHTTPAddr string
|
|
|
|
logger hclog.Logger
|
|
|
|
}
|
2019-08-12 22:41:39 +00:00
|
|
|
|
2020-01-07 02:53:45 +00:00
|
|
|
const (
|
|
|
|
envoyBaseAdminPort = 19000
|
|
|
|
envoyAdminBindEnvPrefix = "NOMAD_ENVOY_ADMIN_ADDR_"
|
|
|
|
)
|
2019-12-06 06:49:01 +00:00
|
|
|
|
2019-08-12 22:41:39 +00:00
|
|
|
// envoyBootstrapHook writes the bootstrap config for the Connect Envoy proxy
|
|
|
|
// sidecar.
|
|
|
|
type envoyBootstrapHook struct {
|
2019-12-18 16:23:16 +00:00
|
|
|
// alloc is the allocation with the envoy task being bootstrapped.
|
2019-08-12 22:41:39 +00:00
|
|
|
alloc *structs.Allocation
|
|
|
|
|
|
|
|
// Bootstrapping Envoy requires talking directly to Consul to generate
|
|
|
|
// the bootstrap.json config. Runtime Envoy configuration is done via
|
|
|
|
// Consul's gRPC endpoint.
|
|
|
|
consulHTTPAddr string
|
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
// logger is used to log things
|
|
|
|
logger hclog.Logger
|
2019-08-12 22:41:39 +00:00
|
|
|
}
|
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
func newEnvoyBootstrapHook(c *envoyBootstrapHookConfig) *envoyBootstrapHook {
|
|
|
|
return &envoyBootstrapHook{
|
|
|
|
alloc: c.alloc,
|
|
|
|
consulHTTPAddr: c.consulHTTPAddr,
|
|
|
|
logger: c.logger.Named(envoyBootstrapHookName),
|
2019-08-12 22:41:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (envoyBootstrapHook) Name() string {
|
2019-12-18 16:23:16 +00:00
|
|
|
return envoyBootstrapHookName
|
2019-08-12 22:41:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *envoyBootstrapHook) Prestart(ctx context.Context, req *interfaces.TaskPrestartRequest, resp *interfaces.TaskPrestartResponse) error {
|
|
|
|
if !req.Task.Kind.IsConnectProxy() {
|
|
|
|
// Not a Connect proxy sidecar
|
|
|
|
resp.Done = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
serviceName := req.Task.Kind.Value()
|
|
|
|
if serviceName == "" {
|
2019-12-18 16:23:16 +00:00
|
|
|
return errors.New("connect proxy sidecar does not specify service name")
|
2019-08-12 22:41:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
tg := h.alloc.Job.LookupTaskGroup(h.alloc.TaskGroup)
|
|
|
|
|
|
|
|
var service *structs.Service
|
|
|
|
for _, s := range tg.Services {
|
|
|
|
if s.Name == serviceName {
|
|
|
|
service = s
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if service == nil {
|
2019-12-18 16:23:16 +00:00
|
|
|
return errors.New("connect proxy sidecar task exists but no services configured with a sidecar")
|
2019-08-12 22:41:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
h.logger.Debug("bootstrapping Connect proxy sidecar", "task", req.Task.Name, "service", serviceName)
|
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
//TODO Should connect directly to Consul if the sidecar is running on the host netns.
|
2019-09-03 15:43:38 +00:00
|
|
|
grpcAddr := "unix://" + allocdir.AllocGRPCSocket
|
2019-08-12 22:41:39 +00:00
|
|
|
|
2019-12-06 06:49:01 +00:00
|
|
|
// Envoy runs an administrative API on the loopback interface. If multiple sidecars
|
|
|
|
// are running, the bind addresses need to have unique ports.
|
|
|
|
// TODO: support running in host netns, using freeport to find available port
|
|
|
|
envoyAdminBind := buildEnvoyAdminBind(h.alloc, req.Task.Name)
|
2020-01-08 18:41:38 +00:00
|
|
|
resp.Env = map[string]string{
|
|
|
|
helper.CleanEnvVar(envoyAdminBindEnvPrefix+serviceName, '_'): envoyAdminBind,
|
|
|
|
}
|
2019-12-06 06:49:01 +00:00
|
|
|
|
2019-08-12 22:41:39 +00:00
|
|
|
// Envoy bootstrap configuration may contain a Consul token, so write
|
|
|
|
// it to the secrets directory like Vault tokens.
|
2019-12-18 16:23:16 +00:00
|
|
|
bootstrapFilePath := filepath.Join(req.TaskDir.SecretsDir, "envoy_bootstrap.json")
|
2019-08-12 22:41:39 +00:00
|
|
|
|
2019-11-18 18:04:01 +00:00
|
|
|
id := agentconsul.MakeAllocServiceID(h.alloc.ID, "group-"+tg.Name, service)
|
2019-08-12 22:41:39 +00:00
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
h.logger.Debug("bootstrapping envoy", "sidecar_for", service.Name, "bootstrap_file", bootstrapFilePath, "sidecar_for_id", id, "grpc_addr", grpcAddr, "admin_bind", envoyAdminBind)
|
|
|
|
|
|
|
|
siToken, err := h.maybeLoadSIToken(req.Task.Name, req.TaskDir.SecretsDir)
|
|
|
|
if err != nil {
|
|
|
|
h.logger.Error("failed to generate envoy bootstrap config", "sidecar_for", service.Name)
|
|
|
|
return errors.Wrap(err, "failed to generate envoy bootstrap config")
|
|
|
|
}
|
|
|
|
h.logger.Debug("check for SI token for task", "task", req.Task.Name, "exists", siToken != "")
|
|
|
|
|
|
|
|
bootstrapArgs := envoyBootstrapArgs{
|
|
|
|
sidecarFor: id,
|
|
|
|
grpcAddr: grpcAddr,
|
|
|
|
consulHTTPAddr: h.consulHTTPAddr,
|
|
|
|
envoyAdminBind: envoyAdminBind,
|
|
|
|
siToken: siToken,
|
|
|
|
}.args()
|
|
|
|
|
2019-08-12 22:41:39 +00:00
|
|
|
// Since Consul services are registered asynchronously with this task
|
|
|
|
// hook running, retry a small number of times with backoff.
|
|
|
|
for tries := 3; ; tries-- {
|
2019-12-18 16:23:16 +00:00
|
|
|
|
|
|
|
cmd := exec.CommandContext(ctx, "consul", bootstrapArgs...)
|
2019-08-12 22:41:39 +00:00
|
|
|
|
|
|
|
// Redirect output to secrets/envoy_bootstrap.json
|
2019-12-18 16:23:16 +00:00
|
|
|
fd, err := os.Create(bootstrapFilePath)
|
2019-08-12 22:41:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error creating secrets/envoy_bootstrap.json for envoy: %v", err)
|
|
|
|
}
|
|
|
|
cmd.Stdout = fd
|
|
|
|
|
|
|
|
buf := bytes.NewBuffer(nil)
|
|
|
|
cmd.Stderr = buf
|
|
|
|
|
|
|
|
// Generate bootstrap
|
|
|
|
err = cmd.Run()
|
|
|
|
|
|
|
|
// Close bootstrap.json
|
2020-01-15 14:41:23 +00:00
|
|
|
fd.Close()
|
2019-08-12 22:41:39 +00:00
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
// Happy path! Bootstrap was created, exit.
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for error from command
|
|
|
|
if tries == 0 {
|
|
|
|
h.logger.Error("error creating bootstrap configuration for Connect proxy sidecar", "error", err, "stderr", buf.String())
|
|
|
|
|
|
|
|
// Cleanup the bootstrap file. An errors here is not
|
|
|
|
// important as (a) we test to ensure the deletion
|
|
|
|
// occurs, and (b) the file will either be rewritten on
|
|
|
|
// retry or eventually garbage collected if the task
|
|
|
|
// fails.
|
2020-01-15 14:41:23 +00:00
|
|
|
os.Remove(bootstrapFilePath)
|
2019-08-12 22:41:39 +00:00
|
|
|
|
|
|
|
// ExitErrors are recoverable since they indicate the
|
|
|
|
// command was runnable but exited with a unsuccessful
|
|
|
|
// error code.
|
|
|
|
_, recoverable := err.(*exec.ExitError)
|
|
|
|
return structs.NewRecoverableError(
|
|
|
|
fmt.Errorf("error creating bootstrap configuration for Connect proxy sidecar: %v", err),
|
|
|
|
recoverable,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sleep before retrying to give Consul services time to register
|
|
|
|
select {
|
|
|
|
case <-time.After(2 * time.Second):
|
|
|
|
case <-ctx.Done():
|
|
|
|
// Killed before bootstrap, exit without setting Done
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bootstrap written. Mark as done and move on.
|
|
|
|
resp.Done = true
|
|
|
|
return nil
|
|
|
|
}
|
2019-12-06 06:49:01 +00:00
|
|
|
|
|
|
|
func buildEnvoyAdminBind(alloc *structs.Allocation, taskName string) string {
|
|
|
|
port := envoyBaseAdminPort
|
|
|
|
for idx, task := range alloc.Job.LookupTaskGroup(alloc.TaskGroup).Tasks {
|
|
|
|
if task.Name == taskName {
|
|
|
|
port += idx
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("localhost:%d", port)
|
|
|
|
}
|
2019-12-18 16:23:16 +00:00
|
|
|
|
|
|
|
func (h *envoyBootstrapHook) writeConfig(filename, config string) error {
|
|
|
|
if err := ioutil.WriteFile(filename, []byte(config), 0440); err != nil {
|
|
|
|
_ = os.Remove(filename)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *envoyBootstrapHook) execute(cmd *exec.Cmd) (string, error) {
|
|
|
|
var (
|
|
|
|
stdout bytes.Buffer
|
|
|
|
stderr bytes.Buffer
|
|
|
|
)
|
|
|
|
|
|
|
|
cmd.Stdout = &stdout
|
|
|
|
cmd.Stderr = &stderr
|
|
|
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
_, recoverable := err.(*exec.ExitError)
|
|
|
|
// ExitErrors are recoverable since they indicate the
|
|
|
|
// command was runnable but exited with a unsuccessful
|
|
|
|
// error code.
|
|
|
|
return stderr.String(), structs.NewRecoverableError(err, recoverable)
|
|
|
|
}
|
|
|
|
return stdout.String(), nil
|
|
|
|
}
|
|
|
|
|
2020-01-15 15:29:47 +00:00
|
|
|
// envoyBootstrapArgs is used to accumulate CLI arguments that will be passed
|
|
|
|
// along to the exec invocation of consul which will then generate the bootstrap
|
|
|
|
// configuration file for envoy.
|
2019-12-18 16:23:16 +00:00
|
|
|
type envoyBootstrapArgs struct {
|
|
|
|
sidecarFor string
|
|
|
|
grpcAddr string
|
|
|
|
envoyAdminBind string
|
|
|
|
consulHTTPAddr string
|
|
|
|
siToken string
|
|
|
|
}
|
|
|
|
|
2020-01-15 15:29:47 +00:00
|
|
|
// args returns the CLI arguments consul needs in the correct order, with the
|
|
|
|
// -token argument present or not present depending on whether it is set.
|
2019-12-18 16:23:16 +00:00
|
|
|
func (e envoyBootstrapArgs) args() []string {
|
|
|
|
arguments := []string{
|
|
|
|
"connect",
|
|
|
|
"envoy",
|
|
|
|
"-grpc-addr", e.grpcAddr,
|
|
|
|
"-http-addr", e.consulHTTPAddr,
|
|
|
|
"-admin-bind", e.envoyAdminBind,
|
|
|
|
"-bootstrap",
|
|
|
|
"-sidecar-for", e.sidecarFor,
|
|
|
|
}
|
|
|
|
if e.siToken != "" {
|
2020-01-15 14:41:23 +00:00
|
|
|
arguments = append(arguments, "-token", e.siToken)
|
2019-12-18 16:23:16 +00:00
|
|
|
}
|
|
|
|
return arguments
|
|
|
|
}
|
|
|
|
|
2020-01-15 14:41:23 +00:00
|
|
|
// maybeLoadSIToken reads the SI token saved to disk in the secrets directory
|
2019-12-18 16:23:16 +00:00
|
|
|
// by the service identities prestart hook. This envoy bootstrap hook blocks
|
|
|
|
// until the sids hook completes, so if the SI token is required to exist (i.e.
|
|
|
|
// Consul ACLs are enabled), it will be in place by the time we try to read it.
|
|
|
|
func (h *envoyBootstrapHook) maybeLoadSIToken(task, dir string) (string, error) {
|
|
|
|
tokenPath := filepath.Join(dir, sidsTokenFile)
|
|
|
|
token, err := ioutil.ReadFile(tokenPath)
|
|
|
|
if err != nil {
|
|
|
|
if !os.IsNotExist(err) {
|
|
|
|
h.logger.Error("failed to load SI token", "task", task, "error", err)
|
|
|
|
return "", errors.Wrapf(err, "failed to load SI token for %s", task)
|
|
|
|
}
|
|
|
|
h.logger.Trace("no SI token to load", "task", task)
|
|
|
|
return "", nil // token file does not exist
|
|
|
|
}
|
|
|
|
h.logger.Trace("recovered pre-existing SI token", "task", task)
|
|
|
|
return string(token), nil
|
|
|
|
}
|